michael@0: /* -*- Mode: c++; tab-width: 2; indent-tabs-mode: nil; -*- */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #include "base/message_loop.h" michael@0: michael@0: #include "nsBaseAppShell.h" michael@0: #if defined(MOZ_CRASHREPORTER) michael@0: #include "nsExceptionHandler.h" michael@0: #endif michael@0: #include "nsThreadUtils.h" michael@0: #include "nsIObserverService.h" michael@0: #include "nsServiceManagerUtils.h" michael@0: #include "mozilla/Services.h" michael@0: michael@0: // When processing the next thread event, the appshell may process native michael@0: // events (if not in performance mode), which can result in suppressing the michael@0: // next thread event for at most this many ticks: michael@0: #define THREAD_EVENT_STARVATION_LIMIT PR_MillisecondsToInterval(20) michael@0: michael@0: NS_IMPL_ISUPPORTS(nsBaseAppShell, nsIAppShell, nsIThreadObserver, nsIObserver) michael@0: michael@0: nsBaseAppShell::nsBaseAppShell() michael@0: : mSuspendNativeCount(0) michael@0: , mEventloopNestingLevel(0) michael@0: , mBlockedWait(nullptr) michael@0: , mFavorPerf(0) michael@0: , mNativeEventPending(false) michael@0: , mStarvationDelay(0) michael@0: , mSwitchTime(0) michael@0: , mLastNativeEventTime(0) michael@0: , mEventloopNestingState(eEventloopNone) michael@0: , mRunning(false) michael@0: , mExiting(false) michael@0: , mBlockNativeEvent(false) michael@0: { michael@0: } michael@0: michael@0: nsBaseAppShell::~nsBaseAppShell() michael@0: { michael@0: NS_ASSERTION(mSyncSections.IsEmpty(), "Must have run all sync sections"); michael@0: } michael@0: michael@0: nsresult michael@0: nsBaseAppShell::Init() michael@0: { michael@0: // Configure ourselves as an observer for the current thread: michael@0: michael@0: nsCOMPtr threadInt = michael@0: do_QueryInterface(NS_GetCurrentThread()); michael@0: NS_ENSURE_STATE(threadInt); michael@0: michael@0: threadInt->SetObserver(this); michael@0: michael@0: nsCOMPtr obsSvc = michael@0: mozilla::services::GetObserverService(); michael@0: if (obsSvc) michael@0: obsSvc->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false); michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Called by nsAppShell's native event callback michael@0: void michael@0: nsBaseAppShell::NativeEventCallback() michael@0: { michael@0: if (!mNativeEventPending.exchange(false)) michael@0: return; michael@0: michael@0: // If DoProcessNextNativeEvent is on the stack, then we assume that we can michael@0: // just unwind and let nsThread::ProcessNextEvent process the next event. michael@0: // However, if we are called from a nested native event loop (maybe via some michael@0: // plug-in or library function), then go ahead and process Gecko events now. michael@0: if (mEventloopNestingState == eEventloopXPCOM) { michael@0: mEventloopNestingState = eEventloopOther; michael@0: // XXX there is a tiny risk we will never get a new NativeEventCallback, michael@0: // XXX see discussion in bug 389931. michael@0: return; michael@0: } michael@0: michael@0: // nsBaseAppShell::Run is not being used to pump events, so this may be michael@0: // our only opportunity to process pending gecko events. michael@0: michael@0: nsIThread *thread = NS_GetCurrentThread(); michael@0: bool prevBlockNativeEvent = mBlockNativeEvent; michael@0: if (mEventloopNestingState == eEventloopOther) { michael@0: if (!NS_HasPendingEvents(thread)) michael@0: return; michael@0: // We're in a nested native event loop and have some gecko events to michael@0: // process. While doing that we block processing native events from the michael@0: // appshell - instead, we want to get back to the nested native event michael@0: // loop ASAP (bug 420148). michael@0: mBlockNativeEvent = true; michael@0: } michael@0: michael@0: IncrementEventloopNestingLevel(); michael@0: EventloopNestingState prevVal = mEventloopNestingState; michael@0: NS_ProcessPendingEvents(thread, THREAD_EVENT_STARVATION_LIMIT); michael@0: mProcessedGeckoEvents = true; michael@0: mEventloopNestingState = prevVal; michael@0: mBlockNativeEvent = prevBlockNativeEvent; michael@0: michael@0: // Continue processing pending events later (we don't want to starve the michael@0: // embedders event loop). michael@0: if (NS_HasPendingEvents(thread)) michael@0: DoProcessMoreGeckoEvents(); michael@0: michael@0: DecrementEventloopNestingLevel(); michael@0: } michael@0: michael@0: // Note, this is currently overidden on windows, see comments in nsAppShell for michael@0: // details. michael@0: void michael@0: nsBaseAppShell::DoProcessMoreGeckoEvents() michael@0: { michael@0: OnDispatchedEvent(nullptr); michael@0: } michael@0: michael@0: michael@0: // Main thread via OnProcessNextEvent below michael@0: bool michael@0: nsBaseAppShell::DoProcessNextNativeEvent(bool mayWait, uint32_t recursionDepth) michael@0: { michael@0: // The next native event to be processed may trigger our NativeEventCallback, michael@0: // in which case we do not want it to process any thread events since we'll michael@0: // do that when this function returns. michael@0: // michael@0: // If the next native event is not our NativeEventCallback, then we may end michael@0: // up recursing into this function. michael@0: // michael@0: // However, if the next native event is not our NativeEventCallback, but it michael@0: // results in another native event loop, then our NativeEventCallback could michael@0: // fire and it will see mEventloopNestingState as eEventloopOther. michael@0: // michael@0: EventloopNestingState prevVal = mEventloopNestingState; michael@0: mEventloopNestingState = eEventloopXPCOM; michael@0: michael@0: IncrementEventloopNestingLevel(); michael@0: michael@0: bool result = ProcessNextNativeEvent(mayWait); michael@0: michael@0: // Make sure that any sync sections registered during this most recent event michael@0: // are run now. This is not considered a stable state because we're not back michael@0: // to the event loop yet. michael@0: RunSyncSections(false, recursionDepth); michael@0: michael@0: DecrementEventloopNestingLevel(); michael@0: michael@0: mEventloopNestingState = prevVal; michael@0: return result; michael@0: } michael@0: michael@0: //------------------------------------------------------------------------- michael@0: // nsIAppShell methods: michael@0: michael@0: NS_IMETHODIMP michael@0: nsBaseAppShell::Run(void) michael@0: { michael@0: NS_ENSURE_STATE(!mRunning); // should not call Run twice michael@0: mRunning = true; michael@0: michael@0: nsIThread *thread = NS_GetCurrentThread(); michael@0: michael@0: MessageLoop::current()->Run(); michael@0: michael@0: NS_ProcessPendingEvents(thread); michael@0: michael@0: mRunning = false; michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsBaseAppShell::Exit(void) michael@0: { michael@0: if (mRunning && !mExiting) { michael@0: MessageLoop::current()->Quit(); michael@0: } michael@0: mExiting = true; michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsBaseAppShell::FavorPerformanceHint(bool favorPerfOverStarvation, michael@0: uint32_t starvationDelay) michael@0: { michael@0: mStarvationDelay = PR_MillisecondsToInterval(starvationDelay); michael@0: if (favorPerfOverStarvation) { michael@0: ++mFavorPerf; michael@0: } else { michael@0: --mFavorPerf; michael@0: mSwitchTime = PR_IntervalNow(); michael@0: } michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsBaseAppShell::SuspendNative() michael@0: { michael@0: ++mSuspendNativeCount; michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsBaseAppShell::ResumeNative() michael@0: { michael@0: --mSuspendNativeCount; michael@0: NS_ASSERTION(mSuspendNativeCount >= 0, "Unbalanced call to nsBaseAppShell::ResumeNative!"); michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsBaseAppShell::GetEventloopNestingLevel(uint32_t* aNestingLevelResult) michael@0: { michael@0: NS_ENSURE_ARG_POINTER(aNestingLevelResult); michael@0: michael@0: *aNestingLevelResult = mEventloopNestingLevel; michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: //------------------------------------------------------------------------- michael@0: // nsIThreadObserver methods: michael@0: michael@0: // Called from any thread michael@0: NS_IMETHODIMP michael@0: nsBaseAppShell::OnDispatchedEvent(nsIThreadInternal *thr) michael@0: { michael@0: if (mBlockNativeEvent) michael@0: return NS_OK; michael@0: michael@0: if (mNativeEventPending.exchange(true)) michael@0: return NS_OK; michael@0: michael@0: // Returns on the main thread in NativeEventCallback above michael@0: ScheduleNativeEventCallback(); michael@0: return NS_OK; michael@0: } michael@0: michael@0: // Called from the main thread michael@0: NS_IMETHODIMP michael@0: nsBaseAppShell::OnProcessNextEvent(nsIThreadInternal *thr, bool mayWait, michael@0: uint32_t recursionDepth) michael@0: { michael@0: if (mBlockNativeEvent) { michael@0: if (!mayWait) michael@0: return NS_OK; michael@0: // Hmm, we're in a nested native event loop and would like to get michael@0: // back to it ASAP, but it seems a gecko event has caused us to michael@0: // spin up a nested XPCOM event loop (eg. modal window), so we michael@0: // really must start processing native events here again. michael@0: mBlockNativeEvent = false; michael@0: if (NS_HasPendingEvents(thr)) michael@0: OnDispatchedEvent(thr); // in case we blocked it earlier michael@0: } michael@0: michael@0: PRIntervalTime start = PR_IntervalNow(); michael@0: PRIntervalTime limit = THREAD_EVENT_STARVATION_LIMIT; michael@0: michael@0: // Unblock outer nested wait loop (below). michael@0: if (mBlockedWait) michael@0: *mBlockedWait = false; michael@0: michael@0: bool *oldBlockedWait = mBlockedWait; michael@0: mBlockedWait = &mayWait; michael@0: michael@0: // When mayWait is true, we need to make sure that there is an event in the michael@0: // thread's event queue before we return. Otherwise, the thread will block michael@0: // on its event queue waiting for an event. michael@0: bool needEvent = mayWait; michael@0: // Reset prior to invoking DoProcessNextNativeEvent which might cause michael@0: // NativeEventCallback to process gecko events. michael@0: mProcessedGeckoEvents = false; michael@0: michael@0: if (mFavorPerf <= 0 && start > mSwitchTime + mStarvationDelay) { michael@0: // Favor pending native events michael@0: PRIntervalTime now = start; michael@0: bool keepGoing; michael@0: do { michael@0: mLastNativeEventTime = now; michael@0: keepGoing = DoProcessNextNativeEvent(false, recursionDepth); michael@0: } while (keepGoing && ((now = PR_IntervalNow()) - start) < limit); michael@0: } else { michael@0: // Avoid starving native events completely when in performance mode michael@0: if (start - mLastNativeEventTime > limit) { michael@0: mLastNativeEventTime = start; michael@0: DoProcessNextNativeEvent(false, recursionDepth); michael@0: } michael@0: } michael@0: michael@0: while (!NS_HasPendingEvents(thr) && !mProcessedGeckoEvents) { michael@0: // If we have been asked to exit from Run, then we should not wait for michael@0: // events to process. Note that an inner nested event loop causes michael@0: // 'mayWait' to become false too, through 'mBlockedWait'. michael@0: if (mExiting) michael@0: mayWait = false; michael@0: michael@0: mLastNativeEventTime = PR_IntervalNow(); michael@0: if (!DoProcessNextNativeEvent(mayWait, recursionDepth) || !mayWait) michael@0: break; michael@0: } michael@0: michael@0: mBlockedWait = oldBlockedWait; michael@0: michael@0: // Make sure that the thread event queue does not block on its monitor, as michael@0: // it normally would do if it did not have any pending events. To avoid michael@0: // that, we simply insert a dummy event into its queue during shutdown. michael@0: if (needEvent && !mExiting && !NS_HasPendingEvents(thr)) { michael@0: DispatchDummyEvent(thr); michael@0: } michael@0: michael@0: // We're about to run an event, so we're in a stable state. michael@0: RunSyncSections(true, recursionDepth); michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: bool michael@0: nsBaseAppShell::DispatchDummyEvent(nsIThread* aTarget) michael@0: { michael@0: NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); michael@0: michael@0: if (!mDummyEvent) michael@0: mDummyEvent = new nsRunnable(); michael@0: michael@0: return NS_SUCCEEDED(aTarget->Dispatch(mDummyEvent, NS_DISPATCH_NORMAL)); michael@0: } michael@0: michael@0: void michael@0: nsBaseAppShell::IncrementEventloopNestingLevel() michael@0: { michael@0: ++mEventloopNestingLevel; michael@0: #if defined(MOZ_CRASHREPORTER) michael@0: CrashReporter::SetEventloopNestingLevel(mEventloopNestingLevel); michael@0: #endif michael@0: } michael@0: michael@0: void michael@0: nsBaseAppShell::DecrementEventloopNestingLevel() michael@0: { michael@0: --mEventloopNestingLevel; michael@0: #if defined(MOZ_CRASHREPORTER) michael@0: CrashReporter::SetEventloopNestingLevel(mEventloopNestingLevel); michael@0: #endif michael@0: } michael@0: michael@0: void michael@0: nsBaseAppShell::RunSyncSectionsInternal(bool aStable, michael@0: uint32_t aThreadRecursionLevel) michael@0: { michael@0: NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); michael@0: NS_ASSERTION(!mSyncSections.IsEmpty(), "Nothing to do!"); michael@0: michael@0: // We've got synchronous sections. Run all of them that are are awaiting a michael@0: // stable state if aStable is true (i.e. we really are in a stable state). michael@0: // Also run the synchronous sections that are simply waiting for the right michael@0: // combination of event loop nesting level and thread recursion level. michael@0: // Note that a synchronous section could add another synchronous section, so michael@0: // we don't remove elements from mSyncSections until all sections have been michael@0: // run, or else we'll screw up our iteration. Any sync sections that are not michael@0: // ready to be run are saved for later. michael@0: michael@0: nsTArray pendingSyncSections; michael@0: michael@0: for (uint32_t i = 0; i < mSyncSections.Length(); i++) { michael@0: SyncSection& section = mSyncSections[i]; michael@0: if ((aStable && section.mStable) || michael@0: (!section.mStable && michael@0: section.mEventloopNestingLevel == mEventloopNestingLevel && michael@0: section.mThreadRecursionLevel == aThreadRecursionLevel)) { michael@0: section.mRunnable->Run(); michael@0: } michael@0: else { michael@0: // Add to pending list. michael@0: SyncSection* pending = pendingSyncSections.AppendElement(); michael@0: section.Forget(pending); michael@0: } michael@0: } michael@0: michael@0: mSyncSections.SwapElements(pendingSyncSections); michael@0: } michael@0: michael@0: void michael@0: nsBaseAppShell::ScheduleSyncSection(nsIRunnable* aRunnable, bool aStable) michael@0: { michael@0: NS_ASSERTION(NS_IsMainThread(), "Should be on main thread."); michael@0: michael@0: nsIThread* thread = NS_GetCurrentThread(); michael@0: michael@0: // Add this runnable to our list of synchronous sections. michael@0: SyncSection* section = mSyncSections.AppendElement(); michael@0: section->mStable = aStable; michael@0: section->mRunnable = aRunnable; michael@0: michael@0: // If aStable is false then this synchronous section is supposed to run before michael@0: // the next event at the current nesting level. Record the event loop nesting michael@0: // level and the thread recursion level so that the synchronous section will michael@0: // run at the proper time. michael@0: if (!aStable) { michael@0: section->mEventloopNestingLevel = mEventloopNestingLevel; michael@0: michael@0: nsCOMPtr threadInternal = do_QueryInterface(thread); michael@0: NS_ASSERTION(threadInternal, "This should never fail!"); michael@0: michael@0: uint32_t recursionLevel; michael@0: if (NS_FAILED(threadInternal->GetRecursionDepth(&recursionLevel))) { michael@0: NS_ERROR("This should never fail!"); michael@0: } michael@0: michael@0: // Due to the weird way that the thread recursion counter is implemented we michael@0: // subtract one from the recursion level if we have one. michael@0: section->mThreadRecursionLevel = recursionLevel ? recursionLevel - 1 : 0; michael@0: } michael@0: michael@0: // Ensure we've got a pending event, else the callbacks will never run. michael@0: if (!NS_HasPendingEvents(thread) && !DispatchDummyEvent(thread)) { michael@0: RunSyncSections(true, 0); michael@0: } michael@0: } michael@0: michael@0: // Called from the main thread michael@0: NS_IMETHODIMP michael@0: nsBaseAppShell::AfterProcessNextEvent(nsIThreadInternal *thr, michael@0: uint32_t recursionDepth, michael@0: bool eventWasProcessed) michael@0: { michael@0: // We've just finished running an event, so we're in a stable state. michael@0: RunSyncSections(true, recursionDepth); michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsBaseAppShell::Observe(nsISupports *subject, const char *topic, michael@0: const char16_t *data) michael@0: { michael@0: NS_ASSERTION(!strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID), "oops"); michael@0: Exit(); michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsBaseAppShell::RunInStableState(nsIRunnable* aRunnable) michael@0: { michael@0: ScheduleSyncSection(aRunnable, true); michael@0: return NS_OK; michael@0: } michael@0: michael@0: NS_IMETHODIMP michael@0: nsBaseAppShell::RunBeforeNextEvent(nsIRunnable* aRunnable) michael@0: { michael@0: ScheduleSyncSection(aRunnable, false); michael@0: return NS_OK; michael@0: }