compositor.h revision a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7
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 blink {
32class WebGraphicsContext3D;
33}
34
35namespace cc {
36class ContextProvider;
37class Layer;
38class LayerTreeDebugState;
39class LayerTreeHost;
40}
41
42namespace gfx {
43class Rect;
44class Size;
45}
46
47namespace ui {
48
49class Compositor;
50class Layer;
51class PostedSwapQueue;
52class Reflector;
53class Texture;
54struct LatencyInfo;
55
56// This class abstracts the creation of the 3D context for the compositor. It is
57// a global object.
58class COMPOSITOR_EXPORT ContextFactory {
59 public:
60  virtual ~ContextFactory() {}
61
62  // Gets the global instance.
63  static ContextFactory* GetInstance();
64
65  // Sets the global instance. Caller keeps ownership.
66  // If this function isn't called (for tests), a "default" factory will be
67  // created on the first call of GetInstance.
68  static void SetInstance(ContextFactory* instance);
69
70  // Creates an output surface for the given compositor. The factory may keep
71  // per-compositor data (e.g. a shared context), that needs to be cleaned up
72  // by calling RemoveCompositor when the compositor gets destroyed.
73  virtual scoped_ptr<cc::OutputSurface> CreateOutputSurface(
74      Compositor* compositor, bool software_fallback) = 0;
75
76  // Creates a reflector that copies the content of the |mirrored_compositor|
77  // onto |mirroing_layer|.
78  virtual scoped_refptr<Reflector> CreateReflector(
79      Compositor* mirrored_compositor,
80      Layer* mirroring_layer) = 0;
81  // Removes the reflector, which stops the mirroring.
82  virtual void RemoveReflector(scoped_refptr<Reflector> reflector) = 0;
83
84  // Returns a reference to the offscreen context provider used by the
85  // compositor. This provider is bound and used on whichever thread the
86  // compositor is rendering from.
87  virtual scoped_refptr<cc::ContextProvider>
88      OffscreenCompositorContextProvider() = 0;
89
90  // Return a reference to a shared offscreen context provider usable from the
91  // main thread. This may be the same as OffscreenCompositorContextProvider()
92  // depending on the compositor's threading configuration. This provider will
93  // be bound to the main thread.
94  virtual scoped_refptr<cc::ContextProvider>
95      SharedMainThreadContextProvider() = 0;
96
97  // Destroys per-compositor data.
98  virtual void RemoveCompositor(Compositor* compositor) = 0;
99
100  // When true, the factory uses test contexts that do not do real GL
101  // operations.
102  virtual bool DoesCreateTestContexts() = 0;
103};
104
105// Texture provide an abstraction over the external texture that can be passed
106// to a layer.
107class COMPOSITOR_EXPORT Texture : public base::RefCounted<Texture> {
108 public:
109  Texture(bool flipped, const gfx::Size& size, float device_scale_factor);
110
111  bool flipped() const { return flipped_; }
112  gfx::Size size() const { return size_; }
113  float device_scale_factor() const { return device_scale_factor_; }
114
115  virtual unsigned int PrepareTexture() = 0;
116  virtual blink::WebGraphicsContext3D* HostContext3D() = 0;
117
118  // Replaces the texture with the texture from the specified mailbox.
119  virtual void Consume(const std::string& mailbox_name,
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 std::string 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// This is only to be used for test. It allows execution of other tasks on
165// the current message loop before the current task finishs (there is a
166// potential for re-entrancy).
167class COMPOSITOR_EXPORT DrawWaiterForTest : public CompositorObserver {
168 public:
169  // Waits for a draw to be issued by the compositor. If the test times out
170  // here, there may be a logic error in the compositor code causing it
171  // not to draw.
172  static void Wait(Compositor* compositor);
173
174  // Waits for a commit instead of a draw.
175  static void WaitForCommit(Compositor* compositor);
176
177 private:
178  DrawWaiterForTest();
179  virtual ~DrawWaiterForTest();
180
181  void WaitImpl(Compositor* compositor);
182
183  // CompositorObserver implementation.
184  virtual void OnCompositingDidCommit(Compositor* compositor) OVERRIDE;
185  virtual void OnCompositingStarted(Compositor* compositor,
186                                    base::TimeTicks start_time) OVERRIDE;
187  virtual void OnCompositingEnded(Compositor* compositor) OVERRIDE;
188  virtual void OnCompositingAborted(Compositor* compositor) OVERRIDE;
189  virtual void OnCompositingLockStateChanged(Compositor* compositor) OVERRIDE;
190  virtual void OnUpdateVSyncParameters(Compositor* compositor,
191                                       base::TimeTicks timebase,
192                                       base::TimeDelta interval) OVERRIDE;
193
194  scoped_ptr<base::RunLoop> wait_run_loop_;
195
196  bool wait_for_commit_;
197
198  DISALLOW_COPY_AND_ASSIGN(DrawWaiterForTest);
199};
200
201// Compositor object to take care of GPU painting.
202// A Browser compositor object is responsible for generating the final
203// displayable form of pixels comprising a single widget's contents. It draws an
204// appropriately transformed texture for each transformed view in the widget's
205// view hierarchy.
206class COMPOSITOR_EXPORT Compositor
207    : NON_EXPORTED_BASE(public cc::LayerTreeHostClient),
208      NON_EXPORTED_BASE(public cc::LayerTreeHostSingleThreadClient),
209      public base::SupportsWeakPtr<Compositor> {
210 public:
211  explicit Compositor(gfx::AcceleratedWidget widget);
212  virtual ~Compositor();
213
214  static void Initialize();
215  static bool WasInitializedWithThread();
216  static scoped_refptr<base::MessageLoopProxy> GetCompositorMessageLoop();
217  static void Terminate();
218
219  // Schedules a redraw of the layer tree associated with this compositor.
220  void ScheduleDraw();
221
222  // Sets the root of the layer tree drawn by this Compositor. The root layer
223  // must have no parent. The compositor's root layer is reset if the root layer
224  // is destroyed. NULL can be passed to reset the root layer, in which case the
225  // compositor will stop drawing anything.
226  // The Compositor does not own the root layer.
227  const Layer* root_layer() const { return root_layer_; }
228  Layer* root_layer() { return root_layer_; }
229  void SetRootLayer(Layer* root_layer);
230
231  // Called when we need the compositor to preserve the alpha channel in the
232  // output for situations when we want to render transparently atop something
233  // else, e.g. Aero glass.
234  void SetHostHasTransparentBackground(bool host_has_transparent_background);
235
236  // The scale factor of the device that this compositor is
237  // compositing layers on.
238  float device_scale_factor() const { return device_scale_factor_; }
239
240  // Draws the scene created by the layer tree and any visual effects.
241  void Draw();
242
243  // Where possible, draws are scissored to a damage region calculated from
244  // changes to layer properties.  This bypasses that and indicates that
245  // the whole frame needs to be drawn.
246  void ScheduleFullRedraw();
247
248  // Schedule redraw and append damage_rect to the damage region calculated
249  // from changes to layer properties.
250  void ScheduleRedrawRect(const gfx::Rect& damage_rect);
251
252  void SetLatencyInfo(const LatencyInfo& latency_info);
253
254  // Reads the region |bounds_in_pixel| of the contents of the last rendered
255  // frame into the given bitmap.
256  // Returns false if the pixels could not be read.
257  bool ReadPixels(SkBitmap* bitmap, const gfx::Rect& bounds_in_pixel);
258
259  // Sets the compositor's device scale factor and size.
260  void SetScaleAndSize(float scale, const gfx::Size& size_in_pixel);
261
262  // Returns the size of the widget that is being drawn to in pixel coordinates.
263  const gfx::Size& size() const { return size_; }
264
265  // Sets the background color used for areas that aren't covered by
266  // the |root_layer|.
267  void SetBackgroundColor(SkColor color);
268
269  // Returns the widget for this compositor.
270  gfx::AcceleratedWidget widget() const { return widget_; }
271
272  // Compositor does not own observers. It is the responsibility of the
273  // observer to remove itself when it is done observing.
274  void AddObserver(CompositorObserver* observer);
275  void RemoveObserver(CompositorObserver* observer);
276  bool HasObserver(CompositorObserver* observer);
277
278  // Creates a compositor lock. Returns NULL if it is not possible to lock at
279  // this time (i.e. we're waiting to complete a previous unlock).
280  scoped_refptr<CompositorLock> GetCompositorLock();
281
282  // Internal functions, called back by command-buffer contexts on swap buffer
283  // events.
284
285  // Signals swap has been posted.
286  void OnSwapBuffersPosted();
287
288  // Signals swap has completed.
289  void OnSwapBuffersComplete();
290
291  // Signals swap has aborted (e.g. lost context).
292  void OnSwapBuffersAborted();
293
294  void OnUpdateVSyncParameters(base::TimeTicks timebase,
295                               base::TimeDelta interval);
296
297  // LayerTreeHostClient implementation.
298  virtual void WillBeginMainFrame(int frame_id) OVERRIDE {}
299  virtual void DidBeginMainFrame() OVERRIDE {}
300  virtual void Animate(double frame_begin_time) OVERRIDE {}
301  virtual void Layout() OVERRIDE;
302  virtual void ApplyScrollAndScale(gfx::Vector2d scroll_delta,
303                                   float page_scale) OVERRIDE {}
304  virtual scoped_ptr<cc::OutputSurface> CreateOutputSurface(bool fallback)
305      OVERRIDE;
306  virtual void DidInitializeOutputSurface(bool success) OVERRIDE {}
307  virtual void WillCommit() OVERRIDE {}
308  virtual void DidCommit() OVERRIDE;
309  virtual void DidCommitAndDrawFrame() OVERRIDE;
310  virtual void DidCompleteSwapBuffers() OVERRIDE;
311  virtual scoped_refptr<cc::ContextProvider>
312      OffscreenContextProvider() OVERRIDE;
313
314  // cc::LayerTreeHostSingleThreadClient implementation.
315  virtual void ScheduleComposite() OVERRIDE;
316  virtual void ScheduleAnimation() OVERRIDE;
317  virtual void DidPostSwapBuffers() OVERRIDE;
318  virtual void DidAbortSwapBuffers() OVERRIDE;
319
320  int last_started_frame() { return last_started_frame_; }
321  int last_ended_frame() { return last_ended_frame_; }
322
323  bool IsLocked() { return compositor_lock_ != NULL; }
324
325  const cc::LayerTreeDebugState& GetLayerTreeDebugState() const;
326  void SetLayerTreeDebugState(const cc::LayerTreeDebugState& debug_state);
327
328 private:
329  friend class base::RefCounted<Compositor>;
330  friend class CompositorLock;
331
332  // Called by CompositorLock.
333  void UnlockCompositor();
334
335  // Called to release any pending CompositorLock
336  void CancelCompositorLock();
337
338  // Notifies the compositor that compositing is complete.
339  void NotifyEnd();
340
341  gfx::Size size_;
342
343  // The root of the Layer tree drawn by this compositor.
344  Layer* root_layer_;
345
346  ObserverList<CompositorObserver> observer_list_;
347
348  gfx::AcceleratedWidget widget_;
349  scoped_refptr<cc::Layer> root_web_layer_;
350  scoped_ptr<cc::LayerTreeHost> host_;
351
352  // Used to verify that we have at most one draw swap in flight.
353  scoped_ptr<PostedSwapQueue> posted_swaps_;
354
355  // The device scale factor of the monitor that this compositor is compositing
356  // layers on.
357  float device_scale_factor_;
358
359  int last_started_frame_;
360  int last_ended_frame_;
361
362  bool next_draw_is_resize_;
363
364  bool disable_schedule_composite_;
365
366  CompositorLock* compositor_lock_;
367
368  // Prevent more than one draw from being scheduled.
369  bool defer_draw_scheduling_;
370
371  // Used to prevent Draw()s while a composite is in progress.
372  bool waiting_on_compositing_end_;
373  bool draw_on_compositing_end_;
374
375  base::WeakPtrFactory<Compositor> schedule_draw_factory_;
376
377  DISALLOW_COPY_AND_ASSIGN(Compositor);
378};
379
380}  // namespace ui
381
382#endif  // UI_COMPOSITOR_COMPOSITOR_H_
383