Bug 1649121: part 26) Move `CollectTopMostChildContentsCompletelyInRange`. r=masayuki
[gecko.git] / widget / nsIdleService.cpp
blob25329c59ba6fbe1a77240a3cedbaffff963a37e9
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 "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 // interval in milliseconds between internal idle time requests.
30 #define MIN_IDLE_POLL_INTERVAL_MSEC (5 * PR_MSEC_PER_SEC) /* 5 sec */
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
34 // event.
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 {
55 public:
56 bool Equals(IdleListener a, IdleListener b) const {
57 return (a.observer == b.observer) && (a.reqIdleTime == b.reqIdleTime);
61 ////////////////////////////////////////////////////////////////////////////////
62 //// nsIdleServiceDaily
64 NS_IMPL_ISUPPORTS(nsIdleServiceDaily, nsIObserver, nsISupportsWeakReference)
66 NS_IMETHODIMP
67 nsIdleServiceDaily::Observe(nsISupports*, const char* aTopic, const char16_t*) {
68 MOZ_LOG(
69 sLog, LogLevel::Debug,
70 ("nsIdleServiceDaily: Observe '%s' (%d)", aTopic, mShutdownInProgress));
72 if (strcmp(aTopic, "profile-after-change") == 0) {
73 // We are back. Start sending notifications again.
74 mShutdownInProgress = false;
75 return NS_OK;
78 if (strcmp(aTopic, "xpcom-will-shutdown") == 0 ||
79 strcmp(aTopic, "profile-change-teardown") == 0) {
80 mShutdownInProgress = true;
83 if (mShutdownInProgress || strcmp(aTopic, OBSERVER_TOPIC_ACTIVE) == 0) {
84 return NS_OK;
86 MOZ_ASSERT(strcmp(aTopic, OBSERVER_TOPIC_IDLE) == 0);
88 MOZ_LOG(sLog, LogLevel::Debug,
89 ("nsIdleServiceDaily: Notifying idle-daily observers"));
90 #ifdef MOZ_WIDGET_ANDROID
91 __android_log_print(LOG_LEVEL, LOG_TAG, "Notifying idle-daily observers");
92 #endif
94 // Send the idle-daily observer event
95 nsCOMPtr<nsIObserverService> observerService =
96 mozilla::services::GetObserverService();
97 NS_ENSURE_STATE(observerService);
98 (void)observerService->NotifyObservers(nullptr, OBSERVER_TOPIC_IDLE_DAILY,
99 nullptr);
101 // Notify the category observers.
102 nsCOMArray<nsIObserver> entries;
103 mCategoryObservers.GetEntries(entries);
104 for (int32_t i = 0; i < entries.Count(); ++i) {
105 (void)entries[i]->Observe(nullptr, OBSERVER_TOPIC_IDLE_DAILY, nullptr);
108 // Stop observing idle for today.
109 (void)mIdleService->RemoveIdleObserver(this, mIdleDailyTriggerWait);
111 // Set the last idle-daily time pref.
112 int32_t nowSec = static_cast<int32_t>(PR_Now() / PR_USEC_PER_SEC);
113 Preferences::SetInt(PREF_LAST_DAILY, nowSec);
115 // Force that to be stored so we don't retrigger twice a day under
116 // any circumstances.
117 nsIPrefService* prefs = Preferences::GetService();
118 if (prefs) {
119 prefs->SavePrefFile(nullptr);
122 MOZ_LOG(sLog, LogLevel::Debug,
123 ("nsIdleServiceDaily: Storing last idle time as %d sec.", nowSec));
124 #ifdef MOZ_WIDGET_ANDROID
125 __android_log_print(LOG_LEVEL, LOG_TAG, "Storing last idle time as %d",
126 nowSec);
127 #endif
129 // Note the moment we expect to get the next timer callback
130 mExpectedTriggerTime =
131 PR_Now() + ((PRTime)SECONDS_PER_DAY * (PRTime)PR_USEC_PER_SEC);
133 MOZ_LOG(sLog, LogLevel::Debug,
134 ("nsIdleServiceDaily: Restarting daily timer"));
136 // Start timer for the next check in one day.
137 (void)mTimer->InitWithNamedFuncCallback(
138 DailyCallback, this, SECONDS_PER_DAY * PR_MSEC_PER_SEC,
139 nsITimer::TYPE_ONE_SHOT, "nsIdleServiceDaily::Observe");
141 return NS_OK;
144 nsIdleServiceDaily::nsIdleServiceDaily(nsIIdleService* aIdleService)
145 : mIdleService(aIdleService),
146 mTimer(NS_NewTimer()),
147 mCategoryObservers(OBSERVER_TOPIC_IDLE_DAILY),
148 mShutdownInProgress(false),
149 mExpectedTriggerTime(0),
150 mIdleDailyTriggerWait(DAILY_SIGNIFICANT_IDLE_SERVICE_SEC) {}
152 void nsIdleServiceDaily::Init() {
153 // First check the time of the last idle-daily event notification. If it
154 // has been 24 hours or higher, or if we have never sent an idle-daily,
155 // get ready to send an idle-daily event. Otherwise set a timer targeted
156 // at 24 hours past the last idle-daily we sent.
158 int32_t lastDaily = Preferences::GetInt(PREF_LAST_DAILY, 0);
159 // Setting the pref to -1 allows to disable idle-daily, and it's particularly
160 // useful in tests. Normally there should be no need for the user to set
161 // this value.
162 if (lastDaily == -1) {
163 MOZ_LOG(sLog, LogLevel::Debug,
164 ("nsIdleServiceDaily: Init: disabled idle-daily"));
165 return;
168 int32_t nowSec = static_cast<int32_t>(PR_Now() / PR_USEC_PER_SEC);
169 if (lastDaily < 0 || lastDaily > nowSec) {
170 // The time is bogus, use default.
171 lastDaily = 0;
173 int32_t secondsSinceLastDaily = nowSec - lastDaily;
175 MOZ_LOG(sLog, LogLevel::Debug,
176 ("nsIdleServiceDaily: Init: seconds since last daily: %d",
177 secondsSinceLastDaily));
179 // If it has been twenty four hours or more or if we have never sent an
180 // idle-daily event get ready to send it during the next idle period.
181 if (secondsSinceLastDaily > SECONDS_PER_DAY) {
182 // Check for a "long wait", e.g. 48-hours or more.
183 bool hasBeenLongWait =
184 (lastDaily && (secondsSinceLastDaily > (SECONDS_PER_DAY * 2)));
186 MOZ_LOG(sLog, LogLevel::Debug,
187 ("nsIdleServiceDaily: 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 ("nsIdleServiceDaily: 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 ("nsIdleServiceDaily: 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 "nsIdleServiceDaily::Init");
219 // Register for when we should terminate/pause
220 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
221 if (obs) {
222 MOZ_LOG(sLog, LogLevel::Debug,
223 ("nsIdleServiceDaily: Registering for system event observers."));
224 obs->AddObserver(this, "xpcom-will-shutdown", true);
225 obs->AddObserver(this, "profile-change-teardown", true);
226 obs->AddObserver(this, "profile-after-change", true);
230 nsIdleServiceDaily::~nsIdleServiceDaily() {
231 if (mTimer) {
232 mTimer->Cancel();
233 mTimer = nullptr;
237 void nsIdleServiceDaily::StageIdleDaily(bool aHasBeenLongWait) {
238 NS_ASSERTION(mIdleService, "No idle service available?");
239 MOZ_LOG(sLog, LogLevel::Debug,
240 ("nsIdleServiceDaily: Registering Idle observer callback "
241 "(short wait requested? %d)",
242 aHasBeenLongWait));
243 #ifdef MOZ_WIDGET_ANDROID
244 __android_log_print(LOG_LEVEL, LOG_TAG, "Registering Idle observer callback");
245 #endif
246 mIdleDailyTriggerWait =
247 (aHasBeenLongWait ? DAILY_SHORTENED_IDLE_SERVICE_SEC
248 : DAILY_SIGNIFICANT_IDLE_SERVICE_SEC);
249 (void)mIdleService->AddIdleObserver(this, mIdleDailyTriggerWait);
252 // static
253 void nsIdleServiceDaily::DailyCallback(nsITimer* aTimer, void* aClosure) {
254 MOZ_LOG(sLog, LogLevel::Debug, ("nsIdleServiceDaily: DailyCallback running"));
255 #ifdef MOZ_WIDGET_ANDROID
256 __android_log_print(LOG_LEVEL, LOG_TAG, "DailyCallback running");
257 #endif
259 nsIdleServiceDaily* self = static_cast<nsIdleServiceDaily*>(aClosure);
261 // Check to be sure the timer didn't fire early. This currently only
262 // happens on android.
263 PRTime now = PR_Now();
264 if (self->mExpectedTriggerTime && now < self->mExpectedTriggerTime) {
265 // Timer returned early, reschedule to the appropriate time.
266 PRTime delayTime = self->mExpectedTriggerTime - now;
268 // Add 10 ms to ensure we don't undershoot, and never get a "0" timer.
269 delayTime += 10 * PR_USEC_PER_MSEC;
271 MOZ_LOG(sLog, LogLevel::Debug,
272 ("nsIdleServiceDaily: DailyCallback resetting timer to %" PRId64
273 " msec",
274 delayTime / PR_USEC_PER_MSEC));
275 #ifdef MOZ_WIDGET_ANDROID
276 __android_log_print(LOG_LEVEL, LOG_TAG,
277 "DailyCallback resetting timer to %" PRId64 " msec",
278 delayTime / PR_USEC_PER_MSEC);
279 #endif
281 (void)self->mTimer->InitWithNamedFuncCallback(
282 DailyCallback, self, delayTime / PR_USEC_PER_MSEC,
283 nsITimer::TYPE_ONE_SHOT, "nsIdleServiceDaily::DailyCallback");
284 return;
287 // Register for a short term wait for idle event. When this fires we fire
288 // our idle-daily event.
289 self->StageIdleDaily(false);
293 * The idle services goal is to notify subscribers when a certain time has
294 * passed since the last user interaction with the system.
296 * On some platforms this is defined as the last time user events reached this
297 * application, on other platforms it is a system wide thing - the preferred
298 * implementation is to use the system idle time, rather than the application
299 * idle time, as the things depending on the idle service are likely to use
300 * significant resources (network, disk, memory, cpu, etc.).
302 * When the idle service needs to use the system wide idle timer, it typically
303 * needs to poll the idle time value by the means of a timer. It needs to
304 * poll fast when it is in active idle mode (when it has a listener in the idle
305 * mode) as it needs to detect if the user is active in other applications.
307 * When the service is waiting for the first listener to become idle, or when
308 * it is only monitoring application idle time, it only needs to have the timer
309 * expire at the time the next listener goes idle.
311 * The core state of the service is determined by:
313 * - A list of listeners.
315 * - A boolean that tells if any listeners are in idle mode.
317 * - A delta value that indicates when, measured from the last non-idle time,
318 * the next listener should switch to idle mode.
320 * - An absolute time of the last time idle mode was detected (this is used to
321 * judge if we have been out of idle mode since the last invocation of the
322 * service.
324 * There are four entry points into the system:
326 * - A new listener is registered.
328 * - An existing listener is deregistered.
330 * - User interaction is detected.
332 * - The timer expires.
334 * When a new listener is added its idle timeout, is compared with the next idle
335 * timeout, and if lower, that time is stored as the new timeout, and the timer
336 * is reconfigured to ensure a timeout around the time the new listener should
337 * timeout.
339 * If the next idle time is above the idle time requested by the new listener
340 * it won't be informed until the timer expires, this is to avoid recursive
341 * behavior and to simplify the code. In this case the timer will be set to
342 * about 10 ms.
344 * When an existing listener is deregistered, it is just removed from the list
345 * of active listeners, we don't stop the timer, we just let it expire.
347 * When user interaction is detected, either because it was directly detected or
348 * because we polled the system timer and found it to be unexpected low, then we
349 * check the flag that tells us if any listeners are in idle mode, if there are
350 * they are removed from idle mode and told so, and we reset our state
351 * caculating the next timeout and restart the timer if needed.
353 * ---- Build in logic
355 * In order to avoid restarting the timer endlessly, the timer function has
356 * logic that will only restart the timer, if the requested timeout is before
357 * the current timeout.
361 ////////////////////////////////////////////////////////////////////////////////
362 //// nsIdleService
364 namespace {
365 nsIdleService* gIdleService;
366 } // namespace
368 already_AddRefed<nsIdleService> nsIdleService::GetInstance() {
369 RefPtr<nsIdleService> instance(gIdleService);
370 return instance.forget();
373 nsIdleService::nsIdleService()
374 : mCurrentlySetToTimeoutAt(TimeStamp()),
375 mIdleObserverCount(0),
376 mDeltaToNextIdleSwitchInS(UINT32_MAX),
377 mLastUserInteraction(TimeStamp::Now()) {
378 MOZ_ASSERT(!gIdleService);
379 gIdleService = this;
380 if (XRE_IsParentProcess()) {
381 mDailyIdle = new nsIdleServiceDaily(this);
382 mDailyIdle->Init();
386 nsIdleService::~nsIdleService() {
387 if (mTimer) {
388 mTimer->Cancel();
391 MOZ_ASSERT(gIdleService == this);
392 gIdleService = nullptr;
395 NS_IMPL_ISUPPORTS(nsIdleService, nsIIdleService, nsIIdleServiceInternal)
397 NS_IMETHODIMP
398 nsIdleService::AddIdleObserver(nsIObserver* aObserver, uint32_t aIdleTimeInS) {
399 NS_ENSURE_ARG_POINTER(aObserver);
400 // We don't accept idle time at 0, and we can't handle idle time that are too
401 // high either - no more than ~136 years.
402 NS_ENSURE_ARG_RANGE(aIdleTimeInS, 1, (UINT32_MAX / 10) - 1);
404 if (XRE_IsContentProcess()) {
405 dom::ContentChild* cpc = dom::ContentChild::GetSingleton();
406 cpc->AddIdleObserver(aObserver, aIdleTimeInS);
407 return NS_OK;
410 MOZ_LOG(sLog, LogLevel::Debug,
411 ("idleService: Register idle observer %p for %d seconds", aObserver,
412 aIdleTimeInS));
413 #ifdef MOZ_WIDGET_ANDROID
414 __android_log_print(LOG_LEVEL, LOG_TAG,
415 "Register idle observer %p for %d seconds", aObserver,
416 aIdleTimeInS);
417 #endif
419 // Put the time + observer in a struct we can keep:
420 IdleListener listener(aObserver, aIdleTimeInS);
422 // XXX(Bug 1631371) Check if this should use a fallible operation as it
423 // pretended earlier.
424 mArrayListeners.AppendElement(listener);
426 // Create our timer callback if it's not there already.
427 if (!mTimer) {
428 mTimer = NS_NewTimer();
429 NS_ENSURE_TRUE(mTimer, NS_ERROR_OUT_OF_MEMORY);
432 // Check if the newly added observer has a smaller wait time than what we
433 // are waiting for now.
434 if (mDeltaToNextIdleSwitchInS > aIdleTimeInS) {
435 // If it is, then this is the next to move to idle (at this point we
436 // don't care if it should have switched already).
437 MOZ_LOG(
438 sLog, LogLevel::Debug,
439 ("idleService: Register: adjusting next switch from %d to %d seconds",
440 mDeltaToNextIdleSwitchInS, aIdleTimeInS));
441 #ifdef MOZ_WIDGET_ANDROID
442 __android_log_print(LOG_LEVEL, LOG_TAG,
443 "Register: adjusting next switch from %d to %d seconds",
444 mDeltaToNextIdleSwitchInS, aIdleTimeInS);
445 #endif
447 mDeltaToNextIdleSwitchInS = aIdleTimeInS;
450 // Ensure timer is running.
451 ReconfigureTimer();
453 return NS_OK;
456 NS_IMETHODIMP
457 nsIdleService::RemoveIdleObserver(nsIObserver* aObserver, uint32_t aTimeInS) {
458 NS_ENSURE_ARG_POINTER(aObserver);
459 NS_ENSURE_ARG(aTimeInS);
461 if (XRE_IsContentProcess()) {
462 dom::ContentChild* cpc = dom::ContentChild::GetSingleton();
463 cpc->RemoveIdleObserver(aObserver, aTimeInS);
464 return NS_OK;
467 IdleListener listener(aObserver, aTimeInS);
469 // Find the entry and remove it, if it was the last entry, we just let the
470 // existing timer run to completion (there might be a new registration in a
471 // little while.
472 IdleListenerComparator c;
473 nsTArray<IdleListener>::index_type listenerIndex =
474 mArrayListeners.IndexOf(listener, 0, c);
475 if (listenerIndex != mArrayListeners.NoIndex) {
476 if (mArrayListeners.ElementAt(listenerIndex).isIdle) mIdleObserverCount--;
477 mArrayListeners.RemoveElementAt(listenerIndex);
478 MOZ_LOG(sLog, LogLevel::Debug,
479 ("idleService: Remove observer %p (%d seconds), %d remain idle",
480 aObserver, aTimeInS, mIdleObserverCount));
481 #ifdef MOZ_WIDGET_ANDROID
482 __android_log_print(LOG_LEVEL, LOG_TAG,
483 "Remove observer %p (%d seconds), %d remain idle",
484 aObserver, aTimeInS, mIdleObserverCount);
485 #endif
486 return NS_OK;
489 // If we get here, we haven't removed anything:
490 MOZ_LOG(sLog, LogLevel::Warning,
491 ("idleService: Failed to remove idle observer %p (%d seconds)",
492 aObserver, aTimeInS));
493 #ifdef MOZ_WIDGET_ANDROID
494 __android_log_print(LOG_LEVEL, LOG_TAG,
495 "Failed to remove idle observer %p (%d seconds)",
496 aObserver, aTimeInS);
497 #endif
498 return NS_ERROR_FAILURE;
501 NS_IMETHODIMP
502 nsIdleService::ResetIdleTimeOut(uint32_t idleDeltaInMS) {
503 MOZ_LOG(sLog, LogLevel::Debug,
504 ("idleService: Reset idle timeout (last interaction %u msec)",
505 idleDeltaInMS));
507 // Store the time
508 mLastUserInteraction =
509 TimeStamp::Now() - TimeDuration::FromMilliseconds(idleDeltaInMS);
511 // If no one is idle, then we are done, any existing timers can keep running.
512 if (mIdleObserverCount == 0) {
513 MOZ_LOG(sLog, LogLevel::Debug,
514 ("idleService: Reset idle timeout: no idle observers"));
515 return NS_OK;
518 // Mark all idle services as non-idle, and calculate the next idle timeout.
519 nsCOMArray<nsIObserver> notifyList;
520 mDeltaToNextIdleSwitchInS = UINT32_MAX;
522 // Loop through all listeners, and find any that have detected idle.
523 for (uint32_t i = 0; i < mArrayListeners.Length(); i++) {
524 IdleListener& curListener = mArrayListeners.ElementAt(i);
526 // If the listener was idle, then he shouldn't be any longer.
527 if (curListener.isIdle) {
528 notifyList.AppendObject(curListener.observer);
529 curListener.isIdle = false;
532 // Check if the listener is the next one to timeout.
533 mDeltaToNextIdleSwitchInS =
534 std::min(mDeltaToNextIdleSwitchInS, curListener.reqIdleTime);
537 // When we are done, then we wont have anyone idle.
538 mIdleObserverCount = 0;
540 // Restart the idle timer, and do so before anyone can delay us.
541 ReconfigureTimer();
543 int32_t numberOfPendingNotifications = notifyList.Count();
545 // Bail if nothing to do.
546 if (!numberOfPendingNotifications) {
547 return NS_OK;
550 // Now send "active" events to all, if any should have timed out already,
551 // then they will be reawaken by the timer that is already running.
553 // We need a text string to send with any state change events.
554 nsAutoString timeStr;
556 timeStr.AppendInt((int32_t)(idleDeltaInMS / PR_MSEC_PER_SEC));
558 // Send the "non-idle" events.
559 while (numberOfPendingNotifications--) {
560 MOZ_LOG(sLog, LogLevel::Debug,
561 ("idleService: Reset idle timeout: tell observer %p user is back",
562 notifyList[numberOfPendingNotifications]));
563 #ifdef MOZ_WIDGET_ANDROID
564 __android_log_print(LOG_LEVEL, LOG_TAG,
565 "Reset idle timeout: tell observer %p user is back",
566 notifyList[numberOfPendingNotifications]);
567 #endif
568 notifyList[numberOfPendingNotifications]->Observe(
569 this, OBSERVER_TOPIC_ACTIVE, timeStr.get());
571 return NS_OK;
574 NS_IMETHODIMP
575 nsIdleService::GetIdleTime(uint32_t* idleTime) {
576 // Check sanity of in parameter.
577 if (!idleTime) {
578 return NS_ERROR_NULL_POINTER;
581 // Polled idle time in ms.
582 uint32_t polledIdleTimeMS;
584 bool polledIdleTimeIsValid = PollIdleTime(&polledIdleTimeMS);
586 MOZ_LOG(sLog, LogLevel::Debug,
587 ("idleService: Get idle time: polled %u msec, valid = %d",
588 polledIdleTimeMS, polledIdleTimeIsValid));
590 // timeSinceReset is in milliseconds.
591 TimeDuration timeSinceReset = TimeStamp::Now() - mLastUserInteraction;
592 uint32_t timeSinceResetInMS = timeSinceReset.ToMilliseconds();
594 MOZ_LOG(sLog, LogLevel::Debug,
595 ("idleService: Get idle time: time since reset %u msec",
596 timeSinceResetInMS));
597 #ifdef MOZ_WIDGET_ANDROID
598 __android_log_print(LOG_LEVEL, LOG_TAG,
599 "Get idle time: time since reset %u msec",
600 timeSinceResetInMS);
601 #endif
603 // If we did't get pulled data, return the time since last idle reset.
604 if (!polledIdleTimeIsValid) {
605 // We need to convert to ms before returning the time.
606 *idleTime = timeSinceResetInMS;
607 return NS_OK;
610 // Otherwise return the shortest time detected (in ms).
611 *idleTime = std::min(timeSinceResetInMS, polledIdleTimeMS);
613 return NS_OK;
616 bool nsIdleService::PollIdleTime(uint32_t* /*aIdleTime*/) {
617 // Default behavior is not to have the ability to poll an idle time.
618 return false;
621 bool nsIdleService::UsePollMode() {
622 uint32_t dummy;
623 return PollIdleTime(&dummy);
626 nsresult nsIdleService::GetDisabled(bool* aResult) {
627 *aResult = mDisabled;
628 return NS_OK;
631 nsresult nsIdleService::SetDisabled(bool aDisabled) {
632 mDisabled = aDisabled;
633 return NS_OK;
636 void nsIdleService::StaticIdleTimerCallback(nsITimer* aTimer, void* aClosure) {
637 static_cast<nsIdleService*>(aClosure)->IdleTimerCallback();
640 void nsIdleService::IdleTimerCallback(void) {
641 // Remember that we no longer have a timer running.
642 mCurrentlySetToTimeoutAt = TimeStamp();
644 // Find the last detected idle time.
645 uint32_t lastIdleTimeInMS = static_cast<uint32_t>(
646 (TimeStamp::Now() - mLastUserInteraction).ToMilliseconds());
647 // Get the current idle time.
648 uint32_t currentIdleTimeInMS;
650 if (NS_FAILED(GetIdleTime(&currentIdleTimeInMS))) {
651 MOZ_LOG(sLog, LogLevel::Info,
652 ("idleService: Idle timer callback: failed to get idle time"));
653 #ifdef MOZ_WIDGET_ANDROID
654 __android_log_print(LOG_LEVEL, LOG_TAG,
655 "Idle timer callback: failed to get idle time");
656 #endif
657 return;
660 MOZ_LOG(sLog, LogLevel::Debug,
661 ("idleService: Idle timer callback: current idle time %u msec",
662 currentIdleTimeInMS));
663 #ifdef MOZ_WIDGET_ANDROID
664 __android_log_print(LOG_LEVEL, LOG_TAG,
665 "Idle timer callback: current idle time %u msec",
666 currentIdleTimeInMS);
667 #endif
669 // Check if we have had some user interaction we didn't handle previously
670 // we do the calculation in ms to lessen the chance for rounding errors to
671 // trigger wrong results.
672 if (lastIdleTimeInMS > currentIdleTimeInMS) {
673 // We had user activity, so handle that part first (to ensure the listeners
674 // don't risk getting an non-idle after they get a new idle indication.
675 ResetIdleTimeOut(currentIdleTimeInMS);
677 // NOTE: We can't bail here, as we might have something already timed out.
680 // Find the idle time in S.
681 uint32_t currentIdleTimeInS = currentIdleTimeInMS / PR_MSEC_PER_SEC;
683 // Restart timer and bail if no-one are expected to be in idle
684 if (mDeltaToNextIdleSwitchInS > currentIdleTimeInS) {
685 // If we didn't expect anyone to be idle, then just re-start the timer.
686 ReconfigureTimer();
687 return;
690 if (mDisabled) {
691 MOZ_LOG(sLog, LogLevel::Info,
692 ("idleService: Skipping idle callback while disabled"));
694 ReconfigureTimer();
695 return;
698 // Tell expired listeners they are expired,and find the next timeout
699 Telemetry::AutoTimer<Telemetry::IDLE_NOTIFY_IDLE_MS> timer;
701 // We need to initialise the time to the next idle switch.
702 mDeltaToNextIdleSwitchInS = UINT32_MAX;
704 // Create list of observers that should be notified.
705 nsCOMArray<nsIObserver> notifyList;
707 for (uint32_t i = 0; i < mArrayListeners.Length(); i++) {
708 IdleListener& curListener = mArrayListeners.ElementAt(i);
710 // We are only interested in items, that are not in the idle state.
711 if (!curListener.isIdle) {
712 // If they have an idle time smaller than the actual idle time.
713 if (curListener.reqIdleTime <= currentIdleTimeInS) {
714 // Then add the listener to the list of listeners that should be
715 // notified.
716 notifyList.AppendObject(curListener.observer);
717 // This listener is now idle.
718 curListener.isIdle = true;
719 // Remember we have someone idle.
720 mIdleObserverCount++;
721 } else {
722 // Listeners that are not timed out yet are candidates for timing out.
723 mDeltaToNextIdleSwitchInS =
724 std::min(mDeltaToNextIdleSwitchInS, curListener.reqIdleTime);
729 // Restart the timer before any notifications that could slow us down are
730 // done.
731 ReconfigureTimer();
733 int32_t numberOfPendingNotifications = notifyList.Count();
735 // Bail if nothing to do.
736 if (!numberOfPendingNotifications) {
737 MOZ_LOG(
738 sLog, LogLevel::Debug,
739 ("idleService: **** Idle timer callback: no observers to message."));
740 return;
743 // We need a text string to send with any state change events.
744 nsAutoString timeStr;
745 timeStr.AppendInt(currentIdleTimeInS);
747 // Notify all listeners that just timed out.
748 while (numberOfPendingNotifications--) {
749 MOZ_LOG(
750 sLog, LogLevel::Debug,
751 ("idleService: **** Idle timer callback: tell observer %p user is idle",
752 notifyList[numberOfPendingNotifications]));
753 #ifdef MOZ_WIDGET_ANDROID
754 __android_log_print(LOG_LEVEL, LOG_TAG,
755 "Idle timer callback: tell observer %p user is idle",
756 notifyList[numberOfPendingNotifications]);
757 #endif
758 notifyList[numberOfPendingNotifications]->Observe(this, OBSERVER_TOPIC_IDLE,
759 timeStr.get());
763 void nsIdleService::SetTimerExpiryIfBefore(TimeStamp aNextTimeout) {
764 TimeDuration nextTimeoutDuration = aNextTimeout - TimeStamp::Now();
766 MOZ_LOG(
767 sLog, LogLevel::Debug,
768 ("idleService: SetTimerExpiryIfBefore: next timeout %0.f msec from now",
769 nextTimeoutDuration.ToMilliseconds()));
771 #ifdef MOZ_WIDGET_ANDROID
772 __android_log_print(LOG_LEVEL, LOG_TAG,
773 "SetTimerExpiryIfBefore: next timeout %0.f msec from now",
774 nextTimeoutDuration.ToMilliseconds());
775 #endif
777 // Bail if we don't have a timer service.
778 if (!mTimer) {
779 return;
782 // If the new timeout is before the old one or we don't have a timer running,
783 // then restart the timer.
784 if (mCurrentlySetToTimeoutAt.IsNull() ||
785 mCurrentlySetToTimeoutAt > aNextTimeout) {
786 mCurrentlySetToTimeoutAt = aNextTimeout;
788 // Stop the current timer (it's ok to try'n stop it, even it isn't running).
789 mTimer->Cancel();
791 // Check that the timeout is actually in the future, otherwise make it so.
792 TimeStamp currentTime = TimeStamp::Now();
793 if (currentTime > mCurrentlySetToTimeoutAt) {
794 mCurrentlySetToTimeoutAt = currentTime;
797 // Add 10 ms to ensure we don't undershoot, and never get a "0" timer.
798 mCurrentlySetToTimeoutAt += TimeDuration::FromMilliseconds(10);
800 TimeDuration deltaTime = mCurrentlySetToTimeoutAt - currentTime;
801 MOZ_LOG(
802 sLog, LogLevel::Debug,
803 ("idleService: IdleService reset timer expiry to %0.f msec from now",
804 deltaTime.ToMilliseconds()));
805 #ifdef MOZ_WIDGET_ANDROID
806 __android_log_print(LOG_LEVEL, LOG_TAG,
807 "reset timer expiry to %0.f msec from now",
808 deltaTime.ToMilliseconds());
809 #endif
811 // Start the timer
812 mTimer->InitWithNamedFuncCallback(
813 StaticIdleTimerCallback, this, deltaTime.ToMilliseconds(),
814 nsITimer::TYPE_ONE_SHOT, "nsIdleService::SetTimerExpiryIfBefore");
818 void nsIdleService::ReconfigureTimer(void) {
819 // Check if either someone is idle, or someone will become idle.
820 if ((mIdleObserverCount == 0) && UINT32_MAX == mDeltaToNextIdleSwitchInS) {
821 // If not, just let any existing timers run to completion
822 // And bail out.
823 MOZ_LOG(sLog, LogLevel::Debug,
824 ("idleService: ReconfigureTimer: no idle or waiting observers"));
825 #ifdef MOZ_WIDGET_ANDROID
826 __android_log_print(LOG_LEVEL, LOG_TAG,
827 "ReconfigureTimer: no idle or waiting observers");
828 #endif
829 return;
832 // Find the next timeout value, assuming we are not polling.
834 // We need to store the current time, so we don't get artifacts from the time
835 // ticking while we are processing.
836 TimeStamp curTime = TimeStamp::Now();
838 TimeStamp nextTimeoutAt =
839 mLastUserInteraction +
840 TimeDuration::FromSeconds(mDeltaToNextIdleSwitchInS);
842 TimeDuration nextTimeoutDuration = nextTimeoutAt - curTime;
844 MOZ_LOG(sLog, LogLevel::Debug,
845 ("idleService: next timeout %0.f msec from now",
846 nextTimeoutDuration.ToMilliseconds()));
848 #ifdef MOZ_WIDGET_ANDROID
849 __android_log_print(LOG_LEVEL, LOG_TAG, "next timeout %0.f msec from now",
850 nextTimeoutDuration.ToMilliseconds());
851 #endif
853 // Check if we should correct the timeout time because we should poll before.
854 if ((mIdleObserverCount > 0) && UsePollMode()) {
855 TimeStamp pollTimeout =
856 curTime + TimeDuration::FromMilliseconds(MIN_IDLE_POLL_INTERVAL_MSEC);
858 if (nextTimeoutAt > pollTimeout) {
859 MOZ_LOG(
860 sLog, LogLevel::Debug,
861 ("idleService: idle observers, reducing timeout to %lu msec from now",
862 MIN_IDLE_POLL_INTERVAL_MSEC));
863 #ifdef MOZ_WIDGET_ANDROID
864 __android_log_print(
865 LOG_LEVEL, LOG_TAG,
866 "idle observers, reducing timeout to %lu msec from now",
867 MIN_IDLE_POLL_INTERVAL_MSEC);
868 #endif
869 nextTimeoutAt = pollTimeout;
873 SetTimerExpiryIfBefore(nextTimeoutAt);