|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file, |
|
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 |
|
5 #include "Hal.h" |
|
6 |
|
7 #include <algorithm> |
|
8 |
|
9 #include "mozilla/ClearOnShutdown.h" |
|
10 #include "mozilla/StaticPtr.h" |
|
11 #include "nsComponentManagerUtils.h" |
|
12 #include "nsITimer.h" |
|
13 #include "nsThreadUtils.h" |
|
14 |
|
15 namespace mozilla { |
|
16 namespace hal_impl { |
|
17 |
|
18 static void |
|
19 TimerCallbackFunc(nsITimer *aTimer, void *aClosure) |
|
20 { |
|
21 hal::NotifyAlarmFired(); |
|
22 } |
|
23 |
|
24 static StaticRefPtr<nsITimer> sTimer; |
|
25 |
|
26 bool |
|
27 EnableAlarm() |
|
28 { |
|
29 static bool initialized = false; |
|
30 if (!initialized) { |
|
31 initialized = true; |
|
32 ClearOnShutdown(&sTimer); |
|
33 } |
|
34 |
|
35 nsCOMPtr<nsITimer> timer = do_CreateInstance("@mozilla.org/timer;1"); |
|
36 sTimer = timer; |
|
37 MOZ_ASSERT(sTimer); |
|
38 return true; |
|
39 } |
|
40 |
|
41 void |
|
42 DisableAlarm() |
|
43 { |
|
44 /* |
|
45 * DisableAlarm() may be called after sTimer has been set to null by |
|
46 * ClearOnShutdown(). |
|
47 */ |
|
48 if (sTimer) { |
|
49 sTimer->Cancel(); |
|
50 } |
|
51 } |
|
52 |
|
53 bool |
|
54 SetAlarm(int32_t aSeconds, int32_t aNanoseconds) |
|
55 { |
|
56 if (!sTimer) { |
|
57 HAL_LOG(("We should have enabled the alarm")); |
|
58 MOZ_ASSERT(false); |
|
59 return false; |
|
60 } |
|
61 |
|
62 // Do the math to convert aSeconds and aNanoseconds into milliseconds since |
|
63 // the epoch. |
|
64 int64_t milliseconds = static_cast<int64_t>(aSeconds) * 1000 + |
|
65 static_cast<int64_t>(aNanoseconds) / 1000000; |
|
66 |
|
67 // nsITimer expects relative milliseconds. |
|
68 int64_t relMilliseconds = milliseconds - PR_Now() / 1000; |
|
69 |
|
70 // If the alarm time is in the past relative to PR_Now(), |
|
71 // we choose to immediately fire the alarm. Passing 0 means nsITimer will |
|
72 // queue a timeout event immediately. |
|
73 sTimer->InitWithFuncCallback(TimerCallbackFunc, nullptr, |
|
74 clamped<int64_t>(relMilliseconds, 0, INT32_MAX), |
|
75 nsITimer::TYPE_ONE_SHOT); |
|
76 return true; |
|
77 } |
|
78 |
|
79 } // hal_impl |
|
80 } // namespace mozilla |