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