Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / cc / trees / thread_proxy.cc
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/thread_proxy.h"
6
7 #include <algorithm>
8 #include <string>
9
10 #include "base/auto_reset.h"
11 #include "base/bind.h"
12 #include "base/debug/trace_event.h"
13 #include "base/debug/trace_event_argument.h"
14 #include "base/debug/trace_event_synthetic_delay.h"
15 #include "cc/base/swap_promise.h"
16 #include "cc/debug/benchmark_instrumentation.h"
17 #include "cc/debug/devtools_instrumentation.h"
18 #include "cc/input/input_handler.h"
19 #include "cc/output/context_provider.h"
20 #include "cc/output/output_surface.h"
21 #include "cc/quads/draw_quad.h"
22 #include "cc/resources/prioritized_resource_manager.h"
23 #include "cc/scheduler/delay_based_time_source.h"
24 #include "cc/scheduler/scheduler.h"
25 #include "cc/trees/blocking_task_runner.h"
26 #include "cc/trees/layer_tree_host.h"
27 #include "cc/trees/layer_tree_impl.h"
28 #include "gpu/command_buffer/client/gles2_interface.h"
29 #include "ui/gfx/frame_time.h"
30
31 namespace cc {
32
33 namespace {
34
35 // Measured in seconds.
36 const double kSmoothnessTakesPriorityExpirationDelay = 0.25;
37
38 unsigned int nextBeginFrameId = 0;
39
40 class SwapPromiseChecker {
41  public:
42   explicit SwapPromiseChecker(LayerTreeHost* layer_tree_host)
43       : layer_tree_host_(layer_tree_host) {}
44
45   ~SwapPromiseChecker() {
46     layer_tree_host_->BreakSwapPromises(SwapPromise::COMMIT_FAILS);
47   }
48
49  private:
50   LayerTreeHost* layer_tree_host_;
51 };
52
53 }  // namespace
54
55 struct ThreadProxy::SchedulerStateRequest {
56   CompletionEvent completion;
57   scoped_ptr<base::Value> state;
58 };
59
60 scoped_ptr<Proxy> ThreadProxy::Create(
61     LayerTreeHost* layer_tree_host,
62     scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
63     scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner) {
64   return make_scoped_ptr(new ThreadProxy(layer_tree_host,
65                                          main_task_runner,
66                                          impl_task_runner)).PassAs<Proxy>();
67 }
68
69 ThreadProxy::ThreadProxy(
70     LayerTreeHost* layer_tree_host,
71     scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
72     scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner)
73     : Proxy(main_task_runner, impl_task_runner),
74       main_thread_only_vars_unsafe_(this, layer_tree_host->id()),
75       main_thread_or_blocked_vars_unsafe_(layer_tree_host),
76       compositor_thread_vars_unsafe_(
77           this,
78           layer_tree_host->id(),
79           layer_tree_host->rendering_stats_instrumentation()) {
80   TRACE_EVENT0("cc", "ThreadProxy::ThreadProxy");
81   DCHECK(IsMainThread());
82   DCHECK(this->layer_tree_host());
83 }
84
85 ThreadProxy::MainThreadOnly::MainThreadOnly(ThreadProxy* proxy,
86                                             int layer_tree_host_id)
87     : layer_tree_host_id(layer_tree_host_id),
88       animate_requested(false),
89       commit_requested(false),
90       commit_request_sent_to_impl_thread(false),
91       started(false),
92       manage_tiles_pending(false),
93       can_cancel_commit(true),
94       defer_commits(false),
95       weak_factory(proxy) {}
96
97 ThreadProxy::MainThreadOnly::~MainThreadOnly() {}
98
99 ThreadProxy::MainThreadOrBlockedMainThread::MainThreadOrBlockedMainThread(
100     LayerTreeHost* host)
101     : layer_tree_host(host),
102       commit_waits_for_activation(false),
103       main_thread_inside_commit(false) {}
104
105 ThreadProxy::MainThreadOrBlockedMainThread::~MainThreadOrBlockedMainThread() {}
106
107 PrioritizedResourceManager*
108 ThreadProxy::MainThreadOrBlockedMainThread::contents_texture_manager() {
109   return layer_tree_host->contents_texture_manager();
110 }
111
112 ThreadProxy::CompositorThreadOnly::CompositorThreadOnly(
113     ThreadProxy* proxy,
114     int layer_tree_host_id,
115     RenderingStatsInstrumentation* rendering_stats_instrumentation)
116     : layer_tree_host_id(layer_tree_host_id),
117       contents_texture_manager(NULL),
118       commit_completion_event(NULL),
119       completion_event_for_commit_held_on_tree_activation(NULL),
120       next_frame_is_newly_committed_frame(false),
121       inside_draw(false),
122       input_throttled_until_commit(false),
123       animations_frozen_until_next_draw(false),
124       did_commit_after_animating(false),
125       smoothness_priority_expiration_notifier(
126           proxy->ImplThreadTaskRunner(),
127           base::Bind(&ThreadProxy::RenewTreePriority, base::Unretained(proxy)),
128           base::TimeDelta::FromMilliseconds(
129               kSmoothnessTakesPriorityExpirationDelay * 1000)),
130       timing_history(rendering_stats_instrumentation),
131       weak_factory(proxy) {
132 }
133
134 ThreadProxy::CompositorThreadOnly::~CompositorThreadOnly() {}
135
136 ThreadProxy::~ThreadProxy() {
137   TRACE_EVENT0("cc", "ThreadProxy::~ThreadProxy");
138   DCHECK(IsMainThread());
139   DCHECK(!main().started);
140 }
141
142 void ThreadProxy::FinishAllRendering() {
143   DCHECK(Proxy::IsMainThread());
144   DCHECK(!main().defer_commits);
145
146   // Make sure all GL drawing is finished on the impl thread.
147   DebugScopedSetMainThreadBlocked main_thread_blocked(this);
148   CompletionEvent completion;
149   Proxy::ImplThreadTaskRunner()->PostTask(
150       FROM_HERE,
151       base::Bind(&ThreadProxy::FinishAllRenderingOnImplThread,
152                  impl_thread_weak_ptr_,
153                  &completion));
154   completion.Wait();
155 }
156
157 bool ThreadProxy::IsStarted() const {
158   DCHECK(Proxy::IsMainThread());
159   return main().started;
160 }
161
162 void ThreadProxy::SetLayerTreeHostClientReady() {
163   TRACE_EVENT0("cc", "ThreadProxy::SetLayerTreeHostClientReady");
164   Proxy::ImplThreadTaskRunner()->PostTask(
165       FROM_HERE,
166       base::Bind(&ThreadProxy::SetLayerTreeHostClientReadyOnImplThread,
167                  impl_thread_weak_ptr_));
168 }
169
170 void ThreadProxy::SetLayerTreeHostClientReadyOnImplThread() {
171   TRACE_EVENT0("cc", "ThreadProxy::SetLayerTreeHostClientReadyOnImplThread");
172   impl().scheduler->SetCanStart();
173 }
174
175 void ThreadProxy::SetVisible(bool visible) {
176   TRACE_EVENT0("cc", "ThreadProxy::SetVisible");
177   DebugScopedSetMainThreadBlocked main_thread_blocked(this);
178
179   CompletionEvent completion;
180   Proxy::ImplThreadTaskRunner()->PostTask(
181       FROM_HERE,
182       base::Bind(&ThreadProxy::SetVisibleOnImplThread,
183                  impl_thread_weak_ptr_,
184                  &completion,
185                  visible));
186   completion.Wait();
187 }
188
189 void ThreadProxy::SetVisibleOnImplThread(CompletionEvent* completion,
190                                          bool visible) {
191   TRACE_EVENT0("cc", "ThreadProxy::SetVisibleOnImplThread");
192   impl().layer_tree_host_impl->SetVisible(visible);
193   impl().scheduler->SetVisible(visible);
194   UpdateBackgroundAnimateTicking();
195   completion->Signal();
196 }
197
198 void ThreadProxy::UpdateBackgroundAnimateTicking() {
199   bool should_background_tick =
200       !impl().scheduler->WillDrawIfNeeded() &&
201       impl().layer_tree_host_impl->active_tree()->root_layer();
202   impl().layer_tree_host_impl->UpdateBackgroundAnimateTicking(
203       should_background_tick);
204   if (should_background_tick)
205     impl().animations_frozen_until_next_draw = false;
206 }
207
208 void ThreadProxy::DidLoseOutputSurface() {
209   TRACE_EVENT0("cc", "ThreadProxy::DidLoseOutputSurface");
210   DCHECK(IsMainThread());
211   layer_tree_host()->DidLoseOutputSurface();
212
213   {
214     DebugScopedSetMainThreadBlocked main_thread_blocked(this);
215
216     // Return lost resources to their owners immediately.
217     BlockingTaskRunner::CapturePostTasks blocked;
218
219     CompletionEvent completion;
220     Proxy::ImplThreadTaskRunner()->PostTask(
221         FROM_HERE,
222         base::Bind(&ThreadProxy::DeleteContentsTexturesOnImplThread,
223                    impl_thread_weak_ptr_,
224                    &completion));
225     completion.Wait();
226   }
227 }
228
229 void ThreadProxy::CreateAndInitializeOutputSurface() {
230   TRACE_EVENT0("cc", "ThreadProxy::DoCreateAndInitializeOutputSurface");
231   DCHECK(IsMainThread());
232
233   scoped_ptr<OutputSurface> output_surface =
234       layer_tree_host()->CreateOutputSurface();
235
236   if (output_surface) {
237     Proxy::ImplThreadTaskRunner()->PostTask(
238         FROM_HERE,
239         base::Bind(&ThreadProxy::InitializeOutputSurfaceOnImplThread,
240                    impl_thread_weak_ptr_,
241                    base::Passed(&output_surface)));
242     return;
243   }
244
245   DidInitializeOutputSurface(false, RendererCapabilities());
246 }
247
248 void ThreadProxy::DidInitializeOutputSurface(
249     bool success,
250     const RendererCapabilities& capabilities) {
251   TRACE_EVENT0("cc", "ThreadProxy::DidInitializeOutputSurface");
252   DCHECK(IsMainThread());
253   main().renderer_capabilities_main_thread_copy = capabilities;
254   layer_tree_host()->OnCreateAndInitializeOutputSurfaceAttempted(success);
255
256   if (!success) {
257     Proxy::MainThreadTaskRunner()->PostTask(
258         FROM_HERE,
259         base::Bind(&ThreadProxy::CreateAndInitializeOutputSurface,
260                    main_thread_weak_ptr_));
261   }
262 }
263
264 void ThreadProxy::SetRendererCapabilitiesMainThreadCopy(
265     const RendererCapabilities& capabilities) {
266   main().renderer_capabilities_main_thread_copy = capabilities;
267 }
268
269 void ThreadProxy::SendCommitRequestToImplThreadIfNeeded() {
270   DCHECK(IsMainThread());
271   if (main().commit_request_sent_to_impl_thread)
272     return;
273   main().commit_request_sent_to_impl_thread = true;
274   Proxy::ImplThreadTaskRunner()->PostTask(
275       FROM_HERE,
276       base::Bind(&ThreadProxy::SetNeedsCommitOnImplThread,
277                  impl_thread_weak_ptr_));
278 }
279
280 const RendererCapabilities& ThreadProxy::GetRendererCapabilities() const {
281   DCHECK(IsMainThread());
282   DCHECK(!layer_tree_host()->output_surface_lost());
283   return main().renderer_capabilities_main_thread_copy;
284 }
285
286 void ThreadProxy::SetNeedsAnimate() {
287   DCHECK(IsMainThread());
288   if (main().animate_requested)
289     return;
290
291   TRACE_EVENT0("cc", "ThreadProxy::SetNeedsAnimate");
292   main().animate_requested = true;
293   SendCommitRequestToImplThreadIfNeeded();
294 }
295
296 void ThreadProxy::SetNeedsUpdateLayers() {
297   DCHECK(IsMainThread());
298
299   if (main().commit_request_sent_to_impl_thread)
300     return;
301   TRACE_EVENT0("cc", "ThreadProxy::SetNeedsUpdateLayers");
302
303   SendCommitRequestToImplThreadIfNeeded();
304 }
305
306 void ThreadProxy::SetNeedsCommit() {
307   DCHECK(IsMainThread());
308   // Unconditionally set here to handle SetNeedsCommit calls during a commit.
309   main().can_cancel_commit = false;
310
311   if (main().commit_requested)
312     return;
313   TRACE_EVENT0("cc", "ThreadProxy::SetNeedsCommit");
314   main().commit_requested = true;
315
316   SendCommitRequestToImplThreadIfNeeded();
317 }
318
319 void ThreadProxy::UpdateRendererCapabilitiesOnImplThread() {
320   DCHECK(IsImplThread());
321   Proxy::MainThreadTaskRunner()->PostTask(
322       FROM_HERE,
323       base::Bind(&ThreadProxy::SetRendererCapabilitiesMainThreadCopy,
324                  main_thread_weak_ptr_,
325                  impl()
326                      .layer_tree_host_impl->GetRendererCapabilities()
327                      .MainThreadCapabilities()));
328 }
329
330 void ThreadProxy::DidLoseOutputSurfaceOnImplThread() {
331   TRACE_EVENT0("cc", "ThreadProxy::DidLoseOutputSurfaceOnImplThread");
332   DCHECK(IsImplThread());
333   Proxy::MainThreadTaskRunner()->PostTask(
334       FROM_HERE,
335       base::Bind(&ThreadProxy::DidLoseOutputSurface, main_thread_weak_ptr_));
336   impl().scheduler->DidLoseOutputSurface();
337 }
338
339 void ThreadProxy::CommitVSyncParameters(base::TimeTicks timebase,
340                                         base::TimeDelta interval) {
341   impl().scheduler->CommitVSyncParameters(timebase, interval);
342 }
343
344 void ThreadProxy::SetEstimatedParentDrawTime(base::TimeDelta draw_time) {
345   impl().scheduler->SetEstimatedParentDrawTime(draw_time);
346 }
347
348 void ThreadProxy::SetMaxSwapsPendingOnImplThread(int max) {
349   impl().scheduler->SetMaxSwapsPending(max);
350 }
351
352 void ThreadProxy::DidSwapBuffersOnImplThread() {
353   impl().scheduler->DidSwapBuffers();
354 }
355
356 void ThreadProxy::DidSwapBuffersCompleteOnImplThread() {
357   TRACE_EVENT0("cc", "ThreadProxy::DidSwapBuffersCompleteOnImplThread");
358   DCHECK(IsImplThread());
359   impl().scheduler->DidSwapBuffersComplete();
360   Proxy::MainThreadTaskRunner()->PostTask(
361       FROM_HERE,
362       base::Bind(&ThreadProxy::DidCompleteSwapBuffers, main_thread_weak_ptr_));
363 }
364
365 void ThreadProxy::SetNeedsBeginFrame(bool enable) {
366   TRACE_EVENT1("cc", "ThreadProxy::SetNeedsBeginFrame", "enable", enable);
367   impl().layer_tree_host_impl->SetNeedsBeginFrame(enable);
368   UpdateBackgroundAnimateTicking();
369 }
370
371 void ThreadProxy::BeginFrame(const BeginFrameArgs& args) {
372   impl().scheduler->BeginFrame(args);
373 }
374
375 void ThreadProxy::WillBeginImplFrame(const BeginFrameArgs& args) {
376   impl().layer_tree_host_impl->WillBeginImplFrame(args);
377 }
378
379 void ThreadProxy::OnCanDrawStateChanged(bool can_draw) {
380   TRACE_EVENT1(
381       "cc", "ThreadProxy::OnCanDrawStateChanged", "can_draw", can_draw);
382   DCHECK(IsImplThread());
383   impl().scheduler->SetCanDraw(can_draw);
384   UpdateBackgroundAnimateTicking();
385 }
386
387 void ThreadProxy::NotifyReadyToActivate() {
388   TRACE_EVENT0("cc", "ThreadProxy::NotifyReadyToActivate");
389   impl().scheduler->NotifyReadyToActivate();
390 }
391
392 void ThreadProxy::SetNeedsCommitOnImplThread() {
393   TRACE_EVENT0("cc", "ThreadProxy::SetNeedsCommitOnImplThread");
394   DCHECK(IsImplThread());
395   impl().scheduler->SetNeedsCommit();
396 }
397
398 void ThreadProxy::PostAnimationEventsToMainThreadOnImplThread(
399     scoped_ptr<AnimationEventsVector> events) {
400   TRACE_EVENT0("cc",
401                "ThreadProxy::PostAnimationEventsToMainThreadOnImplThread");
402   DCHECK(IsImplThread());
403   Proxy::MainThreadTaskRunner()->PostTask(
404       FROM_HERE,
405       base::Bind(&ThreadProxy::SetAnimationEvents,
406                  main_thread_weak_ptr_,
407                  base::Passed(&events)));
408 }
409
410 bool ThreadProxy::ReduceContentsTextureMemoryOnImplThread(size_t limit_bytes,
411                                                           int priority_cutoff) {
412   DCHECK(IsImplThread());
413
414   if (!impl().contents_texture_manager)
415     return false;
416   if (!impl().layer_tree_host_impl->resource_provider())
417     return false;
418
419   bool reduce_result =
420       impl().contents_texture_manager->ReduceMemoryOnImplThread(
421           limit_bytes,
422           priority_cutoff,
423           impl().layer_tree_host_impl->resource_provider());
424   if (!reduce_result)
425     return false;
426
427   // The texture upload queue may reference textures that were just purged,
428   // clear them from the queue.
429   if (impl().current_resource_update_controller) {
430     impl()
431         .current_resource_update_controller->DiscardUploadsToEvictedResources();
432   }
433   return true;
434 }
435
436 bool ThreadProxy::IsInsideDraw() { return impl().inside_draw; }
437
438 void ThreadProxy::SetNeedsRedraw(const gfx::Rect& damage_rect) {
439   TRACE_EVENT0("cc", "ThreadProxy::SetNeedsRedraw");
440   DCHECK(IsMainThread());
441   Proxy::ImplThreadTaskRunner()->PostTask(
442       FROM_HERE,
443       base::Bind(&ThreadProxy::SetNeedsRedrawRectOnImplThread,
444                  impl_thread_weak_ptr_,
445                  damage_rect));
446 }
447
448 void ThreadProxy::SetNextCommitWaitsForActivation() {
449   DCHECK(IsMainThread());
450   DCHECK(!blocked_main().main_thread_inside_commit);
451   blocked_main().commit_waits_for_activation = true;
452 }
453
454 void ThreadProxy::SetDeferCommits(bool defer_commits) {
455   DCHECK(IsMainThread());
456   DCHECK_NE(main().defer_commits, defer_commits);
457   main().defer_commits = defer_commits;
458
459   if (main().defer_commits)
460     TRACE_EVENT_ASYNC_BEGIN0("cc", "ThreadProxy::SetDeferCommits", this);
461   else
462     TRACE_EVENT_ASYNC_END0("cc", "ThreadProxy::SetDeferCommits", this);
463
464   if (!main().defer_commits && main().pending_deferred_commit) {
465     Proxy::MainThreadTaskRunner()->PostTask(
466         FROM_HERE,
467         base::Bind(&ThreadProxy::BeginMainFrame,
468                    main_thread_weak_ptr_,
469                    base::Passed(&main().pending_deferred_commit)));
470   }
471 }
472
473 bool ThreadProxy::CommitRequested() const {
474   DCHECK(IsMainThread());
475   return main().commit_requested;
476 }
477
478 bool ThreadProxy::BeginMainFrameRequested() const {
479   DCHECK(IsMainThread());
480   return main().commit_request_sent_to_impl_thread;
481 }
482
483 void ThreadProxy::SetNeedsRedrawOnImplThread() {
484   TRACE_EVENT0("cc", "ThreadProxy::SetNeedsRedrawOnImplThread");
485   DCHECK(IsImplThread());
486   impl().scheduler->SetNeedsRedraw();
487 }
488
489 void ThreadProxy::SetNeedsAnimateOnImplThread() {
490   TRACE_EVENT0("cc", "ThreadProxy::SetNeedsAnimateOnImplThread");
491   DCHECK(IsImplThread());
492   impl().scheduler->SetNeedsAnimate();
493 }
494
495 void ThreadProxy::SetNeedsManageTilesOnImplThread() {
496   DCHECK(IsImplThread());
497   impl().scheduler->SetNeedsManageTiles();
498 }
499
500 void ThreadProxy::SetNeedsRedrawRectOnImplThread(const gfx::Rect& damage_rect) {
501   DCHECK(IsImplThread());
502   impl().layer_tree_host_impl->SetViewportDamage(damage_rect);
503   SetNeedsRedrawOnImplThread();
504 }
505
506 void ThreadProxy::SetSwapUsedIncompleteTileOnImplThread(
507     bool used_incomplete_tile) {
508   DCHECK(IsImplThread());
509   if (used_incomplete_tile) {
510     TRACE_EVENT_INSTANT0("cc",
511                          "ThreadProxy::SetSwapUsedIncompleteTileOnImplThread",
512                          TRACE_EVENT_SCOPE_THREAD);
513   }
514   impl().scheduler->SetSwapUsedIncompleteTile(used_incomplete_tile);
515 }
516
517 void ThreadProxy::DidInitializeVisibleTileOnImplThread() {
518   TRACE_EVENT0("cc", "ThreadProxy::DidInitializeVisibleTileOnImplThread");
519   DCHECK(IsImplThread());
520   impl().scheduler->SetNeedsRedraw();
521 }
522
523 void ThreadProxy::MainThreadHasStoppedFlinging() {
524   DCHECK(IsMainThread());
525   Proxy::ImplThreadTaskRunner()->PostTask(
526       FROM_HERE,
527       base::Bind(&ThreadProxy::MainThreadHasStoppedFlingingOnImplThread,
528                  impl_thread_weak_ptr_));
529 }
530
531 void ThreadProxy::MainThreadHasStoppedFlingingOnImplThread() {
532   DCHECK(IsImplThread());
533   impl().layer_tree_host_impl->MainThreadHasStoppedFlinging();
534 }
535
536 void ThreadProxy::NotifyInputThrottledUntilCommit() {
537   DCHECK(IsMainThread());
538   Proxy::ImplThreadTaskRunner()->PostTask(
539       FROM_HERE,
540       base::Bind(&ThreadProxy::SetInputThrottledUntilCommitOnImplThread,
541                  impl_thread_weak_ptr_,
542                  true));
543 }
544
545 void ThreadProxy::SetInputThrottledUntilCommitOnImplThread(bool is_throttled) {
546   DCHECK(IsImplThread());
547   if (is_throttled == impl().input_throttled_until_commit)
548     return;
549   impl().input_throttled_until_commit = is_throttled;
550   RenewTreePriority();
551 }
552
553 LayerTreeHost* ThreadProxy::layer_tree_host() {
554   return blocked_main().layer_tree_host;
555 }
556
557 const LayerTreeHost* ThreadProxy::layer_tree_host() const {
558   return blocked_main().layer_tree_host;
559 }
560
561 ThreadProxy::MainThreadOnly& ThreadProxy::main() {
562   DCHECK(IsMainThread());
563   return main_thread_only_vars_unsafe_;
564 }
565 const ThreadProxy::MainThreadOnly& ThreadProxy::main() const {
566   DCHECK(IsMainThread());
567   return main_thread_only_vars_unsafe_;
568 }
569
570 ThreadProxy::MainThreadOrBlockedMainThread& ThreadProxy::blocked_main() {
571   DCHECK(IsMainThread() || IsMainThreadBlocked());
572   return main_thread_or_blocked_vars_unsafe_;
573 }
574
575 const ThreadProxy::MainThreadOrBlockedMainThread& ThreadProxy::blocked_main()
576     const {
577   DCHECK(IsMainThread() || IsMainThreadBlocked());
578   return main_thread_or_blocked_vars_unsafe_;
579 }
580
581 ThreadProxy::CompositorThreadOnly& ThreadProxy::impl() {
582   DCHECK(IsImplThread());
583   return compositor_thread_vars_unsafe_;
584 }
585
586 const ThreadProxy::CompositorThreadOnly& ThreadProxy::impl() const {
587   DCHECK(IsImplThread());
588   return compositor_thread_vars_unsafe_;
589 }
590
591 void ThreadProxy::Start() {
592   DCHECK(IsMainThread());
593   DCHECK(Proxy::HasImplThread());
594
595   // Create LayerTreeHostImpl.
596   DebugScopedSetMainThreadBlocked main_thread_blocked(this);
597   CompletionEvent completion;
598   Proxy::ImplThreadTaskRunner()->PostTask(
599       FROM_HERE,
600       base::Bind(&ThreadProxy::InitializeImplOnImplThread,
601                  base::Unretained(this),
602                  &completion));
603   completion.Wait();
604
605   main_thread_weak_ptr_ = main().weak_factory.GetWeakPtr();
606
607   main().started = true;
608 }
609
610 void ThreadProxy::Stop() {
611   TRACE_EVENT0("cc", "ThreadProxy::Stop");
612   DCHECK(IsMainThread());
613   DCHECK(main().started);
614
615   // Synchronously finishes pending GL operations and deletes the impl.
616   // The two steps are done as separate post tasks, so that tasks posted
617   // by the GL implementation due to the Finish can be executed by the
618   // renderer before shutting it down.
619   {
620     DebugScopedSetMainThreadBlocked main_thread_blocked(this);
621
622     CompletionEvent completion;
623     Proxy::ImplThreadTaskRunner()->PostTask(
624         FROM_HERE,
625         base::Bind(&ThreadProxy::FinishGLOnImplThread,
626                    impl_thread_weak_ptr_,
627                    &completion));
628     completion.Wait();
629   }
630   {
631     DebugScopedSetMainThreadBlocked main_thread_blocked(this);
632
633     CompletionEvent completion;
634     Proxy::ImplThreadTaskRunner()->PostTask(
635         FROM_HERE,
636         base::Bind(&ThreadProxy::LayerTreeHostClosedOnImplThread,
637                    impl_thread_weak_ptr_,
638                    &completion));
639     completion.Wait();
640   }
641
642   main().weak_factory.InvalidateWeakPtrs();
643   blocked_main().layer_tree_host = NULL;
644   main().started = false;
645 }
646
647 void ThreadProxy::ForceSerializeOnSwapBuffers() {
648   DebugScopedSetMainThreadBlocked main_thread_blocked(this);
649   CompletionEvent completion;
650   Proxy::ImplThreadTaskRunner()->PostTask(
651       FROM_HERE,
652       base::Bind(&ThreadProxy::ForceSerializeOnSwapBuffersOnImplThread,
653                  impl_thread_weak_ptr_,
654                  &completion));
655   completion.Wait();
656 }
657
658 void ThreadProxy::ForceSerializeOnSwapBuffersOnImplThread(
659     CompletionEvent* completion) {
660   if (impl().layer_tree_host_impl->renderer())
661     impl().layer_tree_host_impl->renderer()->DoNoOp();
662   completion->Signal();
663 }
664
665 bool ThreadProxy::SupportsImplScrolling() const {
666   return true;
667 }
668
669 void ThreadProxy::SetDebugState(const LayerTreeDebugState& debug_state) {
670   Proxy::ImplThreadTaskRunner()->PostTask(
671       FROM_HERE,
672       base::Bind(&ThreadProxy::SetDebugStateOnImplThread,
673                  impl_thread_weak_ptr_,
674                  debug_state));
675 }
676
677 void ThreadProxy::SetDebugStateOnImplThread(
678     const LayerTreeDebugState& debug_state) {
679   DCHECK(IsImplThread());
680   impl().scheduler->SetContinuousPainting(debug_state.continuous_painting);
681 }
682
683 void ThreadProxy::FinishAllRenderingOnImplThread(CompletionEvent* completion) {
684   TRACE_EVENT0("cc", "ThreadProxy::FinishAllRenderingOnImplThread");
685   DCHECK(IsImplThread());
686   impl().layer_tree_host_impl->FinishAllRendering();
687   completion->Signal();
688 }
689
690 void ThreadProxy::ScheduledActionSendBeginMainFrame() {
691   unsigned int begin_frame_id = nextBeginFrameId++;
692   benchmark_instrumentation::ScopedBeginFrameTask begin_frame_task(
693       benchmark_instrumentation::kSendBeginFrame, begin_frame_id);
694   scoped_ptr<BeginMainFrameAndCommitState> begin_main_frame_state(
695       new BeginMainFrameAndCommitState);
696   begin_main_frame_state->begin_frame_id = begin_frame_id;
697   begin_main_frame_state->monotonic_frame_begin_time =
698       impl().layer_tree_host_impl->CurrentFrameTimeTicks();
699   begin_main_frame_state->scroll_info =
700       impl().layer_tree_host_impl->ProcessScrollDeltas();
701
702   if (!impl().layer_tree_host_impl->settings().impl_side_painting) {
703     DCHECK_GT(impl().layer_tree_host_impl->memory_allocation_limit_bytes(), 0u);
704   }
705   begin_main_frame_state->memory_allocation_limit_bytes =
706       impl().layer_tree_host_impl->memory_allocation_limit_bytes();
707   begin_main_frame_state->memory_allocation_priority_cutoff =
708       impl().layer_tree_host_impl->memory_allocation_priority_cutoff();
709   begin_main_frame_state->evicted_ui_resources =
710       impl().layer_tree_host_impl->EvictedUIResourcesExist();
711   Proxy::MainThreadTaskRunner()->PostTask(
712       FROM_HERE,
713       base::Bind(&ThreadProxy::BeginMainFrame,
714                  main_thread_weak_ptr_,
715                  base::Passed(&begin_main_frame_state)));
716   devtools_instrumentation::DidRequestMainThreadFrame(
717       impl().layer_tree_host_id);
718   impl().timing_history.DidBeginMainFrame();
719 }
720
721 void ThreadProxy::BeginMainFrame(
722     scoped_ptr<BeginMainFrameAndCommitState> begin_main_frame_state) {
723   benchmark_instrumentation::ScopedBeginFrameTask begin_frame_task(
724       benchmark_instrumentation::kDoBeginFrame,
725       begin_main_frame_state->begin_frame_id);
726   TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("cc.BeginMainFrame");
727   DCHECK(IsMainThread());
728
729   if (main().defer_commits) {
730     main().pending_deferred_commit = begin_main_frame_state.Pass();
731     layer_tree_host()->DidDeferCommit();
732     TRACE_EVENT_INSTANT0(
733         "cc", "EarlyOut_DeferCommits", TRACE_EVENT_SCOPE_THREAD);
734     return;
735   }
736
737   // If the commit finishes, LayerTreeHost will transfer its swap promises to
738   // LayerTreeImpl. The destructor of SwapPromiseChecker checks LayerTressHost's
739   // swap promises.
740   SwapPromiseChecker swap_promise_checker(layer_tree_host());
741
742   main().commit_requested = false;
743   main().commit_request_sent_to_impl_thread = false;
744   main().animate_requested = false;
745
746   if (!layer_tree_host()->visible()) {
747     TRACE_EVENT_INSTANT0("cc", "EarlyOut_NotVisible", TRACE_EVENT_SCOPE_THREAD);
748     bool did_handle = false;
749     Proxy::ImplThreadTaskRunner()->PostTask(
750         FROM_HERE,
751         base::Bind(&ThreadProxy::BeginMainFrameAbortedOnImplThread,
752                    impl_thread_weak_ptr_,
753                    did_handle));
754     return;
755   }
756
757   if (layer_tree_host()->output_surface_lost()) {
758     TRACE_EVENT_INSTANT0(
759         "cc", "EarlyOut_OutputSurfaceLost", TRACE_EVENT_SCOPE_THREAD);
760     bool did_handle = false;
761     Proxy::ImplThreadTaskRunner()->PostTask(
762         FROM_HERE,
763         base::Bind(&ThreadProxy::BeginMainFrameAbortedOnImplThread,
764                    impl_thread_weak_ptr_,
765                    did_handle));
766     return;
767   }
768
769   // Do not notify the impl thread of commit requests that occur during
770   // the apply/animate/layout part of the BeginMainFrameAndCommit process since
771   // those commit requests will get painted immediately. Once we have done
772   // the paint, main().commit_requested will be set to false to allow new commit
773   // requests to be scheduled.
774   // On the other hand, the animate_requested flag should remain cleared
775   // here so that any animation requests generated by the apply or animate
776   // callbacks will trigger another frame.
777   main().commit_requested = true;
778   main().commit_request_sent_to_impl_thread = true;
779
780   layer_tree_host()->ApplyScrollAndScale(
781       begin_main_frame_state->scroll_info.get());
782
783   layer_tree_host()->WillBeginMainFrame();
784
785   layer_tree_host()->UpdateClientAnimations(
786       begin_main_frame_state->monotonic_frame_begin_time);
787   layer_tree_host()->AnimateLayers(
788       begin_main_frame_state->monotonic_frame_begin_time);
789   blocked_main().last_monotonic_frame_begin_time =
790       begin_main_frame_state->monotonic_frame_begin_time;
791
792   // Unlink any backings that the impl thread has evicted, so that we know to
793   // re-paint them in UpdateLayers.
794   if (blocked_main().contents_texture_manager()) {
795     blocked_main().contents_texture_manager()->UnlinkAndClearEvictedBackings();
796
797     blocked_main().contents_texture_manager()->SetMaxMemoryLimitBytes(
798         begin_main_frame_state->memory_allocation_limit_bytes);
799     blocked_main().contents_texture_manager()->SetExternalPriorityCutoff(
800         begin_main_frame_state->memory_allocation_priority_cutoff);
801   }
802
803   // Recreate all UI resources if there were evicted UI resources when the impl
804   // thread initiated the commit.
805   if (begin_main_frame_state->evicted_ui_resources)
806     layer_tree_host()->RecreateUIResources();
807
808   layer_tree_host()->Layout();
809   TRACE_EVENT_SYNTHETIC_DELAY_END("cc.BeginMainFrame");
810
811   // Clear the commit flag after updating animations and layout here --- objects
812   // that only layout when painted will trigger another SetNeedsCommit inside
813   // UpdateLayers.
814   main().commit_requested = false;
815   main().commit_request_sent_to_impl_thread = false;
816   bool can_cancel_this_commit =
817       main().can_cancel_commit && !begin_main_frame_state->evicted_ui_resources;
818   main().can_cancel_commit = true;
819
820   scoped_ptr<ResourceUpdateQueue> queue =
821       make_scoped_ptr(new ResourceUpdateQueue);
822
823   bool updated = layer_tree_host()->UpdateLayers(queue.get());
824
825   layer_tree_host()->WillCommit();
826
827   // Before calling animate, we set main().animate_requested to false. If it is
828   // true now, it means SetNeedAnimate was called again, but during a state when
829   // main().commit_request_sent_to_impl_thread = true. We need to force that
830   // call to happen again now so that the commit request is sent to the impl
831   // thread.
832   if (main().animate_requested) {
833     // Forces SetNeedsAnimate to consider posting a commit task.
834     main().animate_requested = false;
835     SetNeedsAnimate();
836   }
837
838   if (!updated && can_cancel_this_commit) {
839     TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoUpdates", TRACE_EVENT_SCOPE_THREAD);
840     bool did_handle = true;
841     Proxy::ImplThreadTaskRunner()->PostTask(
842         FROM_HERE,
843         base::Bind(&ThreadProxy::BeginMainFrameAbortedOnImplThread,
844                    impl_thread_weak_ptr_,
845                    did_handle));
846
847     // Although the commit is internally aborted, this is because it has been
848     // detected to be a no-op.  From the perspective of an embedder, this commit
849     // went through, and input should no longer be throttled, etc.
850     layer_tree_host()->CommitComplete();
851     layer_tree_host()->DidBeginMainFrame();
852     layer_tree_host()->BreakSwapPromises(SwapPromise::COMMIT_NO_UPDATE);
853     return;
854   }
855
856   // Notify the impl thread that the main thread is ready to commit. This will
857   // begin the commit process, which is blocking from the main thread's
858   // point of view, but asynchronously performed on the impl thread,
859   // coordinated by the Scheduler.
860   {
861     TRACE_EVENT0("cc", "ThreadProxy::BeginMainFrame::commit");
862
863     DebugScopedSetMainThreadBlocked main_thread_blocked(this);
864
865     // This CapturePostTasks should be destroyed before CommitComplete() is
866     // called since that goes out to the embedder, and we want the embedder
867     // to receive its callbacks before that.
868     BlockingTaskRunner::CapturePostTasks blocked;
869
870     CompletionEvent completion;
871     Proxy::ImplThreadTaskRunner()->PostTask(
872         FROM_HERE,
873         base::Bind(&ThreadProxy::StartCommitOnImplThread,
874                    impl_thread_weak_ptr_,
875                    &completion,
876                    queue.release()));
877     completion.Wait();
878
879     RenderingStatsInstrumentation* stats_instrumentation =
880         layer_tree_host()->rendering_stats_instrumentation();
881     benchmark_instrumentation::IssueMainThreadRenderingStatsEvent(
882         stats_instrumentation->main_thread_rendering_stats());
883     stats_instrumentation->AccumulateAndClearMainThreadStats();
884   }
885
886   layer_tree_host()->CommitComplete();
887   layer_tree_host()->DidBeginMainFrame();
888 }
889
890 void ThreadProxy::StartCommitOnImplThread(CompletionEvent* completion,
891                                           ResourceUpdateQueue* raw_queue) {
892   TRACE_EVENT0("cc", "ThreadProxy::StartCommitOnImplThread");
893   DCHECK(!impl().commit_completion_event);
894   DCHECK(IsImplThread() && IsMainThreadBlocked());
895   DCHECK(impl().scheduler);
896   DCHECK(impl().scheduler->CommitPending());
897
898   if (!impl().layer_tree_host_impl) {
899     TRACE_EVENT_INSTANT0(
900         "cc", "EarlyOut_NoLayerTree", TRACE_EVENT_SCOPE_THREAD);
901     completion->Signal();
902     return;
903   }
904
905   // Ideally, we should inform to impl thread when BeginMainFrame is started.
906   // But, we can avoid a PostTask in here.
907   impl().scheduler->NotifyBeginMainFrameStarted();
908
909   scoped_ptr<ResourceUpdateQueue> queue(raw_queue);
910
911   if (impl().contents_texture_manager) {
912     DCHECK_EQ(impl().contents_texture_manager,
913               blocked_main().contents_texture_manager());
914   } else {
915     // Cache this pointer that was created on the main thread side to avoid a
916     // data race between creating it and using it on the compositor thread.
917     impl().contents_texture_manager = blocked_main().contents_texture_manager();
918   }
919
920   if (impl().contents_texture_manager) {
921     if (impl().contents_texture_manager->LinkedEvictedBackingsExist()) {
922       // Clear any uploads we were making to textures linked to evicted
923       // resources
924       queue->ClearUploadsToEvictedResources();
925       // Some textures in the layer tree are invalid. Kick off another commit
926       // to fill them again.
927       SetNeedsCommitOnImplThread();
928     }
929
930     impl().contents_texture_manager->PushTexturePrioritiesToBackings();
931   }
932
933   impl().commit_completion_event = completion;
934   impl().current_resource_update_controller = ResourceUpdateController::Create(
935       this,
936       Proxy::ImplThreadTaskRunner(),
937       queue.Pass(),
938       impl().layer_tree_host_impl->resource_provider());
939   impl().current_resource_update_controller->PerformMoreUpdates(
940       impl().scheduler->AnticipatedDrawTime());
941 }
942
943 void ThreadProxy::BeginMainFrameAbortedOnImplThread(bool did_handle) {
944   TRACE_EVENT0("cc", "ThreadProxy::BeginMainFrameAbortedOnImplThread");
945   DCHECK(IsImplThread());
946   DCHECK(impl().scheduler);
947   DCHECK(impl().scheduler->CommitPending());
948   DCHECK(!impl().layer_tree_host_impl->pending_tree());
949
950   if (did_handle)
951     SetInputThrottledUntilCommitOnImplThread(false);
952   impl().layer_tree_host_impl->BeginMainFrameAborted(did_handle);
953   impl().scheduler->BeginMainFrameAborted(did_handle);
954 }
955
956 void ThreadProxy::ScheduledActionAnimate() {
957   TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionAnimate");
958   DCHECK(IsImplThread());
959
960   if (!impl().animations_frozen_until_next_draw) {
961     impl().animation_time =
962         impl().layer_tree_host_impl->CurrentFrameTimeTicks();
963   }
964   impl().layer_tree_host_impl->Animate(impl().animation_time);
965   impl().did_commit_after_animating = false;
966 }
967
968 void ThreadProxy::ScheduledActionCommit() {
969   TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionCommit");
970   DCHECK(IsImplThread());
971   DCHECK(IsMainThreadBlocked());
972   DCHECK(impl().commit_completion_event);
973   DCHECK(impl().current_resource_update_controller);
974
975   // Complete all remaining texture updates.
976   impl().current_resource_update_controller->Finalize();
977   impl().current_resource_update_controller.reset();
978
979   if (impl().animations_frozen_until_next_draw) {
980     impl().animation_time = std::max(
981         impl().animation_time, blocked_main().last_monotonic_frame_begin_time);
982   }
983   impl().did_commit_after_animating = true;
984
985   blocked_main().main_thread_inside_commit = true;
986   impl().layer_tree_host_impl->BeginCommit();
987   layer_tree_host()->BeginCommitOnImplThread(impl().layer_tree_host_impl.get());
988   layer_tree_host()->FinishCommitOnImplThread(
989       impl().layer_tree_host_impl.get());
990   blocked_main().main_thread_inside_commit = false;
991
992   bool hold_commit = layer_tree_host()->settings().impl_side_painting &&
993                      blocked_main().commit_waits_for_activation;
994   blocked_main().commit_waits_for_activation = false;
995
996   if (hold_commit) {
997     // For some layer types in impl-side painting, the commit is held until
998     // the sync tree is activated.  It's also possible that the
999     // sync tree has already activated if there was no work to be done.
1000     TRACE_EVENT_INSTANT0("cc", "HoldCommit", TRACE_EVENT_SCOPE_THREAD);
1001     impl().completion_event_for_commit_held_on_tree_activation =
1002         impl().commit_completion_event;
1003     impl().commit_completion_event = NULL;
1004   } else {
1005     impl().commit_completion_event->Signal();
1006     impl().commit_completion_event = NULL;
1007   }
1008
1009   // Delay this step until afer the main thread has been released as it's
1010   // often a good bit of work to update the tree and prepare the new frame.
1011   impl().layer_tree_host_impl->CommitComplete();
1012
1013   SetInputThrottledUntilCommitOnImplThread(false);
1014
1015   UpdateBackgroundAnimateTicking();
1016
1017   impl().next_frame_is_newly_committed_frame = true;
1018
1019   impl().timing_history.DidCommit();
1020 }
1021
1022 void ThreadProxy::ScheduledActionUpdateVisibleTiles() {
1023   TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionUpdateVisibleTiles");
1024   DCHECK(IsImplThread());
1025   impl().layer_tree_host_impl->UpdateVisibleTiles();
1026 }
1027
1028 void ThreadProxy::ScheduledActionActivateSyncTree() {
1029   TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionActivateSyncTree");
1030   DCHECK(IsImplThread());
1031   impl().layer_tree_host_impl->ActivateSyncTree();
1032 }
1033
1034 void ThreadProxy::ScheduledActionBeginOutputSurfaceCreation() {
1035   TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionBeginOutputSurfaceCreation");
1036   DCHECK(IsImplThread());
1037   Proxy::MainThreadTaskRunner()->PostTask(
1038       FROM_HERE,
1039       base::Bind(&ThreadProxy::CreateAndInitializeOutputSurface,
1040                  main_thread_weak_ptr_));
1041 }
1042
1043 DrawResult ThreadProxy::DrawSwapInternal(bool forced_draw) {
1044   TRACE_EVENT_SYNTHETIC_DELAY("cc.DrawAndSwap");
1045   DrawResult result;
1046
1047   DCHECK(IsImplThread());
1048   DCHECK(impl().layer_tree_host_impl.get());
1049
1050   impl().timing_history.DidStartDrawing();
1051   base::AutoReset<bool> mark_inside(&impl().inside_draw, true);
1052
1053   if (impl().did_commit_after_animating) {
1054     impl().layer_tree_host_impl->Animate(impl().animation_time);
1055     impl().did_commit_after_animating = false;
1056   }
1057
1058   if (impl().layer_tree_host_impl->pending_tree())
1059     impl().layer_tree_host_impl->pending_tree()->UpdateDrawProperties();
1060
1061   // This method is called on a forced draw, regardless of whether we are able
1062   // to produce a frame, as the calling site on main thread is blocked until its
1063   // request completes, and we signal completion here. If CanDraw() is false, we
1064   // will indicate success=false to the caller, but we must still signal
1065   // completion to avoid deadlock.
1066
1067   // We guard PrepareToDraw() with CanDraw() because it always returns a valid
1068   // frame, so can only be used when such a frame is possible. Since
1069   // DrawLayers() depends on the result of PrepareToDraw(), it is guarded on
1070   // CanDraw() as well.
1071
1072   LayerTreeHostImpl::FrameData frame;
1073   bool draw_frame = false;
1074
1075   if (impl().layer_tree_host_impl->CanDraw()) {
1076     result = impl().layer_tree_host_impl->PrepareToDraw(&frame);
1077     draw_frame = forced_draw || result == DRAW_SUCCESS;
1078   } else {
1079     result = DRAW_ABORTED_CANT_DRAW;
1080   }
1081
1082   if (draw_frame) {
1083     impl().layer_tree_host_impl->DrawLayers(
1084         &frame, impl().scheduler->LastBeginImplFrameTime());
1085     result = DRAW_SUCCESS;
1086     impl().animations_frozen_until_next_draw = false;
1087   } else if (result == DRAW_ABORTED_CHECKERBOARD_ANIMATIONS &&
1088              !impl().layer_tree_host_impl->settings().impl_side_painting) {
1089     // Without impl-side painting, the animated layer that is checkerboarding
1090     // will continue to checkerboard until the next commit. If this layer
1091     // continues to move during the commit, it may continue to checkerboard
1092     // after the commit since the region rasterized during the commit will not
1093     // match the region that is currently visible; eventually this
1094     // checkerboarding will be displayed when we force a draw. To avoid this,
1095     // we freeze animations until we successfully draw.
1096     impl().animations_frozen_until_next_draw = true;
1097   } else {
1098     DCHECK_NE(DRAW_SUCCESS, result);
1099   }
1100   impl().layer_tree_host_impl->DidDrawAllLayers(frame);
1101
1102   bool start_ready_animations = draw_frame;
1103   impl().layer_tree_host_impl->UpdateAnimationState(start_ready_animations);
1104
1105   if (draw_frame) {
1106     bool did_request_swap = impl().layer_tree_host_impl->SwapBuffers(frame);
1107
1108     // We don't know if we have incomplete tiles if we didn't actually swap.
1109     if (did_request_swap) {
1110       DCHECK(!frame.has_no_damage);
1111       SetSwapUsedIncompleteTileOnImplThread(frame.contains_incomplete_tile);
1112     }
1113   }
1114
1115   // Tell the main thread that the the newly-commited frame was drawn.
1116   if (impl().next_frame_is_newly_committed_frame) {
1117     impl().next_frame_is_newly_committed_frame = false;
1118     Proxy::MainThreadTaskRunner()->PostTask(
1119         FROM_HERE,
1120         base::Bind(&ThreadProxy::DidCommitAndDrawFrame, main_thread_weak_ptr_));
1121   }
1122
1123   if (result == DRAW_SUCCESS)
1124     impl().timing_history.DidFinishDrawing();
1125
1126   DCHECK_NE(INVALID_RESULT, result);
1127   return result;
1128 }
1129
1130 void ThreadProxy::ScheduledActionManageTiles() {
1131   TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionManageTiles");
1132   DCHECK(impl().layer_tree_host_impl->settings().impl_side_painting);
1133   impl().layer_tree_host_impl->ManageTiles();
1134 }
1135
1136 DrawResult ThreadProxy::ScheduledActionDrawAndSwapIfPossible() {
1137   TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionDrawAndSwap");
1138
1139   // SchedulerStateMachine::DidDrawIfPossibleCompleted isn't set up to
1140   // handle DRAW_ABORTED_CANT_DRAW.  Moreover, the scheduler should
1141   // never generate this call when it can't draw.
1142   DCHECK(impl().layer_tree_host_impl->CanDraw());
1143
1144   bool forced_draw = false;
1145   return DrawSwapInternal(forced_draw);
1146 }
1147
1148 DrawResult ThreadProxy::ScheduledActionDrawAndSwapForced() {
1149   TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionDrawAndSwapForced");
1150   bool forced_draw = true;
1151   return DrawSwapInternal(forced_draw);
1152 }
1153
1154 void ThreadProxy::DidAnticipatedDrawTimeChange(base::TimeTicks time) {
1155   if (impl().current_resource_update_controller)
1156     impl().current_resource_update_controller->PerformMoreUpdates(time);
1157 }
1158
1159 base::TimeDelta ThreadProxy::DrawDurationEstimate() {
1160   return impl().timing_history.DrawDurationEstimate();
1161 }
1162
1163 base::TimeDelta ThreadProxy::BeginMainFrameToCommitDurationEstimate() {
1164   return impl().timing_history.BeginMainFrameToCommitDurationEstimate();
1165 }
1166
1167 base::TimeDelta ThreadProxy::CommitToActivateDurationEstimate() {
1168   return impl().timing_history.CommitToActivateDurationEstimate();
1169 }
1170
1171 void ThreadProxy::DidBeginImplFrameDeadline() {
1172   impl().layer_tree_host_impl->ResetCurrentFrameTimeForNextFrame();
1173 }
1174
1175 void ThreadProxy::ReadyToFinalizeTextureUpdates() {
1176   DCHECK(IsImplThread());
1177   impl().scheduler->NotifyReadyToCommit();
1178 }
1179
1180 void ThreadProxy::DidCommitAndDrawFrame() {
1181   DCHECK(IsMainThread());
1182   layer_tree_host()->DidCommitAndDrawFrame();
1183 }
1184
1185 void ThreadProxy::DidCompleteSwapBuffers() {
1186   DCHECK(IsMainThread());
1187   layer_tree_host()->DidCompleteSwapBuffers();
1188 }
1189
1190 void ThreadProxy::SetAnimationEvents(scoped_ptr<AnimationEventsVector> events) {
1191   TRACE_EVENT0("cc", "ThreadProxy::SetAnimationEvents");
1192   DCHECK(IsMainThread());
1193   layer_tree_host()->SetAnimationEvents(events.Pass());
1194 }
1195
1196 void ThreadProxy::InitializeImplOnImplThread(CompletionEvent* completion) {
1197   TRACE_EVENT0("cc", "ThreadProxy::InitializeImplOnImplThread");
1198   DCHECK(IsImplThread());
1199   impl().layer_tree_host_impl =
1200       layer_tree_host()->CreateLayerTreeHostImpl(this);
1201   SchedulerSettings scheduler_settings(layer_tree_host()->settings());
1202   impl().scheduler = Scheduler::Create(this,
1203                                        scheduler_settings,
1204                                        impl().layer_tree_host_id,
1205                                        ImplThreadTaskRunner());
1206   impl().scheduler->SetVisible(impl().layer_tree_host_impl->visible());
1207
1208   impl_thread_weak_ptr_ = impl().weak_factory.GetWeakPtr();
1209   completion->Signal();
1210 }
1211
1212 void ThreadProxy::DeleteContentsTexturesOnImplThread(
1213     CompletionEvent* completion) {
1214   TRACE_EVENT0("cc", "ThreadProxy::DeleteContentsTexturesOnImplThread");
1215   DCHECK(IsImplThread());
1216   DCHECK(IsMainThreadBlocked());
1217   layer_tree_host()->DeleteContentsTexturesOnImplThread(
1218       impl().layer_tree_host_impl->resource_provider());
1219   completion->Signal();
1220 }
1221
1222 void ThreadProxy::InitializeOutputSurfaceOnImplThread(
1223     scoped_ptr<OutputSurface> output_surface) {
1224   TRACE_EVENT0("cc", "ThreadProxy::InitializeOutputSurfaceOnImplThread");
1225   DCHECK(IsImplThread());
1226
1227   LayerTreeHostImpl* host_impl = impl().layer_tree_host_impl.get();
1228   bool success = host_impl->InitializeRenderer(output_surface.Pass());
1229   RendererCapabilities capabilities;
1230   if (success) {
1231     capabilities =
1232         host_impl->GetRendererCapabilities().MainThreadCapabilities();
1233   }
1234
1235   Proxy::MainThreadTaskRunner()->PostTask(
1236       FROM_HERE,
1237       base::Bind(&ThreadProxy::DidInitializeOutputSurface,
1238                  main_thread_weak_ptr_,
1239                  success,
1240                  capabilities));
1241
1242   if (success)
1243     impl().scheduler->DidCreateAndInitializeOutputSurface();
1244 }
1245
1246 void ThreadProxy::FinishGLOnImplThread(CompletionEvent* completion) {
1247   TRACE_EVENT0("cc", "ThreadProxy::FinishGLOnImplThread");
1248   DCHECK(IsImplThread());
1249   if (impl().layer_tree_host_impl->output_surface()) {
1250     ContextProvider* context_provider =
1251         impl().layer_tree_host_impl->output_surface()->context_provider();
1252     if (context_provider)
1253       context_provider->ContextGL()->Finish();
1254   }
1255   completion->Signal();
1256 }
1257
1258 void ThreadProxy::LayerTreeHostClosedOnImplThread(CompletionEvent* completion) {
1259   TRACE_EVENT0("cc", "ThreadProxy::LayerTreeHostClosedOnImplThread");
1260   DCHECK(IsImplThread());
1261   DCHECK(IsMainThreadBlocked());
1262   layer_tree_host()->DeleteContentsTexturesOnImplThread(
1263       impl().layer_tree_host_impl->resource_provider());
1264   impl().current_resource_update_controller.reset();
1265   impl().layer_tree_host_impl->SetNeedsBeginFrame(false);
1266   impl().scheduler.reset();
1267   impl().layer_tree_host_impl.reset();
1268   impl().weak_factory.InvalidateWeakPtrs();
1269   impl().contents_texture_manager = NULL;
1270   completion->Signal();
1271 }
1272
1273 size_t ThreadProxy::MaxPartialTextureUpdates() const {
1274   return ResourceUpdateController::MaxPartialTextureUpdates();
1275 }
1276
1277 ThreadProxy::BeginMainFrameAndCommitState::BeginMainFrameAndCommitState()
1278     : memory_allocation_limit_bytes(0),
1279       memory_allocation_priority_cutoff(0),
1280       evicted_ui_resources(false) {}
1281
1282 ThreadProxy::BeginMainFrameAndCommitState::~BeginMainFrameAndCommitState() {}
1283
1284 void ThreadProxy::AsValueInto(base::debug::TracedValue* state) const {
1285   CompletionEvent completion;
1286   {
1287     DebugScopedSetMainThreadBlocked main_thread_blocked(
1288         const_cast<ThreadProxy*>(this));
1289     scoped_refptr<base::debug::TracedValue> state_refptr(state);
1290     Proxy::ImplThreadTaskRunner()->PostTask(
1291         FROM_HERE,
1292         base::Bind(&ThreadProxy::AsValueOnImplThread,
1293                    impl_thread_weak_ptr_,
1294                    &completion,
1295                    state_refptr));
1296     completion.Wait();
1297   }
1298 }
1299
1300 void ThreadProxy::AsValueOnImplThread(CompletionEvent* completion,
1301                                       base::debug::TracedValue* state) const {
1302   state->BeginDictionary("layer_tree_host_impl");
1303   impl().layer_tree_host_impl->AsValueInto(state);
1304   state->EndDictionary();
1305   completion->Signal();
1306 }
1307
1308 bool ThreadProxy::MainFrameWillHappenForTesting() {
1309   DCHECK(IsMainThread());
1310   CompletionEvent completion;
1311   bool main_frame_will_happen = false;
1312   {
1313     DebugScopedSetMainThreadBlocked main_thread_blocked(this);
1314     Proxy::ImplThreadTaskRunner()->PostTask(
1315         FROM_HERE,
1316         base::Bind(&ThreadProxy::MainFrameWillHappenOnImplThreadForTesting,
1317                    impl_thread_weak_ptr_,
1318                    &completion,
1319                    &main_frame_will_happen));
1320     completion.Wait();
1321   }
1322   return main_frame_will_happen;
1323 }
1324
1325 void ThreadProxy::MainFrameWillHappenOnImplThreadForTesting(
1326     CompletionEvent* completion,
1327     bool* main_frame_will_happen) {
1328   DCHECK(IsImplThread());
1329   if (impl().layer_tree_host_impl->output_surface()) {
1330     *main_frame_will_happen = impl().scheduler->MainFrameForTestingWillHappen();
1331   } else {
1332     *main_frame_will_happen = false;
1333   }
1334   completion->Signal();
1335 }
1336
1337 void ThreadProxy::RenewTreePriority() {
1338   DCHECK(IsImplThread());
1339   bool smoothness_takes_priority =
1340       impl().layer_tree_host_impl->pinch_gesture_active() ||
1341       impl().layer_tree_host_impl->page_scale_animation_active() ||
1342       (impl().layer_tree_host_impl->IsCurrentlyScrolling() &&
1343        !impl().layer_tree_host_impl->scroll_affects_scroll_handler());
1344
1345   // Schedule expiration if smoothness currently takes priority.
1346   if (smoothness_takes_priority)
1347     impl().smoothness_priority_expiration_notifier.Schedule();
1348
1349   // We use the same priority for both trees by default.
1350   TreePriority priority = SAME_PRIORITY_FOR_BOTH_TREES;
1351
1352   // Smoothness takes priority if we have an expiration for it scheduled.
1353   if (impl().smoothness_priority_expiration_notifier.HasPendingNotification())
1354     priority = SMOOTHNESS_TAKES_PRIORITY;
1355
1356   // New content always takes priority when the active tree has
1357   // evicted resources or there is an invalid viewport size.
1358   if (impl().layer_tree_host_impl->active_tree()->ContentsTexturesPurged() ||
1359       impl().layer_tree_host_impl->active_tree()->ViewportSizeInvalid() ||
1360       impl().layer_tree_host_impl->EvictedUIResourcesExist() ||
1361       impl().input_throttled_until_commit) {
1362     // Once we enter NEW_CONTENTS_TAKES_PRIORITY mode, visible tiles on active
1363     // tree might be freed. We need to set RequiresHighResToDraw to ensure that
1364     // high res tiles will be required to activate pending tree.
1365     impl().layer_tree_host_impl->active_tree()->SetRequiresHighResToDraw();
1366     priority = NEW_CONTENT_TAKES_PRIORITY;
1367   }
1368
1369   impl().layer_tree_host_impl->SetTreePriority(priority);
1370   impl().scheduler->SetSmoothnessTakesPriority(priority ==
1371                                                SMOOTHNESS_TAKES_PRIORITY);
1372
1373   // Notify the the client of this compositor via the output surface.
1374   // TODO(epenner): Route this to compositor-thread instead of output-surface
1375   // after GTFO refactor of compositor-thread (http://crbug/170828).
1376   if (impl().layer_tree_host_impl->output_surface()) {
1377     impl()
1378         .layer_tree_host_impl->output_surface()
1379         ->UpdateSmoothnessTakesPriority(priority == SMOOTHNESS_TAKES_PRIORITY);
1380   }
1381 }
1382
1383 void ThreadProxy::PostDelayedScrollbarFadeOnImplThread(
1384     const base::Closure& start_fade,
1385     base::TimeDelta delay) {
1386   Proxy::ImplThreadTaskRunner()->PostDelayedTask(FROM_HERE, start_fade, delay);
1387 }
1388
1389 void ThreadProxy::DidActivateSyncTree() {
1390   TRACE_EVENT0("cc", "ThreadProxy::DidActivateSyncTreeOnImplThread");
1391   DCHECK(IsImplThread());
1392
1393   if (impl().completion_event_for_commit_held_on_tree_activation) {
1394     TRACE_EVENT_INSTANT0(
1395         "cc", "ReleaseCommitbyActivation", TRACE_EVENT_SCOPE_THREAD);
1396     DCHECK(impl().layer_tree_host_impl->settings().impl_side_painting);
1397     impl().completion_event_for_commit_held_on_tree_activation->Signal();
1398     impl().completion_event_for_commit_held_on_tree_activation = NULL;
1399   }
1400
1401   UpdateBackgroundAnimateTicking();
1402
1403   impl().timing_history.DidActivateSyncTree();
1404 }
1405
1406 void ThreadProxy::DidManageTiles() {
1407   DCHECK(IsImplThread());
1408   impl().scheduler->DidManageTiles();
1409 }
1410
1411 }  // namespace cc