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 : mCurrentlySetToTimeoutAt(TimeStamp()),
388 mIdleObserverCount(0),
389 mDeltaToNextIdleSwitchInS(UINT32_MAX
),
390 mLastUserInteraction(TimeStamp::Now()) {
391 MOZ_ASSERT(!gIdleService
);
393 if (XRE_IsParentProcess()) {
394 mDailyIdle
= new nsUserIdleServiceDaily(this);
397 nsCOMPtr
<nsIAsyncShutdownService
> svc
= services::GetAsyncShutdownService();
399 nsCOMPtr
<nsIAsyncShutdownClient
> client
;
400 auto rv
= svc
->GetQuitApplicationGranted(getter_AddRefs(client
));
402 // quitApplicationGranted can be undefined in some environments.
403 rv
= svc
->GetXpcomWillShutdown(getter_AddRefs(client
));
405 MOZ_ASSERT(NS_SUCCEEDED(rv
));
406 client
->AddBlocker(new UserIdleBlocker(),
407 NS_LITERAL_STRING_FROM_CSTRING(__FILE__
), __LINE__
,
411 nsUserIdleService::~nsUserIdleService() {
416 MOZ_ASSERT(gIdleService
== this);
417 gIdleService
= nullptr;
420 NS_IMPL_ISUPPORTS(nsUserIdleService
, nsIUserIdleService
,
421 nsIUserIdleServiceInternal
)
423 void nsUserIdleService::SetDisabledForShutdown() {
432 nsUserIdleService::AddIdleObserver(nsIObserver
* aObserver
,
433 uint32_t aIdleTimeInS
) {
434 NS_ENSURE_ARG_POINTER(aObserver
);
435 // We don't accept idle time at 0, and we can't handle idle time that are too
436 // high either - no more than ~136 years.
437 NS_ENSURE_ARG_RANGE(aIdleTimeInS
, 1, (UINT32_MAX
/ 10) - 1);
439 if (profiler_thread_is_being_profiled_for_markers()) {
440 nsAutoCString timeCStr
;
441 timeCStr
.AppendInt(aIdleTimeInS
);
442 PROFILER_MARKER_TEXT("UserIdle::AddObserver", OTHER
, MarkerStack::Capture(),
446 if (XRE_IsContentProcess()) {
447 dom::ContentChild
* cpc
= dom::ContentChild::GetSingleton();
448 cpc
->AddIdleObserver(aObserver
, aIdleTimeInS
);
452 MOZ_LOG(sLog
, LogLevel::Debug
,
453 ("idleService: Register idle observer %p for %d seconds", aObserver
,
455 #ifdef MOZ_WIDGET_ANDROID
456 __android_log_print(LOG_LEVEL
, LOG_TAG
,
457 "Register idle observer %p for %d seconds", aObserver
,
461 // Put the time + observer in a struct we can keep:
462 IdleListener
listener(aObserver
, aIdleTimeInS
);
464 // XXX(Bug 1631371) Check if this should use a fallible operation as it
465 // pretended earlier.
466 mArrayListeners
.AppendElement(listener
);
468 // Create our timer callback if it's not there already.
470 mTimer
= NS_NewTimer();
471 NS_ENSURE_TRUE(mTimer
, NS_ERROR_OUT_OF_MEMORY
);
474 // Check if the newly added observer has a smaller wait time than what we
475 // are waiting for now.
476 if (mDeltaToNextIdleSwitchInS
> aIdleTimeInS
) {
477 // If it is, then this is the next to move to idle (at this point we
478 // don't care if it should have switched already).
480 sLog
, LogLevel::Debug
,
481 ("idleService: Register: adjusting next switch from %d to %d seconds",
482 mDeltaToNextIdleSwitchInS
, aIdleTimeInS
));
483 #ifdef MOZ_WIDGET_ANDROID
484 __android_log_print(LOG_LEVEL
, LOG_TAG
,
485 "Register: adjusting next switch from %d to %d seconds",
486 mDeltaToNextIdleSwitchInS
, aIdleTimeInS
);
489 mDeltaToNextIdleSwitchInS
= aIdleTimeInS
;
497 nsUserIdleService::RemoveIdleObserver(nsIObserver
* aObserver
,
499 NS_ENSURE_ARG_POINTER(aObserver
);
500 NS_ENSURE_ARG(aTimeInS
);
502 if (profiler_thread_is_being_profiled_for_markers()) {
503 nsAutoCString timeCStr
;
504 timeCStr
.AppendInt(aTimeInS
);
505 PROFILER_MARKER_TEXT("UserIdle::RemoveObserver", OTHER
,
506 MarkerStack::Capture(), timeCStr
);
509 if (XRE_IsContentProcess()) {
510 dom::ContentChild
* cpc
= dom::ContentChild::GetSingleton();
511 cpc
->RemoveIdleObserver(aObserver
, aTimeInS
);
515 IdleListener
listener(aObserver
, aTimeInS
);
517 // Find the entry and remove it, if it was the last entry, we just let the
518 // existing timer run to completion (there might be a new registration in a
520 IdleListenerComparator c
;
521 nsTArray
<IdleListener
>::index_type listenerIndex
=
522 mArrayListeners
.IndexOf(listener
, 0, c
);
523 if (listenerIndex
!= mArrayListeners
.NoIndex
) {
524 if (mArrayListeners
.ElementAt(listenerIndex
).isIdle
) mIdleObserverCount
--;
525 mArrayListeners
.RemoveElementAt(listenerIndex
);
526 MOZ_LOG(sLog
, LogLevel::Debug
,
527 ("idleService: Remove observer %p (%d seconds), %d remain idle",
528 aObserver
, aTimeInS
, mIdleObserverCount
));
529 #ifdef MOZ_WIDGET_ANDROID
530 __android_log_print(LOG_LEVEL
, LOG_TAG
,
531 "Remove observer %p (%d seconds), %d remain idle",
532 aObserver
, aTimeInS
, mIdleObserverCount
);
537 // If we get here, we haven't removed anything:
538 MOZ_LOG(sLog
, LogLevel::Warning
,
539 ("idleService: Failed to remove idle observer %p (%d seconds)",
540 aObserver
, aTimeInS
));
541 #ifdef MOZ_WIDGET_ANDROID
542 __android_log_print(LOG_LEVEL
, LOG_TAG
,
543 "Failed to remove idle observer %p (%d seconds)",
544 aObserver
, aTimeInS
);
546 return NS_ERROR_FAILURE
;
550 nsUserIdleService::ResetIdleTimeOut(uint32_t idleDeltaInMS
) {
551 MOZ_LOG(sLog
, LogLevel::Debug
,
552 ("idleService: Reset idle timeout (last interaction %u msec)",
556 mLastUserInteraction
=
557 TimeStamp::Now() - TimeDuration::FromMilliseconds(idleDeltaInMS
);
559 // If no one is idle, then we are done, any existing timers can keep running.
560 if (mIdleObserverCount
== 0) {
561 MOZ_LOG(sLog
, LogLevel::Debug
,
562 ("idleService: Reset idle timeout: no idle observers"));
566 // Mark all idle services as non-idle, and calculate the next idle timeout.
567 nsCOMArray
<nsIObserver
> notifyList
;
568 mDeltaToNextIdleSwitchInS
= UINT32_MAX
;
570 // Loop through all listeners, and find any that have detected idle.
571 for (uint32_t i
= 0; i
< mArrayListeners
.Length(); i
++) {
572 IdleListener
& curListener
= mArrayListeners
.ElementAt(i
);
574 // If the listener was idle, then he shouldn't be any longer.
575 if (curListener
.isIdle
) {
576 notifyList
.AppendObject(curListener
.observer
);
577 curListener
.isIdle
= false;
580 // Check if the listener is the next one to timeout.
581 mDeltaToNextIdleSwitchInS
=
582 std::min(mDeltaToNextIdleSwitchInS
, curListener
.reqIdleTime
);
585 // When we are done, then we wont have anyone idle.
586 mIdleObserverCount
= 0;
588 // Restart the idle timer, and do so before anyone can delay us.
591 int32_t numberOfPendingNotifications
= notifyList
.Count();
593 // Bail if nothing to do.
594 if (!numberOfPendingNotifications
) {
598 // Now send "active" events to all, if any should have timed out already,
599 // then they will be reawaken by the timer that is already running.
601 // We need a text string to send with any state change events.
602 nsAutoString timeStr
;
604 timeStr
.AppendInt((int32_t)(idleDeltaInMS
/ PR_MSEC_PER_SEC
));
606 // Send the "non-idle" events.
607 while (numberOfPendingNotifications
--) {
608 MOZ_LOG(sLog
, LogLevel::Debug
,
609 ("idleService: Reset idle timeout: tell observer %p user is back",
610 notifyList
[numberOfPendingNotifications
]));
611 #ifdef MOZ_WIDGET_ANDROID
612 __android_log_print(LOG_LEVEL
, LOG_TAG
,
613 "Reset idle timeout: tell observer %p user is back",
614 notifyList
[numberOfPendingNotifications
]);
616 notifyList
[numberOfPendingNotifications
]->Observe(
617 this, OBSERVER_TOPIC_ACTIVE
, timeStr
.get());
623 nsUserIdleService::GetIdleTime(uint32_t* idleTime
) {
624 // Check sanity of in parameter.
626 return NS_ERROR_NULL_POINTER
;
629 // Polled idle time in ms.
630 uint32_t polledIdleTimeMS
;
632 bool polledIdleTimeIsValid
= PollIdleTime(&polledIdleTimeMS
);
634 MOZ_LOG(sLog
, LogLevel::Debug
,
635 ("idleService: Get idle time: polled %u msec, valid = %d",
636 polledIdleTimeMS
, polledIdleTimeIsValid
));
638 // timeSinceReset is in milliseconds.
639 TimeDuration timeSinceReset
= TimeStamp::Now() - mLastUserInteraction
;
640 uint32_t timeSinceResetInMS
= timeSinceReset
.ToMilliseconds();
642 MOZ_LOG(sLog
, LogLevel::Debug
,
643 ("idleService: Get idle time: time since reset %u msec",
644 timeSinceResetInMS
));
645 #ifdef MOZ_WIDGET_ANDROID
646 __android_log_print(LOG_LEVEL
, LOG_TAG
,
647 "Get idle time: time since reset %u msec",
651 // If we did't get pulled data, return the time since last idle reset.
652 if (!polledIdleTimeIsValid
) {
653 // We need to convert to ms before returning the time.
654 *idleTime
= timeSinceResetInMS
;
658 // Otherwise return the shortest time detected (in ms).
659 *idleTime
= std::min(timeSinceResetInMS
, polledIdleTimeMS
);
664 bool nsUserIdleService::PollIdleTime(uint32_t* /*aIdleTime*/) {
665 // Default behavior is not to have the ability to poll an idle time.
669 nsresult
nsUserIdleService::GetDisabled(bool* aResult
) {
670 *aResult
= mDisabled
;
674 nsresult
nsUserIdleService::SetDisabled(bool aDisabled
) {
675 mDisabled
= aDisabled
;
679 void nsUserIdleService::StaticIdleTimerCallback(nsITimer
* aTimer
,
681 static_cast<nsUserIdleService
*>(aClosure
)->IdleTimerCallback();
684 void nsUserIdleService::IdleTimerCallback(void) {
685 // Remember that we no longer have a timer running.
686 mCurrentlySetToTimeoutAt
= TimeStamp();
688 // Find the last detected idle time.
689 uint32_t lastIdleTimeInMS
= static_cast<uint32_t>(
690 (TimeStamp::Now() - mLastUserInteraction
).ToMilliseconds());
691 // Get the current idle time.
692 uint32_t currentIdleTimeInMS
;
694 if (NS_FAILED(GetIdleTime(¤tIdleTimeInMS
))) {
695 MOZ_LOG(sLog
, LogLevel::Info
,
696 ("idleService: Idle timer callback: failed to get idle time"));
697 #ifdef MOZ_WIDGET_ANDROID
698 __android_log_print(LOG_LEVEL
, LOG_TAG
,
699 "Idle timer callback: failed to get idle time");
704 MOZ_LOG(sLog
, LogLevel::Debug
,
705 ("idleService: Idle timer callback: current idle time %u msec",
706 currentIdleTimeInMS
));
707 #ifdef MOZ_WIDGET_ANDROID
708 __android_log_print(LOG_LEVEL
, LOG_TAG
,
709 "Idle timer callback: current idle time %u msec",
710 currentIdleTimeInMS
);
713 // Check if we have had some user interaction we didn't handle previously
714 // we do the calculation in ms to lessen the chance for rounding errors to
715 // trigger wrong results.
716 if (lastIdleTimeInMS
> currentIdleTimeInMS
) {
717 // We had user activity, so handle that part first (to ensure the listeners
718 // don't risk getting an non-idle after they get a new idle indication.
719 ResetIdleTimeOut(currentIdleTimeInMS
);
721 // NOTE: We can't bail here, as we might have something already timed out.
724 // Find the idle time in S.
725 uint32_t currentIdleTimeInS
= currentIdleTimeInMS
/ PR_MSEC_PER_SEC
;
727 // Restart timer and bail if no-one are expected to be in idle
728 if (mDeltaToNextIdleSwitchInS
> currentIdleTimeInS
) {
729 // If we didn't expect anyone to be idle, then just re-start the timer.
735 MOZ_LOG(sLog
, LogLevel::Info
,
736 ("idleService: Skipping idle callback while disabled"));
742 // Tell expired listeners they are expired,and find the next timeout
743 Telemetry::AutoTimer
<Telemetry::IDLE_NOTIFY_IDLE_MS
> timer
;
745 // We need to initialise the time to the next idle switch.
746 mDeltaToNextIdleSwitchInS
= UINT32_MAX
;
748 // Create list of observers that should be notified.
749 nsCOMArray
<nsIObserver
> notifyList
;
751 for (uint32_t i
= 0; i
< mArrayListeners
.Length(); i
++) {
752 IdleListener
& curListener
= mArrayListeners
.ElementAt(i
);
754 // We are only interested in items, that are not in the idle state.
755 if (!curListener
.isIdle
) {
756 // If they have an idle time smaller than the actual idle time.
757 if (curListener
.reqIdleTime
<= currentIdleTimeInS
) {
758 // Then add the listener to the list of listeners that should be
760 notifyList
.AppendObject(curListener
.observer
);
761 // This listener is now idle.
762 curListener
.isIdle
= true;
763 // Remember we have someone idle.
764 mIdleObserverCount
++;
766 // Listeners that are not timed out yet are candidates for timing out.
767 mDeltaToNextIdleSwitchInS
=
768 std::min(mDeltaToNextIdleSwitchInS
, curListener
.reqIdleTime
);
773 // Restart the timer before any notifications that could slow us down are
777 int32_t numberOfPendingNotifications
= notifyList
.Count();
779 // Bail if nothing to do.
780 if (!numberOfPendingNotifications
) {
782 sLog
, LogLevel::Debug
,
783 ("idleService: **** Idle timer callback: no observers to message."));
787 // We need a text string to send with any state change events.
788 nsAutoString timeStr
;
789 timeStr
.AppendInt(currentIdleTimeInS
);
791 // Notify all listeners that just timed out.
792 while (numberOfPendingNotifications
--) {
794 sLog
, LogLevel::Debug
,
795 ("idleService: **** Idle timer callback: tell observer %p user is idle",
796 notifyList
[numberOfPendingNotifications
]));
797 #ifdef MOZ_WIDGET_ANDROID
798 __android_log_print(LOG_LEVEL
, LOG_TAG
,
799 "Idle timer callback: tell observer %p user is idle",
800 notifyList
[numberOfPendingNotifications
]);
802 nsAutoCString timeCStr
;
803 timeCStr
.AppendInt(currentIdleTimeInS
);
804 AUTO_PROFILER_MARKER_TEXT("UserIdle::IdleCallback", OTHER
, {}, timeCStr
);
805 notifyList
[numberOfPendingNotifications
]->Observe(this, OBSERVER_TOPIC_IDLE
,
810 void nsUserIdleService::SetTimerExpiryIfBefore(TimeStamp aNextTimeout
) {
811 TimeDuration nextTimeoutDuration
= aNextTimeout
- TimeStamp::Now();
814 sLog
, LogLevel::Debug
,
815 ("idleService: SetTimerExpiryIfBefore: next timeout %0.f msec from now",
816 nextTimeoutDuration
.ToMilliseconds()));
818 #ifdef MOZ_WIDGET_ANDROID
819 __android_log_print(LOG_LEVEL
, LOG_TAG
,
820 "SetTimerExpiryIfBefore: next timeout %0.f msec from now",
821 nextTimeoutDuration
.ToMilliseconds());
824 // Bail if we don't have a timer service.
829 // If the new timeout is before the old one or we don't have a timer running,
830 // then restart the timer.
831 if (mCurrentlySetToTimeoutAt
.IsNull() ||
832 mCurrentlySetToTimeoutAt
> aNextTimeout
) {
833 mCurrentlySetToTimeoutAt
= aNextTimeout
;
835 // Stop the current timer (it's ok to try'n stop it, even it isn't running).
838 // Check that the timeout is actually in the future, otherwise make it so.
839 TimeStamp currentTime
= TimeStamp::Now();
840 if (currentTime
> mCurrentlySetToTimeoutAt
) {
841 mCurrentlySetToTimeoutAt
= currentTime
;
844 // Add 10 ms to ensure we don't undershoot, and never get a "0" timer.
845 mCurrentlySetToTimeoutAt
+= TimeDuration::FromMilliseconds(10);
847 TimeDuration deltaTime
= mCurrentlySetToTimeoutAt
- currentTime
;
849 sLog
, LogLevel::Debug
,
850 ("idleService: IdleService reset timer expiry to %0.f msec from now",
851 deltaTime
.ToMilliseconds()));
852 #ifdef MOZ_WIDGET_ANDROID
853 __android_log_print(LOG_LEVEL
, LOG_TAG
,
854 "reset timer expiry to %0.f msec from now",
855 deltaTime
.ToMilliseconds());
859 mTimer
->InitWithNamedFuncCallback(
860 StaticIdleTimerCallback
, this, deltaTime
.ToMilliseconds(),
861 nsITimer::TYPE_ONE_SHOT
, "nsUserIdleService::SetTimerExpiryIfBefore");
865 void nsUserIdleService::ReconfigureTimer(void) {
866 // Check if either someone is idle, or someone will become idle.
867 if ((mIdleObserverCount
== 0) && UINT32_MAX
== mDeltaToNextIdleSwitchInS
) {
868 // If not, just let any existing timers run to completion
870 MOZ_LOG(sLog
, LogLevel::Debug
,
871 ("idleService: ReconfigureTimer: no idle or waiting observers"));
872 #ifdef MOZ_WIDGET_ANDROID
873 __android_log_print(LOG_LEVEL
, LOG_TAG
,
874 "ReconfigureTimer: no idle or waiting observers");
879 // Find the next timeout value, assuming we are not polling.
881 // We need to store the current time, so we don't get artifacts from the time
882 // ticking while we are processing.
883 TimeStamp curTime
= TimeStamp::Now();
885 TimeStamp nextTimeoutAt
=
886 mLastUserInteraction
+
887 TimeDuration::FromSeconds(mDeltaToNextIdleSwitchInS
);
889 TimeDuration nextTimeoutDuration
= nextTimeoutAt
- curTime
;
891 MOZ_LOG(sLog
, LogLevel::Debug
,
892 ("idleService: next timeout %0.f msec from now",
893 nextTimeoutDuration
.ToMilliseconds()));
895 #ifdef MOZ_WIDGET_ANDROID
896 __android_log_print(LOG_LEVEL
, LOG_TAG
, "next timeout %0.f msec from now",
897 nextTimeoutDuration
.ToMilliseconds());
900 SetTimerExpiryIfBefore(nextTimeoutAt
);