Added llvm into exceptions as we can't add README.chromium into 3rd party repository
[chromium-blink-merge.git] / ui / compositor / compositor.cc
blob5f2a43bba0f68316d9b4c10c294454c9a0bc1f30
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"
7 #include <algorithm>
8 #include <deque>
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/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/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/gfx/frame_time.h"
34 #include "ui/gfx/hud_font.h"
35 #include "ui/gl/gl_context.h"
36 #include "ui/gl/gl_switches.h"
38 namespace {
40 const double kDefaultRefreshRate = 60.0;
41 const double kTestRefreshRate = 200.0;
43 const int kCompositorLockTimeoutMs = 67;
45 } // namespace
47 namespace ui {
49 CompositorLock::CompositorLock(Compositor* compositor)
50 : compositor_(compositor) {
51 compositor_->task_runner_->PostDelayedTask(
52 FROM_HERE,
53 base::Bind(&CompositorLock::CancelLock, AsWeakPtr()),
54 base::TimeDelta::FromMilliseconds(kCompositorLockTimeoutMs));
57 CompositorLock::~CompositorLock() {
58 CancelLock();
61 void CompositorLock::CancelLock() {
62 if (!compositor_)
63 return;
64 compositor_->UnlockCompositor();
65 compositor_ = NULL;
68 Compositor::Compositor(gfx::AcceleratedWidget widget,
69 ui::ContextFactory* context_factory,
70 scoped_refptr<base::SingleThreadTaskRunner> task_runner)
71 : context_factory_(context_factory),
72 root_layer_(NULL),
73 widget_(widget),
74 surface_id_allocator_(context_factory->CreateSurfaceIdAllocator()),
75 compositor_thread_loop_(context_factory->GetCompositorMessageLoop()),
76 task_runner_(task_runner),
77 vsync_manager_(new CompositorVSyncManager()),
78 device_scale_factor_(0.0f),
79 last_started_frame_(0),
80 last_ended_frame_(0),
81 num_failed_recreate_attempts_(0),
82 disable_schedule_composite_(false),
83 compositor_lock_(NULL),
84 layer_animator_collection_(this),
85 weak_ptr_factory_(this) {
86 root_web_layer_ = cc::Layer::Create();
88 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
90 cc::LayerTreeSettings settings;
91 // When impl-side painting is enabled, this will ensure PictureLayers always
92 // can have LCD text, to match the previous behaviour with ContentLayers,
93 // where LCD-not-allowed notifications were ignored.
94 settings.layers_always_allowed_lcd_text = true;
95 settings.renderer_settings.refresh_rate =
96 context_factory_->DoesCreateTestContexts() ? kTestRefreshRate
97 : kDefaultRefreshRate;
98 settings.main_frame_before_activation_enabled = false;
99 settings.throttle_frame_production =
100 !command_line->HasSwitch(switches::kDisableGpuVsync);
101 #if !defined(OS_MACOSX)
102 settings.renderer_settings.partial_swap_enabled =
103 !command_line->HasSwitch(cc::switches::kUIDisablePartialSwap);
104 #endif
105 #if defined(OS_CHROMEOS)
106 settings.per_tile_painting_enabled = true;
107 #endif
108 #if defined(OS_WIN)
109 settings.disable_hi_res_timer_tasks_on_battery =
110 !context_factory_->DoesCreateTestContexts();
111 settings.renderer_settings.finish_rendering_on_resize = true;
112 #endif
114 // These flags should be mirrored by renderer versions in content/renderer/.
115 settings.initial_debug_state.show_debug_borders =
116 command_line->HasSwitch(cc::switches::kUIShowCompositedLayerBorders);
117 settings.initial_debug_state.show_fps_counter =
118 command_line->HasSwitch(cc::switches::kUIShowFPSCounter);
119 settings.initial_debug_state.show_layer_animation_bounds_rects =
120 command_line->HasSwitch(cc::switches::kUIShowLayerAnimationBounds);
121 settings.initial_debug_state.show_paint_rects =
122 command_line->HasSwitch(switches::kUIShowPaintRects);
123 settings.initial_debug_state.show_property_changed_rects =
124 command_line->HasSwitch(cc::switches::kUIShowPropertyChangedRects);
125 settings.initial_debug_state.show_surface_damage_rects =
126 command_line->HasSwitch(cc::switches::kUIShowSurfaceDamageRects);
127 settings.initial_debug_state.show_screen_space_rects =
128 command_line->HasSwitch(cc::switches::kUIShowScreenSpaceRects);
129 settings.initial_debug_state.show_replica_screen_space_rects =
130 command_line->HasSwitch(cc::switches::kUIShowReplicaScreenSpaceRects);
132 settings.initial_debug_state.SetRecordRenderingStats(
133 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking));
135 settings.impl_side_painting = IsUIImplSidePaintingEnabled();
136 settings.use_zero_copy = IsUIZeroCopyEnabled();
137 settings.hud_typeface = ui::GetHudTypeface();
139 base::TimeTicks before_create = base::TimeTicks::Now();
140 if (compositor_thread_loop_.get()) {
141 host_ = cc::LayerTreeHost::CreateThreaded(
142 this,
143 context_factory_->GetSharedBitmapManager(),
144 context_factory_->GetGpuMemoryBufferManager(),
145 settings,
146 task_runner_,
147 compositor_thread_loop_,
148 nullptr);
149 } else {
150 host_ = cc::LayerTreeHost::CreateSingleThreaded(
151 this,
152 this,
153 context_factory_->GetSharedBitmapManager(),
154 context_factory_->GetGpuMemoryBufferManager(),
155 settings,
156 task_runner_,
157 nullptr);
159 UMA_HISTOGRAM_TIMES("GPU.CreateBrowserCompositor",
160 base::TimeTicks::Now() - before_create);
161 host_->SetRootLayer(root_web_layer_);
162 host_->set_surface_id_namespace(surface_id_allocator_->id_namespace());
163 host_->SetLayerTreeHostClientReady();
166 Compositor::~Compositor() {
167 TRACE_EVENT0("shutdown", "Compositor::destructor");
169 CancelCompositorLock();
170 DCHECK(!compositor_lock_);
172 FOR_EACH_OBSERVER(CompositorObserver, observer_list_,
173 OnCompositingShuttingDown(this));
175 if (root_layer_)
176 root_layer_->SetCompositor(NULL);
178 // Stop all outstanding draws before telling the ContextFactory to tear
179 // down any contexts that the |host_| may rely upon.
180 host_.reset();
182 context_factory_->RemoveCompositor(this);
185 void Compositor::SetOutputSurface(
186 scoped_ptr<cc::OutputSurface> output_surface) {
187 host_->SetOutputSurface(output_surface.Pass());
190 void Compositor::ScheduleDraw() {
191 host_->SetNeedsCommit();
194 void Compositor::SetRootLayer(Layer* root_layer) {
195 if (root_layer_ == root_layer)
196 return;
197 if (root_layer_)
198 root_layer_->SetCompositor(NULL);
199 root_layer_ = root_layer;
200 if (root_layer_ && !root_layer_->GetCompositor())
201 root_layer_->SetCompositor(this);
202 root_web_layer_->RemoveAllChildren();
203 if (root_layer_)
204 root_web_layer_->AddChild(root_layer_->cc_layer());
207 void Compositor::SetHostHasTransparentBackground(
208 bool host_has_transparent_background) {
209 host_->set_has_transparent_background(host_has_transparent_background);
212 void Compositor::ScheduleFullRedraw() {
213 // TODO(enne): Some callers (mac) call this function expecting that it
214 // will also commit. This should probably just redraw the screen
215 // from damage and not commit. ScheduleDraw/ScheduleRedraw need
216 // better names.
217 host_->SetNeedsRedraw();
218 host_->SetNeedsCommit();
221 void Compositor::ScheduleRedrawRect(const gfx::Rect& damage_rect) {
222 // TODO(enne): Make this not commit. See ScheduleFullRedraw.
223 host_->SetNeedsRedrawRect(damage_rect);
224 host_->SetNeedsCommit();
227 void Compositor::FinishAllRendering() {
228 host_->FinishAllRendering();
231 void Compositor::DisableSwapUntilResize() {
232 host_->FinishAllRendering();
233 context_factory_->ResizeDisplay(this, gfx::Size());
236 void Compositor::SetLatencyInfo(const ui::LatencyInfo& latency_info) {
237 scoped_ptr<cc::SwapPromise> swap_promise(
238 new cc::LatencyInfoSwapPromise(latency_info));
239 host_->QueueSwapPromise(swap_promise.Pass());
242 void Compositor::SetScaleAndSize(float scale, const gfx::Size& size_in_pixel) {
243 DCHECK_GT(scale, 0);
244 if (!size_in_pixel.IsEmpty()) {
245 size_ = size_in_pixel;
246 host_->SetViewportSize(size_in_pixel);
247 root_web_layer_->SetBounds(size_in_pixel);
248 context_factory_->ResizeDisplay(this, size_in_pixel);
250 if (device_scale_factor_ != scale) {
251 device_scale_factor_ = scale;
252 host_->SetDeviceScaleFactor(scale);
253 if (root_layer_)
254 root_layer_->OnDeviceScaleFactorChanged(scale);
258 void Compositor::SetBackgroundColor(SkColor color) {
259 host_->set_background_color(color);
260 ScheduleDraw();
263 void Compositor::SetVisible(bool visible) {
264 host_->SetVisible(visible);
267 bool Compositor::IsVisible() {
268 return host_->visible();
271 scoped_refptr<CompositorVSyncManager> Compositor::vsync_manager() const {
272 return vsync_manager_;
275 void Compositor::AddObserver(CompositorObserver* observer) {
276 observer_list_.AddObserver(observer);
279 void Compositor::RemoveObserver(CompositorObserver* observer) {
280 observer_list_.RemoveObserver(observer);
283 bool Compositor::HasObserver(const CompositorObserver* observer) const {
284 return observer_list_.HasObserver(observer);
287 void Compositor::AddAnimationObserver(CompositorAnimationObserver* observer) {
288 animation_observer_list_.AddObserver(observer);
289 host_->SetNeedsAnimate();
292 void Compositor::RemoveAnimationObserver(
293 CompositorAnimationObserver* observer) {
294 animation_observer_list_.RemoveObserver(observer);
297 bool Compositor::HasAnimationObserver(
298 const CompositorAnimationObserver* observer) const {
299 return animation_observer_list_.HasObserver(observer);
302 void Compositor::BeginMainFrame(const cc::BeginFrameArgs& args) {
303 FOR_EACH_OBSERVER(CompositorAnimationObserver,
304 animation_observer_list_,
305 OnAnimationStep(args.frame_time));
306 if (animation_observer_list_.might_have_observers())
307 host_->SetNeedsAnimate();
310 void Compositor::BeginMainFrameNotExpectedSoon() {
313 void Compositor::Layout() {
314 // We're sending damage that will be addressed during this composite
315 // cycle, so we don't need to schedule another composite to address it.
316 disable_schedule_composite_ = true;
317 if (root_layer_)
318 root_layer_->SendDamagedRects();
319 disable_schedule_composite_ = false;
322 void Compositor::RequestNewOutputSurface() {
323 bool fallback =
324 num_failed_recreate_attempts_ >= OUTPUT_SURFACE_RETRIES_BEFORE_FALLBACK;
325 context_factory_->CreateOutputSurface(weak_ptr_factory_.GetWeakPtr(),
326 fallback);
329 void Compositor::DidInitializeOutputSurface() {
330 num_failed_recreate_attempts_ = 0;
333 void Compositor::DidFailToInitializeOutputSurface() {
334 num_failed_recreate_attempts_++;
336 // Tolerate a certain number of recreation failures to work around races
337 // in the output-surface-lost machinery.
338 if (num_failed_recreate_attempts_ >= MAX_OUTPUT_SURFACE_RETRIES)
339 LOG(FATAL) << "Failed to create a fallback OutputSurface.";
341 base::MessageLoop::current()->PostTask(
342 FROM_HERE, base::Bind(&Compositor::RequestNewOutputSurface,
343 weak_ptr_factory_.GetWeakPtr()));
346 void Compositor::DidCommit() {
347 DCHECK(!IsLocked());
348 FOR_EACH_OBSERVER(CompositorObserver,
349 observer_list_,
350 OnCompositingDidCommit(this));
353 void Compositor::DidCommitAndDrawFrame() {
356 void Compositor::DidCompleteSwapBuffers() {
357 // DidPostSwapBuffers is a SingleThreadProxy-only feature. Synthetically
358 // generate OnCompositingStarted messages for the threaded case so that
359 // OnCompositingStarted/OnCompositingEnded messages match.
360 if (compositor_thread_loop_.get()) {
361 base::TimeTicks start_time = gfx::FrameTime::Now();
362 FOR_EACH_OBSERVER(CompositorObserver, observer_list_,
363 OnCompositingStarted(this, start_time));
365 FOR_EACH_OBSERVER(CompositorObserver, observer_list_,
366 OnCompositingEnded(this));
369 void Compositor::DidPostSwapBuffers() {
370 base::TimeTicks start_time = gfx::FrameTime::Now();
371 FOR_EACH_OBSERVER(CompositorObserver, observer_list_,
372 OnCompositingStarted(this, start_time));
375 void Compositor::DidAbortSwapBuffers() {
376 FOR_EACH_OBSERVER(CompositorObserver,
377 observer_list_,
378 OnCompositingAborted(this));
381 const cc::LayerTreeDebugState& Compositor::GetLayerTreeDebugState() const {
382 return host_->debug_state();
385 void Compositor::SetLayerTreeDebugState(
386 const cc::LayerTreeDebugState& debug_state) {
387 host_->SetDebugState(debug_state);
390 const cc::RendererSettings& Compositor::GetRendererSettings() const {
391 return host_->settings().renderer_settings;
394 scoped_refptr<CompositorLock> Compositor::GetCompositorLock() {
395 if (!compositor_lock_) {
396 compositor_lock_ = new CompositorLock(this);
397 host_->SetDeferCommits(true);
398 FOR_EACH_OBSERVER(CompositorObserver,
399 observer_list_,
400 OnCompositingLockStateChanged(this));
402 return compositor_lock_;
405 void Compositor::UnlockCompositor() {
406 DCHECK(compositor_lock_);
407 compositor_lock_ = NULL;
408 host_->SetDeferCommits(false);
409 FOR_EACH_OBSERVER(CompositorObserver,
410 observer_list_,
411 OnCompositingLockStateChanged(this));
414 void Compositor::CancelCompositorLock() {
415 if (compositor_lock_)
416 compositor_lock_->CancelLock();
419 } // namespace ui