compositor.h revision 1320f92c476a1ad9d19dba2a48c72b75566198e9
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/single_thread_task_runner.h"
15#include "base/time/time.h"
16#include "cc/trees/layer_tree_host_client.h"
17#include "cc/trees/layer_tree_host_single_thread_client.h"
18#include "third_party/skia/include/core/SkColor.h"
19#include "ui/compositor/compositor_animation_observer.h"
20#include "ui/compositor/compositor_export.h"
21#include "ui/compositor/compositor_observer.h"
22#include "ui/compositor/layer_animator_collection.h"
23#include "ui/gfx/native_widget_types.h"
24#include "ui/gfx/size.h"
25#include "ui/gfx/vector2d.h"
26
27class SkBitmap;
28
29namespace base {
30class MessageLoopProxy;
31class RunLoop;
32}
33
34namespace cc {
35class ContextProvider;
36class Layer;
37class LayerTreeDebugState;
38class LayerTreeHost;
39class SharedBitmapManager;
40}
41
42namespace gfx {
43class Rect;
44class Size;
45}
46
47namespace gpu {
48struct Mailbox;
49}
50
51namespace ui {
52
53class Compositor;
54class CompositorVSyncManager;
55class Layer;
56class Reflector;
57class Texture;
58struct LatencyInfo;
59
60// This class abstracts the creation of the 3D context for the compositor. It is
61// a global object.
62class COMPOSITOR_EXPORT ContextFactory {
63 public:
64  virtual ~ContextFactory() {}
65
66  // Creates an output surface for the given compositor. The factory may keep
67  // per-compositor data (e.g. a shared context), that needs to be cleaned up
68  // by calling RemoveCompositor when the compositor gets destroyed.
69  virtual scoped_ptr<cc::OutputSurface> CreateOutputSurface(
70      Compositor* compositor, bool software_fallback) = 0;
71
72  // Creates a reflector that copies the content of the |mirrored_compositor|
73  // onto |mirroing_layer|.
74  virtual scoped_refptr<Reflector> CreateReflector(
75      Compositor* mirrored_compositor,
76      Layer* mirroring_layer) = 0;
77  // Removes the reflector, which stops the mirroring.
78  virtual void RemoveReflector(scoped_refptr<Reflector> reflector) = 0;
79
80  // Return a reference to a shared offscreen context provider usable from the
81  // main thread.
82  virtual scoped_refptr<cc::ContextProvider>
83      SharedMainThreadContextProvider() = 0;
84
85  // Destroys per-compositor data.
86  virtual void RemoveCompositor(Compositor* compositor) = 0;
87
88  // When true, the factory uses test contexts that do not do real GL
89  // operations.
90  virtual bool DoesCreateTestContexts() = 0;
91
92  // Gets the shared bitmap manager for software mode.
93  virtual cc::SharedBitmapManager* GetSharedBitmapManager() = 0;
94
95  // Gets the compositor message loop, or NULL if not using threaded
96  // compositing.
97  virtual base::MessageLoopProxy* GetCompositorMessageLoop() = 0;
98};
99
100// This class represents a lock on the compositor, that can be used to prevent
101// commits to the compositor tree while we're waiting for an asynchronous
102// event. The typical use case is when waiting for a renderer to produce a frame
103// at the right size. The caller keeps a reference on this object, and drops the
104// reference once it desires to release the lock.
105// Note however that the lock is cancelled after a short timeout to ensure
106// responsiveness of the UI, so the compositor tree should be kept in a
107// "reasonable" state while the lock is held.
108// Don't instantiate this class directly, use Compositor::GetCompositorLock.
109class COMPOSITOR_EXPORT CompositorLock
110    : public base::RefCounted<CompositorLock>,
111      public base::SupportsWeakPtr<CompositorLock> {
112 private:
113  friend class base::RefCounted<CompositorLock>;
114  friend class Compositor;
115
116  explicit CompositorLock(Compositor* compositor);
117  ~CompositorLock();
118
119  void CancelLock();
120
121  Compositor* compositor_;
122  DISALLOW_COPY_AND_ASSIGN(CompositorLock);
123};
124
125// Compositor object to take care of GPU painting.
126// A Browser compositor object is responsible for generating the final
127// displayable form of pixels comprising a single widget's contents. It draws an
128// appropriately transformed texture for each transformed view in the widget's
129// view hierarchy.
130class COMPOSITOR_EXPORT Compositor
131    : NON_EXPORTED_BASE(public cc::LayerTreeHostClient),
132      NON_EXPORTED_BASE(public cc::LayerTreeHostSingleThreadClient) {
133 public:
134  Compositor(gfx::AcceleratedWidget widget,
135             ui::ContextFactory* context_factory,
136             scoped_refptr<base::SingleThreadTaskRunner> task_runner);
137  virtual ~Compositor();
138
139  ui::ContextFactory* context_factory() { return context_factory_; }
140
141  // Schedules a redraw of the layer tree associated with this compositor.
142  void ScheduleDraw();
143
144  // Sets the root of the layer tree drawn by this Compositor. The root layer
145  // must have no parent. The compositor's root layer is reset if the root layer
146  // is destroyed. NULL can be passed to reset the root layer, in which case the
147  // compositor will stop drawing anything.
148  // The Compositor does not own the root layer.
149  const Layer* root_layer() const { return root_layer_; }
150  Layer* root_layer() { return root_layer_; }
151  void SetRootLayer(Layer* root_layer);
152
153  // Called when we need the compositor to preserve the alpha channel in the
154  // output for situations when we want to render transparently atop something
155  // else, e.g. Aero glass.
156  void SetHostHasTransparentBackground(bool host_has_transparent_background);
157
158  // The scale factor of the device that this compositor is
159  // compositing layers on.
160  float device_scale_factor() const { return device_scale_factor_; }
161
162  // Draws the scene created by the layer tree and any visual effects.
163  void Draw();
164
165  // Where possible, draws are scissored to a damage region calculated from
166  // changes to layer properties.  This bypasses that and indicates that
167  // the whole frame needs to be drawn.
168  void ScheduleFullRedraw();
169
170  // Schedule redraw and append damage_rect to the damage region calculated
171  // from changes to layer properties.
172  void ScheduleRedrawRect(const gfx::Rect& damage_rect);
173
174  // Finishes all outstanding rendering on the GPU.
175  void FinishAllRendering();
176
177  void SetLatencyInfo(const LatencyInfo& latency_info);
178
179  // Sets the compositor's device scale factor and size.
180  void SetScaleAndSize(float scale, const gfx::Size& size_in_pixel);
181
182  // Returns the size of the widget that is being drawn to in pixel coordinates.
183  const gfx::Size& size() const { return size_; }
184
185  // Sets the background color used for areas that aren't covered by
186  // the |root_layer|.
187  void SetBackgroundColor(SkColor color);
188
189  // Set the visibility of the underlying compositor.
190  void SetVisible(bool visible);
191
192  // Returns the widget for this compositor.
193  gfx::AcceleratedWidget widget() const { return widget_; }
194
195  // Returns the vsync manager for this compositor.
196  scoped_refptr<CompositorVSyncManager> vsync_manager() const;
197
198  // Returns the main thread task runner this compositor uses. Users of the
199  // compositor generally shouldn't use this.
200  scoped_refptr<base::SingleThreadTaskRunner> task_runner() const {
201    return task_runner_;
202  }
203
204  // Compositor does not own observers. It is the responsibility of the
205  // observer to remove itself when it is done observing.
206  void AddObserver(CompositorObserver* observer);
207  void RemoveObserver(CompositorObserver* observer);
208  bool HasObserver(CompositorObserver* observer);
209
210  void AddAnimationObserver(CompositorAnimationObserver* observer);
211  void RemoveAnimationObserver(CompositorAnimationObserver* observer);
212  bool HasAnimationObserver(CompositorAnimationObserver* observer);
213
214  // Creates a compositor lock. Returns NULL if it is not possible to lock at
215  // this time (i.e. we're waiting to complete a previous unlock).
216  scoped_refptr<CompositorLock> GetCompositorLock();
217
218  // Internal functions, called back by command-buffer contexts on swap buffer
219  // events.
220
221  // Signals swap has been posted.
222  void OnSwapBuffersPosted();
223
224  // Signals swap has completed.
225  void OnSwapBuffersComplete();
226
227  // Signals swap has aborted (e.g. lost context).
228  void OnSwapBuffersAborted();
229
230  // LayerTreeHostClient implementation.
231  virtual void WillBeginMainFrame(int frame_id) OVERRIDE {}
232  virtual void DidBeginMainFrame() OVERRIDE {}
233  virtual void BeginMainFrame(const cc::BeginFrameArgs& args) OVERRIDE;
234  virtual void Layout() OVERRIDE;
235  virtual void ApplyViewportDeltas(
236      const gfx::Vector2d& scroll_delta,
237      float page_scale,
238      float top_controls_delta) OVERRIDE {}
239  virtual void RequestNewOutputSurface(bool fallback) OVERRIDE;
240  virtual void DidInitializeOutputSurface() OVERRIDE {}
241  virtual void WillCommit() OVERRIDE {}
242  virtual void DidCommit() OVERRIDE;
243  virtual void DidCommitAndDrawFrame() OVERRIDE;
244  virtual void DidCompleteSwapBuffers() OVERRIDE;
245
246  // cc::LayerTreeHostSingleThreadClient implementation.
247  virtual void ScheduleComposite() OVERRIDE;
248  virtual void ScheduleAnimation() OVERRIDE;
249  virtual void DidPostSwapBuffers() OVERRIDE;
250  virtual void DidAbortSwapBuffers() OVERRIDE;
251
252  int last_started_frame() { return last_started_frame_; }
253  int last_ended_frame() { return last_ended_frame_; }
254
255  bool IsLocked() { return compositor_lock_ != NULL; }
256
257  const cc::LayerTreeDebugState& GetLayerTreeDebugState() const;
258  void SetLayerTreeDebugState(const cc::LayerTreeDebugState& debug_state);
259
260  LayerAnimatorCollection* layer_animator_collection() {
261    return &layer_animator_collection_;
262  }
263
264 private:
265  friend class base::RefCounted<Compositor>;
266  friend class CompositorLock;
267
268  // Called by CompositorLock.
269  void UnlockCompositor();
270
271  // Called to release any pending CompositorLock
272  void CancelCompositorLock();
273
274  // Notifies the compositor that compositing is complete.
275  void NotifyEnd();
276
277  gfx::Size size_;
278
279  ui::ContextFactory* context_factory_;
280
281  // The root of the Layer tree drawn by this compositor.
282  Layer* root_layer_;
283
284  ObserverList<CompositorObserver> observer_list_;
285  ObserverList<CompositorAnimationObserver> animation_observer_list_;
286
287  gfx::AcceleratedWidget widget_;
288  scoped_refptr<cc::Layer> root_web_layer_;
289  scoped_ptr<cc::LayerTreeHost> host_;
290  scoped_refptr<base::MessageLoopProxy> compositor_thread_loop_;
291  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
292
293  // The manager of vsync parameters for this compositor.
294  scoped_refptr<CompositorVSyncManager> vsync_manager_;
295
296  // The device scale factor of the monitor that this compositor is compositing
297  // layers on.
298  float device_scale_factor_;
299
300  int last_started_frame_;
301  int last_ended_frame_;
302
303  bool disable_schedule_composite_;
304
305  CompositorLock* compositor_lock_;
306
307  // Prevent more than one draw from being scheduled.
308  bool defer_draw_scheduling_;
309
310  // Used to prevent Draw()s while a composite is in progress.
311  bool waiting_on_compositing_end_;
312  bool draw_on_compositing_end_;
313  enum SwapState { SWAP_NONE, SWAP_POSTED, SWAP_COMPLETED };
314  SwapState swap_state_;
315
316  LayerAnimatorCollection layer_animator_collection_;
317
318  base::WeakPtrFactory<Compositor> schedule_draw_factory_;
319
320  DISALLOW_COPY_AND_ASSIGN(Compositor);
321};
322
323}  // namespace ui
324
325#endif  // UI_COMPOSITOR_COMPOSITOR_H_
326