Bug 1735754 [wpt PR 31232] - Make the higher-order comparisons in the structured...
[gecko.git] / widget / nsBaseAppShell.cpp
blob648096b8c27dc078136801fa7e08e3d6d0cb8bc6
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 "nsThreadUtils.h"
11 #include "nsIObserverService.h"
12 #include "nsServiceManagerUtils.h"
13 #include "mozilla/Services.h"
14 #include "nsXULAppAPI.h"
16 // When processing the next thread event, the appshell may process native
17 // events (if not in performance mode), which can result in suppressing the
18 // next thread event for at most this many ticks:
19 #define THREAD_EVENT_STARVATION_LIMIT PR_MillisecondsToInterval(10)
21 NS_IMPL_ISUPPORTS(nsBaseAppShell, nsIAppShell, nsIThreadObserver, nsIObserver)
23 nsBaseAppShell::nsBaseAppShell()
24 : mSuspendNativeCount(0),
25 mEventloopNestingLevel(0),
26 mBlockedWait(nullptr),
27 mFavorPerf(0),
28 mNativeEventPending(false),
29 mStarvationDelay(0),
30 mSwitchTime(0),
31 mLastNativeEventTime(0),
32 mEventloopNestingState(eEventloopNone),
33 mRunning(false),
34 mExiting(false),
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);
53 return NS_OK;
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.
68 return;
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 // Note, this is currently overidden on windows, see comments in nsAppShell for
100 // details.
101 void nsBaseAppShell::DoProcessMoreGeckoEvents() { OnDispatchedEvent(); }
103 // Main thread via OnProcessNextEvent below
104 bool nsBaseAppShell::DoProcessNextNativeEvent(bool mayWait) {
105 // The next native event to be processed may trigger our NativeEventCallback,
106 // in which case we do not want it to process any thread events since we'll
107 // do that when this function returns.
109 // If the next native event is not our NativeEventCallback, then we may end
110 // up recursing into this function.
112 // However, if the next native event is not our NativeEventCallback, but it
113 // results in another native event loop, then our NativeEventCallback could
114 // fire and it will see mEventloopNestingState as eEventloopOther.
116 EventloopNestingState prevVal = mEventloopNestingState;
117 mEventloopNestingState = eEventloopXPCOM;
119 IncrementEventloopNestingLevel();
120 bool result = ProcessNextNativeEvent(mayWait);
121 DecrementEventloopNestingLevel();
123 mEventloopNestingState = prevVal;
124 return result;
127 //-------------------------------------------------------------------------
128 // nsIAppShell methods:
130 NS_IMETHODIMP
131 nsBaseAppShell::Run(void) {
132 NS_ENSURE_STATE(!mRunning); // should not call Run twice
133 mRunning = true;
135 nsIThread* thread = NS_GetCurrentThread();
137 MessageLoop::current()->Run();
139 NS_ProcessPendingEvents(thread);
141 mRunning = false;
142 return NS_OK;
145 NS_IMETHODIMP
146 nsBaseAppShell::Exit(void) {
147 if (mRunning && !mExiting) {
148 MessageLoop::current()->Quit();
150 mExiting = true;
151 return NS_OK;
154 NS_IMETHODIMP
155 nsBaseAppShell::FavorPerformanceHint(bool favorPerfOverStarvation,
156 uint32_t starvationDelay) {
157 mStarvationDelay = PR_MillisecondsToInterval(starvationDelay);
158 if (favorPerfOverStarvation) {
159 ++mFavorPerf;
160 } else {
161 --mFavorPerf;
162 mSwitchTime = PR_IntervalNow();
164 return NS_OK;
167 NS_IMETHODIMP
168 nsBaseAppShell::SuspendNative() {
169 ++mSuspendNativeCount;
170 return NS_OK;
173 NS_IMETHODIMP
174 nsBaseAppShell::ResumeNative() {
175 --mSuspendNativeCount;
176 NS_ASSERTION(mSuspendNativeCount >= 0,
177 "Unbalanced call to nsBaseAppShell::ResumeNative!");
178 return NS_OK;
181 NS_IMETHODIMP
182 nsBaseAppShell::GetEventloopNestingLevel(uint32_t* aNestingLevelResult) {
183 NS_ENSURE_ARG_POINTER(aNestingLevelResult);
185 *aNestingLevelResult = mEventloopNestingLevel;
187 return NS_OK;
190 //-------------------------------------------------------------------------
191 // nsIThreadObserver methods:
193 // Called from any thread
194 NS_IMETHODIMP
195 nsBaseAppShell::OnDispatchedEvent() {
196 if (mBlockNativeEvent) return NS_OK;
198 if (mNativeEventPending.exchange(true)) return NS_OK;
200 // Returns on the main thread in NativeEventCallback above
201 ScheduleNativeEventCallback();
202 return NS_OK;
205 // Called from the main thread
206 NS_IMETHODIMP
207 nsBaseAppShell::OnProcessNextEvent(nsIThreadInternal* thr, bool mayWait) {
208 if (mBlockNativeEvent) {
209 if (!mayWait) return NS_OK;
210 // Hmm, we're in a nested native event loop and would like to get
211 // back to it ASAP, but it seems a gecko event has caused us to
212 // spin up a nested XPCOM event loop (eg. modal window), so we
213 // really must start processing native events here again.
214 mBlockNativeEvent = false;
215 if (NS_HasPendingEvents(thr))
216 OnDispatchedEvent(); // in case we blocked it earlier
219 PRIntervalTime start = PR_IntervalNow();
220 PRIntervalTime limit = THREAD_EVENT_STARVATION_LIMIT;
222 // Unblock outer nested wait loop (below).
223 if (mBlockedWait) *mBlockedWait = false;
225 bool* oldBlockedWait = mBlockedWait;
226 mBlockedWait = &mayWait;
228 // When mayWait is true, we need to make sure that there is an event in the
229 // thread's event queue before we return. Otherwise, the thread will block
230 // on its event queue waiting for an event.
231 bool needEvent = mayWait;
232 // Reset prior to invoking DoProcessNextNativeEvent which might cause
233 // NativeEventCallback to process gecko events.
234 mProcessedGeckoEvents = false;
236 if (mFavorPerf <= 0 && start > mSwitchTime + mStarvationDelay) {
237 // Favor pending native events
238 PRIntervalTime now = start;
239 bool keepGoing;
240 do {
241 mLastNativeEventTime = now;
242 keepGoing = DoProcessNextNativeEvent(false);
243 } while (keepGoing && ((now = PR_IntervalNow()) - start) < limit);
244 } else {
245 // Avoid starving native events completely when in performance mode
246 if (start - mLastNativeEventTime > limit) {
247 mLastNativeEventTime = start;
248 DoProcessNextNativeEvent(false);
252 while (!NS_HasPendingEvents(thr) && !mProcessedGeckoEvents) {
253 // If we have been asked to exit from Run, then we should not wait for
254 // events to process. Note that an inner nested event loop causes
255 // 'mayWait' to become false too, through 'mBlockedWait'.
256 if (mExiting) mayWait = false;
258 mLastNativeEventTime = PR_IntervalNow();
259 if (!DoProcessNextNativeEvent(mayWait) || !mayWait) break;
262 mBlockedWait = oldBlockedWait;
264 // Make sure that the thread event queue does not block on its monitor, as
265 // it normally would do if it did not have any pending events. To avoid
266 // that, we simply insert a dummy event into its queue during shutdown.
267 if (needEvent && !mExiting && !NS_HasPendingEvents(thr)) {
268 DispatchDummyEvent(thr);
271 return NS_OK;
274 bool nsBaseAppShell::DispatchDummyEvent(nsIThread* aTarget) {
275 NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
277 if (!mDummyEvent) mDummyEvent = new mozilla::Runnable("DummyEvent");
279 return NS_SUCCEEDED(aTarget->Dispatch(mDummyEvent, NS_DISPATCH_NORMAL));
282 void nsBaseAppShell::IncrementEventloopNestingLevel() {
283 ++mEventloopNestingLevel;
284 CrashReporter::SetEventloopNestingLevel(mEventloopNestingLevel);
287 void nsBaseAppShell::DecrementEventloopNestingLevel() {
288 --mEventloopNestingLevel;
289 CrashReporter::SetEventloopNestingLevel(mEventloopNestingLevel);
292 // Called from the main thread
293 NS_IMETHODIMP
294 nsBaseAppShell::AfterProcessNextEvent(nsIThreadInternal* thr,
295 bool eventWasProcessed) {
296 return NS_OK;
299 NS_IMETHODIMP
300 nsBaseAppShell::Observe(nsISupports* subject, const char* topic,
301 const char16_t* data) {
302 NS_ASSERTION(!strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID), "oops");
303 Exit();
304 return NS_OK;