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 "nsExceptionHandler.h"
10 #include "nsJSUtils.h"
11 #include "nsThreadUtils.h"
12 #include "nsIAppShell.h"
13 #include "nsIObserverService.h"
14 #include "nsServiceManagerUtils.h"
15 #include "mozilla/Services.h"
16 #include "nsXULAppAPI.h"
18 // When processing the next thread event, the appshell may process native
19 // events (if not in performance mode), which can result in suppressing the
20 // next thread event for at most this many ticks:
21 #define THREAD_EVENT_STARVATION_LIMIT PR_MillisecondsToInterval(10)
23 NS_IMPL_ISUPPORTS(nsBaseAppShell
, nsIAppShell
, nsIThreadObserver
, nsIObserver
)
25 nsBaseAppShell::nsBaseAppShell()
26 : mSuspendNativeCount(0),
27 mEventloopNestingLevel(0),
28 mBlockedWait(nullptr),
29 mNativeEventPending(false),
30 mGeckoTaskBurstStartTime(0),
31 mLastNativeEventTime(0),
32 mEventloopNestingState(eEventloopNone
),
35 mBlockNativeEvent(false),
36 mProcessedGeckoEvents(false) {}
38 nsBaseAppShell::~nsBaseAppShell() = default;
40 nsresult
nsBaseAppShell::Init() {
41 // Configure ourselves as an observer for the current thread:
43 if (XRE_UseNativeEventProcessing()) {
44 nsCOMPtr
<nsIThreadInternal
> threadInt
=
45 do_QueryInterface(NS_GetCurrentThread());
46 NS_ENSURE_STATE(threadInt
);
48 threadInt
->SetObserver(this);
51 nsCOMPtr
<nsIObserverService
> obsSvc
= mozilla::services::GetObserverService();
52 if (obsSvc
) obsSvc
->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID
, false);
56 // Called by nsAppShell's native event callback
57 void nsBaseAppShell::NativeEventCallback() {
58 if (!mNativeEventPending
.exchange(false)) return;
60 // If DoProcessNextNativeEvent is on the stack, then we assume that we can
61 // just unwind and let nsThread::ProcessNextEvent process the next event.
62 // However, if we are called from a nested native event loop (maybe via some
63 // plug-in or library function), then go ahead and process Gecko events now.
64 if (mEventloopNestingState
== eEventloopXPCOM
) {
65 mEventloopNestingState
= eEventloopOther
;
66 // XXX there is a tiny risk we will never get a new NativeEventCallback,
67 // XXX see discussion in bug 389931.
71 // nsBaseAppShell::Run is not being used to pump events, so this may be
72 // our only opportunity to process pending gecko events.
74 nsIThread
* thread
= NS_GetCurrentThread();
75 bool prevBlockNativeEvent
= mBlockNativeEvent
;
76 if (mEventloopNestingState
== eEventloopOther
) {
77 if (!NS_HasPendingEvents(thread
)) return;
78 // We're in a nested native event loop and have some gecko events to
79 // process. While doing that we block processing native events from the
80 // appshell - instead, we want to get back to the nested native event
81 // loop ASAP (bug 420148).
82 mBlockNativeEvent
= true;
85 IncrementEventloopNestingLevel();
86 EventloopNestingState prevVal
= mEventloopNestingState
;
87 NS_ProcessPendingEvents(thread
, THREAD_EVENT_STARVATION_LIMIT
);
88 mProcessedGeckoEvents
= true;
89 mEventloopNestingState
= prevVal
;
90 mBlockNativeEvent
= prevBlockNativeEvent
;
92 // Continue processing pending events later (we don't want to starve the
93 // embedders event loop).
94 if (NS_HasPendingEvents(thread
)) DoProcessMoreGeckoEvents();
96 DecrementEventloopNestingLevel();
99 void nsBaseAppShell::OnSystemTimezoneChange() {
100 nsJSUtils::ResetTimeZone();
102 nsCOMPtr
<nsIObserverService
> obsSvc
= mozilla::services::GetObserverService();
104 // Timezone changed notification
105 obsSvc
->NotifyObservers(nullptr, DEFAULT_TIMEZONE_CHANGED_OBSERVER_TOPIC
,
110 // Note, this is currently overidden on windows, see comments in nsAppShell for
112 void nsBaseAppShell::DoProcessMoreGeckoEvents() { OnDispatchedEvent(); }
114 // Main thread via OnProcessNextEvent below
115 bool nsBaseAppShell::DoProcessNextNativeEvent(bool mayWait
) {
116 // The next native event to be processed may trigger our NativeEventCallback,
117 // in which case we do not want it to process any thread events since we'll
118 // do that when this function returns.
120 // If the next native event is not our NativeEventCallback, then we may end
121 // up recursing into this function.
123 // However, if the next native event is not our NativeEventCallback, but it
124 // results in another native event loop, then our NativeEventCallback could
125 // fire and it will see mEventloopNestingState as eEventloopOther.
127 EventloopNestingState prevVal
= mEventloopNestingState
;
128 mEventloopNestingState
= eEventloopXPCOM
;
130 IncrementEventloopNestingLevel();
131 bool result
= ProcessNextNativeEvent(mayWait
);
132 DecrementEventloopNestingLevel();
134 mEventloopNestingState
= prevVal
;
138 //-------------------------------------------------------------------------
139 // nsIAppShell methods:
142 nsBaseAppShell::Run(void) {
143 NS_ENSURE_STATE(!mRunning
); // should not call Run twice
146 nsIThread
* thread
= NS_GetCurrentThread();
148 MessageLoop::current()->Run();
150 NS_ProcessPendingEvents(thread
);
157 nsBaseAppShell::Exit(void) {
158 if (mRunning
&& !mExiting
) {
159 MessageLoop::current()->Quit();
166 nsBaseAppShell::GeckoTaskBurst() {
167 if (mGeckoTaskBurstStartTime
== 0) {
168 mGeckoTaskBurstStartTime
= PR_IntervalNow();
174 nsBaseAppShell::SuspendNative() {
175 ++mSuspendNativeCount
;
180 nsBaseAppShell::ResumeNative() {
181 --mSuspendNativeCount
;
182 NS_ASSERTION(mSuspendNativeCount
>= 0,
183 "Unbalanced call to nsBaseAppShell::ResumeNative!");
188 nsBaseAppShell::GetEventloopNestingLevel(uint32_t* aNestingLevelResult
) {
189 NS_ENSURE_ARG_POINTER(aNestingLevelResult
);
191 *aNestingLevelResult
= mEventloopNestingLevel
;
196 //-------------------------------------------------------------------------
197 // nsIThreadObserver methods:
199 // Called from any thread
201 nsBaseAppShell::OnDispatchedEvent() {
202 if (mBlockNativeEvent
) return NS_OK
;
204 if (mNativeEventPending
.exchange(true)) return NS_OK
;
206 // Returns on the main thread in NativeEventCallback above
207 ScheduleNativeEventCallback();
211 // Called from the main thread
213 nsBaseAppShell::OnProcessNextEvent(nsIThreadInternal
* thr
, bool mayWait
) {
214 if (mBlockNativeEvent
) {
215 if (!mayWait
) return NS_OK
;
216 // Hmm, we're in a nested native event loop and would like to get
217 // back to it ASAP, but it seems a gecko event has caused us to
218 // spin up a nested XPCOM event loop (eg. modal window), so we
219 // really must start processing native events here again.
220 mBlockNativeEvent
= false;
221 if (NS_HasPendingEvents(thr
))
222 OnDispatchedEvent(); // in case we blocked it earlier
225 PRIntervalTime start
= PR_IntervalNow();
226 PRIntervalTime limit
= THREAD_EVENT_STARVATION_LIMIT
;
228 // Unblock outer nested wait loop (below).
229 if (mBlockedWait
) *mBlockedWait
= false;
231 bool* oldBlockedWait
= mBlockedWait
;
232 mBlockedWait
= &mayWait
;
234 // When mayWait is true, we need to make sure that there is an event in the
235 // thread's event queue before we return. Otherwise, the thread will block
236 // on its event queue waiting for an event.
237 bool needEvent
= mayWait
;
238 // Reset prior to invoking DoProcessNextNativeEvent which might cause
239 // NativeEventCallback to process gecko events.
240 mProcessedGeckoEvents
= false;
242 // Content processes always priorize gecko events.
243 if (!XRE_IsContentProcess() && (start
> (mGeckoTaskBurstStartTime
+ limit
))) {
244 mGeckoTaskBurstStartTime
= 0;
245 // Favor pending native events
246 PRIntervalTime now
= start
;
249 mLastNativeEventTime
= now
;
250 keepGoing
= DoProcessNextNativeEvent(false);
251 } while (keepGoing
&& ((now
= PR_IntervalNow()) - start
) < limit
);
253 // Avoid starving native events completely when in performance mode
254 if (start
- mLastNativeEventTime
> limit
) {
255 mLastNativeEventTime
= start
;
256 DoProcessNextNativeEvent(false);
260 while (!NS_HasPendingEvents(thr
) && !mProcessedGeckoEvents
) {
261 // If we have been asked to exit from Run, then we should not wait for
262 // events to process. Note that an inner nested event loop causes
263 // 'mayWait' to become false too, through 'mBlockedWait'.
264 if (mExiting
) mayWait
= false;
266 mLastNativeEventTime
= PR_IntervalNow();
267 if (!DoProcessNextNativeEvent(mayWait
) || !mayWait
) break;
270 mBlockedWait
= oldBlockedWait
;
272 // Make sure that the thread event queue does not block on its monitor, as
273 // it normally would do if it did not have any pending events. To avoid
274 // that, we simply insert a dummy event into its queue during shutdown.
275 if (needEvent
&& !mExiting
&& !NS_HasPendingEvents(thr
)) {
276 DispatchDummyEvent(thr
);
282 bool nsBaseAppShell::DispatchDummyEvent(nsIThread
* aTarget
) {
283 NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
285 if (!mDummyEvent
) mDummyEvent
= new mozilla::Runnable("DummyEvent");
287 return NS_SUCCEEDED(aTarget
->Dispatch(mDummyEvent
, NS_DISPATCH_NORMAL
));
290 void nsBaseAppShell::IncrementEventloopNestingLevel() {
291 ++mEventloopNestingLevel
;
292 CrashReporter::SetEventloopNestingLevel(mEventloopNestingLevel
);
295 void nsBaseAppShell::DecrementEventloopNestingLevel() {
296 --mEventloopNestingLevel
;
297 CrashReporter::SetEventloopNestingLevel(mEventloopNestingLevel
);
300 // Called from the main thread
302 nsBaseAppShell::AfterProcessNextEvent(nsIThreadInternal
* thr
,
303 bool eventWasProcessed
) {
308 nsBaseAppShell::Observe(nsISupports
* subject
, const char* topic
,
309 const char16_t
* data
) {
310 NS_ASSERTION(!strcmp(topic
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
), "oops");