Title: [271493] trunk/Source
Revision
271493
Author
[email protected]
Date
2021-01-14 10:44:13 -0800 (Thu, 14 Jan 2021)

Log Message

Removed most uses of dispatch_async(dispatch_get_main_queue(), ...)
https://bugs.webkit.org/show_bug.cgi?id=220066

Reviewed by Antti Koivisto.

dispatch_async has two downsides:

(1) Its order is undefined (and in practice highly variable) relative to
other WebKit operations. This sometimes causes flakiness.

(2) It doesn't honor the RunLoop first paint optimization.

We can use RunLoop::dispatch() instead.

Source/WebCore:

* accessibility/mac/WebAccessibilityObjectWrapperMac.mm:
(-[WebAccessibilityObjectWrapper accessibilityPerformPressAction]):
(-[WebAccessibilityObjectWrapper accessibilityPerformIncrementAction]):
(-[WebAccessibilityObjectWrapper accessibilityPerformDecrementAction]):
* platform/audio/cocoa/AudioSampleDataSource.mm:
(WebCore::AudioSampleDataSource::setupConverter):
(WebCore::AudioSampleDataSource::pushSamplesInternal):
(WebCore::AudioSampleDataSource::pullSamplesInternal):
* platform/audio/ios/MediaSessionHelperIOS.mm:
(-[WebMediaSessionHelper initWithCallback:]):
(-[WebMediaSessionHelper dealloc]):
* platform/cocoa/ContentFilterUnblockHandlerCocoa.mm:
(WebCore::ContentFilterUnblockHandler::requestUnblockAsync const):
(WebCore::dispatchToMainThread): Deleted.
* platform/cocoa/PowerSourceNotifier.mm:
(WebCore::PowerSourceNotifier::PowerSourceNotifier):
* platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm:
(WebCore::MediaPlayerPrivateAVFoundationObjC::setAVPlayerItem):
* platform/graphics/ca/cocoa/PlatformCALayerCocoa.mm:
(WebCore::PlatformCALayerCocoa::clone const):
(WebCore::PlatformCALayer::setBoundsOnMainThread):
(WebCore::PlatformCALayer::setPositionOnMainThread):
(WebCore::PlatformCALayer::setAnchorPointOnMainThread):
* platform/graphics/cocoa/WebCoreDecompressionSession.mm:
(WebCore::WebCoreDecompressionSession::maybeBecomeReadyForMoreMediaData):
(WebCore::WebCoreDecompressionSession::enqueueDecodedSample):
(WebCore::WebCoreDecompressionSession::requestMediaDataWhenReady):
(WebCore::WebCoreDecompressionSession::notifyWhenHasAvailableVideoFrame):
* platform/ios/VideoFullscreenInterfaceAVKit.mm:
(-[WebAVPlayerLayer layoutSublayers]):
(VideoFullscreenInterfaceAVKit::finalizeSetup):
(VideoFullscreenInterfaceAVKit::doExitFullscreen):
* platform/ios/WebSQLiteDatabaseTrackerClient.mm:
(WebCore::WebSQLiteDatabaseTrackerClient::willBeginFirstTransaction):
(WebCore::WebSQLiteDatabaseTrackerClient::didFinishLastTransaction):
* platform/ios/WebVideoFullscreenControllerAVKit.mm:
(VideoFullscreenControllerContext::requestUpdateInlineRect):
(VideoFullscreenControllerContext::requestVideoContentLayer):
(VideoFullscreenControllerContext::returnVideoContentLayer):
(VideoFullscreenControllerContext::didSetupFullscreen):
(VideoFullscreenControllerContext::didExitFullscreen):
(VideoFullscreenControllerContext::fullscreenMayReturnToInline):
(VideoFullscreenControllerContext::durationChanged):
(VideoFullscreenControllerContext::currentTimeChanged):
(VideoFullscreenControllerContext::bufferedTimeChanged):
(VideoFullscreenControllerContext::rateChanged):
(VideoFullscreenControllerContext::hasVideoChanged):
(VideoFullscreenControllerContext::videoDimensionsChanged):
(VideoFullscreenControllerContext::seekableRangesChanged):
(VideoFullscreenControllerContext::canPlayFastReverseChanged):
(VideoFullscreenControllerContext::audioMediaSelectionOptionsChanged):
(VideoFullscreenControllerContext::legibleMediaSelectionOptionsChanged):
(VideoFullscreenControllerContext::wirelessVideoPlaybackDisabledChanged):
(VideoFullscreenControllerContext::mutedChanged):
(VideoFullscreenControllerContext::volumeChanged):
(VideoFullscreenControllerContext::setUpFullscreen):
(VideoFullscreenControllerContext::exitFullscreen):
* platform/ios/wak/WebCoreThread.mm:
(MainThreadAdoptAndRelease):
(WebThreadPostNotification):
* platform/mac/VideoFullscreenInterfaceMac.mm:
(WebCore::VideoFullscreenInterfaceMac::setupFullscreen):
* platform/mediastream/mac/AVCaptureDeviceManager.mm:
(-[WebCoreAVCaptureDeviceManagerObserver deviceConnectedDidChange:]):

Source/WebKit:

* Platform/cocoa/WKPaymentAuthorizationDelegate.mm:
(-[WKPaymentAuthorizationDelegate _didRequestMerchantSession:]):
* Shared/Cocoa/DefaultWebBrowserChecks.mm:
(WebKit::determineITPState):
* UIProcess/API/C/mac/WKContextPrivateMac.mm:
(WKContextGetInfoForInstalledPlugIns):
* UIProcess/API/Cocoa/NSAttributedString.mm:
(+[NSAttributedString _loadFromHTMLWithOptions:contentLoader:completionHandler:]):
* UIProcess/API/Cocoa/WKBrowsingContextController.mm:
(+[WKBrowsingContextController registerSchemeForCustomProtocol:]):
(+[WKBrowsingContextController unregisterSchemeForCustomProtocol:]):
* UIProcess/API/Cocoa/WKWebView.mm:
(-[WKWebView _evaluateJavaScript:asAsyncFunction:withSourceURL:withArguments:forceUserGesture:inFrame:inWorld:completionHandler:]):
(-[WKWebView _internalDoAfterNextPresentationUpdate:withoutWaitingForPainting:withoutWaitingForAnimatedResize:]):
* UIProcess/API/Cocoa/WKWebViewTesting.mm:
(-[WKWebView _doAfterNextVisibleContentRectUpdate:]):
* UIProcess/API/ios/WKWebViewIOS.mm:
(-[WKWebView _scheduleVisibleContentRectUpdateAfterScrollInView:]):
(-[WKWebView _updateVisibleContentRects]):
(-[WKWebView _firePresentationUpdateForPendingStableStatePresentationCallbacks]):
(-[WKWebView _doAfterNextStablePresentationUpdate:]):
* UIProcess/Cocoa/AutomationClient.mm:
(WebKit::AutomationClient::requestAutomationSession):
* UIProcess/Cocoa/NavigationState.mm:
(WebKit::tryInterceptNavigation):
* UIProcess/Cocoa/PreferenceObserver.mm:
(-[WKPreferenceObserver preferenceDidChange:key:encodedValue:]):
* UIProcess/Cocoa/WebInspectorPreferenceObserver.mm:
(-[WKWebInspectorPreferenceObserver observeValueForKeyPath:ofObject:change:context:]):
* UIProcess/Cocoa/WebPageProxyCocoa.mm:
(WebKit::WebPageProxy::requestThumbnailWithOperation):
* UIProcess/Cocoa/WebProcessPoolCocoa.mm:
(WebKit::webProcessPoolHighDynamicRangeDidChangeCallback):
* UIProcess/Cocoa/WebViewImpl.mm:
(-[WKDOMPasteMenuDelegate menuDidClose:]):
(WebKit::WebViewImpl::updateWindowAndViewFrames):
(WebKit::WebViewImpl::setTopContentInset):
(WebKit::WebViewImpl::didBecomeEditable):
(WebKit::WebViewImpl::requestCandidatesForSelectionIfNeeded):
(WebKit::WebViewImpl::performDragOperation):
* UIProcess/EndowmentStateTracker.mm:
(WebKit::EndowmentStateTracker::registerMonitorIfNecessary):
* UIProcess/_WKTouchEventGenerator.mm:
(-[_WKTouchEventGenerator _sendHIDEvent:]):
(-[_WKTouchEventGenerator _sendMarkerHIDEventWithCompletionBlock:]):
* UIProcess/ios/ProcessAssertionIOS.mm:
(-[WKProcessAssertionBackgroundTaskManager _updateBackgroundTask]):
(-[WKProcessAssertionBackgroundTaskManager _handleBackgroundTaskExpirationOnMainThread]):
(-[WKRBSAssertionDelegate assertion:didInvalidateWithError:]):
(WebKit::ProcessAssertion::ProcessAssertion):
* UIProcess/ios/WKContentViewInteraction.mm:
(-[WKContentView resignFirstResponderForWebView]):
* UIProcess/ios/WKPDFView.mm:
(-[WKPDFView pdfHostViewControllerExtensionProcessDidCrash:]):
* UIProcess/ios/forms/WKFileUploadPanel.mm:
(-[WKFileUploadPanel imagePickerController:didFinishPickingMediaWithInfo:]):
(-[WKFileUploadPanel imagePickerController:didFinishPickingMultipleMediaWithInfo:]):
* UIProcess/ios/fullscreen/WKFullScreenWindowControllerIOS.mm:
(-[WKFullScreenWindowController placeholderWillMoveToSuperview:]):
* WebProcess/WebPage/RemoteLayerTree/PlatformCALayerRemoteCustom.mm:
(WebKit::PlatformCALayerRemoteCustom::clone const):
* WebProcess/WebPage/RemoteLayerTree/RemoteLayerTreeDrawingArea.mm:
(WebKit::RemoteLayerTreeDrawingArea::updateRendering):
* WebProcess/cocoa/VideoFullscreenManager.mm:
(WebKit::VideoFullscreenManager::requestVideoContentLayer):
(WebKit::VideoFullscreenManager::returnVideoContentLayer):
(WebKit::VideoFullscreenManager::didSetupFullscreen):
(WebKit::VideoFullscreenManager::willExitFullscreen):
(WebKit::VideoFullscreenManager::didEnterFullscreen):
(WebKit::VideoFullscreenManager::didExitFullscreen):
(WebKit::VideoFullscreenManager::didCleanupFullscreen):

Source/WebKitLegacy/ios:

* Misc/WebGeolocationProviderIOS.mm:
(-[WebGeolocationProviderIOS registerWebView:]):
(-[WebGeolocationProviderIOS unregisterWebView:]):
(-[WebGeolocationProviderIOS setEnableHighAccuracy:]):
(-[WebGeolocationProviderIOS initializeGeolocationForWebView:listener:]):
* WebCoreSupport/WebChromeClientIOS.mm:
(WebChromeClientIOS::runOpenPanel):
* WebCoreSupport/WebInspectorClientIOS.mm:
(WebInspectorClient::didSetSearchingForNode):

Source/WebKitLegacy/mac:

* Plugins/npapi.mm:
(NPN_PluginThreadAsyncCall):
* WebCoreSupport/WebEditorClient.mm:
(WebEditorClient::requestCandidatesForSelection):
* WebCoreSupport/WebFrameLoaderClient.mm:
* WebView/WebImmediateActionController.mm:
(-[WebImmediateActionController immediateActionRecognizerWillPrepare:]):
* WebView/WebView.mm:
(+[WebView willEnterBackgroundWithCompletionHandler:]):
(-[_WebSafeAsyncForwarder forwardInvocation:]):
(-[WebView performDragOperation:]):
(-[WebView setEditable:]):

Source/WTF:

* wtf/cocoa/MainThreadCocoa.mm:
(WTF::dispatchAsyncOnMainThreadWithWebThreadLockIfNeeded):
(WTF::callOnWebThreadOrDispatchAsyncOnMainThread):

Modified Paths

Diff

Modified: trunk/Source/WTF/ChangeLog (271492 => 271493)


