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_THREADSAFE_ISUPPORTS3(nsBaseAppShell
, nsIAppShell
, nsIThreadObserver
,
22 nsBaseAppShell::nsBaseAppShell()
23 : mSuspendNativeCount(0)
24 , mEventloopNestingLevel(0)
25 , mBlockedWait(nullptr)
27 , mNativeEventPending(0)
30 , mLastNativeEventTime(0)
31 , mEventloopNestingState(eEventloopNone
)
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 int32_t hasPending
= PR_ATOMIC_SET(&mNativeEventPending
, 0);
69 // If DoProcessNextNativeEvent is on the stack, then we assume that we can
70 // just unwind and let nsThread::ProcessNextEvent process the next event.
71 // However, if we are called from a nested native event loop (maybe via some
72 // plug-in or library function), then go ahead and process Gecko events now.
73 if (mEventloopNestingState
== eEventloopXPCOM
) {
74 mEventloopNestingState
= eEventloopOther
;
75 // XXX there is a tiny risk we will never get a new NativeEventCallback,
76 // XXX see discussion in bug 389931.
80 // nsBaseAppShell::Run is not being used to pump events, so this may be
81 // our only opportunity to process pending gecko events.
83 nsIThread
*thread
= NS_GetCurrentThread();
84 bool prevBlockNativeEvent
= mBlockNativeEvent
;
85 if (mEventloopNestingState
== eEventloopOther
) {
86 if (!NS_HasPendingEvents(thread
))
88 // We're in a nested native event loop and have some gecko events to
89 // process. While doing that we block processing native events from the
90 // appshell - instead, we want to get back to the nested native event
91 // loop ASAP (bug 420148).
92 mBlockNativeEvent
= true;
95 ++mEventloopNestingLevel
;
96 EventloopNestingState prevVal
= mEventloopNestingState
;
97 NS_ProcessPendingEvents(thread
, THREAD_EVENT_STARVATION_LIMIT
);
98 mProcessedGeckoEvents
= true;
99 mEventloopNestingState
= prevVal
;
100 mBlockNativeEvent
= prevBlockNativeEvent
;
102 // Continue processing pending events later (we don't want to starve the
103 // embedders event loop).
104 if (NS_HasPendingEvents(thread
))
105 DoProcessMoreGeckoEvents();
107 --mEventloopNestingLevel
;
110 // Note, this is currently overidden on windows, see comments in nsAppShell for
113 nsBaseAppShell::DoProcessMoreGeckoEvents()
115 OnDispatchedEvent(nullptr);
119 // Main thread via OnProcessNextEvent below
121 nsBaseAppShell::DoProcessNextNativeEvent(bool mayWait
, uint32_t recursionDepth
)
123 // The next native event to be processed may trigger our NativeEventCallback,
124 // in which case we do not want it to process any thread events since we'll
125 // do that when this function returns.
127 // If the next native event is not our NativeEventCallback, then we may end
128 // up recursing into this function.
130 // However, if the next native event is not our NativeEventCallback, but it
131 // results in another native event loop, then our NativeEventCallback could
132 // fire and it will see mEventloopNestingState as eEventloopOther.
134 EventloopNestingState prevVal
= mEventloopNestingState
;
135 mEventloopNestingState
= eEventloopXPCOM
;
137 ++mEventloopNestingLevel
;
139 bool result
= ProcessNextNativeEvent(mayWait
);
141 // Make sure that any sync sections registered during this most recent event
142 // are run now. This is not considered a stable state because we're not back
143 // to the event loop yet.
144 RunSyncSections(false, recursionDepth
);
146 --mEventloopNestingLevel
;
148 mEventloopNestingState
= prevVal
;
152 //-------------------------------------------------------------------------
153 // nsIAppShell methods:
156 nsBaseAppShell::Run(void)
158 NS_ENSURE_STATE(!mRunning
); // should not call Run twice
161 nsIThread
*thread
= NS_GetCurrentThread();
163 MessageLoop::current()->Run();
165 NS_ProcessPendingEvents(thread
);
172 nsBaseAppShell::Exit(void)
174 if (mRunning
&& !mExiting
) {
175 MessageLoop::current()->Quit();
182 nsBaseAppShell::FavorPerformanceHint(bool favorPerfOverStarvation
,
183 uint32_t starvationDelay
)
185 mStarvationDelay
= PR_MillisecondsToInterval(starvationDelay
);
186 if (favorPerfOverStarvation
) {
190 mSwitchTime
= PR_IntervalNow();
196 nsBaseAppShell::SuspendNative()
198 ++mSuspendNativeCount
;
203 nsBaseAppShell::ResumeNative()
205 --mSuspendNativeCount
;
206 NS_ASSERTION(mSuspendNativeCount
>= 0, "Unbalanced call to nsBaseAppShell::ResumeNative!");
211 nsBaseAppShell::GetEventloopNestingLevel(uint32_t* aNestingLevelResult
)
213 NS_ENSURE_ARG_POINTER(aNestingLevelResult
);
215 *aNestingLevelResult
= mEventloopNestingLevel
;
220 //-------------------------------------------------------------------------
221 // nsIThreadObserver methods:
223 // Called from any thread
225 nsBaseAppShell::OnDispatchedEvent(nsIThreadInternal
*thr
)
227 if (mBlockNativeEvent
)
230 int32_t lastVal
= PR_ATOMIC_SET(&mNativeEventPending
, 1);
234 // Returns on the main thread in NativeEventCallback above
235 ScheduleNativeEventCallback();
239 // Called from the main thread
241 nsBaseAppShell::OnProcessNextEvent(nsIThreadInternal
*thr
, bool mayWait
,
242 uint32_t recursionDepth
)
244 if (mBlockNativeEvent
) {
247 // Hmm, we're in a nested native event loop and would like to get
248 // back to it ASAP, but it seems a gecko event has caused us to
249 // spin up a nested XPCOM event loop (eg. modal window), so we
250 // really must start processing native events here again.
251 mBlockNativeEvent
= false;
252 if (NS_HasPendingEvents(thr
))
253 OnDispatchedEvent(thr
); // in case we blocked it earlier
256 PRIntervalTime start
= PR_IntervalNow();
257 PRIntervalTime limit
= THREAD_EVENT_STARVATION_LIMIT
;
259 // Unblock outer nested wait loop (below).
261 *mBlockedWait
= false;
263 bool *oldBlockedWait
= mBlockedWait
;
264 mBlockedWait
= &mayWait
;
266 // When mayWait is true, we need to make sure that there is an event in the
267 // thread's event queue before we return. Otherwise, the thread will block
268 // on its event queue waiting for an event.
269 bool needEvent
= mayWait
;
270 // Reset prior to invoking DoProcessNextNativeEvent which might cause
271 // NativeEventCallback to process gecko events.
272 mProcessedGeckoEvents
= false;
274 if (mFavorPerf
<= 0 && start
> mSwitchTime
+ mStarvationDelay
) {
275 // Favor pending native events
276 PRIntervalTime now
= start
;
279 mLastNativeEventTime
= now
;
280 keepGoing
= DoProcessNextNativeEvent(false, recursionDepth
);
281 } while (keepGoing
&& ((now
= PR_IntervalNow()) - start
) < limit
);
283 // Avoid starving native events completely when in performance mode
284 if (start
- mLastNativeEventTime
> limit
) {
285 mLastNativeEventTime
= start
;
286 DoProcessNextNativeEvent(false, recursionDepth
);
290 while (!NS_HasPendingEvents(thr
) && !mProcessedGeckoEvents
) {
291 // If we have been asked to exit from Run, then we should not wait for
292 // events to process. Note that an inner nested event loop causes
293 // 'mayWait' to become false too, through 'mBlockedWait'.
297 mLastNativeEventTime
= PR_IntervalNow();
298 if (!DoProcessNextNativeEvent(mayWait
, recursionDepth
) || !mayWait
)
302 mBlockedWait
= oldBlockedWait
;
304 // Make sure that the thread event queue does not block on its monitor, as
305 // it normally would do if it did not have any pending events. To avoid
306 // that, we simply insert a dummy event into its queue during shutdown.
307 if (needEvent
&& !mExiting
&& !NS_HasPendingEvents(thr
)) {
308 DispatchDummyEvent(thr
);
311 // We're about to run an event, so we're in a stable state.
312 RunSyncSections(true, recursionDepth
);
318 nsBaseAppShell::DispatchDummyEvent(nsIThread
* aTarget
)
320 NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
323 mDummyEvent
= new nsRunnable();
325 return NS_SUCCEEDED(aTarget
->Dispatch(mDummyEvent
, NS_DISPATCH_NORMAL
));
329 nsBaseAppShell::RunSyncSectionsInternal(bool aStable
,
330 uint32_t aThreadRecursionLevel
)
332 NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
333 NS_ASSERTION(!mSyncSections
.IsEmpty(), "Nothing to do!");
335 // We've got synchronous sections. Run all of them that are are awaiting a
336 // stable state if aStable is true (i.e. we really are in a stable state).
337 // Also run the synchronous sections that are simply waiting for the right
338 // combination of event loop nesting level and thread recursion level.
339 // Note that a synchronous section could add another synchronous section, so
340 // we don't remove elements from mSyncSections until all sections have been
341 // run, or else we'll screw up our iteration. Any sync sections that are not
342 // ready to be run are saved for later.
344 nsTArray
<SyncSection
> pendingSyncSections
;
346 for (uint32_t i
= 0; i
< mSyncSections
.Length(); i
++) {
347 SyncSection
& section
= mSyncSections
[i
];
348 if ((aStable
&& section
.mStable
) ||
350 section
.mEventloopNestingLevel
== mEventloopNestingLevel
&&
351 section
.mThreadRecursionLevel
== aThreadRecursionLevel
)) {
352 section
.mRunnable
->Run();
355 // Add to pending list.
356 SyncSection
* pending
= pendingSyncSections
.AppendElement();
357 section
.Forget(pending
);
361 mSyncSections
.SwapElements(pendingSyncSections
);
365 nsBaseAppShell::ScheduleSyncSection(nsIRunnable
* aRunnable
, bool aStable
)
367 NS_ASSERTION(NS_IsMainThread(), "Should be on main thread.");
369 nsIThread
* thread
= NS_GetCurrentThread();
371 // Add this runnable to our list of synchronous sections.
372 SyncSection
* section
= mSyncSections
.AppendElement();
373 section
->mStable
= aStable
;
374 section
->mRunnable
= aRunnable
;
376 // If aStable is false then this synchronous section is supposed to run before
377 // the next event at the current nesting level. Record the event loop nesting
378 // level and the thread recursion level so that the synchronous section will
379 // run at the proper time.
381 section
->mEventloopNestingLevel
= mEventloopNestingLevel
;
383 nsCOMPtr
<nsIThreadInternal
> threadInternal
= do_QueryInterface(thread
);
384 NS_ASSERTION(threadInternal
, "This should never fail!");
386 uint32_t recursionLevel
;
387 if (NS_FAILED(threadInternal
->GetRecursionDepth(&recursionLevel
))) {
388 NS_ERROR("This should never fail!");
391 // Due to the weird way that the thread recursion counter is implemented we
392 // subtract one from the recursion level if we have one.
393 section
->mThreadRecursionLevel
= recursionLevel
? recursionLevel
- 1 : 0;
396 // Ensure we've got a pending event, else the callbacks will never run.
397 if (!NS_HasPendingEvents(thread
) && !DispatchDummyEvent(thread
)) {
398 RunSyncSections(true, 0);
402 // Called from the main thread
404 nsBaseAppShell::AfterProcessNextEvent(nsIThreadInternal
*thr
,
405 uint32_t recursionDepth
)
407 // We've just finished running an event, so we're in a stable state.
408 RunSyncSections(true, recursionDepth
);
413 nsBaseAppShell::Observe(nsISupports
*subject
, const char *topic
,
414 const PRUnichar
*data
)
416 NS_ASSERTION(!strcmp(topic
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
), "oops");
422 nsBaseAppShell::RunInStableState(nsIRunnable
* aRunnable
)
424 ScheduleSyncSection(aRunnable
, true);
429 nsBaseAppShell::RunBeforeNextEvent(nsIRunnable
* aRunnable
)
431 ScheduleSyncSection(aRunnable
, false);