Skip direct map from apk check for Samsung Mega.
[chromium-blink-merge.git] / ui / compositor / compositor.cc
blob0e917265415fd26e79e453e48160b41050ca6031
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/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/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/gl/gl_context.h"
35 #include "ui/gl/gl_switches.h"
37 namespace {
39 const double kDefaultRefreshRate = 60.0;
40 const double kTestRefreshRate = 200.0;
42 const int kCompositorLockTimeoutMs = 67;
44 } // namespace
46 namespace ui {
48 CompositorLock::CompositorLock(Compositor* compositor)
49 : compositor_(compositor) {
50 compositor_->task_runner_->PostDelayedTask(
51 FROM_HERE,
52 base::Bind(&CompositorLock::CancelLock, AsWeakPtr()),
53 base::TimeDelta::FromMilliseconds(kCompositorLockTimeoutMs));
56 CompositorLock::~CompositorLock() {
57 CancelLock();
60 void CompositorLock::CancelLock() {
61 if (!compositor_)
62 return;
63 compositor_->UnlockCompositor();
64 compositor_ = NULL;
67 Compositor::Compositor(gfx::AcceleratedWidget widget,
68 ui::ContextFactory* context_factory,
69 scoped_refptr<base::SingleThreadTaskRunner> task_runner)
70 : context_factory_(context_factory),
71 root_layer_(NULL),
72 widget_(widget),
73 surface_id_allocator_(context_factory->CreateSurfaceIdAllocator()),
74 compositor_thread_loop_(context_factory->GetCompositorMessageLoop()),
75 task_runner_(task_runner),
76 vsync_manager_(new CompositorVSyncManager()),
77 device_scale_factor_(0.0f),
78 last_started_frame_(0),
79 last_ended_frame_(0),
80 num_failed_recreate_attempts_(0),
81 disable_schedule_composite_(false),
82 compositor_lock_(NULL),
83 defer_draw_scheduling_(false),
84 waiting_on_compositing_end_(false),
85 draw_on_compositing_end_(false),
86 swap_state_(SWAP_NONE),
87 layer_animator_collection_(this),
88 weak_ptr_factory_(this) {
89 root_web_layer_ = cc::Layer::Create();
91 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
93 cc::LayerTreeSettings settings;
94 // When impl-side painting is enabled, this will ensure PictureLayers always
95 // can have LCD text, to match the previous behaviour with ContentLayers,
96 // where LCD-not-allowed notifications were ignored.
97 settings.layers_always_allowed_lcd_text = true;
98 settings.renderer_settings.refresh_rate =
99 context_factory_->DoesCreateTestContexts() ? kTestRefreshRate
100 : kDefaultRefreshRate;
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.renderer_settings.partial_swap_enabled =
106 !command_line->HasSwitch(cc::switches::kUIDisablePartialSwap);
107 #endif
108 #if defined(OS_CHROMEOS)
109 settings.per_tile_painting_enabled = true;
110 #endif
111 #if defined(OS_WIN)
112 settings.disable_hi_res_timer_tasks_on_battery = true;
113 settings.renderer_settings.finish_rendering_on_resize = true;
114 #endif
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);
133 settings.initial_debug_state.show_occluding_rects =
134 command_line->HasSwitch(cc::switches::kUIShowOccludingRects);
135 settings.initial_debug_state.show_non_occluding_rects =
136 command_line->HasSwitch(cc::switches::kUIShowNonOccludingRects);
138 settings.initial_debug_state.SetRecordRenderingStats(
139 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking));
141 settings.impl_side_painting = IsUIImplSidePaintingEnabled();
142 settings.use_zero_copy = IsUIZeroCopyEnabled();
143 settings.single_thread_proxy_scheduler = false;
145 base::TimeTicks before_create = base::TimeTicks::Now();
146 if (compositor_thread_loop_.get()) {
147 host_ = cc::LayerTreeHost::CreateThreaded(
148 this,
149 context_factory_->GetSharedBitmapManager(),
150 context_factory_->GetGpuMemoryBufferManager(),
151 settings,
152 task_runner_,
153 compositor_thread_loop_,
154 nullptr);
155 } else {
156 host_ = cc::LayerTreeHost::CreateSingleThreaded(
157 this,
158 this,
159 context_factory_->GetSharedBitmapManager(),
160 context_factory_->GetGpuMemoryBufferManager(),
161 settings,
162 task_runner_,
163 nullptr);
165 UMA_HISTOGRAM_TIMES("GPU.CreateBrowserCompositor",
166 base::TimeTicks::Now() - before_create);
167 host_->SetRootLayer(root_web_layer_);
168 host_->set_surface_id_namespace(surface_id_allocator_->id_namespace());
169 host_->SetLayerTreeHostClientReady();
172 Compositor::~Compositor() {
173 TRACE_EVENT0("shutdown", "Compositor::destructor");
175 CancelCompositorLock();
176 DCHECK(!compositor_lock_);
178 if (root_layer_)
179 root_layer_->SetCompositor(NULL);
181 // Stop all outstanding draws before telling the ContextFactory to tear
182 // down any contexts that the |host_| may rely upon.
183 host_.reset();
185 context_factory_->RemoveCompositor(this);
188 void Compositor::SetOutputSurface(
189 scoped_ptr<cc::OutputSurface> output_surface) {
190 host_->SetOutputSurface(output_surface.Pass());
193 void Compositor::ScheduleDraw() {
194 if (compositor_thread_loop_.get()) {
195 host_->SetNeedsCommit();
196 } else if (!defer_draw_scheduling_) {
197 defer_draw_scheduling_ = true;
198 task_runner_->PostTask(
199 FROM_HERE,
200 base::Bind(&Compositor::Draw, weak_ptr_factory_.GetWeakPtr()));
204 void Compositor::SetRootLayer(Layer* root_layer) {
205 if (root_layer_ == root_layer)
206 return;
207 if (root_layer_)
208 root_layer_->SetCompositor(NULL);
209 root_layer_ = root_layer;
210 if (root_layer_ && !root_layer_->GetCompositor())
211 root_layer_->SetCompositor(this);
212 root_web_layer_->RemoveAllChildren();
213 if (root_layer_)
214 root_web_layer_->AddChild(root_layer_->cc_layer());
217 void Compositor::SetHostHasTransparentBackground(
218 bool host_has_transparent_background) {
219 host_->set_has_transparent_background(host_has_transparent_background);
222 void Compositor::Draw() {
223 DCHECK(!compositor_thread_loop_.get());
225 defer_draw_scheduling_ = false;
226 if (waiting_on_compositing_end_) {
227 draw_on_compositing_end_ = true;
228 return;
230 if (!root_layer_)
231 return;
233 TRACE_EVENT_ASYNC_BEGIN0("ui", "Compositor::Draw", last_started_frame_ + 1);
235 DCHECK_NE(swap_state_, SWAP_POSTED);
236 swap_state_ = SWAP_NONE;
238 waiting_on_compositing_end_ = true;
239 last_started_frame_++;
240 if (!IsLocked()) {
241 // TODO(nduca): Temporary while compositor calls
242 // compositeImmediately() directly.
243 cc::BeginFrameArgs args = cc::BeginFrameArgs::Create(
244 BEGINFRAME_FROM_HERE, gfx::FrameTime::Now(), base::TimeTicks(),
245 cc::BeginFrameArgs::DefaultInterval(), cc::BeginFrameArgs::SYNCHRONOUS);
246 BeginMainFrame(args);
247 host_->Composite(args.frame_time);
249 if (swap_state_ == SWAP_NONE)
250 NotifyEnd();
253 void Compositor::ScheduleFullRedraw() {
254 host_->SetNeedsRedraw();
257 void Compositor::ScheduleRedrawRect(const gfx::Rect& damage_rect) {
258 host_->SetNeedsRedrawRect(damage_rect);
261 void Compositor::DisableSwapUntilResize() {
262 host_->FinishAllRendering();
263 context_factory_->ResizeDisplay(this, gfx::Size());
266 void Compositor::SetLatencyInfo(const ui::LatencyInfo& latency_info) {
267 scoped_ptr<cc::SwapPromise> swap_promise(
268 new cc::LatencyInfoSwapPromise(latency_info));
269 host_->QueueSwapPromise(swap_promise.Pass());
272 void Compositor::SetScaleAndSize(float scale, const gfx::Size& size_in_pixel) {
273 DCHECK_GT(scale, 0);
274 if (!size_in_pixel.IsEmpty()) {
275 size_ = size_in_pixel;
276 host_->SetViewportSize(size_in_pixel);
277 root_web_layer_->SetBounds(size_in_pixel);
278 context_factory_->ResizeDisplay(this, size_in_pixel);
280 if (device_scale_factor_ != scale) {
281 device_scale_factor_ = scale;
282 host_->SetDeviceScaleFactor(scale);
283 if (root_layer_)
284 root_layer_->OnDeviceScaleFactorChanged(scale);
288 void Compositor::SetBackgroundColor(SkColor color) {
289 host_->set_background_color(color);
290 ScheduleDraw();
293 void Compositor::SetVisible(bool visible) {
294 host_->SetVisible(visible);
297 scoped_refptr<CompositorVSyncManager> Compositor::vsync_manager() const {
298 return vsync_manager_;
301 void Compositor::AddObserver(CompositorObserver* observer) {
302 #if defined(OS_MACOSX)
303 // Debugging instrumentation for crbug.com/401630.
304 // TODO(ccameron): remove this.
305 CHECK(observer);
306 if (!observer_list_.HasObserver(observer))
307 observer->observing_count_ += 1;
308 #endif
310 observer_list_.AddObserver(observer);
313 void Compositor::RemoveObserver(CompositorObserver* observer) {
314 #if defined(OS_MACOSX)
315 // Debugging instrumentation for crbug.com/401630.
316 // TODO(ccameron): remove this.
317 if (observer_list_.HasObserver(observer))
318 observer->observing_count_ -= 1;
319 #endif
321 observer_list_.RemoveObserver(observer);
324 bool Compositor::HasObserver(const CompositorObserver* observer) const {
325 return observer_list_.HasObserver(observer);
328 void Compositor::AddAnimationObserver(CompositorAnimationObserver* observer) {
329 animation_observer_list_.AddObserver(observer);
330 host_->SetNeedsAnimate();
333 void Compositor::RemoveAnimationObserver(
334 CompositorAnimationObserver* observer) {
335 animation_observer_list_.RemoveObserver(observer);
338 bool Compositor::HasAnimationObserver(
339 const CompositorAnimationObserver* observer) const {
340 return animation_observer_list_.HasObserver(observer);
343 void Compositor::BeginMainFrame(const cc::BeginFrameArgs& args) {
344 FOR_EACH_OBSERVER(CompositorAnimationObserver,
345 animation_observer_list_,
346 OnAnimationStep(args.frame_time));
347 if (animation_observer_list_.might_have_observers())
348 host_->SetNeedsAnimate();
351 void Compositor::Layout() {
352 // We're sending damage that will be addressed during this composite
353 // cycle, so we don't need to schedule another composite to address it.
354 disable_schedule_composite_ = true;
355 if (root_layer_)
356 root_layer_->SendDamagedRects();
357 disable_schedule_composite_ = false;
360 void Compositor::RequestNewOutputSurface() {
361 bool fallback =
362 num_failed_recreate_attempts_ >= OUTPUT_SURFACE_RETRIES_BEFORE_FALLBACK;
363 context_factory_->CreateOutputSurface(weak_ptr_factory_.GetWeakPtr(),
364 fallback);
367 void Compositor::DidInitializeOutputSurface() {
368 num_failed_recreate_attempts_ = 0;
371 void Compositor::DidFailToInitializeOutputSurface() {
372 num_failed_recreate_attempts_++;
374 // Tolerate a certain number of recreation failures to work around races
375 // in the output-surface-lost machinery.
376 if (num_failed_recreate_attempts_ >= MAX_OUTPUT_SURFACE_RETRIES)
377 LOG(FATAL) << "Failed to create a fallback OutputSurface.";
379 base::MessageLoop::current()->PostTask(
380 FROM_HERE, base::Bind(&Compositor::RequestNewOutputSurface,
381 weak_ptr_factory_.GetWeakPtr()));
384 void Compositor::DidCommit() {
385 DCHECK(!IsLocked());
386 FOR_EACH_OBSERVER(CompositorObserver,
387 observer_list_,
388 OnCompositingDidCommit(this));
391 void Compositor::DidCommitAndDrawFrame() {
392 base::TimeTicks start_time = gfx::FrameTime::Now();
393 FOR_EACH_OBSERVER(CompositorObserver,
394 observer_list_,
395 OnCompositingStarted(this, start_time));
398 void Compositor::DidCompleteSwapBuffers() {
399 if (compositor_thread_loop_.get()) {
400 NotifyEnd();
401 } else {
402 DCHECK_EQ(swap_state_, SWAP_POSTED);
403 NotifyEnd();
404 swap_state_ = SWAP_COMPLETED;
408 void Compositor::ScheduleComposite() {
409 if (!disable_schedule_composite_)
410 ScheduleDraw();
413 void Compositor::ScheduleAnimation() {
414 ScheduleComposite();
417 void Compositor::DidPostSwapBuffers() {
418 DCHECK(!compositor_thread_loop_.get());
419 DCHECK_EQ(swap_state_, SWAP_NONE);
420 swap_state_ = SWAP_POSTED;
423 void Compositor::DidAbortSwapBuffers() {
424 if (!compositor_thread_loop_.get()) {
425 if (swap_state_ == SWAP_POSTED) {
426 NotifyEnd();
427 swap_state_ = SWAP_COMPLETED;
431 FOR_EACH_OBSERVER(CompositorObserver,
432 observer_list_,
433 OnCompositingAborted(this));
436 const cc::LayerTreeDebugState& Compositor::GetLayerTreeDebugState() const {
437 return host_->debug_state();
440 void Compositor::SetLayerTreeDebugState(
441 const cc::LayerTreeDebugState& debug_state) {
442 host_->SetDebugState(debug_state);
445 const cc::RendererSettings& Compositor::GetRendererSettings() const {
446 return host_->settings().renderer_settings;
449 scoped_refptr<CompositorLock> Compositor::GetCompositorLock() {
450 if (!compositor_lock_) {
451 compositor_lock_ = new CompositorLock(this);
452 if (compositor_thread_loop_.get())
453 host_->SetDeferCommits(true);
454 FOR_EACH_OBSERVER(CompositorObserver,
455 observer_list_,
456 OnCompositingLockStateChanged(this));
458 return compositor_lock_;
461 void Compositor::UnlockCompositor() {
462 DCHECK(compositor_lock_);
463 compositor_lock_ = NULL;
464 if (compositor_thread_loop_.get())
465 host_->SetDeferCommits(false);
466 FOR_EACH_OBSERVER(CompositorObserver,
467 observer_list_,
468 OnCompositingLockStateChanged(this));
471 void Compositor::CancelCompositorLock() {
472 if (compositor_lock_)
473 compositor_lock_->CancelLock();
476 void Compositor::NotifyEnd() {
477 last_ended_frame_++;
478 TRACE_EVENT_ASYNC_END0("ui", "Compositor::Draw", last_ended_frame_);
479 waiting_on_compositing_end_ = false;
480 if (draw_on_compositing_end_) {
481 draw_on_compositing_end_ = false;
483 // Call ScheduleDraw() instead of Draw() in order to allow other
484 // CompositorObservers to be notified before starting another
485 // draw cycle.
486 ScheduleDraw();
488 FOR_EACH_OBSERVER(
489 CompositorObserver, observer_list_, OnCompositingEnded(this));
492 } // namespace ui