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