Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(117)

Side by Side Diff: cc/trees/layer_tree_host_impl.cc

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

Powered by Google App Engine
This is Rietveld 408576698