--- trunk/Source/WTF/ChangeLog	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WTF/ChangeLog	2021-01-14 18:44:13 UTC (rev 271493)
@@ -1,3 +1,23 @@
+2021-01-14  Geoffrey Garen  <[email protected]>
+
+        Removed most uses of dispatch_async(dispatch_get_main_queue(), ...)
+        https://bugs.webkit.org/show_bug.cgi?id=220066
+
+        Reviewed by Antti Koivisto.
+
+        dispatch_async has two downsides:
+
+        (1) Its order is undefined (and in practice highly variable) relative to
+        other WebKit operations. This sometimes causes flakiness.
+
+        (2) It doesn't honor the RunLoop first paint optimization.
+
+        We can use RunLoop::dispatch() instead.
+
+        * wtf/cocoa/MainThreadCocoa.mm:
+        (WTF::dispatchAsyncOnMainThreadWithWebThreadLockIfNeeded):
+        (WTF::callOnWebThreadOrDispatchAsyncOnMainThread):
+
 2021-01-14  Per Arne Vollan  <[email protected]>
 
         [GPUP][iOS] Create sandbox extensions for cache and temp directory

Modified: trunk/Source/WTF/wtf/cocoa/MainThreadCocoa.mm (271492 => 271493)


--- trunk/Source/WTF/wtf/cocoa/MainThreadCocoa.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WTF/wtf/cocoa/MainThreadCocoa.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -34,6 +34,7 @@
 #import <dispatch/dispatch.h>
 #import <stdio.h>
 #import <wtf/Assertions.h>
+#import <wtf/BlockPtr.h>
 #import <wtf/HashSet.h>
 #import <wtf/RetainPtr.h>
 #import <wtf/RunLoop.h>
@@ -73,7 +74,7 @@
 {
 #if USE(WEB_THREAD)
     if (WebCoreWebThreadIsEnabled && WebCoreWebThreadIsEnabled()) {
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([block = makeBlockPtr(block)] {
             WebCoreWebThreadLock();
             block();
         });
@@ -80,7 +81,9 @@
         return;
     }
 #endif
-    dispatch_async(dispatch_get_main_queue(), block);
+    RunLoop::main().dispatch([block = makeBlockPtr(block)] {
+        block();
+    });
 }
 
 void callOnWebThreadOrDispatchAsyncOnMainThread(void (^block)())
@@ -91,7 +94,9 @@
         return;
     }
 #endif
-    dispatch_async(dispatch_get_main_queue(), block);
+    RunLoop::main().dispatch([block = makeBlockPtr(block)] {
+        block();
+    });
 }
 
 #if USE(WEB_THREAD)

Modified: trunk/Source/WebCore/ChangeLog (271492 => 271493)


--- trunk/Source/WebCore/ChangeLog	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/ChangeLog	2021-01-14 18:44:13 UTC (rev 271493)
@@ -1,3 +1,84 @@
+2021-01-14  Geoffrey Garen  <[email protected]>
+
+        Removed most uses of dispatch_async(dispatch_get_main_queue(), ...)
+        https://bugs.webkit.org/show_bug.cgi?id=220066
+
+        Reviewed by Antti Koivisto.
+
+        dispatch_async has two downsides:
+
+        (1) Its order is undefined (and in practice highly variable) relative to
+        other WebKit operations. This sometimes causes flakiness.
+
+        (2) It doesn't honor the RunLoop first paint optimization.
+
+        We can use RunLoop::dispatch() instead.
+
+        * accessibility/mac/WebAccessibilityObjectWrapperMac.mm:
+        (-[WebAccessibilityObjectWrapper accessibilityPerformPressAction]):
+        (-[WebAccessibilityObjectWrapper accessibilityPerformIncrementAction]):
+        (-[WebAccessibilityObjectWrapper accessibilityPerformDecrementAction]):
+        * platform/audio/cocoa/AudioSampleDataSource.mm:
+        (WebCore::AudioSampleDataSource::setupConverter):
+        (WebCore::AudioSampleDataSource::pushSamplesInternal):
+        (WebCore::AudioSampleDataSource::pullSamplesInternal):
+        * platform/audio/ios/MediaSessionHelperIOS.mm:
+        (-[WebMediaSessionHelper initWithCallback:]):
+        (-[WebMediaSessionHelper dealloc]):
+        * platform/cocoa/ContentFilterUnblockHandlerCocoa.mm:
+        (WebCore::ContentFilterUnblockHandler::requestUnblockAsync const):
+        (WebCore::dispatchToMainThread): Deleted.
+        * platform/cocoa/PowerSourceNotifier.mm:
+        (WebCore::PowerSourceNotifier::PowerSourceNotifier):
+        * platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm:
+        (WebCore::MediaPlayerPrivateAVFoundationObjC::setAVPlayerItem):
+        * platform/graphics/ca/cocoa/PlatformCALayerCocoa.mm:
+        (WebCore::PlatformCALayerCocoa::clone const):
+        (WebCore::PlatformCALayer::setBoundsOnMainThread):
+        (WebCore::PlatformCALayer::setPositionOnMainThread):
+        (WebCore::PlatformCALayer::setAnchorPointOnMainThread):
+        * platform/graphics/cocoa/WebCoreDecompressionSession.mm:
+        (WebCore::WebCoreDecompressionSession::maybeBecomeReadyForMoreMediaData):
+        (WebCore::WebCoreDecompressionSession::enqueueDecodedSample):
+        (WebCore::WebCoreDecompressionSession::requestMediaDataWhenReady):
+        (WebCore::WebCoreDecompressionSession::notifyWhenHasAvailableVideoFrame):
+        * platform/ios/VideoFullscreenInterfaceAVKit.mm:
+        (-[WebAVPlayerLayer layoutSublayers]):
+        (VideoFullscreenInterfaceAVKit::finalizeSetup):
+        (VideoFullscreenInterfaceAVKit::doExitFullscreen):
+        * platform/ios/WebSQLiteDatabaseTrackerClient.mm:
+        (WebCore::WebSQLiteDatabaseTrackerClient::willBeginFirstTransaction):
+        (WebCore::WebSQLiteDatabaseTrackerClient::didFinishLastTransaction):
+        * platform/ios/WebVideoFullscreenControllerAVKit.mm:
+        (VideoFullscreenControllerContext::requestUpdateInlineRect):
+        (VideoFullscreenControllerContext::requestVideoContentLayer):
+        (VideoFullscreenControllerContext::returnVideoContentLayer):
+        (VideoFullscreenControllerContext::didSetupFullscreen):
+        (VideoFullscreenControllerContext::didExitFullscreen):
+        (VideoFullscreenControllerContext::fullscreenMayReturnToInline):
+        (VideoFullscreenControllerContext::durationChanged):
+        (VideoFullscreenControllerContext::currentTimeChanged):
+        (VideoFullscreenControllerContext::bufferedTimeChanged):
+        (VideoFullscreenControllerContext::rateChanged):
+        (VideoFullscreenControllerContext::hasVideoChanged):
+        (VideoFullscreenControllerContext::videoDimensionsChanged):
+        (VideoFullscreenControllerContext::seekableRangesChanged):
+        (VideoFullscreenControllerContext::canPlayFastReverseChanged):
+        (VideoFullscreenControllerContext::audioMediaSelectionOptionsChanged):
+        (VideoFullscreenControllerContext::legibleMediaSelectionOptionsChanged):
+        (VideoFullscreenControllerContext::wirelessVideoPlaybackDisabledChanged):
+        (VideoFullscreenControllerContext::mutedChanged):
+        (VideoFullscreenControllerContext::volumeChanged):
+        (VideoFullscreenControllerContext::setUpFullscreen):
+        (VideoFullscreenControllerContext::exitFullscreen):
+        * platform/ios/wak/WebCoreThread.mm:
+        (MainThreadAdoptAndRelease):
+        (WebThreadPostNotification):
+        * platform/mac/VideoFullscreenInterfaceMac.mm:
+        (WebCore::VideoFullscreenInterfaceMac::setupFullscreen):
+        * platform/mediastream/mac/AVCaptureDeviceManager.mm:
+        (-[WebCoreAVCaptureDeviceManagerObserver deviceConnectedDidChange:]):
+
 2021-01-14  Youenn Fablet  <[email protected]>
 
         MediaSessionManager should update its state as soon as an audio capture track is ended

Modified: trunk/Source/WebCore/accessibility/mac/WebAccessibilityObjectWrapperMac.mm (271492 => 271493)


