IndexedDB: fsync after transactions.
[chromium-blink-merge.git] / cc / trees / layer_tree_host_impl.cc
blob9063caf66d67f57c2dad462ec1ec9320663c8369
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/scrollbar_animation_controller.h"
17 #include "cc/animation/timing_function.h"
18 #include "cc/base/latency_info_swap_promise_monitor.h"
19 #include "cc/base/math_util.h"
20 #include "cc/base/util.h"
21 #include "cc/debug/benchmark_instrumentation.h"
22 #include "cc/debug/debug_rect_history.h"
23 #include "cc/debug/devtools_instrumentation.h"
24 #include "cc/debug/frame_rate_counter.h"
25 #include "cc/debug/overdraw_metrics.h"
26 #include "cc/debug/paint_time_counter.h"
27 #include "cc/debug/rendering_stats_instrumentation.h"
28 #include "cc/debug/traced_value.h"
29 #include "cc/input/page_scale_animation.h"
30 #include "cc/input/top_controls_manager.h"
31 #include "cc/layers/append_quads_data.h"
32 #include "cc/layers/heads_up_display_layer_impl.h"
33 #include "cc/layers/layer_impl.h"
34 #include "cc/layers/layer_iterator.h"
35 #include "cc/layers/painted_scrollbar_layer_impl.h"
36 #include "cc/layers/render_surface_impl.h"
37 #include "cc/layers/scrollbar_layer_impl_base.h"
38 #include "cc/output/compositor_frame_metadata.h"
39 #include "cc/output/copy_output_request.h"
40 #include "cc/output/delegating_renderer.h"
41 #include "cc/output/gl_renderer.h"
42 #include "cc/output/software_renderer.h"
43 #include "cc/quads/render_pass_draw_quad.h"
44 #include "cc/quads/shared_quad_state.h"
45 #include "cc/quads/solid_color_draw_quad.h"
46 #include "cc/quads/texture_draw_quad.h"
47 #include "cc/resources/memory_history.h"
48 #include "cc/resources/picture_layer_tiling.h"
49 #include "cc/resources/prioritized_resource_manager.h"
50 #include "cc/resources/texture_mailbox_deleter.h"
51 #include "cc/resources/ui_resource_bitmap.h"
52 #include "cc/scheduler/delay_based_time_source.h"
53 #include "cc/scheduler/texture_uploader.h"
54 #include "cc/trees/damage_tracker.h"
55 #include "cc/trees/layer_tree_host.h"
56 #include "cc/trees/layer_tree_host_common.h"
57 #include "cc/trees/layer_tree_impl.h"
58 #include "cc/trees/quad_culler.h"
59 #include "cc/trees/single_thread_proxy.h"
60 #include "cc/trees/tree_synchronizer.h"
61 #include "gpu/GLES2/gl2extchromium.h"
62 #include "ui/gfx/frame_time.h"
63 #include "ui/gfx/size_conversions.h"
64 #include "ui/gfx/vector2d_conversions.h"
66 namespace {
68 void DidVisibilityChange(cc::LayerTreeHostImpl* id, bool visible) {
69 if (visible) {
70 TRACE_EVENT_ASYNC_BEGIN1("webkit",
71 "LayerTreeHostImpl::SetVisible",
72 id,
73 "LayerTreeHostImpl",
74 id);
75 return;
78 TRACE_EVENT_ASYNC_END0("webkit", "LayerTreeHostImpl::SetVisible", id);
81 size_t GetMaxTransferBufferUsageBytes(cc::ContextProvider* context_provider) {
82 // Software compositing should not use this value in production. Just use a
83 // default value when testing uploads with the software compositor.
84 if (!context_provider)
85 return std::numeric_limits<size_t>::max();
87 // We want to make sure the default transfer buffer size is equal to the
88 // amount of data that can be uploaded by the compositor to avoid stalling
89 // the pipeline.
90 // For reference Chromebook Pixel can upload 1MB in about 0.5ms.
91 const size_t kMaxBytesUploadedPerMs = 1024 * 1024 * 2;
92 // Assuming a two frame deep pipeline between CPU and GPU and we are
93 // drawing 60 frames per second which would require us to draw one
94 // frame in 16 milliseconds.
95 const size_t kMaxTransferBufferUsageBytes = 16 * 2 * kMaxBytesUploadedPerMs;
96 return std::min(
97 context_provider->ContextCapabilities().max_transfer_buffer_usage_bytes,
98 kMaxTransferBufferUsageBytes);
101 size_t GetMaxRasterTasksUsageBytes(cc::ContextProvider* context_provider) {
102 // Transfer-buffer/raster-tasks limits are different but related. We make
103 // equal here, as this is ideal when using transfer buffers. When not using
104 // transfer buffers we should still limit raster to something similar, to
105 // preserve caching behavior (and limit memory waste when priorities change).
106 return GetMaxTransferBufferUsageBytes(context_provider);
109 unsigned GetMapImageTextureTarget(cc::ContextProvider* context_provider) {
110 if (!context_provider)
111 return GL_TEXTURE_2D;
113 // TODO(reveman): Determine if GL_TEXTURE_EXTERNAL_OES works well on
114 // Android before we enable this. crbug.com/322780
115 #if !defined(OS_ANDROID)
116 if (context_provider->ContextCapabilities().gpu.egl_image_external)
117 return GL_TEXTURE_EXTERNAL_OES;
118 if (context_provider->ContextCapabilities().gpu.texture_rectangle)
119 return GL_TEXTURE_RECTANGLE_ARB;
120 #endif
122 return GL_TEXTURE_2D;
125 } // namespace
127 namespace cc {
129 class LayerTreeHostImplTimeSourceAdapter : public TimeSourceClient {
130 public:
131 static scoped_ptr<LayerTreeHostImplTimeSourceAdapter> Create(
132 LayerTreeHostImpl* layer_tree_host_impl,
133 scoped_refptr<DelayBasedTimeSource> time_source) {
134 return make_scoped_ptr(
135 new LayerTreeHostImplTimeSourceAdapter(layer_tree_host_impl,
136 time_source));
138 virtual ~LayerTreeHostImplTimeSourceAdapter() {
139 time_source_->SetClient(NULL);
140 time_source_->SetActive(false);
143 virtual void OnTimerTick() OVERRIDE {
144 // In single threaded mode we attempt to simulate changing the current
145 // thread by maintaining a fake thread id. When we switch from one
146 // thread to another, we construct DebugScopedSetXXXThread objects that
147 // update the thread id. This lets DCHECKS that ensure we're on the
148 // right thread to work correctly in single threaded mode. The problem
149 // here is that the timer tasks are run via the message loop, and when
150 // they run, we've had no chance to construct a DebugScopedSetXXXThread
151 // object. The result is that we report that we're running on the main
152 // thread. In multi-threaded mode, this timer is run on the compositor
153 // thread, so to keep this consistent in single-threaded mode, we'll
154 // construct a DebugScopedSetImplThread object. There is no need to do
155 // this in multi-threaded mode since the real thread id's will be
156 // correct. In fact, setting fake thread id's interferes with the real
157 // thread id's and causes breakage.
158 scoped_ptr<DebugScopedSetImplThread> set_impl_thread;
159 if (!layer_tree_host_impl_->proxy()->HasImplThread()) {
160 set_impl_thread.reset(
161 new DebugScopedSetImplThread(layer_tree_host_impl_->proxy()));
164 // TODO(enne): This should probably happen post-animate.
165 if (layer_tree_host_impl_->pending_tree()) {
166 layer_tree_host_impl_->pending_tree()->UpdateDrawProperties();
167 layer_tree_host_impl_->ManageTiles();
170 layer_tree_host_impl_->Animate(
171 layer_tree_host_impl_->CurrentFrameTimeTicks(),
172 layer_tree_host_impl_->CurrentFrameTime());
173 layer_tree_host_impl_->UpdateBackgroundAnimateTicking(true);
174 bool start_ready_animations = true;
175 layer_tree_host_impl_->UpdateAnimationState(start_ready_animations);
176 layer_tree_host_impl_->ResetCurrentFrameTimeForNextFrame();
179 void SetActive(bool active) {
180 if (active != time_source_->Active())
181 time_source_->SetActive(active);
184 bool Active() const { return time_source_->Active(); }
186 private:
187 LayerTreeHostImplTimeSourceAdapter(
188 LayerTreeHostImpl* layer_tree_host_impl,
189 scoped_refptr<DelayBasedTimeSource> time_source)
190 : layer_tree_host_impl_(layer_tree_host_impl),
191 time_source_(time_source) {
192 time_source_->SetClient(this);
195 LayerTreeHostImpl* layer_tree_host_impl_;
196 scoped_refptr<DelayBasedTimeSource> time_source_;
198 DISALLOW_COPY_AND_ASSIGN(LayerTreeHostImplTimeSourceAdapter);
201 LayerTreeHostImpl::FrameData::FrameData()
202 : contains_incomplete_tile(false), has_no_damage(false) {}
204 LayerTreeHostImpl::FrameData::~FrameData() {}
206 scoped_ptr<LayerTreeHostImpl> LayerTreeHostImpl::Create(
207 const LayerTreeSettings& settings,
208 LayerTreeHostImplClient* client,
209 Proxy* proxy,
210 RenderingStatsInstrumentation* rendering_stats_instrumentation,
211 SharedBitmapManager* manager,
212 int id) {
213 return make_scoped_ptr(new LayerTreeHostImpl(
214 settings, client, proxy, rendering_stats_instrumentation, manager, id));
217 LayerTreeHostImpl::LayerTreeHostImpl(
218 const LayerTreeSettings& settings,
219 LayerTreeHostImplClient* client,
220 Proxy* proxy,
221 RenderingStatsInstrumentation* rendering_stats_instrumentation,
222 SharedBitmapManager* manager,
223 int id)
224 : client_(client),
225 proxy_(proxy),
226 input_handler_client_(NULL),
227 did_lock_scrolling_layer_(false),
228 should_bubble_scrolls_(false),
229 wheel_scrolling_(false),
230 scroll_layer_id_when_mouse_over_scrollbar_(0),
231 tile_priorities_dirty_(false),
232 root_layer_scroll_offset_delegate_(NULL),
233 settings_(settings),
234 visible_(true),
235 cached_managed_memory_policy_(
236 PrioritizedResourceManager::DefaultMemoryAllocationLimit(),
237 gpu::MemoryAllocation::CUTOFF_ALLOW_EVERYTHING,
238 ManagedMemoryPolicy::kDefaultNumResourcesLimit),
239 pinch_gesture_active_(false),
240 pinch_gesture_end_should_clear_scrolling_layer_(false),
241 fps_counter_(FrameRateCounter::Create(proxy_->HasImplThread())),
242 paint_time_counter_(PaintTimeCounter::Create()),
243 memory_history_(MemoryHistory::Create()),
244 debug_rect_history_(DebugRectHistory::Create()),
245 texture_mailbox_deleter_(new TextureMailboxDeleter),
246 max_memory_needed_bytes_(0),
247 last_sent_memory_visible_bytes_(0),
248 last_sent_memory_visible_and_nearby_bytes_(0),
249 last_sent_memory_use_bytes_(0),
250 zero_budget_(false),
251 device_scale_factor_(1.f),
252 overhang_ui_resource_id_(0),
253 overdraw_bottom_height_(0.f),
254 device_viewport_valid_for_tile_management_(true),
255 external_stencil_test_enabled_(false),
256 animation_registrar_(AnimationRegistrar::Create()),
257 rendering_stats_instrumentation_(rendering_stats_instrumentation),
258 micro_benchmark_controller_(this),
259 need_to_update_visible_tiles_before_draw_(false),
260 #ifndef NDEBUG
261 did_lose_called_(false),
262 #endif
263 shared_bitmap_manager_(manager),
264 id_(id) {
265 DCHECK(proxy_->IsImplThread());
266 DidVisibilityChange(this, visible_);
268 SetDebugState(settings.initial_debug_state);
270 if (settings.calculate_top_controls_position) {
271 top_controls_manager_ =
272 TopControlsManager::Create(this,
273 settings.top_controls_height,
274 settings.top_controls_show_threshold,
275 settings.top_controls_hide_threshold);
278 SetDebugState(settings.initial_debug_state);
280 // LTHI always has an active tree.
281 active_tree_ = LayerTreeImpl::create(this);
282 TRACE_EVENT_OBJECT_CREATED_WITH_ID(
283 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", this);
286 LayerTreeHostImpl::~LayerTreeHostImpl() {
287 DCHECK(proxy_->IsImplThread());
288 TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()");
289 TRACE_EVENT_OBJECT_DELETED_WITH_ID(
290 TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", this);
292 if (input_handler_client_) {
293 input_handler_client_->WillShutdown();
294 input_handler_client_ = NULL;
297 // The layer trees must be destroyed before the layer tree host. We've
298 // made a contract with our animation controllers that the registrar
299 // will outlive them, and we must make good.
300 recycle_tree_.reset();
301 pending_tree_.reset();
302 active_tree_.reset();
305 void LayerTreeHostImpl::BeginMainFrameAborted(bool did_handle) {
306 // If the begin frame data was handled, then scroll and scale set was applied
307 // by the main thread, so the active tree needs to be updated as if these sent
308 // values were applied and committed.
309 if (did_handle) {
310 active_tree_->ApplySentScrollAndScaleDeltasFromAbortedCommit();
311 active_tree_->ResetContentsTexturesPurged();
315 void LayerTreeHostImpl::BeginCommit() {}
317 void LayerTreeHostImpl::CommitComplete() {
318 TRACE_EVENT0("cc", "LayerTreeHostImpl::CommitComplete");
320 if (settings_.impl_side_painting) {
321 // Impl-side painting needs an update immediately post-commit to have the
322 // opportunity to create tilings. Other paths can call UpdateDrawProperties
323 // more lazily when needed prior to drawing.
324 pending_tree()->ApplyScrollDeltasSinceBeginMainFrame();
325 pending_tree_->set_needs_update_draw_properties();
326 pending_tree_->UpdateDrawProperties();
327 // Start working on newly created tiles immediately if needed.
328 if (!tile_manager_ || !tile_priorities_dirty_)
329 NotifyReadyToActivate();
330 else
331 ManageTiles();
332 } else {
333 active_tree_->set_needs_update_draw_properties();
334 if (time_source_client_adapter_ && time_source_client_adapter_->Active())
335 DCHECK(active_tree_->root_layer());
338 client_->SendManagedMemoryStats();
340 micro_benchmark_controller_.DidCompleteCommit();
343 bool LayerTreeHostImpl::CanDraw() const {
344 // Note: If you are changing this function or any other function that might
345 // affect the result of CanDraw, make sure to call
346 // client_->OnCanDrawStateChanged in the proper places and update the
347 // NotifyIfCanDrawChanged test.
349 if (!renderer_) {
350 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no renderer",
351 TRACE_EVENT_SCOPE_THREAD);
352 return false;
355 // Must have an OutputSurface if |renderer_| is not NULL.
356 DCHECK(output_surface_);
358 // TODO(boliu): Make draws without root_layer work and move this below
359 // draw_and_swap_full_viewport_every_frame check. Tracked in crbug.com/264967.
360 if (!active_tree_->root_layer()) {
361 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw no root layer",
362 TRACE_EVENT_SCOPE_THREAD);
363 return false;
366 if (output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
367 return true;
369 if (DrawViewportSize().IsEmpty()) {
370 TRACE_EVENT_INSTANT0("cc", "LayerTreeHostImpl::CanDraw empty viewport",
371 TRACE_EVENT_SCOPE_THREAD);
372 return false;
374 if (active_tree_->ViewportSizeInvalid()) {
375 TRACE_EVENT_INSTANT0(
376 "cc", "LayerTreeHostImpl::CanDraw viewport size recently changed",
377 TRACE_EVENT_SCOPE_THREAD);
378 return false;
380 if (active_tree_->ContentsTexturesPurged()) {
381 TRACE_EVENT_INSTANT0(
382 "cc", "LayerTreeHostImpl::CanDraw contents textures purged",
383 TRACE_EVENT_SCOPE_THREAD);
384 return false;
386 if (EvictedUIResourcesExist()) {
387 TRACE_EVENT_INSTANT0(
388 "cc", "LayerTreeHostImpl::CanDraw UI resources evicted not recreated",
389 TRACE_EVENT_SCOPE_THREAD);
390 return false;
392 return true;
395 void LayerTreeHostImpl::Animate(base::TimeTicks monotonic_time,
396 base::Time wall_clock_time) {
397 if (input_handler_client_)
398 input_handler_client_->Animate(monotonic_time);
399 AnimatePageScale(monotonic_time);
400 AnimateLayers(monotonic_time, wall_clock_time);
401 AnimateScrollbars(monotonic_time);
402 AnimateTopControls(monotonic_time);
405 void LayerTreeHostImpl::ManageTiles() {
406 if (!tile_manager_)
407 return;
408 if (!tile_priorities_dirty_)
409 return;
410 if (!device_viewport_valid_for_tile_management_)
411 return;
413 tile_priorities_dirty_ = false;
414 tile_manager_->ManageTiles(global_tile_state_);
416 size_t memory_required_bytes;
417 size_t memory_nice_to_have_bytes;
418 size_t memory_allocated_bytes;
419 size_t memory_used_bytes;
420 tile_manager_->GetMemoryStats(&memory_required_bytes,
421 &memory_nice_to_have_bytes,
422 &memory_allocated_bytes,
423 &memory_used_bytes);
424 SendManagedMemoryStats(memory_required_bytes,
425 memory_nice_to_have_bytes,
426 memory_used_bytes);
428 client_->DidManageTiles();
431 void LayerTreeHostImpl::StartPageScaleAnimation(gfx::Vector2d target_offset,
432 bool anchor_point,
433 float page_scale,
434 base::TimeDelta duration) {
435 if (!RootScrollLayer())
436 return;
438 gfx::Vector2dF scroll_total =
439 RootScrollLayer()->scroll_offset() + RootScrollLayer()->ScrollDelta();
440 gfx::SizeF scaled_scrollable_size = active_tree_->ScrollableSize();
441 gfx::SizeF viewport_size = UnscaledScrollableViewportSize();
443 // Easing constants experimentally determined.
444 scoped_ptr<TimingFunction> timing_function =
445 CubicBezierTimingFunction::Create(.8, 0, .3, .9).PassAs<TimingFunction>();
447 page_scale_animation_ =
448 PageScaleAnimation::Create(scroll_total,
449 active_tree_->total_page_scale_factor(),
450 viewport_size,
451 scaled_scrollable_size,
452 timing_function.Pass());
454 if (anchor_point) {
455 gfx::Vector2dF anchor(target_offset);
456 page_scale_animation_->ZoomWithAnchor(anchor,
457 page_scale,
458 duration.InSecondsF());
459 } else {
460 gfx::Vector2dF scaled_target_offset = target_offset;
461 page_scale_animation_->ZoomTo(scaled_target_offset,
462 page_scale,
463 duration.InSecondsF());
466 SetNeedsRedraw();
467 client_->SetNeedsCommitOnImplThread();
468 client_->RenewTreePriority();
471 void LayerTreeHostImpl::ScheduleAnimation() {
472 SetNeedsRedraw();
475 bool LayerTreeHostImpl::HaveTouchEventHandlersAt(gfx::Point viewport_point) {
476 if (!settings_.touch_hit_testing)
477 return true;
478 if (!EnsureRenderSurfaceLayerList())
479 return false;
481 gfx::PointF device_viewport_point =
482 gfx::ScalePoint(viewport_point, device_scale_factor_);
484 LayerImpl* layer_impl =
485 LayerTreeHostCommon::FindLayerThatIsHitByPointInTouchHandlerRegion(
486 device_viewport_point,
487 active_tree_->RenderSurfaceLayerList());
488 return layer_impl != NULL;
491 scoped_ptr<SwapPromiseMonitor>
492 LayerTreeHostImpl::CreateLatencyInfoSwapPromiseMonitor(
493 ui::LatencyInfo* latency) {
494 return scoped_ptr<SwapPromiseMonitor>(
495 new LatencyInfoSwapPromiseMonitor(latency, NULL, this));
498 void LayerTreeHostImpl::TrackDamageForAllSurfaces(
499 LayerImpl* root_draw_layer,
500 const LayerImplList& render_surface_layer_list) {
501 // For now, we use damage tracking to compute a global scissor. To do this, we
502 // must compute all damage tracking before drawing anything, so that we know
503 // the root damage rect. The root damage rect is then used to scissor each
504 // surface.
506 for (int surface_index = render_surface_layer_list.size() - 1;
507 surface_index >= 0;
508 --surface_index) {
509 LayerImpl* render_surface_layer = render_surface_layer_list[surface_index];
510 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
511 DCHECK(render_surface);
512 render_surface->damage_tracker()->UpdateDamageTrackingState(
513 render_surface->layer_list(),
514 render_surface_layer->id(),
515 render_surface->SurfacePropertyChangedOnlyFromDescendant(),
516 render_surface->content_rect(),
517 render_surface_layer->mask_layer(),
518 render_surface_layer->filters());
522 scoped_ptr<base::Value> LayerTreeHostImpl::FrameData::AsValue() const {
523 scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue());
524 value->SetBoolean("contains_incomplete_tile", contains_incomplete_tile);
525 value->SetBoolean("has_no_damage", has_no_damage);
527 // Quad data can be quite large, so only dump render passes if we select
528 // cc.debug.quads.
529 bool quads_enabled;
530 TRACE_EVENT_CATEGORY_GROUP_ENABLED(
531 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), &quads_enabled);
532 if (quads_enabled) {
533 scoped_ptr<base::ListValue> render_pass_list(new base::ListValue());
534 for (size_t i = 0; i < render_passes.size(); ++i)
535 render_pass_list->Append(render_passes[i]->AsValue().release());
536 value->Set("render_passes", render_pass_list.release());
538 return value.PassAs<base::Value>();
541 void LayerTreeHostImpl::FrameData::AppendRenderPass(
542 scoped_ptr<RenderPass> render_pass) {
543 render_passes_by_id[render_pass->id] = render_pass.get();
544 render_passes.push_back(render_pass.Pass());
547 static DrawMode GetDrawMode(OutputSurface* output_surface) {
548 if (output_surface->ForcedDrawToSoftwareDevice()) {
549 return DRAW_MODE_RESOURCELESS_SOFTWARE;
550 } else if (output_surface->context_provider()) {
551 return DRAW_MODE_HARDWARE;
552 } else {
553 DCHECK_EQ(!output_surface->software_device(),
554 output_surface->capabilities().delegated_rendering);
555 return DRAW_MODE_SOFTWARE;
559 static void AppendQuadsForLayer(RenderPass* target_render_pass,
560 LayerImpl* layer,
561 const OcclusionTrackerImpl& occlusion_tracker,
562 AppendQuadsData* append_quads_data) {
563 bool for_surface = false;
564 QuadCuller quad_culler(&target_render_pass->quad_list,
565 &target_render_pass->shared_quad_state_list,
566 layer,
567 occlusion_tracker,
568 layer->ShowDebugBorders(),
569 for_surface);
570 layer->AppendQuads(&quad_culler, append_quads_data);
573 static void AppendQuadsForRenderSurfaceLayer(
574 RenderPass* target_render_pass,
575 LayerImpl* layer,
576 const RenderPass* contributing_render_pass,
577 const OcclusionTrackerImpl& occlusion_tracker,
578 AppendQuadsData* append_quads_data) {
579 bool for_surface = true;
580 QuadCuller quad_culler(&target_render_pass->quad_list,
581 &target_render_pass->shared_quad_state_list,
582 layer,
583 occlusion_tracker,
584 layer->ShowDebugBorders(),
585 for_surface);
587 bool is_replica = false;
588 layer->render_surface()->AppendQuads(&quad_culler,
589 append_quads_data,
590 is_replica,
591 contributing_render_pass->id);
593 // Add replica after the surface so that it appears below the surface.
594 if (layer->has_replica()) {
595 is_replica = true;
596 layer->render_surface()->AppendQuads(&quad_culler,
597 append_quads_data,
598 is_replica,
599 contributing_render_pass->id);
603 static void AppendQuadsToFillScreen(
604 ResourceProvider::ResourceId overhang_resource_id,
605 const gfx::SizeF& overhang_resource_scaled_size,
606 const gfx::Rect& root_scroll_layer_rect,
607 RenderPass* target_render_pass,
608 LayerImpl* root_layer,
609 SkColor screen_background_color,
610 const OcclusionTrackerImpl& occlusion_tracker) {
611 if (!root_layer || !SkColorGetA(screen_background_color))
612 return;
614 Region fill_region = occlusion_tracker.ComputeVisibleRegionInScreen();
615 if (fill_region.IsEmpty())
616 return;
618 // Divide the fill region into the part to be filled with the overhang
619 // resource and the part to be filled with the background color.
620 Region screen_background_color_region = fill_region;
621 Region overhang_region;
622 if (overhang_resource_id) {
623 overhang_region = fill_region;
624 overhang_region.Subtract(root_scroll_layer_rect);
625 screen_background_color_region.Intersect(root_scroll_layer_rect);
628 bool for_surface = false;
629 QuadCuller quad_culler(&target_render_pass->quad_list,
630 &target_render_pass->shared_quad_state_list,
631 root_layer,
632 occlusion_tracker,
633 root_layer->ShowDebugBorders(),
634 for_surface);
636 // Manually create the quad state for the gutter quads, as the root layer
637 // doesn't have any bounds and so can't generate this itself.
638 // TODO(danakj): Make the gutter quads generated by the solid color layer
639 // (make it smarter about generating quads to fill unoccluded areas).
641 gfx::Rect root_target_rect = root_layer->render_surface()->content_rect();
642 float opacity = 1.f;
643 SharedQuadState* shared_quad_state =
644 quad_culler.UseSharedQuadState(SharedQuadState::Create());
645 shared_quad_state->SetAll(root_layer->draw_transform(),
646 root_target_rect.size(),
647 root_target_rect,
648 root_target_rect,
649 false,
650 opacity,
651 SkXfermode::kSrcOver_Mode);
653 AppendQuadsData append_quads_data;
655 gfx::Transform transform_to_layer_space(gfx::Transform::kSkipInitialization);
656 bool did_invert = root_layer->screen_space_transform().GetInverse(
657 &transform_to_layer_space);
658 DCHECK(did_invert);
659 for (Region::Iterator fill_rects(screen_background_color_region);
660 fill_rects.has_rect();
661 fill_rects.next()) {
662 // The root layer transform is composed of translations and scales only,
663 // no perspective, so mapping is sufficient (as opposed to projecting).
664 gfx::Rect layer_rect =
665 MathUtil::MapClippedRect(transform_to_layer_space, fill_rects.rect());
666 // Skip the quad culler and just append the quads directly to avoid
667 // occlusion checks.
668 scoped_ptr<SolidColorDrawQuad> quad = SolidColorDrawQuad::Create();
669 quad->SetNew(
670 shared_quad_state, layer_rect, screen_background_color, false);
671 quad_culler.Append(quad.PassAs<DrawQuad>(), &append_quads_data);
673 for (Region::Iterator fill_rects(overhang_region);
674 fill_rects.has_rect();
675 fill_rects.next()) {
676 DCHECK(overhang_resource_id);
677 gfx::Rect layer_rect =
678 MathUtil::MapClippedRect(transform_to_layer_space, fill_rects.rect());
679 scoped_ptr<TextureDrawQuad> tex_quad = TextureDrawQuad::Create();
680 const float vertex_opacity[4] = {1.f, 1.f, 1.f, 1.f};
681 tex_quad->SetNew(
682 shared_quad_state,
683 layer_rect,
684 layer_rect,
685 overhang_resource_id,
686 false,
687 gfx::PointF(layer_rect.x() / overhang_resource_scaled_size.width(),
688 layer_rect.y() / overhang_resource_scaled_size.height()),
689 gfx::PointF(layer_rect.right() /
690 overhang_resource_scaled_size.width(),
691 layer_rect.bottom() /
692 overhang_resource_scaled_size.height()),
693 screen_background_color,
694 vertex_opacity,
695 false);
696 quad_culler.Append(tex_quad.PassAs<DrawQuad>(), &append_quads_data);
700 bool LayerTreeHostImpl::CalculateRenderPasses(FrameData* frame) {
701 DCHECK(frame->render_passes.empty());
703 if (!CanDraw() || !active_tree_->root_layer())
704 return false;
706 TrackDamageForAllSurfaces(active_tree_->root_layer(),
707 *frame->render_surface_layer_list);
709 // If the root render surface has no visible damage, then don't generate a
710 // frame at all.
711 RenderSurfaceImpl* root_surface =
712 active_tree_->root_layer()->render_surface();
713 bool root_surface_has_no_visible_damage =
714 !root_surface->damage_tracker()->current_damage_rect().Intersects(
715 root_surface->content_rect());
716 bool root_surface_has_contributing_layers =
717 !root_surface->layer_list().empty();
718 if (root_surface_has_contributing_layers &&
719 root_surface_has_no_visible_damage) {
720 TRACE_EVENT0("cc",
721 "LayerTreeHostImpl::CalculateRenderPasses::EmptyDamageRect");
722 frame->has_no_damage = true;
723 // A copy request should cause damage, so we should not have any copy
724 // requests in this case.
725 DCHECK_EQ(0u, active_tree_->LayersWithCopyOutputRequest().size());
726 DCHECK(!output_surface_->capabilities()
727 .draw_and_swap_full_viewport_every_frame);
728 return true;
731 TRACE_EVENT1("cc",
732 "LayerTreeHostImpl::CalculateRenderPasses",
733 "render_surface_layer_list.size()",
734 static_cast<uint64>(frame->render_surface_layer_list->size()));
736 // Create the render passes in dependency order.
737 for (int surface_index = frame->render_surface_layer_list->size() - 1;
738 surface_index >= 0;
739 --surface_index) {
740 LayerImpl* render_surface_layer =
741 (*frame->render_surface_layer_list)[surface_index];
742 RenderSurfaceImpl* render_surface = render_surface_layer->render_surface();
744 bool should_draw_into_render_pass =
745 render_surface_layer->parent() == NULL ||
746 render_surface->contributes_to_drawn_surface() ||
747 render_surface_layer->HasCopyRequest();
748 if (should_draw_into_render_pass)
749 render_surface_layer->render_surface()->AppendRenderPasses(frame);
752 bool record_metrics_for_frame =
753 settings_.show_overdraw_in_tracing &&
754 base::debug::TraceLog::GetInstance() &&
755 base::debug::TraceLog::GetInstance()->IsEnabled();
756 OcclusionTrackerImpl occlusion_tracker(
757 active_tree_->root_layer()->render_surface()->content_rect(),
758 record_metrics_for_frame);
759 occlusion_tracker.set_minimum_tracking_size(
760 settings_.minimum_occlusion_tracking_size);
762 if (debug_state_.show_occluding_rects) {
763 occlusion_tracker.set_occluding_screen_space_rects_container(
764 &frame->occluding_screen_space_rects);
766 if (debug_state_.show_non_occluding_rects) {
767 occlusion_tracker.set_non_occluding_screen_space_rects_container(
768 &frame->non_occluding_screen_space_rects);
771 // Add quads to the Render passes in FrontToBack order to allow for testing
772 // occlusion and performing culling during the tree walk.
773 typedef LayerIterator<LayerImpl,
774 LayerImplList,
775 RenderSurfaceImpl,
776 LayerIteratorActions::FrontToBack> LayerIteratorType;
778 // Typically when we are missing a texture and use a checkerboard quad, we
779 // still draw the frame. However when the layer being checkerboarded is moving
780 // due to an impl-animation, we drop the frame to avoid flashing due to the
781 // texture suddenly appearing in the future.
782 bool draw_frame = true;
783 // When we have a copy request for a layer, we need to draw no matter
784 // what, as the layer may disappear after this frame.
785 bool have_copy_request = false;
787 int layers_drawn = 0;
789 const DrawMode draw_mode = GetDrawMode(output_surface_.get());
791 LayerIteratorType end =
792 LayerIteratorType::End(frame->render_surface_layer_list);
793 for (LayerIteratorType it =
794 LayerIteratorType::Begin(frame->render_surface_layer_list);
795 it != end;
796 ++it) {
797 RenderPass::Id target_render_pass_id =
798 it.target_render_surface_layer()->render_surface()->RenderPassId();
799 RenderPass* target_render_pass =
800 frame->render_passes_by_id[target_render_pass_id];
802 occlusion_tracker.EnterLayer(it);
804 AppendQuadsData append_quads_data(target_render_pass_id);
806 if (it.represents_target_render_surface()) {
807 if (it->HasCopyRequest()) {
808 have_copy_request = true;
809 it->TakeCopyRequestsAndTransformToTarget(
810 &target_render_pass->copy_requests);
812 } else if (it.represents_contributing_render_surface() &&
813 it->render_surface()->contributes_to_drawn_surface()) {
814 RenderPass::Id contributing_render_pass_id =
815 it->render_surface()->RenderPassId();
816 RenderPass* contributing_render_pass =
817 frame->render_passes_by_id[contributing_render_pass_id];
818 AppendQuadsForRenderSurfaceLayer(target_render_pass,
819 *it,
820 contributing_render_pass,
821 occlusion_tracker,
822 &append_quads_data);
823 } else if (it.represents_itself() && it->DrawsContent() &&
824 !it->visible_content_rect().IsEmpty()) {
825 bool impl_draw_transform_is_unknown = false;
826 bool occluded = occlusion_tracker.Occluded(
827 it->render_target(),
828 it->visible_content_rect(),
829 it->draw_transform(),
830 impl_draw_transform_is_unknown);
831 if (!occluded && it->WillDraw(draw_mode, resource_provider_.get())) {
832 DCHECK_EQ(active_tree_, it->layer_tree_impl());
834 frame->will_draw_layers.push_back(*it);
836 if (it->HasContributingDelegatedRenderPasses()) {
837 RenderPass::Id contributing_render_pass_id =
838 it->FirstContributingRenderPassId();
839 while (frame->render_passes_by_id.find(contributing_render_pass_id) !=
840 frame->render_passes_by_id.end()) {
841 RenderPass* render_pass =
842 frame->render_passes_by_id[contributing_render_pass_id];
844 AppendQuadsData append_quads_data(render_pass->id);
845 AppendQuadsForLayer(render_pass,
846 *it,
847 occlusion_tracker,
848 &append_quads_data);
850 contributing_render_pass_id =
851 it->NextContributingRenderPassId(contributing_render_pass_id);
855 AppendQuadsForLayer(target_render_pass,
856 *it,
857 occlusion_tracker,
858 &append_quads_data);
861 ++layers_drawn;
864 if (append_quads_data.num_missing_tiles) {
865 bool layer_has_animating_transform =
866 it->screen_space_transform_is_animating() ||
867 it->draw_transform_is_animating();
868 if (layer_has_animating_transform)
869 draw_frame = false;
872 if (append_quads_data.had_incomplete_tile)
873 frame->contains_incomplete_tile = true;
875 occlusion_tracker.LeaveLayer(it);
878 if (have_copy_request ||
879 output_surface_->capabilities().draw_and_swap_full_viewport_every_frame)
880 draw_frame = true;
882 #ifndef NDEBUG
883 for (size_t i = 0; i < frame->render_passes.size(); ++i) {
884 for (size_t j = 0; j < frame->render_passes[i]->quad_list.size(); ++j)
885 DCHECK(frame->render_passes[i]->quad_list[j]->shared_quad_state);
886 DCHECK(frame->render_passes_by_id.find(frame->render_passes[i]->id)
887 != frame->render_passes_by_id.end());
889 #endif
890 DCHECK(frame->render_passes.back()->output_rect.origin().IsOrigin());
892 if (!active_tree_->has_transparent_background()) {
893 frame->render_passes.back()->has_transparent_background = false;
894 AppendQuadsToFillScreen(
895 ResourceIdForUIResource(overhang_ui_resource_id_),
896 gfx::ScaleSize(overhang_ui_resource_size_, device_scale_factor_),
897 active_tree_->RootScrollLayerDeviceViewportBounds(),
898 frame->render_passes.back(),
899 active_tree_->root_layer(),
900 active_tree_->background_color(),
901 occlusion_tracker);
904 if (draw_frame)
905 occlusion_tracker.overdraw_metrics()->RecordMetrics(this);
906 else
907 DCHECK(!have_copy_request);
909 RemoveRenderPasses(CullRenderPassesWithNoQuads(), frame);
910 renderer_->DecideRenderPassAllocationsForFrame(frame->render_passes);
912 // Any copy requests left in the tree are not going to get serviced, and
913 // should be aborted.
914 ScopedPtrVector<CopyOutputRequest> requests_to_abort;
915 while (!active_tree_->LayersWithCopyOutputRequest().empty()) {
916 LayerImpl* layer = active_tree_->LayersWithCopyOutputRequest().back();
917 layer->TakeCopyRequestsAndTransformToTarget(&requests_to_abort);
919 for (size_t i = 0; i < requests_to_abort.size(); ++i)
920 requests_to_abort[i]->SendEmptyResult();
922 // If we're making a frame to draw, it better have at least one render pass.
923 DCHECK(!frame->render_passes.empty());
925 // Should only have one render pass in resourceless software mode.
926 if (output_surface_->ForcedDrawToSoftwareDevice())
927 DCHECK_EQ(1u, frame->render_passes.size());
929 return draw_frame;
932 void LayerTreeHostImpl::MainThreadHasStoppedFlinging() {
933 if (input_handler_client_)
934 input_handler_client_->MainThreadHasStoppedFlinging();
937 void LayerTreeHostImpl::UpdateBackgroundAnimateTicking(
938 bool should_background_tick) {
939 DCHECK(proxy_->IsImplThread());
940 if (should_background_tick)
941 DCHECK(active_tree_->root_layer());
943 bool enabled = should_background_tick &&
944 !animation_registrar_->active_animation_controllers().empty();
946 // Lazily create the time_source adapter so that we can vary the interval for
947 // testing.
948 if (!time_source_client_adapter_) {
949 time_source_client_adapter_ = LayerTreeHostImplTimeSourceAdapter::Create(
950 this,
951 DelayBasedTimeSource::Create(
952 LowFrequencyAnimationInterval(),
953 proxy_->HasImplThread() ? proxy_->ImplThreadTaskRunner()
954 : proxy_->MainThreadTaskRunner()));
957 time_source_client_adapter_->SetActive(enabled);
960 void LayerTreeHostImpl::DidAnimateScrollOffset() {
961 client_->SetNeedsCommitOnImplThread();
962 client_->RenewTreePriority();
965 void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) {
966 viewport_damage_rect_.Union(damage_rect);
969 static inline RenderPass* FindRenderPassById(
970 RenderPass::Id render_pass_id,
971 const LayerTreeHostImpl::FrameData& frame) {
972 RenderPassIdHashMap::const_iterator it =
973 frame.render_passes_by_id.find(render_pass_id);
974 return it != frame.render_passes_by_id.end() ? it->second : NULL;
977 static void RemoveRenderPassesRecursive(RenderPass::Id remove_render_pass_id,
978 LayerTreeHostImpl::FrameData* frame) {
979 RenderPass* remove_render_pass =
980 FindRenderPassById(remove_render_pass_id, *frame);
981 // The pass was already removed by another quad - probably the original, and
982 // we are the replica.
983 if (!remove_render_pass)
984 return;
985 RenderPassList& render_passes = frame->render_passes;
986 RenderPassList::iterator to_remove = std::find(render_passes.begin(),
987 render_passes.end(),
988 remove_render_pass);
990 DCHECK(to_remove != render_passes.end());
992 scoped_ptr<RenderPass> removed_pass = render_passes.take(to_remove);
993 frame->render_passes.erase(to_remove);
994 frame->render_passes_by_id.erase(remove_render_pass_id);
996 // Now follow up for all RenderPass quads and remove their RenderPasses
997 // recursively.
998 const QuadList& quad_list = removed_pass->quad_list;
999 QuadList::ConstBackToFrontIterator quad_list_iterator =
1000 quad_list.BackToFrontBegin();
1001 for (; quad_list_iterator != quad_list.BackToFrontEnd();
1002 ++quad_list_iterator) {
1003 DrawQuad* current_quad = (*quad_list_iterator);
1004 if (current_quad->material != DrawQuad::RENDER_PASS)
1005 continue;
1007 RenderPass::Id next_remove_render_pass_id =
1008 RenderPassDrawQuad::MaterialCast(current_quad)->render_pass_id;
1009 RemoveRenderPassesRecursive(next_remove_render_pass_id, frame);
1013 bool LayerTreeHostImpl::CullRenderPassesWithNoQuads::ShouldRemoveRenderPass(
1014 const RenderPassDrawQuad& quad, const FrameData& frame) const {
1015 const RenderPass* render_pass =
1016 FindRenderPassById(quad.render_pass_id, frame);
1017 if (!render_pass)
1018 return false;
1020 // If any quad or RenderPass draws into this RenderPass, then keep it.
1021 const QuadList& quad_list = render_pass->quad_list;
1022 for (QuadList::ConstBackToFrontIterator quad_list_iterator =
1023 quad_list.BackToFrontBegin();
1024 quad_list_iterator != quad_list.BackToFrontEnd();
1025 ++quad_list_iterator) {
1026 DrawQuad* current_quad = *quad_list_iterator;
1028 if (current_quad->material != DrawQuad::RENDER_PASS)
1029 return false;
1031 const RenderPass* contributing_pass = FindRenderPassById(
1032 RenderPassDrawQuad::MaterialCast(current_quad)->render_pass_id, frame);
1033 if (contributing_pass)
1034 return false;
1036 return true;
1039 // Defined for linking tests.
1040 template CC_EXPORT void LayerTreeHostImpl::RemoveRenderPasses<
1041 LayerTreeHostImpl::CullRenderPassesWithNoQuads>(
1042 CullRenderPassesWithNoQuads culler, FrameData*);
1044 // static
1045 template <typename RenderPassCuller>
1046 void LayerTreeHostImpl::RemoveRenderPasses(RenderPassCuller culler,
1047 FrameData* frame) {
1048 for (size_t it = culler.RenderPassListBegin(frame->render_passes);
1049 it != culler.RenderPassListEnd(frame->render_passes);
1050 it = culler.RenderPassListNext(it)) {
1051 const RenderPass* current_pass = frame->render_passes[it];
1052 const QuadList& quad_list = current_pass->quad_list;
1053 QuadList::ConstBackToFrontIterator quad_list_iterator =
1054 quad_list.BackToFrontBegin();
1056 for (; quad_list_iterator != quad_list.BackToFrontEnd();
1057 ++quad_list_iterator) {
1058 DrawQuad* current_quad = *quad_list_iterator;
1060 if (current_quad->material != DrawQuad::RENDER_PASS)
1061 continue;
1063 const RenderPassDrawQuad* render_pass_quad =
1064 RenderPassDrawQuad::MaterialCast(current_quad);
1065 if (!culler.ShouldRemoveRenderPass(*render_pass_quad, *frame))
1066 continue;
1068 // We are changing the vector in the middle of iteration. Because we
1069 // delete render passes that draw into the current pass, we are
1070 // guaranteed that any data from the iterator to the end will not
1071 // change. So, capture the iterator position from the end of the
1072 // list, and restore it after the change.
1073 size_t position_from_end = frame->render_passes.size() - it;
1074 RemoveRenderPassesRecursive(render_pass_quad->render_pass_id, frame);
1075 it = frame->render_passes.size() - position_from_end;
1076 DCHECK_GE(frame->render_passes.size(), position_from_end);
1081 bool LayerTreeHostImpl::PrepareToDraw(FrameData* frame,
1082 const gfx::Rect& damage_rect) {
1083 TRACE_EVENT1("cc",
1084 "LayerTreeHostImpl::PrepareToDraw",
1085 "SourceFrameNumber",
1086 active_tree_->source_frame_number());
1088 if (need_to_update_visible_tiles_before_draw_ &&
1089 tile_manager_ && tile_manager_->UpdateVisibleTiles()) {
1090 DidInitializeVisibleTile();
1092 need_to_update_visible_tiles_before_draw_ = true;
1094 active_tree_->UpdateDrawProperties();
1096 frame->render_surface_layer_list = &active_tree_->RenderSurfaceLayerList();
1097 frame->render_passes.clear();
1098 frame->render_passes_by_id.clear();
1099 frame->will_draw_layers.clear();
1100 frame->contains_incomplete_tile = false;
1101 frame->has_no_damage = false;
1103 gfx::Rect device_viewport_damage_rect(damage_rect);
1104 if (active_tree_->root_layer()) {
1105 device_viewport_damage_rect.Union(viewport_damage_rect_);
1106 viewport_damage_rect_ = gfx::Rect();
1108 active_tree_->root_layer()->render_surface()->damage_tracker()->
1109 AddDamageNextUpdate(device_viewport_damage_rect);
1112 if (!CalculateRenderPasses(frame)) {
1113 DCHECK(!output_surface_->capabilities()
1114 .draw_and_swap_full_viewport_every_frame);
1115 return false;
1118 // If we return true, then we expect DrawLayers() to be called before this
1119 // function is called again.
1120 return true;
1123 void LayerTreeHostImpl::EvictTexturesForTesting() {
1124 EnforceManagedMemoryPolicy(ManagedMemoryPolicy(0));
1127 void LayerTreeHostImpl::BlockNotifyReadyToActivateForTesting(bool block) {
1128 NOTREACHED();
1131 void LayerTreeHostImpl::DidInitializeVisibleTileForTesting() {
1132 DidInitializeVisibleTile();
1135 void LayerTreeHostImpl::EnforceManagedMemoryPolicy(
1136 const ManagedMemoryPolicy& policy) {
1138 bool evicted_resources = client_->ReduceContentsTextureMemoryOnImplThread(
1139 visible_ ? policy.bytes_limit_when_visible : 0,
1140 ManagedMemoryPolicy::PriorityCutoffToValue(
1141 visible_ ? policy.priority_cutoff_when_visible
1142 : gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING));
1143 if (evicted_resources) {
1144 active_tree_->SetContentsTexturesPurged();
1145 if (pending_tree_)
1146 pending_tree_->SetContentsTexturesPurged();
1147 client_->SetNeedsCommitOnImplThread();
1148 client_->OnCanDrawStateChanged(CanDraw());
1149 client_->RenewTreePriority();
1151 client_->SendManagedMemoryStats();
1153 UpdateTileManagerMemoryPolicy(policy);
1156 void LayerTreeHostImpl::UpdateTileManagerMemoryPolicy(
1157 const ManagedMemoryPolicy& policy) {
1158 if (!tile_manager_)
1159 return;
1161 // TODO(reveman): We should avoid keeping around unused resources if
1162 // possible. crbug.com/224475
1163 global_tile_state_.memory_limit_in_bytes =
1164 visible_ ?
1165 policy.bytes_limit_when_visible : 0;
1166 global_tile_state_.unused_memory_limit_in_bytes = static_cast<size_t>(
1167 (static_cast<int64>(global_tile_state_.memory_limit_in_bytes) *
1168 settings_.max_unused_resource_memory_percentage) / 100);
1169 global_tile_state_.memory_limit_policy =
1170 ManagedMemoryPolicy::PriorityCutoffToTileMemoryLimitPolicy(
1171 visible_ ?
1172 policy.priority_cutoff_when_visible :
1173 gpu::MemoryAllocation::CUTOFF_ALLOW_NOTHING);
1174 global_tile_state_.num_resources_limit = policy.num_resources_limit;
1176 DidModifyTilePriorities();
1179 void LayerTreeHostImpl::DidModifyTilePriorities() {
1180 DCHECK(settings_.impl_side_painting);
1181 // Mark priorities as dirty and schedule a ManageTiles().
1182 tile_priorities_dirty_ = true;
1183 client_->SetNeedsManageTilesOnImplThread();
1186 void LayerTreeHostImpl::DidInitializeVisibleTile() {
1187 // TODO(reveman): Determine tiles that changed and only damage
1188 // what's necessary.
1189 SetFullRootLayerDamage();
1190 if (client_ && !client_->IsInsideDraw())
1191 client_->DidInitializeVisibleTileOnImplThread();
1194 void LayerTreeHostImpl::NotifyReadyToActivate() {
1195 client_->NotifyReadyToActivate();
1198 void LayerTreeHostImpl::SetMemoryPolicy(const ManagedMemoryPolicy& policy) {
1199 SetManagedMemoryPolicy(policy, zero_budget_);
1202 void LayerTreeHostImpl::SetTreeActivationCallback(
1203 const base::Closure& callback) {
1204 DCHECK(proxy_->IsImplThread());
1205 DCHECK(settings_.impl_side_painting || callback.is_null());
1206 tree_activation_callback_ = callback;
1209 void LayerTreeHostImpl::SetManagedMemoryPolicy(
1210 const ManagedMemoryPolicy& policy, bool zero_budget) {
1211 if (cached_managed_memory_policy_ == policy && zero_budget_ == zero_budget)
1212 return;
1214 ManagedMemoryPolicy old_policy = ActualManagedMemoryPolicy();
1216 cached_managed_memory_policy_ = policy;
1217 zero_budget_ = zero_budget;
1218 ManagedMemoryPolicy actual_policy = ActualManagedMemoryPolicy();
1220 if (old_policy == actual_policy)
1221 return;
1223 if (!proxy_->HasImplThread()) {
1224 // In single-thread mode, this can be called on the main thread by
1225 // GLRenderer::OnMemoryAllocationChanged.
1226 DebugScopedSetImplThread impl_thread(proxy_);
1227 EnforceManagedMemoryPolicy(actual_policy);
1228 } else {
1229 DCHECK(proxy_->IsImplThread());
1230 EnforceManagedMemoryPolicy(actual_policy);
1233 // If there is already enough memory to draw everything imaginable and the
1234 // new memory limit does not change this, then do not re-commit. Don't bother
1235 // skipping commits if this is not visible (commits don't happen when not
1236 // visible, there will almost always be a commit when this becomes visible).
1237 bool needs_commit = true;
1238 if (visible() &&
1239 actual_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1240 old_policy.bytes_limit_when_visible >= max_memory_needed_bytes_ &&
1241 actual_policy.priority_cutoff_when_visible ==
1242 old_policy.priority_cutoff_when_visible) {
1243 needs_commit = false;
1246 if (needs_commit)
1247 client_->SetNeedsCommitOnImplThread();
1250 void LayerTreeHostImpl::SetExternalDrawConstraints(
1251 const gfx::Transform& transform,
1252 const gfx::Rect& viewport,
1253 const gfx::Rect& clip,
1254 bool valid_for_tile_management) {
1255 external_transform_ = transform;
1256 external_viewport_ = viewport;
1257 external_clip_ = clip;
1258 device_viewport_valid_for_tile_management_ = valid_for_tile_management;
1261 void LayerTreeHostImpl::SetNeedsRedrawRect(const gfx::Rect& damage_rect) {
1262 if (damage_rect.IsEmpty())
1263 return;
1264 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1265 client_->SetNeedsRedrawRectOnImplThread(damage_rect);
1268 void LayerTreeHostImpl::BeginImplFrame(const BeginFrameArgs& args) {
1269 client_->BeginImplFrame(args);
1272 void LayerTreeHostImpl::DidSwapBuffers() {
1273 client_->DidSwapBuffersOnImplThread();
1276 void LayerTreeHostImpl::OnSwapBuffersComplete() {
1277 client_->OnSwapBuffersCompleteOnImplThread();
1280 void LayerTreeHostImpl::ReclaimResources(const CompositorFrameAck* ack) {
1281 // TODO(piman): We may need to do some validation on this ack before
1282 // processing it.
1283 if (renderer_)
1284 renderer_->ReceiveSwapBuffersAck(*ack);
1287 void LayerTreeHostImpl::OnCanDrawStateChangedForTree() {
1288 client_->OnCanDrawStateChanged(CanDraw());
1291 CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
1292 CompositorFrameMetadata metadata;
1293 metadata.device_scale_factor = device_scale_factor_;
1294 metadata.page_scale_factor = active_tree_->total_page_scale_factor();
1295 metadata.viewport_size = active_tree_->ScrollableViewportSize();
1296 metadata.root_layer_size = active_tree_->ScrollableSize();
1297 metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
1298 metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
1299 if (top_controls_manager_) {
1300 metadata.location_bar_offset =
1301 gfx::Vector2dF(0.f, top_controls_manager_->controls_top_offset());
1302 metadata.location_bar_content_translation =
1303 gfx::Vector2dF(0.f, top_controls_manager_->content_top_offset());
1304 metadata.overdraw_bottom_height = overdraw_bottom_height_;
1307 if (!RootScrollLayer())
1308 return metadata;
1310 metadata.root_scroll_offset = RootScrollLayer()->TotalScrollOffset();
1312 return metadata;
1315 static void LayerTreeHostImplDidBeginTracingCallback(LayerImpl* layer) {
1316 layer->DidBeginTracing();
1319 void LayerTreeHostImpl::DrawLayers(FrameData* frame,
1320 base::TimeTicks frame_begin_time) {
1321 TRACE_EVENT0("cc", "LayerTreeHostImpl::DrawLayers");
1322 DCHECK(CanDraw());
1324 if (frame->has_no_damage) {
1325 TRACE_EVENT0("cc", "EarlyOut_NoDamage");
1326 DCHECK(!output_surface_->capabilities()
1327 .draw_and_swap_full_viewport_every_frame);
1328 return;
1331 DCHECK(!frame->render_passes.empty());
1333 fps_counter_->SaveTimeStamp(frame_begin_time,
1334 !output_surface_->context_provider());
1336 bool on_main_thread = false;
1337 rendering_stats_instrumentation_->IncrementFrameCount(
1338 1, on_main_thread);
1340 if (tile_manager_) {
1341 memory_history_->SaveEntry(
1342 tile_manager_->memory_stats_from_last_assign());
1345 if (debug_state_.ShowHudRects()) {
1346 debug_rect_history_->SaveDebugRectsForCurrentFrame(
1347 active_tree_->root_layer(),
1348 *frame->render_surface_layer_list,
1349 frame->occluding_screen_space_rects,
1350 frame->non_occluding_screen_space_rects,
1351 debug_state_);
1354 if (!settings_.impl_side_painting && debug_state_.continuous_painting) {
1355 const RenderingStats& stats =
1356 rendering_stats_instrumentation_->GetRenderingStats();
1357 paint_time_counter_->SavePaintTime(stats.main_stats.paint_time);
1360 bool is_new_trace;
1361 TRACE_EVENT_IS_NEW_TRACE(&is_new_trace);
1362 if (is_new_trace) {
1363 if (pending_tree_) {
1364 LayerTreeHostCommon::CallFunctionForSubtree(
1365 pending_tree_->root_layer(),
1366 base::Bind(&LayerTreeHostImplDidBeginTracingCallback));
1368 LayerTreeHostCommon::CallFunctionForSubtree(
1369 active_tree_->root_layer(),
1370 base::Bind(&LayerTreeHostImplDidBeginTracingCallback));
1373 TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
1374 TRACE_DISABLED_BY_DEFAULT("cc.debug") ","
1375 TRACE_DISABLED_BY_DEFAULT("cc.debug.quads"), "cc::LayerTreeHostImpl",
1376 this, TracedValue::FromValue(AsValueWithFrame(frame).release()));
1378 // Because the contents of the HUD depend on everything else in the frame, the
1379 // contents of its texture are updated as the last thing before the frame is
1380 // drawn.
1381 if (active_tree_->hud_layer()) {
1382 TRACE_EVENT0("cc", "DrawLayers.UpdateHudTexture");
1383 active_tree_->hud_layer()->UpdateHudTexture(
1384 GetDrawMode(output_surface_.get()), resource_provider_.get());
1387 if (output_surface_->ForcedDrawToSoftwareDevice()) {
1388 bool allow_partial_swap = false;
1389 bool disable_picture_quad_image_filtering =
1390 IsCurrentlyScrolling() || needs_animate_layers();
1392 scoped_ptr<SoftwareRenderer> temp_software_renderer =
1393 SoftwareRenderer::Create(this, &settings_, output_surface_.get(), NULL);
1394 temp_software_renderer->DrawFrame(&frame->render_passes,
1395 NULL,
1396 device_scale_factor_,
1397 DeviceViewport(),
1398 DeviceClip(),
1399 allow_partial_swap,
1400 disable_picture_quad_image_filtering);
1401 } else {
1402 // We don't track damage on the HUD layer (it interacts with damage tracking
1403 // visualizations), so disable partial swaps to make the HUD layer display
1404 // properly.
1405 bool allow_partial_swap = !debug_state_.ShowHudRects();
1407 renderer_->DrawFrame(&frame->render_passes,
1408 offscreen_context_provider_.get(),
1409 device_scale_factor_,
1410 DeviceViewport(),
1411 DeviceClip(),
1412 allow_partial_swap,
1413 false);
1415 // The render passes should be consumed by the renderer.
1416 DCHECK(frame->render_passes.empty());
1417 frame->render_passes_by_id.clear();
1419 // The next frame should start by assuming nothing has changed, and changes
1420 // are noted as they occur.
1421 // TODO(boliu): If we did a temporary software renderer frame, propogate the
1422 // damage forward to the next frame.
1423 for (size_t i = 0; i < frame->render_surface_layer_list->size(); i++) {
1424 (*frame->render_surface_layer_list)[i]->render_surface()->damage_tracker()->
1425 DidDrawDamagedArea();
1427 active_tree_->root_layer()->ResetAllChangeTrackingForSubtree();
1429 BenchmarkInstrumentation::IssueImplThreadRenderingStatsEvent(
1430 rendering_stats_instrumentation_->impl_thread_rendering_stats());
1431 rendering_stats_instrumentation_->AccumulateAndClearImplThreadStats();
1434 void LayerTreeHostImpl::DidDrawAllLayers(const FrameData& frame) {
1435 for (size_t i = 0; i < frame.will_draw_layers.size(); ++i)
1436 frame.will_draw_layers[i]->DidDraw(resource_provider_.get());
1438 // Once all layers have been drawn, pending texture uploads should no
1439 // longer block future uploads.
1440 resource_provider_->MarkPendingUploadsAsNonBlocking();
1443 void LayerTreeHostImpl::FinishAllRendering() {
1444 if (renderer_)
1445 renderer_->Finish();
1448 bool LayerTreeHostImpl::IsContextLost() {
1449 DCHECK(proxy_->IsImplThread());
1450 return renderer_ && renderer_->IsContextLost();
1453 const RendererCapabilitiesImpl&
1454 LayerTreeHostImpl::GetRendererCapabilities() const {
1455 return renderer_->Capabilities();
1458 bool LayerTreeHostImpl::SwapBuffers(const LayerTreeHostImpl::FrameData& frame) {
1459 if (frame.has_no_damage) {
1460 active_tree()->BreakSwapPromises(SwapPromise::SWAP_FAILS);
1461 return false;
1463 CompositorFrameMetadata metadata = MakeCompositorFrameMetadata();
1464 active_tree()->FinishSwapPromises(&metadata);
1465 renderer_->SwapBuffers(metadata);
1466 return true;
1469 void LayerTreeHostImpl::SetNeedsBeginImplFrame(bool enable) {
1470 if (output_surface_)
1471 output_surface_->SetNeedsBeginImplFrame(enable);
1474 gfx::SizeF LayerTreeHostImpl::UnscaledScrollableViewportSize() const {
1475 // Use the root container layer bounds if it clips to them, otherwise, the
1476 // true viewport size should be used.
1477 LayerImpl* container_layer = active_tree_->RootContainerLayer();
1478 if (container_layer && container_layer->masks_to_bounds()) {
1479 DCHECK(!top_controls_manager_);
1480 DCHECK_EQ(0, overdraw_bottom_height_);
1481 return container_layer->bounds();
1484 gfx::SizeF dip_size =
1485 gfx::ScaleSize(device_viewport_size_, 1.f / device_scale_factor());
1487 float top_offset =
1488 top_controls_manager_ ? top_controls_manager_->content_top_offset() : 0.f;
1489 return gfx::SizeF(dip_size.width(),
1490 dip_size.height() - top_offset - overdraw_bottom_height_);
1493 void LayerTreeHostImpl::DidLoseOutputSurface() {
1494 if (resource_provider_)
1495 resource_provider_->DidLoseOutputSurface();
1496 // TODO(jamesr): The renderer_ check is needed to make some of the
1497 // LayerTreeHostContextTest tests pass, but shouldn't be necessary (or
1498 // important) in production. We should adjust the test to not need this.
1499 if (renderer_)
1500 client_->DidLoseOutputSurfaceOnImplThread();
1501 #ifndef NDEBUG
1502 did_lose_called_ = true;
1503 #endif
1506 void LayerTreeHostImpl::Readback(void* pixels,
1507 const gfx::Rect& rect_in_device_viewport) {
1508 DCHECK(renderer_);
1509 renderer_->GetFramebufferPixels(pixels, rect_in_device_viewport);
1512 bool LayerTreeHostImpl::HaveRootScrollLayer() const {
1513 return !!RootScrollLayer();
1516 LayerImpl* LayerTreeHostImpl::RootLayer() const {
1517 return active_tree_->root_layer();
1520 LayerImpl* LayerTreeHostImpl::RootScrollLayer() const {
1521 return active_tree_->RootScrollLayer();
1524 LayerImpl* LayerTreeHostImpl::CurrentlyScrollingLayer() const {
1525 return active_tree_->CurrentlyScrollingLayer();
1528 bool LayerTreeHostImpl::IsCurrentlyScrolling() const {
1529 return CurrentlyScrollingLayer() ||
1530 (RootScrollLayer() && RootScrollLayer()->IsExternalFlingActive());
1533 // Content layers can be either directly scrollable or contained in an outer
1534 // scrolling layer which applies the scroll transform. Given a content layer,
1535 // this function returns the associated scroll layer if any.
1536 static LayerImpl* FindScrollLayerForContentLayer(LayerImpl* layer_impl) {
1537 if (!layer_impl)
1538 return NULL;
1540 if (layer_impl->scrollable())
1541 return layer_impl;
1543 if (layer_impl->DrawsContent() &&
1544 layer_impl->parent() &&
1545 layer_impl->parent()->scrollable())
1546 return layer_impl->parent();
1548 return NULL;
1551 void LayerTreeHostImpl::CreatePendingTree() {
1552 CHECK(!pending_tree_);
1553 if (recycle_tree_)
1554 recycle_tree_.swap(pending_tree_);
1555 else
1556 pending_tree_ = LayerTreeImpl::create(this);
1557 client_->OnCanDrawStateChanged(CanDraw());
1558 TRACE_EVENT_ASYNC_BEGIN0("cc", "PendingTree:waiting", pending_tree_.get());
1561 void LayerTreeHostImpl::UpdateVisibleTiles() {
1562 if (tile_manager_ && tile_manager_->UpdateVisibleTiles())
1563 DidInitializeVisibleTile();
1564 need_to_update_visible_tiles_before_draw_ = false;
1567 void LayerTreeHostImpl::ActivatePendingTree() {
1568 CHECK(pending_tree_);
1569 TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get());
1571 need_to_update_visible_tiles_before_draw_ = true;
1573 active_tree_->SetRootLayerScrollOffsetDelegate(NULL);
1574 active_tree_->PushPersistedState(pending_tree_.get());
1575 if (pending_tree_->needs_full_tree_sync()) {
1576 active_tree_->SetRootLayer(
1577 TreeSynchronizer::SynchronizeTrees(pending_tree_->root_layer(),
1578 active_tree_->DetachLayerTree(),
1579 active_tree_.get()));
1581 TreeSynchronizer::PushProperties(pending_tree_->root_layer(),
1582 active_tree_->root_layer());
1583 DCHECK(!recycle_tree_);
1585 // Process any requests in the UI resource queue. The request queue is given
1586 // in LayerTreeHost::FinishCommitOnImplThread. This must take place before
1587 // the swap.
1588 pending_tree_->ProcessUIResourceRequestQueue();
1590 pending_tree_->PushPropertiesTo(active_tree_.get());
1592 // Now that we've synced everything from the pending tree to the active
1593 // tree, rename the pending tree the recycle tree so we can reuse it on the
1594 // next sync.
1595 pending_tree_.swap(recycle_tree_);
1597 active_tree_->DidBecomeActive();
1598 active_tree_->SetRootLayerScrollOffsetDelegate(
1599 root_layer_scroll_offset_delegate_);
1601 client_->OnCanDrawStateChanged(CanDraw());
1602 SetNeedsRedraw();
1603 client_->RenewTreePriority();
1605 if (debug_state_.continuous_painting) {
1606 const RenderingStats& stats =
1607 rendering_stats_instrumentation_->GetRenderingStats();
1608 paint_time_counter_->SavePaintTime(stats.main_stats.paint_time +
1609 stats.main_stats.record_time +
1610 stats.impl_stats.rasterize_time);
1613 client_->DidActivatePendingTree();
1614 if (!tree_activation_callback_.is_null())
1615 tree_activation_callback_.Run();
1617 if (time_source_client_adapter_ && time_source_client_adapter_->Active())
1618 DCHECK(active_tree_->root_layer());
1619 devtools_instrumentation::didActivateLayerTree(id_,
1620 active_tree_->source_frame_number());
1623 void LayerTreeHostImpl::SetVisible(bool visible) {
1624 DCHECK(proxy_->IsImplThread());
1626 if (visible_ == visible)
1627 return;
1628 visible_ = visible;
1629 DidVisibilityChange(this, visible_);
1630 EnforceManagedMemoryPolicy(ActualManagedMemoryPolicy());
1632 if (!visible_)
1633 EvictAllUIResources();
1635 // Evict tiles immediately if invisible since this tab may never get another
1636 // draw or timer tick.
1637 if (!visible_)
1638 ManageTiles();
1640 if (!renderer_)
1641 return;
1643 renderer_->SetVisible(visible);
1646 void LayerTreeHostImpl::SetNeedsRedraw() {
1647 NotifySwapPromiseMonitorsOfSetNeedsRedraw();
1648 client_->SetNeedsRedrawOnImplThread();
1651 ManagedMemoryPolicy LayerTreeHostImpl::ActualManagedMemoryPolicy() const {
1652 ManagedMemoryPolicy actual = cached_managed_memory_policy_;
1653 // TODO(ernstm): The second condition disables pre-painting for all layers
1654 // when GPU rasterization is enabled. Once we selectively enable GPU
1655 // rasterization per layer, we also need to disable pre-painting selectively:
1656 // crbug.com/335387
1657 if (debug_state_.rasterize_only_visible_content ||
1658 settings_.gpu_rasterization) {
1659 actual.priority_cutoff_when_visible =
1660 gpu::MemoryAllocation::CUTOFF_ALLOW_REQUIRED_ONLY;
1663 if (zero_budget_) {
1664 actual.bytes_limit_when_visible = 0;
1667 return actual;
1670 size_t LayerTreeHostImpl::memory_allocation_limit_bytes() const {
1671 return ActualManagedMemoryPolicy().bytes_limit_when_visible;
1674 int LayerTreeHostImpl::memory_allocation_priority_cutoff() const {
1675 return ManagedMemoryPolicy::PriorityCutoffToValue(
1676 ActualManagedMemoryPolicy().priority_cutoff_when_visible);
1679 void LayerTreeHostImpl::ReleaseTreeResources() {
1680 if (active_tree_->root_layer())
1681 SendReleaseResourcesRecursive(active_tree_->root_layer());
1682 if (pending_tree_ && pending_tree_->root_layer())
1683 SendReleaseResourcesRecursive(pending_tree_->root_layer());
1684 if (recycle_tree_ && recycle_tree_->root_layer())
1685 SendReleaseResourcesRecursive(recycle_tree_->root_layer());
1687 EvictAllUIResources();
1690 void LayerTreeHostImpl::CreateAndSetRenderer(
1691 OutputSurface* output_surface,
1692 ResourceProvider* resource_provider,
1693 bool skip_gl_renderer) {
1694 DCHECK(!renderer_);
1695 if (output_surface->capabilities().delegated_rendering) {
1696 renderer_ = DelegatingRenderer::Create(
1697 this, &settings_, output_surface, resource_provider);
1698 } else if (output_surface->context_provider() && !skip_gl_renderer) {
1699 renderer_ = GLRenderer::Create(this,
1700 &settings_,
1701 output_surface,
1702 resource_provider,
1703 texture_mailbox_deleter_.get(),
1704 settings_.highp_threshold_min);
1705 } else if (output_surface->software_device()) {
1706 renderer_ = SoftwareRenderer::Create(
1707 this, &settings_, output_surface, resource_provider);
1710 if (renderer_) {
1711 renderer_->SetVisible(visible_);
1712 SetFullRootLayerDamage();
1714 // See note in LayerTreeImpl::UpdateDrawProperties. Renderer needs to be
1715 // initialized to get max texture size. Also, after releasing resources,
1716 // trees need another update to generate new ones.
1717 active_tree_->set_needs_update_draw_properties();
1718 if (pending_tree_)
1719 pending_tree_->set_needs_update_draw_properties();
1723 void LayerTreeHostImpl::CreateAndSetTileManager(
1724 ResourceProvider* resource_provider,
1725 ContextProvider* context_provider,
1726 bool using_map_image) {
1727 DCHECK(settings_.impl_side_painting);
1728 DCHECK(resource_provider);
1729 tile_manager_ =
1730 TileManager::Create(this,
1731 resource_provider,
1732 context_provider,
1733 rendering_stats_instrumentation_,
1734 using_map_image,
1735 GetMaxTransferBufferUsageBytes(context_provider),
1736 GetMaxRasterTasksUsageBytes(context_provider),
1737 GetMapImageTextureTarget(context_provider));
1739 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
1740 need_to_update_visible_tiles_before_draw_ = false;
1743 void LayerTreeHostImpl::EnforceZeroBudget(bool zero_budget) {
1744 SetManagedMemoryPolicy(cached_managed_memory_policy_, zero_budget);
1747 bool LayerTreeHostImpl::InitializeRenderer(
1748 scoped_ptr<OutputSurface> output_surface) {
1749 #ifndef NDEBUG
1750 DCHECK(!renderer_ || did_lose_called_);
1751 #endif
1753 // Since we will create a new resource provider, we cannot continue to use
1754 // the old resources (i.e. render_surfaces and texture IDs). Clear them
1755 // before we destroy the old resource provider.
1756 ReleaseTreeResources();
1758 // Note: order is important here.
1759 renderer_.reset();
1760 tile_manager_.reset();
1761 resource_provider_.reset();
1762 output_surface_.reset();
1764 if (!output_surface->BindToClient(this))
1765 return false;
1767 scoped_ptr<ResourceProvider> resource_provider =
1768 ResourceProvider::Create(output_surface.get(),
1769 shared_bitmap_manager_,
1770 settings_.highp_threshold_min,
1771 settings_.use_rgba_4444_textures,
1772 settings_.texture_id_allocation_chunk_size);
1773 if (!resource_provider)
1774 return false;
1776 if (output_surface->capabilities().deferred_gl_initialization)
1777 EnforceZeroBudget(true);
1779 bool skip_gl_renderer = false;
1780 CreateAndSetRenderer(
1781 output_surface.get(), resource_provider.get(), skip_gl_renderer);
1783 if (!renderer_)
1784 return false;
1786 if (settings_.impl_side_painting) {
1787 CreateAndSetTileManager(resource_provider.get(),
1788 output_surface->context_provider().get(),
1789 GetRendererCapabilities().using_map_image);
1792 // Setup BeginImplFrameEmulation if it's not supported natively
1793 if (!settings_.begin_impl_frame_scheduling_enabled) {
1794 const base::TimeDelta display_refresh_interval =
1795 base::TimeDelta::FromMicroseconds(
1796 base::Time::kMicrosecondsPerSecond /
1797 settings_.refresh_rate);
1799 output_surface->InitializeBeginImplFrameEmulation(
1800 proxy_->ImplThreadTaskRunner(),
1801 settings_.throttle_frame_production,
1802 display_refresh_interval);
1805 int max_frames_pending =
1806 output_surface->capabilities().max_frames_pending;
1807 if (max_frames_pending <= 0)
1808 max_frames_pending = OutputSurface::DEFAULT_MAX_FRAMES_PENDING;
1809 output_surface->SetMaxFramesPending(max_frames_pending);
1811 resource_provider_ = resource_provider.Pass();
1812 output_surface_ = output_surface.Pass();
1814 client_->OnCanDrawStateChanged(CanDraw());
1816 return true;
1819 bool LayerTreeHostImpl::DeferredInitialize(
1820 scoped_refptr<ContextProvider> offscreen_context_provider) {
1821 DCHECK(output_surface_->capabilities().deferred_gl_initialization);
1822 DCHECK(settings_.impl_side_painting);
1823 DCHECK(output_surface_->context_provider());
1825 ReleaseTreeResources();
1826 renderer_.reset();
1828 bool resource_provider_success = resource_provider_->InitializeGL();
1830 bool success = resource_provider_success;
1831 if (success) {
1832 bool skip_gl_renderer = false;
1833 CreateAndSetRenderer(
1834 output_surface_.get(), resource_provider_.get(), skip_gl_renderer);
1835 if (!renderer_)
1836 success = false;
1839 if (success) {
1840 if (offscreen_context_provider.get() &&
1841 !offscreen_context_provider->BindToCurrentThread())
1842 success = false;
1845 if (success) {
1846 EnforceZeroBudget(false);
1847 client_->SetNeedsCommitOnImplThread();
1848 } else {
1849 if (offscreen_context_provider.get()) {
1850 if (offscreen_context_provider->BindToCurrentThread())
1851 offscreen_context_provider->VerifyContexts();
1852 offscreen_context_provider = NULL;
1855 client_->DidLoseOutputSurfaceOnImplThread();
1857 if (resource_provider_success) {
1858 // If this fails the context provider will be dropped from the output
1859 // surface and destroyed. But the GLRenderer expects the output surface
1860 // to stick around - and hold onto the context3d - as long as it is alive.
1861 // TODO(danakj): Remove the need for this code path: crbug.com/276411
1862 renderer_.reset();
1864 // The resource provider can't stay in GL mode or it tries to clean up GL
1865 // stuff, but the context provider is going away on the output surface
1866 // which contradicts being in GL mode.
1867 // TODO(danakj): Remove the need for this code path: crbug.com/276411
1868 resource_provider_->InitializeSoftware();
1872 SetOffscreenContextProvider(offscreen_context_provider);
1873 return success;
1876 void LayerTreeHostImpl::ReleaseGL() {
1877 DCHECK(output_surface_->capabilities().deferred_gl_initialization);
1878 DCHECK(settings_.impl_side_painting);
1879 DCHECK(output_surface_->context_provider());
1881 ReleaseTreeResources();
1882 renderer_.reset();
1883 tile_manager_.reset();
1884 resource_provider_->InitializeSoftware();
1886 bool skip_gl_renderer = true;
1887 CreateAndSetRenderer(
1888 output_surface_.get(), resource_provider_.get(), skip_gl_renderer);
1889 DCHECK(renderer_);
1891 EnforceZeroBudget(true);
1892 CreateAndSetTileManager(resource_provider_.get(),
1893 NULL,
1894 GetRendererCapabilities().using_map_image);
1895 DCHECK(tile_manager_);
1897 SetOffscreenContextProvider(NULL);
1899 client_->SetNeedsCommitOnImplThread();
1902 void LayerTreeHostImpl::SetViewportSize(gfx::Size device_viewport_size) {
1903 if (device_viewport_size == device_viewport_size_)
1904 return;
1906 if (pending_tree_)
1907 active_tree_->SetViewportSizeInvalid();
1909 device_viewport_size_ = device_viewport_size;
1911 UpdateMaxScrollOffset();
1913 client_->OnCanDrawStateChanged(CanDraw());
1914 SetFullRootLayerDamage();
1917 void LayerTreeHostImpl::SetOverdrawBottomHeight(float overdraw_bottom_height) {
1918 if (overdraw_bottom_height == overdraw_bottom_height_)
1919 return;
1920 overdraw_bottom_height_ = overdraw_bottom_height;
1922 UpdateMaxScrollOffset();
1923 SetFullRootLayerDamage();
1926 void LayerTreeHostImpl::SetOverhangUIResource(
1927 UIResourceId overhang_ui_resource_id,
1928 gfx::Size overhang_ui_resource_size) {
1929 overhang_ui_resource_id_ = overhang_ui_resource_id;
1930 overhang_ui_resource_size_ = overhang_ui_resource_size;
1933 void LayerTreeHostImpl::SetDeviceScaleFactor(float device_scale_factor) {
1934 if (device_scale_factor == device_scale_factor_)
1935 return;
1936 device_scale_factor_ = device_scale_factor;
1938 UpdateMaxScrollOffset();
1939 SetFullRootLayerDamage();
1942 gfx::Size LayerTreeHostImpl::DrawViewportSize() const {
1943 return DeviceViewport().size();
1946 gfx::Rect LayerTreeHostImpl::DeviceViewport() const {
1947 if (external_viewport_.IsEmpty())
1948 return gfx::Rect(device_viewport_size_);
1950 return external_viewport_;
1953 gfx::Rect LayerTreeHostImpl::DeviceClip() const {
1954 if (external_clip_.IsEmpty())
1955 return DeviceViewport();
1957 return external_clip_;
1960 const gfx::Transform& LayerTreeHostImpl::DrawTransform() const {
1961 return external_transform_;
1964 void LayerTreeHostImpl::UpdateMaxScrollOffset() {
1965 active_tree_->UpdateMaxScrollOffset();
1968 void LayerTreeHostImpl::DidChangeTopControlsPosition() {
1969 SetNeedsRedraw();
1970 active_tree_->set_needs_update_draw_properties();
1971 SetFullRootLayerDamage();
1974 bool LayerTreeHostImpl::EnsureRenderSurfaceLayerList() {
1975 active_tree_->UpdateDrawProperties();
1976 return !active_tree_->RenderSurfaceLayerList().empty();
1979 void LayerTreeHostImpl::BindToClient(InputHandlerClient* client) {
1980 DCHECK(input_handler_client_ == NULL);
1981 input_handler_client_ = client;
1984 static LayerImpl* NextScrollLayer(LayerImpl* layer) {
1985 if (LayerImpl* scroll_parent = layer->scroll_parent())
1986 return scroll_parent;
1987 return layer->parent();
1990 LayerImpl* LayerTreeHostImpl::FindScrollLayerForDeviceViewportPoint(
1991 const gfx::PointF& device_viewport_point,
1992 InputHandler::ScrollInputType type,
1993 LayerImpl* layer_impl, bool* scroll_on_main_thread) const {
1994 DCHECK(scroll_on_main_thread);
1996 // Walk up the hierarchy and look for a scrollable layer.
1997 LayerImpl* potentially_scrolling_layer_impl = 0;
1998 for (; layer_impl; layer_impl = NextScrollLayer(layer_impl)) {
1999 // The content layer can also block attempts to scroll outside the main
2000 // thread.
2001 ScrollStatus status = layer_impl->TryScroll(device_viewport_point, type);
2002 if (status == ScrollOnMainThread) {
2003 *scroll_on_main_thread = true;
2004 return NULL;
2007 LayerImpl* scroll_layer_impl = FindScrollLayerForContentLayer(layer_impl);
2008 if (!scroll_layer_impl)
2009 continue;
2011 status = scroll_layer_impl->TryScroll(device_viewport_point, type);
2012 // If any layer wants to divert the scroll event to the main thread, abort.
2013 if (status == ScrollOnMainThread) {
2014 *scroll_on_main_thread = true;
2015 return NULL;
2018 if (status == ScrollStarted && !potentially_scrolling_layer_impl)
2019 potentially_scrolling_layer_impl = scroll_layer_impl;
2022 return potentially_scrolling_layer_impl;
2025 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollBegin(
2026 gfx::Point viewport_point, InputHandler::ScrollInputType type) {
2027 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBegin");
2029 if (top_controls_manager_)
2030 top_controls_manager_->ScrollBegin();
2032 DCHECK(!CurrentlyScrollingLayer());
2033 ClearCurrentlyScrollingLayer();
2035 if (!EnsureRenderSurfaceLayerList())
2036 return ScrollIgnored;
2038 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2039 device_scale_factor_);
2040 LayerImpl* layer_impl = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
2041 device_viewport_point,
2042 active_tree_->RenderSurfaceLayerList());
2043 bool scroll_on_main_thread = false;
2044 LayerImpl* potentially_scrolling_layer_impl =
2045 FindScrollLayerForDeviceViewportPoint(device_viewport_point, type,
2046 layer_impl, &scroll_on_main_thread);
2048 if (scroll_on_main_thread) {
2049 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", true);
2050 return ScrollOnMainThread;
2053 if (!potentially_scrolling_layer_impl)
2054 potentially_scrolling_layer_impl = RootScrollLayer();
2056 if (potentially_scrolling_layer_impl) {
2057 active_tree_->SetCurrentlyScrollingLayer(
2058 potentially_scrolling_layer_impl);
2059 should_bubble_scrolls_ = (type != NonBubblingGesture);
2060 wheel_scrolling_ = (type == Wheel);
2061 client_->RenewTreePriority();
2062 UMA_HISTOGRAM_BOOLEAN("TryScroll.SlowScroll", false);
2063 return ScrollStarted;
2065 return ScrollIgnored;
2068 gfx::Vector2dF LayerTreeHostImpl::ScrollLayerWithViewportSpaceDelta(
2069 LayerImpl* layer_impl,
2070 float scale_from_viewport_to_screen_space,
2071 const gfx::PointF& viewport_point,
2072 const gfx::Vector2dF& viewport_delta) {
2073 // Layers with non-invertible screen space transforms should not have passed
2074 // the scroll hit test in the first place.
2075 DCHECK(layer_impl->screen_space_transform().IsInvertible());
2076 gfx::Transform inverse_screen_space_transform(
2077 gfx::Transform::kSkipInitialization);
2078 bool did_invert = layer_impl->screen_space_transform().GetInverse(
2079 &inverse_screen_space_transform);
2080 // TODO(shawnsingh): With the advent of impl-side crolling for non-root
2081 // layers, we may need to explicitly handle uninvertible transforms here.
2082 DCHECK(did_invert);
2084 gfx::PointF screen_space_point =
2085 gfx::ScalePoint(viewport_point, scale_from_viewport_to_screen_space);
2087 gfx::Vector2dF screen_space_delta = viewport_delta;
2088 screen_space_delta.Scale(scale_from_viewport_to_screen_space);
2090 // First project the scroll start and end points to local layer space to find
2091 // the scroll delta in layer coordinates.
2092 bool start_clipped, end_clipped;
2093 gfx::PointF screen_space_end_point = screen_space_point + screen_space_delta;
2094 gfx::PointF local_start_point =
2095 MathUtil::ProjectPoint(inverse_screen_space_transform,
2096 screen_space_point,
2097 &start_clipped);
2098 gfx::PointF local_end_point =
2099 MathUtil::ProjectPoint(inverse_screen_space_transform,
2100 screen_space_end_point,
2101 &end_clipped);
2103 // In general scroll point coordinates should not get clipped.
2104 DCHECK(!start_clipped);
2105 DCHECK(!end_clipped);
2106 if (start_clipped || end_clipped)
2107 return gfx::Vector2dF();
2109 // local_start_point and local_end_point are in content space but we want to
2110 // move them to layer space for scrolling.
2111 float width_scale = 1.f / layer_impl->contents_scale_x();
2112 float height_scale = 1.f / layer_impl->contents_scale_y();
2113 local_start_point.Scale(width_scale, height_scale);
2114 local_end_point.Scale(width_scale, height_scale);
2116 // Apply the scroll delta.
2117 gfx::Vector2dF previous_delta = layer_impl->ScrollDelta();
2118 layer_impl->ScrollBy(local_end_point - local_start_point);
2120 // Get the end point in the layer's content space so we can apply its
2121 // ScreenSpaceTransform.
2122 gfx::PointF actual_local_end_point = local_start_point +
2123 layer_impl->ScrollDelta() -
2124 previous_delta;
2125 gfx::PointF actual_local_content_end_point =
2126 gfx::ScalePoint(actual_local_end_point,
2127 1.f / width_scale,
2128 1.f / height_scale);
2130 // Calculate the applied scroll delta in viewport space coordinates.
2131 gfx::PointF actual_screen_space_end_point =
2132 MathUtil::MapPoint(layer_impl->screen_space_transform(),
2133 actual_local_content_end_point,
2134 &end_clipped);
2135 DCHECK(!end_clipped);
2136 if (end_clipped)
2137 return gfx::Vector2dF();
2138 gfx::PointF actual_viewport_end_point =
2139 gfx::ScalePoint(actual_screen_space_end_point,
2140 1.f / scale_from_viewport_to_screen_space);
2141 return actual_viewport_end_point - viewport_point;
2144 static gfx::Vector2dF ScrollLayerWithLocalDelta(LayerImpl* layer_impl,
2145 const gfx::Vector2dF& local_delta) {
2146 gfx::Vector2dF previous_delta(layer_impl->ScrollDelta());
2147 layer_impl->ScrollBy(local_delta);
2148 return layer_impl->ScrollDelta() - previous_delta;
2151 bool LayerTreeHostImpl::ScrollBy(gfx::Point viewport_point,
2152 const gfx::Vector2dF& scroll_delta) {
2153 TRACE_EVENT0("cc", "LayerTreeHostImpl::ScrollBy");
2154 if (!CurrentlyScrollingLayer())
2155 return false;
2157 gfx::Vector2dF pending_delta = scroll_delta;
2158 gfx::Vector2dF unused_root_delta;
2159 bool did_scroll_x = false;
2160 bool did_scroll_y = false;
2161 bool consume_by_top_controls = top_controls_manager_ &&
2162 (scroll_delta.y() < 0 ||
2163 (RootScrollLayer() && CurrentlyScrollingLayer() == RootScrollLayer() &&
2164 RootScrollLayer()->max_scroll_offset().y() > 0));
2166 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2167 layer_impl;
2168 layer_impl = layer_impl->parent()) {
2169 if (!layer_impl->scrollable())
2170 continue;
2172 if (layer_impl == RootScrollLayer()) {
2173 // Only allow bubble scrolling when the scroll is in the direction to make
2174 // the top controls visible.
2175 if (consume_by_top_controls) {
2176 pending_delta = top_controls_manager_->ScrollBy(pending_delta);
2177 UpdateMaxScrollOffset();
2179 // Track root layer deltas for reporting overscroll.
2180 unused_root_delta = pending_delta;
2183 gfx::Vector2dF applied_delta;
2184 // Gesture events need to be transformed from viewport coordinates to local
2185 // layer coordinates so that the scrolling contents exactly follow the
2186 // user's finger. In contrast, wheel events represent a fixed amount of
2187 // scrolling so we can just apply them directly.
2188 if (!wheel_scrolling_) {
2189 float scale_from_viewport_to_screen_space = device_scale_factor_;
2190 applied_delta =
2191 ScrollLayerWithViewportSpaceDelta(layer_impl,
2192 scale_from_viewport_to_screen_space,
2193 viewport_point, pending_delta);
2194 } else {
2195 applied_delta = ScrollLayerWithLocalDelta(layer_impl, pending_delta);
2198 // If the layer wasn't able to move, try the next one in the hierarchy.
2199 float move_threshold = 0.1f;
2200 bool did_move_layer_x = std::abs(applied_delta.x()) > move_threshold;
2201 bool did_move_layer_y = std::abs(applied_delta.y()) > move_threshold;
2202 did_scroll_x |= did_move_layer_x;
2203 did_scroll_y |= did_move_layer_y;
2204 if (!did_move_layer_x && !did_move_layer_y) {
2205 if (should_bubble_scrolls_ || !did_lock_scrolling_layer_)
2206 continue;
2207 else
2208 break;
2211 if (layer_impl == RootScrollLayer())
2212 unused_root_delta.Subtract(applied_delta);
2214 did_lock_scrolling_layer_ = true;
2215 if (!should_bubble_scrolls_) {
2216 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2217 break;
2220 // If the applied delta is within 45 degrees of the input delta, bail out to
2221 // make it easier to scroll just one layer in one direction without
2222 // affecting any of its parents.
2223 float angle_threshold = 45;
2224 if (MathUtil::SmallestAngleBetweenVectors(
2225 applied_delta, pending_delta) < angle_threshold) {
2226 pending_delta = gfx::Vector2d();
2227 break;
2230 // Allow further movement only on an axis perpendicular to the direction in
2231 // which the layer moved.
2232 gfx::Vector2dF perpendicular_axis(-applied_delta.y(), applied_delta.x());
2233 pending_delta = MathUtil::ProjectVector(pending_delta, perpendicular_axis);
2235 if (gfx::ToRoundedVector2d(pending_delta).IsZero())
2236 break;
2239 bool did_scroll = did_scroll_x || did_scroll_y;
2240 if (did_scroll) {
2241 client_->SetNeedsCommitOnImplThread();
2242 SetNeedsRedraw();
2243 client_->RenewTreePriority();
2246 // Scrolling along an axis resets accumulated root overscroll for that axis.
2247 if (did_scroll_x)
2248 accumulated_root_overscroll_.set_x(0);
2249 if (did_scroll_y)
2250 accumulated_root_overscroll_.set_y(0);
2252 accumulated_root_overscroll_ += unused_root_delta;
2253 bool did_overscroll = !gfx::ToRoundedVector2d(unused_root_delta).IsZero();
2254 if (did_overscroll && input_handler_client_) {
2255 DidOverscrollParams params;
2256 params.accumulated_overscroll = accumulated_root_overscroll_;
2257 params.latest_overscroll_delta = unused_root_delta;
2258 params.current_fling_velocity = current_fling_velocity_;
2259 input_handler_client_->DidOverscroll(params);
2262 return did_scroll;
2265 // This implements scrolling by page as described here:
2266 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms645601(v=vs.85).aspx#_win32_The_Mouse_Wheel
2267 // for events with WHEEL_PAGESCROLL set.
2268 bool LayerTreeHostImpl::ScrollVerticallyByPage(gfx::Point viewport_point,
2269 ScrollDirection direction) {
2270 DCHECK(wheel_scrolling_);
2272 for (LayerImpl* layer_impl = CurrentlyScrollingLayer();
2273 layer_impl;
2274 layer_impl = layer_impl->parent()) {
2275 if (!layer_impl->scrollable())
2276 continue;
2278 if (!layer_impl->vertical_scrollbar_layer())
2279 continue;
2281 float height = layer_impl->vertical_scrollbar_layer()->bounds().height();
2283 // These magical values match WebKit and are designed to scroll nearly the
2284 // entire visible content height but leave a bit of overlap.
2285 float page = std::max(height * 0.875f, 1.f);
2286 if (direction == SCROLL_BACKWARD)
2287 page = -page;
2289 gfx::Vector2dF delta = gfx::Vector2dF(0.f, page);
2291 gfx::Vector2dF applied_delta = ScrollLayerWithLocalDelta(layer_impl, delta);
2293 if (!applied_delta.IsZero()) {
2294 client_->SetNeedsCommitOnImplThread();
2295 SetNeedsRedraw();
2296 client_->RenewTreePriority();
2297 return true;
2300 active_tree_->SetCurrentlyScrollingLayer(layer_impl);
2303 return false;
2306 void LayerTreeHostImpl::SetRootLayerScrollOffsetDelegate(
2307 LayerScrollOffsetDelegate* root_layer_scroll_offset_delegate) {
2308 root_layer_scroll_offset_delegate_ = root_layer_scroll_offset_delegate;
2309 active_tree_->SetRootLayerScrollOffsetDelegate(
2310 root_layer_scroll_offset_delegate_);
2313 void LayerTreeHostImpl::OnRootLayerDelegatedScrollOffsetChanged() {
2314 DCHECK(root_layer_scroll_offset_delegate_ != NULL);
2315 client_->SetNeedsCommitOnImplThread();
2318 void LayerTreeHostImpl::ClearCurrentlyScrollingLayer() {
2319 active_tree_->ClearCurrentlyScrollingLayer();
2320 did_lock_scrolling_layer_ = false;
2321 accumulated_root_overscroll_ = gfx::Vector2dF();
2322 current_fling_velocity_ = gfx::Vector2dF();
2325 void LayerTreeHostImpl::ScrollEnd() {
2326 if (top_controls_manager_)
2327 top_controls_manager_->ScrollEnd();
2328 ClearCurrentlyScrollingLayer();
2329 StartScrollbarAnimation();
2332 InputHandler::ScrollStatus LayerTreeHostImpl::FlingScrollBegin() {
2333 if (!active_tree_->CurrentlyScrollingLayer())
2334 return ScrollIgnored;
2336 if (settings_.ignore_root_layer_flings &&
2337 active_tree_->CurrentlyScrollingLayer() ==
2338 active_tree_->RootScrollLayer()) {
2339 ClearCurrentlyScrollingLayer();
2340 return ScrollIgnored;
2343 if (!wheel_scrolling_) {
2344 // Allow the fling to lock to the first layer that moves after the initial
2345 // fling |ScrollBy()| event.
2346 did_lock_scrolling_layer_ = false;
2347 should_bubble_scrolls_ = false;
2350 return ScrollStarted;
2353 void LayerTreeHostImpl::NotifyCurrentFlingVelocity(
2354 const gfx::Vector2dF& velocity) {
2355 current_fling_velocity_ = velocity;
2358 float LayerTreeHostImpl::DeviceSpaceDistanceToLayer(
2359 const gfx::PointF& device_viewport_point,
2360 LayerImpl* layer_impl) {
2361 if (!layer_impl)
2362 return std::numeric_limits<float>::max();
2364 gfx::Rect layer_impl_bounds(
2365 layer_impl->content_bounds());
2367 gfx::RectF device_viewport_layer_impl_bounds = MathUtil::MapClippedRect(
2368 layer_impl->screen_space_transform(),
2369 layer_impl_bounds);
2371 return device_viewport_layer_impl_bounds.ManhattanDistanceToPoint(
2372 device_viewport_point);
2375 void LayerTreeHostImpl::MouseMoveAt(gfx::Point viewport_point) {
2376 if (!EnsureRenderSurfaceLayerList())
2377 return;
2379 gfx::PointF device_viewport_point = gfx::ScalePoint(viewport_point,
2380 device_scale_factor_);
2382 LayerImpl* layer_impl = LayerTreeHostCommon::FindLayerThatIsHitByPoint(
2383 device_viewport_point,
2384 active_tree_->RenderSurfaceLayerList());
2385 if (HandleMouseOverScrollbar(layer_impl, device_viewport_point))
2386 return;
2388 if (scroll_layer_id_when_mouse_over_scrollbar_) {
2389 LayerImpl* scroll_layer_impl = active_tree_->LayerById(
2390 scroll_layer_id_when_mouse_over_scrollbar_);
2392 ScrollbarAnimationController* animation_controller =
2393 scroll_layer_impl->scrollbar_animation_controller();
2394 if (animation_controller) {
2395 animation_controller->DidMouseMoveOffScrollbar(
2396 CurrentPhysicalTimeTicks());
2397 StartScrollbarAnimation();
2399 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2402 bool scroll_on_main_thread = false;
2403 LayerImpl* scroll_layer_impl = FindScrollLayerForDeviceViewportPoint(
2404 device_viewport_point, InputHandler::Gesture, layer_impl,
2405 &scroll_on_main_thread);
2406 if (scroll_on_main_thread || !scroll_layer_impl)
2407 return;
2409 ScrollbarAnimationController* animation_controller =
2410 scroll_layer_impl->scrollbar_animation_controller();
2411 if (!animation_controller)
2412 return;
2414 float distance_to_scrollbar = std::min(
2415 DeviceSpaceDistanceToLayer(device_viewport_point,
2416 scroll_layer_impl->horizontal_scrollbar_layer()),
2417 DeviceSpaceDistanceToLayer(device_viewport_point,
2418 scroll_layer_impl->vertical_scrollbar_layer()));
2420 bool should_animate = animation_controller->DidMouseMoveNear(
2421 CurrentPhysicalTimeTicks(), distance_to_scrollbar / device_scale_factor_);
2422 if (should_animate)
2423 StartScrollbarAnimation();
2426 bool LayerTreeHostImpl::HandleMouseOverScrollbar(LayerImpl* layer_impl,
2427 const gfx::PointF& device_viewport_point) {
2428 if (layer_impl && layer_impl->ToScrollbarLayer()) {
2429 int scroll_layer_id = layer_impl->ToScrollbarLayer()->ScrollLayerId();
2430 layer_impl = active_tree_->LayerById(scroll_layer_id);
2431 if (layer_impl && layer_impl->scrollbar_animation_controller()) {
2432 scroll_layer_id_when_mouse_over_scrollbar_ = scroll_layer_id;
2433 bool should_animate =
2434 layer_impl->scrollbar_animation_controller()->DidMouseMoveNear(
2435 CurrentPhysicalTimeTicks(), 0);
2436 if (should_animate)
2437 StartScrollbarAnimation();
2438 } else {
2439 scroll_layer_id_when_mouse_over_scrollbar_ = 0;
2442 return true;
2445 return false;
2448 void LayerTreeHostImpl::PinchGestureBegin() {
2449 pinch_gesture_active_ = true;
2450 previous_pinch_anchor_ = gfx::Point();
2451 client_->RenewTreePriority();
2452 pinch_gesture_end_should_clear_scrolling_layer_ = !CurrentlyScrollingLayer();
2453 active_tree_->SetCurrentlyScrollingLayer(RootScrollLayer());
2454 if (top_controls_manager_)
2455 top_controls_manager_->PinchBegin();
2458 void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
2459 gfx::Point anchor) {
2460 TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
2462 if (!RootScrollLayer())
2463 return;
2465 // Keep the center-of-pinch anchor specified by (x, y) in a stable
2466 // position over the course of the magnify.
2467 float page_scale_delta = active_tree_->page_scale_delta();
2468 gfx::PointF previous_scale_anchor =
2469 gfx::ScalePoint(anchor, 1.f / page_scale_delta);
2470 active_tree_->SetPageScaleDelta(page_scale_delta * magnify_delta);
2471 page_scale_delta = active_tree_->page_scale_delta();
2472 gfx::PointF new_scale_anchor =
2473 gfx::ScalePoint(anchor, 1.f / page_scale_delta);
2474 gfx::Vector2dF move = previous_scale_anchor - new_scale_anchor;
2476 previous_pinch_anchor_ = anchor;
2478 move.Scale(1 / active_tree_->page_scale_factor());
2480 RootScrollLayer()->ScrollBy(move);
2482 client_->SetNeedsCommitOnImplThread();
2483 SetNeedsRedraw();
2484 client_->RenewTreePriority();
2487 void LayerTreeHostImpl::PinchGestureEnd() {
2488 pinch_gesture_active_ = false;
2489 if (pinch_gesture_end_should_clear_scrolling_layer_) {
2490 pinch_gesture_end_should_clear_scrolling_layer_ = false;
2491 ClearCurrentlyScrollingLayer();
2493 if (top_controls_manager_)
2494 top_controls_manager_->PinchEnd();
2495 client_->SetNeedsCommitOnImplThread();
2498 static void CollectScrollDeltas(ScrollAndScaleSet* scroll_info,
2499 LayerImpl* layer_impl) {
2500 if (!layer_impl)
2501 return;
2503 gfx::Vector2d scroll_delta =
2504 gfx::ToFlooredVector2d(layer_impl->ScrollDelta());
2505 if (!scroll_delta.IsZero()) {
2506 LayerTreeHostCommon::ScrollUpdateInfo scroll;
2507 scroll.layer_id = layer_impl->id();
2508 scroll.scroll_delta = scroll_delta;
2509 scroll_info->scrolls.push_back(scroll);
2510 layer_impl->SetSentScrollDelta(scroll_delta);
2513 for (size_t i = 0; i < layer_impl->children().size(); ++i)
2514 CollectScrollDeltas(scroll_info, layer_impl->children()[i]);
2517 scoped_ptr<ScrollAndScaleSet> LayerTreeHostImpl::ProcessScrollDeltas() {
2518 scoped_ptr<ScrollAndScaleSet> scroll_info(new ScrollAndScaleSet());
2520 CollectScrollDeltas(scroll_info.get(), active_tree_->root_layer());
2521 scroll_info->page_scale_delta = active_tree_->page_scale_delta();
2522 active_tree_->set_sent_page_scale_delta(scroll_info->page_scale_delta);
2524 return scroll_info.Pass();
2527 void LayerTreeHostImpl::SetFullRootLayerDamage() {
2528 SetViewportDamage(gfx::Rect(DrawViewportSize()));
2531 void LayerTreeHostImpl::AnimatePageScale(base::TimeTicks time) {
2532 if (!page_scale_animation_ || !RootScrollLayer())
2533 return;
2535 double monotonic_time = (time - base::TimeTicks()).InSecondsF();
2536 gfx::Vector2dF scroll_total = RootScrollLayer()->scroll_offset() +
2537 RootScrollLayer()->ScrollDelta();
2539 if (!page_scale_animation_->IsAnimationStarted())
2540 page_scale_animation_->StartAnimation(monotonic_time);
2542 active_tree_->SetPageScaleDelta(
2543 page_scale_animation_->PageScaleFactorAtTime(monotonic_time) /
2544 active_tree_->page_scale_factor());
2545 gfx::Vector2dF next_scroll =
2546 page_scale_animation_->ScrollOffsetAtTime(monotonic_time);
2548 RootScrollLayer()->ScrollBy(next_scroll - scroll_total);
2549 SetNeedsRedraw();
2551 if (page_scale_animation_->IsAnimationCompleteAtTime(monotonic_time)) {
2552 page_scale_animation_.reset();
2553 client_->SetNeedsCommitOnImplThread();
2554 client_->RenewTreePriority();
2558 void LayerTreeHostImpl::AnimateTopControls(base::TimeTicks time) {
2559 if (!top_controls_manager_ || !RootScrollLayer())
2560 return;
2561 gfx::Vector2dF scroll = top_controls_manager_->Animate(time);
2562 UpdateMaxScrollOffset();
2563 if (RootScrollLayer()->TotalScrollOffset().y() == 0.f)
2564 return;
2565 if (scroll.IsZero()) {
2566 // This may happen on the first animation step. Force redraw otherwise
2567 // the animation would stop because of no new frames.
2568 SetNeedsRedraw();
2569 } else {
2570 RootScrollLayer()->ScrollBy(gfx::ScaleVector2d(
2571 scroll, 1.f / active_tree_->total_page_scale_factor()));
2575 void LayerTreeHostImpl::AnimateLayers(base::TimeTicks monotonic_time,
2576 base::Time wall_clock_time) {
2577 if (!settings_.accelerated_animation_enabled ||
2578 animation_registrar_->active_animation_controllers().empty() ||
2579 !active_tree_->root_layer())
2580 return;
2582 TRACE_EVENT0("cc", "LayerTreeHostImpl::AnimateLayers");
2584 last_animation_time_ = wall_clock_time;
2585 double monotonic_seconds = (monotonic_time - base::TimeTicks()).InSecondsF();
2587 AnimationRegistrar::AnimationControllerMap copy =
2588 animation_registrar_->active_animation_controllers();
2589 for (AnimationRegistrar::AnimationControllerMap::iterator iter = copy.begin();
2590 iter != copy.end();
2591 ++iter)
2592 (*iter).second->Animate(monotonic_seconds);
2594 SetNeedsRedraw();
2597 void LayerTreeHostImpl::UpdateAnimationState(bool start_ready_animations) {
2598 if (!settings_.accelerated_animation_enabled ||
2599 animation_registrar_->active_animation_controllers().empty() ||
2600 !active_tree_->root_layer())
2601 return;
2603 TRACE_EVENT0("cc", "LayerTreeHostImpl::UpdateAnimationState");
2604 scoped_ptr<AnimationEventsVector> events =
2605 make_scoped_ptr(new AnimationEventsVector);
2606 AnimationRegistrar::AnimationControllerMap copy =
2607 animation_registrar_->active_animation_controllers();
2608 for (AnimationRegistrar::AnimationControllerMap::iterator iter = copy.begin();
2609 iter != copy.end();
2610 ++iter)
2611 (*iter).second->UpdateState(start_ready_animations, events.get());
2613 if (!events->empty()) {
2614 client_->PostAnimationEventsToMainThreadOnImplThread(events.Pass(),
2615 last_animation_time_);
2619 base::TimeDelta LayerTreeHostImpl::LowFrequencyAnimationInterval() const {
2620 return base::TimeDelta::FromSeconds(1);
2623 void LayerTreeHostImpl::SendReleaseResourcesRecursive(LayerImpl* current) {
2624 DCHECK(current);
2625 current->ReleaseResources();
2626 if (current->mask_layer())
2627 SendReleaseResourcesRecursive(current->mask_layer());
2628 if (current->replica_layer())
2629 SendReleaseResourcesRecursive(current->replica_layer());
2630 for (size_t i = 0; i < current->children().size(); ++i)
2631 SendReleaseResourcesRecursive(current->children()[i]);
2634 void LayerTreeHostImpl::SetOffscreenContextProvider(
2635 const scoped_refptr<ContextProvider>& offscreen_context_provider) {
2636 if (!offscreen_context_provider.get()) {
2637 offscreen_context_provider_ = NULL;
2638 return;
2641 if (!offscreen_context_provider->BindToCurrentThread()) {
2642 offscreen_context_provider_ = NULL;
2643 return;
2646 offscreen_context_provider_ = offscreen_context_provider;
2649 std::string LayerTreeHostImpl::LayerTreeAsJson() const {
2650 std::string str;
2651 if (active_tree_->root_layer()) {
2652 scoped_ptr<base::Value> json(active_tree_->root_layer()->LayerTreeAsJson());
2653 base::JSONWriter::WriteWithOptions(
2654 json.get(), base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
2656 return str;
2659 int LayerTreeHostImpl::SourceAnimationFrameNumber() const {
2660 return fps_counter_->current_frame_number();
2663 void LayerTreeHostImpl::SendManagedMemoryStats(
2664 size_t memory_visible_bytes,
2665 size_t memory_visible_and_nearby_bytes,
2666 size_t memory_use_bytes) {
2667 if (!renderer_)
2668 return;
2670 // Round the numbers being sent up to the next 8MB, to throttle the rate
2671 // at which we spam the GPU process.
2672 static const size_t rounding_step = 8 * 1024 * 1024;
2673 memory_visible_bytes = RoundUp(memory_visible_bytes, rounding_step);
2674 memory_visible_and_nearby_bytes = RoundUp(memory_visible_and_nearby_bytes,
2675 rounding_step);
2676 memory_use_bytes = RoundUp(memory_use_bytes, rounding_step);
2677 if (last_sent_memory_visible_bytes_ == memory_visible_bytes &&
2678 last_sent_memory_visible_and_nearby_bytes_ ==
2679 memory_visible_and_nearby_bytes &&
2680 last_sent_memory_use_bytes_ == memory_use_bytes) {
2681 return;
2683 last_sent_memory_visible_bytes_ = memory_visible_bytes;
2684 last_sent_memory_visible_and_nearby_bytes_ = memory_visible_and_nearby_bytes;
2685 last_sent_memory_use_bytes_ = memory_use_bytes;
2687 renderer_->SendManagedMemoryStats(last_sent_memory_visible_bytes_,
2688 last_sent_memory_visible_and_nearby_bytes_,
2689 last_sent_memory_use_bytes_);
2692 void LayerTreeHostImpl::AnimateScrollbars(base::TimeTicks time) {
2693 AnimateScrollbarsRecursive(active_tree_->root_layer(), time);
2696 void LayerTreeHostImpl::AnimateScrollbarsRecursive(LayerImpl* layer,
2697 base::TimeTicks time) {
2698 if (!layer)
2699 return;
2701 ScrollbarAnimationController* scrollbar_controller =
2702 layer->scrollbar_animation_controller();
2703 if (scrollbar_controller && scrollbar_controller->Animate(time)) {
2704 TRACE_EVENT_INSTANT0(
2705 "cc", "LayerTreeHostImpl::SetNeedsRedraw due to AnimateScrollbars",
2706 TRACE_EVENT_SCOPE_THREAD);
2707 SetNeedsRedraw();
2710 for (size_t i = 0; i < layer->children().size(); ++i)
2711 AnimateScrollbarsRecursive(layer->children()[i], time);
2714 void LayerTreeHostImpl::StartScrollbarAnimation() {
2715 TRACE_EVENT0("cc", "LayerTreeHostImpl::StartScrollbarAnimation");
2716 StartScrollbarAnimationRecursive(RootLayer(), CurrentPhysicalTimeTicks());
2719 void LayerTreeHostImpl::StartScrollbarAnimationRecursive(LayerImpl* layer,
2720 base::TimeTicks time) {
2721 if (!layer)
2722 return;
2724 ScrollbarAnimationController* scrollbar_controller =
2725 layer->scrollbar_animation_controller();
2726 if (scrollbar_controller && scrollbar_controller->IsAnimating()) {
2727 base::TimeDelta delay = scrollbar_controller->DelayBeforeStart(time);
2728 if (delay > base::TimeDelta())
2729 client_->RequestScrollbarAnimationOnImplThread(delay);
2730 else if (scrollbar_controller->Animate(time))
2731 SetNeedsRedraw();
2734 for (size_t i = 0; i < layer->children().size(); ++i)
2735 StartScrollbarAnimationRecursive(layer->children()[i], time);
2738 void LayerTreeHostImpl::SetTreePriority(TreePriority priority) {
2739 if (!tile_manager_)
2740 return;
2742 if (global_tile_state_.tree_priority == priority)
2743 return;
2744 global_tile_state_.tree_priority = priority;
2745 DidModifyTilePriorities();
2748 void LayerTreeHostImpl::ResetCurrentFrameTimeForNextFrame() {
2749 current_frame_timeticks_ = base::TimeTicks();
2750 current_frame_time_ = base::Time();
2753 void LayerTreeHostImpl::UpdateCurrentFrameTime(base::TimeTicks* ticks,
2754 base::Time* now) const {
2755 if (ticks->is_null()) {
2756 DCHECK(now->is_null());
2757 *ticks = CurrentPhysicalTimeTicks();
2758 *now = base::Time::Now();
2762 base::TimeTicks LayerTreeHostImpl::CurrentFrameTimeTicks() {
2763 UpdateCurrentFrameTime(&current_frame_timeticks_, &current_frame_time_);
2764 return current_frame_timeticks_;
2767 base::Time LayerTreeHostImpl::CurrentFrameTime() {
2768 UpdateCurrentFrameTime(&current_frame_timeticks_, &current_frame_time_);
2769 return current_frame_time_;
2772 base::TimeTicks LayerTreeHostImpl::CurrentPhysicalTimeTicks() const {
2773 return gfx::FrameTime::Now();
2776 scoped_ptr<base::Value> LayerTreeHostImpl::AsValueWithFrame(
2777 FrameData* frame) const {
2778 scoped_ptr<base::DictionaryValue> state(new base::DictionaryValue());
2779 if (this->pending_tree_)
2780 state->Set("activation_state", ActivationStateAsValue().release());
2781 state->Set("device_viewport_size",
2782 MathUtil::AsValue(device_viewport_size_).release());
2783 if (tile_manager_)
2784 state->Set("tiles", tile_manager_->AllTilesAsValue().release());
2785 state->Set("active_tree", active_tree_->AsValue().release());
2786 if (pending_tree_)
2787 state->Set("pending_tree", pending_tree_->AsValue().release());
2788 if (frame)
2789 state->Set("frame", frame->AsValue().release());
2790 return state.PassAs<base::Value>();
2793 scoped_ptr<base::Value> LayerTreeHostImpl::ActivationStateAsValue() const {
2794 scoped_ptr<base::DictionaryValue> state(new base::DictionaryValue());
2795 state->Set("lthi", TracedValue::CreateIDRef(this).release());
2796 if (tile_manager_)
2797 state->Set("tile_manager", tile_manager_->BasicStateAsValue().release());
2798 return state.PassAs<base::Value>();
2801 void LayerTreeHostImpl::SetDebugState(
2802 const LayerTreeDebugState& new_debug_state) {
2803 if (LayerTreeDebugState::Equal(debug_state_, new_debug_state))
2804 return;
2805 if (debug_state_.continuous_painting != new_debug_state.continuous_painting)
2806 paint_time_counter_->ClearHistory();
2808 debug_state_ = new_debug_state;
2809 UpdateTileManagerMemoryPolicy(ActualManagedMemoryPolicy());
2810 SetFullRootLayerDamage();
2813 void LayerTreeHostImpl::CreateUIResource(UIResourceId uid,
2814 const UIResourceBitmap& bitmap) {
2815 DCHECK_GT(uid, 0);
2817 GLint wrap_mode = 0;
2818 switch (bitmap.GetWrapMode()) {
2819 case UIResourceBitmap::CLAMP_TO_EDGE:
2820 wrap_mode = GL_CLAMP_TO_EDGE;
2821 break;
2822 case UIResourceBitmap::REPEAT:
2823 wrap_mode = GL_REPEAT;
2824 break;
2827 // Allow for multiple creation requests with the same UIResourceId. The
2828 // previous resource is simply deleted.
2829 ResourceProvider::ResourceId id = ResourceIdForUIResource(uid);
2830 if (id)
2831 DeleteUIResource(uid);
2833 ResourceFormat format = resource_provider_->best_texture_format();
2834 if (bitmap.GetFormat() == UIResourceBitmap::ETC1)
2835 format = ETC1;
2836 id = resource_provider_->CreateResource(
2837 bitmap.GetSize(),
2838 wrap_mode,
2839 ResourceProvider::TextureUsageAny,
2840 format);
2842 UIResourceData data;
2843 data.resource_id = id;
2844 data.size = bitmap.GetSize();
2845 data.opaque = bitmap.GetOpaque();
2847 ui_resource_map_[uid] = data;
2849 AutoLockUIResourceBitmap bitmap_lock(bitmap);
2850 resource_provider_->SetPixels(id,
2851 bitmap_lock.GetPixels(),
2852 gfx::Rect(bitmap.GetSize()),
2853 gfx::Rect(bitmap.GetSize()),
2854 gfx::Vector2d(0, 0));
2855 MarkUIResourceNotEvicted(uid);
2858 void LayerTreeHostImpl::DeleteUIResource(UIResourceId uid) {
2859 ResourceProvider::ResourceId id = ResourceIdForUIResource(uid);
2860 if (id) {
2861 resource_provider_->DeleteResource(id);
2862 ui_resource_map_.erase(uid);
2864 MarkUIResourceNotEvicted(uid);
2867 void LayerTreeHostImpl::EvictAllUIResources() {
2868 if (ui_resource_map_.empty())
2869 return;
2871 for (UIResourceMap::const_iterator iter = ui_resource_map_.begin();
2872 iter != ui_resource_map_.end();
2873 ++iter) {
2874 evicted_ui_resources_.insert(iter->first);
2875 resource_provider_->DeleteResource(iter->second.resource_id);
2877 ui_resource_map_.clear();
2879 client_->SetNeedsCommitOnImplThread();
2880 client_->OnCanDrawStateChanged(CanDraw());
2881 client_->RenewTreePriority();
2884 ResourceProvider::ResourceId LayerTreeHostImpl::ResourceIdForUIResource(
2885 UIResourceId uid) const {
2886 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
2887 if (iter != ui_resource_map_.end())
2888 return iter->second.resource_id;
2889 return 0;
2892 bool LayerTreeHostImpl::IsUIResourceOpaque(UIResourceId uid) const {
2893 UIResourceMap::const_iterator iter = ui_resource_map_.find(uid);
2894 DCHECK(iter != ui_resource_map_.end());
2895 return iter->second.opaque;
2898 bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
2899 return !evicted_ui_resources_.empty();
2902 void LayerTreeHostImpl::MarkUIResourceNotEvicted(UIResourceId uid) {
2903 std::set<UIResourceId>::iterator found_in_evicted =
2904 evicted_ui_resources_.find(uid);
2905 if (found_in_evicted == evicted_ui_resources_.end())
2906 return;
2907 evicted_ui_resources_.erase(found_in_evicted);
2908 if (evicted_ui_resources_.empty())
2909 client_->OnCanDrawStateChanged(CanDraw());
2912 void LayerTreeHostImpl::ScheduleMicroBenchmark(
2913 scoped_ptr<MicroBenchmarkImpl> benchmark) {
2914 micro_benchmark_controller_.ScheduleRun(benchmark.Pass());
2917 void LayerTreeHostImpl::InsertSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
2918 swap_promise_monitor_.insert(monitor);
2921 void LayerTreeHostImpl::RemoveSwapPromiseMonitor(SwapPromiseMonitor* monitor) {
2922 swap_promise_monitor_.erase(monitor);
2925 void LayerTreeHostImpl::NotifySwapPromiseMonitorsOfSetNeedsRedraw() {
2926 std::set<SwapPromiseMonitor*>::iterator it = swap_promise_monitor_.begin();
2927 for (; it != swap_promise_monitor_.end(); it++)
2928 (*it)->OnSetNeedsRedrawOnImpl();
2931 } // namespace cc