summaryrefslogtreecommitdiff
path: root/chromium/ui/compositor/compositor.h
blob: 92cdd7194f80c7991e9b5c60e8d796ad8934a0f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef UI_COMPOSITOR_COMPOSITOR_H_
#define UI_COMPOSITOR_COMPOSITOR_H_

#include <string>

#include "base/containers/hash_tables.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/observer_list.h"
#include "base/time/time.h"
#include "cc/trees/layer_tree_host_client.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/compositor/compositor_export.h"
#include "ui/compositor/compositor_observer.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/gfx/size.h"
#include "ui/gfx/transform.h"
#include "ui/gfx/vector2d.h"
#include "ui/gl/gl_share_group.h"

class SkBitmap;

namespace base {
class MessageLoopProxy;
class RunLoop;
}

namespace cc {
class ContextProvider;
class Layer;
class LayerTreeDebugState;
class LayerTreeHost;
}

namespace gfx {
class GLContext;
class GLSurface;
class GLShareGroup;
class Point;
class Rect;
class Size;
}

namespace WebKit {
class WebGraphicsContext3D;
}

namespace ui {

class Compositor;
class CompositorObserver;
class ContextProviderFromContextFactory;
class Layer;
class PostedSwapQueue;
class Reflector;
class Texture;
struct LatencyInfo;

// This class abstracts the creation of the 3D context for the compositor. It is
// a global object.
class COMPOSITOR_EXPORT ContextFactory {
 public:
  virtual ~ContextFactory() {}

  // Gets the global instance.
  static ContextFactory* GetInstance();

  // Sets the global instance. Caller keeps ownership.
  // If this function isn't called (for tests), a "default" factory will be
  // created on the first call of GetInstance.
  static void SetInstance(ContextFactory* instance);

  // Creates an output surface for the given compositor. The factory may keep
  // per-compositor data (e.g. a shared context), that needs to be cleaned up
  // by calling RemoveCompositor when the compositor gets destroyed.
  virtual scoped_ptr<cc::OutputSurface> CreateOutputSurface(
      Compositor* compositor) = 0;

  // Creates a context used for offscreen rendering. This context can be shared
  // with all compositors.
  virtual scoped_ptr<WebKit::WebGraphicsContext3D> CreateOffscreenContext() = 0;

  // Creates a reflector that copies the content of the |mirrored_compositor|
  // onto |mirroing_layer|.
  virtual scoped_refptr<Reflector> CreateReflector(
      Compositor* mirrored_compositor,
      Layer* mirroring_layer) = 0;
  // Removes the reflector, which stops the mirroring.
  virtual void RemoveReflector(scoped_refptr<Reflector> reflector) = 0;

  virtual scoped_refptr<cc::ContextProvider>
      OffscreenContextProviderForMainThread() = 0;
  virtual scoped_refptr<cc::ContextProvider>
      OffscreenContextProviderForCompositorThread() = 0;

  // Destroys per-compositor data.
  virtual void RemoveCompositor(Compositor* compositor) = 0;

  // When true, the factory uses test contexts that do not do real GL
  // operations.
  virtual bool DoesCreateTestContexts() = 0;
};

// The default factory that creates in-process contexts.
class COMPOSITOR_EXPORT DefaultContextFactory : public ContextFactory {
 public:
  DefaultContextFactory();
  virtual ~DefaultContextFactory();

  // ContextFactory implementation
  virtual scoped_ptr<cc::OutputSurface> CreateOutputSurface(
      Compositor* compositor) OVERRIDE;
  virtual scoped_ptr<WebKit::WebGraphicsContext3D> CreateOffscreenContext()
      OVERRIDE;

  virtual scoped_refptr<Reflector> CreateReflector(
      Compositor* compositor,
      Layer* layer) OVERRIDE;
  virtual void RemoveReflector(scoped_refptr<Reflector> reflector) OVERRIDE;

  virtual scoped_refptr<cc::ContextProvider>
      OffscreenContextProviderForMainThread() OVERRIDE;
  virtual scoped_refptr<cc::ContextProvider>
      OffscreenContextProviderForCompositorThread() OVERRIDE;
  virtual void RemoveCompositor(Compositor* compositor) OVERRIDE;
  virtual bool DoesCreateTestContexts() OVERRIDE;

