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