summaryrefslogtreecommitdiff
path: root/dom/presentation/PresentationServiceBase.h
blob: 227e9543068f91e75b4814791f89e2b76a215b8d (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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=8 et ft=cpp : */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_dom_PresentationServiceBase_h
#define mozilla_dom_PresentationServiceBase_h

#include "mozilla/Unused.h"
#include "nsClassHashtable.h"
#include "nsCOMArray.h"
#include "nsIPresentationListener.h"
#include "nsIPresentationService.h"
#include "nsRefPtrHashtable.h"
#include "nsString.h"
#include "nsTArray.h"

namespace mozilla {
namespace dom {

template<class T>
class PresentationServiceBase
{
public:
  PresentationServiceBase() = default;

  already_AddRefed<T>
  GetSessionInfo(const nsAString& aSessionId, const uint8_t aRole)
  {
    MOZ_ASSERT(aRole == nsIPresentationService::ROLE_CONTROLLER ||
               aRole == nsIPresentationService::ROLE_RECEIVER);

    RefPtr<T> info;
    if (aRole == nsIPresentationService::ROLE_CONTROLLER) {
      return mSessionInfoAtController.Get(aSessionId, getter_AddRefs(info)) ?
             info.forget() : nullptr;
    } else {
      return mSessionInfoAtReceiver.Get(aSessionId, getter_AddRefs(info)) ?
             info.forget() : nullptr;
    }
  }

protected:
  class SessionIdManager final
  {
  public:
    explicit SessionIdManager()
    {
      MOZ_COUNT_CTOR(SessionIdManager);
    }

    ~SessionIdManager()
    {
      MOZ_COUNT_DTOR(SessionIdManager);
    }

    nsresult GetWindowId(const nsAString& aSessionId, uint64_t* aWindowId)
    {
      MOZ_ASSERT(NS_IsMainThread());

      if (mRespondingWindowIds.Get(aSessionId, aWindowId)) {
        return NS_OK;
      }
      return NS_ERROR_NOT_AVAILABLE;
    }

    nsresult GetSessionIds(uint64_t aWindowId, nsTArray<nsString>& aSessionIds)
    {
      MOZ_ASSERT(NS_IsMainThread());

      nsTArray<nsString>* sessionIdArray;
      if (!mRespondingSessionIds.Get(aWindowId, &sessionIdArray)) {
        return NS_ERROR_INVALID_ARG;
      }

      aSessionIds.Assign(*sessionIdArray);
      return NS_OK;
    }

    void AddSessionId(uint64_t aWindowId, const nsAString& aSessionId)
    {
      MOZ_ASSERT(NS_IsMainThread());

      if (NS_WARN_IF(aWindowId == 0)) {
        return;
      }

      nsTArray<nsString>* sessionIdArray;
      if (!mRespondingSessionIds.Get(aWindowId, &sessionIdArray)) {
        sessionIdArray = new nsTArray<nsString>();
        mRespondingSessionIds.Put(aWindowId, sessionIdArray);
      }

      sessionIdArray->AppendElement(nsString(aSessionId));
      mRespondingWindowIds.Put(aSessionId, aWindowId);
    }

    void RemoveSessionId(const nsAString& aSessionId)
    {
      MOZ_ASSERT(NS_IsMainThread());

      uint64_t windowId = 0;
      if (mRespondingWindowIds.Get(aSessionId, &windowId)) {
        mRespondingWindowIds.Remove(aSessionId);
        nsTArray<nsString>* sessionIdArray;
        if (mRespondingSessionIds.Get(windowId, &sessionIdArray)) {
          sessionIdArray->RemoveElement(nsString(aSessionId));
          if (sessionIdArray->IsEmpty()) {
            mRespondingSessionIds.Remove(windowId);
          }
        }
      }
    }

    nsresult UpdateWindowId(const nsAString& aSessionId, const uint64_t aWindowId)
    {
      MOZ_ASSERT(NS_IsMainThread());

      RemoveSessionId(aSessionId);
      AddSessionId(aWindowId, aSessionId);
      return NS_OK;
    }

    void Clear()
    {
      mRespondingSessionIds.Clear();
      mRespondingWindowIds.Clear();
    }

  private:
    nsClassHashtable<nsUint64HashKey, nsTArray<nsString>> mRespondingSessionIds;
    nsDataHashtable<nsStringHashKey, uint64_t> mRespondingWindowIds;
  };

  class AvailabilityManager final
  {
  public:
    explicit AvailabilityManager()
    {
      MOZ_COUNT_CTOR(AvailabilityManager);
    }

    ~AvailabilityManager()
    {
      MOZ_COUNT_DTOR(AvailabilityManager);
    }

    void AddAvailabilityListener(
                               const nsTArray<nsString>& aAvailabilityUrls,
                               nsIPresentationAvailabilityListener* aListener)
    {
      nsTArray<nsString> dummy;
      AddAvailabilityListener(aAvailabilityUrls, aListener, dummy);
    }

    void AddAvailabilityListener(
                               const nsTArray<nsString>& aAvailabilityUrls,
                               nsIPresentationAvailabilityListener* aListener,
                               nsTArray<nsString>& aAddedUrls)
    {
      if (!aListener) {
        MOZ_ASSERT(false, "aListener should not be null.");
        return;
      }

      if (aAvailabilityUrls.IsEmpty()) {
        MOZ_ASSERT(false, "aAvailabilityUrls should not be empty.");
        return;
      }

      aAddedUrls.Clear();
      nsTArray<nsString> knownAvailableUrls;
      for (const auto& url : aAvailabilityUrls) {
        AvailabilityEntry* entry;
        if (!mAvailabilityUrlTable.Get(url, &entry)) {
          entry = new AvailabilityEntry();
          mAvailabilityUrlTable.Put(url, entry);
          aAddedUrls.AppendElement(url);
        }
        if (!entry->mListeners.Contains(aListener)) {
          entry->mListeners.AppendElement(aListener);
        }
        if (entry->mAvailable) {
          knownAvailableUrls.AppendElement(url);
        }
      }

      if (!knownAvailableUrls.IsEmpty()) {
        Unused <<
          NS_WARN_IF(
            NS_FAILED(aListener->NotifyAvailableChange(knownAvailableUrls,
                                                       true)));
      } else {
        // If we can't find any known available url and there is no newly
        // added url, we still need to notify the listener of the result.
        // So, the promise returned by |getAvailability| can be resolved.
        if (aAddedUrls.IsEmpty()) {
          Unused <<
            NS_WARN_IF(
              NS_FAILED(aListener->NotifyAvailableChange(aAvailabilityUrls,
                                                         false)));
        }
      }
    }

    void RemoveAvailabilityListener(
                               const nsTArray<nsString>& aAvailabilityUrls,
                               nsIPresentationAvailabilityListener* aListener)
    {
      nsTArray<nsString> dummy;
      RemoveAvailabilityListener(aAvailabilityUrls, aListener, dummy);
    }

    void RemoveAvailabilityListener(
                               const nsTArray<nsString>& aAvailabilityUrls,
                               nsIPresentationAvailabilityListener* aListener,
                               nsTArray<nsString>& aRemovedUrls)
    {
      if (!aListener) {
        MOZ_ASSERT(false, "aListener should not be null.");
        return;
      }

      if (aAvailabilityUrls.IsEmpty()) {
        MOZ_ASSERT(false, "aAvailabilityUrls should not be empty.");
        return;
      }

      aRemovedUrls.Clear();
      for (const auto& url : aAvailabilityUrls) {
        AvailabilityEntry* entry;
        if (mAvailabilityUrlTable.Get(url, &entry)) {
          entry->mListeners.RemoveElement(aListener);
          if (entry->mListeners.IsEmpty()) {
            mAvailabilityUrlTable.Remove(url);
            aRemovedUrls.AppendElement(url);
          }
        }
      }
    }

    nsresult DoNotifyAvailableChange(const nsTArray<nsString>& aAvailabilityUrls,
                                     bool aAvailable)
    {
      typedef nsClassHashtable<nsISupportsHashKey,
                               nsTArray<nsString>> ListenerToUrlsMap;
      ListenerToUrlsMap availabilityListenerTable;
      // Create a mapping from nsIPresentationAvailabilityListener to
      // availabilityUrls.
      for (auto it = mAvailabilityUrlTable.ConstIter(); !it.Done(); it.Next()) {
        if (aAvailabilityUrls.Contains(it.Key())) {
          AvailabilityEntry* entry = it.UserData();
          entry->mAvailable = aAvailable;

          for (uint32_t i = 0; i < entry->mListeners.Length(); ++i) {
            nsIPresentationAvailabilityListener* listener =
              entry->mListeners.ObjectAt(i);
            nsTArray<nsString>* urlArray;
            if (!availabilityListenerTable.Get(listener, &urlArray)) {
              urlArray = new nsTArray<nsString>();
              availabilityListenerTable.Put(listener, urlArray);
            }
            urlArray->AppendElement(it.Key());
          }
        }
      }

      for (auto it = availabilityListenerTable.Iter(); !it.Done(); it.Next()) {
        auto listener =
          static_cast<nsIPresentationAvailabilityListener*>(it.Key());

        Unused <<
          NS_WARN_IF(NS_FAILED(listener->NotifyAvailableChange(*it.UserData(),
                                                               aAvailable)));
      }
      return NS_OK;
    }

    void GetAvailbilityUrlByAvailability(nsTArray<nsString>& aOutArray,
                                         bool aAvailable)
    {
      aOutArray.Clear();

      for (auto it = mAvailabilityUrlTable.ConstIter(); !it.Done(); it.Next()) {
        if (it.UserData()->mAvailable == aAvailable) {
          aOutArray.AppendElement(it.Key());
        }
      }
    }

    void Clear()
    {
      mAvailabilityUrlTable.Clear();
    }

  private:
    struct AvailabilityEntry
    {
      explicit AvailabilityEntry()
        : mAvailable(false)
      {}

      bool mAvailable;
      nsCOMArray<nsIPresentationAvailabilityListener> mListeners;
    };

    nsClassHashtable<nsStringHashKey, AvailabilityEntry> mAvailabilityUrlTable;
  };

  virtual ~PresentationServiceBase() = default;

  void Shutdown()
  {
    mRespondingListeners.Clear();
    mControllerSessionIdManager.Clear();
    mReceiverSessionIdManager.Clear();
  }

  nsresult GetWindowIdBySessionIdInternal(const nsAString& aSessionId,
                                          uint8_t aRole,
                                          uint64_t* aWindowId)
  {
    MOZ_ASSERT(aRole == nsIPresentationService::ROLE_CONTROLLER ||
               aRole == nsIPresentationService::ROLE_RECEIVER);

    if (NS_WARN_IF(!aWindowId)) {
      return NS_ERROR_INVALID_POINTER;
    }

    if (aRole == nsIPresentationService::ROLE_CONTROLLER) {
      return mControllerSessionIdManager.GetWindowId(aSessionId, aWindowId);
    }

    return mReceiverSessionIdManager.GetWindowId(aSessionId, aWindowId);
  }

  void AddRespondingSessionId(uint64_t aWindowId,
                              const nsAString& aSessionId,
                              uint8_t aRole)
  {
    MOZ_ASSERT(aRole == nsIPresentationService::ROLE_CONTROLLER ||
               aRole == nsIPresentationService::ROLE_RECEIVER);

    if (aRole == nsIPresentationService::ROLE_CONTROLLER) {
      mControllerSessionIdManager.AddSessionId(aWindowId, aSessionId);
    } else {
      mReceiverSessionIdManager.AddSessionId(aWindowId, aSessionId);
    }
  }

  void RemoveRespondingSessionId(const nsAString& aSessionId,
                                 uint8_t aRole)
  {
    MOZ_ASSERT(aRole == nsIPresentationService::ROLE_CONTROLLER ||
               aRole == nsIPresentationService::ROLE_RECEIVER);

    if (aRole == nsIPresentationService::ROLE_CONTROLLER) {
      mControllerSessionIdManager.RemoveSessionId(aSessionId);
    } else {
      mReceiverSessionIdManager.RemoveSessionId(aSessionId);
    }
  }

  nsresult UpdateWindowIdBySessionIdInternal(const nsAString& aSessionId,
                                             uint8_t aRole,
                                             const uint64_t aWindowId)
  {
    MOZ_ASSERT(aRole == nsIPresentationService::ROLE_CONTROLLER ||
               aRole == nsIPresentationService::ROLE_RECEIVER);

    if (aRole == nsIPresentationService::ROLE_CONTROLLER) {
      return mControllerSessionIdManager.UpdateWindowId(aSessionId, aWindowId);
    }

    return mReceiverSessionIdManager.UpdateWindowId(aSessionId, aWindowId);
  }

  // Store the responding listener based on the window ID of the (in-process or
  // OOP) receiver page.
  nsRefPtrHashtable<nsUint64HashKey, nsIPresentationRespondingListener>
  mRespondingListeners;

  // Store the mapping between the window ID of the in-process and OOP page and the ID
  // of the responding session. It's used for both controller and receiver page
  // to retrieve the correspondent session ID. Besides, also keep the mapping
  // between the responding session ID and the window ID to help look up the
  // window ID.
  SessionIdManager mControllerSessionIdManager;
  SessionIdManager mReceiverSessionIdManager;

  nsRefPtrHashtable<nsStringHashKey, T> mSessionInfoAtController;
  nsRefPtrHashtable<nsStringHashKey, T> mSessionInfoAtReceiver;

  AvailabilityManager mAvailabilityManager;
};

} // namespace dom
} // namespace mozilla

#endif // mozilla_dom_PresentationServiceBase_h