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