forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsThreadUtils.h
2005 lines (1751 loc) · 70.1 KB
/
nsThreadUtils.h
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- 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/. */
#ifndef nsThreadUtils_h__
#define nsThreadUtils_h__
#include <type_traits>
#include <utility>
#include "MainThreadUtils.h"
#include "mozilla/EventQueue.h"
#include "mozilla/AbstractThread.h"
#include "mozilla/Atomics.h"
#include "mozilla/Likely.h"
#include "mozilla/Maybe.h"
#include "mozilla/ThreadLocal.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/Tuple.h"
#include "nsCOMPtr.h"
#include "nsICancelableRunnable.h"
#include "nsIIdlePeriod.h"
#include "nsIIdleRunnable.h"
#include "nsINamed.h"
#include "nsIRunnable.h"
#include "nsIThread.h"
#include "nsIThreadManager.h"
#include "nsITimer.h"
#include "nsString.h"
#include "prinrval.h"
#include "prthread.h"
#include "xpcpublic.h"
class MessageLoop;
//-----------------------------------------------------------------------------
// These methods are alternatives to the methods on nsIThreadManager, provided
// for convenience.
/**
* Create a new thread, and optionally provide an initial event for the thread.
*
* @param aName
* The name of the thread.
* @param aResult
* The resulting nsIThread object.
* @param aInitialEvent
* The initial event to run on this thread. This parameter may be null.
* @param aStackSize
* The size in bytes to reserve for the thread's stack.
*
* @returns NS_ERROR_INVALID_ARG
* Indicates that the given name is not unique.
*/
extern nsresult NS_NewNamedThread(
const nsACString& aName, nsIThread** aResult,
nsIRunnable* aInitialEvent = nullptr,
uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE);
extern nsresult NS_NewNamedThread(
const nsACString& aName, nsIThread** aResult,
already_AddRefed<nsIRunnable> aInitialEvent,
uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE);
template <size_t LEN>
inline nsresult NS_NewNamedThread(
const char (&aName)[LEN], nsIThread** aResult,
already_AddRefed<nsIRunnable> aInitialEvent,
uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE) {
static_assert(LEN <= 16, "Thread name must be no more than 16 characters");
return NS_NewNamedThread(nsDependentCString(aName, LEN - 1), aResult,
std::move(aInitialEvent), aStackSize);
}
template <size_t LEN>
inline nsresult NS_NewNamedThread(
const char (&aName)[LEN], nsIThread** aResult,
nsIRunnable* aInitialEvent = nullptr,
uint32_t aStackSize = nsIThreadManager::DEFAULT_STACK_SIZE) {
nsCOMPtr<nsIRunnable> event = aInitialEvent;
static_assert(LEN <= 16, "Thread name must be no more than 16 characters");
return NS_NewNamedThread(nsDependentCString(aName, LEN - 1), aResult,
event.forget(), aStackSize);
}
/**
* Get a reference to the current thread, creating it if it does not exist yet.
*
* @param aResult
* The resulting nsIThread object.
*/
extern nsresult NS_GetCurrentThread(nsIThread** aResult);
/**
* Dispatch the given event to the current thread.
*
* @param aEvent
* The event to dispatch.
*
* @returns NS_ERROR_INVALID_ARG
* If event is null.
*/
extern nsresult NS_DispatchToCurrentThread(nsIRunnable* aEvent);
extern nsresult NS_DispatchToCurrentThread(
already_AddRefed<nsIRunnable>&& aEvent);
/**
* Dispatch the given event to the main thread.
*
* @param aEvent
* The event to dispatch.
* @param aDispatchFlags
* The flags to pass to the main thread's dispatch method.
*
* @returns NS_ERROR_INVALID_ARG
* If event is null.
*/
extern nsresult NS_DispatchToMainThread(
nsIRunnable* aEvent, uint32_t aDispatchFlags = NS_DISPATCH_NORMAL);
extern nsresult NS_DispatchToMainThread(
already_AddRefed<nsIRunnable>&& aEvent,
uint32_t aDispatchFlags = NS_DISPATCH_NORMAL);
extern nsresult NS_DelayedDispatchToCurrentThread(
already_AddRefed<nsIRunnable>&& aEvent, uint32_t aDelayMs);
/**
* Dispatch the given event to the specified queue of the current thread.
*
* @param aEvent The event to dispatch.
* @param aQueue The event queue for the thread to use
*
* @returns NS_ERROR_INVALID_ARG
* If event is null.
* @returns NS_ERROR_UNEXPECTED
* If the thread is shutting down.
*/
extern nsresult NS_DispatchToCurrentThreadQueue(
already_AddRefed<nsIRunnable>&& aEvent, mozilla::EventQueuePriority aQueue);
/**
* Dispatch the given event to the specified queue of the main thread.
*
* @param aEvent The event to dispatch.
* @param aQueue The event queue for the thread to use
*
* @returns NS_ERROR_INVALID_ARG
* If event is null.
* @returns NS_ERROR_UNEXPECTED
* If the thread is shutting down.
*/
extern nsresult NS_DispatchToMainThreadQueue(
already_AddRefed<nsIRunnable>&& aEvent, mozilla::EventQueuePriority aQueue);
/**
* Dispatch the given event to an idle queue of the current thread.
*
* @param aEvent The event to dispatch. If the event implements
* nsIIdleRunnable, it will receive a call on
* nsIIdleRunnable::SetTimer when dispatched, with the value of
* aTimeout.
*
* @param aTimeout The time in milliseconds until the event should be
* moved from an idle queue to the regular queue, if it hasn't been
* executed. If aEvent is also an nsIIdleRunnable, it is expected
* that it should handle the timeout itself, after a call to
* nsIIdleRunnable::SetTimer.
*
* @param aQueue
* The event queue for the thread to use. Must be an idle queue
* (Idle or DeferredTimers)
*
* @returns NS_ERROR_INVALID_ARG
* If event is null.
* @returns NS_ERROR_UNEXPECTED
* If the thread is shutting down.
*/
extern nsresult NS_DispatchToCurrentThreadQueue(
already_AddRefed<nsIRunnable>&& aEvent, uint32_t aTimeout,
mozilla::EventQueuePriority aQueue);
/**
* Dispatch the given event to a queue of a thread.
*
* @param aEvent The event to dispatch.
* @param aThread The target thread for the dispatch.
* @param aQueue The event queue for the thread to use.
*
* @returns NS_ERROR_INVALID_ARG
* If event is null.
* @returns NS_ERROR_UNEXPECTED
* If the thread is shutting down.
*/
extern nsresult NS_DispatchToThreadQueue(already_AddRefed<nsIRunnable>&& aEvent,
nsIThread* aThread,
mozilla::EventQueuePriority aQueue);
/**
* Dispatch the given event to an idle queue of a thread.
*
* @param aEvent The event to dispatch. If the event implements
* nsIIdleRunnable, it will receive a call on
* nsIIdleRunnable::SetTimer when dispatched, with the value of
* aTimeout.
*
* @param aTimeout The time in milliseconds until the event should be
* moved from an idle queue to the regular queue, if it hasn't been
* executed. If aEvent is also an nsIIdleRunnable, it is expected
* that it should handle the timeout itself, after a call to
* nsIIdleRunnable::SetTimer.
*
* @param aThread The target thread for the dispatch.
*
* @param aQueue
* The event queue for the thread to use. Must be an idle queue
* (Idle or DeferredTimers)
*
* @returns NS_ERROR_INVALID_ARG
* If event is null.
* @returns NS_ERROR_UNEXPECTED
* If the thread is shutting down.
*/
extern nsresult NS_DispatchToThreadQueue(already_AddRefed<nsIRunnable>&& aEvent,
uint32_t aTimeout, nsIThread* aThread,
mozilla::EventQueuePriority aQueue);
#ifndef XPCOM_GLUE_AVOID_NSPR
/**
* Process all pending events for the given thread before returning. This
* method simply calls ProcessNextEvent on the thread while HasPendingEvents
* continues to return true and the time spent in NS_ProcessPendingEvents
* does not exceed the given timeout value.
*
* @param aThread
* The thread object for which to process pending events. If null, then
* events will be processed for the current thread.
* @param aTimeout
* The maximum number of milliseconds to spend processing pending events.
* Events are not pre-empted to honor this timeout. Rather, the timeout
* value is simply used to determine whether or not to process another event.
* Pass PR_INTERVAL_NO_TIMEOUT to specify no timeout.
*/
extern nsresult NS_ProcessPendingEvents(
nsIThread* aThread, PRIntervalTime aTimeout = PR_INTERVAL_NO_TIMEOUT);
#endif
/**
* Shortcut for nsIThread::HasPendingEvents.
*
* It is an error to call this function when the given thread is not the
* current thread. This function will return false if called from some
* other thread.
*
* @param aThread
* The current thread or null.
*
* @returns
* A boolean value that if "true" indicates that there are pending events
* in the current thread's event queue.
*/
extern bool NS_HasPendingEvents(nsIThread* aThread = nullptr);
/**
* Shortcut for nsIThread::ProcessNextEvent.
*
* It is an error to call this function when the given thread is not the
* current thread. This function will simply return false if called
* from some other thread.
*
* @param aThread
* The current thread or null.
* @param aMayWait
* A boolean parameter that if "true" indicates that the method may block
* the calling thread to wait for a pending event.
*
* @returns
* A boolean value that if "true" indicates that an event from the current
* thread's event queue was processed.
*/
extern bool NS_ProcessNextEvent(nsIThread* aThread = nullptr,
bool aMayWait = true);
// A wrapper for nested event loops.
//
// This function is intended to make code more obvious (do you remember
// what NS_ProcessNextEvent(nullptr, true) means?) and slightly more
// efficient, as people often pass nullptr or NS_GetCurrentThread to
// NS_ProcessNextEvent, which results in needless querying of the current
// thread every time through the loop.
//
// You should use this function in preference to NS_ProcessNextEvent inside
// a loop unless one of the following is true:
//
// * You need to pass `false` to NS_ProcessNextEvent; or
// * You need to do unusual things around the call to NS_ProcessNextEvent,
// such as unlocking mutexes that you are holding.
//
// If you *do* need to call NS_ProcessNextEvent manually, please do call
// NS_GetCurrentThread() outside of your loop and pass the returned pointer
// into NS_ProcessNextEvent for a tiny efficiency win.
namespace mozilla {
// You should normally not need to deal with this template parameter. If
// you enjoy esoteric event loop details, read on.
//
// If you specify that NS_ProcessNextEvent wait for an event, it is possible
// for NS_ProcessNextEvent to return false, i.e. to indicate that an event
// was not processed. This can only happen when the thread has been shut
// down by another thread, but is still attempting to process events outside
// of a nested event loop.
//
// This behavior is admittedly strange. The scenario it deals with is the
// following:
//
// * The current thread has been shut down by some owner thread.
// * The current thread is spinning an event loop waiting for some condition
// to become true.
// * Said condition is actually being fulfilled by another thread, so there
// are timing issues in play.
//
// Thus, there is a small window where the current thread's event loop
// spinning can check the condition, find it false, and call
// NS_ProcessNextEvent to wait for another event. But we don't actually
// want it to wait indefinitely, because there might not be any other events
// in the event loop, and the current thread can't accept dispatched events
// because it's being shut down. Thus, actually blocking would hang the
// thread, which is bad. The solution, then, is to detect such a scenario
// and not actually block inside NS_ProcessNextEvent.
//
// But this is a problem, because we want to return the status of
// NS_ProcessNextEvent to the caller of SpinEventLoopUntil if possible. In
// the above scenario, however, we'd stop spinning prematurely and cause
// all sorts of havoc. We therefore have this template parameter to
// control whether errors are ignored or passed out to the caller of
// SpinEventLoopUntil. The latter is the default; if you find yourself
// wanting to use the former, you should think long and hard before doing
// so, and write a comment like this defending your choice.
enum class ProcessFailureBehavior {
IgnoreAndContinue,
ReportToCaller,
};
template <
ProcessFailureBehavior Behavior = ProcessFailureBehavior::ReportToCaller,
typename Pred>
bool SpinEventLoopUntil(Pred&& aPredicate, nsIThread* aThread = nullptr) {
nsIThread* thread = aThread ? aThread : NS_GetCurrentThread();
// From a latency perspective, spinning the event loop is like leaving script
// and returning to the event loop. Tell the watchdog we stopped running
// script (until we return).
mozilla::Maybe<xpc::AutoScriptActivity> asa;
if (NS_IsMainThread()) {
asa.emplace(false);
}
while (!aPredicate()) {
bool didSomething = NS_ProcessNextEvent(thread, true);
if (Behavior == ProcessFailureBehavior::IgnoreAndContinue) {
// Don't care what happened, continue on.
continue;
} else if (!didSomething) {
return false;
}
}
return true;
}
} // namespace mozilla
/**
* Returns true if we're in the compositor thread.
*
* We declare this here because the headers required to invoke
* CompositorThreadHolder::IsInCompositorThread() also pull in a bunch of system
* headers that #define various tokens in a way that can break the build.
*/
extern bool NS_IsInCompositorThread();
extern bool NS_IsInCanvasThreadOrWorker();
extern bool NS_IsInVRThread();
//-----------------------------------------------------------------------------
// Helpers that work with nsCOMPtr:
inline already_AddRefed<nsIThread> do_GetCurrentThread() {
nsIThread* thread = nullptr;
NS_GetCurrentThread(&thread);
return already_AddRefed<nsIThread>(thread);
}
inline already_AddRefed<nsIThread> do_GetMainThread() {
nsIThread* thread = nullptr;
NS_GetMainThread(&thread);
return already_AddRefed<nsIThread>(thread);
}
//-----------------------------------------------------------------------------
#ifdef MOZILLA_INTERNAL_API
// Fast access to the current thread. Will create an nsIThread if one does not
// exist already! Do not release the returned pointer! If you want to use this
// pointer from some other thread, then you will need to AddRef it. Otherwise,
// you should only consider this pointer valid from code running on the current
// thread.
extern nsIThread* NS_GetCurrentThread();
// Exactly the same as NS_GetCurrentThread, except it will not create an
// nsThread if one does not exist yet. This is useful in cases where you have
// code that runs on threads that may or may not not be driven by an nsThread
// event loop, and wish to avoid inadvertently creating a superfluous nsThread.
extern nsIThread* NS_GetCurrentThreadNoCreate();
/**
* Set the name of the current thread. Prefer this function over
* PR_SetCurrentThreadName() if possible. The name will also be included in the
* crash report.
*
* @param aName
* Name of the thread. A C language null-terminated string.
*/
extern void NS_SetCurrentThreadName(const char* aName);
#endif
//-----------------------------------------------------------------------------
#ifndef XPCOM_GLUE_AVOID_NSPR
namespace mozilla {
// This class is designed to be subclassed.
class IdlePeriod : public nsIIdlePeriod {
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIIDLEPERIOD
IdlePeriod() = default;
protected:
virtual ~IdlePeriod() = default;
private:
IdlePeriod(const IdlePeriod&) = delete;
IdlePeriod& operator=(const IdlePeriod&) = delete;
IdlePeriod& operator=(const IdlePeriod&&) = delete;
};
// Cancelable runnable methods implement nsICancelableRunnable, and
// Idle and IdleWithTimer also nsIIdleRunnable.
enum class RunnableKind { Standard, Cancelable, Idle, IdleWithTimer };
// Implementing nsINamed on Runnable bloats vtables for the hundreds of
// Runnable subclasses that we have, so we want to avoid that overhead
// when we're not using nsINamed for anything.
# ifndef RELEASE_OR_BETA
# define MOZ_COLLECTING_RUNNABLE_TELEMETRY
# endif
// This class is designed to be subclassed.
class Runnable : public nsIRunnable
# ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
,
public nsINamed
# endif
{
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIRUNNABLE
# ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
NS_DECL_NSINAMED
# endif
Runnable() = delete;
# ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
explicit Runnable(const char* aName) : mName(aName) {}
# else
explicit Runnable(const char* aName) {}
# endif
protected:
virtual ~Runnable() = default;
# ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
const char* mName = nullptr;
# endif
private:
Runnable(const Runnable&) = delete;
Runnable& operator=(const Runnable&) = delete;
Runnable& operator=(const Runnable&&) = delete;
};
// This class is designed to be subclassed.
class CancelableRunnable : public Runnable, public nsICancelableRunnable {
public:
NS_DECL_ISUPPORTS_INHERITED
// nsICancelableRunnable
virtual nsresult Cancel() override;
CancelableRunnable() = delete;
explicit CancelableRunnable(const char* aName) : Runnable(aName) {}
protected:
virtual ~CancelableRunnable() = default;
private:
CancelableRunnable(const CancelableRunnable&) = delete;
CancelableRunnable& operator=(const CancelableRunnable&) = delete;
CancelableRunnable& operator=(const CancelableRunnable&&) = delete;
};
// This class is designed to be subclassed.
class IdleRunnable : public CancelableRunnable, public nsIIdleRunnable {
public:
NS_DECL_ISUPPORTS_INHERITED
IdleRunnable() : CancelableRunnable("IdleRunnable") {}
explicit IdleRunnable(const char* aName) : CancelableRunnable(aName) {}
protected:
virtual ~IdleRunnable() = default;
private:
IdleRunnable(const IdleRunnable&) = delete;
IdleRunnable& operator=(const IdleRunnable&) = delete;
IdleRunnable& operator=(const IdleRunnable&&) = delete;
};
// This class is designed to be a wrapper of a real runnable to support event
// prioritizable.
class PrioritizableRunnable : public Runnable, public nsIRunnablePriority {
public:
PrioritizableRunnable(already_AddRefed<nsIRunnable>&& aRunnable,
uint32_t aPriority);
# ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
NS_IMETHOD GetName(nsACString& aName) override;
# endif
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_NSIRUNNABLE
NS_DECL_NSIRUNNABLEPRIORITY
protected:
virtual ~PrioritizableRunnable() = default;
;
nsCOMPtr<nsIRunnable> mRunnable;
uint32_t mPriority;
};
extern already_AddRefed<nsIRunnable> CreateMediumHighRunnable(
already_AddRefed<nsIRunnable>&& aRunnable);
namespace detail {
// An event that can be used to call a C++11 functions or function objects,
// including lambdas. The function must have no required arguments, and must
// return void.
template <typename StoredFunction>
class RunnableFunction : public Runnable {
public:
template <typename F>
explicit RunnableFunction(const char* aName, F&& aFunction)
: Runnable(aName), mFunction(std::forward<F>(aFunction)) {}
NS_IMETHOD Run() override {
static_assert(std::is_void_v<decltype(mFunction())>,
"The lambda must return void!");
mFunction();
return NS_OK;
}
private:
StoredFunction mFunction;
};
// Type alias for NS_NewRunnableFunction
template <typename Function>
using RunnableFunctionImpl =
// Make sure we store a non-reference in nsRunnableFunction.
typename detail::RunnableFunction<std::remove_reference_t<Function>>;
} // namespace detail
namespace detail {
template <typename CVRemoved>
struct IsRefcountedSmartPointerHelper : std::false_type {};
template <typename Pointee>
struct IsRefcountedSmartPointerHelper<RefPtr<Pointee>> : std::true_type {};
template <typename Pointee>
struct IsRefcountedSmartPointerHelper<nsCOMPtr<Pointee>> : std::true_type {};
} // namespace detail
template <typename T>
struct IsRefcountedSmartPointer
: detail::IsRefcountedSmartPointerHelper<std::remove_cv_t<T>> {};
namespace detail {
template <typename T, typename CVRemoved>
struct RemoveSmartPointerHelper {
typedef T Type;
};
template <typename T, typename Pointee>
struct RemoveSmartPointerHelper<T, RefPtr<Pointee>> {
typedef Pointee Type;
};
template <typename T, typename Pointee>
struct RemoveSmartPointerHelper<T, nsCOMPtr<Pointee>> {
typedef Pointee Type;
};
} // namespace detail
template <typename T>
struct RemoveSmartPointer
: detail::RemoveSmartPointerHelper<T, std::remove_cv_t<T>> {};
namespace detail {
template <typename T, typename CVRemoved>
struct RemoveRawOrSmartPointerHelper {
typedef T Type;
};
template <typename T, typename Pointee>
struct RemoveRawOrSmartPointerHelper<T, Pointee*> {
typedef Pointee Type;
};
template <typename T, typename Pointee>
struct RemoveRawOrSmartPointerHelper<T, RefPtr<Pointee>> {
typedef Pointee Type;
};
template <typename T, typename Pointee>
struct RemoveRawOrSmartPointerHelper<T, nsCOMPtr<Pointee>> {
typedef Pointee Type;
};
} // namespace detail
template <typename T>
struct RemoveRawOrSmartPointer
: detail::RemoveRawOrSmartPointerHelper<T, std::remove_cv_t<T>> {};
} // namespace mozilla
inline nsISupports* ToSupports(mozilla::Runnable* p) {
return static_cast<nsIRunnable*>(p);
}
template <typename Function>
already_AddRefed<mozilla::Runnable> NS_NewRunnableFunction(
const char* aName, Function&& aFunction) {
// We store a non-reference in RunnableFunction, but still forward aFunction
// to move if possible.
return do_AddRef(new mozilla::detail::RunnableFunctionImpl<Function>(
aName, std::forward<Function>(aFunction)));
}
// Creates a new object implementing nsIRunnable and nsICancelableRunnable,
// which runs a given function on Run and clears the stored function object on a
// call to `Cancel` (and thus destroys all objects it holds).
template <typename Function>
already_AddRefed<mozilla::CancelableRunnable> NS_NewCancelableRunnableFunction(
const char* aName, Function&& aFunc) {
class FuncCancelableRunnable final : public mozilla::CancelableRunnable {
public:
static_assert(std::is_void_v<decltype(
std::declval<std::remove_reference_t<Function>>()())>);
NS_INLINE_DECL_REFCOUNTING_INHERITED(FuncCancelableRunnable,
CancelableRunnable)
explicit FuncCancelableRunnable(const char* aName, Function&& aFunc)
: CancelableRunnable{aName},
mFunc{mozilla::Some(std::forward<Function>(aFunc))} {}
NS_IMETHOD Run() override {
if (mFunc) {
(*mFunc)();
}
return NS_OK;
}
nsresult Cancel() override {
mFunc.reset();
return NS_OK;
}
private:
~FuncCancelableRunnable() = default;
mozilla::Maybe<std::remove_reference_t<Function>> mFunc;
};
return mozilla::MakeAndAddRef<FuncCancelableRunnable>(
aName, std::forward<Function>(aFunc));
}
namespace mozilla {
namespace detail {
template <RunnableKind Kind>
class TimerBehaviour {
public:
nsITimer* GetTimer() { return nullptr; }
void CancelTimer() {}
protected:
~TimerBehaviour() = default;
};
template <>
class TimerBehaviour<RunnableKind::IdleWithTimer> {
public:
nsITimer* GetTimer() {
if (!mTimer) {
mTimer = NS_NewTimer();
}
return mTimer;
}
void CancelTimer() {
if (mTimer) {
mTimer->Cancel();
}
}
protected:
~TimerBehaviour() { CancelTimer(); }
private:
nsCOMPtr<nsITimer> mTimer;
};
} // namespace detail
} // namespace mozilla
// An event that can be used to call a method on a class. The class type must
// support reference counting. This event supports Revoke for use
// with nsRevocableEventPtr.
template <class ClassType, typename ReturnType = void, bool Owning = true,
mozilla::RunnableKind Kind = mozilla::RunnableKind::Standard>
class nsRunnableMethod
: public std::conditional_t<
Kind == mozilla::RunnableKind::Standard, mozilla::Runnable,
std::conditional_t<Kind == mozilla::RunnableKind::Cancelable,
mozilla::CancelableRunnable,
mozilla::IdleRunnable>>,
protected mozilla::detail::TimerBehaviour<Kind> {
using BaseType = std::conditional_t<
Kind == mozilla::RunnableKind::Standard, mozilla::Runnable,
std::conditional_t<Kind == mozilla::RunnableKind::Cancelable,
mozilla::CancelableRunnable, mozilla::IdleRunnable>>;
public:
nsRunnableMethod(const char* aName) : BaseType(aName) {}
virtual void Revoke() = 0;
// These ReturnTypeEnforcer classes disallow return types that
// we know are not safe. The default ReturnTypeEnforcer compiles just fine but
// already_AddRefed will not.
template <typename OtherReturnType>
class ReturnTypeEnforcer {
public:
typedef int ReturnTypeIsSafe;
};
template <class T>
class ReturnTypeEnforcer<already_AddRefed<T>> {
// No ReturnTypeIsSafe makes this illegal!
};
// Make sure this return type is safe.
typedef typename ReturnTypeEnforcer<ReturnType>::ReturnTypeIsSafe check;
};
template <class ClassType, bool Owning>
struct nsRunnableMethodReceiver {
RefPtr<ClassType> mObj;
explicit nsRunnableMethodReceiver(ClassType* aObj) : mObj(aObj) {}
~nsRunnableMethodReceiver() { Revoke(); }
ClassType* Get() const { return mObj.get(); }
void Revoke() { mObj = nullptr; }
};
template <class ClassType>
struct nsRunnableMethodReceiver<ClassType, false> {
ClassType* MOZ_NON_OWNING_REF mObj;
explicit nsRunnableMethodReceiver(ClassType* aObj) : mObj(aObj) {}
ClassType* Get() const { return mObj; }
void Revoke() { mObj = nullptr; }
};
static inline constexpr bool IsIdle(mozilla::RunnableKind aKind) {
return aKind == mozilla::RunnableKind::Idle ||
aKind == mozilla::RunnableKind::IdleWithTimer;
}
template <typename PtrType, typename Method, bool Owning,
mozilla::RunnableKind Kind>
struct nsRunnableMethodTraits;
template <typename PtrType, class C, typename R, bool Owning,
mozilla::RunnableKind Kind, typename... As>
struct nsRunnableMethodTraits<PtrType, R (C::*)(As...), Owning, Kind> {
typedef typename mozilla::RemoveRawOrSmartPointer<PtrType>::Type class_type;
static_assert(std::is_base_of<C, class_type>::value,
"Stored class must inherit from method's class");
typedef R return_type;
typedef nsRunnableMethod<C, R, Owning, Kind> base_type;
static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
};
template <typename PtrType, class C, typename R, bool Owning,
mozilla::RunnableKind Kind, typename... As>
struct nsRunnableMethodTraits<PtrType, R (C::*)(As...) const, Owning, Kind> {
typedef const typename mozilla::RemoveRawOrSmartPointer<PtrType>::Type
class_type;
static_assert(std::is_base_of<C, class_type>::value,
"Stored class must inherit from method's class");
typedef R return_type;
typedef nsRunnableMethod<C, R, Owning, Kind> base_type;
static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
};
# ifdef NS_HAVE_STDCALL
template <typename PtrType, class C, typename R, bool Owning,
mozilla::RunnableKind Kind, typename... As>
struct nsRunnableMethodTraits<PtrType, R (__stdcall C::*)(As...), Owning,
Kind> {
typedef typename mozilla::RemoveRawOrSmartPointer<PtrType>::Type class_type;
static_assert(std::is_base_of<C, class_type>::value,
"Stored class must inherit from method's class");
typedef R return_type;
typedef nsRunnableMethod<C, R, Owning, Kind> base_type;
static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
};
template <typename PtrType, class C, typename R, bool Owning,
mozilla::RunnableKind Kind>
struct nsRunnableMethodTraits<PtrType, R (NS_STDCALL C::*)(), Owning, Kind> {
typedef typename mozilla::RemoveRawOrSmartPointer<PtrType>::Type class_type;
static_assert(std::is_base_of<C, class_type>::value,
"Stored class must inherit from method's class");
typedef R return_type;
typedef nsRunnableMethod<C, R, Owning, Kind> base_type;
static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
};
template <typename PtrType, class C, typename R, bool Owning,
mozilla::RunnableKind Kind, typename... As>
struct nsRunnableMethodTraits<PtrType, R (__stdcall C::*)(As...) const, Owning,
Kind> {
typedef const typename mozilla::RemoveRawOrSmartPointer<PtrType>::Type
class_type;
static_assert(std::is_base_of<C, class_type>::value,
"Stored class must inherit from method's class");
typedef R return_type;
typedef nsRunnableMethod<C, R, Owning, Kind> base_type;
static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
};
template <typename PtrType, class C, typename R, bool Owning,
mozilla::RunnableKind Kind>
struct nsRunnableMethodTraits<PtrType, R (NS_STDCALL C::*)() const, Owning,
Kind> {
typedef const typename mozilla::RemoveRawOrSmartPointer<PtrType>::Type
class_type;
static_assert(std::is_base_of<C, class_type>::value,
"Stored class must inherit from method's class");
typedef R return_type;
typedef nsRunnableMethod<C, R, Owning, Kind> base_type;
static const bool can_cancel = Kind == mozilla::RunnableKind::Cancelable;
};
# endif
// IsParameterStorageClass<T>::value is true if T is a parameter-storage class
// that will be recognized by NS_New[NonOwning]RunnableMethodWithArg[s] to
// force a specific storage&passing strategy (instead of inferring one,
// see ParameterStorage).
// When creating a new storage class, add a specialization for it to be
// recognized.
template <typename T>
struct IsParameterStorageClass : public std::false_type {};
// StoreXPassByY structs used to inform nsRunnableMethodArguments how to
// store arguments, and how to pass them to the target method.
template <typename T>
struct StoreCopyPassByValue {
using stored_type = std::decay_t<T>;
typedef stored_type passed_type;
stored_type m;
template <typename A>
MOZ_IMPLICIT StoreCopyPassByValue(A&& a) : m(std::forward<A>(a)) {}
passed_type PassAsParameter() { return m; }
};
template <typename S>
struct IsParameterStorageClass<StoreCopyPassByValue<S>>
: public std::true_type {};
template <typename T>
struct StoreCopyPassByConstLRef {
using stored_type = std::decay_t<T>;
typedef const stored_type& passed_type;
stored_type m;
template <typename A>
MOZ_IMPLICIT StoreCopyPassByConstLRef(A&& a) : m(std::forward<A>(a)) {}
passed_type PassAsParameter() { return m; }
};
template <typename S>
struct IsParameterStorageClass<StoreCopyPassByConstLRef<S>>
: public std::true_type {};
template <typename T>
struct StoreCopyPassByLRef {
using stored_type = std::decay_t<T>;
typedef stored_type& passed_type;
stored_type m;
template <typename A>
MOZ_IMPLICIT StoreCopyPassByLRef(A&& a) : m(std::forward<A>(a)) {}
passed_type PassAsParameter() { return m; }
};
template <typename S>
struct IsParameterStorageClass<StoreCopyPassByLRef<S>> : public std::true_type {
};
template <typename T>
struct StoreCopyPassByRRef {
using stored_type = std::decay_t<T>;
typedef stored_type&& passed_type;
stored_type m;
template <typename A>
MOZ_IMPLICIT StoreCopyPassByRRef(A&& a) : m(std::forward<A>(a)) {}
passed_type PassAsParameter() { return std::move(m); }
};
template <typename S>
struct IsParameterStorageClass<StoreCopyPassByRRef<S>> : public std::true_type {
};
template <typename T>
struct StoreRefPassByLRef {
typedef T& stored_type;
typedef T& passed_type;
stored_type m;
template <typename A>
MOZ_IMPLICIT StoreRefPassByLRef(A& a) : m(a) {}
passed_type PassAsParameter() { return m; }
};
template <typename S>
struct IsParameterStorageClass<StoreRefPassByLRef<S>> : public std::true_type {
};
template <typename T>
struct StoreConstRefPassByConstLRef {
typedef const T& stored_type;
typedef const T& passed_type;
stored_type m;
template <typename A>
MOZ_IMPLICIT StoreConstRefPassByConstLRef(const A& a) : m(a) {}
passed_type PassAsParameter() { return m; }
};
template <typename S>
struct IsParameterStorageClass<StoreConstRefPassByConstLRef<S>>
: public std::true_type {};
template <typename T>
struct StoreRefPtrPassByPtr {
typedef RefPtr<T> stored_type;
typedef T* passed_type;
stored_type m;
template <typename A>
MOZ_IMPLICIT StoreRefPtrPassByPtr(A&& a) : m(std::forward<A>(a)) {}
passed_type PassAsParameter() { return m.get(); }
};
template <typename S>
struct IsParameterStorageClass<StoreRefPtrPassByPtr<S>>
: public std::true_type {};
template <typename T>
struct StorePtrPassByPtr {