1 // Copyright (c) 2012 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 "ui/compositor/compositor.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/debug/trace_event.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/histogram.h"
15 #include "base/strings/string_util.h"
16 #include "base/sys_info.h"
17 #include "cc/base/latency_info_swap_promise.h"
18 #include "cc/base/switches.h"
19 #include "cc/input/input_handler.h"
20 #include "cc/layers/layer.h"
21 #include "cc/output/begin_frame_args.h"
22 #include "cc/output/context_provider.h"
23 #include "cc/trees/layer_tree_host.h"
24 #include "third_party/skia/include/core/SkBitmap.h"
25 #include "ui/compositor/compositor_observer.h"
26 #include "ui/compositor/compositor_switches.h"
27 #include "ui/compositor/compositor_vsync_manager.h"
28 #include "ui/compositor/dip_util.h"
29 #include "ui/compositor/layer.h"
30 #include "ui/compositor/layer_animator_collection.h"
31 #include "ui/gfx/frame_time.h"
32 #include "ui/gl/gl_context.h"
33 #include "ui/gl/gl_switches.h"
37 const double kDefaultRefreshRate
= 60.0;
38 const double kTestRefreshRate
= 200.0;
40 const int kCompositorLockTimeoutMs
= 67;
46 CompositorLock::CompositorLock(Compositor
* compositor
)
47 : compositor_(compositor
) {
48 compositor_
->task_runner_
->PostDelayedTask(
50 base::Bind(&CompositorLock::CancelLock
, AsWeakPtr()),
51 base::TimeDelta::FromMilliseconds(kCompositorLockTimeoutMs
));
54 CompositorLock::~CompositorLock() {
58 void CompositorLock::CancelLock() {
61 compositor_
->UnlockCompositor();
67 namespace {} // namespace
71 Compositor::Compositor(gfx::AcceleratedWidget widget
,
72 ui::ContextFactory
* context_factory
,
73 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
)
74 : context_factory_(context_factory
),
77 compositor_thread_loop_(context_factory
->GetCompositorMessageLoop()),
78 task_runner_(task_runner
),
79 vsync_manager_(new CompositorVSyncManager()),
80 device_scale_factor_(0.0f
),
81 last_started_frame_(0),
83 disable_schedule_composite_(false),
84 compositor_lock_(NULL
),
85 defer_draw_scheduling_(false),
86 waiting_on_compositing_end_(false),
87 draw_on_compositing_end_(false),
88 swap_state_(SWAP_NONE
),
89 layer_animator_collection_(this),
90 schedule_draw_factory_(this) {
91 root_web_layer_
= cc::Layer::Create();
93 CommandLine
* command_line
= CommandLine::ForCurrentProcess();
95 cc::LayerTreeSettings settings
;
96 settings
.refresh_rate
=
97 context_factory_
->DoesCreateTestContexts()
99 : kDefaultRefreshRate
;
100 settings
.main_frame_before_draw_enabled
= false;
101 settings
.main_frame_before_activation_enabled
= false;
102 settings
.throttle_frame_production
=
103 !command_line
->HasSwitch(switches::kDisableGpuVsync
);
104 #if !defined(OS_MACOSX)
105 settings
.partial_swap_enabled
=
106 !command_line
->HasSwitch(cc::switches::kUIDisablePartialSwap
);
108 #if defined(OS_CHROMEOS)
109 settings
.per_tile_painting_enabled
= true;
112 // These flags should be mirrored by renderer versions in content/renderer/.
113 settings
.initial_debug_state
.show_debug_borders
=
114 command_line
->HasSwitch(cc::switches::kUIShowCompositedLayerBorders
);
115 settings
.initial_debug_state
.show_fps_counter
=
116 command_line
->HasSwitch(cc::switches::kUIShowFPSCounter
);
117 settings
.initial_debug_state
.show_layer_animation_bounds_rects
=
118 command_line
->HasSwitch(cc::switches::kUIShowLayerAnimationBounds
);
119 settings
.initial_debug_state
.show_paint_rects
=
120 command_line
->HasSwitch(switches::kUIShowPaintRects
);
121 settings
.initial_debug_state
.show_property_changed_rects
=
122 command_line
->HasSwitch(cc::switches::kUIShowPropertyChangedRects
);
123 settings
.initial_debug_state
.show_surface_damage_rects
=
124 command_line
->HasSwitch(cc::switches::kUIShowSurfaceDamageRects
);
125 settings
.initial_debug_state
.show_screen_space_rects
=
126 command_line
->HasSwitch(cc::switches::kUIShowScreenSpaceRects
);
127 settings
.initial_debug_state
.show_replica_screen_space_rects
=
128 command_line
->HasSwitch(cc::switches::kUIShowReplicaScreenSpaceRects
);
129 settings
.initial_debug_state
.show_occluding_rects
=
130 command_line
->HasSwitch(cc::switches::kUIShowOccludingRects
);
131 settings
.initial_debug_state
.show_non_occluding_rects
=
132 command_line
->HasSwitch(cc::switches::kUIShowNonOccludingRects
);
134 settings
.initial_debug_state
.SetRecordRenderingStats(
135 command_line
->HasSwitch(cc::switches::kEnableGpuBenchmarking
));
137 settings
.impl_side_painting
= IsUIImplSidePaintingEnabled();
138 settings
.use_zero_copy
= IsUIZeroCopyEnabled();
139 settings
.single_thread_proxy_scheduler
= false;
141 base::TimeTicks before_create
= base::TimeTicks::Now();
142 if (compositor_thread_loop_
.get()) {
143 host_
= cc::LayerTreeHost::CreateThreaded(
145 context_factory_
->GetSharedBitmapManager(),
148 compositor_thread_loop_
);
150 host_
= cc::LayerTreeHost::CreateSingleThreaded(
153 context_factory_
->GetSharedBitmapManager(),
157 UMA_HISTOGRAM_TIMES("GPU.CreateBrowserCompositor",
158 base::TimeTicks::Now() - before_create
);
159 host_
->SetRootLayer(root_web_layer_
);
160 host_
->SetLayerTreeHostClientReady();
163 Compositor::~Compositor() {
164 TRACE_EVENT0("shutdown", "Compositor::destructor");
166 CancelCompositorLock();
167 DCHECK(!compositor_lock_
);
170 root_layer_
->SetCompositor(NULL
);
172 // Stop all outstanding draws before telling the ContextFactory to tear
173 // down any contexts that the |host_| may rely upon.
176 context_factory_
->RemoveCompositor(this);
179 void Compositor::ScheduleDraw() {
180 if (compositor_thread_loop_
.get()) {
181 host_
->SetNeedsCommit();
182 } else if (!defer_draw_scheduling_
) {
183 defer_draw_scheduling_
= true;
184 task_runner_
->PostTask(
186 base::Bind(&Compositor::Draw
, schedule_draw_factory_
.GetWeakPtr()));
190 void Compositor::SetRootLayer(Layer
* root_layer
) {
191 if (root_layer_
== root_layer
)
194 root_layer_
->SetCompositor(NULL
);
195 root_layer_
= root_layer
;
196 if (root_layer_
&& !root_layer_
->GetCompositor())
197 root_layer_
->SetCompositor(this);
198 root_web_layer_
->RemoveAllChildren();
200 root_web_layer_
->AddChild(root_layer_
->cc_layer());
203 void Compositor::SetHostHasTransparentBackground(
204 bool host_has_transparent_background
) {
205 host_
->set_has_transparent_background(host_has_transparent_background
);
208 void Compositor::Draw() {
209 DCHECK(!compositor_thread_loop_
.get());
211 defer_draw_scheduling_
= false;
212 if (waiting_on_compositing_end_
) {
213 draw_on_compositing_end_
= true;
219 TRACE_EVENT_ASYNC_BEGIN0("ui", "Compositor::Draw", last_started_frame_
+ 1);
221 DCHECK_NE(swap_state_
, SWAP_POSTED
);
222 swap_state_
= SWAP_NONE
;
224 waiting_on_compositing_end_
= true;
225 last_started_frame_
++;
227 // TODO(nduca): Temporary while compositor calls
228 // compositeImmediately() directly.
229 cc::BeginFrameArgs args
=
230 cc::BeginFrameArgs::Create(gfx::FrameTime::Now(),
232 cc::BeginFrameArgs::DefaultInterval());
233 BeginMainFrame(args
);
235 host_
->Composite(args
.frame_time
);
237 if (swap_state_
== SWAP_NONE
)
241 void Compositor::ScheduleFullRedraw() {
242 host_
->SetNeedsRedraw();
245 void Compositor::ScheduleRedrawRect(const gfx::Rect
& damage_rect
) {
246 host_
->SetNeedsRedrawRect(damage_rect
);
249 void Compositor::FinishAllRendering() {
250 host_
->FinishAllRendering();
253 void Compositor::SetLatencyInfo(const ui::LatencyInfo
& latency_info
) {
254 scoped_ptr
<cc::SwapPromise
> swap_promise(
255 new cc::LatencyInfoSwapPromise(latency_info
));
256 host_
->QueueSwapPromise(swap_promise
.Pass());
259 void Compositor::SetScaleAndSize(float scale
, const gfx::Size
& size_in_pixel
) {
261 if (!size_in_pixel
.IsEmpty()) {
262 size_
= size_in_pixel
;
263 host_
->SetViewportSize(size_in_pixel
);
264 root_web_layer_
->SetBounds(size_in_pixel
);
266 if (device_scale_factor_
!= scale
) {
267 device_scale_factor_
= scale
;
268 host_
->SetDeviceScaleFactor(scale
);
270 root_layer_
->OnDeviceScaleFactorChanged(scale
);
274 void Compositor::SetBackgroundColor(SkColor color
) {
275 host_
->set_background_color(color
);
279 void Compositor::SetVisible(bool visible
) {
280 host_
->SetVisible(visible
);
283 scoped_refptr
<CompositorVSyncManager
> Compositor::vsync_manager() const {
284 return vsync_manager_
;
287 void Compositor::AddObserver(CompositorObserver
* observer
) {
288 #if defined(OS_MACOSX)
289 // Debugging instrumentation for crbug.com/401630.
290 // TODO(ccameron): remove this.
292 if (!observer_list_
.HasObserver(observer
))
293 observer
->observing_count_
+= 1;
296 observer_list_
.AddObserver(observer
);
299 void Compositor::RemoveObserver(CompositorObserver
* observer
) {
300 #if defined(OS_MACOSX)
301 // Debugging instrumentation for crbug.com/401630.
302 // TODO(ccameron): remove this.
303 if (observer_list_
.HasObserver(observer
))
304 observer
->observing_count_
-= 1;
307 observer_list_
.RemoveObserver(observer
);
310 bool Compositor::HasObserver(CompositorObserver
* observer
) {
311 return observer_list_
.HasObserver(observer
);
314 void Compositor::AddAnimationObserver(CompositorAnimationObserver
* observer
) {
315 animation_observer_list_
.AddObserver(observer
);
316 host_
->SetNeedsAnimate();
319 void Compositor::RemoveAnimationObserver(
320 CompositorAnimationObserver
* observer
) {
321 animation_observer_list_
.RemoveObserver(observer
);
324 bool Compositor::HasAnimationObserver(CompositorAnimationObserver
* observer
) {
325 return animation_observer_list_
.HasObserver(observer
);
328 void Compositor::BeginMainFrame(const cc::BeginFrameArgs
& args
) {
329 FOR_EACH_OBSERVER(CompositorAnimationObserver
,
330 animation_observer_list_
,
331 OnAnimationStep(args
.frame_time
));
332 if (animation_observer_list_
.might_have_observers())
333 host_
->SetNeedsAnimate();
336 void Compositor::Layout() {
337 // We're sending damage that will be addressed during this composite
338 // cycle, so we don't need to schedule another composite to address it.
339 disable_schedule_composite_
= true;
341 root_layer_
->SendDamagedRects();
342 disable_schedule_composite_
= false;
345 scoped_ptr
<cc::OutputSurface
> Compositor::CreateOutputSurface(bool fallback
) {
346 return context_factory_
->CreateOutputSurface(this, fallback
);
349 void Compositor::DidCommit() {
351 FOR_EACH_OBSERVER(CompositorObserver
,
353 OnCompositingDidCommit(this));
356 void Compositor::DidCommitAndDrawFrame() {
357 base::TimeTicks start_time
= gfx::FrameTime::Now();
358 FOR_EACH_OBSERVER(CompositorObserver
,
360 OnCompositingStarted(this, start_time
));
363 void Compositor::DidCompleteSwapBuffers() {
364 if (compositor_thread_loop_
.get()) {
367 DCHECK_EQ(swap_state_
, SWAP_POSTED
);
369 swap_state_
= SWAP_COMPLETED
;
373 void Compositor::ScheduleComposite() {
374 if (!disable_schedule_composite_
)
378 void Compositor::ScheduleAnimation() {
382 void Compositor::DidPostSwapBuffers() {
383 DCHECK(!compositor_thread_loop_
.get());
384 DCHECK_EQ(swap_state_
, SWAP_NONE
);
385 swap_state_
= SWAP_POSTED
;
388 void Compositor::DidAbortSwapBuffers() {
389 if (!compositor_thread_loop_
.get()) {
390 if (swap_state_
== SWAP_POSTED
) {
392 swap_state_
= SWAP_COMPLETED
;
396 FOR_EACH_OBSERVER(CompositorObserver
,
398 OnCompositingAborted(this));
401 const cc::LayerTreeDebugState
& Compositor::GetLayerTreeDebugState() const {
402 return host_
->debug_state();
405 void Compositor::SetLayerTreeDebugState(
406 const cc::LayerTreeDebugState
& debug_state
) {
407 host_
->SetDebugState(debug_state
);
410 scoped_refptr
<CompositorLock
> Compositor::GetCompositorLock() {
411 if (!compositor_lock_
) {
412 compositor_lock_
= new CompositorLock(this);
413 if (compositor_thread_loop_
.get())
414 host_
->SetDeferCommits(true);
415 FOR_EACH_OBSERVER(CompositorObserver
,
417 OnCompositingLockStateChanged(this));
419 return compositor_lock_
;
422 void Compositor::UnlockCompositor() {
423 DCHECK(compositor_lock_
);
424 compositor_lock_
= NULL
;
425 if (compositor_thread_loop_
.get())
426 host_
->SetDeferCommits(false);
427 FOR_EACH_OBSERVER(CompositorObserver
,
429 OnCompositingLockStateChanged(this));
432 void Compositor::CancelCompositorLock() {
433 if (compositor_lock_
)
434 compositor_lock_
->CancelLock();
437 void Compositor::NotifyEnd() {
439 TRACE_EVENT_ASYNC_END0("ui", "Compositor::Draw", last_ended_frame_
);
440 waiting_on_compositing_end_
= false;
441 if (draw_on_compositing_end_
) {
442 draw_on_compositing_end_
= false;
444 // Call ScheduleDraw() instead of Draw() in order to allow other
445 // CompositorObservers to be notified before starting another
450 CompositorObserver
, observer_list_
, OnCompositingEnded(this));