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