Update V8 to version 4.7.45.
[chromium-blink-merge.git] / ui / compositor / compositor.cc
blob79c2fce633cc0275d01a8fc35518a1db269e9b22
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/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"
36 namespace {
38 const double kDefaultRefreshRate = 60.0;
39 const double kTestRefreshRate = 200.0;
41 } // namespace
43 namespace ui {
45 CompositorLock::CompositorLock(Compositor* compositor)
46 : compositor_(compositor) {
47 if (compositor_->locks_will_time_out_) {
48 compositor_->task_runner_->PostDelayedTask(
49 FROM_HERE,
50 base::Bind(&CompositorLock::CancelLock, AsWeakPtr()),
51 base::TimeDelta::FromMilliseconds(kCompositorLockTimeoutMs));
55 CompositorLock::~CompositorLock() {
56 CancelLock();
59 void CompositorLock::CancelLock() {
60 if (!compositor_)
61 return;
62 compositor_->UnlockCompositor();
63 compositor_ = NULL;
66 Compositor::Compositor(ui::ContextFactory* context_factory,
67 scoped_refptr<base::SingleThreadTaskRunner> task_runner)
68 : context_factory_(context_factory),
69 root_layer_(NULL),
70 widget_(gfx::kNullAcceleratedWidget),
71 surface_id_allocator_(context_factory->CreateSurfaceIdAllocator()),
72 task_runner_(task_runner),
73 vsync_manager_(new CompositorVSyncManager()),
74 device_scale_factor_(0.0f),
75 last_started_frame_(0),
76 last_ended_frame_(0),
77 locks_will_time_out_(true),
78 compositor_lock_(NULL),
79 layer_animator_collection_(this),
80 weak_ptr_factory_(this) {
81 root_web_layer_ = cc::Layer::Create(Layer::UILayerSettings());
83 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
85 cc::LayerTreeSettings settings;
87 // This will ensure PictureLayers always can have LCD text, to match the
88 // previous behaviour with ContentLayers, where LCD-not-allowed notifications
89 // were ignored.
90 settings.layers_always_allowed_lcd_text = true;
91 // Use occlusion to allow more overlapping windows to take less memory.
92 settings.use_occlusion_for_tile_prioritization = true;
93 settings.renderer_settings.refresh_rate =
94 context_factory_->DoesCreateTestContexts() ? kTestRefreshRate
95 : kDefaultRefreshRate;
96 settings.main_frame_before_activation_enabled = false;
97 if (command_line->HasSwitch(switches::kDisableGpuVsync)) {
98 std::string display_vsync_string =
99 command_line->GetSwitchValueASCII(switches::kDisableGpuVsync);
100 if (display_vsync_string == "gpu") {
101 settings.renderer_settings.disable_display_vsync = true;
102 } else if (display_vsync_string == "beginframe") {
103 settings.wait_for_beginframe_interval = false;
104 } else {
105 settings.renderer_settings.disable_display_vsync = true;
106 settings.wait_for_beginframe_interval = false;
109 settings.renderer_settings.partial_swap_enabled =
110 !command_line->HasSwitch(cc::switches::kUIDisablePartialSwap);
111 #if defined(OS_WIN)
112 settings.renderer_settings.finish_rendering_on_resize = true;
113 #elif defined(OS_MACOSX)
114 settings.renderer_settings.delay_releasing_overlay_resources = true;
115 #endif
117 // These flags should be mirrored by renderer versions in content/renderer/.
118 settings.initial_debug_state.show_debug_borders =
119 command_line->HasSwitch(cc::switches::kUIShowCompositedLayerBorders);
120 settings.initial_debug_state.show_fps_counter =
121 command_line->HasSwitch(cc::switches::kUIShowFPSCounter);
122 settings.initial_debug_state.show_layer_animation_bounds_rects =
123 command_line->HasSwitch(cc::switches::kUIShowLayerAnimationBounds);
124 settings.initial_debug_state.show_paint_rects =
125 command_line->HasSwitch(switches::kUIShowPaintRects);
126 settings.initial_debug_state.show_property_changed_rects =
127 command_line->HasSwitch(cc::switches::kUIShowPropertyChangedRects);
128 settings.initial_debug_state.show_surface_damage_rects =
129 command_line->HasSwitch(cc::switches::kUIShowSurfaceDamageRects);
130 settings.initial_debug_state.show_screen_space_rects =
131 command_line->HasSwitch(cc::switches::kUIShowScreenSpaceRects);
132 settings.initial_debug_state.show_replica_screen_space_rects =
133 command_line->HasSwitch(cc::switches::kUIShowReplicaScreenSpaceRects);
135 settings.initial_debug_state.SetRecordRenderingStats(
136 command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking));
138 settings.use_display_lists = true;
140 settings.use_zero_copy = IsUIZeroCopyEnabled();
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 images is only needed when using multiple
159 // raster threads.
160 settings.gather_images = 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, &params);
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());
182 Compositor::~Compositor() {
183 TRACE_EVENT0("shutdown", "Compositor::destructor");
185 CancelCompositorLock();
186 DCHECK(!compositor_lock_);
188 FOR_EACH_OBSERVER(CompositorObserver, observer_list_,
189 OnCompositingShuttingDown(this));
191 FOR_EACH_OBSERVER(CompositorAnimationObserver, animation_observer_list_,
192 OnCompositingShuttingDown(this));
194 DCHECK(begin_frame_observer_list_.empty());
196 if (root_layer_)
197 root_layer_->ResetCompositor();
199 // Stop all outstanding draws before telling the ContextFactory to tear
200 // down any contexts that the |host_| may rely upon.
201 host_.reset();
203 context_factory_->RemoveCompositor(this);
206 void Compositor::SetOutputSurface(
207 scoped_ptr<cc::OutputSurface> output_surface) {
208 host_->SetOutputSurface(output_surface.Pass());
211 void Compositor::ScheduleDraw() {
212 host_->SetNeedsCommit();
215 void Compositor::SetRootLayer(Layer* root_layer) {
216 if (root_layer_ == root_layer)
217 return;
218 if (root_layer_)
219 root_layer_->ResetCompositor();
220 root_layer_ = root_layer;
221 root_web_layer_->RemoveAllChildren();
222 if (root_layer_)
223 root_layer_->SetCompositor(this, root_web_layer_);
226 void Compositor::SetHostHasTransparentBackground(
227 bool host_has_transparent_background) {
228 host_->set_has_transparent_background(host_has_transparent_background);
231 void Compositor::ScheduleFullRedraw() {
232 // TODO(enne): Some callers (mac) call this function expecting that it
233 // will also commit. This should probably just redraw the screen
234 // from damage and not commit. ScheduleDraw/ScheduleRedraw need
235 // better names.
236 host_->SetNeedsRedraw();
237 host_->SetNeedsCommit();
240 void Compositor::ScheduleRedrawRect(const gfx::Rect& damage_rect) {
241 // TODO(enne): Make this not commit. See ScheduleFullRedraw.
242 host_->SetNeedsRedrawRect(damage_rect);
243 host_->SetNeedsCommit();
246 void Compositor::FinishAllRendering() {
247 host_->FinishAllRendering();
250 void Compositor::DisableSwapUntilResize() {
251 host_->FinishAllRendering();
252 context_factory_->ResizeDisplay(this, gfx::Size());
255 void Compositor::SetLatencyInfo(const ui::LatencyInfo& latency_info) {
256 scoped_ptr<cc::SwapPromise> swap_promise(
257 new cc::LatencyInfoSwapPromise(latency_info));
258 host_->QueueSwapPromise(swap_promise.Pass());
261 void Compositor::SetScaleAndSize(float scale, const gfx::Size& size_in_pixel) {
262 DCHECK_GT(scale, 0);
263 if (!size_in_pixel.IsEmpty()) {
264 size_ = size_in_pixel;
265 host_->SetViewportSize(size_in_pixel);
266 root_web_layer_->SetBounds(size_in_pixel);
267 context_factory_->ResizeDisplay(this, size_in_pixel);
269 if (device_scale_factor_ != scale) {
270 device_scale_factor_ = scale;
271 host_->SetDeviceScaleFactor(scale);
272 if (root_layer_)
273 root_layer_->OnDeviceScaleFactorChanged(scale);
277 void Compositor::SetBackgroundColor(SkColor color) {
278 host_->set_background_color(color);
279 ScheduleDraw();
282 void Compositor::SetVisible(bool visible) {
283 host_->SetVisible(visible);
286 bool Compositor::IsVisible() {
287 return host_->visible();
290 void Compositor::SetAuthoritativeVSyncInterval(
291 const base::TimeDelta& interval) {
292 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
293 cc::switches::kEnableBeginFrameScheduling)) {
294 host_->SetAuthoritativeVSyncInterval(interval);
295 return;
298 vsync_manager_->SetAuthoritativeVSyncInterval(interval);
301 void Compositor::SetAcceleratedWidgetAndStartCompositor(
302 gfx::AcceleratedWidget widget) {
303 // This function should only get called once.
304 DCHECK_EQ(gfx::kNullAcceleratedWidget, widget_);
305 widget_ = widget;
306 host_->SetLayerTreeHostClientReady();
309 scoped_refptr<CompositorVSyncManager> Compositor::vsync_manager() const {
310 return vsync_manager_;
313 void Compositor::AddObserver(CompositorObserver* observer) {
314 observer_list_.AddObserver(observer);
317 void Compositor::RemoveObserver(CompositorObserver* observer) {
318 observer_list_.RemoveObserver(observer);
321 bool Compositor::HasObserver(const CompositorObserver* observer) const {
322 return observer_list_.HasObserver(observer);
325 void Compositor::AddAnimationObserver(CompositorAnimationObserver* observer) {
326 animation_observer_list_.AddObserver(observer);
327 host_->SetNeedsAnimate();
330 void Compositor::RemoveAnimationObserver(
331 CompositorAnimationObserver* observer) {
332 animation_observer_list_.RemoveObserver(observer);
335 bool Compositor::HasAnimationObserver(
336 const CompositorAnimationObserver* observer) const {
337 return animation_observer_list_.HasObserver(observer);
340 void Compositor::AddBeginFrameObserver(CompositorBeginFrameObserver* observer) {
341 DCHECK(std::find(begin_frame_observer_list_.begin(),
342 begin_frame_observer_list_.end(), observer) ==
343 begin_frame_observer_list_.end());
345 if (begin_frame_observer_list_.empty())
346 host_->SetChildrenNeedBeginFrames(true);
348 if (missed_begin_frame_args_.IsValid())
349 observer->OnSendBeginFrame(missed_begin_frame_args_);
351 begin_frame_observer_list_.push_back(observer);
354 void Compositor::RemoveBeginFrameObserver(
355 CompositorBeginFrameObserver* observer) {
356 auto it = std::find(begin_frame_observer_list_.begin(),
357 begin_frame_observer_list_.end(), observer);
358 DCHECK(it != begin_frame_observer_list_.end());
359 begin_frame_observer_list_.erase(it);
361 if (begin_frame_observer_list_.empty()) {
362 host_->SetChildrenNeedBeginFrames(false);
363 missed_begin_frame_args_ = cc::BeginFrameArgs();
367 void Compositor::BeginMainFrame(const cc::BeginFrameArgs& args) {
368 FOR_EACH_OBSERVER(CompositorAnimationObserver,
369 animation_observer_list_,
370 OnAnimationStep(args.frame_time));
371 if (animation_observer_list_.might_have_observers())
372 host_->SetNeedsAnimate();
375 void Compositor::BeginMainFrameNotExpectedSoon() {
378 static void SendDamagedRectsRecursive(ui::Layer* layer) {
379 layer->SendDamagedRects();
380 for (auto* child : layer->children())
381 SendDamagedRectsRecursive(child);
384 void Compositor::Layout() {
385 if (!root_layer())
386 return;
387 SendDamagedRectsRecursive(root_layer());
390 void Compositor::RequestNewOutputSurface() {
391 context_factory_->CreateOutputSurface(weak_ptr_factory_.GetWeakPtr());
394 void Compositor::DidInitializeOutputSurface() {
397 void Compositor::DidFailToInitializeOutputSurface() {
398 // The OutputSurface should already be bound/initialized before being given to
399 // the Compositor.
400 NOTREACHED();
403 void Compositor::DidCommit() {
404 DCHECK(!IsLocked());
405 FOR_EACH_OBSERVER(CompositorObserver,
406 observer_list_,
407 OnCompositingDidCommit(this));
410 void Compositor::DidCommitAndDrawFrame() {
413 void Compositor::DidCompleteSwapBuffers() {
414 FOR_EACH_OBSERVER(CompositorObserver, observer_list_,
415 OnCompositingEnded(this));
418 void Compositor::DidPostSwapBuffers() {
419 base::TimeTicks start_time = base::TimeTicks::Now();
420 FOR_EACH_OBSERVER(CompositorObserver, observer_list_,
421 OnCompositingStarted(this, start_time));
424 void Compositor::DidAbortSwapBuffers() {
425 FOR_EACH_OBSERVER(CompositorObserver,
426 observer_list_,
427 OnCompositingAborted(this));
430 void Compositor::SendBeginFramesToChildren(const cc::BeginFrameArgs& args) {
431 for (auto observer : begin_frame_observer_list_)
432 observer->OnSendBeginFrame(args);
434 missed_begin_frame_args_ = args;
435 missed_begin_frame_args_.type = cc::BeginFrameArgs::MISSED;
438 const cc::LayerTreeDebugState& Compositor::GetLayerTreeDebugState() const {
439 return host_->debug_state();
442 void Compositor::SetLayerTreeDebugState(
443 const cc::LayerTreeDebugState& debug_state) {
444 host_->SetDebugState(debug_state);
447 const cc::RendererSettings& Compositor::GetRendererSettings() const {
448 return host_->settings().renderer_settings;
451 scoped_refptr<CompositorLock> Compositor::GetCompositorLock() {
452 if (!compositor_lock_) {
453 compositor_lock_ = new CompositorLock(this);
454 host_->SetDeferCommits(true);
455 FOR_EACH_OBSERVER(CompositorObserver,
456 observer_list_,
457 OnCompositingLockStateChanged(this));
459 return compositor_lock_;
462 void Compositor::UnlockCompositor() {
463 DCHECK(compositor_lock_);
464 compositor_lock_ = NULL;
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 } // namespace ui