1 /* -*- Mode: c++; tab-width: 2; indent-tabs-mode: nil; -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "base/message_loop.h"
8 #include "nsBaseAppShell.h"
9 #include "nsThreadUtils.h"
10 #include "nsIObserverService.h"
11 #include "nsServiceManagerUtils.h"
12 #include "mozilla/Services.h"
14 // When processing the next thread event, the appshell may process native
15 // events (if not in performance mode), which can result in suppressing the
16 // next thread event for at most this many ticks:
17 #define THREAD_EVENT_STARVATION_LIMIT PR_MillisecondsToInterval(20)
19 NS_IMPL_ISUPPORTS(nsBaseAppShell
, nsIAppShell
, nsIThreadObserver
, nsIObserver
)
21 nsBaseAppShell::nsBaseAppShell()
22 : mSuspendNativeCount(0)
23 , mEventloopNestingLevel(0)
24 , mBlockedWait(nullptr)
26 , mNativeEventPending(false)
29 , mLastNativeEventTime(0)
30 , mEventloopNestingState(eEventloopNone
)
31 , mRunningSyncSections(false)
34 , mBlockNativeEvent(false)
38 nsBaseAppShell::~nsBaseAppShell()
40 NS_ASSERTION(mSyncSections
.IsEmpty(), "Must have run all sync sections");
44 nsBaseAppShell::Init()
46 // Configure ourselves as an observer for the current thread:
48 nsCOMPtr
<nsIThreadInternal
> threadInt
=
49 do_QueryInterface(NS_GetCurrentThread());
50 NS_ENSURE_STATE(threadInt
);
52 threadInt
->SetObserver(this);
54 nsCOMPtr
<nsIObserverService
> obsSvc
=
55 mozilla::services::GetObserverService();
57 obsSvc
->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID
, false);
61 // Called by nsAppShell's native event callback
63 nsBaseAppShell::NativeEventCallback()
65 if (!mNativeEventPending
.exchange(false))
68 // If DoProcessNextNativeEvent is on the stack, then we assume that we can
69 // just unwind and let nsThread::ProcessNextEvent process the next event.
70 // However, if we are called from a nested native event loop (maybe via some
71 // plug-in or library function), then go ahead and process Goanna events now.
72 if (mEventloopNestingState
== eEventloopXPCOM
) {
73 mEventloopNestingState
= eEventloopOther
;
74 // XXX there is a tiny risk we will never get a new NativeEventCallback,
75 // XXX see discussion in bug 389931.
79 // nsBaseAppShell::Run is not being used to pump events, so this may be
80 // our only opportunity to process pending goanna events.
82 nsIThread
*thread
= NS_GetCurrentThread();
83 bool prevBlockNativeEvent
= mBlockNativeEvent
;
84 if (mEventloopNestingState
== eEventloopOther
) {
85 if (!NS_HasPendingEvents(thread
))
87 // We're in a nested native event loop and have some goanna events to
88 // process. While doing that we block processing native events from the
89 // appshell - instead, we want to get back to the nested native event
90 // loop ASAP (bug 420148).
91 mBlockNativeEvent
= true;
94 IncrementEventloopNestingLevel();
95 EventloopNestingState prevVal
= mEventloopNestingState
;
96 NS_ProcessPendingEvents(thread
, THREAD_EVENT_STARVATION_LIMIT
);
97 mProcessedGoannaEvents
= true;
98 mEventloopNestingState
= prevVal
;
99 mBlockNativeEvent
= prevBlockNativeEvent
;
101 // Continue processing pending events later (we don't want to starve the
102 // embedders event loop).
103 if (NS_HasPendingEvents(thread
))
104 DoProcessMoreGoannaEvents();
106 DecrementEventloopNestingLevel();
109 // Note, this is currently overidden on windows, see comments in nsAppShell for
112 nsBaseAppShell::DoProcessMoreGoannaEvents()
114 OnDispatchedEvent(nullptr);
118 // Main thread via OnProcessNextEvent below
120 nsBaseAppShell::DoProcessNextNativeEvent(bool mayWait
, uint32_t recursionDepth
)
122 // The next native event to be processed may trigger our NativeEventCallback,
123 // in which case we do not want it to process any thread events since we'll
124 // do that when this function returns.
126 // If the next native event is not our NativeEventCallback, then we may end
127 // up recursing into this function.
129 // However, if the next native event is not our NativeEventCallback, but it
130 // results in another native event loop, then our NativeEventCallback could
131 // fire and it will see mEventloopNestingState as eEventloopOther.
133 EventloopNestingState prevVal
= mEventloopNestingState
;
134 mEventloopNestingState
= eEventloopXPCOM
;
136 IncrementEventloopNestingLevel();
138 bool result
= ProcessNextNativeEvent(mayWait
);
140 // Make sure that any sync sections registered during this most recent event
141 // are run now. This is not considered a stable state because we're not back
142 // to the event loop yet.
143 RunSyncSections(false, recursionDepth
);
145 DecrementEventloopNestingLevel();
147 mEventloopNestingState
= prevVal
;
151 //-------------------------------------------------------------------------
152 // nsIAppShell methods:
155 nsBaseAppShell::Run(void)
157 NS_ENSURE_STATE(!mRunning
); // should not call Run twice
160 nsIThread
*thread
= NS_GetCurrentThread();
162 MessageLoop::current()->Run();
164 NS_ProcessPendingEvents(thread
);
171 nsBaseAppShell::Exit(void)
173 if (mRunning
&& !mExiting
) {
174 MessageLoop::current()->Quit();
181 nsBaseAppShell::FavorPerformanceHint(bool favorPerfOverStarvation
,
182 uint32_t starvationDelay
)
184 mStarvationDelay
= PR_MillisecondsToInterval(starvationDelay
);
185 if (favorPerfOverStarvation
) {
189 mSwitchTime
= PR_IntervalNow();
195 nsBaseAppShell::SuspendNative()
197 ++mSuspendNativeCount
;
202 nsBaseAppShell::ResumeNative()
204 --mSuspendNativeCount
;
205 NS_ASSERTION(mSuspendNativeCount
>= 0, "Unbalanced call to nsBaseAppShell::ResumeNative!");
210 nsBaseAppShell::GetEventloopNestingLevel(uint32_t* aNestingLevelResult
)
212 NS_ENSURE_ARG_POINTER(aNestingLevelResult
);
214 *aNestingLevelResult
= mEventloopNestingLevel
;
219 //-------------------------------------------------------------------------
220 // nsIThreadObserver methods:
222 // Called from any thread
224 nsBaseAppShell::OnDispatchedEvent(nsIThreadInternal
*thr
)
226 if (mBlockNativeEvent
)
229 if (mNativeEventPending
.exchange(true))
232 // Returns on the main thread in NativeEventCallback above
233 ScheduleNativeEventCallback();
237 // Called from the main thread
239 nsBaseAppShell::OnProcessNextEvent(nsIThreadInternal
*thr
, bool mayWait
,
240 uint32_t recursionDepth
)
242 if (mBlockNativeEvent
) {
245 // Hmm, we're in a nested native event loop and would like to get
246 // back to it ASAP, but it seems a goanna event has caused us to
247 // spin up a nested XPCOM event loop (eg. modal window), so we
248 // really must start processing native events here again.
249 mBlockNativeEvent
= false;
250 if (NS_HasPendingEvents(thr
))
251 OnDispatchedEvent(thr
); // in case we blocked it earlier
254 PRIntervalTime start
= PR_IntervalNow();
255 PRIntervalTime limit
= THREAD_EVENT_STARVATION_LIMIT
;
257 // Unblock outer nested wait loop (below).
259 *mBlockedWait
= false;
261 bool *oldBlockedWait
= mBlockedWait
;
262 mBlockedWait
= &mayWait
;
264 // When mayWait is true, we need to make sure that there is an event in the
265 // thread's event queue before we return. Otherwise, the thread will block
266 // on its event queue waiting for an event.
267 bool needEvent
= mayWait
;
268 // Reset prior to invoking DoProcessNextNativeEvent which might cause
269 // NativeEventCallback to process goanna events.
270 mProcessedGoannaEvents
= false;
272 if (mFavorPerf
<= 0 && start
> mSwitchTime
+ mStarvationDelay
) {
273 // Favor pending native events
274 PRIntervalTime now
= start
;
277 mLastNativeEventTime
= now
;
278 keepGoing
= DoProcessNextNativeEvent(false, recursionDepth
);
279 } while (keepGoing
&& ((now
= PR_IntervalNow()) - start
) < limit
);
281 // Avoid starving native events completely when in performance mode
282 if (start
- mLastNativeEventTime
> limit
) {
283 mLastNativeEventTime
= start
;
284 DoProcessNextNativeEvent(false, recursionDepth
);
288 while (!NS_HasPendingEvents(thr
) && !mProcessedGoannaEvents
) {
289 // If we have been asked to exit from Run, then we should not wait for
290 // events to process. Note that an inner nested event loop causes
291 // 'mayWait' to become false too, through 'mBlockedWait'.
295 mLastNativeEventTime
= PR_IntervalNow();
296 if (!DoProcessNextNativeEvent(mayWait
, recursionDepth
) || !mayWait
)
300 mBlockedWait
= oldBlockedWait
;
302 // Make sure that the thread event queue does not block on its monitor, as
303 // it normally would do if it did not have any pending events. To avoid
304 // that, we simply insert a dummy event into its queue during shutdown.
305 if (needEvent
&& !mExiting
&& !NS_HasPendingEvents(thr
)) {
306 DispatchDummyEvent(thr
);
309 // We're about to run an event, so we're in a stable state.
310 RunSyncSections(true, recursionDepth
);
316 nsBaseAppShell::DispatchDummyEvent(nsIThread
* aTarget
)
318 NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
321 mDummyEvent
= new nsRunnable();
323 return NS_SUCCEEDED(aTarget
->Dispatch(mDummyEvent
, NS_DISPATCH_NORMAL
));
327 nsBaseAppShell::IncrementEventloopNestingLevel()
329 ++mEventloopNestingLevel
;
333 nsBaseAppShell::DecrementEventloopNestingLevel()
335 --mEventloopNestingLevel
;
339 nsBaseAppShell::RunSyncSectionsInternal(bool aStable
,
340 uint32_t aThreadRecursionLevel
)
342 NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
343 NS_ASSERTION(!mSyncSections
.IsEmpty(), "Nothing to do!");
345 // We don't support re-entering sync sections. This effectively means that
346 // sync sections may not spin the event loop.
347 MOZ_RELEASE_ASSERT(!mRunningSyncSections
);
348 mRunningSyncSections
= true;
350 // We've got synchronous sections. Run all of them that are are awaiting a
351 // stable state if aStable is true (i.e. we really are in a stable state).
352 // Also run the synchronous sections that are simply waiting for the right
353 // combination of event loop nesting level and thread recursion level.
354 // Note that a synchronous section could add another synchronous section, so
355 // we don't remove elements from mSyncSections until all sections have been
356 // run, or else we'll screw up our iteration. Any sync sections that are not
357 // ready to be run are saved for later.
359 nsTArray
<SyncSection
> pendingSyncSections
;
361 for (uint32_t i
= 0; i
< mSyncSections
.Length(); i
++) {
362 SyncSection
& section
= mSyncSections
[i
];
363 if ((aStable
&& section
.mStable
) ||
365 section
.mEventloopNestingLevel
== mEventloopNestingLevel
&&
366 section
.mThreadRecursionLevel
== aThreadRecursionLevel
)) {
367 section
.mRunnable
->Run();
370 // Add to pending list.
371 SyncSection
* pending
= pendingSyncSections
.AppendElement();
372 section
.Forget(pending
);
376 mSyncSections
.SwapElements(pendingSyncSections
);
377 mRunningSyncSections
= false;
381 nsBaseAppShell::ScheduleSyncSection(nsIRunnable
* aRunnable
, bool aStable
)
383 NS_ASSERTION(NS_IsMainThread(), "Should be on main thread.");
385 nsIThread
* thread
= NS_GetCurrentThread();
387 // Add this runnable to our list of synchronous sections.
388 SyncSection
* section
= mSyncSections
.AppendElement();
389 section
->mStable
= aStable
;
390 section
->mRunnable
= aRunnable
;
392 // If aStable is false then this synchronous section is supposed to run before
393 // the next event at the current nesting level. Record the event loop nesting
394 // level and the thread recursion level so that the synchronous section will
395 // run at the proper time.
397 section
->mEventloopNestingLevel
= mEventloopNestingLevel
;
399 nsCOMPtr
<nsIThreadInternal
> threadInternal
= do_QueryInterface(thread
);
400 NS_ASSERTION(threadInternal
, "This should never fail!");
402 uint32_t recursionLevel
;
403 if (NS_FAILED(threadInternal
->GetRecursionDepth(&recursionLevel
))) {
404 NS_ERROR("This should never fail!");
407 // Due to the weird way that the thread recursion counter is implemented we
408 // subtract one from the recursion level if we have one.
409 section
->mThreadRecursionLevel
= recursionLevel
? recursionLevel
- 1 : 0;
412 // Ensure we've got a pending event, else the callbacks will never run.
413 if (!NS_HasPendingEvents(thread
) && !DispatchDummyEvent(thread
)) {
414 RunSyncSections(true, 0);
418 // Called from the main thread
420 nsBaseAppShell::AfterProcessNextEvent(nsIThreadInternal
*thr
,
421 uint32_t recursionDepth
,
422 bool eventWasProcessed
)
424 // We've just finished running an event, so we're in a stable state.
425 RunSyncSections(true, recursionDepth
);
430 nsBaseAppShell::Observe(nsISupports
*subject
, const char *topic
,
431 const char16_t
*data
)
433 NS_ASSERTION(!strcmp(topic
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
), "oops");
439 nsBaseAppShell::RunInStableState(nsIRunnable
* aRunnable
)
441 ScheduleSyncSection(aRunnable
, true);
446 nsBaseAppShell::RunBeforeNextEvent(nsIRunnable
* aRunnable
)
448 ScheduleSyncSection(aRunnable
, false);