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/. */
9 #include "nsIAsyncShutdown.h"
10 #include "nsUserIdleService.h"
12 #include "nsIObserverService.h"
14 #include "nsCOMArray.h"
15 #include "nsXULAppAPI.h"
17 #include "mozilla/Logging.h"
19 #include "mozilla/AppShutdown.h"
20 #include "mozilla/dom/ContentChild.h"
21 #include "mozilla/Services.h"
22 #include "mozilla/Preferences.h"
23 #include "mozilla/Telemetry.h"
26 #ifdef MOZ_WIDGET_ANDROID
27 # include <android/log.h>
30 using namespace mozilla
;
32 // After the twenty four hour period expires for an idle daily, this is the
33 // amount of idle time we wait for before actually firing the idle-daily
35 #define DAILY_SIGNIFICANT_IDLE_SERVICE_SEC (3 * 60)
37 // In cases where it's been longer than twenty four hours since the last
38 // idle-daily, this is the shortend amount of idle time we wait for before
39 // firing the idle-daily event.
40 #define DAILY_SHORTENED_IDLE_SERVICE_SEC 60
42 // Pref for last time (seconds since epoch) daily notification was sent.
43 #define PREF_LAST_DAILY "idle.lastDailyNotification"
45 // Number of seconds in a day.
46 #define SECONDS_PER_DAY 86400
48 static LazyLogModule
sLog("idleService");
50 #define LOG_TAG "GeckoIdleService"
51 #define LOG_LEVEL ANDROID_LOG_DEBUG
53 // Use this to find previously added observers in our array:
54 class IdleListenerComparator
{
56 bool Equals(IdleListener a
, IdleListener b
) const {
57 return (a
.observer
== b
.observer
) && (a
.reqIdleTime
== b
.reqIdleTime
);
61 ////////////////////////////////////////////////////////////////////////////////
62 //// nsUserIdleServiceDaily
64 NS_IMPL_ISUPPORTS(nsUserIdleServiceDaily
, nsIObserver
, nsISupportsWeakReference
)
67 nsUserIdleServiceDaily::Observe(nsISupports
*, const char* aTopic
,
69 auto shutdownInProgress
=
70 AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownConfirmed
);
71 MOZ_LOG(sLog
, LogLevel::Debug
,
72 ("nsUserIdleServiceDaily: Observe '%s' (%d)", aTopic
,
75 if (shutdownInProgress
|| strcmp(aTopic
, OBSERVER_TOPIC_ACTIVE
) == 0) {
78 MOZ_ASSERT(strcmp(aTopic
, OBSERVER_TOPIC_IDLE
) == 0);
80 MOZ_LOG(sLog
, LogLevel::Debug
,
81 ("nsUserIdleServiceDaily: Notifying idle-daily observers"));
82 #ifdef MOZ_WIDGET_ANDROID
83 __android_log_print(LOG_LEVEL
, LOG_TAG
, "Notifying idle-daily observers");
86 // Send the idle-daily observer event
87 nsCOMPtr
<nsIObserverService
> observerService
=
88 mozilla::services::GetObserverService();
89 NS_ENSURE_STATE(observerService
);
90 (void)observerService
->NotifyObservers(nullptr, OBSERVER_TOPIC_IDLE_DAILY
,
93 // Notify the category observers.
94 nsCOMArray
<nsIObserver
> entries
;
95 mCategoryObservers
.GetEntries(entries
);
96 for (int32_t i
= 0; i
< entries
.Count(); ++i
) {
97 (void)entries
[i
]->Observe(nullptr, OBSERVER_TOPIC_IDLE_DAILY
, nullptr);
100 // Stop observing idle for today.
101 (void)mIdleService
->RemoveIdleObserver(this, mIdleDailyTriggerWait
);
103 // Set the last idle-daily time pref.
104 int32_t nowSec
= static_cast<int32_t>(PR_Now() / PR_USEC_PER_SEC
);
105 Preferences::SetInt(PREF_LAST_DAILY
, nowSec
);
107 // Force that to be stored so we don't retrigger twice a day under
108 // any circumstances.
109 nsIPrefService
* prefs
= Preferences::GetService();
111 prefs
->SavePrefFile(nullptr);
115 sLog
, LogLevel::Debug
,
116 ("nsUserIdleServiceDaily: Storing last idle time as %d sec.", nowSec
));
117 #ifdef MOZ_WIDGET_ANDROID
118 __android_log_print(LOG_LEVEL
, LOG_TAG
, "Storing last idle time as %d",
122 // Note the moment we expect to get the next timer callback
123 mExpectedTriggerTime
=
124 PR_Now() + ((PRTime
)SECONDS_PER_DAY
* (PRTime
)PR_USEC_PER_SEC
);
126 MOZ_LOG(sLog
, LogLevel::Debug
,
127 ("nsUserIdleServiceDaily: Restarting daily timer"));
129 // Start timer for the next check in one day.
130 (void)mTimer
->InitWithNamedFuncCallback(
131 DailyCallback
, this, SECONDS_PER_DAY
* PR_MSEC_PER_SEC
,
132 nsITimer::TYPE_ONE_SHOT
, "nsUserIdleServiceDaily::Observe");
137 nsUserIdleServiceDaily::nsUserIdleServiceDaily(nsIUserIdleService
* aIdleService
)
138 : mIdleService(aIdleService
),
139 mTimer(NS_NewTimer()),
140 mCategoryObservers(OBSERVER_TOPIC_IDLE_DAILY
),
141 mExpectedTriggerTime(0),
142 mIdleDailyTriggerWait(DAILY_SIGNIFICANT_IDLE_SERVICE_SEC
) {}
144 void nsUserIdleServiceDaily::Init() {
145 // First check the time of the last idle-daily event notification. If it
146 // has been 24 hours or higher, or if we have never sent an idle-daily,
147 // get ready to send an idle-daily event. Otherwise set a timer targeted
148 // at 24 hours past the last idle-daily we sent.
150 int32_t lastDaily
= Preferences::GetInt(PREF_LAST_DAILY
, 0);
151 // Setting the pref to -1 allows to disable idle-daily, and it's particularly
152 // useful in tests. Normally there should be no need for the user to set
154 if (lastDaily
== -1) {
155 MOZ_LOG(sLog
, LogLevel::Debug
,
156 ("nsUserIdleServiceDaily: Init: disabled idle-daily"));
160 int32_t nowSec
= static_cast<int32_t>(PR_Now() / PR_USEC_PER_SEC
);
161 if (lastDaily
< 0 || lastDaily
> nowSec
) {
162 // The time is bogus, use default.
165 int32_t secondsSinceLastDaily
= nowSec
- lastDaily
;
167 MOZ_LOG(sLog
, LogLevel::Debug
,
168 ("nsUserIdleServiceDaily: Init: seconds since last daily: %d",
169 secondsSinceLastDaily
));
171 // If it has been twenty four hours or more or if we have never sent an
172 // idle-daily event get ready to send it during the next idle period.
173 if (secondsSinceLastDaily
> SECONDS_PER_DAY
) {
174 // Check for a "long wait", e.g. 48-hours or more.
175 bool hasBeenLongWait
=
176 (lastDaily
&& (secondsSinceLastDaily
> (SECONDS_PER_DAY
* 2)));
179 sLog
, LogLevel::Debug
,
180 ("nsUserIdleServiceDaily: has been long wait? %d", hasBeenLongWait
));
182 // StageIdleDaily sets up a wait for the user to become idle and then
183 // sends the idle-daily event.
184 StageIdleDaily(hasBeenLongWait
);
186 MOZ_LOG(sLog
, LogLevel::Debug
,
187 ("nsUserIdleServiceDaily: Setting timer a day from now"));
188 #ifdef MOZ_WIDGET_ANDROID
189 __android_log_print(LOG_LEVEL
, LOG_TAG
, "Setting timer a day from now");
192 // According to our last idle-daily pref, the last idle-daily was fired
193 // less then 24 hours ago. Set a wait for the amount of time remaining.
194 int32_t milliSecLeftUntilDaily
=
195 (SECONDS_PER_DAY
- secondsSinceLastDaily
) * PR_MSEC_PER_SEC
;
197 MOZ_LOG(sLog
, LogLevel::Debug
,
198 ("nsUserIdleServiceDaily: Seconds till next timeout: %d",
199 (SECONDS_PER_DAY
- secondsSinceLastDaily
)));
201 // Mark the time at which we expect this to fire. On systems with faulty
202 // timers, we need to be able to cross check that the timer fired at the
204 mExpectedTriggerTime
=
205 PR_Now() + (milliSecLeftUntilDaily
* PR_USEC_PER_MSEC
);
207 (void)mTimer
->InitWithNamedFuncCallback(
208 DailyCallback
, this, milliSecLeftUntilDaily
, nsITimer::TYPE_ONE_SHOT
,
209 "nsUserIdleServiceDaily::Init");
213 nsUserIdleServiceDaily::~nsUserIdleServiceDaily() {
220 void nsUserIdleServiceDaily::StageIdleDaily(bool aHasBeenLongWait
) {
221 NS_ASSERTION(mIdleService
, "No idle service available?");
222 MOZ_LOG(sLog
, LogLevel::Debug
,
223 ("nsUserIdleServiceDaily: Registering Idle observer callback "
224 "(short wait requested? %d)",
226 #ifdef MOZ_WIDGET_ANDROID
227 __android_log_print(LOG_LEVEL
, LOG_TAG
, "Registering Idle observer callback");
229 mIdleDailyTriggerWait
=
230 (aHasBeenLongWait
? DAILY_SHORTENED_IDLE_SERVICE_SEC
231 : DAILY_SIGNIFICANT_IDLE_SERVICE_SEC
);
232 (void)mIdleService
->AddIdleObserver(this, mIdleDailyTriggerWait
);
236 void nsUserIdleServiceDaily::DailyCallback(nsITimer
* aTimer
, void* aClosure
) {
237 MOZ_LOG(sLog
, LogLevel::Debug
,
238 ("nsUserIdleServiceDaily: DailyCallback running"));
239 #ifdef MOZ_WIDGET_ANDROID
240 __android_log_print(LOG_LEVEL
, LOG_TAG
, "DailyCallback running");
243 nsUserIdleServiceDaily
* self
= static_cast<nsUserIdleServiceDaily
*>(aClosure
);
245 // Check to be sure the timer didn't fire early. This currently only
246 // happens on android.
247 PRTime now
= PR_Now();
248 if (self
->mExpectedTriggerTime
&& now
< self
->mExpectedTriggerTime
) {
249 // Timer returned early, reschedule to the appropriate time.
250 PRTime delayTime
= self
->mExpectedTriggerTime
- now
;
252 // Add 10 ms to ensure we don't undershoot, and never get a "0" timer.
253 delayTime
+= 10 * PR_USEC_PER_MSEC
;
255 MOZ_LOG(sLog
, LogLevel::Debug
,
256 ("nsUserIdleServiceDaily: DailyCallback resetting timer to %" PRId64
258 delayTime
/ PR_USEC_PER_MSEC
));
259 #ifdef MOZ_WIDGET_ANDROID
260 __android_log_print(LOG_LEVEL
, LOG_TAG
,
261 "DailyCallback resetting timer to %" PRId64
" msec",
262 delayTime
/ PR_USEC_PER_MSEC
);
265 (void)self
->mTimer
->InitWithNamedFuncCallback(
266 DailyCallback
, self
, delayTime
/ PR_USEC_PER_MSEC
,
267 nsITimer::TYPE_ONE_SHOT
, "nsUserIdleServiceDaily::DailyCallback");
271 // Register for a short term wait for idle event. When this fires we fire
272 // our idle-daily event.
273 self
->StageIdleDaily(false);
277 * The idle services goal is to notify subscribers when a certain time has
278 * passed since the last user interaction with the system.
280 * On some platforms this is defined as the last time user events reached this
281 * application, on other platforms it is a system wide thing - the preferred
282 * implementation is to use the system idle time, rather than the application
283 * idle time, as the things depending on the idle service are likely to use
284 * significant resources (network, disk, memory, cpu, etc.).
286 * When the idle service needs to use the system wide idle timer, it typically
287 * needs to poll the idle time value by the means of a timer. It needs to
288 * poll fast when it is in active idle mode (when it has a listener in the idle
289 * mode) as it needs to detect if the user is active in other applications.
291 * When the service is waiting for the first listener to become idle, or when
292 * it is only monitoring application idle time, it only needs to have the timer
293 * expire at the time the next listener goes idle.
295 * The core state of the service is determined by:
297 * - A list of listeners.
299 * - A boolean that tells if any listeners are in idle mode.
301 * - A delta value that indicates when, measured from the last non-idle time,
302 * the next listener should switch to idle mode.
304 * - An absolute time of the last time idle mode was detected (this is used to
305 * judge if we have been out of idle mode since the last invocation of the
308 * There are four entry points into the system:
310 * - A new listener is registered.
312 * - An existing listener is deregistered.
314 * - User interaction is detected.
316 * - The timer expires.
318 * When a new listener is added its idle timeout, is compared with the next idle
319 * timeout, and if lower, that time is stored as the new timeout, and the timer
320 * is reconfigured to ensure a timeout around the time the new listener should
323 * If the next idle time is above the idle time requested by the new listener
324 * it won't be informed until the timer expires, this is to avoid recursive
325 * behavior and to simplify the code. In this case the timer will be set to
328 * When an existing listener is deregistered, it is just removed from the list
329 * of active listeners, we don't stop the timer, we just let it expire.
331 * When user interaction is detected, either because it was directly detected or
332 * because we polled the system timer and found it to be unexpected low, then we
333 * check the flag that tells us if any listeners are in idle mode, if there are
334 * they are removed from idle mode and told so, and we reset our state
335 * caculating the next timeout and restart the timer if needed.
337 * ---- Build in logic
339 * In order to avoid restarting the timer endlessly, the timer function has
340 * logic that will only restart the timer, if the requested timeout is before
341 * the current timeout.
345 ////////////////////////////////////////////////////////////////////////////////
346 //// nsUserIdleService
349 nsUserIdleService
* gIdleService
;
352 already_AddRefed
<nsUserIdleService
> nsUserIdleService::GetInstance() {
353 RefPtr
<nsUserIdleService
> instance(gIdleService
);
354 return instance
.forget();
357 class UserIdleBlocker final
: public nsIAsyncShutdownBlocker
{
358 ~UserIdleBlocker() = default;
361 explicit UserIdleBlocker() = default;
364 GetName(nsAString
& aNameOut
) override
{
365 aNameOut
= nsLiteralString(u
"UserIdleBlocker");
370 BlockShutdown(nsIAsyncShutdownClient
* aClient
) override
{
372 gIdleService
->SetDisabledForShutdown();
374 aClient
->RemoveBlocker(this);
379 GetState(nsIPropertyBag
**) override
{ return NS_OK
; }
384 NS_IMPL_ISUPPORTS(UserIdleBlocker
, nsIAsyncShutdownBlocker
)
386 nsUserIdleService::nsUserIdleService()
387 : mIdleObserverCount(0),
388 mDeltaToNextIdleSwitchInS(UINT32_MAX
),
389 mLastUserInteraction(TimeStamp::Now()) {
390 MOZ_ASSERT(!gIdleService
);
392 if (XRE_IsParentProcess()) {
393 mDailyIdle
= new nsUserIdleServiceDaily(this);
396 nsCOMPtr
<nsIAsyncShutdownService
> svc
= services::GetAsyncShutdownService();
398 nsCOMPtr
<nsIAsyncShutdownClient
> client
;
399 auto rv
= svc
->GetQuitApplicationGranted(getter_AddRefs(client
));
401 // quitApplicationGranted can be undefined in some environments.
402 rv
= svc
->GetXpcomWillShutdown(getter_AddRefs(client
));
404 MOZ_ASSERT(NS_SUCCEEDED(rv
));
405 client
->AddBlocker(new UserIdleBlocker(),
406 NS_LITERAL_STRING_FROM_CSTRING(__FILE__
), __LINE__
,
410 nsUserIdleService::~nsUserIdleService() {
415 MOZ_ASSERT(gIdleService
== this);
416 gIdleService
= nullptr;
419 NS_IMPL_ISUPPORTS(nsUserIdleService
, nsIUserIdleService
,
420 nsIUserIdleServiceInternal
)
422 void nsUserIdleService::SetDisabledForShutdown() {
431 nsUserIdleService::AddIdleObserver(nsIObserver
* aObserver
,
432 uint32_t aIdleTimeInS
) {
433 NS_ENSURE_ARG_POINTER(aObserver
);
434 // We don't accept idle time at 0, and we can't handle idle time that are too
435 // high either - no more than ~136 years.
436 NS_ENSURE_ARG_RANGE(aIdleTimeInS
, 1, (UINT32_MAX
/ 10) - 1);
438 if (profiler_thread_is_being_profiled_for_markers()) {
439 nsAutoCString timeCStr
;
440 timeCStr
.AppendInt(aIdleTimeInS
);
441 PROFILER_MARKER_TEXT("UserIdle::AddObserver", OTHER
, MarkerStack::Capture(),
445 if (XRE_IsContentProcess()) {
446 dom::ContentChild
* cpc
= dom::ContentChild::GetSingleton();
447 cpc
->AddIdleObserver(aObserver
, aIdleTimeInS
);
451 MOZ_LOG(sLog
, LogLevel::Debug
,
452 ("idleService: Register idle observer %p for %d seconds", aObserver
,
454 #ifdef MOZ_WIDGET_ANDROID
455 __android_log_print(LOG_LEVEL
, LOG_TAG
,
456 "Register idle observer %p for %d seconds", aObserver
,
460 // Put the time + observer in a struct we can keep:
461 IdleListener
listener(aObserver
, aIdleTimeInS
);
463 // XXX(Bug 1631371) Check if this should use a fallible operation as it
464 // pretended earlier.
465 mArrayListeners
.AppendElement(listener
);
467 // Create our timer callback if it's not there already.
469 mTimer
= NS_NewTimer();
470 NS_ENSURE_TRUE(mTimer
, NS_ERROR_OUT_OF_MEMORY
);
473 // Check if the newly added observer has a smaller wait time than what we
474 // are waiting for now.
475 if (mDeltaToNextIdleSwitchInS
> aIdleTimeInS
) {
476 // If it is, then this is the next to move to idle (at this point we
477 // don't care if it should have switched already).
479 sLog
, LogLevel::Debug
,
480 ("idleService: Register: adjusting next switch from %d to %d seconds",
481 mDeltaToNextIdleSwitchInS
, aIdleTimeInS
));
482 #ifdef MOZ_WIDGET_ANDROID
483 __android_log_print(LOG_LEVEL
, LOG_TAG
,
484 "Register: adjusting next switch from %d to %d seconds",
485 mDeltaToNextIdleSwitchInS
, aIdleTimeInS
);
488 mDeltaToNextIdleSwitchInS
= aIdleTimeInS
;
496 nsUserIdleService::RemoveIdleObserver(nsIObserver
* aObserver
,
498 NS_ENSURE_ARG_POINTER(aObserver
);
499 NS_ENSURE_ARG(aTimeInS
);
501 if (profiler_thread_is_being_profiled_for_markers()) {
502 nsAutoCString timeCStr
;
503 timeCStr
.AppendInt(aTimeInS
);
504 PROFILER_MARKER_TEXT("UserIdle::RemoveObserver", OTHER
,
505 MarkerStack::Capture(), timeCStr
);
508 if (XRE_IsContentProcess()) {
509 dom::ContentChild
* cpc
= dom::ContentChild::GetSingleton();
510 cpc
->RemoveIdleObserver(aObserver
, aTimeInS
);
514 IdleListener
listener(aObserver
, aTimeInS
);
516 // Find the entry and remove it, if it was the last entry, we just let the
517 // existing timer run to completion (there might be a new registration in a
519 IdleListenerComparator c
;
520 nsTArray
<IdleListener
>::index_type listenerIndex
=
521 mArrayListeners
.IndexOf(listener
, 0, c
);
522 if (listenerIndex
!= mArrayListeners
.NoIndex
) {
523 if (mArrayListeners
.ElementAt(listenerIndex
).isIdle
) mIdleObserverCount
--;
524 mArrayListeners
.RemoveElementAt(listenerIndex
);
525 MOZ_LOG(sLog
, LogLevel::Debug
,
526 ("idleService: Remove observer %p (%d seconds), %d remain idle",
527 aObserver
, aTimeInS
, mIdleObserverCount
));
528 #ifdef MOZ_WIDGET_ANDROID
529 __android_log_print(LOG_LEVEL
, LOG_TAG
,
530 "Remove observer %p (%d seconds), %d remain idle",
531 aObserver
, aTimeInS
, mIdleObserverCount
);
536 // If we get here, we haven't removed anything:
537 MOZ_LOG(sLog
, LogLevel::Warning
,
538 ("idleService: Failed to remove idle observer %p (%d seconds)",
539 aObserver
, aTimeInS
));
540 #ifdef MOZ_WIDGET_ANDROID
541 __android_log_print(LOG_LEVEL
, LOG_TAG
,
542 "Failed to remove idle observer %p (%d seconds)",
543 aObserver
, aTimeInS
);
545 return NS_ERROR_FAILURE
;
549 nsUserIdleService::ResetIdleTimeOut(uint32_t idleDeltaInMS
) {
550 MOZ_LOG(sLog
, LogLevel::Debug
,
551 ("idleService: Reset idle timeout (last interaction %u msec)",
555 mLastUserInteraction
=
556 TimeStamp::Now() - TimeDuration::FromMilliseconds(idleDeltaInMS
);
558 // If no one is idle, then we are done, any existing timers can keep running.
559 if (mIdleObserverCount
== 0) {
560 MOZ_LOG(sLog
, LogLevel::Debug
,
561 ("idleService: Reset idle timeout: no idle observers"));
565 // Mark all idle services as non-idle, and calculate the next idle timeout.
566 nsCOMArray
<nsIObserver
> notifyList
;
567 mDeltaToNextIdleSwitchInS
= UINT32_MAX
;
569 // Loop through all listeners, and find any that have detected idle.
570 for (uint32_t i
= 0; i
< mArrayListeners
.Length(); i
++) {
571 IdleListener
& curListener
= mArrayListeners
.ElementAt(i
);
573 // If the listener was idle, then he shouldn't be any longer.
574 if (curListener
.isIdle
) {
575 notifyList
.AppendObject(curListener
.observer
);
576 curListener
.isIdle
= false;
579 // Check if the listener is the next one to timeout.
580 mDeltaToNextIdleSwitchInS
=
581 std::min(mDeltaToNextIdleSwitchInS
, curListener
.reqIdleTime
);
584 // When we are done, then we wont have anyone idle.
585 mIdleObserverCount
= 0;
587 // Restart the idle timer, and do so before anyone can delay us.
590 int32_t numberOfPendingNotifications
= notifyList
.Count();
592 // Bail if nothing to do.
593 if (!numberOfPendingNotifications
) {
597 // Now send "active" events to all, if any should have timed out already,
598 // then they will be reawaken by the timer that is already running.
600 // We need a text string to send with any state change events.
601 nsAutoString timeStr
;
603 timeStr
.AppendInt((int32_t)(idleDeltaInMS
/ PR_MSEC_PER_SEC
));
605 // Send the "non-idle" events.
606 while (numberOfPendingNotifications
--) {
607 MOZ_LOG(sLog
, LogLevel::Debug
,
608 ("idleService: Reset idle timeout: tell observer %p user is back",
609 notifyList
[numberOfPendingNotifications
]));
610 #ifdef MOZ_WIDGET_ANDROID
611 __android_log_print(LOG_LEVEL
, LOG_TAG
,
612 "Reset idle timeout: tell observer %p user is back",
613 notifyList
[numberOfPendingNotifications
]);
615 notifyList
[numberOfPendingNotifications
]->Observe(
616 this, OBSERVER_TOPIC_ACTIVE
, timeStr
.get());
622 nsUserIdleService::GetIdleTime(uint32_t* idleTime
) {
623 // Check sanity of in parameter.
625 return NS_ERROR_NULL_POINTER
;
628 // Polled idle time in ms.
629 uint32_t polledIdleTimeMS
;
631 bool polledIdleTimeIsValid
= PollIdleTime(&polledIdleTimeMS
);
633 MOZ_LOG(sLog
, LogLevel::Debug
,
634 ("idleService: Get idle time: polled %u msec, valid = %d",
635 polledIdleTimeMS
, polledIdleTimeIsValid
));
637 // timeSinceReset is in milliseconds.
638 TimeDuration timeSinceReset
= TimeStamp::Now() - mLastUserInteraction
;
639 uint32_t timeSinceResetInMS
= timeSinceReset
.ToMilliseconds();
641 MOZ_LOG(sLog
, LogLevel::Debug
,
642 ("idleService: Get idle time: time since reset %u msec",
643 timeSinceResetInMS
));
644 #ifdef MOZ_WIDGET_ANDROID
645 __android_log_print(LOG_LEVEL
, LOG_TAG
,
646 "Get idle time: time since reset %u msec",
650 // If we did't get pulled data, return the time since last idle reset.
651 if (!polledIdleTimeIsValid
) {
652 // We need to convert to ms before returning the time.
653 *idleTime
= timeSinceResetInMS
;
657 // Otherwise return the shortest time detected (in ms).
658 *idleTime
= std::min(timeSinceResetInMS
, polledIdleTimeMS
);
663 bool nsUserIdleService::PollIdleTime(uint32_t* /*aIdleTime*/) {
664 // Default behavior is not to have the ability to poll an idle time.
668 nsresult
nsUserIdleService::GetDisabled(bool* aResult
) {
669 *aResult
= mDisabled
;
673 nsresult
nsUserIdleService::SetDisabled(bool aDisabled
) {
674 mDisabled
= aDisabled
;
678 void nsUserIdleService::StaticIdleTimerCallback(nsITimer
* aTimer
,
680 static_cast<nsUserIdleService
*>(aClosure
)->IdleTimerCallback();
683 void nsUserIdleService::IdleTimerCallback(void) {
684 // Remember that we no longer have a timer running.
685 mCurrentlySetToTimeoutAt
= TimeStamp();
687 // Find the last detected idle time.
688 uint32_t lastIdleTimeInMS
= static_cast<uint32_t>(
689 (TimeStamp::Now() - mLastUserInteraction
).ToMilliseconds());
690 // Get the current idle time.
691 uint32_t currentIdleTimeInMS
;
693 if (NS_FAILED(GetIdleTime(¤tIdleTimeInMS
))) {
694 MOZ_LOG(sLog
, LogLevel::Info
,
695 ("idleService: Idle timer callback: failed to get idle time"));
696 #ifdef MOZ_WIDGET_ANDROID
697 __android_log_print(LOG_LEVEL
, LOG_TAG
,
698 "Idle timer callback: failed to get idle time");
703 MOZ_LOG(sLog
, LogLevel::Debug
,
704 ("idleService: Idle timer callback: current idle time %u msec",
705 currentIdleTimeInMS
));
706 #ifdef MOZ_WIDGET_ANDROID
707 __android_log_print(LOG_LEVEL
, LOG_TAG
,
708 "Idle timer callback: current idle time %u msec",
709 currentIdleTimeInMS
);
712 // Check if we have had some user interaction we didn't handle previously
713 // we do the calculation in ms to lessen the chance for rounding errors to
714 // trigger wrong results.
715 if (lastIdleTimeInMS
> currentIdleTimeInMS
) {
716 // We had user activity, so handle that part first (to ensure the listeners
717 // don't risk getting an non-idle after they get a new idle indication.
718 ResetIdleTimeOut(currentIdleTimeInMS
);
720 // NOTE: We can't bail here, as we might have something already timed out.
723 // Find the idle time in S.
724 uint32_t currentIdleTimeInS
= currentIdleTimeInMS
/ PR_MSEC_PER_SEC
;
726 // Restart timer and bail if no-one are expected to be in idle
727 if (mDeltaToNextIdleSwitchInS
> currentIdleTimeInS
) {
728 // If we didn't expect anyone to be idle, then just re-start the timer.
734 MOZ_LOG(sLog
, LogLevel::Info
,
735 ("idleService: Skipping idle callback while disabled"));
741 // Tell expired listeners they are expired,and find the next timeout
742 Telemetry::AutoTimer
<Telemetry::IDLE_NOTIFY_IDLE_MS
> timer
;
744 // We need to initialise the time to the next idle switch.
745 mDeltaToNextIdleSwitchInS
= UINT32_MAX
;
747 // Create list of observers that should be notified.
748 nsCOMArray
<nsIObserver
> notifyList
;
750 for (uint32_t i
= 0; i
< mArrayListeners
.Length(); i
++) {
751 IdleListener
& curListener
= mArrayListeners
.ElementAt(i
);
753 // We are only interested in items, that are not in the idle state.
754 if (!curListener
.isIdle
) {
755 // If they have an idle time smaller than the actual idle time.
756 if (curListener
.reqIdleTime
<= currentIdleTimeInS
) {
757 // Then add the listener to the list of listeners that should be
759 notifyList
.AppendObject(curListener
.observer
);
760 // This listener is now idle.
761 curListener
.isIdle
= true;
762 // Remember we have someone idle.
763 mIdleObserverCount
++;
765 // Listeners that are not timed out yet are candidates for timing out.
766 mDeltaToNextIdleSwitchInS
=
767 std::min(mDeltaToNextIdleSwitchInS
, curListener
.reqIdleTime
);
772 // Restart the timer before any notifications that could slow us down are
776 int32_t numberOfPendingNotifications
= notifyList
.Count();
778 // Bail if nothing to do.
779 if (!numberOfPendingNotifications
) {
781 sLog
, LogLevel::Debug
,
782 ("idleService: **** Idle timer callback: no observers to message."));
786 // We need a text string to send with any state change events.
787 nsAutoString timeStr
;
788 timeStr
.AppendInt(currentIdleTimeInS
);
790 // Notify all listeners that just timed out.
791 while (numberOfPendingNotifications
--) {
793 sLog
, LogLevel::Debug
,
794 ("idleService: **** Idle timer callback: tell observer %p user is idle",
795 notifyList
[numberOfPendingNotifications
]));
796 #ifdef MOZ_WIDGET_ANDROID
797 __android_log_print(LOG_LEVEL
, LOG_TAG
,
798 "Idle timer callback: tell observer %p user is idle",
799 notifyList
[numberOfPendingNotifications
]);
801 nsAutoCString timeCStr
;
802 timeCStr
.AppendInt(currentIdleTimeInS
);
803 AUTO_PROFILER_MARKER_TEXT("UserIdle::IdleCallback", OTHER
, {}, timeCStr
);
804 notifyList
[numberOfPendingNotifications
]->Observe(this, OBSERVER_TOPIC_IDLE
,
809 void nsUserIdleService::SetTimerExpiryIfBefore(TimeStamp aNextTimeout
) {
810 TimeDuration nextTimeoutDuration
= aNextTimeout
- TimeStamp::Now();
813 sLog
, LogLevel::Debug
,
814 ("idleService: SetTimerExpiryIfBefore: next timeout %0.f msec from now",
815 nextTimeoutDuration
.ToMilliseconds()));
817 #ifdef MOZ_WIDGET_ANDROID
818 __android_log_print(LOG_LEVEL
, LOG_TAG
,
819 "SetTimerExpiryIfBefore: next timeout %0.f msec from now",
820 nextTimeoutDuration
.ToMilliseconds());
823 // Bail if we don't have a timer service.
828 // If the new timeout is before the old one or we don't have a timer running,
829 // then restart the timer.
830 if (mCurrentlySetToTimeoutAt
.IsNull() ||
831 mCurrentlySetToTimeoutAt
> aNextTimeout
) {
832 mCurrentlySetToTimeoutAt
= aNextTimeout
;
834 // Stop the current timer (it's ok to try'n stop it, even it isn't running).
837 // Check that the timeout is actually in the future, otherwise make it so.
838 TimeStamp currentTime
= TimeStamp::Now();
839 if (currentTime
> mCurrentlySetToTimeoutAt
) {
840 mCurrentlySetToTimeoutAt
= currentTime
;
843 // Add 10 ms to ensure we don't undershoot, and never get a "0" timer.
844 mCurrentlySetToTimeoutAt
+= TimeDuration::FromMilliseconds(10);
846 TimeDuration deltaTime
= mCurrentlySetToTimeoutAt
- currentTime
;
848 sLog
, LogLevel::Debug
,
849 ("idleService: IdleService reset timer expiry to %0.f msec from now",
850 deltaTime
.ToMilliseconds()));
851 #ifdef MOZ_WIDGET_ANDROID
852 __android_log_print(LOG_LEVEL
, LOG_TAG
,
853 "reset timer expiry to %0.f msec from now",
854 deltaTime
.ToMilliseconds());
858 mTimer
->InitWithNamedFuncCallback(
859 StaticIdleTimerCallback
, this, deltaTime
.ToMilliseconds(),
860 nsITimer::TYPE_ONE_SHOT
, "nsUserIdleService::SetTimerExpiryIfBefore");
864 void nsUserIdleService::ReconfigureTimer(void) {
865 // Check if either someone is idle, or someone will become idle.
866 if ((mIdleObserverCount
== 0) && UINT32_MAX
== mDeltaToNextIdleSwitchInS
) {
867 // If not, just let any existing timers run to completion
869 MOZ_LOG(sLog
, LogLevel::Debug
,
870 ("idleService: ReconfigureTimer: no idle or waiting observers"));
871 #ifdef MOZ_WIDGET_ANDROID
872 __android_log_print(LOG_LEVEL
, LOG_TAG
,
873 "ReconfigureTimer: no idle or waiting observers");
878 // Find the next timeout value, assuming we are not polling.
880 // We need to store the current time, so we don't get artifacts from the time
881 // ticking while we are processing.
882 TimeStamp curTime
= TimeStamp::Now();
884 TimeStamp nextTimeoutAt
=
885 mLastUserInteraction
+
886 TimeDuration::FromSeconds(mDeltaToNextIdleSwitchInS
);
888 TimeDuration nextTimeoutDuration
= nextTimeoutAt
- curTime
;
890 MOZ_LOG(sLog
, LogLevel::Debug
,
891 ("idleService: next timeout %0.f msec from now",
892 nextTimeoutDuration
.ToMilliseconds()));
894 #ifdef MOZ_WIDGET_ANDROID
895 __android_log_print(LOG_LEVEL
, LOG_TAG
, "next timeout %0.f msec from now",
896 nextTimeoutDuration
.ToMilliseconds());
899 SetTimerExpiryIfBefore(nextTimeoutAt
);