summaryrefslogtreecommitdiffstats
path: root/dom/base/PlacesObservers.cpp
blob: b5211733ea05934dd9ac552ff3a44fc3f2cff91d (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
402
403
404
405
406
407
408
409
410
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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/. */

#include "PlacesObservers.h"

#include "PlacesWeakCallbackWrapper.h"
#include "nsIWeakReferenceUtils.h"
#include "nsIXPConnect.h"
#include "mozilla/ClearOnShutdown.h"

namespace mozilla::dom {

template <class T>
struct Flagged {
  Flagged(uint32_t aFlags, T&& aValue)
      : flags(aFlags), value(std::forward<T>(aValue)) {}
  Flagged(Flagged&& aOther)
      : Flagged(std::move(aOther.flags), std::move(aOther.value)) {}
  Flagged(const Flagged& aOther) = default;
  ~Flagged() = default;

  uint32_t flags = 0;
  T value;
};

template <class T>
using FlaggedArray = nsTArray<Flagged<T>>;

template <class T>
struct ListenerCollection {
  static StaticAutoPtr<FlaggedArray<T>> gListeners;
  static StaticAutoPtr<FlaggedArray<T>> gListenersToRemove;

  static FlaggedArray<T>* GetListeners(bool aDoNotInit = false) {
    MOZ_ASSERT(NS_IsMainThread());
    if (!gListeners && !aDoNotInit) {
      gListeners = new FlaggedArray<T>();
      ClearOnShutdown(&gListeners);
    }
    return gListeners;
  }

  static FlaggedArray<T>* GetListenersToRemove(bool aDoNotInit = false) {
    MOZ_ASSERT(NS_IsMainThread());
    if (!gListenersToRemove && !aDoNotInit) {
      gListenersToRemove = new FlaggedArray<T>();
      ClearOnShutdown(&gListenersToRemove);
    }
    return gListenersToRemove;
  }
};

template <class T>
StaticAutoPtr<FlaggedArray<T>> ListenerCollection<T>::gListeners;
template <class T>
StaticAutoPtr<FlaggedArray<T>> ListenerCollection<T>::gListenersToRemove;

using JSListeners = ListenerCollection<RefPtr<PlacesEventCallback>>;
using WeakJSListeners = ListenerCollection<WeakPtr<PlacesWeakCallbackWrapper>>;
using WeakNativeListeners =
    ListenerCollection<WeakPtr<places::INativePlacesEventCallback>>;

// Even if NotifyListeners is called any timing, we mange the notifications with
// adding to this queue, then sending in sequence. This avoids sending nested
// notifications while previous ones are still being sent.
static nsTArray<Sequence<OwningNonNull<PlacesEvent>>> gNotificationQueue;

uint32_t GetEventTypeFlag(PlacesEventType aEventType) {
  if (aEventType == PlacesEventType::None) {
    return 0;
  }
  return 1 << ((uint32_t)aEventType - 1);
}

uint32_t GetFlagsForEventTypes(const nsTArray<PlacesEventType>& aEventTypes) {
  uint32_t flags = 0;
  for (PlacesEventType eventType : aEventTypes) {
    flags |= GetEventTypeFlag(eventType);
  }
  return flags;
}

uint32_t GetFlagsForEvents(
    const nsTArray<OwningNonNull<PlacesEvent>>& aEvents) {
  uint32_t flags = 0;
  for (const PlacesEvent& event : aEvents) {
    flags |= GetEventTypeFlag(event.Type());
  }
  return flags;
}

template <class TWrapped, class TUnwrapped, class TListenerCollection>
MOZ_CAN_RUN_SCRIPT void CallListeners(
    uint32_t aEventFlags, const Sequence<OwningNonNull<PlacesEvent>>& aEvents,
    unsigned long aListenersLengthToCall,
    const std::function<TUnwrapped(TWrapped&)>& aUnwrapListener,
    const std::function<void(TUnwrapped&,
                             const Sequence<OwningNonNull<PlacesEvent>>&)>&
        aCallListener) {
  auto& listeners = *TListenerCollection::GetListeners();
  for (uint32_t i = 0; i < aListenersLengthToCall; i++) {
    Flagged<TWrapped>& listener = listeners[i];
    TUnwrapped unwrapped = aUnwrapListener(listener.value);
    if (!unwrapped) {
      continue;
    }

    if ((listener.flags & aEventFlags) == aEventFlags) {
      aCallListener(unwrapped, aEvents);
    } else if (listener.flags & aEventFlags) {
      Sequence<OwningNonNull<PlacesEvent>> filtered;
      for (const OwningNonNull<PlacesEvent>& event : aEvents) {
        if (listener.flags & GetEventTypeFlag(event->Type())) {
          bool success = !!filtered.AppendElement(event, fallible);
          MOZ_RELEASE_ASSERT(success);
        }
      }
      aCallListener(unwrapped, filtered);
    }
  }
}

StaticRefPtr<PlacesEventCounts> PlacesObservers::sCounts;
static void EnsureCountsInitialized() {
  if (!PlacesObservers::sCounts) {
    PlacesObservers::sCounts = new PlacesEventCounts();
    ClearOnShutdown(&PlacesObservers::sCounts);
  }
}

void PlacesObservers::AddListener(GlobalObject& aGlobal,
                                  const nsTArray<PlacesEventType>& aEventTypes,
                                  PlacesEventCallback& aCallback,
                                  ErrorResult& rv) {
  uint32_t flags = GetFlagsForEventTypes(aEventTypes);

  FlaggedArray<RefPtr<PlacesEventCallback>>* listeners =
      JSListeners::GetListeners();
  Flagged<RefPtr<PlacesEventCallback>> pair(flags, &aCallback);
  listeners->AppendElement(pair);
}

void PlacesObservers::AddListener(GlobalObject& aGlobal,
                                  const nsTArray<PlacesEventType>& aEventTypes,
                                  PlacesWeakCallbackWrapper& aCallback,
                                  ErrorResult& rv) {
  uint32_t flags = GetFlagsForEventTypes(aEventTypes);

  FlaggedArray<WeakPtr<PlacesWeakCallbackWrapper>>* listeners =
      WeakJSListeners::GetListeners();
  WeakPtr<PlacesWeakCallbackWrapper> weakCb(&aCallback);
  MOZ_ASSERT(weakCb.get());
  Flagged<WeakPtr<PlacesWeakCallbackWrapper>> flagged(flags, std::move(weakCb));
  listeners->AppendElement(flagged);
}

void PlacesObservers::AddListener(
    const nsTArray<PlacesEventType>& aEventTypes,
    places::INativePlacesEventCallback* aCallback) {
  uint32_t flags = GetFlagsForEventTypes(aEventTypes);

  FlaggedArray<WeakPtr<places::INativePlacesEventCallback>>* listeners =
      WeakNativeListeners::GetListeners();
  Flagged<WeakPtr<places::INativePlacesEventCallback>> pair(flags, aCallback);
  listeners->AppendElement(pair);
}

void PlacesObservers::RemoveListener(
    GlobalObject& aGlobal, const nsTArray<PlacesEventType>& aEventTypes,
    PlacesEventCallback& aCallback, ErrorResult& rv) {
  uint32_t flags = GetFlagsForEventTypes(aEventTypes);
  if (!gNotificationQueue.IsEmpty()) {
    FlaggedArray<RefPtr<PlacesEventCallback>>* listeners =
        JSListeners::GetListenersToRemove();
    Flagged<RefPtr<PlacesEventCallback>> pair(flags, &aCallback);
    listeners->AppendElement(pair);
  } else {
    RemoveListener(flags, aCallback);
  }
}

void PlacesObservers::RemoveListener(
    GlobalObject& aGlobal, const nsTArray<PlacesEventType>& aEventTypes,
    PlacesWeakCallbackWrapper& aCallback, ErrorResult& rv) {
  uint32_t flags = GetFlagsForEventTypes(aEventTypes);
  if (!gNotificationQueue.IsEmpty()) {
    FlaggedArray<WeakPtr<PlacesWeakCallbackWrapper>>* listeners =
        WeakJSListeners::GetListenersToRemove();
    WeakPtr<PlacesWeakCallbackWrapper> weakCb(&aCallback);
    MOZ_ASSERT(weakCb.get());
    Flagged<WeakPtr<PlacesWeakCallbackWrapper>> flagged(flags,
                                                        std::move(weakCb));
    listeners->AppendElement(flagged);
  } else {
    RemoveListener(flags, aCallback);
  }
}

void PlacesObservers::RemoveListener(
    const nsTArray<PlacesEventType>& aEventTypes,
    places::INativePlacesEventCallback* aCallback) {
  uint32_t flags = GetFlagsForEventTypes(aEventTypes);
  if (!gNotificationQueue.IsEmpty()) {
    FlaggedArray<WeakPtr<places::INativePlacesEventCallback>>* listeners =
        WeakNativeListeners::GetListenersToRemove();
    Flagged<WeakPtr<places::INativePlacesEventCallback>> pair(flags, aCallback);
    listeners->AppendElement(pair);
  } else {
    RemoveListener(flags, aCallback);
  }
}

void PlacesObservers::RemoveListener(uint32_t aFlags,
                                     PlacesEventCallback& aCallback) {
  FlaggedArray<RefPtr<PlacesEventCallback>>* listeners =
      JSListeners::GetListeners(/* aDoNotInit: */ true);
  if (!listeners) {
    return;
  }
  for (uint32_t i = 0; i < listeners->Length(); i++) {
    Flagged<RefPtr<PlacesEventCallback>>& l = listeners->ElementAt(i);
    if (!(*l.value == aCallback)) {
      continue;
    }
    if (l.flags == (aFlags & l.flags)) {
      listeners->RemoveElementAt(i);
      i--;
    } else {
      l.flags &= ~aFlags;
    }
  }
}

void PlacesObservers::RemoveListener(uint32_t aFlags,
                                     PlacesWeakCallbackWrapper& aCallback) {
  FlaggedArray<WeakPtr<PlacesWeakCallbackWrapper>>* listeners =
      WeakJSListeners::GetListeners(/* aDoNotInit: */ true);
  if (!listeners) {
    return;
  }
  for (uint32_t i = 0; i < listeners->Length(); i++) {
    Flagged<WeakPtr<PlacesWeakCallbackWrapper>>& l = listeners->ElementAt(i);
    RefPtr<PlacesWeakCallbackWrapper> unwrapped = l.value.get();
    if (unwrapped != &aCallback) {
      continue;
    }
    if (l.flags == (aFlags & l.flags)) {
      listeners->RemoveElementAt(i);
      i--;
    } else {
      l.flags &= ~aFlags;
    }
  }
}

void PlacesObservers::RemoveListener(
    uint32_t aFlags, places::INativePlacesEventCallback* aCallback) {
  FlaggedArray<WeakPtr<places::INativePlacesEventCallback>>* listeners =
      WeakNativeListeners::GetListeners(/* aDoNotInit: */ true);
  if (!listeners) {
    return;
  }
  for (uint32_t i = 0; i < listeners->Length(); i++) {
    Flagged<WeakPtr<places::INativePlacesEventCallback>>& l =
        listeners->ElementAt(i);
    RefPtr<places::INativePlacesEventCallback> unwrapped = l.value.get();
    if (unwrapped != aCallback) {
      continue;
    }
    if (l.flags == (aFlags & l.flags)) {
      listeners->RemoveElementAt(i);
      i--;
    } else {
      l.flags &= ~aFlags;
    }
  }
}

template <class TWrapped, class TUnwrapped, class TListenerCollection>
void CleanupListeners(
    const std::function<TUnwrapped(TWrapped&)>& aUnwrapListener,
    const std::function<void(Flagged<TWrapped>&)>& aRemoveListener) {
  auto& listeners = *TListenerCollection::GetListeners();
  for (uint32_t i = 0; i < listeners.Length(); i++) {
    Flagged<TWrapped>& listener = listeners[i];
    TUnwrapped unwrapped = aUnwrapListener(listener.value);
    if (!unwrapped) {
      listeners.RemoveElementAt(i);
      i--;
    }
  }

  auto& listenersToRemove = *TListenerCollection::GetListenersToRemove();
  for (auto& listener : listenersToRemove) {
    aRemoveListener(listener);
  }
  listenersToRemove.Clear();
}

void PlacesObservers::NotifyListeners(
    GlobalObject& aGlobal, const Sequence<OwningNonNull<PlacesEvent>>& aEvents,
    ErrorResult& rv) {
  NotifyListeners(aEvents);
}

void PlacesObservers::NotifyListeners(
    const Sequence<OwningNonNull<PlacesEvent>>& aEvents) {
  MOZ_ASSERT(aEvents.Length() > 0, "Must pass a populated array of events");
  if (aEvents.Length() == 0) {
    return;
  }
  EnsureCountsInitialized();
  for (const auto& event : aEvents) {
    DebugOnly<nsresult> rv = sCounts->Increment(event->Type());
    MOZ_ASSERT(NS_SUCCEEDED(rv));
  }
#ifdef DEBUG
  if (!gNotificationQueue.IsEmpty()) {
    NS_WARNING(
        "Avoid nested Places notifications if possible, the order of events "
        "cannot be guaranteed");
    nsCOMPtr<nsIXPConnect> xpc = nsIXPConnect::XPConnect();
    Unused << xpc->DebugDumpJSStack(false, false, false);
  }
#endif

  gNotificationQueue.AppendElement(aEvents);

  // If gNotificationQueue has only the events we added now, start to notify.
  // Otherwise, as it already started the notification processing,
  // rely on the processing.
  if (gNotificationQueue.Length() == 1) {
    NotifyNext();
  }
}

void PlacesObservers::NotifyNext() {
  auto events = gNotificationQueue[0];
  uint32_t flags = GetFlagsForEvents(events);

  // Send up to the number of current listeners, to avoid handling listeners
  // added during this notification.
  unsigned long jsListenersLength = JSListeners::GetListeners()->Length();
  unsigned long weakNativeListenersLength =
      WeakNativeListeners::GetListeners()->Length();
  unsigned long weakJSListenersLength =
      WeakJSListeners::GetListeners()->Length();

  CallListeners<RefPtr<PlacesEventCallback>, RefPtr<PlacesEventCallback>,
                JSListeners>(
      flags, events, jsListenersLength, [](auto& cb) { return cb; },
      // MOZ_CAN_RUN_SCRIPT_BOUNDARY because on Windows this gets called from
      // some internals of the std::function implementation that we can't
      // annotate.  We handle this by annotating CallListeners and making sure
      // it holds a strong ref to the callback.
      [&](auto& cb, const auto& events)
          MOZ_CAN_RUN_SCRIPT_BOUNDARY { MOZ_KnownLive(cb)->Call(events); });

  CallListeners<WeakPtr<places::INativePlacesEventCallback>,
                RefPtr<places::INativePlacesEventCallback>,
                WeakNativeListeners>(
      flags, events, weakNativeListenersLength,
      [](auto& cb) { return cb.get(); },
      [&](auto& cb, const Sequence<OwningNonNull<PlacesEvent>>& events) {
        cb->HandlePlacesEvent(events);
      });

  CallListeners<WeakPtr<PlacesWeakCallbackWrapper>,
                RefPtr<PlacesWeakCallbackWrapper>, WeakJSListeners>(
      flags, events, weakJSListenersLength, [](auto& cb) { return cb.get(); },
      // MOZ_CAN_RUN_SCRIPT_BOUNDARY because on Windows this gets called from
      // some internals of the std::function implementation that we can't
      // annotate.  We handle this by annotating CallListeners and making sure
      // it holds a strong ref to the callback.
      [&](auto& cb, const auto& events) MOZ_CAN_RUN_SCRIPT_BOUNDARY {
        RefPtr<PlacesEventCallback> callback(cb->mCallback);
        callback->Call(events);
      });

  gNotificationQueue.RemoveElementAt(0);

  CleanupListeners<RefPtr<PlacesEventCallback>, RefPtr<PlacesEventCallback>,
                   JSListeners>(
      [](auto& cb) { return cb; },
      [&](auto& cb) { RemoveListener(cb.flags, *cb.value); });
  CleanupListeners<WeakPtr<PlacesWeakCallbackWrapper>,
                   RefPtr<PlacesWeakCallbackWrapper>, WeakJSListeners>(
      [](auto& cb) { return cb.get(); },
      [&](auto& cb) { RemoveListener(cb.flags, *cb.value.get()); });
  CleanupListeners<WeakPtr<places::INativePlacesEventCallback>,
                   RefPtr<places::INativePlacesEventCallback>,
                   WeakNativeListeners>(
      [](auto& cb) { return cb.get(); },
      [&](auto& cb) { RemoveListener(cb.flags, cb.value.get()); });

  if (!gNotificationQueue.IsEmpty()) {
    NotifyNext();
  }
}

already_AddRefed<PlacesEventCounts> PlacesObservers::Counts(
    const GlobalObject& global) {
  EnsureCountsInitialized();
  return do_AddRef(sCounts);
};

}  // namespace mozilla::dom