Linux: Depend on liberation-fonts package for RPMs.
[chromium-blink-merge.git] / ui / compositor / compositor.cc
blobae500efeb9793083ef0b611a7bdc5c77f8afd78d
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_zero_copy = IsUIZeroCopyEnabled();
140 settings.renderer_settings.use_rgba_4444_textures =
141 command_line->HasSwitch(switches::kUIEnableRGBA4444Textures);
143 // Use PERSISTENT_MAP memory buffers to support partial tile raster for
144 // software raster into GpuMemoryBuffers.
145 gfx::BufferUsage usage = gfx::BufferUsage::PERSISTENT_MAP;
146 settings.use_persistent_map_for_gpu_memory_buffers = true;
148 for (size_t format = 0;
149 format < static_cast<size_t>(gfx::BufferFormat::LAST) + 1; format++) {
150 DCHECK_GT(settings.use_image_texture_targets.size(), format);
151 settings.use_image_texture_targets[format] =
152 context_factory_->GetImageTextureTarget(
153 static_cast<gfx::BufferFormat>(format), usage);
156 // Note: gathering of images is only needed when using multiple
157 // raster threads.
158 settings.gather_images = false;
160 settings.use_compositor_animation_timelines =
161 command_line->HasSwitch(switches::kUIEnableCompositorAnimationTimelines);
163 base::TimeTicks before_create = base::TimeTicks::Now();
165 cc::LayerTreeHost::InitParams params;
166 params.client = this;
167 params.shared_bitmap_manager = context_factory_->GetSharedBitmapManager();
168 params.gpu_memory_buffer_manager =
169 context_factory_->GetGpuMemoryBufferManager();
170 params.task_graph_runner = context_factory_->GetTaskGraphRunner();
171 params.settings = &settings;
172 params.main_task_runner = task_runner_;
173 host_ = cc::LayerTreeHost::CreateSingleThreaded(this, &params);
174 UMA_HISTOGRAM_TIMES("GPU.CreateBrowserCompositor",
175 base::TimeTicks::Now() - before_create);
176 host_->SetRootLayer(root_web_layer_);
177 host_->set_surface_id_namespace(surface_id_allocator_->id_namespace());
180 Compositor::~Compositor() {
181 TRACE_EVENT0("shutdown", "Compositor::destructor");
183 CancelCompositorLock();
184 DCHECK(!compositor_lock_);
186 FOR_EACH_OBSERVER(CompositorObserver, observer_list_,
187 OnCompositingShuttingDown(this));
189 FOR_EACH_OBSERVER(CompositorAnimationObserver, animation_observer_list_,
190 OnCompositingShuttingDown(this));
192 DCHECK(begin_frame_observer_list_.empty());
194 if (root_layer_)
195 root_layer_->ResetCompositor();
197 // Stop all outstanding draws before telling the ContextFactory to tear
198 // down any contexts that the |host_| may rely upon.
199 host_.reset();
201 context_factory_->RemoveCompositor(this);
204 void Compositor::SetOutputSurface(
205 scoped_ptr<cc::OutputSurface> output_surface) {
206 host_->SetOutputSurface(output_surface.Pass());
209 void Compositor::ScheduleDraw() {
210 host_->SetNeedsCommit();
213 void Compositor::SetRootLayer(Layer* root_layer) {
214 if (root_layer_ == root_layer)
215 return;
216 if (root_layer_)
217 root_layer_->ResetCompositor();
218 root_layer_ = root_layer;
219 root_web_layer_->RemoveAllChildren();
220 if (root_layer_)
221 root_layer_->SetCompositor(this, root_web_layer_);
224 void Compositor::SetHostHasTransparentBackground(
225 bool host_has_transparent_background) {
226 host_->set_has_transparent_background(host_has_transparent_background);
229 void Compositor::ScheduleFullRedraw() {
230 // TODO(enne): Some callers (mac) call this function expecting that it
231 // will also commit. This should probably just redraw the screen
232 // from damage and not commit. ScheduleDraw/ScheduleRedraw need
233 // better names.
234 host_->SetNeedsRedraw();
235 host_->SetNeedsCommit();
238 void Compositor::ScheduleRedrawRect(const gfx::Rect& damage_rect) {
239 // TODO(enne): Make this not commit. See ScheduleFullRedraw.
240 host_->SetNeedsRedrawRect(damage_rect);
241 host_->SetNeedsCommit();
244 void Compositor::FinishAllRendering() {
245 host_->FinishAllRendering();
248 void Compositor::DisableSwapUntilResize() {
249 host_->FinishAllRendering();
250 context_factory_->ResizeDisplay(this, gfx::Size());
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) {
260 DCHECK_GT(scale, 0);
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);
265 context_factory_->ResizeDisplay(this, size_in_pixel);
267 if (device_scale_factor_ != scale) {
268 device_scale_factor_ = scale;
269 host_->SetDeviceScaleFactor(scale);
270 if (root_layer_)
271 root_layer_->OnDeviceScaleFactorChanged(scale);
275 void Compositor::SetBackgroundColor(SkColor color) {
276 host_->set_background_color(color);
277 ScheduleDraw();
280 void Compositor::SetVisible(bool visible) {
281 host_->SetVisible(visible);
284 bool Compositor::IsVisible() {
285 return host_->visible();
288 void Compositor::SetAuthoritativeVSyncInterval(
289 const base::TimeDelta& interval) {
290 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
291 cc::switches::kEnableBeginFrameScheduling)) {
292 host_->SetAuthoritativeVSyncInterval(interval);
293 return;
296 vsync_manager_->SetAuthoritativeVSyncInterval(interval);
299 void Compositor::SetAcceleratedWidgetAndStartCompositor(
300 gfx::AcceleratedWidget widget) {
301 // This function should only get called once.
302 DCHECK_EQ(gfx::kNullAcceleratedWidget, widget_);
303 widget_ = widget;
304 host_->SetLayerTreeHostClientReady();
307 scoped_refptr<CompositorVSyncManager> Compositor::vsync_manager() const {
308 return vsync_manager_;
311 void Compositor::AddObserver(CompositorObserver* observer) {
312 observer_list_.AddObserver(observer);
315 void Compositor::RemoveObserver(CompositorObserver* observer) {
316 observer_list_.RemoveObserver(observer);
319 bool Compositor::HasObserver(const CompositorObserver* observer) const {
320 return observer_list_.HasObserver(observer);
323 void Compositor::AddAnimationObserver(CompositorAnimationObserver* observer) {
324 animation_observer_list_.AddObserver(observer);
325 host_->SetNeedsAnimate();
328 void Compositor::RemoveAnimationObserver(
329 CompositorAnimationObserver* observer) {
330 animation_observer_list_.RemoveObserver(observer);
333 bool Compositor::HasAnimationObserver(
334 const CompositorAnimationObserver* observer) const {
335 return animation_observer_list_.HasObserver(observer);
338 void Compositor::AddBeginFrameObserver(CompositorBeginFrameObserver* observer) {
339 DCHECK(std::find(begin_frame_observer_list_.begin(),
340 begin_frame_observer_list_.end(), observer) ==
341 begin_frame_observer_list_.end());
343 if (begin_frame_observer_list_.empty())
344 host_->SetChildrenNeedBeginFrames(true);
346 if (missed_begin_frame_args_.IsValid())
347 observer->OnSendBeginFrame(missed_begin_frame_args_);
349 begin_frame_observer_list_.push_back(observer);
352 void Compositor::RemoveBeginFrameObserver(
353 CompositorBeginFrameObserver* observer) {
354 auto it = std::find(begin_frame_observer_list_.begin(),
355 begin_frame_observer_list_.end(), observer);
356 DCHECK(it != begin_frame_observer_list_.end());
357 begin_frame_observer_list_.erase(it);
359 if (begin_frame_observer_list_.empty()) {
360 host_->SetChildrenNeedBeginFrames(false);
361 missed_begin_frame_args_ = cc::BeginFrameArgs();
365 void Compositor::BeginMainFrame(const cc::BeginFrameArgs& args) {
366 FOR_EACH_OBSERVER(CompositorAnimationObserver,
367 animation_observer_list_,
368 OnAnimationStep(args.frame_time));
369 if (animation_observer_list_.might_have_observers())
370 host_->SetNeedsAnimate();
373 void Compositor::BeginMainFrameNotExpectedSoon() {
376 static void SendDamagedRectsRecursive(ui::Layer* layer) {
377 layer->SendDamagedRects();
378 for (auto* child : layer->children())
379 SendDamagedRectsRecursive(child);
382 void Compositor::Layout() {
383 if (!root_layer())
384 return;
385 SendDamagedRectsRecursive(root_layer());
388 void Compositor::RequestNewOutputSurface() {
389 context_factory_->CreateOutputSurface(weak_ptr_factory_.GetWeakPtr());
392 void Compositor::DidInitializeOutputSurface() {
395 void Compositor::DidFailToInitializeOutputSurface() {
396 // The OutputSurface should already be bound/initialized before being given to
397 // the Compositor.
398 NOTREACHED();
401 void Compositor::DidCommit() {
402 DCHECK(!IsLocked());
403 FOR_EACH_OBSERVER(CompositorObserver,
404 observer_list_,
405 OnCompositingDidCommit(this));
408 void Compositor::DidCommitAndDrawFrame() {
411 void Compositor::DidCompleteSwapBuffers() {
412 FOR_EACH_OBSERVER(CompositorObserver, observer_list_,
413 OnCompositingEnded(this));
416 void Compositor::DidPostSwapBuffers() {
417 base::TimeTicks start_time = base::TimeTicks::Now();
418 FOR_EACH_OBSERVER(CompositorObserver, observer_list_,
419 OnCompositingStarted(this, start_time));
422 void Compositor::DidAbortSwapBuffers() {
423 FOR_EACH_OBSERVER(CompositorObserver,
424 observer_list_,
425 OnCompositingAborted(this));
428 void Compositor::SendBeginFramesToChildren(const cc::BeginFrameArgs& args) {
429 for (auto observer : begin_frame_observer_list_)
430 observer->OnSendBeginFrame(args);
432 missed_begin_frame_args_ = args;
433 missed_begin_frame_args_.type = cc::BeginFrameArgs::MISSED;
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 host_->SetDeferCommits(true);
453 FOR_EACH_OBSERVER(CompositorObserver,
454 observer_list_,
455 OnCompositingLockStateChanged(this));
457 return compositor_lock_;
460 void Compositor::UnlockCompositor() {
461 DCHECK(compositor_lock_);
462 compositor_lock_ = NULL;
463 host_->SetDeferCommits(false);
464 FOR_EACH_OBSERVER(CompositorObserver,
465 observer_list_,
466 OnCompositingLockStateChanged(this));
469 void Compositor::CancelCompositorLock() {
470 if (compositor_lock_)
471 compositor_lock_->CancelLock();
474 } // namespace ui