  bool Initialize();

 private:
  scoped_ptr<WebKit::WebGraphicsContext3D> CreateContextCommon(
      Compositor* compositor,
      bool offscreen);

  scoped_refptr<ContextProviderFromContextFactory>
      offscreen_contexts_main_thread_;
  scoped_refptr<ContextProviderFromContextFactory>
      offscreen_contexts_compositor_thread_;

  DISALLOW_COPY_AND_ASSIGN(DefaultContextFactory);
};

// The factory that creates test contexts.
class COMPOSITOR_EXPORT TestContextFactory : public ContextFactory {
 public:
  TestContextFactory();
  virtual ~TestContextFactory();

  // ContextFactory implementation
  virtual scoped_ptr<cc::OutputSurface> CreateOutputSurface(
      Compositor* compositor) OVERRIDE;
  virtual scoped_ptr<WebKit::WebGraphicsContext3D> CreateOffscreenContext()
      OVERRIDE;

  virtual scoped_refptr<Reflector> CreateReflector(
      Compositor* mirrored_compositor,
      Layer* mirroring_layer) OVERRIDE;
  virtual void RemoveReflector(scoped_refptr<Reflector> reflector) OVERRIDE;

  virtual scoped_refptr<cc::ContextProvider>
      OffscreenContextProviderForMainThread() OVERRIDE;
  virtual scoped_refptr<cc::ContextProvider>
      OffscreenContextProviderForCompositorThread() OVERRIDE;
  virtual void RemoveCompositor(Compositor* compositor) OVERRIDE;
  virtual bool DoesCreateTestContexts() OVERRIDE;

 private:
  scoped_refptr<ContextProviderFromContextFactory>
      offscreen_contexts_main_thread_;
  scoped_refptr<ContextProviderFromContextFactory>
      offscreen_contexts_compositor_thread_;

  DISALLOW_COPY_AND_ASSIGN(TestContextFactory);
};

// Texture provide an abstraction over the external texture that can be passed
// to a layer.
class COMPOSITOR_EXPORT Texture : public base::RefCounted<Texture> {
 public:
  Texture(bool flipped, const gfx::Size& size, float device_scale_factor);

  bool flipped() const { return flipped_; }
  gfx::Size size() const { return size_; }
  float device_scale_factor() const { return device_scale_factor_; }

  virtual unsigned int PrepareTexture() = 0;
  virtual WebKit::WebGraphicsContext3D* HostContext3D() = 0;

  // Replaces the texture with the texture from the specified mailbox.
  virtual void Consume(const std::string& mailbox_name,
                       const gfx::Size& new_size) {}

  // Moves the texture into the mailbox and returns the mailbox name.
  // The texture must have been previously consumed from a mailbox.
  virtual std::string Produce();

 protected:
  virtual ~Texture();
  gfx::Size size_;  // in pixel

 private:
  friend class base::RefCounted<Texture>;

  bool flipped_;
  float device_scale_factor_;

  DISALLOW_COPY_AND_ASSIGN(Texture);
};

// An interface to allow the compositor to communicate with its owner.
class COMPOSITOR_EXPORT CompositorDelegate {
 public:
  // Requests the owner to schedule a redraw of the layer tree.
  virtual void ScheduleDraw() = 0;

 protected:
  virtual ~CompositorDelegate() {}
};

// This class represents a lock on the compositor, that can be used to prevent
// commits to the compositor tree while we're waiting for an asynchronous
// event. The typical use case is when waiting for a renderer to produce a frame
// at the right size. The caller keeps a reference on this object, and drops the
// reference once it desires to release the lock.
// Note however that the lock is cancelled after a short timeout to ensure
// responsiveness of the UI, so the compositor tree should be kept in a
// "reasonable" state while the lock is held.
// Don't instantiate this class directly, use Compositor::GetCompositorLock.
class COMPOSITOR_EXPORT CompositorLock
    : public base::RefCounted<CompositorLock>,
      public base::SupportsWeakPtr<CompositorLock> {
 private:
  friend class base::RefCounted<CompositorLock>;
  friend class Compositor;

  explicit CompositorLock(Compositor* compositor);
  ~CompositorLock();

  void CancelLock();

  Compositor* compositor_;
  DISALLOW_COPY_AND_ASSIGN(CompositorLock);
};

// This is only to be used for test. It allows execution of other tasks on
// the current message loop before the current task finishs (there is a
// potential for re-entrancy).
class COMPOSITOR_EXPORT DrawWaiterForTest : public ui::CompositorObserver {
 public:
  // Waits for a draw to be issued by the compositor. If the test times out
  // here, there may be a logic error in the compositor code causing it
  // not to draw.
  static void Wait(Compositor* compositor);

