1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:expandtab:shiftwidth=2:tabstop=2:
4 /* This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 #include "nsIdleService.h"
10 #include "nsIObserverService.h"
11 #include "nsIServiceManager.h"
13 #include "nsCOMArray.h"
14 #include "nsXULAppAPI.h"
18 #include "mozilla/dom/ContentChild.h"
19 #include "mozilla/Services.h"
20 #include "mozilla/Preferences.h"
21 #include "mozilla/Telemetry.h"
24 #ifdef MOZ_WIDGET_ANDROID
25 #include <android/log.h>
28 using namespace mozilla
;
30 // interval in milliseconds between internal idle time requests.
31 #define MIN_IDLE_POLL_INTERVAL_MSEC (5 * PR_MSEC_PER_SEC) /* 5 sec */
33 // After the twenty four hour period expires for an idle daily, this is the
34 // amount of idle time we wait for before actually firing the idle-daily
36 #define DAILY_SIGNIFICANT_IDLE_SERVICE_SEC (3 * 60)
38 // In cases where it's been longer than twenty four hours since the last
39 // idle-daily, this is the shortend amount of idle time we wait for before
40 // firing the idle-daily event.
41 #define DAILY_SHORTENED_IDLE_SERVICE_SEC 60
43 // Pref for last time (seconds since epoch) daily notification was sent.
44 #define PREF_LAST_DAILY "idle.lastDailyNotification"
46 // Number of seconds in a day.
47 #define SECONDS_PER_DAY 86400
50 static PRLogModuleInfo
*sLog
= nullptr;
53 #define LOG_TAG "GeckoIdleService"
54 #define LOG_LEVEL ANDROID_LOG_DEBUG
56 // Use this to find previously added observers in our array:
57 class IdleListenerComparator
60 bool Equals(IdleListener a
, IdleListener b
) const
62 return (a
.observer
== b
.observer
) &&
63 (a
.reqIdleTime
== b
.reqIdleTime
);
67 ////////////////////////////////////////////////////////////////////////////////
68 //// nsIdleServiceDaily
70 NS_IMPL_ISUPPORTS(nsIdleServiceDaily
, nsIObserver
, nsISupportsWeakReference
)
73 nsIdleServiceDaily::Observe(nsISupports
*,
77 PR_LOG(sLog
, PR_LOG_DEBUG
,
78 ("nsIdleServiceDaily: Observe '%s' (%d)",
79 aTopic
, mShutdownInProgress
));
81 if (strcmp(aTopic
, "profile-after-change") == 0) {
82 // We are back. Start sending notifications again.
83 mShutdownInProgress
= false;
87 if (strcmp(aTopic
, "xpcom-will-shutdown") == 0 ||
88 strcmp(aTopic
, "profile-change-teardown") == 0) {
89 mShutdownInProgress
= true;
92 if (mShutdownInProgress
|| strcmp(aTopic
, OBSERVER_TOPIC_ACTIVE
) == 0) {
95 MOZ_ASSERT(strcmp(aTopic
, OBSERVER_TOPIC_IDLE
) == 0);
97 PR_LOG(sLog
, PR_LOG_DEBUG
,
98 ("nsIdleServiceDaily: Notifying idle-daily observers"));
99 #ifdef MOZ_WIDGET_ANDROID
100 __android_log_print(LOG_LEVEL
, LOG_TAG
,
101 "Notifying idle-daily observers");
104 // Send the idle-daily observer event
105 nsCOMPtr
<nsIObserverService
> observerService
=
106 mozilla::services::GetObserverService();
107 NS_ENSURE_STATE(observerService
);
108 (void)observerService
->NotifyObservers(nullptr,
109 OBSERVER_TOPIC_IDLE_DAILY
,
112 // Notify the category observers.
113 nsCOMArray
<nsIObserver
> entries
;
114 mCategoryObservers
.GetEntries(entries
);
115 for (int32_t i
= 0; i
< entries
.Count(); ++i
) {
116 (void)entries
[i
]->Observe(nullptr, OBSERVER_TOPIC_IDLE_DAILY
, nullptr);
119 // Stop observing idle for today.
120 (void)mIdleService
->RemoveIdleObserver(this, mIdleDailyTriggerWait
);
122 // Set the last idle-daily time pref.
123 int32_t nowSec
= static_cast<int32_t>(PR_Now() / PR_USEC_PER_SEC
);
124 Preferences::SetInt(PREF_LAST_DAILY
, nowSec
);
126 // Force that to be stored so we don't retrigger twice a day under
127 // any circumstances.
128 nsIPrefService
* prefs
= Preferences::GetService();
130 prefs
->SavePrefFile(nullptr);
133 PR_LOG(sLog
, PR_LOG_DEBUG
,
134 ("nsIdleServiceDaily: Storing last idle time as %d sec.", nowSec
));
135 #ifdef MOZ_WIDGET_ANDROID
136 __android_log_print(LOG_LEVEL
, LOG_TAG
,
137 "Storing last idle time as %d", nowSec
);
140 // Note the moment we expect to get the next timer callback
141 mExpectedTriggerTime
= PR_Now() + ((PRTime
)SECONDS_PER_DAY
*
142 (PRTime
)PR_USEC_PER_SEC
);
144 PR_LOG(sLog
, PR_LOG_DEBUG
,
145 ("nsIdleServiceDaily: Restarting daily timer"));
147 // Start timer for the next check in one day.
148 (void)mTimer
->InitWithFuncCallback(DailyCallback
,
150 SECONDS_PER_DAY
* PR_MSEC_PER_SEC
,
151 nsITimer::TYPE_ONE_SHOT
);
156 nsIdleServiceDaily::nsIdleServiceDaily(nsIIdleService
* aIdleService
)
157 : mIdleService(aIdleService
)
158 , mTimer(do_CreateInstance(NS_TIMER_CONTRACTID
))
159 , mCategoryObservers(OBSERVER_TOPIC_IDLE_DAILY
)
160 , mShutdownInProgress(false)
161 , mExpectedTriggerTime(0)
162 , mIdleDailyTriggerWait(DAILY_SIGNIFICANT_IDLE_SERVICE_SEC
)
167 nsIdleServiceDaily::Init()
169 // First check the time of the last idle-daily event notification. If it
170 // has been 24 hours or higher, or if we have never sent an idle-daily,
171 // get ready to send an idle-daily event. Otherwise set a timer targeted
172 // at 24 hours past the last idle-daily we sent.
174 int32_t nowSec
= static_cast<int32_t>(PR_Now() / PR_USEC_PER_SEC
);
175 int32_t lastDaily
= Preferences::GetInt(PREF_LAST_DAILY
, 0);
176 if (lastDaily
< 0 || lastDaily
> nowSec
) {
177 // The time is bogus, use default.
180 int32_t secondsSinceLastDaily
= nowSec
- lastDaily
;
182 PR_LOG(sLog
, PR_LOG_DEBUG
,
183 ("nsIdleServiceDaily: Init: seconds since last daily: %d",
184 secondsSinceLastDaily
));
186 // If it has been twenty four hours or more or if we have never sent an
187 // idle-daily event get ready to send it during the next idle period.
188 if (secondsSinceLastDaily
> SECONDS_PER_DAY
) {
189 // Check for a "long wait", e.g. 48-hours or more.
190 bool hasBeenLongWait
= (lastDaily
&&
191 (secondsSinceLastDaily
> (SECONDS_PER_DAY
* 2)));
193 PR_LOG(sLog
, PR_LOG_DEBUG
,
194 ("nsIdleServiceDaily: has been long wait? %d",
197 // StageIdleDaily sets up a wait for the user to become idle and then
198 // sends the idle-daily event.
199 StageIdleDaily(hasBeenLongWait
);
201 PR_LOG(sLog
, PR_LOG_DEBUG
,
202 ("nsIdleServiceDaily: Setting timer a day from now"));
203 #ifdef MOZ_WIDGET_ANDROID
204 __android_log_print(LOG_LEVEL
, LOG_TAG
,
205 "Setting timer a day from now");
208 // According to our last idle-daily pref, the last idle-daily was fired
209 // less then 24 hours ago. Set a wait for the amount of time remaining.
210 int32_t milliSecLeftUntilDaily
= (SECONDS_PER_DAY
- secondsSinceLastDaily
)
213 PR_LOG(sLog
, PR_LOG_DEBUG
,
214 ("nsIdleServiceDaily: Seconds till next timeout: %d",
215 (SECONDS_PER_DAY
- secondsSinceLastDaily
)));
217 // Mark the time at which we expect this to fire. On systems with faulty
218 // timers, we need to be able to cross check that the timer fired at the
220 mExpectedTriggerTime
= PR_Now() +
221 (milliSecLeftUntilDaily
* PR_USEC_PER_MSEC
);
223 (void)mTimer
->InitWithFuncCallback(DailyCallback
,
225 milliSecLeftUntilDaily
,
226 nsITimer::TYPE_ONE_SHOT
);
229 // Register for when we should terminate/pause
230 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
232 PR_LOG(sLog
, PR_LOG_DEBUG
,
233 ("nsIdleServiceDaily: Registering for system event observers."));
234 obs
->AddObserver(this, "xpcom-will-shutdown", true);
235 obs
->AddObserver(this, "profile-change-teardown", true);
236 obs
->AddObserver(this, "profile-after-change", true);
240 nsIdleServiceDaily::~nsIdleServiceDaily()
250 nsIdleServiceDaily::StageIdleDaily(bool aHasBeenLongWait
)
252 NS_ASSERTION(mIdleService
, "No idle service available?");
253 PR_LOG(sLog
, PR_LOG_DEBUG
,
254 ("nsIdleServiceDaily: Registering Idle observer callback "
255 "(short wait requested? %d)", aHasBeenLongWait
));
256 #ifdef MOZ_WIDGET_ANDROID
257 __android_log_print(LOG_LEVEL
, LOG_TAG
,
258 "Registering Idle observer callback");
260 mIdleDailyTriggerWait
= (aHasBeenLongWait
?
261 DAILY_SHORTENED_IDLE_SERVICE_SEC
:
262 DAILY_SIGNIFICANT_IDLE_SERVICE_SEC
);
263 (void)mIdleService
->AddIdleObserver(this, mIdleDailyTriggerWait
);
268 nsIdleServiceDaily::DailyCallback(nsITimer
* aTimer
, void* aClosure
)
270 PR_LOG(sLog
, PR_LOG_DEBUG
,
271 ("nsIdleServiceDaily: DailyCallback running"));
272 #ifdef MOZ_WIDGET_ANDROID
273 __android_log_print(LOG_LEVEL
, LOG_TAG
,
274 "DailyCallback running");
277 nsIdleServiceDaily
* self
= static_cast<nsIdleServiceDaily
*>(aClosure
);
279 // Check to be sure the timer didn't fire early. This currently only
280 // happens on android.
281 PRTime now
= PR_Now();
282 if (self
->mExpectedTriggerTime
&& now
< self
->mExpectedTriggerTime
) {
283 // Timer returned early, reschedule to the appropriate time.
284 PRTime delayTime
= self
->mExpectedTriggerTime
- now
;
286 // Add 10 ms to ensure we don't undershoot, and never get a "0" timer.
287 delayTime
+= 10 * PR_USEC_PER_MSEC
;
289 PR_LOG(sLog
, PR_LOG_DEBUG
, ("nsIdleServiceDaily: DailyCallback resetting timer to %lld msec",
290 delayTime
/ PR_USEC_PER_MSEC
));
291 #ifdef MOZ_WIDGET_ANDROID
292 __android_log_print(LOG_LEVEL
, LOG_TAG
,
293 "DailyCallback resetting timer to %lld msec",
294 delayTime
/ PR_USEC_PER_MSEC
);
297 (void)self
->mTimer
->InitWithFuncCallback(DailyCallback
,
299 delayTime
/ PR_USEC_PER_MSEC
,
300 nsITimer::TYPE_ONE_SHOT
);
304 // Register for a short term wait for idle event. When this fires we fire
305 // our idle-daily event.
306 self
->StageIdleDaily(false);
311 * The idle services goal is to notify subscribers when a certain time has
312 * passed since the last user interaction with the system.
314 * On some platforms this is defined as the last time user events reached this
315 * application, on other platforms it is a system wide thing - the preferred
316 * implementation is to use the system idle time, rather than the application
317 * idle time, as the things depending on the idle service are likely to use
318 * significant resources (network, disk, memory, cpu, etc.).
320 * When the idle service needs to use the system wide idle timer, it typically
321 * needs to poll the idle time value by the means of a timer. It needs to
322 * poll fast when it is in active idle mode (when it has a listener in the idle
323 * mode) as it needs to detect if the user is active in other applications.
325 * When the service is waiting for the first listener to become idle, or when
326 * it is only monitoring application idle time, it only needs to have the timer
327 * expire at the time the next listener goes idle.
329 * The core state of the service is determined by:
331 * - A list of listeners.
333 * - A boolean that tells if any listeners are in idle mode.
335 * - A delta value that indicates when, measured from the last non-idle time,
336 * the next listener should switch to idle mode.
338 * - An absolute time of the last time idle mode was detected (this is used to
339 * judge if we have been out of idle mode since the last invocation of the
342 * There are four entry points into the system:
344 * - A new listener is registered.
346 * - An existing listener is deregistered.
348 * - User interaction is detected.
350 * - The timer expires.
352 * When a new listener is added its idle timeout, is compared with the next idle
353 * timeout, and if lower, that time is stored as the new timeout, and the timer
354 * is reconfigured to ensure a timeout around the time the new listener should
357 * If the next idle time is above the idle time requested by the new listener
358 * it won't be informed until the timer expires, this is to avoid recursive
359 * behavior and to simplify the code. In this case the timer will be set to
362 * When an existing listener is deregistered, it is just removed from the list
363 * of active listeners, we don't stop the timer, we just let it expire.
365 * When user interaction is detected, either because it was directly detected or
366 * because we polled the system timer and found it to be unexpected low, then we
367 * check the flag that tells us if any listeners are in idle mode, if there are
368 * they are removed from idle mode and told so, and we reset our state
369 * caculating the next timeout and restart the timer if needed.
371 * ---- Build in logic
373 * In order to avoid restarting the timer endlessly, the timer function has
374 * logic that will only restart the timer, if the requested timeout is before
375 * the current timeout.
380 ////////////////////////////////////////////////////////////////////////////////
384 nsIdleService
* gIdleService
;
387 already_AddRefed
<nsIdleService
>
388 nsIdleService::GetInstance()
390 nsRefPtr
<nsIdleService
> instance(gIdleService
);
391 return instance
.forget();
394 nsIdleService::nsIdleService() : mCurrentlySetToTimeoutAt(TimeStamp()),
395 mIdleObserverCount(0),
396 mDeltaToNextIdleSwitchInS(UINT32_MAX
),
397 mLastUserInteraction(TimeStamp::Now())
401 sLog
= PR_NewLogModule("idleService");
403 MOZ_ASSERT(!gIdleService
);
405 if (XRE_GetProcessType() == GeckoProcessType_Default
) {
406 mDailyIdle
= new nsIdleServiceDaily(this);
411 nsIdleService::~nsIdleService()
418 MOZ_ASSERT(gIdleService
== this);
419 gIdleService
= nullptr;
422 NS_IMPL_ISUPPORTS(nsIdleService
, nsIIdleService
, nsIIdleServiceInternal
)
425 nsIdleService::AddIdleObserver(nsIObserver
* aObserver
, uint32_t aIdleTimeInS
)
427 NS_ENSURE_ARG_POINTER(aObserver
);
428 // We don't accept idle time at 0, and we can't handle idle time that are too
429 // high either - no more than ~136 years.
430 NS_ENSURE_ARG_RANGE(aIdleTimeInS
, 1, (UINT32_MAX
/ 10) - 1);
432 if (XRE_GetProcessType() == GeckoProcessType_Content
) {
433 dom::ContentChild
* cpc
= dom::ContentChild::GetSingleton();
434 cpc
->AddIdleObserver(aObserver
, aIdleTimeInS
);
438 PR_LOG(sLog
, PR_LOG_DEBUG
,
439 ("idleService: Register idle observer %p for %d seconds",
440 aObserver
, aIdleTimeInS
));
441 #ifdef MOZ_WIDGET_ANDROID
442 __android_log_print(LOG_LEVEL
, LOG_TAG
,
443 "Register idle observer %p for %d seconds",
444 aObserver
, aIdleTimeInS
);
447 // Put the time + observer in a struct we can keep:
448 IdleListener
listener(aObserver
, aIdleTimeInS
);
450 if (!mArrayListeners
.AppendElement(listener
)) {
451 return NS_ERROR_OUT_OF_MEMORY
;
454 // Create our timer callback if it's not there already.
457 mTimer
= do_CreateInstance(NS_TIMER_CONTRACTID
, &rv
);
458 NS_ENSURE_SUCCESS(rv
, rv
);
461 // Check if the newly added observer has a smaller wait time than what we
462 // are waiting for now.
463 if (mDeltaToNextIdleSwitchInS
> aIdleTimeInS
) {
464 // If it is, then this is the next to move to idle (at this point we
465 // don't care if it should have switched already).
466 PR_LOG(sLog
, PR_LOG_DEBUG
,
467 ("idleService: Register: adjusting next switch from %d to %d seconds",
468 mDeltaToNextIdleSwitchInS
, aIdleTimeInS
));
469 #ifdef MOZ_WIDGET_ANDROID
470 __android_log_print(LOG_LEVEL
, LOG_TAG
,
471 "Register: adjusting next switch from %d to %d seconds",
472 mDeltaToNextIdleSwitchInS
, aIdleTimeInS
);
475 mDeltaToNextIdleSwitchInS
= aIdleTimeInS
;
478 // Ensure timer is running.
485 nsIdleService::RemoveIdleObserver(nsIObserver
* aObserver
, uint32_t aTimeInS
)
488 NS_ENSURE_ARG_POINTER(aObserver
);
489 NS_ENSURE_ARG(aTimeInS
);
491 if (XRE_GetProcessType() == GeckoProcessType_Content
) {
492 dom::ContentChild
* cpc
= dom::ContentChild::GetSingleton();
493 cpc
->RemoveIdleObserver(aObserver
, aTimeInS
);
497 IdleListener
listener(aObserver
, aTimeInS
);
499 // Find the entry and remove it, if it was the last entry, we just let the
500 // existing timer run to completion (there might be a new registration in a
502 IdleListenerComparator c
;
503 nsTArray
<IdleListener
>::index_type listenerIndex
= mArrayListeners
.IndexOf(listener
, 0, c
);
504 if (listenerIndex
!= mArrayListeners
.NoIndex
) {
505 if (mArrayListeners
.ElementAt(listenerIndex
).isIdle
)
506 mIdleObserverCount
--;
507 mArrayListeners
.RemoveElementAt(listenerIndex
);
508 PR_LOG(sLog
, PR_LOG_DEBUG
,
509 ("idleService: Remove observer %p (%d seconds), %d remain idle",
510 aObserver
, aTimeInS
, mIdleObserverCount
));
511 #ifdef MOZ_WIDGET_ANDROID
512 __android_log_print(LOG_LEVEL
, LOG_TAG
,
513 "Remove observer %p (%d seconds), %d remain idle",
514 aObserver
, aTimeInS
, mIdleObserverCount
);
519 // If we get here, we haven't removed anything:
520 PR_LOG(sLog
, PR_LOG_WARNING
,
521 ("idleService: Failed to remove idle observer %p (%d seconds)",
522 aObserver
, aTimeInS
));
523 #ifdef MOZ_WIDGET_ANDROID
524 __android_log_print(LOG_LEVEL
, LOG_TAG
,
525 "Failed to remove idle observer %p (%d seconds)",
526 aObserver
, aTimeInS
);
528 return NS_ERROR_FAILURE
;
532 nsIdleService::ResetIdleTimeOut(uint32_t idleDeltaInMS
)
534 PR_LOG(sLog
, PR_LOG_DEBUG
,
535 ("idleService: Reset idle timeout (last interaction %u msec)",
539 mLastUserInteraction
= TimeStamp::Now() -
540 TimeDuration::FromMilliseconds(idleDeltaInMS
);
542 // If no one is idle, then we are done, any existing timers can keep running.
543 if (mIdleObserverCount
== 0) {
544 PR_LOG(sLog
, PR_LOG_DEBUG
,
545 ("idleService: Reset idle timeout: no idle observers"));
549 // Mark all idle services as non-idle, and calculate the next idle timeout.
550 Telemetry::AutoTimer
<Telemetry::IDLE_NOTIFY_BACK_MS
> timer
;
551 nsCOMArray
<nsIObserver
> notifyList
;
552 mDeltaToNextIdleSwitchInS
= UINT32_MAX
;
554 // Loop through all listeners, and find any that have detected idle.
555 for (uint32_t i
= 0; i
< mArrayListeners
.Length(); i
++) {
556 IdleListener
& curListener
= mArrayListeners
.ElementAt(i
);
558 // If the listener was idle, then he shouldn't be any longer.
559 if (curListener
.isIdle
) {
560 notifyList
.AppendObject(curListener
.observer
);
561 curListener
.isIdle
= false;
564 // Check if the listener is the next one to timeout.
565 mDeltaToNextIdleSwitchInS
= std::min(mDeltaToNextIdleSwitchInS
,
566 curListener
.reqIdleTime
);
569 // When we are done, then we wont have anyone idle.
570 mIdleObserverCount
= 0;
572 // Restart the idle timer, and do so before anyone can delay us.
575 int32_t numberOfPendingNotifications
= notifyList
.Count();
576 Telemetry::Accumulate(Telemetry::IDLE_NOTIFY_BACK_LISTENERS
,
577 numberOfPendingNotifications
);
579 // Bail if nothing to do.
580 if (!numberOfPendingNotifications
) {
584 // Now send "active" events to all, if any should have timed out already,
585 // then they will be reawaken by the timer that is already running.
587 // We need a text string to send with any state change events.
588 nsAutoString timeStr
;
590 timeStr
.AppendInt((int32_t)(idleDeltaInMS
/ PR_MSEC_PER_SEC
));
592 // Send the "non-idle" events.
593 while (numberOfPendingNotifications
--) {
594 PR_LOG(sLog
, PR_LOG_DEBUG
,
595 ("idleService: Reset idle timeout: tell observer %p user is back",
596 notifyList
[numberOfPendingNotifications
]));
597 #ifdef MOZ_WIDGET_ANDROID
598 __android_log_print(LOG_LEVEL
, LOG_TAG
,
599 "Reset idle timeout: tell observer %p user is back",
600 notifyList
[numberOfPendingNotifications
]);
602 notifyList
[numberOfPendingNotifications
]->Observe(this,
603 OBSERVER_TOPIC_ACTIVE
,
610 nsIdleService::GetIdleTime(uint32_t* idleTime
)
612 // Check sanity of in parameter.
614 return NS_ERROR_NULL_POINTER
;
617 // Polled idle time in ms.
618 uint32_t polledIdleTimeMS
;
620 bool polledIdleTimeIsValid
= PollIdleTime(&polledIdleTimeMS
);
622 PR_LOG(sLog
, PR_LOG_DEBUG
,
623 ("idleService: Get idle time: polled %u msec, valid = %d",
624 polledIdleTimeMS
, polledIdleTimeIsValid
));
626 // timeSinceReset is in milliseconds.
627 TimeDuration timeSinceReset
= TimeStamp::Now() - mLastUserInteraction
;
628 uint32_t timeSinceResetInMS
= timeSinceReset
.ToMilliseconds();
630 PR_LOG(sLog
, PR_LOG_DEBUG
,
631 ("idleService: Get idle time: time since reset %u msec",
632 timeSinceResetInMS
));
633 #ifdef MOZ_WIDGET_ANDROID
634 __android_log_print(LOG_LEVEL
, LOG_TAG
,
635 "Get idle time: time since reset %u msec",
639 // If we did't get pulled data, return the time since last idle reset.
640 if (!polledIdleTimeIsValid
) {
641 // We need to convert to ms before returning the time.
642 *idleTime
= timeSinceResetInMS
;
646 // Otherwise return the shortest time detected (in ms).
647 *idleTime
= std::min(timeSinceResetInMS
, polledIdleTimeMS
);
654 nsIdleService::PollIdleTime(uint32_t* /*aIdleTime*/)
656 // Default behavior is not to have the ability to poll an idle time.
661 nsIdleService::UsePollMode()
664 return PollIdleTime(&dummy
);
668 nsIdleService::StaticIdleTimerCallback(nsITimer
* aTimer
, void* aClosure
)
670 static_cast<nsIdleService
*>(aClosure
)->IdleTimerCallback();
674 nsIdleService::IdleTimerCallback(void)
676 // Remember that we no longer have a timer running.
677 mCurrentlySetToTimeoutAt
= TimeStamp();
679 // Find the last detected idle time.
680 uint32_t lastIdleTimeInMS
= static_cast<uint32_t>((TimeStamp::Now() -
681 mLastUserInteraction
).ToMilliseconds());
682 // Get the current idle time.
683 uint32_t currentIdleTimeInMS
;
685 if (NS_FAILED(GetIdleTime(¤tIdleTimeInMS
))) {
686 PR_LOG(sLog
, PR_LOG_ALWAYS
,
687 ("idleService: Idle timer callback: failed to get idle time"));
688 #ifdef MOZ_WIDGET_ANDROID
689 __android_log_print(LOG_LEVEL
, LOG_TAG
,
690 "Idle timer callback: failed to get idle time");
695 PR_LOG(sLog
, PR_LOG_DEBUG
,
696 ("idleService: Idle timer callback: current idle time %u msec",
697 currentIdleTimeInMS
));
698 #ifdef MOZ_WIDGET_ANDROID
699 __android_log_print(LOG_LEVEL
, LOG_TAG
,
700 "Idle timer callback: current idle time %u msec",
701 currentIdleTimeInMS
);
704 // Check if we have had some user interaction we didn't handle previously
705 // we do the calculation in ms to lessen the chance for rounding errors to
706 // trigger wrong results.
707 if (lastIdleTimeInMS
> currentIdleTimeInMS
)
709 // We had user activity, so handle that part first (to ensure the listeners
710 // don't risk getting an non-idle after they get a new idle indication.
711 ResetIdleTimeOut(currentIdleTimeInMS
);
713 // NOTE: We can't bail here, as we might have something already timed out.
716 // Find the idle time in S.
717 uint32_t currentIdleTimeInS
= currentIdleTimeInMS
/ PR_MSEC_PER_SEC
;
719 // Restart timer and bail if no-one are expected to be in idle
720 if (mDeltaToNextIdleSwitchInS
> currentIdleTimeInS
) {
721 // If we didn't expect anyone to be idle, then just re-start the timer.
726 // Tell expired listeners they are expired,and find the next timeout
727 Telemetry::AutoTimer
<Telemetry::IDLE_NOTIFY_IDLE_MS
> timer
;
729 // We need to initialise the time to the next idle switch.
730 mDeltaToNextIdleSwitchInS
= UINT32_MAX
;
732 // Create list of observers that should be notified.
733 nsCOMArray
<nsIObserver
> notifyList
;
735 for (uint32_t i
= 0; i
< mArrayListeners
.Length(); i
++) {
736 IdleListener
& curListener
= mArrayListeners
.ElementAt(i
);
738 // We are only interested in items, that are not in the idle state.
739 if (!curListener
.isIdle
) {
740 // If they have an idle time smaller than the actual idle time.
741 if (curListener
.reqIdleTime
<= currentIdleTimeInS
) {
742 // Then add the listener to the list of listeners that should be
744 notifyList
.AppendObject(curListener
.observer
);
745 // This listener is now idle.
746 curListener
.isIdle
= true;
747 // Remember we have someone idle.
748 mIdleObserverCount
++;
750 // Listeners that are not timed out yet are candidates for timing out.
751 mDeltaToNextIdleSwitchInS
= std::min(mDeltaToNextIdleSwitchInS
,
752 curListener
.reqIdleTime
);
757 // Restart the timer before any notifications that could slow us down are
761 int32_t numberOfPendingNotifications
= notifyList
.Count();
762 Telemetry::Accumulate(Telemetry::IDLE_NOTIFY_IDLE_LISTENERS
,
763 numberOfPendingNotifications
);
765 // Bail if nothing to do.
766 if (!numberOfPendingNotifications
) {
767 PR_LOG(sLog
, PR_LOG_DEBUG
,
768 ("idleService: **** Idle timer callback: no observers to message."));
772 // We need a text string to send with any state change events.
773 nsAutoString timeStr
;
774 timeStr
.AppendInt(currentIdleTimeInS
);
776 // Notify all listeners that just timed out.
777 while (numberOfPendingNotifications
--) {
778 PR_LOG(sLog
, PR_LOG_DEBUG
,
779 ("idleService: **** Idle timer callback: tell observer %p user is idle",
780 notifyList
[numberOfPendingNotifications
]));
781 #ifdef MOZ_WIDGET_ANDROID
782 __android_log_print(LOG_LEVEL
, LOG_TAG
,
783 "Idle timer callback: tell observer %p user is idle",
784 notifyList
[numberOfPendingNotifications
]);
786 notifyList
[numberOfPendingNotifications
]->Observe(this,
793 nsIdleService::SetTimerExpiryIfBefore(TimeStamp aNextTimeout
)
795 #if defined(PR_LOGGING) || defined(MOZ_WIDGET_ANDROID)
796 TimeDuration nextTimeoutDuration
= aNextTimeout
- TimeStamp::Now();
799 PR_LOG(sLog
, PR_LOG_DEBUG
,
800 ("idleService: SetTimerExpiryIfBefore: next timeout %0.f msec from now",
801 nextTimeoutDuration
.ToMilliseconds()));
803 #ifdef MOZ_WIDGET_ANDROID
804 __android_log_print(LOG_LEVEL
, LOG_TAG
,
805 "SetTimerExpiryIfBefore: next timeout %0.f msec from now",
806 nextTimeoutDuration
.ToMilliseconds());
809 // Bail if we don't have a timer service.
814 // If the new timeout is before the old one or we don't have a timer running,
815 // then restart the timer.
816 if (mCurrentlySetToTimeoutAt
.IsNull() ||
817 mCurrentlySetToTimeoutAt
> aNextTimeout
) {
819 mCurrentlySetToTimeoutAt
= aNextTimeout
;
821 // Stop the current timer (it's ok to try'n stop it, even it isn't running).
824 // Check that the timeout is actually in the future, otherwise make it so.
825 TimeStamp currentTime
= TimeStamp::Now();
826 if (currentTime
> mCurrentlySetToTimeoutAt
) {
827 mCurrentlySetToTimeoutAt
= currentTime
;
830 // Add 10 ms to ensure we don't undershoot, and never get a "0" timer.
831 mCurrentlySetToTimeoutAt
+= TimeDuration::FromMilliseconds(10);
833 TimeDuration deltaTime
= mCurrentlySetToTimeoutAt
- currentTime
;
834 PR_LOG(sLog
, PR_LOG_DEBUG
,
835 ("idleService: IdleService reset timer expiry to %0.f msec from now",
836 deltaTime
.ToMilliseconds()));
837 #ifdef MOZ_WIDGET_ANDROID
838 __android_log_print(LOG_LEVEL
, LOG_TAG
,
839 "reset timer expiry to %0.f msec from now",
840 deltaTime
.ToMilliseconds());
844 mTimer
->InitWithFuncCallback(StaticIdleTimerCallback
,
846 deltaTime
.ToMilliseconds(),
847 nsITimer::TYPE_ONE_SHOT
);
853 nsIdleService::ReconfigureTimer(void)
855 // Check if either someone is idle, or someone will become idle.
856 if ((mIdleObserverCount
== 0) && UINT32_MAX
== mDeltaToNextIdleSwitchInS
) {
857 // If not, just let any existing timers run to completion
859 PR_LOG(sLog
, PR_LOG_DEBUG
,
860 ("idleService: ReconfigureTimer: no idle or waiting observers"));
861 #ifdef MOZ_WIDGET_ANDROID
862 __android_log_print(LOG_LEVEL
, LOG_TAG
,
863 "ReconfigureTimer: no idle or waiting observers");
868 // Find the next timeout value, assuming we are not polling.
870 // We need to store the current time, so we don't get artifacts from the time
871 // ticking while we are processing.
872 TimeStamp curTime
= TimeStamp::Now();
874 TimeStamp nextTimeoutAt
= mLastUserInteraction
+
875 TimeDuration::FromSeconds(mDeltaToNextIdleSwitchInS
);
877 #if defined(PR_LOGGING) || defined(MOZ_WIDGET_ANDROID)
878 TimeDuration nextTimeoutDuration
= nextTimeoutAt
- curTime
;
881 PR_LOG(sLog
, PR_LOG_DEBUG
,
882 ("idleService: next timeout %0.f msec from now",
883 nextTimeoutDuration
.ToMilliseconds()));
885 #ifdef MOZ_WIDGET_ANDROID
886 __android_log_print(LOG_LEVEL
, LOG_TAG
,
887 "next timeout %0.f msec from now",
888 nextTimeoutDuration
.ToMilliseconds());
891 // Check if we should correct the timeout time because we should poll before.
892 if ((mIdleObserverCount
> 0) && UsePollMode()) {
893 TimeStamp pollTimeout
=
894 curTime
+ TimeDuration::FromMilliseconds(MIN_IDLE_POLL_INTERVAL_MSEC
);
896 if (nextTimeoutAt
> pollTimeout
) {
897 PR_LOG(sLog
, PR_LOG_DEBUG
,
898 ("idleService: idle observers, reducing timeout to %lu msec from now",
899 MIN_IDLE_POLL_INTERVAL_MSEC
));
900 #ifdef MOZ_WIDGET_ANDROID
901 __android_log_print(LOG_LEVEL
, LOG_TAG
,
902 "idle observers, reducing timeout to %lu msec from now",
903 MIN_IDLE_POLL_INTERVAL_MSEC
);
905 nextTimeoutAt
= pollTimeout
;
909 SetTimerExpiryIfBefore(nextTimeoutAt
);