From 25c0d109329e7ba21802d13ad8563572833fb399 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emilio=20Cobos=20=C3=81lvarez?= Date: Tue, 10 Oct 2023 08:51:12 +0000 Subject: [PATCH] Bug 1624819 - Remove TaskCategory and other quantum dom remnants. r=smaug,media-playback-reviewers,credential-management-reviewers,cookie-reviewers,places-reviewers,win-reviewers,valentin,mhowell,sgalich,alwu Sorry this is not a particularly easy patch to review. But it should be mostly straight-forward. I kept Document::Dispatch mostly for convenience, but could be cleaned-up too / changed by SchedulerGroup::Dispatch. Similarly maybe that can just be NS_DispatchToMainThread if we add an NS_IsMainThread check there or something (to preserve shutdown semantics). Differential Revision: https://phabricator.services.mozilla.com/D190450 --- docshell/base/nsDocShell.cpp | 37 +++---- docshell/base/nsDocShell.h | 3 +- docshell/base/nsDocShellTreeOwner.cpp | 8 +- docshell/base/nsPingListener.cpp | 2 +- docshell/shistory/nsSHEntryShared.cpp | 23 ++--- dom/base/ChromeUtils.cpp | 3 +- dom/base/DispatcherTrait.cpp | 28 ------ dom/base/DispatcherTrait.h | 44 --------- dom/base/DocGroup.cpp | 34 +------ dom/base/DocGroup.h | 8 -- dom/base/Document.cpp | 66 ++++--------- dom/base/Document.h | 10 +- dom/base/PointerLockManager.cpp | 2 +- dom/base/PostMessageEvent.cpp | 2 +- dom/base/Selection.cpp | 4 +- dom/base/moz.build | 2 - dom/base/nsContentPolicy.cpp | 15 +-- dom/base/nsContentUtils.cpp | 22 ----- dom/base/nsContentUtils.h | 4 - dom/base/nsGlobalWindowInner.cpp | 38 ++------ dom/base/nsGlobalWindowInner.h | 10 +- dom/base/nsGlobalWindowOuter.cpp | 33 ++----- dom/base/nsGlobalWindowOuter.h | 10 +- dom/base/nsIGlobalObject.h | 7 +- dom/base/nsPIDOMWindow.h | 5 - dom/bindings/SimpleGlobalObject.h | 14 ++- dom/canvas/ImageBitmap.cpp | 2 +- dom/clients/api/Client.cpp | 7 +- dom/clients/api/ClientDOMUtil.h | 4 +- dom/clients/api/Clients.cpp | 8 +- dom/clients/manager/ClientManagerService.cpp | 6 +- dom/clients/manager/ClientNavigateOpChild.cpp | 2 +- dom/clients/manager/ClientSourceParent.cpp | 9 +- dom/events/AsyncEventDispatcher.cpp | 18 +--- dom/events/DataTransferItem.cpp | 2 +- dom/events/EventListenerService.cpp | 8 +- dom/events/IMEContentObserver.cpp | 16 +--- dom/fetch/Fetch.cpp | 13 ++- dom/fetch/FetchChild.cpp | 9 +- dom/fetch/FetchStreamReader.cpp | 4 +- dom/fetch/FetchUtil.cpp | 3 +- dom/file/Blob.cpp | 2 +- dom/file/FileReader.cpp | 2 +- dom/file/ipc/RemoteLazyInputStreamThread.cpp | 4 +- dom/file/uri/BlobURLProtocolHandler.cpp | 3 +- dom/filesystem/FileSystemUtils.cpp | 2 +- dom/geolocation/Geolocation.cpp | 32 ++----- dom/html/HTMLCanvasElement.cpp | 14 ++- dom/html/HTMLDialogElement.cpp | 8 +- dom/html/HTMLMediaElement.cpp | 96 ++++++++----------- dom/html/HTMLMediaElement.h | 11 --- dom/html/HTMLTrackElement.cpp | 4 +- dom/html/HTMLVideoElement.cpp | 8 +- dom/html/TextTrackManager.cpp | 10 +- dom/html/nsGenericHTMLElement.cpp | 3 +- dom/html/nsHTMLContentSink.cpp | 4 +- dom/html/nsHTMLDocument.cpp | 3 +- dom/indexedDB/ActorsParent.cpp | 4 +- dom/indexedDB/IDBFactory.cpp | 2 +- dom/indexedDB/SchemaUpgrades.cpp | 4 +- dom/indexedDB/ScriptErrorHelper.cpp | 6 +- dom/ipc/BrowserChild.cpp | 49 +--------- dom/ipc/BrowserChild.h | 22 +---- dom/ipc/ContentChild.cpp | 1 - dom/jsurl/nsJSProtocolHandler.cpp | 2 +- ...kgroundVideoDecodingPermissionObserver.cpp | 19 ++-- dom/media/GraphDriver.cpp | 2 +- dom/media/MediaDevices.cpp | 8 +- dom/media/MediaRecorder.cpp | 45 +++++---- dom/media/MediaStreamTrack.cpp | 9 +- dom/media/MediaTrackGraph.cpp | 12 +-- dom/media/MediaTrackGraph.h | 3 +- dom/media/VideoStreamTrack.cpp | 4 +- dom/media/VideoUtils.cpp | 3 +- .../autoplay/GVAutoplayPermissionRequest.cpp | 2 +- dom/media/doctor/DecoderDoctorLogger.cpp | 1 - dom/media/gmp/GMPServiceChild.cpp | 2 +- dom/media/gtest/GMPTestMonitor.h | 6 +- dom/media/gtest/TestCDMStorage.cpp | 23 ++--- dom/media/imagecapture/CaptureTask.cpp | 2 +- .../mediacapabilities/MediaCapabilities.cpp | 3 +- dom/media/mediasource/MediaSource.cpp | 3 +- dom/media/platforms/AllocationPolicy.cpp | 22 ++--- dom/media/webaudio/AnalyserNode.cpp | 2 +- dom/media/webaudio/AudioContext.cpp | 9 +- dom/media/webaudio/AudioDestinationNode.cpp | 8 +- dom/media/webaudio/AudioNode.cpp | 7 +- dom/media/webaudio/AudioNode.h | 7 -- dom/media/webaudio/AudioNodeEngine.cpp | 5 +- dom/media/webaudio/AudioNodeEngine.h | 3 - dom/media/webaudio/DynamicsCompressorNode.cpp | 3 +- dom/media/webaudio/MediaBufferDecoder.cpp | 3 +- .../webaudio/MediaElementAudioSourceNode.cpp | 7 +- dom/media/webaudio/ScriptProcessorNode.cpp | 2 +- dom/media/webaudio/WebAudioUtils.cpp | 2 +- dom/media/webrtc/CubebDeviceEnumerator.cpp | 1 - dom/media/webrtc/jsapi/PeerConnectionImpl.cpp | 3 +- dom/media/webvtt/TextTrack.cpp | 8 +- dom/media/webvtt/TextTrackCue.cpp | 6 +- dom/media/webvtt/TextTrackList.cpp | 8 +- dom/messagechannel/MessagePort.cpp | 8 -- dom/network/TCPSocket.cpp | 4 +- dom/notification/Notification.cpp | 20 +--- dom/payments/PaymentResponse.cpp | 4 +- dom/performance/Performance.cpp | 6 +- dom/promise/Promise.cpp | 2 +- .../PrototypeDocumentContentSink.cpp | 3 +- dom/script/ScriptLoader.cpp | 6 +- dom/script/ShadowRealmGlobalScope.h | 11 ++- dom/security/nsCSPContext.cpp | 2 +- dom/serviceworkers/ServiceWorkerContainer.cpp | 10 +- .../ServiceWorkerContainerProxy.cpp | 12 +-- dom/serviceworkers/ServiceWorkerOp.cpp | 4 +- dom/serviceworkers/ServiceWorkerProxy.cpp | 9 +- .../ServiceWorkerRegistration.cpp | 4 +- .../ServiceWorkerRegistrationInfo.cpp | 4 +- .../ServiceWorkerRegistrationProxy.cpp | 21 ++-- .../ServiceWorkerShutdownState.cpp | 3 +- dom/smil/SMILTimedElement.cpp | 3 +- dom/storage/Storage.cpp | 2 +- dom/storage/StorageActivityService.cpp | 4 +- dom/websocket/WebSocket.cpp | 13 +-- dom/webtransport/api/WebTransport.cpp | 7 +- dom/workers/WorkerPrivate.cpp | 3 +- dom/workers/WorkerScope.cpp | 10 +- dom/workers/WorkerScope.h | 10 +- .../remoteworkers/RemoteWorkerChild.cpp | 12 +-- .../remoteworkers/RemoteWorkerManager.cpp | 5 +- .../remoteworkers/RemoteWorkerParent.cpp | 3 +- .../remoteworkers/RemoteWorkerService.cpp | 3 +- .../sharedworkers/SharedWorkerService.cpp | 16 ++-- dom/worklet/WorkletGlobalScope.cpp | 13 +++ dom/worklet/WorkletGlobalScope.h | 7 +- dom/xhr/XMLHttpRequestMainThread.cpp | 17 ++-- dom/xml/nsXMLContentSink.cpp | 6 +- dom/xul/XULButtonElement.cpp | 26 +++-- dom/xul/XULMenuParentElement.cpp | 2 +- editor/spellchecker/EditorSpellCheck.cpp | 2 +- gfx/ipc/VsyncIOThreadHolder.cpp | 6 +- gfx/layers/ipc/SharedSurfacesChild.cpp | 7 +- gfx/src/gfxCrashReporterUtils.cpp | 11 +-- gfx/src/nsThebesFontEnumerator.cpp | 3 +- image/IProgressObserver.h | 4 - image/ImageFactory.cpp | 2 +- image/ProgressTracker.cpp | 58 +---------- image/ProgressTracker.h | 16 ---- image/decoders/icon/mac/nsIconChannelCocoa.mm | 4 +- image/decoders/icon/win/nsIconChannel.cpp | 11 +-- image/imgLoader.cpp | 3 +- image/imgRequestProxy.cpp | 73 ++------------ image/imgRequestProxy.h | 9 +- ipc/mscom/EnsureMTA.cpp | 1 - js/xpconnect/src/BackstagePass.h | 8 ++ js/xpconnect/src/SandboxPrivate.h | 20 ++-- layout/base/PresShell.cpp | 7 +- layout/base/ZoomConstraintsClient.cpp | 2 +- layout/base/nsCaret.cpp | 9 +- layout/base/nsDocumentViewer.cpp | 2 +- layout/base/nsPresContext.cpp | 7 +- layout/base/nsRefreshDriver.cpp | 2 +- layout/generic/nsGfxScrollFrame.cpp | 3 +- layout/printing/nsPagePrintTimer.cpp | 17 ++-- layout/printing/nsPrintJob.cpp | 3 +- layout/style/ErrorReporter.cpp | 3 +- layout/style/Loader.cpp | 17 +--- layout/style/Loader.h | 4 - layout/style/StyleSheet.cpp | 3 +- layout/style/nsFontFaceLoader.cpp | 14 +-- layout/style/nsStyleStruct.cpp | 2 +- layout/tables/nsTableFrame.cpp | 3 +- layout/xul/nsMenuPopupFrame.cpp | 2 +- layout/xul/nsRepeatService.cpp | 2 +- layout/xul/nsXULPopupManager.cpp | 9 +- layout/xul/nsXULTooltipListener.cpp | 2 +- layout/xul/tree/nsTreeBodyFrame.cpp | 10 +- layout/xul/tree/nsTreeSelection.cpp | 3 +- modules/libpref/Preferences.cpp | 16 ++-- netwerk/base/Predictor.cpp | 3 +- netwerk/base/nsBaseChannel.cpp | 3 +- netwerk/cookie/CookieJarSettings.cpp | 3 +- netwerk/dns/DNSRequestChild.cpp | 3 +- netwerk/ipc/NeckoChild.cpp | 11 +-- netwerk/protocol/gio/GIOChannelChild.cpp | 7 +- netwerk/protocol/http/HttpChannelChild.cpp | 15 +-- .../protocol/http/InterceptedHttpChannel.cpp | 3 +- .../protocol/res/ExtensionProtocolHandler.cpp | 6 +- .../websocket/WebSocketChannelChild.cpp | 3 +- parser/html/nsHtml5StreamParser.cpp | 20 +--- parser/html/nsHtml5StreamParser.h | 5 - parser/html/nsHtml5TreeOpExecutor.cpp | 9 +- parser/html/nsHtml5TreeOperation.cpp | 3 +- .../win/src/sandboxbroker/sandboxBroker.cpp | 6 +- .../backgroundhangmonitor/HangDetails.cpp | 3 +- .../places/nsAnnoProtocolHandler.cpp | 3 +- .../satchel/nsFormFillController.cpp | 2 +- .../core/ipc/TelemetryIPCAccumulator.cpp | 3 +- .../other/UntrustedModulesBackupService.cpp | 8 +- toolkit/xre/dllservices/WinDllServices.cpp | 6 +- .../dllservices/mozglue/WindowsDllServices.h | 5 +- tools/profiler/core/platform.cpp | 2 +- tools/profiler/gecko/nsProfiler.cpp | 56 +++++------ uriloader/base/nsDocLoader.cpp | 10 +- widget/PuppetWidget.cpp | 2 +- widget/gtk/nsClipboard.cpp | 1 - widget/nsNativeTheme.cpp | 3 +- widget/windows/WinUtils.cpp | 6 +- xpcom/base/DebuggerOnGCRunnable.cpp | 7 +- xpcom/base/nsConsoleService.cpp | 2 +- xpcom/threads/IdleTaskRunner.cpp | 1 - xpcom/threads/SchedulerGroup.cpp | 21 +--- xpcom/threads/SchedulerGroup.h | 12 +-- xpcom/threads/TaskCategory.h | 47 --------- xpcom/threads/moz.build | 1 - xpcom/threads/nsThreadPool.cpp | 6 +- 214 files changed, 595 insertions(+), 1481 deletions(-) delete mode 100644 dom/base/DispatcherTrait.cpp delete mode 100644 dom/base/DispatcherTrait.h delete mode 100644 xpcom/threads/TaskCategory.h diff --git a/docshell/base/nsDocShell.cpp b/docshell/base/nsDocShell.cpp index 962e51179f36..31b1e8df64d9 100644 --- a/docshell/base/nsDocShell.cpp +++ b/docshell/base/nsDocShell.cpp @@ -1373,29 +1373,21 @@ void nsDocShell::FirePageHideShowNonRecursive(bool aShow) { } } -nsresult nsDocShell::Dispatch(TaskCategory aCategory, - already_AddRefed&& aRunnable) { +nsresult nsDocShell::Dispatch(already_AddRefed&& aRunnable) { nsCOMPtr runnable(aRunnable); - nsCOMPtr win = GetWindow(); - if (NS_WARN_IF(!win)) { + if (NS_WARN_IF(!GetWindow())) { // Window should only be unavailable after destroyed. MOZ_ASSERT(mIsBeingDestroyed); return NS_ERROR_FAILURE; } - - if (win->GetDocGroup()) { - return win->GetDocGroup()->Dispatch(aCategory, runnable.forget()); - } - - return SchedulerGroup::Dispatch(aCategory, runnable.forget()); + return SchedulerGroup::Dispatch(runnable.forget()); } NS_IMETHODIMP nsDocShell::DispatchLocationChangeEvent() { - return Dispatch( - TaskCategory::Other, - NewRunnableMethod("nsDocShell::FireDummyOnLocationChange", this, - &nsDocShell::FireDummyOnLocationChange)); + return Dispatch(NewRunnableMethod("nsDocShell::FireDummyOnLocationChange", + this, + &nsDocShell::FireDummyOnLocationChange)); } NS_IMETHODIMP @@ -2579,7 +2571,7 @@ void nsDocShell::MaybeCreateInitialClientSource(nsIPrincipal* aPrincipal) { } mInitialClientSource = ClientManager::CreateSource( - ClientType::Window, win->EventTargetFor(TaskCategory::Other), principal); + ClientType::Window, GetMainThreadSerialEventTarget(), principal); MOZ_DIAGNOSTIC_ASSERT(mInitialClientSource); // Mark the initial client as execution ready, but owned by the docshell. @@ -7262,7 +7254,7 @@ nsresult nsDocShell::RestorePresentation(nsISHEntry* aSHEntry, mRestorePresentationEvent.Revoke(); RefPtr evt = new RestorePresentationEvent(this); - nsresult rv = Dispatch(TaskCategory::Other, do_AddRef(evt)); + nsresult rv = Dispatch(do_AddRef(evt)); if (NS_SUCCEEDED(rv)) { mRestorePresentationEvent = evt.get(); // The rest of the restore processing will happen on our event @@ -9350,7 +9342,7 @@ nsresult nsDocShell::InternalLoad(nsDocShellLoadState* aLoadState, // Do this asynchronously nsCOMPtr ev = new InternalLoadEvent(this, aLoadState); - return Dispatch(TaskCategory::Other, ev.forget()); + return Dispatch(ev.forget()); } // Just ignore this load attempt @@ -10756,13 +10748,13 @@ nsresult nsDocShell::OpenInitializedChannel(nsIChannel* aChannel, // When using DocumentChannel, all redirect handling is done in the parent, // so we just need the child variant to watch for the internal redirect // to the final channel. - rv = AddClientChannelHelperInChild( - aChannel, win->EventTargetFor(TaskCategory::Other)); + rv = AddClientChannelHelperInChild(aChannel, + GetMainThreadSerialEventTarget()); docChannel->SetInitialClientInfo(GetInitialClientInfo()); } else { rv = AddClientChannelHelper(aChannel, std::move(noReservedClient), GetInitialClientInfo(), - win->EventTargetFor(TaskCategory::Other)); + GetMainThreadSerialEventTarget()); } NS_ENSURE_SUCCESS(rv, rv); @@ -10807,8 +10799,7 @@ nsresult nsDocShell::OpenRedirectedChannel(nsDocShellLoadState* aLoadState) { // If we did a process switch, then we should have an existing allocated // ClientInfo, so we just need to allocate a corresponding ClientSource. - CreateReservedSourceIfNeeded(channel, - win->EventTargetFor(TaskCategory::Other)); + CreateReservedSourceIfNeeded(channel, GetMainThreadSerialEventTarget()); RefPtr loader = new nsDocumentOpenInfo(this, nsIURILoader::DONT_RETARGET, nullptr); @@ -12913,7 +12904,7 @@ nsresult nsDocShell::OnLinkClick( nsCOMPtr ev = new OnLinkClickEvent(this, aContent, loadState, noOpenerImplied, aIsTrusted, aTriggeringPrincipal); - return Dispatch(TaskCategory::UI, ev.forget()); + return Dispatch(ev.forget()); } bool nsDocShell::ShouldOpenInBlankTarget(const nsAString& aOriginalTarget, diff --git a/docshell/base/nsDocShell.h b/docshell/base/nsDocShell.h index 2427bbe4b028..6cb39a4ffabe 100644 --- a/docshell/base/nsDocShell.h +++ b/docshell/base/nsDocShell.h @@ -980,8 +980,7 @@ class nsDocShell final : public nsDocLoader, // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230) MOZ_CAN_RUN_SCRIPT_BOUNDARY void FirePageHideShowNonRecursive(bool aShow); - nsresult Dispatch(mozilla::TaskCategory aCategory, - already_AddRefed&& aRunnable); + nsresult Dispatch(already_AddRefed&& aRunnable); void ReattachEditorToWindow(nsISHEntry* aSHEntry); void ClearFrameHistory(nsISHEntry* aEntry); diff --git a/docshell/base/nsDocShellTreeOwner.cpp b/docshell/base/nsDocShellTreeOwner.cpp index 45a3361defb7..9f1ab23a6c47 100644 --- a/docshell/base/nsDocShellTreeOwner.cpp +++ b/docshell/base/nsDocShellTreeOwner.cpp @@ -1177,20 +1177,16 @@ nsresult ChromeTooltipListener::MouseMove(Event* aMouseEvent) { } if (!mShowingTooltip) { - nsIEventTarget* target = nullptr; if (nsCOMPtr eventTarget = aMouseEvent->GetComposedTarget()) { mPossibleTooltipNode = nsINode::FromEventTarget(eventTarget); - nsCOMPtr global(eventTarget->GetOwnerGlobal()); - if (global) { - target = global->EventTargetFor(TaskCategory::UI); - } } if (mPossibleTooltipNode) { nsresult rv = NS_NewTimerWithFuncCallback( getter_AddRefs(mTooltipTimer), sTooltipCallback, this, LookAndFeel::GetInt(LookAndFeel::IntID::TooltipDelay, 500), - nsITimer::TYPE_ONE_SHOT, "ChromeTooltipListener::MouseMove", target); + nsITimer::TYPE_ONE_SHOT, "ChromeTooltipListener::MouseMove", + GetMainThreadSerialEventTarget()); if (NS_FAILED(rv)) { mPossibleTooltipNode = nullptr; NS_WARNING("Could not create a timer for tooltip tracking"); diff --git a/docshell/base/nsPingListener.cpp b/docshell/base/nsPingListener.cpp index 491f46e8a9c1..094074a0b9e5 100644 --- a/docshell/base/nsPingListener.cpp +++ b/docshell/base/nsPingListener.cpp @@ -319,7 +319,7 @@ nsresult nsPingListener::StartTimeout(DocGroup* aDocGroup) { return NS_NewTimerWithFuncCallback( getter_AddRefs(mTimer), OnPingTimeout, mLoadGroup, PING_TIMEOUT, nsITimer::TYPE_ONE_SHOT, "nsPingListener::StartTimeout", - aDocGroup->EventTargetFor(TaskCategory::Network)); + GetMainThreadSerialEventTarget()); } NS_IMETHODIMP diff --git a/docshell/shistory/nsSHEntryShared.cpp b/docshell/shistory/nsSHEntryShared.cpp index 9b8bc3936d88..0cf9beccdc9f 100644 --- a/docshell/shistory/nsSHEntryShared.cpp +++ b/docshell/shistory/nsSHEntryShared.cpp @@ -290,20 +290,17 @@ nsresult nsSHEntryShared::RemoveFromBFCacheAsync() { nsCOMPtr viewer = mContentViewer; RefPtr document = mDocument; RefPtr self = this; - nsresult rv = mDocument->Dispatch( - mozilla::TaskCategory::Other, - NS_NewRunnableFunction( - "nsSHEntryShared::RemoveFromBFCacheAsync", - [self, viewer, document]() { - if (viewer) { - viewer->Destroy(); - } + nsresult rv = mDocument->Dispatch(NS_NewRunnableFunction( + "nsSHEntryShared::RemoveFromBFCacheAsync", [self, viewer, document]() { + if (viewer) { + viewer->Destroy(); + } - nsCOMPtr shistory = do_QueryReferent(self->mSHistory); - if (shistory) { - shistory->RemoveDynEntriesForBFCacheEntry(self); - } - })); + nsCOMPtr shistory = do_QueryReferent(self->mSHistory); + if (shistory) { + shistory->RemoveDynEntriesForBFCacheEntry(self); + } + })); if (NS_FAILED(rv)) { NS_WARNING("Failed to dispatch RemoveFromBFCacheAsync runnable."); diff --git a/dom/base/ChromeUtils.cpp b/dom/base/ChromeUtils.cpp index 9bae57717e9c..d76fb3e83c15 100644 --- a/dom/base/ChromeUtils.cpp +++ b/dom/base/ChromeUtils.cpp @@ -1418,8 +1418,7 @@ already_AddRefed ChromeUtils::RequestProcInfo(GlobalObject& aGlobal, } // Now place background request. - RefPtr target = - global->EventTargetFor(TaskCategory::Performance); + RefPtr target = global->SerialEventTarget(); mozilla::GetProcInfo(std::move(requests)) ->Then( target, __func__, diff --git a/dom/base/DispatcherTrait.cpp b/dom/base/DispatcherTrait.cpp deleted file mode 100644 index 1cba3a031c14..000000000000 --- a/dom/base/DispatcherTrait.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "mozilla/dom/DispatcherTrait.h" - -#include "mozilla/AbstractThread.h" -#include "mozilla/SchedulerGroup.h" - -using namespace mozilla; -using namespace mozilla::dom; - -nsresult DispatcherTrait::Dispatch(TaskCategory aCategory, - already_AddRefed&& aRunnable) { - return SchedulerGroup::Dispatch(aCategory, std::move(aRunnable)); -} - -nsISerialEventTarget* DispatcherTrait::EventTargetFor( - TaskCategory aCategory) const { - return GetMainThreadSerialEventTarget(); -} - -AbstractThread* DispatcherTrait::AbstractMainThreadFor(TaskCategory aCategory) { - // Return non DocGroup version by default. - return AbstractThread::MainThread(); -} diff --git a/dom/base/DispatcherTrait.h b/dom/base/DispatcherTrait.h deleted file mode 100644 index 3600cd5eded7..000000000000 --- a/dom/base/DispatcherTrait.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_DispatcherTrait_h -#define mozilla_dom_DispatcherTrait_h - -#include "mozilla/AlreadyAddRefed.h" -#include "mozilla/TaskCategory.h" -#include "ErrorList.h" - -class nsIRunnable; -class nsISerialEventTarget; - -namespace mozilla { -class AbstractThread; -namespace dom { -// This trait should be attached to classes like nsIGlobalObject and -// Document that have a DocGroup attached to them. The methods here -// should delegate to the DocGroup. We can't use the -// Dispatcher class directly because it inherits from nsISupports. -class DispatcherTrait { - public: - // This method may or may not be safe off of the main thread. For Document it - // is safe. For nsIGlobalWindow it is not safe. - virtual nsresult Dispatch(TaskCategory aCategory, - already_AddRefed&& aRunnable); - - // This method may or may not be safe off of the main thread. For Document it - // is safe. For nsIGlobalWindow it is not safe. The nsISerialEventTarget can - // always be used off the main thread. - virtual nsISerialEventTarget* EventTargetFor(TaskCategory aCategory) const; - - // Must be called on the main thread. The AbstractThread can always be used - // off the main thread. - virtual AbstractThread* AbstractMainThreadFor(TaskCategory aCategory); -}; - -} // namespace dom -} // namespace mozilla - -#endif // mozilla_dom_DispatcherTrait_h diff --git a/dom/base/DocGroup.cpp b/dom/base/DocGroup.cpp index b533bba8cdd5..7c7f44de396b 100644 --- a/dom/base/DocGroup.cpp +++ b/dom/base/DocGroup.cpp @@ -50,9 +50,7 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_END /* static */ already_AddRefed DocGroup::Create( BrowsingContextGroup* aBrowsingContextGroup, const nsACString& aKey) { - RefPtr docGroup = new DocGroup(aBrowsingContextGroup, aKey); - docGroup->mEventTarget = mozilla::GetMainThreadSerialEventTarget(); - return docGroup.forget(); + return do_AddRef(new DocGroup(aBrowsingContextGroup, aKey)); } /* static */ @@ -129,34 +127,6 @@ DocGroup::~DocGroup() { FlushIframePostMessageQueue(); } } - -nsresult DocGroup::Dispatch(TaskCategory aCategory, - already_AddRefed&& aRunnable) { - MOZ_RELEASE_ASSERT(NS_IsMainThread()); - - return SchedulerGroup::Dispatch(aCategory, std::move(aRunnable)); -} - -nsISerialEventTarget* DocGroup::EventTargetFor(TaskCategory aCategory) const { - MOZ_RELEASE_ASSERT(NS_IsMainThread()); - MOZ_ASSERT(!mDocuments.IsEmpty()); - - // Here we have the same event target for every TaskCategory. The - // reason for that is that currently TaskCategory isn't used, and - // it's unsure if it ever will be (See Bug 1624819). - return mEventTarget; -} - -AbstractThread* DocGroup::AbstractMainThreadFor(TaskCategory aCategory) { - MOZ_RELEASE_ASSERT(NS_IsMainThread()); - MOZ_ASSERT(!mDocuments.IsEmpty()); - - // Here we have the same thread for every TaskCategory. The reason - // for that is that currently TaskCategory isn't used, and it's - // unsure if it ever will be (See Bug 1624819). - return AbstractThread::MainThread(); -} - void DocGroup::SignalSlotChange(HTMLSlotElement& aSlot) { MOZ_ASSERT(!mSignalSlotList.Contains(&aSlot)); mSignalSlotList.AppendElement(&aSlot); @@ -218,7 +188,7 @@ void DocGroup::TryFlushIframePostMessages(uint64_t aWindowId) { void DocGroup::FlushIframePostMessageQueue() { nsCOMPtr event; while ((event = mIframePostMessageQueue->GetEvent())) { - Dispatch(TaskCategory::Other, event.forget()); + SchedulerGroup::Dispatch(event.forget()); } } diff --git a/dom/base/DocGroup.h b/dom/base/DocGroup.h index 3af206682dfd..f5c80eaf3cf4 100644 --- a/dom/base/DocGroup.h +++ b/dom/base/DocGroup.h @@ -87,13 +87,6 @@ class DocGroup final { return mDocuments.end(); } - nsresult Dispatch(TaskCategory aCategory, - already_AddRefed&& aRunnable); - - nsISerialEventTarget* EventTargetFor(TaskCategory aCategory) const; - - AbstractThread* AbstractMainThreadFor(TaskCategory aCategory); - // Return a pointer that can be continually checked to see if access to this // DocGroup is valid. This pointer should live at least as long as the // DocGroup. @@ -135,7 +128,6 @@ class DocGroup final { RefPtr mBrowsingContextGroup; RefPtr mIframePostMessageQueue; nsTHashSet mIframesUsedPostMessageQueue; - nsCOMPtr mEventTarget; // non-null if the JS execution for this docgroup is regulated with regards // to worker threads. This should only be used when we are forcing serialized diff --git a/dom/base/Document.cpp b/dom/base/Document.cpp index 9d002caee405..d48910105336 100644 --- a/dom/base/Document.cpp +++ b/dom/base/Document.cpp @@ -100,6 +100,7 @@ #include "mozilla/RelativeTo.h" #include "mozilla/RestyleManager.h" #include "mozilla/ReverseIterator.h" +#include "mozilla/SchedulerGroup.h" #include "mozilla/ScrollTimelineAnimationTracker.h" #include "mozilla/SMILAnimationController.h" #include "mozilla/SMILTimeContainer.h" @@ -4292,29 +4293,8 @@ void Document::AssertDocGroupMatchesKey() const { } #endif -nsresult Document::Dispatch(TaskCategory aCategory, - already_AddRefed&& aRunnable) { - // Note that this method may be called off the main thread. - if (mDocGroup) { - return mDocGroup->Dispatch(aCategory, std::move(aRunnable)); - } - return DispatcherTrait::Dispatch(aCategory, std::move(aRunnable)); -} - -nsISerialEventTarget* Document::EventTargetFor(TaskCategory aCategory) const { - if (mDocGroup) { - return mDocGroup->EventTargetFor(aCategory); - } - return DispatcherTrait::EventTargetFor(aCategory); -} - -AbstractThread* Document::AbstractMainThreadFor( - mozilla::TaskCategory aCategory) { - MOZ_ASSERT(NS_IsMainThread()); - if (mDocGroup) { - return mDocGroup->AbstractMainThreadFor(aCategory); - } - return DispatcherTrait::AbstractMainThreadFor(aCategory); +nsresult Document::Dispatch(already_AddRefed&& aRunnable) const { + return SchedulerGroup::Dispatch(std::move(aRunnable)); } void Document::NoteScriptTrackingStatus(const nsACString& aURL, @@ -8243,7 +8223,7 @@ void Document::UnblockDOMContentLoaded() { nsCOMPtr ev = NewRunnableMethod("Document::DispatchContentLoadedEvents", this, &Document::DispatchContentLoadedEvents); - Dispatch(TaskCategory::Other, ev.forget()); + Dispatch(ev.forget()); } else { DispatchContentLoadedEvents(); } @@ -9271,7 +9251,7 @@ void Document::NotifyPossibleTitleChange(bool aBoundTitleElement) { RefPtr> event = NewNonOwningRunnableMethod("Document::DoNotifyPossibleTitleChange", this, &Document::DoNotifyPossibleTitleChange); - if (NS_WARN_IF(NS_FAILED(Dispatch(TaskCategory::Other, do_AddRef(event))))) { + if (NS_WARN_IF(NS_FAILED(Dispatch(do_AddRef(event))))) { return; } mPendingTitleChangeEvent = std::move(event); @@ -11671,7 +11651,7 @@ class nsUnblockOnloadEvent : public Runnable { void Document::PostUnblockOnloadEvent() { MOZ_RELEASE_ASSERT(NS_IsMainThread()); nsCOMPtr evt = new nsUnblockOnloadEvent(this); - nsresult rv = Dispatch(TaskCategory::Other, evt.forget()); + nsresult rv = Dispatch(evt.forget()); if (NS_SUCCEEDED(rv)) { // Stabilize block count so we don't post more events while this one is up ++mOnloadBlockCount; @@ -12716,7 +12696,7 @@ void Document::UnsuppressEventHandlingAndFireEvents(bool aFireEvents) { MOZ_RELEASE_ASSERT(NS_IsMainThread()); nsCOMPtr ded = new nsDelayedEventDispatcher(std::move(documents)); - Dispatch(TaskCategory::Other, ded.forget()); + Dispatch(ded.forget()); } else { FireOrClearDelayedEvents(std::move(documents), false); } @@ -14472,11 +14452,7 @@ class nsCallExitFullscreen : public Runnable { void Document::AsyncExitFullscreen(Document* aDoc) { MOZ_RELEASE_ASSERT(NS_IsMainThread()); nsCOMPtr exit = new nsCallExitFullscreen(aDoc); - if (aDoc) { - aDoc->Dispatch(TaskCategory::Other, exit.forget()); - } else { - NS_DispatchToCurrentThread(exit.forget()); - } + NS_DispatchToCurrentThread(exit.forget()); } static uint32_t CountFullscreenSubDocuments(Document& aDoc) { @@ -15476,17 +15452,15 @@ void Document::RequestFullscreenInContentProcess( PendingFullscreenChangeList::Add(std::move(aRequest)); // If we are not the top level process, dispatch an event to make // our parent process go fullscreen first. - Dispatch( - TaskCategory::Other, - NS_NewRunnableFunction( - "Document::RequestFullscreenInContentProcess", [self = RefPtr{this}] { - if (!self->HasPendingFullscreenRequests()) { - return; - } - nsContentUtils::DispatchEventOnlyToChrome( - self, self, u"MozDOMFullscreen:Request"_ns, CanBubble::eYes, - Cancelable::eNo, /* DefaultAction */ nullptr); - })); + Dispatch(NS_NewRunnableFunction( + "Document::RequestFullscreenInContentProcess", [self = RefPtr{this}] { + if (!self->HasPendingFullscreenRequests()) { + return; + } + nsContentUtils::DispatchEventOnlyToChrome( + self, self, u"MozDOMFullscreen:Request"_ns, CanBubble::eYes, + Cancelable::eNo, /* DefaultAction */ nullptr); + })); } void Document::RequestFullscreenInParentProcess( @@ -15742,7 +15716,7 @@ void Document::PostVisibilityUpdateEvent() { nsCOMPtr event = NewRunnableMethod( "Document::UpdateVisibilityState", this, &Document::UpdateVisibilityState, DispatchVisibilityChange::Yes); - Dispatch(TaskCategory::Other, event.forget()); + Dispatch(event.forget()); } void Document::MaybeActiveMediaComponents() { @@ -16372,7 +16346,7 @@ void Document::ScheduleIntersectionObserverNotification() { nsCOMPtr notification = NewRunnableMethod("Document::NotifyIntersectionObservers", this, &Document::NotifyIntersectionObservers); - Dispatch(TaskCategory::Other, notification.forget()); + Dispatch(notification.forget()); } void Document::NotifyIntersectionObservers() { @@ -17528,7 +17502,7 @@ Document::CreatePermissionGrantPromise( // If we get here, the auto-decision failed and we need to // wait for the user prompt to complete. sapr->RequestDelayedTask( - inner->EventTargetFor(TaskCategory::Other), + GetMainThreadSerialEventTarget(), ContentPermissionRequestBase::DelayedTaskType::Request); }); }, diff --git a/dom/base/Document.h b/dom/base/Document.h index 55d6e69a4987..f570ed050851 100644 --- a/dom/base/Document.h +++ b/dom/base/Document.h @@ -40,14 +40,12 @@ #include "mozilla/Result.h" #include "mozilla/SegmentedVector.h" #include "mozilla/StorageAccessAPIHelper.h" -#include "mozilla/TaskCategory.h" #include "mozilla/TimeStamp.h" #include "mozilla/UniquePtr.h" #include "mozilla/UseCounter.h" #include "mozilla/WeakPtr.h" #include "mozilla/css/StylePreloadKind.h" #include "mozilla/dom/AnimationFrameProvider.h" -#include "mozilla/dom/DispatcherTrait.h" #include "mozilla/dom/DocumentOrShadowRoot.h" #include "mozilla/dom/Element.h" #include "mozilla/dom/EventTarget.h" @@ -533,7 +531,6 @@ class Document : public nsINode, public DocumentOrShadowRoot, public nsSupportsWeakReference, public nsIScriptObjectPrincipal, - public DispatcherTrait, public SupportsWeakPtr { friend class DocumentOrShadowRoot; @@ -3745,12 +3742,7 @@ class Document : public nsINode, void UnobserveForLastRememberedSize(Element&); // Dispatch a runnable related to the document. - nsresult Dispatch(TaskCategory aCategory, - already_AddRefed&& aRunnable) final; - - nsISerialEventTarget* EventTargetFor(TaskCategory) const override; - - AbstractThread* AbstractMainThreadFor(TaskCategory) override; + nsresult Dispatch(already_AddRefed&& aRunnable) const; // The URLs passed to this function should match what // JS::DescribeScriptedCaller() returns, since this API is used to diff --git a/dom/base/PointerLockManager.cpp b/dom/base/PointerLockManager.cpp index af144ab600a0..dabfbed4903e 100644 --- a/dom/base/PointerLockManager.cpp +++ b/dom/base/PointerLockManager.cpp @@ -162,7 +162,7 @@ void PointerLockManager::RequestLock(Element* aElement, aCallerType == CallerType::System; nsCOMPtr request = new PointerLockRequest(aElement, userInputOrSystemCaller); - doc->Dispatch(TaskCategory::Other, request.forget()); + doc->Dispatch(request.forget()); } /* static */ diff --git a/dom/base/PostMessageEvent.cpp b/dom/base/PostMessageEvent.cpp index 46630ae67b07..de06b16ef46a 100644 --- a/dom/base/PostMessageEvent.cpp +++ b/dom/base/PostMessageEvent.cpp @@ -302,7 +302,7 @@ void PostMessageEvent::DispatchToTargetThread(ErrorResult& aError) { } } - aError = mTargetWindow->Dispatch(TaskCategory::Other, event.forget()); + aError = mTargetWindow->Dispatch(event.forget()); } } // namespace mozilla::dom diff --git a/dom/base/Selection.cpp b/dom/base/Selection.cpp index c596cd6d2441..4a6d2c3cf26b 100644 --- a/dom/base/Selection.cpp +++ b/dom/base/Selection.cpp @@ -382,9 +382,7 @@ class AutoScroller final : public nsITimerCallback, public nsINamed { mContent = PresShell::GetCapturingContent(); if (!mTimer) { - mTimer = NS_NewTimer( - mPresContext->Document()->EventTargetFor(TaskCategory::Other)); - + mTimer = NS_NewTimer(GetMainThreadSerialEventTarget()); if (!mTimer) { return NS_ERROR_OUT_OF_MEMORY; } diff --git a/dom/base/moz.build b/dom/base/moz.build index a3f314b0d258..9210804b890a 100644 --- a/dom/base/moz.build +++ b/dom/base/moz.build @@ -171,7 +171,6 @@ EXPORTS.mozilla.dom += [ "CustomElementRegistry.h", "DecompressionStream.h", "DirectionalityUtils.h", - "DispatcherTrait.h", "DocGroup.h", "Document.h", "DocumentFragment.h", @@ -333,7 +332,6 @@ UNIFIED_SOURCES += [ "Crypto.cpp", "CustomElementRegistry.cpp", "DirectionalityUtils.cpp", - "DispatcherTrait.cpp", "DocGroup.cpp", "Document.cpp", "DocumentFragment.cpp", diff --git a/dom/base/nsContentPolicy.cpp b/dom/base/nsContentPolicy.cpp index 003bffb01b82..da990b7bdf3e 100644 --- a/dom/base/nsContentPolicy.cpp +++ b/dom/base/nsContentPolicy.cpp @@ -23,7 +23,6 @@ #include "nsContentUtils.h" #include "mozilla/dom/nsMixedContentBlocker.h" #include "nsIContentSecurityPolicy.h" -#include "mozilla/TaskCategory.h" class nsIDOMWindow; @@ -97,19 +96,9 @@ inline nsresult nsContentPolicy::CheckPolicy(CPMethod policyMethod, */ nsresult rv; const nsCOMArray& entries = mPolicies.GetCachedEntries(); - - nsCOMPtr window; - if (nsCOMPtr node = do_QueryInterface(requestingContext)) { - window = node->OwnerDoc()->GetWindow(); - } else { - window = do_QueryInterface(requestingContext); - } - if (doc) { - nsCOMPtr csp = doc->GetCsp(); - if (csp && window) { - csp->EnsureEventTarget( - window->EventTargetFor(mozilla::TaskCategory::Other)); + if (nsCOMPtr csp = doc->GetCsp()) { + csp->EnsureEventTarget(mozilla::GetMainThreadSerialEventTarget()); } } diff --git a/dom/base/nsContentUtils.cpp b/dom/base/nsContentUtils.cpp index 1fc168562b18..df095e43783c 100644 --- a/dom/base/nsContentUtils.cpp +++ b/dom/base/nsContentUtils.cpp @@ -122,7 +122,6 @@ #include "mozilla/StaticPrefs_test.h" #include "mozilla/StaticPrefs_ui.h" #include "mozilla/StaticPtr.h" -#include "mozilla/TaskCategory.h" #include "mozilla/TextControlState.h" #include "mozilla/TextEditor.h" #include "mozilla/TextEvents.h" @@ -10458,27 +10457,6 @@ uint32_t nsContentUtils::HtmlObjectContentTypeForMIMEType( return nsIObjectLoadingContent::TYPE_NULL; } -/* static */ -already_AddRefed nsContentUtils::GetEventTargetByLoadInfo( - nsILoadInfo* aLoadInfo, TaskCategory aCategory) { - if (NS_WARN_IF(!aLoadInfo)) { - return nullptr; - } - - RefPtr doc; - aLoadInfo->GetLoadingDocument(getter_AddRefs(doc)); - nsCOMPtr target; - if (doc) { - if (DocGroup* group = doc->GetDocGroup()) { - target = group->EventTargetFor(aCategory); - } - } else { - target = GetMainThreadSerialEventTarget(); - } - - return target.forget(); -} - /* static */ bool nsContentUtils::IsLocalRefURL(const nsAString& aString) { return !aString.IsEmpty() && aString[0] == '#'; diff --git a/dom/base/nsContentUtils.h b/dom/base/nsContentUtils.h index 180c7fe15d6a..530f5cb346e9 100644 --- a/dom/base/nsContentUtils.h +++ b/dom/base/nsContentUtils.h @@ -35,7 +35,6 @@ #include "mozilla/CallState.h" #include "mozilla/Maybe.h" #include "mozilla/RefPtr.h" -#include "mozilla/TaskCategory.h" #include "mozilla/TimeStamp.h" #include "mozilla/UniquePtr.h" #include "mozilla/dom/BindingDeclarations.h" @@ -3179,9 +3178,6 @@ class nsContentUtils { static uint32_t HtmlObjectContentTypeForMIMEType(const nsCString& aMIMEType, bool aNoFakePlugin); - static already_AddRefed GetEventTargetByLoadInfo( - nsILoadInfo* aLoadInfo, mozilla::TaskCategory aCategory); - /** * Detect whether a string is a local-url. * https://drafts.csswg.org/css-values/#local-urls diff --git a/dom/base/nsGlobalWindowInner.cpp b/dom/base/nsGlobalWindowInner.cpp index 2050ef4efd7b..3e4f34a51a7f 100644 --- a/dom/base/nsGlobalWindowInner.cpp +++ b/dom/base/nsGlobalWindowInner.cpp @@ -84,7 +84,6 @@ #include "mozilla/StaticPrefs_privacy.h" #include "mozilla/StorageAccess.h" #include "mozilla/StoragePrincipalHelper.h" -#include "mozilla/TaskCategory.h" #include "mozilla/Telemetry.h" #include "mozilla/TelemetryHistogramEnums.h" #include "mozilla/TimeStamp.h" @@ -112,7 +111,6 @@ #include "mozilla/dom/DebuggerNotification.h" #include "mozilla/dom/DebuggerNotificationBinding.h" #include "mozilla/dom/DebuggerNotificationManager.h" -#include "mozilla/dom/DispatcherTrait.h" #include "mozilla/dom/DocGroup.h" #include "mozilla/dom/Document.h" #include "mozilla/dom/DocumentInlines.h" @@ -461,7 +459,7 @@ class nsGlobalWindowObserver final : public nsIObserver, } nsIEventTarget* GetEventTarget() const override { - return mWindow ? mWindow->EventTargetFor(TaskCategory::Other) : nullptr; + return mWindow ? mWindow->SerialEventTarget() : nullptr; } private: @@ -1952,8 +1950,7 @@ nsresult nsGlobalWindowInner::EnsureClientSource() { // the opener, but we probably don't handle that yet. if (!mClientSource) { mClientSource = ClientManager::CreateSource( - ClientType::Window, EventTargetFor(TaskCategory::Other), - foreignPartitionedPrincipal); + ClientType::Window, SerialEventTarget(), foreignPartitionedPrincipal); MOZ_DIAGNOSTIC_ASSERT(mClientSource); newClientSource = true; @@ -1991,8 +1988,7 @@ nsresult nsGlobalWindowInner::EnsureClientSource() { else if (mClientSource->GetController().isSome()) { mClientSource.reset(); mClientSource = ClientManager::CreateSource( - ClientType::Window, EventTargetFor(TaskCategory::Other), - foreignPartitionedPrincipal); + ClientType::Window, SerialEventTarget(), foreignPartitionedPrincipal); MOZ_DIAGNOSTIC_ASSERT(mClientSource); newClientSource = true; } @@ -4089,7 +4085,7 @@ void nsGlobalWindowInner::NotifyDOMWindowDestroyed( void nsGlobalWindowInner::NotifyWindowIDDestroyed(const char* aTopic) { nsCOMPtr runnable = new WindowDestroyedEvent(this, mWindowID, aTopic); - Dispatch(TaskCategory::Other, runnable.forget()); + Dispatch(runnable.forget()); } // static @@ -4529,7 +4525,7 @@ nsresult nsGlobalWindowInner::DispatchAsyncHashchange(nsIURI* aOldURI, nsCOMPtr callback = new HashchangeCallback(oldWideSpec, newWideSpec, this); - return Dispatch(TaskCategory::Other, callback.forget()); + return Dispatch(callback.forget()); } nsresult nsGlobalWindowInner::FireHashchange(const nsAString& aOldURL, @@ -7376,30 +7372,14 @@ void nsGlobalWindowInner::StructuredClone( } nsresult nsGlobalWindowInner::Dispatch( - TaskCategory aCategory, already_AddRefed&& aRunnable) { + already_AddRefed&& aRunnable) const { MOZ_RELEASE_ASSERT(NS_IsMainThread()); - if (GetDocGroup()) { - return GetDocGroup()->Dispatch(aCategory, std::move(aRunnable)); - } - return DispatcherTrait::Dispatch(aCategory, std::move(aRunnable)); + return NS_DispatchToCurrentThread(std::move(aRunnable)); } -nsISerialEventTarget* nsGlobalWindowInner::EventTargetFor( - TaskCategory aCategory) const { +nsISerialEventTarget* nsGlobalWindowInner::SerialEventTarget() const { MOZ_RELEASE_ASSERT(NS_IsMainThread()); - if (GetDocGroup()) { - return GetDocGroup()->EventTargetFor(aCategory); - } - return DispatcherTrait::EventTargetFor(aCategory); -} - -AbstractThread* nsGlobalWindowInner::AbstractMainThreadFor( - TaskCategory aCategory) { - MOZ_RELEASE_ASSERT(NS_IsMainThread()); - if (GetDocGroup()) { - return GetDocGroup()->AbstractMainThreadFor(aCategory); - } - return DispatcherTrait::AbstractMainThreadFor(aCategory); + return GetMainThreadSerialEventTarget(); } Worklet* nsGlobalWindowInner::GetPaintWorklet(ErrorResult& aRv) { diff --git a/dom/base/nsGlobalWindowInner.h b/dom/base/nsGlobalWindowInner.h index 4162356ea975..4bf37d1eaaeb 100644 --- a/dom/base/nsGlobalWindowInner.h +++ b/dom/base/nsGlobalWindowInner.h @@ -1186,14 +1186,8 @@ class nsGlobalWindowInner final : public mozilla::dom::EventTarget, static uint32_t GetShortcutsPermission(nsIPrincipal* aPrincipal); // Dispatch a runnable related to the global. - virtual nsresult Dispatch(mozilla::TaskCategory aCategory, - already_AddRefed&& aRunnable) override; - - virtual nsISerialEventTarget* EventTargetFor( - mozilla::TaskCategory aCategory) const override; - - virtual mozilla::AbstractThread* AbstractMainThreadFor( - mozilla::TaskCategory aCategory) override; + nsresult Dispatch(already_AddRefed&& aRunnable) const final; + nsISerialEventTarget* SerialEventTarget() const final; void DisableIdleCallbackRequests(); uint32_t LastIdleRequestHandle() const { diff --git a/dom/base/nsGlobalWindowOuter.cpp b/dom/base/nsGlobalWindowOuter.cpp index cdace15eb881..f6d83ca8ee31 100644 --- a/dom/base/nsGlobalWindowOuter.cpp +++ b/dom/base/nsGlobalWindowOuter.cpp @@ -15,7 +15,6 @@ // Local Includes #include "Navigator.h" -#include "mozilla/Encoding.h" #include "nsContentSecurityManager.h" #include "nsGlobalWindowOuter.h" #include "nsScreen.h" @@ -92,6 +91,7 @@ #include "mozilla/dom/ScriptSettings.h" #include "mozilla/Preferences.h" #include "mozilla/Likely.h" +#include "mozilla/SchedulerGroup.h" #include "mozilla/SpinEventLoopUntil.h" #include "mozilla/Sprintf.h" #include "mozilla/Unused.h" @@ -5874,8 +5874,7 @@ class nsCloseEvent : public Runnable { public: static nsresult PostCloseEvent(nsGlobalWindowOuter* aWindow, bool aIndirect) { nsCOMPtr ev = new nsCloseEvent(aWindow, aIndirect); - nsresult rv = aWindow->Dispatch(TaskCategory::Other, ev.forget()); - return rv; + return aWindow->Dispatch(ev.forget()); } NS_IMETHOD Run() override { @@ -6239,7 +6238,7 @@ bool nsGlobalWindowOuter::IsInModalState() { void nsGlobalWindowOuter::NotifyWindowIDDestroyed(const char* aTopic) { nsCOMPtr runnable = new WindowDestroyedEvent(this, mWindowID, aTopic); - Dispatch(TaskCategory::Other, runnable.forget()); + Dispatch(runnable.forget()); } Element* nsGlobalWindowOuter::GetFrameElement(nsIPrincipal& aSubjectPrincipal) { @@ -6679,7 +6678,7 @@ class AutoUnblockScriptClosing { &nsGlobalWindowOuter::UnblockScriptedClosing; nsCOMPtr caller = NewRunnableMethod( "AutoUnblockScriptClosing::~AutoUnblockScriptClosing", mWin, run); - mWin->Dispatch(TaskCategory::Other, caller.forget()); + mWin->Dispatch(caller.forget()); } }; @@ -7253,30 +7252,14 @@ void nsGlobalWindowOuter::CheckForDPIChange() { } nsresult nsGlobalWindowOuter::Dispatch( - TaskCategory aCategory, already_AddRefed&& aRunnable) { + already_AddRefed&& aRunnable) const { MOZ_RELEASE_ASSERT(NS_IsMainThread()); - if (GetDocGroup()) { - return GetDocGroup()->Dispatch(aCategory, std::move(aRunnable)); - } - return DispatcherTrait::Dispatch(aCategory, std::move(aRunnable)); + return NS_DispatchToCurrentThread(std::move(aRunnable)); } -nsISerialEventTarget* nsGlobalWindowOuter::EventTargetFor( - TaskCategory aCategory) const { +nsISerialEventTarget* nsGlobalWindowOuter::SerialEventTarget() const { MOZ_RELEASE_ASSERT(NS_IsMainThread()); - if (GetDocGroup()) { - return GetDocGroup()->EventTargetFor(aCategory); - } - return DispatcherTrait::EventTargetFor(aCategory); -} - -AbstractThread* nsGlobalWindowOuter::AbstractMainThreadFor( - TaskCategory aCategory) { - MOZ_RELEASE_ASSERT(NS_IsMainThread()); - if (GetDocGroup()) { - return GetDocGroup()->AbstractMainThreadFor(aCategory); - } - return DispatcherTrait::AbstractMainThreadFor(aCategory); + return GetMainThreadSerialEventTarget(); } void nsGlobalWindowOuter::MaybeResetWindowName(Document* aNewDocument) { diff --git a/dom/base/nsGlobalWindowOuter.h b/dom/base/nsGlobalWindowOuter.h index 361ffe4b6ada..093b2e59f6fb 100644 --- a/dom/base/nsGlobalWindowOuter.h +++ b/dom/base/nsGlobalWindowOuter.h @@ -983,14 +983,8 @@ class nsGlobalWindowOuter final : public mozilla::dom::EventTarget, } // Dispatch a runnable related to the global. - virtual nsresult Dispatch(mozilla::TaskCategory aCategory, - already_AddRefed&& aRunnable) override; - - virtual nsISerialEventTarget* EventTargetFor( - mozilla::TaskCategory aCategory) const override; - - virtual mozilla::AbstractThread* AbstractMainThreadFor( - mozilla::TaskCategory aCategory) override; + nsresult Dispatch(already_AddRefed&&) const final; + nsISerialEventTarget* SerialEventTarget() const final; protected: nsresult ProcessWidgetFullscreenRequest(FullscreenReason aReason, diff --git a/dom/base/nsIGlobalObject.h b/dom/base/nsIGlobalObject.h index 7d350bb4381b..f3135646f4ce 100644 --- a/dom/base/nsIGlobalObject.h +++ b/dom/base/nsIGlobalObject.h @@ -10,7 +10,6 @@ #include "mozilla/LinkedList.h" #include "mozilla/Maybe.h" #include "mozilla/dom/ClientInfo.h" -#include "mozilla/dom/DispatcherTrait.h" #include "mozilla/dom/ServiceWorkerDescriptor.h" #include "mozilla/OriginTrials.h" #include "nsContentUtils.h" @@ -65,8 +64,7 @@ class ModuleLoaderBase; /** * See . */ -class nsIGlobalObject : public nsISupports, - public mozilla::dom::DispatcherTrait { +class nsIGlobalObject : public nsISupports { private: nsTArray mHostObjectURIs; @@ -140,6 +138,9 @@ class nsIGlobalObject : public nsISupports, */ bool HasJSGlobal() const { return GetGlobalJSObjectPreserveColor(); } + virtual nsISerialEventTarget* SerialEventTarget() const = 0; + virtual nsresult Dispatch(already_AddRefed&&) const = 0; + // This method is not meant to be overridden. nsIPrincipal* PrincipalOrNull() const; diff --git a/dom/base/nsPIDOMWindow.h b/dom/base/nsPIDOMWindow.h index 2b78eb42210f..9d5ee556bbc8 100644 --- a/dom/base/nsPIDOMWindow.h +++ b/dom/base/nsPIDOMWindow.h @@ -16,7 +16,6 @@ #include "mozilla/dom/EventTarget.h" #include "mozilla/EventForwards.h" #include "mozilla/Maybe.h" -#include "mozilla/TaskCategory.h" #include "js/TypeDecls.h" #include "nsRefPtrHashtable.h" #include "nsILoadInfo.h" @@ -635,8 +634,6 @@ class nsPIDOMWindowInner : public mozIDOMWindow { virtual nsresult Close() = 0; mozilla::dom::DocGroup* GetDocGroup() const; - virtual nsISerialEventTarget* EventTargetFor( - mozilla::TaskCategory aCategory) const = 0; void SaveStorageAccessPermissionGranted(); void SaveStorageAccessPermissionRevoked(); @@ -1136,8 +1133,6 @@ class nsPIDOMWindowOuter : public mozIDOMWindowProxy { virtual void UpdateCommands(const nsAString& anAction) = 0; mozilla::dom::DocGroup* GetDocGroup() const; - virtual nsISerialEventTarget* EventTargetFor( - mozilla::TaskCategory aCategory) const = 0; already_AddRefed GetTreeOwner(); already_AddRefed GetTreeOwnerWindow(); diff --git a/dom/bindings/SimpleGlobalObject.h b/dom/bindings/SimpleGlobalObject.h index 342869abaf2e..9358c498efa5 100644 --- a/dom/bindings/SimpleGlobalObject.h +++ b/dom/bindings/SimpleGlobalObject.h @@ -13,17 +13,18 @@ #ifndef mozilla_dom_SimpleGlobalObject_h__ #define mozilla_dom_SimpleGlobalObject_h__ +#include "nsThreadUtils.h" #include "nsContentUtils.h" +#include "nsCycleCollectionParticipant.h" #include "nsIGlobalObject.h" +#include "nsISupportsImpl.h" #include "nsWrapperCache.h" #include "js/TypeDecls.h" #include "js/Value.h" -#include "nsISupportsImpl.h" -#include "nsCycleCollectionParticipant.h" namespace mozilla::dom { -class SimpleGlobalObject : public nsIGlobalObject, public nsWrapperCache { +class SimpleGlobalObject final : public nsIGlobalObject, public nsWrapperCache { public: enum class GlobalType { BindingDetail, // Should only be used by DOM bindings code. @@ -68,6 +69,13 @@ class SimpleGlobalObject : public nsIGlobalObject, public nsWrapperCache { OriginTrials Trials() const override { return {}; } + nsISerialEventTarget* SerialEventTarget() const final { + return NS_GetCurrentThread(); + } + nsresult Dispatch(already_AddRefed&& aRunnable) const final { + return NS_DispatchToCurrentThread(std::move(aRunnable)); + } + JSObject* WrapObject(JSContext* cx, JS::Handle aGivenProto) override { MOZ_CRASH("SimpleGlobalObject doesn't use DOM bindings!"); diff --git a/dom/canvas/ImageBitmap.cpp b/dom/canvas/ImageBitmap.cpp index 300e783c6449..f0bbb46543d2 100644 --- a/dom/canvas/ImageBitmap.cpp +++ b/dom/canvas/ImageBitmap.cpp @@ -1729,7 +1729,7 @@ static void AsyncCreateImageBitmapFromBlob(Promise* aPromise, // Let's identify the main-thread event target. nsCOMPtr mainThreadEventTarget; if (NS_IsMainThread()) { - mainThreadEventTarget = aGlobal->EventTargetFor(TaskCategory::Other); + mainThreadEventTarget = aGlobal->SerialEventTarget(); } else { WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate(); MOZ_ASSERT(workerPrivate); diff --git a/dom/clients/api/Client.cpp b/dom/clients/api/Client.cpp index 1b0b4a2a591e..c3dd6175deb3 100644 --- a/dom/clients/api/Client.cpp +++ b/dom/clients/api/Client.cpp @@ -34,9 +34,8 @@ NS_INTERFACE_MAP_END void Client::EnsureHandle() { NS_ASSERT_OWNINGTHREAD(mozilla::dom::Client); if (!mHandle) { - mHandle = ClientManager::CreateHandle( - ClientInfo(mData->info()), - mGlobal->EventTargetFor(TaskCategory::Other)); + mHandle = ClientManager::CreateHandle(ClientInfo(mData->info()), + mGlobal->SerialEventTarget()); } } @@ -147,7 +146,7 @@ already_AddRefed Client::Focus(CallerType aCallerType, mHandle->Focus(aCallerType) ->Then( - mGlobal->EventTargetFor(TaskCategory::Other), __func__, + mGlobal->SerialEventTarget(), __func__, [ipcClientInfo, holder, outerPromise](const ClientState& aResult) { holder->Complete(); NS_ENSURE_TRUE_VOID(holder->GetParentObject()); diff --git a/dom/clients/api/ClientDOMUtil.h b/dom/clients/api/ClientDOMUtil.h index 2798aeec53b6..a1ad6a49ed97 100644 --- a/dom/clients/api/ClientDOMUtil.h +++ b/dom/clients/api/ClientDOMUtil.h @@ -23,9 +23,7 @@ void StartClientManagerOp(Func aFunc, const Arg& aArg, nsIGlobalObject* aGlobal, Resolve aResolve, Reject aReject) { MOZ_DIAGNOSTIC_ASSERT(aGlobal); - nsCOMPtr target = - aGlobal->EventTargetFor(TaskCategory::Other); - + nsCOMPtr target = aGlobal->SerialEventTarget(); auto holder = MakeRefPtr>(aGlobal); diff --git a/dom/clients/api/Clients.cpp b/dom/clients/api/Clients.cpp index 6dd88953b3ab..b08a7fa59801 100644 --- a/dom/clients/api/Clients.cpp +++ b/dom/clients/api/Clients.cpp @@ -73,9 +73,7 @@ already_AddRefed Clients::Get(const nsAString& aClientID, } const PrincipalInfo& principalInfo = workerPrivate->GetPrincipalInfo(); - nsCOMPtr target = - mGlobal->EventTargetFor(TaskCategory::Other); - + nsCOMPtr target = mGlobal->SerialEventTarget(); RefPtr innerPromise = ClientManager::GetInfoAndState( ClientGetInfoAndStateArgs(id, principalInfo), target); @@ -103,7 +101,7 @@ already_AddRefed Clients::Get(const nsAString& aClientID, scope, "ServiceWorkerGetClientStorageError", nsTArray()); }); - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget()); + SchedulerGroup::Dispatch(r.forget()); outerPromise->MaybeResolveWithUndefined(); }, [outerPromise, holder](const CopyableErrorResult& aResult) { @@ -188,7 +186,7 @@ already_AddRefed Clients::MatchAll(const ClientQueryOptions& aOptions, scope, "ServiceWorkerGetClientStorageError", nsTArray()); }); - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget()); + SchedulerGroup::Dispatch(r.forget()); } clientList.Sort(MatchAllComparator()); outerPromise->MaybeResolve(clientList); diff --git a/dom/clients/manager/ClientManagerService.cpp b/dom/clients/manager/ClientManagerService.cpp index b2d4cada9584..1ce741a5521e 100644 --- a/dom/clients/manager/ClientManagerService.cpp +++ b/dom/clients/manager/ClientManagerService.cpp @@ -102,8 +102,7 @@ RefPtr OnShutdown() { } }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return ref; } @@ -611,8 +610,7 @@ RefPtr ClaimOnMainThread( scopeExit.release(); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return promise; } diff --git a/dom/clients/manager/ClientNavigateOpChild.cpp b/dom/clients/manager/ClientNavigateOpChild.cpp index b1fd5fb36f20..4d47dd826eb6 100644 --- a/dom/clients/manager/ClientNavigateOpChild.cpp +++ b/dom/clients/manager/ClientNavigateOpChild.cpp @@ -182,7 +182,7 @@ RefPtr ClientNavigateOpChild::DoNavigate( MOZ_ASSERT(NS_IsMainThread()); - mSerialEventTarget = window->EventTargetFor(TaskCategory::Other); + mSerialEventTarget = GetMainThreadSerialEventTarget(); // In theory we could do the URL work before paying the IPC overhead // cost, but in practice its easier to do it here. The ClientHandle diff --git a/dom/clients/manager/ClientSourceParent.cpp b/dom/clients/manager/ClientSourceParent.cpp index 8d94a501d4b4..8364871cd452 100644 --- a/dom/clients/manager/ClientSourceParent.cpp +++ b/dom/clients/manager/ClientSourceParent.cpp @@ -77,8 +77,7 @@ void ClientSourceParent::KillInvalidChild() { // there is a small window of time before we kill the process. This is why // we start the actor destruction immediately above. nsCOMPtr r = new KillContentParentRunnable(std::move(process)); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); } mozilla::ipc::IPCResult ClientSourceParent::RecvWorkerSyncPing() { @@ -154,8 +153,7 @@ IPCResult ClientSourceParent::RecvInheritController( swm->NoteInheritedController(clientInfo, controller); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return IPC_OK(); } @@ -172,8 +170,7 @@ IPCResult ClientSourceParent::RecvNoteDOMContentLoaded() { swm->MaybeCheckNavigationUpdate(clientInfo); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); } return IPC_OK(); } diff --git a/dom/events/AsyncEventDispatcher.cpp b/dom/events/AsyncEventDispatcher.cpp index 2b087d7e31c3..297a03d7cb5d 100644 --- a/dom/events/AsyncEventDispatcher.cpp +++ b/dom/events/AsyncEventDispatcher.cpp @@ -96,26 +96,12 @@ nsresult AsyncEventDispatcher::Cancel() { nsresult AsyncEventDispatcher::PostDOMEvent() { RefPtr ensureDeletionWhenFailing = this; - if (NS_IsMainThread()) { - if (nsCOMPtr global = mTarget->GetOwnerGlobal()) { - return global->Dispatch(TaskCategory::Other, - ensureDeletionWhenFailing.forget()); - } - - // Sometimes GetOwnerGlobal returns null because it uses - // GetScriptHandlingObject rather than GetScopeObject. - if (nsINode* node = nsINode::FromEventTargetOrNull(mTarget)) { - RefPtr doc = node->OwnerDoc(); - return doc->Dispatch(TaskCategory::Other, - ensureDeletionWhenFailing.forget()); - } - } - return NS_DispatchToCurrentThread(this); + return NS_DispatchToCurrentThread(ensureDeletionWhenFailing.forget()); } void AsyncEventDispatcher::RunDOMEventWhenSafe() { RefPtr ensureDeletionWhenFailing = this; - nsContentUtils::AddScriptRunner(this); + nsContentUtils::AddScriptRunner(ensureDeletionWhenFailing.forget()); } // static diff --git a/dom/events/DataTransferItem.cpp b/dom/events/DataTransferItem.cpp index 94869b4c4ee1..4df09c081e3e 100644 --- a/dom/events/DataTransferItem.cpp +++ b/dom/events/DataTransferItem.cpp @@ -503,7 +503,7 @@ void DataTransferItem::GetAsString(FunctionStringCallback* aCallback, } } if (global) { - rv = global->Dispatch(TaskCategory::Other, runnable.forget()); + rv = global->Dispatch(runnable.forget()); } else { rv = NS_DispatchToMainThread(runnable); } diff --git a/dom/events/EventListenerService.cpp b/dom/events/EventListenerService.cpp index 4336476aa959..7e4919d93817 100644 --- a/dom/events/EventListenerService.cpp +++ b/dom/events/EventListenerService.cpp @@ -371,13 +371,7 @@ void EventListenerService::NotifyAboutMainThreadListenerChangeInternal( nsCOMPtr runnable = NewRunnableMethod("EventListenerService::NotifyPendingChanges", this, &EventListenerService::NotifyPendingChanges); - if (nsCOMPtr global = aTarget->GetOwnerGlobal()) { - global->Dispatch(TaskCategory::Other, runnable.forget()); - } else if (nsINode* node = nsINode::FromEventTarget(aTarget)) { - node->OwnerDoc()->Dispatch(TaskCategory::Other, runnable.forget()); - } else { - NS_DispatchToCurrentThread(runnable); - } + NS_DispatchToCurrentThread(runnable.forget()); } RefPtr changes = diff --git a/dom/events/IMEContentObserver.cpp b/dom/events/IMEContentObserver.cpp index 6d52aa38a4f7..d672c722c74d 100644 --- a/dom/events/IMEContentObserver.cpp +++ b/dom/events/IMEContentObserver.cpp @@ -1665,24 +1665,14 @@ bool IMEContentObserver::AChangeEvent::IsSafeToNotifyIME( void IMEContentObserver::IMENotificationSender::Dispatch( nsIDocShell* aDocShell) { if (XRE_IsContentProcess() && aDocShell) { - RefPtr presContext = aDocShell->GetPresContext(); - if (presContext) { - nsRefreshDriver* refreshDriver = presContext->RefreshDriver(); - if (refreshDriver) { + if (RefPtr presContext = aDocShell->GetPresContext()) { + if (nsRefreshDriver* refreshDriver = presContext->RefreshDriver()) { refreshDriver->AddEarlyRunner(this); return; } } } - - nsIScriptGlobalObject* globalObject = - aDocShell ? aDocShell->GetScriptGlobalObject() : nullptr; - if (globalObject) { - RefPtr queuedSender = this; - globalObject->Dispatch(TaskCategory::Other, queuedSender.forget()); - } else { - NS_DispatchToCurrentThread(this); - } + NS_DispatchToCurrentThread(this); } NS_IMETHODIMP diff --git a/dom/fetch/Fetch.cpp b/dom/fetch/Fetch.cpp index 7fe66ab19488..2e8fdea02e44 100644 --- a/dom/fetch/Fetch.cpp +++ b/dom/fetch/Fetch.cpp @@ -588,11 +588,10 @@ already_AddRefed FetchRequest(nsIGlobalObject* aGlobal, RefPtr resolver = new MainThreadFetchResolver( p, observer, signalImpl, request->MozErrors()); - RefPtr fetch = - new FetchDriver(std::move(r), principal, loadGroup, - aGlobal->EventTargetFor(TaskCategory::Other), - cookieJarSettings, nullptr, // PerformanceStorage - isTrackingFetch); + RefPtr fetch = new FetchDriver( + std::move(r), principal, loadGroup, aGlobal->SerialEventTarget(), + cookieJarSettings, nullptr, // PerformanceStorage + isTrackingFetch); fetch->SetDocument(doc); resolver->SetLoadGroup(loadGroup); aRv = fetch->Fetch(signalImpl, resolver); @@ -1197,7 +1196,7 @@ FetchBody::FetchBody(nsIGlobalObject* aOwner) MOZ_ASSERT(wp); mMainThreadEventTarget = wp->MainThreadEventTarget(); } else { - mMainThreadEventTarget = aOwner->EventTargetFor(TaskCategory::Other); + mMainThreadEventTarget = GetMainThreadSerialEventTarget(); } MOZ_ASSERT(mMainThreadEventTarget); @@ -1237,7 +1236,7 @@ template bool FetchBody::BodyUsed() const; template void FetchBody::SetBodyUsed(JSContext* aCx, ErrorResult& aRv) { MOZ_ASSERT(aCx); - MOZ_ASSERT(mOwner->EventTargetFor(TaskCategory::Other)->IsOnCurrentThread()); + MOZ_ASSERT(mOwner->SerialEventTarget()->IsOnCurrentThread()); MOZ_DIAGNOSTIC_ASSERT(!BodyUsed(), "Consuming already used body?"); if (BodyUsed()) { diff --git a/dom/fetch/FetchChild.cpp b/dom/fetch/FetchChild.cpp index 774eb516e70d..eff5b3ff3a2e 100644 --- a/dom/fetch/FetchChild.cpp +++ b/dom/fetch/FetchChild.cpp @@ -181,8 +181,7 @@ mozilla::ipc::IPCResult FetchChild::RecvOnFlushConsoleReport( reporter->FlushConsoleReports(workerRef->Private()->GetLoadGroup()); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return IPC_OK(); } @@ -245,8 +244,7 @@ mozilla::ipc::IPCResult FetchChild::RecvOnCSPViolationEvent( return; } }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); if (mCSPEventListener) { Unused << NS_WARN_IF( @@ -305,8 +303,7 @@ mozilla::ipc::IPCResult FetchChild::RecvOnNotifyNetworkMonitorAlternateStack( NotifyNetworkMonitorAlternateStack(channel, std::move(stack)); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return IPC_OK(); } diff --git a/dom/fetch/FetchStreamReader.cpp b/dom/fetch/FetchStreamReader.cpp index 47f0cb97c277..3756dc1544c1 100644 --- a/dom/fetch/FetchStreamReader.cpp +++ b/dom/fetch/FetchStreamReader.cpp @@ -18,7 +18,6 @@ #include "mozilla/dom/WorkerPrivate.h" #include "mozilla/dom/WorkerRef.h" #include "mozilla/HoldDropJSObjects.h" -#include "mozilla/TaskCategory.h" #include "nsContentUtils.h" #include "nsDebug.h" #include "nsIAsyncInputStream.h" @@ -105,8 +104,7 @@ nsresult FetchStreamReader::Create(JSContext* aCx, nsIGlobalObject* aGlobal, } FetchStreamReader::FetchStreamReader(nsIGlobalObject* aGlobal) - : mGlobal(aGlobal), - mOwningEventTarget(mGlobal->EventTargetFor(TaskCategory::Other)) { + : mGlobal(aGlobal), mOwningEventTarget(mGlobal->SerialEventTarget()) { MOZ_ASSERT(aGlobal); mozilla::HoldJSObjects(this); diff --git a/dom/fetch/FetchUtil.cpp b/dom/fetch/FetchUtil.cpp index 48281df32196..040e23e4dc03 100644 --- a/dom/fetch/FetchUtil.cpp +++ b/dom/fetch/FetchUtil.cpp @@ -497,8 +497,7 @@ class JSStreamConsumer final : public nsIInputStreamCallback, RefPtr consumer; if (aMaybeWorker) { RefPtr owner = WorkerStreamOwner::Create( - asyncStream, aMaybeWorker, - aGlobal->EventTargetFor(TaskCategory::Other)); + asyncStream, aMaybeWorker, aGlobal->SerialEventTarget()); if (!owner) { return false; } diff --git a/dom/file/Blob.cpp b/dom/file/Blob.cpp index dc3a70c74c84..f5d8b057c47f 100644 --- a/dom/file/Blob.cpp +++ b/dom/file/Blob.cpp @@ -280,7 +280,7 @@ already_AddRefed Blob::ConsumeBody( MOZ_ASSERT(workerPrivate); mainThreadEventTarget = workerPrivate->MainThreadEventTarget(); } else { - mainThreadEventTarget = mGlobal->EventTargetFor(TaskCategory::Other); + mainThreadEventTarget = GetMainThreadSerialEventTarget(); } MOZ_ASSERT(mainThreadEventTarget); diff --git a/dom/file/FileReader.cpp b/dom/file/FileReader.cpp index 12c1853ab121..4a6d394fe181 100644 --- a/dom/file/FileReader.cpp +++ b/dom/file/FileReader.cpp @@ -131,7 +131,7 @@ FileReader::FileReader(nsIGlobalObject* aGlobal, WeakWorkerRef* aWorkerRef) MOZ_ASSERT_IF(NS_IsMainThread(), !mWeakWorkerRef); if (NS_IsMainThread()) { - mTarget = aGlobal->EventTargetFor(TaskCategory::Other); + mTarget = aGlobal->SerialEventTarget(); } else { mTarget = GetCurrentSerialEventTarget(); } diff --git a/dom/file/ipc/RemoteLazyInputStreamThread.cpp b/dom/file/ipc/RemoteLazyInputStreamThread.cpp index ec6c99952b81..9b2125248317 100644 --- a/dom/file/ipc/RemoteLazyInputStreamThread.cpp +++ b/dom/file/ipc/RemoteLazyInputStreamThread.cpp @@ -11,7 +11,6 @@ #include "mozilla/SchedulerGroup.h" #include "mozilla/StaticMutex.h" #include "mozilla/StaticPtr.h" -#include "mozilla/TaskCategory.h" #include "mozilla/ipc/BackgroundChild.h" #include "mozilla/ipc/PBackgroundChild.h" #include "nsXPCOMPrivate.h" @@ -96,8 +95,7 @@ bool RemoteLazyInputStreamThread::Initialize() { if (!NS_IsMainThread()) { RefPtr runnable = new ThreadInitializeRunnable(); - nsresult rv = - SchedulerGroup::Dispatch(TaskCategory::Other, runnable.forget()); + nsresult rv = SchedulerGroup::Dispatch(runnable.forget()); return !NS_WARN_IF(NS_FAILED(rv)); } diff --git a/dom/file/uri/BlobURLProtocolHandler.cpp b/dom/file/uri/BlobURLProtocolHandler.cpp index d36ade493fb2..7eb859e437aa 100644 --- a/dom/file/uri/BlobURLProtocolHandler.cpp +++ b/dom/file/uri/BlobURLProtocolHandler.cpp @@ -404,8 +404,7 @@ class ReleasingTimerHolder final : public Runnable, // but we need at least to be able to dispatch to the main thread here. auto raii = MakeScopeExit([holder] { holder->CancelTimerAndRevokeURI(); }); - nsresult rv = - SchedulerGroup::Dispatch(TaskCategory::Other, holder.forget()); + nsresult rv = SchedulerGroup::Dispatch(holder.forget()); NS_ENSURE_SUCCESS_VOID(rv); raii.release(); diff --git a/dom/filesystem/FileSystemUtils.cpp b/dom/filesystem/FileSystemUtils.cpp index 5d4b391596a6..136f683e5e09 100644 --- a/dom/filesystem/FileSystemUtils.cpp +++ b/dom/filesystem/FileSystemUtils.cpp @@ -68,7 +68,7 @@ nsresult FileSystemUtils::DispatchRunnable( if (!aGlobal) { target = GetMainThreadSerialEventTarget(); } else { - target = aGlobal->EventTargetFor(TaskCategory::Other); + target = aGlobal->SerialEventTarget(); } MOZ_ASSERT(target); diff --git a/dom/geolocation/Geolocation.cpp b/dom/geolocation/Geolocation.cpp index 197146d71e97..cb9107deb1ac 100644 --- a/dom/geolocation/Geolocation.cpp +++ b/dom/geolocation/Geolocation.cpp @@ -82,7 +82,7 @@ class nsGeolocationRequest final : public ContentPermissionRequestBase, nsGeolocationRequest(Geolocation* aLocator, GeoPositionCallback aCallback, GeoPositionErrorCallback aErrorCallback, UniquePtr&& aOptions, - nsIEventTarget* aMainThreadTarget, + nsIEventTarget* aMainThreadSerialEventTarget, bool aWatchPositionRequest = false, int32_t aWatchId = 0); @@ -145,7 +145,7 @@ class nsGeolocationRequest final : public ContentPermissionRequestBase, int32_t mWatchId; bool mShutdown; - nsCOMPtr mMainThreadTarget; + nsCOMPtr mMainThreadSerialEventTarget; }; static UniquePtr CreatePositionOptionsCopy( @@ -195,8 +195,9 @@ static nsPIDOMWindowInner* ConvertWeakReferenceToWindow( nsGeolocationRequest::nsGeolocationRequest( Geolocation* aLocator, GeoPositionCallback aCallback, GeoPositionErrorCallback aErrorCallback, - UniquePtr&& aOptions, nsIEventTarget* aMainThreadTarget, - bool aWatchPositionRequest, int32_t aWatchId) + UniquePtr&& aOptions, + nsIEventTarget* aMainThreadSerialEventTarget, bool aWatchPositionRequest, + int32_t aWatchId) : ContentPermissionRequestBase( aLocator->GetPrincipal(), ConvertWeakReferenceToWindow(aLocator->GetOwner()), "geo"_ns, @@ -208,11 +209,7 @@ nsGeolocationRequest::nsGeolocationRequest( mLocator(aLocator), mWatchId(aWatchId), mShutdown(false), - mMainThreadTarget(aMainThreadTarget) { - if (nsCOMPtr win = - do_QueryReferent(mLocator->GetOwner())) { - } -} + mMainThreadSerialEventTarget(aMainThreadSerialEventTarget) {} nsGeolocationRequest::~nsGeolocationRequest() { StopTimeoutTimer(); } @@ -418,7 +415,7 @@ nsIPrincipal* nsGeolocationRequest::GetPrincipal() { NS_IMETHODIMP nsGeolocationRequest::Update(nsIDOMGeoPosition* aPosition) { nsCOMPtr ev = new RequestSendLocationEvent(aPosition, this); - mMainThreadTarget->Dispatch(ev.forget()); + mMainThreadSerialEventTarget->Dispatch(ev.forget()); return NS_OK; } @@ -1012,15 +1009,6 @@ void Geolocation::GetCurrentPosition(PositionCallback& aCallback, } } -static nsIEventTarget* MainThreadTarget(Geolocation* geo) { - nsCOMPtr window = do_QueryReferent(geo->GetOwner()); - if (!window) { - return GetMainThreadSerialEventTarget(); - } - return nsGlobalWindowInner::Cast(window)->EventTargetFor( - mozilla::TaskCategory::Other); -} - nsresult Geolocation::GetCurrentPosition(GeoPositionCallback callback, GeoPositionErrorCallback errorCallback, UniquePtr&& options, @@ -1039,7 +1027,7 @@ nsresult Geolocation::GetCurrentPosition(GeoPositionCallback callback, // After this we hand over ownership of options to our nsGeolocationRequest. - nsIEventTarget* target = MainThreadTarget(this); + nsIEventTarget* target = GetMainThreadSerialEventTarget(); RefPtr request = new nsGeolocationRequest( this, std::move(callback), std::move(errorCallback), std::move(options), target); @@ -1115,7 +1103,7 @@ int32_t Geolocation::WatchPosition(GeoPositionCallback aCallback, // The watch ID: int32_t watchId = mLastWatchId++; - nsIEventTarget* target = MainThreadTarget(this); + nsIEventTarget* target = GetMainThreadSerialEventTarget(); RefPtr request = new nsGeolocationRequest( this, std::move(aCallback), std::move(aErrorCallback), std::move(aOptions), target, true, watchId); @@ -1209,7 +1197,7 @@ void Geolocation::NotifyAllowedRequest(nsGeolocationRequest* aRequest) { } bool Geolocation::RegisterRequestWithPrompt(nsGeolocationRequest* request) { - nsIEventTarget* target = MainThreadTarget(this); + nsIEventTarget* target = GetMainThreadSerialEventTarget(); ContentPermissionRequestBase::PromptResult pr = request->CheckPromptPrefs(); if (pr == ContentPermissionRequestBase::PromptResult::Granted) { request->RequestDelayedTask(target, diff --git a/dom/html/HTMLCanvasElement.cpp b/dom/html/HTMLCanvasElement.cpp index be5e14d2aecd..8e8538c1bd49 100644 --- a/dom/html/HTMLCanvasElement.cpp +++ b/dom/html/HTMLCanvasElement.cpp @@ -645,7 +645,7 @@ nsresult HTMLCanvasElement::DispatchPrintCallback(nsITimerCallback* aCallback) { RefPtr> renderEvent = NewRunnableMethod("dom::HTMLCanvasElement::CallPrintCallback", this, &HTMLCanvasElement::CallPrintCallback); - return OwnerDoc()->Dispatch(TaskCategory::Other, renderEvent.forget()); + return OwnerDoc()->Dispatch(renderEvent.forget()); } void HTMLCanvasElement::CallPrintCallback() { @@ -972,13 +972,11 @@ void HTMLCanvasElement::ToBlob(JSContext* aCx, BlobCallback& aCallback, // According to spec, blob should return null if either its horizontal // dimension or its vertical dimension is zero. See link below. // https://html.spec.whatwg.org/multipage/scripting.html#dom-canvas-toblob - OwnerDoc()->Dispatch( - TaskCategory::Other, - NewRunnableMethod( - "dom::HTMLCanvasElement::ToBlob", &aCallback, - static_cast( - &BlobCallback::Call), - nullptr, nullptr)); + OwnerDoc()->Dispatch(NewRunnableMethod( + "dom::HTMLCanvasElement::ToBlob", &aCallback, + static_cast( + &BlobCallback::Call), + nullptr, nullptr)); return; } diff --git a/dom/html/HTMLDialogElement.cpp b/dom/html/HTMLDialogElement.cpp index 260d168849ff..998ac5ee4f5e 100644 --- a/dom/html/HTMLDialogElement.cpp +++ b/dom/html/HTMLDialogElement.cpp @@ -156,11 +156,9 @@ int32_t HTMLDialogElement::TabIndexDefault() { return 0; } void HTMLDialogElement::QueueCancelDialog() { // queues an element task on the user interaction task source - OwnerDoc() - ->EventTargetFor(TaskCategory::UI) - ->Dispatch(NewRunnableMethod("HTMLDialogElement::RunCancelDialogSteps", - this, - &HTMLDialogElement::RunCancelDialogSteps)); + OwnerDoc()->Dispatch( + NewRunnableMethod("HTMLDialogElement::RunCancelDialogSteps", this, + &HTMLDialogElement::RunCancelDialogSteps)); } void HTMLDialogElement::RunCancelDialogSteps() { diff --git a/dom/html/HTMLMediaElement.cpp b/dom/html/HTMLMediaElement.cpp index 6764b716e94c..670343916103 100644 --- a/dom/html/HTMLMediaElement.cpp +++ b/dom/html/HTMLMediaElement.cpp @@ -61,6 +61,7 @@ #include "mozilla/Preferences.h" #include "mozilla/PresShell.h" #include "mozilla/ScopeExit.h" +#include "mozilla/SchedulerGroup.h" #include "mozilla/Sprintf.h" #include "mozilla/StaticPrefs_media.h" #include "mozilla/SVGObserverUtils.h" @@ -991,15 +992,13 @@ class HTMLMediaElement::MediaElementTrackSource MediaStreamTrackSource) /* MediaDecoder track source */ - MediaElementTrackSource(nsISerialEventTarget* aMainThreadEventTarget, - ProcessedMediaTrack* aTrack, nsIPrincipal* aPrincipal, + MediaElementTrackSource(ProcessedMediaTrack* aTrack, nsIPrincipal* aPrincipal, OutputMuteState aMuteState, bool aHasAlpha) : MediaStreamTrackSource( aPrincipal, nsString(), TrackingId(TrackingId::Source::MediaElementDecoder, sDecoderCaptureSourceId++, TrackingId::TrackAcrossProcesses::Yes)), - mMainThreadEventTarget(aMainThreadEventTarget), mTrack(aTrack), mIntendedElementMuteState(aMuteState), mElementMuteState(aMuteState), @@ -1008,8 +1007,7 @@ class HTMLMediaElement::MediaElementTrackSource } /* MediaStream track source */ - MediaElementTrackSource(nsISerialEventTarget* aMainThreadEventTarget, - MediaStreamTrack* aCapturedTrack, + MediaElementTrackSource(MediaStreamTrack* aCapturedTrack, MediaStreamTrackSource* aCapturedTrackSource, ProcessedMediaTrack* aTrack, MediaInputPort* aPort, OutputMuteState aMuteState) @@ -1018,7 +1016,6 @@ class HTMLMediaElement::MediaElementTrackSource TrackingId(TrackingId::Source::MediaElementStream, sStreamCaptureSourceId++, TrackingId::TrackAcrossProcesses::Yes)), - mMainThreadEventTarget(aMainThreadEventTarget), mCapturedTrack(aCapturedTrack), mCapturedTrackSource(aCapturedTrackSource), mTrack(aTrack), @@ -1052,7 +1049,7 @@ class HTMLMediaElement::MediaElementTrackSource return; } mIntendedElementMuteState = aMuteState; - mMainThreadEventTarget->Dispatch(NS_NewRunnableFunction( + GetMainThreadSerialEventTarget()->Dispatch(NS_NewRunnableFunction( "MediaElementTrackSource::SetMutedByElement", [self = RefPtr(this), this, aMuteState] { mElementMuteState = aMuteState; @@ -1145,7 +1142,6 @@ class HTMLMediaElement::MediaElementTrackSource private: virtual ~MediaElementTrackSource() { Destroy(); }; - const RefPtr mMainThreadEventTarget; RefPtr mCapturedTrack; RefPtr mCapturedTrackSource; const RefPtr mTrack; @@ -1789,10 +1785,9 @@ class HTMLMediaElement::ChannelLoader final { MOZ_ASSERT(aElement); // Per bug 1235183 comment 8, we can't spin the event loop from stable // state. Defer NS_NewChannel() to a new regular runnable. - return aElement->MainThreadEventTarget()->Dispatch( - NewRunnableMethod("ChannelLoader::LoadInternal", - this, &ChannelLoader::LoadInternal, - aElement)); + return aElement->OwnerDoc()->Dispatch(NewRunnableMethod( + "ChannelLoader::LoadInternal", this, &ChannelLoader::LoadInternal, + aElement)); } void Cancel() { @@ -2034,7 +2029,7 @@ already_AddRefed HTMLMediaElement::MozRequestDebugInfo( if (mDecoder) { mDecoder->RequestDebugInfo(result->mDecoder) ->Then( - mAbstractMainThread, __func__, + AbstractMainThread(), __func__, [promise, ptr = std::move(result)]() { promise->MaybeResolve(ptr.get()); }, @@ -2060,7 +2055,7 @@ already_AddRefed HTMLMediaElement::MozRequestDebugLog( } DecoderDoctorLogger::RetrieveMessages(this)->Then( - mAbstractMainThread, __func__, + AbstractMainThread(), __func__, [promise](const nsACString& aString) { promise->MaybeResolve(NS_ConvertUTF8toUTF16(aString)); }, @@ -2619,7 +2614,7 @@ void HTMLMediaElement::SelectResource() { // The media element has neither a src attribute nor a source element child: // set the networkState to NETWORK_EMPTY, and abort these steps; the // synchronous section ends. - mMainThreadEventTarget->Dispatch(NewRunnableMethod( + GetMainThreadSerialEventTarget()->Dispatch(NewRunnableMethod( "HTMLMediaElement::NoSupportedMediaSourceError", this, &HTMLMediaElement::NoSupportedMediaSourceError, rv.Description())); } else { @@ -2770,7 +2765,7 @@ void HTMLMediaElement::DealWithFailedElement(nsIContent* aSourceElement) { } DispatchAsyncSourceError(aSourceElement); - mMainThreadEventTarget->Dispatch( + GetMainThreadSerialEventTarget()->Dispatch( NewRunnableMethod("HTMLMediaElement::QueueLoadFromSourceTask", this, &HTMLMediaElement::QueueLoadFromSourceTask)); } @@ -3563,7 +3558,7 @@ void HTMLMediaElement::AddOutputTrackSourceToOutputStream( switch (aMode) { case AddTrackMode::ASYNC: - mMainThreadEventTarget->Dispatch( + GetMainThreadSerialEventTarget()->Dispatch( NewRunnableMethod>( "DOMMediaStream::AddTrackInternal", aOutputStream.mStream, &DOMMediaStream::AddTrackInternal, domTrack)); @@ -3654,7 +3649,7 @@ void HTMLMediaElement::UpdateOutputTrackSources() { // If we bounce it to the MediaTrackGraph it might not be picked up, // for instance if the MediaInputPort was destroyed in the same // iteration as it was added. - mMainThreadEventTarget->Dispatch( + GetMainThreadSerialEventTarget()->Dispatch( NewRunnableMethod("MediaElementTrackSource::OverrideEnded", source, &MediaElementTrackSource::OverrideEnded)); @@ -3670,7 +3665,7 @@ void HTMLMediaElement::UpdateOutputTrackSources() { if (&aTrack->GetSource() != source) { return false; } - mMainThreadEventTarget->Dispatch( + GetMainThreadSerialEventTarget()->Dispatch( NewRunnableMethod>( "DOMMediaStream::RemoveTrackInternal", ms.mStream, &DOMMediaStream::RemoveTrackInternal, aTrack)); @@ -3755,7 +3750,7 @@ void HTMLMediaElement::UpdateOutputTrackSources() { principal = NodePrincipal(); } source = MakeAndAddRef( - mMainThreadEventTarget, track, principal, OutputTracksMuted(), + track, principal, OutputTracksMuted(), type == MediaSegment::VIDEO ? HTMLVideoElement::FromNode(this)->HasAlpha() : false); @@ -3779,8 +3774,8 @@ void HTMLMediaElement::UpdateOutputTrackSources() { track = inputTrack->Graph()->CreateForwardedInputTrack(type); RefPtr port = inputTrack->ForwardTrackContentsTo(track); source = MakeAndAddRef( - mMainThreadEventTarget, inputTrack, &inputTrack->GetSource(), track, - port, OutputTracksMuted()); + inputTrack, &inputTrack->GetSource(), track, port, + OutputTracksMuted()); // Track is muted initially, so we don't leak data if it's added while // paused and an MTG iteration passes before the mute comes into effect. @@ -4225,11 +4220,7 @@ NS_IMPL_ISUPPORTS(HTMLMediaElement::TitleChangeObserver, nsIObserver) HTMLMediaElement::HTMLMediaElement( already_AddRefed&& aNodeInfo) : nsGenericHTMLElement(std::move(aNodeInfo)), - mWatchManager(this, - OwnerDoc()->AbstractMainThreadFor(TaskCategory::Other)), - mMainThreadEventTarget(OwnerDoc()->EventTargetFor(TaskCategory::Other)), - mAbstractMainThread( - OwnerDoc()->AbstractMainThreadFor(TaskCategory::Other)), + mWatchManager(this, AbstractThread::MainThread()), mShutdownObserver(new ShutdownObserver), mTitleChangeObserver(new TitleChangeObserver(this)), mEventBlocker(new EventBlocker(this)), @@ -4240,8 +4231,7 @@ HTMLMediaElement::HTMLMediaElement( mSink(std::pair(nsString(), RefPtr())), mShowPoster(IsVideo()), mMediaControlKeyListener(new MediaControlKeyListener(this)) { - MOZ_ASSERT(mMainThreadEventTarget); - MOZ_ASSERT(mAbstractMainThread); + MOZ_ASSERT(GetMainThreadSerialEventTarget()); // Please don't add anything to this constructor or the initialization // list that can cause AddRef to be called. This prevents subclasses // from overriding AddRef in a way that works with our refcount @@ -5188,11 +5178,11 @@ void HTMLMediaElement::SetupSrcMediaStreamPlayback(DOMMediaStream* aStream) { VideoFrameContainer* container = GetVideoFrameContainer(); RefPtr firstFrameOutput = - container - ? MakeAndAddRef(container, mAbstractMainThread) - : nullptr; + container ? MakeAndAddRef(container, + AbstractMainThread()) + : nullptr; mMediaStreamRenderer = MakeAndAddRef( - mAbstractMainThread, container, firstFrameOutput, this); + AbstractMainThread(), container, firstFrameOutput, this); mWatchManager.Watch(mPaused, &HTMLMediaElement::UpdateSrcStreamPotentiallyPlaying); mWatchManager.Watch(mReadyState, @@ -5587,7 +5577,7 @@ void HTMLMediaElement::SeekCompleted() { } if (mSeekDOMPromise) { - mAbstractMainThread->Dispatch(NS_NewRunnableFunction( + AbstractMainThread()->Dispatch(NS_NewRunnableFunction( __func__, [promise = std::move(mSeekDOMPromise)] { promise->MaybeResolveWithUndefined(); })); @@ -5597,7 +5587,7 @@ void HTMLMediaElement::SeekCompleted() { void HTMLMediaElement::SeekAborted() { if (mSeekDOMPromise) { - mAbstractMainThread->Dispatch(NS_NewRunnableFunction( + AbstractMainThread()->Dispatch(NS_NewRunnableFunction( __func__, [promise = std::move(mSeekDOMPromise)] { promise->MaybeReject(NS_ERROR_DOM_ABORT_ERR); })); @@ -5696,7 +5686,7 @@ void HTMLMediaElement::StartProgressTimer() { NS_NewTimerWithFuncCallback( getter_AddRefs(mProgressTimer), ProgressTimerCallback, this, PROGRESS_MS, nsITimer::TYPE_REPEATING_SLACK, "HTMLMediaElement::ProgressTimerCallback", - mMainThreadEventTarget); + GetMainThreadSerialEventTarget()); } void HTMLMediaElement::StartProgress() { @@ -6279,7 +6269,7 @@ void HTMLMediaElement::DispatchAsyncEvent(RefPtr aRunner) { mEventBlocker->PostponeEvent(aRunner); return; } - mMainThreadEventTarget->Dispatch(aRunner.forget()); + GetMainThreadSerialEventTarget()->Dispatch(aRunner.forget()); } bool HTMLMediaElement::IsPotentiallyPlaying() const { @@ -6521,13 +6511,13 @@ void HTMLMediaElement::AddRemoveSelfReference() { // The shutdown observer will hold a strong reference to us. This // will do to keep us alive. We need to know about shutdown so that // we can release our self-reference. - mMainThreadEventTarget->Dispatch(NS_NewRunnableFunction( + GetMainThreadSerialEventTarget()->Dispatch(NS_NewRunnableFunction( "dom::HTMLMediaElement::AddSelfReference", [self]() { self->mShutdownObserver->AddRefMediaElement(); })); } else { // Dispatch Release asynchronously so that we don't destroy this object // inside a call stack of method calls on this object - mMainThreadEventTarget->Dispatch(NS_NewRunnableFunction( + GetMainThreadSerialEventTarget()->Dispatch(NS_NewRunnableFunction( "dom::HTMLMediaElement::AddSelfReference", [self]() { self->mShutdownObserver->ReleaseMediaElement(); })); } @@ -6545,7 +6535,7 @@ void HTMLMediaElement::DispatchAsyncSourceError(nsIContent* aSourceElement) { nsCOMPtr event = new nsSourceErrorEventRunner(this, aSourceElement); - mMainThreadEventTarget->Dispatch(event.forget()); + GetMainThreadSerialEventTarget()->Dispatch(event.forget()); } void HTMLMediaElement::NotifyAddedSource() { @@ -6893,7 +6883,7 @@ bool HTMLMediaElement::TryRemoveMediaKeysAssociation() { RefPtr self = this; mDecoder->SetCDMProxy(nullptr) ->Then( - mAbstractMainThread, __func__, + AbstractMainThread(), __func__, [self]() { self->mSetCDMRequest.Complete(); @@ -6967,7 +6957,7 @@ bool HTMLMediaElement::TryMakeAssociationWithCDM(CDMProxy* aProxy) { RefPtr self = this; mDecoder->SetCDMProxy(aProxy) ->Then( - mAbstractMainThread, __func__, + AbstractMainThread(), __func__, [self]() { self->mSetCDMRequest.Complete(); self->MakeAssociationWithCDMResolved(); @@ -7341,9 +7331,7 @@ void HTMLMediaElement::UpdateCustomPolicyAfterPlayed() { } AbstractThread* HTMLMediaElement::AbstractMainThread() const { - MOZ_ASSERT(mAbstractMainThread); - - return mAbstractMainThread; + return AbstractThread::MainThread(); } nsTArray> HTMLMediaElement::TakePendingPlayPromises() { @@ -7391,7 +7379,7 @@ void HTMLMediaElement::AsyncResolvePendingPlayPromises() { nsCOMPtr event = new nsResolveOrRejectPendingPlayPromisesRunner( this, TakePendingPlayPromises()); - mMainThreadEventTarget->Dispatch(event.forget()); + GetMainThreadSerialEventTarget()->Dispatch(event.forget()); } void HTMLMediaElement::AsyncRejectPendingPlayPromises(nsresult aError) { @@ -7411,7 +7399,7 @@ void HTMLMediaElement::AsyncRejectPendingPlayPromises(nsresult aError) { nsCOMPtr event = new nsResolveOrRejectPendingPlayPromisesRunner( this, TakePendingPlayPromises(), aError); - mMainThreadEventTarget->Dispatch(event.forget()); + GetMainThreadSerialEventTarget()->Dispatch(event.forget()); } void HTMLMediaElement::GetEMEInfo(dom::EMEDebugInfo& aInfo) { @@ -7559,14 +7547,14 @@ already_AddRefed HTMLMediaElement::SetSinkId(const nsAString& aSinkId, nsString sinkId(aSinkId); mediaDevices->GetSinkDevice(sinkId) ->Then( - mAbstractMainThread, __func__, + AbstractMainThread(), __func__, [self = RefPtr(this), this](RefPtr&& aInfo) { // Sink found switch output device. MOZ_ASSERT(aInfo); if (mDecoder) { RefPtr p = mDecoder->SetSink(aInfo)->Then( - mAbstractMainThread, __func__, + AbstractMainThread(), __func__, [aInfo](const GenericPromise::ResolveOrRejectValue& aValue) { if (aValue.IsResolve()) { return SinkInfoPromise::CreateAndResolve(aInfo, __func__); @@ -7580,7 +7568,7 @@ already_AddRefed HTMLMediaElement::SetSinkId(const nsAString& aSinkId, MOZ_ASSERT(mMediaStreamRenderer); RefPtr p = mMediaStreamRenderer->SetAudioOutputDevice(aInfo)->Then( - mAbstractMainThread, __func__, + AbstractMainThread(), __func__, [aInfo](const GenericPromise::AllPromiseType:: ResolveOrRejectValue& aValue) { if (aValue.IsResolve()) { @@ -7599,7 +7587,7 @@ already_AddRefed HTMLMediaElement::SetSinkId(const nsAString& aSinkId, // Promise is rejected, sink not found. return SinkInfoPromise::CreateAndReject(res, __func__); }) - ->Then(mAbstractMainThread, __func__, + ->Then(AbstractMainThread(), __func__, [promise, self = RefPtr(this), this, sinkId](const SinkInfoPromise::ResolveOrRejectValue& aValue) { if (aValue.IsResolve()) { @@ -7630,7 +7618,7 @@ void HTMLMediaElement::NotifyTextTrackModeChanged() { return; } mPendingTextTrackChanged = true; - mAbstractMainThread->Dispatch( + AbstractMainThread()->Dispatch( NS_NewRunnableFunction("HTMLMediaElement::NotifyTextTrackModeChanged", [this, self = RefPtr(this)]() { mPendingTextTrackChanged = false; @@ -7659,7 +7647,7 @@ void HTMLMediaElement::CreateResumeDelayedMediaPlaybackAgentIfNeeded() { } mResumeDelayedPlaybackAgent->GetResumePromise() ->Then( - mAbstractMainThread, __func__, + AbstractMainThread(), __func__, [self = RefPtr(this)]() { LOG(LogLevel::Debug, ("%p Resume delayed Play() call", self.get())); self->mResumePlaybackRequest.Complete(); @@ -7775,7 +7763,7 @@ void HTMLMediaElement::SetSecondaryMediaStreamRenderer( } if (aContainer) { mSecondaryMediaStreamRenderer = MakeAndAddRef( - mAbstractMainThread, aContainer, aFirstFrameOutput, this); + AbstractMainThread(), aContainer, aFirstFrameOutput, this); if (mSrcStreamIsPlaying) { mSecondaryMediaStreamRenderer->Start(); } diff --git a/dom/html/HTMLMediaElement.h b/dom/html/HTMLMediaElement.h index 52c1521d1339..5f25ae5799f7 100644 --- a/dom/html/HTMLMediaElement.h +++ b/dom/html/HTMLMediaElement.h @@ -809,10 +809,6 @@ class HTMLMediaElement : public nsGenericHTMLElement, already_AddRefed CreateGMPCrashHelper() override; - nsISerialEventTarget* MainThreadEventTarget() { - return mMainThreadEventTarget; - } - // Set the sink id (of the output device) that the audio will play. If aSinkId // is empty the default device will be set. already_AddRefed SetSinkId(const nsAString& aSinkId, @@ -1416,13 +1412,6 @@ class HTMLMediaElement : public nsGenericHTMLElement, // At most one of mDecoder and mSrcStream can be non-null. RefPtr mDecoder; - // The DocGroup-specific nsISerialEventTarget of this HTML element on the main - // thread. - nsCOMPtr mMainThreadEventTarget; - - // The DocGroup-specific AbstractThread::MainThread() of this HTML element. - RefPtr mAbstractMainThread; - // A reference to the VideoFrameContainer which contains the current frame // of video to display. RefPtr mVideoFrameContainer; diff --git a/dom/html/HTMLTrackElement.cpp b/dom/html/HTMLTrackElement.cpp index 11411bcddc62..5363d3e39936 100644 --- a/dom/html/HTMLTrackElement.cpp +++ b/dom/html/HTMLTrackElement.cpp @@ -370,7 +370,7 @@ void HTMLTrackElement::LoadResource(RefPtr&& aWebVTTListener) { } mChannel = channel; }); - doc->Dispatch(TaskCategory::Other, runnable.forget()); + doc->Dispatch(runnable.forget()); } nsresult HTMLTrackElement::BindToTree(BindContext& aContext, nsINode& aParent) { @@ -460,7 +460,7 @@ void HTMLTrackElement::DispatchTrackRunnable(const nsString& aEventName) { nsCOMPtr runnable = NewRunnableMethod( "dom::HTMLTrackElement::DispatchTrustedEvent", this, &HTMLTrackElement::DispatchTrustedEvent, aEventName); - doc->Dispatch(TaskCategory::Other, runnable.forget()); + doc->Dispatch(runnable.forget()); } void HTMLTrackElement::DispatchTrustedEvent(const nsAString& aName) { diff --git a/dom/html/HTMLVideoElement.cpp b/dom/html/HTMLVideoElement.cpp index daf4a18a495e..24989d0b177f 100644 --- a/dom/html/HTMLVideoElement.cpp +++ b/dom/html/HTMLVideoElement.cpp @@ -94,7 +94,7 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END HTMLVideoElement::HTMLVideoElement(already_AddRefed&& aNodeInfo) : HTMLMediaElement(std::move(aNodeInfo)), mIsOrientationLocked(false), - mVideoWatchManager(this, mAbstractMainThread) { + mVideoWatchManager(this, AbstractThread::MainThread()) { DecoderDoctorLogger::LogConstruction(this); } @@ -583,8 +583,8 @@ void HTMLVideoElement::MaybeBeginCloningVisually() { VideoFrameContainer* container = mVisualCloneTarget->GetVideoFrameContainer(); if (container) { - mSecondaryVideoOutput = - MakeRefPtr(container, mAbstractMainThread); + mSecondaryVideoOutput = MakeRefPtr( + container, AbstractThread::MainThread()); mVideoWatchManager.Watch( mSecondaryVideoOutput->mFirstFrameRendered, &HTMLVideoElement::OnSecondaryVideoOutputFirstFrameRendered); @@ -635,7 +635,7 @@ void HTMLVideoElement::OnSecondaryVideoContainerInstalled( return; } - mMainThreadEventTarget->Dispatch(NewRunnableMethod( + NS_DispatchToCurrentThread(NewRunnableMethod( "Promise::MaybeResolveWithUndefined", mVisualCloneTargetPromise, &Promise::MaybeResolveWithUndefined)); mVisualCloneTargetPromise = nullptr; diff --git a/dom/html/TextTrackManager.cpp b/dom/html/TextTrackManager.cpp index 9e3f9dbad09a..7aacb5bf736e 100644 --- a/dom/html/TextTrackManager.cpp +++ b/dom/html/TextTrackManager.cpp @@ -463,7 +463,7 @@ class SimpleTextTrackEvent : public Runnable { void Dispatch() { if (nsCOMPtr global = mCue->GetOwnerGlobal()) { - global->Dispatch(TaskCategory::Other, do_AddRef(this)); + global->Dispatch(do_AddRef(this)); } else { NS_DispatchToMainThread(do_AddRef(this)); } @@ -587,10 +587,8 @@ class TextTrackListInternal { void TextTrackManager::DispatchUpdateCueDisplay() { if (!mUpdateCueDisplayDispatched && !IsShutdown()) { WEBVTT_LOG("DispatchUpdateCueDisplay"); - nsPIDOMWindowInner* win = mMediaElement->OwnerDoc()->GetInnerWindow(); - if (win) { + if (nsPIDOMWindowInner* win = mMediaElement->OwnerDoc()->GetInnerWindow()) { nsGlobalWindowInner::Cast(win)->Dispatch( - TaskCategory::Other, NewRunnableMethod("dom::TextTrackManager::UpdateCueDisplay", this, &TextTrackManager::UpdateCueDisplay)); mUpdateCueDisplayDispatched = true; @@ -605,10 +603,8 @@ void TextTrackManager::DispatchTimeMarchesOn() { // executing call upon completion will check queue for further 'work'. if (!mTimeMarchesOnDispatched && !IsShutdown()) { WEBVTT_LOG("DispatchTimeMarchesOn"); - nsPIDOMWindowInner* win = mMediaElement->OwnerDoc()->GetInnerWindow(); - if (win) { + if (nsPIDOMWindowInner* win = mMediaElement->OwnerDoc()->GetInnerWindow()) { nsGlobalWindowInner::Cast(win)->Dispatch( - TaskCategory::Other, NewRunnableMethod("dom::TextTrackManager::TimeMarchesOn", this, &TextTrackManager::TimeMarchesOn)); mTimeMarchesOnDispatched = true; diff --git a/dom/html/nsGenericHTMLElement.cpp b/dom/html/nsGenericHTMLElement.cpp index 6a2a5b08822e..11b02b96c20d 100644 --- a/dom/html/nsGenericHTMLElement.cpp +++ b/dom/html/nsGenericHTMLElement.cpp @@ -3253,8 +3253,7 @@ void nsGenericHTMLElement::QueuePopoverEventTask( auto task = MakeRefPtr(do_GetWeakReference(this), aOldState); data->SetToggleEventTask(task); - - OwnerDoc()->Dispatch(TaskCategory::UI, task.forget()); + OwnerDoc()->Dispatch(task.forget()); } void nsGenericHTMLElement::RunPopoverToggleEventTask( diff --git a/dom/html/nsHTMLContentSink.cpp b/dom/html/nsHTMLContentSink.cpp index e7956d674ce6..0c22b3e9aa6d 100644 --- a/dom/html/nsHTMLContentSink.cpp +++ b/dom/html/nsHTMLContentSink.cpp @@ -933,7 +933,5 @@ void HTMLContentSink::ContinueInterruptedParsingAsync() { nsCOMPtr ev = NewRunnableMethod( "HTMLContentSink::ContinueInterruptedParsingIfEnabled", this, &HTMLContentSink::ContinueInterruptedParsingIfEnabled); - - RefPtr doc = mHTMLDocument; - doc->Dispatch(mozilla::TaskCategory::Other, ev.forget()); + mHTMLDocument->Dispatch(ev.forget()); } diff --git a/dom/html/nsHTMLDocument.cpp b/dom/html/nsHTMLDocument.cpp index b5ce86e33bd7..d76de92f50ee 100644 --- a/dom/html/nsHTMLDocument.cpp +++ b/dom/html/nsHTMLDocument.cpp @@ -737,8 +737,7 @@ void nsHTMLDocument::GetFormsAndFormControls(nsContentList** aFormList, holder = new ContentListHolder(this, htmlForms, htmlFormControls); RefPtr runnable = holder; - if (NS_SUCCEEDED( - Dispatch(TaskCategory::GarbageCollection, runnable.forget()))) { + if (NS_SUCCEEDED(Dispatch(runnable.forget()))) { mContentListHolder = holder; } } diff --git a/dom/indexedDB/ActorsParent.cpp b/dom/indexedDB/ActorsParent.cpp index c551efd0fd9c..3f88e27f5f9b 100644 --- a/dom/indexedDB/ActorsParent.cpp +++ b/dom/indexedDB/ActorsParent.cpp @@ -86,7 +86,6 @@ #include "mozilla/SnappyCompressOutputStream.h" #include "mozilla/SpinEventLoopUntil.h" #include "mozilla/StaticPtr.h" -#include "mozilla/TaskCategory.h" #include "mozilla/TimeStamp.h" #include "mozilla/UniquePtr.h" #include "mozilla/Unused.h" @@ -6413,8 +6412,7 @@ class DeserializeIndexValueHelper final : public Runnable { MonitorAutoLock lock(mMonitor); RefPtr self = this; - QM_TRY(MOZ_TO_RESULT( - SchedulerGroup::Dispatch(TaskCategory::Other, self.forget()))); + QM_TRY(MOZ_TO_RESULT(SchedulerGroup::Dispatch(self.forget()))); lock.Wait(); return mStatus; diff --git a/dom/indexedDB/IDBFactory.cpp b/dom/indexedDB/IDBFactory.cpp index 51f5970debbf..c136d93fabb1 100644 --- a/dom/indexedDB/IDBFactory.cpp +++ b/dom/indexedDB/IDBFactory.cpp @@ -179,7 +179,7 @@ Result, nsresult> IDBFactory::CreateForWindow( factory->mBrowserChild = BrowserChild::GetFrom(aWindow); factory->mEventTarget = - nsGlobalWindowInner::Cast(aWindow)->EventTargetFor(TaskCategory::Other); + nsGlobalWindowInner::Cast(aWindow)->SerialEventTarget(); factory->mInnerWindowID = aWindow->WindowID(); factory->mPrivateBrowsingMode = loadContext && loadContext->UsePrivateBrowsing(); diff --git a/dom/indexedDB/SchemaUpgrades.cpp b/dom/indexedDB/SchemaUpgrades.cpp index d33ebafd6a55..60663907406d 100644 --- a/dom/indexedDB/SchemaUpgrades.cpp +++ b/dom/indexedDB/SchemaUpgrades.cpp @@ -42,7 +42,6 @@ #include "mozilla/RefPtr.h" #include "mozilla/SchedulerGroup.h" #include "mozilla/Span.h" -#include "mozilla/TaskCategory.h" #include "mozilla/UniquePtr.h" #include "mozilla/dom/ScriptSettings.h" #include "mozilla/dom/indexedDB/IDBResult.h" @@ -2755,8 +2754,7 @@ class DeserializeUpgradeValueHelper final : public Runnable { MonitorAutoLock lock(mMonitor); RefPtr self = this; - const nsresult rv = - SchedulerGroup::Dispatch(TaskCategory::Other, self.forget()); + const nsresult rv = SchedulerGroup::Dispatch(self.forget()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/dom/indexedDB/ScriptErrorHelper.cpp b/dom/indexedDB/ScriptErrorHelper.cpp index c867a6654dcc..0bf33336ba32 100644 --- a/dom/indexedDB/ScriptErrorHelper.cpp +++ b/dom/indexedDB/ScriptErrorHelper.cpp @@ -165,8 +165,7 @@ void ScriptErrorHelper::Dump(const nsAString& aMessage, RefPtr runnable = new ScriptErrorRunnable(aMessage, aFilename, aLineNumber, aColumnNumber, aSeverityFlag, aIsChrome, aInnerWindowID); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, runnable.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(runnable.forget())); } } @@ -183,8 +182,7 @@ void ScriptErrorHelper::DumpLocalizedMessage( RefPtr runnable = new ScriptErrorRunnable( aMessageName, aFilename, aLineNumber, aColumnNumber, aSeverityFlag, aIsChrome, aInnerWindowID); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, runnable.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(runnable.forget())); } } diff --git a/dom/ipc/BrowserChild.cpp b/dom/ipc/BrowserChild.cpp index 694932338877..7815060c31bc 100644 --- a/dom/ipc/BrowserChild.cpp +++ b/dom/ipc/BrowserChild.cpp @@ -4,33 +4,24 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include "base/basictypes.h" - #include "BrowserChild.h" #ifdef ACCESSIBILITY # include "mozilla/a11y/DocAccessibleChild.h" #endif -#include #include #include "BrowserParent.h" #include "ContentChild.h" -#include "DocumentInlines.h" #include "EventStateManager.h" #include "MMPrinter.h" -#include "PermissionMessageUtils.h" #include "PuppetWidget.h" #include "StructuredCloneData.h" #include "UnitTransforms.h" #include "Units.h" #include "VRManagerChild.h" -#include "ipc/nsGUIEventIPC.h" -#include "js/JSON.h" #include "mozilla/Assertions.h" -#include "mozilla/AsyncEventDispatcher.h" #include "mozilla/BasePrincipal.h" -#include "mozilla/ClearOnShutdown.h" #include "mozilla/EventForwards.h" #include "mozilla/EventListenerManager.h" #include "mozilla/HoldDropJSObjects.h" @@ -39,36 +30,29 @@ #include "mozilla/MouseEvents.h" #include "mozilla/NativeKeyBindingsType.h" #include "mozilla/NullPrincipal.h" -#include "mozilla/Preferences.h" #include "mozilla/PresShell.h" #include "mozilla/ProcessHangMonitor.h" #include "mozilla/ProfilerLabels.h" -#include "mozilla/ResultExtensions.h" +#include "mozilla/SchedulerGroup.h" #include "mozilla/ScopeExit.h" #include "mozilla/Services.h" #include "mozilla/StaticPrefs_dom.h" -#include "mozilla/StaticPrefs_fission.h" -#include "mozilla/StaticPtr.h" -#include "mozilla/Telemetry.h" #include "mozilla/TextEvents.h" -#include "mozilla/TouchEvents.h" #include "mozilla/ToString.h" #include "mozilla/Unused.h" #include "mozilla/dom/AutoPrintEventDispatcher.h" #include "mozilla/dom/BrowserBridgeChild.h" #include "mozilla/dom/DataTransfer.h" -#include "mozilla/dom/DocGroup.h" #include "mozilla/dom/Element.h" #include "mozilla/dom/Event.h" #include "mozilla/dom/JSWindowActorChild.h" #include "mozilla/dom/ImageDocument.h" #include "mozilla/dom/LoadURIOptionsBinding.h" -#include "mozilla/dom/MediaDocument.h" #include "mozilla/dom/MessageManagerBinding.h" #include "mozilla/dom/MouseEventBinding.h" #include "mozilla/dom/Nullable.h" -#include "mozilla/dom/PBrowser.h" #include "mozilla/dom/PaymentRequestChild.h" +#include "mozilla/dom/PBrowser.h" #include "mozilla/dom/PointerEventHandler.h" #include "mozilla/dom/SessionStoreUtils.h" #include "mozilla/dom/SessionStoreChild.h" @@ -76,11 +60,9 @@ #include "mozilla/dom/WindowProxyHolder.h" #include "mozilla/gfx/CrossProcessPaint.h" #include "mozilla/gfx/Matrix.h" -#include "mozilla/gfx/gfxVars.h" #include "mozilla/ipc/BackgroundChild.h" #include "mozilla/ipc/BackgroundUtils.h" #include "mozilla/ipc/PBackgroundChild.h" -#include "mozilla/ipc/URIUtils.h" #include "mozilla/layers/APZCCallbackHelper.h" #include "mozilla/layers/TouchActionHelper.h" #include "mozilla/layers/APZCTreeManagerChild.h" @@ -94,14 +76,12 @@ #include "mozilla/layers/InputAPZContext.h" #include "mozilla/layers/WebRenderLayerManager.h" #include "nsBrowserStatusFilter.h" -#include "nsColorPickerProxy.h" #include "nsCommandParams.h" #include "nsContentPermissionHelper.h" #include "nsContentUtils.h" #include "nsDeviceContext.h" #include "nsDocShell.h" #include "nsDocShellLoadState.h" -#include "nsEmbedCID.h" #include "nsExceptionHandler.h" #include "nsFilePickerProxy.h" #include "nsFocusManager.h" @@ -116,7 +96,6 @@ #include "nsISHistory.h" #include "nsIScreenManager.h" #include "nsIScriptError.h" -#include "nsISecureBrowserUI.h" #include "nsIURI.h" #include "nsIURIMutator.h" #include "nsIWeakReferenceUtils.h" @@ -127,18 +106,11 @@ #include "nsIOpenWindowInfo.h" #include "nsPIDOMWindow.h" #include "nsPIWindowRoot.h" -#include "nsPointerHashKeys.h" #include "nsPrintfCString.h" -#include "nsQueryActor.h" -#include "nsQueryObject.h" #include "nsRefreshDriver.h" -#include "nsSandboxFlags.h" -#include "nsString.h" -#include "nsTHashtable.h" #include "nsThreadManager.h" #include "nsThreadUtils.h" #include "nsViewManager.h" -#include "nsViewportInfo.h" #include "nsWebBrowser.h" #include "nsWindowWatcher.h" #include "nsIXULRuntime.h" @@ -3808,21 +3780,10 @@ already_AddRefed BrowserChildMessageManager::GetDocShell( already_AddRefed BrowserChildMessageManager::GetTabEventTarget() { - nsCOMPtr target = EventTargetFor(TaskCategory::Other); - return target.forget(); + return do_AddRef(GetMainThreadSerialEventTarget()); } nsresult BrowserChildMessageManager::Dispatch( - TaskCategory aCategory, already_AddRefed&& aRunnable) { - return DispatcherTrait::Dispatch(aCategory, std::move(aRunnable)); -} - -nsISerialEventTarget* BrowserChildMessageManager::EventTargetFor( - TaskCategory aCategory) const { - return DispatcherTrait::EventTargetFor(aCategory); -} - -AbstractThread* BrowserChildMessageManager::AbstractMainThreadFor( - TaskCategory aCategory) { - return DispatcherTrait::AbstractMainThreadFor(aCategory); + already_AddRefed&& aRunnable) const { + return SchedulerGroup::Dispatch(std::move(aRunnable)); } diff --git a/dom/ipc/BrowserChild.h b/dom/ipc/BrowserChild.h index cc1d5b1cdcb2..91945783a225 100644 --- a/dom/ipc/BrowserChild.h +++ b/dom/ipc/BrowserChild.h @@ -13,7 +13,6 @@ #include "nsCOMPtr.h" #include "nsIWebBrowserChrome.h" #include "nsIWebBrowserChromeFocus.h" -#include "nsIDOMEventListener.h" #include "nsIInterfaceRequestor.h" #include "nsIWindowProvider.h" #include "nsIDocShell.h" @@ -33,16 +32,14 @@ #include "mozilla/DOMEventTargetHelper.h" #include "mozilla/EventDispatcher.h" #include "mozilla/EventForwards.h" -#include "mozilla/layers/CompositorTypes.h" #include "mozilla/layers/APZCCallbackHelper.h" #include "mozilla/layers/CompositorOptions.h" +#include "mozilla/layers/CompositorTypes.h" #include "mozilla/layers/GeckoContentControllerTypes.h" #include "mozilla/dom/ipc/IdType.h" -#include "AudioChannelService.h" #include "PuppetWidget.h" #include "nsDeque.h" #include "nsIRemoteTab.h" -#include "nsTHashSet.h" class nsBrowserStatusFilter; class nsIDOMWindow; @@ -91,7 +88,6 @@ class WebProgressData; class BrowserChildMessageManager : public ContentFrameMessageManager, public nsIMessageSender, - public DispatcherTrait, public nsSupportsWeakReference { public: explicit BrowserChildMessageManager(BrowserChild* aBrowserChild); @@ -105,10 +101,9 @@ class BrowserChildMessageManager : public ContentFrameMessageManager, JSObject* WrapObject(JSContext* aCx, JS::Handle aGivenProto) override; - virtual Nullable GetContent(ErrorResult& aError) override; - virtual already_AddRefed GetDocShell( - ErrorResult& aError) override; - virtual already_AddRefed GetTabEventTarget() override; + Nullable GetContent(ErrorResult& aError) override; + already_AddRefed GetDocShell(ErrorResult& aError) override; + already_AddRefed GetTabEventTarget() override; NS_FORWARD_SAFE_NSIMESSAGESENDER(mMessageManager) @@ -117,14 +112,7 @@ class BrowserChildMessageManager : public ContentFrameMessageManager, } // Dispatch a runnable related to the global. - virtual nsresult Dispatch(mozilla::TaskCategory aCategory, - already_AddRefed&& aRunnable) override; - - virtual nsISerialEventTarget* EventTargetFor( - mozilla::TaskCategory aCategory) const override; - - virtual AbstractThread* AbstractMainThreadFor( - mozilla::TaskCategory aCategory) override; + nsresult Dispatch(already_AddRefed&& aRunnable) const; RefPtr mBrowserChild; diff --git a/dom/ipc/ContentChild.cpp b/dom/ipc/ContentChild.cpp index 3f7b6fe09ff6..89e6b4d114ac 100644 --- a/dom/ipc/ContentChild.cpp +++ b/dom/ipc/ContentChild.cpp @@ -802,7 +802,6 @@ void ContentChild::Init(mozilla::ipc::UntypedEndpoint&& aEndpoint, // NOTE: We have to register the annotator on the main thread, as annotators // only affect a single thread. SchedulerGroup::Dispatch( - TaskCategory::Other, NS_NewRunnableFunction("RegisterPendingInputEventHangAnnotator", [] { BackgroundHangMonitor::RegisterAnnotator( PendingInputEventHangAnnotator::sSingleton); diff --git a/dom/jsurl/nsJSProtocolHandler.cpp b/dom/jsurl/nsJSProtocolHandler.cpp index b4e0f2187a2b..763ddfd5cbc1 100644 --- a/dom/jsurl/nsJSProtocolHandler.cpp +++ b/dom/jsurl/nsJSProtocolHandler.cpp @@ -708,7 +708,7 @@ nsJSChannel::AsyncOpen(nsIStreamListener* aListener) { nsCOMPtr runnable = mozilla::NewRunnableMethod(name, this, method); nsGlobalWindowInner* window = nsGlobalWindowInner::Cast(mOriginalInnerWindow); - rv = window->Dispatch(mozilla::TaskCategory::Other, runnable.forget()); + rv = window->Dispatch(runnable.forget()); if (NS_FAILED(rv)) { loadGroup->RemoveRequest(this, nullptr, rv); diff --git a/dom/media/BackgroundVideoDecodingPermissionObserver.cpp b/dom/media/BackgroundVideoDecodingPermissionObserver.cpp index 6e477b49b903..f91629a090ea 100644 --- a/dom/media/BackgroundVideoDecodingPermissionObserver.cpp +++ b/dom/media/BackgroundVideoDecodingPermissionObserver.cpp @@ -51,12 +51,9 @@ void BackgroundVideoDecodingPermissionObserver::RegisterEvent() { // Events shall not be fired synchronously to prevent anything visible // from the scripts while we are in stable state. if (nsCOMPtr doc = GetOwnerDoc()) { - doc->Dispatch( - TaskCategory::Other, - NewRunnableMethod( - "BackgroundVideoDecodingPermissionObserver::" - "EnableEvent", - this, &BackgroundVideoDecodingPermissionObserver::EnableEvent)); + doc->Dispatch(NewRunnableMethod( + "BackgroundVideoDecodingPermissionObserver::EnableEvent", this, + &BackgroundVideoDecodingPermissionObserver::EnableEvent)); } } else { EnableEvent(); @@ -75,13 +72,9 @@ void BackgroundVideoDecodingPermissionObserver::UnregisterEvent() { // Events shall not be fired synchronously to prevent anything visible // from the scripts while we are in stable state. if (nsCOMPtr doc = GetOwnerDoc()) { - doc->Dispatch( - TaskCategory::Other, - NewRunnableMethod( - "BackgroundVideoDecodingPermissionObserver::" - "DisableEvent", - this, - &BackgroundVideoDecodingPermissionObserver::DisableEvent)); + doc->Dispatch(NewRunnableMethod( + "BackgroundVideoDecodingPermissionObserver::DisableEvent", this, + &BackgroundVideoDecodingPermissionObserver::DisableEvent)); } } else { DisableEvent(); diff --git a/dom/media/GraphDriver.cpp b/dom/media/GraphDriver.cpp index fdd1803a46cc..f346c6fab4b2 100644 --- a/dom/media/GraphDriver.cpp +++ b/dom/media/GraphDriver.cpp @@ -98,7 +98,7 @@ ThreadedDriver::~ThreadedDriver() { if (mThread) { nsCOMPtr event = new MediaTrackGraphShutdownThreadRunnable(mThread.forget()); - SchedulerGroup::Dispatch(TaskCategory::Other, event.forget()); + SchedulerGroup::Dispatch(event.forget()); } } diff --git a/dom/media/MediaDevices.cpp b/dom/media/MediaDevices.cpp index 5849fb2759bc..cfbc148337bd 100644 --- a/dom/media/MediaDevices.cpp +++ b/dom/media/MediaDevices.cpp @@ -766,14 +766,8 @@ void MediaDevices::SetupDeviceChangeListener() { return; } - nsISerialEventTarget* mainThread = - window->EventTargetFor(TaskCategory::Other); - if (!mainThread) { - return; - } - mDeviceChangeListener = MediaManager::Get()->DeviceListChangeEvent().Connect( - mainThread, this, &MediaDevices::OnDeviceChange); + GetMainThreadSerialEventTarget(), this, &MediaDevices::OnDeviceChange); mIsDeviceChangeListenerSetUp = true; MediaManager::Get()->GetPhysicalDevices()->Then( diff --git a/dom/media/MediaRecorder.cpp b/dom/media/MediaRecorder.cpp index 9f8c2ad4256e..bdfab11056b6 100644 --- a/dom/media/MediaRecorder.cpp +++ b/dom/media/MediaRecorder.cpp @@ -588,7 +588,6 @@ class MediaRecorder::Session : public PrincipalChangeObserver, uint32_t aVideoBitsPerSecond, uint32_t aAudioBitsPerSecond) : mRecorder(aRecorder), mMediaStreamTracks(std::move(aMediaStreamTracks)), - mMainThread(mRecorder->GetOwner()->EventTargetFor(TaskCategory::Other)), mMimeType(SelectMimeType( mMediaStreamTracks.Contains(TrackTypeComparator::VIDEO, TrackTypeComparator()), @@ -762,7 +761,7 @@ class MediaRecorder::Session : public PrincipalChangeObserver, InvokeAsync(mEncoderThread, mEncoder.get(), __func__, &MediaEncoder::RequestData) ->Then( - mMainThread, __func__, + GetMainThreadSerialEventTarget(), __func__, [this, self = RefPtr(this)]( const MediaEncoder::BlobPromise::ResolveOrRejectValue& aRrv) { if (aRrv.IsReject()) { @@ -868,13 +867,14 @@ class MediaRecorder::Session : public PrincipalChangeObserver, return; } - mStartedListener = mEncoder->StartedEvent().Connect(mMainThread, this, - &Session::OnStarted); + nsISerialEventTarget* mainThread = GetMainThreadSerialEventTarget(); + mStartedListener = + mEncoder->StartedEvent().Connect(mainThread, this, &Session::OnStarted); mDataAvailableListener = mEncoder->DataAvailableEvent().Connect( - mMainThread, this, &Session::OnDataAvailable); + mainThread, this, &Session::OnDataAvailable); mErrorListener = - mEncoder->ErrorEvent().Connect(mMainThread, this, &Session::OnError); - mShutdownListener = mEncoder->ShutdownEvent().Connect(mMainThread, this, + mEncoder->ErrorEvent().Connect(mainThread, this, &Session::OnError); + mShutdownListener = mEncoder->ShutdownEvent().Connect(mainThread, this, &Session::OnShutdown); if (mRecorder->mAudioNode) { @@ -946,7 +946,7 @@ class MediaRecorder::Session : public PrincipalChangeObserver, blobPromise ->Then( - mMainThread, __func__, + GetMainThreadSerialEventTarget(), __func__, [this, self = RefPtr(this), rv, needsStartEvent]( const MediaEncoder::BlobPromise::ResolveOrRejectValue& aRv) { if (mRecorder->mSessions.LastElement() == this) { @@ -991,16 +991,17 @@ class MediaRecorder::Session : public PrincipalChangeObserver, // And finally, Shutdown and destroy the Session return Shutdown(); }) - ->Then(mMainThread, __func__, [this, self = RefPtr(this)] { - // Guard against the case where we fail to add a blocker due to being - // in XPCOM shutdown. If we're in this state we shouldn't try and get - // a shutdown barrier as we'll fail. - if (!mShutdownBlocker) { - return; - } - MustGetShutdownBarrier()->RemoveBlocker(mShutdownBlocker); - mShutdownBlocker = nullptr; - }); + ->Then(GetMainThreadSerialEventTarget(), __func__, + [this, self = RefPtr(this)] { + // Guard against the case where we fail to add a blocker due to + // being in XPCOM shutdown. If we're in this state we shouldn't + // try and get a shutdown barrier as we'll fail. + if (!mShutdownBlocker) { + return; + } + MustGetShutdownBarrier()->RemoveBlocker(mShutdownBlocker); + mShutdownBlocker = nullptr; + }); } void OnStarted() { @@ -1065,7 +1066,7 @@ class MediaRecorder::Session : public PrincipalChangeObserver, if (mEncoder) { mShutdownPromise = mShutdownPromise - ->Then(mMainThread, __func__, + ->Then(GetMainThreadSerialEventTarget(), __func__, [this, self = RefPtr(this)] { mStartedListener.DisconnectIfExists(); mDataAvailableListener.DisconnectIfExists(); @@ -1095,7 +1096,7 @@ class MediaRecorder::Session : public PrincipalChangeObserver, // Break the cycle reference between Session and MediaRecorder. mShutdownPromise = mShutdownPromise->Then( - mMainThread, __func__, + GetMainThreadSerialEventTarget(), __func__, [self = RefPtr(this)]() { self->mRecorder->RemoveSession(self); return ShutdownPromise::CreateAndResolve(true, __func__); @@ -1107,7 +1108,7 @@ class MediaRecorder::Session : public PrincipalChangeObserver, if (mEncoderThread) { mShutdownPromise = mShutdownPromise->Then( - mMainThread, __func__, + GetMainThreadSerialEventTarget(), __func__, [encoderThread = mEncoderThread]() { return encoderThread->BeginShutdown(); }, @@ -1139,8 +1140,6 @@ class MediaRecorder::Session : public PrincipalChangeObserver, // set. nsTArray> mMediaStreamTracks; - // Main thread used for MozPromise operations. - const RefPtr mMainThread; // Runnable thread for reading data from MediaEncoder. RefPtr mEncoderThread; // MediaEncoder pipeline. diff --git a/dom/media/MediaStreamTrack.cpp b/dom/media/MediaStreamTrack.cpp index 58b44cb30837..8ddb16d8e1fc 100644 --- a/dom/media/MediaStreamTrack.cpp +++ b/dom/media/MediaStreamTrack.cpp @@ -122,12 +122,9 @@ class MediaStreamTrack::MTGListener : public MediaTrackListener { return; } - AbstractThread* mainThread = - nsGlobalWindowInner::Cast(mTrack->GetParentObject()) - ->AbstractMainThreadFor(TaskCategory::Other); - mainThread->Dispatch(NewRunnableMethod("MediaStreamTrack::OverrideEnded", - mTrack.get(), - &MediaStreamTrack::OverrideEnded)); + AbstractThread::MainThread()->Dispatch( + NewRunnableMethod("MediaStreamTrack::OverrideEnded", mTrack.get(), + &MediaStreamTrack::OverrideEnded)); } void NotifyEnded(MediaTrackGraph* aGraph) override { diff --git a/dom/media/MediaTrackGraph.cpp b/dom/media/MediaTrackGraph.cpp index 9a412f9f470f..2f16e28e7291 100644 --- a/dom/media/MediaTrackGraph.cpp +++ b/dom/media/MediaTrackGraph.cpp @@ -3418,22 +3418,14 @@ MediaTrackGraph* MediaTrackGraph::GetInstance( aGraphDriverRequested, aWindow->WindowID(), aWindow->AsGlobal()->ShouldResistFingerprinting( RFPTarget::AudioSampleRate), - aSampleRate, aOutputDeviceID, - aWindow->EventTargetFor(TaskCategory::Other)); + aSampleRate, aOutputDeviceID, GetMainThreadSerialEventTarget()); } MediaTrackGraph* MediaTrackGraph::CreateNonRealtimeInstance( - TrackRate aSampleRate, nsPIDOMWindowInner* aWindow) { + TrackRate aSampleRate) { MOZ_ASSERT(NS_IsMainThread(), "Main thread only"); nsISerialEventTarget* mainThread = GetMainThreadSerialEventTarget(); - // aWindow can be null when the document is being unlinked, so this works when - // with a generic main thread if that's the case. - if (aWindow) { - mainThread = - aWindow->AsGlobal()->AbstractMainThreadFor(TaskCategory::Other); - } - // Offline graphs have 0 output channel count: they write the output to a // buffer, not an audio output track. MediaTrackGraphImpl* graph = diff --git a/dom/media/MediaTrackGraph.h b/dom/media/MediaTrackGraph.h index 34004f6262ec..4668141a83b3 100644 --- a/dom/media/MediaTrackGraph.h +++ b/dom/media/MediaTrackGraph.h @@ -1025,8 +1025,7 @@ class MediaTrackGraph { static MediaTrackGraph* GetInstance( GraphDriverType aGraphDriverRequested, nsPIDOMWindowInner* aWindow, TrackRate aSampleRate, CubebUtils::AudioDeviceID aOutputDeviceID); - static MediaTrackGraph* CreateNonRealtimeInstance( - TrackRate aSampleRate, nsPIDOMWindowInner* aWindowId); + static MediaTrackGraph* CreateNonRealtimeInstance(TrackRate aSampleRate); // Idempotent void ForceShutDown(); diff --git a/dom/media/VideoStreamTrack.cpp b/dom/media/VideoStreamTrack.cpp index ff02017dacfa..bfb7da4e2900 100644 --- a/dom/media/VideoStreamTrack.cpp +++ b/dom/media/VideoStreamTrack.cpp @@ -31,9 +31,7 @@ void VideoStreamTrack::AddVideoOutput(VideoFrameContainer* aSink) { if (Ended()) { return; } - auto output = MakeRefPtr( - aSink, nsGlobalWindowInner::Cast(GetParentObject()) - ->AbstractMainThreadFor(TaskCategory::Other)); + auto output = MakeRefPtr(aSink, AbstractThread::MainThread()); AddVideoOutput(output); } diff --git a/dom/media/VideoUtils.cpp b/dom/media/VideoUtils.cpp index 296b97dadb07..b1035b3a5434 100644 --- a/dom/media/VideoUtils.cpp +++ b/dom/media/VideoUtils.cpp @@ -18,7 +18,6 @@ #include "mozilla/SharedThreadPool.h" #include "mozilla/StaticPrefs_accessibility.h" #include "mozilla/StaticPrefs_media.h" -#include "mozilla/TaskCategory.h" #include "mozilla/TaskQueue.h" #include "mozilla/Telemetry.h" #include "nsCharSeparatedTokenizer.h" @@ -1028,7 +1027,7 @@ void LogToBrowserConsole(const nsAString& aMsg) { nsString msg(aMsg); nsCOMPtr task = NS_NewRunnableFunction( "LogToBrowserConsole", [msg]() { LogToBrowserConsole(msg); }); - SchedulerGroup::Dispatch(TaskCategory::Other, task.forget()); + SchedulerGroup::Dispatch(task.forget()); return; } nsCOMPtr console( diff --git a/dom/media/autoplay/GVAutoplayPermissionRequest.cpp b/dom/media/autoplay/GVAutoplayPermissionRequest.cpp index 600c7d291e9f..beb3fb59fc67 100644 --- a/dom/media/autoplay/GVAutoplayPermissionRequest.cpp +++ b/dom/media/autoplay/GVAutoplayPermissionRequest.cpp @@ -111,7 +111,7 @@ void GVAutoplayPermissionRequest::CreateRequest(nsGlobalWindowInner* aWindow, } else { LOG("Dispatch async request"); request->RequestDelayedTask( - aWindow->EventTargetFor(TaskCategory::Other), + aWindow->SerialEventTarget(), GVAutoplayPermissionRequest::DelayedTaskType::Request); } } diff --git a/dom/media/doctor/DecoderDoctorLogger.cpp b/dom/media/doctor/DecoderDoctorLogger.cpp index 927650babc81..57a86e742178 100644 --- a/dom/media/doctor/DecoderDoctorLogger.cpp +++ b/dom/media/doctor/DecoderDoctorLogger.cpp @@ -113,7 +113,6 @@ bool DecoderDoctorLogger::EnsureLogIsEnabled() { sMediaLogs = mediaLogsConstruction.mMediaLogs; // Setup shutdown-time clean-up. MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch( - TaskCategory::Other, NS_NewRunnableFunction("DDLogger shutdown setup", [] { sDDLogShutdowner = MakeUnique(); ClearOnShutdown(&sDDLogShutdowner, diff --git a/dom/media/gmp/GMPServiceChild.cpp b/dom/media/gmp/GMPServiceChild.cpp index 5ecafa24650c..8b54bf09734a 100644 --- a/dom/media/gmp/GMPServiceChild.cpp +++ b/dom/media/gmp/GMPServiceChild.cpp @@ -425,7 +425,7 @@ GeckoMediaPluginServiceChild::GetServiceChild() { if (mGetServiceChildPromises.Length() == 1) { nsCOMPtr r = WrapRunnable(contentChild, &dom::ContentChild::SendCreateGMPService); - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget()); + SchedulerGroup::Dispatch(r.forget()); } return promise; } diff --git a/dom/media/gtest/GMPTestMonitor.h b/dom/media/gtest/GMPTestMonitor.h index 226d5c77a9f5..27477b6a42d7 100644 --- a/dom/media/gtest/GMPTestMonitor.h +++ b/dom/media/gtest/GMPTestMonitor.h @@ -29,10 +29,8 @@ class GMPTestMonitor { public: void SetFinished() { - mozilla::SchedulerGroup::Dispatch(mozilla::TaskCategory::Other, - mozilla::NewNonOwningRunnableMethod( - "GMPTestMonitor::MarkFinished", this, - &GMPTestMonitor::MarkFinished)); + mozilla::SchedulerGroup::Dispatch(mozilla::NewNonOwningRunnableMethod( + "GMPTestMonitor::MarkFinished", this, &GMPTestMonitor::MarkFinished)); } private: diff --git a/dom/media/gtest/TestCDMStorage.cpp b/dom/media/gtest/TestCDMStorage.cpp index ca965e497efd..c248d10d3192 100644 --- a/dom/media/gtest/TestCDMStorage.cpp +++ b/dom/media/gtest/TestCDMStorage.cpp @@ -194,7 +194,7 @@ static void ClearCDMStorage(already_AddRefed aContinuation, nsIThread* aTarget, PRTime aSince = -1) { RefPtr task( new ClearCDMStorageTask(std::move(aContinuation), aTarget, aSince)); - SchedulerGroup::Dispatch(TaskCategory::Other, task.forget()); + SchedulerGroup::Dispatch(task.forget()); } static void SimulatePBModeExit() { @@ -504,11 +504,9 @@ class CDMStorageTest { // Collect nodeIds that are expected to remain for later comparison. EnumerateCDMStorageDir("id"_ns, NodeIdCollector(siteInfo.get())); // Invoke "Forget this site" on the main thread. - SchedulerGroup::Dispatch( - TaskCategory::Other, - NewRunnableMethod&&>( - "CDMStorageTest::TestForgetThisSite_Forget", this, - &CDMStorageTest::TestForgetThisSite_Forget, std::move(siteInfo))); + SchedulerGroup::Dispatch(NewRunnableMethod&&>( + "CDMStorageTest::TestForgetThisSite_Forget", this, + &CDMStorageTest::TestForgetThisSite_Forget, std::move(siteInfo))); } void TestForgetThisSite_Forget(UniquePtr&& aSiteInfo) { @@ -669,12 +667,9 @@ class CDMStorageTest { // Collect nodeIds that are expected to remain for later comparison. EnumerateCDMStorageDir("id"_ns, BaseDomainNodeIdCollector(siteInfo.get())); // Invoke "ForgetThisBaseDomain" on the main thread. - SchedulerGroup::Dispatch( - TaskCategory::Other, - NewRunnableMethod&&>( - "CDMStorageTest::TestForgetThisBaseDomain_Forget", this, - &CDMStorageTest::TestForgetThisBaseDomain_Forget, - std::move(siteInfo))); + SchedulerGroup::Dispatch(NewRunnableMethod&&>( + "CDMStorageTest::TestForgetThisBaseDomain_Forget", this, + &CDMStorageTest::TestForgetThisBaseDomain_Forget, std::move(siteInfo))); } void TestForgetThisBaseDomain_Forget( @@ -1093,7 +1088,7 @@ class CDMStorageTest { NewRunnableMethod("CDMStorageTest::Shutdown", this, &CDMStorageTest::Shutdown), std::move(aContinuation), mNodeId)); - SchedulerGroup::Dispatch(TaskCategory::Other, task.forget()); + SchedulerGroup::Dispatch(task.forget()); } void Shutdown() { @@ -1111,7 +1106,7 @@ class CDMStorageTest { Shutdown(); nsCOMPtr task = NewRunnableMethod( "CDMStorageTest::Dummy", this, &CDMStorageTest::Dummy); - SchedulerGroup::Dispatch(TaskCategory::Other, task.forget()); + SchedulerGroup::Dispatch(task.forget()); } void SessionMessage(const nsACString& aSessionId, uint32_t aMessageType, diff --git a/dom/media/imagecapture/CaptureTask.cpp b/dom/media/imagecapture/CaptureTask.cpp index d83de76f5ed6..42dbdde46e59 100644 --- a/dom/media/imagecapture/CaptureTask.cpp +++ b/dom/media/imagecapture/CaptureTask.cpp @@ -191,7 +191,7 @@ void CaptureTask::PostTrackEndEvent() { IC_LOG("Got MediaTrack track removed or finished event."); nsCOMPtr event = new TrackEndRunnable(this); - SchedulerGroup::Dispatch(TaskCategory::Other, event.forget()); + SchedulerGroup::Dispatch(event.forget()); } } // namespace mozilla diff --git a/dom/media/mediacapabilities/MediaCapabilities.cpp b/dom/media/mediacapabilities/MediaCapabilities.cpp index c8fa03e74776..abc83dae4d02 100644 --- a/dom/media/mediacapabilities/MediaCapabilities.cpp +++ b/dom/media/mediacapabilities/MediaCapabilities.cpp @@ -296,7 +296,6 @@ already_AddRefed MediaCapabilities::DecodingInfo( // otherwise. static RefPtr sVideoAllocPolicy = [&taskQueue]() { SchedulerGroup::Dispatch( - TaskCategory::Other, NS_NewRunnableFunction( "MediaCapabilities::AllocPolicy:Video", []() { ClearOnShutdown(&sVideoAllocPolicy, @@ -436,7 +435,7 @@ already_AddRefed MediaCapabilities::DecodingInfo( RefPtr workerRef; if (NS_IsMainThread()) { - targetThread = mParent->AbstractMainThreadFor(TaskCategory::Other); + targetThread = GetMainThreadSerialEventTarget(); } else { WorkerPrivate* wp = GetCurrentThreadWorkerPrivate(); MOZ_ASSERT(wp, "Must be called from a worker thread"); diff --git a/dom/media/mediasource/MediaSource.cpp b/dom/media/mediasource/MediaSource.cpp index c8de4228b8cf..148876716667 100644 --- a/dom/media/mediasource/MediaSource.cpp +++ b/dom/media/mediasource/MediaSource.cpp @@ -530,8 +530,7 @@ MediaSource::MediaSource(nsPIDOMWindowInner* aWindow) : DOMEventTargetHelper(aWindow), mDecoder(nullptr), mPrincipal(nullptr), - mAbstractMainThread( - GetOwnerGlobal()->AbstractMainThreadFor(TaskCategory::Other)), + mAbstractMainThread(AbstractThread::MainThread()), mReadyState(MediaSourceReadyState::Closed) { MOZ_ASSERT(NS_IsMainThread()); mSourceBuffers = new SourceBufferList(this); diff --git a/dom/media/platforms/AllocationPolicy.cpp b/dom/media/platforms/AllocationPolicy.cpp index a56bf1d3a1dd..ea7aaa74c8b1 100644 --- a/dom/media/platforms/AllocationPolicy.cpp +++ b/dom/media/platforms/AllocationPolicy.cpp @@ -93,25 +93,19 @@ NotNull GlobalAllocPolicy::Instance(TrackType aTrack) { StaticMutexAutoLock lock(sMutex); if (aTrack == TrackType::kAudioTrack) { static RefPtr sAudioPolicy = []() { - SchedulerGroup::Dispatch( - TaskCategory::Other, - NS_NewRunnableFunction( - "GlobalAllocPolicy::GlobalAllocPolicy:Audio", []() { - ClearOnShutdown(&sAudioPolicy, - ShutdownPhase::XPCOMShutdownThreads); - })); + SchedulerGroup::Dispatch(NS_NewRunnableFunction( + "GlobalAllocPolicy::GlobalAllocPolicy:Audio", []() { + ClearOnShutdown(&sAudioPolicy, ShutdownPhase::XPCOMShutdownThreads); + })); return new AllocPolicyImpl(MediaDecoderLimitDefault()); }(); return WrapNotNull(sAudioPolicy.get()); } static RefPtr sVideoPolicy = []() { - SchedulerGroup::Dispatch( - TaskCategory::Other, - NS_NewRunnableFunction( - "GlobalAllocPolicy::GlobalAllocPolicy:Audio", []() { - ClearOnShutdown(&sVideoPolicy, - ShutdownPhase::XPCOMShutdownThreads); - })); + SchedulerGroup::Dispatch(NS_NewRunnableFunction( + "GlobalAllocPolicy::GlobalAllocPolicy:Audio", []() { + ClearOnShutdown(&sVideoPolicy, ShutdownPhase::XPCOMShutdownThreads); + })); return new AllocPolicyImpl(MediaDecoderLimitDefault()); }(); return WrapNotNull(sVideoPolicy.get()); diff --git a/dom/media/webaudio/AnalyserNode.cpp b/dom/media/webaudio/AnalyserNode.cpp index eacb8957ff40..d8b547477e55 100644 --- a/dom/media/webaudio/AnalyserNode.cpp +++ b/dom/media/webaudio/AnalyserNode.cpp @@ -76,7 +76,7 @@ class AnalyserNodeEngine final : public AudioNodeEngine { RefPtr transfer = new TransferBuffer(aTrack, aInput.AsAudioChunk()); - mAbstractMainThread->Dispatch(transfer.forget()); + AbstractThread::MainThread()->Dispatch(transfer.forget()); } virtual bool IsActive() const override { return mChunksToProcess != 0; } diff --git a/dom/media/webaudio/AudioContext.cpp b/dom/media/webaudio/AudioContext.cpp index 6bede8139c8f..2ef5fdd65bcb 100644 --- a/dom/media/webaudio/AudioContext.cpp +++ b/dom/media/webaudio/AudioContext.cpp @@ -766,9 +766,8 @@ double AudioContext::CurrentTime() { nsISerialEventTarget* AudioContext::GetMainThread() const { if (nsPIDOMWindowInner* window = GetParentObject()) { - return window->AsGlobal()->EventTargetFor(TaskCategory::Other); + return window->AsGlobal()->SerialEventTarget(); } - return GetCurrentSerialEventTarget(); } @@ -851,12 +850,10 @@ class OnStateChangeTask final : public Runnable { void AudioContext::Dispatch(already_AddRefed&& aRunnable) { MOZ_ASSERT(NS_IsMainThread()); - nsCOMPtr parentObject = do_QueryInterface(GetParentObject()); // It can happen that this runnable took a long time to reach the main thread, // and the global is not valid anymore. - if (parentObject) { - parentObject->AbstractMainThreadFor(TaskCategory::Other) - ->Dispatch(std::move(aRunnable)); + if (GetParentObject()) { + AbstractThread::MainThread()->Dispatch(std::move(aRunnable)); } else { RefPtr runnable(aRunnable); runnable = nullptr; diff --git a/dom/media/webaudio/AudioDestinationNode.cpp b/dom/media/webaudio/AudioDestinationNode.cpp index a40e3b5eea24..c0c483d4bacd 100644 --- a/dom/media/webaudio/AudioDestinationNode.cpp +++ b/dom/media/webaudio/AudioDestinationNode.cpp @@ -390,8 +390,8 @@ AudioNodeTrack* AudioDestinationNode::Track() { // GetParentObject can return nullptr here when the document has been // unlinked. - MediaTrackGraph* graph = MediaTrackGraph::CreateNonRealtimeInstance( - context->SampleRate(), context->GetParentObject()); + MediaTrackGraph* graph = + MediaTrackGraph::CreateNonRealtimeInstance(context->SampleRate()); AudioNodeEngine* engine = new OfflineDestinationNodeEngine(this); mTrack = AudioNodeTrack::Create(context, engine, kTrackFlags, graph); @@ -426,8 +426,8 @@ void AudioDestinationNode::NotifyMainThreadTrackEnded() { MOZ_ASSERT(NS_IsMainThread()); MOZ_ASSERT(mTrack->IsEnded()); - if (mIsOffline && GetAbstractMainThread()) { - GetAbstractMainThread()->Dispatch(NewRunnableMethod( + if (mIsOffline) { + AbstractThread::MainThread()->Dispatch(NewRunnableMethod( "dom::AudioDestinationNode::FireOfflineCompletionEvent", this, &AudioDestinationNode::FireOfflineCompletionEvent)); } diff --git a/dom/media/webaudio/AudioNode.cpp b/dom/media/webaudio/AudioNode.cpp index 8bbbffe1b7ad..f5c56d0da663 100644 --- a/dom/media/webaudio/AudioNode.cpp +++ b/dom/media/webaudio/AudioNode.cpp @@ -54,12 +54,7 @@ AudioNode::AudioNode(AudioContext* aContext, uint32_t aChannelCount, mChannelCountMode(aChannelCountMode), mChannelInterpretation(aChannelInterpretation), mId(gId++), - mPassThrough(false), - mAbstractMainThread( - aContext->GetOwnerGlobal() - ? aContext->GetOwnerGlobal()->AbstractMainThreadFor( - TaskCategory::Other) - : nullptr) { + mPassThrough(false) { MOZ_ASSERT(aContext); aContext->RegisterNode(this); } diff --git a/dom/media/webaudio/AudioNode.h b/dom/media/webaudio/AudioNode.h index 795123dcea65..561749fd6185 100644 --- a/dom/media/webaudio/AudioNode.h +++ b/dom/media/webaudio/AudioNode.h @@ -207,10 +207,6 @@ class AudioNode : public DOMEventTargetHelper, public nsSupportsWeakReference { // type. virtual const char* NodeType() const = 0; - // This can return nullptr, but only when the AudioNode has been created - // during document shutdown. - AbstractThread* GetAbstractMainThread() const { return mAbstractMainThread; } - const nsTArray>& GetAudioParams() const { return mParams; } private: @@ -286,9 +282,6 @@ class AudioNode : public DOMEventTargetHelper, public nsSupportsWeakReference { // Whether the node just passes through its input. This is a devtools API // that only works for some node types. bool mPassThrough; - // DocGroup-specifc AbstractThread::MainThread() for MediaTrackGraph - // operations. - const RefPtr mAbstractMainThread; }; } // namespace dom diff --git a/dom/media/webaudio/AudioNodeEngine.cpp b/dom/media/webaudio/AudioNodeEngine.cpp index 75f0edde97e9..3fba688b8cc0 100644 --- a/dom/media/webaudio/AudioNodeEngine.cpp +++ b/dom/media/webaudio/AudioNodeEngine.cpp @@ -410,10 +410,7 @@ AudioNodeEngine::AudioNodeEngine(dom::AudioNode* aNode) : mNode(aNode), mNodeType(aNode ? aNode->NodeType() : nullptr), mInputCount(aNode ? aNode->NumberOfInputs() : 1), - mOutputCount(aNode ? aNode->NumberOfOutputs() : 0), - mAbstractMainThread(aNode && aNode->GetAbstractMainThread() - ? aNode->GetAbstractMainThread() - : AbstractThread::MainThread()) { + mOutputCount(aNode ? aNode->NumberOfOutputs() : 0) { MOZ_ASSERT(NS_IsMainThread()); MOZ_COUNT_CTOR(AudioNodeEngine); } diff --git a/dom/media/webaudio/AudioNodeEngine.h b/dom/media/webaudio/AudioNodeEngine.h index fabddb798cbf..7a30e1b4ccea 100644 --- a/dom/media/webaudio/AudioNodeEngine.h +++ b/dom/media/webaudio/AudioNodeEngine.h @@ -382,9 +382,6 @@ class AudioNodeEngine { const char* const mNodeType; const uint16_t mInputCount; const uint16_t mOutputCount; - - protected: - const RefPtr mAbstractMainThread; }; } // namespace mozilla diff --git a/dom/media/webaudio/DynamicsCompressorNode.cpp b/dom/media/webaudio/DynamicsCompressorNode.cpp index 1508c4487661..7ec27d9495b0 100644 --- a/dom/media/webaudio/DynamicsCompressorNode.cpp +++ b/dom/media/webaudio/DynamicsCompressorNode.cpp @@ -147,7 +147,8 @@ class DynamicsCompressorNodeEngine final : public AudioNodeEngine { float mReduction; }; - mAbstractMainThread->Dispatch(do_AddRef(new Command(aTrack, aReduction))); + AbstractThread::MainThread()->Dispatch( + do_AddRef(new Command(aTrack, aReduction))); } private: diff --git a/dom/media/webaudio/MediaBufferDecoder.cpp b/dom/media/webaudio/MediaBufferDecoder.cpp index b98d461511cc..425c0639b58c 100644 --- a/dom/media/webaudio/MediaBufferDecoder.cpp +++ b/dom/media/webaudio/MediaBufferDecoder.cpp @@ -204,8 +204,7 @@ bool MediaDecodeTask::Init() { RefPtr resource = new BufferMediaResource(static_cast(mBuffer), mLength); - mMainThread = mDecodeJob.mContext->GetOwnerGlobal()->AbstractMainThreadFor( - TaskCategory::Other); + mMainThread = AbstractThread::MainThread(); mPSupervisorTaskQueue = TaskQueue::Create(GetMediaThreadPool(MediaThreadType::SUPERVISOR), diff --git a/dom/media/webaudio/MediaElementAudioSourceNode.cpp b/dom/media/webaudio/MediaElementAudioSourceNode.cpp index d02ef2f4dea0..953fee66d919 100644 --- a/dom/media/webaudio/MediaElementAudioSourceNode.cpp +++ b/dom/media/webaudio/MediaElementAudioSourceNode.cpp @@ -74,14 +74,9 @@ JSObject* MediaElementAudioSourceNode::WrapObject( void MediaElementAudioSourceNode::ListenForAllowedToPlay( const MediaElementAudioSourceOptions& aOptions) { - if (!GetAbstractMainThread()) { - // The AudioContext must have been closed. It won't be able to start anyway. - return; - } - aOptions.mMediaElement->GetAllowedToPlayPromise() ->Then( - GetAbstractMainThread(), __func__, + AbstractThread::MainThread(), __func__, // Capture by reference to bypass the mozilla-refcounted-inside-lambda // static analysis. We capture a non-owning reference so as to allow // cycle collection of the node. The reference is cleared via diff --git a/dom/media/webaudio/ScriptProcessorNode.cpp b/dom/media/webaudio/ScriptProcessorNode.cpp index aafbec4202cf..1e645a2b428c 100644 --- a/dom/media/webaudio/ScriptProcessorNode.cpp +++ b/dom/media/webaudio/ScriptProcessorNode.cpp @@ -455,7 +455,7 @@ class ScriptProcessorNodeEngine final : public AudioNodeEngine { RefPtr command = new Command(aTrack, mInputBuffer.forget(), playbackTime); - mAbstractMainThread->Dispatch(command.forget()); + AbstractThread::MainThread()->Dispatch(command.forget()); } friend class ScriptProcessorNode; diff --git a/dom/media/webaudio/WebAudioUtils.cpp b/dom/media/webaudio/WebAudioUtils.cpp index cbc1177b9d67..78edc2947e5a 100644 --- a/dom/media/webaudio/WebAudioUtils.cpp +++ b/dom/media/webaudio/WebAudioUtils.cpp @@ -69,7 +69,7 @@ void WebAudioUtils::LogToDeveloperConsole(uint64_t aWindowID, nsCOMPtr task = NS_NewRunnableFunction( "dom::WebAudioUtils::LogToDeveloperConsole", [aWindowID, aKey] { LogToDeveloperConsole(aWindowID, aKey); }); - SchedulerGroup::Dispatch(TaskCategory::Other, task.forget()); + SchedulerGroup::Dispatch(task.forget()); return; } diff --git a/dom/media/webrtc/CubebDeviceEnumerator.cpp b/dom/media/webrtc/CubebDeviceEnumerator.cpp index b5e705ea7d36..625f5724b934 100644 --- a/dom/media/webrtc/CubebDeviceEnumerator.cpp +++ b/dom/media/webrtc/CubebDeviceEnumerator.cpp @@ -38,7 +38,6 @@ CubebDeviceEnumerator* CubebDeviceEnumerator::GetInstance() { setClearOnShutdown(); } else { SchedulerGroup::Dispatch( - TaskCategory::Other, NS_NewRunnableFunction("CubebDeviceEnumerator::::GetInstance()", std::move(setClearOnShutdown))); } diff --git a/dom/media/webrtc/jsapi/PeerConnectionImpl.cpp b/dom/media/webrtc/jsapi/PeerConnectionImpl.cpp index fd18861b3b36..ab2a1bdf7412 100644 --- a/dom/media/webrtc/jsapi/PeerConnectionImpl.cpp +++ b/dom/media/webrtc/jsapi/PeerConnectionImpl.cpp @@ -818,8 +818,7 @@ PeerConnectionImpl::EnsureDataConnection(uint16_t aLocalPort, return NS_OK; } - nsCOMPtr target = - mWindow ? mWindow->EventTargetFor(TaskCategory::Other) : nullptr; + nsCOMPtr target = GetMainThreadSerialEventTarget(); Maybe mms = aMMSSet ? Some(aMaxMessageSize) : Nothing(); if (auto res = DataChannelConnection::Create(this, target, mTransportHandler, aLocalPort, aNumstreams, mms)) { diff --git a/dom/media/webvtt/TextTrack.cpp b/dom/media/webvtt/TextTrack.cpp index 97b6c4f96069..7ee9ee63d235 100644 --- a/dom/media/webvtt/TextTrack.cpp +++ b/dom/media/webvtt/TextTrack.cpp @@ -283,11 +283,9 @@ void TextTrack::DispatchAsyncTrustedEvent(const nsString& aEventName) { return; } RefPtr self = this; - nsGlobalWindowInner::Cast(win)->Dispatch( - TaskCategory::Other, - NS_NewRunnableFunction( - "dom::TextTrack::DispatchAsyncTrustedEvent", - [self, aEventName]() { self->DispatchTrustedEvent(aEventName); })); + nsGlobalWindowInner::Cast(win)->Dispatch(NS_NewRunnableFunction( + "dom::TextTrack::DispatchAsyncTrustedEvent", + [self, aEventName]() { self->DispatchTrustedEvent(aEventName); })); } bool TextTrack::IsLoaded() { diff --git a/dom/media/webvtt/TextTrackCue.cpp b/dom/media/webvtt/TextTrackCue.cpp index a1d46e3c2a54..038ebef79ab2 100644 --- a/dom/media/webvtt/TextTrackCue.cpp +++ b/dom/media/webvtt/TextTrackCue.cpp @@ -58,8 +58,7 @@ TextTrackCue::TextTrackCue(nsPIDOMWindowInner* aOwnerWindow, double aStartTime, mLine(0.0), mReset(false, "TextTrackCue::mReset"), mHaveStartedWatcher(false), - mWatchManager( - this, GetOwnerGlobal()->AbstractMainThreadFor(TaskCategory::Other)) { + mWatchManager(this, AbstractThread::MainThread()) { LOG("create TextTrackCue"); SetDefaultCueSettings(); MOZ_ASSERT(aOwnerWindow); @@ -80,8 +79,7 @@ TextTrackCue::TextTrackCue(nsPIDOMWindowInner* aOwnerWindow, double aStartTime, mLine(0.0), mReset(false, "TextTrackCue::mReset"), mHaveStartedWatcher(false), - mWatchManager( - this, GetOwnerGlobal()->AbstractMainThreadFor(TaskCategory::Other)) { + mWatchManager(this, AbstractThread::MainThread()) { LOG("create TextTrackCue"); SetDefaultCueSettings(); MOZ_ASSERT(aOwnerWindow); diff --git a/dom/media/webvtt/TextTrackList.cpp b/dom/media/webvtt/TextTrackList.cpp index e415adbeb4f4..5d51ff48fecd 100644 --- a/dom/media/webvtt/TextTrackList.cpp +++ b/dom/media/webvtt/TextTrackList.cpp @@ -132,13 +132,11 @@ void TextTrackList::CreateAndDispatchChangeEvent() { event->SetTrusted(true); nsCOMPtr eventRunner = new TrackEventRunner(this, event); - nsGlobalWindowInner::Cast(win)->Dispatch(TaskCategory::Other, - eventRunner.forget()); + nsGlobalWindowInner::Cast(win)->Dispatch(eventRunner.forget()); } void TextTrackList::CreateAndDispatchTrackEventRunner( TextTrack* aTrack, const nsAString& aEventName) { - DebugOnly rv; nsCOMPtr target = GetMainThreadSerialEventTarget(); if (!target) { // If we are not able to get the main-thread object we are shutting down. @@ -151,8 +149,8 @@ void TextTrackList::CreateAndDispatchTrackEventRunner( TrackEvent::Constructor(this, aEventName, eventInit); // Dispatch the TrackEvent asynchronously. - rv = target->Dispatch(do_AddRef(new TrackEventRunner(this, event)), - NS_DISPATCH_NORMAL); + DebugOnly rv = target->Dispatch( + do_AddRef(new TrackEventRunner(this, event)), NS_DISPATCH_NORMAL); // If we are shutting down this can file but it's still ok. NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Dispatch failed"); diff --git a/dom/messagechannel/MessagePort.cpp b/dom/messagechannel/MessagePort.cpp index 6d7cae3436d0..1c4df2006969 100644 --- a/dom/messagechannel/MessagePort.cpp +++ b/dom/messagechannel/MessagePort.cpp @@ -473,14 +473,6 @@ void MessagePort::Dispatch() { mMessages.RemoveElementAt(0); mPostMessageRunnable = new PostMessageRunnable(this, data); - - nsCOMPtr global = GetOwnerGlobal(); - if (NS_IsMainThread() && global) { - MOZ_ALWAYS_SUCCEEDS( - global->Dispatch(TaskCategory::Other, do_AddRef(mPostMessageRunnable))); - return; - } - MOZ_ALWAYS_SUCCEEDS(NS_DispatchToCurrentThread(mPostMessageRunnable)); } diff --git a/dom/network/TCPSocket.cpp b/dom/network/TCPSocket.cpp index 9b4e56f3bde3..f7ac7d3f9b6b 100644 --- a/dom/network/TCPSocket.cpp +++ b/dom/network/TCPSocket.cpp @@ -239,12 +239,12 @@ nsresult TCPSocket::Init(nsIProxyInfo* aProxyInfo) { obs->AddObserver(this, "profile-change-net-teardown", true); // weak ref } - if (XRE_GetProcessType() == GeckoProcessType_Content) { + if (XRE_IsContentProcess()) { mReadyState = TCPReadyState::Connecting; nsCOMPtr target; if (nsCOMPtr global = GetOwnerGlobal()) { - target = global->EventTargetFor(TaskCategory::Other); + target = global->SerialEventTarget(); } mSocketBridgeChild = new TCPSocketChild(mHost, mPort, target); mSocketBridgeChild->SendOpen(this, mSsl, mUseArrayBuffers); diff --git a/dom/notification/Notification.cpp b/dom/notification/Notification.cpp index a28a1cf59b24..e691b1785d66 100644 --- a/dom/notification/Notification.cpp +++ b/dom/notification/Notification.cpp @@ -584,10 +584,7 @@ inline nsresult NotificationPermissionRequest::DispatchResolvePromise() { nsCOMPtr resolver = NewRunnableMethod("NotificationPermissionRequest::DispatchResolvePromise", this, &NotificationPermissionRequest::ResolvePromise); - if (nsIEventTarget* target = mWindow->EventTargetFor(TaskCategory::Other)) { - return target->Dispatch(resolver.forget(), nsIEventTarget::DISPATCH_NORMAL); - } - return NS_ERROR_FAILURE; + return nsGlobalWindowInner::Cast(mWindow.get())->Dispatch(resolver.forget()); } nsresult NotificationPermissionRequest::ResolvePromise() { @@ -1489,7 +1486,7 @@ already_AddRefed Notification::RequestPermission( nsCOMPtr request = new NotificationPermissionRequest( principal, window, promise, permissionCallback); - window->AsGlobal()->Dispatch(TaskCategory::Other, request.forget()); + window->AsGlobal()->Dispatch(request.forget()); return promise.forget(); } @@ -1689,7 +1686,7 @@ already_AddRefed Notification::Get( RefPtr r = new NotificationGetRunnable(origin, aFilter.mTag, callback); - aRv = aWindow->AsGlobal()->Dispatch(TaskCategory::Other, r.forget()); + aRv = aWindow->AsGlobal()->Dispatch(r.forget()); if (NS_WARN_IF(aRv.Failed())) { return nullptr; } @@ -2319,16 +2316,7 @@ nsresult Notification::DispatchToMainThread( return mWorkerPrivate->DispatchToMainThread(std::move(aRunnable)); } AssertIsOnMainThread(); - if (nsCOMPtr global = GetOwnerGlobal()) { - if (nsIEventTarget* target = global->EventTargetFor(TaskCategory::Other)) { - return target->Dispatch(std::move(aRunnable), - nsIEventTarget::DISPATCH_NORMAL); - } - } - nsCOMPtr mainTarget = GetMainThreadSerialEventTarget(); - MOZ_ASSERT(mainTarget); - return mainTarget->Dispatch(std::move(aRunnable), - nsIEventTarget::DISPATCH_NORMAL); + return NS_DispatchToCurrentThread(std::move(aRunnable)); } } // namespace mozilla::dom diff --git a/dom/payments/PaymentResponse.cpp b/dom/payments/PaymentResponse.cpp index 1f107b07470e..2ea393455c46 100644 --- a/dom/payments/PaymentResponse.cpp +++ b/dom/payments/PaymentResponse.cpp @@ -68,7 +68,7 @@ PaymentResponse::PaymentResponse( NS_NewTimerWithCallback(getter_AddRefs(mTimer), this, StaticPrefs::dom_payments_response_timeout(), nsITimer::TYPE_ONE_SHOT, - aWindow->EventTargetFor(TaskCategory::Other)); + GetMainThreadSerialEventTarget()); } PaymentResponse::~PaymentResponse() = default; @@ -299,7 +299,7 @@ void PaymentResponse::RespondRetry(const nsAString& aMethodName, NS_NewTimerWithCallback(getter_AddRefs(mTimer), this, StaticPrefs::dom_payments_response_timeout(), nsITimer::TYPE_ONE_SHOT, - GetOwner()->EventTargetFor(TaskCategory::Other)); + GetMainThreadSerialEventTarget()); MOZ_ASSERT(mRetryPromise); mRetryPromise->MaybeResolve(JS::UndefinedHandleValue); mRetryPromise = nullptr; diff --git a/dom/performance/Performance.cpp b/dom/performance/Performance.cpp index 8ad246ca94f2..84ef58a46bfa 100644 --- a/dom/performance/Performance.cpp +++ b/dom/performance/Performance.cpp @@ -998,10 +998,10 @@ void Performance::RunNotificationObserversTask() { mPendingNotificationObserversTask = true; nsCOMPtr task = new NotifyObserversTask(this); nsresult rv; - if (GetOwnerGlobal()) { - rv = GetOwnerGlobal()->Dispatch(TaskCategory::Other, task.forget()); + if (nsIGlobalObject* global = GetOwnerGlobal()) { + rv = global->Dispatch(task.forget()); } else { - rv = NS_DispatchToCurrentThread(task); + rv = NS_DispatchToCurrentThread(task.forget()); } if (NS_WARN_IF(NS_FAILED(rv))) { mPendingNotificationObserversTask = false; diff --git a/dom/promise/Promise.cpp b/dom/promise/Promise.cpp index c44e053172d1..d9266e6dd3f2 100644 --- a/dom/promise/Promise.cpp +++ b/dom/promise/Promise.cpp @@ -732,7 +732,7 @@ void Promise::ReportRejectedPromise(JSContext* aCx, event->SerializeStack(aCx, resolutionSite); } } - winForDispatch->Dispatch(mozilla::TaskCategory::Other, event.forget()); + winForDispatch->Dispatch(event.forget()); } else { NS_DispatchToMainThread(event); } diff --git a/dom/prototype/PrototypeDocumentContentSink.cpp b/dom/prototype/PrototypeDocumentContentSink.cpp index 29195c2d8992..5a5888e1f112 100644 --- a/dom/prototype/PrototypeDocumentContentSink.cpp +++ b/dom/prototype/PrototypeDocumentContentSink.cpp @@ -175,8 +175,7 @@ void PrototypeDocumentContentSink::ContinueInterruptedParsingAsync() { nsCOMPtr ev = NewRunnableMethod( "PrototypeDocumentContentSink::ContinueInterruptedParsingIfEnabled", this, &PrototypeDocumentContentSink::ContinueInterruptedParsingIfEnabled); - - mDocument->Dispatch(mozilla::TaskCategory::Other, ev.forget()); + mDocument->Dispatch(ev.forget()); } //---------------------------------------------------------------------- diff --git a/dom/script/ScriptLoader.cpp b/dom/script/ScriptLoader.cpp index 227b208dc998..fccc4262f7d5 100644 --- a/dom/script/ScriptLoader.cpp +++ b/dom/script/ScriptLoader.cpp @@ -1155,9 +1155,9 @@ bool ScriptLoader::ProcessExternalScript(nsIScriptElement* aElement, NewRunnableMethod("nsIScriptElement::FireErrorEvent", aElement, &nsIScriptElement::FireErrorEvent); if (mDocument) { - mDocument->Dispatch(TaskCategory::Other, runnable.forget()); + mDocument->Dispatch(runnable.forget()); } else { - NS_DispatchToCurrentThread(runnable); + NS_DispatchToCurrentThread(runnable.forget()); } return false; } @@ -3042,7 +3042,7 @@ void ScriptLoader::ProcessPendingRequestsAsync() { NewRunnableMethod("dom::ScriptLoader::ProcessPendingRequests", this, &ScriptLoader::ProcessPendingRequests); if (mDocument) { - mDocument->Dispatch(TaskCategory::Other, task.forget()); + mDocument->Dispatch(task.forget()); } else { NS_DispatchToCurrentThread(task.forget()); } diff --git a/dom/script/ShadowRealmGlobalScope.h b/dom/script/ShadowRealmGlobalScope.h index 994df15e5a75..cf7b2a3bd3fe 100644 --- a/dom/script/ShadowRealmGlobalScope.h +++ b/dom/script/ShadowRealmGlobalScope.h @@ -11,6 +11,7 @@ #include "mozilla/Attributes.h" #include "mozilla/Maybe.h" #include "mozilla/OriginTrials.h" +#include "mozilla/SchedulerGroup.h" #include "mozilla/dom/BindingDeclarations.h" #include "nsContentUtils.h" #include "nsIGlobalObject.h" @@ -29,7 +30,8 @@ namespace mozilla::dom { // Required for providing the wrapper, as this is the global used inside a Gecko // backed ShadowRealm, but also required to power module resolution. -class ShadowRealmGlobalScope : public nsIGlobalObject, public nsWrapperCache { +class ShadowRealmGlobalScope final : public nsIGlobalObject, + public nsWrapperCache { public: NS_DECL_CYCLE_COLLECTING_ISUPPORTS NS_DECL_CYCLE_COLLECTION_WRAPPERCACHE_CLASS(ShadowRealmGlobalScope) @@ -62,6 +64,13 @@ class ShadowRealmGlobalScope : public nsIGlobalObject, public nsWrapperCache { aTarget); } + nsISerialEventTarget* SerialEventTarget() const final { + return mozilla::GetMainThreadSerialEventTarget(); + } + nsresult Dispatch(already_AddRefed&& aRunnable) const final { + return mozilla::SchedulerGroup::Dispatch(std::move(aRunnable)); + } + private: virtual ~ShadowRealmGlobalScope() = default; diff --git a/dom/security/nsCSPContext.cpp b/dom/security/nsCSPContext.cpp index 9bf025141537..e4c8cedeaf31 100644 --- a/dom/security/nsCSPContext.cpp +++ b/dom/security/nsCSPContext.cpp @@ -852,7 +852,7 @@ nsCSPContext::SetRequestContextWithDocument(Document* aDocument) { mQueueUpMessages = !mInnerWindowID; mCallingChannelLoadGroup = aDocument->GetDocumentLoadGroup(); // set the flag on the document for CSP telemetry - mEventTarget = aDocument->EventTargetFor(TaskCategory::Other); + mEventTarget = GetMainThreadSerialEventTarget(); MOZ_ASSERT(mLoadingPrincipal, "need a valid requestPrincipal"); MOZ_ASSERT(mSelfURI, "need mSelfURI to translate 'self' into actual URI"); diff --git a/dom/serviceworkers/ServiceWorkerContainer.cpp b/dom/serviceworkers/ServiceWorkerContainer.cpp index 4e33b9fc753c..b25422dd71fe 100644 --- a/dom/serviceworkers/ServiceWorkerContainer.cpp +++ b/dom/serviceworkers/ServiceWorkerContainer.cpp @@ -747,13 +747,9 @@ nsIGlobalObject* ServiceWorkerContainer::GetGlobalIfValid( void ServiceWorkerContainer::EnqueueReceivedMessageDispatch( RefPtr aMessage) { - if (nsPIDOMWindowInner* const window = GetOwner()) { - if (auto* const target = window->EventTargetFor(TaskCategory::Other)) { - target->Dispatch(NewRunnableMethod>( - "ServiceWorkerContainer::DispatchMessage", this, - &ServiceWorkerContainer::DispatchMessage, std::move(aMessage))); - } - } + NS_DispatchToMainThread(NewRunnableMethod>( + "ServiceWorkerContainer::DispatchMessage", this, + &ServiceWorkerContainer::DispatchMessage, std::move(aMessage))); } template diff --git a/dom/serviceworkers/ServiceWorkerContainerProxy.cpp b/dom/serviceworkers/ServiceWorkerContainerProxy.cpp index 71a853e1ee3a..888731acef9f 100644 --- a/dom/serviceworkers/ServiceWorkerContainerProxy.cpp +++ b/dom/serviceworkers/ServiceWorkerContainerProxy.cpp @@ -64,8 +64,7 @@ RefPtr ServiceWorkerContainerProxy::Register( scopeExit.release(); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return promise; } @@ -92,8 +91,7 @@ ServiceWorkerContainerProxy::GetRegistration(const ClientInfo& aClientInfo, scopeExit.release(); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return promise; } @@ -118,8 +116,7 @@ ServiceWorkerContainerProxy::GetRegistrations(const ClientInfo& aClientInfo) { scopeExit.release(); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return promise; } @@ -144,8 +141,7 @@ RefPtr ServiceWorkerContainerProxy::GetReady( scopeExit.release(); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return promise; } diff --git a/dom/serviceworkers/ServiceWorkerOp.cpp b/dom/serviceworkers/ServiceWorkerOp.cpp index 33bf6cd40b47..e098a39b1e63 100644 --- a/dom/serviceworkers/ServiceWorkerOp.cpp +++ b/dom/serviceworkers/ServiceWorkerOp.cpp @@ -379,9 +379,7 @@ bool ServiceWorkerOp::MaybeStart(RemoteWorkerChild* aOwner, mStarted = true; - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); - + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return true; } diff --git a/dom/serviceworkers/ServiceWorkerProxy.cpp b/dom/serviceworkers/ServiceWorkerProxy.cpp index aa6b77c1fae8..24480dd5c77a 100644 --- a/dom/serviceworkers/ServiceWorkerProxy.cpp +++ b/dom/serviceworkers/ServiceWorkerProxy.cpp @@ -86,8 +86,7 @@ void ServiceWorkerProxy::Init(ServiceWorkerParent* aActor) { // returns. nsCOMPtr r = NewRunnableMethod( "ServiceWorkerProxy::Init", this, &ServiceWorkerProxy::InitOnMainThread); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); } void ServiceWorkerProxy::RevokeActor(ServiceWorkerParent* aActor) { @@ -98,8 +97,7 @@ void ServiceWorkerProxy::RevokeActor(ServiceWorkerParent* aActor) { nsCOMPtr r = NewRunnableMethod( __func__, this, &ServiceWorkerProxy::StopListeningOnMainThread); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); } void ServiceWorkerProxy::PostMessage(RefPtr&& aData, @@ -115,8 +113,7 @@ void ServiceWorkerProxy::PostMessage(RefPtr&& aData, } self->mInfo->PostMessage(std::move(data), aClientInfo, aClientState); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); } } // namespace mozilla::dom diff --git a/dom/serviceworkers/ServiceWorkerRegistration.cpp b/dom/serviceworkers/ServiceWorkerRegistration.cpp index ed5b9d8571c1..e0b870025827 100644 --- a/dom/serviceworkers/ServiceWorkerRegistration.cpp +++ b/dom/serviceworkers/ServiceWorkerRegistration.cpp @@ -548,8 +548,8 @@ void ServiceWorkerRegistration::MaybeDispatchUpdateFoundRunnable() { "ServiceWorkerRegistration::MaybeDispatchUpdateFound", this, &ServiceWorkerRegistration::MaybeDispatchUpdateFound); - Unused << global->EventTargetFor(TaskCategory::Other) - ->Dispatch(r.forget(), NS_DISPATCH_NORMAL); + Unused << global->SerialEventTarget()->Dispatch(r.forget(), + NS_DISPATCH_NORMAL); } void ServiceWorkerRegistration::MaybeDispatchUpdateFound() { diff --git a/dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp b/dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp index cf8c7543ee2b..d4a99e977ebb 100644 --- a/dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp +++ b/dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp @@ -713,9 +713,7 @@ void ServiceWorkerRegistrationInfo::TransitionWaitingToActive() { swm->CheckPendingReadyPromises(); } }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); - + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); UpdateRegistrationState(); NotifyChromeRegistrationListeners(); } diff --git a/dom/serviceworkers/ServiceWorkerRegistrationProxy.cpp b/dom/serviceworkers/ServiceWorkerRegistrationProxy.cpp index 39f845bb56a5..60756b828d79 100644 --- a/dom/serviceworkers/ServiceWorkerRegistrationProxy.cpp +++ b/dom/serviceworkers/ServiceWorkerRegistrationProxy.cpp @@ -186,8 +186,7 @@ void ServiceWorkerRegistrationProxy::Init( nsCOMPtr r = NewRunnableMethod("ServiceWorkerRegistrationProxy::Init", this, &ServiceWorkerRegistrationProxy::InitOnMainThread); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); } void ServiceWorkerRegistrationProxy::RevokeActor( @@ -200,8 +199,7 @@ void ServiceWorkerRegistrationProxy::RevokeActor( nsCOMPtr r = NewRunnableMethod( __func__, this, &ServiceWorkerRegistrationProxy::StopListeningOnMainThread); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); } RefPtr ServiceWorkerRegistrationProxy::Unregister() { @@ -230,8 +228,7 @@ RefPtr ServiceWorkerRegistrationProxy::Unregister() { scopeExit.release(); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return promise; } @@ -386,8 +383,7 @@ RefPtr ServiceWorkerRegistrationProxy::Update( scopeExit.release(); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return promise; } @@ -421,8 +417,7 @@ ServiceWorkerRegistrationProxy::SetNavigationPreloadEnabled( promise->Resolve(true, __func__); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return promise; } @@ -456,8 +451,7 @@ ServiceWorkerRegistrationProxy::SetNavigationPreloadHeader( promise->Resolve(true, __func__); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return promise; } @@ -481,8 +475,7 @@ ServiceWorkerRegistrationProxy::GetNavigationPreloadState() { promise->Resolve(self->mReg->GetNavigationPreloadState(), __func__); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return promise; } diff --git a/dom/serviceworkers/ServiceWorkerShutdownState.cpp b/dom/serviceworkers/ServiceWorkerShutdownState.cpp index 40f2e09f3fae..686f31487703 100644 --- a/dom/serviceworkers/ServiceWorkerShutdownState.cpp +++ b/dom/serviceworkers/ServiceWorkerShutdownState.cpp @@ -112,8 +112,7 @@ void ReportServiceWorkerShutdownProgress(uint32_t aShutdownStateId, if (NS_IsMainThread()) { MOZ_ALWAYS_SUCCEEDS(r->Run()); } else { - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(r.forget())); } } diff --git a/dom/smil/SMILTimedElement.cpp b/dom/smil/SMILTimedElement.cpp index baa640a8b4da..28028b053f2f 100644 --- a/dom/smil/SMILTimedElement.cpp +++ b/dom/smil/SMILTimedElement.cpp @@ -16,7 +16,6 @@ #include "mozilla/SMILTimeContainer.h" #include "mozilla/SMILTimeValue.h" #include "mozilla/SMILTimeValueSpec.h" -#include "mozilla/TaskCategory.h" #include "mozilla/dom/DocumentInlines.h" #include "mozilla/dom/SVGAnimationElement.h" #include "nsAttrValueInlines.h" @@ -2125,7 +2124,7 @@ void SMILTimedElement::FireTimeEventAsync(EventMessage aMsg, int32_t aDetail) { nsCOMPtr event = new AsyncTimeEventRunner(mAnimationElement, aMsg, aDetail); - mAnimationElement->OwnerDoc()->Dispatch(TaskCategory::Other, event.forget()); + mAnimationElement->OwnerDoc()->Dispatch(event.forget()); } const SMILInstanceTime* SMILTimedElement::GetEffectiveBeginInstance() const { diff --git a/dom/storage/Storage.cpp b/dom/storage/Storage.cpp index cf0f4f32d7d6..cfc609969c15 100644 --- a/dom/storage/Storage.cpp +++ b/dom/storage/Storage.cpp @@ -149,7 +149,7 @@ void Storage::NotifyChange(Storage* aStorage, nsIPrincipal* aPrincipal, if (aImmediateDispatch) { Unused << r->Run(); } else { - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget()); + SchedulerGroup::Dispatch(r.forget()); } } diff --git a/dom/storage/StorageActivityService.cpp b/dom/storage/StorageActivityService.cpp index 8652d8265325..a08189cce7c6 100644 --- a/dom/storage/StorageActivityService.cpp +++ b/dom/storage/StorageActivityService.cpp @@ -76,7 +76,7 @@ void StorageActivityService::SendActivity( } }); - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget()); + SchedulerGroup::Dispatch(r.forget()); } /* static */ @@ -101,7 +101,7 @@ void StorageActivityService::SendActivity(const nsACString& aOrigin) { if (NS_IsMainThread()) { Unused << r->Run(); } else { - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget()); + NS_DispatchToMainThread(r.forget()); } } diff --git a/dom/websocket/WebSocket.cpp b/dom/websocket/WebSocket.cpp index da92e9237cba..043f9f33764b 100644 --- a/dom/websocket/WebSocket.cpp +++ b/dom/websocket/WebSocket.cpp @@ -255,9 +255,6 @@ class WebSocketImpl final : public nsIInterfaceRequestor, RefPtr mService; nsCOMPtr mLoadingPrincipal; - // For dispatching runnables to main thread. - nsCOMPtr mMainThreadEventTarget; - RefPtr mImplProxy; private: @@ -1922,10 +1919,6 @@ nsresult WebSocketImpl::InitializeConnection( mChannel->Serial()); } - if (mIsMainThread && doc) { - mMainThreadEventTarget = doc->EventTargetFor(TaskCategory::Other); - } - return NS_OK; } @@ -2797,12 +2790,8 @@ WebSocketImpl::DispatchFromScript(nsIRunnable* aEvent, uint32_t aFlags) { NS_IMETHODIMP WebSocketImpl::Dispatch(already_AddRefed aEvent, uint32_t aFlags) { nsCOMPtr event_ref(aEvent); - // If the target is the main-thread, we should try to dispatch the runnable - // to a labeled event target. if (mIsMainThread) { - return mMainThreadEventTarget - ? mMainThreadEventTarget->Dispatch(event_ref.forget()) - : GetMainThreadSerialEventTarget()->Dispatch(event_ref.forget()); + return GetMainThreadSerialEventTarget()->Dispatch(event_ref.forget()); } MutexAutoLock lock(mMutex); diff --git a/dom/webtransport/api/WebTransport.cpp b/dom/webtransport/api/WebTransport.cpp index fab7dd9dee6a..1919465b1b69 100644 --- a/dom/webtransport/api/WebTransport.cpp +++ b/dom/webtransport/api/WebTransport.cpp @@ -278,11 +278,8 @@ void WebTransport::Init(const GlobalObject& aGlobal, const nsAString& aURL, if (!childEndpoint.Bind(child)) { return; } - } else { - if (!childEndpoint.Bind(child, - mGlobal->EventTargetFor(TaskCategory::Other))) { - return; - } + } else if (!childEndpoint.Bind(child, mGlobal->SerialEventTarget())) { + return; } mState = WebTransportState::CONNECTING; diff --git a/dom/workers/WorkerPrivate.cpp b/dom/workers/WorkerPrivate.cpp index f7a8cec1ef69..c3e81d5f9f1b 100644 --- a/dom/workers/WorkerPrivate.cpp +++ b/dom/workers/WorkerPrivate.cpp @@ -5128,8 +5128,7 @@ int32_t WorkerPrivate::SetTimeout(JSContext* aCx, TimeoutHandler* aHandler, if (insertedInfo == data->mTimeouts.Elements() && !data->mRunningExpiredTimeouts) { if (!data->mTimer) { - data->mTimer = - NS_NewTimer(GlobalScope()->EventTargetFor(TaskCategory::Timer)); + data->mTimer = NS_NewTimer(GlobalScope()->SerialEventTarget()); if (!data->mTimer) { aRv.Throw(NS_ERROR_UNEXPECTED); return 0; diff --git a/dom/workers/WorkerScope.cpp b/dom/workers/WorkerScope.cpp index 73bfc7b8f40c..082252ef99e3 100644 --- a/dom/workers/WorkerScope.cpp +++ b/dom/workers/WorkerScope.cpp @@ -36,7 +36,6 @@ #include "mozilla/Result.h" #include "mozilla/StaticAnalysisFunctions.h" #include "mozilla/StorageAccess.h" -#include "mozilla/TaskCategory.h" #include "mozilla/UniquePtr.h" #include "mozilla/Unused.h" #include "mozilla/dom/AutoEntryScript.h" @@ -338,13 +337,12 @@ void WorkerGlobalScopeBase::Control( } nsresult WorkerGlobalScopeBase::Dispatch( - TaskCategory aCategory, already_AddRefed&& aRunnable) { - return EventTargetFor(aCategory)->Dispatch(std::move(aRunnable), - NS_DISPATCH_NORMAL); + already_AddRefed&& aRunnable) const { + return SerialEventTarget()->Dispatch(std::move(aRunnable), + NS_DISPATCH_NORMAL); } -nsISerialEventTarget* WorkerGlobalScopeBase::EventTargetFor( - TaskCategory) const { +nsISerialEventTarget* WorkerGlobalScopeBase::SerialEventTarget() const { AssertIsOnWorkerThread(); return mSerialEventTarget; } diff --git a/dom/workers/WorkerScope.h b/dom/workers/WorkerScope.h index 6d4ea76ef1fc..7e00f9b59b93 100644 --- a/dom/workers/WorkerScope.h +++ b/dom/workers/WorkerScope.h @@ -133,14 +133,8 @@ class WorkerGlobalScopeBase : public DOMEventTargetHelper, virtual void Control(const ServiceWorkerDescriptor& aServiceWorker); // DispatcherTrait implementation - nsresult Dispatch(TaskCategory aCategory, - already_AddRefed&& aRunnable) final; - - nsISerialEventTarget* EventTargetFor(TaskCategory) const final; - - AbstractThread* AbstractMainThreadFor(TaskCategory) final { - MOZ_CRASH("AbstractMainThreadFor not supported for workers."); - } + nsresult Dispatch(already_AddRefed&& aRunnable) const final; + nsISerialEventTarget* SerialEventTarget() const final; MOZ_CAN_RUN_SCRIPT void ReportError(JSContext* aCx, JS::Handle aError, diff --git a/dom/workers/remoteworkers/RemoteWorkerChild.cpp b/dom/workers/remoteworkers/RemoteWorkerChild.cpp index fb5dd8c8a826..2801a62b8c08 100644 --- a/dom/workers/remoteworkers/RemoteWorkerChild.cpp +++ b/dom/workers/remoteworkers/RemoteWorkerChild.cpp @@ -179,8 +179,7 @@ void RemoteWorkerChild::ActorDestroy(ActorDestroyReason) { RefPtr runnable = NewRunnableMethod("RequestWorkerCancellation", this, &RemoteWorkerChild::RequestWorkerCancellation); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, runnable.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(runnable.forget())); } } @@ -202,8 +201,7 @@ void RemoteWorkerChild::ExecWorker(const RemoteWorkerData& aData) { Unused << NS_WARN_IF(NS_FAILED(rv)); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); } nsresult RemoteWorkerChild::ExecWorkerOnMainThread(RemoteWorkerData&& aData) { @@ -445,8 +443,7 @@ void RemoteWorkerChild::InitializeOnWorker() { nsCOMPtr r = NewRunnableMethod("TransitionStateToRunning", this, &RemoteWorkerChild::TransitionStateToRunning); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); } RefPtr RemoteWorkerChild::GetTerminationPromise() { @@ -837,8 +834,7 @@ class RemoteWorkerChild::SharedWorkerOp : public RemoteWorkerChild::Op { self->StartOnMainThread(owner); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); #ifdef DEBUG mStarted = true; diff --git a/dom/workers/remoteworkers/RemoteWorkerManager.cpp b/dom/workers/remoteworkers/RemoteWorkerManager.cpp index af3e3a69a6b6..fefa91d3849e 100644 --- a/dom/workers/remoteworkers/RemoteWorkerManager.cpp +++ b/dom/workers/remoteworkers/RemoteWorkerManager.cpp @@ -358,8 +358,7 @@ void RemoteWorkerManager::LaunchInternal( } }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); } RefPtr workerActor = MakeAndAddRef(); @@ -621,7 +620,7 @@ void RemoteWorkerManager::LaunchNewContentProcess( }); }); - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget()); + SchedulerGroup::Dispatch(r.forget()); } } // namespace dom diff --git a/dom/workers/remoteworkers/RemoteWorkerParent.cpp b/dom/workers/remoteworkers/RemoteWorkerParent.cpp index ee6c8b436ebf..1a9613b7993a 100644 --- a/dom/workers/remoteworkers/RemoteWorkerParent.cpp +++ b/dom/workers/remoteworkers/RemoteWorkerParent.cpp @@ -89,8 +89,7 @@ void RemoteWorkerParent::ActorDestroy(IProtocol::ActorDestroyReason) { if (parent) { RefPtr r = new UnregisterActorRunnable(parent.forget()); - - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget()); + SchedulerGroup::Dispatch(r.forget()); } if (mController) { diff --git a/dom/workers/remoteworkers/RemoteWorkerService.cpp b/dom/workers/remoteworkers/RemoteWorkerService.cpp index b62c551c22ec..5a33160c04f3 100644 --- a/dom/workers/remoteworkers/RemoteWorkerService.cpp +++ b/dom/workers/remoteworkers/RemoteWorkerService.cpp @@ -108,8 +108,7 @@ RemoteWorkerServiceKeepAlive::~RemoteWorkerServiceKeepAlive() { NS_NewRunnableFunction(__func__, [blocker = std::move(mBlocker)] { blocker->RemoteWorkersAllGoneAllowShutdown(); }); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); } /* static */ diff --git a/dom/workers/sharedworkers/SharedWorkerService.cpp b/dom/workers/sharedworkers/SharedWorkerService.cpp index cbec8671869e..0a076cb4e663 100644 --- a/dom/workers/sharedworkers/SharedWorkerService.cpp +++ b/dom/workers/sharedworkers/SharedWorkerService.cpp @@ -125,14 +125,12 @@ already_AddRefed SharedWorkerService::GetOrCreate() { if (!sSharedWorkerService) { sSharedWorkerService = new SharedWorkerService(); // ClearOnShutdown can only be called on main thread - nsresult rv = SchedulerGroup::Dispatch( - TaskCategory::Other, - NS_NewRunnableFunction("RegisterSharedWorkerServiceClearOnShutdown", - []() { - StaticMutexAutoLock lock(sSharedWorkerMutex); - MOZ_ASSERT(sSharedWorkerService); - ClearOnShutdown(&sSharedWorkerService); - })); + nsresult rv = SchedulerGroup::Dispatch(NS_NewRunnableFunction( + "RegisterSharedWorkerServiceClearOnShutdown", []() { + StaticMutexAutoLock lock(sSharedWorkerMutex); + MOZ_ASSERT(sSharedWorkerService); + ClearOnShutdown(&sSharedWorkerService); + })); Unused << NS_WARN_IF(NS_FAILED(rv)); } @@ -158,7 +156,7 @@ void SharedWorkerService::GetOrCreateWorkerManager( new GetOrCreateWorkerManagerRunnable(this, aActor, aData, aWindowID, aPortIdentifier); - nsresult rv = SchedulerGroup::Dispatch(TaskCategory::Other, r.forget()); + nsresult rv = SchedulerGroup::Dispatch(r.forget()); Unused << NS_WARN_IF(NS_FAILED(rv)); } diff --git a/dom/worklet/WorkletGlobalScope.cpp b/dom/worklet/WorkletGlobalScope.cpp index d976097dcc0f..4437db398e25 100644 --- a/dom/worklet/WorkletGlobalScope.cpp +++ b/dom/worklet/WorkletGlobalScope.cpp @@ -5,6 +5,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "WorkletGlobalScope.h" +#include "mozilla/SchedulerGroup.h" #include "mozilla/dom/WorkletGlobalScopeBinding.h" #include "mozilla/dom/WorkletImpl.h" #include "mozilla/dom/WorkletThread.h" @@ -13,6 +14,7 @@ #include "js/RealmOptions.h" #include "nsContentUtils.h" #include "nsJSUtils.h" +#include "nsThreadUtils.h" #include "nsRFPService.h" using JS::loader::ModuleLoaderBase; @@ -54,6 +56,17 @@ JSObject* WorkletGlobalScope::WrapObject(JSContext* aCx, return nullptr; } +nsISerialEventTarget* WorkletGlobalScope::SerialEventTarget() const { + WorkletThread::AssertIsOnWorkletThread(); + return NS_GetCurrentThread(); +} + +nsresult WorkletGlobalScope::Dispatch( + already_AddRefed&& aRunnable) const { + WorkletThread::AssertIsOnWorkletThread(); + return SerialEventTarget()->Dispatch(std::move(aRunnable)); +} + already_AddRefed WorkletGlobalScope::GetConsole(JSContext* aCx, ErrorResult& aRv) { if (!mConsole) { diff --git a/dom/worklet/WorkletGlobalScope.h b/dom/worklet/WorkletGlobalScope.h index f23aa080f087..7cb86f12d4a8 100644 --- a/dom/worklet/WorkletGlobalScope.h +++ b/dom/worklet/WorkletGlobalScope.h @@ -54,9 +54,7 @@ class WorkletGlobalScope : public nsIGlobalObject, public nsWrapperCache { nsIGlobalObject* GetParentObject() const { return nullptr; } - virtual JSObject* WrapObject(JSContext* aCx, - JS::Handle aGivenProto) override; - + JSObject* WrapObject(JSContext* aCx, JS::Handle aGivenProto) final; virtual bool WrapGlobalObject(JSContext* aCx, JS::MutableHandle aReflector) = 0; @@ -65,6 +63,9 @@ class WorkletGlobalScope : public nsIGlobalObject, public nsWrapperCache { return GetWrapperPreserveColor(); } + nsISerialEventTarget* SerialEventTarget() const final; + nsresult Dispatch(already_AddRefed&&) const final; + already_AddRefed GetConsole(JSContext* aCx, ErrorResult& aRv); WorkletImpl* Impl() const { return mImpl.get(); } diff --git a/dom/xhr/XMLHttpRequestMainThread.cpp b/dom/xhr/XMLHttpRequestMainThread.cpp index 807532e2208f..1b85234e4e44 100644 --- a/dom/xhr/XMLHttpRequestMainThread.cpp +++ b/dom/xhr/XMLHttpRequestMainThread.cpp @@ -3289,22 +3289,17 @@ void XMLHttpRequestMainThread::SetTimeout(uint32_t aTimeout, ErrorResult& aRv) { } nsIEventTarget* XMLHttpRequestMainThread::GetTimerEventTarget() { - if (nsCOMPtr global = GetOwnerGlobal()) { - return global->EventTargetFor(TaskCategory::Other); + if (nsIGlobalObject* global = GetOwnerGlobal()) { + return global->SerialEventTarget(); } return nullptr; } nsresult XMLHttpRequestMainThread::DispatchToMainThread( already_AddRefed aRunnable) { - if (nsCOMPtr global = GetOwnerGlobal()) { - nsCOMPtr target = - global->EventTargetFor(TaskCategory::Other); - MOZ_ASSERT(target); - - return target->Dispatch(std::move(aRunnable), NS_DISPATCH_NORMAL); + if (nsIGlobalObject* global = GetOwnerGlobal()) { + return global->Dispatch(std::move(aRunnable)); } - return NS_DispatchToMainThread(std::move(aRunnable)); } @@ -3861,8 +3856,8 @@ void XMLHttpRequestMainThread::MaybeCreateBlobStorage() { : MutableBlobStorage::eOnlyInMemory; nsCOMPtr eventTarget; - if (nsCOMPtr global = GetOwnerGlobal()) { - eventTarget = global->EventTargetFor(TaskCategory::Other); + if (nsIGlobalObject* global = GetOwnerGlobal()) { + eventTarget = global->SerialEventTarget(); } mBlobStorage = new MutableBlobStorage(storageType, eventTarget); diff --git a/dom/xml/nsXMLContentSink.cpp b/dom/xml/nsXMLContentSink.cpp index 65ecd6483cee..4a3465749dcf 100644 --- a/dom/xml/nsXMLContentSink.cpp +++ b/dom/xml/nsXMLContentSink.cpp @@ -1073,8 +1073,7 @@ nsresult nsXMLContentSink::HandleEndElement(const char16_t* aName, if (content->IsSVGElement(nsGkAtoms::svg)) { FlushTags(); nsCOMPtr event = new nsHtml5SVGLoadDispatcher(content); - if (NS_FAILED(content->OwnerDoc()->Dispatch(TaskCategory::Other, - event.forget()))) { + if (NS_FAILED(content->OwnerDoc()->Dispatch(event.forget()))) { NS_WARNING("failed to dispatch svg load dispatcher"); } } @@ -1514,8 +1513,7 @@ void nsXMLContentSink::ContinueInterruptedParsingAsync() { nsCOMPtr ev = NewRunnableMethod( "nsXMLContentSink::ContinueInterruptedParsingIfEnabled", this, &nsXMLContentSink::ContinueInterruptedParsingIfEnabled); - - mDocument->Dispatch(mozilla::TaskCategory::Other, ev.forget()); + mDocument->Dispatch(ev.forget()); } nsIParser* nsXMLContentSink::GetParser() { diff --git a/dom/xul/XULButtonElement.cpp b/dom/xul/XULButtonElement.cpp index 2fc0690945b7..fa9ee2862808 100644 --- a/dom/xul/XULButtonElement.cpp +++ b/dom/xul/XULButtonElement.cpp @@ -188,17 +188,15 @@ void XULButtonElement::OpenMenuPopup(bool aSelectFirstItem) { } // Open the menu asynchronously. - OwnerDoc()->Dispatch( - TaskCategory::Other, - NS_NewRunnableFunction( - "AsyncOpenMenu", [self = RefPtr{this}, aSelectFirstItem] { - if (self->GetMenuParent() && !self->IsMenuActive()) { - return; - } - if (nsXULPopupManager* pm = nsXULPopupManager::GetInstance()) { - pm->ShowMenu(self, aSelectFirstItem); - } - })); + OwnerDoc()->Dispatch(NS_NewRunnableFunction( + "AsyncOpenMenu", [self = RefPtr{this}, aSelectFirstItem] { + if (self->GetMenuParent() && !self->IsMenuActive()) { + return; + } + if (nsXULPopupManager* pm = nsXULPopupManager::GetInstance()) { + pm->ShowMenu(self, aSelectFirstItem); + } + })); } void XULButtonElement::CloseMenuPopup(bool aDeselectMenu) { @@ -316,8 +314,7 @@ void XULButtonElement::StartBlinking() { "XULButtonElement::ContinueBlinking"); }, this, kBlinkDelay, nsITimer::TYPE_ONE_SHOT, - "XULButtonElement::StartBlinking", - OwnerDoc()->EventTargetFor(TaskCategory::Other)); + "XULButtonElement::StartBlinking", GetMainThreadSerialEventTarget()); } void XULButtonElement::UnbindFromTree(bool aNullParent) { @@ -528,8 +525,7 @@ void XULButtonElement::PostHandleEventForMenus( self->OpenMenuPopup(false); }, this, MenuOpenCloseDelay(), nsITimer::TYPE_ONE_SHOT, - "XULButtonElement::OpenMenu", - OwnerDoc()->EventTargetFor(TaskCategory::Other)); + "XULButtonElement::OpenMenu", GetMainThreadSerialEventTarget()); } } diff --git a/dom/xul/XULMenuParentElement.cpp b/dom/xul/XULMenuParentElement.cpp index f2e4d1e5721f..c45718702579 100644 --- a/dom/xul/XULMenuParentElement.cpp +++ b/dom/xul/XULMenuParentElement.cpp @@ -89,7 +89,7 @@ static void ActivateOrDeactivate(XULButtonElement& aButton, bool aActivate) { } nsCOMPtr event = new MenuActivateEvent(&aButton, aActivate); - aButton.OwnerDoc()->Dispatch(TaskCategory::Other, event.forget()); + aButton.OwnerDoc()->Dispatch(event.forget()); } XULButtonElement* XULMenuParentElement::GetContainingMenu() const { diff --git a/editor/spellchecker/EditorSpellCheck.cpp b/editor/spellchecker/EditorSpellCheck.cpp index 35b4da06cf37..67c8ff4d2044 100644 --- a/editor/spellchecker/EditorSpellCheck.cpp +++ b/editor/spellchecker/EditorSpellCheck.cpp @@ -432,7 +432,7 @@ EditorSpellCheck::InitSpellChecker(nsIEditor* aEditor, // discard the failure. Do it asynchronously so that the caller is always // guaranteed async behavior. RefPtr caller = new CallbackCaller(aCallback); - rv = doc->Dispatch(TaskCategory::Other, caller.forget()); + rv = doc->Dispatch(caller.forget()); NS_ENSURE_SUCCESS(rv, rv); } diff --git a/gfx/ipc/VsyncIOThreadHolder.cpp b/gfx/ipc/VsyncIOThreadHolder.cpp index 51e25cc85356..b5b04dcf1858 100644 --- a/gfx/ipc/VsyncIOThreadHolder.cpp +++ b/gfx/ipc/VsyncIOThreadHolder.cpp @@ -25,10 +25,8 @@ VsyncIOThreadHolder::~VsyncIOThreadHolder() { if (NS_IsMainThread()) { mThread->AsyncShutdown(); } else { - SchedulerGroup::Dispatch( - TaskCategory::Other, - NewRunnableMethod("nsIThread::AsyncShutdown", mThread, - &nsIThread::AsyncShutdown)); + SchedulerGroup::Dispatch(NewRunnableMethod( + "nsIThread::AsyncShutdown", mThread, &nsIThread::AsyncShutdown)); } } diff --git a/gfx/layers/ipc/SharedSurfacesChild.cpp b/gfx/layers/ipc/SharedSurfacesChild.cpp index 2ea97b2f7ac2..d6404b8e9a68 100644 --- a/gfx/layers/ipc/SharedSurfacesChild.cpp +++ b/gfx/layers/ipc/SharedSurfacesChild.cpp @@ -82,7 +82,7 @@ void SharedSurfacesChild::SharedUserData::Destroy(void* aClosure) { RefPtr data = dont_AddRef(static_cast(aClosure)); if (data->mShared || !data->mKeys.IsEmpty()) { - SchedulerGroup::Dispatch(TaskCategory::Other, data.forget()); + SchedulerGroup::Dispatch(data.forget()); } } @@ -277,8 +277,7 @@ void SharedSurfacesChild::Share(SourceSurfaceSharedData* aSurface) { RefPtr mSurface; }; - SchedulerGroup::Dispatch(TaskCategory::Other, - MakeAndAddRef(aSurface)); + SchedulerGroup::Dispatch(MakeAndAddRef(aSurface)); return; } @@ -422,7 +421,7 @@ void SharedSurfacesAnimation::Destroy() { nsCOMPtr task = NewRunnableMethod("SharedSurfacesAnimation::Destroy", this, &SharedSurfacesAnimation::Destroy); - SchedulerGroup::Dispatch(TaskCategory::Other, task.forget()); + NS_DispatchToMainThread(task.forget()); return; } diff --git a/gfx/src/gfxCrashReporterUtils.cpp b/gfx/src/gfxCrashReporterUtils.cpp index dcc97c2f08bd..d4b19f7b0554 100644 --- a/gfx/src/gfxCrashReporterUtils.cpp +++ b/gfx/src/gfxCrashReporterUtils.cpp @@ -6,7 +6,6 @@ #include "gfxCrashReporterUtils.h" #include // for strcmp -#include "mozilla/Assertions.h" // for MOZ_ASSERT_HELPER2 #include "mozilla/SchedulerGroup.h" // for SchedulerGroup #include "mozilla/Services.h" // for GetObserverService #include "mozilla/StaticMutex.h" @@ -16,13 +15,13 @@ #include "nsCOMPtr.h" // for nsCOMPtr #include "nsError.h" // for NS_OK, NS_FAILED, nsresult #include "nsExceptionHandler.h" // for AppendAppNotesToCrashReport -#include "nsID.h" #include "nsIObserver.h" // for nsIObserver, etc #include "nsIObserverService.h" // for nsIObserverService #include "nsIRunnable.h" // for nsIRunnable #include "nsISupports.h" -#include "nsTArray.h" // for nsTArray -#include "nscore.h" // for NS_IMETHOD, NS_IMETHODIMP, etc +#include "nsThreadUtils.h" // for Runnable +#include "nsTArray.h" // for nsTArray +#include "nscore.h" // for NS_IMETHOD, NS_IMETHODIMP, etc namespace mozilla { @@ -99,7 +98,7 @@ void ScopedGfxFeatureReporter::WriteAppNote(char statusChar, if (!gFeaturesAlreadyReported) { gFeaturesAlreadyReported = new nsTArray; nsCOMPtr r = new RegisterObserverRunnable(); - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget()); + SchedulerGroup::Dispatch(r.forget()); } nsAutoCString featureString; @@ -120,7 +119,7 @@ void ScopedGfxFeatureReporter::AppNote(const nsACString& aMessage) { CrashReporter::AppendAppNotesToCrashReport(aMessage); } else { nsCOMPtr r = new AppendAppNotesRunnable(aMessage); - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget()); + NS_DispatchToMainThread(r.forget()); } } diff --git a/gfx/src/nsThebesFontEnumerator.cpp b/gfx/src/nsThebesFontEnumerator.cpp index 9e3b3e29897d..baf8c50142c2 100644 --- a/gfx/src/nsThebesFontEnumerator.cpp +++ b/gfx/src/nsThebesFontEnumerator.cpp @@ -174,8 +174,7 @@ nsThebesFontEnumerator::EnumerateFontsAsync( generic.SetIsVoid(true); } - nsCOMPtr target = - global->EventTargetFor(mozilla::TaskCategory::Other); + nsCOMPtr target = global->SerialEventTarget(); nsCOMPtr runnable = new EnumerateFontsTask( langGroupAtom, generic, std::move(enumerateFontsPromise), target); thread->Dispatch(runnable.forget(), NS_DISPATCH_NORMAL); diff --git a/image/IProgressObserver.h b/image/IProgressObserver.h index c4b16f70dee1..fea5c3f148c3 100644 --- a/image/IProgressObserver.h +++ b/image/IProgressObserver.h @@ -43,10 +43,6 @@ class IProgressObserver : public SupportsWeakPtr { virtual void MarkPendingNotify() = 0; virtual void ClearPendingNotify() = 0; - virtual already_AddRefed GetEventTarget() const { - return nullptr; - } - protected: virtual ~IProgressObserver() = default; }; diff --git a/image/ImageFactory.cpp b/image/ImageFactory.cpp index 27541634dc6e..fbe2cac41bbc 100644 --- a/image/ImageFactory.cpp +++ b/image/ImageFactory.cpp @@ -84,7 +84,7 @@ static void NotifyImageLoading(nsIURI* aURI) { nsCOMPtr uri(aURI); nsCOMPtr ev = NS_NewRunnableFunction( "NotifyImageLoading", [uri]() -> void { NotifyImageLoading(uri); }); - SchedulerGroup::Dispatch(TaskCategory::Other, ev.forget()); + NS_DispatchToMainThread(ev.forget()); return; } diff --git a/image/ProgressTracker.cpp b/image/ProgressTracker.cpp index 2d8720fa7604..7cc378323105 100644 --- a/image/ProgressTracker.cpp +++ b/image/ProgressTracker.cpp @@ -15,6 +15,7 @@ #include "mozilla/AppShutdown.h" #include "mozilla/Assertions.h" +#include "mozilla/SchedulerGroup.h" #include "mozilla/Services.h" using mozilla::WeakPtr; @@ -67,9 +68,6 @@ static void CheckProgressConsistency(Progress aOldProgress, ProgressTracker::ProgressTracker() : mMutex("ProgressTracker::mMutex"), mImage(nullptr), - mEventTarget(WrapNotNull( - nsCOMPtr(GetMainThreadSerialEventTarget()))), - mObserversWithTargets(0), mObservers(new ObserverTable), mProgress(NoProgress), mIsMultipart(false) {} @@ -203,7 +201,7 @@ void ProgressTracker::Notify(IProgressObserver* aObserver) { // Avoid dispatch if we are late in shutdown. RefPtr ev = new AsyncNotifyRunnable(this, aObserver); mRunnable = ProgressTracker::RenderBlockingRunnable::Create(ev.forget()); - mEventTarget->Dispatch(mRunnable, NS_DISPATCH_NORMAL); + SchedulerGroup::Dispatch(do_AddRef(mRunnable)); } } @@ -259,7 +257,7 @@ void ProgressTracker::NotifyCurrentState(IProgressObserver* aObserver) { if (!AppShutdown::IsInOrBeyond(ShutdownPhase::XPCOMShutdownThreads)) { nsCOMPtr ev = new AsyncNotifyCurrentStateRunnable(this, aObserver); - mEventTarget->Dispatch(ev.forget(), NS_DISPATCH_NORMAL); + SchedulerGroup::Dispatch(ev.forget()); } } @@ -411,33 +409,12 @@ void ProgressTracker::EmulateRequestFinished(IProgressObserver* aObserver) { } already_AddRefed ProgressTracker::GetEventTarget() const { - MutexAutoLock lock(mMutex); - nsCOMPtr target = mEventTarget; - return target.forget(); + return do_AddRef(GetMainThreadSerialEventTarget()); } void ProgressTracker::AddObserver(IProgressObserver* aObserver) { MOZ_ASSERT(NS_IsMainThread()); RefPtr observer = aObserver; - - nsCOMPtr target = observer->GetEventTarget(); - if (target) { - if (mObserversWithTargets == 0) { - // On the first observer with a target (i.e. listener), always accept its - // event target; this may be for a specific DocGroup, or it may be the - // unlabelled main thread target. - MutexAutoLock lock(mMutex); - mEventTarget = WrapNotNull(target); - } else if (mEventTarget.get() != target.get()) { - // If a subsequent observer comes in with a different target, we need to - // switch to use the unlabelled main thread target, if we haven't already. - MutexAutoLock lock(mMutex); - nsCOMPtr mainTarget(do_GetMainThread()); - mEventTarget = WrapNotNull(mainTarget); - } - ++mObserversWithTargets; - } - mObservers.Write([=](ObserverTable* aTable) { MOZ_ASSERT(!aTable->Contains(observer), "Adding duplicate entry for image observer"); @@ -445,8 +422,6 @@ void ProgressTracker::AddObserver(IProgressObserver* aObserver) { WeakPtr weakPtr = observer.get(); aTable->InsertOrUpdate(observer, weakPtr); }); - - MOZ_ASSERT(mObserversWithTargets <= ObserverCount()); } bool ProgressTracker::RemoveObserver(IProgressObserver* aObserver) { @@ -457,31 +432,6 @@ bool ProgressTracker::RemoveObserver(IProgressObserver* aObserver) { bool removed = mObservers.Write( [observer](ObserverTable* aTable) { return aTable->Remove(observer); }); - // Sometimes once an image is decoded, and all of its observers removed, a new - // document may request the same image. Thus we need to clear our event target - // state when the last observer is removed, so that we select the most - // appropriate event target when a new observer is added. Since the event - // target may have changed (e.g. due to the scheduler group going away before - // we were removed), so we should be cautious comparing this target against - // anything at this stage. - if (removed) { - nsCOMPtr target = observer->GetEventTarget(); - if (target) { - MOZ_ASSERT(mObserversWithTargets > 0); - --mObserversWithTargets; - - // If we're shutting down there's no need to update event targets. - if ((mObserversWithTargets == 0) && - !AppShutdown::IsInOrBeyond(ShutdownPhase::XPCOMShutdownThreads)) { - MutexAutoLock lock(mMutex); - nsCOMPtr target(do_GetMainThread()); - mEventTarget = WrapNotNull(target); - } - } - - MOZ_ASSERT(mObserversWithTargets <= ObserverCount()); - } - // Observers can get confused if they don't get all the proper teardown // notifications. Part ways on good terms. if (removed && !aObserver->NotificationsDeferred()) { diff --git a/image/ProgressTracker.h b/image/ProgressTracker.h index 568fb5e28c26..ffa66cd3bf71 100644 --- a/image/ProgressTracker.h +++ b/image/ProgressTracker.h @@ -232,22 +232,6 @@ class ProgressTracker : public mozilla::SupportsWeakPtr { // scope. Image* mImage; - // mEventTarget is the current, best effort event target to dispatch - // notifications to from the decoder threads. It will change as observers are - // added and removed (see mObserversWithTargets). - NotNull> mEventTarget; - - // How many observers have been added that have an explicit event target. - // When the first observer is added with an explicit event target, we will - // default to that as long as all observers use the same target. If a new - // observer is added which has a different event target, we will switch to - // using the unlabeled main thread event target which is safe for all - // observers. If all observers with explicit event targets are removed, we - // will revert back to the initial event target (for SystemGroup). An - // observer without an explicit event target does not care what context it - // is dispatched in, and thus does not impact the state. - uint32_t mObserversWithTargets; - // Hashtable of observers attached to the image. Each observer represents a // consumer using the image. Main thread only. CopyOnWrite mObservers; diff --git a/image/decoders/icon/mac/nsIconChannelCocoa.mm b/image/decoders/icon/mac/nsIconChannelCocoa.mm index 61a3cee6d9ee..335e3614084c 100644 --- a/image/decoders/icon/mac/nsIconChannelCocoa.mm +++ b/image/decoders/icon/mac/nsIconChannelCocoa.mm @@ -224,9 +224,7 @@ nsIconChannel::AsyncOpen(nsIStreamListener* aListener) { } // Init our stream pump - nsCOMPtr target = - nsContentUtils::GetEventTargetByLoadInfo(mLoadInfo, - mozilla::TaskCategory::Other); + nsCOMPtr target = GetMainThreadSerialEventTarget(); rv = mPump->Init(inStream, 0, 0, false, target); if (NS_FAILED(rv)) { mCallbacks = nullptr; diff --git a/image/decoders/icon/win/nsIconChannel.cpp b/image/decoders/icon/win/nsIconChannel.cpp index fe76afe9b1a3..6c93dc3bf200 100644 --- a/image/decoders/icon/win/nsIconChannel.cpp +++ b/image/decoders/icon/win/nsIconChannel.cpp @@ -841,17 +841,8 @@ nsresult nsIconChannel::StartAsyncOpen() { [outputStream](nsresult rv) { outputStream->CloseWithStatus(rv); }); } - // Use the main thread for the pumped events unless the load info - // specifies otherwise - nsCOMPtr listenerTarget = - nsContentUtils::GetEventTargetByLoadInfo(mLoadInfo, - mozilla::TaskCategory::Other); - if (!listenerTarget) { - listenerTarget = do_GetMainThread(); - } - rv = mPump->Init(inputStream.get(), 0 /*segmentSize*/, 0 /*segmentCount*/, - false /*closeWhenDone*/, listenerTarget); + false /*closeWhenDone*/, GetMainThreadSerialEventTarget()); NS_ENSURE_SUCCESS(rv, rv); return mPump->AsyncRead(this); diff --git a/image/imgLoader.cpp b/image/imgLoader.cpp index 84b3af3bdae4..992118a6792f 100644 --- a/image/imgLoader.cpp +++ b/image/imgLoader.cpp @@ -1154,8 +1154,7 @@ nsresult imgLoader::CreateNewProxyForRequest( proxyRequest->SetLoadFlags(aLoadFlags); // init adds itself to imgRequest's list of observers - nsresult rv = proxyRequest->Init(aRequest, aLoadGroup, aLoadingDocument, aURI, - aObserver); + nsresult rv = proxyRequest->Init(aRequest, aLoadGroup, aURI, aObserver); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/image/imgRequestProxy.cpp b/image/imgRequestProxy.cpp index 797ae918a9ec..45140edd3eb6 100644 --- a/image/imgRequestProxy.cpp +++ b/image/imgRequestProxy.cpp @@ -116,8 +116,7 @@ imgRequestProxy::imgRequestProxy() mDecodeRequested(false), mPendingNotify(false), mValidating(false), - mHadListener(false), - mHadDispatch(false) { + mHadListener(false) { /* member initializers and constructor code */ LOG_FUNC(gImgLog, "imgRequestProxy::imgRequestProxy"); } @@ -125,22 +124,6 @@ imgRequestProxy::imgRequestProxy() imgRequestProxy::~imgRequestProxy() { /* destructor code */ MOZ_ASSERT(!mListener, "Someone forgot to properly cancel this request!"); - - // If we had a listener, that means we would have issued notifications. With - // bug 1359833, we added support for main thread scheduler groups. Each - // imgRequestProxy may have its own associated listener, document and/or - // scheduler group. Typically most imgRequestProxy belong to the same - // document, or have no listener, which means we will want to execute all main - // thread code in that shared scheduler group. Less frequently, there may be - // multiple imgRequests and they have separate documents, which means that - // when we issue state notifications, some or all need to be dispatched to the - // appropriate scheduler group for each request. This should be rare, so we - // want to monitor the frequency of dispatching in the wild. - if (mHadListener) { - mozilla::Telemetry::Accumulate(mozilla::Telemetry::IMAGE_REQUEST_DISPATCHED, - mHadDispatch); - } - MOZ_RELEASE_ASSERT(!mLockCount, "Someone forgot to unlock on time?"); ClearAnimationConsumers(); @@ -164,7 +147,7 @@ imgRequestProxy::~imgRequestProxy() { } nsresult imgRequestProxy::Init(imgRequest* aOwner, nsILoadGroup* aLoadGroup, - Document* aLoadingDocument, nsIURI* aURI, + nsIURI* aURI, imgINotificationObserver* aObserver) { MOZ_ASSERT(!GetOwner() && !mListener, "imgRequestProxy is already initialized"); @@ -187,7 +170,7 @@ nsresult imgRequestProxy::Init(imgRequest* aOwner, nsILoadGroup* aLoadGroup, mURI = aURI; // Note: AddToOwner won't send all the On* notifications immediately - AddToOwner(aLoadingDocument); + AddToOwner(); return NS_OK; } @@ -229,7 +212,7 @@ nsresult imgRequestProxy::ChangeOwner(imgRequest* aNewOwner) { IncrementAnimationConsumers(); } - AddToOwner(nullptr); + AddToOwner(); return NS_OK; } @@ -260,11 +243,6 @@ void imgRequestProxy::ClearValidating() { } } -already_AddRefed imgRequestProxy::GetEventTarget() const { - nsCOMPtr target(mEventTarget); - return target.forget(); -} - bool imgRequestProxy::HasDecodedPixels() { if (IsValidating()) { return false; @@ -281,47 +259,11 @@ bool imgRequestProxy::HasDecodedPixels() { nsresult imgRequestProxy::DispatchWithTargetIfAvailable( already_AddRefed aEvent) { LOG_FUNC(gImgLog, "imgRequestProxy::DispatchWithTargetIfAvailable"); - - // This method should only be used when it is *expected* that we are - // dispatching an event (e.g. we want to handle an event asynchronously) - // rather we need to (e.g. we are in the wrong scheduler group context). - // As such, we do not set mHadDispatch for telemetry purposes. - if (mEventTarget) { - mEventTarget->Dispatch(CreateRenderBlockingRunnable(std::move(aEvent)), - NS_DISPATCH_NORMAL); - return NS_OK; - } - return NS_DispatchToMainThread( CreateRenderBlockingRunnable(std::move(aEvent))); } -void imgRequestProxy::AddToOwner(Document* aLoadingDocument) { - // An imgRequestProxy can be initialized with neither a listener nor a - // document. The caller could follow up later by cloning the canonical - // imgRequestProxy with the actual listener. This is possible because - // imgLoader::LoadImage does not require a valid listener to be provided. - // - // Without a listener, we don't need to set our scheduler group, because - // we have nothing to signal. However if we were told what document this - // is for, it is likely that future listeners will belong to the same - // scheduler group. - // - // With a listener, we always need to update our scheduler group. A null - // scheduler group is valid with or without a document, but that means - // we will use the most generic event target possible on dispatch. - if (aLoadingDocument) { - RefPtr docGroup = aLoadingDocument->GetDocGroup(); - if (docGroup) { - mEventTarget = docGroup->EventTargetFor(mozilla::TaskCategory::Other); - MOZ_ASSERT(mEventTarget); - } - } - - if (mListener && !mEventTarget) { - mEventTarget = do_GetMainThread(); - } - +void imgRequestProxy::AddToOwner() { imgRequest* owner = GetOwner(); if (!owner) { return; @@ -859,8 +801,7 @@ nsresult imgRequestProxy::PerformClone(imgINotificationObserver* aObserver, // XXXldb That's not true anymore. Stuff from imgLoader adds the // request to the loadgroup. clone->SetLoadFlags(mLoadFlags); - nsresult rv = clone->Init(mBehaviour->GetOwner(), loadGroup, aLoadingDocument, - mURI, aObserver); + nsresult rv = clone->Init(mBehaviour->GetOwner(), loadGroup, mURI, aObserver); if (NS_FAILED(rv)) { return rv; } @@ -1163,7 +1104,7 @@ already_AddRefed imgRequestProxy::GetStaticRequest( RefPtr req = new imgRequestProxyStatic(frozenImage, currentPrincipal, triggeringPrincipal, hadCrossOriginRedirects); - req->Init(nullptr, nullptr, aLoadingDocument, mURI, nullptr); + req->Init(nullptr, nullptr, mURI, nullptr); return req.forget(); } diff --git a/image/imgRequestProxy.h b/image/imgRequestProxy.h index 950c78341ca4..cb4853540d9f 100644 --- a/image/imgRequestProxy.h +++ b/image/imgRequestProxy.h @@ -66,8 +66,7 @@ class imgRequestProxy : public mozilla::PreloaderBase, // Callers to Init or ChangeOwner are required to call NotifyListener after // (although not immediately after) doing so. - nsresult Init(imgRequest* aOwner, nsILoadGroup* aLoadGroup, - Document* aLoadingDocument, nsIURI* aURI, + nsresult Init(imgRequest* aOwner, nsILoadGroup* aLoadGroup, nsIURI* aURI, imgINotificationObserver* aObserver); nsresult ChangeOwner(imgRequest* aNewOwner); // this will change mOwner. @@ -115,8 +114,6 @@ class imgRequestProxy : public mozilla::PreloaderBase, // stylesheets can be shared across documents properly, see bug 1800979. void SetCancelable(bool); - already_AddRefed GetEventTarget() const override; - // Removes all animation consumers that were created with // IncrementAnimationConsumers. This is necessary since we need // to do it before the proxy itself is destroyed. See @@ -197,7 +194,7 @@ class imgRequestProxy : public mozilla::PreloaderBase, private: friend class imgCacheValidator; - void AddToOwner(Document* aLoadingDocument); + void AddToOwner(); void RemoveFromOwner(nsresult aStatus); nsresult DispatchWithTargetIfAvailable(already_AddRefed aEvent); @@ -214,7 +211,6 @@ class imgRequestProxy : public mozilla::PreloaderBase, "they are destroyed") mListener; nsCOMPtr mLoadGroup; - nsCOMPtr mEventTarget; nsLoadFlags mLoadFlags; uint32_t mLockCount; @@ -231,7 +227,6 @@ class imgRequestProxy : public mozilla::PreloaderBase, bool mPendingNotify : 1; bool mValidating : 1; bool mHadListener : 1; - bool mHadDispatch : 1; }; NS_DEFINE_STATIC_IID_ACCESSOR(imgRequestProxy, NS_IMGREQUESTPROXY_CID) diff --git a/ipc/mscom/EnsureMTA.cpp b/ipc/mscom/EnsureMTA.cpp index 0a84eeabf98b..33dfe018d2e1 100644 --- a/ipc/mscom/EnsureMTA.cpp +++ b/ipc/mscom/EnsureMTA.cpp @@ -183,7 +183,6 @@ nsCOMPtr EnsureMTA::GetPersistentMTAThread() { } SchedulerGroup::Dispatch( - TaskCategory::Other, NS_NewRunnableFunction("mscom::EnsureMTA::GetPersistentMTAThread", std::move(setClearOnShutdown))); diff --git a/js/xpconnect/src/BackstagePass.h b/js/xpconnect/src/BackstagePass.h index f29494258c2a..1e6c5531eb08 100644 --- a/js/xpconnect/src/BackstagePass.h +++ b/js/xpconnect/src/BackstagePass.h @@ -9,6 +9,7 @@ #include "js/loader/ModuleLoaderBase.h" #include "mozilla/BasePrincipal.h" +#include "mozilla/SchedulerGroup.h" #include "mozilla/StorageAccess.h" #include "nsISupports.h" #include "nsWeakReference.h" @@ -68,6 +69,13 @@ class BackstagePass final : public nsIGlobalObject, mModuleLoader = aModuleLoader; } + nsISerialEventTarget* SerialEventTarget() const final { + return mozilla::GetMainThreadSerialEventTarget(); + } + nsresult Dispatch(already_AddRefed&& aRunnable) const final { + return mozilla::SchedulerGroup::Dispatch(std::move(aRunnable)); + } + bool ShouldResistFingerprinting(RFPTarget aTarget) const override { // BackstagePass is always the System Principal MOZ_RELEASE_ASSERT(mPrincipal->IsSystemPrincipal()); diff --git a/js/xpconnect/src/SandboxPrivate.h b/js/xpconnect/src/SandboxPrivate.h index bfe2fae1bcc4..a0482c933bbe 100644 --- a/js/xpconnect/src/SandboxPrivate.h +++ b/js/xpconnect/src/SandboxPrivate.h @@ -7,9 +7,10 @@ #ifndef __SANDBOXPRIVATE_H__ #define __SANDBOXPRIVATE_H__ -#include "mozilla/WeakPtr.h" +#include "mozilla/SchedulerGroup.h" #include "mozilla/StaticPrefs_dom.h" #include "mozilla/StorageAccess.h" +#include "mozilla/WeakPtr.h" #include "mozilla/net/CookieJarSettings.h" #include "nsContentUtils.h" #include "nsIGlobalObject.h" @@ -23,11 +24,11 @@ #include "js/Object.h" // JS::GetPrivate, JS::SetPrivate #include "js/RootingAPI.h" -class SandboxPrivate : public nsIGlobalObject, - public nsIScriptObjectPrincipal, - public nsSupportsWeakReference, - public mozilla::SupportsWeakPtr, - public nsWrapperCache { +class SandboxPrivate final : public nsIGlobalObject, + public nsIScriptObjectPrincipal, + public nsSupportsWeakReference, + public mozilla::SupportsWeakPtr, + public nsWrapperCache { public: NS_DECL_CYCLE_COLLECTING_ISUPPORTS NS_DECL_CYCLE_COLLECTION_WRAPPERCACHE_CLASS_AMBIGUOUS(SandboxPrivate, @@ -81,6 +82,13 @@ class SandboxPrivate : public nsIGlobalObject, void ForgetGlobalObject(JSObject* obj) { ClearWrapper(obj); } + nsISerialEventTarget* SerialEventTarget() const final { + return mozilla::GetMainThreadSerialEventTarget(); + } + nsresult Dispatch(already_AddRefed&& aRunnable) const final { + return mozilla::SchedulerGroup::Dispatch(std::move(aRunnable)); + } + virtual JSObject* WrapObject(JSContext* cx, JS::Handle aGivenProto) override { MOZ_CRASH("SandboxPrivate doesn't use DOM bindings!"); diff --git a/layout/base/PresShell.cpp b/layout/base/PresShell.cpp index 1c719cc3c304..1ca085ed1cb3 100644 --- a/layout/base/PresShell.cpp +++ b/layout/base/PresShell.cpp @@ -1870,8 +1870,7 @@ nsresult PresShell::Initialize() { mPaintingSuppressed = false; } else { // Initialize the timer. - mPaintSuppressionTimer->SetTarget( - mDocument->EventTargetFor(TaskCategory::Other)); + mPaintSuppressionTimer->SetTarget(GetMainThreadSerialEventTarget()); InitPaintSuppressionTimer(); if (mHasTriedFastUnsuppress) { // Someone tried to unsuppress painting before Initialize was called so @@ -6247,7 +6246,7 @@ void PresShell::ScheduleApproximateFrameVisibilityUpdateNow() { RefPtr> event = NewRunnableMethod("PresShell::UpdateApproximateFrameVisibility", this, &PresShell::UpdateApproximateFrameVisibility); - nsresult rv = mDocument->Dispatch(TaskCategory::Other, do_AddRef(event)); + nsresult rv = mDocument->Dispatch(do_AddRef(event)); if (NS_SUCCEEDED(rv)) { mUpdateApproximateFrameVisibilityEvent = std::move(event); @@ -9531,7 +9530,7 @@ bool PresShell::ScheduleReflowOffTimer() { nsresult rv = NS_NewTimerWithFuncCallback( getter_AddRefs(mReflowContinueTimer), sReflowContinueCallback, this, 30, nsITimer::TYPE_ONE_SHOT, "sReflowContinueCallback", - mDocument->EventTargetFor(TaskCategory::Other)); + GetMainThreadSerialEventTarget()); return NS_SUCCEEDED(rv); } return true; diff --git a/layout/base/ZoomConstraintsClient.cpp b/layout/base/ZoomConstraintsClient.cpp index 183f3eb22e39..6266f6bf1814 100644 --- a/layout/base/ZoomConstraintsClient.cpp +++ b/layout/base/ZoomConstraintsClient.cpp @@ -167,7 +167,7 @@ ZoomConstraintsClient::Observe(nsISupports* aSubject, const char* aTopic, RefPtr> event = NewRunnableMethod("ZoomConstraintsClient::RefreshZoomConstraints", this, &ZoomConstraintsClient::RefreshZoomConstraints); - mDocument->Dispatch(TaskCategory::Other, event.forget()); + mDocument->Dispatch(event.forget()); } return NS_OK; } diff --git a/layout/base/nsCaret.cpp b/layout/base/nsCaret.cpp index d0573ec5f8f9..de521a0d8264 100644 --- a/layout/base/nsCaret.cpp +++ b/layout/base/nsCaret.cpp @@ -658,14 +658,7 @@ void nsCaret::ResetBlinking() { if (mBlinkTimer) { mBlinkTimer->Cancel(); } else { - nsIEventTarget* target = nullptr; - if (RefPtr presShell = do_QueryReferent(mPresShell)) { - if (nsCOMPtr doc = presShell->GetDocument()) { - target = doc->EventTargetFor(TaskCategory::Other); - } - } - - mBlinkTimer = NS_NewTimer(target); + mBlinkTimer = NS_NewTimer(GetMainThreadSerialEventTarget()); if (!mBlinkTimer) { return; } diff --git a/layout/base/nsDocumentViewer.cpp b/layout/base/nsDocumentViewer.cpp index 3bd1816faea8..1ae17010a699 100644 --- a/layout/base/nsDocumentViewer.cpp +++ b/layout/base/nsDocumentViewer.cpp @@ -2154,7 +2154,7 @@ nsDocumentViewer::Show() { // from the event loop after we actually draw the page. RefPtr event = new nsDocumentShownDispatcher(document); - document->Dispatch(TaskCategory::Other, event.forget()); + document->Dispatch(event.forget()); return NS_OK; } diff --git a/layout/base/nsPresContext.cpp b/layout/base/nsPresContext.cpp index 1e25441066d1..846182cfcf03 100644 --- a/layout/base/nsPresContext.cpp +++ b/layout/base/nsPresContext.cpp @@ -1851,7 +1851,7 @@ void nsPresContext::UIResolutionChanged() { nsCOMPtr ev = NewRunnableMethod("nsPresContext::UIResolutionChangedInternal", this, &nsPresContext::UIResolutionChangedInternal); - nsresult rv = Document()->Dispatch(TaskCategory::Other, ev.forget()); + nsresult rv = Document()->Dispatch(ev.forget()); if (NS_SUCCEEDED(rv)) { mPendingUIResolutionChanged = true; } @@ -2547,7 +2547,7 @@ already_AddRefed nsPresContext::CreateTimer( nsCOMPtr timer; NS_NewTimerWithFuncCallback(getter_AddRefs(timer), aCallback, this, aDelay, nsITimer::TYPE_ONE_SHOT, aName, - Document()->EventTargetFor(TaskCategory::Other)); + GetMainThreadSerialEventTarget()); return timer.forget(); } @@ -3065,8 +3065,7 @@ nsRootPresContext::nsRootPresContext(dom::Document* aDocument, void nsRootPresContext::AddWillPaintObserver(nsIRunnable* aRunnable) { if (!mWillPaintFallbackEvent.IsPending()) { mWillPaintFallbackEvent = new RunWillPaintObservers(this); - Document()->Dispatch(TaskCategory::Other, - do_AddRef(mWillPaintFallbackEvent)); + Document()->Dispatch(do_AddRef(mWillPaintFallbackEvent)); } mWillPaintObservers.AppendElement(aRunnable); } diff --git a/layout/base/nsRefreshDriver.cpp b/layout/base/nsRefreshDriver.cpp index 6758cf750a64..f7c67aa790ab 100644 --- a/layout/base/nsRefreshDriver.cpp +++ b/layout/base/nsRefreshDriver.cpp @@ -2975,7 +2975,7 @@ void nsRefreshDriver::Thaw() { "nsRefreshDriver::DoRefresh", this, &nsRefreshDriver::DoRefresh); nsPresContext* pc = GetPresContext(); if (pc) { - pc->Document()->Dispatch(TaskCategory::Other, event.forget()); + pc->Document()->Dispatch(event.forget()); EnsureTimerStarted(); } else { NS_ERROR("Thawing while document is being destroyed"); diff --git a/layout/generic/nsGfxScrollFrame.cpp b/layout/generic/nsGfxScrollFrame.cpp index 15e526fc98f6..aee3f4280e7a 100644 --- a/layout/generic/nsGfxScrollFrame.cpp +++ b/layout/generic/nsGfxScrollFrame.cpp @@ -2899,8 +2899,7 @@ void nsHTMLScrollFrame::ScrollActivityCallback(nsITimer* aTimer, void nsHTMLScrollFrame::ScheduleSyntheticMouseMove() { if (!mScrollActivityTimer) { - mScrollActivityTimer = NS_NewTimer( - PresContext()->Document()->EventTargetFor(TaskCategory::Other)); + mScrollActivityTimer = NS_NewTimer(GetMainThreadSerialEventTarget()); if (!mScrollActivityTimer) { return; } diff --git a/layout/printing/nsPagePrintTimer.cpp b/layout/printing/nsPagePrintTimer.cpp index 9afd5834b6bf..90e39c758fde 100644 --- a/layout/printing/nsPagePrintTimer.cpp +++ b/layout/printing/nsPagePrintTimer.cpp @@ -55,9 +55,9 @@ nsresult nsPagePrintTimer::StartTimer(bool aUseDelay) { delay = mDelay; } } - return NS_NewTimerWithCallback( - getter_AddRefs(mTimer), this, delay, nsITimer::TYPE_ONE_SHOT, - mDocument->EventTargetFor(TaskCategory::Other)); + return NS_NewTimerWithCallback(getter_AddRefs(mTimer), this, delay, + nsITimer::TYPE_ONE_SHOT, + GetMainThreadSerialEventTarget()); } nsresult nsPagePrintTimer::StartWatchDogTimer() { @@ -66,9 +66,9 @@ nsresult nsPagePrintTimer::StartWatchDogTimer() { } // Instead of just doing one timer for a long period do multiple so we // can check if the user cancelled the printing. - return NS_NewTimerWithCallback( - getter_AddRefs(mWatchDogTimer), this, WATCH_DOG_INTERVAL, - nsITimer::TYPE_ONE_SHOT, mDocument->EventTargetFor(TaskCategory::Other)); + return NS_NewTimerWithCallback(getter_AddRefs(mWatchDogTimer), this, + WATCH_DOG_INTERVAL, nsITimer::TYPE_ONE_SHOT, + GetMainThreadSerialEventTarget()); } void nsPagePrintTimer::StopWatchDogTimer() { @@ -163,7 +163,7 @@ nsPagePrintTimer::Notify(nsITimer* timer) { if (donePrePrint && !mWaitingForRemotePrint) { StopWatchDogTimer(); // Pass nullptr here since name already was set in constructor. - mDocument->Dispatch(TaskCategory::Other, do_AddRef(this)); + mDocument->Dispatch(do_AddRef(this)); } else { // Start the watch dog if we're waiting for preprint to ensure that if any // mozPrintCallbacks take to long we error out. @@ -190,8 +190,7 @@ void nsPagePrintTimer::RemotePrintFinished() { mDone = mPrintJob->DonePrintingSheets(mPrintObj, NS_OK); } - mWaitingForRemotePrint->SetTarget( - mDocument->EventTargetFor(mozilla::TaskCategory::Other)); + mWaitingForRemotePrint->SetTarget(GetMainThreadSerialEventTarget()); mozilla::Unused << mWaitingForRemotePrint->InitWithCallback( this, 0, nsITimer::TYPE_ONE_SHOT); } diff --git a/layout/printing/nsPrintJob.cpp b/layout/printing/nsPrintJob.cpp index 205a6388958b..490be9cb89fb 100644 --- a/layout/printing/nsPrintJob.cpp +++ b/layout/printing/nsPrintJob.cpp @@ -2101,8 +2101,7 @@ void nsPrintJob::FirePrintCompletionEvent() { NS_ENSURE_TRUE_VOID(cv); nsCOMPtr doc = cv->GetDocument(); NS_ENSURE_TRUE_VOID(doc); - - NS_ENSURE_SUCCESS_VOID(doc->Dispatch(TaskCategory::Other, event.forget())); + NS_ENSURE_SUCCESS_VOID(doc->Dispatch(event.forget())); } void nsPrintJob::DisconnectPagePrintTimer() { diff --git a/layout/style/ErrorReporter.cpp b/layout/style/ErrorReporter.cpp index da857b5c817b..6335c695acca 100644 --- a/layout/style/ErrorReporter.cpp +++ b/layout/style/ErrorReporter.cpp @@ -146,8 +146,7 @@ ErrorReporter::~ErrorReporter() { // short-term caching. if (sSpecCache && sSpecCache->IsInUse() && !sSpecCache->IsPending()) { nsCOMPtr runnable(sSpecCache); - nsresult rv = - SchedulerGroup::Dispatch(TaskCategory::Other, runnable.forget()); + nsresult rv = SchedulerGroup::Dispatch(runnable.forget()); if (NS_FAILED(rv)) { // Peform the "deferred" cleanup immediately if the dispatch fails. sSpecCache->Run(); diff --git a/layout/style/Loader.cpp b/layout/style/Loader.cpp index 2702476e2380..fd729b7180cc 100644 --- a/layout/style/Loader.cpp +++ b/layout/style/Loader.cpp @@ -1568,10 +1568,9 @@ Loader::Completed Loader::ParseSheet(const nsACString& aBytes, // Note that load is already blocked from // IncrementOngoingLoadCountAndMaybeBlockOnload(), and will be unblocked from // SheetFinishedParsingAsync which will end up in NotifyObservers as needed. - nsCOMPtr target = DispatchTarget(); sheet->ParseSheet(*this, aBytes, aLoadData) ->Then( - target, __func__, + GetMainThreadSerialEventTarget(), __func__, [loadData = RefPtr(&aLoadData)](bool aDummy) { MOZ_ASSERT(NS_IsMainThread()); loadData->SheetFinishedParsingAsync(); @@ -2288,19 +2287,5 @@ void Loader::UnblockOnload(bool aFireSync) { } } -already_AddRefed Loader::DispatchTarget() { - nsCOMPtr target; - if (mDocument) { - // If you change this, you may want to change StyleSheet::Replace - target = mDocument->EventTargetFor(TaskCategory::Other); - } else if (mDocGroup) { - target = mDocGroup->EventTargetFor(TaskCategory::Other); - } else { - target = GetMainThreadSerialEventTarget(); - } - - return target.forget(); -} - } // namespace css } // namespace mozilla diff --git a/layout/style/Loader.h b/layout/style/Loader.h index 08b09bf21679..dd5bd771510d 100644 --- a/layout/style/Loader.h +++ b/layout/style/Loader.h @@ -514,10 +514,6 @@ class Loader final { void BlockOnload(); void UnblockOnload(bool aFireSync); - // Helper to select the correct dispatch target for asynchronous events for - // this loader. - already_AddRefed DispatchTarget(); - nsresult CheckContentPolicy(nsIPrincipal* aLoadingPrincipal, nsIPrincipal* aTriggeringPrincipal, nsIURI* aTargetURI, nsINode* aRequestingNode, diff --git a/layout/style/StyleSheet.cpp b/layout/style/StyleSheet.cpp index 6e64d218ac56..d3613bc6733c 100644 --- a/layout/style/StyleSheet.cpp +++ b/layout/style/StyleSheet.cpp @@ -728,8 +728,7 @@ already_AddRefed StyleSheet::Replace(const nsACString& aText, // 5.1 Parse aText into rules. // 5.2 Load import rules, throw NetworkError if failed. // 5.3 Set sheet's rules to new rules. - nsCOMPtr target = - mConstructorDocument->EventTargetFor(TaskCategory::Other); + nsISerialEventTarget* target = GetMainThreadSerialEventTarget(); loadData->mIsBeingParsed = true; MOZ_ASSERT(!mReplacePromise); mReplacePromise = promise; diff --git a/layout/style/nsFontFaceLoader.cpp b/layout/style/nsFontFaceLoader.cpp index 35daf2eb4e35..4003e7e3ecc2 100644 --- a/layout/style/nsFontFaceLoader.cpp +++ b/layout/style/nsFontFaceLoader.cpp @@ -101,16 +101,10 @@ void nsFontFaceLoader::StartedLoading(nsIStreamLoader* aStreamLoader) { } if (loadTimeout > 0) { - nsIEventTarget* target; - auto* doc = mFontFaceSet->GetDocument(); - if (doc) { - target = doc->EventTargetFor(TaskCategory::Other); - } else { - target = GetMainThreadSerialEventTarget(); - } - NS_NewTimerWithFuncCallback( - getter_AddRefs(mLoadTimer), LoadTimerCallback, static_cast(this), - loadTimeout, nsITimer::TYPE_ONE_SHOT, "LoadTimerCallback", target); + NS_NewTimerWithFuncCallback(getter_AddRefs(mLoadTimer), LoadTimerCallback, + static_cast(this), loadTimeout, + nsITimer::TYPE_ONE_SHOT, "LoadTimerCallback", + GetMainThreadSerialEventTarget()); } else { mUserFontEntry->mFontDataLoadingState = gfxUserFontEntry::LOADING_SLOWLY; } diff --git a/layout/style/nsStyleStruct.cpp b/layout/style/nsStyleStruct.cpp index 6e0d7d92e895..fb4cce7384e0 100644 --- a/layout/style/nsStyleStruct.cpp +++ b/layout/style/nsStyleStruct.cpp @@ -193,7 +193,7 @@ void Gecko_LoadData_Drop(StyleLoadData* aData) { // We want to dispatch this async to prevent reentrancy issues, as // imgRequestProxy going away can destroy documents, etc, see bug 1677555. auto task = MakeRefPtr(*aData); - SchedulerGroup::Dispatch(TaskCategory::Other, task.forget()); + SchedulerGroup::Dispatch(task.forget()); } // URIs are safe to refcount from any thread. diff --git a/layout/tables/nsTableFrame.cpp b/layout/tables/nsTableFrame.cpp index a475a4eac0b6..00725948018a 100644 --- a/layout/tables/nsTableFrame.cpp +++ b/layout/tables/nsTableFrame.cpp @@ -4507,8 +4507,7 @@ bool nsTableFrame::BCRecalcNeeded(ComputedStyle* aOldComputedStyle, // so it stores in the cellmap where a new border segment starts and this // introduces a unwanted cellmap data dependence on color nsCOMPtr evt = new nsDelayedCalcBCBorders(this); - nsresult rv = - GetContent()->OwnerDoc()->Dispatch(TaskCategory::Other, evt.forget()); + nsresult rv = GetContent()->OwnerDoc()->Dispatch(evt.forget()); return NS_SUCCEEDED(rv); } return false; diff --git a/layout/xul/nsMenuPopupFrame.cpp b/layout/xul/nsMenuPopupFrame.cpp index ca94156172af..db275dc3ab57 100644 --- a/layout/xul/nsMenuPopupFrame.cpp +++ b/layout/xul/nsMenuPopupFrame.cpp @@ -689,7 +689,7 @@ void nsMenuPopupFrame::LayoutPopup(nsPresContext* aPresContext, // If there are no transitions, fire the popupshown event right away. nsCOMPtr event = new nsXULPopupShownEvent(GetContent(), aPresContext); - mContent->OwnerDoc()->Dispatch(TaskCategory::Other, event.forget()); + mContent->OwnerDoc()->Dispatch(event.forget()); } } diff --git a/layout/xul/nsRepeatService.cpp b/layout/xul/nsRepeatService.cpp index b23c17396e4e..5495a0a10f31 100644 --- a/layout/xul/nsRepeatService.cpp +++ b/layout/xul/nsRepeatService.cpp @@ -48,7 +48,7 @@ void nsRepeatService::Start(Callback aCallback, void* aCallbackData, mCallbackData = aCallbackData; mCallbackName = aCallbackName; - mRepeatTimer = NS_NewTimer(aDocument->EventTargetFor(TaskCategory::Other)); + mRepeatTimer = NS_NewTimer(GetMainThreadSerialEventTarget()); if (mRepeatTimer) { InitTimerCallback(aInitialDelay); diff --git a/layout/xul/nsXULPopupManager.cpp b/layout/xul/nsXULPopupManager.cpp index 1054ffb65e54..c47e403e4825 100644 --- a/layout/xul/nsXULPopupManager.cpp +++ b/layout/xul/nsXULPopupManager.cpp @@ -1282,7 +1282,7 @@ void nsXULPopupManager::HidePopup(Element* aPopup, HidePopupOptions aOptions, nsCOMPtr event = new nsXULPopupHidingEvent(popupToHide, nextPopup, lastPopup, popupFrame->GetPopupType(), aOptions); - aPopup->OwnerDoc()->Dispatch(TaskCategory::Other, event.forget()); + aPopup->OwnerDoc()->Dispatch(event.forget()); } else { RefPtr presContext = popupFrame->PresContext(); FirePopupHidingEvent(popupToHide, nextPopup, lastPopup, presContext, @@ -1429,8 +1429,7 @@ void nsXULPopupManager::HidePopupAfterDelay(nsMenuPopupFrame* aPopup, KillMenuTimer(); // Kick off the timer. - nsIEventTarget* target = - aPopup->PopupElement().OwnerDoc()->EventTargetFor(TaskCategory::Other); + nsIEventTarget* target = GetMainThreadSerialEventTarget(); NS_NewTimerWithFuncCallback( getter_AddRefs(mCloseTimer), [](nsITimer* aTimer, void* aClosure) { @@ -1556,7 +1555,7 @@ void nsXULPopupManager::ExecuteMenu(nsIContent* aMenu, HideOpenMenusBeforeExecutingMenu(cmm); aEvent->SetCloseMenuMode(cmm); nsCOMPtr event = aEvent; - aMenu->OwnerDoc()->Dispatch(TaskCategory::Other, event.forget()); + aMenu->OwnerDoc()->Dispatch(event.forget()); } bool nsXULPopupManager::ActivateNativeMenuItem(nsIContent* aItem, @@ -2728,7 +2727,7 @@ bool nsXULPopupPositionedEvent::DispatchIfNeeded(Element* aPopup) { if (aPopup->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type, nsGkAtoms::arrow, eCaseMatters)) { nsCOMPtr event = new nsXULPopupPositionedEvent(aPopup); - aPopup->OwnerDoc()->Dispatch(TaskCategory::Other, event.forget()); + aPopup->OwnerDoc()->Dispatch(event.forget()); return true; } diff --git a/layout/xul/nsXULTooltipListener.cpp b/layout/xul/nsXULTooltipListener.cpp index 64c62c95f0d0..c6b1e87df041 100644 --- a/layout/xul/nsXULTooltipListener.cpp +++ b/layout/xul/nsXULTooltipListener.cpp @@ -206,7 +206,7 @@ void nsXULTooltipListener::MouseMove(Event* aEvent) { getter_AddRefs(mTooltipTimer), sTooltipCallback, this, LookAndFeel::GetInt(LookAndFeel::IntID::TooltipDelay, 500), nsITimer::TYPE_ONE_SHOT, "sTooltipCallback", - sourceContent->OwnerDoc()->EventTargetFor(TaskCategory::Other)); + GetMainThreadSerialEventTarget()); if (NS_FAILED(rv)) { mTargetNode = nullptr; mSourceNode = nullptr; diff --git a/layout/xul/tree/nsTreeBodyFrame.cpp b/layout/xul/tree/nsTreeBodyFrame.cpp index 4e181b00fe5c..52c175e71dc9 100644 --- a/layout/xul/tree/nsTreeBodyFrame.cpp +++ b/layout/xul/tree/nsTreeBodyFrame.cpp @@ -1600,9 +1600,8 @@ nsresult nsTreeBodyFrame::CreateTimer(const LookAndFeel::IntID aID, // Zero value means that this feature is completely disabled. if (delay > 0) { MOZ_TRY_VAR(timer, - NS_NewTimerWithFuncCallback( - aFunc, this, delay, aType, aName, - mContent->OwnerDoc()->EventTargetFor(TaskCategory::Other))); + NS_NewTimerWithFuncCallback(aFunc, this, delay, aType, aName, + GetMainThreadSerialEventTarget())); } timer.forget(aTimer); @@ -4181,8 +4180,7 @@ void nsTreeBodyFrame::PostScrollEvent() { if (mScrollEvent.IsPending()) return; RefPtr event = new ScrollEvent(this); - nsresult rv = - mContent->OwnerDoc()->Dispatch(TaskCategory::Other, do_AddRef(event)); + nsresult rv = mContent->OwnerDoc()->Dispatch(do_AddRef(event)); if (NS_FAILED(rv)) { NS_WARNING("failed to dispatch ScrollEvent"); } else { @@ -4354,7 +4352,7 @@ bool nsTreeBodyFrame::FullScrollbarsUpdate(bool aNeedsFullInvalidation) { if (!mCheckingOverflow) { nsContentUtils::AddScriptRunner(checker); } else { - mContent->OwnerDoc()->Dispatch(TaskCategory::Other, checker.forget()); + mContent->OwnerDoc()->Dispatch(checker.forget()); } return weakFrame.IsAlive(); } diff --git a/layout/xul/tree/nsTreeSelection.cpp b/layout/xul/tree/nsTreeSelection.cpp index 952a9bf37677..2ffbd6b37c91 100644 --- a/layout/xul/tree/nsTreeSelection.cpp +++ b/layout/xul/tree/nsTreeSelection.cpp @@ -299,8 +299,7 @@ NS_IMETHODIMP nsTreeSelection::TimedSelect(int32_t aIndex, int32_t aMsec) { if (!mTree) { return NS_ERROR_UNEXPECTED; } - nsIEventTarget* target = - mTree->OwnerDoc()->EventTargetFor(TaskCategory::Other); + nsIEventTarget* target = GetMainThreadSerialEventTarget(); NS_NewTimerWithFuncCallback(getter_AddRefs(mSelectTimer), SelectCallback, this, aMsec, nsITimer::TYPE_ONE_SHOT, "nsTreeSelection::SelectCallback", target); diff --git a/modules/libpref/Preferences.cpp b/modules/libpref/Preferences.cpp index d61fd9e6b5f2..37d9ab63c209 100644 --- a/modules/libpref/Preferences.cpp +++ b/modules/libpref/Preferences.cpp @@ -3335,15 +3335,13 @@ class PWRunnable : public Runnable { // ref counted pointer off main thread. nsresult rvCopy = rv; nsCOMPtr fileCopy(mFile); - SchedulerGroup::Dispatch( - TaskCategory::Other, - NS_NewRunnableFunction("Preferences::WriterRunnable", - [fileCopy, rvCopy] { - MOZ_RELEASE_ASSERT(NS_IsMainThread()); - if (NS_FAILED(rvCopy)) { - Preferences::HandleDirty(); - } - })); + SchedulerGroup::Dispatch(NS_NewRunnableFunction( + "Preferences::WriterRunnable", [fileCopy, rvCopy] { + MOZ_RELEASE_ASSERT(NS_IsMainThread()); + if (NS_FAILED(rvCopy)) { + Preferences::HandleDirty(); + } + })); } } // We've completed the write to the best of our abilities, whether diff --git a/netwerk/base/Predictor.cpp b/netwerk/base/Predictor.cpp index 0832e4ff74a5..de19d0e06e07 100644 --- a/netwerk/base/Predictor.cpp +++ b/netwerk/base/Predictor.cpp @@ -1243,8 +1243,7 @@ Predictor::LearnNative(nsIURI* targetURI, nsIURI* sourceURI, RefPtr runnable = new PredictorLearnRunnable( targetURI, sourceURI, reason, originAttributes); - SchedulerGroup::Dispatch(TaskCategory::Other, runnable.forget()); - + SchedulerGroup::Dispatch(runnable.forget()); return NS_OK; } diff --git a/netwerk/base/nsBaseChannel.cpp b/netwerk/base/nsBaseChannel.cpp index d5453e7993e3..148d6c0ab748 100644 --- a/netwerk/base/nsBaseChannel.cpp +++ b/netwerk/base/nsBaseChannel.cpp @@ -948,8 +948,7 @@ NS_IMETHODIMP nsBaseChannel::GetCanceled(bool* aCanceled) { } void nsBaseChannel::SetupNeckoTarget() { - mNeckoTarget = - nsContentUtils::GetEventTargetByLoadInfo(mLoadInfo, TaskCategory::Other); + mNeckoTarget = GetMainThreadSerialEventTarget(); } nsBaseChannel::ContentRange::ContentRange(const nsACString& aRangeHeader, diff --git a/netwerk/cookie/CookieJarSettings.cpp b/netwerk/cookie/CookieJarSettings.cpp index b5c0b611ab86..09a4789d8598 100644 --- a/netwerk/cookie/CookieJarSettings.cpp +++ b/netwerk/cookie/CookieJarSettings.cpp @@ -185,8 +185,7 @@ CookieJarSettings::~CookieJarSettings() { RefPtr r = new ReleaseCookiePermissions(std::move(mCookiePermissions)); MOZ_ASSERT(mCookiePermissions.IsEmpty()); - - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget()); + SchedulerGroup::Dispatch(r.forget()); } } diff --git a/netwerk/dns/DNSRequestChild.cpp b/netwerk/dns/DNSRequestChild.cpp index d8ee335b6fff..578895186a1f 100644 --- a/netwerk/dns/DNSRequestChild.cpp +++ b/netwerk/dns/DNSRequestChild.cpp @@ -414,7 +414,7 @@ DNSRequestSender::Cancel(nsresult reason) { host, trrServer, port, type, originAttributes, flags, reason); } }); - SchedulerGroup::Dispatch(TaskCategory::Other, runnable.forget()); + SchedulerGroup::Dispatch(runnable.forget()); } return NS_OK; } @@ -423,7 +423,6 @@ void DNSRequestSender::StartRequest() { // we can only do IPDL on the main thread if (!NS_IsMainThread()) { SchedulerGroup::Dispatch( - TaskCategory::Other, NewRunnableMethod("net::DNSRequestSender::StartRequest", this, &DNSRequestSender::StartRequest)); return; diff --git a/netwerk/ipc/NeckoChild.cpp b/netwerk/ipc/NeckoChild.cpp index 29bd27421abb..fe2b3df0bff8 100644 --- a/netwerk/ipc/NeckoChild.cpp +++ b/netwerk/ipc/NeckoChild.cpp @@ -176,15 +176,8 @@ bool NeckoChild::DeallocPWebSocketChild(PWebSocketChild* child) { PWebSocketEventListenerChild* NeckoChild::AllocPWebSocketEventListenerChild( const uint64_t& aInnerWindowID) { - nsCOMPtr target; - if (nsGlobalWindowInner* win = - nsGlobalWindowInner::GetInnerWindowWithId(aInnerWindowID)) { - target = win->EventTargetFor(TaskCategory::Other); - } - - RefPtr c = - new WebSocketEventListenerChild(aInnerWindowID, target); - + RefPtr c = new WebSocketEventListenerChild( + aInnerWindowID, GetMainThreadSerialEventTarget()); return c.forget().take(); } diff --git a/netwerk/protocol/gio/GIOChannelChild.cpp b/netwerk/protocol/gio/GIOChannelChild.cpp index 75e519b2ce76..9f8d19ce1e14 100644 --- a/netwerk/protocol/gio/GIOChannelChild.cpp +++ b/netwerk/protocol/gio/GIOChannelChild.cpp @@ -449,12 +449,7 @@ void GIOChannelChild::SetupNeckoTarget() { if (mNeckoTarget) { return; } - nsCOMPtr loadInfo = LoadInfo(); - mNeckoTarget = - nsContentUtils::GetEventTargetByLoadInfo(loadInfo, TaskCategory::Network); - if (!mNeckoTarget) { - return; - } + mNeckoTarget = GetMainThreadSerialEventTarget(); } } // namespace net diff --git a/netwerk/protocol/http/HttpChannelChild.cpp b/netwerk/protocol/http/HttpChannelChild.cpp index 0fb39e1ded59..f4f63a82cf44 100644 --- a/netwerk/protocol/http/HttpChannelChild.cpp +++ b/netwerk/protocol/http/HttpChannelChild.cpp @@ -2121,19 +2121,8 @@ nsresult HttpChannelChild::AsyncOpenInternal(nsIStreamListener* aListener) { // Assigns an nsISerialEventTarget to our IPDL actor so that IPC messages are // sent to the correct DocGroup/TabGroup. void HttpChannelChild::SetEventTarget() { - nsCOMPtr loadInfo = LoadInfo(); - - nsCOMPtr target = - nsContentUtils::GetEventTargetByLoadInfo(loadInfo, TaskCategory::Network); - - if (!target) { - return; - } - - { - MutexAutoLock lock(mEventTargetMutex); - mNeckoTarget = target; - } + MutexAutoLock lock(mEventTargetMutex); + mNeckoTarget = GetMainThreadSerialEventTarget(); } already_AddRefed HttpChannelChild::GetNeckoTarget() { diff --git a/netwerk/protocol/http/InterceptedHttpChannel.cpp b/netwerk/protocol/http/InterceptedHttpChannel.cpp index 03a2605c5d55..b4c3203536e4 100644 --- a/netwerk/protocol/http/InterceptedHttpChannel.cpp +++ b/netwerk/protocol/http/InterceptedHttpChannel.cpp @@ -418,8 +418,7 @@ void InterceptedHttpChannel::MaybeCallStatusAndProgress() { nsCOMPtr r = NewRunnableMethod( "InterceptedHttpChannel::MaybeCallStatusAndProgress", this, &InterceptedHttpChannel::MaybeCallStatusAndProgress); - MOZ_ALWAYS_SUCCEEDS( - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget())); + MOZ_ALWAYS_SUCCEEDS(SchedulerGroup::Dispatch(r.forget())); return; } diff --git a/netwerk/protocol/res/ExtensionProtocolHandler.cpp b/netwerk/protocol/res/ExtensionProtocolHandler.cpp index 5400bf24fbf0..4f56578100cc 100644 --- a/netwerk/protocol/res/ExtensionProtocolHandler.cpp +++ b/netwerk/protocol/res/ExtensionProtocolHandler.cpp @@ -134,11 +134,7 @@ class ExtensionStreamGetter final : public nsICancelable { } void SetupEventTarget() { - mMainThreadEventTarget = nsContentUtils::GetEventTargetByLoadInfo( - mLoadInfo, TaskCategory::Other); - if (!mMainThreadEventTarget) { - mMainThreadEventTarget = GetMainThreadSerialEventTarget(); - } + mMainThreadEventTarget = GetMainThreadSerialEventTarget(); } // Get an input stream or file descriptor from the parent asynchronously. diff --git a/netwerk/protocol/websocket/WebSocketChannelChild.cpp b/netwerk/protocol/websocket/WebSocketChannelChild.cpp index 52341c799ca9..5586035d7dec 100644 --- a/netwerk/protocol/websocket/WebSocketChannelChild.cpp +++ b/netwerk/protocol/websocket/WebSocketChannelChild.cpp @@ -444,8 +444,7 @@ void WebSocketChannelChild::OnServerClose(const uint16_t& aCode, } void WebSocketChannelChild::SetupNeckoTarget() { - mNeckoTarget = nsContentUtils::GetEventTargetByLoadInfo( - mLoadInfo, TaskCategory::Network); + mNeckoTarget = GetMainThreadSerialEventTarget(); } NS_IMETHODIMP diff --git a/parser/html/nsHtml5StreamParser.cpp b/parser/html/nsHtml5StreamParser.cpp index fe3493ab1554..18a995aa5a83 100644 --- a/parser/html/nsHtml5StreamParser.cpp +++ b/parser/html/nsHtml5StreamParser.cpp @@ -28,7 +28,6 @@ #include "mozilla/Services.h" #include "mozilla/StaticPrefs_html5.h" #include "mozilla/StaticPrefs_intl.h" -#include "mozilla/TaskCategory.h" #include "mozilla/TextUtils.h" #include "mozilla/UniquePtrExtensions.h" @@ -165,8 +164,7 @@ class nsHtml5ExecutorFlusher : public Runnable { // Possible early paint pending, reuse the runnable and try to // call RunFlushLoop later. nsCOMPtr flusher = this; - if (NS_SUCCEEDED( - doc->Dispatch(TaskCategory::Network, flusher.forget()))) { + if (NS_SUCCEEDED(doc->Dispatch(flusher.forget()))) { PROFILER_MARKER_UNTYPED("HighPrio blocking parser flushing(1)", DOM); return NS_OK; } @@ -1192,16 +1190,8 @@ nsresult nsHtml5StreamParser::OnStartRequest(nsIRequest* aRequest) { rv = NS_OK; - mNetworkEventTarget = - mExecutor->GetDocument()->EventTargetFor(TaskCategory::Network); - nsCOMPtr httpChannel(do_QueryInterface(mRequest, &rv)); if (NS_SUCCEEDED(rv)) { - // Non-HTTP channels are bogus enough that we let them work with unlabeled - // runnables for now. Asserting for HTTP channels only. - MOZ_ASSERT(mNetworkEventTarget || mMode == LOAD_AS_DATA, - "How come the network event target is still null?"); - nsAutoCString method; Unused << httpChannel->GetRequestMethod(method); // XXX does Necko have a way to renavigate POST, etc. without hitting @@ -1226,8 +1216,7 @@ nsresult nsHtml5StreamParser::OnStartRequest(nsIRequest* aRequest) { // the request. nsCOMPtr runnable = new MaybeRunCollector(mExecutor->GetDocument()->GetDocShell()); - mozilla::SchedulerGroup::Dispatch( - mozilla::TaskCategory::GarbageCollection, runnable.forget()); + mozilla::SchedulerGroup::Dispatch(runnable.forget()); } } @@ -2857,8 +2846,5 @@ void nsHtml5StreamParser::MarkAsBroken(nsresult aRv) { nsresult nsHtml5StreamParser::DispatchToMain( already_AddRefed&& aRunnable) { - if (mNetworkEventTarget) { - return mNetworkEventTarget->Dispatch(std::move(aRunnable)); - } - return SchedulerGroup::Dispatch(TaskCategory::Network, std::move(aRunnable)); + return SchedulerGroup::Dispatch(std::move(aRunnable)); } diff --git a/parser/html/nsHtml5StreamParser.h b/parser/html/nsHtml5StreamParser.h index 0dacf257bf34..40a33fab4033 100644 --- a/parser/html/nsHtml5StreamParser.h +++ b/parser/html/nsHtml5StreamParser.h @@ -593,11 +593,6 @@ class nsHtml5StreamParser final : public nsISupports { */ nsHtml5TreeOpExecutor* mExecutor; - /** - * Network event target for mExecutor->mDocument - */ - nsCOMPtr mNetworkEventTarget; - /** * The HTML5 tree builder */ diff --git a/parser/html/nsHtml5TreeOpExecutor.cpp b/parser/html/nsHtml5TreeOpExecutor.cpp index 9fa4338b8c15..125728fa7318 100644 --- a/parser/html/nsHtml5TreeOpExecutor.cpp +++ b/parser/html/nsHtml5TreeOpExecutor.cpp @@ -75,8 +75,7 @@ class nsHtml5ExecutorReflusher : public Runnable { // Possible early paint pending, reuse the runnable and try to // call RunFlushLoop later. nsCOMPtr flusher = this; - if (NS_SUCCEEDED( - doc->Dispatch(TaskCategory::Network, flusher.forget()))) { + if (NS_SUCCEEDED(doc->Dispatch(flusher.forget()))) { PROFILER_MARKER_UNTYPED("HighPrio blocking parser flushing(2)", DOM); return NS_OK; } @@ -468,8 +467,7 @@ nsresult nsHtml5TreeOpExecutor::MarkAsBroken(nsresult aReason) { if (mParser && mDocument) { // can mParser ever be null here? nsCOMPtr terminator = NewRunnableMethod( "nsHtml5Parser::Terminate", GetParser(), &nsHtml5Parser::Terminate); - if (NS_FAILED( - mDocument->Dispatch(TaskCategory::Network, terminator.forget()))) { + if (NS_FAILED(mDocument->Dispatch(terminator.forget()))) { NS_WARNING("failed to dispatch executor flush event"); } } @@ -494,8 +492,7 @@ static bool BackgroundFlushCallback(TimeStamp /*aDeadline*/) { void nsHtml5TreeOpExecutor::ContinueInterruptedParsingAsync() { if (mDocument && !mDocument->IsInBackgroundWindow()) { nsCOMPtr flusher = new nsHtml5ExecutorReflusher(this); - if (NS_FAILED( - mDocument->Dispatch(TaskCategory::Network, flusher.forget()))) { + if (NS_FAILED(mDocument->Dispatch(flusher.forget()))) { NS_WARNING("failed to dispatch executor flush event"); } } else { diff --git a/parser/html/nsHtml5TreeOperation.cpp b/parser/html/nsHtml5TreeOperation.cpp index 8d0c972b5ffe..a389e078c8d9 100644 --- a/parser/html/nsHtml5TreeOperation.cpp +++ b/parser/html/nsHtml5TreeOperation.cpp @@ -719,8 +719,7 @@ void nsHtml5TreeOperation::DoneCreatingElement(nsIContent* aNode) { void nsHtml5TreeOperation::SvgLoad(nsIContent* aNode) { nsCOMPtr event = new nsHtml5SVGLoadDispatcher(aNode); - if (NS_FAILED( - aNode->OwnerDoc()->Dispatch(TaskCategory::Network, event.forget()))) { + if (NS_FAILED(aNode->OwnerDoc()->Dispatch(event.forget()))) { NS_WARNING("failed to dispatch svg load dispatcher"); } } diff --git a/security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp b/security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp index 881394c21059..be524425950a 100644 --- a/security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp +++ b/security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp @@ -507,10 +507,8 @@ static sandbox::ResultCode AllowProxyLoadFromBinDir( if (NS_IsMainThread()) { setClearOnShutdown(); } else { - SchedulerGroup::Dispatch( - TaskCategory::Other, - NS_NewRunnableFunction("InitSignedPolicyRulesToBypassCig", - std::move(setClearOnShutdown))); + SchedulerGroup::Dispatch(NS_NewRunnableFunction( + "InitSignedPolicyRulesToBypassCig", std::move(setClearOnShutdown))); } } diff --git a/toolkit/components/backgroundhangmonitor/HangDetails.cpp b/toolkit/components/backgroundhangmonitor/HangDetails.cpp index daa32205abbb..34148a22ef82 100644 --- a/toolkit/components/backgroundhangmonitor/HangDetails.cpp +++ b/toolkit/components/backgroundhangmonitor/HangDetails.cpp @@ -324,8 +324,7 @@ void nsHangDetails::Submit() { } }); - nsresult rv = - SchedulerGroup::Dispatch(TaskCategory::Other, notifyObservers.forget()); + nsresult rv = SchedulerGroup::Dispatch(notifyObservers.forget()); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); } diff --git a/toolkit/components/places/nsAnnoProtocolHandler.cpp b/toolkit/components/places/nsAnnoProtocolHandler.cpp index c3ad2e64101e..89451b411203 100644 --- a/toolkit/components/places/nsAnnoProtocolHandler.cpp +++ b/toolkit/components/places/nsAnnoProtocolHandler.cpp @@ -156,8 +156,7 @@ class faviconAsyncLoader : public AsyncStatementCallback, public nsICancelable { nsresult rv; nsCOMPtr loadInfo = mChannel->LoadInfo(); - nsCOMPtr target = - nsContentUtils::GetEventTargetByLoadInfo(loadInfo, TaskCategory::Other); + nsISerialEventTarget* target = GetMainThreadSerialEventTarget(); if (!mData.IsEmpty()) { nsCOMPtr stream; rv = NS_NewCStringInputStream(getter_AddRefs(stream), mData); diff --git a/toolkit/components/satchel/nsFormFillController.cpp b/toolkit/components/satchel/nsFormFillController.cpp index c3abebfb45ab..f3dd1f20171b 100644 --- a/toolkit/components/satchel/nsFormFillController.cpp +++ b/toolkit/components/satchel/nsFormFillController.cpp @@ -153,7 +153,7 @@ void nsFormFillController::AttributeChanged(mozilla::dom::Element* aElement, mozilla::NewRunnableMethod>( "nsFormFillController::MaybeStartControllingInput", this, &nsFormFillController::MaybeStartControllingInput, focusedInput); - aElement->OwnerDoc()->Dispatch(TaskCategory::Other, event.forget()); + aElement->OwnerDoc()->Dispatch(event.forget()); } if (mListNode && mListNode->Contains(aElement)) { diff --git a/toolkit/components/telemetry/core/ipc/TelemetryIPCAccumulator.cpp b/toolkit/components/telemetry/core/ipc/TelemetryIPCAccumulator.cpp index f645edd27dee..fd0f945daf1f 100644 --- a/toolkit/components/telemetry/core/ipc/TelemetryIPCAccumulator.cpp +++ b/toolkit/components/telemetry/core/ipc/TelemetryIPCAccumulator.cpp @@ -24,7 +24,6 @@ using mozilla::StaticAutoPtr; using mozilla::StaticMutex; using mozilla::StaticMutexAutoLock; -using mozilla::TaskCategory; using mozilla::Telemetry::ChildEventData; using mozilla::Telemetry::DiscardedData; using mozilla::Telemetry::HistogramAccumulation; @@ -348,5 +347,5 @@ void TelemetryIPCAccumulator::DeInitializeGlobalState() { void TelemetryIPCAccumulator::DispatchToMainThread( already_AddRefed&& aEvent) { - SchedulerGroup::Dispatch(TaskCategory::Other, std::move(aEvent)); + SchedulerGroup::Dispatch(std::move(aEvent)); } diff --git a/toolkit/components/telemetry/other/UntrustedModulesBackupService.cpp b/toolkit/components/telemetry/other/UntrustedModulesBackupService.cpp index a0638e5aecc3..1cbe35e8c057 100644 --- a/toolkit/components/telemetry/other/UntrustedModulesBackupService.cpp +++ b/toolkit/components/telemetry/other/UntrustedModulesBackupService.cpp @@ -66,11 +66,9 @@ UntrustedModulesBackupService* UntrustedModulesBackupService::Get() { return instance.forget(); } - SchedulerGroup::Dispatch( - TaskCategory::Other, - NS_NewRunnableFunction( - "mozilla::UntrustedModulesBackupService::Get", - std::move(setClearOnShutdown))); + SchedulerGroup::Dispatch(NS_NewRunnableFunction( + "mozilla::UntrustedModulesBackupService::Get", + std::move(setClearOnShutdown))); return instance.forget(); }()); diff --git a/toolkit/xre/dllservices/WinDllServices.cpp b/toolkit/xre/dllservices/WinDllServices.cpp index 115e9e362796..31e466c5f1ca 100644 --- a/toolkit/xre/dllservices/WinDllServices.cpp +++ b/toolkit/xre/dllservices/WinDllServices.cpp @@ -41,10 +41,8 @@ DllServices* DllServices::Get() { return dllSvc.forget(); } - SchedulerGroup::Dispatch( - TaskCategory::Other, - NS_NewRunnableFunction("mozilla::DllServices::Get", - std::move(setClearOnShutdown))); + SchedulerGroup::Dispatch(NS_NewRunnableFunction( + "mozilla::DllServices::Get", std::move(setClearOnShutdown))); return dllSvc.forget(); }()); diff --git a/toolkit/xre/dllservices/mozglue/WindowsDllServices.h b/toolkit/xre/dllservices/mozglue/WindowsDllServices.h index 74810fb6555d..92ef01e1b4da 100644 --- a/toolkit/xre/dllservices/mozglue/WindowsDllServices.h +++ b/toolkit/xre/dllservices/mozglue/WindowsDllServices.h @@ -171,8 +171,7 @@ class DllServices : public detail::DllServicesBase { NewRunnableMethod>( "DllServices::NotifyDllLoad", this, &DllServices::NotifyDllLoad, std::move(aModLoadInfo))); - - SchedulerGroup::Dispatch(TaskCategory::Other, runnable.forget()); + SchedulerGroup::Dispatch(runnable.forget()); } void DispatchModuleLoadBacklogNotification( @@ -182,7 +181,7 @@ class DllServices : public detail::DllServicesBase { "DllServices::NotifyModuleLoadBacklog", this, &DllServices::NotifyModuleLoadBacklog, std::move(aEvents))); - SchedulerGroup::Dispatch(TaskCategory::Other, runnable.forget()); + SchedulerGroup::Dispatch(runnable.forget()); } # if defined(DEBUG) diff --git a/tools/profiler/core/platform.cpp b/tools/profiler/core/platform.cpp index 048386b507e8..02cc688496a9 100644 --- a/tools/profiler/core/platform.cpp +++ b/tools/profiler/core/platform.cpp @@ -5807,7 +5807,7 @@ static void TriggerPollJSSamplingOnMainThread() { nsCOMPtr task = NS_NewRunnableFunction("TriggerPollJSSamplingOnMainThread", []() { PollJSSamplingForCurrentThread(); }); - SchedulerGroup::Dispatch(TaskCategory::Other, task.forget()); + SchedulerGroup::Dispatch(task.forget()); } } diff --git a/tools/profiler/gecko/nsProfiler.cpp b/tools/profiler/gecko/nsProfiler.cpp index 66e32ce2bcf6..35cf838a0fb4 100644 --- a/tools/profiler/gecko/nsProfiler.cpp +++ b/tools/profiler/gecko/nsProfiler.cpp @@ -256,38 +256,34 @@ nsProfiler::WaitOnePeriodicSampling(JSContext* aCx, Promise** aPromise) { new nsMainThreadPtrHolder( "WaitOnePeriodicSampling promise for Sampler", promise))]( SamplingState aSamplingState) mutable { - SchedulerGroup::Dispatch( - TaskCategory::Other, - NS_NewRunnableFunction( - "nsProfiler::WaitOnePeriodicSampling result on main thread", - [promiseHandleInMT = std::move(promiseHandleInSampler), - aSamplingState]() mutable { - switch (aSamplingState) { - case SamplingState::JustStopped: - case SamplingState::SamplingPaused: - promiseHandleInMT->MaybeReject(NS_ERROR_FAILURE); - break; + SchedulerGroup::Dispatch(NS_NewRunnableFunction( + "nsProfiler::WaitOnePeriodicSampling result on main thread", + [promiseHandleInMT = std::move(promiseHandleInSampler), + aSamplingState]() mutable { + switch (aSamplingState) { + case SamplingState::JustStopped: + case SamplingState::SamplingPaused: + promiseHandleInMT->MaybeReject(NS_ERROR_FAILURE); + break; - case SamplingState::NoStackSamplingCompleted: - case SamplingState::SamplingCompleted: - // The parent process has succesfully done a sampling, - // check the child processes (if any). - ProfilerParent::WaitOnePeriodicSampling()->Then( - GetMainThreadSerialEventTarget(), __func__, - [promiseHandleInMT = - std::move(promiseHandleInMT)]( - GenericPromise::ResolveOrRejectValue&&) { - promiseHandleInMT->MaybeResolveWithUndefined(); - }); - break; + case SamplingState::NoStackSamplingCompleted: + case SamplingState::SamplingCompleted: + // The parent process has succesfully done a sampling, + // check the child processes (if any). + ProfilerParent::WaitOnePeriodicSampling()->Then( + GetMainThreadSerialEventTarget(), __func__, + [promiseHandleInMT = std::move(promiseHandleInMT)]( + GenericPromise::ResolveOrRejectValue&&) { + promiseHandleInMT->MaybeResolveWithUndefined(); + }); + break; - default: - MOZ_ASSERT(false, "Unexpected SamplingState value"); - promiseHandleInMT->MaybeReject( - NS_ERROR_DOM_UNKNOWN_ERR); - break; - } - })); + default: + MOZ_ASSERT(false, "Unexpected SamplingState value"); + promiseHandleInMT->MaybeReject(NS_ERROR_DOM_UNKNOWN_ERR); + break; + } + })); })) { // Callback was not added (e.g., profiler is not running) and will never be // invoked, so we need to resolve the promise here. diff --git a/uriloader/base/nsDocLoader.cpp b/uriloader/base/nsDocLoader.cpp index f779f0028e87..d54be4a4d769 100644 --- a/uriloader/base/nsDocLoader.cpp +++ b/uriloader/base/nsDocLoader.cpp @@ -1052,15 +1052,7 @@ nsDocLoader::GetLoadType(uint32_t* aLoadType) { NS_IMETHODIMP nsDocLoader::GetTarget(nsIEventTarget** aTarget) { - nsCOMPtr window; - nsresult rv = GetDOMWindow(getter_AddRefs(window)); - NS_ENSURE_SUCCESS(rv, rv); - - nsCOMPtr global = do_QueryInterface(window); - NS_ENSURE_STATE(global); - - nsCOMPtr target = - global->EventTargetFor(mozilla::TaskCategory::Other); + nsCOMPtr target = GetMainThreadSerialEventTarget(); target.forget(aTarget); return NS_OK; } diff --git a/widget/PuppetWidget.cpp b/widget/PuppetWidget.cpp index 1267ae47d723..07b22d9a2b1c 100644 --- a/widget/PuppetWidget.cpp +++ b/widget/PuppetWidget.cpp @@ -241,7 +241,7 @@ void PuppetWidget::Invalidate(const LayoutDeviceIntRect& aRect) { if (mBrowserChild && !aRect.IsEmpty() && !mWidgetPaintTask.IsPending()) { mWidgetPaintTask = new WidgetPaintTask(this); nsCOMPtr event(mWidgetPaintTask.get()); - SchedulerGroup::Dispatch(TaskCategory::Other, event.forget()); + SchedulerGroup::Dispatch(event.forget()); } } diff --git a/widget/gtk/nsClipboard.cpp b/widget/gtk/nsClipboard.cpp index 77ff2e2a53f1..eee3a3b74436 100644 --- a/widget/gtk/nsClipboard.cpp +++ b/widget/gtk/nsClipboard.cpp @@ -241,7 +241,6 @@ nsClipboard::Observe(nsISupports* aSubject, const char* aTopic, // gtk_clipboard_store() can run an event loop, so call from a dedicated // runnable. return SchedulerGroup::Dispatch( - TaskCategory::Other, NS_NewRunnableFunction("gtk_clipboard_store()", []() { LOGCLIP("nsClipboard storing clipboard content\n"); gtk_clipboard_store(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD)); diff --git a/widget/nsNativeTheme.cpp b/widget/nsNativeTheme.cpp index 8eb3fdc30281..bb83cf4cad11 100644 --- a/widget/nsNativeTheme.cpp +++ b/widget/nsNativeTheme.cpp @@ -440,8 +440,7 @@ bool nsNativeTheme::QueueAnimatedContentForRefresh(nsIContent* aContent, } if (XRE_IsContentProcess() && NS_IsMainThread()) { - mAnimatedContentTimer->SetTarget( - aContent->OwnerDoc()->EventTargetFor(TaskCategory::Other)); + mAnimatedContentTimer->SetTarget(GetMainThreadSerialEventTarget()); } rv = mAnimatedContentTimer->InitWithCallback(this, timeout, nsITimer::TYPE_ONE_SHOT); diff --git a/widget/windows/WinUtils.cpp b/widget/windows/WinUtils.cpp index b3abcf279c9a..4cfbd36ce9d4 100644 --- a/widget/windows/WinUtils.cpp +++ b/widget/windows/WinUtils.cpp @@ -1795,10 +1795,8 @@ const WinUtils::WhitelistVec& WinUtils::GetWhitelistedPaths() { if (NS_IsMainThread()) { setClearFn(); } else { - SchedulerGroup::Dispatch( - TaskCategory::Other, - NS_NewRunnableFunction("WinUtils::GetWhitelistedPaths", - std::move(setClearFn))); + SchedulerGroup::Dispatch(NS_NewRunnableFunction( + "WinUtils::GetWhitelistedPaths", std::move(setClearFn))); } return BuildWhitelist(); diff --git a/xpcom/base/DebuggerOnGCRunnable.cpp b/xpcom/base/DebuggerOnGCRunnable.cpp index bcb13b322620..f8415dc3d82b 100644 --- a/xpcom/base/DebuggerOnGCRunnable.cpp +++ b/xpcom/base/DebuggerOnGCRunnable.cpp @@ -25,12 +25,7 @@ nsresult DebuggerOnGCRunnable::Enqueue(JSContext* aCx, RefPtr runOnGC = new DebuggerOnGCRunnable(std::move(gcEvent)); - if (NS_IsMainThread()) { - return SchedulerGroup::Dispatch(TaskCategory::GarbageCollection, - runOnGC.forget()); - } else { - return NS_DispatchToCurrentThread(runOnGC); - } + return NS_DispatchToCurrentThread(runOnGC); } NS_IMETHODIMP diff --git a/xpcom/base/nsConsoleService.cpp b/xpcom/base/nsConsoleService.cpp index 45d09436b148..e6b17a6571ba 100644 --- a/xpcom/base/nsConsoleService.cpp +++ b/xpcom/base/nsConsoleService.cpp @@ -389,7 +389,7 @@ nsresult nsConsoleService::LogMessageWithMode( // avoid failing in XPCShell tests nsCOMPtr mainThread = do_GetMainThread(); if (mainThread) { - SchedulerGroup::Dispatch(TaskCategory::Other, r.forget()); + SchedulerGroup::Dispatch(r.forget()); } } diff --git a/xpcom/threads/IdleTaskRunner.cpp b/xpcom/threads/IdleTaskRunner.cpp index d47a4b75d116..2a61877fa050 100644 --- a/xpcom/threads/IdleTaskRunner.cpp +++ b/xpcom/threads/IdleTaskRunner.cpp @@ -5,7 +5,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "IdleTaskRunner.h" -#include "mozilla/TaskCategory.h" #include "mozilla/TaskController.h" #include "nsRefreshDriver.h" diff --git a/xpcom/threads/SchedulerGroup.cpp b/xpcom/threads/SchedulerGroup.cpp index ed67fbbd786c..f69ce070039c 100644 --- a/xpcom/threads/SchedulerGroup.cpp +++ b/xpcom/threads/SchedulerGroup.cpp @@ -5,27 +5,16 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "mozilla/SchedulerGroup.h" - -#include - -#include "jsfriendapi.h" -#include "mozilla/Atomics.h" -#include "mozilla/Telemetry.h" -#include "mozilla/Unused.h" -#include "mozilla/dom/DocGroup.h" -#include "mozilla/dom/ScriptSettings.h" -#include "nsINamed.h" -#include "nsQueryObject.h" #include "nsThreadUtils.h" -using namespace mozilla; +namespace mozilla { /* static */ -nsresult SchedulerGroup::Dispatch(TaskCategory aCategory, - already_AddRefed&& aRunnable) { +nsresult SchedulerGroup::Dispatch(already_AddRefed&& aRunnable) { if (NS_IsMainThread()) { return NS_DispatchToCurrentThread(std::move(aRunnable)); - } else { - return NS_DispatchToMainThread(std::move(aRunnable)); } + return NS_DispatchToMainThread(std::move(aRunnable)); } + +} // namespace mozilla diff --git a/xpcom/threads/SchedulerGroup.h b/xpcom/threads/SchedulerGroup.h index e6cb8a04e60f..09f0aac26adc 100644 --- a/xpcom/threads/SchedulerGroup.h +++ b/xpcom/threads/SchedulerGroup.h @@ -7,15 +7,8 @@ #ifndef mozilla_SchedulerGroup_h #define mozilla_SchedulerGroup_h -#include "mozilla/RefPtr.h" -#include "mozilla/TaskCategory.h" -#include "nsCOMPtr.h" -#include "nsID.h" -#include "nsIRunnable.h" -#include "nsISupports.h" -#include "nsStringFwd.h" -#include "nsThreadUtils.h" #include "nscore.h" +#include "mozilla/AlreadyAddRefed.h" class nsIEventTarget; class nsIRunnable; @@ -25,8 +18,7 @@ namespace mozilla { class SchedulerGroup { public: - static nsresult Dispatch(TaskCategory aCategory, - already_AddRefed&& aRunnable); + static nsresult Dispatch(already_AddRefed&& aRunnable); }; } // namespace mozilla diff --git a/xpcom/threads/TaskCategory.h b/xpcom/threads/TaskCategory.h deleted file mode 100644 index 8f189c873728..000000000000 --- a/xpcom/threads/TaskCategory.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_TaskCategory_h -#define mozilla_TaskCategory_h - -namespace mozilla { - -// The different kinds of tasks we can dispatch to a SystemGroup, TabGroup, or -// DocGroup. -enum class TaskCategory { - // User input (clicks, keypresses, etc.) - UI, - - // Data from the network - Network, - - // setTimeout, setInterval - Timer, - - // Runnables posted from a worker to the main thread - Worker, - - // requestIdleCallback - IdleCallback, - - // Vsync notifications - RefreshDriver, - - // GC/CC-related tasks - GarbageCollection, - - // Most DOM events (postMessage, media, plugins) - Other, - - // Runnables related to Performance Counting - Performance, - - Count -}; - -} // namespace mozilla - -#endif // mozilla_TaskCategory_h diff --git a/xpcom/threads/moz.build b/xpcom/threads/moz.build index 285db3a34575..741d037c235b 100644 --- a/xpcom/threads/moz.build +++ b/xpcom/threads/moz.build @@ -72,7 +72,6 @@ EXPORTS.mozilla += [ "StateWatching.h", "SynchronizedEventQueue.h", "SyncRunnable.h", - "TaskCategory.h", "TaskController.h", "TaskDispatcher.h", "TaskQueue.h", diff --git a/xpcom/threads/nsThreadPool.cpp b/xpcom/threads/nsThreadPool.cpp index 362e18f5a7f3..fd7fad5f8e6a 100644 --- a/xpcom/threads/nsThreadPool.cpp +++ b/xpcom/threads/nsThreadPool.cpp @@ -170,10 +170,8 @@ void nsThreadPool::ShutdownThread(nsIThread* aThread) { // shutdown requires this thread have an event loop (and it may not, see bug // 10204784). The simplest way to cover all cases is to asynchronously // shutdown aThread from the main thread. - SchedulerGroup::Dispatch( - TaskCategory::Other, - NewRunnableMethod("nsIThread::AsyncShutdown", aThread, - &nsIThread::AsyncShutdown)); + SchedulerGroup::Dispatch(NewRunnableMethod( + "nsIThread::AsyncShutdown", aThread, &nsIThread::AsyncShutdown)); } NS_IMETHODIMP