compositor.h revision 5f1c94371a64b3196d4be9466099bb892df9b88e
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.
4
5#ifndef UI_COMPOSITOR_COMPOSITOR_H_
6#define UI_COMPOSITOR_COMPOSITOR_H_
7
8#include <string>
9
10#include "base/containers/hash_tables.h"
11#include "base/memory/ref_counted.h"
12#include "base/memory/scoped_ptr.h"
13#include "base/observer_list.h"
14#include "base/single_thread_task_runner.h"
15#include "base/time/time.h"
16#include "cc/trees/layer_tree_host_client.h"
17#include "cc/trees/layer_tree_host_single_thread_client.h"
18#include "third_party/skia/include/core/SkColor.h"
19#include "ui/compositor/compositor_animation_observer.h"
20#include "ui/compositor/compositor_export.h"
21#include "ui/compositor/compositor_observer.h"
22#include "ui/compositor/layer_animator_collection.h"
23#include "ui/gfx/native_widget_types.h"
24#include "ui/gfx/size.h"
25#include "ui/gfx/vector2d.h"
26
27class SkBitmap;
28
29namespace base {
30class MessageLoopProxy;
31class RunLoop;
32}
33
34namespace cc {
35class ContextProvider;
36class Layer;
37class LayerTreeDebugState;
38class LayerTreeHost;
39class SharedBitmapManager;
40}
41
42namespace gfx {
43class Rect;
44class Size;
45}
46
47namespace gpu {
48struct Mailbox;
49}
50
51namespace ui {
52
53class Compositor;
54class CompositorVSyncManager;
55class Layer;
56class Reflector;
57class Texture;
58struct LatencyInfo;
59
60// This class abstracts the creation of the 3D context for the compositor. It is
61// a global object.
62class COMPOSITOR_EXPORT ContextFactory {
63 public:
64  virtual ~ContextFactory() {}
65
66  // Creates an output surface for the given compositor. The factory may keep
67  // per-compositor data (e.g. a shared context), that needs to be cleaned up
68  // by calling RemoveCompositor when the compositor gets destroyed.
69  virtual scoped_ptr<cc::OutputSurface> CreateOutputSurface(
70      Compositor* compositor, bool software_fallback) = 0;
71
72  // Creates a reflector that copies the content of the |mirrored_compositor|
73  // onto |mirroing_layer|.
74  virtual scoped_refptr<Reflector> CreateReflector(
75      Compositor* mirrored_compositor,
76      Layer* mirroring_layer) = 0;
77  // Removes the reflector, which stops the mirroring.
78  virtual void RemoveReflector(scoped_refptr<Reflector> reflector) = 0;
79
80  // Return a reference to a shared offscreen context provider usable from the
81  // main thread.
82  virtual scoped_refptr<cc::ContextProvider>
83      SharedMainThreadContextProvider() = 0;
84
85  // Destroys per-compositor data.
86  virtual void RemoveCompositor(Compositor* compositor) = 0;
87
88  // When true, the factory uses test contexts that do not do real GL
89  // operations.
90  virtual bool DoesCreateTestContexts() = 0;
91
92  // Gets the shared bitmap manager for software mode.
93  virtual cc::SharedBitmapManager* GetSharedBitmapManager() = 0;
94
95  // Gets the compositor message loop, or NULL if not using threaded
96  // compositing.
97  virtual base::MessageLoopProxy* GetCompositorMessageLoop() = 0;
98};
99
100// This class represents a lock on the compositor, that can be used to prevent
101// commits to the compositor tree while we're waiting for an asynchronous
102// event. The typical use case is when waiting for a renderer to produce a frame
103// at the right size. The caller keeps a reference on this object, and drops the
104// reference once it desires to release the lock.
105// Note however that the lock is cancelled after a short timeout to ensure
106// responsiveness of the UI, so the compositor tree should be kept in a
107// "reasonable" state while the lock is held.
108// Don't instantiate this class directly, use Compositor::GetCompositorLock.
109class COMPOSITOR_EXPORT CompositorLock
110    : public base::RefCounted<CompositorLock>,
111      public base::SupportsWeakPtr<CompositorLock> {
112 private:
113  friend class base::RefCounted<CompositorLock>;
114  friend class Compositor;
115
116  explicit CompositorLock(Compositor* compositor);
117  ~CompositorLock();
118
119  void CancelLock();
120
121  Compositor* compositor_;
122  DISALLOW_COPY_AND_ASSIGN(CompositorLock);
123};
124
125// Compositor object to take care of GPU painting.
126// A Browser compositor object is responsible for generating the final
127// displayable form of pixels comprising a single widget's contents. It draws an
128// appropriately transformed texture for each transformed view in the widget's
129// view hierarchy.
130class COMPOSITOR_EXPORT Compositor
131    : NON_EXPORTED_BASE(public cc::LayerTreeHostClient),
132      NON_EXPORTED_BASE(public cc::LayerTreeHostSingleThreadClient) {
133 public:
134  Compositor(gfx::AcceleratedWidget widget,
135             ui::ContextFactory* context_factory,
136             scoped_refptr<base::SingleThreadTaskRunner> task_runner);
137  virtual ~Compositor();
138
139  ui::ContextFactory* context_factory() { return context_factory_; }
140
141  // Schedules a redraw of the layer tree associated with this compositor.
142  void ScheduleDraw();
143
144  // Sets the root of the layer tree drawn by this Compositor. The root layer
145  // must have no parent. The compositor's root layer is reset if the root layer
146  // is destroyed. NULL can be passed to reset the root layer, in which case the
147  // compositor will stop drawing anything.
148  // The Compositor does not own the root layer.
149  const Layer* root_layer() const { return root_layer_; }
150  Layer* root_layer() { return root_layer_; }
151  void SetRootLayer(Layer* root_layer);
152
153  // Called when we need the compositor to preserve the alpha channel in the
154  // output for situations when we want to render transparently atop something
155  // else, e.g. Aero glass.
156  void SetHostHasTransparentBackground(bool host_has_transparent_background);
157
158  // The scale factor of the device that this compositor is
159  // compositing layers on.
160  float device_scale_factor() const { return device_scale_factor_; }
161
162  // Draws the scene created by the layer tree and any visual effects.
163  void Draw();
164
165  // Where possible, draws are scissored to a damage region calculated from
166  // changes to layer properties.  This bypasses that and indicates that
167  // the whole frame needs to be drawn.
168  void ScheduleFullRedraw();
169
170  // Schedule redraw and append damage_rect to the damage region calculated
171  // from changes to layer properties.
172  void ScheduleRedrawRect(const gfx::Rect& damage_rect);
173
174  // Finishes all outstanding rendering on the GPU.
175  void FinishAllRendering();
176
177  void SetLatencyInfo(const LatencyInfo& latency_info);
178
179  // Sets the compositor's device scale factor and size.
180  void SetScaleAndSize(float scale, const gfx::Size& size_in_pixel);
181
182  // Returns the size of the widget that is being drawn to in pixel coordinates.
183  const gfx::Size& size() const { return size_; }
184
185  // Sets the background color used for areas that aren't covered by
186  // the |root_layer|.
187  void SetBackgroundColor(SkColor color);
188
189  // Returns the widget for this compositor.
190  gfx::AcceleratedWidget widget() const { return widget_; }
191
192  // Returns the vsync manager for this compositor.
193  scoped_refptr<CompositorVSyncManager> vsync_manager() const;
194
195  // Compositor does not own observers. It is the responsibility of the
196  // observer to remove itself when it is done observing.
197  void AddObserver(CompositorObserver* observer);
198  void RemoveObserver(CompositorObserver* observer);
199  bool HasObserver(CompositorObserver* observer);
200
201  void AddAnimationObserver(CompositorAnimationObserver* observer);
202  void RemoveAnimationObserver(CompositorAnimationObserver* observer);
203  bool HasAnimationObserver(CompositorAnimationObserver* observer);
204
205  // Creates a compositor lock. Returns NULL if it is not possible to lock at
206  // this time (i.e. we're waiting to complete a previous unlock).
207  scoped_refptr<CompositorLock> GetCompositorLock();
208
209  // Internal functions, called back by command-buffer contexts on swap buffer
210  // events.
211
212  // Signals swap has been posted.
213  void OnSwapBuffersPosted();
214
215  // Signals swap has completed.
216  void OnSwapBuffersComplete();
217
218  // Signals swap has aborted (e.g. lost context).
219  void OnSwapBuffersAborted();
220
221  // LayerTreeHostClient implementation.
222  virtual void WillBeginMainFrame(int frame_id) OVERRIDE {}
223  virtual void DidBeginMainFrame() OVERRIDE {}
224  virtual void Animate(base::TimeTicks frame_begin_time) OVERRIDE;
225  virtual void Layout() OVERRIDE;
226  virtual void ApplyScrollAndScale(const gfx::Vector2d& scroll_delta,
227                                   float page_scale) OVERRIDE {}
228  virtual scoped_ptr<cc::OutputSurface> CreateOutputSurface(bool fallback)
229      OVERRIDE;
230  virtual void DidInitializeOutputSurface() OVERRIDE {}
231  virtual void WillCommit() OVERRIDE {}
232  virtual void DidCommit() OVERRIDE;
233  virtual void DidCommitAndDrawFrame() OVERRIDE;
234  virtual void DidCompleteSwapBuffers() OVERRIDE;
235
236  // cc::LayerTreeHostSingleThreadClient implementation.
237  virtual void ScheduleComposite() OVERRIDE;
238  virtual void ScheduleAnimation() OVERRIDE;
239  virtual void DidPostSwapBuffers() OVERRIDE;
240  virtual void DidAbortSwapBuffers() OVERRIDE;
241
242  int last_started_frame() { return last_started_frame_; }
243  int last_ended_frame() { return last_ended_frame_; }
244
245  bool IsLocked() { return compositor_lock_ != NULL; }
246
247  const cc::LayerTreeDebugState& GetLayerTreeDebugState() const;
248  void SetLayerTreeDebugState(const cc::LayerTreeDebugState& debug_state);
249
250  LayerAnimatorCollection* layer_animator_collection() {
251    return &layer_animator_collection_;
252  }
253
254 private:
255  friend class base::RefCounted<Compositor>;
256  friend class CompositorLock;
257
258  // Called by CompositorLock.
259  void UnlockCompositor();
260
261  // Called to release any pending CompositorLock
262  void CancelCompositorLock();
263
264  // Notifies the compositor that compositing is complete.
265  void NotifyEnd();
266
267  gfx::Size size_;
268
269  ui::ContextFactory* context_factory_;
270
271  // The root of the Layer tree drawn by this compositor.
272  Layer* root_layer_;
273
274  ObserverList<CompositorObserver> observer_list_;
275  ObserverList<CompositorAnimationObserver> animation_observer_list_;
276
277  gfx::AcceleratedWidget widget_;
278  scoped_refptr<cc::Layer> root_web_layer_;
279  scoped_ptr<cc::LayerTreeHost> host_;
280  scoped_refptr<base::MessageLoopProxy> compositor_thread_loop_;
281  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
282
283  // The manager of vsync parameters for this compositor.
284  scoped_refptr<CompositorVSyncManager> vsync_manager_;
285
286  // The device scale factor of the monitor that this compositor is compositing
287  // layers on.
288  float device_scale_factor_;
289
290  int last_started_frame_;
291  int last_ended_frame_;
292
293  bool disable_schedule_composite_;
294
295  CompositorLock* compositor_lock_;
296
297  // Prevent more than one draw from being scheduled.
298  bool defer_draw_scheduling_;
299
300  // Used to prevent Draw()s while a composite is in progress.
301  bool waiting_on_compositing_end_;
302  bool draw_on_compositing_end_;
303  enum SwapState { SWAP_NONE, SWAP_POSTED, SWAP_COMPLETED };
304  SwapState swap_state_;
305
306  LayerAnimatorCollection layer_animator_collection_;
307
308  base::WeakPtrFactory<Compositor> schedule_draw_factory_;
309
310  DISALLOW_COPY_AND_ASSIGN(Compositor);
311};
312
313}  // namespace ui
314
315#endif  // UI_COMPOSITOR_COMPOSITOR_H_
316