1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set sw=4 ts=8 et 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 mozilla_layers_CompositorBridgeParent_h
8 #define mozilla_layers_CompositorBridgeParent_h
9 
10 // Enable this pref to turn on compositor performance warning.
11 // This will print warnings if the compositor isn't meeting
12 // its responsiveness objectives:
13 //    1) Compose a frame within 15ms of receiving a ScheduleCompositeCall
14 //    2) Unless a frame was composited within the throttle threshold in
15 //       which the deadline will be 15ms + throttle threshold
16 //#define COMPOSITOR_PERFORMANCE_WARNING
17 
18 #include <stdint.h>                     // for uint64_t
19 #include "Layers.h"                     // for Layer
20 #include "mozilla/Assertions.h"         // for MOZ_ASSERT_HELPER2
21 #include "mozilla/Attributes.h"         // for override
22 #include "mozilla/Maybe.h"
23 #include "mozilla/Monitor.h"            // for Monitor
24 #include "mozilla/RefPtr.h"             // for RefPtr
25 #include "mozilla/TimeStamp.h"          // for TimeStamp
26 #include "mozilla/dom/ipc/IdType.h"
27 #include "mozilla/gfx/Point.h"          // for IntSize
28 #include "mozilla/ipc/ProtocolUtils.h"
29 #include "mozilla/ipc/SharedMemory.h"
30 #include "mozilla/layers/CompositorController.h"
31 #include "mozilla/layers/GeckoContentController.h"
32 #include "mozilla/layers/ISurfaceAllocator.h" // for ShmemAllocator
33 #include "mozilla/layers/LayersMessages.h"  // for TargetConfig
34 #include "mozilla/layers/MetricsSharingController.h"
35 #include "mozilla/layers/PCompositorBridgeParent.h"
36 #include "mozilla/layers/APZTestData.h"
37 #include "mozilla/widget/CompositorWidget.h"
38 #include "nsISupportsImpl.h"
39 #include "ThreadSafeRefcountingWithMainThreadDestruction.h"
40 #include "mozilla/VsyncDispatcher.h"
41 
42 class MessageLoop;
43 class nsIWidget;
44 
45 namespace mozilla {
46 
47 class CancelableRunnable;
48 
49 namespace gfx {
50 class DrawTarget;
51 class GPUProcessManager;
52 class GPUParent;
53 } // namespace gfx
54 
55 namespace ipc {
56 class Shmem;
57 } // namespace ipc
58 
59 namespace layers {
60 
61 class APZCTreeManager;
62 class APZCTreeManagerParent;
63 class AsyncCompositionManager;
64 class Compositor;
65 class CompositorBridgeParent;
66 class LayerManagerComposite;
67 class LayerTransactionParent;
68 class PAPZParent;
69 class CrossProcessCompositorBridgeParent;
70 class CompositorThreadHolder;
71 class InProcessCompositorSession;
72 
73 struct ScopedLayerTreeRegistration
74 {
75   ScopedLayerTreeRegistration(APZCTreeManager* aApzctm,
76                               uint64_t aLayersId,
77                               Layer* aRoot,
78                               GeckoContentController* aController);
79   ~ScopedLayerTreeRegistration();
80 
81 private:
82   uint64_t mLayersId;
83 };
84 
85 /**
86  * Manages the vsync (de)registration and tracking on behalf of the
87  * compositor when it need to paint.
88  * Turns vsync notifications into scheduled composites.
89  **/
90 class CompositorVsyncScheduler
91 {
92   NS_INLINE_DECL_THREADSAFE_REFCOUNTING(CompositorVsyncScheduler)
93 
94 public:
95   explicit CompositorVsyncScheduler(CompositorBridgeParent* aCompositorBridgeParent,
96                                     widget::CompositorWidget* aWidget);
97 
98   bool NotifyVsync(TimeStamp aVsyncTimestamp);
99   void SetNeedsComposite();
100   void OnForceComposeToTarget();
101 
102   void ScheduleTask(already_AddRefed<CancelableRunnable>, int);
103   void ResumeComposition();
104   void ComposeToTarget(gfx::DrawTarget* aTarget, const gfx::IntRect* aRect = nullptr);
105   void PostCompositeTask(TimeStamp aCompositeTimestamp);
106   void Destroy();
107   void ScheduleComposition();
108   void CancelCurrentCompositeTask();
109   bool NeedsComposite();
110   void Composite(TimeStamp aVsyncTimestamp);
111   void ForceComposeToTarget(gfx::DrawTarget* aTarget, const gfx::IntRect* aRect);
112 
GetLastComposeTime()113   const TimeStamp& GetLastComposeTime()
114   {
115     return mLastCompose;
116   }
117 
118 #ifdef COMPOSITOR_PERFORMANCE_WARNING
GetExpectedComposeStartTime()119   const TimeStamp& GetExpectedComposeStartTime()
120   {
121     return mExpectedComposeStartTime;
122   }
123 #endif
124 
125 private:
126   virtual ~CompositorVsyncScheduler();
127 
128   void NotifyCompositeTaskExecuted();
129   void ObserveVsync();
130   void UnobserveVsync();
131   void DispatchTouchEvents(TimeStamp aVsyncTimestamp);
132   void DispatchVREvents(TimeStamp aVsyncTimestamp);
133   void CancelCurrentSetNeedsCompositeTask();
134 
135   class Observer final : public VsyncObserver
136   {
137   public:
138     explicit Observer(CompositorVsyncScheduler* aOwner);
139     virtual bool NotifyVsync(TimeStamp aVsyncTimestamp) override;
140     void Destroy();
141   private:
142     virtual ~Observer();
143 
144     Mutex mMutex;
145     // Hold raw pointer to avoid mutual reference.
146     CompositorVsyncScheduler* mOwner;
147   };
148 
149   CompositorBridgeParent* mCompositorBridgeParent;
150   TimeStamp mLastCompose;
151 
152 #ifdef COMPOSITOR_PERFORMANCE_WARNING
153   TimeStamp mExpectedComposeStartTime;
154 #endif
155 
156   bool mAsapScheduling;
157   bool mIsObservingVsync;
158   uint32_t mNeedsComposite;
159   int32_t mVsyncNotificationsSkipped;
160   widget::CompositorWidget* mWidget;
161   RefPtr<CompositorVsyncScheduler::Observer> mVsyncObserver;
162 
163   mozilla::Monitor mCurrentCompositeTaskMonitor;
164   RefPtr<CancelableRunnable> mCurrentCompositeTask;
165 
166   mozilla::Monitor mSetNeedsCompositeMonitor;
167   RefPtr<CancelableRunnable> mSetNeedsCompositeTask;
168 };
169 
170 class CompositorBridgeParentBase : public PCompositorBridgeParent,
171                                    public HostIPCAllocator,
172                                    public ShmemAllocator,
173                                    public MetricsSharingController
174 {
175 public:
176   virtual void ShadowLayersUpdated(LayerTransactionParent* aLayerTree,
177                                    const uint64_t& aTransactionId,
178                                    const TargetConfig& aTargetConfig,
179                                    const InfallibleTArray<PluginWindowData>& aPlugins,
180                                    bool aIsFirstPaint,
181                                    bool aScheduleComposite,
182                                    uint32_t aPaintSequenceNumber,
183                                    bool aIsRepeatTransaction,
184                                    int32_t aPaintSyncId,
185                                    bool aHitTestUpdate) = 0;
186 
GetCompositionManager(LayerTransactionParent * aLayerTree)187   virtual AsyncCompositionManager* GetCompositionManager(LayerTransactionParent* aLayerTree) { return nullptr; }
188 
NotifyClearCachedResources(LayerTransactionParent * aLayerTree)189   virtual void NotifyClearCachedResources(LayerTransactionParent* aLayerTree) { }
190 
ForceComposite(LayerTransactionParent * aLayerTree)191   virtual void ForceComposite(LayerTransactionParent* aLayerTree) { }
SetTestSampleTime(LayerTransactionParent * aLayerTree,const TimeStamp & aTime)192   virtual bool SetTestSampleTime(LayerTransactionParent* aLayerTree,
193                                  const TimeStamp& aTime) { return true; }
LeaveTestMode(LayerTransactionParent * aLayerTree)194   virtual void LeaveTestMode(LayerTransactionParent* aLayerTree) { }
195   virtual void ApplyAsyncProperties(LayerTransactionParent* aLayerTree) = 0;
196   virtual void FlushApzRepaints(const LayerTransactionParent* aLayerTree) = 0;
GetAPZTestData(const LayerTransactionParent * aLayerTree,APZTestData * aOutData)197   virtual void GetAPZTestData(const LayerTransactionParent* aLayerTree,
198                               APZTestData* aOutData) { }
199   virtual void SetConfirmedTargetAPZC(const LayerTransactionParent* aLayerTree,
200                                       const uint64_t& aInputBlockId,
201                                       const nsTArray<ScrollableLayerGuid>& aTargets) = 0;
UpdatePaintTime(LayerTransactionParent * aLayerTree,const TimeDuration & aPaintTime)202   virtual void UpdatePaintTime(LayerTransactionParent* aLayerTree, const TimeDuration& aPaintTime) {}
203 
AsShmemAllocator()204   virtual ShmemAllocator* AsShmemAllocator() override { return this; }
205 
RecvSyncWithCompositor()206   virtual bool RecvSyncWithCompositor() override { return true; }
207 
208   // HostIPCAllocator
209   virtual base::ProcessId GetChildProcessId() override;
210   virtual void NotifyNotUsed(PTextureParent* aTexture, uint64_t aTransactionId) override;
211   virtual void SendAsyncMessage(const InfallibleTArray<AsyncParentMessageData>& aMessage) override;
212 
213   // ShmemAllocator
214   virtual bool AllocShmem(size_t aSize,
215                           mozilla::ipc::SharedMemory::SharedMemoryType aType,
216                           mozilla::ipc::Shmem* aShmem) override;
217   virtual bool AllocUnsafeShmem(size_t aSize,
218                                 mozilla::ipc::SharedMemory::SharedMemoryType aType,
219                                 mozilla::ipc::Shmem* aShmem) override;
220   virtual void DeallocShmem(mozilla::ipc::Shmem& aShmem) override;
221 
222   // MetricsSharingController
AddRef()223   NS_IMETHOD_(MozExternalRefCountType) AddRef() override { return HostIPCAllocator::AddRef(); }
Release()224   NS_IMETHOD_(MozExternalRefCountType) Release() override { return HostIPCAllocator::Release(); }
225   base::ProcessId RemotePid() override;
226   bool StartSharingMetrics(mozilla::ipc::SharedMemoryBasic::Handle aHandle,
227                            CrossProcessMutexHandle aMutexHandle,
228                            uint64_t aLayersId,
229                            uint32_t aApzcId) override;
230   bool StopSharingMetrics(FrameMetrics::ViewID aScrollId,
231                           uint32_t aApzcId) override;
232 };
233 
234 class CompositorBridgeParent final : public CompositorBridgeParentBase
235                                    , public CompositorController
236 {
237   friend class CompositorVsyncScheduler;
238   friend class CompositorThreadHolder;
239   friend class InProcessCompositorSession;
240   friend class gfx::GPUProcessManager;
241   friend class gfx::GPUParent;
242 
243 public:
NS_IMETHOD_(MozExternalRefCountType)244   NS_IMETHOD_(MozExternalRefCountType) AddRef() override { return CompositorBridgeParentBase::AddRef(); }
Release()245   NS_IMETHOD_(MozExternalRefCountType) Release() override { return CompositorBridgeParentBase::Release(); }
246 
247   explicit CompositorBridgeParent(CSSToLayoutDeviceScale aScale,
248                                   const TimeDuration& aVsyncRate,
249                                   bool aUseExternalSurfaceSize,
250                                   const gfx::IntSize& aSurfaceSize);
251 
252   // Must only be called by CompositorBridgeChild. After invoking this, the
253   // IPC channel is active and RecvWillStop/ActorDestroy must be called to
254   // free the compositor.
255   void InitSameProcess(widget::CompositorWidget* aWidget,
256                        const uint64_t& aLayerTreeId,
257                        bool aUseAPZ);
258 
259   // Must only be called by GPUParent. After invoking this, the IPC channel
260   // is active and RecvWillStop/ActorDestroy must be called to free the
261   // compositor.
262   bool Bind(Endpoint<PCompositorBridgeParent>&& aEndpoint);
263 
264   virtual bool RecvInitialize(const uint64_t& aRootLayerTreeId) override;
265   virtual bool RecvReset(nsTArray<LayersBackend>&& aBackendHints, bool* aResult, TextureFactoryIdentifier* aOutIdentifier) override;
266   virtual bool RecvGetFrameUniformity(FrameUniformityData* aOutData) override;
267   virtual bool RecvRequestOverfill() override;
268   virtual bool RecvWillClose() override;
269   virtual bool RecvPause() override;
270   virtual bool RecvResume() override;
271   virtual bool RecvNotifyChildCreated(const uint64_t& child) override;
272   virtual bool RecvNotifyChildRecreated(const uint64_t& child) override;
273   virtual bool RecvAdoptChild(const uint64_t& child) override;
274   virtual bool RecvMakeSnapshot(const SurfaceDescriptor& aInSnapshot,
275                                 const gfx::IntRect& aRect) override;
276   virtual bool RecvFlushRendering() override;
277   virtual bool RecvForcePresent() override;
278 
RecvAcknowledgeCompositorUpdate(const uint64_t & aLayersId)279   virtual bool RecvAcknowledgeCompositorUpdate(const uint64_t& aLayersId) override {
280     MOZ_ASSERT_UNREACHABLE("This message is only sent cross-process");
281     return true;
282   }
283 
284   virtual bool RecvNotifyRegionInvalidated(const nsIntRegion& aRegion) override;
285   virtual bool RecvStartFrameTimeRecording(const int32_t& aBufferSize, uint32_t* aOutStartIndex) override;
286   virtual bool RecvStopFrameTimeRecording(const uint32_t& aStartIndex, InfallibleTArray<float>* intervals) override;
287 
288   // Unused for chrome <-> compositor communication (which this class does).
289   // @see CrossProcessCompositorBridgeParent::RecvRequestNotifyAfterRemotePaint
RecvRequestNotifyAfterRemotePaint()290   virtual bool RecvRequestNotifyAfterRemotePaint() override { return true; };
291 
292   virtual bool RecvClearApproximatelyVisibleRegions(const uint64_t& aLayersId,
293                                                     const uint32_t& aPresShellId) override;
294   void ClearApproximatelyVisibleRegions(const uint64_t& aLayersId,
295                                         const Maybe<uint32_t>& aPresShellId);
296   virtual bool RecvNotifyApproximatelyVisibleRegion(const ScrollableLayerGuid& aGuid,
297                                                     const CSSIntRegion& aRegion) override;
298 
299   virtual bool RecvAllPluginsCaptured() override;
300 
301   virtual void ActorDestroy(ActorDestroyReason why) override;
302 
303   virtual void ShadowLayersUpdated(LayerTransactionParent* aLayerTree,
304                                    const uint64_t& aTransactionId,
305                                    const TargetConfig& aTargetConfig,
306                                    const InfallibleTArray<PluginWindowData>& aPlugins,
307                                    bool aIsFirstPaint,
308                                    bool aScheduleComposite,
309                                    uint32_t aPaintSequenceNumber,
310                                    bool aIsRepeatTransaction,
311                                    int32_t aPaintSyncId,
312                                    bool aHitTestUpdate) override;
313   virtual void ForceComposite(LayerTransactionParent* aLayerTree) override;
314   virtual bool SetTestSampleTime(LayerTransactionParent* aLayerTree,
315                                  const TimeStamp& aTime) override;
316   virtual void LeaveTestMode(LayerTransactionParent* aLayerTree) override;
317   virtual void ApplyAsyncProperties(LayerTransactionParent* aLayerTree)
318                override;
319   virtual void FlushApzRepaints(const LayerTransactionParent* aLayerTree) override;
320   virtual void GetAPZTestData(const LayerTransactionParent* aLayerTree,
321                               APZTestData* aOutData) override;
322   virtual void SetConfirmedTargetAPZC(const LayerTransactionParent* aLayerTree,
323                                       const uint64_t& aInputBlockId,
324                                       const nsTArray<ScrollableLayerGuid>& aTargets) override;
GetCompositionManager(LayerTransactionParent * aLayerTree)325   virtual AsyncCompositionManager* GetCompositionManager(LayerTransactionParent* aLayerTree) override { return mCompositionManager; }
326 
327   virtual PTextureParent* AllocPTextureParent(const SurfaceDescriptor& aSharedData,
328                                               const LayersBackend& aLayersBackend,
329                                               const TextureFlags& aFlags,
330                                               const uint64_t& aId,
331                                               const uint64_t& aSerial) override;
332   virtual bool DeallocPTextureParent(PTextureParent* actor) override;
333 
334   virtual bool IsSameProcess() const override;
335 
336 
337   PCompositorWidgetParent* AllocPCompositorWidgetParent(const CompositorWidgetInitData& aInitData) override;
338   bool DeallocPCompositorWidgetParent(PCompositorWidgetParent* aActor) override;
339 
340   /**
341    * Request that the compositor be recreated due to a shared device reset.
342    * This must be called on the main thread, and blocks until a task posted
343    * to the compositor thread has completed.
344    *
345    * Note that this posts a task directly, rather than using synchronous
346    * IPDL, and waits on a monitor notification from the compositor thread.
347    * We do this as a best-effort attempt to jump any IPDL messages that
348    * have not yet been posted (and are sitting around in the IO pipe), to
349    * minimize the amount of time the main thread is blocked.
350    */
351   bool ResetCompositor(const nsTArray<LayersBackend>& aBackendHints,
352                        TextureFactoryIdentifier* aOutIdentifier);
353 
354   /**
355    * This forces the is-first-paint flag to true. This is intended to
356    * be called by the widget code when it loses its viewport information
357    * (or for whatever reason wants to refresh the viewport information).
358    * The information refresh happens because the compositor will call
359    * SetFirstPaintViewport on the next frame of composition.
360    */
361   void ForceIsFirstPaint();
362 
363   static void SetShadowProperties(Layer* aLayer);
364 
365   void NotifyChildCreated(uint64_t aChild);
366 
367   void AsyncRender();
368 
369   // Can be called from any thread
370   void ScheduleRenderOnCompositorThread() override;
371   void SchedulePauseOnCompositorThread();
372   void InvalidateOnCompositorThread();
373   /**
374    * Returns true if a surface was obtained and the resume succeeded; false
375    * otherwise.
376    */
377   bool ScheduleResumeOnCompositorThread();
378   bool ScheduleResumeOnCompositorThread(int width, int height);
379 
380   virtual void ScheduleComposition();
381   void NotifyShadowTreeTransaction(uint64_t aId, bool aIsFirstPaint,
382       bool aScheduleComposite, uint32_t aPaintSequenceNumber,
383       bool aIsRepeatTransaction, bool aHitTestUpdate);
384 
385   void UpdatePaintTime(LayerTransactionParent* aLayerTree,
386                        const TimeDuration& aPaintTime) override;
387 
388   /**
389    * Check rotation info and schedule a rendering task if needed.
390    * Only can be called from compositor thread.
391    */
392   void ScheduleRotationOnCompositorThread(const TargetConfig& aTargetConfig, bool aIsFirstPaint);
393 
394   /**
395    * Returns the unique layer tree identifier that corresponds to the root
396    * tree of this compositor.
397    */
398   uint64_t RootLayerTreeId();
399 
400   /**
401    * Notify local and remote layer trees connected to this compositor that
402    * the compositor's local device is being reset. All layers must be
403    * invalidated to clear any cached TextureSources.
404    *
405    * This must be called on the compositor thread.
406    */
407   void InvalidateRemoteLayers();
408 
409   /**
410    * Returns a pointer to the CompositorBridgeParent corresponding to the given ID.
411    */
412   static CompositorBridgeParent* GetCompositorBridgeParent(uint64_t id);
413 
414   /**
415    * Notify the compositor for the given layer tree that vsync has occurred.
416    */
417   static void NotifyVsync(const TimeStamp& aTimeStamp, const uint64_t& aLayersId);
418 
419   /**
420    * Set aController as the pan/zoom callback for the subtree referred
421    * to by aLayersId.
422    *
423    * Must run on content main thread.
424    */
425   static void SetControllerForLayerTree(uint64_t aLayersId,
426                                         GeckoContentController* aController);
427 
428   /**
429    * A new child process has been configured to push transactions
430    * directly to us.  Transport is to its thread context.
431    */
432   static bool
433   CreateForContent(Endpoint<PCompositorBridgeParent>&& aEndpoint);
434 
435   struct LayerTreeState {
436     LayerTreeState();
437     ~LayerTreeState();
438     RefPtr<Layer> mRoot;
439     RefPtr<GeckoContentController> mController;
440     APZCTreeManagerParent* mApzcTreeManagerParent;
441     CompositorBridgeParent* mParent;
442     LayerManagerComposite* mLayerManager;
443     // Pointer to the CrossProcessCompositorBridgeParent. Used by APZCs to share
444     // their FrameMetrics with the corresponding child process that holds
445     // the PCompositorBridgeChild
446     CrossProcessCompositorBridgeParent* mCrossProcessParent;
447     TargetConfig mTargetConfig;
448     APZTestData mApzTestData;
449     LayerTransactionParent* mLayerTree;
450     nsTArray<PluginWindowData> mPluginData;
451     bool mUpdatedPluginDataAvailable;
452 
453     // Number of times the compositor has been reset without having been
454     // acknowledged by the child.
455     uint32_t mPendingCompositorUpdates;
456 
457     CompositorController* GetCompositorController() const;
458     MetricsSharingController* CrossProcessSharingController() const;
459     MetricsSharingController* InProcessSharingController() const;
460   };
461 
462   /**
463    * Lookup the indirect shadow tree for |aId| and return it if it
464    * exists.  Otherwise null is returned.  This must only be called on
465    * the compositor thread.
466    */
467   static LayerTreeState* GetIndirectShadowTree(uint64_t aId);
468 
469   /**
470    * Given the layers id for a content process, get the APZCTreeManagerParent
471    * for the corresponding *root* layers id. That is, the APZCTreeManagerParent,
472    * if one is found, will always be connected to the parent process rather
473    * than a content process. Note that unless the compositor process is
474    * separated this is expected to return null, because if the compositor is
475    * living in the gecko parent process then there is no APZCTreeManagerParent
476    * for the parent process.
477    */
478   static APZCTreeManagerParent* GetApzcTreeManagerParentForRoot(
479         uint64_t aContentLayersId);
480   /**
481    * Same as the GetApzcTreeManagerParentForRoot function, but returns
482    * the GeckoContentController for the parent process.
483    */
484   static GeckoContentController* GetGeckoContentControllerForRoot(
485         uint64_t aContentLayersId);
486 
487 #if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)
488   /**
489    * Calculates and requests the main thread update plugin positioning, clip,
490    * and visibility via ipc.
491    */
492   bool UpdatePluginWindowState(uint64_t aId);
493 
494   /**
495    * Plugin visibility helpers for the apz (main thread) and compositor
496    * thread.
497    */
498   void ScheduleShowAllPluginWindows() override;
499   void ScheduleHideAllPluginWindows() override;
500   void ShowAllPluginWindows();
501   void HideAllPluginWindows();
502 #else
ScheduleShowAllPluginWindows()503   void ScheduleShowAllPluginWindows() override {}
ScheduleHideAllPluginWindows()504   void ScheduleHideAllPluginWindows() override {}
505 #endif
506 
507   /**
508    * Main thread response for a plugin visibility request made by the
509    * compositor thread.
510    */
511   virtual bool RecvRemotePluginsReady() override;
512 
513   /**
514    * Used by the profiler to denote when a vsync occured
515    */
516   static void PostInsertVsyncProfilerMarker(mozilla::TimeStamp aVsyncTimestamp);
517 
GetWidget()518   widget::CompositorWidget* GetWidget() { return mWidget; }
519 
520   void ForceComposeToTarget(gfx::DrawTarget* aTarget, const gfx::IntRect* aRect = nullptr);
521 
522   PAPZCTreeManagerParent* AllocPAPZCTreeManagerParent(const uint64_t& aLayersId) override;
523   bool DeallocPAPZCTreeManagerParent(PAPZCTreeManagerParent* aActor) override;
524 
525   PAPZParent* AllocPAPZParent(const uint64_t& aLayersId) override;
526   bool DeallocPAPZParent(PAPZParent* aActor) override;
527 
528   bool RecvAsyncPanZoomEnabled(const uint64_t& aLayersId, bool* aHasAPZ) override;
529 
530   RefPtr<APZCTreeManager> GetAPZCTreeManager();
531 
AsyncPanZoomEnabled()532   bool AsyncPanZoomEnabled() const {
533     return !!mApzcTreeManager;
534   }
535 
536 private:
537 
538   void Initialize();
539 
540   /**
541    * Called during destruction in order to release resources as early as possible.
542    */
543   void StopAndClearResources();
544 
545   /**
546    * This returns a reference to the APZCTreeManager to which
547    * pan/zoom-related events can be sent.
548    */
549   static already_AddRefed<APZCTreeManager> GetAPZCTreeManager(uint64_t aLayersId);
550 
551   /**
552    * Release compositor-thread resources referred to by |aID|.
553    *
554    * Must run on the content main thread.
555    */
556   static void DeallocateLayerTreeId(uint64_t aId);
557 
558 protected:
559   // Protected destructor, to discourage deletion outside of Release():
560   virtual ~CompositorBridgeParent();
561 
562   void DeferredDestroy();
563 
564   virtual PLayerTransactionParent*
565     AllocPLayerTransactionParent(const nsTArray<LayersBackend>& aBackendHints,
566                                  const uint64_t& aId,
567                                  TextureFactoryIdentifier* aTextureFactoryIdentifier,
568                                  bool* aSuccess) override;
569   virtual bool DeallocPLayerTransactionParent(PLayerTransactionParent* aLayers) override;
570   virtual void ScheduleTask(already_AddRefed<CancelableRunnable>, int);
571   void CompositeToTarget(gfx::DrawTarget* aTarget, const gfx::IntRect* aRect = nullptr);
572 
573   void SetEGLSurfaceSize(int width, int height);
574 
575   void InitializeLayerManager(const nsTArray<LayersBackend>& aBackendHints);
576   void PauseComposition();
577   void ResumeComposition();
578   void ResumeCompositionAndResize(int width, int height);
579   void ForceComposition();
580   void CancelCurrentCompositeTask();
581   void Invalidate();
582   bool IsPendingComposite();
583   void FinishPendingComposite();
584 
585   RefPtr<Compositor> NewCompositor(const nsTArray<LayersBackend>& aBackendHints);
586   void ResetCompositorTask(const nsTArray<LayersBackend>& aBackendHints,
587                            Maybe<TextureFactoryIdentifier>* aOutNewIdentifier);
588   Maybe<TextureFactoryIdentifier> ResetCompositorImpl(const nsTArray<LayersBackend>& aBackendHints);
589 
590   /**
591    * Add a compositor to the global compositor map.
592    */
593   static void AddCompositor(CompositorBridgeParent* compositor, uint64_t* id);
594   /**
595    * Remove a compositor from the global compositor map.
596    */
597   static CompositorBridgeParent* RemoveCompositor(uint64_t id);
598 
599   /**
600    * Creates the global compositor map.
601    */
602   static void Setup();
603 
604   /**
605    * Destroys the compositor thread and global compositor map.
606    */
607   static void Shutdown();
608 
609   /**
610    * Finish the shutdown operation on the compositor thread.
611    */
612   static void FinishShutdown();
613 
614   /**
615    * Return true if current state allows compositing, that is
616    * finishing a layers transaction.
617    */
618   bool CanComposite();
619 
620   void DidComposite(TimeStamp& aCompositeStart, TimeStamp& aCompositeEnd);
621 
622   // The indirect layer tree lock must be held before calling this function.
623   // Callback should take (LayerTreeState* aState, const uint64_t& aLayersId)
624   template <typename Lambda>
625   inline void ForEachIndirectLayerTree(const Lambda& aCallback);
626 
627   RefPtr<LayerManagerComposite> mLayerManager;
628   RefPtr<Compositor> mCompositor;
629   RefPtr<AsyncCompositionManager> mCompositionManager;
630   widget::CompositorWidget* mWidget;
631   TimeStamp mTestTime;
632   CSSToLayoutDeviceScale mScale;
633   TimeDuration mVsyncRate;
634   bool mIsTesting;
635 
636   uint64_t mPendingTransaction;
637 
638   bool mPaused;
639 
640   bool mUseExternalSurfaceSize;
641   gfx::IntSize mEGLSurfaceSize;
642 
643   mozilla::Monitor mPauseCompositionMonitor;
644   mozilla::Monitor mResumeCompositionMonitor;
645   mozilla::Monitor mResetCompositorMonitor;
646 
647   uint64_t mCompositorID;
648   uint64_t mRootLayerTreeID;
649 
650   bool mOverrideComposeReadiness;
651   RefPtr<CancelableRunnable> mForceCompositionTask;
652 
653   RefPtr<APZCTreeManager> mApzcTreeManager;
654 
655   RefPtr<CompositorThreadHolder> mCompositorThreadHolder;
656   RefPtr<CompositorVsyncScheduler> mCompositorScheduler;
657   // This makes sure the compositorParent is not destroyed before receiving
658   // confirmation that the channel is closed.
659   // mSelfRef is cleared in DeferredDestroy which is scheduled by ActorDestroy.
660   RefPtr<CompositorBridgeParent> mSelfRef;
661 
662   TimeDuration mPaintTime;
663 
664 #if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)
665   // cached plugin data used to reduce the number of updates we request.
666   uint64_t mLastPluginUpdateLayerTreeId;
667   nsIntPoint mPluginsLayerOffset;
668   nsIntRegion mPluginsLayerVisibleRegion;
669   nsTArray<PluginWindowData> mCachedPluginData;
670   // Time until which we will block composition to wait for plugin updates.
671   TimeStamp mWaitForPluginsUntil;
672   // Indicates that we have actually blocked a composition waiting for plugins.
673   bool mHaveBlockedForPlugins = false;
674   // indicates if plugin window visibility and metric updates are currently
675   // being defered due to a scroll operation.
676   bool mDeferPluginWindows;
677   // indicates if the plugin windows were hidden, and need to be made
678   // visible again even if their geometry has not changed.
679   bool mPluginWindowsHidden;
680 #endif
681 
682   DISALLOW_EVIL_CONSTRUCTORS(CompositorBridgeParent);
683 };
684 
685 } // namespace layers
686 } // namespace mozilla
687 
688 #endif // mozilla_layers_CompositorBridgeParent_h
689