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.
5 #ifndef UI_COMPOSITOR_COMPOSITOR_H_
6 #define UI_COMPOSITOR_COMPOSITOR_H_
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"
28 class MessageLoopProxy
;
33 class ContextProvider
;
35 class LayerTreeDebugState
;
37 class TestContextProvider
;
50 class WebGraphicsContext3D
;
55 class ContextProviderInProcess
;
56 class WebGraphicsContext3DInProcessCommandBufferImpl
;
63 class CompositorObserver
;
64 class ContextProviderFromContextFactory
;
66 class PostedSwapQueue
;
71 // This class abstracts the creation of the 3D context for the compositor. It is
73 class COMPOSITOR_EXPORT ContextFactory
{
75 virtual ~ContextFactory() {}
77 // Gets the global instance.
78 static ContextFactory
* GetInstance();
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
);
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;
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;
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;
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;
112 // Destroys per-compositor data.
113 virtual void RemoveCompositor(Compositor
* compositor
) = 0;
115 // When true, the factory uses test contexts that do not do real GL
117 virtual bool DoesCreateTestContexts() = 0;
120 // The default factory that creates in-process contexts.
121 class COMPOSITOR_EXPORT DefaultContextFactory
: public ContextFactory
{
123 DefaultContextFactory();
124 virtual ~DefaultContextFactory();
126 // ContextFactory implementation
127 virtual scoped_ptr
<cc::OutputSurface
> CreateOutputSurface(
128 Compositor
* compositor
) OVERRIDE
;
130 virtual scoped_refptr
<Reflector
> CreateReflector(
131 Compositor
* compositor
,
132 Layer
* layer
) OVERRIDE
;
133 virtual void RemoveReflector(scoped_refptr
<Reflector
> reflector
) OVERRIDE
;
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
;
145 scoped_refptr
<webkit::gpu::ContextProviderInProcess
>
146 offscreen_compositor_contexts_
;
147 scoped_refptr
<webkit::gpu::ContextProviderInProcess
>
148 shared_main_thread_contexts_
;
150 DISALLOW_COPY_AND_ASSIGN(DefaultContextFactory
);
153 // The factory that creates test contexts.
154 class COMPOSITOR_EXPORT TestContextFactory
: public ContextFactory
{
156 TestContextFactory();
157 virtual ~TestContextFactory();
159 // ContextFactory implementation
160 virtual scoped_ptr
<cc::OutputSurface
> CreateOutputSurface(
161 Compositor
* compositor
) OVERRIDE
;
163 virtual scoped_refptr
<Reflector
> CreateReflector(
164 Compositor
* mirrored_compositor
,
165 Layer
* mirroring_layer
) OVERRIDE
;
166 virtual void RemoveReflector(scoped_refptr
<Reflector
> reflector
) OVERRIDE
;
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
;
176 scoped_refptr
<cc::TestContextProvider
> offscreen_compositor_contexts_
;
177 scoped_refptr
<cc::TestContextProvider
> shared_main_thread_contexts_
;
179 DISALLOW_COPY_AND_ASSIGN(TestContextFactory
);
182 // Texture provide an abstraction over the external texture that can be passed
184 class COMPOSITOR_EXPORT Texture
: public base::RefCounted
<Texture
> {
186 Texture(bool flipped
, const gfx::Size
& size
, float device_scale_factor
);
188 bool flipped() const { return flipped_
; }
189 gfx::Size
size() const { return size_
; }
190 float device_scale_factor() const { return device_scale_factor_
; }
192 virtual unsigned int PrepareTexture() = 0;
193 virtual WebKit::WebGraphicsContext3D
* HostContext3D() = 0;
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
) {}
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();
205 gfx::Size size_
; // in pixel
208 friend class base::RefCounted
<Texture
>;
211 float device_scale_factor_
;
213 DISALLOW_COPY_AND_ASSIGN(Texture
);
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.
225 class COMPOSITOR_EXPORT CompositorLock
226 : public base::RefCounted
<CompositorLock
>,
227 public base::SupportsWeakPtr
<CompositorLock
> {
229 friend class base::RefCounted
<CompositorLock
>;
230 friend class Compositor
;
232 explicit CompositorLock(Compositor
* compositor
);
237 Compositor
* compositor_
;
238 DISALLOW_COPY_AND_ASSIGN(CompositorLock
);
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).
244 class COMPOSITOR_EXPORT DrawWaiterForTest
: public ui::CompositorObserver
{
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
249 static void Wait(Compositor
* compositor
);
251 // Waits for a commit instead of a draw.
252 static void WaitForCommit(Compositor
* compositor
);
256 virtual ~DrawWaiterForTest();
258 void WaitImpl(Compositor
* compositor
);
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
;
271 scoped_ptr
<base::RunLoop
> wait_run_loop_
;
273 bool wait_for_commit_
;
275 DISALLOW_COPY_AND_ASSIGN(DrawWaiterForTest
);
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
283 class COMPOSITOR_EXPORT Compositor
284 : NON_EXPORTED_BASE(public cc::LayerTreeHostClient
),
285 public base::SupportsWeakPtr
<Compositor
> {
287 Compositor(bool use_software_renderer
,
288 gfx::AcceleratedWidget widget
);
289 virtual ~Compositor();
291 // Set up the compositor ContextFactory for a test environment. Unit tests
292 // that do not have a full content environment need to call this before
293 // initializing the Compositor.
294 // Some tests expect pixel output, and they should pass false for
295 // |allow_test_contexts|. Most unit tests should pass true. Once this has been
296 // called, the Initialize() and Terminate() methods should be used as normal.
297 static void InitializeContextFactoryForTests(bool allow_test_contexts
);
299 static void Initialize();
300 static bool WasInitializedWithThread();
301 static scoped_refptr
<base::MessageLoopProxy
> GetCompositorMessageLoop();
302 static void Terminate();
304 // Schedules a redraw of the layer tree associated with this compositor.
307 // Sets the root of the layer tree drawn by this Compositor. The root layer
308 // must have no parent. The compositor's root layer is reset if the root layer
309 // is destroyed. NULL can be passed to reset the root layer, in which case the
310 // compositor will stop drawing anything.
311 // The Compositor does not own the root layer.
312 const Layer
* root_layer() const { return root_layer_
; }
313 Layer
* root_layer() { return root_layer_
; }
314 void SetRootLayer(Layer
* root_layer
);
316 // Called when we need the compositor to preserve the alpha channel in the
317 // output for situations when we want to render transparently atop something
318 // else, e.g. Aero glass.
319 void SetHostHasTransparentBackground(bool host_has_transparent_background
);
321 // The scale factor of the device that this compositor is
322 // compositing layers on.
323 float device_scale_factor() const { return device_scale_factor_
; }
325 // Draws the scene created by the layer tree and any visual effects.
328 // Where possible, draws are scissored to a damage region calculated from
329 // changes to layer properties. This bypasses that and indicates that
330 // the whole frame needs to be drawn.
331 void ScheduleFullRedraw();
333 // Schedule redraw and append damage_rect to the damage region calculated
334 // from changes to layer properties.
335 void ScheduleRedrawRect(const gfx::Rect
& damage_rect
);
337 void SetLatencyInfo(const ui::LatencyInfo
& latency_info
);
339 // Reads the region |bounds_in_pixel| of the contents of the last rendered
340 // frame into the given bitmap.
341 // Returns false if the pixels could not be read.
342 bool ReadPixels(SkBitmap
* bitmap
, const gfx::Rect
& bounds_in_pixel
);
344 // Sets the compositor's device scale factor and size.
345 void SetScaleAndSize(float scale
, const gfx::Size
& size_in_pixel
);
347 // Returns the size of the widget that is being drawn to in pixel coordinates.
348 const gfx::Size
& size() const { return size_
; }
350 // Sets the background color used for areas that aren't covered by
352 void SetBackgroundColor(SkColor color
);
354 // Returns the widget for this compositor.
355 gfx::AcceleratedWidget
widget() const { return widget_
; }
357 // Compositor does not own observers. It is the responsibility of the
358 // observer to remove itself when it is done observing.
359 void AddObserver(CompositorObserver
* observer
);
360 void RemoveObserver(CompositorObserver
* observer
);
361 bool HasObserver(CompositorObserver
* observer
);
363 // Creates a compositor lock. Returns NULL if it is not possible to lock at
364 // this time (i.e. we're waiting to complete a previous unlock).
365 scoped_refptr
<CompositorLock
> GetCompositorLock();
367 // Internal functions, called back by command-buffer contexts on swap buffer
370 // Signals swap has been posted.
371 void OnSwapBuffersPosted();
373 // Signals swap has completed.
374 void OnSwapBuffersComplete();
376 // Signals swap has aborted (e.g. lost context).
377 void OnSwapBuffersAborted();
379 void OnUpdateVSyncParameters(base::TimeTicks timebase
,
380 base::TimeDelta interval
);
382 // LayerTreeHostClient implementation.
383 virtual void WillBeginMainFrame() OVERRIDE
{}
384 virtual void DidBeginMainFrame() OVERRIDE
{}
385 virtual void Animate(double frame_begin_time
) OVERRIDE
{}
386 virtual void Layout() OVERRIDE
;
387 virtual void ApplyScrollAndScale(gfx::Vector2d scroll_delta
,
388 float page_scale
) OVERRIDE
{}
389 virtual scoped_ptr
<cc::OutputSurface
> CreateOutputSurface(bool fallback
)
391 virtual void DidInitializeOutputSurface(bool success
) OVERRIDE
{}
392 virtual void WillCommit() OVERRIDE
{}
393 virtual void DidCommit() OVERRIDE
;
394 virtual void DidCommitAndDrawFrame() OVERRIDE
;
395 virtual void DidCompleteSwapBuffers() OVERRIDE
;
396 virtual void ScheduleComposite() OVERRIDE
;
397 virtual scoped_refptr
<cc::ContextProvider
>
398 OffscreenContextProvider() OVERRIDE
;
400 int last_started_frame() { return last_started_frame_
; }
401 int last_ended_frame() { return last_ended_frame_
; }
403 bool IsLocked() { return compositor_lock_
!= NULL
; }
405 const cc::LayerTreeDebugState
& GetLayerTreeDebugState() const;
406 void SetLayerTreeDebugState(const cc::LayerTreeDebugState
& debug_state
);
408 // Should the compositor use a software output device. If false, it may still
409 // use a software output device if no GPU is available.
410 bool use_software_renderer() { return use_software_renderer_
; }
413 friend class base::RefCounted
<Compositor
>;
414 friend class CompositorLock
;
416 // Called by CompositorLock.
417 void UnlockCompositor();
419 // Called to release any pending CompositorLock
420 void CancelCompositorLock();
422 // Notifies the compositor that compositing is complete.
427 // The root of the Layer tree drawn by this compositor.
430 ObserverList
<CompositorObserver
> observer_list_
;
432 gfx::AcceleratedWidget widget_
;
433 scoped_refptr
<cc::Layer
> root_web_layer_
;
434 scoped_ptr
<cc::LayerTreeHost
> host_
;
436 // Used to verify that we have at most one draw swap in flight.
437 scoped_ptr
<PostedSwapQueue
> posted_swaps_
;
439 // The device scale factor of the monitor that this compositor is compositing
441 float device_scale_factor_
;
443 int last_started_frame_
;
444 int last_ended_frame_
;
446 bool next_draw_is_resize_
;
448 bool disable_schedule_composite_
;
450 CompositorLock
* compositor_lock_
;
452 // Prevent more than one draw from being scheduled.
453 bool defer_draw_scheduling_
;
455 // Used to prevent Draw()s while a composite is in progress.
456 bool waiting_on_compositing_end_
;
457 bool draw_on_compositing_end_
;
459 base::WeakPtrFactory
<Compositor
> schedule_draw_factory_
;
461 bool use_software_renderer_
;
463 DISALLOW_COPY_AND_ASSIGN(Compositor
);
468 #endif // UI_COMPOSITOR_COMPOSITOR_H_