michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this file, michael@0: * You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #include "Hal.h" michael@0: michael@0: #include michael@0: michael@0: #include "mozilla/ClearOnShutdown.h" michael@0: #include "mozilla/StaticPtr.h" michael@0: #include "nsComponentManagerUtils.h" michael@0: #include "nsITimer.h" michael@0: #include "nsThreadUtils.h" michael@0: michael@0: namespace mozilla { michael@0: namespace hal_impl { michael@0: michael@0: static void michael@0: TimerCallbackFunc(nsITimer *aTimer, void *aClosure) michael@0: { michael@0: hal::NotifyAlarmFired(); michael@0: } michael@0: michael@0: static StaticRefPtr sTimer; michael@0: michael@0: bool michael@0: EnableAlarm() michael@0: { michael@0: static bool initialized = false; michael@0: if (!initialized) { michael@0: initialized = true; michael@0: ClearOnShutdown(&sTimer); michael@0: } michael@0: michael@0: nsCOMPtr timer = do_CreateInstance("@mozilla.org/timer;1"); michael@0: sTimer = timer; michael@0: MOZ_ASSERT(sTimer); michael@0: return true; michael@0: } michael@0: michael@0: void michael@0: DisableAlarm() michael@0: { michael@0: /* michael@0: * DisableAlarm() may be called after sTimer has been set to null by michael@0: * ClearOnShutdown(). michael@0: */ michael@0: if (sTimer) { michael@0: sTimer->Cancel(); michael@0: } michael@0: } michael@0: michael@0: bool michael@0: SetAlarm(int32_t aSeconds, int32_t aNanoseconds) michael@0: { michael@0: if (!sTimer) { michael@0: HAL_LOG(("We should have enabled the alarm")); michael@0: MOZ_ASSERT(false); michael@0: return false; michael@0: } michael@0: michael@0: // Do the math to convert aSeconds and aNanoseconds into milliseconds since michael@0: // the epoch. michael@0: int64_t milliseconds = static_cast(aSeconds) * 1000 + michael@0: static_cast(aNanoseconds) / 1000000; michael@0: michael@0: // nsITimer expects relative milliseconds. michael@0: int64_t relMilliseconds = milliseconds - PR_Now() / 1000; michael@0: michael@0: // If the alarm time is in the past relative to PR_Now(), michael@0: // we choose to immediately fire the alarm. Passing 0 means nsITimer will michael@0: // queue a timeout event immediately. michael@0: sTimer->InitWithFuncCallback(TimerCallbackFunc, nullptr, michael@0: clamped(relMilliseconds, 0, INT32_MAX), michael@0: nsITimer::TYPE_ONE_SHOT); michael@0: return true; michael@0: } michael@0: michael@0: } // hal_impl michael@0: } // namespace mozilla