compositor.h revision 868fa2fe829687343ffae624259930155e16dbd8
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/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.h"
15#include "cc/trees/layer_tree_host_client.h"
16#include "third_party/skia/include/core/SkColor.h"
17#include "ui/compositor/compositor_export.h"
18#include "ui/compositor/compositor_observer.h"
19#include "ui/gfx/native_widget_types.h"
20#include "ui/gfx/size.h"
21#include "ui/gfx/transform.h"
22#include "ui/gfx/vector2d.h"
23#include "ui/gl/gl_share_group.h"
24
25class SkBitmap;
26
27namespace base {
28class MessageLoopProxy;
29class RunLoop;
30}
31
32namespace cc {
33class ContextProvider;
34class Layer;
35class LayerTreeDebugState;
36class LayerTreeHost;
37}
38
39namespace gfx {
40class GLContext;
41class GLSurface;
42class GLShareGroup;
43class Point;
44class Rect;
45class Size;
46}
47
48namespace WebKit {
49class WebGraphicsContext3D;
50}
51
52namespace ui {
53
54class Compositor;
55class CompositorObserver;
56class ContextProviderFromContextFactory;
57class Layer;
58class PostedSwapQueue;
59class Reflector;
60class Texture;
61struct LatencyInfo;
62
63// This class abstracts the creation of the 3D context for the compositor. It is
64// a global object.
65class COMPOSITOR_EXPORT ContextFactory {
66 public:
67  virtual ~ContextFactory() {}
68
69  // Gets the global instance.
70  static ContextFactory* GetInstance();
71
72  // Sets the global instance. Caller keeps ownership.
73  // If this function isn't called (for tests), a "default" factory will be
74  // created on the first call of GetInstance.
75  static void SetInstance(ContextFactory* instance);
76
77  // Creates an output surface for the given compositor. The factory may keep
78  // per-compositor data (e.g. a shared context), that needs to be cleaned up
79  // by calling RemoveCompositor when the compositor gets destroyed.
80  virtual cc::OutputSurface* CreateOutputSurface(
81      Compositor* compositor) = 0;
82
83  // Creates a context used for offscreen rendering. This context can be shared
84  // with all compositors.
85  virtual WebKit::WebGraphicsContext3D* CreateOffscreenContext() = 0;
86
87  // Creates a reflector that copies the content of the |mirrored_compositor|
88  // onto |mirroing_layer|.
89  virtual scoped_refptr<Reflector> CreateReflector(
90      Compositor* mirrored_compositor,
91      Layer* mirroring_layer) = 0;
92  // Removes the reflector, which stops the mirroring.
93  virtual void RemoveReflector(scoped_refptr<Reflector> reflector) = 0;
94
95  virtual scoped_refptr<cc::ContextProvider>
96      OffscreenContextProviderForMainThread() = 0;
97  virtual scoped_refptr<cc::ContextProvider>
98      OffscreenContextProviderForCompositorThread() = 0;
99
100  // Destroys per-compositor data.
101  virtual void RemoveCompositor(Compositor* compositor) = 0;
102};
103
104// The default factory that creates in-process contexts.
105class COMPOSITOR_EXPORT DefaultContextFactory : public ContextFactory {
106 public:
107  DefaultContextFactory();
108  virtual ~DefaultContextFactory();
109
110  // ContextFactory implementation
111  virtual cc::OutputSurface* CreateOutputSurface(
112      Compositor* compositor) OVERRIDE;
113  virtual WebKit::WebGraphicsContext3D* CreateOffscreenContext() OVERRIDE;
114
115  virtual scoped_refptr<Reflector> CreateReflector(
116      Compositor* compositor,
117      Layer* layer) OVERRIDE;
118  virtual void RemoveReflector(scoped_refptr<Reflector> reflector) OVERRIDE;
119
120  virtual scoped_refptr<cc::ContextProvider>
121      OffscreenContextProviderForMainThread() OVERRIDE;
122  virtual scoped_refptr<cc::ContextProvider>
123      OffscreenContextProviderForCompositorThread() OVERRIDE;
124  virtual void RemoveCompositor(Compositor* compositor) OVERRIDE;
125
126  bool Initialize();
127
128 private:
129  WebKit::WebGraphicsContext3D* CreateContextCommon(
130      Compositor* compositor,
131      bool offscreen);
132
133  scoped_refptr<ContextProviderFromContextFactory>
134      offscreen_contexts_main_thread_;
135  scoped_refptr<ContextProviderFromContextFactory>
136      offscreen_contexts_compositor_thread_;
137
138  DISALLOW_COPY_AND_ASSIGN(DefaultContextFactory);
139};
140
141// The factory that creates test contexts.
142class COMPOSITOR_EXPORT TestContextFactory : public ContextFactory {
143 public:
144  TestContextFactory();
145  virtual ~TestContextFactory();
146
147  // ContextFactory implementation
148  virtual cc::OutputSurface* CreateOutputSurface(
149      Compositor* compositor) OVERRIDE;
150  virtual WebKit::WebGraphicsContext3D* CreateOffscreenContext() OVERRIDE;
151
152  virtual scoped_refptr<Reflector> CreateReflector(
153      Compositor* mirrored_compositor,
154      Layer* mirroring_layer) OVERRIDE;
155  virtual void RemoveReflector(scoped_refptr<Reflector> reflector) OVERRIDE;
156
157  virtual scoped_refptr<cc::ContextProvider>
158      OffscreenContextProviderForMainThread() OVERRIDE;
159  virtual scoped_refptr<cc::ContextProvider>
160      OffscreenContextProviderForCompositorThread() OVERRIDE;
161  virtual void RemoveCompositor(Compositor* compositor) OVERRIDE;
162
163 private:
164  scoped_refptr<ContextProviderFromContextFactory>
165      offscreen_contexts_main_thread_;
166  scoped_refptr<ContextProviderFromContextFactory>
167      offscreen_contexts_compositor_thread_;
168
169  DISALLOW_COPY_AND_ASSIGN(TestContextFactory);
170};
171
172// Texture provide an abstraction over the external texture that can be passed
173// to a layer.
174class COMPOSITOR_EXPORT Texture : public base::RefCounted<Texture> {
175 public:
176  Texture(bool flipped, const gfx::Size& size, float device_scale_factor);
177
178  bool flipped() const { return flipped_; }
179  gfx::Size size() const { return size_; }
180  float device_scale_factor() const { return device_scale_factor_; }
181
182  virtual unsigned int PrepareTexture() = 0;
183  virtual WebKit::WebGraphicsContext3D* HostContext3D() = 0;
184
185  // Replaces the texture with the texture from the specified mailbox.
186  virtual void Consume(const std::string& mailbox_name,
187                       const gfx::Size& new_size) {}
188
189  // Moves the texture into the mailbox and returns the mailbox name.
190  // The texture must have been previously consumed from a mailbox.
191  virtual std::string Produce();
192
193 protected:
194  virtual ~Texture();
195  gfx::Size size_;  // in pixel
196
197 private:
198  friend class base::RefCounted<Texture>;
199
200  bool flipped_;
201  float device_scale_factor_;
202
203  DISALLOW_COPY_AND_ASSIGN(Texture);
204};
205
206// An interface to allow the compositor to communicate with its owner.
207class COMPOSITOR_EXPORT CompositorDelegate {
208 public:
209  // Requests the owner to schedule a redraw of the layer tree.
210  virtual void ScheduleDraw() = 0;
211
212 protected:
213  virtual ~CompositorDelegate() {}
214};
215
216class COMPOSITOR_EXPORT Reflector
217    : public base::RefCountedThreadSafe<Reflector> {
218 public:
219  Reflector() {}
220
221  virtual void OnMirroringCompositorResized() {}
222
223 protected:
224  friend class base::RefCountedThreadSafe<Reflector>;
225  virtual ~Reflector() {}
226
227  DISALLOW_COPY_AND_ASSIGN(Reflector);
228};
229
230// This class represents a lock on the compositor, that can be used to prevent
231// commits to the compositor tree while we're waiting for an asynchronous
232// event. The typical use case is when waiting for a renderer to produce a frame
233// at the right size. The caller keeps a reference on this object, and drops the
234// reference once it desires to release the lock.
235// Note however that the lock is cancelled after a short timeout to ensure
236// responsiveness of the UI, so the compositor tree should be kept in a
237// "reasonable" state while the lock is held.
238// Don't instantiate this class directly, use Compositor::GetCompositorLock.
239class COMPOSITOR_EXPORT CompositorLock
240    : public base::RefCounted<CompositorLock>,
241      public base::SupportsWeakPtr<CompositorLock> {
242 private:
243  friend class base::RefCounted<CompositorLock>;
244  friend class Compositor;
245
246  explicit CompositorLock(Compositor* compositor);
247  ~CompositorLock();
248
249  void CancelLock();
250
251  Compositor* compositor_;
252  DISALLOW_COPY_AND_ASSIGN(CompositorLock);
253};
254
255// This is only to be used for test. It allows execution of other tasks on
256// the current message loop before the current task finishs (there is a
257// potential for re-entrancy).
258class COMPOSITOR_EXPORT DrawWaiterForTest : public ui::CompositorObserver {
259 public:
260  // Waits for a draw to be issued by the compositor. If the test times out
261  // here, there may be a logic error in the compositor code causing it
262  // not to draw.
263  static void Wait(Compositor* compositor);
264
265 private:
266  DrawWaiterForTest();
267  virtual ~DrawWaiterForTest();
268
269  void WaitImpl(Compositor* compositor);
270
271  // CompositorObserver implementation.
272  virtual void OnCompositingDidCommit(Compositor* compositor) OVERRIDE;
273  virtual void OnCompositingStarted(Compositor* compositor,
274                                    base::TimeTicks start_time) OVERRIDE;
275  virtual void OnCompositingEnded(Compositor* compositor) OVERRIDE;
276  virtual void OnCompositingAborted(Compositor* compositor) OVERRIDE;
277  virtual void OnCompositingLockStateChanged(Compositor* compositor) OVERRIDE;
278  virtual void OnUpdateVSyncParameters(Compositor* compositor,
279                                       base::TimeTicks timebase,
280                                       base::TimeDelta interval) OVERRIDE;
281
282  scoped_ptr<base::RunLoop> wait_run_loop_;
283
284  DISALLOW_COPY_AND_ASSIGN(DrawWaiterForTest);
285};
286
287// Compositor object to take care of GPU painting.
288// A Browser compositor object is responsible for generating the final
289// displayable form of pixels comprising a single widget's contents. It draws an
290// appropriately transformed texture for each transformed view in the widget's
291// view hierarchy.
292class COMPOSITOR_EXPORT Compositor
293    : NON_EXPORTED_BASE(public cc::LayerTreeHostClient),
294      public base::SupportsWeakPtr<Compositor> {
295 public:
296  Compositor(CompositorDelegate* delegate,
297             gfx::AcceleratedWidget widget);
298  virtual ~Compositor();
299
300  static void Initialize();
301  static bool WasInitializedWithThread();
302  static scoped_refptr<base::MessageLoopProxy> GetCompositorMessageLoop();
303  static void Terminate();
304
305  // Schedules a redraw of the layer tree associated with this compositor.
306  void ScheduleDraw();
307
308  // Sets the root of the layer tree drawn by this Compositor. The root layer
309  // must have no parent. The compositor's root layer is reset if the root layer
310  // is destroyed. NULL can be passed to reset the root layer, in which case the
311  // compositor will stop drawing anything.
312  // The Compositor does not own the root layer.
313  const Layer* root_layer() const { return root_layer_; }
314  Layer* root_layer() { return root_layer_; }
315  void SetRootLayer(Layer* root_layer);
316
317  // Called when we need the compositor to preserve the alpha channel in the
318  // output for situations when we want to render transparently atop something
319  // else, e.g. Aero glass.
320  void SetHostHasTransparentBackground(bool host_has_transparent_background);
321
322  // The scale factor of the device that this compositor is
323  // compositing layers on.
324  float device_scale_factor() const { return device_scale_factor_; }
325
326  // Draws the scene created by the layer tree and any visual effects.
327  void Draw();
328
329  // Where possible, draws are scissored to a damage region calculated from
330  // changes to layer properties.  This bypasses that and indicates that
331  // the whole frame needs to be drawn.
332  void ScheduleFullRedraw();
333
334  // Schedule redraw and append damage_rect to the damage region calculated
335  // from changes to layer properties.
336  void ScheduleRedrawRect(const gfx::Rect& damage_rect);
337
338  void SetLatencyInfo(const ui::LatencyInfo& latency_info);
339
340  // Reads the region |bounds_in_pixel| of the contents of the last rendered
341  // frame into the given bitmap.
342  // Returns false if the pixels could not be read.
343  bool ReadPixels(SkBitmap* bitmap, const gfx::Rect& bounds_in_pixel);
344
345  // Sets the compositor's device scale factor and size.
346  void SetScaleAndSize(float scale, const gfx::Size& size_in_pixel);
347
348  // Returns the size of the widget that is being drawn to in pixel coordinates.
349  const gfx::Size& size() const { return size_; }
350
351  // Sets the background color used for areas that aren't covered by
352  // the |root_layer|.
353  void SetBackgroundColor(SkColor color);
354
355  // Returns the widget for this compositor.
356  gfx::AcceleratedWidget widget() const { return widget_; }
357
358  // Compositor does not own observers. It is the responsibility of the
359  // observer to remove itself when it is done observing.
360  void AddObserver(CompositorObserver* observer);
361  void RemoveObserver(CompositorObserver* observer);
362  bool HasObserver(CompositorObserver* observer);
363
364  // Creates a compositor lock. Returns NULL if it is not possible to lock at
365  // this time (i.e. we're waiting to complete a previous unlock).
366  scoped_refptr<CompositorLock> GetCompositorLock();
367
368  // Internal functions, called back by command-buffer contexts on swap buffer
369  // events.
370
371  // Signals swap has been posted.
372  void OnSwapBuffersPosted();
373
374  // Signals swap has completed.
375  void OnSwapBuffersComplete();
376
377  // Signals swap has aborted (e.g. lost context).
378  void OnSwapBuffersAborted();
379
380  void OnUpdateVSyncParameters(base::TimeTicks timebase,
381                               base::TimeDelta interval);
382
383  // LayerTreeHostClient implementation.
384  virtual void WillBeginFrame() OVERRIDE {}
385  virtual void DidBeginFrame() OVERRIDE {}
386  virtual void Animate(double frame_begin_time) OVERRIDE {}
387  virtual void Layout() OVERRIDE;
388  virtual void ApplyScrollAndScale(gfx::Vector2d scroll_delta,
389                                   float page_scale) OVERRIDE {}
390  virtual scoped_ptr<cc::OutputSurface>
391      CreateOutputSurface() OVERRIDE;
392  virtual void DidInitializeOutputSurface(bool success) OVERRIDE {}
393  virtual void WillCommit() OVERRIDE {}
394  virtual void DidCommit() OVERRIDE;
395  virtual void DidCommitAndDrawFrame() OVERRIDE;
396  virtual void DidCompleteSwapBuffers() OVERRIDE;
397  virtual void ScheduleComposite() OVERRIDE;
398  virtual scoped_refptr<cc::ContextProvider>
399      OffscreenContextProviderForMainThread() OVERRIDE;
400  virtual scoped_refptr<cc::ContextProvider>
401      OffscreenContextProviderForCompositorThread() OVERRIDE;
402
403  int last_started_frame() { return last_started_frame_; }
404  int last_ended_frame() { return last_ended_frame_; }
405
406  bool IsLocked() { return compositor_lock_ != NULL; }
407
408  const cc::LayerTreeDebugState& GetLayerTreeDebugState() const;
409  void SetLayerTreeDebugState(const cc::LayerTreeDebugState& debug_state);
410
411 private:
412  friend class base::RefCounted<Compositor>;
413  friend class CompositorLock;
414
415  // Called by CompositorLock.
416  void UnlockCompositor();
417
418  // Called to release any pending CompositorLock
419  void CancelCompositorLock();
420
421  // Notifies the compositor that compositing is complete.
422  void NotifyEnd();
423
424  CompositorDelegate* delegate_;
425  gfx::Size size_;
426
427  // The root of the Layer tree drawn by this compositor.
428  Layer* root_layer_;
429
430  ObserverList<CompositorObserver> observer_list_;
431
432  gfx::AcceleratedWidget widget_;
433  scoped_refptr<cc::Layer> root_web_layer_;
434  scoped_ptr<cc::LayerTreeHost> host_;
435
436  // Used to verify that we have at most one draw swap in flight.
437  scoped_ptr<PostedSwapQueue> posted_swaps_;
438
439  // The device scale factor of the monitor that this compositor is compositing
440  // layers on.
441  float device_scale_factor_;
442
443  int last_started_frame_;
444  int last_ended_frame_;
445
446  bool next_draw_is_resize_;
447
448  bool disable_schedule_composite_;
449
450  CompositorLock* compositor_lock_;
451
452  DISALLOW_COPY_AND_ASSIGN(Compositor);
453};
454
455}  // namespace ui
456
457#endif  // UI_COMPOSITOR_COMPOSITOR_H_
458