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/message_loop/message_loop.h"
13 #include "base/metrics/histogram.h"
14 #include "base/strings/string_util.h"
15 #include "base/sys_info.h"
16 #include "base/trace_event/trace_event.h"
17 #include "cc/base/switches.h"
18 #include "cc/input/input_handler.h"
19 #include "cc/layers/layer.h"
20 #include "cc/output/begin_frame_args.h"
21 #include "cc/output/context_provider.h"
22 #include "cc/output/latency_info_swap_promise.h"
23 #include "cc/scheduler/begin_frame_source.h"
24 #include "cc/surfaces/surface_id_allocator.h"
25 #include "cc/trees/layer_tree_host.h"
26 #include "third_party/skia/include/core/SkBitmap.h"
27 #include "ui/compositor/compositor_observer.h"
28 #include "ui/compositor/compositor_switches.h"
29 #include "ui/compositor/compositor_vsync_manager.h"
30 #include "ui/compositor/dip_util.h"
31 #include "ui/compositor/layer.h"
32 #include "ui/compositor/layer_animator_collection.h"
33 #include "ui/gl/gl_context.h"
34 #include "ui/gl/gl_switches.h"
38 const double kDefaultRefreshRate
= 60.0;
39 const double kTestRefreshRate
= 200.0;
45 CompositorLock::CompositorLock(Compositor
* compositor
)
46 : compositor_(compositor
) {
47 if (compositor_
->locks_will_time_out_
) {
48 compositor_
->task_runner_
->PostDelayedTask(
50 base::Bind(&CompositorLock::CancelLock
, AsWeakPtr()),
51 base::TimeDelta::FromMilliseconds(kCompositorLockTimeoutMs
));
55 CompositorLock::~CompositorLock() {
59 void CompositorLock::CancelLock() {
62 compositor_
->UnlockCompositor();
66 Compositor::Compositor(gfx::AcceleratedWidget widget
,
67 ui::ContextFactory
* context_factory
,
68 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
)
69 : context_factory_(context_factory
),
72 surface_id_allocator_(context_factory
->CreateSurfaceIdAllocator()),
73 task_runner_(task_runner
),
74 vsync_manager_(new CompositorVSyncManager()),
75 device_scale_factor_(0.0f
),
76 last_started_frame_(0),
78 locks_will_time_out_(true),
79 compositor_lock_(NULL
),
80 layer_animator_collection_(this),
81 weak_ptr_factory_(this) {
82 root_web_layer_
= cc::Layer::Create(Layer::UILayerSettings());
84 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
86 cc::LayerTreeSettings settings
;
88 // This will ensure PictureLayers always can have LCD text, to match the
89 // previous behaviour with ContentLayers, where LCD-not-allowed notifications
91 settings
.layers_always_allowed_lcd_text
= true;
92 // Use occlusion to allow more overlapping windows to take less memory.
93 settings
.use_occlusion_for_tile_prioritization
= true;
94 settings
.renderer_settings
.refresh_rate
=
95 context_factory_
->DoesCreateTestContexts() ? kTestRefreshRate
96 : kDefaultRefreshRate
;
97 settings
.main_frame_before_activation_enabled
= false;
98 if (command_line
->HasSwitch(switches::kDisableGpuVsync
)) {
99 std::string display_vsync_string
=
100 command_line
->GetSwitchValueASCII(switches::kDisableGpuVsync
);
101 if (display_vsync_string
== "gpu") {
102 settings
.renderer_settings
.disable_display_vsync
= true;
103 } else if (display_vsync_string
== "beginframe") {
104 settings
.wait_for_beginframe_interval
= false;
106 settings
.renderer_settings
.disable_display_vsync
= true;
107 settings
.wait_for_beginframe_interval
= false;
110 settings
.renderer_settings
.partial_swap_enabled
=
111 !command_line
->HasSwitch(cc::switches::kUIDisablePartialSwap
);
113 settings
.renderer_settings
.finish_rendering_on_resize
= true;
116 // These flags should be mirrored by renderer versions in content/renderer/.
117 settings
.initial_debug_state
.show_debug_borders
=
118 command_line
->HasSwitch(cc::switches::kUIShowCompositedLayerBorders
);
119 settings
.initial_debug_state
.show_fps_counter
=
120 command_line
->HasSwitch(cc::switches::kUIShowFPSCounter
);
121 settings
.initial_debug_state
.show_layer_animation_bounds_rects
=
122 command_line
->HasSwitch(cc::switches::kUIShowLayerAnimationBounds
);
123 settings
.initial_debug_state
.show_paint_rects
=
124 command_line
->HasSwitch(switches::kUIShowPaintRects
);
125 settings
.initial_debug_state
.show_property_changed_rects
=
126 command_line
->HasSwitch(cc::switches::kUIShowPropertyChangedRects
);
127 settings
.initial_debug_state
.show_surface_damage_rects
=
128 command_line
->HasSwitch(cc::switches::kUIShowSurfaceDamageRects
);
129 settings
.initial_debug_state
.show_screen_space_rects
=
130 command_line
->HasSwitch(cc::switches::kUIShowScreenSpaceRects
);
131 settings
.initial_debug_state
.show_replica_screen_space_rects
=
132 command_line
->HasSwitch(cc::switches::kUIShowReplicaScreenSpaceRects
);
134 settings
.initial_debug_state
.SetRecordRenderingStats(
135 command_line
->HasSwitch(cc::switches::kEnableGpuBenchmarking
));
137 settings
.use_display_lists
= true;
139 settings
.use_zero_copy
= IsUIZeroCopyEnabled();
140 settings
.use_one_copy
= IsUIOneCopyEnabled();
142 settings
.renderer_settings
.use_rgba_4444_textures
=
143 command_line
->HasSwitch(switches::kUIEnableRGBA4444Textures
);
145 // Use PERSISTENT_MAP memory buffers to support partial tile raster for
146 // software raster into GpuMemoryBuffers.
147 gfx::BufferUsage usage
= gfx::BufferUsage::PERSISTENT_MAP
;
148 settings
.use_persistent_map_for_gpu_memory_buffers
= true;
150 for (size_t format
= 0;
151 format
< static_cast<size_t>(gfx::BufferFormat::LAST
) + 1; format
++) {
152 DCHECK_GT(settings
.use_image_texture_targets
.size(), format
);
153 settings
.use_image_texture_targets
[format
] =
154 context_factory_
->GetImageTextureTarget(
155 static_cast<gfx::BufferFormat
>(format
), usage
);
158 // Note: gathering of pixel refs is only needed when using multiple
160 settings
.gather_pixel_refs
= false;
162 settings
.use_compositor_animation_timelines
=
163 command_line
->HasSwitch(switches::kUIEnableCompositorAnimationTimelines
);
165 base::TimeTicks before_create
= base::TimeTicks::Now();
167 cc::LayerTreeHost::InitParams params
;
168 params
.client
= this;
169 params
.shared_bitmap_manager
= context_factory_
->GetSharedBitmapManager();
170 params
.gpu_memory_buffer_manager
=
171 context_factory_
->GetGpuMemoryBufferManager();
172 params
.task_graph_runner
= context_factory_
->GetTaskGraphRunner();
173 params
.settings
= &settings
;
174 params
.main_task_runner
= task_runner_
;
175 host_
= cc::LayerTreeHost::CreateSingleThreaded(this, ¶ms
);
176 UMA_HISTOGRAM_TIMES("GPU.CreateBrowserCompositor",
177 base::TimeTicks::Now() - before_create
);
178 host_
->SetRootLayer(root_web_layer_
);
179 host_
->set_surface_id_namespace(surface_id_allocator_
->id_namespace());
180 host_
->SetLayerTreeHostClientReady();
183 Compositor::~Compositor() {
184 TRACE_EVENT0("shutdown", "Compositor::destructor");
186 CancelCompositorLock();
187 DCHECK(!compositor_lock_
);
189 FOR_EACH_OBSERVER(CompositorObserver
, observer_list_
,
190 OnCompositingShuttingDown(this));
192 FOR_EACH_OBSERVER(CompositorAnimationObserver
, animation_observer_list_
,
193 OnCompositingShuttingDown(this));
195 DCHECK(begin_frame_observer_list_
.empty());
198 root_layer_
->ResetCompositor();
200 // Stop all outstanding draws before telling the ContextFactory to tear
201 // down any contexts that the |host_| may rely upon.
204 context_factory_
->RemoveCompositor(this);
207 void Compositor::SetOutputSurface(
208 scoped_ptr
<cc::OutputSurface
> output_surface
) {
209 host_
->SetOutputSurface(output_surface
.Pass());
212 void Compositor::ScheduleDraw() {
213 host_
->SetNeedsCommit();
216 void Compositor::SetRootLayer(Layer
* root_layer
) {
217 if (root_layer_
== root_layer
)
220 root_layer_
->ResetCompositor();
221 root_layer_
= root_layer
;
222 root_web_layer_
->RemoveAllChildren();
224 root_layer_
->SetCompositor(this, root_web_layer_
);
227 void Compositor::SetHostHasTransparentBackground(
228 bool host_has_transparent_background
) {
229 host_
->set_has_transparent_background(host_has_transparent_background
);
232 void Compositor::ScheduleFullRedraw() {
233 // TODO(enne): Some callers (mac) call this function expecting that it
234 // will also commit. This should probably just redraw the screen
235 // from damage and not commit. ScheduleDraw/ScheduleRedraw need
237 host_
->SetNeedsRedraw();
238 host_
->SetNeedsCommit();
241 void Compositor::ScheduleRedrawRect(const gfx::Rect
& damage_rect
) {
242 // TODO(enne): Make this not commit. See ScheduleFullRedraw.
243 host_
->SetNeedsRedrawRect(damage_rect
);
244 host_
->SetNeedsCommit();
247 void Compositor::FinishAllRendering() {
248 host_
->FinishAllRendering();
251 void Compositor::DisableSwapUntilResize() {
252 host_
->FinishAllRendering();
253 context_factory_
->ResizeDisplay(this, gfx::Size());
256 void Compositor::SetLatencyInfo(const ui::LatencyInfo
& latency_info
) {
257 scoped_ptr
<cc::SwapPromise
> swap_promise(
258 new cc::LatencyInfoSwapPromise(latency_info
));
259 host_
->QueueSwapPromise(swap_promise
.Pass());
262 void Compositor::SetScaleAndSize(float scale
, const gfx::Size
& size_in_pixel
) {
264 if (!size_in_pixel
.IsEmpty()) {
265 size_
= size_in_pixel
;
266 host_
->SetViewportSize(size_in_pixel
);
267 root_web_layer_
->SetBounds(size_in_pixel
);
268 context_factory_
->ResizeDisplay(this, size_in_pixel
);
270 if (device_scale_factor_
!= scale
) {
271 device_scale_factor_
= scale
;
272 host_
->SetDeviceScaleFactor(scale
);
274 root_layer_
->OnDeviceScaleFactorChanged(scale
);
278 void Compositor::SetBackgroundColor(SkColor color
) {
279 host_
->set_background_color(color
);
283 void Compositor::SetVisible(bool visible
) {
284 host_
->SetVisible(visible
);
287 bool Compositor::IsVisible() {
288 return host_
->visible();
291 void Compositor::SetAuthoritativeVSyncInterval(
292 const base::TimeDelta
& interval
) {
293 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
294 cc::switches::kEnableBeginFrameScheduling
)) {
295 host_
->SetAuthoritativeVSyncInterval(interval
);
299 vsync_manager_
->SetAuthoritativeVSyncInterval(interval
);
302 scoped_refptr
<CompositorVSyncManager
> Compositor::vsync_manager() const {
303 return vsync_manager_
;
306 void Compositor::AddObserver(CompositorObserver
* observer
) {
307 observer_list_
.AddObserver(observer
);
310 void Compositor::RemoveObserver(CompositorObserver
* observer
) {
311 observer_list_
.RemoveObserver(observer
);
314 bool Compositor::HasObserver(const CompositorObserver
* observer
) const {
315 return observer_list_
.HasObserver(observer
);
318 void Compositor::AddAnimationObserver(CompositorAnimationObserver
* observer
) {
319 animation_observer_list_
.AddObserver(observer
);
320 host_
->SetNeedsAnimate();
323 void Compositor::RemoveAnimationObserver(
324 CompositorAnimationObserver
* observer
) {
325 animation_observer_list_
.RemoveObserver(observer
);
328 bool Compositor::HasAnimationObserver(
329 const CompositorAnimationObserver
* observer
) const {
330 return animation_observer_list_
.HasObserver(observer
);
333 void Compositor::AddBeginFrameObserver(CompositorBeginFrameObserver
* observer
) {
334 DCHECK(std::find(begin_frame_observer_list_
.begin(),
335 begin_frame_observer_list_
.end(), observer
) ==
336 begin_frame_observer_list_
.end());
338 if (begin_frame_observer_list_
.empty())
339 host_
->SetChildrenNeedBeginFrames(true);
341 if (missed_begin_frame_args_
.IsValid())
342 observer
->OnSendBeginFrame(missed_begin_frame_args_
);
344 begin_frame_observer_list_
.push_back(observer
);
347 void Compositor::RemoveBeginFrameObserver(
348 CompositorBeginFrameObserver
* observer
) {
349 auto it
= std::find(begin_frame_observer_list_
.begin(),
350 begin_frame_observer_list_
.end(), observer
);
351 DCHECK(it
!= begin_frame_observer_list_
.end());
352 begin_frame_observer_list_
.erase(it
);
354 if (begin_frame_observer_list_
.empty()) {
355 host_
->SetChildrenNeedBeginFrames(false);
356 missed_begin_frame_args_
= cc::BeginFrameArgs();
360 void Compositor::BeginMainFrame(const cc::BeginFrameArgs
& args
) {
361 FOR_EACH_OBSERVER(CompositorAnimationObserver
,
362 animation_observer_list_
,
363 OnAnimationStep(args
.frame_time
));
364 if (animation_observer_list_
.might_have_observers())
365 host_
->SetNeedsAnimate();
368 void Compositor::BeginMainFrameNotExpectedSoon() {
371 static void SendDamagedRectsRecursive(ui::Layer
* layer
) {
372 layer
->SendDamagedRects();
373 for (auto* child
: layer
->children())
374 SendDamagedRectsRecursive(child
);
377 void Compositor::Layout() {
380 SendDamagedRectsRecursive(root_layer());
383 void Compositor::RequestNewOutputSurface() {
384 context_factory_
->CreateOutputSurface(weak_ptr_factory_
.GetWeakPtr());
387 void Compositor::DidInitializeOutputSurface() {
390 void Compositor::DidFailToInitializeOutputSurface() {
391 // The OutputSurface should already be bound/initialized before being given to
396 void Compositor::DidCommit() {
398 FOR_EACH_OBSERVER(CompositorObserver
,
400 OnCompositingDidCommit(this));
403 void Compositor::DidCommitAndDrawFrame() {
406 void Compositor::DidCompleteSwapBuffers() {
407 FOR_EACH_OBSERVER(CompositorObserver
, observer_list_
,
408 OnCompositingEnded(this));
411 void Compositor::DidPostSwapBuffers() {
412 base::TimeTicks start_time
= base::TimeTicks::Now();
413 FOR_EACH_OBSERVER(CompositorObserver
, observer_list_
,
414 OnCompositingStarted(this, start_time
));
417 void Compositor::DidAbortSwapBuffers() {
418 FOR_EACH_OBSERVER(CompositorObserver
,
420 OnCompositingAborted(this));
423 void Compositor::SendBeginFramesToChildren(const cc::BeginFrameArgs
& args
) {
424 for (auto observer
: begin_frame_observer_list_
)
425 observer
->OnSendBeginFrame(args
);
427 missed_begin_frame_args_
= args
;
428 missed_begin_frame_args_
.type
= cc::BeginFrameArgs::MISSED
;
431 const cc::LayerTreeDebugState
& Compositor::GetLayerTreeDebugState() const {
432 return host_
->debug_state();
435 void Compositor::SetLayerTreeDebugState(
436 const cc::LayerTreeDebugState
& debug_state
) {
437 host_
->SetDebugState(debug_state
);
440 const cc::RendererSettings
& Compositor::GetRendererSettings() const {
441 return host_
->settings().renderer_settings
;
444 scoped_refptr
<CompositorLock
> Compositor::GetCompositorLock() {
445 if (!compositor_lock_
) {
446 compositor_lock_
= new CompositorLock(this);
447 host_
->SetDeferCommits(true);
448 FOR_EACH_OBSERVER(CompositorObserver
,
450 OnCompositingLockStateChanged(this));
452 return compositor_lock_
;
455 void Compositor::UnlockCompositor() {
456 DCHECK(compositor_lock_
);
457 compositor_lock_
= NULL
;
458 host_
->SetDeferCommits(false);
459 FOR_EACH_OBSERVER(CompositorObserver
,
461 OnCompositingLockStateChanged(this));
464 void Compositor::CancelCompositorLock() {
465 if (compositor_lock_
)
466 compositor_lock_
->CancelLock();