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 mozilla_dom_DebuggerNotificationManager_h
8 #define mozilla_dom_DebuggerNotificationManager_h
9 
10 #include "DebuggerNotificationObserver.h"
11 #include "nsCycleCollectionParticipant.h"
12 #include "nsIGlobalObject.h"
13 #include "nsISupports.h"
14 #include "nsTObserverArray.h"
15 
16 namespace mozilla {
17 namespace dom {
18 
19 class DebuggerNotification;
20 class DebuggerNotificationObserver;
21 
22 class DebuggerNotificationManager final : public nsISupports {
23  public:
24   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(DebuggerNotificationManager)25   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(DebuggerNotificationManager)
26 
27   static RefPtr<DebuggerNotificationManager> ForDispatch(
28       nsIGlobalObject* aDebuggeeGlobal) {
29     if (MOZ_UNLIKELY(!aDebuggeeGlobal)) {
30       return nullptr;
31     }
32     auto managerPtr = aDebuggeeGlobal->GetExistingDebuggerNotificationManager();
33     if (MOZ_LIKELY(!managerPtr) || !managerPtr->HasListeners()) {
34       return nullptr;
35     }
36 
37     return managerPtr;
38   }
39 
DebuggerNotificationManager(nsIGlobalObject * aDebuggeeGlobal)40   explicit DebuggerNotificationManager(nsIGlobalObject* aDebuggeeGlobal)
41       : mDebuggeeGlobal(aDebuggeeGlobal), mNotificationObservers() {}
42 
43   bool Attach(DebuggerNotificationObserver* aObserver);
44   bool Detach(DebuggerNotificationObserver* aObserver);
45 
46   bool HasListeners();
47 
48   template <typename T, typename... Args>
Dispatch(Args...aArgs)49   MOZ_CAN_RUN_SCRIPT void Dispatch(Args... aArgs) {
50     RefPtr<DebuggerNotification> notification(new T(mDebuggeeGlobal, aArgs...));
51     NotifyListeners(notification);
52   }
53 
54  private:
55   ~DebuggerNotificationManager() = default;
56 
57   MOZ_CAN_RUN_SCRIPT void NotifyListeners(DebuggerNotification* aNotification);
58 
59   nsCOMPtr<nsIGlobalObject> mDebuggeeGlobal;
60   nsTObserverArray<RefPtr<DebuggerNotificationObserver>> mNotificationObservers;
61 };
62 
63 }  // namespace dom
64 }  // namespace mozilla
65 
66 #endif  // mozilla_dom_DebuggerNotificationManager_h
67