--- trunk/Source/WebCore/accessibility/mac/WebAccessibilityObjectWrapperMac.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/accessibility/mac/WebAccessibilityObjectWrapperMac.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -3180,7 +3180,7 @@
 {
     // In case anything we do by performing the press action causes an alert or other modal
     // behaviors, we need to return now, so that VoiceOver doesn't hang indefinitely.
-    dispatch_async(dispatch_get_main_queue(), ^ {
+    RunLoop::main().dispatch([self, protectedSelf = retainPtr(self)] {
         [self _accessibilityPerformPressAction];
     });
 }
@@ -3199,7 +3199,7 @@
 
 - (void)accessibilityPerformIncrementAction
 {
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([self, protectedSelf = retainPtr(self)] {
         [self _accessibilityPerformIncrementAction];
     });
 }
@@ -3218,7 +3218,7 @@
 
 - (void)accessibilityPerformDecrementAction
 {
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([self, protectedSelf = retainPtr(self)] {
         [self _accessibilityPerformDecrementAction];
     });
 }

Modified: trunk/Source/WebCore/platform/audio/cocoa/AudioSampleDataSource.mm (271492 => 271493)


--- trunk/Source/WebCore/platform/audio/cocoa/AudioSampleDataSource.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/platform/audio/cocoa/AudioSampleDataSource.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -36,6 +36,7 @@
 #import <mutex>
 #import <pal/avfoundation/MediaTimeAVFoundation.h>
 #import <syslog.h>
+#import <wtf/RunLoop.h>
 #import <wtf/StringPrintStream.h>
 
 #import <pal/cf/CoreMediaSoftLink.h>
@@ -87,7 +88,7 @@
 
     OSStatus err = AudioConverterNew(&m_inputDescription->streamDescription(), &m_outputDescription->streamDescription(), &m_converter);
     if (err) {
-        dispatch_async(dispatch_get_main_queue(), [this, protectedThis = makeRefPtr(*this), err] {
+        RunLoop::main().dispatch([this, protectedThis = makeRefPtr(*this), err] {
             ERROR_LOG("AudioConverterNew returned error ", err);
         });
     }
@@ -161,7 +162,7 @@
 
     if (m_inputSampleOffset == MediaTime::invalidTime()) {
         m_inputSampleOffset = MediaTime(1 - sampleTime.timeValue(), sampleTime.timeScale());
-        dispatch_async(dispatch_get_main_queue(), [logIdentifier = LOGIDENTIFIER, inputSampleOffset = m_inputSampleOffset.timeValue(), maximumSampleCount = m_maximumSampleCount, this, protectedThis = makeRefPtr(*this)] {
+        RunLoop::main().dispatch([logIdentifier = LOGIDENTIFIER, inputSampleOffset = m_inputSampleOffset.timeValue(), maximumSampleCount = m_maximumSampleCount, this, protectedThis = makeRefPtr(*this)] {
             ALWAYS_LOG(logIdentifier, "input sample offset is ", inputSampleOffset, ", maximumSampleCount is ", maximumSampleCount);
         });
     }
@@ -238,7 +239,7 @@
 
         m_outputSampleOffset = (endFrame - sampleCount) - timeStamp;
         m_outputSampleOffset -= computeOffsetDelay(m_outputDescription->sampleRate(), m_lastPushedSampleCount);
-        dispatch_async(dispatch_get_main_queue(), [logIdentifier = LOGIDENTIFIER, outputSampleOffset = m_outputSampleOffset, this, protectedThis = makeRefPtr(*this)] {
+        RunLoop::main().dispatch([logIdentifier = LOGIDENTIFIER, outputSampleOffset = m_outputSampleOffset, this, protectedThis = makeRefPtr(*this)] {
             ALWAYS_LOG(logIdentifier, "setting new offset to ", outputSampleOffset);
         });
     }
@@ -246,7 +247,7 @@
     timeStamp += m_outputSampleOffset;
 
     if (timeStamp < startFrame || timeStamp + sampleCount > endFrame) {
-        dispatch_async(dispatch_get_main_queue(), [logIdentifier = LOGIDENTIFIER, timeStamp, startFrame, endFrame, sampleCount, outputSampleOffset = m_outputSampleOffset, this, protectedThis = makeRefPtr(*this)] {
+        RunLoop::main().dispatch([logIdentifier = LOGIDENTIFIER, timeStamp, startFrame, endFrame, sampleCount, outputSampleOffset = m_outputSampleOffset, this, protectedThis = makeRefPtr(*this)] {
             ERROR_LOG(logIdentifier, "not enough data, sample ", timeStamp, " with offset ", outputSampleOffset, ", trying to get ", sampleCount, " samples, but not completely in range [", startFrame, " .. ", endFrame, "]");
         });
 
@@ -259,7 +260,7 @@
         } else {
             // We are too close from endFrame, let's wait for more data to be pushed.
             m_outputSampleOffset -= sampleCount;
-            dispatch_async(dispatch_get_main_queue(), [logIdentifier = LOGIDENTIFIER, outputSampleOffset = m_outputSampleOffset, this, protectedThis = makeRefPtr(*this)] {
+            RunLoop::main().dispatch([logIdentifier = LOGIDENTIFIER, outputSampleOffset = m_outputSampleOffset, this, protectedThis = makeRefPtr(*this)] {
                 ALWAYS_LOG(logIdentifier, "updating offset to ", outputSampleOffset);
             });
         }

Modified: trunk/Source/WebCore/platform/audio/ios/MediaSessionHelperIOS.mm (271492 => 271493)


--- trunk/Source/WebCore/platform/audio/ios/MediaSessionHelperIOS.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/platform/audio/ios/MediaSessionHelperIOS.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -39,6 +39,7 @@
 #import <wtf/BlockObjCExceptions.h>
 #import <wtf/MainThread.h>
 #import <wtf/RetainPtr.h>
+#import <wtf/RunLoop.h>
 #import <wtf/UniqueRef.h>
 
 #import <pal/cocoa/AVFoundationSoftLink.h>
@@ -362,7 +363,7 @@
 #endif
 
     // Now playing won't work unless we turn on the delivery of remote control events.
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([] {
         BEGIN_BLOCK_OBJC_EXCEPTIONS
         [[PAL::getUIApplicationClass() sharedApplication] beginReceivingRemoteControlEvents];
         END_BLOCK_OBJC_EXCEPTIONS
@@ -377,7 +378,7 @@
 
 #if !PLATFORM(WATCHOS)
     if (!pthread_main_np()) {
-        dispatch_async(dispatch_get_main_queue(), [routeDetector = WTFMove(_routeDetector)] () mutable {
+        RunLoop::main().dispatch([routeDetector = WTFMove(_routeDetector)] () mutable {
             LOG(Media, "safelyTearDown - dipatched to UI thread.");
             BEGIN_BLOCK_OBJC_EXCEPTIONS
             routeDetector.get().routeDetectionEnabled = NO;

Modified: trunk/Source/WebCore/platform/cocoa/ContentFilterUnblockHandlerCocoa.mm (271492 => 271493)


--- trunk/Source/WebCore/platform/cocoa/ContentFilterUnblockHandlerCocoa.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/platform/cocoa/ContentFilterUnblockHandlerCocoa.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -137,23 +137,12 @@
     return isUnblockRequest;
 }
 
-static inline void dispatchToMainThread(void (^block)())
-{
-    dispatch_async(dispatch_get_main_queue(), ^{
-#if PLATFORM(IOS_FAMILY)
-        WebThreadRun(block);
-#else
-        block();
-#endif
-    });
-}
-
 void ContentFilterUnblockHandler::requestUnblockAsync(DecisionHandlerFunction decisionHandler) const
 {
 #if HAVE(PARENTAL_CONTROLS_WITH_UNBLOCK_HANDLER)
     if (m_webFilterEvaluator) {
         [m_webFilterEvaluator unblockWithCompletion:[decisionHandler](BOOL unblocked, NSError *) {
-            dispatchToMainThread([decisionHandler, unblocked] {
+            callOnMainThread([decisionHandler, unblocked] {
                 LOG(ContentFiltering, "WebFilterEvaluator %s the unblock request.\n", unblocked ? "allowed" : "did not allow");
                 decisionHandler(unblocked);
             });
@@ -164,7 +153,7 @@
 
     if (m_unblockRequester) {
         m_unblockRequester([decisionHandler](bool unblocked) {
-            dispatchToMainThread([decisionHandler, unblocked] {
+            callOnMainThread([decisionHandler, unblocked] {
                 decisionHandler(unblocked);
             });
         });

Modified: trunk/Source/WebCore/platform/cocoa/PowerSourceNotifier.mm (271492 => 271493)


--- trunk/Source/WebCore/platform/cocoa/PowerSourceNotifier.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/platform/cocoa/PowerSourceNotifier.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -29,6 +29,7 @@
 #import "SystemBattery.h"
 #import <notify.h>
 #import <pal/spi/cocoa/IOPSLibSPI.h>
+#import <wtf/RunLoop.h>
 
 namespace WebCore {
 
@@ -45,7 +46,7 @@
 
     // If the current value of systemHasAC() is uncached, force a notification.
     if (!cachedSystemHasAC()) {
-        dispatch_async(dispatch_get_main_queue(), [weakThis = makeWeakPtr(*this)] {
+        RunLoop::main().dispatch([weakThis = makeWeakPtr(*this)] {
             if (weakThis)
                 weakThis->notifyPowerSourceChanged();
         });

Modified: trunk/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm (271492 => 271493)


--- trunk/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -942,7 +942,7 @@
 
     RetainPtr<AVPlayer> strongPlayer = m_avPlayer.get();
     RetainPtr<AVPlayerItem> strongItem = item;
-    dispatch_async(dispatch_get_main_queue(), [strongPlayer, strongItem] {
+    RunLoop::main().dispatch([strongPlayer, strongItem] {
         [strongPlayer replaceCurrentItemWithPlayerItem:strongItem.get()];
     });
 }

Modified: trunk/Source/WebCore/platform/graphics/ca/cocoa/PlatformCALayerCocoa.mm (271492 => 271493)


--- trunk/Source/WebCore/platform/graphics/ca/cocoa/PlatformCALayerCocoa.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/platform/graphics/ca/cocoa/PlatformCALayerCocoa.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -372,7 +372,7 @@
         AVPlayerLayer *sourcePlayerLayer = avPlayerLayer();
         ASSERT(sourcePlayerLayer);
 
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([destinationPlayerLayer = retainPtr(destinationPlayerLayer), sourcePlayerLayer = retainPtr(sourcePlayerLayer)] {
             [destinationPlayerLayer setPlayer:[sourcePlayerLayer player]];
         });
     }
@@ -1090,8 +1090,7 @@
 
 void PlatformCALayer::setBoundsOnMainThread(CGRect bounds)
 {
-    CALayer *layer = m_layer.get();
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([layer = m_layer, bounds] {
         BEGIN_BLOCK_OBJC_EXCEPTIONS
         [layer setBounds:bounds];
         END_BLOCK_OBJC_EXCEPTIONS
@@ -1100,8 +1099,7 @@
 
 void PlatformCALayer::setPositionOnMainThread(CGPoint position)
 {
-    CALayer *layer = m_layer.get();
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([layer = m_layer, position] {
         BEGIN_BLOCK_OBJC_EXCEPTIONS
         [layer setPosition:position];
         END_BLOCK_OBJC_EXCEPTIONS
@@ -1110,8 +1108,7 @@
 
 void PlatformCALayer::setAnchorPointOnMainThread(FloatPoint3D value)
 {
-    CALayer *layer = m_layer.get();
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([layer = m_layer, value] {
         BEGIN_BLOCK_OBJC_EXCEPTIONS
         [layer setAnchorPoint:CGPointMake(value.x(), value.y())];
         [layer setAnchorPointZ:value.z()];

Modified: trunk/Source/WebCore/platform/graphics/cocoa/WebCoreDecompressionSession.mm (271492 => 271493)


--- trunk/Source/WebCore/platform/graphics/cocoa/WebCoreDecompressionSession.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/platform/graphics/cocoa/WebCoreDecompressionSession.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -101,7 +101,7 @@
     }
 
     RefPtr<WebCoreDecompressionSession> protectedThis { this };
-    dispatch_async(dispatch_get_main_queue(), [protectedThis] {
+    RunLoop::main().dispatch([protectedThis] {
         if (protectedThis->m_notificationCallback)
             protectedThis->m_notificationCallback();
     });
@@ -419,7 +419,7 @@
     if (!shouldNotify)
         return;
 
-    dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), callback = WTFMove(m_hasAvailableFrameCallback)] {
+    RunLoop::main().dispatch([protectedThis = makeRefPtr(this), callback = WTFMove(m_hasAvailableFrameCallback)] {
         callback();
     });
 }
@@ -437,7 +437,7 @@
 
     if (notificationCallback && isReadyForMoreMediaData()) {
         RefPtr<WebCoreDecompressionSession> protectedThis { this };
-        dispatch_async(dispatch_get_main_queue(), [protectedThis] {
+        RunLoop::main().dispatch([protectedThis] {
             if (protectedThis->m_notificationCallback)
                 protectedThis->m_notificationCallback();
         });
@@ -453,7 +453,7 @@
 void WebCoreDecompressionSession::notifyWhenHasAvailableVideoFrame(std::function<void()> callback)
 {
     if (callback && m_producerQueue && !CMBufferQueueIsEmpty(m_producerQueue.get())) {
-        dispatch_async(dispatch_get_main_queue(), [callback] {
+        RunLoop::main().dispatch([callback] {
             callback();
         });
         return;

Modified: trunk/Source/WebCore/platform/ios/VideoFullscreenInterfaceAVKit.mm (271492 => 271493)


--- trunk/Source/WebCore/platform/ios/VideoFullscreenInterfaceAVKit.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/platform/ios/VideoFullscreenInterfaceAVKit.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -317,7 +317,7 @@
     [view setTransform:transform];
 
     NSTimeInterval animationDuration = [CATransaction animationDuration];
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([self, strongSelf = retainPtr(self), targetVideoFrame, animationDuration] {
         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(resolveBounds) object:nil];
 
         _videoSublayerFrame = targetVideoFrame;
@@ -1419,7 +1419,7 @@
 
 void VideoFullscreenInterfaceAVKit::finalizeSetup()
 {
-    dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), this] {
+    RunLoop::main().dispatch([protectedThis = makeRefPtr(this), this] {
         if (m_fullscreenChangeObserver) {
             if (!m_hasVideoContentLayer && m_targetMode.hasVideo()) {
                 m_finalizeSetupNeedsVideoContentLayer = true;
@@ -1539,7 +1539,7 @@
 
     m_standby = false;
 
-    dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), this] {
+    RunLoop::main().dispatch([protectedThis = makeRefPtr(this), this] {
         if (m_fullscreenChangeObserver)
             m_fullscreenChangeObserver->didExitFullscreen();
         m_changingStandbyOnly = false;

Modified: trunk/Source/WebCore/platform/ios/WebSQLiteDatabaseTrackerClient.mm (271492 => 271493)


--- trunk/Source/WebCore/platform/ios/WebSQLiteDatabaseTrackerClient.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/platform/ios/WebSQLiteDatabaseTrackerClient.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -61,7 +61,7 @@
 
 void WebSQLiteDatabaseTrackerClient::willBeginFirstTransaction()
 {
-    dispatch_async(dispatch_get_main_queue(), [this] {
+    RunLoop::main().dispatch([this] {
         m_hysteresis.start();
     });
 }
@@ -68,7 +68,7 @@
 
 void WebSQLiteDatabaseTrackerClient::didFinishLastTransaction()
 {
-    dispatch_async(dispatch_get_main_queue(), [this] {
+    RunLoop::main().dispatch([this] {
         m_hysteresis.stop();
     });
 }

Modified: trunk/Source/WebCore/platform/ios/WebVideoFullscreenControllerAVKit.mm (271492 => 271493)


--- trunk/Source/WebCore/platform/ios/WebVideoFullscreenControllerAVKit.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/platform/ios/WebVideoFullscreenControllerAVKit.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -242,7 +242,7 @@
     ASSERT(isUIThread());
     WebThreadRun([protectedThis = makeRefPtr(this), this] () mutable {
         IntRect clientRect = elementRectInWindow(m_videoElement.get());
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = WTFMove(protectedThis), this, clientRect] {
+        RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), this, clientRect] {
             m_interface->setInlineRect(clientRect, clientRect != IntRect(0, 0, 0, 0));
         });
     });
@@ -258,7 +258,7 @@
     WebThreadRun([protectedThis = makeRefPtr(this), this, videoFullscreenLayer = retainPtr([m_videoFullscreenView layer])] () mutable {
         [videoFullscreenLayer setBackgroundColor:cachedCGColor(WebCore::Color::transparentBlack)];
         m_fullscreenModel->setVideoFullscreenLayer(videoFullscreenLayer.get(), [protectedThis = WTFMove(protectedThis), this] () mutable {
-            dispatch_async(dispatch_get_main_queue(), [protectedThis = WTFMove(protectedThis), this] {
+            RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), this] {
                 if (!m_interface)
                     return;
 
@@ -278,7 +278,7 @@
     WebThreadRun([protectedThis = makeRefPtr(this), this, videoFullscreenLayer = retainPtr([m_videoFullscreenView layer])] () mutable {
         [videoFullscreenLayer setBackgroundColor:cachedCGColor(WebCore::Color::transparentBlack)];
         m_fullscreenModel->setVideoFullscreenLayer(nil, [protectedThis = WTFMove(protectedThis), this] () mutable {
-            dispatch_async(dispatch_get_main_queue(), [protectedThis = WTFMove(protectedThis), this] {
+            RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), this] {
                 if (!m_interface)
                     return;
 
@@ -295,7 +295,7 @@
 {
     ASSERT(isUIThread());
 #if PLATFORM(IOS_FAMILY)
-    dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), this] {
+    RunLoop::main().dispatch([protectedThis = makeRefPtr(this), this] {
         m_interface->enterFullscreen();
     });
 #else
@@ -302,7 +302,7 @@
     WebThreadRun([protectedThis = makeRefPtr(this), this, videoFullscreenLayer = retainPtr([m_videoFullscreenView layer])] () mutable {
         [videoFullscreenLayer setBackgroundColor:cachedCGColor(WebCore::Color::transparentBlack)];
         m_fullscreenModel->setVideoFullscreenLayer(videoFullscreenLayer.get(), [protectedThis = WTFMove(protectedThis), this] () mutable {
-            dispatch_async(dispatch_get_main_queue(), [protectedThis = WTFMove(protectedThis), this] {
+            RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), this] {
                 m_interface->enterFullscreen();
             });
         });
@@ -324,13 +324,13 @@
 {
     ASSERT(isUIThread());
 #if PLATFORM(IOS_FAMILY)
-    dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), this] {
+    RunLoop::main().dispatch([protectedThis = makeRefPtr(this), this] {
         m_interface->cleanupFullscreen();
     });
 #else
     WebThreadRun([protectedThis = makeRefPtr(this), this] () mutable {
         m_fullscreenModel->setVideoFullscreenLayer(nil, [protectedThis = WTFMove(protectedThis), this] () mutable {
-            dispatch_async(dispatch_get_main_queue(), [protectedThis = WTFMove(protectedThis), this] {
+            RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), this] {
                 m_interface->cleanupFullscreen();
             });
         });
@@ -364,7 +364,7 @@
     ASSERT(isUIThread());
     WebThreadRun([protectedThis = makeRefPtr(this), this] () mutable {
         IntRect clientRect = elementRectInWindow(m_videoElement.get());
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = WTFMove(protectedThis), this, clientRect] {
+        RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), this, clientRect] {
             m_interface->preparedToReturnToInline(true, clientRect);
         });
     });
@@ -375,7 +375,7 @@
 void VideoFullscreenControllerContext::durationChanged(double duration)
 {
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), duration] {
+        RunLoop::main().dispatch([protectedThis = makeRefPtr(this), duration] {
             protectedThis->durationChanged(duration);
         });
         return;
@@ -388,7 +388,7 @@
 void VideoFullscreenControllerContext::currentTimeChanged(double currentTime, double anchorTime)
 {
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), currentTime, anchorTime] {
+        RunLoop::main().dispatch([protectedThis = makeRefPtr(this), currentTime, anchorTime] {
             protectedThis->currentTimeChanged(currentTime, anchorTime);
         });
         return;
@@ -401,7 +401,7 @@
 void VideoFullscreenControllerContext::bufferedTimeChanged(double bufferedTime)
 {
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), bufferedTime] {
+        RunLoop::main().dispatch([protectedThis = makeRefPtr(this), bufferedTime] {
             protectedThis->bufferedTimeChanged(bufferedTime);
         });
         return;
@@ -414,7 +414,7 @@
 void VideoFullscreenControllerContext::rateChanged(bool isPlaying, float playbackRate)
 {
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), isPlaying, playbackRate] {
+        RunLoop::main().dispatch([protectedThis = makeRefPtr(this), isPlaying, playbackRate] {
             protectedThis->rateChanged(isPlaying, playbackRate);
         });
         return;
@@ -427,7 +427,7 @@
 void VideoFullscreenControllerContext::hasVideoChanged(bool hasVideo)
 {
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), hasVideo] {
+        RunLoop::main().dispatch([protectedThis = makeRefPtr(this), hasVideo] {
             protectedThis->hasVideoChanged(hasVideo);
         });
         return;
@@ -440,7 +440,7 @@
 void VideoFullscreenControllerContext::videoDimensionsChanged(const FloatSize& videoDimensions)
 {
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), videoDimensions = videoDimensions] {
+        RunLoop::main().dispatch([protectedThis = makeRefPtr(this), videoDimensions = videoDimensions] {
             protectedThis->videoDimensionsChanged(videoDimensions);
         });
         return;
@@ -453,7 +453,7 @@
 void VideoFullscreenControllerContext::seekableRangesChanged(const TimeRanges& timeRanges, double lastModifiedTime, double liveUpdateInterval)
 {
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), platformTimeRanges = timeRanges.ranges(), lastModifiedTime, liveUpdateInterval] {
+        RunLoop::main().dispatch([protectedThis = makeRefPtr(this), platformTimeRanges = timeRanges.ranges(), lastModifiedTime, liveUpdateInterval] {
             protectedThis->seekableRangesChanged(TimeRanges::create(platformTimeRanges), lastModifiedTime, liveUpdateInterval);
         });
         return;
@@ -466,7 +466,7 @@
 void VideoFullscreenControllerContext::canPlayFastReverseChanged(bool canPlayFastReverse)
 {
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), canPlayFastReverse] {
+        RunLoop::main().dispatch([protectedThis = makeRefPtr(this), canPlayFastReverse] {
             protectedThis->canPlayFastReverseChanged(canPlayFastReverse);
         });
         return;
@@ -488,7 +488,7 @@
 void VideoFullscreenControllerContext::audioMediaSelectionOptionsChanged(const Vector<MediaSelectionOption>& options, uint64_t selectedIndex)
 {
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), options = isolatedCopy(options), selectedIndex] {
+        RunLoop::main().dispatch([protectedThis = makeRefPtr(this), options = isolatedCopy(options), selectedIndex] {
             protectedThis->audioMediaSelectionOptionsChanged(options, selectedIndex);
         });
         return;
@@ -501,7 +501,7 @@
 void VideoFullscreenControllerContext::legibleMediaSelectionOptionsChanged(const Vector<MediaSelectionOption>& options, uint64_t selectedIndex)
 {
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), options = isolatedCopy(options), selectedIndex] {
+        RunLoop::main().dispatch([protectedThis = makeRefPtr(this), options = isolatedCopy(options), selectedIndex] {
             protectedThis->legibleMediaSelectionOptionsChanged(options, selectedIndex);
         });
         return;
@@ -528,7 +528,7 @@
 void VideoFullscreenControllerContext::wirelessVideoPlaybackDisabledChanged(bool disabled)
 {
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), disabled] {
+        RunLoop::main().dispatch([protectedThis = makeRefPtr(this), disabled] {
             protectedThis->wirelessVideoPlaybackDisabledChanged(disabled);
         });
         return;
@@ -541,7 +541,7 @@
 void VideoFullscreenControllerContext::mutedChanged(bool muted)
 {
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), muted] {
+        RunLoop::main().dispatch([protectedThis = makeRefPtr(this), muted] {
             protectedThis->mutedChanged(muted);
         });
         return;
@@ -554,7 +554,7 @@
 void VideoFullscreenControllerContext::volumeChanged(double volume)
 {
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), volume] {
+        RunLoop::main().dispatch([protectedThis = makeRefPtr(this), volume] {
             protectedThis->volumeChanged(volume);
         });
         return;
@@ -983,7 +983,7 @@
 
     FloatSize videoDimensions = { (float)videoElement.videoWidth(), (float)videoElement.videoHeight() };
 
-    dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), this, videoElementClientRect, videoDimensions, viewRef, mode, allowsPictureInPicture] {
+    RunLoop::main().dispatch([protectedThis = makeRefPtr(this), this, videoElementClientRect, videoDimensions, viewRef, mode, allowsPictureInPicture] {
         ASSERT(isUIThread());
         WebThreadLock();
 
@@ -1002,7 +1002,7 @@
 {
     ASSERT(WebThreadIsCurrent() || isMainThread());
     IntRect clientRect = elementRectInWindow(m_videoElement.get());
-    dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), this, clientRect] {
+    RunLoop::main().dispatch([protectedThis = makeRefPtr(this), this, clientRect] {
         ASSERT(isUIThread());
         m_interface->exitFullscreen(clientRect);
     });

Modified: trunk/Source/WebCore/platform/ios/wak/WebCoreThread.mm (271492 => 271493)


--- trunk/Source/WebCore/platform/ios/wak/WebCoreThread.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/platform/ios/wak/WebCoreThread.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -289,9 +289,8 @@
 #endif
     // We own obj at this point, so we don't need the block to implicitly
     // retain it.
-    __block id objNotRetained = obj;
-    dispatch_async(dispatch_get_main_queue(), ^{
-        [objNotRetained release];
+    RunLoop::main().dispatch([obj] {
+        [obj release];
     });
 }
 
@@ -437,8 +436,8 @@
     if (pthread_main_np())
         [[NSNotificationCenter defaultCenter] postNotificationName:name object:object userInfo:userInfo];
     else {
-        dispatch_async(dispatch_get_main_queue(), ^ {
-            [[NSNotificationCenter defaultCenter] postNotificationName:name object:object userInfo:userInfo];
+        RunLoop::main().dispatch([name = retainPtr(name), object = retainPtr(object), userInfo = retainPtr(userInfo)] {
+            [[NSNotificationCenter defaultCenter] postNotificationName:name.get() object:object.get() userInfo:userInfo.get()];
         });
     }
 }

Modified: trunk/Source/WebCore/platform/mac/VideoFullscreenInterfaceMac.mm (271492 => 271493)


--- trunk/Source/WebCore/platform/mac/VideoFullscreenInterfaceMac.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/platform/mac/VideoFullscreenInterfaceMac.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -456,7 +456,7 @@
 
     [videoFullscreenInterfaceObjC() setUpPIPForVideoView:&layerHostedView withFrame:(NSRect)initialRect inWindow:parentWindow];
 
-    dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), this] {
+    RunLoop::main().dispatch([protectedThis = makeRefPtr(this), this] {
         if (m_fullscreenChangeObserver)
             m_fullscreenChangeObserver->didSetupFullscreen();
     });

Modified: trunk/Source/WebCore/platform/mediastream/mac/AVCaptureDeviceManager.mm (271492 => 271493)


--- trunk/Source/WebCore/platform/mediastream/mac/AVCaptureDeviceManager.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebCore/platform/mediastream/mac/AVCaptureDeviceManager.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -260,7 +260,7 @@
     if (!m_callback)
         return;
 
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([self, protectedSelf = retainPtr(self)] {
         if (m_callback)
             m_callback->refreshCaptureDevices();
     });

Modified: trunk/Source/WebKit/ChangeLog (271492 => 271493)


--- trunk/Source/WebKit/ChangeLog	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/ChangeLog	2021-01-14 18:44:13 UTC (rev 271493)
@@ -1,3 +1,91 @@
+2021-01-14  Geoffrey Garen  <[email protected]>
+
+        Removed most uses of dispatch_async(dispatch_get_main_queue(), ...)
+        https://bugs.webkit.org/show_bug.cgi?id=220066
+
+        Reviewed by Antti Koivisto.
+
+        dispatch_async has two downsides:
+
+        (1) Its order is undefined (and in practice highly variable) relative to
+        other WebKit operations. This sometimes causes flakiness.
+
+        (2) It doesn't honor the RunLoop first paint optimization.
+
+        We can use RunLoop::dispatch() instead.
+
+        * Platform/cocoa/WKPaymentAuthorizationDelegate.mm:
+        (-[WKPaymentAuthorizationDelegate _didRequestMerchantSession:]):
+        * Shared/Cocoa/DefaultWebBrowserChecks.mm:
+        (WebKit::determineITPState):
+        * UIProcess/API/C/mac/WKContextPrivateMac.mm:
+        (WKContextGetInfoForInstalledPlugIns):
+        * UIProcess/API/Cocoa/NSAttributedString.mm:
+        (+[NSAttributedString _loadFromHTMLWithOptions:contentLoader:completionHandler:]):
+        * UIProcess/API/Cocoa/WKBrowsingContextController.mm:
+        (+[WKBrowsingContextController registerSchemeForCustomProtocol:]):
+        (+[WKBrowsingContextController unregisterSchemeForCustomProtocol:]):
+        * UIProcess/API/Cocoa/WKWebView.mm:
+        (-[WKWebView _evaluateJavaScript:asAsyncFunction:withSourceURL:withArguments:forceUserGesture:inFrame:inWorld:completionHandler:]):
+        (-[WKWebView _internalDoAfterNextPresentationUpdate:withoutWaitingForPainting:withoutWaitingForAnimatedResize:]):
+        * UIProcess/API/Cocoa/WKWebViewTesting.mm:
+        (-[WKWebView _doAfterNextVisibleContentRectUpdate:]):
+        * UIProcess/API/ios/WKWebViewIOS.mm:
+        (-[WKWebView _scheduleVisibleContentRectUpdateAfterScrollInView:]):
+        (-[WKWebView _updateVisibleContentRects]):
+        (-[WKWebView _firePresentationUpdateForPendingStableStatePresentationCallbacks]):
+        (-[WKWebView _doAfterNextStablePresentationUpdate:]):
+        * UIProcess/Cocoa/AutomationClient.mm:
+        (WebKit::AutomationClient::requestAutomationSession):
+        * UIProcess/Cocoa/NavigationState.mm:
+        (WebKit::tryInterceptNavigation):
+        * UIProcess/Cocoa/PreferenceObserver.mm:
+        (-[WKPreferenceObserver preferenceDidChange:key:encodedValue:]):
+        * UIProcess/Cocoa/WebInspectorPreferenceObserver.mm:
+        (-[WKWebInspectorPreferenceObserver observeValueForKeyPath:ofObject:change:context:]):
+        * UIProcess/Cocoa/WebPageProxyCocoa.mm:
+        (WebKit::WebPageProxy::requestThumbnailWithOperation):
+        * UIProcess/Cocoa/WebProcessPoolCocoa.mm:
+        (WebKit::webProcessPoolHighDynamicRangeDidChangeCallback):
+        * UIProcess/Cocoa/WebViewImpl.mm:
+        (-[WKDOMPasteMenuDelegate menuDidClose:]):
+        (WebKit::WebViewImpl::updateWindowAndViewFrames):
+        (WebKit::WebViewImpl::setTopContentInset):
+        (WebKit::WebViewImpl::didBecomeEditable):
+        (WebKit::WebViewImpl::requestCandidatesForSelectionIfNeeded):
+        (WebKit::WebViewImpl::performDragOperation):
+        * UIProcess/EndowmentStateTracker.mm:
+        (WebKit::EndowmentStateTracker::registerMonitorIfNecessary):
+        * UIProcess/_WKTouchEventGenerator.mm:
+        (-[_WKTouchEventGenerator _sendHIDEvent:]):
+        (-[_WKTouchEventGenerator _sendMarkerHIDEventWithCompletionBlock:]):
+        * UIProcess/ios/ProcessAssertionIOS.mm:
+        (-[WKProcessAssertionBackgroundTaskManager _updateBackgroundTask]):
+        (-[WKProcessAssertionBackgroundTaskManager _handleBackgroundTaskExpirationOnMainThread]):
+        (-[WKRBSAssertionDelegate assertion:didInvalidateWithError:]):
+        (WebKit::ProcessAssertion::ProcessAssertion):
+        * UIProcess/ios/WKContentViewInteraction.mm:
+        (-[WKContentView resignFirstResponderForWebView]):
+        * UIProcess/ios/WKPDFView.mm:
+        (-[WKPDFView pdfHostViewControllerExtensionProcessDidCrash:]):
+        * UIProcess/ios/forms/WKFileUploadPanel.mm:
+        (-[WKFileUploadPanel imagePickerController:didFinishPickingMediaWithInfo:]):
+        (-[WKFileUploadPanel imagePickerController:didFinishPickingMultipleMediaWithInfo:]):
+        * UIProcess/ios/fullscreen/WKFullScreenWindowControllerIOS.mm:
+        (-[WKFullScreenWindowController placeholderWillMoveToSuperview:]):
+        * WebProcess/WebPage/RemoteLayerTree/PlatformCALayerRemoteCustom.mm:
+        (WebKit::PlatformCALayerRemoteCustom::clone const):
+        * WebProcess/WebPage/RemoteLayerTree/RemoteLayerTreeDrawingArea.mm:
+        (WebKit::RemoteLayerTreeDrawingArea::updateRendering):
+        * WebProcess/cocoa/VideoFullscreenManager.mm:
+        (WebKit::VideoFullscreenManager::requestVideoContentLayer):
+        (WebKit::VideoFullscreenManager::returnVideoContentLayer):
+        (WebKit::VideoFullscreenManager::didSetupFullscreen):
+        (WebKit::VideoFullscreenManager::willExitFullscreen):
+        (WebKit::VideoFullscreenManager::didEnterFullscreen):
+        (WebKit::VideoFullscreenManager::didExitFullscreen):
+        (WebKit::VideoFullscreenManager::didCleanupFullscreen):
+
 2021-01-14  Youenn Fablet  <[email protected]>
 
         Use callOnMainRunLoop in MediaPermissionUtilities

Modified: trunk/Source/WebKit/Platform/cocoa/WKPaymentAuthorizationDelegate.mm (271492 => 271493)


--- trunk/Source/WebKit/Platform/cocoa/WKPaymentAuthorizationDelegate.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/Platform/cocoa/WKPaymentAuthorizationDelegate.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -135,7 +135,7 @@
         if (error)
             LOG_ERROR("PKCanMakePaymentsWithMerchantIdentifierAndDomain error %@", error);
 
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([self, protectedSelf = retainPtr(self), merchantURL = retainPtr(merchantURL)] {
             ASSERT(_didRequestMerchantSessionCompletion);
 
             auto presenter = _presenter.get();
@@ -144,7 +144,7 @@
                 return;
             }
 
-            presenter->client().presenterWillValidateMerchant(*presenter, merchantURL);
+            presenter->client().presenterWillValidateMerchant(*presenter, merchantURL.get());
         });
     }];
 }

Modified: trunk/Source/WebKit/Shared/Cocoa/DefaultWebBrowserChecks.mm (271492 => 271493)


--- trunk/Source/WebKit/Shared/Cocoa/DefaultWebBrowserChecks.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/Shared/Cocoa/DefaultWebBrowserChecks.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -135,7 +135,7 @@
     dispatch_async(g_itpQueue, [appWasLinkedOnOrAfter, bundleIdentifier = WebCore::applicationBundleIdentifier().isolatedCopy()] {
         g_currentITPState = determineITPStateInternal(appWasLinkedOnOrAfter, bundleIdentifier) ? ITPState::Enabled : ITPState::Disabled;
 
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([] {
             dispatch_release(g_itpQueue);
             g_itpQueue = nullptr;
         });

Modified: trunk/Source/WebKit/UIProcess/API/C/mac/WKContextPrivateMac.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/API/C/mac/WKContextPrivateMac.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/API/C/mac/WKContextPrivateMac.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -40,6 +40,7 @@
 #import "WebProcessPool.h"
 #import <WebCore/PluginBlocklist.h>
 #import <WebCore/WebGLBlocklist.h>
+#import <wtf/BlockPtr.h>
 #import <wtf/RetainPtr.h>
 
 bool WKContextIsPlugInUpdateAvailable(WKContextRef, WKStringRef)
@@ -83,7 +84,7 @@
     RefPtr<API::Array> array = API::Array::create(WTFMove(pluginInfoDictionaries));
 
     WebKit::toImpl(contextRef)->ref();
-    dispatch_async(dispatch_get_main_queue(), ^() {
+    RunLoop::main().dispatch([block = makeBlockPtr(block), array = WTFMove(array), contextRef] {
         block(WebKit::toAPI(array.get()), 0);
     
         WebKit::toImpl(contextRef)->deref();

Modified: trunk/Source/WebKit/UIProcess/API/Cocoa/NSAttributedString.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/API/Cocoa/NSAttributedString.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/API/Cocoa/NSAttributedString.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -335,7 +335,9 @@
     if ([NSThread isMainThread])
         runConversion();
     else
-        dispatch_async(dispatch_get_main_queue(), runConversion);
+        RunLoop::main().dispatch([runConversion = makeBlockPtr(runConversion)] {
+            runConversion();
+        });
 }
 
 @end

Modified: trunk/Source/WebKit/UIProcess/API/Cocoa/WKBrowsingContextController.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/API/Cocoa/WKBrowsingContextController.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/API/Cocoa/WKBrowsingContextController.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -105,9 +105,9 @@
     if ([NSThread isMainThread])
         WebKit::WebProcessPool::registerGlobalURLSchemeAsHavingCustomProtocolHandlers(scheme);
     else {
-        dispatch_async(dispatch_get_main_queue(), makeBlockPtr([scheme = retainPtr(scheme)] {
+        RunLoop::main().dispatch([scheme = retainPtr(scheme)] {
             WebKit::WebProcessPool::registerGlobalURLSchemeAsHavingCustomProtocolHandlers(scheme.get());
-        }).get());
+        });
     }
 }
 
@@ -116,9 +116,9 @@
     if ([NSThread isMainThread])
         WebKit::WebProcessPool::unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(scheme);
     else {
-        dispatch_async(dispatch_get_main_queue(), makeBlockPtr([scheme = retainPtr(scheme)] {
+        RunLoop::main().dispatch([scheme = retainPtr(scheme)] {
             WebKit::WebProcessPool::unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(scheme.get());
-        }).get());
+        });
     }
 }
 

Modified: trunk/Source/WebKit/UIProcess/API/Cocoa/WKWebView.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/API/Cocoa/WKWebView.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/API/Cocoa/WKWebView.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -1030,7 +1030,7 @@
         [userInfo setObject:errorMessage forKey:_WKJavaScriptExceptionMessageErrorKey];
 
         auto error = adoptNS([[NSError alloc] initWithDomain:WKErrorDomain code:WKErrorJavaScriptExceptionOccurred userInfo:userInfo.get()]);
-        dispatch_async(dispatch_get_main_queue(), [handler, error] {
+        RunLoop::main().dispatch([handler, error] {
             auto rawHandler = (void (^)(id, NSError *))handler.get();
             rawHandler(nil, error.get());
         });
@@ -1345,7 +1345,9 @@
 {
 #if PLATFORM(IOS_FAMILY)
     if (![self usesStandardContentView]) {
-        dispatch_async(dispatch_get_main_queue(), updateBlock);
+        RunLoop::main().dispatch([updateBlock = makeBlockPtr(updateBlock)] {
+            updateBlock();
+        });
         return;
     }
 #endif

Modified: trunk/Source/WebKit/UIProcess/API/Cocoa/WKWebViewTesting.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/API/Cocoa/WKWebViewTesting.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/API/Cocoa/WKWebViewTesting.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -114,7 +114,9 @@
     _visibleContentRectUpdateCallbacks.append(makeBlockPtr(updateBlock));
     [self _scheduleVisibleContentRectUpdate];
 #else
-    dispatch_async(dispatch_get_main_queue(), updateBlock);
+    RunLoop::main().dispatch([updateBlock = makeBlockPtr(updateBlock)] {
+        updateBlock();
+    });
 #endif
 }
 

Modified: trunk/Source/WebKit/UIProcess/API/ios/WKWebViewIOS.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/API/ios/WKWebViewIOS.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/API/ios/WKWebViewIOS.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -1941,7 +1941,7 @@
         return;
     }
 
-    dispatch_async(dispatch_get_main_queue(), [retainedSelf = retainPtr(self)] {
+    RunLoop::main().dispatch([retainedSelf = retainPtr(self)] {
         WKWebView *webView = retainedSelf.get();
         if (![webView _isValid])
             return;
@@ -2079,7 +2079,7 @@
 
             if (!CGPointEqualToPoint(activePoint, currentPoint)) {
                 RetainPtr<WKScrollView> strongScrollView = _scrollView;
-                dispatch_async(dispatch_get_main_queue(), [strongScrollView, activePoint] {
+                RunLoop::main().dispatch([strongScrollView, activePoint] {
                     [strongScrollView setContentOffset:activePoint animated:NO];
                 });
             }
@@ -2438,7 +2438,7 @@
 {
     RetainPtr<WKWebView> strongSelf = self;
     [self _doAfterNextPresentationUpdate:[strongSelf] {
-        dispatch_async(dispatch_get_main_queue(), [strongSelf] {
+        RunLoop::main().dispatch([strongSelf] {
             if ([strongSelf->_stableStatePresentationUpdateCallbacks count])
                 [strongSelf _firePresentationUpdateForPendingStableStatePresentationCallbacks];
         });
@@ -2719,7 +2719,9 @@
 - (void)_doAfterNextStablePresentationUpdate:(dispatch_block_t)updateBlock
 {
     if (![self usesStandardContentView]) {
-        dispatch_async(dispatch_get_main_queue(), updateBlock);
+        RunLoop::main().dispatch([updateBlock = makeBlockPtr(updateBlock)] {
+            updateBlock();
+        });
         return;
     }
 

Modified: trunk/Source/WebKit/UIProcess/Cocoa/AutomationClient.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/Cocoa/AutomationClient.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/Cocoa/AutomationClient.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -85,9 +85,9 @@
     // RemoteInspector will try to acquire its lock to register the new session and
     // deadlock because it's already taken while handling XPC messages.
     NSString *requestedSessionIdentifier = sessionIdentifier;
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([this, requestedSessionIdentifier = retainPtr(requestedSessionIdentifier), configuration = retainPtr(configuration)] {
         if (m_delegateMethods.requestAutomationSession)
-            [m_delegate.get() _processPool:m_processPool didRequestAutomationSessionWithIdentifier:requestedSessionIdentifier configuration:configuration];
+            [m_delegate.get() _processPool:m_processPool didRequestAutomationSessionWithIdentifier:requestedSessionIdentifier.get() configuration:configuration.get()];
     });
 }
 

Modified: trunk/Source/WebKit/UIProcess/Cocoa/NavigationState.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/Cocoa/NavigationState.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/Cocoa/NavigationState.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -451,7 +451,7 @@
             completionHandler(success);
         });
         [LSAppLink openWithURL:url completionHandler:[localCompletionHandler](BOOL success, NSError *) {
-            dispatch_async(dispatch_get_main_queue(), [localCompletionHandler, success] {
+            RunLoop::main().dispatch([localCompletionHandler, success] {
                 (*localCompletionHandler)(success);
                 delete localCompletionHandler;
             });

Modified: trunk/Source/WebKit/UIProcess/Cocoa/PreferenceObserver.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/Cocoa/PreferenceObserver.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/Cocoa/PreferenceObserver.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -179,13 +179,13 @@
 - (void)preferenceDidChange:(NSString *)domain key:(NSString *)key encodedValue:(NSString *)encodedValue
 {
 #if ENABLE(CFPREFS_DIRECT_MODE)
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([domain = retainPtr(domain), key = retainPtr(key), encodedValue = retainPtr(encodedValue)] {
         Optional<String> encodedString;
         if (encodedValue)
-            encodedString = String(encodedValue);
+            encodedString = String(encodedValue.get());
 
         for (auto* processPool : WebKit::WebProcessPool::allProcessPools())
-            processPool->notifyPreferencesChanged(domain, key, encodedString);
+            processPool->notifyPreferencesChanged(domain.get(), key.get(), encodedString);
     });
 #endif
 }

Modified: trunk/Source/WebKit/UIProcess/Cocoa/WebInspectorPreferenceObserver.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/Cocoa/WebInspectorPreferenceObserver.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/Cocoa/WebInspectorPreferenceObserver.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -67,7 +67,7 @@
 
 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context
 {
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([] {
         for (auto* pool : WebKit::WebProcessPool::allProcessPools()) {
             for (size_t i = 0; i < pool->processes().size(); ++i) {
                 auto process = pool->processes()[i];

Modified: trunk/Source/WebKit/UIProcess/Cocoa/WebPageProxyCocoa.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/Cocoa/WebPageProxyCocoa.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/Cocoa/WebPageProxyCocoa.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -456,7 +456,7 @@
 void WebPageProxy::requestThumbnailWithOperation(WKQLThumbnailLoadOperation *operation)
 {
     [operation setCompletionBlock:^{
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([this, operation = retainPtr(operation)] {
             auto identifier = [operation identifier];
             auto convertedImage = convertPlatformImageToBitmap([operation thumbnail], WebCore::IntSize(400, 400));
             if (!convertedImage)

Modified: trunk/Source/WebKit/UIProcess/Cocoa/WebProcessPoolCocoa.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/Cocoa/WebProcessPoolCocoa.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/Cocoa/WebProcessPoolCocoa.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -889,7 +889,7 @@
 #if PLATFORM(MAC)
 static void webProcessPoolHighDynamicRangeDidChangeCallback(CMNotificationCenterRef, const void*, CFStringRef notificationName, const void*, CFTypeRef)
 {
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([] {
         auto properties = WebCore::collectScreenProperties();
         for (auto& pool : WebProcessPool::allProcessPools())
             pool->sendToAllProcesses(Messages::WebProcess::SetScreenProperties(properties));

Modified: trunk/Source/WebKit/UIProcess/Cocoa/WebViewImpl.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/Cocoa/WebViewImpl.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/Cocoa/WebViewImpl.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -929,7 +929,7 @@
 
 - (void)menuDidClose:(NSMenu *)menu
 {
-    dispatch_async(dispatch_get_main_queue(), [impl = _impl] {
+    RunLoop::main().dispatch([impl = _impl] {
         if (impl)
             impl->handleDOMPasteRequestWithResult(WebCore::DOMPasteAccessResponse::DeniedForGesture);
     });
@@ -1809,8 +1809,7 @@
 
     m_didScheduleWindowAndViewFrameUpdate = true;
 
-    auto weakThis = makeWeakPtr(*this);
-    dispatch_async(dispatch_get_main_queue(), [weakThis] {
+    RunLoop::main().dispatch([weakThis = makeWeakPtr(*this)] {
         if (!weakThis)
             return;
 
@@ -1936,8 +1935,7 @@
 
     m_didScheduleSetTopContentInset = true;
 
-    auto weakThis = makeWeakPtr(*this);
-    dispatch_async(dispatch_get_main_queue(), [weakThis] {
+    RunLoop::main().dispatch([weakThis = makeWeakPtr(*this)] {
         if (!weakThis)
             return;
         weakThis->dispatchSetTopContentInset();
@@ -2940,7 +2938,7 @@
 {
     [m_windowVisibilityObserver startObservingFontPanel];
 
-    dispatch_async(dispatch_get_main_queue(), [] {
+    RunLoop::main().dispatch([] {
         [[NSSpellChecker sharedSpellChecker] _preflightChosenSpellServer];
     });
 }
@@ -3383,10 +3381,10 @@
     NSTextCheckingTypes checkingTypes = NSTextCheckingTypeSpelling | NSTextCheckingTypeReplacement | NSTextCheckingTypeCorrection;
     auto weakThis = makeWeakPtr(*this);
     m_lastCandidateRequestSequenceNumber = [[NSSpellChecker sharedSpellChecker] requestCandidatesForSelectedRange:selectedRange inString:postLayoutData.paragraphContextForCandidateRequest types:checkingTypes options:nil inSpellDocumentWithTag:spellCheckerDocumentTag() completionHandler:[weakThis](NSInteger sequenceNumber, NSArray<NSTextCheckingResult *> *candidates) {
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([weakThis, sequenceNumber, candidates = retainPtr(candidates)] {
             if (!weakThis)
                 return;
-            weakThis->handleRequestedCandidates(sequenceNumber, candidates);
+            weakThis->handleRequestedCandidates(sequenceNumber, candidates.get());
         });
     }];
 }
@@ -4129,7 +4127,7 @@
                 if (errorOrNil)
                     return;
 
-                dispatch_async(dispatch_get_main_queue(), [this, path = RetainPtr<NSString>(fileURL.path), fileNames, fileCount, dragData, pasteboardName] {
+                RunLoop::main().dispatch([this, path = RetainPtr<NSString>(fileURL.path), fileNames, fileCount, dragData, pasteboardName] {
                     fileNames->append(path.get());
                     if (fileNames->size() == fileCount) {
                         SandboxExtension::Handle sandboxExtensionHandle;

Modified: trunk/Source/WebKit/UIProcess/EndowmentStateTracker.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/EndowmentStateTracker.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/EndowmentStateTracker.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -31,6 +31,7 @@
 #import "Logging.h"
 #import "RunningBoardServicesSPI.h"
 #include <wtf/NeverDestroyed.h>
+#include <wtf/RunLoop.h>
 
 namespace WebKit {
 
@@ -104,7 +105,7 @@
         [config setStateDescriptor:stateDescriptor];
 
         [config setUpdateHandler:[this] (RBSProcessMonitor * _Nonnull monitor, RBSProcessHandle * _Nonnull process, RBSProcessStateUpdate * _Nonnull update) mutable {
-            dispatch_async(dispatch_get_main_queue(), [this, state = stateFromEndowments(update.state.endowmentNamespaces)]() mutable {
+            RunLoop::main().dispatch([this, state = stateFromEndowments(update.state.endowmentNamespaces)]() mutable {
                 setState(WTFMove(state));
             });
         }];

Modified: trunk/Source/WebKit/UIProcess/_WKTouchEventGenerator.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/_WKTouchEventGenerator.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/_WKTouchEventGenerator.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -33,6 +33,7 @@
 #import <pal/spi/cocoa/IOKitSPI.h>
 #import <wtf/Assertions.h>
 #import <wtf/RetainPtr.h>
+#import <wtf/RunLoop.h>
 #import <wtf/SoftLinking.h>
 
 SOFT_LINK_PRIVATE_FRAMEWORK(BackBoardServices)
@@ -212,8 +213,7 @@
         _ioSystemClient = IOHIDEventSystemClientCreate(kCFAllocatorDefault);
 
     if (eventRef) {
-        RetainPtr<IOHIDEventRef> strongEvent = eventRef;
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([strongEvent = retainPtr(eventRef)] {
 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
             uint32_t contextID = [UIApplication sharedApplication].keyWindow._contextId;
 ALLOW_DEPRECATED_DECLARATIONS_END
@@ -240,7 +240,7 @@
         kIOHIDEventOptionNone));
     
     if (markerEvent) {
-        dispatch_async(dispatch_get_main_queue(), [markerEvent = WTFMove(markerEvent)] {
+        RunLoop::main().dispatch([markerEvent = WTFMove(markerEvent)] {
 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
             auto contextID = [UIApplication sharedApplication].keyWindow._contextId;
 ALLOW_DEPRECATED_DECLARATIONS_END

Modified: trunk/Source/WebKit/UIProcess/ios/ProcessAssertionIOS.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/ios/ProcessAssertionIOS.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/ios/ProcessAssertionIOS.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -182,7 +182,7 @@
     } else if (_assertionsNeedingBackgroundTask.computesEmpty()) {
         // Release the background task asynchronously because releasing the background task may destroy the ProcessThrottler and we don't
         // want it to get destroyed while in the middle of updating its assertion.
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([self, strongSelf = retainPtr(self)] {
             if (_assertionsNeedingBackgroundTask.computesEmpty())
                 [self _releaseBackgroundTask];
         });
@@ -223,7 +223,7 @@
     // upon resuming, or the user reactivated the app shortly after expiration).
     if (remainingTime == RBSProcessTimeLimitationNone) {
         [self _releaseBackgroundTask];
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([self, strongSelf = retainPtr(self)] {
             [self _updateBackgroundTask];
         });
         return;
@@ -271,11 +271,10 @@
 {
     RELEASE_LOG(ProcessSuspension, "%p - WKRBSAssertionDelegate: assertion was invalidated, error: %{public}@", error, self);
 
-    __weak WKRBSAssertionDelegate *weakSelf = self;
-    dispatch_async(dispatch_get_main_queue(), ^{
-        WKRBSAssertionDelegate *strongSelf = weakSelf;
-        if (strongSelf && strongSelf.invalidationCallback)
-            strongSelf.invalidationCallback();
+    RunLoop::main().dispatch([weakSelf = WeakObjCPtr<WKRBSAssertionDelegate>(self)] {
+        auto strongSelf = weakSelf.get();
+        if (strongSelf && strongSelf.get().invalidationCallback)
+            strongSelf.get().invalidationCallback();
     });
 }
 @end
@@ -302,7 +301,6 @@
     : m_assertionType(assertionType)
     , m_pid(pid)
 {
-    auto weakThis = makeWeakPtr(*this);
     NSString *runningBoardAssertionName = runningBoardNameForAssertionType(assertionType);
     ASSERT(runningBoardAssertionName);
     if (!pid) {
@@ -324,9 +322,9 @@
     NSError *acquisitionError = nil;
     if (![m_rbsAssertion acquireWithError:&acquisitionError]) {
         RELEASE_LOG_ERROR(ProcessSuspension, "%p - ProcessAssertion: Failed to acquire RBS %{public}@ assertion '%{public}s' for process with PID %d, error: %{public}@", this, runningBoardAssertionName, reason.utf8().data(), pid, acquisitionError);
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([weakThis = makeWeakPtr(*this)] {
             if (weakThis)
-                processAssertionWasInvalidated();
+                weakThis->processAssertionWasInvalidated();
         });
     } else
         RELEASE_LOG(ProcessSuspension, "%p - ProcessAssertion: Successfully took RBS %{public}@ assertion '%{public}s' for process with PID %d", this, runningBoardAssertionName, reason.utf8().data(), pid);

Modified: trunk/Source/WebKit/UIProcess/ios/WKContentViewInteraction.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/ios/WKContentViewInteraction.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/ios/WKContentViewInteraction.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -1450,7 +1450,7 @@
         _page->activityStateDidChange(WebCore::ActivityState::IsFocused, WebKit::WebPageProxy::ActivityStateChangeDispatchMode::Immediate);
 
         if (_keyWebEventHandler) {
-            dispatch_async(dispatch_get_main_queue(), [weakHandler = WeakObjCPtr<id>(_keyWebEventHandler.get()), weakSelf = WeakObjCPtr<WKContentView>(self)] {
+            RunLoop::main().dispatch([weakHandler = WeakObjCPtr<id>(_keyWebEventHandler.get()), weakSelf = WeakObjCPtr<WKContentView>(self)] {
                 auto strongSelf = weakSelf.get();
                 if (!strongSelf || [strongSelf isFirstResponder])
                     return;

Modified: trunk/Source/WebKit/UIProcess/ios/WKPDFView.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/ios/WKPDFView.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/ios/WKPDFView.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -509,7 +509,7 @@
 - (void)pdfHostViewControllerExtensionProcessDidCrash:(PDFHostViewController *)controller
 {
     // FIXME 40916725: PDFKit should dispatch this message to the main thread like it does for other delegate messages.
-    dispatch_async(dispatch_get_main_queue(), [webView = _webView] {
+    RunLoop::main().dispatch([webView = _webView] {
         if (auto page = [webView _page])
             page->dispatchProcessDidTerminate(WebKit::ProcessTerminationReason::Crash);
     });

Modified: trunk/Source/WebKit/UIProcess/ios/forms/WKFileUploadPanel.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/ios/forms/WKFileUploadPanel.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/ios/forms/WKFileUploadPanel.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -683,12 +683,12 @@
         successBlock:^(NSArray *processedResults, NSString *displayString) {
             ASSERT([processedResults count] == 1);
             _WKFileUploadItem *result = [processedResults objectAtIndex:0];
-            dispatch_async(dispatch_get_main_queue(), ^{
-                [self _chooseFiles:@[result.fileURL] displayString:displayString iconImage:result.displayImage.get()];
+            RunLoop::main().dispatch([self, strongSelf = retainPtr(self), result = retainPtr(result), displayString = retainPtr(displayString)] {
+                [self _chooseFiles:@[result.get().fileURL] displayString:displayString.get() iconImage:result.get().displayImage.get()];
             });
         }
         failureBlock:^{
-            dispatch_async(dispatch_get_main_queue(), ^{
+            RunLoop::main().dispatch([self, strongSelf = retainPtr(self)] {
                 [self _cancel];
             });
         }
@@ -712,12 +712,12 @@
                     iconImage = result.displayImage;
             }
 
-            dispatch_async(dispatch_get_main_queue(), ^{
-                [self _chooseFiles:fileURLs displayString:displayString iconImage:iconImage.get()];
+            RunLoop::main().dispatch([self, strongSelf = retainPtr(self), fileURLs = retainPtr(fileURLs), displayString = retainPtr(displayString), iconImage] {
+                [self _chooseFiles:fileURLs.get() displayString:displayString.get() iconImage:iconImage.get()];
             });
         }
         failureBlock:^{
-            dispatch_async(dispatch_get_main_queue(), ^{
+            RunLoop::main().dispatch([self, strongSelf = retainPtr(self)] {
                 [self _cancel];
             });
         }

Modified: trunk/Source/WebKit/UIProcess/ios/fullscreen/WKFullScreenWindowControllerIOS.mm (271492 => 271493)


--- trunk/Source/WebKit/UIProcess/ios/fullscreen/WKFullScreenWindowControllerIOS.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/UIProcess/ios/fullscreen/WKFullScreenWindowControllerIOS.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -879,7 +879,7 @@
     if (superview)
         return;
 
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([self, strongSelf = retainPtr(self)] {
         if ([_webViewPlaceholder superview] == nil && [_webViewPlaceholder parent] == self)
             [self close];
     });

Modified: trunk/Source/WebKit/WebProcess/WebPage/RemoteLayerTree/PlatformCALayerRemoteCustom.mm (271492 => 271493)


--- trunk/Source/WebKit/WebProcess/WebPage/RemoteLayerTree/PlatformCALayerRemoteCustom.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/WebProcess/WebPage/RemoteLayerTree/PlatformCALayerRemoteCustom.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -112,7 +112,7 @@
 
             AVPlayerLayer *destinationPlayerLayer = static_cast<AVPlayerLayer *>(clonedLayer.get());
             AVPlayerLayer *sourcePlayerLayer = static_cast<AVPlayerLayer *>(platformLayer());
-            dispatch_async(dispatch_get_main_queue(), [destinationPlayerLayer, sourcePlayerLayer] {
+            RunLoop::main().dispatch([destinationPlayerLayer, sourcePlayerLayer] {
                 [destinationPlayerLayer setPlayer:[sourcePlayerLayer player]];
             });
         } else {

Modified: trunk/Source/WebKit/WebProcess/WebPage/RemoteLayerTree/RemoteLayerTreeDrawingArea.mm (271492 => 271493)


--- trunk/Source/WebKit/WebProcess/WebPage/RemoteLayerTree/RemoteLayerTreeDrawingArea.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/WebProcess/WebPage/RemoteLayerTree/RemoteLayerTreeDrawingArea.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -416,7 +416,7 @@
         backingStoreFlusher->flush();
 
         MonotonicTime timestamp = MonotonicTime::now();
-        dispatch_async(dispatch_get_main_queue(), [pageID, timestamp] {
+        RunLoop::main().dispatch([pageID, timestamp] {
             if (WebPage* webPage = WebProcess::singleton().webPage(pageID))
                 webPage->didFlushLayerTreeAtTime(timestamp);
         });

Modified: trunk/Source/WebKit/WebProcess/cocoa/VideoFullscreenManager.mm (271492 => 271493)


--- trunk/Source/WebKit/WebProcess/cocoa/VideoFullscreenManager.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKit/WebProcess/cocoa/VideoFullscreenManager.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -385,7 +385,7 @@
     CALayer* videoLayer = interface->layerHostingContext()->rootLayer();
 
     model->setVideoFullscreenLayer(videoLayer, [protectedThis = makeRefPtr(this), this, contextId] () mutable {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = WTFMove(protectedThis), this, contextId] {
+        RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), this, contextId] {
             if (protectedThis->m_page)
                 m_page->send(Messages::VideoFullscreenManagerProxy::SetHasVideoContentLayer(contextId, true));
         });
@@ -399,9 +399,9 @@
     std::tie(model, interface) = ensureModelAndInterface(contextId);
 
     model->waitForPreparedForInlineThen([protectedThis = makeRefPtr(this), this, contextId, model] () mutable { // need this for return video layer
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = WTFMove(protectedThis), this, contextId, model] () mutable {
+        RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), this, contextId, model] () mutable {
             model->setVideoFullscreenLayer(nil, [protectedThis = WTFMove(protectedThis), this, contextId] () mutable {
-                dispatch_async(dispatch_get_main_queue(), [protectedThis = WTFMove(protectedThis), this, contextId] {
+                RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), this, contextId] {
                     if (protectedThis->m_page)
                         m_page->send(Messages::VideoFullscreenManagerProxy::SetHasVideoContentLayer(contextId, false));
                 });
@@ -420,7 +420,7 @@
     CALayer* videoLayer = interface->layerHostingContext()->rootLayer();
 
     model->setVideoFullscreenLayer(videoLayer, [protectedThis = makeRefPtr(this), this, contextId] () mutable {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = WTFMove(protectedThis), this, contextId] {
+        RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), this, contextId] {
             if (protectedThis->m_page)
                 m_page->send(Messages::VideoFullscreenManagerProxy::EnterFullscreen(contextId));
         });
@@ -438,7 +438,7 @@
     if (!videoElement)
         return;
 
-    dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), videoElement = WTFMove(videoElement), contextId] {
+    RunLoop::main().dispatch([protectedThis = makeRefPtr(this), videoElement = WTFMove(videoElement), contextId] {
         videoElement->willExitFullscreen();
         if (protectedThis->m_page)
             protectedThis->m_page->send(Messages::VideoFullscreenManagerProxy::PreparedToExitFullscreen(contextId));
@@ -464,7 +464,7 @@
         return;
 
     // exit fullscreen now if it was previously requested during an animation.
-    dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), videoElement] {
+    RunLoop::main().dispatch([protectedThis = makeRefPtr(this), videoElement] {
         if (protectedThis->m_page)
             protectedThis->exitVideoFullscreenForVideoElement(*videoElement, [](bool) { });
     });
@@ -479,15 +479,15 @@
     std::tie(model, interface) = ensureModelAndInterface(contextId);
 
 #if PLATFORM(IOS_FAMILY)
-    dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), contextId, interface] {
+    RunLoop::main().dispatch([protectedThis = makeRefPtr(this), contextId, interface] {
         if (protectedThis->m_page)
             protectedThis->m_page->send(Messages::VideoFullscreenManagerProxy::CleanupFullscreen(contextId));
     });
 #else
     model->waitForPreparedForInlineThen([protectedThis = makeRefPtr(this), contextId, interface, model]() mutable {
-        dispatch_async(dispatch_get_main_queue(), [protectedThis = WTFMove(protectedThis), contextId, interface, model] () mutable {
+        RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), contextId, interface, model] () mutable {
             model->setVideoFullscreenLayer(nil, [protectedThis = WTFMove(protectedThis), contextId, interface] () mutable {
-                dispatch_async(dispatch_get_main_queue(), [protectedThis = WTFMove(protectedThis), contextId, interface] {
+                RunLoop::main().dispatch([protectedThis = WTFMove(protectedThis), contextId, interface] {
                     if (interface->layerHostingContext()) {
                         interface->layerHostingContext()->setRootLayer(nullptr);
                         interface->setLayerHostingContext(nullptr);
@@ -530,7 +530,7 @@
     if (!videoElement || !targetIsFullscreen)
         return;
 
-    dispatch_async(dispatch_get_main_queue(), [protectedThis = makeRefPtr(this), videoElement, mode, standby] {
+    RunLoop::main().dispatch([protectedThis = makeRefPtr(this), videoElement, mode, standby] {
         if (protectedThis->m_page)
             protectedThis->enterVideoFullscreenForVideoElement(*videoElement, mode, standby);
     });

Modified: trunk/Source/WebKitLegacy/ios/ChangeLog (271492 => 271493)


--- trunk/Source/WebKitLegacy/ios/ChangeLog	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKitLegacy/ios/ChangeLog	2021-01-14 18:44:13 UTC (rev 271493)
@@ -1,3 +1,29 @@
+2021-01-14  Geoffrey Garen  <[email protected]>
+
+        Removed most uses of dispatch_async(dispatch_get_main_queue(), ...)
+        https://bugs.webkit.org/show_bug.cgi?id=220066
+
+        Reviewed by Antti Koivisto.
+
+        dispatch_async has two downsides:
+
+        (1) Its order is undefined (and in practice highly variable) relative to
+        other WebKit operations. This sometimes causes flakiness.
+
+        (2) It doesn't honor the RunLoop first paint optimization.
+
+        We can use RunLoop::dispatch() instead.
+
+        * Misc/WebGeolocationProviderIOS.mm:
+        (-[WebGeolocationProviderIOS registerWebView:]):
+        (-[WebGeolocationProviderIOS unregisterWebView:]):
+        (-[WebGeolocationProviderIOS setEnableHighAccuracy:]):
+        (-[WebGeolocationProviderIOS initializeGeolocationForWebView:listener:]):
+        * WebCoreSupport/WebChromeClientIOS.mm:
+        (WebChromeClientIOS::runOpenPanel):
+        * WebCoreSupport/WebInspectorClientIOS.mm:
+        (WebInspectorClient::didSetSearchingForNode):
+
 2020-11-06  Sam Weinig  <[email protected]>
 
         Further progress towards merging Settings.yaml into WebPreferences.yaml

Modified: trunk/Source/WebKitLegacy/ios/Misc/WebGeolocationProviderIOS.mm (271492 => 271493)


--- trunk/Source/WebKitLegacy/ios/Misc/WebGeolocationProviderIOS.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKitLegacy/ios/Misc/WebGeolocationProviderIOS.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -37,6 +37,7 @@
 #import <wtf/HashSet.h>
 #import <wtf/HashMap.h>
 #import <wtf/RetainPtr.h>
+#import <wtf/RunLoop.h>
 #import <wtf/Vector.h>
 
 using namespace WebCore;
@@ -178,7 +179,7 @@
         return;
 
     if (!_isSuspended) {
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([self, strongSelf = retainPtr(self)] {
             if (!_coreLocationProvider) {
                 ASSERT(!_coreLocationUpdateListenerProxy);
                 _coreLocationUpdateListenerProxy = adoptNS([[_WebCoreLocationUpdateThreadingProxy alloc] initWithProvider:self]);
@@ -208,7 +209,7 @@
     _pendingInitialPositionWebView.remove(webView);
 
     if (_registeredWebViews.isEmpty()) {
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([self, strongSelf = retainPtr(self)] {
             [_coreLocationProvider stop];
         });
         _enableHighAccuracy = NO;
@@ -226,7 +227,7 @@
 {
     ASSERT(WebThreadIsLockedOrDisabled());
     _enableHighAccuracy = _enableHighAccuracy || enableHighAccuracy;
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([self, strongSelf = retainPtr(self)] {
         [_coreLocationProvider setEnableHighAccuracy:_enableHighAccuracy];
     });
 }
@@ -241,7 +242,7 @@
     _webViewsWaitingForCoreLocationAuthorization.add(webView, listener);
     _trackedWebViews.add(webView);
 
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([self, strongSelf = retainPtr(self)] {
         if (!_coreLocationProvider) {
             ASSERT(!_coreLocationUpdateListenerProxy);
             _coreLocationUpdateListenerProxy = adoptNS([[_WebCoreLocationUpdateThreadingProxy alloc] initWithProvider:self]);

Modified: trunk/Source/WebKitLegacy/ios/WebCoreSupport/WebChromeClientIOS.mm (271492 => 271493)


--- trunk/Source/WebKitLegacy/ios/WebCoreSupport/WebChromeClientIOS.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKitLegacy/ios/WebCoreSupport/WebChromeClientIOS.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -146,8 +146,8 @@
     };
 
     if (WebThreadIsCurrent()) {
-        dispatch_async(dispatch_get_main_queue(), ^{
-            [[webView() _UIKitDelegateForwarder] webView:webView() runOpenPanelForFileButtonWithResultListener:listener configuration:configuration];
+        RunLoop::main().dispatch([this, listener = retainPtr(listener), configuration = retainPtr(configuration)] {
+            [[webView() _UIKitDelegateForwarder] webView:webView() runOpenPanelForFileButtonWithResultListener:listener.get() configuration:configuration.get()];
         });
     } else
         [[webView() _UIKitDelegateForwarder] webView:webView() runOpenPanelForFileButtonWithResultListener:listener configuration:configuration];

Modified: trunk/Source/WebKitLegacy/ios/WebCoreSupport/WebInspectorClientIOS.mm (271492 => 271493)


--- trunk/Source/WebKitLegacy/ios/WebCoreSupport/WebInspectorClientIOS.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKitLegacy/ios/WebCoreSupport/WebInspectorClientIOS.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -104,10 +104,9 @@
 
 void WebInspectorClient::didSetSearchingForNode(bool enabled)
 {
-    WebInspector *inspector = [m_inspectedWebView inspector];
     NSString *notificationName = enabled ? WebInspectorDidStartSearchingForNode : WebInspectorDidStopSearchingForNode;
-    dispatch_async(dispatch_get_main_queue(), ^{
-        [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:inspector];
+    RunLoop::main().dispatch([notificationName = retainPtr(notificationName), inspector = retainPtr([m_inspectedWebView inspector])] {
+        [[NSNotificationCenter defaultCenter] postNotificationName:notificationName.get() object:inspector.get()];
     });
 }
 

Modified: trunk/Source/WebKitLegacy/mac/ChangeLog (271492 => 271493)


--- trunk/Source/WebKitLegacy/mac/ChangeLog	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKitLegacy/mac/ChangeLog	2021-01-14 18:44:13 UTC (rev 271493)
@@ -1,3 +1,32 @@
+2021-01-14  Geoffrey Garen  <[email protected]>
+
+        Removed most uses of dispatch_async(dispatch_get_main_queue(), ...)
+        https://bugs.webkit.org/show_bug.cgi?id=220066
+
+        Reviewed by Antti Koivisto.
+
+        dispatch_async has two downsides:
+
+        (1) Its order is undefined (and in practice highly variable) relative to
+        other WebKit operations. This sometimes causes flakiness.
+
+        (2) It doesn't honor the RunLoop first paint optimization.
+
+        We can use RunLoop::dispatch() instead.
+
+        * Plugins/npapi.mm:
+        (NPN_PluginThreadAsyncCall):
+        * WebCoreSupport/WebEditorClient.mm:
+        (WebEditorClient::requestCandidatesForSelection):
+        * WebCoreSupport/WebFrameLoaderClient.mm:
+        * WebView/WebImmediateActionController.mm:
+        (-[WebImmediateActionController immediateActionRecognizerWillPrepare:]):
+        * WebView/WebView.mm:
+        (+[WebView willEnterBackgroundWithCompletionHandler:]):
+        (-[_WebSafeAsyncForwarder forwardInvocation:]):
+        (-[WebView performDragOperation:]):
+        (-[WebView setEditable:]):
+
 2021-01-13  Alex Christensen  <[email protected]>
 
         Remove deprecated script and stylesheet injection SPI, replaced with more inclusively-named SPI

Modified: trunk/Source/WebKitLegacy/mac/Plugins/npapi.mm (271492 => 271493)


--- trunk/Source/WebKitLegacy/mac/Plugins/npapi.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKitLegacy/mac/Plugins/npapi.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -31,6 +31,7 @@
 
 #import "WebNetscapePluginView.h"
 #import "WebKitLogging.h"
+#import <wtf/RunLoop.h>
 
 using namespace WebCore;
 
@@ -174,7 +175,7 @@
 {
     WebNetscapePluginView *pluginView = pluginViewForInstance(instance);
 
-    dispatch_async(dispatch_get_main_queue(), ^{
+    RunLoop::main().dispatch([pluginView = retainPtr(pluginView), userData, func] {
         if (!pluginView || !pluginView->plugin) {
             // The plug-in has already been destroyed.
             return;

Modified: trunk/Source/WebKitLegacy/mac/WebCoreSupport/WebEditorClient.mm (271492 => 271493)


--- trunk/Source/WebKitLegacy/mac/WebCoreSupport/WebEditorClient.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKitLegacy/mac/WebCoreSupport/WebEditorClient.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -1122,10 +1122,10 @@
     NSTextCheckingTypes checkingTypes = NSTextCheckingTypeSpelling | NSTextCheckingTypeReplacement | NSTextCheckingTypeCorrection;
     auto weakEditor = makeWeakPtr(*this);
     m_lastCandidateRequestSequenceNumber = [[NSSpellChecker sharedSpellChecker] requestCandidatesForSelectedRange:m_rangeForCandidates inString:m_paragraphContextForCandidateRequest.get() types:checkingTypes options:nil inSpellDocumentWithTag:spellCheckerDocumentTag() completionHandler:[weakEditor](NSInteger sequenceNumber, NSArray<NSTextCheckingResult *> *candidates) {
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([weakEditor, sequenceNumber, candidates = retainPtr(candidates)] {
             if (!weakEditor)
                 return;
-            weakEditor->handleRequestedCandidates(sequenceNumber, candidates);
+            weakEditor->handleRequestedCandidates(sequenceNumber, candidates.get());
         });
     }];
 }

Modified: trunk/Source/WebKitLegacy/mac/WebCoreSupport/WebFrameLoaderClient.mm (271492 => 271493)


--- trunk/Source/WebKitLegacy/mac/WebCoreSupport/WebFrameLoaderClient.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKitLegacy/mac/WebCoreSupport/WebFrameLoaderClient.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -2372,7 +2372,7 @@
 #if USE(WEB_THREAD)
             WebThreadRun(^{
 #else
-            dispatch_async(dispatch_get_main_queue(), ^{
+            RunLoop::main().dispatch([self, strongSelf = retainPtr(self), success] {
 #endif
                 if (success)
                     [self receivedPolicyDecision:WebCore::PolicyAction::Ignore];

Modified: trunk/Source/WebKitLegacy/mac/WebView/WebImmediateActionController.mm (271492 => 271493)


--- trunk/Source/WebKitLegacy/mac/WebView/WebImmediateActionController.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKitLegacy/mac/WebView/WebImmediateActionController.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -199,7 +199,7 @@
 
     if (![_immediateActionRecognizer animationController]) {
         // FIXME: We should be able to remove the dispatch_async when rdar://problem/19502927 is resolved.
-        dispatch_async(dispatch_get_main_queue(), ^{
+        RunLoop::main().dispatch([self, strongSelf = retainPtr(self)] {
             [self _cancelImmediateAction];
         });
     }

Modified: trunk/Source/WebKitLegacy/mac/WebView/WebView.mm (271492 => 271493)


--- trunk/Source/WebKitLegacy/mac/WebView/WebView.mm	2021-01-14 18:30:57 UTC (rev 271492)
+++ trunk/Source/WebKitLegacy/mac/WebView/WebView.mm	2021-01-14 18:44:13 UTC (rev 271493)
@@ -244,6 +244,7 @@
 #import <pal/spi/mac/NSViewSPI.h>
 #import <pal/spi/mac/NSWindowSPI.h>
 #import <wtf/Assertions.h>
+#import <wtf/BlockPtr.h>
 #import <wtf/FileSystem.h>
 #import <wtf/HashTraits.h>
 #import <wtf/MainThread.h>
@@ -1891,7 +1892,9 @@
 {
     WebThreadRun(^{
         [WebView _releaseMemoryNow];
-        dispatch_async(dispatch_get_main_queue(), handler);
+        RunLoop::main().dispatch([handler = makeBlockPtr(handler)] {
+            handler();
+        });
     });
 }
 
@@ -5024,15 +5027,13 @@
 
 - (void)forwardInvocation:(NSInvocation *)invocation
 {
-    // Store _forwarder in an ivar so it is retained by the block.
-    _WebSafeForwarder *forwarder = _forwarder;
     if (WebThreadIsCurrent()) {
         [invocation retainArguments];
-        dispatch_async(dispatch_get_main_queue(), ^{
-            [forwarder forwardInvocation:invocation];
+        RunLoop::main().dispatch([forwarder = retainPtr(_forwarder), invocation = retainPtr(invocation)] {
+            [forwarder forwardInvocation:invocation.get()];
         });
     } else
-        [forwarder forwardInvocation:invocation];
+        [_forwarder forwardInvocation:invocation];
 }
 
 - (BOOL)respondsToSelector:(SEL)aSelector
@@ -6449,7 +6450,7 @@
                 if (errorOrNil)
                     return;
 
-                dispatch_async(dispatch_get_main_queue(), [self, path = RetainPtr<NSString>(fileURL.path), fileNames, fileCount, dragData] {
+                RunLoop::main().dispatch([self, path = RetainPtr<NSString>(fileURL.path), fileNames, fileCount, dragData] {
                     fileNames->append(path.get());
                     if (fileNames->size() == fileCount) {
                         dragData->setFileNames(*fileNames);
@@ -7977,7 +7978,7 @@
             _private->page->setTabKeyCyclesThroughElements(!flag);
 #if PLATFORM(MAC)
         if (flag) {
-            dispatch_async(dispatch_get_main_queue(), [] {
+            RunLoop::main().dispatch([] {
                 [[NSSpellChecker sharedSpellChecker] _preflightChosenSpellServer];
             });
         }
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to