Bug 1462329 [wpt PR 10991] - Server-Timing: test TAO:* for cross-origin resource...
[gecko.git] / widget / nsIdleService.cpp
blobe2abd5b392fadbc391e72c3ab1160c62a7a4a23a
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 "nsIdleService.h"
9 #include "nsString.h"
10 #include "nsIObserverService.h"
11 #include "nsIServiceManager.h"
12 #include "nsDebug.h"
13 #include "nsCOMArray.h"
14 #include "nsXULAppAPI.h"
15 #include "prinrval.h"
16 #include "mozilla/Logging.h"
17 #include "prtime.h"
18 #include "mozilla/dom/ContentChild.h"
19 #include "mozilla/Services.h"
20 #include "mozilla/Preferences.h"
21 #include "mozilla/Telemetry.h"
22 #include <algorithm>
24 #ifdef MOZ_WIDGET_ANDROID
25 #include <android/log.h>
26 #endif
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
35 // event.
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
49 static LazyLogModule sLog("idleService");
51 #define LOG_TAG "GeckoIdleService"
52 #define LOG_LEVEL ANDROID_LOG_DEBUG
54 // Use this to find previously added observers in our array:
55 class IdleListenerComparator
57 public:
58 bool Equals(IdleListener a, IdleListener b) const
60 return (a.observer == b.observer) &&
61 (a.reqIdleTime == b.reqIdleTime);
65 ////////////////////////////////////////////////////////////////////////////////
66 //// nsIdleServiceDaily
68 NS_IMPL_ISUPPORTS(nsIdleServiceDaily, nsIObserver, nsISupportsWeakReference)
70 NS_IMETHODIMP
71 nsIdleServiceDaily::Observe(nsISupports *,
72 const char *aTopic,
73 const char16_t *)
75 MOZ_LOG(sLog, LogLevel::Debug,
76 ("nsIdleServiceDaily: Observe '%s' (%d)",
77 aTopic, mShutdownInProgress));
79 if (strcmp(aTopic, "profile-after-change") == 0) {
80 // We are back. Start sending notifications again.
81 mShutdownInProgress = false;
82 return NS_OK;
85 if (strcmp(aTopic, "xpcom-will-shutdown") == 0 ||
86 strcmp(aTopic, "profile-change-teardown") == 0) {
87 mShutdownInProgress = true;
90 if (mShutdownInProgress || strcmp(aTopic, OBSERVER_TOPIC_ACTIVE) == 0) {
91 return NS_OK;
93 MOZ_ASSERT(strcmp(aTopic, OBSERVER_TOPIC_IDLE) == 0);
95 MOZ_LOG(sLog, LogLevel::Debug,
96 ("nsIdleServiceDaily: Notifying idle-daily observers"));
97 #ifdef MOZ_WIDGET_ANDROID
98 __android_log_print(LOG_LEVEL, LOG_TAG,
99 "Notifying idle-daily observers");
100 #endif
102 // Send the idle-daily observer event
103 nsCOMPtr<nsIObserverService> observerService =
104 mozilla::services::GetObserverService();
105 NS_ENSURE_STATE(observerService);
106 (void)observerService->NotifyObservers(nullptr,
107 OBSERVER_TOPIC_IDLE_DAILY,
108 nullptr);
110 // Notify the category observers.
111 nsCOMArray<nsIObserver> entries;
112 mCategoryObservers.GetEntries(entries);
113 for (int32_t i = 0; i < entries.Count(); ++i) {
114 (void)entries[i]->Observe(nullptr, OBSERVER_TOPIC_IDLE_DAILY, nullptr);
117 // Stop observing idle for today.
118 (void)mIdleService->RemoveIdleObserver(this, mIdleDailyTriggerWait);
120 // Set the last idle-daily time pref.
121 int32_t nowSec = static_cast<int32_t>(PR_Now() / PR_USEC_PER_SEC);
122 Preferences::SetInt(PREF_LAST_DAILY, nowSec);
124 // Force that to be stored so we don't retrigger twice a day under
125 // any circumstances.
126 nsIPrefService* prefs = Preferences::GetService();
127 if (prefs) {
128 prefs->SavePrefFile(nullptr);
131 MOZ_LOG(sLog, LogLevel::Debug,
132 ("nsIdleServiceDaily: Storing last idle time as %d sec.", nowSec));
133 #ifdef MOZ_WIDGET_ANDROID
134 __android_log_print(LOG_LEVEL, LOG_TAG,
135 "Storing last idle time as %d", nowSec);
136 #endif
138 // Note the moment we expect to get the next timer callback
139 mExpectedTriggerTime = PR_Now() + ((PRTime)SECONDS_PER_DAY *
140 (PRTime)PR_USEC_PER_SEC);
142 MOZ_LOG(sLog, LogLevel::Debug,
143 ("nsIdleServiceDaily: Restarting daily timer"));
145 // Start timer for the next check in one day.
146 (void)mTimer->InitWithNamedFuncCallback(DailyCallback,
147 this,
148 SECONDS_PER_DAY * PR_MSEC_PER_SEC,
149 nsITimer::TYPE_ONE_SHOT,
150 "nsIdleServiceDaily::Observe");
152 return NS_OK;
155 nsIdleServiceDaily::nsIdleServiceDaily(nsIIdleService* aIdleService)
156 : mIdleService(aIdleService)
157 , mTimer(NS_NewTimer())
158 , mCategoryObservers(OBSERVER_TOPIC_IDLE_DAILY)
159 , mShutdownInProgress(false)
160 , mExpectedTriggerTime(0)
161 , mIdleDailyTriggerWait(DAILY_SIGNIFICANT_IDLE_SERVICE_SEC)
165 void
166 nsIdleServiceDaily::Init()
168 // First check the time of the last idle-daily event notification. If it
169 // has been 24 hours or higher, or if we have never sent an idle-daily,
170 // get ready to send an idle-daily event. Otherwise set a timer targeted
171 // at 24 hours past the last idle-daily we sent.
173 int32_t nowSec = static_cast<int32_t>(PR_Now() / PR_USEC_PER_SEC);
174 int32_t lastDaily = Preferences::GetInt(PREF_LAST_DAILY, 0);
175 if (lastDaily < 0 || lastDaily > nowSec) {
176 // The time is bogus, use default.
177 lastDaily = 0;
179 int32_t secondsSinceLastDaily = nowSec - lastDaily;
181 MOZ_LOG(sLog, LogLevel::Debug,
182 ("nsIdleServiceDaily: Init: seconds since last daily: %d",
183 secondsSinceLastDaily));
185 // If it has been twenty four hours or more or if we have never sent an
186 // idle-daily event get ready to send it during the next idle period.
187 if (secondsSinceLastDaily > SECONDS_PER_DAY) {
188 // Check for a "long wait", e.g. 48-hours or more.
189 bool hasBeenLongWait = (lastDaily &&
190 (secondsSinceLastDaily > (SECONDS_PER_DAY * 2)));
192 MOZ_LOG(sLog, LogLevel::Debug,
193 ("nsIdleServiceDaily: has been long wait? %d",
194 hasBeenLongWait));
196 // StageIdleDaily sets up a wait for the user to become idle and then
197 // sends the idle-daily event.
198 StageIdleDaily(hasBeenLongWait);
199 } else {
200 MOZ_LOG(sLog, LogLevel::Debug,
201 ("nsIdleServiceDaily: Setting timer a day from now"));
202 #ifdef MOZ_WIDGET_ANDROID
203 __android_log_print(LOG_LEVEL, LOG_TAG,
204 "Setting timer a day from now");
205 #endif
207 // According to our last idle-daily pref, the last idle-daily was fired
208 // less then 24 hours ago. Set a wait for the amount of time remaining.
209 int32_t milliSecLeftUntilDaily = (SECONDS_PER_DAY - secondsSinceLastDaily)
210 * PR_MSEC_PER_SEC;
212 MOZ_LOG(sLog, LogLevel::Debug,
213 ("nsIdleServiceDaily: Seconds till next timeout: %d",
214 (SECONDS_PER_DAY - secondsSinceLastDaily)));
216 // Mark the time at which we expect this to fire. On systems with faulty
217 // timers, we need to be able to cross check that the timer fired at the
218 // expected time.
219 mExpectedTriggerTime = PR_Now() +
220 (milliSecLeftUntilDaily * PR_USEC_PER_MSEC);
222 (void)mTimer->InitWithNamedFuncCallback(DailyCallback,
223 this,
224 milliSecLeftUntilDaily,
225 nsITimer::TYPE_ONE_SHOT,
226 "nsIdleServiceDaily::Init");
229 // Register for when we should terminate/pause
230 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
231 if (obs) {
232 MOZ_LOG(sLog, LogLevel::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()
242 if (mTimer) {
243 mTimer->Cancel();
244 mTimer = nullptr;
249 void
250 nsIdleServiceDaily::StageIdleDaily(bool aHasBeenLongWait)
252 NS_ASSERTION(mIdleService, "No idle service available?");
253 MOZ_LOG(sLog, LogLevel::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");
259 #endif
260 mIdleDailyTriggerWait = (aHasBeenLongWait ?
261 DAILY_SHORTENED_IDLE_SERVICE_SEC :
262 DAILY_SIGNIFICANT_IDLE_SERVICE_SEC);
263 (void)mIdleService->AddIdleObserver(this, mIdleDailyTriggerWait);
266 // static
267 void
268 nsIdleServiceDaily::DailyCallback(nsITimer* aTimer, void* aClosure)
270 MOZ_LOG(sLog, LogLevel::Debug,
271 ("nsIdleServiceDaily: DailyCallback running"));
272 #ifdef MOZ_WIDGET_ANDROID
273 __android_log_print(LOG_LEVEL, LOG_TAG,
274 "DailyCallback running");
275 #endif
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 MOZ_LOG(sLog, LogLevel::Debug, ("nsIdleServiceDaily: DailyCallback resetting timer to %" PRId64 " 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 %" PRId64 " msec",
294 delayTime / PR_USEC_PER_MSEC);
295 #endif
297 (void)self->mTimer->InitWithNamedFuncCallback(
298 DailyCallback,
299 self,
300 delayTime / PR_USEC_PER_MSEC,
301 nsITimer::TYPE_ONE_SHOT,
302 "nsIdleServiceDaily::DailyCallback");
303 return;
306 // Register for a short term wait for idle event. When this fires we fire
307 // our idle-daily event.
308 self->StageIdleDaily(false);
313 * The idle services goal is to notify subscribers when a certain time has
314 * passed since the last user interaction with the system.
316 * On some platforms this is defined as the last time user events reached this
317 * application, on other platforms it is a system wide thing - the preferred
318 * implementation is to use the system idle time, rather than the application
319 * idle time, as the things depending on the idle service are likely to use
320 * significant resources (network, disk, memory, cpu, etc.).
322 * When the idle service needs to use the system wide idle timer, it typically
323 * needs to poll the idle time value by the means of a timer. It needs to
324 * poll fast when it is in active idle mode (when it has a listener in the idle
325 * mode) as it needs to detect if the user is active in other applications.
327 * When the service is waiting for the first listener to become idle, or when
328 * it is only monitoring application idle time, it only needs to have the timer
329 * expire at the time the next listener goes idle.
331 * The core state of the service is determined by:
333 * - A list of listeners.
335 * - A boolean that tells if any listeners are in idle mode.
337 * - A delta value that indicates when, measured from the last non-idle time,
338 * the next listener should switch to idle mode.
340 * - An absolute time of the last time idle mode was detected (this is used to
341 * judge if we have been out of idle mode since the last invocation of the
342 * service.
344 * There are four entry points into the system:
346 * - A new listener is registered.
348 * - An existing listener is deregistered.
350 * - User interaction is detected.
352 * - The timer expires.
354 * When a new listener is added its idle timeout, is compared with the next idle
355 * timeout, and if lower, that time is stored as the new timeout, and the timer
356 * is reconfigured to ensure a timeout around the time the new listener should
357 * timeout.
359 * If the next idle time is above the idle time requested by the new listener
360 * it won't be informed until the timer expires, this is to avoid recursive
361 * behavior and to simplify the code. In this case the timer will be set to
362 * about 10 ms.
364 * When an existing listener is deregistered, it is just removed from the list
365 * of active listeners, we don't stop the timer, we just let it expire.
367 * When user interaction is detected, either because it was directly detected or
368 * because we polled the system timer and found it to be unexpected low, then we
369 * check the flag that tells us if any listeners are in idle mode, if there are
370 * they are removed from idle mode and told so, and we reset our state
371 * caculating the next timeout and restart the timer if needed.
373 * ---- Build in logic
375 * In order to avoid restarting the timer endlessly, the timer function has
376 * logic that will only restart the timer, if the requested timeout is before
377 * the current timeout.
382 ////////////////////////////////////////////////////////////////////////////////
383 //// nsIdleService
385 namespace {
386 nsIdleService* gIdleService;
387 } // namespace
389 already_AddRefed<nsIdleService>
390 nsIdleService::GetInstance()
392 RefPtr<nsIdleService> instance(gIdleService);
393 return instance.forget();
396 nsIdleService::nsIdleService() : mCurrentlySetToTimeoutAt(TimeStamp()),
397 mIdleObserverCount(0),
398 mDeltaToNextIdleSwitchInS(UINT32_MAX),
399 mLastUserInteraction(TimeStamp::Now())
401 MOZ_ASSERT(!gIdleService);
402 gIdleService = this;
403 if (XRE_IsParentProcess()) {
404 mDailyIdle = new nsIdleServiceDaily(this);
405 mDailyIdle->Init();
409 nsIdleService::~nsIdleService()
411 if(mTimer) {
412 mTimer->Cancel();
416 MOZ_ASSERT(gIdleService == this);
417 gIdleService = nullptr;
420 NS_IMPL_ISUPPORTS(nsIdleService, nsIIdleService, nsIIdleServiceInternal)
422 NS_IMETHODIMP
423 nsIdleService::AddIdleObserver(nsIObserver* aObserver, uint32_t aIdleTimeInS)
425 NS_ENSURE_ARG_POINTER(aObserver);
426 // We don't accept idle time at 0, and we can't handle idle time that are too
427 // high either - no more than ~136 years.
428 NS_ENSURE_ARG_RANGE(aIdleTimeInS, 1, (UINT32_MAX / 10) - 1);
430 if (XRE_IsContentProcess()) {
431 dom::ContentChild* cpc = dom::ContentChild::GetSingleton();
432 cpc->AddIdleObserver(aObserver, aIdleTimeInS);
433 return NS_OK;
436 MOZ_LOG(sLog, LogLevel::Debug,
437 ("idleService: Register idle observer %p for %d seconds",
438 aObserver, aIdleTimeInS));
439 #ifdef MOZ_WIDGET_ANDROID
440 __android_log_print(LOG_LEVEL, LOG_TAG,
441 "Register idle observer %p for %d seconds",
442 aObserver, aIdleTimeInS);
443 #endif
445 // Put the time + observer in a struct we can keep:
446 IdleListener listener(aObserver, aIdleTimeInS);
448 if (!mArrayListeners.AppendElement(listener)) {
449 return NS_ERROR_OUT_OF_MEMORY;
452 // Create our timer callback if it's not there already.
453 if (!mTimer) {
454 mTimer = NS_NewTimer();
455 NS_ENSURE_TRUE(mTimer, NS_ERROR_OUT_OF_MEMORY);
458 // Check if the newly added observer has a smaller wait time than what we
459 // are waiting for now.
460 if (mDeltaToNextIdleSwitchInS > aIdleTimeInS) {
461 // If it is, then this is the next to move to idle (at this point we
462 // don't care if it should have switched already).
463 MOZ_LOG(sLog, LogLevel::Debug,
464 ("idleService: Register: adjusting next switch from %d to %d seconds",
465 mDeltaToNextIdleSwitchInS, aIdleTimeInS));
466 #ifdef MOZ_WIDGET_ANDROID
467 __android_log_print(LOG_LEVEL, LOG_TAG,
468 "Register: adjusting next switch from %d to %d seconds",
469 mDeltaToNextIdleSwitchInS, aIdleTimeInS);
470 #endif
472 mDeltaToNextIdleSwitchInS = aIdleTimeInS;
475 // Ensure timer is running.
476 ReconfigureTimer();
478 return NS_OK;
481 NS_IMETHODIMP
482 nsIdleService::RemoveIdleObserver(nsIObserver* aObserver, uint32_t aTimeInS)
485 NS_ENSURE_ARG_POINTER(aObserver);
486 NS_ENSURE_ARG(aTimeInS);
488 if (XRE_IsContentProcess()) {
489 dom::ContentChild* cpc = dom::ContentChild::GetSingleton();
490 cpc->RemoveIdleObserver(aObserver, aTimeInS);
491 return NS_OK;
494 IdleListener listener(aObserver, aTimeInS);
496 // Find the entry and remove it, if it was the last entry, we just let the
497 // existing timer run to completion (there might be a new registration in a
498 // little while.
499 IdleListenerComparator c;
500 nsTArray<IdleListener>::index_type listenerIndex = mArrayListeners.IndexOf(listener, 0, c);
501 if (listenerIndex != mArrayListeners.NoIndex) {
502 if (mArrayListeners.ElementAt(listenerIndex).isIdle)
503 mIdleObserverCount--;
504 mArrayListeners.RemoveElementAt(listenerIndex);
505 MOZ_LOG(sLog, LogLevel::Debug,
506 ("idleService: Remove observer %p (%d seconds), %d remain idle",
507 aObserver, aTimeInS, mIdleObserverCount));
508 #ifdef MOZ_WIDGET_ANDROID
509 __android_log_print(LOG_LEVEL, LOG_TAG,
510 "Remove observer %p (%d seconds), %d remain idle",
511 aObserver, aTimeInS, mIdleObserverCount);
512 #endif
513 return NS_OK;
516 // If we get here, we haven't removed anything:
517 MOZ_LOG(sLog, LogLevel::Warning,
518 ("idleService: Failed to remove idle observer %p (%d seconds)",
519 aObserver, aTimeInS));
520 #ifdef MOZ_WIDGET_ANDROID
521 __android_log_print(LOG_LEVEL, LOG_TAG,
522 "Failed to remove idle observer %p (%d seconds)",
523 aObserver, aTimeInS);
524 #endif
525 return NS_ERROR_FAILURE;
528 NS_IMETHODIMP
529 nsIdleService::ResetIdleTimeOut(uint32_t idleDeltaInMS)
531 MOZ_LOG(sLog, LogLevel::Debug,
532 ("idleService: Reset idle timeout (last interaction %u msec)",
533 idleDeltaInMS));
535 // Store the time
536 mLastUserInteraction = TimeStamp::Now() -
537 TimeDuration::FromMilliseconds(idleDeltaInMS);
539 // If no one is idle, then we are done, any existing timers can keep running.
540 if (mIdleObserverCount == 0) {
541 MOZ_LOG(sLog, LogLevel::Debug,
542 ("idleService: Reset idle timeout: no idle observers"));
543 return NS_OK;
546 // Mark all idle services as non-idle, and calculate the next idle timeout.
547 nsCOMArray<nsIObserver> notifyList;
548 mDeltaToNextIdleSwitchInS = UINT32_MAX;
550 // Loop through all listeners, and find any that have detected idle.
551 for (uint32_t i = 0; i < mArrayListeners.Length(); i++) {
552 IdleListener& curListener = mArrayListeners.ElementAt(i);
554 // If the listener was idle, then he shouldn't be any longer.
555 if (curListener.isIdle) {
556 notifyList.AppendObject(curListener.observer);
557 curListener.isIdle = false;
560 // Check if the listener is the next one to timeout.
561 mDeltaToNextIdleSwitchInS = std::min(mDeltaToNextIdleSwitchInS,
562 curListener.reqIdleTime);
565 // When we are done, then we wont have anyone idle.
566 mIdleObserverCount = 0;
568 // Restart the idle timer, and do so before anyone can delay us.
569 ReconfigureTimer();
571 int32_t numberOfPendingNotifications = notifyList.Count();
573 // Bail if nothing to do.
574 if (!numberOfPendingNotifications) {
575 return NS_OK;
578 // Now send "active" events to all, if any should have timed out already,
579 // then they will be reawaken by the timer that is already running.
581 // We need a text string to send with any state change events.
582 nsAutoString timeStr;
584 timeStr.AppendInt((int32_t)(idleDeltaInMS / PR_MSEC_PER_SEC));
586 // Send the "non-idle" events.
587 while (numberOfPendingNotifications--) {
588 MOZ_LOG(sLog, LogLevel::Debug,
589 ("idleService: Reset idle timeout: tell observer %p user is back",
590 notifyList[numberOfPendingNotifications]));
591 #ifdef MOZ_WIDGET_ANDROID
592 __android_log_print(LOG_LEVEL, LOG_TAG,
593 "Reset idle timeout: tell observer %p user is back",
594 notifyList[numberOfPendingNotifications]);
595 #endif
596 notifyList[numberOfPendingNotifications]->Observe(this,
597 OBSERVER_TOPIC_ACTIVE,
598 timeStr.get());
600 return NS_OK;
603 NS_IMETHODIMP
604 nsIdleService::GetIdleTime(uint32_t* idleTime)
606 // Check sanity of in parameter.
607 if (!idleTime) {
608 return NS_ERROR_NULL_POINTER;
611 // Polled idle time in ms.
612 uint32_t polledIdleTimeMS;
614 bool polledIdleTimeIsValid = PollIdleTime(&polledIdleTimeMS);
616 MOZ_LOG(sLog, LogLevel::Debug,
617 ("idleService: Get idle time: polled %u msec, valid = %d",
618 polledIdleTimeMS, polledIdleTimeIsValid));
620 // timeSinceReset is in milliseconds.
621 TimeDuration timeSinceReset = TimeStamp::Now() - mLastUserInteraction;
622 uint32_t timeSinceResetInMS = timeSinceReset.ToMilliseconds();
624 MOZ_LOG(sLog, LogLevel::Debug,
625 ("idleService: Get idle time: time since reset %u msec",
626 timeSinceResetInMS));
627 #ifdef MOZ_WIDGET_ANDROID
628 __android_log_print(LOG_LEVEL, LOG_TAG,
629 "Get idle time: time since reset %u msec",
630 timeSinceResetInMS);
631 #endif
633 // If we did't get pulled data, return the time since last idle reset.
634 if (!polledIdleTimeIsValid) {
635 // We need to convert to ms before returning the time.
636 *idleTime = timeSinceResetInMS;
637 return NS_OK;
640 // Otherwise return the shortest time detected (in ms).
641 *idleTime = std::min(timeSinceResetInMS, polledIdleTimeMS);
643 return NS_OK;
647 bool
648 nsIdleService::PollIdleTime(uint32_t* /*aIdleTime*/)
650 // Default behavior is not to have the ability to poll an idle time.
651 return false;
654 bool
655 nsIdleService::UsePollMode()
657 uint32_t dummy;
658 return PollIdleTime(&dummy);
661 void
662 nsIdleService::StaticIdleTimerCallback(nsITimer* aTimer, void* aClosure)
664 static_cast<nsIdleService*>(aClosure)->IdleTimerCallback();
667 void
668 nsIdleService::IdleTimerCallback(void)
670 // Remember that we no longer have a timer running.
671 mCurrentlySetToTimeoutAt = TimeStamp();
673 // Find the last detected idle time.
674 uint32_t lastIdleTimeInMS = static_cast<uint32_t>((TimeStamp::Now() -
675 mLastUserInteraction).ToMilliseconds());
676 // Get the current idle time.
677 uint32_t currentIdleTimeInMS;
679 if (NS_FAILED(GetIdleTime(&currentIdleTimeInMS))) {
680 MOZ_LOG(sLog, LogLevel::Info,
681 ("idleService: Idle timer callback: failed to get idle time"));
682 #ifdef MOZ_WIDGET_ANDROID
683 __android_log_print(LOG_LEVEL, LOG_TAG,
684 "Idle timer callback: failed to get idle time");
685 #endif
686 return;
689 MOZ_LOG(sLog, LogLevel::Debug,
690 ("idleService: Idle timer callback: current idle time %u msec",
691 currentIdleTimeInMS));
692 #ifdef MOZ_WIDGET_ANDROID
693 __android_log_print(LOG_LEVEL, LOG_TAG,
694 "Idle timer callback: current idle time %u msec",
695 currentIdleTimeInMS);
696 #endif
698 // Check if we have had some user interaction we didn't handle previously
699 // we do the calculation in ms to lessen the chance for rounding errors to
700 // trigger wrong results.
701 if (lastIdleTimeInMS > currentIdleTimeInMS)
703 // We had user activity, so handle that part first (to ensure the listeners
704 // don't risk getting an non-idle after they get a new idle indication.
705 ResetIdleTimeOut(currentIdleTimeInMS);
707 // NOTE: We can't bail here, as we might have something already timed out.
710 // Find the idle time in S.
711 uint32_t currentIdleTimeInS = currentIdleTimeInMS / PR_MSEC_PER_SEC;
713 // Restart timer and bail if no-one are expected to be in idle
714 if (mDeltaToNextIdleSwitchInS > currentIdleTimeInS) {
715 // If we didn't expect anyone to be idle, then just re-start the timer.
716 ReconfigureTimer();
717 return;
720 // Tell expired listeners they are expired,and find the next timeout
721 Telemetry::AutoTimer<Telemetry::IDLE_NOTIFY_IDLE_MS> timer;
723 // We need to initialise the time to the next idle switch.
724 mDeltaToNextIdleSwitchInS = UINT32_MAX;
726 // Create list of observers that should be notified.
727 nsCOMArray<nsIObserver> notifyList;
729 for (uint32_t i = 0; i < mArrayListeners.Length(); i++) {
730 IdleListener& curListener = mArrayListeners.ElementAt(i);
732 // We are only interested in items, that are not in the idle state.
733 if (!curListener.isIdle) {
734 // If they have an idle time smaller than the actual idle time.
735 if (curListener.reqIdleTime <= currentIdleTimeInS) {
736 // Then add the listener to the list of listeners that should be
737 // notified.
738 notifyList.AppendObject(curListener.observer);
739 // This listener is now idle.
740 curListener.isIdle = true;
741 // Remember we have someone idle.
742 mIdleObserverCount++;
743 } else {
744 // Listeners that are not timed out yet are candidates for timing out.
745 mDeltaToNextIdleSwitchInS = std::min(mDeltaToNextIdleSwitchInS,
746 curListener.reqIdleTime);
751 // Restart the timer before any notifications that could slow us down are
752 // done.
753 ReconfigureTimer();
755 int32_t numberOfPendingNotifications = notifyList.Count();
757 // Bail if nothing to do.
758 if (!numberOfPendingNotifications) {
759 MOZ_LOG(sLog, LogLevel::Debug,
760 ("idleService: **** Idle timer callback: no observers to message."));
761 return;
764 // We need a text string to send with any state change events.
765 nsAutoString timeStr;
766 timeStr.AppendInt(currentIdleTimeInS);
768 // Notify all listeners that just timed out.
769 while (numberOfPendingNotifications--) {
770 MOZ_LOG(sLog, LogLevel::Debug,
771 ("idleService: **** Idle timer callback: tell observer %p user is idle",
772 notifyList[numberOfPendingNotifications]));
773 #ifdef MOZ_WIDGET_ANDROID
774 __android_log_print(LOG_LEVEL, LOG_TAG,
775 "Idle timer callback: tell observer %p user is idle",
776 notifyList[numberOfPendingNotifications]);
777 #endif
778 notifyList[numberOfPendingNotifications]->Observe(this,
779 OBSERVER_TOPIC_IDLE,
780 timeStr.get());
784 void
785 nsIdleService::SetTimerExpiryIfBefore(TimeStamp aNextTimeout)
787 TimeDuration nextTimeoutDuration = aNextTimeout - TimeStamp::Now();
789 MOZ_LOG(sLog, LogLevel::Debug,
790 ("idleService: SetTimerExpiryIfBefore: next timeout %0.f msec from now",
791 nextTimeoutDuration.ToMilliseconds()));
793 #ifdef MOZ_WIDGET_ANDROID
794 __android_log_print(LOG_LEVEL, LOG_TAG,
795 "SetTimerExpiryIfBefore: next timeout %0.f msec from now",
796 nextTimeoutDuration.ToMilliseconds());
797 #endif
799 // Bail if we don't have a timer service.
800 if (!mTimer) {
801 return;
804 // If the new timeout is before the old one or we don't have a timer running,
805 // then restart the timer.
806 if (mCurrentlySetToTimeoutAt.IsNull() ||
807 mCurrentlySetToTimeoutAt > aNextTimeout) {
809 mCurrentlySetToTimeoutAt = aNextTimeout;
811 // Stop the current timer (it's ok to try'n stop it, even it isn't running).
812 mTimer->Cancel();
814 // Check that the timeout is actually in the future, otherwise make it so.
815 TimeStamp currentTime = TimeStamp::Now();
816 if (currentTime > mCurrentlySetToTimeoutAt) {
817 mCurrentlySetToTimeoutAt = currentTime;
820 // Add 10 ms to ensure we don't undershoot, and never get a "0" timer.
821 mCurrentlySetToTimeoutAt += TimeDuration::FromMilliseconds(10);
823 TimeDuration deltaTime = mCurrentlySetToTimeoutAt - currentTime;
824 MOZ_LOG(sLog, LogLevel::Debug,
825 ("idleService: IdleService reset timer expiry to %0.f msec from now",
826 deltaTime.ToMilliseconds()));
827 #ifdef MOZ_WIDGET_ANDROID
828 __android_log_print(LOG_LEVEL, LOG_TAG,
829 "reset timer expiry to %0.f msec from now",
830 deltaTime.ToMilliseconds());
831 #endif
833 // Start the timer
834 mTimer->InitWithNamedFuncCallback(StaticIdleTimerCallback,
835 this,
836 deltaTime.ToMilliseconds(),
837 nsITimer::TYPE_ONE_SHOT,
838 "nsIdleService::SetTimerExpiryIfBefore");
842 void
843 nsIdleService::ReconfigureTimer(void)
845 // Check if either someone is idle, or someone will become idle.
846 if ((mIdleObserverCount == 0) && UINT32_MAX == mDeltaToNextIdleSwitchInS) {
847 // If not, just let any existing timers run to completion
848 // And bail out.
849 MOZ_LOG(sLog, LogLevel::Debug,
850 ("idleService: ReconfigureTimer: no idle or waiting observers"));
851 #ifdef MOZ_WIDGET_ANDROID
852 __android_log_print(LOG_LEVEL, LOG_TAG,
853 "ReconfigureTimer: no idle or waiting observers");
854 #endif
855 return;
858 // Find the next timeout value, assuming we are not polling.
860 // We need to store the current time, so we don't get artifacts from the time
861 // ticking while we are processing.
862 TimeStamp curTime = TimeStamp::Now();
864 TimeStamp nextTimeoutAt = mLastUserInteraction +
865 TimeDuration::FromSeconds(mDeltaToNextIdleSwitchInS);
867 TimeDuration nextTimeoutDuration = nextTimeoutAt - curTime;
869 MOZ_LOG(sLog, LogLevel::Debug,
870 ("idleService: next timeout %0.f msec from now",
871 nextTimeoutDuration.ToMilliseconds()));
873 #ifdef MOZ_WIDGET_ANDROID
874 __android_log_print(LOG_LEVEL, LOG_TAG,
875 "next timeout %0.f msec from now",
876 nextTimeoutDuration.ToMilliseconds());
877 #endif
879 // Check if we should correct the timeout time because we should poll before.
880 if ((mIdleObserverCount > 0) && UsePollMode()) {
881 TimeStamp pollTimeout =
882 curTime + TimeDuration::FromMilliseconds(MIN_IDLE_POLL_INTERVAL_MSEC);
884 if (nextTimeoutAt > pollTimeout) {
885 MOZ_LOG(sLog, LogLevel::Debug,
886 ("idleService: idle observers, reducing timeout to %lu msec from now",
887 MIN_IDLE_POLL_INTERVAL_MSEC));
888 #ifdef MOZ_WIDGET_ANDROID
889 __android_log_print(LOG_LEVEL, LOG_TAG,
890 "idle observers, reducing timeout to %lu msec from now",
891 MIN_IDLE_POLL_INTERVAL_MSEC);
892 #endif
893 nextTimeoutAt = pollTimeout;
897 SetTimerExpiryIfBefore(nextTimeoutAt);