michael@0: /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* vim:expandtab:shiftwidth=2:tabstop=2: michael@0: */ 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 michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #include "nsIdleService.h" michael@0: #include "nsString.h" michael@0: #include "nsIObserverService.h" michael@0: #include "nsIServiceManager.h" michael@0: #include "nsDebug.h" michael@0: #include "nsCOMArray.h" michael@0: #include "nsXULAppAPI.h" michael@0: #include "prinrval.h" michael@0: #include "prlog.h" michael@0: #include "prtime.h" michael@0: #include "mozilla/dom/ContentChild.h" michael@0: #include "mozilla/Services.h" michael@0: #include "mozilla/Preferences.h" michael@0: #include "mozilla/Telemetry.h" michael@0: #include michael@0: michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: #include michael@0: #endif michael@0: michael@0: using namespace mozilla; michael@0: michael@0: // interval in milliseconds between internal idle time requests. michael@0: #define MIN_IDLE_POLL_INTERVAL_MSEC (5 * PR_MSEC_PER_SEC) /* 5 sec */ michael@0: michael@0: // After the twenty four hour period expires for an idle daily, this is the michael@0: // amount of idle time we wait for before actually firing the idle-daily michael@0: // event. michael@0: #define DAILY_SIGNIFICANT_IDLE_SERVICE_SEC (3 * 60) michael@0: michael@0: // In cases where it's been longer than twenty four hours since the last michael@0: // idle-daily, this is the shortend amount of idle time we wait for before michael@0: // firing the idle-daily event. michael@0: #define DAILY_SHORTENED_IDLE_SERVICE_SEC 60 michael@0: michael@0: // Pref for last time (seconds since epoch) daily notification was sent. michael@0: #define PREF_LAST_DAILY "idle.lastDailyNotification" michael@0: michael@0: // Number of seconds in a day. michael@0: #define SECONDS_PER_DAY 86400 michael@0: michael@0: #ifdef PR_LOGGING michael@0: static PRLogModuleInfo *sLog = nullptr; michael@0: #endif michael@0: michael@0: // Use this to find previously added observers in our array: michael@0: class IdleListenerComparator michael@0: { michael@0: public: michael@0: bool Equals(IdleListener a, IdleListener b) const michael@0: { michael@0: return (a.observer == b.observer) && michael@0: (a.reqIdleTime == b.reqIdleTime); michael@0: } michael@0: }; michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: //// nsIdleServiceDaily michael@0: michael@0: NS_IMPL_ISUPPORTS(nsIdleServiceDaily, nsIObserver, nsISupportsWeakReference) michael@0: michael@0: NS_IMETHODIMP michael@0: nsIdleServiceDaily::Observe(nsISupports *, michael@0: const char *aTopic, michael@0: const char16_t *) michael@0: { michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("nsIdleServiceDaily: Observe '%s' (%d)", michael@0: aTopic, mShutdownInProgress)); michael@0: michael@0: if (strcmp(aTopic, "profile-after-change") == 0) { michael@0: // We are back. Start sending notifications again. michael@0: mShutdownInProgress = false; michael@0: return NS_OK; michael@0: } michael@0: michael@0: if (strcmp(aTopic, "xpcom-will-shutdown") == 0 || michael@0: strcmp(aTopic, "profile-change-teardown") == 0) { michael@0: mShutdownInProgress = true; michael@0: } michael@0: michael@0: if (mShutdownInProgress || strcmp(aTopic, OBSERVER_TOPIC_ACTIVE) == 0) { michael@0: return NS_OK; michael@0: } michael@0: MOZ_ASSERT(strcmp(aTopic, OBSERVER_TOPIC_IDLE) == 0); michael@0: michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("nsIdleServiceDaily: Notifying idle-daily observers")); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "Notifying idle-daily observers"); michael@0: #endif michael@0: michael@0: // Send the idle-daily observer event michael@0: nsCOMPtr observerService = michael@0: mozilla::services::GetObserverService(); michael@0: NS_ENSURE_STATE(observerService); michael@0: (void)observerService->NotifyObservers(nullptr, michael@0: OBSERVER_TOPIC_IDLE_DAILY, michael@0: nullptr); michael@0: michael@0: // Notify the category observers. michael@0: nsCOMArray entries; michael@0: mCategoryObservers.GetEntries(entries); michael@0: for (int32_t i = 0; i < entries.Count(); ++i) { michael@0: (void)entries[i]->Observe(nullptr, OBSERVER_TOPIC_IDLE_DAILY, nullptr); michael@0: } michael@0: michael@0: // Stop observing idle for today. michael@0: (void)mIdleService->RemoveIdleObserver(this, mIdleDailyTriggerWait); michael@0: michael@0: // Set the last idle-daily time pref. michael@0: int32_t nowSec = static_cast(PR_Now() / PR_USEC_PER_SEC); michael@0: Preferences::SetInt(PREF_LAST_DAILY, nowSec); michael@0: michael@0: // Force that to be stored so we don't retrigger twice a day under michael@0: // any circumstances. michael@0: nsIPrefService* prefs = Preferences::GetService(); michael@0: if (prefs) { michael@0: prefs->SavePrefFile(nullptr); michael@0: } michael@0: michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("nsIdleServiceDaily: Storing last idle time as %d sec.", nowSec)); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "Storing last idle time as %d", nowSec); michael@0: #endif michael@0: michael@0: // Note the moment we expect to get the next timer callback michael@0: mExpectedTriggerTime = PR_Now() + ((PRTime)SECONDS_PER_DAY * michael@0: (PRTime)PR_USEC_PER_SEC); michael@0: michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("nsIdleServiceDaily: Restarting daily timer")); michael@0: michael@0: // Start timer for the next check in one day. michael@0: (void)mTimer->InitWithFuncCallback(DailyCallback, michael@0: this, michael@0: SECONDS_PER_DAY * PR_MSEC_PER_SEC, michael@0: nsITimer::TYPE_ONE_SHOT); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsIdleServiceDaily::nsIdleServiceDaily(nsIIdleService* aIdleService) michael@0: : mIdleService(aIdleService) michael@0: , mTimer(do_CreateInstance(NS_TIMER_CONTRACTID)) michael@0: , mCategoryObservers(OBSERVER_TOPIC_IDLE_DAILY) michael@0: , mShutdownInProgress(false) michael@0: , mExpectedTriggerTime(0) michael@0: , mIdleDailyTriggerWait(DAILY_SIGNIFICANT_IDLE_SERVICE_SEC) michael@0: { michael@0: } michael@0: michael@0: void michael@0: nsIdleServiceDaily::Init() michael@0: { michael@0: // First check the time of the last idle-daily event notification. If it michael@0: // has been 24 hours or higher, or if we have never sent an idle-daily, michael@0: // get ready to send an idle-daily event. Otherwise set a timer targeted michael@0: // at 24 hours past the last idle-daily we sent. michael@0: michael@0: int32_t nowSec = static_cast(PR_Now() / PR_USEC_PER_SEC); michael@0: int32_t lastDaily = Preferences::GetInt(PREF_LAST_DAILY, 0); michael@0: if (lastDaily < 0 || lastDaily > nowSec) { michael@0: // The time is bogus, use default. michael@0: lastDaily = 0; michael@0: } michael@0: int32_t secondsSinceLastDaily = nowSec - lastDaily; michael@0: michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("nsIdleServiceDaily: Init: seconds since last daily: %d", michael@0: secondsSinceLastDaily)); michael@0: michael@0: // If it has been twenty four hours or more or if we have never sent an michael@0: // idle-daily event get ready to send it during the next idle period. michael@0: if (secondsSinceLastDaily > SECONDS_PER_DAY) { michael@0: // Check for a "long wait", e.g. 48-hours or more. michael@0: bool hasBeenLongWait = (lastDaily && michael@0: (secondsSinceLastDaily > (SECONDS_PER_DAY * 2))); michael@0: michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("nsIdleServiceDaily: has been long wait? %d", michael@0: hasBeenLongWait)); michael@0: michael@0: // StageIdleDaily sets up a wait for the user to become idle and then michael@0: // sends the idle-daily event. michael@0: StageIdleDaily(hasBeenLongWait); michael@0: } else { michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("nsIdleServiceDaily: Setting timer a day from now")); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "Setting timer a day from now"); michael@0: #endif michael@0: michael@0: // According to our last idle-daily pref, the last idle-daily was fired michael@0: // less then 24 hours ago. Set a wait for the amount of time remaining. michael@0: int32_t milliSecLeftUntilDaily = (SECONDS_PER_DAY - secondsSinceLastDaily) michael@0: * PR_MSEC_PER_SEC; michael@0: michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("nsIdleServiceDaily: Seconds till next timeout: %d", michael@0: (SECONDS_PER_DAY - secondsSinceLastDaily))); michael@0: michael@0: // Mark the time at which we expect this to fire. On systems with faulty michael@0: // timers, we need to be able to cross check that the timer fired at the michael@0: // expected time. michael@0: mExpectedTriggerTime = PR_Now() + michael@0: (milliSecLeftUntilDaily * PR_USEC_PER_MSEC); michael@0: michael@0: (void)mTimer->InitWithFuncCallback(DailyCallback, michael@0: this, michael@0: milliSecLeftUntilDaily, michael@0: nsITimer::TYPE_ONE_SHOT); michael@0: } michael@0: michael@0: // Register for when we should terminate/pause michael@0: nsCOMPtr obs = mozilla::services::GetObserverService(); michael@0: if (obs) { michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("nsIdleServiceDaily: Registering for system event observers.")); michael@0: obs->AddObserver(this, "xpcom-will-shutdown", true); michael@0: obs->AddObserver(this, "profile-change-teardown", true); michael@0: obs->AddObserver(this, "profile-after-change", true); michael@0: } michael@0: } michael@0: michael@0: nsIdleServiceDaily::~nsIdleServiceDaily() michael@0: { michael@0: if (mTimer) { michael@0: mTimer->Cancel(); michael@0: mTimer = nullptr; michael@0: } michael@0: } michael@0: michael@0: michael@0: void michael@0: nsIdleServiceDaily::StageIdleDaily(bool aHasBeenLongWait) michael@0: { michael@0: NS_ASSERTION(mIdleService, "No idle service available?"); michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("nsIdleServiceDaily: Registering Idle observer callback " michael@0: "(short wait requested? %d)", aHasBeenLongWait)); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "Registering Idle observer callback"); michael@0: #endif michael@0: mIdleDailyTriggerWait = (aHasBeenLongWait ? michael@0: DAILY_SHORTENED_IDLE_SERVICE_SEC : michael@0: DAILY_SIGNIFICANT_IDLE_SERVICE_SEC); michael@0: (void)mIdleService->AddIdleObserver(this, mIdleDailyTriggerWait); michael@0: } michael@0: michael@0: // static michael@0: void michael@0: nsIdleServiceDaily::DailyCallback(nsITimer* aTimer, void* aClosure) michael@0: { michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("nsIdleServiceDaily: DailyCallback running")); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "DailyCallback running"); michael@0: #endif michael@0: michael@0: nsIdleServiceDaily* self = static_cast(aClosure); michael@0: michael@0: // Check to be sure the timer didn't fire early. This currently only michael@0: // happens on android. michael@0: PRTime now = PR_Now(); michael@0: if (self->mExpectedTriggerTime && now < self->mExpectedTriggerTime) { michael@0: // Timer returned early, reschedule to the appropriate time. michael@0: PRTime delayTime = self->mExpectedTriggerTime - now; michael@0: michael@0: // Add 10 ms to ensure we don't undershoot, and never get a "0" timer. michael@0: delayTime += 10 * PR_USEC_PER_MSEC; michael@0: michael@0: PR_LOG(sLog, PR_LOG_DEBUG, ("nsIdleServiceDaily: DailyCallback resetting timer to %lld msec", michael@0: delayTime / PR_USEC_PER_MSEC)); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "DailyCallback resetting timer to %lld msec", michael@0: delayTime / PR_USEC_PER_MSEC); michael@0: #endif michael@0: michael@0: (void)self->mTimer->InitWithFuncCallback(DailyCallback, michael@0: self, michael@0: delayTime / PR_USEC_PER_MSEC, michael@0: nsITimer::TYPE_ONE_SHOT); michael@0: return; michael@0: } michael@0: michael@0: // Register for a short term wait for idle event. When this fires we fire michael@0: // our idle-daily event. michael@0: self->StageIdleDaily(false); michael@0: } michael@0: michael@0: michael@0: /** michael@0: * The idle services goal is to notify subscribers when a certain time has michael@0: * passed since the last user interaction with the system. michael@0: * michael@0: * On some platforms this is defined as the last time user events reached this michael@0: * application, on other platforms it is a system wide thing - the preferred michael@0: * implementation is to use the system idle time, rather than the application michael@0: * idle time, as the things depending on the idle service are likely to use michael@0: * significant resources (network, disk, memory, cpu, etc.). michael@0: * michael@0: * When the idle service needs to use the system wide idle timer, it typically michael@0: * needs to poll the idle time value by the means of a timer. It needs to michael@0: * poll fast when it is in active idle mode (when it has a listener in the idle michael@0: * mode) as it needs to detect if the user is active in other applications. michael@0: * michael@0: * When the service is waiting for the first listener to become idle, or when michael@0: * it is only monitoring application idle time, it only needs to have the timer michael@0: * expire at the time the next listener goes idle. michael@0: * michael@0: * The core state of the service is determined by: michael@0: * michael@0: * - A list of listeners. michael@0: * michael@0: * - A boolean that tells if any listeners are in idle mode. michael@0: * michael@0: * - A delta value that indicates when, measured from the last non-idle time, michael@0: * the next listener should switch to idle mode. michael@0: * michael@0: * - An absolute time of the last time idle mode was detected (this is used to michael@0: * judge if we have been out of idle mode since the last invocation of the michael@0: * service. michael@0: * michael@0: * There are four entry points into the system: michael@0: * michael@0: * - A new listener is registered. michael@0: * michael@0: * - An existing listener is deregistered. michael@0: * michael@0: * - User interaction is detected. michael@0: * michael@0: * - The timer expires. michael@0: * michael@0: * When a new listener is added its idle timeout, is compared with the next idle michael@0: * timeout, and if lower, that time is stored as the new timeout, and the timer michael@0: * is reconfigured to ensure a timeout around the time the new listener should michael@0: * timeout. michael@0: * michael@0: * If the next idle time is above the idle time requested by the new listener michael@0: * it won't be informed until the timer expires, this is to avoid recursive michael@0: * behavior and to simplify the code. In this case the timer will be set to michael@0: * about 10 ms. michael@0: * michael@0: * When an existing listener is deregistered, it is just removed from the list michael@0: * of active listeners, we don't stop the timer, we just let it expire. michael@0: * michael@0: * When user interaction is detected, either because it was directly detected or michael@0: * because we polled the system timer and found it to be unexpected low, then we michael@0: * check the flag that tells us if any listeners are in idle mode, if there are michael@0: * they are removed from idle mode and told so, and we reset our state michael@0: * caculating the next timeout and restart the timer if needed. michael@0: * michael@0: * ---- Build in logic michael@0: * michael@0: * In order to avoid restarting the timer endlessly, the timer function has michael@0: * logic that will only restart the timer, if the requested timeout is before michael@0: * the current timeout. michael@0: * michael@0: */ michael@0: michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: //// nsIdleService michael@0: michael@0: namespace { michael@0: nsIdleService* gIdleService; michael@0: } michael@0: michael@0: already_AddRefed michael@0: nsIdleService::GetInstance() michael@0: { michael@0: nsRefPtr instance(gIdleService); michael@0: return instance.forget(); michael@0: } michael@0: michael@0: nsIdleService::nsIdleService() : mCurrentlySetToTimeoutAt(TimeStamp()), michael@0: mIdleObserverCount(0), michael@0: mDeltaToNextIdleSwitchInS(UINT32_MAX), michael@0: mLastUserInteraction(TimeStamp::Now()) michael@0: { michael@0: #ifdef PR_LOGGING michael@0: if (sLog == nullptr) michael@0: sLog = PR_NewLogModule("idleService"); michael@0: #endif michael@0: MOZ_ASSERT(!gIdleService); michael@0: gIdleService = this; michael@0: if (XRE_GetProcessType() == GeckoProcessType_Default) { michael@0: mDailyIdle = new nsIdleServiceDaily(this); michael@0: mDailyIdle->Init(); michael@0: } michael@0: } michael@0: michael@0: nsIdleService::~nsIdleService() michael@0: { michael@0: if(mTimer) { michael@0: mTimer->Cancel(); michael@0: } michael@0: michael@0: michael@0: MOZ_ASSERT(gIdleService == this); michael@0: gIdleService = nullptr; michael@0: } michael@0: michael@0: NS_IMPL_ISUPPORTS(nsIdleService, nsIIdleService, nsIIdleServiceInternal) michael@0: michael@0: NS_IMETHODIMP michael@0: nsIdleService::AddIdleObserver(nsIObserver* aObserver, uint32_t aIdleTimeInS) michael@0: { michael@0: NS_ENSURE_ARG_POINTER(aObserver); michael@0: // We don't accept idle time at 0, and we can't handle idle time that are too michael@0: // high either - no more than ~136 years. michael@0: NS_ENSURE_ARG_RANGE(aIdleTimeInS, 1, (UINT32_MAX / 10) - 1); michael@0: michael@0: if (XRE_GetProcessType() == GeckoProcessType_Content) { michael@0: dom::ContentChild* cpc = dom::ContentChild::GetSingleton(); michael@0: cpc->AddIdleObserver(aObserver, aIdleTimeInS); michael@0: return NS_OK; michael@0: } michael@0: michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: Register idle observer %p for %d seconds", michael@0: aObserver, aIdleTimeInS)); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "Register idle observer %p for %d seconds", michael@0: aObserver, aIdleTimeInS); michael@0: #endif michael@0: michael@0: // Put the time + observer in a struct we can keep: michael@0: IdleListener listener(aObserver, aIdleTimeInS); michael@0: michael@0: if (!mArrayListeners.AppendElement(listener)) { michael@0: return NS_ERROR_OUT_OF_MEMORY; michael@0: } michael@0: michael@0: // Create our timer callback if it's not there already. michael@0: if (!mTimer) { michael@0: nsresult rv; michael@0: mTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: } michael@0: michael@0: // Check if the newly added observer has a smaller wait time than what we michael@0: // are waiting for now. michael@0: if (mDeltaToNextIdleSwitchInS > aIdleTimeInS) { michael@0: // If it is, then this is the next to move to idle (at this point we michael@0: // don't care if it should have switched already). michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: Register: adjusting next switch from %d to %d seconds", michael@0: mDeltaToNextIdleSwitchInS, aIdleTimeInS)); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "Register: adjusting next switch from %d to %d seconds", michael@0: mDeltaToNextIdleSwitchInS, aIdleTimeInS); michael@0: #endif michael@0: michael@0: mDeltaToNextIdleSwitchInS = aIdleTimeInS; michael@0: } michael@0: michael@0: // Ensure timer is running. michael@0: ReconfigureTimer(); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsIdleService::RemoveIdleObserver(nsIObserver* aObserver, uint32_t aTimeInS) michael@0: { michael@0: michael@0: NS_ENSURE_ARG_POINTER(aObserver); michael@0: NS_ENSURE_ARG(aTimeInS); michael@0: michael@0: if (XRE_GetProcessType() == GeckoProcessType_Content) { michael@0: dom::ContentChild* cpc = dom::ContentChild::GetSingleton(); michael@0: cpc->RemoveIdleObserver(aObserver, aTimeInS); michael@0: return NS_OK; michael@0: } michael@0: michael@0: IdleListener listener(aObserver, aTimeInS); michael@0: michael@0: // Find the entry and remove it, if it was the last entry, we just let the michael@0: // existing timer run to completion (there might be a new registration in a michael@0: // little while. michael@0: IdleListenerComparator c; michael@0: nsTArray::index_type listenerIndex = mArrayListeners.IndexOf(listener, 0, c); michael@0: if (listenerIndex != mArrayListeners.NoIndex) { michael@0: if (mArrayListeners.ElementAt(listenerIndex).isIdle) michael@0: mIdleObserverCount--; michael@0: mArrayListeners.RemoveElementAt(listenerIndex); michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: Remove observer %p (%d seconds), %d remain idle", michael@0: aObserver, aTimeInS, mIdleObserverCount)); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "Remove observer %p (%d seconds), %d remain idle", michael@0: aObserver, aTimeInS, mIdleObserverCount); michael@0: #endif michael@0: return NS_OK; michael@0: } michael@0: michael@0: // If we get here, we haven't removed anything: michael@0: PR_LOG(sLog, PR_LOG_WARNING, michael@0: ("idleService: Failed to remove idle observer %p (%d seconds)", michael@0: aObserver, aTimeInS)); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "Failed to remove idle observer %p (%d seconds)", michael@0: aObserver, aTimeInS); michael@0: #endif michael@0: return NS_ERROR_FAILURE; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsIdleService::ResetIdleTimeOut(uint32_t idleDeltaInMS) michael@0: { michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: Reset idle timeout (last interaction %u msec)", michael@0: idleDeltaInMS)); michael@0: michael@0: // Store the time michael@0: mLastUserInteraction = TimeStamp::Now() - michael@0: TimeDuration::FromMilliseconds(idleDeltaInMS); michael@0: michael@0: // If no one is idle, then we are done, any existing timers can keep running. michael@0: if (mIdleObserverCount == 0) { michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: Reset idle timeout: no idle observers")); michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Mark all idle services as non-idle, and calculate the next idle timeout. michael@0: Telemetry::AutoTimer timer; michael@0: nsCOMArray notifyList; michael@0: mDeltaToNextIdleSwitchInS = UINT32_MAX; michael@0: michael@0: // Loop through all listeners, and find any that have detected idle. michael@0: for (uint32_t i = 0; i < mArrayListeners.Length(); i++) { michael@0: IdleListener& curListener = mArrayListeners.ElementAt(i); michael@0: michael@0: // If the listener was idle, then he shouldn't be any longer. michael@0: if (curListener.isIdle) { michael@0: notifyList.AppendObject(curListener.observer); michael@0: curListener.isIdle = false; michael@0: } michael@0: michael@0: // Check if the listener is the next one to timeout. michael@0: mDeltaToNextIdleSwitchInS = std::min(mDeltaToNextIdleSwitchInS, michael@0: curListener.reqIdleTime); michael@0: } michael@0: michael@0: // When we are done, then we wont have anyone idle. michael@0: mIdleObserverCount = 0; michael@0: michael@0: // Restart the idle timer, and do so before anyone can delay us. michael@0: ReconfigureTimer(); michael@0: michael@0: int32_t numberOfPendingNotifications = notifyList.Count(); michael@0: Telemetry::Accumulate(Telemetry::IDLE_NOTIFY_BACK_LISTENERS, michael@0: numberOfPendingNotifications); michael@0: michael@0: // Bail if nothing to do. michael@0: if (!numberOfPendingNotifications) { michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Now send "active" events to all, if any should have timed out already, michael@0: // then they will be reawaken by the timer that is already running. michael@0: michael@0: // We need a text string to send with any state change events. michael@0: nsAutoString timeStr; michael@0: michael@0: timeStr.AppendInt((int32_t)(idleDeltaInMS / PR_MSEC_PER_SEC)); michael@0: michael@0: // Send the "non-idle" events. michael@0: while (numberOfPendingNotifications--) { michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: Reset idle timeout: tell observer %p user is back", michael@0: notifyList[numberOfPendingNotifications])); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "Reset idle timeout: tell observer %p user is back", michael@0: notifyList[numberOfPendingNotifications]); michael@0: #endif michael@0: notifyList[numberOfPendingNotifications]->Observe(this, michael@0: OBSERVER_TOPIC_ACTIVE, michael@0: timeStr.get()); michael@0: } michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsIdleService::GetIdleTime(uint32_t* idleTime) michael@0: { michael@0: // Check sanity of in parameter. michael@0: if (!idleTime) { michael@0: return NS_ERROR_NULL_POINTER; michael@0: } michael@0: michael@0: // Polled idle time in ms. michael@0: uint32_t polledIdleTimeMS; michael@0: michael@0: bool polledIdleTimeIsValid = PollIdleTime(&polledIdleTimeMS); michael@0: michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: Get idle time: polled %u msec, valid = %d", michael@0: polledIdleTimeMS, polledIdleTimeIsValid)); michael@0: michael@0: // timeSinceReset is in milliseconds. michael@0: TimeDuration timeSinceReset = TimeStamp::Now() - mLastUserInteraction; michael@0: uint32_t timeSinceResetInMS = timeSinceReset.ToMilliseconds(); michael@0: michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: Get idle time: time since reset %u msec", michael@0: timeSinceResetInMS)); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "Get idle time: time since reset %u msec", michael@0: timeSinceResetInMS); michael@0: #endif michael@0: michael@0: // If we did't get pulled data, return the time since last idle reset. michael@0: if (!polledIdleTimeIsValid) { michael@0: // We need to convert to ms before returning the time. michael@0: *idleTime = timeSinceResetInMS; michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Otherwise return the shortest time detected (in ms). michael@0: *idleTime = std::min(timeSinceResetInMS, polledIdleTimeMS); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: michael@0: bool michael@0: nsIdleService::PollIdleTime(uint32_t* /*aIdleTime*/) michael@0: { michael@0: // Default behavior is not to have the ability to poll an idle time. michael@0: return false; michael@0: } michael@0: michael@0: bool michael@0: nsIdleService::UsePollMode() michael@0: { michael@0: uint32_t dummy; michael@0: return PollIdleTime(&dummy); michael@0: } michael@0: michael@0: void michael@0: nsIdleService::StaticIdleTimerCallback(nsITimer* aTimer, void* aClosure) michael@0: { michael@0: static_cast(aClosure)->IdleTimerCallback(); michael@0: } michael@0: michael@0: void michael@0: nsIdleService::IdleTimerCallback(void) michael@0: { michael@0: // Remember that we no longer have a timer running. michael@0: mCurrentlySetToTimeoutAt = TimeStamp(); michael@0: michael@0: // Find the last detected idle time. michael@0: uint32_t lastIdleTimeInMS = static_cast((TimeStamp::Now() - michael@0: mLastUserInteraction).ToMilliseconds()); michael@0: // Get the current idle time. michael@0: uint32_t currentIdleTimeInMS; michael@0: michael@0: if (NS_FAILED(GetIdleTime(¤tIdleTimeInMS))) { michael@0: PR_LOG(sLog, PR_LOG_ALWAYS, michael@0: ("idleService: Idle timer callback: failed to get idle time")); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "Idle timer callback: failed to get idle time"); michael@0: #endif michael@0: return; michael@0: } michael@0: michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: Idle timer callback: current idle time %u msec", michael@0: currentIdleTimeInMS)); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "Idle timer callback: current idle time %u msec", michael@0: currentIdleTimeInMS); michael@0: #endif michael@0: michael@0: // Check if we have had some user interaction we didn't handle previously michael@0: // we do the calculation in ms to lessen the chance for rounding errors to michael@0: // trigger wrong results. michael@0: if (lastIdleTimeInMS > currentIdleTimeInMS) michael@0: { michael@0: // We had user activity, so handle that part first (to ensure the listeners michael@0: // don't risk getting an non-idle after they get a new idle indication. michael@0: ResetIdleTimeOut(currentIdleTimeInMS); michael@0: michael@0: // NOTE: We can't bail here, as we might have something already timed out. michael@0: } michael@0: michael@0: // Find the idle time in S. michael@0: uint32_t currentIdleTimeInS = currentIdleTimeInMS / PR_MSEC_PER_SEC; michael@0: michael@0: // Restart timer and bail if no-one are expected to be in idle michael@0: if (mDeltaToNextIdleSwitchInS > currentIdleTimeInS) { michael@0: // If we didn't expect anyone to be idle, then just re-start the timer. michael@0: ReconfigureTimer(); michael@0: return; michael@0: } michael@0: michael@0: // Tell expired listeners they are expired,and find the next timeout michael@0: Telemetry::AutoTimer timer; michael@0: michael@0: // We need to initialise the time to the next idle switch. michael@0: mDeltaToNextIdleSwitchInS = UINT32_MAX; michael@0: michael@0: // Create list of observers that should be notified. michael@0: nsCOMArray notifyList; michael@0: michael@0: for (uint32_t i = 0; i < mArrayListeners.Length(); i++) { michael@0: IdleListener& curListener = mArrayListeners.ElementAt(i); michael@0: michael@0: // We are only interested in items, that are not in the idle state. michael@0: if (!curListener.isIdle) { michael@0: // If they have an idle time smaller than the actual idle time. michael@0: if (curListener.reqIdleTime <= currentIdleTimeInS) { michael@0: // Then add the listener to the list of listeners that should be michael@0: // notified. michael@0: notifyList.AppendObject(curListener.observer); michael@0: // This listener is now idle. michael@0: curListener.isIdle = true; michael@0: // Remember we have someone idle. michael@0: mIdleObserverCount++; michael@0: } else { michael@0: // Listeners that are not timed out yet are candidates for timing out. michael@0: mDeltaToNextIdleSwitchInS = std::min(mDeltaToNextIdleSwitchInS, michael@0: curListener.reqIdleTime); michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Restart the timer before any notifications that could slow us down are michael@0: // done. michael@0: ReconfigureTimer(); michael@0: michael@0: int32_t numberOfPendingNotifications = notifyList.Count(); michael@0: Telemetry::Accumulate(Telemetry::IDLE_NOTIFY_IDLE_LISTENERS, michael@0: numberOfPendingNotifications); michael@0: michael@0: // Bail if nothing to do. michael@0: if (!numberOfPendingNotifications) { michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: **** Idle timer callback: no observers to message.")); michael@0: return; michael@0: } michael@0: michael@0: // We need a text string to send with any state change events. michael@0: nsAutoString timeStr; michael@0: timeStr.AppendInt(currentIdleTimeInS); michael@0: michael@0: // Notify all listeners that just timed out. michael@0: while (numberOfPendingNotifications--) { michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: **** Idle timer callback: tell observer %p user is idle", michael@0: notifyList[numberOfPendingNotifications])); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "Idle timer callback: tell observer %p user is idle", michael@0: notifyList[numberOfPendingNotifications]); michael@0: #endif michael@0: notifyList[numberOfPendingNotifications]->Observe(this, michael@0: OBSERVER_TOPIC_IDLE, michael@0: timeStr.get()); michael@0: } michael@0: } michael@0: michael@0: void michael@0: nsIdleService::SetTimerExpiryIfBefore(TimeStamp aNextTimeout) michael@0: { michael@0: #if defined(PR_LOGGING) || defined(MOZ_WIDGET_ANDROID) michael@0: TimeDuration nextTimeoutDuration = aNextTimeout - TimeStamp::Now(); michael@0: #endif michael@0: michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: SetTimerExpiryIfBefore: next timeout %0.f msec from now", michael@0: nextTimeoutDuration.ToMilliseconds())); michael@0: michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "SetTimerExpiryIfBefore: next timeout %0.f msec from now", michael@0: nextTimeoutDuration.ToMilliseconds()); michael@0: #endif michael@0: michael@0: // Bail if we don't have a timer service. michael@0: if (!mTimer) { michael@0: return; michael@0: } michael@0: michael@0: // If the new timeout is before the old one or we don't have a timer running, michael@0: // then restart the timer. michael@0: if (mCurrentlySetToTimeoutAt.IsNull() || michael@0: mCurrentlySetToTimeoutAt > aNextTimeout) { michael@0: michael@0: mCurrentlySetToTimeoutAt = aNextTimeout; michael@0: michael@0: // Stop the current timer (it's ok to try'n stop it, even it isn't running). michael@0: mTimer->Cancel(); michael@0: michael@0: // Check that the timeout is actually in the future, otherwise make it so. michael@0: TimeStamp currentTime = TimeStamp::Now(); michael@0: if (currentTime > mCurrentlySetToTimeoutAt) { michael@0: mCurrentlySetToTimeoutAt = currentTime; michael@0: } michael@0: michael@0: // Add 10 ms to ensure we don't undershoot, and never get a "0" timer. michael@0: mCurrentlySetToTimeoutAt += TimeDuration::FromMilliseconds(10); michael@0: michael@0: TimeDuration deltaTime = mCurrentlySetToTimeoutAt - currentTime; michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: IdleService reset timer expiry to %0.f msec from now", michael@0: deltaTime.ToMilliseconds())); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "reset timer expiry to %0.f msec from now", michael@0: deltaTime.ToMilliseconds()); michael@0: #endif michael@0: michael@0: // Start the timer michael@0: mTimer->InitWithFuncCallback(StaticIdleTimerCallback, michael@0: this, michael@0: deltaTime.ToMilliseconds(), michael@0: nsITimer::TYPE_ONE_SHOT); michael@0: michael@0: } michael@0: } michael@0: michael@0: void michael@0: nsIdleService::ReconfigureTimer(void) michael@0: { michael@0: // Check if either someone is idle, or someone will become idle. michael@0: if ((mIdleObserverCount == 0) && UINT32_MAX == mDeltaToNextIdleSwitchInS) { michael@0: // If not, just let any existing timers run to completion michael@0: // And bail out. michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: ReconfigureTimer: no idle or waiting observers")); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "ReconfigureTimer: no idle or waiting observers"); michael@0: #endif michael@0: return; michael@0: } michael@0: michael@0: // Find the next timeout value, assuming we are not polling. michael@0: michael@0: // We need to store the current time, so we don't get artifacts from the time michael@0: // ticking while we are processing. michael@0: TimeStamp curTime = TimeStamp::Now(); michael@0: michael@0: TimeStamp nextTimeoutAt = mLastUserInteraction + michael@0: TimeDuration::FromSeconds(mDeltaToNextIdleSwitchInS); michael@0: michael@0: #if defined(PR_LOGGING) || defined(MOZ_WIDGET_ANDROID) michael@0: TimeDuration nextTimeoutDuration = nextTimeoutAt - curTime; michael@0: #endif michael@0: michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: next timeout %0.f msec from now", michael@0: nextTimeoutDuration.ToMilliseconds())); michael@0: michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "next timeout %0.f msec from now", michael@0: nextTimeoutDuration.ToMilliseconds()); michael@0: #endif michael@0: michael@0: // Check if we should correct the timeout time because we should poll before. michael@0: if ((mIdleObserverCount > 0) && UsePollMode()) { michael@0: TimeStamp pollTimeout = michael@0: curTime + TimeDuration::FromMilliseconds(MIN_IDLE_POLL_INTERVAL_MSEC); michael@0: michael@0: if (nextTimeoutAt > pollTimeout) { michael@0: PR_LOG(sLog, PR_LOG_DEBUG, michael@0: ("idleService: idle observers, reducing timeout to %lu msec from now", michael@0: MIN_IDLE_POLL_INTERVAL_MSEC)); michael@0: #ifdef MOZ_WIDGET_ANDROID michael@0: __android_log_print(ANDROID_LOG_INFO, "IdleService", michael@0: "idle observers, reducing timeout to %lu msec from now", michael@0: MIN_IDLE_POLL_INTERVAL_MSEC); michael@0: #endif michael@0: nextTimeoutAt = pollTimeout; michael@0: } michael@0: } michael@0: michael@0: SetTimerExpiryIfBefore(nextTimeoutAt); michael@0: }