Bug 1858509 add thread-safety annotations around MediaSourceDemuxer::mMonitor r=alwu
[gecko.git] / widget / nsUserIdleService.cpp
blobf70a4bb459554c8d8803fc36f11f5ba6b8e8ba0e
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 "nsError.h"
9 #include "nsIAsyncShutdown.h"
10 #include "nsUserIdleService.h"
11 #include "nsString.h"
12 #include "nsIObserverService.h"
13 #include "nsDebug.h"
14 #include "nsCOMArray.h"
15 #include "nsXULAppAPI.h"
16 #include "prinrval.h"
17 #include "mozilla/Logging.h"
18 #include "prtime.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"
24 #include <algorithm>
26 #ifdef MOZ_WIDGET_ANDROID
27 # include <android/log.h>
28 #endif
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
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 //// nsUserIdleServiceDaily
64 NS_IMPL_ISUPPORTS(nsUserIdleServiceDaily, nsIObserver, nsISupportsWeakReference)
66 NS_IMETHODIMP
67 nsUserIdleServiceDaily::Observe(nsISupports*, const char* aTopic,
68 const char16_t*) {
69 auto shutdownInProgress =
70 AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownConfirmed);
71 MOZ_LOG(sLog, LogLevel::Debug,
72 ("nsUserIdleServiceDaily: Observe '%s' (%d)", aTopic,
73 shutdownInProgress));
75 if (shutdownInProgress || strcmp(aTopic, OBSERVER_TOPIC_ACTIVE) == 0) {
76 return NS_OK;
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");
84 #endif
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,
91 nullptr);
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();
110 if (prefs) {
111 prefs->SavePrefFile(nullptr);
114 MOZ_LOG(
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",
119 nowSec);
120 #endif
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");
134 return NS_OK;
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
153 // this value.
154 if (lastDaily == -1) {
155 MOZ_LOG(sLog, LogLevel::Debug,
156 ("nsUserIdleServiceDaily: Init: disabled idle-daily"));
157 return;
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.
163 lastDaily = 0;
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)));
178 MOZ_LOG(
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);
185 } else {
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");
190 #endif
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
203 // expected time.
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() {
214 if (mTimer) {
215 mTimer->Cancel();
216 mTimer = nullptr;
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)",
225 aHasBeenLongWait));
226 #ifdef MOZ_WIDGET_ANDROID
227 __android_log_print(LOG_LEVEL, LOG_TAG, "Registering Idle observer callback");
228 #endif
229 mIdleDailyTriggerWait =
230 (aHasBeenLongWait ? DAILY_SHORTENED_IDLE_SERVICE_SEC
231 : DAILY_SIGNIFICANT_IDLE_SERVICE_SEC);
232 (void)mIdleService->AddIdleObserver(this, mIdleDailyTriggerWait);
235 // static
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");
241 #endif
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
257 " msec",
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);
263 #endif
265 (void)self->mTimer->InitWithNamedFuncCallback(
266 DailyCallback, self, delayTime / PR_USEC_PER_MSEC,
267 nsITimer::TYPE_ONE_SHOT, "nsUserIdleServiceDaily::DailyCallback");
268 return;
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
306 * service.
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
321 * timeout.
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
326 * about 10 ms.
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
348 namespace {
349 nsUserIdleService* gIdleService;
350 } // namespace
352 already_AddRefed<nsUserIdleService> nsUserIdleService::GetInstance() {
353 RefPtr<nsUserIdleService> instance(gIdleService);
354 return instance.forget();
357 class UserIdleBlocker final : public nsIAsyncShutdownBlocker {
358 ~UserIdleBlocker() = default;
360 public:
361 explicit UserIdleBlocker() = default;
363 NS_IMETHOD
364 GetName(nsAString& aNameOut) override {
365 aNameOut = nsLiteralString(u"UserIdleBlocker");
366 return NS_OK;
369 NS_IMETHOD
370 BlockShutdown(nsIAsyncShutdownClient* aClient) override {
371 if (gIdleService) {
372 gIdleService->SetDisabledForShutdown();
374 aClient->RemoveBlocker(this);
375 return NS_OK;
378 NS_IMETHOD
379 GetState(nsIPropertyBag**) override { return NS_OK; }
381 NS_DECL_ISUPPORTS
384 NS_IMPL_ISUPPORTS(UserIdleBlocker, nsIAsyncShutdownBlocker)
386 nsUserIdleService::nsUserIdleService()
387 : mIdleObserverCount(0),
388 mDeltaToNextIdleSwitchInS(UINT32_MAX),
389 mLastUserInteraction(TimeStamp::Now()) {
390 MOZ_ASSERT(!gIdleService);
391 gIdleService = this;
392 if (XRE_IsParentProcess()) {
393 mDailyIdle = new nsUserIdleServiceDaily(this);
394 mDailyIdle->Init();
396 nsCOMPtr<nsIAsyncShutdownService> svc = services::GetAsyncShutdownService();
397 MOZ_ASSERT(svc);
398 nsCOMPtr<nsIAsyncShutdownClient> client;
399 auto rv = svc->GetQuitApplicationGranted(getter_AddRefs(client));
400 if (NS_FAILED(rv)) {
401 // quitApplicationGranted can be undefined in some environments.
402 rv = svc->GetXpcomWillShutdown(getter_AddRefs(client));
404 MOZ_ASSERT(NS_SUCCEEDED(rv));
405 client->AddBlocker(new UserIdleBlocker(),
406 NS_LITERAL_STRING_FROM_CSTRING(__FILE__), __LINE__,
407 u""_ns);
410 nsUserIdleService::~nsUserIdleService() {
411 if (mTimer) {
412 mTimer->Cancel();
415 MOZ_ASSERT(gIdleService == this);
416 gIdleService = nullptr;
419 NS_IMPL_ISUPPORTS(nsUserIdleService, nsIUserIdleService,
420 nsIUserIdleServiceInternal)
422 void nsUserIdleService::SetDisabledForShutdown() {
423 SetDisabled(true);
424 if (mTimer) {
425 mTimer->Cancel();
426 mTimer = nullptr;
430 NS_IMETHODIMP
431 nsUserIdleService::AddIdleObserver(nsIObserver* aObserver,
432 uint32_t aIdleTimeInS) {
433 NS_ENSURE_ARG_POINTER(aObserver);
434 // We don't accept idle time at 0, and we can't handle idle time that are too
435 // high either - no more than ~136 years.
436 NS_ENSURE_ARG_RANGE(aIdleTimeInS, 1, (UINT32_MAX / 10) - 1);
438 if (profiler_thread_is_being_profiled_for_markers()) {
439 nsAutoCString timeCStr;
440 timeCStr.AppendInt(aIdleTimeInS);
441 PROFILER_MARKER_TEXT("UserIdle::AddObserver", OTHER, MarkerStack::Capture(),
442 timeCStr);
445 if (XRE_IsContentProcess()) {
446 dom::ContentChild* cpc = dom::ContentChild::GetSingleton();
447 cpc->AddIdleObserver(aObserver, aIdleTimeInS);
448 return NS_OK;
451 MOZ_LOG(sLog, LogLevel::Debug,
452 ("idleService: Register idle observer %p for %d seconds", aObserver,
453 aIdleTimeInS));
454 #ifdef MOZ_WIDGET_ANDROID
455 __android_log_print(LOG_LEVEL, LOG_TAG,
456 "Register idle observer %p for %d seconds", aObserver,
457 aIdleTimeInS);
458 #endif
460 // Put the time + observer in a struct we can keep:
461 IdleListener listener(aObserver, aIdleTimeInS);
463 // XXX(Bug 1631371) Check if this should use a fallible operation as it
464 // pretended earlier.
465 mArrayListeners.AppendElement(listener);
467 // Create our timer callback if it's not there already.
468 if (!mTimer) {
469 mTimer = NS_NewTimer();
470 NS_ENSURE_TRUE(mTimer, NS_ERROR_OUT_OF_MEMORY);
473 // Check if the newly added observer has a smaller wait time than what we
474 // are waiting for now.
475 if (mDeltaToNextIdleSwitchInS > aIdleTimeInS) {
476 // If it is, then this is the next to move to idle (at this point we
477 // don't care if it should have switched already).
478 MOZ_LOG(
479 sLog, LogLevel::Debug,
480 ("idleService: Register: adjusting next switch from %d to %d seconds",
481 mDeltaToNextIdleSwitchInS, aIdleTimeInS));
482 #ifdef MOZ_WIDGET_ANDROID
483 __android_log_print(LOG_LEVEL, LOG_TAG,
484 "Register: adjusting next switch from %d to %d seconds",
485 mDeltaToNextIdleSwitchInS, aIdleTimeInS);
486 #endif
488 mDeltaToNextIdleSwitchInS = aIdleTimeInS;
489 ReconfigureTimer();
492 return NS_OK;
495 NS_IMETHODIMP
496 nsUserIdleService::RemoveIdleObserver(nsIObserver* aObserver,
497 uint32_t aTimeInS) {
498 NS_ENSURE_ARG_POINTER(aObserver);
499 NS_ENSURE_ARG(aTimeInS);
501 if (profiler_thread_is_being_profiled_for_markers()) {
502 nsAutoCString timeCStr;
503 timeCStr.AppendInt(aTimeInS);
504 PROFILER_MARKER_TEXT("UserIdle::RemoveObserver", OTHER,
505 MarkerStack::Capture(), timeCStr);
508 if (XRE_IsContentProcess()) {
509 dom::ContentChild* cpc = dom::ContentChild::GetSingleton();
510 cpc->RemoveIdleObserver(aObserver, aTimeInS);
511 return NS_OK;
514 IdleListener listener(aObserver, aTimeInS);
516 // Find the entry and remove it, if it was the last entry, we just let the
517 // existing timer run to completion (there might be a new registration in a
518 // little while.
519 IdleListenerComparator c;
520 nsTArray<IdleListener>::index_type listenerIndex =
521 mArrayListeners.IndexOf(listener, 0, c);
522 if (listenerIndex != mArrayListeners.NoIndex) {
523 if (mArrayListeners.ElementAt(listenerIndex).isIdle) mIdleObserverCount--;
524 mArrayListeners.RemoveElementAt(listenerIndex);
525 MOZ_LOG(sLog, LogLevel::Debug,
526 ("idleService: Remove observer %p (%d seconds), %d remain idle",
527 aObserver, aTimeInS, mIdleObserverCount));
528 #ifdef MOZ_WIDGET_ANDROID
529 __android_log_print(LOG_LEVEL, LOG_TAG,
530 "Remove observer %p (%d seconds), %d remain idle",
531 aObserver, aTimeInS, mIdleObserverCount);
532 #endif
533 return NS_OK;
536 // If we get here, we haven't removed anything:
537 MOZ_LOG(sLog, LogLevel::Warning,
538 ("idleService: Failed to remove idle observer %p (%d seconds)",
539 aObserver, aTimeInS));
540 #ifdef MOZ_WIDGET_ANDROID
541 __android_log_print(LOG_LEVEL, LOG_TAG,
542 "Failed to remove idle observer %p (%d seconds)",
543 aObserver, aTimeInS);
544 #endif
545 return NS_ERROR_FAILURE;
548 NS_IMETHODIMP
549 nsUserIdleService::ResetIdleTimeOut(uint32_t idleDeltaInMS) {
550 MOZ_LOG(sLog, LogLevel::Debug,
551 ("idleService: Reset idle timeout (last interaction %u msec)",
552 idleDeltaInMS));
554 // Store the time
555 mLastUserInteraction =
556 TimeStamp::Now() - TimeDuration::FromMilliseconds(idleDeltaInMS);
558 // If no one is idle, then we are done, any existing timers can keep running.
559 if (mIdleObserverCount == 0) {
560 MOZ_LOG(sLog, LogLevel::Debug,
561 ("idleService: Reset idle timeout: no idle observers"));
562 return NS_OK;
565 // Mark all idle services as non-idle, and calculate the next idle timeout.
566 nsCOMArray<nsIObserver> notifyList;
567 mDeltaToNextIdleSwitchInS = UINT32_MAX;
569 // Loop through all listeners, and find any that have detected idle.
570 for (uint32_t i = 0; i < mArrayListeners.Length(); i++) {
571 IdleListener& curListener = mArrayListeners.ElementAt(i);
573 // If the listener was idle, then he shouldn't be any longer.
574 if (curListener.isIdle) {
575 notifyList.AppendObject(curListener.observer);
576 curListener.isIdle = false;
579 // Check if the listener is the next one to timeout.
580 mDeltaToNextIdleSwitchInS =
581 std::min(mDeltaToNextIdleSwitchInS, curListener.reqIdleTime);
584 // When we are done, then we wont have anyone idle.
585 mIdleObserverCount = 0;
587 // Restart the idle timer, and do so before anyone can delay us.
588 ReconfigureTimer();
590 int32_t numberOfPendingNotifications = notifyList.Count();
592 // Bail if nothing to do.
593 if (!numberOfPendingNotifications) {
594 return NS_OK;
597 // Now send "active" events to all, if any should have timed out already,
598 // then they will be reawaken by the timer that is already running.
600 // We need a text string to send with any state change events.
601 nsAutoString timeStr;
603 timeStr.AppendInt((int32_t)(idleDeltaInMS / PR_MSEC_PER_SEC));
605 // Send the "non-idle" events.
606 while (numberOfPendingNotifications--) {
607 MOZ_LOG(sLog, LogLevel::Debug,
608 ("idleService: Reset idle timeout: tell observer %p user is back",
609 notifyList[numberOfPendingNotifications]));
610 #ifdef MOZ_WIDGET_ANDROID
611 __android_log_print(LOG_LEVEL, LOG_TAG,
612 "Reset idle timeout: tell observer %p user is back",
613 notifyList[numberOfPendingNotifications]);
614 #endif
615 notifyList[numberOfPendingNotifications]->Observe(
616 this, OBSERVER_TOPIC_ACTIVE, timeStr.get());
618 return NS_OK;
621 NS_IMETHODIMP
622 nsUserIdleService::GetIdleTime(uint32_t* idleTime) {
623 // Check sanity of in parameter.
624 if (!idleTime) {
625 return NS_ERROR_NULL_POINTER;
628 // Polled idle time in ms.
629 uint32_t polledIdleTimeMS;
631 bool polledIdleTimeIsValid = PollIdleTime(&polledIdleTimeMS);
633 MOZ_LOG(sLog, LogLevel::Debug,
634 ("idleService: Get idle time: polled %u msec, valid = %d",
635 polledIdleTimeMS, polledIdleTimeIsValid));
637 // timeSinceReset is in milliseconds.
638 TimeDuration timeSinceReset = TimeStamp::Now() - mLastUserInteraction;
639 uint32_t timeSinceResetInMS = timeSinceReset.ToMilliseconds();
641 MOZ_LOG(sLog, LogLevel::Debug,
642 ("idleService: Get idle time: time since reset %u msec",
643 timeSinceResetInMS));
644 #ifdef MOZ_WIDGET_ANDROID
645 __android_log_print(LOG_LEVEL, LOG_TAG,
646 "Get idle time: time since reset %u msec",
647 timeSinceResetInMS);
648 #endif
650 // If we did't get pulled data, return the time since last idle reset.
651 if (!polledIdleTimeIsValid) {
652 // We need to convert to ms before returning the time.
653 *idleTime = timeSinceResetInMS;
654 return NS_OK;
657 // Otherwise return the shortest time detected (in ms).
658 *idleTime = std::min(timeSinceResetInMS, polledIdleTimeMS);
660 return NS_OK;
663 bool nsUserIdleService::PollIdleTime(uint32_t* /*aIdleTime*/) {
664 // Default behavior is not to have the ability to poll an idle time.
665 return false;
668 nsresult nsUserIdleService::GetDisabled(bool* aResult) {
669 *aResult = mDisabled;
670 return NS_OK;
673 nsresult nsUserIdleService::SetDisabled(bool aDisabled) {
674 mDisabled = aDisabled;
675 return NS_OK;
678 void nsUserIdleService::StaticIdleTimerCallback(nsITimer* aTimer,
679 void* aClosure) {
680 static_cast<nsUserIdleService*>(aClosure)->IdleTimerCallback();
683 void nsUserIdleService::IdleTimerCallback(void) {
684 // Remember that we no longer have a timer running.
685 mCurrentlySetToTimeoutAt = TimeStamp();
687 // Find the last detected idle time.
688 uint32_t lastIdleTimeInMS = static_cast<uint32_t>(
689 (TimeStamp::Now() - mLastUserInteraction).ToMilliseconds());
690 // Get the current idle time.
691 uint32_t currentIdleTimeInMS;
693 if (NS_FAILED(GetIdleTime(&currentIdleTimeInMS))) {
694 MOZ_LOG(sLog, LogLevel::Info,
695 ("idleService: Idle timer callback: failed to get idle time"));
696 #ifdef MOZ_WIDGET_ANDROID
697 __android_log_print(LOG_LEVEL, LOG_TAG,
698 "Idle timer callback: failed to get idle time");
699 #endif
700 return;
703 MOZ_LOG(sLog, LogLevel::Debug,
704 ("idleService: Idle timer callback: current idle time %u msec",
705 currentIdleTimeInMS));
706 #ifdef MOZ_WIDGET_ANDROID
707 __android_log_print(LOG_LEVEL, LOG_TAG,
708 "Idle timer callback: current idle time %u msec",
709 currentIdleTimeInMS);
710 #endif
712 // Check if we have had some user interaction we didn't handle previously
713 // we do the calculation in ms to lessen the chance for rounding errors to
714 // trigger wrong results.
715 if (lastIdleTimeInMS > currentIdleTimeInMS) {
716 // We had user activity, so handle that part first (to ensure the listeners
717 // don't risk getting an non-idle after they get a new idle indication.
718 ResetIdleTimeOut(currentIdleTimeInMS);
720 // NOTE: We can't bail here, as we might have something already timed out.
723 // Find the idle time in S.
724 uint32_t currentIdleTimeInS = currentIdleTimeInMS / PR_MSEC_PER_SEC;
726 // Restart timer and bail if no-one are expected to be in idle
727 if (mDeltaToNextIdleSwitchInS > currentIdleTimeInS) {
728 // If we didn't expect anyone to be idle, then just re-start the timer.
729 ReconfigureTimer();
730 return;
733 if (mDisabled) {
734 MOZ_LOG(sLog, LogLevel::Info,
735 ("idleService: Skipping idle callback while disabled"));
737 ReconfigureTimer();
738 return;
741 // Tell expired listeners they are expired,and find the next timeout
742 Telemetry::AutoTimer<Telemetry::IDLE_NOTIFY_IDLE_MS> timer;
744 // We need to initialise the time to the next idle switch.
745 mDeltaToNextIdleSwitchInS = UINT32_MAX;
747 // Create list of observers that should be notified.
748 nsCOMArray<nsIObserver> notifyList;
750 for (uint32_t i = 0; i < mArrayListeners.Length(); i++) {
751 IdleListener& curListener = mArrayListeners.ElementAt(i);
753 // We are only interested in items, that are not in the idle state.
754 if (!curListener.isIdle) {
755 // If they have an idle time smaller than the actual idle time.
756 if (curListener.reqIdleTime <= currentIdleTimeInS) {
757 // Then add the listener to the list of listeners that should be
758 // notified.
759 notifyList.AppendObject(curListener.observer);
760 // This listener is now idle.
761 curListener.isIdle = true;
762 // Remember we have someone idle.
763 mIdleObserverCount++;
764 } else {
765 // Listeners that are not timed out yet are candidates for timing out.
766 mDeltaToNextIdleSwitchInS =
767 std::min(mDeltaToNextIdleSwitchInS, curListener.reqIdleTime);
772 // Restart the timer before any notifications that could slow us down are
773 // done.
774 ReconfigureTimer();
776 int32_t numberOfPendingNotifications = notifyList.Count();
778 // Bail if nothing to do.
779 if (!numberOfPendingNotifications) {
780 MOZ_LOG(
781 sLog, LogLevel::Debug,
782 ("idleService: **** Idle timer callback: no observers to message."));
783 return;
786 // We need a text string to send with any state change events.
787 nsAutoString timeStr;
788 timeStr.AppendInt(currentIdleTimeInS);
790 // Notify all listeners that just timed out.
791 while (numberOfPendingNotifications--) {
792 MOZ_LOG(
793 sLog, LogLevel::Debug,
794 ("idleService: **** Idle timer callback: tell observer %p user is idle",
795 notifyList[numberOfPendingNotifications]));
796 #ifdef MOZ_WIDGET_ANDROID
797 __android_log_print(LOG_LEVEL, LOG_TAG,
798 "Idle timer callback: tell observer %p user is idle",
799 notifyList[numberOfPendingNotifications]);
800 #endif
801 nsAutoCString timeCStr;
802 timeCStr.AppendInt(currentIdleTimeInS);
803 AUTO_PROFILER_MARKER_TEXT("UserIdle::IdleCallback", OTHER, {}, timeCStr);
804 notifyList[numberOfPendingNotifications]->Observe(this, OBSERVER_TOPIC_IDLE,
805 timeStr.get());
809 void nsUserIdleService::SetTimerExpiryIfBefore(TimeStamp aNextTimeout) {
810 TimeDuration nextTimeoutDuration = aNextTimeout - TimeStamp::Now();
812 MOZ_LOG(
813 sLog, LogLevel::Debug,
814 ("idleService: SetTimerExpiryIfBefore: next timeout %0.f msec from now",
815 nextTimeoutDuration.ToMilliseconds()));
817 #ifdef MOZ_WIDGET_ANDROID
818 __android_log_print(LOG_LEVEL, LOG_TAG,
819 "SetTimerExpiryIfBefore: next timeout %0.f msec from now",
820 nextTimeoutDuration.ToMilliseconds());
821 #endif
823 // Bail if we don't have a timer service.
824 if (!mTimer) {
825 return;
828 // If the new timeout is before the old one or we don't have a timer running,
829 // then restart the timer.
830 if (mCurrentlySetToTimeoutAt.IsNull() ||
831 mCurrentlySetToTimeoutAt > aNextTimeout) {
832 mCurrentlySetToTimeoutAt = aNextTimeout;
834 // Stop the current timer (it's ok to try'n stop it, even it isn't running).
835 mTimer->Cancel();
837 // Check that the timeout is actually in the future, otherwise make it so.
838 TimeStamp currentTime = TimeStamp::Now();
839 if (currentTime > mCurrentlySetToTimeoutAt) {
840 mCurrentlySetToTimeoutAt = currentTime;
843 // Add 10 ms to ensure we don't undershoot, and never get a "0" timer.
844 mCurrentlySetToTimeoutAt += TimeDuration::FromMilliseconds(10);
846 TimeDuration deltaTime = mCurrentlySetToTimeoutAt - currentTime;
847 MOZ_LOG(
848 sLog, LogLevel::Debug,
849 ("idleService: IdleService reset timer expiry to %0.f msec from now",
850 deltaTime.ToMilliseconds()));
851 #ifdef MOZ_WIDGET_ANDROID
852 __android_log_print(LOG_LEVEL, LOG_TAG,
853 "reset timer expiry to %0.f msec from now",
854 deltaTime.ToMilliseconds());
855 #endif
857 // Start the timer
858 mTimer->InitWithNamedFuncCallback(
859 StaticIdleTimerCallback, this, deltaTime.ToMilliseconds(),
860 nsITimer::TYPE_ONE_SHOT, "nsUserIdleService::SetTimerExpiryIfBefore");
864 void nsUserIdleService::ReconfigureTimer(void) {
865 // Check if either someone is idle, or someone will become idle.
866 if ((mIdleObserverCount == 0) && UINT32_MAX == mDeltaToNextIdleSwitchInS) {
867 // If not, just let any existing timers run to completion
868 // And bail out.
869 MOZ_LOG(sLog, LogLevel::Debug,
870 ("idleService: ReconfigureTimer: no idle or waiting observers"));
871 #ifdef MOZ_WIDGET_ANDROID
872 __android_log_print(LOG_LEVEL, LOG_TAG,
873 "ReconfigureTimer: no idle or waiting observers");
874 #endif
875 return;
878 // Find the next timeout value, assuming we are not polling.
880 // We need to store the current time, so we don't get artifacts from the time
881 // ticking while we are processing.
882 TimeStamp curTime = TimeStamp::Now();
884 TimeStamp nextTimeoutAt =
885 mLastUserInteraction +
886 TimeDuration::FromSeconds(mDeltaToNextIdleSwitchInS);
888 TimeDuration nextTimeoutDuration = nextTimeoutAt - curTime;
890 MOZ_LOG(sLog, LogLevel::Debug,
891 ("idleService: next timeout %0.f msec from now",
892 nextTimeoutDuration.ToMilliseconds()));
894 #ifdef MOZ_WIDGET_ANDROID
895 __android_log_print(LOG_LEVEL, LOG_TAG, "next timeout %0.f msec from now",
896 nextTimeoutDuration.ToMilliseconds());
897 #endif
899 SetTimerExpiryIfBefore(nextTimeoutAt);