Disable flaky UnloadTest.CrossSiteInfiniteBeforeUnloadSync on Mac.
[chromium-blink-merge.git] / cc / trees / thread_proxy.cc
blob3010fba95c32165329df0ad5ea7a3d56d8c2a879
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::SetVideoNeedsBeginFrames(bool needs_begin_frames) {
405 TRACE_EVENT1("cc", "ThreadProxy::SetVideoNeedsBeginFrames",
406 "needs_begin_frames", needs_begin_frames);
407 DCHECK(IsImplThread());
408 // In tests the layer tree is destroyed after the scheduler is.
409 if (impl().scheduler)
410 impl().scheduler->SetVideoNeedsBeginFrames(needs_begin_frames);
413 void ThreadProxy::PostAnimationEventsToMainThreadOnImplThread(
414 scoped_ptr<AnimationEventsVector> events) {
415 TRACE_EVENT0("cc",
416 "ThreadProxy::PostAnimationEventsToMainThreadOnImplThread");
417 DCHECK(IsImplThread());
418 Proxy::MainThreadTaskRunner()->PostTask(
419 FROM_HERE,
420 base::Bind(&ThreadProxy::SetAnimationEvents,
421 main_thread_weak_ptr_,
422 base::Passed(&events)));
425 bool ThreadProxy::ReduceContentsTextureMemoryOnImplThread(size_t limit_bytes,
426 int priority_cutoff) {
427 DCHECK(IsImplThread());
429 if (!impl().contents_texture_manager)
430 return false;
431 if (!impl().layer_tree_host_impl->resource_provider())
432 return false;
434 bool reduce_result =
435 impl().contents_texture_manager->ReduceMemoryOnImplThread(
436 limit_bytes,
437 priority_cutoff,
438 impl().layer_tree_host_impl->resource_provider());
439 if (!reduce_result)
440 return false;
442 // The texture upload queue may reference textures that were just purged,
443 // clear them from the queue.
444 if (impl().current_resource_update_controller) {
445 impl()
446 .current_resource_update_controller->DiscardUploadsToEvictedResources();
448 return true;
451 bool ThreadProxy::IsInsideDraw() { return impl().inside_draw; }
453 void ThreadProxy::SetNeedsRedraw(const gfx::Rect& damage_rect) {
454 TRACE_EVENT0("cc", "ThreadProxy::SetNeedsRedraw");
455 DCHECK(IsMainThread());
456 Proxy::ImplThreadTaskRunner()->PostTask(
457 FROM_HERE,
458 base::Bind(&ThreadProxy::SetNeedsRedrawRectOnImplThread,
459 impl_thread_weak_ptr_,
460 damage_rect));
463 void ThreadProxy::SetNextCommitWaitsForActivation() {
464 DCHECK(IsMainThread());
465 DCHECK(!blocked_main().main_thread_inside_commit);
466 blocked_main().commit_waits_for_activation = true;
469 void ThreadProxy::SetDeferCommits(bool defer_commits) {
470 DCHECK(IsMainThread());
471 if (main().defer_commits == defer_commits)
472 return;
474 main().defer_commits = defer_commits;
475 if (main().defer_commits)
476 TRACE_EVENT_ASYNC_BEGIN0("cc", "ThreadProxy::SetDeferCommits", this);
477 else
478 TRACE_EVENT_ASYNC_END0("cc", "ThreadProxy::SetDeferCommits", this);
480 Proxy::ImplThreadTaskRunner()->PostTask(
481 FROM_HERE,
482 base::Bind(&ThreadProxy::SetDeferCommitsOnImplThread,
483 impl_thread_weak_ptr_,
484 defer_commits));
487 void ThreadProxy::SetDeferCommitsOnImplThread(bool defer_commits) const {
488 DCHECK(IsImplThread());
489 impl().scheduler->SetDeferCommits(defer_commits);
492 bool ThreadProxy::CommitRequested() const {
493 DCHECK(IsMainThread());
494 return main().commit_requested;
497 bool ThreadProxy::BeginMainFrameRequested() const {
498 DCHECK(IsMainThread());
499 return main().commit_request_sent_to_impl_thread;
502 void ThreadProxy::SetNeedsRedrawOnImplThread() {
503 TRACE_EVENT0("cc", "ThreadProxy::SetNeedsRedrawOnImplThread");
504 DCHECK(IsImplThread());
505 impl().scheduler->SetNeedsRedraw();
508 void ThreadProxy::SetNeedsAnimateOnImplThread() {
509 TRACE_EVENT0("cc", "ThreadProxy::SetNeedsAnimateOnImplThread");
510 DCHECK(IsImplThread());
511 impl().scheduler->SetNeedsAnimate();
514 void ThreadProxy::SetNeedsPrepareTilesOnImplThread() {
515 DCHECK(IsImplThread());
516 impl().scheduler->SetNeedsPrepareTiles();
519 void ThreadProxy::SetNeedsRedrawRectOnImplThread(const gfx::Rect& damage_rect) {
520 DCHECK(IsImplThread());
521 impl().layer_tree_host_impl->SetViewportDamage(damage_rect);
522 SetNeedsRedrawOnImplThread();
525 void ThreadProxy::MainThreadHasStoppedFlinging() {
526 DCHECK(IsMainThread());
527 Proxy::ImplThreadTaskRunner()->PostTask(
528 FROM_HERE,
529 base::Bind(&ThreadProxy::MainThreadHasStoppedFlingingOnImplThread,
530 impl_thread_weak_ptr_));
533 void ThreadProxy::MainThreadHasStoppedFlingingOnImplThread() {
534 DCHECK(IsImplThread());
535 impl().layer_tree_host_impl->MainThreadHasStoppedFlinging();
538 void ThreadProxy::NotifyInputThrottledUntilCommit() {
539 DCHECK(IsMainThread());
540 Proxy::ImplThreadTaskRunner()->PostTask(
541 FROM_HERE,
542 base::Bind(&ThreadProxy::SetInputThrottledUntilCommitOnImplThread,
543 impl_thread_weak_ptr_,
544 true));
547 void ThreadProxy::SetInputThrottledUntilCommitOnImplThread(bool is_throttled) {
548 DCHECK(IsImplThread());
549 if (is_throttled == impl().input_throttled_until_commit)
550 return;
551 impl().input_throttled_until_commit = is_throttled;
552 RenewTreePriority();
555 LayerTreeHost* ThreadProxy::layer_tree_host() {
556 return blocked_main().layer_tree_host;
559 const LayerTreeHost* ThreadProxy::layer_tree_host() const {
560 return blocked_main().layer_tree_host;
563 ThreadProxy::MainThreadOnly& ThreadProxy::main() {
564 DCHECK(IsMainThread());
565 return main_thread_only_vars_unsafe_;
567 const ThreadProxy::MainThreadOnly& ThreadProxy::main() const {
568 DCHECK(IsMainThread());
569 return main_thread_only_vars_unsafe_;
572 ThreadProxy::MainThreadOrBlockedMainThread& ThreadProxy::blocked_main() {
573 DCHECK(IsMainThread() || IsMainThreadBlocked());
574 return main_thread_or_blocked_vars_unsafe_;
577 const ThreadProxy::MainThreadOrBlockedMainThread& ThreadProxy::blocked_main()
578 const {
579 DCHECK(IsMainThread() || IsMainThreadBlocked());
580 return main_thread_or_blocked_vars_unsafe_;
583 ThreadProxy::CompositorThreadOnly& ThreadProxy::impl() {
584 DCHECK(IsImplThread());
585 return compositor_thread_vars_unsafe_;
588 const ThreadProxy::CompositorThreadOnly& ThreadProxy::impl() const {
589 DCHECK(IsImplThread());
590 return compositor_thread_vars_unsafe_;
593 void ThreadProxy::Start() {
594 DCHECK(IsMainThread());
595 DCHECK(Proxy::HasImplThread());
597 // Create LayerTreeHostImpl.
598 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
599 CompletionEvent completion;
600 Proxy::ImplThreadTaskRunner()->PostTask(
601 FROM_HERE,
602 base::Bind(&ThreadProxy::InitializeImplOnImplThread,
603 base::Unretained(this),
604 &completion));
605 completion.Wait();
607 main_thread_weak_ptr_ = main().weak_factory.GetWeakPtr();
609 main().started = true;
612 void ThreadProxy::Stop() {
613 TRACE_EVENT0("cc", "ThreadProxy::Stop");
614 DCHECK(IsMainThread());
615 DCHECK(main().started);
617 // Synchronously finishes pending GL operations and deletes the impl.
618 // The two steps are done as separate post tasks, so that tasks posted
619 // by the GL implementation due to the Finish can be executed by the
620 // renderer before shutting it down.
622 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
624 CompletionEvent completion;
625 Proxy::ImplThreadTaskRunner()->PostTask(
626 FROM_HERE,
627 base::Bind(&ThreadProxy::FinishGLOnImplThread,
628 impl_thread_weak_ptr_,
629 &completion));
630 completion.Wait();
633 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
635 CompletionEvent completion;
636 Proxy::ImplThreadTaskRunner()->PostTask(
637 FROM_HERE,
638 base::Bind(&ThreadProxy::LayerTreeHostClosedOnImplThread,
639 impl_thread_weak_ptr_,
640 &completion));
641 completion.Wait();
644 main().weak_factory.InvalidateWeakPtrs();
645 blocked_main().layer_tree_host = NULL;
646 main().started = false;
649 void ThreadProxy::ForceSerializeOnSwapBuffers() {
650 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
651 CompletionEvent completion;
652 Proxy::ImplThreadTaskRunner()->PostTask(
653 FROM_HERE,
654 base::Bind(&ThreadProxy::ForceSerializeOnSwapBuffersOnImplThread,
655 impl_thread_weak_ptr_,
656 &completion));
657 completion.Wait();
660 void ThreadProxy::ForceSerializeOnSwapBuffersOnImplThread(
661 CompletionEvent* completion) {
662 if (impl().layer_tree_host_impl->renderer())
663 impl().layer_tree_host_impl->renderer()->DoNoOp();
664 completion->Signal();
667 bool ThreadProxy::SupportsImplScrolling() const {
668 return true;
671 void ThreadProxy::SetDebugState(const LayerTreeDebugState& debug_state) {
672 Proxy::ImplThreadTaskRunner()->PostTask(
673 FROM_HERE,
674 base::Bind(&ThreadProxy::SetDebugStateOnImplThread,
675 impl_thread_weak_ptr_,
676 debug_state));
679 void ThreadProxy::SetDebugStateOnImplThread(
680 const LayerTreeDebugState& debug_state) {
681 DCHECK(IsImplThread());
682 impl().scheduler->SetContinuousPainting(debug_state.continuous_painting);
685 void ThreadProxy::FinishAllRenderingOnImplThread(CompletionEvent* completion) {
686 TRACE_EVENT0("cc", "ThreadProxy::FinishAllRenderingOnImplThread");
687 DCHECK(IsImplThread());
688 impl().layer_tree_host_impl->FinishAllRendering();
689 completion->Signal();
692 void ThreadProxy::ScheduledActionSendBeginMainFrame() {
693 unsigned int begin_frame_id = nextBeginFrameId++;
694 benchmark_instrumentation::ScopedBeginFrameTask begin_frame_task(
695 benchmark_instrumentation::kSendBeginFrame, begin_frame_id);
696 scoped_ptr<BeginMainFrameAndCommitState> begin_main_frame_state(
697 new BeginMainFrameAndCommitState);
698 begin_main_frame_state->begin_frame_id = begin_frame_id;
699 begin_main_frame_state->begin_frame_args =
700 impl().layer_tree_host_impl->CurrentBeginFrameArgs();
701 begin_main_frame_state->scroll_info =
702 impl().layer_tree_host_impl->ProcessScrollDeltas();
704 if (!impl().layer_tree_host_impl->settings().impl_side_painting) {
705 DCHECK_GT(impl().layer_tree_host_impl->memory_allocation_limit_bytes(), 0u);
707 begin_main_frame_state->memory_allocation_limit_bytes =
708 impl().layer_tree_host_impl->memory_allocation_limit_bytes();
709 begin_main_frame_state->memory_allocation_priority_cutoff =
710 impl().layer_tree_host_impl->memory_allocation_priority_cutoff();
711 begin_main_frame_state->evicted_ui_resources =
712 impl().layer_tree_host_impl->EvictedUIResourcesExist();
713 // TODO(vmpstr): This needs to be fixed if
714 // main_frame_before_activation_enabled is set, since we might run this code
715 // twice before recording a duration. crbug.com/469824
716 impl().last_begin_main_frame_args = begin_main_frame_state->begin_frame_args;
717 Proxy::MainThreadTaskRunner()->PostTask(
718 FROM_HERE,
719 base::Bind(&ThreadProxy::BeginMainFrame,
720 main_thread_weak_ptr_,
721 base::Passed(&begin_main_frame_state)));
722 devtools_instrumentation::DidRequestMainThreadFrame(
723 impl().layer_tree_host_id);
724 impl().timing_history.DidBeginMainFrame();
727 void ThreadProxy::SendBeginMainFrameNotExpectedSoon() {
728 Proxy::MainThreadTaskRunner()->PostTask(
729 FROM_HERE, base::Bind(&ThreadProxy::BeginMainFrameNotExpectedSoon,
730 main_thread_weak_ptr_));
733 void ThreadProxy::BeginMainFrame(
734 scoped_ptr<BeginMainFrameAndCommitState> begin_main_frame_state) {
735 benchmark_instrumentation::ScopedBeginFrameTask begin_frame_task(
736 benchmark_instrumentation::kDoBeginFrame,
737 begin_main_frame_state->begin_frame_id);
738 TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("cc.BeginMainFrame");
739 DCHECK(IsMainThread());
741 if (main().defer_commits) {
742 TRACE_EVENT_INSTANT0("cc", "EarlyOut_DeferCommit",
743 TRACE_EVENT_SCOPE_THREAD);
744 Proxy::ImplThreadTaskRunner()->PostTask(
745 FROM_HERE, base::Bind(&ThreadProxy::BeginMainFrameAbortedOnImplThread,
746 impl_thread_weak_ptr_,
747 CommitEarlyOutReason::ABORTED_DEFERRED_COMMIT));
748 return;
751 // If the commit finishes, LayerTreeHost will transfer its swap promises to
752 // LayerTreeImpl. The destructor of ScopedSwapPromiseChecker aborts the
753 // remaining swap promises.
754 ScopedAbortRemainingSwapPromises swap_promise_checker(layer_tree_host());
756 main().commit_requested = false;
757 main().commit_request_sent_to_impl_thread = false;
758 main().animate_requested = false;
760 if (!layer_tree_host()->visible()) {
761 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NotVisible", TRACE_EVENT_SCOPE_THREAD);
762 Proxy::ImplThreadTaskRunner()->PostTask(
763 FROM_HERE, base::Bind(&ThreadProxy::BeginMainFrameAbortedOnImplThread,
764 impl_thread_weak_ptr_,
765 CommitEarlyOutReason::ABORTED_NOT_VISIBLE));
766 return;
769 if (layer_tree_host()->output_surface_lost()) {
770 TRACE_EVENT_INSTANT0(
771 "cc", "EarlyOut_OutputSurfaceLost", TRACE_EVENT_SCOPE_THREAD);
772 Proxy::ImplThreadTaskRunner()->PostTask(
773 FROM_HERE,
774 base::Bind(&ThreadProxy::BeginMainFrameAbortedOnImplThread,
775 impl_thread_weak_ptr_,
776 CommitEarlyOutReason::ABORTED_OUTPUT_SURFACE_LOST));
777 return;
780 // Do not notify the impl thread of commit requests that occur during
781 // the apply/animate/layout part of the BeginMainFrameAndCommit process since
782 // those commit requests will get painted immediately. Once we have done
783 // the paint, main().commit_requested will be set to false to allow new commit
784 // requests to be scheduled.
785 // On the other hand, the animate_requested flag should remain cleared
786 // here so that any animation requests generated by the apply or animate
787 // callbacks will trigger another frame.
788 main().commit_requested = true;
789 main().commit_request_sent_to_impl_thread = true;
791 layer_tree_host()->ApplyScrollAndScale(
792 begin_main_frame_state->scroll_info.get());
794 layer_tree_host()->WillBeginMainFrame();
796 layer_tree_host()->BeginMainFrame(begin_main_frame_state->begin_frame_args);
797 layer_tree_host()->AnimateLayers(
798 begin_main_frame_state->begin_frame_args.frame_time);
800 // Unlink any backings that the impl thread has evicted, so that we know to
801 // re-paint them in UpdateLayers.
802 if (blocked_main().contents_texture_manager()) {
803 blocked_main().contents_texture_manager()->UnlinkAndClearEvictedBackings();
805 blocked_main().contents_texture_manager()->SetMaxMemoryLimitBytes(
806 begin_main_frame_state->memory_allocation_limit_bytes);
807 blocked_main().contents_texture_manager()->SetExternalPriorityCutoff(
808 begin_main_frame_state->memory_allocation_priority_cutoff);
811 // Recreate all UI resources if there were evicted UI resources when the impl
812 // thread initiated the commit.
813 if (begin_main_frame_state->evicted_ui_resources)
814 layer_tree_host()->RecreateUIResources();
816 layer_tree_host()->Layout();
817 TRACE_EVENT_SYNTHETIC_DELAY_END("cc.BeginMainFrame");
819 // Clear the commit flag after updating animations and layout here --- objects
820 // that only layout when painted will trigger another SetNeedsCommit inside
821 // UpdateLayers.
822 main().commit_requested = false;
823 main().commit_request_sent_to_impl_thread = false;
824 bool can_cancel_this_commit =
825 main().can_cancel_commit && !begin_main_frame_state->evicted_ui_resources;
826 main().can_cancel_commit = true;
828 scoped_ptr<ResourceUpdateQueue> queue =
829 make_scoped_ptr(new ResourceUpdateQueue);
831 bool updated = layer_tree_host()->UpdateLayers(queue.get());
833 layer_tree_host()->WillCommit();
834 devtools_instrumentation::ScopedCommitTrace commit_task(
835 layer_tree_host()->id());
837 // Before calling animate, we set main().animate_requested to false. If it is
838 // true now, it means SetNeedAnimate was called again, but during a state when
839 // main().commit_request_sent_to_impl_thread = true. We need to force that
840 // call to happen again now so that the commit request is sent to the impl
841 // thread.
842 if (main().animate_requested) {
843 // Forces SetNeedsAnimate to consider posting a commit task.
844 main().animate_requested = false;
845 SetNeedsAnimate();
848 if (!updated && can_cancel_this_commit) {
849 TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoUpdates", TRACE_EVENT_SCOPE_THREAD);
850 Proxy::ImplThreadTaskRunner()->PostTask(
851 FROM_HERE, base::Bind(&ThreadProxy::BeginMainFrameAbortedOnImplThread,
852 impl_thread_weak_ptr_,
853 CommitEarlyOutReason::FINISHED_NO_UPDATES));
855 // Although the commit is internally aborted, this is because it has been
856 // detected to be a no-op. From the perspective of an embedder, this commit
857 // went through, and input should no longer be throttled, etc.
858 layer_tree_host()->CommitComplete();
859 layer_tree_host()->DidBeginMainFrame();
860 layer_tree_host()->BreakSwapPromises(SwapPromise::COMMIT_NO_UPDATE);
861 return;
864 // Notify the impl thread that the main thread is ready to commit. This will
865 // begin the commit process, which is blocking from the main thread's
866 // point of view, but asynchronously performed on the impl thread,
867 // coordinated by the Scheduler.
869 TRACE_EVENT0("cc", "ThreadProxy::BeginMainFrame::commit");
871 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
873 // This CapturePostTasks should be destroyed before CommitComplete() is
874 // called since that goes out to the embedder, and we want the embedder
875 // to receive its callbacks before that.
876 BlockingTaskRunner::CapturePostTasks blocked(
877 blocking_main_thread_task_runner());
879 CompletionEvent completion;
880 Proxy::ImplThreadTaskRunner()->PostTask(
881 FROM_HERE,
882 base::Bind(&ThreadProxy::StartCommitOnImplThread,
883 impl_thread_weak_ptr_,
884 &completion,
885 queue.release()));
886 completion.Wait();
889 layer_tree_host()->CommitComplete();
890 layer_tree_host()->DidBeginMainFrame();
893 void ThreadProxy::BeginMainFrameNotExpectedSoon() {
894 TRACE_EVENT0("cc", "ThreadProxy::BeginMainFrameNotExpectedSoon");
895 DCHECK(IsMainThread());
896 layer_tree_host()->BeginMainFrameNotExpectedSoon();
899 void ThreadProxy::StartCommitOnImplThread(CompletionEvent* completion,
900 ResourceUpdateQueue* raw_queue) {
901 TRACE_EVENT0("cc", "ThreadProxy::StartCommitOnImplThread");
902 DCHECK(!impl().commit_completion_event);
903 DCHECK(IsImplThread() && IsMainThreadBlocked());
904 DCHECK(impl().scheduler);
905 DCHECK(impl().scheduler->CommitPending());
907 if (!impl().layer_tree_host_impl) {
908 TRACE_EVENT_INSTANT0(
909 "cc", "EarlyOut_NoLayerTree", TRACE_EVENT_SCOPE_THREAD);
910 completion->Signal();
911 return;
914 // Ideally, we should inform to impl thread when BeginMainFrame is started.
915 // But, we can avoid a PostTask in here.
916 impl().scheduler->NotifyBeginMainFrameStarted();
918 scoped_ptr<ResourceUpdateQueue> queue(raw_queue);
920 if (impl().contents_texture_manager) {
921 DCHECK_EQ(impl().contents_texture_manager,
922 blocked_main().contents_texture_manager());
923 } else {
924 // Cache this pointer that was created on the main thread side to avoid a
925 // data race between creating it and using it on the compositor thread.
926 impl().contents_texture_manager = blocked_main().contents_texture_manager();
929 if (impl().contents_texture_manager) {
930 if (impl().contents_texture_manager->LinkedEvictedBackingsExist()) {
931 // Clear any uploads we were making to textures linked to evicted
932 // resources
933 queue->ClearUploadsToEvictedResources();
934 // Some textures in the layer tree are invalid. Kick off another commit
935 // to fill them again.
936 SetNeedsCommitOnImplThread();
939 impl().contents_texture_manager->PushTexturePrioritiesToBackings();
942 impl().commit_completion_event = completion;
943 impl().current_resource_update_controller = ResourceUpdateController::Create(
944 this,
945 Proxy::ImplThreadTaskRunner(),
946 queue.Pass(),
947 impl().layer_tree_host_impl->resource_provider());
948 impl().current_resource_update_controller->PerformMoreUpdates(
949 impl().scheduler->AnticipatedDrawTime());
952 void ThreadProxy::BeginMainFrameAbortedOnImplThread(
953 CommitEarlyOutReason reason) {
954 TRACE_EVENT1("cc", "ThreadProxy::BeginMainFrameAbortedOnImplThread", "reason",
955 CommitEarlyOutReasonToString(reason));
956 DCHECK(IsImplThread());
957 DCHECK(impl().scheduler);
958 DCHECK(impl().scheduler->CommitPending());
959 DCHECK(!impl().layer_tree_host_impl->pending_tree());
961 if (CommitEarlyOutHandledCommit(reason)) {
962 SetInputThrottledUntilCommitOnImplThread(false);
963 impl().last_processed_begin_main_frame_args =
964 impl().last_begin_main_frame_args;
966 impl().layer_tree_host_impl->BeginMainFrameAborted(reason);
967 impl().scheduler->BeginMainFrameAborted(reason);
970 void ThreadProxy::ScheduledActionAnimate() {
971 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionAnimate");
972 DCHECK(IsImplThread());
974 // Don't animate if there is no root layer.
975 // TODO(mithro): Both Animate and UpdateAnimationState already have a
976 // "!active_tree_->root_layer()" check?
977 if (!impl().layer_tree_host_impl->active_tree()->root_layer()) {
978 return;
981 impl().animation_time =
982 impl().layer_tree_host_impl->CurrentBeginFrameArgs().frame_time;
983 impl().layer_tree_host_impl->Animate(impl().animation_time);
985 // If animations are not visible, update the state now as
986 // ScheduledActionDrawAndSwapIfPossible will never be called.
987 if (!impl().layer_tree_host_impl->AnimationsAreVisible()) {
988 impl().layer_tree_host_impl->UpdateAnimationState(true);
992 void ThreadProxy::ScheduledActionCommit() {
993 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionCommit");
994 DCHECK(IsImplThread());
995 DCHECK(IsMainThreadBlocked());
996 DCHECK(impl().commit_completion_event);
997 DCHECK(impl().current_resource_update_controller);
999 // Complete all remaining texture updates.
1000 impl().current_resource_update_controller->Finalize();
1001 impl().current_resource_update_controller = nullptr;
1003 blocked_main().main_thread_inside_commit = true;
1004 impl().layer_tree_host_impl->BeginCommit();
1005 layer_tree_host()->BeginCommitOnImplThread(impl().layer_tree_host_impl.get());
1006 layer_tree_host()->FinishCommitOnImplThread(
1007 impl().layer_tree_host_impl.get());
1008 blocked_main().main_thread_inside_commit = false;
1010 bool hold_commit = layer_tree_host()->settings().impl_side_painting &&
1011 blocked_main().commit_waits_for_activation;
1012 blocked_main().commit_waits_for_activation = false;
1014 if (hold_commit) {
1015 // For some layer types in impl-side painting, the commit is held until
1016 // the sync tree is activated. It's also possible that the
1017 // sync tree has already activated if there was no work to be done.
1018 TRACE_EVENT_INSTANT0("cc", "HoldCommit", TRACE_EVENT_SCOPE_THREAD);
1019 impl().completion_event_for_commit_held_on_tree_activation =
1020 impl().commit_completion_event;
1021 impl().commit_completion_event = NULL;
1022 } else {
1023 impl().commit_completion_event->Signal();
1024 impl().commit_completion_event = NULL;
1027 // Delay this step until afer the main thread has been released as it's
1028 // often a good bit of work to update the tree and prepare the new frame.
1029 impl().layer_tree_host_impl->CommitComplete();
1031 SetInputThrottledUntilCommitOnImplThread(false);
1033 impl().next_frame_is_newly_committed_frame = true;
1035 impl().timing_history.DidCommit();
1038 void ThreadProxy::ScheduledActionActivateSyncTree() {
1039 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionActivateSyncTree");
1040 DCHECK(IsImplThread());
1041 impl().layer_tree_host_impl->ActivateSyncTree();
1044 void ThreadProxy::ScheduledActionBeginOutputSurfaceCreation() {
1045 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionBeginOutputSurfaceCreation");
1046 DCHECK(IsImplThread());
1047 Proxy::MainThreadTaskRunner()->PostTask(
1048 FROM_HERE,
1049 base::Bind(&ThreadProxy::RequestNewOutputSurface, main_thread_weak_ptr_));
1052 DrawResult ThreadProxy::DrawSwapInternal(bool forced_draw) {
1053 TRACE_EVENT_SYNTHETIC_DELAY("cc.DrawAndSwap");
1054 DrawResult result;
1056 DCHECK(IsImplThread());
1057 DCHECK(impl().layer_tree_host_impl.get());
1059 impl().timing_history.DidStartDrawing();
1060 base::AutoReset<bool> mark_inside(&impl().inside_draw, true);
1062 if (impl().layer_tree_host_impl->pending_tree()) {
1063 bool update_lcd_text = false;
1064 impl().layer_tree_host_impl->pending_tree()->UpdateDrawProperties(
1065 update_lcd_text);
1068 // This method is called on a forced draw, regardless of whether we are able
1069 // to produce a frame, as the calling site on main thread is blocked until its
1070 // request completes, and we signal completion here. If CanDraw() is false, we
1071 // will indicate success=false to the caller, but we must still signal
1072 // completion to avoid deadlock.
1074 // We guard PrepareToDraw() with CanDraw() because it always returns a valid
1075 // frame, so can only be used when such a frame is possible. Since
1076 // DrawLayers() depends on the result of PrepareToDraw(), it is guarded on
1077 // CanDraw() as well.
1079 LayerTreeHostImpl::FrameData frame;
1080 bool draw_frame = false;
1082 if (impl().layer_tree_host_impl->CanDraw()) {
1083 result = impl().layer_tree_host_impl->PrepareToDraw(&frame);
1084 draw_frame = forced_draw || result == DRAW_SUCCESS;
1085 } else {
1086 result = DRAW_ABORTED_CANT_DRAW;
1089 if (draw_frame) {
1090 impl().layer_tree_host_impl->DrawLayers(&frame);
1091 result = DRAW_SUCCESS;
1092 } else {
1093 DCHECK_NE(DRAW_SUCCESS, result);
1095 impl().layer_tree_host_impl->DidDrawAllLayers(frame);
1097 bool start_ready_animations = draw_frame;
1098 impl().layer_tree_host_impl->UpdateAnimationState(start_ready_animations);
1100 if (draw_frame)
1101 impl().layer_tree_host_impl->SwapBuffers(frame);
1103 // Tell the main thread that the the newly-commited frame was drawn.
1104 if (impl().next_frame_is_newly_committed_frame) {
1105 impl().next_frame_is_newly_committed_frame = false;
1106 Proxy::MainThreadTaskRunner()->PostTask(
1107 FROM_HERE,
1108 base::Bind(&ThreadProxy::DidCommitAndDrawFrame, main_thread_weak_ptr_));
1111 if (result == DRAW_SUCCESS)
1112 impl().timing_history.DidFinishDrawing();
1114 DCHECK_NE(INVALID_RESULT, result);
1115 return result;
1118 void ThreadProxy::ScheduledActionPrepareTiles() {
1119 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionPrepareTiles");
1120 DCHECK(impl().layer_tree_host_impl->settings().impl_side_painting);
1121 impl().layer_tree_host_impl->PrepareTiles();
1124 DrawResult ThreadProxy::ScheduledActionDrawAndSwapIfPossible() {
1125 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionDrawAndSwap");
1127 // SchedulerStateMachine::DidDrawIfPossibleCompleted isn't set up to
1128 // handle DRAW_ABORTED_CANT_DRAW. Moreover, the scheduler should
1129 // never generate this call when it can't draw.
1130 DCHECK(impl().layer_tree_host_impl->CanDraw());
1132 bool forced_draw = false;
1133 return DrawSwapInternal(forced_draw);
1136 DrawResult ThreadProxy::ScheduledActionDrawAndSwapForced() {
1137 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionDrawAndSwapForced");
1138 bool forced_draw = true;
1139 return DrawSwapInternal(forced_draw);
1142 void ThreadProxy::ScheduledActionInvalidateOutputSurface() {
1143 TRACE_EVENT0("cc", "ThreadProxy::ScheduledActionInvalidateOutputSurface");
1144 DCHECK(impl().layer_tree_host_impl->output_surface());
1145 impl().layer_tree_host_impl->output_surface()->Invalidate();
1148 void ThreadProxy::DidAnticipatedDrawTimeChange(base::TimeTicks time) {
1149 if (impl().current_resource_update_controller)
1150 impl().current_resource_update_controller->PerformMoreUpdates(time);
1153 base::TimeDelta ThreadProxy::DrawDurationEstimate() {
1154 return impl().timing_history.DrawDurationEstimate();
1157 base::TimeDelta ThreadProxy::BeginMainFrameToCommitDurationEstimate() {
1158 return impl().timing_history.BeginMainFrameToCommitDurationEstimate();
1161 base::TimeDelta ThreadProxy::CommitToActivateDurationEstimate() {
1162 return impl().timing_history.CommitToActivateDurationEstimate();
1165 void ThreadProxy::DidFinishImplFrame() {
1166 impl().layer_tree_host_impl->DidFinishImplFrame();
1169 void ThreadProxy::SendBeginFramesToChildren(const BeginFrameArgs& args) {
1170 NOTREACHED() << "Only used by SingleThreadProxy";
1173 void ThreadProxy::SetAuthoritativeVSyncInterval(
1174 const base::TimeDelta& interval) {
1175 NOTREACHED() << "Only used by SingleThreadProxy";
1178 void ThreadProxy::ReadyToFinalizeTextureUpdates() {
1179 DCHECK(IsImplThread());
1180 impl().scheduler->NotifyReadyToCommit();
1183 void ThreadProxy::DidCommitAndDrawFrame() {
1184 DCHECK(IsMainThread());
1185 layer_tree_host()->DidCommitAndDrawFrame();
1188 void ThreadProxy::DidCompleteSwapBuffers() {
1189 DCHECK(IsMainThread());
1190 layer_tree_host()->DidCompleteSwapBuffers();
1193 void ThreadProxy::SetAnimationEvents(scoped_ptr<AnimationEventsVector> events) {
1194 TRACE_EVENT0("cc", "ThreadProxy::SetAnimationEvents");
1195 DCHECK(IsMainThread());
1196 layer_tree_host()->SetAnimationEvents(events.Pass());
1199 void ThreadProxy::InitializeImplOnImplThread(CompletionEvent* completion) {
1200 TRACE_EVENT0("cc", "ThreadProxy::InitializeImplOnImplThread");
1201 DCHECK(IsImplThread());
1202 impl().layer_tree_host_impl =
1203 layer_tree_host()->CreateLayerTreeHostImpl(this);
1204 SchedulerSettings scheduler_settings(
1205 layer_tree_host()->settings().ToSchedulerSettings());
1206 impl().scheduler = Scheduler::Create(
1207 this,
1208 scheduler_settings,
1209 impl().layer_tree_host_id,
1210 ImplThreadTaskRunner(),
1211 impl().external_begin_frame_source.Pass());
1212 impl().scheduler->SetVisible(impl().layer_tree_host_impl->visible());
1213 impl_thread_weak_ptr_ = impl().weak_factory.GetWeakPtr();
1214 completion->Signal();
1217 void ThreadProxy::DeleteContentsTexturesOnImplThread(
1218 CompletionEvent* completion) {
1219 TRACE_EVENT0("cc", "ThreadProxy::DeleteContentsTexturesOnImplThread");
1220 DCHECK(IsImplThread());
1221 DCHECK(IsMainThreadBlocked());
1222 layer_tree_host()->DeleteContentsTexturesOnImplThread(
1223 impl().layer_tree_host_impl->resource_provider());
1224 completion->Signal();
1227 void ThreadProxy::InitializeOutputSurfaceOnImplThread(
1228 scoped_ptr<OutputSurface> output_surface) {
1229 TRACE_EVENT0("cc", "ThreadProxy::InitializeOutputSurfaceOnImplThread");
1230 DCHECK(IsImplThread());
1232 LayerTreeHostImpl* host_impl = impl().layer_tree_host_impl.get();
1233 bool success = host_impl->InitializeRenderer(output_surface.Pass());
1234 RendererCapabilities capabilities;
1235 if (success) {
1236 capabilities =
1237 host_impl->GetRendererCapabilities().MainThreadCapabilities();
1240 Proxy::MainThreadTaskRunner()->PostTask(
1241 FROM_HERE,
1242 base::Bind(&ThreadProxy::DidInitializeOutputSurface,
1243 main_thread_weak_ptr_,
1244 success,
1245 capabilities));
1247 if (success)
1248 impl().scheduler->DidCreateAndInitializeOutputSurface();
1251 void ThreadProxy::FinishGLOnImplThread(CompletionEvent* completion) {
1252 TRACE_EVENT0("cc", "ThreadProxy::FinishGLOnImplThread");
1253 DCHECK(IsImplThread());
1254 if (impl().layer_tree_host_impl->output_surface()) {
1255 ContextProvider* context_provider =
1256 impl().layer_tree_host_impl->output_surface()->context_provider();
1257 if (context_provider)
1258 context_provider->ContextGL()->Finish();
1260 completion->Signal();
1263 void ThreadProxy::LayerTreeHostClosedOnImplThread(CompletionEvent* completion) {
1264 TRACE_EVENT0("cc", "ThreadProxy::LayerTreeHostClosedOnImplThread");
1265 DCHECK(IsImplThread());
1266 DCHECK(IsMainThreadBlocked());
1267 layer_tree_host()->DeleteContentsTexturesOnImplThread(
1268 impl().layer_tree_host_impl->resource_provider());
1269 impl().current_resource_update_controller = nullptr;
1270 impl().scheduler = nullptr;
1271 impl().layer_tree_host_impl = nullptr;
1272 impl().weak_factory.InvalidateWeakPtrs();
1273 // We need to explicitly shutdown the notifier to destroy any weakptrs it is
1274 // holding while still on the compositor thread. This also ensures any
1275 // callbacks holding a ThreadProxy pointer are cancelled.
1276 impl().smoothness_priority_expiration_notifier.Shutdown();
1277 impl().contents_texture_manager = NULL;
1278 completion->Signal();
1281 size_t ThreadProxy::MaxPartialTextureUpdates() const {
1282 return ResourceUpdateController::MaxPartialTextureUpdates();
1285 ThreadProxy::BeginMainFrameAndCommitState::BeginMainFrameAndCommitState()
1286 : memory_allocation_limit_bytes(0),
1287 memory_allocation_priority_cutoff(0),
1288 evicted_ui_resources(false) {}
1290 ThreadProxy::BeginMainFrameAndCommitState::~BeginMainFrameAndCommitState() {}
1292 bool ThreadProxy::MainFrameWillHappenForTesting() {
1293 DCHECK(IsMainThread());
1294 CompletionEvent completion;
1295 bool main_frame_will_happen = false;
1297 DebugScopedSetMainThreadBlocked main_thread_blocked(this);
1298 Proxy::ImplThreadTaskRunner()->PostTask(
1299 FROM_HERE,
1300 base::Bind(&ThreadProxy::MainFrameWillHappenOnImplThreadForTesting,
1301 impl_thread_weak_ptr_,
1302 &completion,
1303 &main_frame_will_happen));
1304 completion.Wait();
1306 return main_frame_will_happen;
1309 void ThreadProxy::SetChildrenNeedBeginFrames(bool children_need_begin_frames) {
1310 NOTREACHED() << "Only used by SingleThreadProxy";
1313 void ThreadProxy::MainFrameWillHappenOnImplThreadForTesting(
1314 CompletionEvent* completion,
1315 bool* main_frame_will_happen) {
1316 DCHECK(IsImplThread());
1317 if (impl().layer_tree_host_impl->output_surface()) {
1318 *main_frame_will_happen = impl().scheduler->MainFrameForTestingWillHappen();
1319 } else {
1320 *main_frame_will_happen = false;
1322 completion->Signal();
1325 void ThreadProxy::RenewTreePriority() {
1326 DCHECK(IsImplThread());
1327 bool smoothness_takes_priority =
1328 impl().layer_tree_host_impl->pinch_gesture_active() ||
1329 impl().layer_tree_host_impl->page_scale_animation_active() ||
1330 impl().layer_tree_host_impl->IsActivelyScrolling();
1332 // Schedule expiration if smoothness currently takes priority.
1333 if (smoothness_takes_priority)
1334 impl().smoothness_priority_expiration_notifier.Schedule();
1336 // We use the same priority for both trees by default.
1337 TreePriority priority = SAME_PRIORITY_FOR_BOTH_TREES;
1339 // Smoothness takes priority if we have an expiration for it scheduled.
1340 if (impl().smoothness_priority_expiration_notifier.HasPendingNotification())
1341 priority = SMOOTHNESS_TAKES_PRIORITY;
1343 // New content always takes priority when the active tree has
1344 // evicted resources or there is an invalid viewport size.
1345 if (impl().layer_tree_host_impl->active_tree()->ContentsTexturesPurged() ||
1346 impl().layer_tree_host_impl->active_tree()->ViewportSizeInvalid() ||
1347 impl().layer_tree_host_impl->EvictedUIResourcesExist() ||
1348 impl().input_throttled_until_commit) {
1349 // Once we enter NEW_CONTENTS_TAKES_PRIORITY mode, visible tiles on active
1350 // tree might be freed. We need to set RequiresHighResToDraw to ensure that
1351 // high res tiles will be required to activate pending tree.
1352 impl().layer_tree_host_impl->SetRequiresHighResToDraw();
1353 priority = NEW_CONTENT_TAKES_PRIORITY;
1356 impl().layer_tree_host_impl->SetTreePriority(priority);
1358 // Only put the scheduler in impl latency prioritization mode if we don't
1359 // have a scroll listener. This gives the scroll listener a better chance of
1360 // handling scroll updates within the same frame. The tree itself is still
1361 // kept in prefer smoothness mode to allow checkerboarding.
1362 impl().scheduler->SetImplLatencyTakesPriority(
1363 priority == SMOOTHNESS_TAKES_PRIORITY &&
1364 !impl().layer_tree_host_impl->scroll_affects_scroll_handler());
1366 // Notify the the client of this compositor via the output surface.
1367 // TODO(epenner): Route this to compositor-thread instead of output-surface
1368 // after GTFO refactor of compositor-thread (http://crbug/170828).
1369 if (impl().layer_tree_host_impl->output_surface()) {
1370 impl()
1371 .layer_tree_host_impl->output_surface()
1372 ->UpdateSmoothnessTakesPriority(priority == SMOOTHNESS_TAKES_PRIORITY);
1376 void ThreadProxy::PostDelayedAnimationTaskOnImplThread(
1377 const base::Closure& task,
1378 base::TimeDelta delay) {
1379 Proxy::ImplThreadTaskRunner()->PostDelayedTask(FROM_HERE, task, delay);
1382 void ThreadProxy::DidActivateSyncTree() {
1383 TRACE_EVENT0("cc", "ThreadProxy::DidActivateSyncTreeOnImplThread");
1384 DCHECK(IsImplThread());
1386 if (impl().completion_event_for_commit_held_on_tree_activation) {
1387 TRACE_EVENT_INSTANT0(
1388 "cc", "ReleaseCommitbyActivation", TRACE_EVENT_SCOPE_THREAD);
1389 DCHECK(impl().layer_tree_host_impl->settings().impl_side_painting);
1390 impl().completion_event_for_commit_held_on_tree_activation->Signal();
1391 impl().completion_event_for_commit_held_on_tree_activation = NULL;
1394 impl().timing_history.DidActivateSyncTree();
1395 impl().last_processed_begin_main_frame_args =
1396 impl().last_begin_main_frame_args;
1399 void ThreadProxy::DidPrepareTiles() {
1400 DCHECK(IsImplThread());
1401 impl().scheduler->DidPrepareTiles();
1404 void ThreadProxy::DidCompletePageScaleAnimationOnImplThread() {
1405 DCHECK(IsImplThread());
1406 Proxy::MainThreadTaskRunner()->PostTask(
1407 FROM_HERE, base::Bind(&ThreadProxy::DidCompletePageScaleAnimation,
1408 main_thread_weak_ptr_));
1411 void ThreadProxy::OnDrawForOutputSurface() {
1412 DCHECK(IsImplThread());
1413 impl().scheduler->OnDrawForOutputSurface();
1416 } // namespace cc