Give names to all utility processes.
[chromium-blink-merge.git] / cc / trees / thread_proxy.cc
blobbeaf92f50b474d3491752d578936d817ddb380a6
1 // Copyright 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/trees/thread_proxy.h"
7 #include <algorithm>
8 #include <string>
10 #include "base/auto_reset.h"
11 #include "base/bind.h"
12 #include "base/trace_event/trace_event.h"
13 #include "base/trace_event/trace_event_argument.h"
14 #include "base/trace_event/trace_event_synthetic_delay.h"
15 #include "cc/debug/benchmark_instrumentation.h"
16 #include "cc/debug/devtools_instrumentation.h"
17 #include "cc/input/input_handler.h"
18 #include "cc/output/context_provider.h"
19 #include "cc/output/output_surface.h"
20 #include "cc/output/swap_promise.h"
21 #include "cc/quads/draw_quad.h"
22 #include "cc/resources/prioritized_resource_manager.h"
23 #include "cc/scheduler/commit_earlyout_reason.h"
24 #include "cc/scheduler/delay_based_time_source.h"
25 #include "cc/scheduler/scheduler.h"
26 #include "cc/trees/blocking_task_runner.h"
27 #include "cc/trees/layer_tree_host.h"
28 #include "cc/trees/layer_tree_impl.h"
29 #include "cc/trees/scoped_abort_remaining_swap_promises.h"
30 #include "gpu/command_buffer/client/gles2_interface.h"
31 #include "ui/gfx/frame_time.h"
33 namespace cc {
35 namespace {
37 // Measured in seconds.
38 const double kSmoothnessTakesPriorityExpirationDelay = 0.25;
40 unsigned int nextBeginFrameId = 0;
42 } // namespace
44 struct ThreadProxy::SchedulerStateRequest {
45 CompletionEvent completion;
46 scoped_ptr<base::Value> state;
49 scoped_ptr<Proxy> ThreadProxy::Create(
50 LayerTreeHost* layer_tree_host,
51 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
52 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner,
53 scoped_ptr<BeginFrameSource> external_begin_frame_source) {
54 return make_scoped_ptr(new ThreadProxy(layer_tree_host,
55 main_task_runner,
56 impl_task_runner,
57 external_begin_frame_source.Pass()));
60 ThreadProxy::ThreadProxy(
61 LayerTreeHost* layer_tree_host,
62 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner,
63 scoped_refptr<base::SingleThreadTaskRunner> impl_task_runner,
64 scoped_ptr<BeginFrameSource> external_begin_frame_source)
65 : Proxy(main_task_runner, impl_task_runner),
66 main_thread_only_vars_unsafe_(this, layer_tree_host->id()),
67 main_thread_or_blocked_vars_unsafe_(layer_tree_host),
68 compositor_thread_vars_unsafe_(
69 this,
70 layer_tree_host->id(),
71 layer_tree_host->rendering_stats_instrumentation(),
72 external_begin_frame_source.Pass()) {
73 TRACE_EVENT0("cc", "ThreadProxy::ThreadProxy");
74 DCHECK(IsMainThread());
75 DCHECK(this->layer_tree_host());
78 ThreadProxy::MainThreadOnly::MainThreadOnly(ThreadProxy* proxy,
79 int layer_tree_host_id)
80 : layer_tree_host_id(layer_tree_host_id),
81 animate_requested(false),
82 commit_requested(false),
83 commit_request_sent_to_impl_thread(false),
84 started(false),
85 prepare_tiles_pending(false),
86 can_cancel_commit(true),
87 defer_commits(false),
88 weak_factory(proxy) {
91 ThreadProxy::MainThreadOnly::~MainThreadOnly() {}
93 ThreadProxy::MainThreadOrBlockedMainThread::MainThreadOrBlockedMainThread(
94 LayerTreeHost* host)
95 : layer_tree_host(host),
96 commit_waits_for_activation(false),
97 main_thread_inside_commit(false) {}
99 ThreadProxy::MainThreadOrBlockedMainThread::~MainThreadOrBlockedMainThread() {}
101 PrioritizedResourceManager*
102 ThreadProxy::MainThreadOrBlockedMainThread::contents_texture_manager() {
103 return layer_tree_host->contents_texture_manager();
106 ThreadProxy::CompositorThreadOnly::CompositorThreadOnly(
107 ThreadProxy* proxy,
108 int layer_tree_host_id,
109 RenderingStatsInstrumentation* rendering_stats_instrumentation,
110 scoped_ptr<BeginFrameSource> external_begin_frame_source)
111 : layer_tree_host_id(layer_tree_host_id),
112 contents_texture_manager(NULL),
113 commit_completion_event(NULL),
114 completion_event_for_commit_held_on_tree_activation(NULL),
115 next_frame_is_newly_committed_frame(false),
116 inside_draw(false),
117 input_throttled_until_commit(false),
118 smoothness_priority_expiration_notifier(
119 proxy->ImplThreadTaskRunner(),
120 base::Bind(&ThreadProxy::RenewTreePriority, base::Unretained(proxy)),
121 base::TimeDelta::FromMilliseconds(
122 kSmoothnessTakesPriorityExpirationDelay * 1000)),
123 timing_history(rendering_stats_instrumentation),
124 external_begin_frame_source(external_begin_frame_source.Pass()),
125 weak_factory(proxy) {
128 ThreadProxy::CompositorThreadOnly::~CompositorThreadOnly() {}
130 ThreadProxy::~ThreadProxy() {
131 TRACE_EVENT0("cc", "ThreadProxy::~ThreadProxy");
132 DCHECK(IsMainThread());
133 DCHECK(!main().started);
136 void ThreadProxy::FinishAllRendering() {
137 DCHECK(Proxy::IsMainThread());
138 DCHECK(!main().defer_commits);
140 // Make sure all GL drawing is finished on the impl thread.
141 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
142 CompletionEvent completion;
143 Proxy::ImplThreadTaskRunner()->PostTask(
144 FROM_HERE,
145 base::Bind(&ThreadProxy::FinishAllRenderingOnImplThread,
146 impl_thread_weak_ptr_,
147 &completion));
148 completion.Wait();
151 bool ThreadProxy::IsStarted() const {
152 DCHECK(Proxy::IsMainThread());
153 return main().started;
156 bool ThreadProxy::CommitToActiveTree() const {
157 // With ThreadProxy and impl-side painting, we use a pending tree and activate
158 // it once it's ready to draw.
159 return !impl().layer_tree_host_impl->settings().impl_side_painting;
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_));
170 void ThreadProxy::SetLayerTreeHostClientReadyOnImplThread() {
171 TRACE_EVENT0("cc", "ThreadProxy::SetLayerTreeHostClientReadyOnImplThread");
172 impl().scheduler->SetCanStart();
175 void ThreadProxy::SetVisible(bool visible) {
176 TRACE_EVENT1("cc", "ThreadProxy::SetVisible", "visible", visible);
177 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
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();
189 void ThreadProxy::SetVisibleOnImplThread(CompletionEvent* completion,
190 bool visible) {
191 TRACE_EVENT1("cc", "ThreadProxy::SetVisibleOnImplThread", "visible", visible);
192 impl().layer_tree_host_impl->SetVisible(visible);
193 impl().scheduler->SetVisible(visible);
194 completion->Signal();
197 void ThreadProxy::SetThrottleFrameProduction(bool throttle) {
198 TRACE_EVENT1("cc", "ThreadProxy::SetThrottleFrameProduction", "throttle",
199 throttle);
200 Proxy::ImplThreadTaskRunner()->PostTask(
201 FROM_HERE,
202 base::Bind(&ThreadProxy::SetThrottleFrameProductionOnImplThread,
203 impl_thread_weak_ptr_, throttle));
206 void ThreadProxy::SetThrottleFrameProductionOnImplThread(bool throttle) {
207 TRACE_EVENT1("cc", "ThreadProxy::SetThrottleFrameProductionOnImplThread",
208 "throttle", throttle);
209 impl().scheduler->SetThrottleFrameProduction(throttle);
212 void ThreadProxy::DidLoseOutputSurface() {
213 TRACE_EVENT0("cc", "ThreadProxy::DidLoseOutputSurface");
214 DCHECK(IsMainThread());
215 layer_tree_host()->DidLoseOutputSurface();
218 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
220 // Return lost resources to their owners immediately.
221 BlockingTaskRunner::CapturePostTasks blocked(
222 blocking_main_thread_task_runner());
224 CompletionEvent completion;
225 Proxy::ImplThreadTaskRunner()->PostTask(
226 FROM_HERE,
227 base::Bind(&ThreadProxy::DeleteContentsTexturesOnImplThread,
228 impl_thread_weak_ptr_,
229 &completion));
230 completion.Wait();
234 void ThreadProxy::RequestNewOutputSurface() {
235 DCHECK(IsMainThread());
236 layer_tree_host()->RequestNewOutputSurface();
239 void ThreadProxy::SetOutputSurface(scoped_ptr<OutputSurface> output_surface) {
240 Proxy::ImplThreadTaskRunner()->PostTask(
241 FROM_HERE,
242 base::Bind(&ThreadProxy::InitializeOutputSurfaceOnImplThread,
243 impl_thread_weak_ptr_, base::Passed(&output_surface)));
246 void ThreadProxy::DidInitializeOutputSurface(
247 bool success,
248 const RendererCapabilities& capabilities) {
249 TRACE_EVENT0("cc", "ThreadProxy::DidInitializeOutputSurface");
250 DCHECK(IsMainThread());
252 if (!success) {
253 layer_tree_host()->DidFailToInitializeOutputSurface();
254 return;
256 main().renderer_capabilities_main_thread_copy = capabilities;
257 layer_tree_host()->DidInitializeOutputSurface();
260 void ThreadProxy::SetRendererCapabilitiesMainThreadCopy(
261 const RendererCapabilities& capabilities) {
262 main().renderer_capabilities_main_thread_copy = capabilities;
265 void ThreadProxy::SendCommitRequestToImplThreadIfNeeded() {
266 DCHECK(IsMainThread());
267 if (main().commit_request_sent_to_impl_thread)
268 return;
269 main().commit_request_sent_to_impl_thread = true;
270 Proxy::ImplThreadTaskRunner()->PostTask(
271 FROM_HERE,
272 base::Bind(&ThreadProxy::SetNeedsCommitOnImplThread,
273 impl_thread_weak_ptr_));
276 void ThreadProxy::DidCompletePageScaleAnimation() {
277 DCHECK(IsMainThread());
278 layer_tree_host()->DidCompletePageScaleAnimation();
281 const RendererCapabilities& ThreadProxy::GetRendererCapabilities() const {
282 DCHECK(IsMainThread());
283 DCHECK(!layer_tree_host()->output_surface_lost());
284 return main().renderer_capabilities_main_thread_copy;
287 void ThreadProxy::SetNeedsAnimate() {
288 DCHECK(IsMainThread());
289 if (main().animate_requested)
290 return;
292 TRACE_EVENT0("cc", "ThreadProxy::SetNeedsAnimate");
293 main().animate_requested = true;
294 SendCommitRequestToImplThreadIfNeeded();
297 void ThreadProxy::SetNeedsUpdateLayers() {
298 DCHECK(IsMainThread());
300 if (main().commit_request_sent_to_impl_thread)
301 return;
302 TRACE_EVENT0("cc", "ThreadProxy::SetNeedsUpdateLayers");
304 SendCommitRequestToImplThreadIfNeeded();
307 void ThreadProxy::SetNeedsCommit() {
308 DCHECK(IsMainThread());
309 // Unconditionally set here to handle SetNeedsCommit calls during a commit.
310 main().can_cancel_commit = false;
312 if (main().commit_requested)
313 return;
314 TRACE_EVENT0("cc", "ThreadProxy::SetNeedsCommit");
315 main().commit_requested = true;
317 SendCommitRequestToImplThreadIfNeeded();
320 void ThreadProxy::UpdateRendererCapabilitiesOnImplThread() {
321 DCHECK(IsImplThread());
322 Proxy::MainThreadTaskRunner()->PostTask(
323 FROM_HERE,
324 base::Bind(&ThreadProxy::SetRendererCapabilitiesMainThreadCopy,
325 main_thread_weak_ptr_,
326 impl()
327 .layer_tree_host_impl->GetRendererCapabilities()
328 .MainThreadCapabilities()));
331 void ThreadProxy::DidLoseOutputSurfaceOnImplThread() {
332 TRACE_EVENT0("cc", "ThreadProxy::DidLoseOutputSurfaceOnImplThread");
333 DCHECK(IsImplThread());
334 Proxy::MainThreadTaskRunner()->PostTask(
335 FROM_HERE,
336 base::Bind(&ThreadProxy::DidLoseOutputSurface, main_thread_weak_ptr_));
337 impl().scheduler->DidLoseOutputSurface();
340 void ThreadProxy::CommitVSyncParameters(base::TimeTicks timebase,
341 base::TimeDelta interval) {
342 impl().scheduler->CommitVSyncParameters(timebase, interval);
345 void ThreadProxy::SetEstimatedParentDrawTime(base::TimeDelta draw_time) {
346 impl().scheduler->SetEstimatedParentDrawTime(draw_time);
349 void ThreadProxy::SetMaxSwapsPendingOnImplThread(int max) {
350 impl().scheduler->SetMaxSwapsPending(max);
353 void ThreadProxy::DidSwapBuffersOnImplThread() {
354 impl().scheduler->DidSwapBuffers();
357 void ThreadProxy::DidSwapBuffersCompleteOnImplThread() {
358 TRACE_EVENT0("cc,benchmark",
359 "ThreadProxy::DidSwapBuffersCompleteOnImplThread");
360 DCHECK(IsImplThread());
361 impl().scheduler->DidSwapBuffersComplete();
362 Proxy::MainThreadTaskRunner()->PostTask(
363 FROM_HERE,
364 base::Bind(&ThreadProxy::DidCompleteSwapBuffers, main_thread_weak_ptr_));
367 void ThreadProxy::WillBeginImplFrame(const BeginFrameArgs& args) {
368 impl().layer_tree_host_impl->WillBeginImplFrame(args);
369 if (impl().last_processed_begin_main_frame_args.IsValid()) {
370 // Last processed begin main frame args records the frame args that we sent
371 // to the main thread for the last frame that we've processed. If that is
372 // set, that means the current frame is one past the frame in which we've
373 // finished the processing.
374 impl().layer_tree_host_impl->RecordMainFrameTiming(
375 impl().last_processed_begin_main_frame_args,
376 impl().layer_tree_host_impl->CurrentBeginFrameArgs());
377 impl().last_processed_begin_main_frame_args = BeginFrameArgs();
381 void ThreadProxy::OnCanDrawStateChanged(bool can_draw) {
382 TRACE_EVENT1(
383 "cc", "ThreadProxy::OnCanDrawStateChanged", "can_draw", can_draw);
384 DCHECK(IsImplThread());
385 impl().scheduler->SetCanDraw(can_draw);
388 void ThreadProxy::NotifyReadyToActivate() {
389 TRACE_EVENT0("cc", "ThreadProxy::NotifyReadyToActivate");
390 impl().scheduler->NotifyReadyToActivate();
393 void ThreadProxy::NotifyReadyToDraw() {
394 TRACE_EVENT0("cc", "ThreadProxy::NotifyReadyToDraw");
395 impl().scheduler->NotifyReadyToDraw();
398 void ThreadProxy::SetNeedsCommitOnImplThread() {
399 TRACE_EVENT0("cc", "ThreadProxy::SetNeedsCommitOnImplThread");
400 DCHECK(IsImplThread());
401 impl().scheduler->SetNeedsCommit();
404 void ThreadProxy::PostAnimationEventsToMainThreadOnImplThread(
405 scoped_ptr<AnimationEventsVector> events) {
406 TRACE_EVENT0("cc",
407 "ThreadProxy::PostAnimationEventsToMainThreadOnImplThread");
408 DCHECK(IsImplThread());
409 Proxy::MainThreadTaskRunner()->PostTask(
410 FROM_HERE,
411 base::Bind(&ThreadProxy::SetAnimationEvents,
412 main_thread_weak_ptr_,
413 base::Passed(&events)));
416 bool ThreadProxy::ReduceContentsTextureMemoryOnImplThread(size_t limit_bytes,
417 int priority_cutoff) {
418 DCHECK(IsImplThread());
420 if (!impl().contents_texture_manager)
421 return false;
422 if (!impl().layer_tree_host_impl->resource_provider())
423 return false;
425 bool reduce_result =
426 impl().contents_texture_manager->ReduceMemoryOnImplThread(
427 limit_bytes,
428 priority_cutoff,
429 impl().layer_tree_host_impl->resource_provider());
430 if (!reduce_result)
431 return false;
433 // The texture upload queue may reference textures that were just purged,
434 // clear them from the queue.
435 if (impl().current_resource_update_controller) {
436 impl()
437 .current_resource_update_controller->DiscardUploadsToEvictedResources();
439 return true;
442 bool ThreadProxy::IsInsideDraw() { return impl().inside_draw; }
444 void ThreadProxy::SetNeedsRedraw(const gfx::Rect& damage_rect) {
445 TRACE_EVENT0("cc", "ThreadProxy::SetNeedsRedraw");
446 DCHECK(IsMainThread());
447 Proxy::ImplThreadTaskRunner()->PostTask(
448 FROM_HERE,
449 base::Bind(&ThreadProxy::SetNeedsRedrawRectOnImplThread,
450 impl_thread_weak_ptr_,
451 damage_rect));
454 void ThreadProxy::SetNextCommitWaitsForActivation() {
455 DCHECK(IsMainThread());
456 DCHECK(!blocked_main().main_thread_inside_commit);
457 blocked_main().commit_waits_for_activation = true;
460 void ThreadProxy::SetDeferCommits(bool defer_commits) {
461 DCHECK(IsMainThread());
462 if (main().defer_commits == defer_commits)
463 return;
465 main().defer_commits = defer_commits;
466 if (main().defer_commits)
467 TRACE_EVENT_ASYNC_BEGIN0("cc", "ThreadProxy::SetDeferCommits", this);
468 else
469 TRACE_EVENT_ASYNC_END0("cc", "ThreadProxy::SetDeferCommits", this);
471 Proxy::ImplThreadTaskRunner()->PostTask(
472 FROM_HERE,
473 base::Bind(&ThreadProxy::SetDeferCommitsOnImplThread,
474 impl_thread_weak_ptr_,
475 defer_commits));
478 void ThreadProxy::SetDeferCommitsOnImplThread(bool defer_commits) const {
479 DCHECK(IsImplThread());
480 impl().scheduler->SetDeferCommits(defer_commits);
483 bool ThreadProxy::CommitRequested() const {
484 DCHECK(IsMainThread());
485 return main().commit_requested;
488 bool ThreadProxy::BeginMainFrameRequested() const {
489 DCHECK(IsMainThread());
490 return main().commit_request_sent_to_impl_thread;
493 void ThreadProxy::SetNeedsRedrawOnImplThread() {
494 TRACE_EVENT0("cc", "ThreadProxy::SetNeedsRedrawOnImplThread");
495 DCHECK(IsImplThread());
496 impl().scheduler->SetNeedsRedraw();
499 void ThreadProxy::SetNeedsAnimateOnImplThread() {
500 TRACE_EVENT0("cc", "ThreadProxy::SetNeedsAnimateOnImplThread");
501 DCHECK(IsImplThread());
502 impl().scheduler->SetNeedsAnimate();
505 void ThreadProxy::SetNeedsPrepareTilesOnImplThread() {
506 DCHECK(IsImplThread());
507 impl().scheduler->SetNeedsPrepareTiles();
510 void ThreadProxy::SetNeedsRedrawRectOnImplThread(const gfx::Rect& damage_rect) {
511 DCHECK(IsImplThread());
512 impl().layer_tree_host_impl->SetViewportDamage(damage_rect);
513 SetNeedsRedrawOnImplThread();
516 void ThreadProxy::MainThreadHasStoppedFlinging() {
517 DCHECK(IsMainThread());
518 Proxy::ImplThreadTaskRunner()->PostTask(
519 FROM_HERE,
520 base::Bind(&ThreadProxy::MainThreadHasStoppedFlingingOnImplThread,
521 impl_thread_weak_ptr_));
524 void ThreadProxy::MainThreadHasStoppedFlingingOnImplThread() {
525 DCHECK(IsImplThread());
526 impl().layer_tree_host_impl->MainThreadHasStoppedFlinging();
529 void ThreadProxy::NotifyInputThrottledUntilCommit() {
530 DCHECK(IsMainThread());
531 Proxy::ImplThreadTaskRunner()->PostTask(
532 FROM_HERE,
533 base::Bind(&ThreadProxy::SetInputThrottledUntilCommitOnImplThread,
534 impl_thread_weak_ptr_,
535 true));
538 void ThreadProxy::SetInputThrottledUntilCommitOnImplThread(bool is_throttled) {
539 DCHECK(IsImplThread());
540 if (is_throttled == impl().input_throttled_until_commit)
541 return;
542 impl().input_throttled_until_commit = is_throttled;
543 RenewTreePriority();
546 LayerTreeHost* ThreadProxy::layer_tree_host() {
547 return blocked_main().layer_tree_host;
550 const LayerTreeHost* ThreadProxy::layer_tree_host() const {
551 return blocked_main().layer_tree_host;
554 ThreadProxy::MainThreadOnly& ThreadProxy::main() {
555 DCHECK(IsMainThread());
556 return main_thread_only_vars_unsafe_;
558 const ThreadProxy::MainThreadOnly& ThreadProxy::main() const {
559 DCHECK(IsMainThread());
560 return main_thread_only_vars_unsafe_;
563 ThreadProxy::MainThreadOrBlockedMainThread& ThreadProxy::blocked_main() {
564 DCHECK(IsMainThread() || IsMainThreadBlocked());
565 return main_thread_or_blocked_vars_unsafe_;
568 const ThreadProxy::MainThreadOrBlockedMainThread& ThreadProxy::blocked_main()
569 const {
570 DCHECK(IsMainThread() || IsMainThreadBlocked());
571 return main_thread_or_blocked_vars_unsafe_;
574 ThreadProxy::CompositorThreadOnly& ThreadProxy::impl() {
575 DCHECK(IsImplThread());
576 return compositor_thread_vars_unsafe_;
579 const ThreadProxy::CompositorThreadOnly& ThreadProxy::impl() const {
580 DCHECK(IsImplThread());
581 return compositor_thread_vars_unsafe_;
584 void ThreadProxy::Start() {
585 DCHECK(IsMainThread());
586 DCHECK(Proxy::HasImplThread());
588 // Create LayerTreeHostImpl.
589 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
590 CompletionEvent completion;
591 Proxy::ImplThreadTaskRunner()->PostTask(
592 FROM_HERE,
593 base::Bind(&ThreadProxy::InitializeImplOnImplThread,
594 base::Unretained(this),
595 &completion));
596 completion.Wait();
598 main_thread_weak_ptr_ = main().weak_factory.GetWeakPtr();
600 main().started = true;
603 void ThreadProxy::Stop() {
604 TRACE_EVENT0("cc", "ThreadProxy::Stop");
605 DCHECK(IsMainThread());
606 DCHECK(main().started);
608 // Synchronously finishes pending GL operations and deletes the impl.
609 // The two steps are done as separate post tasks, so that tasks posted
610 // by the GL implementation due to the Finish can be executed by the
611 // renderer before shutting it down.
613 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
615 CompletionEvent completion;
616 Proxy::ImplThreadTaskRunner()->PostTask(
617 FROM_HERE,
618 base::Bind(&ThreadProxy::FinishGLOnImplThread,
619 impl_thread_weak_ptr_,
620 &completion));
621 completion.Wait();
624 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
626 CompletionEvent completion;
627 Proxy::ImplThreadTaskRunner()->PostTask(
628 FROM_HERE,
629 base::Bind(&ThreadProxy::LayerTreeHostClosedOnImplThread,
630 impl_thread_weak_ptr_,
631 &completion));
632 completion.Wait();
635 main().weak_factory.InvalidateWeakPtrs();
636 blocked_main().layer_tree_host = NULL;
637 main().started = false;
640 void ThreadProxy::ForceSerializeOnSwapBuffers() {
641 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
642 CompletionEvent completion;
643 Proxy::ImplThreadTaskRunner()->PostTask(
644 FROM_HERE,
645 base::Bind(&ThreadProxy::ForceSerializeOnSwapBuffersOnImplThread,
646 impl_thread_weak_ptr_,
647 &completion));
648 completion.Wait();
651 void ThreadProxy::ForceSerializeOnSwapBuffersOnImplThread(
652 CompletionEvent* completion) {
653 if (impl().layer_tree_host_impl->renderer())
654 impl().layer_tree_host_impl->renderer()->DoNoOp();
655 completion->Signal();
658 bool ThreadProxy::SupportsImplScrolling() const {
659 return true;
662 void ThreadProxy::SetDebugState(const LayerTreeDebugState& debug_state) {
663 Proxy::ImplThreadTaskRunner()->PostTask(
664 FROM_HERE,
665 base::Bind(&ThreadProxy::SetDebugStateOnImplThread,
666 impl_thread_weak_ptr_,
667 debug_state));
670 void ThreadProxy::SetDebugStateOnImplThread(
671 const LayerTreeDebugState& debug_state) {
672 DCHECK(IsImplThread());
673 impl().scheduler->SetContinuousPainting(debug_state.continuous_painting);
676 void ThreadProxy::FinishAllRenderingOnImplThread(CompletionEvent* completion) {
677 TRACE_EVENT0("cc", "ThreadProxy::FinishAllRenderingOnImplThread");
678 DCHECK(IsImplThread());
679 impl().layer_tree_host_impl->FinishAllRendering();
680 completion->Signal();
683 void ThreadProxy::ScheduledActionSendBeginMainFrame() {
684 unsigned int begin_frame_id = nextBeginFrameId++;
685 benchmark_instrumentation::ScopedBeginFrameTask begin_frame_task(
686 benchmark_instrumentation::kSendBeginFrame, begin_frame_id);
687 scoped_ptr<BeginMainFrameAndCommitState> begin_main_frame_state(
688 new BeginMainFrameAndCommitState);
689 begin_main_frame_state->begin_frame_id = begin_frame_id;
690 begin_main_frame_state->begin_frame_args =
691 impl().layer_tree_host_impl->CurrentBeginFrameArgs();
692 begin_main_frame_state->scroll_info =
693 impl().layer_tree_host_impl->ProcessScrollDeltas();
695 if (!impl().layer_tree_host_impl->settings().impl_side_painting) {
696 DCHECK_GT(impl().layer_tree_host_impl->memory_allocation_limit_bytes(), 0u);
698 begin_main_frame_state->memory_allocation_limit_bytes =
699 impl().layer_tree_host_impl->memory_allocation_limit_bytes();
700 begin_main_frame_state->memory_allocation_priority_cutoff =
701 impl().layer_tree_host_impl->memory_allocation_priority_cutoff();
702 begin_main_frame_state->evicted_ui_resources =
703 impl().layer_tree_host_impl->EvictedUIResourcesExist();
704 // TODO(vmpstr): This needs to be fixed if
705 // main_frame_before_activation_enabled is set, since we might run this code
706 // twice before recording a duration. crbug.com/469824
707 impl().last_begin_main_frame_args = begin_main_frame_state->begin_frame_args;
708 Proxy::MainThreadTaskRunner()->PostTask(
709 FROM_HERE,
710 base::Bind(&ThreadProxy::BeginMainFrame,
711 main_thread_weak_ptr_,
712 base::Passed(&begin_main_frame_state)));
713 devtools_instrumentation::DidRequestMainThreadFrame(
714 impl().layer_tree_host_id);
715 impl().timing_history.DidBeginMainFrame();
718 void ThreadProxy::SendBeginMainFrameNotExpectedSoon() {
719 Proxy::MainThreadTaskRunner()->PostTask(
720 FROM_HERE, base::Bind(&ThreadProxy::BeginMainFrameNotExpectedSoon,
721 main_thread_weak_ptr_));
724 void ThreadProxy::BeginMainFrame(
725 scoped_ptr<BeginMainFrameAndCommitState> begin_main_frame_state) {
726 benchmark_instrumentation::ScopedBeginFrameTask begin_frame_task(
727 benchmark_instrumentation::kDoBeginFrame,
728 begin_main_frame_state->begin_frame_id);
729 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("cc.BeginMainFrame");
730 DCHECK(IsMainThread());
732 if (main().defer_commits) {
733 TRACE_EVENT_INSTANT0("cc", "EarlyOut_DeferCommit",
734 TRACE_EVENT_SCOPE_THREAD);
735 Proxy::ImplThreadTaskRunner()->PostTask(
736 FROM_HERE, base::Bind(&ThreadProxy::BeginMainFrameAbortedOnImplThread,
737 impl_thread_weak_ptr_,
738 CommitEarlyOutReason::ABORTED_DEFERRED_COMMIT));
739 return;
742 // If the commit finishes, LayerTreeHost will transfer its swap promises to
743 // LayerTreeImpl. The destructor of ScopedSwapPromiseChecker aborts the
744 // remaining swap promises.
745 ScopedAbortRemainingSwapPromises swap_promise_checker(layer_tree_host());
747 main().commit_requested = false;
748 main().commit_request_sent_to_impl_thread = false;
749 main().animate_requested = false;
751 if (!layer_tree_host()->visible()) {
752 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NotVisible", TRACE_EVENT_SCOPE_THREAD);
753 Proxy::ImplThreadTaskRunner()->PostTask(
754 FROM_HERE, base::Bind(&ThreadProxy::BeginMainFrameAbortedOnImplThread,
755 impl_thread_weak_ptr_,
756 CommitEarlyOutReason::ABORTED_NOT_VISIBLE));
757 return;
760 if (layer_tree_host()->output_surface_lost()) {
761 TRACE_EVENT_INSTANT0(
762 "cc", "EarlyOut_OutputSurfaceLost", TRACE_EVENT_SCOPE_THREAD);
763 Proxy::ImplThreadTaskRunner()->PostTask(
764 FROM_HERE,
765 base::Bind(&ThreadProxy::BeginMainFrameAbortedOnImplThread,
766 impl_thread_weak_ptr_,
767 CommitEarlyOutReason::ABORTED_OUTPUT_SURFACE_LOST));
768 return;
771 // Do not notify the impl thread of commit requests that occur during
772 // the apply/animate/layout part of the BeginMainFrameAndCommit process since
773 // those commit requests will get painted immediately. Once we have done
774 // the paint, main().commit_requested will be set to false to allow new commit
775 // requests to be scheduled.
776 // On the other hand, the animate_requested flag should remain cleared
777 // here so that any animation requests generated by the apply or animate
778 // callbacks will trigger another frame.
779 main().commit_requested = true;
780 main().commit_request_sent_to_impl_thread = true;
782 layer_tree_host()->ApplyScrollAndScale(
783 begin_main_frame_state->scroll_info.get());
785 layer_tree_host()->WillBeginMainFrame();
787 layer_tree_host()->BeginMainFrame(begin_main_frame_state->begin_frame_args);
788 layer_tree_host()->AnimateLayers(
789 begin_main_frame_state->begin_frame_args.frame_time);
791 // Unlink any backings that the impl thread has evicted, so that we know to
792 // re-paint them in UpdateLayers.
793 if (blocked_main().contents_texture_manager()) {
794 blocked_main().contents_texture_manager()->UnlinkAndClearEvictedBackings();
796 blocked_main().contents_texture_manager()->SetMaxMemoryLimitBytes(
797 begin_main_frame_state->memory_allocation_limit_bytes);
798 blocked_main().contents_texture_manager()->SetExternalPriorityCutoff(
799 begin_main_frame_state->memory_allocation_priority_cutoff);
802 // Recreate all UI resources if there were evicted UI resources when the impl
803 // thread initiated the commit.
804 if (begin_main_frame_state->evicted_ui_resources)
805 layer_tree_host()->RecreateUIResources();
807 layer_tree_host()->Layout();
808 TRACE_EVENT_SYNTHETIC_DELAY_END("cc.BeginMainFrame");
810 // Clear the commit flag after updating animations and layout here --- objects
811 // that only layout when painted will trigger another SetNeedsCommit inside
812 // UpdateLayers.
813 main().commit_requested = false;
814 main().commit_request_sent_to_impl_thread = false;
815 bool can_cancel_this_commit =
816 main().can_cancel_commit && !begin_main_frame_state->evicted_ui_resources;
817 main().can_cancel_commit = true;
819 scoped_ptr<ResourceUpdateQueue> queue =
820 make_scoped_ptr(new ResourceUpdateQueue);
822 bool updated = layer_tree_host()->UpdateLayers(queue.get());
824 layer_tree_host()->WillCommit();
825 devtools_instrumentation::ScopedCommitTrace commit_task(
826 layer_tree_host()->id());
828 // Before calling animate, we set main().animate_requested to false. If it is
829 // true now, it means SetNeedAnimate was called again, but during a state when
830 // main().commit_request_sent_to_impl_thread = true. We need to force that
831 // call to happen again now so that the commit request is sent to the impl
832 // thread.
833 if (main().animate_requested) {
834 // Forces SetNeedsAnimate to consider posting a commit task.
835 main().animate_requested = false;
836 SetNeedsAnimate();
839 if (!updated && can_cancel_this_commit) {
840 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoUpdates", TRACE_EVENT_SCOPE_THREAD);
841 Proxy::ImplThreadTaskRunner()->PostTask(
842 FROM_HERE, base::Bind(&ThreadProxy::BeginMainFrameAbortedOnImplThread,
843 impl_thread_weak_ptr_,
844 CommitEarlyOutReason::FINISHED_NO_UPDATES));
846 // Although the commit is internally aborted, this is because it has been
847 // detected to be a no-op. From the perspective of an embedder, this commit
848 // went through, and input should no longer be throttled, etc.
849 layer_tree_host()->CommitComplete();
850 layer_tree_host()->DidBeginMainFrame();
851 layer_tree_host()->BreakSwapPromises(SwapPromise::COMMIT_NO_UPDATE);
852 return;
855 // Notify the impl thread that the main thread is ready to commit. This will
856 // begin the commit process, which is blocking from the main thread's
857 // point of view, but asynchronously performed on the impl thread,
858 // coordinated by the Scheduler.
860 TRACE_EVENT0("cc", "ThreadProxy::BeginMainFrame::commit");
862 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
864 // This CapturePostTasks should be destroyed before CommitComplete() is
865 // called since that goes out to the embedder, and we want the embedder
866 // to receive its callbacks before that.
867 BlockingTaskRunner::CapturePostTasks blocked(
868 blocking_main_thread_task_runner());
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();
880 layer_tree_host()->CommitComplete();
881 layer_tree_host()->DidBeginMainFrame();
884 void ThreadProxy::BeginMainFrameNotExpectedSoon() {
885 TRACE_EVENT0("cc", "ThreadProxy::BeginMainFrameNotExpectedSoon");
886 DCHECK(IsMainThread());
887 layer_tree_host()->BeginMainFrameNotExpectedSoon();
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());
898 if (!impl().layer_tree_host_impl) {
899 TRACE_EVENT_INSTANT0(
900 "cc", "EarlyOut_NoLayerTree", TRACE_EVENT_SCOPE_THREAD);
901 completion->Signal();
902 return;
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();
909 scoped_ptr<ResourceUpdateQueue> queue(raw_queue);
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();
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();
930 impl().contents_texture_manager->PushTexturePrioritiesToBackings();
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());
943 void ThreadProxy::BeginMainFrameAbortedOnImplThread(
944 CommitEarlyOutReason reason) {
945 TRACE_EVENT1("cc", "ThreadProxy::BeginMainFrameAbortedOnImplThread", "reason",
946 CommitEarlyOutReasonToString(reason));
947 DCHECK(IsImplThread());
948 DCHECK(impl().scheduler);
949 DCHECK(impl().scheduler->CommitPending());
950 DCHECK(!impl().layer_tree_host_impl->pending_tree());
952 if (CommitEarlyOutHandledCommit(reason)) {
953 SetInputThrottledUntilCommitOnImplThread(false);
954 impl().last_processed_begin_main_frame_args =
955 impl().last_begin_main_frame_args;
957 impl().layer_tree_host_impl->BeginMainFrameAborted(reason);
958 impl().scheduler->BeginMainFrameAborted(reason);
961 void ThreadProxy::ScheduledActionAnimate() {
962 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionAnimate");
963 DCHECK(IsImplThread());
965 // Don't animate if there is no root layer.
966 // TODO(mithro): Both Animate and UpdateAnimationState already have a
967 // "!active_tree_->root_layer()" check?
968 if (!impl().layer_tree_host_impl->active_tree()->root_layer()) {
969 return;
972 impl().animation_time =
973 impl().layer_tree_host_impl->CurrentBeginFrameArgs().frame_time;
974 impl().layer_tree_host_impl->Animate(impl().animation_time);
976 // If animations are not visible, update the state now as
977 // ScheduledActionDrawAndSwapIfPossible will never be called.
978 if (!impl().layer_tree_host_impl->AnimationsAreVisible()) {
979 impl().layer_tree_host_impl->UpdateAnimationState(true);
983 void ThreadProxy::ScheduledActionCommit() {
984 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionCommit");
985 DCHECK(IsImplThread());
986 DCHECK(IsMainThreadBlocked());
987 DCHECK(impl().commit_completion_event);
988 DCHECK(impl().current_resource_update_controller);
990 // Complete all remaining texture updates.
991 impl().current_resource_update_controller->Finalize();
992 impl().current_resource_update_controller = nullptr;
994 blocked_main().main_thread_inside_commit = true;
995 impl().layer_tree_host_impl->BeginCommit();
996 layer_tree_host()->BeginCommitOnImplThread(impl().layer_tree_host_impl.get());
997 layer_tree_host()->FinishCommitOnImplThread(
998 impl().layer_tree_host_impl.get());
999 blocked_main().main_thread_inside_commit = false;
1001 bool hold_commit = layer_tree_host()->settings().impl_side_painting &&
1002 blocked_main().commit_waits_for_activation;
1003 blocked_main().commit_waits_for_activation = false;
1005 if (hold_commit) {
1006 // For some layer types in impl-side painting, the commit is held until
1007 // the sync tree is activated. It's also possible that the
1008 // sync tree has already activated if there was no work to be done.
1009 TRACE_EVENT_INSTANT0("cc", "HoldCommit", TRACE_EVENT_SCOPE_THREAD);
1010 impl().completion_event_for_commit_held_on_tree_activation =
1011 impl().commit_completion_event;
1012 impl().commit_completion_event = NULL;
1013 } else {
1014 impl().commit_completion_event->Signal();
1015 impl().commit_completion_event = NULL;
1018 // Delay this step until afer the main thread has been released as it's
1019 // often a good bit of work to update the tree and prepare the new frame.
1020 impl().layer_tree_host_impl->CommitComplete();
1022 SetInputThrottledUntilCommitOnImplThread(false);
1024 impl().next_frame_is_newly_committed_frame = true;
1026 impl().timing_history.DidCommit();
1029 void ThreadProxy::ScheduledActionActivateSyncTree() {
1030 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionActivateSyncTree");
1031 DCHECK(IsImplThread());
1032 impl().layer_tree_host_impl->ActivateSyncTree();
1035 void ThreadProxy::ScheduledActionBeginOutputSurfaceCreation() {
1036 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionBeginOutputSurfaceCreation");
1037 DCHECK(IsImplThread());
1038 Proxy::MainThreadTaskRunner()->PostTask(
1039 FROM_HERE,
1040 base::Bind(&ThreadProxy::RequestNewOutputSurface, main_thread_weak_ptr_));
1043 DrawResult ThreadProxy::DrawSwapInternal(bool forced_draw) {
1044 TRACE_EVENT_SYNTHETIC_DELAY("cc.DrawAndSwap");
1045 DrawResult result;
1047 DCHECK(IsImplThread());
1048 DCHECK(impl().layer_tree_host_impl.get());
1050 impl().timing_history.DidStartDrawing();
1051 base::AutoReset<bool> mark_inside(&impl().inside_draw, true);
1053 if (impl().layer_tree_host_impl->pending_tree()) {
1054 bool update_lcd_text = false;
1055 impl().layer_tree_host_impl->pending_tree()->UpdateDrawProperties(
1056 update_lcd_text);
1059 // This method is called on a forced draw, regardless of whether we are able
1060 // to produce a frame, as the calling site on main thread is blocked until its
1061 // request completes, and we signal completion here. If CanDraw() is false, we
1062 // will indicate success=false to the caller, but we must still signal
1063 // completion to avoid deadlock.
1065 // We guard PrepareToDraw() with CanDraw() because it always returns a valid
1066 // frame, so can only be used when such a frame is possible. Since
1067 // DrawLayers() depends on the result of PrepareToDraw(), it is guarded on
1068 // CanDraw() as well.
1070 LayerTreeHostImpl::FrameData frame;
1071 bool draw_frame = false;
1073 if (impl().layer_tree_host_impl->CanDraw()) {
1074 result = impl().layer_tree_host_impl->PrepareToDraw(&frame);
1075 draw_frame = forced_draw || result == DRAW_SUCCESS;
1076 } else {
1077 result = DRAW_ABORTED_CANT_DRAW;
1080 if (draw_frame) {
1081 impl().layer_tree_host_impl->DrawLayers(
1082 &frame, impl().scheduler->LastBeginImplFrameTime());
1083 result = DRAW_SUCCESS;
1084 } else {
1085 DCHECK_NE(DRAW_SUCCESS, result);
1087 impl().layer_tree_host_impl->DidDrawAllLayers(frame);
1089 bool start_ready_animations = draw_frame;
1090 impl().layer_tree_host_impl->UpdateAnimationState(start_ready_animations);
1092 if (draw_frame)
1093 impl().layer_tree_host_impl->SwapBuffers(frame);
1095 // Tell the main thread that the the newly-commited frame was drawn.
1096 if (impl().next_frame_is_newly_committed_frame) {
1097 impl().next_frame_is_newly_committed_frame = false;
1098 Proxy::MainThreadTaskRunner()->PostTask(
1099 FROM_HERE,
1100 base::Bind(&ThreadProxy::DidCommitAndDrawFrame, main_thread_weak_ptr_));
1103 if (result == DRAW_SUCCESS)
1104 impl().timing_history.DidFinishDrawing();
1106 DCHECK_NE(INVALID_RESULT, result);
1107 return result;
1110 void ThreadProxy::ScheduledActionPrepareTiles() {
1111 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionPrepareTiles");
1112 DCHECK(impl().layer_tree_host_impl->settings().impl_side_painting);
1113 impl().layer_tree_host_impl->PrepareTiles();
1116 DrawResult ThreadProxy::ScheduledActionDrawAndSwapIfPossible() {
1117 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionDrawAndSwap");
1119 // SchedulerStateMachine::DidDrawIfPossibleCompleted isn't set up to
1120 // handle DRAW_ABORTED_CANT_DRAW. Moreover, the scheduler should
1121 // never generate this call when it can't draw.
1122 DCHECK(impl().layer_tree_host_impl->CanDraw());
1124 bool forced_draw = false;
1125 return DrawSwapInternal(forced_draw);
1128 DrawResult ThreadProxy::ScheduledActionDrawAndSwapForced() {
1129 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionDrawAndSwapForced");
1130 bool forced_draw = true;
1131 return DrawSwapInternal(forced_draw);
1134 void ThreadProxy::ScheduledActionInvalidateOutputSurface() {
1135 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionInvalidateOutputSurface");
1136 DCHECK(impl().layer_tree_host_impl->output_surface());
1137 impl().layer_tree_host_impl->output_surface()->Invalidate();
1140 void ThreadProxy::DidAnticipatedDrawTimeChange(base::TimeTicks time) {
1141 if (impl().current_resource_update_controller)
1142 impl().current_resource_update_controller->PerformMoreUpdates(time);
1145 base::TimeDelta ThreadProxy::DrawDurationEstimate() {
1146 return impl().timing_history.DrawDurationEstimate();
1149 base::TimeDelta ThreadProxy::BeginMainFrameToCommitDurationEstimate() {
1150 return impl().timing_history.BeginMainFrameToCommitDurationEstimate();
1153 base::TimeDelta ThreadProxy::CommitToActivateDurationEstimate() {
1154 return impl().timing_history.CommitToActivateDurationEstimate();
1157 void ThreadProxy::DidBeginImplFrameDeadline() {
1158 impl().layer_tree_host_impl->ResetCurrentBeginFrameArgsForNextFrame();
1161 void ThreadProxy::SendBeginFramesToChildren(const BeginFrameArgs& args) {
1162 NOTREACHED() << "Only used by SingleThreadProxy";
1165 void ThreadProxy::SetAuthoritativeVSyncInterval(
1166 const base::TimeDelta& interval) {
1167 NOTREACHED() << "Only used by SingleThreadProxy";
1170 void ThreadProxy::ReadyToFinalizeTextureUpdates() {
1171 DCHECK(IsImplThread());
1172 impl().scheduler->NotifyReadyToCommit();
1175 void ThreadProxy::DidCommitAndDrawFrame() {
1176 DCHECK(IsMainThread());
1177 layer_tree_host()->DidCommitAndDrawFrame();
1180 void ThreadProxy::DidCompleteSwapBuffers() {
1181 DCHECK(IsMainThread());
1182 layer_tree_host()->DidCompleteSwapBuffers();
1185 void ThreadProxy::SetAnimationEvents(scoped_ptr<AnimationEventsVector> events) {
1186 TRACE_EVENT0("cc", "ThreadProxy::SetAnimationEvents");
1187 DCHECK(IsMainThread());
1188 layer_tree_host()->SetAnimationEvents(events.Pass());
1191 void ThreadProxy::InitializeImplOnImplThread(CompletionEvent* completion) {
1192 TRACE_EVENT0("cc", "ThreadProxy::InitializeImplOnImplThread");
1193 DCHECK(IsImplThread());
1194 impl().layer_tree_host_impl =
1195 layer_tree_host()->CreateLayerTreeHostImpl(this);
1196 SchedulerSettings scheduler_settings(
1197 layer_tree_host()->settings().ToSchedulerSettings());
1198 impl().scheduler = Scheduler::Create(
1199 this,
1200 scheduler_settings,
1201 impl().layer_tree_host_id,
1202 ImplThreadTaskRunner(),
1203 impl().external_begin_frame_source.Pass());
1204 impl().scheduler->SetVisible(impl().layer_tree_host_impl->visible());
1205 impl_thread_weak_ptr_ = impl().weak_factory.GetWeakPtr();
1206 completion->Signal();
1209 void ThreadProxy::DeleteContentsTexturesOnImplThread(
1210 CompletionEvent* completion) {
1211 TRACE_EVENT0("cc", "ThreadProxy::DeleteContentsTexturesOnImplThread");
1212 DCHECK(IsImplThread());
1213 DCHECK(IsMainThreadBlocked());
1214 layer_tree_host()->DeleteContentsTexturesOnImplThread(
1215 impl().layer_tree_host_impl->resource_provider());
1216 completion->Signal();
1219 void ThreadProxy::InitializeOutputSurfaceOnImplThread(
1220 scoped_ptr<OutputSurface> output_surface) {
1221 TRACE_EVENT0("cc", "ThreadProxy::InitializeOutputSurfaceOnImplThread");
1222 DCHECK(IsImplThread());
1224 LayerTreeHostImpl* host_impl = impl().layer_tree_host_impl.get();
1225 bool success = host_impl->InitializeRenderer(output_surface.Pass());
1226 RendererCapabilities capabilities;
1227 if (success) {
1228 capabilities =
1229 host_impl->GetRendererCapabilities().MainThreadCapabilities();
1232 Proxy::MainThreadTaskRunner()->PostTask(
1233 FROM_HERE,
1234 base::Bind(&ThreadProxy::DidInitializeOutputSurface,
1235 main_thread_weak_ptr_,
1236 success,
1237 capabilities));
1239 if (success)
1240 impl().scheduler->DidCreateAndInitializeOutputSurface();
1243 void ThreadProxy::FinishGLOnImplThread(CompletionEvent* completion) {
1244 TRACE_EVENT0("cc", "ThreadProxy::FinishGLOnImplThread");
1245 DCHECK(IsImplThread());
1246 if (impl().layer_tree_host_impl->output_surface()) {
1247 ContextProvider* context_provider =
1248 impl().layer_tree_host_impl->output_surface()->context_provider();
1249 if (context_provider)
1250 context_provider->ContextGL()->Finish();
1252 completion->Signal();
1255 void ThreadProxy::LayerTreeHostClosedOnImplThread(CompletionEvent* completion) {
1256 TRACE_EVENT0("cc", "ThreadProxy::LayerTreeHostClosedOnImplThread");
1257 DCHECK(IsImplThread());
1258 DCHECK(IsMainThreadBlocked());
1259 layer_tree_host()->DeleteContentsTexturesOnImplThread(
1260 impl().layer_tree_host_impl->resource_provider());
1261 impl().current_resource_update_controller = nullptr;
1262 impl().scheduler = nullptr;
1263 impl().layer_tree_host_impl = nullptr;
1264 impl().weak_factory.InvalidateWeakPtrs();
1265 // We need to explicitly shutdown the notifier to destroy any weakptrs it is
1266 // holding while still on the compositor thread. This also ensures any
1267 // callbacks holding a ThreadProxy pointer are cancelled.
1268 impl().smoothness_priority_expiration_notifier.Shutdown();
1269 impl().contents_texture_manager = NULL;
1270 completion->Signal();
1273 size_t ThreadProxy::MaxPartialTextureUpdates() const {
1274 return ResourceUpdateController::MaxPartialTextureUpdates();
1277 ThreadProxy::BeginMainFrameAndCommitState::BeginMainFrameAndCommitState()
1278 : memory_allocation_limit_bytes(0),
1279 memory_allocation_priority_cutoff(0),
1280 evicted_ui_resources(false) {}
1282 ThreadProxy::BeginMainFrameAndCommitState::~BeginMainFrameAndCommitState() {}
1284 bool ThreadProxy::MainFrameWillHappenForTesting() {
1285 DCHECK(IsMainThread());
1286 CompletionEvent completion;
1287 bool main_frame_will_happen = false;
1289 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
1290 Proxy::ImplThreadTaskRunner()->PostTask(
1291 FROM_HERE,
1292 base::Bind(&ThreadProxy::MainFrameWillHappenOnImplThreadForTesting,
1293 impl_thread_weak_ptr_,
1294 &completion,
1295 &main_frame_will_happen));
1296 completion.Wait();
1298 return main_frame_will_happen;
1301 void ThreadProxy::SetChildrenNeedBeginFrames(bool children_need_begin_frames) {
1302 NOTREACHED() << "Only used by SingleThreadProxy";
1305 void ThreadProxy::MainFrameWillHappenOnImplThreadForTesting(
1306 CompletionEvent* completion,
1307 bool* main_frame_will_happen) {
1308 DCHECK(IsImplThread());
1309 if (impl().layer_tree_host_impl->output_surface()) {
1310 *main_frame_will_happen = impl().scheduler->MainFrameForTestingWillHappen();
1311 } else {
1312 *main_frame_will_happen = false;
1314 completion->Signal();
1317 void ThreadProxy::RenewTreePriority() {
1318 DCHECK(IsImplThread());
1319 bool smoothness_takes_priority =
1320 impl().layer_tree_host_impl->pinch_gesture_active() ||
1321 impl().layer_tree_host_impl->page_scale_animation_active() ||
1322 impl().layer_tree_host_impl->IsActivelyScrolling();
1324 // Schedule expiration if smoothness currently takes priority.
1325 if (smoothness_takes_priority)
1326 impl().smoothness_priority_expiration_notifier.Schedule();
1328 // We use the same priority for both trees by default.
1329 TreePriority priority = SAME_PRIORITY_FOR_BOTH_TREES;
1331 // Smoothness takes priority if we have an expiration for it scheduled.
1332 if (impl().smoothness_priority_expiration_notifier.HasPendingNotification())
1333 priority = SMOOTHNESS_TAKES_PRIORITY;
1335 // New content always takes priority when the active tree has
1336 // evicted resources or there is an invalid viewport size.
1337 if (impl().layer_tree_host_impl->active_tree()->ContentsTexturesPurged() ||
1338 impl().layer_tree_host_impl->active_tree()->ViewportSizeInvalid() ||
1339 impl().layer_tree_host_impl->EvictedUIResourcesExist() ||
1340 impl().input_throttled_until_commit) {
1341 // Once we enter NEW_CONTENTS_TAKES_PRIORITY mode, visible tiles on active
1342 // tree might be freed. We need to set RequiresHighResToDraw to ensure that
1343 // high res tiles will be required to activate pending tree.
1344 impl().layer_tree_host_impl->SetRequiresHighResToDraw();
1345 priority = NEW_CONTENT_TAKES_PRIORITY;
1348 impl().layer_tree_host_impl->SetTreePriority(priority);
1350 // Only put the scheduler in impl latency prioritization mode if we don't
1351 // have a scroll listener. This gives the scroll listener a better chance of
1352 // handling scroll updates within the same frame. The tree itself is still
1353 // kept in prefer smoothness mode to allow checkerboarding.
1354 impl().scheduler->SetImplLatencyTakesPriority(
1355 priority == SMOOTHNESS_TAKES_PRIORITY &&
1356 !impl().layer_tree_host_impl->scroll_affects_scroll_handler());
1358 // Notify the the client of this compositor via the output surface.
1359 // TODO(epenner): Route this to compositor-thread instead of output-surface
1360 // after GTFO refactor of compositor-thread (http://crbug/170828).
1361 if (impl().layer_tree_host_impl->output_surface()) {
1362 impl()
1363 .layer_tree_host_impl->output_surface()
1364 ->UpdateSmoothnessTakesPriority(priority == SMOOTHNESS_TAKES_PRIORITY);
1368 void ThreadProxy::PostDelayedAnimationTaskOnImplThread(
1369 const base::Closure& task,
1370 base::TimeDelta delay) {
1371 Proxy::ImplThreadTaskRunner()->PostDelayedTask(FROM_HERE, task, delay);
1374 void ThreadProxy::DidActivateSyncTree() {
1375 TRACE_EVENT0("cc", "ThreadProxy::DidActivateSyncTreeOnImplThread");
1376 DCHECK(IsImplThread());
1378 if (impl().completion_event_for_commit_held_on_tree_activation) {
1379 TRACE_EVENT_INSTANT0(
1380 "cc", "ReleaseCommitbyActivation", TRACE_EVENT_SCOPE_THREAD);
1381 DCHECK(impl().layer_tree_host_impl->settings().impl_side_painting);
1382 impl().completion_event_for_commit_held_on_tree_activation->Signal();
1383 impl().completion_event_for_commit_held_on_tree_activation = NULL;
1386 impl().timing_history.DidActivateSyncTree();
1387 impl().last_processed_begin_main_frame_args =
1388 impl().last_begin_main_frame_args;
1391 void ThreadProxy::DidPrepareTiles() {
1392 DCHECK(IsImplThread());
1393 impl().scheduler->DidPrepareTiles();
1396 void ThreadProxy::DidCompletePageScaleAnimationOnImplThread() {
1397 DCHECK(IsImplThread());
1398 Proxy::MainThreadTaskRunner()->PostTask(
1399 FROM_HERE, base::Bind(&ThreadProxy::DidCompletePageScaleAnimation,
1400 main_thread_weak_ptr_));
1403 void ThreadProxy::OnDrawForOutputSurface() {
1404 DCHECK(IsImplThread());
1405 impl().scheduler->OnDrawForOutputSurface();
1408 } // namespace cc