  // Waits for a commit instead of a draw.
  static void WaitForCommit(Compositor* compositor);

 private:
  DrawWaiterForTest();
  virtual ~DrawWaiterForTest();

  void WaitImpl(Compositor* compositor);

  // CompositorObserver implementation.
  virtual void OnCompositingDidCommit(Compositor* compositor) OVERRIDE;
  virtual void OnCompositingStarted(Compositor* compositor,
                                    base::TimeTicks start_time) OVERRIDE;
  virtual void OnCompositingEnded(Compositor* compositor) OVERRIDE;
  virtual void OnCompositingAborted(Compositor* compositor) OVERRIDE;
  virtual void OnCompositingLockStateChanged(Compositor* compositor) OVERRIDE;
  virtual void OnUpdateVSyncParameters(Compositor* compositor,
                                       base::TimeTicks timebase,
                                       base::TimeDelta interval) OVERRIDE;

  scoped_ptr<base::RunLoop> wait_run_loop_;

  bool wait_for_commit_;

  DISALLOW_COPY_AND_ASSIGN(DrawWaiterForTest);
};

// Compositor object to take care of GPU painting.
// A Browser compositor object is responsible for generating the final
// displayable form of pixels comprising a single widget's contents. It draws an
// appropriately transformed texture for each transformed view in the widget's
// view hierarchy.
class COMPOSITOR_EXPORT Compositor
    : NON_EXPORTED_BASE(public cc::LayerTreeHostClient),
      public base::SupportsWeakPtr<Compositor> {
 public:
  Compositor(CompositorDelegate* delegate,
             gfx::AcceleratedWidget widget);
  virtual ~Compositor();

  // Set up the compositor ContextFactory for a test environment. Unit tests
  // that do not have a full content environment need to call this before
  // initializing the Compositor.
  // Some tests expect pixel output, and they should pass false for
  // |allow_test_contexts|. Most unit tests should pass true. Once this has been
  // called, the Initialize() and Terminate() methods should be used as normal.
  static void InitializeContextFactoryForTests(bool allow_test_contexts);

  static void Initialize();
  static bool WasInitializedWithThread();
  static scoped_refptr<base::MessageLoopProxy> GetCompositorMessageLoop();
  static void Terminate();

  // Schedules a redraw of the layer tree associated with this compositor.
  void ScheduleDraw();

  // Sets the root of the layer tree drawn by this Compositor. The root layer
  // must have no parent. The compositor's root layer is reset if the root layer
  // is destroyed. NULL can be passed to reset the root layer, in which case the
  // compositor will stop drawing anything.
  // The Compositor does not own the root layer.
  const Layer* root_layer() const { return root_layer_; }
  Layer* root_layer() { return root_layer_; }
  void SetRootLayer(Layer* root_layer);

  // Called when we need the compositor to preserve the alpha channel in the
  // output for situations when we want to render transparently atop something
  // else, e.g. Aero glass.
  void SetHostHasTransparentBackground(bool host_has_transparent_background);

  // The scale factor of the device that this compositor is
  // compositing layers on.
  float device_scale_factor() const { return device_scale_factor_; }

  // Draws the scene created by the layer tree and any visual effects.
  void Draw();

  // Where possible, draws are scissored to a damage region calculated from
  // changes to layer properties.  This bypasses that and indicates that
  // the whole frame needs to be drawn.
  void ScheduleFullRedraw();

  // Schedule redraw and append damage_rect to the damage region calculated
  // from changes to layer properties.
  void ScheduleRedrawRect(const gfx::Rect& damage_rect);

  void SetLatencyInfo(const ui::LatencyInfo& latency_info);

  // Reads the region |bounds_in_pixel| of the contents of the last rendered
  // frame into the given bitmap.
  // Returns false if the pixels could not be read.
  bool ReadPixels(SkBitmap* bitmap, const gfx::Rect& bounds_in_pixel);

  // Sets the compositor's device scale factor and size.
  void SetScaleAndSize(float scale, const gfx::Size& size_in_pixel);

  // Returns the size of the widget that is being drawn to in pixel coordinates.
  const gfx::Size& size() const { return size_; }

  // Sets the background color used for areas that aren't covered by
  // the |root_layer|.
  void SetBackgroundColor(SkColor color);

  // Returns the widget for this compositor.
  gfx::AcceleratedWidget widget() const { return widget_; }

  // Compositor does not own observers. It is the responsibility of the
  // observer to remove itself when it is done observing.
  void AddObserver(CompositorObserver* observer);
  void RemoveObserver(CompositorObserver* observer);
  bool HasObserver(CompositorObserver* observer);

  // Creates a compositor lock. Returns NULL if it is not possible to lock at
  // this time (i.e. we're waiting to complete a previous unlock).
  scoped_refptr<CompositorLock> GetCompositorLock();

  // Internal functions, called back by command-buffer contexts on swap buffer
  // events.

  // Signals swap has been posted.
  void OnSwapBuffersPosted();

  // Signals swap has completed.
  void OnSwapBuffersComplete();

  // Signals swap has aborted (e.g. lost context).
  void OnSwapBuffersAborted();

  void OnUpdateVSyncParameters(base::TimeTicks timebase,
                               base::TimeDelta interval);

  // LayerTreeHostClient implementation.
  virtual void WillBeginFrame() OVERRIDE {}
  virtual void DidBeginFrame() OVERRIDE {}
  virtual void Animate(double frame_begin_time) OVERRIDE {}
  virtual void Layout() OVERRIDE;
  virtual void ApplyScrollAndScale(gfx::Vector2d scroll_delta,
                                   float page_scale) OVERRIDE {}
  virtual scoped_ptr<cc::OutputSurface> CreateOutputSurface(bool fallback)
      OVERRIDE;
  virtual void DidInitializeOutputSurface(bool success) OVERRIDE {}
  virtual void WillCommit() OVERRIDE {}
  virtual void DidCommit() OVERRIDE;
  virtual void DidCommitAndDrawFrame() OVERRIDE;
  virtual void DidCompleteSwapBuffers() OVERRIDE;
  virtual void ScheduleComposite() OVERRIDE;
  virtual scoped_refptr<cc::ContextProvider>
      OffscreenContextProviderForMainThread() OVERRIDE;
  virtual scoped_refptr<cc::ContextProvider>
      OffscreenContextProviderForCompositorThread() OVERRIDE;

  int last_started_frame() { return last_started_frame_; }
  int last_ended_frame() { return last_ended_frame_; }

  bool IsLocked() { return compositor_lock_ != NULL; }

  const cc::LayerTreeDebugState& GetLayerTreeDebugState() const;
  void SetLayerTreeDebugState(const cc::LayerTreeDebugState& debug_state);

 private:
  friend class base::RefCounted<Compositor>;
  friend class CompositorLock;

  // Called by CompositorLock.
  void UnlockCompositor();

  // Called to release any pending CompositorLock
  void CancelCompositorLock();

  // Notifies the compositor that compositing is complete.
  void NotifyEnd();

  CompositorDelegate* delegate_;
  gfx::Size size_;

  // The root of the Layer tree drawn by this compositor.
  Layer* root_layer_;

  ObserverList<CompositorObserver> observer_list_;

  gfx::AcceleratedWidget widget_;
  scoped_refptr<cc::Layer> root_web_layer_;
  scoped_ptr<cc::LayerTreeHost> host_;

  // Used to verify that we have at most one draw swap in flight.
  scoped_ptr<PostedSwapQueue> posted_swaps_;

  // The device scale factor of the monitor that this compositor is compositing
  // layers on.
  float device_scale_factor_;

  int last_started_frame_;
  int last_ended_frame_;

  bool next_draw_is_resize_;

  bool disable_schedule_composite_;

  CompositorLock* compositor_lock_;

  DISALLOW_COPY_AND_ASSIGN(Compositor);
};

}  // namespace ui

#endif  // UI_COMPOSITOR_COMPOSITOR_H_