Bug 1631735 Part 1: Make nsCocoaWindow animated transitions asynchronous and atomic...
[gecko.git] / widget / nsUserIdleService.cpp
blob7b54a4749d4d6e6561707f70732576398ebc7b70
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:expandtab:shiftwidth=2:tabstop=2:
3 */
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 "nsUserIdleService.h"
9 #include "nsString.h"
10 #include "nsIObserverService.h"
11 #include "nsDebug.h"
12 #include "nsCOMArray.h"
13 #include "nsXULAppAPI.h"
14 #include "prinrval.h"
15 #include "mozilla/Logging.h"
16 #include "prtime.h"
17 #include "mozilla/dom/ContentChild.h"
18 #include "mozilla/Services.h"
19 #include "mozilla/Preferences.h"
20 #include "mozilla/Telemetry.h"
21 #include <algorithm>
23 #ifdef MOZ_WIDGET_ANDROID
24 # include <android/log.h>
25 #endif
27 using namespace mozilla;
29 // After the twenty four hour period expires for an idle daily, this is the
30 // amount of idle time we wait for before actually firing the idle-daily
31 // event.
32 #define DAILY_SIGNIFICANT_IDLE_SERVICE_SEC (3 * 60)
34 // In cases where it's been longer than twenty four hours since the last
35 // idle-daily, this is the shortend amount of idle time we wait for before
36 // firing the idle-daily event.
37 #define DAILY_SHORTENED_IDLE_SERVICE_SEC 60
39 // Pref for last time (seconds since epoch) daily notification was sent.
40 #define PREF_LAST_DAILY "idle.lastDailyNotification"
42 // Number of seconds in a day.
43 #define SECONDS_PER_DAY 86400
45 static LazyLogModule sLog("idleService");
47 #define LOG_TAG "GeckoIdleService"
48 #define LOG_LEVEL ANDROID_LOG_DEBUG
50 // Use this to find previously added observers in our array:
51 class IdleListenerComparator {
52 public:
53 bool Equals(IdleListener a, IdleListener b) const {
54 return (a.observer == b.observer) && (a.reqIdleTime == b.reqIdleTime);
58 ////////////////////////////////////////////////////////////////////////////////
59 //// nsUserIdleServiceDaily
61 NS_IMPL_ISUPPORTS(nsUserIdleServiceDaily, nsIObserver, nsISupportsWeakReference)
63 NS_IMETHODIMP
64 nsUserIdleServiceDaily::Observe(nsISupports*, const char* aTopic,
65 const char16_t*) {
66 MOZ_LOG(sLog, LogLevel::Debug,
67 ("nsUserIdleServiceDaily: Observe '%s' (%d)", aTopic,
68 mShutdownInProgress));
70 if (strcmp(aTopic, "profile-after-change") == 0) {
71 // We are back. Start sending notifications again.
72 mShutdownInProgress = false;
73 return NS_OK;
76 if (strcmp(aTopic, "xpcom-will-shutdown") == 0 ||
77 strcmp(aTopic, "profile-change-teardown") == 0) {
78 mShutdownInProgress = true;
81 if (mShutdownInProgress || strcmp(aTopic, OBSERVER_TOPIC_ACTIVE) == 0) {
82 return NS_OK;
84 MOZ_ASSERT(strcmp(aTopic, OBSERVER_TOPIC_IDLE) == 0);
86 MOZ_LOG(sLog, LogLevel::Debug,
87 ("nsUserIdleServiceDaily: Notifying idle-daily observers"));
88 #ifdef MOZ_WIDGET_ANDROID
89 __android_log_print(LOG_LEVEL, LOG_TAG, "Notifying idle-daily observers");
90 #endif
92 // Send the idle-daily observer event
93 nsCOMPtr<nsIObserverService> observerService =
94 mozilla::services::GetObserverService();
95 NS_ENSURE_STATE(observerService);
96 (void)observerService->NotifyObservers(nullptr, OBSERVER_TOPIC_IDLE_DAILY,
97 nullptr);
99 // Notify the category observers.
100 nsCOMArray<nsIObserver> entries;
101 mCategoryObservers.GetEntries(entries);
102 for (int32_t i = 0; i < entries.Count(); ++i) {
103 (void)entries[i]->Observe(nullptr, OBSERVER_TOPIC_IDLE_DAILY, nullptr);
106 // Stop observing idle for today.
107 (void)mIdleService->RemoveIdleObserver(this, mIdleDailyTriggerWait);
109 // Set the last idle-daily time pref.
110 int32_t nowSec = static_cast<int32_t>(PR_Now() / PR_USEC_PER_SEC);
111 Preferences::SetInt(PREF_LAST_DAILY, nowSec);
113 // Force that to be stored so we don't retrigger twice a day under
114 // any circumstances.
115 nsIPrefService* prefs = Preferences::GetService();
116 if (prefs) {
117 prefs->SavePrefFile(nullptr);
120 MOZ_LOG(
121 sLog, LogLevel::Debug,
122 ("nsUserIdleServiceDaily: Storing last idle time as %d sec.", nowSec));
123 #ifdef MOZ_WIDGET_ANDROID
124 __android_log_print(LOG_LEVEL, LOG_TAG, "Storing last idle time as %d",
125 nowSec);
126 #endif
128 // Note the moment we expect to get the next timer callback
129 mExpectedTriggerTime =
130 PR_Now() + ((PRTime)SECONDS_PER_DAY * (PRTime)PR_USEC_PER_SEC);
132 MOZ_LOG(sLog, LogLevel::Debug,
133 ("nsUserIdleServiceDaily: Restarting daily timer"));
135 // Start timer for the next check in one day.
136 (void)mTimer->InitWithNamedFuncCallback(
137 DailyCallback, this, SECONDS_PER_DAY * PR_MSEC_PER_SEC,
138 nsITimer::TYPE_ONE_SHOT, "nsUserIdleServiceDaily::Observe");
140 return NS_OK;
143 nsUserIdleServiceDaily::nsUserIdleServiceDaily(nsIUserIdleService* aIdleService)
144 : mIdleService(aIdleService),
145 mTimer(NS_NewTimer()),
146 mCategoryObservers(OBSERVER_TOPIC_IDLE_DAILY),
147 mShutdownInProgress(false),
148 mExpectedTriggerTime(0),
149 mIdleDailyTriggerWait(DAILY_SIGNIFICANT_IDLE_SERVICE_SEC) {}
151 void nsUserIdleServiceDaily::Init() {
152 // First check the time of the last idle-daily event notification. If it
153 // has been 24 hours or higher, or if we have never sent an idle-daily,
154 // get ready to send an idle-daily event. Otherwise set a timer targeted
155 // at 24 hours past the last idle-daily we sent.
157 int32_t lastDaily = Preferences::GetInt(PREF_LAST_DAILY, 0);
158 // Setting the pref to -1 allows to disable idle-daily, and it's particularly
159 // useful in tests. Normally there should be no need for the user to set
160 // this value.
161 if (lastDaily == -1) {
162 MOZ_LOG(sLog, LogLevel::Debug,
163 ("nsUserIdleServiceDaily: Init: disabled idle-daily"));
164 return;
167 int32_t nowSec = static_cast<int32_t>(PR_Now() / PR_USEC_PER_SEC);
168 if (lastDaily < 0 || lastDaily > nowSec) {
169 // The time is bogus, use default.
170 lastDaily = 0;
172 int32_t secondsSinceLastDaily = nowSec - lastDaily;
174 MOZ_LOG(sLog, LogLevel::Debug,
175 ("nsUserIdleServiceDaily: Init: seconds since last daily: %d",
176 secondsSinceLastDaily));
178 // If it has been twenty four hours or more or if we have never sent an
179 // idle-daily event get ready to send it during the next idle period.
180 if (secondsSinceLastDaily > SECONDS_PER_DAY) {
181 // Check for a "long wait", e.g. 48-hours or more.
182 bool hasBeenLongWait =
183 (lastDaily && (secondsSinceLastDaily > (SECONDS_PER_DAY * 2)));
185 MOZ_LOG(
186 sLog, LogLevel::Debug,
187 ("nsUserIdleServiceDaily: has been long wait? %d", hasBeenLongWait));
189 // StageIdleDaily sets up a wait for the user to become idle and then
190 // sends the idle-daily event.
191 StageIdleDaily(hasBeenLongWait);
192 } else {
193 MOZ_LOG(sLog, LogLevel::Debug,
194 ("nsUserIdleServiceDaily: Setting timer a day from now"));
195 #ifdef MOZ_WIDGET_ANDROID
196 __android_log_print(LOG_LEVEL, LOG_TAG, "Setting timer a day from now");
197 #endif
199 // According to our last idle-daily pref, the last idle-daily was fired
200 // less then 24 hours ago. Set a wait for the amount of time remaining.
201 int32_t milliSecLeftUntilDaily =
202 (SECONDS_PER_DAY - secondsSinceLastDaily) * PR_MSEC_PER_SEC;
204 MOZ_LOG(sLog, LogLevel::Debug,
205 ("nsUserIdleServiceDaily: Seconds till next timeout: %d",
206 (SECONDS_PER_DAY - secondsSinceLastDaily)));
208 // Mark the time at which we expect this to fire. On systems with faulty
209 // timers, we need to be able to cross check that the timer fired at the
210 // expected time.
211 mExpectedTriggerTime =
212 PR_Now() + (milliSecLeftUntilDaily * PR_USEC_PER_MSEC);
214 (void)mTimer->InitWithNamedFuncCallback(
215 DailyCallback, this, milliSecLeftUntilDaily, nsITimer::TYPE_ONE_SHOT,
216 "nsUserIdleServiceDaily::Init");
219 // Register for when we should terminate/pause
220 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
221 if (obs) {
222 MOZ_LOG(
223 sLog, LogLevel::Debug,
224 ("nsUserIdleServiceDaily: Registering for system event observers."));
225 obs->AddObserver(this, "xpcom-will-shutdown", true);
226 obs->AddObserver(this, "profile-change-teardown", true);
227 obs->AddObserver(this, "profile-after-change", true);
231 nsUserIdleServiceDaily::~nsUserIdleServiceDaily() {
232 if (mTimer) {
233 mTimer->Cancel();
234 mTimer = nullptr;
238 void nsUserIdleServiceDaily::StageIdleDaily(bool aHasBeenLongWait) {
239 NS_ASSERTION(mIdleService, "No idle service available?");
240 MOZ_LOG(sLog, LogLevel::Debug,
241 ("nsUserIdleServiceDaily: Registering Idle observer callback "
242 "(short wait requested? %d)",
243 aHasBeenLongWait));
244 #ifdef MOZ_WIDGET_ANDROID
245 __android_log_print(LOG_LEVEL, LOG_TAG, "Registering Idle observer callback");
246 #endif
247 mIdleDailyTriggerWait =
248 (aHasBeenLongWait ? DAILY_SHORTENED_IDLE_SERVICE_SEC
249 : DAILY_SIGNIFICANT_IDLE_SERVICE_SEC);
250 (void)mIdleService->AddIdleObserver(this, mIdleDailyTriggerWait);
253 // static
254 void nsUserIdleServiceDaily::DailyCallback(nsITimer* aTimer, void* aClosure) {
255 MOZ_LOG(sLog, LogLevel::Debug,
256 ("nsUserIdleServiceDaily: DailyCallback running"));
257 #ifdef MOZ_WIDGET_ANDROID
258 __android_log_print(LOG_LEVEL, LOG_TAG, "DailyCallback running");
259 #endif
261 nsUserIdleServiceDaily* self = static_cast<nsUserIdleServiceDaily*>(aClosure);
263 // Check to be sure the timer didn't fire early. This currently only
264 // happens on android.
265 PRTime now = PR_Now();
266 if (self->mExpectedTriggerTime && now < self->mExpectedTriggerTime) {
267 // Timer returned early, reschedule to the appropriate time.
268 PRTime delayTime = self->mExpectedTriggerTime - now;
270 // Add 10 ms to ensure we don't undershoot, and never get a "0" timer.
271 delayTime += 10 * PR_USEC_PER_MSEC;
273 MOZ_LOG(sLog, LogLevel::Debug,
274 ("nsUserIdleServiceDaily: DailyCallback resetting timer to %" PRId64
275 " msec",
276 delayTime / PR_USEC_PER_MSEC));
277 #ifdef MOZ_WIDGET_ANDROID
278 __android_log_print(LOG_LEVEL, LOG_TAG,
279 "DailyCallback resetting timer to %" PRId64 " msec",
280 delayTime / PR_USEC_PER_MSEC);
281 #endif
283 (void)self->mTimer->InitWithNamedFuncCallback(
284 DailyCallback, self, delayTime / PR_USEC_PER_MSEC,
285 nsITimer::TYPE_ONE_SHOT, "nsUserIdleServiceDaily::DailyCallback");
286 return;
289 // Register for a short term wait for idle event. When this fires we fire
290 // our idle-daily event.
291 self->StageIdleDaily(false);
295 * The idle services goal is to notify subscribers when a certain time has
296 * passed since the last user interaction with the system.
298 * On some platforms this is defined as the last time user events reached this
299 * application, on other platforms it is a system wide thing - the preferred
300 * implementation is to use the system idle time, rather than the application
301 * idle time, as the things depending on the idle service are likely to use
302 * significant resources (network, disk, memory, cpu, etc.).
304 * When the idle service needs to use the system wide idle timer, it typically
305 * needs to poll the idle time value by the means of a timer. It needs to
306 * poll fast when it is in active idle mode (when it has a listener in the idle
307 * mode) as it needs to detect if the user is active in other applications.
309 * When the service is waiting for the first listener to become idle, or when
310 * it is only monitoring application idle time, it only needs to have the timer
311 * expire at the time the next listener goes idle.
313 * The core state of the service is determined by:
315 * - A list of listeners.
317 * - A boolean that tells if any listeners are in idle mode.
319 * - A delta value that indicates when, measured from the last non-idle time,
320 * the next listener should switch to idle mode.
322 * - An absolute time of the last time idle mode was detected (this is used to
323 * judge if we have been out of idle mode since the last invocation of the
324 * service.
326 * There are four entry points into the system:
328 * - A new listener is registered.
330 * - An existing listener is deregistered.
332 * - User interaction is detected.
334 * - The timer expires.
336 * When a new listener is added its idle timeout, is compared with the next idle
337 * timeout, and if lower, that time is stored as the new timeout, and the timer
338 * is reconfigured to ensure a timeout around the time the new listener should
339 * timeout.
341 * If the next idle time is above the idle time requested by the new listener
342 * it won't be informed until the timer expires, this is to avoid recursive
343 * behavior and to simplify the code. In this case the timer will be set to
344 * about 10 ms.
346 * When an existing listener is deregistered, it is just removed from the list
347 * of active listeners, we don't stop the timer, we just let it expire.
349 * When user interaction is detected, either because it was directly detected or
350 * because we polled the system timer and found it to be unexpected low, then we
351 * check the flag that tells us if any listeners are in idle mode, if there are
352 * they are removed from idle mode and told so, and we reset our state
353 * caculating the next timeout and restart the timer if needed.
355 * ---- Build in logic
357 * In order to avoid restarting the timer endlessly, the timer function has
358 * logic that will only restart the timer, if the requested timeout is before
359 * the current timeout.
363 ////////////////////////////////////////////////////////////////////////////////
364 //// nsUserIdleService
366 namespace {
367 nsUserIdleService* gIdleService;
368 } // namespace
370 already_AddRefed<nsUserIdleService> nsUserIdleService::GetInstance() {
371 RefPtr<nsUserIdleService> instance(gIdleService);
372 return instance.forget();
375 nsUserIdleService::nsUserIdleService()
376 : mCurrentlySetToTimeoutAt(TimeStamp()),
377 mIdleObserverCount(0),
378 mDeltaToNextIdleSwitchInS(UINT32_MAX),
379 mLastUserInteraction(TimeStamp::Now()) {
380 MOZ_ASSERT(!gIdleService);
381 gIdleService = this;
382 if (XRE_IsParentProcess()) {
383 mDailyIdle = new nsUserIdleServiceDaily(this);
384 mDailyIdle->Init();
388 nsUserIdleService::~nsUserIdleService() {
389 if (mTimer) {
390 mTimer->Cancel();
393 MOZ_ASSERT(gIdleService == this);
394 gIdleService = nullptr;
397 NS_IMPL_ISUPPORTS(nsUserIdleService, nsIUserIdleService,
398 nsIUserIdleServiceInternal)
400 NS_IMETHODIMP
401 nsUserIdleService::AddIdleObserver(nsIObserver* aObserver,
402 uint32_t aIdleTimeInS) {
403 NS_ENSURE_ARG_POINTER(aObserver);
404 // We don't accept idle time at 0, and we can't handle idle time that are too
405 // high either - no more than ~136 years.
406 NS_ENSURE_ARG_RANGE(aIdleTimeInS, 1, (UINT32_MAX / 10) - 1);
408 if (profiler_thread_is_being_profiled_for_markers()) {
409 nsAutoCString timeCStr;
410 timeCStr.AppendInt(aIdleTimeInS);
411 PROFILER_MARKER_TEXT("UserIdle::AddObserver", OTHER, MarkerStack::Capture(),
412 timeCStr);
415 if (XRE_IsContentProcess()) {
416 dom::ContentChild* cpc = dom::ContentChild::GetSingleton();
417 cpc->AddIdleObserver(aObserver, aIdleTimeInS);
418 return NS_OK;
421 MOZ_LOG(sLog, LogLevel::Debug,
422 ("idleService: Register idle observer %p for %d seconds", aObserver,
423 aIdleTimeInS));
424 #ifdef MOZ_WIDGET_ANDROID
425 __android_log_print(LOG_LEVEL, LOG_TAG,
426 "Register idle observer %p for %d seconds", aObserver,
427 aIdleTimeInS);
428 #endif
430 // Put the time + observer in a struct we can keep:
431 IdleListener listener(aObserver, aIdleTimeInS);
433 // XXX(Bug 1631371) Check if this should use a fallible operation as it
434 // pretended earlier.
435 mArrayListeners.AppendElement(listener);
437 // Create our timer callback if it's not there already.
438 if (!mTimer) {
439 mTimer = NS_NewTimer();
440 NS_ENSURE_TRUE(mTimer, NS_ERROR_OUT_OF_MEMORY);
443 // Check if the newly added observer has a smaller wait time than what we
444 // are waiting for now.
445 if (mDeltaToNextIdleSwitchInS > aIdleTimeInS) {
446 // If it is, then this is the next to move to idle (at this point we
447 // don't care if it should have switched already).
448 MOZ_LOG(
449 sLog, LogLevel::Debug,
450 ("idleService: Register: adjusting next switch from %d to %d seconds",
451 mDeltaToNextIdleSwitchInS, aIdleTimeInS));
452 #ifdef MOZ_WIDGET_ANDROID
453 __android_log_print(LOG_LEVEL, LOG_TAG,
454 "Register: adjusting next switch from %d to %d seconds",
455 mDeltaToNextIdleSwitchInS, aIdleTimeInS);
456 #endif
458 mDeltaToNextIdleSwitchInS = aIdleTimeInS;
459 ReconfigureTimer();
462 return NS_OK;
465 NS_IMETHODIMP
466 nsUserIdleService::RemoveIdleObserver(nsIObserver* aObserver,
467 uint32_t aTimeInS) {
468 NS_ENSURE_ARG_POINTER(aObserver);
469 NS_ENSURE_ARG(aTimeInS);
471 if (profiler_thread_is_being_profiled_for_markers()) {
472 nsAutoCString timeCStr;
473 timeCStr.AppendInt(aTimeInS);
474 PROFILER_MARKER_TEXT("UserIdle::RemoveObserver", OTHER,
475 MarkerStack::Capture(), timeCStr);
478 if (XRE_IsContentProcess()) {
479 dom::ContentChild* cpc = dom::ContentChild::GetSingleton();
480 cpc->RemoveIdleObserver(aObserver, aTimeInS);
481 return NS_OK;
484 IdleListener listener(aObserver, aTimeInS);
486 // Find the entry and remove it, if it was the last entry, we just let the
487 // existing timer run to completion (there might be a new registration in a
488 // little while.
489 IdleListenerComparator c;
490 nsTArray<IdleListener>::index_type listenerIndex =
491 mArrayListeners.IndexOf(listener, 0, c);
492 if (listenerIndex != mArrayListeners.NoIndex) {
493 if (mArrayListeners.ElementAt(listenerIndex).isIdle) mIdleObserverCount--;
494 mArrayListeners.RemoveElementAt(listenerIndex);
495 MOZ_LOG(sLog, LogLevel::Debug,
496 ("idleService: Remove observer %p (%d seconds), %d remain idle",
497 aObserver, aTimeInS, mIdleObserverCount));
498 #ifdef MOZ_WIDGET_ANDROID
499 __android_log_print(LOG_LEVEL, LOG_TAG,
500 "Remove observer %p (%d seconds), %d remain idle",
501 aObserver, aTimeInS, mIdleObserverCount);
502 #endif
503 return NS_OK;
506 // If we get here, we haven't removed anything:
507 MOZ_LOG(sLog, LogLevel::Warning,
508 ("idleService: Failed to remove idle observer %p (%d seconds)",
509 aObserver, aTimeInS));
510 #ifdef MOZ_WIDGET_ANDROID
511 __android_log_print(LOG_LEVEL, LOG_TAG,
512 "Failed to remove idle observer %p (%d seconds)",
513 aObserver, aTimeInS);
514 #endif
515 return NS_ERROR_FAILURE;
518 NS_IMETHODIMP
519 nsUserIdleService::ResetIdleTimeOut(uint32_t idleDeltaInMS) {
520 MOZ_LOG(sLog, LogLevel::Debug,
521 ("idleService: Reset idle timeout (last interaction %u msec)",
522 idleDeltaInMS));
524 // Store the time
525 mLastUserInteraction =
526 TimeStamp::Now() - TimeDuration::FromMilliseconds(idleDeltaInMS);
528 // If no one is idle, then we are done, any existing timers can keep running.
529 if (mIdleObserverCount == 0) {
530 MOZ_LOG(sLog, LogLevel::Debug,
531 ("idleService: Reset idle timeout: no idle observers"));
532 return NS_OK;
535 // Mark all idle services as non-idle, and calculate the next idle timeout.
536 nsCOMArray<nsIObserver> notifyList;
537 mDeltaToNextIdleSwitchInS = UINT32_MAX;
539 // Loop through all listeners, and find any that have detected idle.
540 for (uint32_t i = 0; i < mArrayListeners.Length(); i++) {
541 IdleListener& curListener = mArrayListeners.ElementAt(i);
543 // If the listener was idle, then he shouldn't be any longer.
544 if (curListener.isIdle) {
545 notifyList.AppendObject(curListener.observer);
546 curListener.isIdle = false;
549 // Check if the listener is the next one to timeout.
550 mDeltaToNextIdleSwitchInS =
551 std::min(mDeltaToNextIdleSwitchInS, curListener.reqIdleTime);
554 // When we are done, then we wont have anyone idle.
555 mIdleObserverCount = 0;
557 // Restart the idle timer, and do so before anyone can delay us.
558 ReconfigureTimer();
560 int32_t numberOfPendingNotifications = notifyList.Count();
562 // Bail if nothing to do.
563 if (!numberOfPendingNotifications) {
564 return NS_OK;
567 // Now send "active" events to all, if any should have timed out already,
568 // then they will be reawaken by the timer that is already running.
570 // We need a text string to send with any state change events.
571 nsAutoString timeStr;
573 timeStr.AppendInt((int32_t)(idleDeltaInMS / PR_MSEC_PER_SEC));
575 // Send the "non-idle" events.
576 while (numberOfPendingNotifications--) {
577 MOZ_LOG(sLog, LogLevel::Debug,
578 ("idleService: Reset idle timeout: tell observer %p user is back",
579 notifyList[numberOfPendingNotifications]));
580 #ifdef MOZ_WIDGET_ANDROID
581 __android_log_print(LOG_LEVEL, LOG_TAG,
582 "Reset idle timeout: tell observer %p user is back",
583 notifyList[numberOfPendingNotifications]);
584 #endif
585 notifyList[numberOfPendingNotifications]->Observe(
586 this, OBSERVER_TOPIC_ACTIVE, timeStr.get());
588 return NS_OK;
591 NS_IMETHODIMP
592 nsUserIdleService::GetIdleTime(uint32_t* idleTime) {
593 // Check sanity of in parameter.
594 if (!idleTime) {
595 return NS_ERROR_NULL_POINTER;
598 // Polled idle time in ms.
599 uint32_t polledIdleTimeMS;
601 bool polledIdleTimeIsValid = PollIdleTime(&polledIdleTimeMS);
603 MOZ_LOG(sLog, LogLevel::Debug,
604 ("idleService: Get idle time: polled %u msec, valid = %d",
605 polledIdleTimeMS, polledIdleTimeIsValid));
607 // timeSinceReset is in milliseconds.
608 TimeDuration timeSinceReset = TimeStamp::Now() - mLastUserInteraction;
609 uint32_t timeSinceResetInMS = timeSinceReset.ToMilliseconds();
611 MOZ_LOG(sLog, LogLevel::Debug,
612 ("idleService: Get idle time: time since reset %u msec",
613 timeSinceResetInMS));
614 #ifdef MOZ_WIDGET_ANDROID
615 __android_log_print(LOG_LEVEL, LOG_TAG,
616 "Get idle time: time since reset %u msec",
617 timeSinceResetInMS);
618 #endif
620 // If we did't get pulled data, return the time since last idle reset.
621 if (!polledIdleTimeIsValid) {
622 // We need to convert to ms before returning the time.
623 *idleTime = timeSinceResetInMS;
624 return NS_OK;
627 // Otherwise return the shortest time detected (in ms).
628 *idleTime = std::min(timeSinceResetInMS, polledIdleTimeMS);
630 return NS_OK;
633 bool nsUserIdleService::PollIdleTime(uint32_t* /*aIdleTime*/) {
634 // Default behavior is not to have the ability to poll an idle time.
635 return false;
638 nsresult nsUserIdleService::GetDisabled(bool* aResult) {
639 *aResult = mDisabled;
640 return NS_OK;
643 nsresult nsUserIdleService::SetDisabled(bool aDisabled) {
644 mDisabled = aDisabled;
645 return NS_OK;
648 void nsUserIdleService::StaticIdleTimerCallback(nsITimer* aTimer,
649 void* aClosure) {
650 static_cast<nsUserIdleService*>(aClosure)->IdleTimerCallback();
653 void nsUserIdleService::IdleTimerCallback(void) {
654 // Remember that we no longer have a timer running.
655 mCurrentlySetToTimeoutAt = TimeStamp();
657 // Find the last detected idle time.
658 uint32_t lastIdleTimeInMS = static_cast<uint32_t>(
659 (TimeStamp::Now() - mLastUserInteraction).ToMilliseconds());
660 // Get the current idle time.
661 uint32_t currentIdleTimeInMS;
663 if (NS_FAILED(GetIdleTime(&currentIdleTimeInMS))) {
664 MOZ_LOG(sLog, LogLevel::Info,
665 ("idleService: Idle timer callback: failed to get idle time"));
666 #ifdef MOZ_WIDGET_ANDROID
667 __android_log_print(LOG_LEVEL, LOG_TAG,
668 "Idle timer callback: failed to get idle time");
669 #endif
670 return;
673 MOZ_LOG(sLog, LogLevel::Debug,
674 ("idleService: Idle timer callback: current idle time %u msec",
675 currentIdleTimeInMS));
676 #ifdef MOZ_WIDGET_ANDROID
677 __android_log_print(LOG_LEVEL, LOG_TAG,
678 "Idle timer callback: current idle time %u msec",
679 currentIdleTimeInMS);
680 #endif
682 // Check if we have had some user interaction we didn't handle previously
683 // we do the calculation in ms to lessen the chance for rounding errors to
684 // trigger wrong results.
685 if (lastIdleTimeInMS > currentIdleTimeInMS) {
686 // We had user activity, so handle that part first (to ensure the listeners
687 // don't risk getting an non-idle after they get a new idle indication.
688 ResetIdleTimeOut(currentIdleTimeInMS);
690 // NOTE: We can't bail here, as we might have something already timed out.
693 // Find the idle time in S.
694 uint32_t currentIdleTimeInS = currentIdleTimeInMS / PR_MSEC_PER_SEC;
696 // Restart timer and bail if no-one are expected to be in idle
697 if (mDeltaToNextIdleSwitchInS > currentIdleTimeInS) {
698 // If we didn't expect anyone to be idle, then just re-start the timer.
699 ReconfigureTimer();
700 return;
703 if (mDisabled) {
704 MOZ_LOG(sLog, LogLevel::Info,
705 ("idleService: Skipping idle callback while disabled"));
707 ReconfigureTimer();
708 return;
711 // Tell expired listeners they are expired,and find the next timeout
712 Telemetry::AutoTimer<Telemetry::IDLE_NOTIFY_IDLE_MS> timer;
714 // We need to initialise the time to the next idle switch.
715 mDeltaToNextIdleSwitchInS = UINT32_MAX;
717 // Create list of observers that should be notified.
718 nsCOMArray<nsIObserver> notifyList;
720 for (uint32_t i = 0; i < mArrayListeners.Length(); i++) {
721 IdleListener& curListener = mArrayListeners.ElementAt(i);
723 // We are only interested in items, that are not in the idle state.
724 if (!curListener.isIdle) {
725 // If they have an idle time smaller than the actual idle time.
726 if (curListener.reqIdleTime <= currentIdleTimeInS) {
727 // Then add the listener to the list of listeners that should be
728 // notified.
729 notifyList.AppendObject(curListener.observer);
730 // This listener is now idle.
731 curListener.isIdle = true;
732 // Remember we have someone idle.
733 mIdleObserverCount++;
734 } else {
735 // Listeners that are not timed out yet are candidates for timing out.
736 mDeltaToNextIdleSwitchInS =
737 std::min(mDeltaToNextIdleSwitchInS, curListener.reqIdleTime);
742 // Restart the timer before any notifications that could slow us down are
743 // done.
744 ReconfigureTimer();
746 int32_t numberOfPendingNotifications = notifyList.Count();
748 // Bail if nothing to do.
749 if (!numberOfPendingNotifications) {
750 MOZ_LOG(
751 sLog, LogLevel::Debug,
752 ("idleService: **** Idle timer callback: no observers to message."));
753 return;
756 // We need a text string to send with any state change events.
757 nsAutoString timeStr;
758 timeStr.AppendInt(currentIdleTimeInS);
760 // Notify all listeners that just timed out.
761 while (numberOfPendingNotifications--) {
762 MOZ_LOG(
763 sLog, LogLevel::Debug,
764 ("idleService: **** Idle timer callback: tell observer %p user is idle",
765 notifyList[numberOfPendingNotifications]));
766 #ifdef MOZ_WIDGET_ANDROID
767 __android_log_print(LOG_LEVEL, LOG_TAG,
768 "Idle timer callback: tell observer %p user is idle",
769 notifyList[numberOfPendingNotifications]);
770 #endif
771 nsAutoCString timeCStr;
772 timeCStr.AppendInt(currentIdleTimeInS);
773 AUTO_PROFILER_MARKER_TEXT("UserIdle::IdleCallback", OTHER, {}, timeCStr);
774 notifyList[numberOfPendingNotifications]->Observe(this, OBSERVER_TOPIC_IDLE,
775 timeStr.get());
779 void nsUserIdleService::SetTimerExpiryIfBefore(TimeStamp aNextTimeout) {
780 TimeDuration nextTimeoutDuration = aNextTimeout - TimeStamp::Now();
782 MOZ_LOG(
783 sLog, LogLevel::Debug,
784 ("idleService: SetTimerExpiryIfBefore: next timeout %0.f msec from now",
785 nextTimeoutDuration.ToMilliseconds()));
787 #ifdef MOZ_WIDGET_ANDROID
788 __android_log_print(LOG_LEVEL, LOG_TAG,
789 "SetTimerExpiryIfBefore: next timeout %0.f msec from now",
790 nextTimeoutDuration.ToMilliseconds());
791 #endif
793 // Bail if we don't have a timer service.
794 if (!mTimer) {
795 return;
798 // If the new timeout is before the old one or we don't have a timer running,
799 // then restart the timer.
800 if (mCurrentlySetToTimeoutAt.IsNull() ||
801 mCurrentlySetToTimeoutAt > aNextTimeout) {
802 mCurrentlySetToTimeoutAt = aNextTimeout;
804 // Stop the current timer (it's ok to try'n stop it, even it isn't running).
805 mTimer->Cancel();
807 // Check that the timeout is actually in the future, otherwise make it so.
808 TimeStamp currentTime = TimeStamp::Now();
809 if (currentTime > mCurrentlySetToTimeoutAt) {
810 mCurrentlySetToTimeoutAt = currentTime;
813 // Add 10 ms to ensure we don't undershoot, and never get a "0" timer.
814 mCurrentlySetToTimeoutAt += TimeDuration::FromMilliseconds(10);
816 TimeDuration deltaTime = mCurrentlySetToTimeoutAt - currentTime;
817 MOZ_LOG(
818 sLog, LogLevel::Debug,
819 ("idleService: IdleService reset timer expiry to %0.f msec from now",
820 deltaTime.ToMilliseconds()));
821 #ifdef MOZ_WIDGET_ANDROID
822 __android_log_print(LOG_LEVEL, LOG_TAG,
823 "reset timer expiry to %0.f msec from now",
824 deltaTime.ToMilliseconds());
825 #endif
827 // Start the timer
828 mTimer->InitWithNamedFuncCallback(
829 StaticIdleTimerCallback, this, deltaTime.ToMilliseconds(),
830 nsITimer::TYPE_ONE_SHOT, "nsUserIdleService::SetTimerExpiryIfBefore");
834 void nsUserIdleService::ReconfigureTimer(void) {
835 // Check if either someone is idle, or someone will become idle.
836 if ((mIdleObserverCount == 0) && UINT32_MAX == mDeltaToNextIdleSwitchInS) {
837 // If not, just let any existing timers run to completion
838 // And bail out.
839 MOZ_LOG(sLog, LogLevel::Debug,
840 ("idleService: ReconfigureTimer: no idle or waiting observers"));
841 #ifdef MOZ_WIDGET_ANDROID
842 __android_log_print(LOG_LEVEL, LOG_TAG,
843 "ReconfigureTimer: no idle or waiting observers");
844 #endif
845 return;
848 // Find the next timeout value, assuming we are not polling.
850 // We need to store the current time, so we don't get artifacts from the time
851 // ticking while we are processing.
852 TimeStamp curTime = TimeStamp::Now();
854 TimeStamp nextTimeoutAt =
855 mLastUserInteraction +
856 TimeDuration::FromSeconds(mDeltaToNextIdleSwitchInS);
858 TimeDuration nextTimeoutDuration = nextTimeoutAt - curTime;
860 MOZ_LOG(sLog, LogLevel::Debug,
861 ("idleService: next timeout %0.f msec from now",
862 nextTimeoutDuration.ToMilliseconds()));
864 #ifdef MOZ_WIDGET_ANDROID
865 __android_log_print(LOG_LEVEL, LOG_TAG, "next timeout %0.f msec from now",
866 nextTimeoutDuration.ToMilliseconds());
867 #endif
869 SetTimerExpiryIfBefore(nextTimeoutAt);