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_mscom_MainThreadInvoker_h
8 #define mozilla_mscom_MainThreadInvoker_h
9 
10 #include <windows.h>
11 
12 #include <utility>
13 
14 #include "mozilla/AlreadyAddRefed.h"
15 #include "mozilla/StaticPtr.h"
16 #include "mozilla/TimeStamp.h"
17 #include "nsCOMPtr.h"
18 #include "nsThreadUtils.h"
19 
20 class nsIRunnable;
21 
22 namespace mozilla {
23 namespace mscom {
24 
25 class MainThreadInvoker {
26  public:
27   MainThreadInvoker();
28 
29   bool Invoke(already_AddRefed<nsIRunnable>&& aRunnable);
GetDuration()30   const TimeDuration& GetDuration() const { return mDuration; }
GetTargetThread()31   static HANDLE GetTargetThread() { return sMainThread; }
32 
33  private:
34   TimeDuration mDuration;
35 
36   static bool InitStatics();
37   static VOID CALLBACK MainThreadAPC(ULONG_PTR aParam);
38 
39   static HANDLE sMainThread;
40 };
41 
42 template <typename Class, typename... Args>
InvokeOnMainThread(const char * aName,Class * aObject,void (Class::* aMethod)(Args...),Args &&...aArgs)43 inline bool InvokeOnMainThread(const char* aName, Class* aObject,
44                                void (Class::*aMethod)(Args...),
45                                Args&&... aArgs) {
46   nsCOMPtr<nsIRunnable> runnable(NewNonOwningRunnableMethod<Args...>(
47       aName, aObject, aMethod, std::forward<Args>(aArgs)...));
48 
49   MainThreadInvoker invoker;
50   return invoker.Invoke(runnable.forget());
51 }
52 
53 }  // namespace mscom
54 }  // namespace mozilla
55 
56 #endif  // mozilla_mscom_MainThreadInvoker_h
57