1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #ifndef GFX_LAYERMANAGER_H
8 #define GFX_LAYERMANAGER_H
9 
10 #include <cstdint>         // for uint32_t, uint64_t, int32_t, uint8_t
11 #include <iosfwd>          // for stringstream
12 #include <new>             // for operator new
13 #include <unordered_set>   // for unordered_set
14 #include <utility>         // for forward
15 #include "FrameMetrics.h"  // for ScrollUpdatesMap
16 #include "ImageContainer.h"  // for ImageContainer, ImageContainer::Mode, ImageContainer::SYNCHRONOUS
17 #include "mozilla/AlreadyAddRefed.h"  // for already_AddRefed
18 #include "mozilla/Maybe.h"            // for Maybe
19 #include "mozilla/RefPtr.h"           // for RefPtr
20 #include "mozilla/TimeStamp.h"        // for TimeStamp
21 #include "mozilla/UniquePtr.h"        // for UniquePtr
22 #include "mozilla/dom/Animation.h"    // for Animation
23 #include "mozilla/gfx/Point.h"        // for IntSize
24 #include "mozilla/gfx/Types.h"        // for SurfaceFormat
25 #include "mozilla/gfx/UserData.h"     // for UserData, UserDataKey (ptr only)
26 #include "mozilla/layers/CompositorTypes.h"  // for TextureFactoryIdentifier
27 #include "mozilla/layers/ScrollableLayerGuid.h"  // for ScrollableLayerGuid, ScrollableLayerGuid::ViewID
28 #include "nsHashKeys.h"                          // for nsUint64HashKey
29 #include "nsISupports.h"        // for NS_INLINE_DECL_REFCOUNTING
30 #include "nsIWidget.h"          // for nsIWidget
31 #include "nsRefPtrHashtable.h"  // for nsRefPtrHashtable
32 #include "nsRegion.h"           // for nsIntRegion
33 #include "nsStringFwd.h"        // for nsCString, nsAString
34 #include "nsTArray.h"           // for nsTArray
35 
36 // XXX These includes could be avoided by moving function implementations to the
37 // cpp file
38 #include "mozilla/Assertions.h"  // for AssertionConditionType, MOZ_ASSERT, MOZ_A...
39 #include "mozilla/layers/LayersTypes.h"  // for CompositionPayload, LayersBackend, TransactionId, DrawRegionClip, LayersBackend:...
40 
41 class gfxContext;
42 
43 extern uint8_t gLayerManagerLayerBuilder;
44 
45 namespace mozilla {
46 
47 class FrameLayerBuilder;
48 class LogModule;
49 class ScrollPositionUpdate;
50 
51 namespace gfx {
52 class DrawTarget;
53 }  // namespace gfx
54 
55 namespace layers {
56 
57 class AsyncPanZoomController;
58 class BasicLayerManager;
59 class ClientLayerManager;
60 class HostLayerManager;
61 class Layer;
62 class LayerMetricsWrapper;
63 class PaintedLayer;
64 class ContainerLayer;
65 class ImageLayer;
66 class ColorLayer;
67 class CompositorBridgeChild;
68 class CanvasLayer;
69 class ReadbackLayer;
70 class ReadbackProcessor;
71 class RefLayer;
72 class HostLayer;
73 class FocusTarget;
74 class KnowsCompositor;
75 class ShadowableLayer;
76 class ShadowLayerForwarder;
77 class LayerManagerComposite;
78 class TransactionIdAllocator;
79 class FrameUniformityData;
80 class PersistentBufferProvider;
81 class GlyphArray;
82 class WebRenderLayerManager;
83 struct AnimData;
84 
85 namespace layerscope {
86 class LayersPacket;
87 }  // namespace layerscope
88 
89 // Defined in LayerUserData.h; please include that file instead.
90 class LayerUserData;
91 
92 class DidCompositeObserver {
93  public:
94   virtual void DidComposite() = 0;
95 };
96 
97 class FrameRecorder {
98  public:
99   /**
100    * Record (and return) frame-intervals and paint-times for frames which were
101    * presented between calling StartFrameTimeRecording and
102    * StopFrameTimeRecording.
103    *
104    * - Uses a cyclic buffer and serves concurrent consumers, so if Stop is
105    *   called too late
106    *     (elements were overwritten since Start), result is considered invalid
107    *      and hence empty.)
108    * - Buffer is capable of holding 10 seconds @ 60fps (or more if frames were
109    *   less frequent).
110    *     Can be changed (up to 1 hour) via pref:
111    *     toolkit.framesRecording.bufferSize.
112    * - Note: the first frame-interval may be longer than expected because last
113    *   frame
114    *     might have been presented some time before calling
115    *     StartFrameTimeRecording.
116    */
117 
118   /**
119    * Returns a handle which represents current recording start position.
120    */
121   virtual uint32_t StartFrameTimeRecording(int32_t aBufferSize);
122 
123   /**
124    *  Clears, then populates aFrameIntervals with the recorded frame timing
125    *  data. The array will be empty if data was overwritten since
126    *  aStartIndex was obtained.
127    */
128   virtual void StopFrameTimeRecording(uint32_t aStartIndex,
129                                       nsTArray<float>& aFrameIntervals);
130 
131   void RecordFrame();
132 
133  private:
134   struct FramesTimingRecording {
135     // Stores state and data for frame intervals and paint times recording.
136     // see LayerManager::StartFrameTimeRecording() at Layers.cpp for more
137     // details.
FramesTimingRecordingFramesTimingRecording138     FramesTimingRecording()
139         : mNextIndex(0),
140           mLatestStartIndex(0),
141           mCurrentRunStartIndex(0),
142           mIsPaused(true) {}
143     nsTArray<float> mIntervals;
144     TimeStamp mLastFrameTime;
145     uint32_t mNextIndex;
146     uint32_t mLatestStartIndex;
147     uint32_t mCurrentRunStartIndex;
148     bool mIsPaused;
149   };
150   FramesTimingRecording mRecording;
151 };
152 
153 /*
154  * Motivation: For truly smooth animation and video playback, we need to
155  * be able to compose frames and render them on a dedicated thread (i.e.
156  * off the main thread where DOM manipulation, script execution and layout
157  * induce difficult-to-bound latency). This requires Gecko to construct
158  * some kind of persistent scene structure (graph or tree) that can be
159  * safely transmitted across threads. We have other scenarios (e.g. mobile
160  * browsing) where retaining some rendered data between paints is desired
161  * for performance, so again we need a retained scene structure.
162  *
163  * Our retained scene structure is a layer tree. Each layer represents
164  * content which can be composited onto a destination surface; the root
165  * layer is usually composited into a window, and non-root layers are
166  * composited into their parent layers. Layers have attributes (e.g.
167  * opacity and clipping) that influence their compositing.
168  *
169  * We want to support a variety of layer implementations, including
170  * a simple "immediate mode" implementation that doesn't retain any
171  * rendered data between paints (i.e. uses cairo in just the way that
172  * Gecko used it before layers were introduced). But we also don't want
173  * to have bifurcated "layers"/"non-layers" rendering paths in Gecko.
174  * Therefore the layers API is carefully designed to permit maximally
175  * efficient implementation in an "immediate mode" style. See the
176  * BasicLayerManager for such an implementation.
177  */
178 
179 /**
180  * A LayerManager controls a tree of layers. All layers in the tree
181  * must use the same LayerManager.
182  *
183  * All modifications to a layer tree must happen inside a transaction.
184  * Only the state of the layer tree at the end of a transaction is
185  * rendered. Transactions cannot be nested
186  *
187  * Each transaction has two phases:
188  * 1) Construction: layers are created, inserted, removed and have
189  * properties set on them in this phase.
190  * BeginTransaction and BeginTransactionWithTarget start a transaction in
191  * the Construction phase.
192  * 2) Drawing: PaintedLayers are rendered into in this phase, in tree
193  * order. When the client has finished drawing into the PaintedLayers, it should
194  * call EndTransaction to complete the transaction.
195  *
196  * All layer API calls happen on the main thread.
197  *
198  * Layers are refcounted. The layer manager holds a reference to the
199  * root layer, and each container layer holds a reference to its children.
200  */
201 class LayerManager : public FrameRecorder {
202   NS_INLINE_DECL_REFCOUNTING(LayerManager)
203 
204  protected:
205   typedef mozilla::gfx::DrawTarget DrawTarget;
206   typedef mozilla::gfx::IntSize IntSize;
207   typedef mozilla::gfx::SurfaceFormat SurfaceFormat;
208 
209  public:
210   LayerManager();
211 
212   /**
213    * Release layers and resources held by this layer manager, and mark
214    * it as destroyed.  Should do any cleanup necessary in preparation
215    * for its widget going away.  After this call, only user data calls
216    * are valid on the layer manager.
217    */
218   virtual void Destroy();
IsDestroyed()219   bool IsDestroyed() { return mDestroyed; }
220 
AsShadowForwarder()221   virtual ShadowLayerForwarder* AsShadowForwarder() { return nullptr; }
222 
AsKnowsCompositor()223   virtual KnowsCompositor* AsKnowsCompositor() { return nullptr; }
224 
AsLayerManagerComposite()225   virtual LayerManagerComposite* AsLayerManagerComposite() { return nullptr; }
226 
AsClientLayerManager()227   virtual ClientLayerManager* AsClientLayerManager() { return nullptr; }
228 
AsBasicLayerManager()229   virtual BasicLayerManager* AsBasicLayerManager() { return nullptr; }
AsHostLayerManager()230   virtual HostLayerManager* AsHostLayerManager() { return nullptr; }
231 
AsWebRenderLayerManager()232   virtual WebRenderLayerManager* AsWebRenderLayerManager() { return nullptr; }
233 
234   /**
235    * Returns true if this LayerManager is owned by an nsIWidget,
236    * and is used for drawing into the widget.
237    */
IsWidgetLayerManager()238   virtual bool IsWidgetLayerManager() { return true; }
IsInactiveLayerManager()239   virtual bool IsInactiveLayerManager() { return false; }
240 
241   /**
242    * Start a new transaction. Nested transactions are not allowed so
243    * there must be no transaction currently in progress.
244    * This transaction will update the state of the window from which
245    * this LayerManager was obtained.
246    */
247   virtual bool BeginTransaction(const nsCString& aURL = nsCString()) = 0;
248   /**
249    * Start a new transaction. Nested transactions are not allowed so
250    * there must be no transaction currently in progress.
251    * This transaction will render the contents of the layer tree to
252    * the given target context. The rendering will be complete when
253    * EndTransaction returns.
254    */
255   virtual bool BeginTransactionWithTarget(
256       gfxContext* aTarget, const nsCString& aURL = nsCString()) = 0;
257 
258   enum EndTransactionFlags {
259     END_DEFAULT = 0,
260     END_NO_IMMEDIATE_REDRAW = 1 << 0,  // Do not perform the drawing phase
261     END_NO_COMPOSITE =
262         1 << 1,  // Do not composite after drawing painted layer contents.
263     END_NO_REMOTE_COMPOSITE = 1 << 2  // Do not schedule a composition with a
264                                       // remote Compositor, if one exists.
265   };
266 
GetLayerBuilder()267   FrameLayerBuilder* GetLayerBuilder() {
268     return reinterpret_cast<FrameLayerBuilder*>(
269         GetUserData(&gLayerManagerLayerBuilder));
270   }
271 
272   /**
273    * Attempts to end an "empty transaction". There must have been no
274    * changes to the layer tree since the BeginTransaction().
275    * It's possible for this to fail; PaintedLayers may need to be updated
276    * due to VRAM data being lost, for example. In such cases this method
277    * returns false, and the caller must proceed with a normal layer tree
278    * update and EndTransaction.
279    */
280   virtual bool EndEmptyTransaction(
281       EndTransactionFlags aFlags = END_DEFAULT) = 0;
282 
283   /**
284    * Function called to draw the contents of each PaintedLayer.
285    * aRegionToDraw contains the region that needs to be drawn.
286    * This would normally be a subregion of the visible region.
287    * The callee must draw all of aRegionToDraw. Drawing outside
288    * aRegionToDraw will be clipped out or ignored.
289    * The callee must draw all of aRegionToDraw.
290    * This region is relative to 0,0 in the PaintedLayer.
291    *
292    * aDirtyRegion should contain the total region that is be due to be painted
293    * during the transaction, even though only aRegionToDraw should be drawn
294    * during this call. aRegionToDraw must be entirely contained within
295    * aDirtyRegion. If the total dirty region is unknown it is okay to pass a
296    * subregion of the total dirty region, e.g. just aRegionToDraw, though it
297    * may not be as efficient.
298    *
299    * aRegionToInvalidate contains a region whose contents have been
300    * changed by the layer manager and which must therefore be invalidated.
301    * For example, this could be non-empty if a retained layer internally
302    * switches from RGBA to RGB or back ... we might want to repaint it to
303    * consistently use subpixel-AA or not.
304    * This region is relative to 0,0 in the PaintedLayer.
305    * aRegionToInvalidate may contain areas that are outside
306    * aRegionToDraw; the callee must ensure that these areas are repainted
307    * in the current layer manager transaction or in a later layer
308    * manager transaction.
309    *
310    * aContext must not be used after the call has returned.
311    * We guarantee that buffered contents in the visible
312    * region are valid once drawing is complete.
313    *
314    * The origin of aContext is 0,0 in the PaintedLayer.
315    */
316   typedef void (*DrawPaintedLayerCallback)(
317       PaintedLayer* aLayer, gfxContext* aContext,
318       const nsIntRegion& aRegionToDraw, const nsIntRegion& aDirtyRegion,
319       DrawRegionClip aClip, const nsIntRegion& aRegionToInvalidate,
320       void* aCallbackData);
321 
322   /**
323    * Finish the construction phase of the transaction, perform the
324    * drawing phase, and end the transaction.
325    * During the drawing phase, all PaintedLayers in the tree are
326    * drawn in tree order, exactly once each, except for those layers
327    * where it is known that the visible region is empty.
328    */
329   virtual void EndTransaction(DrawPaintedLayerCallback aCallback,
330                               void* aCallbackData,
331                               EndTransactionFlags aFlags = END_DEFAULT) = 0;
332 
333   /**
334    * Schedule a composition with the remote Compositor, if one exists
335    * for this LayerManager. Useful in conjunction with the
336    * END_NO_REMOTE_COMPOSITE flag to EndTransaction.
337    */
ScheduleComposite()338   virtual void ScheduleComposite() {}
339 
SetNeedsComposite(bool aNeedsComposite)340   virtual void SetNeedsComposite(bool aNeedsComposite) {}
NeedsComposite()341   virtual bool NeedsComposite() const { return false; }
342 
HasShadowManagerInternal()343   virtual bool HasShadowManagerInternal() const { return false; }
HasShadowManager()344   bool HasShadowManager() const { return HasShadowManagerInternal(); }
StorePluginWidgetConfigurations(const nsTArray<nsIWidget::Configuration> & aConfigurations)345   virtual void StorePluginWidgetConfigurations(
346       const nsTArray<nsIWidget::Configuration>& aConfigurations) {}
IsSnappingEffectiveTransforms()347   bool IsSnappingEffectiveTransforms() { return mSnapEffectiveTransforms; }
348 
349   /**
350    * Returns true if the underlying platform can properly support layers with
351    * SurfaceMode::SURFACE_COMPONENT_ALPHA.
352    */
353   static bool LayersComponentAlphaEnabled();
354 
355   /**
356    * Returns true if this LayerManager can properly support layers with
357    * SurfaceMode::SURFACE_COMPONENT_ALPHA. LayerManagers that can't will use
358    * transparent surfaces (and lose subpixel-AA for text).
359    */
360   virtual bool AreComponentAlphaLayersEnabled();
361 
362   /**
363    * Returns true if this LayerManager always requires an intermediate surface
364    * to render blend operations.
365    */
BlendingRequiresIntermediateSurface()366   virtual bool BlendingRequiresIntermediateSurface() { return false; }
367 
368   /**
369    * CONSTRUCTION PHASE ONLY
370    * Set the root layer. The root layer is initially null. If there is
371    * no root layer, EndTransaction won't draw anything.
372    */
373   virtual void SetRoot(Layer* aLayer) = 0;
374   /**
375    * Can be called anytime
376    */
GetRoot()377   Layer* GetRoot() { return mRoot; }
378 
379   /**
380    * Does a breadth-first search from the root layer to find the first
381    * scrollable layer, and returns its ViewID. Note that there may be
382    * other layers in the tree which share the same ViewID.
383    * Can be called any time.
384    */
385   ScrollableLayerGuid::ViewID GetRootScrollableLayerId();
386 
387   /**
388    * Returns a LayerMetricsWrapper containing the Root
389    * Content Documents layer.
390    */
391   LayerMetricsWrapper GetRootContentLayer();
392 
393   /**
394    * CONSTRUCTION PHASE ONLY
395    * Called when a managee has mutated.
396    * Subclasses overriding this method must first call their
397    * superclass's impl
398    */
Mutated(Layer * aLayer)399   virtual void Mutated(Layer* aLayer) {}
MutatedSimple(Layer * aLayer)400   virtual void MutatedSimple(Layer* aLayer) {}
401 
402   /**
403    * Hints that can be used during PaintedLayer creation to influence the type
404    * or properties of the layer created.
405    *
406    * NONE: No hint.
407    * SCROLLABLE: This layer may represent scrollable content.
408    */
409   enum PaintedLayerCreationHint { NONE, SCROLLABLE };
410 
411   /**
412    * CONSTRUCTION PHASE ONLY
413    * Create a PaintedLayer for this manager's layer tree.
414    */
415   virtual already_AddRefed<PaintedLayer> CreatePaintedLayer() = 0;
416   /**
417    * CONSTRUCTION PHASE ONLY
418    * Create a PaintedLayer for this manager's layer tree, with a creation hint
419    * parameter to help optimise the type of layer created.
420    */
CreatePaintedLayerWithHint(PaintedLayerCreationHint)421   virtual already_AddRefed<PaintedLayer> CreatePaintedLayerWithHint(
422       PaintedLayerCreationHint) {
423     return CreatePaintedLayer();
424   }
425   /**
426    * CONSTRUCTION PHASE ONLY
427    * Create a ContainerLayer for this manager's layer tree.
428    */
429   virtual already_AddRefed<ContainerLayer> CreateContainerLayer() = 0;
430   /**
431    * CONSTRUCTION PHASE ONLY
432    * Create an ImageLayer for this manager's layer tree.
433    */
434   virtual already_AddRefed<ImageLayer> CreateImageLayer() = 0;
435   /**
436    * CONSTRUCTION PHASE ONLY
437    * Create a ColorLayer for this manager's layer tree.
438    */
439   virtual already_AddRefed<ColorLayer> CreateColorLayer() = 0;
440   /**
441    * CONSTRUCTION PHASE ONLY
442    * Create a CanvasLayer for this manager's layer tree.
443    */
444   virtual already_AddRefed<CanvasLayer> CreateCanvasLayer() = 0;
445   /**
446    * CONSTRUCTION PHASE ONLY
447    * Create a ReadbackLayer for this manager's layer tree.
448    */
CreateReadbackLayer()449   virtual already_AddRefed<ReadbackLayer> CreateReadbackLayer() {
450     return nullptr;
451   }
452   /**
453    * CONSTRUCTION PHASE ONLY
454    * Create a RefLayer for this manager's layer tree.
455    */
CreateRefLayer()456   virtual already_AddRefed<RefLayer> CreateRefLayer() { return nullptr; }
457   /**
458    * Can be called anytime, from any thread.
459    *
460    * Creates an Image container which forwards its images to the compositor
461    * within layer transactions on the main thread or asynchronously using the
462    * ImageBridge IPDL protocol. In the case of asynchronous, If the protocol is
463    * not available, the returned ImageContainer will forward images within layer
464    * transactions.
465    */
466   static already_AddRefed<ImageContainer> CreateImageContainer(
467       ImageContainer::Mode flag = ImageContainer::SYNCHRONOUS);
468 
469   /**
470    * Type of layer manager his is. This is to be used sparsely in order to
471    * avoid a lot of Layers backend specific code. It should be used only when
472    * Layers backend specific functionality is necessary.
473    */
474   virtual LayersBackend GetBackendType() = 0;
475 
476   /**
477    * Type of layers backend that will be used to composite this layer tree.
478    * When compositing is done remotely, then this returns the layers type
479    * of the compositor.
480    */
GetCompositorBackendType()481   virtual LayersBackend GetCompositorBackendType() { return GetBackendType(); }
482 
483   /**
484    * Creates a DrawTarget which is optimized for inter-operating with this
485    * layer manager.
486    */
487   virtual already_AddRefed<DrawTarget> CreateOptimalDrawTarget(
488       const IntSize& aSize, SurfaceFormat imageFormat);
489 
490   /**
491    * Creates a DrawTarget for alpha masks which is optimized for inter-
492    * operating with this layer manager. In contrast to CreateOptimalDrawTarget,
493    * this surface is optimised for drawing alpha only and we assume that
494    * drawing the mask is fairly simple.
495    */
496   virtual already_AddRefed<DrawTarget> CreateOptimalMaskDrawTarget(
497       const IntSize& aSize);
498 
499   /**
500    * Creates a DrawTarget for use with canvas which is optimized for
501    * inter-operating with this layermanager.
502    */
503   virtual already_AddRefed<mozilla::gfx::DrawTarget> CreateDrawTarget(
504       const mozilla::gfx::IntSize& aSize, mozilla::gfx::SurfaceFormat aFormat);
505 
506   /**
507    * Creates a PersistentBufferProvider for use with canvas which is optimized
508    * for inter-operating with this layermanager.
509    */
510   virtual already_AddRefed<PersistentBufferProvider>
511   CreatePersistentBufferProvider(const mozilla::gfx::IntSize& aSize,
512                                  mozilla::gfx::SurfaceFormat aFormat);
513 
CanUseCanvasLayerForSize(const gfx::IntSize & aSize)514   virtual bool CanUseCanvasLayerForSize(const gfx::IntSize& aSize) {
515     return true;
516   }
517 
518   /**
519    * returns the maximum texture size on this layer backend, or INT32_MAX
520    * if there is no maximum
521    */
522   virtual int32_t GetMaxTextureSize() const = 0;
523 
524   /**
525    * Return the name of the layer manager's backend.
526    */
527   virtual void GetBackendName(nsAString& aName) = 0;
528 
529   /**
530    * This setter can be used anytime. The user data for all keys is
531    * initially null. Ownership pases to the layer manager.
532    */
SetUserData(void * aKey,LayerUserData * aData)533   void SetUserData(void* aKey, LayerUserData* aData) {
534     mUserData.Add(static_cast<gfx::UserDataKey*>(aKey), aData,
535                   LayerUserDataDestroy);
536   }
537   /**
538    * This can be used anytime. Ownership passes to the caller!
539    */
540   UniquePtr<LayerUserData> RemoveUserData(void* aKey);
541 
542   /**
543    * This getter can be used anytime.
544    */
HasUserData(void * aKey)545   bool HasUserData(void* aKey) {
546     return mUserData.Has(static_cast<gfx::UserDataKey*>(aKey));
547   }
548   /**
549    * This getter can be used anytime. Ownership is retained by the layer
550    * manager.
551    */
GetUserData(void * aKey)552   LayerUserData* GetUserData(void* aKey) const {
553     return static_cast<LayerUserData*>(
554         mUserData.Get(static_cast<gfx::UserDataKey*>(aKey)));
555   }
556 
557   /**
558    * Must be called outside of a layers transaction.
559    *
560    * For the subtree rooted at |aSubtree|, this attempts to free up
561    * any free-able resources like retained buffers, but may do nothing
562    * at all.  After this call, the layer tree is left in an undefined
563    * state; the layers in |aSubtree|'s subtree may no longer have
564    * buffers with valid content and may no longer be able to draw
565    * their visible and valid regions.
566    *
567    * In general, a painting or forwarding transaction on |this| must
568    * complete on the tree before it returns to a valid state.
569    *
570    * Resource freeing begins from |aSubtree| or |mRoot| if |aSubtree|
571    * is null.  |aSubtree|'s manager must be this.
572    */
573   virtual void ClearCachedResources(Layer* aSubtree = nullptr) {}
574 
575   /**
576    * Flag the next paint as the first for a document.
577    */
SetIsFirstPaint()578   virtual void SetIsFirstPaint() {}
GetIsFirstPaint()579   virtual bool GetIsFirstPaint() const { return false; }
580 
581   /**
582    * Set the current focus target to be sent with the next paint.
583    */
SetFocusTarget(const FocusTarget & aFocusTarget)584   virtual void SetFocusTarget(const FocusTarget& aFocusTarget) {}
585 
586   /**
587    * Make sure that the previous transaction has been entirely
588    * completed.
589    *
590    * Note: This may sychronously wait on a remote compositor
591    * to complete rendering.
592    */
FlushRendering()593   virtual void FlushRendering() {}
594 
595   /**
596    * Make sure that the previous transaction has been
597    * received. This will synchronsly wait on a remote compositor. */
WaitOnTransactionProcessed()598   virtual void WaitOnTransactionProcessed() {}
599 
SendInvalidRegion(const nsIntRegion & aRegion)600   virtual void SendInvalidRegion(const nsIntRegion& aRegion) {}
601 
602   /**
603    * Checks if we need to invalidate the OS widget to trigger
604    * painting when updating this layer manager.
605    */
NeedsWidgetInvalidation()606   virtual bool NeedsWidgetInvalidation() { return true; }
607 
Name()608   virtual const char* Name() const { return "???"; }
609 
610   /**
611    * Dump information about this layer manager and its managed tree to
612    * aStream.
613    */
614   void Dump(std::stringstream& aStream, const char* aPrefix = "",
615             bool aDumpHtml = false, bool aSorted = false);
616   /**
617    * Dump information about just this layer manager itself to aStream
618    */
619   void DumpSelf(std::stringstream& aStream, const char* aPrefix = "",
620                 bool aSorted = false);
621   void Dump(bool aSorted = false);
622 
623   /**
624    * Dump information about this layer manager and its managed tree to
625    * layerscope packet.
626    */
627   void Dump(layerscope::LayersPacket* aPacket);
628 
629   /**
630    * Log information about this layer manager and its managed tree to
631    * the NSPR log (if enabled for "Layers").
632    */
633   void Log(const char* aPrefix = "");
634   /**
635    * Log information about just this layer manager itself to the NSPR
636    * log (if enabled for "Layers").
637    */
638   void LogSelf(const char* aPrefix = "");
639 
640   static bool IsLogEnabled();
641   static mozilla::LogModule* GetLog();
642 
IsCompositingCheap(LayersBackend aBackend)643   bool IsCompositingCheap(LayersBackend aBackend) {
644     // LayersBackend::LAYERS_NONE is an error state, but in that case we should
645     // try to avoid loading the compositor!
646     return LayersBackend::LAYERS_BASIC != aBackend &&
647            LayersBackend::LAYERS_NONE != aBackend;
648   }
649 
IsCompositingCheap()650   virtual bool IsCompositingCheap() { return true; }
651 
IsInTransaction()652   bool IsInTransaction() const { return mInTransaction; }
GetFrameUniformity(FrameUniformityData * aOutData)653   virtual void GetFrameUniformity(FrameUniformityData* aOutData) {}
654 
SetRegionToClear(const nsIntRegion & aRegion)655   virtual void SetRegionToClear(const nsIntRegion& aRegion) {
656     mRegionToClear = aRegion;
657   }
658 
RequestProperty(const nsAString & property)659   virtual float RequestProperty(const nsAString& property) { return -1; }
660 
GetAnimationReadyTime()661   const TimeStamp& GetAnimationReadyTime() const { return mAnimationReadyTime; }
662 
AsyncPanZoomEnabled()663   virtual bool AsyncPanZoomEnabled() const { return false; }
664 
665   static void LayerUserDataDestroy(void* data);
666 
AddPaintedPixelCount(int32_t aCount)667   void AddPaintedPixelCount(int32_t aCount) { mPaintedPixelCount += aCount; }
668 
GetAndClearPaintedPixelCount()669   uint32_t GetAndClearPaintedPixelCount() {
670     uint32_t count = mPaintedPixelCount;
671     mPaintedPixelCount = 0;
672     return count;
673   }
674 
SetLayersObserverEpoch(LayersObserverEpoch aEpoch)675   virtual void SetLayersObserverEpoch(LayersObserverEpoch aEpoch) {}
676 
DidComposite(TransactionId aTransactionId,const mozilla::TimeStamp & aCompositeStart,const mozilla::TimeStamp & aCompositeEnd)677   virtual void DidComposite(TransactionId aTransactionId,
678                             const mozilla::TimeStamp& aCompositeStart,
679                             const mozilla::TimeStamp& aCompositeEnd) {}
680 
AddDidCompositeObserver(DidCompositeObserver * aObserver)681   virtual void AddDidCompositeObserver(DidCompositeObserver* aObserver) {
682     MOZ_CRASH("GFX: LayerManager");
683   }
RemoveDidCompositeObserver(DidCompositeObserver * aObserver)684   virtual void RemoveDidCompositeObserver(DidCompositeObserver* aObserver) {
685     MOZ_CRASH("GFX: LayerManager");
686   }
687 
UpdateTextureFactoryIdentifier(const TextureFactoryIdentifier & aNewIdentifier)688   virtual void UpdateTextureFactoryIdentifier(
689       const TextureFactoryIdentifier& aNewIdentifier) {}
690 
GetTextureFactoryIdentifier()691   virtual TextureFactoryIdentifier GetTextureFactoryIdentifier() {
692     return TextureFactoryIdentifier();
693   }
694 
SetTransactionIdAllocator(TransactionIdAllocator * aAllocator)695   virtual void SetTransactionIdAllocator(TransactionIdAllocator* aAllocator) {}
696 
GetLastTransactionId()697   virtual TransactionId GetLastTransactionId() { return TransactionId{0}; }
698 
GetCompositorBridgeChild()699   virtual CompositorBridgeChild* GetCompositorBridgeChild() { return nullptr; }
700 
RegisterPayload(const CompositionPayload & aPayload)701   void RegisterPayload(const CompositionPayload& aPayload) {
702     mPayload.AppendElement(aPayload);
703     MOZ_ASSERT(mPayload.Length() < 10000);
704   }
705 
RegisterPayloads(const nsTArray<CompositionPayload> & aPayload)706   void RegisterPayloads(const nsTArray<CompositionPayload>& aPayload) {
707     mPayload.AppendElements(aPayload);
708     MOZ_ASSERT(mPayload.Length() < 10000);
709   }
710 
711   virtual void PayloadPresented(const TimeStamp& aTimeStamp);
712 
SetContainsSVG(bool aContainsSVG)713   void SetContainsSVG(bool aContainsSVG) { mContainsSVG = aContainsSVG; }
714 
715   void AddPartialPrerenderedAnimation(uint64_t aCompositorAnimationId,
716                                       dom::Animation* aAnimation);
717   void RemovePartialPrerenderedAnimation(uint64_t aCompositorAnimationId,
718                                          dom::Animation* aAnimation);
719   void UpdatePartialPrerenderedAnimations(
720       const nsTArray<uint64_t>& aJankedAnimations);
721 
722  protected:
723   RefPtr<Layer> mRoot;
724   gfx::UserData mUserData;
725   bool mDestroyed;
726   bool mSnapEffectiveTransforms;
727 
728   nsIntRegion mRegionToClear;
729 
730   // Protected destructor, to discourage deletion outside of Release():
731   virtual ~LayerManager();
732 
733   // Print interesting information about this into aStreamo.  Internally
734   // used to implement Dump*() and Log*().
735   virtual void PrintInfo(std::stringstream& aStream, const char* aPrefix);
736 
737   // Print interesting information about this into layerscope packet.
738   // Internally used to implement Dump().
739   virtual void DumpPacket(layerscope::LayersPacket* aPacket);
740 
741   uint64_t mId;
742   bool mInTransaction;
743 
744   // Used for tracking CONTENT_FRAME_TIME_WITH_SVG
745   bool mContainsSVG;
746   // The time when painting most recently finished. This is recorded so that
747   // we can time any play-pending animations from this point.
748   TimeStamp mAnimationReadyTime;
749   // The count of pixels that were painted in the current transaction.
750   uint32_t mPaintedPixelCount;
751   // The payload associated with currently pending painting work, for
752   // client layer managers that typically means payload that is part of the
753   // 'upcoming transaction', for HostLayerManagers this typically means
754   // what has been included in received transactions to be presented on the
755   // next composite.
756   // IMPORTANT: Clients should take care to clear this or risk it slowly
757   // growing out of control.
758   nsTArray<CompositionPayload> mPayload;
759   // Transform animations which are not fully pre-rendered because it's on a
760   // large frame.  We need to update the pre-rendered area once after we tried
761   // to composite area which is outside of the pre-rendered area on the
762   // compositor.
763   nsRefPtrHashtable<nsUint64HashKey, dom::Animation>
764       mPartialPrerenderedAnimations;
765 
766  public:
767   /*
768    * Methods to store/get/clear a "pending scroll info update" object on a
769    * per-scrollid basis. This is used for empty transactions that push over
770    * scroll position updates to the APZ code.
771    */
772   virtual bool AddPendingScrollUpdateForNextTransaction(
773       ScrollableLayerGuid::ViewID aScrollId,
774       const ScrollPositionUpdate& aUpdateInfo);
775   Maybe<nsTArray<ScrollPositionUpdate>> GetPendingScrollInfoUpdate(
776       ScrollableLayerGuid::ViewID aScrollId);
777   std::unordered_set<ScrollableLayerGuid::ViewID>
778   ClearPendingScrollInfoUpdate();
779 
780  protected:
781   ScrollUpdatesMap mPendingScrollUpdates;
782 };
783 
784 }  // namespace layers
785 }  // namespace mozilla
786 
787 #endif /* GFX_LAYERS_H */
788