Add base class to get WeakPtrFactory member and avoid some boilerplate code
authorcdumez@apple.com <cdumez@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 8 Jun 2018 03:56:04 +0000 (03:56 +0000)
committercdumez@apple.com <cdumez@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 8 Jun 2018 03:56:04 +0000 (03:56 +0000)
https://bugs.webkit.org/show_bug.cgi?id=186407

Reviewed by Brent Fulgham.

Source/JavaScriptCore:

Add CanMakeWeakPtr base class to get WeakPtrFactory member and its getter, in
order to avoid some boilerplate code in every class needing a WeakPtrFactory.
This also gets rid of old-style createWeakPtr() methods in favor of the newer
makeWeakPtr().

* wasm/WasmInstance.h:
* wasm/WasmMemory.cpp:
(JSC::Wasm::Memory::registerInstance):

Source/WebCore:

Add CanMakeWeakPtr base class to get WeakPtrFactory member and its getter, in
order to avoid some boilerplate code in every class needing a WeakPtrFactory.
This also gets rid of old-style createWeakPtr() methods in favor of the newer
makeWeakPtr().

* Modules/credentialmanagement/CredentialsMessenger.h:
* Modules/credentialmanagement/NavigatorCredentials.cpp:
(WebCore::NavigatorCredentials::credentials):
* Modules/encryptedmedia/CDM.cpp:
(WebCore::CDM::doSupportedConfigurationStep):
(WebCore::CDM::getConsentStatus):
* Modules/encryptedmedia/CDM.h:
* Modules/encryptedmedia/MediaKeySession.cpp:
(WebCore::MediaKeySession::generateRequest):
(WebCore::MediaKeySession::load):
(WebCore::MediaKeySession::update):
(WebCore::MediaKeySession::close):
(WebCore::MediaKeySession::remove):
* Modules/encryptedmedia/MediaKeySession.h:
* Modules/encryptedmedia/MediaKeys.cpp:
(WebCore::MediaKeys::createSession):
* Modules/encryptedmedia/MediaKeys.h:
* Modules/gamepad/GamepadManager.cpp:
(WebCore::GamepadManager::platformGamepadDisconnected):
(WebCore::GamepadManager::makeGamepadVisible):
* Modules/mediastream/MediaDevices.cpp:
(WebCore::MediaDevices::MediaDevices):
* Modules/mediastream/MediaDevices.h:
* Modules/mediastream/MediaStreamTrack.cpp:
(WebCore::MediaStreamTrack::applyConstraints):
* Modules/mediastream/MediaStreamTrack.h:
* Modules/webauthn/cocoa/LocalAuthenticator.h:
* Modules/webauthn/cocoa/LocalAuthenticator.mm:
(WebCore::LocalAuthenticator::makeCredential):
* accessibility/AccessibilityRenderObject.h:
* accessibility/AccessibilitySVGRoot.cpp:
(WebCore::AccessibilitySVGRoot::setParent):
* crypto/SubtleCrypto.cpp:
(WebCore::SubtleCrypto::encrypt):
(WebCore::SubtleCrypto::decrypt):
(WebCore::SubtleCrypto::sign):
(WebCore::SubtleCrypto::verify):
(WebCore::SubtleCrypto::digest):
(WebCore::SubtleCrypto::generateKey):
(WebCore::SubtleCrypto::deriveKey):
(WebCore::SubtleCrypto::deriveBits):
(WebCore::SubtleCrypto::importKey):
(WebCore::SubtleCrypto::exportKey):
(WebCore::SubtleCrypto::wrapKey):
(WebCore::SubtleCrypto::unwrapKey):
* crypto/SubtleCrypto.h:
* css/CSSFontFace.cpp:
(WebCore::CSSFontFace::CSSFontFace):
(WebCore::CSSFontFace::wrapper):
(WebCore::CSSFontFace::setWrapper):
* css/DeprecatedCSSOMValue.h:
* css/FontFace.cpp:
* css/FontFace.h:
* css/MediaQueryEvaluator.cpp:
(WebCore::MediaQueryEvaluator::MediaQueryEvaluator):
* css/StyleSheetContents.h:
* css/parser/CSSDeferredParser.cpp:
(WebCore::CSSDeferredParser::CSSDeferredParser):
* dom/DataTransferItemList.cpp:
(WebCore::DataTransferItemList::add):
(WebCore::DataTransferItemList::ensureItems const):
(WebCore::DataTransferItemList::didSetStringData):
* dom/DataTransferItemList.h:
* dom/Document.cpp:
(WebCore::Document::postTask):
(WebCore::Document::hasStorageAccess):
(WebCore::Document::requestStorageAccess):
* dom/Document.h:
(WebCore::Document::setContextDocument):
* dom/MessagePort.h:
* html/HTMLImageElement.cpp:
(WebCore::HTMLImageElement::setPictureElement):
* html/HTMLInputElement.h:
* html/HTMLMediaElement.cpp:
(WebCore::HTMLMediaElement::mediaPlayerCreateResourceLoader):
* html/HTMLMediaElement.h:
* html/HTMLPictureElement.h:
* html/parser/HTMLResourcePreloader.h:
* layout/layouttree/LayoutBox.h:
(WebCore::Layout::Box::style const):
* loader/FormState.h:
* loader/LinkLoader.cpp:
(WebCore::LinkLoader::preconnectIfNeeded):
* loader/LinkLoader.h:
* loader/LinkPreloadResourceClients.cpp:
(WebCore::LinkPreloadResourceClient::LinkPreloadResourceClient):
* loader/MediaResourceLoader.cpp:
(WebCore::MediaResourceLoader::MediaResourceLoader):
* loader/MediaResourceLoader.h:
* page/DOMWindow.h:
* page/EventHandler.cpp:
(WebCore::widgetForElement):
(WebCore::EventHandler::updateLastScrollbarUnderMouse):
* platform/GenericTaskQueue.cpp:
(WebCore::TaskDispatcher<Timer>::postTask):
* platform/GenericTaskQueue.h:
(WebCore::GenericTaskQueue::enqueueTask):
(WebCore::GenericTaskQueue::cancelAllTasks):
* platform/ScrollView.h:
* platform/ScrollableArea.h:
* platform/Scrollbar.h:
* platform/Widget.cpp:
(WebCore::Widget::setParent):
* platform/Widget.h:
* platform/audio/gstreamer/AudioFileReaderGStreamer.cpp:
(WebCore::AudioFileReader::decodeAudioForBusCreation):
* platform/audio/mac/AudioHardwareListenerMac.cpp:
(WebCore::AudioHardwareListenerMac::AudioHardwareListenerMac):
* platform/audio/mac/AudioHardwareListenerMac.h:
* platform/encryptedmedia/clearkey/CDMClearKey.cpp:
(WebCore::CDMInstanceClearKey::requestLicense):
(WebCore::CDMInstanceClearKey::updateLicense):
(WebCore::CDMInstanceClearKey::loadSession):
(WebCore::CDMInstanceClearKey::closeSession):
(WebCore::CDMInstanceClearKey::removeSessionData):
* platform/encryptedmedia/clearkey/CDMClearKey.h:
* platform/graphics/FontCascade.h:
* platform/graphics/avfoundation/MediaPlayerPrivateAVFoundation.cpp:
(WebCore::MediaPlayerPrivateAVFoundation::scheduleMainThreadNotification):
(WebCore::MediaPlayerPrivateAVFoundation::dispatchNotification):
* platform/graphics/avfoundation/MediaPlayerPrivateAVFoundation.h:
* platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.h:
* platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm:
(WebCore::CDMInstanceFairPlayStreamingAVFObjC::didProvideRequest):
* platform/graphics/avfoundation/objc/CDMSessionAVFoundationObjC.h:
* platform/graphics/avfoundation/objc/CDMSessionAVFoundationObjC.mm:
(WebCore::CDMSessionAVFoundationObjC::CDMSessionAVFoundationObjC):
* platform/graphics/avfoundation/objc/CDMSessionAVStreamSession.h:
* platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.h:
* platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm:
(WebCore::MediaPlayerPrivateAVFoundationObjC::createVideoLayer):
(WebCore::MediaPlayerPrivateAVFoundationObjC::checkPlayability):
(WebCore::MediaPlayerPrivateAVFoundationObjC::beginLoadingMetadata):
(WebCore::MediaPlayerPrivateAVFoundationObjC::seekToTime):
(WebCore::MediaPlayerPrivateAVFoundationObjC::createSession):
(WebCore::MediaPlayerPrivateAVFoundationObjC::setShouldPlayToPlaybackTarget):
(-[WebCoreAVFMovieObserver observeValueForKeyPath:ofObject:change:context:]):
* platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.h:
* platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.mm:
(WebCore::MediaPlayerPrivateMediaStreamAVFObjC::requestNotificationWhenReadyForVideoData):
(WebCore::MediaPlayerPrivateMediaStreamAVFObjC::scheduleDeferredTask):
* platform/graphics/cv/TextureCacheCV.h:
* platform/graphics/cv/TextureCacheCV.mm:
(WebCore::TextureCacheCV::textureFromImage):
* platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.cpp:
(WebCore::MediaPlayerPrivateGStreamer::notifyPlayerOfVideo):
(WebCore::MediaPlayerPrivateGStreamer::notifyPlayerOfAudio):
(WebCore::MediaPlayerPrivateGStreamer::handleMessage):
* platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.h:
* platform/graphics/gstreamer/MediaPlayerPrivateGStreamerBase.cpp:
(WebCore::MediaPlayerPrivateGStreamerBase::handleSyncMessage):
(WebCore::MediaPlayerPrivateGStreamerBase::initializationDataEncountered):
* platform/graphics/gstreamer/MediaPlayerPrivateGStreamerBase.h:
* platform/graphics/gstreamer/mse/AppendPipeline.cpp:
(WebCore::AppendPipeline::connectDemuxerSrcPadToAppsink):
* platform/graphics/mac/DisplayRefreshMonitorMac.cpp:
(WebCore::DisplayRefreshMonitorMac::displayLinkFired):
* platform/graphics/mac/DisplayRefreshMonitorMac.h:
* platform/graphics/texmap/TextureMapperLayer.cpp:
(WebCore::TextureMapperLayer::setMaskLayer):
(WebCore::TextureMapperLayer::setReplicaLayer):
* platform/graphics/texmap/TextureMapperLayer.h:
* platform/graphics/win/MediaPlayerPrivateMediaFoundation.cpp:
(WebCore::MediaPlayerPrivateMediaFoundation::endCreatedMediaSource):
(WebCore::MediaPlayerPrivateMediaFoundation::endGetEvent):
(WebCore::MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::processInputNotify):
* platform/graphics/win/MediaPlayerPrivateMediaFoundation.h:
* platform/ios/RemoteCommandListenerIOS.h:
* platform/ios/RemoteCommandListenerIOS.mm:
(WebCore::RemoteCommandListenerIOS::RemoteCommandListenerIOS):
* platform/mac/RemoteCommandListenerMac.h:
* platform/mac/RemoteCommandListenerMac.mm:
(WebCore::RemoteCommandListenerMac::RemoteCommandListenerMac):
* platform/mediastream/MediaStreamPrivate.cpp:
(WebCore::MediaStreamPrivate::scheduleDeferredTask):
* platform/mediastream/MediaStreamPrivate.h:
* platform/mediastream/RealtimeMediaSource.cpp:
(WebCore::RealtimeMediaSource::scheduleDeferredTask):
* platform/mediastream/RealtimeMediaSource.h:
* platform/mediastream/mac/ScreenDisplayCaptureSourceMac.h:
* platform/mediastream/mac/ScreenDisplayCaptureSourceMac.mm:
(WebCore::ScreenDisplayCaptureSourceMac::createDisplayStream):
* platform/vr/VRPlatformDisplay.h:
* platform/vr/openvr/VRPlatformManagerOpenVR.cpp:
(WebCore::VRPlatformManagerOpenVR::getVRDisplays):
* rendering/FloatingObjects.h:
(WebCore::FloatingObject::setOriginatingLine):
* rendering/RenderObject.h:
* rendering/RootInlineBox.cpp:
* rendering/RootInlineBox.h:
* svg/SVGPathElement.h:
* svg/SVGPathSegWithContext.h:
(WebCore::SVGPathSegWithContext::SVGPathSegWithContext):
(WebCore::SVGPathSegWithContext::setContextAndRole):
* svg/SVGTransformList.h:
* svg/properties/SVGAnimatedListPropertyTearOff.h:
(WebCore::SVGAnimatedListPropertyTearOff::baseVal):
(WebCore::SVGAnimatedListPropertyTearOff::animVal):
* svg/properties/SVGAnimatedPathSegListPropertyTearOff.h:
* svg/properties/SVGAnimatedPropertyTearOff.h:
* svg/properties/SVGAnimatedTransformListPropertyTearOff.h:
* svg/properties/SVGListProperty.h:
(WebCore::SVGListProperty::initializeValuesAndWrappers):
(WebCore::SVGListProperty::getItemValuesAndWrappers):
(WebCore::SVGListProperty::insertItemBeforeValuesAndWrappers):
(WebCore::SVGListProperty::replaceItemValuesAndWrappers):
(WebCore::SVGListProperty::appendItemValuesAndWrappers):
* svg/properties/SVGMatrixTearOff.h:
* svg/properties/SVGPropertyTearOff.h:
* testing/MockCDMFactory.cpp:
(WebCore::MockCDMFactory::createCDM):
(WebCore::MockCDM::createInstance):
* testing/MockCDMFactory.h:
* workers/service/ExtendableEvent.h:
* workers/service/FetchEvent.cpp:
(WebCore::FetchEvent::respondWith):
* workers/service/server/SWServer.h:
* xml/DOMParser.cpp:
(WebCore::DOMParser::DOMParser):

Source/WebCore/PAL:

186407_CanMakeWeakPtr

* pal/system/mac/SystemSleepListenerMac.h:
* pal/system/mac/SystemSleepListenerMac.mm:
(PAL::SystemSleepListenerMac::SystemSleepListenerMac):

Source/WebKit:

Add CanMakeWeakPtr base class to get WeakPtrFactory member and its getter, in
order to avoid some boilerplate code in every class needing a WeakPtrFactory.
This also gets rid of old-style createWeakPtr() methods in favor of the newer
makeWeakPtr().

* NetworkProcess/NetworkLoadChecker.h:
* NetworkProcess/NetworkProcess.cpp:
(WebKit::NetworkProcess::canAuthenticateAgainstProtectionSpace):
* NetworkProcess/PreconnectTask.h:
* NetworkProcess/cache/CacheStorageEngine.h:
* Shared/Authentication/AuthenticationManager.h:
* UIProcess/API/APIAttachment.cpp:
(API::Attachment::Attachment):
* UIProcess/ApplePay/WebPaymentCoordinatorProxy.cpp:
(WebKit::WebPaymentCoordinatorProxy::canMakePaymentsWithActiveCard):
(WebKit::WebPaymentCoordinatorProxy::openPaymentSetup):
* UIProcess/ApplePay/WebPaymentCoordinatorProxy.h:
* UIProcess/ApplePay/mac/WebPaymentCoordinatorProxyMac.mm:
(WebKit::WebPaymentCoordinatorProxy::platformShowPaymentUI):
* UIProcess/ApplicationStateTracker.h:
* UIProcess/ApplicationStateTracker.mm:
(WebKit::ApplicationStateTracker::ApplicationStateTracker):
* UIProcess/Cocoa/ViewGestureController.cpp:
(WebKit::ViewGestureController::setAlternateBackForwardListSourcePage):
* UIProcess/Cocoa/WebViewImpl.h:
* UIProcess/Cocoa/WebViewImpl.mm:
(WebKit::WebViewImpl::updateWindowAndViewFrames):
(WebKit::WebViewImpl::setTopContentInset):
(WebKit::WebViewImpl::viewDidMoveToWindow):
(WebKit::WebViewImpl::prepareForMoveToWindow):
(WebKit::WebViewImpl::validateUserInterfaceItem):
(WebKit::WebViewImpl::requestCandidatesForSelectionIfNeeded):
(WebKit::WebViewImpl::interpretKeyEvent):
(WebKit::WebViewImpl::firstRectForCharacterRange):
(WebKit::WebViewImpl::performKeyEquivalent):
(WebKit::WebViewImpl::keyUp):
(WebKit::WebViewImpl::keyDown):
* UIProcess/CredentialManagement/WebCredentialsMessengerProxy.cpp:
(WebKit::WebCredentialsMessengerProxy::makeCredential):
(WebKit::WebCredentialsMessengerProxy::getAssertion):
* UIProcess/CredentialManagement/WebCredentialsMessengerProxy.h:
* UIProcess/Downloads/DownloadProxy.cpp:
(WebKit::DownloadProxy::setOriginatingPage):
* UIProcess/Launcher/ProcessLauncher.h:
* UIProcess/Launcher/mac/ProcessLauncherMac.mm:
(WebKit::ProcessLauncher::launchProcess):
* UIProcess/ProcessAssertion.h:
* UIProcess/WebPageProxy.h:
* UIProcess/WebsiteData/WebsiteDataStore.h:
* UIProcess/gtk/WaylandCompositor.cpp:
(WebKit::WaylandCompositor::Surface::attachBuffer):
* UIProcess/gtk/WaylandCompositor.h:
* UIProcess/ios/ProcessAssertionIOS.mm:
(WebKit::ProcessAssertion::ProcessAssertion):
* UIProcess/mac/DisplayLink.cpp:
(WebKit::DisplayLink::displayLinkCallback):
* WebProcess/WebPage/RemoteLayerTree/RemoteLayerTreeDisplayRefreshMonitor.mm:
(WebKit::RemoteLayerTreeDisplayRefreshMonitor::RemoteLayerTreeDisplayRefreshMonitor):
* WebProcess/WebPage/RemoteLayerTree/RemoteLayerTreeDrawingArea.h:

Source/WebKitLegacy/mac:

Add CanMakeWeakPtr base class to get WeakPtrFactory member and its getter, in
order to avoid some boilerplate code in every class needing a WeakPtrFactory.
This also gets rid of old-style createWeakPtr() methods in favor of the newer
makeWeakPtr().

* WebCoreSupport/WebEditorClient.h:
* WebCoreSupport/WebEditorClient.mm:
(WebEditorClient::requestCandidatesForSelection):

Source/WTF:

Add CanMakeWeakPtr base class to get WeakPtrFactory member and its getter, in
order to avoid some boilerplate code in every class needing a WeakPtrFactory.
This also gets rid of old-style createWeakPtr() methods in favor of the newer
makeWeakPtr().

* wtf/WeakPtr.h:
(WTF::CanMakeWeakPtr::weakPtrFactory const):
(WTF::CanMakeWeakPtr::weakPtrFactory):

git-svn-id: http://svn.webkit.org/repository/webkit/trunk@232613 268f45cc-cd09-0410-ab3c-d52691b4dbfc

157 files changed:
Source/JavaScriptCore/ChangeLog
Source/JavaScriptCore/wasm/WasmInstance.h
Source/JavaScriptCore/wasm/WasmMemory.cpp
Source/WTF/ChangeLog
Source/WTF/wtf/WeakPtr.h
Source/WebCore/ChangeLog
Source/WebCore/Modules/credentialmanagement/CredentialsMessenger.h
Source/WebCore/Modules/credentialmanagement/NavigatorCredentials.cpp
Source/WebCore/Modules/encryptedmedia/CDM.cpp
Source/WebCore/Modules/encryptedmedia/CDM.h
Source/WebCore/Modules/encryptedmedia/MediaKeySession.cpp
Source/WebCore/Modules/encryptedmedia/MediaKeySession.h
Source/WebCore/Modules/encryptedmedia/MediaKeys.cpp
Source/WebCore/Modules/encryptedmedia/MediaKeys.h
Source/WebCore/Modules/gamepad/GamepadManager.cpp
Source/WebCore/Modules/mediastream/MediaDevices.cpp
Source/WebCore/Modules/mediastream/MediaDevices.h
Source/WebCore/Modules/mediastream/MediaStreamTrack.cpp
Source/WebCore/Modules/mediastream/MediaStreamTrack.h
Source/WebCore/Modules/webauthn/cocoa/LocalAuthenticator.h
Source/WebCore/Modules/webauthn/cocoa/LocalAuthenticator.mm
Source/WebCore/PAL/ChangeLog
Source/WebCore/PAL/pal/system/mac/SystemSleepListenerMac.h
Source/WebCore/PAL/pal/system/mac/SystemSleepListenerMac.mm
Source/WebCore/accessibility/AccessibilityRenderObject.h
Source/WebCore/accessibility/AccessibilitySVGRoot.cpp
Source/WebCore/crypto/SubtleCrypto.cpp
Source/WebCore/crypto/SubtleCrypto.h
Source/WebCore/css/CSSFontFace.cpp
Source/WebCore/css/DeprecatedCSSOMValue.h
Source/WebCore/css/FontFace.cpp
Source/WebCore/css/FontFace.h
Source/WebCore/css/MediaQueryEvaluator.cpp
Source/WebCore/css/StyleSheetContents.h
Source/WebCore/css/parser/CSSDeferredParser.cpp
Source/WebCore/dom/DataTransferItemList.cpp
Source/WebCore/dom/DataTransferItemList.h
Source/WebCore/dom/Document.cpp
Source/WebCore/dom/Document.h
Source/WebCore/dom/MessagePort.h
Source/WebCore/html/HTMLImageElement.cpp
Source/WebCore/html/HTMLInputElement.h
Source/WebCore/html/HTMLMediaElement.cpp
Source/WebCore/html/HTMLMediaElement.h
Source/WebCore/html/HTMLPictureElement.h
Source/WebCore/html/parser/HTMLResourcePreloader.h
Source/WebCore/layout/layouttree/LayoutBox.h
Source/WebCore/loader/FormState.h
Source/WebCore/loader/LinkLoader.cpp
Source/WebCore/loader/LinkLoader.h
Source/WebCore/loader/LinkPreloadResourceClients.cpp
Source/WebCore/loader/MediaResourceLoader.cpp
Source/WebCore/loader/MediaResourceLoader.h
Source/WebCore/page/DOMWindow.h
Source/WebCore/page/EventHandler.cpp
Source/WebCore/platform/GenericTaskQueue.cpp
Source/WebCore/platform/GenericTaskQueue.h
Source/WebCore/platform/ScrollView.h
Source/WebCore/platform/ScrollableArea.h
Source/WebCore/platform/Scrollbar.h
Source/WebCore/platform/Widget.cpp
Source/WebCore/platform/Widget.h
Source/WebCore/platform/audio/gstreamer/AudioFileReaderGStreamer.cpp
Source/WebCore/platform/audio/mac/AudioHardwareListenerMac.cpp
Source/WebCore/platform/audio/mac/AudioHardwareListenerMac.h
Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp
Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.h
Source/WebCore/platform/graphics/FontCascade.h
Source/WebCore/platform/graphics/avfoundation/MediaPlayerPrivateAVFoundation.cpp
Source/WebCore/platform/graphics/avfoundation/MediaPlayerPrivateAVFoundation.h
Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.h
Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm
Source/WebCore/platform/graphics/avfoundation/objc/CDMSessionAVFoundationObjC.h
Source/WebCore/platform/graphics/avfoundation/objc/CDMSessionAVFoundationObjC.mm
Source/WebCore/platform/graphics/avfoundation/objc/CDMSessionAVStreamSession.h
Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.h
Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm
Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.h
Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.mm
Source/WebCore/platform/graphics/cv/TextureCacheCV.h
Source/WebCore/platform/graphics/cv/TextureCacheCV.mm
Source/WebCore/platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.cpp
Source/WebCore/platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.h
Source/WebCore/platform/graphics/gstreamer/MediaPlayerPrivateGStreamerBase.cpp
Source/WebCore/platform/graphics/gstreamer/MediaPlayerPrivateGStreamerBase.h
Source/WebCore/platform/graphics/gstreamer/mse/AppendPipeline.cpp
Source/WebCore/platform/graphics/mac/DisplayRefreshMonitorMac.cpp
Source/WebCore/platform/graphics/mac/DisplayRefreshMonitorMac.h
Source/WebCore/platform/graphics/texmap/TextureMapperLayer.cpp
Source/WebCore/platform/graphics/texmap/TextureMapperLayer.h
Source/WebCore/platform/graphics/win/MediaPlayerPrivateMediaFoundation.cpp
Source/WebCore/platform/graphics/win/MediaPlayerPrivateMediaFoundation.h
Source/WebCore/platform/ios/RemoteCommandListenerIOS.h
Source/WebCore/platform/ios/RemoteCommandListenerIOS.mm
Source/WebCore/platform/mac/RemoteCommandListenerMac.h
Source/WebCore/platform/mac/RemoteCommandListenerMac.mm
Source/WebCore/platform/mediastream/MediaStreamPrivate.cpp
Source/WebCore/platform/mediastream/MediaStreamPrivate.h
Source/WebCore/platform/mediastream/RealtimeMediaSource.cpp
Source/WebCore/platform/mediastream/RealtimeMediaSource.h
Source/WebCore/platform/mediastream/mac/ScreenDisplayCaptureSourceMac.h
Source/WebCore/platform/mediastream/mac/ScreenDisplayCaptureSourceMac.mm
Source/WebCore/platform/vr/VRPlatformDisplay.h
Source/WebCore/platform/vr/openvr/VRPlatformManagerOpenVR.cpp
Source/WebCore/rendering/FloatingObjects.h
Source/WebCore/rendering/RenderObject.h
Source/WebCore/rendering/RootInlineBox.cpp
Source/WebCore/rendering/RootInlineBox.h
Source/WebCore/svg/SVGPathElement.h
Source/WebCore/svg/SVGPathSegWithContext.h
Source/WebCore/svg/SVGTransformList.h
Source/WebCore/svg/properties/SVGAnimatedListPropertyTearOff.h
Source/WebCore/svg/properties/SVGAnimatedPathSegListPropertyTearOff.h
Source/WebCore/svg/properties/SVGAnimatedPropertyTearOff.h
Source/WebCore/svg/properties/SVGAnimatedTransformListPropertyTearOff.h
Source/WebCore/svg/properties/SVGListProperty.h
Source/WebCore/svg/properties/SVGMatrixTearOff.h
Source/WebCore/svg/properties/SVGPropertyTearOff.h
Source/WebCore/testing/MockCDMFactory.cpp
Source/WebCore/testing/MockCDMFactory.h
Source/WebCore/workers/service/ExtendableEvent.h
Source/WebCore/workers/service/FetchEvent.cpp
Source/WebCore/workers/service/server/SWServer.h
Source/WebCore/xml/DOMParser.cpp
Source/WebKit/ChangeLog
Source/WebKit/NetworkProcess/NetworkLoadChecker.h
Source/WebKit/NetworkProcess/NetworkProcess.cpp
Source/WebKit/NetworkProcess/PreconnectTask.h
Source/WebKit/NetworkProcess/cache/CacheStorageEngine.h
Source/WebKit/Shared/Authentication/AuthenticationManager.h
Source/WebKit/Shared/Authentication/cocoa/AuthenticationManagerCocoa.mm
Source/WebKit/UIProcess/API/APIAttachment.cpp
Source/WebKit/UIProcess/ApplePay/WebPaymentCoordinatorProxy.cpp
Source/WebKit/UIProcess/ApplePay/WebPaymentCoordinatorProxy.h
Source/WebKit/UIProcess/ApplePay/mac/WebPaymentCoordinatorProxyMac.mm
Source/WebKit/UIProcess/ApplicationStateTracker.h
Source/WebKit/UIProcess/ApplicationStateTracker.mm
Source/WebKit/UIProcess/Cocoa/ViewGestureController.cpp
Source/WebKit/UIProcess/Cocoa/WebViewImpl.h
Source/WebKit/UIProcess/Cocoa/WebViewImpl.mm
Source/WebKit/UIProcess/CredentialManagement/WebCredentialsMessengerProxy.cpp
Source/WebKit/UIProcess/CredentialManagement/WebCredentialsMessengerProxy.h
Source/WebKit/UIProcess/Downloads/DownloadProxy.cpp
Source/WebKit/UIProcess/Launcher/ProcessLauncher.h
Source/WebKit/UIProcess/Launcher/mac/ProcessLauncherMac.mm
Source/WebKit/UIProcess/ProcessAssertion.h
Source/WebKit/UIProcess/WebPageProxy.h
Source/WebKit/UIProcess/WebsiteData/WebsiteDataStore.h
Source/WebKit/UIProcess/gtk/WaylandCompositor.cpp
Source/WebKit/UIProcess/gtk/WaylandCompositor.h
Source/WebKit/UIProcess/ios/ProcessAssertionIOS.mm
Source/WebKit/UIProcess/mac/DisplayLink.cpp
Source/WebKit/WebProcess/WebPage/RemoteLayerTree/RemoteLayerTreeDisplayRefreshMonitor.mm
Source/WebKit/WebProcess/WebPage/RemoteLayerTree/RemoteLayerTreeDrawingArea.h
Source/WebKitLegacy/mac/ChangeLog
Source/WebKitLegacy/mac/WebCoreSupport/WebEditorClient.h
Source/WebKitLegacy/mac/WebCoreSupport/WebEditorClient.mm

index ca899d9..e89b573 100644 (file)
@@ -1,3 +1,19 @@
+2018-06-07  Chris Dumez  <cdumez@apple.com>
+
+        Add base class to get WeakPtrFactory member and avoid some boilerplate code
+        https://bugs.webkit.org/show_bug.cgi?id=186407
+
+        Reviewed by Brent Fulgham.
+
+        Add CanMakeWeakPtr base class to get WeakPtrFactory member and its getter, in
+        order to avoid some boilerplate code in every class needing a WeakPtrFactory.
+        This also gets rid of old-style createWeakPtr() methods in favor of the newer
+        makeWeakPtr().
+
+        * wasm/WasmInstance.h:
+        * wasm/WasmMemory.cpp:
+        (JSC::Wasm::Memory::registerInstance):
+
 2018-06-07  Tadeu Zagallo  <tzagallo@apple.com>
 
         Don't try to allocate JIT memory if we don't have the JIT entitlement
index c70c498..a773878 100644 (file)
@@ -40,7 +40,7 @@ namespace JSC { namespace Wasm {
 
 struct Context;
 
-class Instance : public ThreadSafeRefCounted<Instance> {
+class Instance : public ThreadSafeRefCounted<Instance>, public CanMakeWeakPtr<Instance> {
 public:
     using StoreTopCallFrameCallback = WTF::Function<void(void*)>;
 
@@ -69,7 +69,6 @@ public:
     void* cachedMemory() const { return m_cachedMemory; }
     size_t cachedMemorySize() const { return m_cachedMemorySize; }
 
-    WeakPtr<Instance> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
     void setMemory(Ref<Memory>&& memory)
     {
         m_memory = WTFMove(memory);
@@ -157,7 +156,6 @@ private:
     void** m_pointerToActualStackLimit { nullptr };
     void* m_cachedStackLimit { bitwise_cast<void*>(std::numeric_limits<uintptr_t>::max()) };
     StoreTopCallFrameCallback m_storeTopCallFrame;
-    WeakPtrFactory<Instance> m_weakPtrFactory;
     unsigned m_numImportFunctions { 0 };
 };
 
index 4c040d2..a685f0e 100644 (file)
@@ -445,11 +445,11 @@ void Memory::registerInstance(Instance* instance)
     size_t count = m_instances.size();
     for (size_t index = 0; index < count; index++) {
         if (m_instances.at(index).get() == nullptr) {
-            m_instances.at(index) = instance->createWeakPtr();
+            m_instances.at(index) = makeWeakPtr(*instance);
             return;
         }
     }
-    m_instances.append(instance->createWeakPtr());
+    m_instances.append(makeWeakPtr(*instance));
 }
 
 void Memory::dump(PrintStream& out) const
index 5ab2eb4..82b8e70 100644 (file)
@@ -1,3 +1,19 @@
+2018-06-07  Chris Dumez  <cdumez@apple.com>
+
+        Add base class to get WeakPtrFactory member and avoid some boilerplate code
+        https://bugs.webkit.org/show_bug.cgi?id=186407
+
+        Reviewed by Brent Fulgham.
+
+        Add CanMakeWeakPtr base class to get WeakPtrFactory member and its getter, in
+        order to avoid some boilerplate code in every class needing a WeakPtrFactory.
+        This also gets rid of old-style createWeakPtr() methods in favor of the newer
+        makeWeakPtr().
+
+        * wtf/WeakPtr.h:
+        (WTF::CanMakeWeakPtr::weakPtrFactory const):
+        (WTF::CanMakeWeakPtr::weakPtrFactory):
+
 2018-06-07  Tadeu Zagallo  <tzagallo@apple.com>
 
         Don't try to allocate JIT memory if we don't have the JIT entitlement
index fd9ff76..eedd81f 100644 (file)
@@ -123,6 +123,15 @@ private:
     mutable RefPtr<WeakReference<T>> m_ref;
 };
 
+template<typename T> class CanMakeWeakPtr {
+public:
+    const WeakPtrFactory<T>& weakPtrFactory() const { return m_weakFactory; }
+    WeakPtrFactory<T>& weakPtrFactory() { return m_weakFactory; }
+
+private:
+    WeakPtrFactory<T> m_weakFactory;
+};
+
 template<typename T, typename U> inline WeakReference<T>* weak_reference_upcast(WeakReference<U>* weakReference)
 {
     static_assert(std::is_convertible<U*, T*>::value, "U* must be convertible to T*");
@@ -201,6 +210,7 @@ template<typename T, typename U> inline bool operator!=(T* a, const WeakPtr<U>&
 
 } // namespace WTF
 
+using WTF::CanMakeWeakPtr;
 using WTF::WeakPtr;
 using WTF::WeakPtrFactory;
 using WTF::WeakReference;
index a3c795d..1c6d01f 100644 (file)
@@ -1,5 +1,237 @@
 2018-06-07  Chris Dumez  <cdumez@apple.com>
 
+        Add base class to get WeakPtrFactory member and avoid some boilerplate code
+        https://bugs.webkit.org/show_bug.cgi?id=186407
+
+        Reviewed by Brent Fulgham.
+
+        Add CanMakeWeakPtr base class to get WeakPtrFactory member and its getter, in
+        order to avoid some boilerplate code in every class needing a WeakPtrFactory.
+        This also gets rid of old-style createWeakPtr() methods in favor of the newer
+        makeWeakPtr().
+
+        * Modules/credentialmanagement/CredentialsMessenger.h:
+        * Modules/credentialmanagement/NavigatorCredentials.cpp:
+        (WebCore::NavigatorCredentials::credentials):
+        * Modules/encryptedmedia/CDM.cpp:
+        (WebCore::CDM::doSupportedConfigurationStep):
+        (WebCore::CDM::getConsentStatus):
+        * Modules/encryptedmedia/CDM.h:
+        * Modules/encryptedmedia/MediaKeySession.cpp:
+        (WebCore::MediaKeySession::generateRequest):
+        (WebCore::MediaKeySession::load):
+        (WebCore::MediaKeySession::update):
+        (WebCore::MediaKeySession::close):
+        (WebCore::MediaKeySession::remove):
+        * Modules/encryptedmedia/MediaKeySession.h:
+        * Modules/encryptedmedia/MediaKeys.cpp:
+        (WebCore::MediaKeys::createSession):
+        * Modules/encryptedmedia/MediaKeys.h:
+        * Modules/gamepad/GamepadManager.cpp:
+        (WebCore::GamepadManager::platformGamepadDisconnected):
+        (WebCore::GamepadManager::makeGamepadVisible):
+        * Modules/mediastream/MediaDevices.cpp:
+        (WebCore::MediaDevices::MediaDevices):
+        * Modules/mediastream/MediaDevices.h:
+        * Modules/mediastream/MediaStreamTrack.cpp:
+        (WebCore::MediaStreamTrack::applyConstraints):
+        * Modules/mediastream/MediaStreamTrack.h:
+        * Modules/webauthn/cocoa/LocalAuthenticator.h:
+        * Modules/webauthn/cocoa/LocalAuthenticator.mm:
+        (WebCore::LocalAuthenticator::makeCredential):
+        * accessibility/AccessibilityRenderObject.h:
+        * accessibility/AccessibilitySVGRoot.cpp:
+        (WebCore::AccessibilitySVGRoot::setParent):
+        * crypto/SubtleCrypto.cpp:
+        (WebCore::SubtleCrypto::encrypt):
+        (WebCore::SubtleCrypto::decrypt):
+        (WebCore::SubtleCrypto::sign):
+        (WebCore::SubtleCrypto::verify):
+        (WebCore::SubtleCrypto::digest):
+        (WebCore::SubtleCrypto::generateKey):
+        (WebCore::SubtleCrypto::deriveKey):
+        (WebCore::SubtleCrypto::deriveBits):
+        (WebCore::SubtleCrypto::importKey):
+        (WebCore::SubtleCrypto::exportKey):
+        (WebCore::SubtleCrypto::wrapKey):
+        (WebCore::SubtleCrypto::unwrapKey):
+        * crypto/SubtleCrypto.h:
+        * css/CSSFontFace.cpp:
+        (WebCore::CSSFontFace::CSSFontFace):
+        (WebCore::CSSFontFace::wrapper):
+        (WebCore::CSSFontFace::setWrapper):
+        * css/DeprecatedCSSOMValue.h:
+        * css/FontFace.cpp:
+        * css/FontFace.h:
+        * css/MediaQueryEvaluator.cpp:
+        (WebCore::MediaQueryEvaluator::MediaQueryEvaluator):
+        * css/StyleSheetContents.h:
+        * css/parser/CSSDeferredParser.cpp:
+        (WebCore::CSSDeferredParser::CSSDeferredParser):
+        * dom/DataTransferItemList.cpp:
+        (WebCore::DataTransferItemList::add):
+        (WebCore::DataTransferItemList::ensureItems const):
+        (WebCore::DataTransferItemList::didSetStringData):
+        * dom/DataTransferItemList.h:
+        * dom/Document.cpp:
+        (WebCore::Document::postTask):
+        (WebCore::Document::hasStorageAccess):
+        (WebCore::Document::requestStorageAccess):
+        * dom/Document.h:
+        (WebCore::Document::setContextDocument):
+        * dom/MessagePort.h:
+        * html/HTMLImageElement.cpp:
+        (WebCore::HTMLImageElement::setPictureElement):
+        * html/HTMLInputElement.h:
+        * html/HTMLMediaElement.cpp:
+        (WebCore::HTMLMediaElement::mediaPlayerCreateResourceLoader):
+        * html/HTMLMediaElement.h:
+        * html/HTMLPictureElement.h:
+        * html/parser/HTMLResourcePreloader.h:
+        * layout/layouttree/LayoutBox.h:
+        (WebCore::Layout::Box::style const):
+        * loader/FormState.h:
+        * loader/LinkLoader.cpp:
+        (WebCore::LinkLoader::preconnectIfNeeded):
+        * loader/LinkLoader.h:
+        * loader/LinkPreloadResourceClients.cpp:
+        (WebCore::LinkPreloadResourceClient::LinkPreloadResourceClient):
+        * loader/MediaResourceLoader.cpp:
+        (WebCore::MediaResourceLoader::MediaResourceLoader):
+        * loader/MediaResourceLoader.h:
+        * page/DOMWindow.h:
+        * page/EventHandler.cpp:
+        (WebCore::widgetForElement):
+        (WebCore::EventHandler::updateLastScrollbarUnderMouse):
+        * platform/GenericTaskQueue.cpp:
+        (WebCore::TaskDispatcher<Timer>::postTask):
+        * platform/GenericTaskQueue.h:
+        (WebCore::GenericTaskQueue::enqueueTask):
+        (WebCore::GenericTaskQueue::cancelAllTasks):
+        * platform/ScrollView.h:
+        * platform/ScrollableArea.h:
+        * platform/Scrollbar.h:
+        * platform/Widget.cpp:
+        (WebCore::Widget::setParent):
+        * platform/Widget.h:
+        * platform/audio/gstreamer/AudioFileReaderGStreamer.cpp:
+        (WebCore::AudioFileReader::decodeAudioForBusCreation):
+        * platform/audio/mac/AudioHardwareListenerMac.cpp:
+        (WebCore::AudioHardwareListenerMac::AudioHardwareListenerMac):
+        * platform/audio/mac/AudioHardwareListenerMac.h:
+        * platform/encryptedmedia/clearkey/CDMClearKey.cpp:
+        (WebCore::CDMInstanceClearKey::requestLicense):
+        (WebCore::CDMInstanceClearKey::updateLicense):
+        (WebCore::CDMInstanceClearKey::loadSession):
+        (WebCore::CDMInstanceClearKey::closeSession):
+        (WebCore::CDMInstanceClearKey::removeSessionData):
+        * platform/encryptedmedia/clearkey/CDMClearKey.h:
+        * platform/graphics/FontCascade.h:
+        * platform/graphics/avfoundation/MediaPlayerPrivateAVFoundation.cpp:
+        (WebCore::MediaPlayerPrivateAVFoundation::scheduleMainThreadNotification):
+        (WebCore::MediaPlayerPrivateAVFoundation::dispatchNotification):
+        * platform/graphics/avfoundation/MediaPlayerPrivateAVFoundation.h:
+        * platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.h:
+        * platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm:
+        (WebCore::CDMInstanceFairPlayStreamingAVFObjC::didProvideRequest):
+        * platform/graphics/avfoundation/objc/CDMSessionAVFoundationObjC.h:
+        * platform/graphics/avfoundation/objc/CDMSessionAVFoundationObjC.mm:
+        (WebCore::CDMSessionAVFoundationObjC::CDMSessionAVFoundationObjC):
+        * platform/graphics/avfoundation/objc/CDMSessionAVStreamSession.h:
+        * platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.h:
+        * platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm:
+        (WebCore::MediaPlayerPrivateAVFoundationObjC::createVideoLayer):
+        (WebCore::MediaPlayerPrivateAVFoundationObjC::checkPlayability):
+        (WebCore::MediaPlayerPrivateAVFoundationObjC::beginLoadingMetadata):
+        (WebCore::MediaPlayerPrivateAVFoundationObjC::seekToTime):
+        (WebCore::MediaPlayerPrivateAVFoundationObjC::createSession):
+        (WebCore::MediaPlayerPrivateAVFoundationObjC::setShouldPlayToPlaybackTarget):
+        (-[WebCoreAVFMovieObserver observeValueForKeyPath:ofObject:change:context:]):
+        * platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.h:
+        * platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.mm:
+        (WebCore::MediaPlayerPrivateMediaStreamAVFObjC::requestNotificationWhenReadyForVideoData):
+        (WebCore::MediaPlayerPrivateMediaStreamAVFObjC::scheduleDeferredTask):
+        * platform/graphics/cv/TextureCacheCV.h:
+        * platform/graphics/cv/TextureCacheCV.mm:
+        (WebCore::TextureCacheCV::textureFromImage):
+        * platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.cpp:
+        (WebCore::MediaPlayerPrivateGStreamer::notifyPlayerOfVideo):
+        (WebCore::MediaPlayerPrivateGStreamer::notifyPlayerOfAudio):
+        (WebCore::MediaPlayerPrivateGStreamer::handleMessage):
+        * platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.h:
+        * platform/graphics/gstreamer/MediaPlayerPrivateGStreamerBase.cpp:
+        (WebCore::MediaPlayerPrivateGStreamerBase::handleSyncMessage):
+        (WebCore::MediaPlayerPrivateGStreamerBase::initializationDataEncountered):
+        * platform/graphics/gstreamer/MediaPlayerPrivateGStreamerBase.h:
+        * platform/graphics/gstreamer/mse/AppendPipeline.cpp:
+        (WebCore::AppendPipeline::connectDemuxerSrcPadToAppsink):
+        * platform/graphics/mac/DisplayRefreshMonitorMac.cpp:
+        (WebCore::DisplayRefreshMonitorMac::displayLinkFired):
+        * platform/graphics/mac/DisplayRefreshMonitorMac.h:
+        * platform/graphics/texmap/TextureMapperLayer.cpp:
+        (WebCore::TextureMapperLayer::setMaskLayer):
+        (WebCore::TextureMapperLayer::setReplicaLayer):
+        * platform/graphics/texmap/TextureMapperLayer.h:
+        * platform/graphics/win/MediaPlayerPrivateMediaFoundation.cpp:
+        (WebCore::MediaPlayerPrivateMediaFoundation::endCreatedMediaSource):
+        (WebCore::MediaPlayerPrivateMediaFoundation::endGetEvent):
+        (WebCore::MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::processInputNotify):
+        * platform/graphics/win/MediaPlayerPrivateMediaFoundation.h:
+        * platform/ios/RemoteCommandListenerIOS.h:
+        * platform/ios/RemoteCommandListenerIOS.mm:
+        (WebCore::RemoteCommandListenerIOS::RemoteCommandListenerIOS):
+        * platform/mac/RemoteCommandListenerMac.h:
+        * platform/mac/RemoteCommandListenerMac.mm:
+        (WebCore::RemoteCommandListenerMac::RemoteCommandListenerMac):
+        * platform/mediastream/MediaStreamPrivate.cpp:
+        (WebCore::MediaStreamPrivate::scheduleDeferredTask):
+        * platform/mediastream/MediaStreamPrivate.h:
+        * platform/mediastream/RealtimeMediaSource.cpp:
+        (WebCore::RealtimeMediaSource::scheduleDeferredTask):
+        * platform/mediastream/RealtimeMediaSource.h:
+        * platform/mediastream/mac/ScreenDisplayCaptureSourceMac.h:
+        * platform/mediastream/mac/ScreenDisplayCaptureSourceMac.mm:
+        (WebCore::ScreenDisplayCaptureSourceMac::createDisplayStream):
+        * platform/vr/VRPlatformDisplay.h:
+        * platform/vr/openvr/VRPlatformManagerOpenVR.cpp:
+        (WebCore::VRPlatformManagerOpenVR::getVRDisplays):
+        * rendering/FloatingObjects.h:
+        (WebCore::FloatingObject::setOriginatingLine):
+        * rendering/RenderObject.h:
+        * rendering/RootInlineBox.cpp:
+        * rendering/RootInlineBox.h:
+        * svg/SVGPathElement.h:
+        * svg/SVGPathSegWithContext.h:
+        (WebCore::SVGPathSegWithContext::SVGPathSegWithContext):
+        (WebCore::SVGPathSegWithContext::setContextAndRole):
+        * svg/SVGTransformList.h:
+        * svg/properties/SVGAnimatedListPropertyTearOff.h:
+        (WebCore::SVGAnimatedListPropertyTearOff::baseVal):
+        (WebCore::SVGAnimatedListPropertyTearOff::animVal):
+        * svg/properties/SVGAnimatedPathSegListPropertyTearOff.h:
+        * svg/properties/SVGAnimatedPropertyTearOff.h:
+        * svg/properties/SVGAnimatedTransformListPropertyTearOff.h:
+        * svg/properties/SVGListProperty.h:
+        (WebCore::SVGListProperty::initializeValuesAndWrappers):
+        (WebCore::SVGListProperty::getItemValuesAndWrappers):
+        (WebCore::SVGListProperty::insertItemBeforeValuesAndWrappers):
+        (WebCore::SVGListProperty::replaceItemValuesAndWrappers):
+        (WebCore::SVGListProperty::appendItemValuesAndWrappers):
+        * svg/properties/SVGMatrixTearOff.h:
+        * svg/properties/SVGPropertyTearOff.h:
+        * testing/MockCDMFactory.cpp:
+        (WebCore::MockCDMFactory::createCDM):
+        (WebCore::MockCDM::createInstance):
+        * testing/MockCDMFactory.h:
+        * workers/service/ExtendableEvent.h:
+        * workers/service/FetchEvent.cpp:
+        (WebCore::FetchEvent::respondWith):
+        * workers/service/server/SWServer.h:
+        * xml/DOMParser.cpp:
+        (WebCore::DOMParser::DOMParser):
+
+2018-06-07  Chris Dumez  <cdumez@apple.com>
+
         PopStateEvent should not be cancelable by default
         https://bugs.webkit.org/show_bug.cgi?id=186420
 
index 3d8cc95..f28af95 100644 (file)
@@ -70,7 +70,7 @@ using CreationCompletionHandler = CompletionHandler<void(ExceptionOr<CreationRet
 using RequestCompletionHandler = CompletionHandler<void(ExceptionOr<AssertionReturnBundle>&&)>;
 using QueryCompletionHandler = CompletionHandler<void(bool)>;
 
-class CredentialsMessenger {
+class CredentialsMessenger : public CanMakeWeakPtr<CredentialsMessenger> {
     WTF_MAKE_FAST_ALLOCATED;
     WTF_MAKE_NONCOPYABLE(CredentialsMessenger);
 public:
@@ -87,8 +87,6 @@ public:
     virtual void getAssertionReply(uint64_t messageId, const Vector<uint8_t>& credentialId, const Vector<uint8_t>& authenticatorData, const Vector<uint8_t>& signature, const Vector<uint8_t>& userHandle) = 0;
     virtual void isUserVerifyingPlatformAuthenticatorAvailableReply(uint64_t messageId, bool) = 0;
 
-    auto& weakPtrFactory() const { return m_weakFactory; }
-
 protected:
     virtual ~CredentialsMessenger() = default;
 
@@ -100,8 +98,6 @@ protected:
     WEBCORE_EXPORT QueryCompletionHandler takeQueryCompletionHandler(uint64_t);
 
 private:
-    WeakPtrFactory<CredentialsMessenger> m_weakFactory;
-
     enum CallBackClassifier : uint64_t {
         Creation = 0x01,
         Request = 0x02,
index 9d8f0cf..71f438c 100644 (file)
@@ -56,7 +56,7 @@ CredentialsContainer* NavigatorCredentials::credentials(Navigator& navigator)
 {
     if (!navigator.frame() || !navigator.frame()->document())
         return nullptr;
-    return NavigatorCredentials::from(&navigator)->credentials(navigator.frame()->document()->createWeakPtr());
+    return NavigatorCredentials::from(&navigator)->credentials(makeWeakPtr(*navigator.frame()->document()));
 }
 
 NavigatorCredentials* NavigatorCredentials::from(Navigator* navigator)
index a2bd44c..34cf3d3 100644 (file)
@@ -106,7 +106,7 @@ void CDM::doSupportedConfigurationStep(MediaKeySystemConfiguration&& candidateCo
         return;
     }
 
-    auto consentCallback = [weakThis = createWeakPtr(), callback = WTFMove(callback)] (ConsentStatus status, MediaKeySystemConfiguration&& configuration, MediaKeysRestrictions&& restrictions) mutable {
+    auto consentCallback = [weakThis = makeWeakPtr(*this), callback = WTFMove(callback)] (ConsentStatus status, MediaKeySystemConfiguration&& configuration, MediaKeysRestrictions&& restrictions) mutable {
         if (!weakThis) {
             callback(std::nullopt);
             return;
@@ -511,7 +511,7 @@ void CDM::getConsentStatus(MediaKeySystemConfiguration&& accumulatedConfiguratio
     // NOTE: In the future, these checks belowe will involve asking the page client, possibly across a process boundary.
     // They will by necessity be asynchronous with callbacks. For now, imply this behavior by performing it in an async task.
 
-    m_scriptExecutionContext->postTask([this, weakThis = createWeakPtr(), accumulatedConfiguration = WTFMove(accumulatedConfiguration), restrictions = WTFMove(restrictions), callback = WTFMove(callback)] (ScriptExecutionContext&) mutable {
+    m_scriptExecutionContext->postTask([this, weakThis = makeWeakPtr(*this), accumulatedConfiguration = WTFMove(accumulatedConfiguration), restrictions = WTFMove(restrictions), callback = WTFMove(callback)] (ScriptExecutionContext&) mutable {
         if (!weakThis || !m_private) {
             callback(ConsentStatus::ConsentDenied, WTFMove(accumulatedConfiguration), WTFMove(restrictions));
             return;
index 4bf7b68..e1558c5 100644 (file)
@@ -49,7 +49,7 @@ class Document;
 class ScriptExecutionContext;
 class SharedBuffer;
 
-class CDM : public RefCounted<CDM>, private ContextDestructionObserver {
+class CDM : public RefCounted<CDM>, public CanMakeWeakPtr<CDM>, private ContextDestructionObserver {
 public:
     static bool supportsKeySystem(const String&);
     static bool isPersistentType(MediaKeySessionType);
@@ -101,13 +101,10 @@ private:
     std::optional<MediaKeySystemConfiguration>  getSupportedConfiguration(const MediaKeySystemConfiguration& candidateConfiguration, MediaKeysRestrictions&);
     std::optional<Vector<MediaKeySystemMediaCapability>> getSupportedCapabilitiesForAudioVideoType(AudioVideoType, const Vector<MediaKeySystemMediaCapability>& requestedCapabilities, const MediaKeySystemConfiguration& partialConfiguration, MediaKeysRestrictions&);
 
-    WeakPtr<CDM> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
     using ConsentStatusCallback = WTF::Function<void(ConsentStatus, MediaKeySystemConfiguration&&, MediaKeysRestrictions&&)>;
     void getConsentStatus(MediaKeySystemConfiguration&& accumulatedConfiguration, MediaKeysRestrictions&&, ConsentStatusCallback&&);
     String m_keySystem;
     std::unique_ptr<CDMPrivate> m_private;
-    WeakPtrFactory<CDM> m_weakPtrFactory;
 };
 
 }
index 77c3771..9427cd4 100644 (file)
@@ -194,7 +194,7 @@ void MediaKeySession::generateRequest(const AtomicString& initDataType, const Bu
             m_latestDecryptTime = 0;
         }
 
-        m_instance->requestLicense(m_sessionType, initDataType, WTFMove(initData), [this, weakThis = m_weakPtrFactory.createWeakPtr(*this), promise = WTFMove(promise)] (Ref<SharedBuffer>&& message, const String& sessionId, bool needsIndividualization, CDMInstance::SuccessValue succeeded) mutable {
+        m_instance->requestLicense(m_sessionType, initDataType, WTFMove(initData), [this, weakThis = makeWeakPtr(*this), promise = WTFMove(promise)] (Ref<SharedBuffer>&& message, const String& sessionId, bool needsIndividualization, CDMInstance::SuccessValue succeeded) mutable {
             if (!weakThis)
                 return;
 
@@ -287,7 +287,7 @@ void MediaKeySession::load(const String& sessionId, Ref<DeferredPromise>&& promi
         // 8.6. Let message type be null.
         // 8.7. Let cdm be the CDM instance represented by this object's cdm instance value.
         // 8.8. Use the cdm to execute the following steps:
-        m_instance->loadSession(m_sessionType, *sanitizedSessionId, origin, [this, weakThis = m_weakPtrFactory.createWeakPtr(*this), promise = WTFMove(promise), sanitizedSessionId = *sanitizedSessionId] (std::optional<CDMInstance::KeyStatusVector>&& knownKeys, std::optional<double>&& expiration, std::optional<CDMInstance::Message>&& message, CDMInstance::SuccessValue succeeded, CDMInstance::SessionLoadFailure failure) mutable {
+        m_instance->loadSession(m_sessionType, *sanitizedSessionId, origin, [this, weakThis = makeWeakPtr(*this), promise = WTFMove(promise), sanitizedSessionId = *sanitizedSessionId] (std::optional<CDMInstance::KeyStatusVector>&& knownKeys, std::optional<double>&& expiration, std::optional<CDMInstance::Message>&& message, CDMInstance::SuccessValue succeeded, CDMInstance::SessionLoadFailure failure) mutable {
             // 8.8.1. If there is no data stored for the sanitized session ID in the origin, resolve promise with false and abort these steps.
             // 8.8.2. If the stored session's session type is not the same as the current MediaKeySession session type, reject promise with a newly created TypeError.
             // 8.8.3. Let session data be the data stored for the sanitized session ID in the origin. This must not include data from other origin(s) or that is not associated with an origin.
@@ -388,7 +388,7 @@ void MediaKeySession::update(const BufferSource& response, Ref<DeferredPromise>&
         // 6.5. Let session closed be false.
         // 6.6. Let cdm be the CDM instance represented by this object's cdm instance value.
         // 6.7. Use the cdm to execute the following steps:
-        m_instance->updateLicense(m_sessionId, m_sessionType, *sanitizedResponse, [this, weakThis = m_weakPtrFactory.createWeakPtr(*this), promise = WTFMove(promise)] (bool sessionWasClosed, std::optional<CDMInstance::KeyStatusVector>&& changedKeys, std::optional<double>&& changedExpiration, std::optional<CDMInstance::Message>&& message, CDMInstance::SuccessValue succeeded) mutable {
+        m_instance->updateLicense(m_sessionId, m_sessionType, *sanitizedResponse, [this, weakThis = makeWeakPtr(*this), promise = WTFMove(promise)] (bool sessionWasClosed, std::optional<CDMInstance::KeyStatusVector>&& changedKeys, std::optional<double>&& changedExpiration, std::optional<CDMInstance::Message>&& message, CDMInstance::SuccessValue succeeded) mutable {
             if (!weakThis)
                 return;
 
@@ -500,7 +500,7 @@ void MediaKeySession::close(Ref<DeferredPromise>&& promise)
     m_taskQueue.enqueueTask([this, promise = WTFMove(promise)] () mutable {
         // 5.1. Let cdm be the CDM instance represented by session's cdm instance value.
         // 5.2. Use cdm to close the key session associated with session.
-        m_instance->closeSession(m_sessionId, [this, weakThis = m_weakPtrFactory.createWeakPtr(*this), promise = WTFMove(promise)] () mutable {
+        m_instance->closeSession(m_sessionId, [this, weakThis = makeWeakPtr(*this), promise = WTFMove(promise)] () mutable {
             if (!weakThis)
                 return;
 
@@ -538,7 +538,7 @@ void MediaKeySession::remove(Ref<DeferredPromise>&& promise)
         // 4.3. Let message type be null.
 
         // 4.4. Use the cdm to execute the following steps:
-        m_instance->removeSessionData(m_sessionId, m_sessionType, [this, weakThis = m_weakPtrFactory.createWeakPtr(*this), promise = WTFMove(promise)] (CDMInstance::KeyStatusVector&& keys, std::optional<Ref<SharedBuffer>>&& message, CDMInstance::SuccessValue succeeded) mutable {
+        m_instance->removeSessionData(m_sessionId, m_sessionType, [this, weakThis = makeWeakPtr(*this), promise = WTFMove(promise)] (CDMInstance::KeyStatusVector&& keys, std::optional<Ref<SharedBuffer>>&& message, CDMInstance::SuccessValue succeeded) mutable {
             if (!weakThis)
                 return;
 
index ecc57b4..0d1900e 100644 (file)
@@ -52,7 +52,7 @@ class MediaKeyStatusMap;
 class MediaKeys;
 class SharedBuffer;
 
-class MediaKeySession final : public RefCounted<MediaKeySession>, public EventTargetWithInlineData, public ActiveDOMObject, public CDMInstanceClient {
+class MediaKeySession final : public RefCounted<MediaKeySession>, public EventTargetWithInlineData, public ActiveDOMObject, public CanMakeWeakPtr<MediaKeySession>, public CDMInstanceClient {
 public:
     static Ref<MediaKeySession> create(ScriptExecutionContext&, WeakPtr<MediaKeys>&&, MediaKeySessionType, bool useDistinctiveIdentifier, Ref<CDM>&&, Ref<CDMInstance>&&);
     virtual ~MediaKeySession();
@@ -117,7 +117,6 @@ private:
     double m_firstDecryptTime { 0 };
     double m_latestDecryptTime { 0 };
     Vector<std::pair<Ref<SharedBuffer>, MediaKeyStatus>> m_statuses;
-    WeakPtrFactory<MediaKeySession> m_weakPtrFactory;
 };
 
 } // namespace WebCore
index bef36a3..39fbb80 100644 (file)
@@ -67,7 +67,7 @@ ExceptionOr<Ref<MediaKeySession>> MediaKeys::createSession(ScriptExecutionContex
     // 3. Let session be a new MediaKeySession object, and initialize it as follows:
     // NOTE: Continued in MediaKeySession.
     // 4. Return session.
-    auto session = MediaKeySession::create(context, m_weakPtrFactory.createWeakPtr(*this), sessionType, m_useDistinctiveIdentifier, m_implementation.copyRef(), m_instance.copyRef());
+    auto session = MediaKeySession::create(context, makeWeakPtr(*this), sessionType, m_useDistinctiveIdentifier, m_implementation.copyRef(), m_instance.copyRef());
     m_sessions.append(session.copyRef());
     return WTFMove(session);
 }
index 73c9fb2..914614d 100644 (file)
@@ -46,7 +46,7 @@ class CDMInstance;
 class BufferSource;
 class MediaKeySession;
 
-class MediaKeys : public RefCounted<MediaKeys> {
+class MediaKeys : public RefCounted<MediaKeys>, public CanMakeWeakPtr<MediaKeys> {
 public:
     using KeySessionType = MediaKeySessionType;
 
@@ -77,7 +77,6 @@ protected:
     Ref<CDM> m_implementation;
     Ref<CDMInstance> m_instance;
 
-    WeakPtrFactory<MediaKeys> m_weakPtrFactory;
     Vector<Ref<MediaKeySession>> m_sessions;
     Vector<CDMClient*> m_cdmClients;
     GenericTaskQueue<Timer> m_taskQueue;
index b21a0d5..3d30ec7 100644 (file)
@@ -82,7 +82,7 @@ void GamepadManager::platformGamepadDisconnected(PlatformGamepad& platformGamepa
 {
     Vector<WeakPtr<DOMWindow>> weakWindows;
     for (auto* domWindow : m_domWindows)
-        weakWindows.append(domWindow->createWeakPtr());
+        weakWindows.append(makeWeakPtr(*domWindow));
 
     HashSet<NavigatorGamepad*> notifiedNavigators;
 
@@ -144,7 +144,7 @@ void GamepadManager::makeGamepadVisible(PlatformGamepad& platformGamepad, HashSe
 
     Vector<WeakPtr<DOMWindow>> weakWindows;
     for (auto* domWindow : m_domWindows)
-        weakWindows.append(domWindow->createWeakPtr());
+        weakWindows.append(makeWeakPtr(*domWindow));
 
     for (auto& window : weakWindows) {
         // Event dispatch might have made this window go away.
index 0d82fc3..af3bf13 100644 (file)
@@ -50,7 +50,7 @@ inline MediaDevices::MediaDevices(Document& document)
     : ContextDestructionObserver(&document)
     , m_scheduledEventTimer(*this, &MediaDevices::scheduledEventTimerFired)
 {
-    m_deviceChangedToken = RealtimeMediaSourceCenter::singleton().addDevicesChangedObserver([weakThis = createWeakPtr(), this]() {
+    m_deviceChangedToken = RealtimeMediaSourceCenter::singleton().addDevicesChangedObserver([weakThis = makeWeakPtr(*this), this]() {
 
         if (!weakThis)
             return;
index 04cc605..ae35d5e 100644 (file)
@@ -49,7 +49,7 @@ class MediaStream;
 
 struct MediaTrackSupportedConstraints;
 
-class MediaDevices : public RefCounted<MediaDevices>, public ContextDestructionObserver, public EventTargetWithInlineData {
+class MediaDevices : public RefCounted<MediaDevices>, public ContextDestructionObserver, public EventTargetWithInlineData, public CanMakeWeakPtr<MediaDevices> {
 public:
     static Ref<MediaDevices> create(Document&);
 
@@ -90,11 +90,8 @@ private:
     void refEventTarget() override { ref(); }
     void derefEventTarget() override { deref(); }
 
-    WeakPtr<MediaDevices> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
     Timer m_scheduledEventTimer;
     std::optional<RealtimeMediaSourceCenter::DevicesChangedObserverToken> m_deviceChangedToken;
-    WeakPtrFactory<MediaDevices> m_weakPtrFactory;
 };
 
 } // namespace WebCore
index 8676942..b2a8f0b 100644 (file)
@@ -277,7 +277,7 @@ void MediaStreamTrack::applyConstraints(const std::optional<MediaTrackConstraint
 {
     m_promise = WTFMove(promise);
 
-    auto weakThis = createWeakPtr();
+    auto weakThis = makeWeakPtr(*this);
     auto failureHandler = [weakThis] (const String& failedConstraint, const String& message) {
         if (!weakThis || !weakThis->m_promise)
             return;
index da1b1c0..515acc1 100644 (file)
@@ -50,6 +50,7 @@ class MediaStreamTrack :
     public RefCounted<MediaStreamTrack>,
     public ActiveDOMObject,
     public EventTargetWithInlineData,
+    public CanMakeWeakPtr<MediaStreamTrack>,
     private MediaProducer,
     private MediaStreamTrackPrivate::Observer {
 public:
@@ -169,14 +170,11 @@ private:
     void trackSettingsChanged(MediaStreamTrackPrivate&) final;
     void trackEnabledChanged(MediaStreamTrackPrivate&) final;
 
-    WeakPtr<MediaStreamTrack> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
     Vector<Observer*> m_observers;
     Ref<MediaStreamTrackPrivate> m_private;
 
     MediaTrackConstraints m_constraints;
     std::optional<DOMPromiseDeferred<void>> m_promise;
-    WeakPtrFactory<MediaStreamTrack> m_weakPtrFactory;
     GenericTaskQueue<ScriptExecutionContext> m_taskQueue;
 
     bool m_ended { false };
index e19b5d9..2ae4035 100644 (file)
@@ -44,7 +44,7 @@ using ExceptionCallback = Function<void(const WebCore::ExceptionData&)>;
 typedef void (^CompletionBlock)(SecKeyRef _Nullable referenceKey, NSArray * _Nullable certificates, NSError * _Nullable error);
 
 // FIXME(182769): LocalAuthenticator should belongs to WebKit. However, we need unit tests.
-class WEBCORE_EXPORT LocalAuthenticator {
+class WEBCORE_EXPORT LocalAuthenticator : public CanMakeWeakPtr<LocalAuthenticator> {
     WTF_MAKE_NONCOPYABLE(LocalAuthenticator);
 public:
     LocalAuthenticator();
@@ -57,8 +57,6 @@ public:
 protected:
     // Apple Attestation is moved into this virtual method such that it can be overrided by self attestation for testing.
     virtual void issueClientCertificate(const String& rpId, const String& username, const Vector<uint8_t>& hash, CompletionBlock _Nonnull) const;
-
-    WeakPtrFactory<LocalAuthenticator> m_weakFactory;
 };
 
 } // namespace WebCore
index 74a19a3..3a740ed 100644 (file)
@@ -186,7 +186,7 @@ void LocalAuthenticator::makeCredential(const Vector<uint8_t>& hash, const Publi
 
     NSString *reason = [NSString stringWithFormat:@"Allow %@ to create a public key credential for %@", (id)options.rp.id, (id)options.user.name];
     // FIXME(183534): Optimize the following nested callbacks and threading.
-    [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:reason reply:BlockPtr<void(BOOL, NSError *)>::fromCallable([weakThis = m_weakFactory.createWeakPtr(*this), callback = WTFMove(callback), exceptionCallback = WTFMove(exceptionCallback), options = crossThreadCopy(options), hash] (BOOL success, NSError *error) mutable {
+    [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:reason reply:BlockPtr<void(BOOL, NSError *)>::fromCallable([weakThis = makeWeakPtr(*this), callback = WTFMove(callback), exceptionCallback = WTFMove(exceptionCallback), options = crossThreadCopy(options), hash] (BOOL success, NSError *error) mutable {
         ASSERT(!isMainThread());
         if (!success || error) {
             LOG_ERROR("Couldn't authenticate with biometrics: %@", error);
index 0b887c0..316b921 100644 (file)
@@ -1,3 +1,16 @@
+2018-06-07  Chris Dumez  <cdumez@apple.com>
+
+        Add base class to get WeakPtrFactory member and avoid some boilerplate code
+        https://bugs.webkit.org/show_bug.cgi?id=186407
+
+        Reviewed by Brent Fulgham.
+
+        186407_CanMakeWeakPtr
+
+        * pal/system/mac/SystemSleepListenerMac.h:
+        * pal/system/mac/SystemSleepListenerMac.mm:
+        (PAL::SystemSleepListenerMac::SystemSleepListenerMac):
+
 2018-06-06  Simon Fraser  <simon.fraser@apple.com>
 
         Logging macros are sensitive to pal/Logging.h vs Logging.h include order
index 9226e10..5251bb7 100644 (file)
@@ -32,7 +32,7 @@
 
 namespace PAL {
 
-class SystemSleepListenerMac : public SystemSleepListener {
+class SystemSleepListenerMac : public SystemSleepListener, public CanMakeWeakPtr<SystemSleepListenerMac> {
     WTF_MAKE_FAST_ALLOCATED;
 protected:
     SystemSleepListenerMac(Client&);
@@ -40,7 +40,6 @@ protected:
 
     friend std::unique_ptr<SystemSleepListener> SystemSleepListener::create(Client&);
 
-    WeakPtrFactory<SystemSleepListenerMac> m_weakPtrFactory;
     id m_sleepObserver;
     id m_wakeObserver;
 };
index 6d53a7b..17f646c 100644 (file)
@@ -46,7 +46,7 @@ SystemSleepListenerMac::SystemSleepListenerMac(Client& client)
     NSNotificationCenter *center = [[NSWorkspace sharedWorkspace] notificationCenter];
     NSOperationQueue *queue = [NSOperationQueue mainQueue];
 
-    auto weakThis = m_weakPtrFactory.createWeakPtr(*this);
+    auto weakThis = makeWeakPtr(*this);
 
     m_sleepObserver = [center addObserverForName:NSWorkspaceWillSleepNotification object:nil queue:queue usingBlock:^(NSNotification *) {
         callOnMainThread([weakThis] {
index 81bb5be..48af65a 100644 (file)
@@ -52,7 +52,7 @@ class RenderView;
 class VisibleSelection;
 class Widget;
     
-class AccessibilityRenderObject : public AccessibilityNodeObject {
+class AccessibilityRenderObject : public AccessibilityNodeObject, public CanMakeWeakPtr<AccessibilityRenderObject> {
 public:
     static Ref<AccessibilityRenderObject> create(RenderObject*);
     virtual ~AccessibilityRenderObject();
@@ -200,8 +200,6 @@ public:
     AccessibilityRole roleValueForMSAA() const override;
 
     String passwordFieldValue() const override;
-    
-    WeakPtr<AccessibilityRenderObject> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
 
 protected:
     explicit AccessibilityRenderObject(RenderObject*);
@@ -220,7 +218,6 @@ protected:
     WeakPtr<RenderObject> m_renderer;
 
 private:
-    WeakPtrFactory<AccessibilityRenderObject> m_weakPtrFactory;
     bool isAccessibilityRenderObject() const final { return true; }
     void ariaListboxSelectedChildren(AccessibilityChildrenVector&);
     void ariaListboxVisibleChildren(AccessibilityChildrenVector&);
index f14dd67..3236af0 100644 (file)
@@ -45,12 +45,9 @@ Ref<AccessibilitySVGRoot> AccessibilitySVGRoot::create(RenderObject* renderer)
     return adoptRef(*new AccessibilitySVGRoot(renderer));
 }
 
-void AccessibilitySVGRoot::setParent(AccessibilityRenderObject *parent)
+void AccessibilitySVGRoot::setParent(AccessibilityRenderObjectparent)
 {
-    if (parent)
-        m_parent = parent->createWeakPtr();
-    else
-        m_parent = nullptr;
+    m_parent = makeWeakPtr(parent);
 }
     
 AccessibilityObject* AccessibilitySVGRoot::parentObject() const
index fc6aa12..a0d0d9a 100644 (file)
@@ -543,7 +543,7 @@ void SubtleCrypto::encrypt(JSC::ExecState& state, AlgorithmIdentifier&& algorith
 
     auto index = promise.ptr();
     m_pendingPromises.add(index, WTFMove(promise));
-    auto subtleCryptoWeakPointer = m_weakPtrFactory.createWeakPtr(*this);
+    auto subtleCryptoWeakPointer = makeWeakPtr(*this);
     auto callback = [index, subtleCryptoWeakPointer](const Vector<uint8_t>& cipherText) mutable {
         if (auto promise = getPromise(index, subtleCryptoWeakPointer))
             fulfillPromiseWithArrayBuffer(promise.releaseNonNull(), cipherText.data(), cipherText.size());
@@ -581,7 +581,7 @@ void SubtleCrypto::decrypt(JSC::ExecState& state, AlgorithmIdentifier&& algorith
 
     auto index = promise.ptr();
     m_pendingPromises.add(index, WTFMove(promise));
-    auto subtleCryptoWeakPointer = m_weakPtrFactory.createWeakPtr(*this);
+    auto subtleCryptoWeakPointer = makeWeakPtr(*this);
     auto callback = [index, subtleCryptoWeakPointer](const Vector<uint8_t>& plainText) mutable {
         if (auto promise = getPromise(index, subtleCryptoWeakPointer))
             fulfillPromiseWithArrayBuffer(promise.releaseNonNull(), plainText.data(), plainText.size());
@@ -619,7 +619,7 @@ void SubtleCrypto::sign(JSC::ExecState& state, AlgorithmIdentifier&& algorithmId
 
     auto index = promise.ptr();
     m_pendingPromises.add(index, WTFMove(promise));
-    auto subtleCryptoWeakPointer = m_weakPtrFactory.createWeakPtr(*this);
+    auto subtleCryptoWeakPointer = makeWeakPtr(*this);
     auto callback = [index, subtleCryptoWeakPointer](const Vector<uint8_t>& signature) mutable {
         if (auto promise = getPromise(index, subtleCryptoWeakPointer))
             fulfillPromiseWithArrayBuffer(promise.releaseNonNull(), signature.data(), signature.size());
@@ -658,7 +658,7 @@ void SubtleCrypto::verify(JSC::ExecState& state, AlgorithmIdentifier&& algorithm
 
     auto index = promise.ptr();
     m_pendingPromises.add(index, WTFMove(promise));
-    auto subtleCryptoWeakPointer = m_weakPtrFactory.createWeakPtr(*this);
+    auto subtleCryptoWeakPointer = makeWeakPtr(*this);
     auto callback = [index, subtleCryptoWeakPointer](bool result) mutable {
         if (auto promise = getPromise(index, subtleCryptoWeakPointer))
             promise->resolve<IDLBoolean>(result);
@@ -686,7 +686,7 @@ void SubtleCrypto::digest(JSC::ExecState& state, AlgorithmIdentifier&& algorithm
 
     auto index = promise.ptr();
     m_pendingPromises.add(index, WTFMove(promise));
-    auto subtleCryptoWeakPointer = m_weakPtrFactory.createWeakPtr(*this);
+    auto subtleCryptoWeakPointer = makeWeakPtr(*this);
     auto callback = [index, subtleCryptoWeakPointer](const Vector<uint8_t>& digest) mutable {
         if (auto promise = getPromise(index, subtleCryptoWeakPointer))
             fulfillPromiseWithArrayBuffer(promise.releaseNonNull(), digest.data(), digest.size());
@@ -714,7 +714,7 @@ void SubtleCrypto::generateKey(JSC::ExecState& state, AlgorithmIdentifier&& algo
 
     auto index = promise.ptr();
     m_pendingPromises.add(index, WTFMove(promise));
-    auto subtleCryptoWeakPointer = m_weakPtrFactory.createWeakPtr(*this);
+    auto subtleCryptoWeakPointer = makeWeakPtr(*this);
     auto callback = [index, subtleCryptoWeakPointer](KeyOrKeyPair&& keyOrKeyPair) mutable {
         if (auto promise = getPromise(index, subtleCryptoWeakPointer)) {
             WTF::switchOn(keyOrKeyPair,
@@ -795,7 +795,7 @@ void SubtleCrypto::deriveKey(JSC::ExecState& state, AlgorithmIdentifier&& algori
 
     auto index = promise.ptr();
     m_pendingPromises.add(index, WTFMove(promise));
-    auto subtleCryptoWeakPointer = m_weakPtrFactory.createWeakPtr(*this);
+    auto subtleCryptoWeakPointer = makeWeakPtr(*this);
     auto callback = [index, subtleCryptoWeakPointer, importAlgorithm, importParams = WTFMove(importParams), extractable, keyUsagesBitmap](const Vector<uint8_t>& derivedKey) mutable {
         // FIXME: https://bugs.webkit.org/show_bug.cgi?id=169395
         KeyData data = derivedKey;
@@ -846,7 +846,7 @@ void SubtleCrypto::deriveBits(JSC::ExecState& state, AlgorithmIdentifier&& algor
 
     auto index = promise.ptr();
     m_pendingPromises.add(index, WTFMove(promise));
-    auto subtleCryptoWeakPointer = m_weakPtrFactory.createWeakPtr(*this);
+    auto subtleCryptoWeakPointer = makeWeakPtr(*this);
     auto callback = [index, subtleCryptoWeakPointer](const Vector<uint8_t>& derivedKey) mutable {
         if (auto promise = getPromise(index, subtleCryptoWeakPointer))
             fulfillPromiseWithArrayBuffer(promise.releaseNonNull(), derivedKey.data(), derivedKey.size());
@@ -881,7 +881,7 @@ void SubtleCrypto::importKey(JSC::ExecState& state, KeyFormat format, KeyDataVar
 
     auto index = promise.ptr();
     m_pendingPromises.add(index, WTFMove(promise));
-    auto subtleCryptoWeakPointer = m_weakPtrFactory.createWeakPtr(*this);
+    auto subtleCryptoWeakPointer = makeWeakPtr(*this);
     auto callback = [index, subtleCryptoWeakPointer](CryptoKey& key) mutable {
         if (auto promise = getPromise(index, subtleCryptoWeakPointer)) {
             if ((key.type() == CryptoKeyType::Private || key.type() == CryptoKeyType::Secret) && !key.usagesBitmap()) {
@@ -918,7 +918,7 @@ void SubtleCrypto::exportKey(KeyFormat format, CryptoKey& key, Ref<DeferredPromi
 
     auto index = promise.ptr();
     m_pendingPromises.add(index, WTFMove(promise));
-    auto subtleCryptoWeakPointer = m_weakPtrFactory.createWeakPtr(*this);
+    auto subtleCryptoWeakPointer = makeWeakPtr(*this);
     auto callback = [index, subtleCryptoWeakPointer](SubtleCrypto::KeyFormat format, KeyData&& key) mutable {
         if (auto promise = getPromise(index, subtleCryptoWeakPointer)) {
             switch (format) {
@@ -992,7 +992,7 @@ void SubtleCrypto::wrapKey(JSC::ExecState& state, KeyFormat format, CryptoKey& k
 
     auto index = promise.ptr();
     m_pendingPromises.add(index, WTFMove(promise));
-    auto subtleCryptoWeakPointer = m_weakPtrFactory.createWeakPtr(*this);
+    auto subtleCryptoWeakPointer = makeWeakPtr(*this);
     auto callback = [index, subtleCryptoWeakPointer, wrapAlgorithm, wrappingKey = makeRef(wrappingKey), wrapParams = WTFMove(wrapParams), isEncryption, context, workQueue = m_workQueue.copyRef()](SubtleCrypto::KeyFormat format, KeyData&& key) mutable {
         if (subtleCryptoWeakPointer) {
             if (auto promise = subtleCryptoWeakPointer->m_pendingPromises.get(index)) {
@@ -1095,7 +1095,7 @@ void SubtleCrypto::unwrapKey(JSC::ExecState& state, KeyFormat format, BufferSour
 
     auto index = promise.ptr();
     m_pendingPromises.add(index, WTFMove(promise));
-    auto subtleCryptoWeakPointer = m_weakPtrFactory.createWeakPtr(*this);
+    auto subtleCryptoWeakPointer = makeWeakPtr(*this);
     auto callback = [index, subtleCryptoWeakPointer, format, importAlgorithm, unwrappedKeyAlgorithm = WTFMove(unwrappedKeyAlgorithm), extractable, keyUsagesBitmap](const Vector<uint8_t>& bytes) mutable {
         if (subtleCryptoWeakPointer) {
             if (auto promise = subtleCryptoWeakPointer->m_pendingPromises.get(index)) {
index caf48f9..04e603e 100644 (file)
@@ -52,7 +52,7 @@ class DeferredPromise;
 
 enum class CryptoKeyUsage;
 
-class SubtleCrypto : public ContextDestructionObserver, public RefCounted<SubtleCrypto> {
+class SubtleCrypto : public ContextDestructionObserver, public RefCounted<SubtleCrypto>, public CanMakeWeakPtr<SubtleCrypto> {
 public:
     static Ref<SubtleCrypto> create(ScriptExecutionContext& context) { return adoptRef(*new SubtleCrypto(context)); }
     ~SubtleCrypto();
@@ -82,7 +82,6 @@ private:
 
     Ref<WorkQueue> m_workQueue;
     HashMap<DeferredPromise*, Ref<DeferredPromise>> m_pendingPromises;
-    WeakPtrFactory<SubtleCrypto> m_weakPtrFactory;
 };
 
 }
index 90a1808..f7d775f 100644 (file)
@@ -92,7 +92,7 @@ CSSFontFace::CSSFontFace(CSSFontSelector* fontSelector, StyleRuleFontFace* cssCo
     : m_timeoutTimer(*this, &CSSFontFace::timeoutFired)
     , m_fontSelector(fontSelector)
     , m_cssConnection(cssConnection)
-    , m_wrapper(wrapper ? wrapper->createWeakPtr() : WeakPtr<FontFace>())
+    , m_wrapper(makeWeakPtr(wrapper))
     , m_isLocalFallback(isLocalFallback)
     , m_mayBePurged(!wrapper)
 {
@@ -563,14 +563,14 @@ Ref<FontFace> CSSFontFace::wrapper()
         return *m_wrapper.get();
 
     auto wrapper = FontFace::create(*this);
-    m_wrapper = wrapper->createWeakPtr();
+    m_wrapper = makeWeakPtr(wrapper.get());
     initializeWrapper();
     return wrapper;
 }
 
 void CSSFontFace::setWrapper(FontFace& newWrapper)
 {
-    m_wrapper = newWrapper.createWeakPtr();
+    m_wrapper = makeWeakPtr(newWrapper);
     initializeWrapper();
 }
 
index 77e2e36..16bca96 100644 (file)
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-class DeprecatedCSSOMValue : public RefCounted<DeprecatedCSSOMValue> {
+class DeprecatedCSSOMValue : public RefCounted<DeprecatedCSSOMValue>, public CanMakeWeakPtr<DeprecatedCSSOMValue> {
 public:
     // Exactly match the IDL. No reason to add anything if it's not in the IDL.
     enum Type {
@@ -65,8 +65,6 @@ public:
 
     CSSStyleDeclaration& owner() const { return m_owner; }
 
-    WeakPtrFactory<DeprecatedCSSOMValue>& weakPtrFactory() { return m_weakPtrFactory; }
-
 protected:
     static const size_t ClassTypeBits = 2;
     enum DeprecatedClassType {
@@ -95,7 +93,6 @@ protected:
     unsigned m_classType : ClassTypeBits; // ClassType
     
     Ref<CSSStyleDeclaration> m_owner;
-    WeakPtrFactory<DeprecatedCSSOMValue> m_weakPtrFactory;
 };
 
 class DeprecatedCSSOMComplexValue : public DeprecatedCSSOMValue {
index 581f5e8..1fffb17 100644 (file)
@@ -142,11 +142,6 @@ FontFace::~FontFace()
     m_backing->removeClient(*this);
 }
 
-WeakPtr<FontFace> FontFace::createWeakPtr()
-{
-    return m_weakPtrFactory.createWeakPtr(*this);
-}
-
 RefPtr<CSSValue> FontFace::parseString(const String& string, CSSPropertyID propertyID)
 {
     // FIXME: Should use the Document to get the right parsing mode.
index 3480030..3d9a0ec 100644 (file)
@@ -38,7 +38,7 @@ class ArrayBufferView;
 
 namespace WebCore {
 
-class FontFace final : public RefCounted<FontFace>, private CSSFontFace::Client {
+class FontFace final : public RefCounted<FontFace>, public CanMakeWeakPtr<FontFace>, private CSSFontFace::Client {
 public:
     struct Descriptors {
         String style;
@@ -88,8 +88,6 @@ public:
 
     void fontStateChanged(CSSFontFace&, CSSFontFace::Status oldState, CSSFontFace::Status newState) final;
 
-    WeakPtr<FontFace> createWeakPtr();
-
     void ref() final { RefCounted::ref(); }
     void deref() final { RefCounted::deref(); }
 
@@ -100,7 +98,6 @@ private:
     // Callback for LoadedPromise.
     FontFace& loadedPromiseResolve();
 
-    WeakPtrFactory<FontFace> m_weakPtrFactory;
     Ref<CSSFontFace> m_backing;
     LoadedPromise m_loadedPromise;
 };
index 8c793c2..cc6eb1b 100644 (file)
@@ -110,7 +110,7 @@ MediaQueryEvaluator::MediaQueryEvaluator(const String& acceptedMediaType, bool m
 
 MediaQueryEvaluator::MediaQueryEvaluator(const String& acceptedMediaType, const Document& document, const RenderStyle* style)
     : m_mediaType(acceptedMediaType)
-    , m_document(const_cast<Document&>(document).createWeakPtr())
+    , m_document(makeWeakPtr(const_cast<Document&>(document)))
     , m_style(style)
 {
 }
index 0117eaa..490803d 100644 (file)
@@ -43,7 +43,7 @@ class StyleRuleBase;
 class StyleRuleImport;
 class StyleRuleNamespace;
 
-class StyleSheetContents final : public RefCounted<StyleSheetContents> {
+class StyleSheetContents final : public RefCounted<StyleSheetContents>, public CanMakeWeakPtr<StyleSheetContents> {
 public:
     static Ref<StyleSheetContents> create(const CSSParserContext& context = CSSParserContext(HTMLStandardMode))
     {
@@ -144,8 +144,6 @@ public:
 
     void shrinkToFit();
 
-    WeakPtr<StyleSheetContents> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
 private:
     WEBCORE_EXPORT StyleSheetContents(StyleRuleImport* ownerRule, const String& originalURL, const CSSParserContext&);
     StyleSheetContents(const StyleSheetContents&);
@@ -175,8 +173,6 @@ private:
     CSSParserContext m_parserContext;
 
     Vector<CSSStyleSheet*> m_clients;
-    
-    WeakPtrFactory<StyleSheetContents> m_weakPtrFactory;
 };
 
 } // namespace WebCore
index 06469ea..d34c19b 100644 (file)
@@ -35,7 +35,7 @@ namespace WebCore {
 CSSDeferredParser::CSSDeferredParser(const CSSParserContext& context, const String& sheetText, StyleSheetContents& styleSheet)
     : m_context(context)
     , m_sheetText(sheetText)
-    , m_styleSheet(styleSheet.createWeakPtr())
+    , m_styleSheet(makeWeakPtr(styleSheet))
 {
 }
 
index 8127194..cea8bc2 100644 (file)
@@ -76,7 +76,7 @@ ExceptionOr<RefPtr<DataTransferItem>> DataTransferItemList::add(const String& da
 
     m_dataTransfer.setDataFromItemList(lowercasedType, data);
     ASSERT(m_items);
-    m_items->append(DataTransferItem::create(m_weakPtrFactory.createWeakPtr(*this), lowercasedType));
+    m_items->append(DataTransferItem::create(makeWeakPtr(*this), lowercasedType));
     return m_items->last().ptr();
 }
 
@@ -85,7 +85,7 @@ RefPtr<DataTransferItem> DataTransferItemList::add(Ref<File>&& file)
     if (!m_dataTransfer.canWriteData())
         return nullptr;
 
-    ensureItems().append(DataTransferItem::create(m_weakPtrFactory.createWeakPtr(*this), file->type(), file.copyRef()));
+    ensureItems().append(DataTransferItem::create(makeWeakPtr(*this), file->type(), file.copyRef()));
     m_dataTransfer.didAddFileToItemList();
     return m_items->last().ptr();
 }
@@ -136,11 +136,11 @@ Vector<Ref<DataTransferItem>>& DataTransferItemList::ensureItems() const
     for (auto& type : m_dataTransfer.typesForItemList()) {
         auto lowercasedType = type.convertToASCIILowercase();
         if (shouldExposeTypeInItemList(lowercasedType))
-            items.append(DataTransferItem::create(m_weakPtrFactory.createWeakPtr(*const_cast<DataTransferItemList*>(this)), lowercasedType));
+            items.append(DataTransferItem::create(makeWeakPtr(*const_cast<DataTransferItemList*>(this)), lowercasedType));
     }
 
     for (auto& file : m_dataTransfer.files().files())
-        items.append(DataTransferItem::create(m_weakPtrFactory.createWeakPtr(*const_cast<DataTransferItemList*>(this)), file->type(), file.copyRef()));
+        items.append(DataTransferItem::create(makeWeakPtr(*const_cast<DataTransferItemList*>(this)), file->type(), file.copyRef()));
 
     m_items = WTFMove(items);
 
@@ -185,7 +185,7 @@ void DataTransferItemList::didSetStringData(const String& type)
     String lowercasedType = type.convertToASCIILowercase();
     removeStringItemOfLowercasedType(*m_items, type.convertToASCIILowercase());
 
-    m_items->append(DataTransferItem::create(m_weakPtrFactory.createWeakPtr(*this), lowercasedType));
+    m_items->append(DataTransferItem::create(makeWeakPtr(*this), lowercasedType));
 }
 
 }
index 13120e5..d25359a 100644 (file)
@@ -44,7 +44,7 @@ namespace WebCore {
 class DataTransferItem;
 class File;
 
-class DataTransferItemList : public ScriptWrappable {
+class DataTransferItemList : public ScriptWrappable, public CanMakeWeakPtr<DataTransferItemList> {
     WTF_MAKE_NONCOPYABLE(DataTransferItemList); WTF_MAKE_FAST_ALLOCATED;
 public:
     DataTransferItemList(DataTransfer&);
@@ -75,7 +75,6 @@ public:
 private:
     Vector<Ref<DataTransferItem>>& ensureItems() const;
 
-    WeakPtrFactory<DataTransferItemList> m_weakPtrFactory;
     DataTransfer& m_dataTransfer;
     mutable std::optional<Vector<Ref<DataTransferItem>>> m_items;
 };
index 3b8d419..6873146 100644 (file)
@@ -5821,7 +5821,7 @@ void Document::addMessage(MessageSource source, MessageLevel level, const String
 
 void Document::postTask(Task&& task)
 {
-    callOnMainThread([documentReference = m_weakFactory.createWeakPtr(*this), task = WTFMove(task)]() mutable {
+    callOnMainThread([documentReference = makeWeakPtr(*this), task = WTFMove(task)]() mutable {
         ASSERT(isMainThread());
 
         Document* document = documentReference.get();
@@ -7559,7 +7559,7 @@ void Document::hasStorageAccess(Ref<DeferredPromise>&& promise)
     if (Page* page = this->page()) {
         auto iframeHost = securityOrigin.host();
         auto topHost = topSecurityOrigin.host();
-        page->chrome().client().hasStorageAccess(WTFMove(iframeHost), WTFMove(topHost), frameID.value(), pageID.value(), [documentReference = m_weakFactory.createWeakPtr(*this), promise = WTFMove(promise)] (bool hasAccess) {
+        page->chrome().client().hasStorageAccess(WTFMove(iframeHost), WTFMove(topHost), frameID.value(), pageID.value(), [documentReference = makeWeakPtr(*this), promise = WTFMove(promise)] (bool hasAccess) {
             Document* document = documentReference.get();
             if (!document)
                 return;
@@ -7629,14 +7629,14 @@ void Document::requestStorageAccess(Ref<DeferredPromise>&& promise)
         return;
     }
 
-    page->chrome().client().requestStorageAccess(WTFMove(iframeHost), WTFMove(topHost), frameID.value(), pageID.value(), [documentReference = m_weakFactory.createWeakPtr(*this), promise = WTFMove(promise)] (bool wasGranted) mutable {
+    page->chrome().client().requestStorageAccess(WTFMove(iframeHost), WTFMove(topHost), frameID.value(), pageID.value(), [documentReference = makeWeakPtr(*this), promise = WTFMove(promise)] (bool wasGranted) mutable {
         Document* document = documentReference.get();
         if (!document)
             return;
         
         if (wasGranted) {
             document->setHasFrameSpecificStorageAccess(true);
-            MicrotaskQueue::mainThreadQueue().append(std::make_unique<VoidMicrotask>([documentReference = document->m_weakFactory.createWeakPtr(*document)] () {
+            MicrotaskQueue::mainThreadQueue().append(std::make_unique<VoidMicrotask>([documentReference = makeWeakPtr(*document)] () {
                 if (auto* document = documentReference.get())
                     document->enableTemporaryTimeUserGesture();
             }));
index 499bacb..0cb3c1c 100644 (file)
@@ -321,6 +321,7 @@ class Document
     , public TreeScope
     , public ScriptExecutionContext
     , public FontSelectorClient
+    , public CanMakeWeakPtr<Document>
     , public FrameDestructionObserver
     , public Supplementable<Document>
     , public Logger::Observer {
@@ -799,7 +800,7 @@ public:
     WEBCORE_EXPORT WindowProxy* windowProxy() const;
 
     Document& contextDocument() const;
-    void setContextDocument(Document& document) { m_contextDocument = document.createWeakPtr(); }
+    void setContextDocument(Document& document) { m_contextDocument = makeWeakPtr(document); }
 
     // Helper functions for forwarding DOMWindow event related tasks to the DOMWindow if it exists.
     void setWindowAttributeEventListener(const AtomicString& eventType, const QualifiedName& attributeName, const AtomicString& value, DOMWrapperWorld&);
@@ -1311,7 +1312,6 @@ public:
     bool isCapturing() const { return MediaProducer::isCapturing(m_mediaState); }
     WEBCORE_EXPORT void updateIsPlayingMedia(uint64_t = HTMLMediaElementInvalidID);
     void pageMutedStateDidChange();
-    WeakPtr<Document> createWeakPtr() { return m_weakFactory.createWeakPtr(*this); }
 
 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
     void addPlaybackTargetPickerClient(MediaPlaybackTargetClient&);
@@ -1694,8 +1694,6 @@ private:
     RenderPtr<RenderView> m_renderView;
     mutable DocumentEventQueue m_eventQueue;
 
-    WeakPtrFactory<Document> m_weakFactory;
-
     HashSet<MediaCanStartListener*> m_mediaCanStartListeners;
 
 #if ENABLE(FULLSCREEN_API)
index cb97d11..8eadf79 100644 (file)
@@ -44,13 +44,11 @@ namespace WebCore {
 
 class Frame;
 
-class MessagePort final : public ActiveDOMObject, public EventTargetWithInlineData {
+class MessagePort final : public ActiveDOMObject, public EventTargetWithInlineData, public CanMakeWeakPtr<MessagePort> {
 public:
     static Ref<MessagePort> create(ScriptExecutionContext&, const MessagePortIdentifier& local, const MessagePortIdentifier& remote);
     virtual ~MessagePort();
 
-    auto& weakPtrFactory() const { return m_weakFactory; }
-
     ExceptionOr<void> postMessage(JSC::ExecState&, JSC::JSValue message, Vector<JSC::Strong<JSC::JSObject>>&&);
 
     void start();
@@ -115,8 +113,6 @@ private:
     bool m_closed { false };
     bool m_entangled { true };
 
-    WeakPtrFactory<MessagePort> m_weakFactory;
-
     // Flags to manage querying the remote port for GC purposes
     mutable bool m_mightBeEligibleForGC { false };
     mutable bool m_hasHadLocalActivitySinceLastCheck { false };
index 57399a4..abe006d 100644 (file)
@@ -371,7 +371,7 @@ void HTMLImageElement::setPictureElement(HTMLPictureElement* pictureElement)
     
     if (!gPictureOwnerMap)
         gPictureOwnerMap = new PictureOwnerMap();
-    gPictureOwnerMap->add(this, pictureElement->createWeakPtr());
+    gPictureOwnerMap->add(this, makeWeakPtr(*pictureElement));
 }
     
 unsigned HTMLImageElement::width(bool ignorePendingStylesheets)
index bf605df..80a7e22 100644 (file)
@@ -55,7 +55,7 @@ struct InputElementClickState {
     RefPtr<HTMLInputElement> checkedRadioButton;
 };
 
-class HTMLInputElement : public HTMLTextFormControlElement {
+class HTMLInputElement : public HTMLTextFormControlElement, public CanMakeWeakPtr<HTMLInputElement> {
     WTF_MAKE_ISO_ALLOCATED(HTMLInputElement);
 public:
     static Ref<HTMLInputElement> create(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
@@ -343,8 +343,6 @@ public:
 
     ExceptionOr<void> setSelectionRangeForBindings(int start, int end, const String& direction);
 
-    auto& weakPtrFactory() const { return m_weakFactory; }
-
 protected:
     HTMLInputElement(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
 
@@ -485,7 +483,6 @@ private:
 #if ENABLE(DATALIST_ELEMENT)
     std::unique_ptr<ListAttributeTargetObserver> m_listAttributeTargetObserver;
 #endif
-    WeakPtrFactory<HTMLInputElement> m_weakFactory;
 };
 
 }
index 16270ea..f6b5e36 100644 (file)
@@ -6910,7 +6910,7 @@ RefPtr<PlatformMediaResourceLoader> HTMLMediaElement::mediaPlayerCreateResourceL
 {
     auto mediaResourceLoader = adoptRef(*new MediaResourceLoader(document(), *this, crossOrigin()));
 
-    m_lastMediaResourceLoaderForTesting = mediaResourceLoader->createWeakPtr();
+    m_lastMediaResourceLoaderForTesting = makeWeakPtr(mediaResourceLoader.get());
 
     return WTFMove(mediaResourceLoader);
 }
index 237c360..3ee881a 100644 (file)
@@ -123,6 +123,7 @@ class HTMLMediaElement
     : public HTMLElement
     , public ActiveDOMObject
     , public MediaControllerInterface
+    , public CanMakeWeakPtr<HTMLMediaElement>
     , public PlatformMediaSessionClient
     , private MediaCanStartListener
     , private MediaPlayerClient
@@ -146,7 +147,6 @@ class HTMLMediaElement
 {
     WTF_MAKE_ISO_ALLOCATED(HTMLMediaElement);
 public:
-    WeakPtr<HTMLMediaElement> createWeakPtr() { return m_weakFactory.createWeakPtr(*this); }
     RefPtr<MediaPlayer> player() const { return m_player; }
 
     virtual bool isVideo() const { return false; }
@@ -922,7 +922,6 @@ private:
     const Logger& mediaPlayerLogger() final { return logger(); }
 #endif
 
-    WeakPtrFactory<HTMLMediaElement> m_weakFactory;
     Timer m_pendingActionTimer;
     Timer m_progressEventTimer;
     Timer m_playbackProgressTimer;
index 3d507ce..c6da357 100644 (file)
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-class HTMLPictureElement final : public HTMLElement {
+class HTMLPictureElement final : public HTMLElement, public CanMakeWeakPtr<HTMLPictureElement> {
     WTF_MAKE_ISO_ALLOCATED(HTMLPictureElement);
 public:
     static Ref<HTMLPictureElement> create(const QualifiedName&, Document&);
@@ -44,8 +44,6 @@ public:
 
     bool viewportChangeAffectedPicture() const;
 
-    WeakPtr<HTMLPictureElement> createWeakPtr() { return m_weakFactory.createWeakPtr(*this); }
-
 #if USE(SYSTEM_PREVIEW)
     WEBCORE_EXPORT bool isSystemPreviewImage() const;
 #endif
@@ -55,7 +53,6 @@ private:
 
     void didMoveToNewDocument(Document& oldDocument, Document& newDocument) final;
 
-    WeakPtrFactory<HTMLPictureElement> m_weakFactory;
     Vector<MediaQueryResult> m_viewportDependentMediaQueryResults;
 };
 
index aa2c782..dae7464 100644 (file)
@@ -72,7 +72,7 @@ private:
 
 typedef Vector<std::unique_ptr<PreloadRequest>> PreloadRequestStream;
 
-class HTMLResourcePreloader {
+class HTMLResourcePreloader : public CanMakeWeakPtr<HTMLResourcePreloader> {
     WTF_MAKE_NONCOPYABLE(HTMLResourcePreloader); WTF_MAKE_FAST_ALLOCATED;
 public:
     explicit HTMLResourcePreloader(Document& document)
@@ -83,11 +83,8 @@ public:
     void preload(PreloadRequestStream);
     void preload(std::unique_ptr<PreloadRequest>);
 
-    WeakPtr<HTMLResourcePreloader> createWeakPtr() { return m_weakFactory.createWeakPtr(*this); }
-
 private:
     Document& m_document;
-    WeakPtrFactory<HTMLResourcePreloader> m_weakFactory;
 };
 
 } // namespace WebCore
index 6215b39..9db2060 100644 (file)
@@ -39,7 +39,7 @@ namespace Layout {
 class Container;
 class TreeBuilder;
 
-class Box {
+class Box : public CanMakeWeakPtr<Box> {
     WTF_MAKE_ISO_ALLOCATED(Box);
 public:
     friend class TreeBuilder;
@@ -94,7 +94,6 @@ public:
     bool isPaddingApplicable() const;
 
     const RenderStyle& style() const { return m_style; }
-    auto& weakPtrFactory() const { return m_weakFactory; }
 
     std::optional<const Replaced> replaced() const { return m_replaced; }
 
@@ -129,7 +128,6 @@ private:
     void setNextSibling(Box& nextSibling) { m_nextSibling = &nextSibling; }
     void setPreviousSibling(Box& previousSibling) { m_previousSibling = &previousSibling; }
 
-    WeakPtrFactory<Box> m_weakFactory;
     RenderStyle m_style;
     std::optional<ElementAttributes> m_elementAttributes;
 
index 7758432..6ed8bec 100644 (file)
@@ -41,7 +41,7 @@ enum FormSubmissionTrigger { SubmittedByJavaScript, NotSubmittedByJavaScript };
 
 using StringPairVector = Vector<std::pair<String, String>>;
 
-class FormState : public RefCounted<FormState>, public FrameDestructionObserver {
+class FormState : public RefCounted<FormState>, public CanMakeWeakPtr<FormState>, public FrameDestructionObserver {
 public:
     static Ref<FormState> create(HTMLFormElement&, StringPairVector&& textFieldValues, Document&, FormSubmissionTrigger);
 
@@ -50,8 +50,6 @@ public:
     Document& sourceDocument() const { return m_sourceDocument; }
     FormSubmissionTrigger formSubmissionTrigger() const { return m_formSubmissionTrigger; }
 
-    auto& weakPtrFactory() const { return m_weakFactory; }
-
 private:
     FormState(HTMLFormElement&, StringPairVector&& textFieldValues, Document&, FormSubmissionTrigger);
     void willDetachPage() override;
@@ -60,7 +58,6 @@ private:
     StringPairVector m_textFieldValues;
     Ref<Document> m_sourceDocument;
     FormSubmissionTrigger m_formSubmissionTrigger;
-    WeakPtrFactory<FormState> m_weakFactory;
 };
 
 } // namespace WebCore
index bcb50d6..e637b39 100644 (file)
@@ -215,7 +215,7 @@ void LinkLoader::preconnectIfNeeded(const LinkRelAttribute& relAttribute, const
     if (equalIgnoringASCIICase(crossOrigin, "anonymous") && document.securityOrigin().canAccess(SecurityOrigin::create(href)))
         storageCredentialsPolicy = StoredCredentialsPolicy::DoNotUse;
     ASSERT(document.frame()->loader().networkingContext());
-    platformStrategies()->loaderStrategy()->preconnectTo(document.frame()->loader(), href, storageCredentialsPolicy, [weakDocument = document.createWeakPtr(), href](ResourceError error) {
+    platformStrategies()->loaderStrategy()->preconnectTo(document.frame()->loader(), href, storageCredentialsPolicy, [weakDocument = makeWeakPtr(document), href](ResourceError error) {
         if (!weakDocument)
             return;
 
index 7b9bd39..01d1efc 100644 (file)
@@ -46,7 +46,7 @@ class LinkPreloadResourceClient;
 
 struct LinkRelAttribute;
 
-class LinkLoader : private CachedResourceClient {
+class LinkLoader : private CachedResourceClient, public CanMakeWeakPtr<LinkLoader> {
 public:
     explicit LinkLoader(LinkLoaderClient&);
     virtual ~LinkLoader();
@@ -58,7 +58,6 @@ public:
     static void loadLinksFromHeader(const String& headerValue, const URL& baseURL, Document&, MediaAttributeCheck);
     static bool isSupportedType(CachedResource::Type, const String& mimeType);
 
-    WeakPtr<LinkLoader> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
     void triggerEvents(const CachedResource&);
     void cancelLoad();
 
@@ -71,7 +70,6 @@ private:
     LinkLoaderClient& m_client;
     CachedResourceHandle<CachedResource> m_cachedLinkResource;
     std::unique_ptr<LinkPreloadResourceClient> m_preloadResourceClient;
-    WeakPtrFactory<LinkLoader> m_weakPtrFactory;
 };
 
 }
index 1cd7443..ab93773 100644 (file)
@@ -33,7 +33,7 @@ namespace WebCore {
 
 LinkPreloadResourceClient::LinkPreloadResourceClient(LinkLoader& loader, CachedResource& resource)
 {
-    m_loader = loader.createWeakPtr();
+    m_loader = makeWeakPtr(loader);
     m_resource = &resource;
 }
 
index 3d7c4d4..8077d5a 100644 (file)
@@ -43,7 +43,7 @@ namespace WebCore {
 MediaResourceLoader::MediaResourceLoader(Document& document, HTMLMediaElement& mediaElement, const String& crossOriginMode)
     : ContextDestructionObserver(&document)
     , m_document(&document)
-    , m_mediaElement(mediaElement.createWeakPtr())
+    , m_mediaElement(makeWeakPtr(mediaElement))
     , m_crossOriginMode(crossOriginMode)
 {
 }
index 349277e..618458a 100644 (file)
@@ -44,7 +44,7 @@ class Document;
 class HTMLMediaElement;
 class MediaResource;
 
-class MediaResourceLoader final : public PlatformMediaResourceLoader, public ContextDestructionObserver {
+class MediaResourceLoader final : public PlatformMediaResourceLoader, public CanMakeWeakPtr<MediaResourceLoader>, public ContextDestructionObserver {
 public:
     WEBCORE_EXPORT MediaResourceLoader(Document&, HTMLMediaElement&, const String& crossOriginMode);
     WEBCORE_EXPORT virtual ~MediaResourceLoader();
@@ -58,8 +58,6 @@ public:
     Vector<ResourceResponse> responsesForTesting() const { return m_responsesForTesting; }
     void addResponseForTesting(const ResourceResponse&);
 
-    WeakPtr<const MediaResourceLoader> createWeakPtr() { return m_weakFactory.createWeakPtr(*this); }
-
 private:
     void contextDestroyed() override;
 
@@ -67,7 +65,6 @@ private:
     WeakPtr<HTMLMediaElement> m_mediaElement;
     String m_crossOriginMode;
     HashSet<MediaResource*> m_resources;
-    WeakPtrFactory<const MediaResourceLoader> m_weakFactory;
     Vector<ResourceResponse> m_responsesForTesting;
 };
 
index c7ba747..5c48e7c 100644 (file)
@@ -92,6 +92,7 @@ enum class IncludeTargetOrigin { No, Yes };
 // FIXME: Rename DOMWindow to LocalWindow and AbstractDOMWindow to DOMWindow.
 class DOMWindow final
     : public AbstractDOMWindow
+    , public CanMakeWeakPtr<DOMWindow>
     , public ContextDestructionObserver
     , public FrameDestructionObserver
     , public Base64Utilities
@@ -335,8 +336,6 @@ public:
     void enableSuddenTermination();
     void disableSuddenTermination();
 
-    WeakPtr<DOMWindow> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
 private:
     explicit DOMWindow(Document&);
 
@@ -393,8 +392,6 @@ private:
     enum class PageStatus { None, Shown, Hidden };
     PageStatus m_lastPageStatus { PageStatus::None };
 
-    WeakPtrFactory<DOMWindow> m_weakPtrFactory;
-
 #if PLATFORM(IOS)
     unsigned m_scrollEventListenerCount { 0 };
 #endif
index a4f6331..a5bbf90 100644 (file)
@@ -2724,7 +2724,7 @@ static WeakPtr<Widget> widgetForElement(const Element& element)
     if (!is<RenderWidget>(target) || !downcast<RenderWidget>(*target).widget())
         return { };
 
-    return downcast<RenderWidget>(*target).widget()->createWeakPtr();
+    return makeWeakPtr(*downcast<RenderWidget>(*target).widget());
 }
 
 bool EventHandler::completeWidgetWheelEvent(const PlatformWheelEvent& event, const WeakPtr<Widget>& widget, const WeakPtr<ScrollableArea>& scrollableArea, ContainerNode* scrollableContainer)
@@ -3980,7 +3980,7 @@ void EventHandler::updateLastScrollbarUnderMouse(Scrollbar* scrollbar, SetOrClea
         // Send mouse entered if we're setting a new scrollbar.
         if (scrollbar && setOrClear == SetOrClearLastScrollbar::Set) {
             scrollbar->mouseEntered();
-            m_lastScrollbarUnderMouse = scrollbar->createWeakPtr();
+            m_lastScrollbarUnderMouse = makeWeakPtr(*scrollbar);
         } else
             m_lastScrollbarUnderMouse = nullptr;
     }
index ab08862..7dbba92 100644 (file)
@@ -38,7 +38,7 @@ TaskDispatcher<Timer>::TaskDispatcher()
 void TaskDispatcher<Timer>::postTask(Function<void()>&& function)
 {
     m_pendingTasks.append(WTFMove(function));
-    pendingDispatchers().append(m_weakPtrFactory.createWeakPtr(*this));
+    pendingDispatchers().append(makeWeakPtr(*this));
     if (!sharedTimer().isActive())
         sharedTimer().startOneShot(0_s);
 }
index 02c0ab9..aaa9450 100644 (file)
@@ -50,7 +50,7 @@ private:
 };
 
 template<>
-class TaskDispatcher<Timer> {
+class TaskDispatcher<Timer> : public CanMakeWeakPtr<TaskDispatcher<Timer>> {
 public:
     TaskDispatcher();
     void postTask(WTF::Function<void()>&&);
@@ -62,12 +62,11 @@ private:
 
     void dispatchOneTask();
 
-    WeakPtrFactory<TaskDispatcher> m_weakPtrFactory;
     Deque<WTF::Function<void()>> m_pendingTasks;
 };
 
 template <typename T>
-class GenericTaskQueue {
+class GenericTaskQueue : public CanMakeWeakPtr<GenericTaskQueue<T>> {
 public:
     GenericTaskQueue()
         : m_dispatcher()
@@ -87,8 +86,7 @@ public:
             return;
 
         ++m_pendingTasks;
-        auto weakThis = m_weakPtrFactory.createWeakPtr(*this);
-        m_dispatcher.postTask([weakThis, task = WTFMove(task)] {
+        m_dispatcher.postTask([weakThis = makeWeakPtr(*this), task = WTFMove(task)] {
             if (!weakThis)
                 return;
             ASSERT(weakThis->m_pendingTasks);
@@ -105,13 +103,12 @@ public:
 
     void cancelAllTasks()
     {
-        m_weakPtrFactory.revokeAll();
+        CanMakeWeakPtr<GenericTaskQueue<T>>::weakPtrFactory().revokeAll();
         m_pendingTasks = 0;
     }
     bool hasPendingTasks() const { return m_pendingTasks; }
 
 private:
-    WeakPtrFactory<GenericTaskQueue> m_weakPtrFactory;
     TaskDispatcher<T> m_dispatcher;
     unsigned m_pendingTasks { 0 };
     bool m_isClosed { false };
index 7978102..e45ad2b 100644 (file)
@@ -74,6 +74,8 @@ public:
 
     virtual void notifyPageThatContentAreaWillPaint() const;
 
+    using Widget::weakPtrFactory;
+
     IntPoint locationOfContents() const;
 
     // NOTE: This should only be called by the overriden setScrollOffset from ScrollableArea.
@@ -372,8 +374,6 @@ public:
     void setAllowsUnclampedScrollPositionForTesting(bool allowsUnclampedScrollPosition) { m_allowsUnclampedScrollPosition = allowsUnclampedScrollPosition; }
     bool allowsUnclampedScrollPosition() const { return m_allowsUnclampedScrollPosition; }
 
-    auto& weakPtrFactory() const { return m_weakPtrFactory; }
-
 protected:
     ScrollView();
 
@@ -460,8 +460,6 @@ private:
 
     IntPoint m_panScrollIconPoint;
 
-    WeakPtrFactory<ScrollView> m_weakPtrFactory;
-
     bool m_horizontalScrollbarLock { false };
     bool m_verticalScrollbarLock { false };
 
index b273af0..b71939b 100644 (file)
@@ -48,7 +48,7 @@ typedef IntPoint ScrollPosition;
 // scrollOffset() is the value used by scrollbars (min is 0,0), and should never have negative components.
 typedef IntPoint ScrollOffset;
 
-class ScrollableArea {
+class ScrollableArea : public CanMakeWeakPtr<ScrollableArea> {
 public:
     WEBCORE_EXPORT bool scroll(ScrollDirection, ScrollGranularity, float multiplier = 1);
     WEBCORE_EXPORT void scrollToOffsetWithoutAnimation(const FloatPoint&, ScrollClamping = ScrollClamping::Clamped);
@@ -65,8 +65,6 @@ public:
 
     WEBCORE_EXPORT bool handleWheelEvent(const PlatformWheelEvent&);
 
-    auto& weakPtrFactory() const { return m_weakPtrFactory; }
-
 #if ENABLE(CSS_SCROLL_SNAP)
     WEBCORE_EXPORT const Vector<LayoutUnit>* horizontalSnapOffsets() const;
     WEBCORE_EXPORT const Vector<LayoutUnit>* verticalSnapOffsets() const;
@@ -338,8 +336,6 @@ protected:
 
     bool hasLayerForScrollCorner() const;
 
-    WeakPtrFactory<ScrollableArea> m_weakPtrFactory;
-
 private:
     WEBCORE_EXPORT virtual IntRect visibleContentRectInternal(VisibleContentRectIncludesScrollbars, VisibleContentRectBehavior) const;
     void scrollPositionChanged(const ScrollPosition&);
index 1a86bf3..62f5044 100644 (file)
@@ -28,7 +28,6 @@
 #include "ScrollTypes.h"
 #include "Timer.h"
 #include "Widget.h"
-#include <wtf/WeakPtr.h>
 
 namespace WebCore {
 
@@ -133,8 +132,6 @@ public:
 
     bool supportsUpdateOnSecondaryThread() const;
 
-    WeakPtr<Scrollbar> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
 protected:
     Scrollbar(ScrollableArea&, ScrollbarOrientation, ScrollbarControlSize, ScrollbarTheme* = 0, bool isCustomScrollbar = false);
 
@@ -183,8 +180,6 @@ protected:
 
 private:
     bool isScrollbar() const override { return true; }
-
-    WeakPtrFactory<Scrollbar> m_weakPtrFactory;
 };
 
 } // namespace WebCore
index 402358b..c5f78d2 100644 (file)
@@ -46,7 +46,7 @@ void Widget::setParent(ScrollView* view)
     ASSERT(!view || !m_parent);
     if (!view || !view->isVisible())
         setParentVisible(false);
-    m_parent = view ? makeWeakPtr(*view) : nullptr;
+    m_parent = makeWeakPtr(view);
     if (view && view->isVisible())
         setParentVisible(true);
 }
index 4081460..f31f245 100644 (file)
@@ -87,7 +87,7 @@ enum WidgetNotification { WillPaintFlattened, DidPaintFlattened };
 // Scrollbar - Mac, Gtk
 // Plugin - Mac, Windows (windowed only), Qt (windowed only, widget is an HWND on windows), Gtk (windowed only)
 //
-class Widget : public RefCounted<Widget> {
+class Widget : public RefCounted<Widget>, public CanMakeWeakPtr<Widget> {
 public:
     WEBCORE_EXPORT explicit Widget(PlatformWidget = nullptr);
     WEBCORE_EXPORT virtual ~Widget();
@@ -187,8 +187,6 @@ public:
     WEBCORE_EXPORT virtual IntPoint convertToContainingView(const IntPoint&) const;
     WEBCORE_EXPORT virtual IntPoint convertFromContainingView(const IntPoint&) const;
 
-    WeakPtr<Widget> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
 private:
     void init(PlatformWidget); // Must be called by all Widget constructors to initialize cross-platform data.
 
@@ -210,7 +208,6 @@ private:
 #else
     RetainPtr<NSView> m_widget;
 #endif
-    WeakPtrFactory<Widget> m_weakPtrFactory;
     bool m_selfVisible;
     bool m_parentVisible;
 
index 7898693..b912077 100644 (file)
@@ -38,7 +38,7 @@
 
 namespace WebCore {
 
-class AudioFileReader {
+class AudioFileReader : public CanMakeWeakPtr<AudioFileReader> {
     WTF_MAKE_NONCOPYABLE(AudioFileReader);
 public:
     AudioFileReader(const char* filePath);
@@ -48,8 +48,6 @@ public:
     RefPtr<AudioBus> createBus(float sampleRate, bool mixToMono);
 
 private:
-    WeakPtr<AudioFileReader> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
     static void deinterleavePadAddedCallback(AudioFileReader*, GstPad*);
     static void deinterleaveReadyCallback(AudioFileReader*);
     static void decodebinPadAddedCallback(AudioFileReader*, GstPad*);
@@ -61,7 +59,6 @@ private:
     void decodeAudioForBusCreation();
     GstFlowReturn handleSample(GstAppSink*);
 
-    WeakPtrFactory<AudioFileReader> m_weakPtrFactory;
     RunLoop& m_runLoop;
     const void* m_data { nullptr };
     size_t m_dataSize { 0 };
@@ -301,7 +298,7 @@ void AudioFileReader::decodeAudioForBusCreation()
             reader.handleMessage(message);
         else {
             GRefPtr<GstMessage> protectMessage(message);
-            auto weakThis = reader.createWeakPtr();
+            auto weakThis = makeWeakPtr(reader);
             reader.m_runLoop.dispatch([weakThis, protectMessage] {
                 if (weakThis)
                     weakThis->handleMessage(protectMessage.get());
index dbbdc9f..78cb607 100644 (file)
@@ -125,7 +125,7 @@ AudioHardwareListenerMac::AudioHardwareListenerMac(Client& client)
     setHardwareActivity(isAudioHardwareProcessRunning());
     setOutputDeviceSupportsLowPowerMode(currentDeviceSupportsLowPowerBufferSize());
 
-    auto weakThis = m_weakFactory.createWeakPtr(*this);
+    auto weakThis = makeWeakPtr(*this);
     m_block = Block_copy(^(UInt32 count, const AudioObjectPropertyAddress properties[]) {
         if (weakThis)
             weakThis->propertyChanged(count, properties);
index 6057d38..0720ce4 100644 (file)
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-class AudioHardwareListenerMac : public AudioHardwareListener {
+class AudioHardwareListenerMac : public AudioHardwareListener, public CanMakeWeakPtr<AudioHardwareListenerMac> {
 public:
     static WTF::Ref<AudioHardwareListenerMac> create(Client&);
 
@@ -49,7 +49,6 @@ private:
     void propertyChanged(UInt32, const AudioObjectPropertyAddress[]);
 
     AudioObjectPropertyListenerBlock m_block;
-    WeakPtrFactory<AudioHardwareListenerMac> m_weakFactory;
 };
 
 }
index ced546c..b452780 100644 (file)
@@ -472,7 +472,7 @@ void CDMInstanceClearKey::requestLicense(LicenseType, const AtomicString& initDa
         initData = extractKeyidsFromCencInitData(initData.get());
 
     callOnMainThread(
-        [weakThis = m_weakPtrFactory.createWeakPtr(*this), callback = WTFMove(callback), initData = WTFMove(initData), sessionIdValue = s_sessionIdValue]() mutable {
+        [weakThis = makeWeakPtr(*this), callback = WTFMove(callback), initData = WTFMove(initData), sessionIdValue = s_sessionIdValue]() mutable {
             if (!weakThis)
                 return;
 
@@ -497,7 +497,7 @@ void CDMInstanceClearKey::updateLicense(const String& sessionId, LicenseType, co
     auto dispatchCallback =
         [this, &callback](bool sessionWasClosed, std::optional<KeyStatusVector>&& changedKeys, SuccessValue succeeded) {
             callOnMainThread(
-                [weakThis = m_weakPtrFactory.createWeakPtr(*this), callback = WTFMove(callback), sessionWasClosed, changedKeys = WTFMove(changedKeys), succeeded] () mutable {
+                [weakThis = makeWeakPtr(*this), callback = WTFMove(callback), sessionWasClosed, changedKeys = WTFMove(changedKeys), succeeded] () mutable {
                     if (!weakThis)
                         return;
 
@@ -597,7 +597,7 @@ void CDMInstanceClearKey::loadSession(LicenseType, const String& sessionId, cons
     auto dispatchCallback =
         [this, &callback](std::optional<KeyStatusVector>&& existingKeys, SuccessValue success, SessionLoadFailure loadFailure) {
             callOnMainThread(
-                [weakThis = m_weakPtrFactory.createWeakPtr(*this), callback = WTFMove(callback), existingKeys = WTFMove(existingKeys), success, loadFailure]() mutable {
+                [weakThis = makeWeakPtr(*this), callback = WTFMove(callback), existingKeys = WTFMove(existingKeys), success, loadFailure]() mutable {
                     if (!weakThis)
                         return;
 
@@ -627,7 +627,7 @@ void CDMInstanceClearKey::loadSession(LicenseType, const String& sessionId, cons
 void CDMInstanceClearKey::closeSession(const String&, CloseSessionCallback callback)
 {
     callOnMainThread(
-        [weakThis = m_weakPtrFactory.createWeakPtr(*this), callback = WTFMove(callback)] {
+        [weakThis = makeWeakPtr(*this), callback = WTFMove(callback)] {
             if (!weakThis)
                 return;
 
@@ -641,7 +641,7 @@ void CDMInstanceClearKey::removeSessionData(const String& sessionId, LicenseType
     auto dispatchCallback =
         [this, &callback](KeyStatusVector&& keyStatusVector, std::optional<Ref<SharedBuffer>>&& message, SuccessValue success) {
             callOnMainThread(
-                [weakThis = m_weakPtrFactory.createWeakPtr(*this), callback = WTFMove(callback), keyStatusVector = WTFMove(keyStatusVector), message = WTFMove(message), success]() mutable {
+                [weakThis = makeWeakPtr(*this), callback = WTFMove(callback), keyStatusVector = WTFMove(keyStatusVector), message = WTFMove(message), success]() mutable {
                     if (!weakThis)
                         return;
 
index d98fe07..cd4c880 100644 (file)
@@ -74,7 +74,7 @@ public:
     std::optional<String> sanitizeSessionId(const String&) const override;
 };
 
-class CDMInstanceClearKey final : public CDMInstance {
+class CDMInstanceClearKey final : public CDMInstance, public CanMakeWeakPtr<CDMInstanceClearKey> {
 public:
     CDMInstanceClearKey();
     virtual ~CDMInstanceClearKey();
@@ -103,9 +103,6 @@ public:
     };
 
     const Vector<Key> keys() const;
-
-private:
-    WeakPtrFactory<CDMInstanceClearKey> m_weakPtrFactory;
 };
 
 } // namespace WebCore
index 3529a95..0059075 100644 (file)
@@ -98,7 +98,7 @@ public:
     void operator()(TextLayout*) const;
 };
 
-class FontCascade {
+class FontCascade : public CanMakeWeakPtr<FontCascade> {
 public:
     WEBCORE_EXPORT FontCascade();
     WEBCORE_EXPORT FontCascade(FontCascadeDescription&&, float letterSpacing = 0, float wordSpacing = 0);
@@ -199,8 +199,6 @@ public:
 
     bool primaryFontIsSystemFont() const;
 
-    WeakPtr<FontCascade> createWeakPtr() const { return m_weakPtrFactory.createWeakPtr(*const_cast<FontCascade*>(this)); }
-
     std::unique_ptr<DisplayList::DisplayList> displayListForTextRun(GraphicsContext&, const TextRun&, unsigned from = 0, std::optional<unsigned> to = { }, CustomFontNotReadyAction = CustomFontNotReadyAction::DoNotPaintIfFontNotReady) const;
     
 private:
@@ -313,7 +311,6 @@ private:
 
     FontCascadeDescription m_fontDescription;
     mutable RefPtr<FontCascadeFonts> m_fonts;
-    WeakPtrFactory<FontCascade> m_weakPtrFactory;
     float m_letterSpacing { 0 };
     float m_wordSpacing { 0 };
     mutable bool m_useBackslashAsYenSymbol { false };
index 1d2870e..ce97351 100644 (file)
@@ -799,7 +799,7 @@ void MediaPlayerPrivateAVFoundation::scheduleMainThreadNotification(Notification
     if (delayDispatch && !m_mainThreadCallPending) {
         m_mainThreadCallPending = true;
 
-        callOnMainThread([weakThis = createWeakPtr()] {
+        callOnMainThread([weakThis = makeWeakPtr(*this)] {
             if (!weakThis)
                 return;
 
@@ -832,7 +832,7 @@ void MediaPlayerPrivateAVFoundation::dispatchNotification()
         }
         
         if (!m_queuedNotifications.isEmpty() && !m_mainThreadCallPending) {
-            callOnMainThread([weakThis = createWeakPtr()] {
+            callOnMainThread([weakThis = makeWeakPtr(*this)] {
                 if (!weakThis)
                     return;
 
index 703f35d..3fbcdaf 100644 (file)
@@ -46,7 +46,7 @@ class InbandMetadataTextTrackPrivateAVF;
 class InbandTextTrackPrivateAVF;
 class GenericCueData;
 
-class MediaPlayerPrivateAVFoundation : public MediaPlayerPrivateInterface, public AVFInbandTrackParent
+class MediaPlayerPrivateAVFoundation : public CanMakeWeakPtr<MediaPlayerPrivateAVFoundation>, public MediaPlayerPrivateInterface, public AVFInbandTrackParent
 #if !RELEASE_LOG_DISABLED
     , private LoggerHelper
 #endif
@@ -159,8 +159,6 @@ protected:
     explicit MediaPlayerPrivateAVFoundation(MediaPlayer*);
     virtual ~MediaPlayerPrivateAVFoundation();
 
-    WeakPtr<MediaPlayerPrivateAVFoundation> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
     // MediaPlayerPrivatePrivateInterface overrides.
     void load(const String& url) override;
 #if ENABLE(MEDIA_SOURCE)
@@ -330,8 +328,6 @@ protected:
 private:
     MediaPlayer* m_player;
 
-    WeakPtrFactory<MediaPlayerPrivateAVFoundation> m_weakPtrFactory;
-
     WTF::Function<void()> m_pendingSeek;
 
     Deque<Notification> m_queuedNotifications;
index bca7b93..83b9d50 100644 (file)
@@ -42,7 +42,7 @@ OBJC_CLASS WebCoreFPSContentKeySessionDelegate;
 
 namespace WebCore {
 
-class CDMInstanceFairPlayStreamingAVFObjC final : public CDMInstance {
+class CDMInstanceFairPlayStreamingAVFObjC final : public CDMInstance, public CanMakeWeakPtr<CDMInstanceFairPlayStreamingAVFObjC> {
 public:
     CDMInstanceFairPlayStreamingAVFObjC();
     virtual ~CDMInstanceFairPlayStreamingAVFObjC();
@@ -82,12 +82,10 @@ public:
     AVContentKeySession *contentKeySession() { return m_session.get(); }
 
 private:
-    WeakPtr<CDMInstanceFairPlayStreamingAVFObjC> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
     bool isLicenseTypeSupported(LicenseType) const;
 
     Vector<Ref<SharedBuffer>> keyIDs();
 
-    WeakPtrFactory<CDMInstanceFairPlayStreamingAVFObjC> m_weakPtrFactory;
     RefPtr<SharedBuffer> m_serverCertificate;
     bool m_persistentStateAllowed { true };
     RetainPtr<NSURL> m_storageDirectory;
index 03aa627..4630416 100644 (file)
@@ -455,7 +455,7 @@ void CDMInstanceFairPlayStreamingAVFObjC::didProvideRequest(AVContentKeyRequest
     }
 
     RetainPtr<NSData> contentIdentifier = keyIDs.first()->createNSData();
-    [m_request makeStreamingContentKeyRequestDataForApp:appIdentifier.get() contentIdentifier:contentIdentifier.get() options:nil completionHandler:[this, weakThis = createWeakPtr()] (NSData *contentKeyRequestData, NSError *error) mutable {
+    [m_request makeStreamingContentKeyRequestDataForApp:appIdentifier.get() contentIdentifier:contentIdentifier.get() options:nil completionHandler:[this, weakThis = makeWeakPtr(*this)] (NSData *contentKeyRequestData, NSError *error) mutable {
         callOnMainThread([this, weakThis = WTFMove(weakThis), error = retainPtr(error), contentKeyRequestData = retainPtr(contentKeyRequestData)] {
             if (!weakThis || !m_requestLicenseCallback)
                 return;
index 1abe72a..22aafec 100644 (file)
@@ -39,7 +39,7 @@ namespace WebCore {
 
 class MediaPlayerPrivateAVFoundationObjC;
 
-class CDMSessionAVFoundationObjC : public LegacyCDMSession {
+class CDMSessionAVFoundationObjC : public LegacyCDMSession, public CanMakeWeakPtr<CDMSessionAVFoundationObjC> {
 public:
     CDMSessionAVFoundationObjC(MediaPlayerPrivateAVFoundationObjC* parent, LegacyCDMSessionClient*);
     virtual ~CDMSessionAVFoundationObjC();
@@ -53,14 +53,11 @@ public:
 
     void playerDidReceiveError(NSError *);
 
-    WeakPtr<CDMSessionAVFoundationObjC> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
 protected:
     WeakPtr<MediaPlayerPrivateAVFoundationObjC> m_parent;
     LegacyCDMSessionClient* m_client;
     String m_sessionId;
     RetainPtr<AVAssetResourceLoadingRequest> m_request;
-    WeakPtrFactory<CDMSessionAVFoundationObjC> m_weakPtrFactory;
 };
 
 }
index d82ef74..82f4cdc 100644 (file)
@@ -50,7 +50,7 @@ SOFT_LINK_CLASS(AVFoundation, AVAssetResourceLoadingRequest)
 namespace WebCore {
 
 CDMSessionAVFoundationObjC::CDMSessionAVFoundationObjC(MediaPlayerPrivateAVFoundationObjC* parent, LegacyCDMSessionClient* client)
-    : m_parent(parent->createWeakPtr())
+    : m_parent(makeWeakPtr(*parent))
     , m_client(client)
     , m_sessionId(createCanonicalUUIDString())
 {
index 0b74da4..e1de72a 100644 (file)
@@ -40,7 +40,7 @@ namespace WebCore {
 
 class CDMPrivateMediaSourceAVFObjC;
 
-class CDMSessionAVStreamSession : public CDMSessionMediaSourceAVFObjC {
+class CDMSessionAVStreamSession : public CDMSessionMediaSourceAVFObjC, public CanMakeWeakPtr<CDMSessionAVStreamSession> {
 public:
     CDMSessionAVStreamSession(const Vector<int>& protocolVersions, CDMPrivateMediaSourceAVFObjC&, LegacyCDMSessionClient*);
     virtual ~CDMSessionAVStreamSession();
@@ -60,7 +60,6 @@ public:
 protected:
     RefPtr<Uint8Array> generateKeyReleaseMessage(unsigned short& errorCode, uint32_t& systemCode);
 
-    WeakPtrFactory<CDMSessionAVStreamSession> m_weakPtrFactory;
     RetainPtr<AVStreamSession> m_streamSession;
     RefPtr<Uint8Array> m_initData;
     RefPtr<Uint8Array> m_certificate;
index 133cc08..38325e5 100644 (file)
@@ -148,8 +148,6 @@ public:
     void attemptToDecryptWithInstance(CDMInstance&) final;
 #endif
 
-    WeakPtr<MediaPlayerPrivateAVFoundationObjC> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
 private:
     // engine support
     static void getSupportedTypes(HashSet<String, ASCIICaseInsensitiveHash>& types);
@@ -325,8 +323,6 @@ private:
 
     AVPlayer *objCAVFoundationAVPlayer() const final { return m_avPlayer.get(); }
 
-    WeakPtrFactory<MediaPlayerPrivateAVFoundationObjC> m_weakPtrFactory;
-
     RetainPtr<AVURLAsset> m_avAsset;
     RetainPtr<AVPlayer> m_avPlayer;
     RetainPtr<AVPlayerItem> m_avPlayerItem;
index 48ce779..ab6024d 100644 (file)
@@ -667,7 +667,7 @@ void MediaPlayerPrivateAVFoundationObjC::createVideoLayer()
     if (!m_avPlayer || m_haveBeenAskedToCreateLayer)
         return;
 
-    callOnMainThread([this, weakThis = createWeakPtr()] {
+    callOnMainThread([this, weakThis = makeWeakPtr(*this)] {
         if (!weakThis)
             return;
 
@@ -1097,7 +1097,7 @@ void MediaPlayerPrivateAVFoundationObjC::checkPlayability()
     m_haveCheckedPlayability = true;
 
     INFO_LOG(LOGIDENTIFIER);
-    auto weakThis = createWeakPtr();
+    auto weakThis = makeWeakPtr(*this);
 
     [m_avAsset.get() loadValuesAsynchronouslyForKeys:[NSArray arrayWithObjects:@"playable", @"tracks", nil] completionHandler:^{
         callOnMainThread([weakThis] {
@@ -1113,7 +1113,7 @@ void MediaPlayerPrivateAVFoundationObjC::beginLoadingMetadata()
 
     OSObjectPtr<dispatch_group_t> metadataLoadingGroup = adoptOSObject(dispatch_group_create());
     dispatch_group_enter(metadataLoadingGroup.get());
-    auto weakThis = createWeakPtr();
+    auto weakThis = makeWeakPtr(*this);
     [m_avAsset.get() loadValuesAsynchronouslyForKeys:assetMetadataKeyNames() completionHandler:^{
 
         callOnMainThread([weakThis, metadataLoadingGroup] {
@@ -1337,7 +1337,7 @@ void MediaPlayerPrivateAVFoundationObjC::seekToTime(const MediaTime& time, const
     if (CMTimeCompare(cmBefore, kCMTimeZero) < 0)
         cmBefore = kCMTimeZero;
     
-    auto weakThis = createWeakPtr();
+    auto weakThis = makeWeakPtr(*this);
 
     [m_avPlayerItem.get() seekToTime:cmTime toleranceBefore:cmBefore toleranceAfter:cmAfter completionHandler:^(BOOL finished) {
         callOnMainThread([weakThis, finished] {
@@ -2419,7 +2419,7 @@ std::unique_ptr<LegacyCDMSession> MediaPlayerPrivateAVFoundationObjC::createSess
     if (!keySystemIsSupported(keySystem))
         return nullptr;
     auto session = std::make_unique<CDMSessionAVFoundationObjC>(this, client);
-    m_session = session->createWeakPtr();
+    m_session = makeWeakPtr(*session);
     return WTFMove(session);
 }
 #endif
@@ -2941,7 +2941,7 @@ void MediaPlayerPrivateAVFoundationObjC::setShouldPlayToPlaybackTarget(bool shou
     ASSERT(m_playbackTarget->targetType() == MediaPlaybackTarget::Mock);
 
     setDelayCallbacks(true);
-    auto weakThis = createWeakPtr();
+    auto weakThis = makeWeakPtr(*this);
     scheduleMainThreadNotification(MediaPlayerPrivateAVFoundation::Notification([weakThis] {
         if (!weakThis)
             return;
@@ -3422,7 +3422,7 @@ NSArray* playerKVOProperties()
     if (!function)
         return;
 
-    auto weakThis = m_callback->createWeakPtr();
+    auto weakThis = makeWeakPtr(*m_callback);
     m_callback->scheduleMainThreadNotification(MediaPlayerPrivateAVFoundation::Notification([weakThis, function = WTFMove(function)]{
         // weakThis and function both refer to the same MediaPlayerPrivateAVFoundationObjC instance. If the WeakPtr has
         // been cleared, the underlying object has been destroyed, and it is unsafe to call function().
index d61e722..6bb1016 100644 (file)
@@ -57,7 +57,7 @@ class PixelBufferConformerCV;
 class VideoFullscreenLayerManagerObjC;
 class VideoTrackPrivateMediaStream;
 
-class MediaPlayerPrivateMediaStreamAVFObjC final : public MediaPlayerPrivateInterface, private MediaStreamPrivate::Observer, private MediaStreamTrackPrivate::Observer
+class MediaPlayerPrivateMediaStreamAVFObjC final : public CanMakeWeakPtr<MediaPlayerPrivateMediaStreamAVFObjC>, public MediaPlayerPrivateInterface, private MediaStreamPrivate::Observer, private MediaStreamTrackPrivate::Observer
 #if !RELEASE_LOG_DISABLED
     , private LoggerHelper
 #endif
@@ -78,8 +78,6 @@ public:
     MediaPlayer::ReadyState readyState() const override;
     void setReadyState(MediaPlayer::ReadyState);
 
-    WeakPtr<MediaPlayerPrivateMediaStreamAVFObjC> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
     void ensureLayers();
     void destroyLayers();
 
@@ -232,7 +230,6 @@ private:
     void applicationDidBecomeActive() final;
 
     MediaPlayer* m_player { nullptr };
-    WeakPtrFactory<MediaPlayerPrivateMediaStreamAVFObjC> m_weakPtrFactory;
     RefPtr<MediaStreamPrivate> m_mediaStreamPrivate;
     RefPtr<MediaStreamTrackPrivate> m_activeVideoTrack;
     RetainPtr<WebAVSampleBufferStatusChangeListener> m_statusChangeListener;
index a97c938..e1d301d 100644 (file)
@@ -395,7 +395,7 @@ void MediaPlayerPrivateMediaStreamAVFObjC::enqueueVideoSample(MediaStreamTrackPr
 
 void MediaPlayerPrivateMediaStreamAVFObjC::requestNotificationWhenReadyForVideoData()
 {
-    auto weakThis = createWeakPtr();
+    auto weakThis = makeWeakPtr(*this);
     [m_sampleBufferDisplayLayer requestMediaDataWhenReadyOnQueue:dispatch_get_main_queue() usingBlock:^ {
         if (!weakThis)
             return;
@@ -1133,7 +1133,7 @@ void MediaPlayerPrivateMediaStreamAVFObjC::setShouldBufferData(bool shouldBuffer
 void MediaPlayerPrivateMediaStreamAVFObjC::scheduleDeferredTask(Function<void ()>&& function)
 {
     ASSERT(function);
-    callOnMainThread([weakThis = createWeakPtr(), function = WTFMove(function)] {
+    callOnMainThread([weakThis = makeWeakPtr(*this), function = WTFMove(function)] {
         if (!weakThis)
             return;
 
index 547c79c..81ab2f9 100644 (file)
@@ -43,7 +43,7 @@ namespace WebCore {
 
 class GraphicsContext3D;
 
-class TextureCacheCV {
+class TextureCacheCV : public CanMakeWeakPtr<TextureCacheCV> {
 public:
     static std::unique_ptr<TextureCacheCV> create(GraphicsContext3D&);
 
@@ -63,7 +63,6 @@ public:
 private:
     Ref<GraphicsContext3D> m_context;
     RetainPtr<TextureCacheType> m_cache;
-    WeakPtrFactory<TextureCacheCV> m_weakPtrFactory;
 };
 
 }
index bbb8e75..cf95929 100644 (file)
@@ -74,7 +74,7 @@ RetainPtr<TextureCacheCV::TextureType> TextureCacheCV::textureFromImage(CVPixelB
 #endif
     RetainPtr<TextureType> videoTexture = adoptCF(bareVideoTexture);
 
-    auto weakThis = m_weakPtrFactory.createWeakPtr(*this);
+    auto weakThis = makeWeakPtr(*this);
     dispatch_async(dispatch_get_main_queue(), [weakThis] {
         if (!weakThis)
             return;
index 0ec4b13..bff7406 100644 (file)
@@ -657,7 +657,7 @@ void MediaPlayerPrivateGStreamer::clearTracks()
 #define CREATE_TRACK(type, Type) \
     m_has##Type = true; \
     if (!useMediaSource) {\
-        RefPtr<Type##TrackPrivateGStreamer> track = Type##TrackPrivateGStreamer::create(createWeakPtr(), i, stream); \
+        RefPtr<Type##TrackPrivateGStreamer> track = Type##TrackPrivateGStreamer::create(makeWeakPtr(*this), i, stream); \
         m_##type##Tracks.add(track->id(), track); \
         m_player->add##Type##Track(*track);\
         if (gst_stream_get_stream_flags(stream.get()) & GST_STREAM_FLAG_SELECT) {                                    \
@@ -847,7 +847,7 @@ void MediaPlayerPrivateGStreamer::notifyPlayerOfVideo()
             }
         }
 
-        RefPtr<VideoTrackPrivateGStreamer> track = VideoTrackPrivateGStreamer::create(createWeakPtr(), i, pad);
+        RefPtr<VideoTrackPrivateGStreamer> track = VideoTrackPrivateGStreamer::create(makeWeakPtr(*this), i, pad);
         ASSERT(streamId == track->id());
         m_videoTracks.add(streamId, track);
         m_player->addVideoTrack(*track);
@@ -921,7 +921,7 @@ void MediaPlayerPrivateGStreamer::notifyPlayerOfAudio()
             }
         }
 
-        RefPtr<AudioTrackPrivateGStreamer> track = AudioTrackPrivateGStreamer::create(createWeakPtr(), i, pad);
+        RefPtr<AudioTrackPrivateGStreamer> track = AudioTrackPrivateGStreamer::create(makeWeakPtr(*this), i, pad);
         ASSERT(streamId == track->id());
         m_audioTracks.add(streamId, track);
         m_player->addAudioTrack(*track);
@@ -1249,7 +1249,7 @@ void MediaPlayerPrivateGStreamer::handleMessage(GstMessage* message)
     case GST_MESSAGE_ELEMENT:
         if (gst_is_missing_plugin_message(message)) {
             if (gst_install_plugins_supported()) {
-                RefPtr<MediaPlayerRequestInstallMissingPluginsCallback> missingPluginCallback = MediaPlayerRequestInstallMissingPluginsCallback::create([weakThis = createWeakPtr()](uint32_t result, MediaPlayerRequestInstallMissingPluginsCallback& missingPluginCallback) {
+                RefPtr<MediaPlayerRequestInstallMissingPluginsCallback> missingPluginCallback = MediaPlayerRequestInstallMissingPluginsCallback::create([weakThis = makeWeakPtr(*this)](uint32_t result, MediaPlayerRequestInstallMissingPluginsCallback& missingPluginCallback) {
                     if (!weakThis) {
                         GST_INFO("got missing pluging installation callback in destroyed player with result %u", result);
                         return;
index b2ee5e6..ad67d24 100644 (file)
@@ -65,8 +65,6 @@ public:
     explicit MediaPlayerPrivateGStreamer(MediaPlayer*);
     virtual ~MediaPlayerPrivateGStreamer();
 
-    WeakPtr<MediaPlayerPrivateGStreamer> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
     static void registerMediaEngine(MediaEngineRegistrar);
     void handleMessage(GstMessage*);
     void handlePluginInstallerResult(GstInstallPluginsReturn);
@@ -237,7 +235,6 @@ protected:
 #endif
 
 private:
-    WeakPtrFactory<MediaPlayerPrivateGStreamer> m_weakPtrFactory;
 
 #if ENABLE(VIDEO_TRACK)
     GRefPtr<GstElement> m_textAppSink;
index 627c4b2..cfeb3e0 100644 (file)
@@ -391,7 +391,7 @@ bool MediaPlayerPrivateGStreamerBase::handleSyncMessage(GstMessage* message)
         if (concatenatedInitDataChunksNumber > 1)
             eventKeySystemIdString = emptyString();
 
-        RunLoop::main().dispatch([weakThis = m_weakPtrFactory.createWeakPtr(*this), eventKeySystemIdString, initData = WTFMove(concatenatedInitDataChunks)] {
+        RunLoop::main().dispatch([weakThis = makeWeakPtr(*this), eventKeySystemIdString, initData = WTFMove(concatenatedInitDataChunks)] {
             if (!weakThis)
                 return;
 
@@ -1250,7 +1250,7 @@ void MediaPlayerPrivateGStreamerBase::initializationDataEncountered(GstEvent* ev
     gst_buffer_unmap(data, &mapInfo);
 
     String eventKeySystemUUIDString = eventKeySystemUUID;
-    RunLoop::main().dispatch([weakThis = m_weakPtrFactory.createWeakPtr(*this), eventKeySystemUUID = eventKeySystemUUIDString, initData] {
+    RunLoop::main().dispatch([weakThis = makeWeakPtr(*this), eventKeySystemUUID = eventKeySystemUUIDString, initData] {
         if (!weakThis)
             return;
 
index ce5d825..7862a8c 100644 (file)
@@ -61,7 +61,7 @@ class TextureMapperPlatformLayerProxy;
 
 void registerWebKitGStreamerElements();
 
-class MediaPlayerPrivateGStreamerBase : public MediaPlayerPrivateInterface
+class MediaPlayerPrivateGStreamerBase : public MediaPlayerPrivateInterface, public CanMakeWeakPtr<MediaPlayerPrivateGStreamerBase>
 #if USE(TEXTURE_MAPPER_GL)
     , public PlatformLayer
 #endif
@@ -217,7 +217,6 @@ protected:
 #endif
     };
 
-    WeakPtrFactory<MediaPlayerPrivateGStreamerBase> m_weakPtrFactory;
     Ref<MainThreadNotifier<MainThreadNotification>> m_notifier;
     MediaPlayer* m_player;
     GRefPtr<GstElement> m_pipeline;
index e213d2d..fd186af 100644 (file)
@@ -1013,11 +1013,11 @@ void AppendPipeline::connectDemuxerSrcPadToAppsink(GstPad* demuxerSrcPad)
     switch (m_streamType) {
     case WebCore::MediaSourceStreamTypeGStreamer::Audio:
         if (m_playerPrivate)
-            m_track = WebCore::AudioTrackPrivateGStreamer::create(m_playerPrivate->createWeakPtr(), id(), sinkSinkPad.get());
+            m_track = WebCore::AudioTrackPrivateGStreamer::create(makeWeakPtr(*m_playerPrivate), id(), sinkSinkPad.get());
         break;
     case WebCore::MediaSourceStreamTypeGStreamer::Video:
         if (m_playerPrivate)
-            m_track = WebCore::VideoTrackPrivateGStreamer::create(m_playerPrivate->createWeakPtr(), id(), sinkSinkPad.get());
+            m_track = WebCore::VideoTrackPrivateGStreamer::create(makeWeakPtr(*m_playerPrivate), id(), sinkSinkPad.get());
         break;
     case WebCore::MediaSourceStreamTypeGStreamer::Text:
         m_track = WebCore::InbandTextTrackPrivateGStreamer::create(id(), sinkSinkPad.get());
index d93d2b1..beb6c04 100644 (file)
@@ -89,7 +89,7 @@ void DisplayRefreshMonitorMac::displayLinkFired()
 
     setIsPreviousFrameDone(false);
 
-    RunLoop::main().dispatch([weakPtr = m_weakFactory.createWeakPtr(*this)] {
+    RunLoop::main().dispatch([weakPtr = makeWeakPtr(*this)] {
         if (auto* monitor = weakPtr.get())
             handleDisplayRefreshedNotificationOnMainThread(monitor);
     });
index 3f7ccdf..a454577 100644 (file)
@@ -34,7 +34,7 @@ typedef struct __CVDisplayLink *CVDisplayLinkRef;
 
 namespace WebCore {
 
-class DisplayRefreshMonitorMac : public DisplayRefreshMonitor {
+class DisplayRefreshMonitorMac : public DisplayRefreshMonitor, public CanMakeWeakPtr<DisplayRefreshMonitorMac> {
 public:
     static Ref<DisplayRefreshMonitorMac> create(PlatformDisplayID displayID)
     {
@@ -49,7 +49,6 @@ public:
 private:
     explicit DisplayRefreshMonitorMac(PlatformDisplayID);
 
-    WeakPtrFactory<DisplayRefreshMonitorMac> m_weakFactory;
     CVDisplayLinkRef m_displayLink { nullptr };
 };
 
index 25b6ca4..1dc8376 100644 (file)
@@ -495,8 +495,8 @@ void TextureMapperLayer::removeAllChildren()
 void TextureMapperLayer::setMaskLayer(TextureMapperLayer* maskLayer)
 {
     if (maskLayer) {
-        maskLayer->m_effectTarget = createWeakPtr();
-        m_state.maskLayer = maskLayer->createWeakPtr();
+        maskLayer->m_effectTarget = makeWeakPtr(*this);
+        m_state.maskLayer = makeWeakPtr(*maskLayer);
     } else
         m_state.maskLayer = nullptr;
 }
@@ -504,8 +504,8 @@ void TextureMapperLayer::setMaskLayer(TextureMapperLayer* maskLayer)
 void TextureMapperLayer::setReplicaLayer(TextureMapperLayer* replicaLayer)
 {
     if (replicaLayer) {
-        replicaLayer->m_effectTarget = createWeakPtr();
-        m_state.replicaLayer = replicaLayer->createWeakPtr();
+        replicaLayer->m_effectTarget = makeWeakPtr(*this);
+        m_state.replicaLayer = makeWeakPtr(*replicaLayer);
     } else
         m_state.replicaLayer = nullptr;
 }
index ac10794..33fc9ae 100644 (file)
@@ -34,13 +34,12 @@ class Region;
 class TextureMapperPaintOptions;
 class TextureMapperPlatformLayer;
 
-class WEBCORE_EXPORT TextureMapperLayer {
+class WEBCORE_EXPORT TextureMapperLayer : public CanMakeWeakPtr<TextureMapperLayer> {
     WTF_MAKE_NONCOPYABLE(TextureMapperLayer);
     WTF_MAKE_FAST_ALLOCATED;
 public:
     TextureMapperLayer();
     virtual ~TextureMapperLayer();
-    WeakPtr<TextureMapperLayer> createWeakPtr() { return m_weakFactory.createWeakPtr(*this); }
 
     void setID(uint32_t id) { m_id = id; }
     uint32_t id() { return m_id; }
@@ -141,7 +140,6 @@ private:
         return FloatRect(FloatPoint::zero(), m_state.size);
     }
 
-    WeakPtrFactory<TextureMapperLayer> m_weakFactory;
     Vector<TextureMapperLayer*> m_children;
     TextureMapperLayer* m_parent { nullptr };
     WeakPtr<TextureMapperLayer> m_effectTarget;
index 359ee11..3840fdd 100644 (file)
@@ -499,7 +499,7 @@ bool MediaPlayerPrivateMediaFoundation::endCreatedMediaSource(IMFAsyncResult* as
     hr = asyncResult->GetStatus();
     m_loadingProgress = SUCCEEDED(hr);
 
-    callOnMainThread([weakPtr = m_weakPtrFactory.createWeakPtr(*this)] {
+    callOnMainThread([weakPtr = makeWeakPtr(*this)] {
         if (!weakPtr)
             return;
         weakPtr->onCreatedMediaSource();
@@ -528,7 +528,7 @@ bool MediaPlayerPrivateMediaFoundation::endGetEvent(IMFAsyncResult* asyncResult)
 
     switch (mediaEventType) {
     case MESessionTopologySet: {
-        callOnMainThread([weakPtr = m_weakPtrFactory.createWeakPtr(*this)] {
+        callOnMainThread([weakPtr = makeWeakPtr(*this)] {
             if (!weakPtr)
                 return;
             weakPtr->onTopologySet();
@@ -537,7 +537,7 @@ bool MediaPlayerPrivateMediaFoundation::endGetEvent(IMFAsyncResult* asyncResult)
     }
 
     case MESessionStarted: {
-        callOnMainThread([weakPtr = m_weakPtrFactory.createWeakPtr(*this)] {
+        callOnMainThread([weakPtr = makeWeakPtr(*this)] {
             if (!weakPtr)
                 return;
             weakPtr->onSessionStarted();
@@ -546,7 +546,7 @@ bool MediaPlayerPrivateMediaFoundation::endGetEvent(IMFAsyncResult* asyncResult)
     }
 
     case MEBufferingStarted: {
-        callOnMainThread([weakPtr = m_weakPtrFactory.createWeakPtr(*this)] {
+        callOnMainThread([weakPtr = makeWeakPtr(*this)] {
             if (!weakPtr)
                 return;
             weakPtr->onBufferingStarted();
@@ -555,7 +555,7 @@ bool MediaPlayerPrivateMediaFoundation::endGetEvent(IMFAsyncResult* asyncResult)
     }
 
     case MEBufferingStopped: {
-        callOnMainThread([weakPtr = m_weakPtrFactory.createWeakPtr(*this)] {
+        callOnMainThread([weakPtr = makeWeakPtr(*this)] {
             if (!weakPtr)
                 return;
             weakPtr->onBufferingStopped();
@@ -564,7 +564,7 @@ bool MediaPlayerPrivateMediaFoundation::endGetEvent(IMFAsyncResult* asyncResult)
     }
 
     case MESessionEnded: {
-        callOnMainThread([weakPtr = m_weakPtrFactory.createWeakPtr(*this)] {
+        callOnMainThread([weakPtr = makeWeakPtr(*this)] {
             if (!weakPtr)
                 return;
             weakPtr->onSessionEnded();
@@ -1723,7 +1723,7 @@ HRESULT MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::processInputNot
     
     // Invalidate the video area
     if (m_mediaPlayer) {
-        callOnMainThread([weakPtr = m_mediaPlayer->m_weakPtrFactory.createWeakPtr(*m_mediaPlayer)] {
+        callOnMainThread([weakPtr = m_mediaPlayer->makeWeakPtr(*m_mediaPlayer)] {
             if (weakPtr)
                 weakPtr->invalidateFrameView();
         });
index c672c22..fccee1c 100644 (file)
@@ -46,7 +46,7 @@
 
 namespace WebCore {
 
-class MediaPlayerPrivateMediaFoundation : public MediaPlayerPrivateInterface {
+class MediaPlayerPrivateMediaFoundation : public MediaPlayerPrivateInterface, public CanMakeWeakPtr<MediaPlayerPrivateMediaFoundation> {
 public:
     explicit MediaPlayerPrivateMediaFoundation(MediaPlayer*);
     ~MediaPlayerPrivateMediaFoundation();
@@ -124,7 +124,6 @@ private:
     FloatSize m_cachedNaturalSize;
     mutable Lock m_cachedNaturalSizeLock;
 
-    WeakPtrFactory<MediaPlayerPrivateMediaFoundation> m_weakPtrFactory;
     COMPtr<IMFMediaSession> m_mediaSession;
     COMPtr<IMFSourceResolver> m_sourceResolver;
     COMPtr<IMFMediaSource> m_mediaSource;
index d507c31..f8b141b 100644 (file)
@@ -38,16 +38,14 @@ typedef void *id;
 
 namespace WebCore {
 
-class RemoteCommandListenerIOS : public RemoteCommandListener {
+class RemoteCommandListenerIOS : public RemoteCommandListener, public CanMakeWeakPtr<RemoteCommandListenerIOS> {
 public:
     RemoteCommandListenerIOS(RemoteCommandListenerClient&);
     virtual ~RemoteCommandListenerIOS();
 
 protected:
-    WeakPtr<RemoteCommandListenerIOS> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
     void updateSupportedCommands() override;
 
-    WeakPtrFactory<RemoteCommandListenerIOS> m_weakPtrFactory;
     RetainPtr<id> m_playTarget;
     RetainPtr<id> m_pauseTarget;
     RetainPtr<id> m_togglePlayPauseTarget;
index 35ef1cf..9ae7739 100644 (file)
@@ -52,7 +52,7 @@ RemoteCommandListenerIOS::RemoteCommandListenerIOS(RemoteCommandListenerClient&
     : RemoteCommandListener(client)
 {
     MPRemoteCommandCenter *center = [getMPRemoteCommandCenterClass() sharedCommandCenter];
-    auto weakThis = createWeakPtr();
+    auto weakThis = makeWeakPtr(*this);
     
     m_pauseTarget = [[center pauseCommand] addTargetWithHandler:^(MPRemoteCommandEvent *) {
         callOnMainThread([weakThis] {
index b781e6a..94a42e1 100644 (file)
 
 namespace WebCore {
 
-class RemoteCommandListenerMac : public RemoteCommandListener {
+class RemoteCommandListenerMac : public RemoteCommandListener, public CanMakeWeakPtr<RemoteCommandListenerMac> {
 public:
     RemoteCommandListenerMac(RemoteCommandListenerClient&);
     virtual ~RemoteCommandListenerMac();
 
 protected:
-    WeakPtr<RemoteCommandListenerMac> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
     void updateSupportedCommands() override;
 
-    WeakPtrFactory<RemoteCommandListenerMac> m_weakPtrFactory;
     void* m_commandHandler { nullptr };
 };
     
index 3d74722..05cc089 100644 (file)
@@ -84,7 +84,7 @@ RemoteCommandListenerMac::RemoteCommandListenerMac(RemoteCommandListenerClient&
 
     updateSupportedCommands();
 
-    auto weakThis = createWeakPtr();
+    auto weakThis = makeWeakPtr(*this);
     m_commandHandler = MRMediaRemoteAddAsyncCommandHandlerBlock(^(MRMediaRemoteCommand command, CFDictionaryRef options, void(^completion)(CFArrayRef)) {
 
         LOG(Media, "RemoteCommandListenerMac::RemoteCommandListenerMac - received command %u", command);
index 4264770..fcb423f 100644 (file)
@@ -294,7 +294,7 @@ void MediaStreamPrivate::trackEnded(MediaStreamTrackPrivate&)
 void MediaStreamPrivate::scheduleDeferredTask(Function<void ()>&& function)
 {
     ASSERT(function);
-    callOnMainThread([weakThis = createWeakPtr(), function = WTFMove(function)] {
+    callOnMainThread([weakThis = makeWeakPtr(*this), function = WTFMove(function)] {
         if (!weakThis)
             return;
 
index c984deb..357fd30 100644 (file)
@@ -53,7 +53,7 @@ namespace WebCore {
 class MediaStream;
 class OrientationNotifier;
 
-class MediaStreamPrivate : public MediaStreamTrackPrivate::Observer, public RefCounted<MediaStreamPrivate> {
+class MediaStreamPrivate : public MediaStreamTrackPrivate::Observer, public RefCounted<MediaStreamPrivate>, public CanMakeWeakPtr<MediaStreamPrivate> {
 public:
     class Observer {
     public:
@@ -102,8 +102,6 @@ public:
 
     FloatSize intrinsicSize() const;
 
-    WeakPtr<MediaStreamPrivate> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
     void monitorOrientation(OrientationNotifier&);
 
 private:
@@ -121,7 +119,6 @@ private:
 
     void scheduleDeferredTask(Function<void ()>&&);
 
-    WeakPtrFactory<MediaStreamPrivate> m_weakPtrFactory;
     Vector<Observer*> m_observers;
     String m_id;
     MediaStreamTrackPrivate* m_activeVideoTrack { nullptr };
index 6c089d0..7ba40fc 100644 (file)
@@ -913,7 +913,7 @@ void RealtimeMediaSource::setEchoCancellation(bool echoCancellation)
 void RealtimeMediaSource::scheduleDeferredTask(WTF::Function<void()>&& function)
 {
     ASSERT(function);
-    callOnMainThread([weakThis = createWeakPtr(), function = WTFMove(function)] {
+    callOnMainThread([weakThis = makeWeakPtr(*this), function = WTFMove(function)] {
         if (!weakThis)
             return;
 
index 5411085..395d834 100644 (file)
@@ -62,7 +62,7 @@ class RealtimeMediaSourceSettings;
 
 struct CaptureSourceOrError;
 
-class WEBCORE_EXPORT RealtimeMediaSource : public ThreadSafeRefCounted<RealtimeMediaSource> {
+class WEBCORE_EXPORT RealtimeMediaSource : public ThreadSafeRefCounted<RealtimeMediaSource>, public CanMakeWeakPtr<RealtimeMediaSource> {
 public:
     class Observer {
     public:
@@ -249,15 +249,12 @@ protected:
     void videoSampleAvailable(MediaSample&);
     void audioSamplesAvailable(const MediaTime&, const PlatformAudioData&, const AudioStreamDescription&, size_t);
 
-    WeakPtr<RealtimeMediaSource> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
 private:
     virtual void startProducingData() { }
     virtual void stopProducingData() { }
 
     bool m_muted { false };
 
-    WeakPtrFactory<RealtimeMediaSource> m_weakPtrFactory;
     String m_id;
     String m_persistentID;
     Type m_type;
index 07bc3f8..3db270f 100644 (file)
@@ -100,7 +100,6 @@ private:
     RetainPtr<CGDisplayStreamRef> m_displayStream;
     RetainPtr<CFMutableDictionaryRef> m_bufferAttributes;
     CGDisplayStreamFrameAvailableHandler m_frameAvailableBlock;
-    WeakPtrFactory<ScreenDisplayCaptureSourceMac> m_weakFactory;
     MediaTime m_presentationTimeStamp;
     MediaTime m_frameDuration;
 
index 78aa012..cf494b8 100644 (file)
@@ -167,7 +167,7 @@ bool ScreenDisplayCaptureSourceMac::createDisplayStream()
         };
         auto streamOptions = adoptCF(CFDictionaryCreate(kCFAllocatorDefault, keys, values, WTF_ARRAY_LENGTH(keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
 
-        auto weakThis = m_weakFactory.createWeakPtr(*this);
+        auto weakThis = makeWeakPtr(*this);
         m_frameAvailableBlock = Block_copy(^(CGDisplayStreamFrameStatus status, uint64_t displayTime, IOSurfaceRef frameSurface, CGDisplayStreamUpdateRef updateRef) {
             if (!weakThis)
                 return;
index 762325c..1a08eb2 100644 (file)
@@ -157,15 +157,11 @@ struct VRPlatformTrackingInfo {
     double timestamp { 0 };
 };
 
-class VRPlatformDisplay {
+class VRPlatformDisplay : public CanMakeWeakPtr<VRPlatformDisplay> {
 public:
     virtual VRPlatformDisplayInfo getDisplayInfo() = 0;
     virtual VRPlatformTrackingInfo getTrackingInfo() = 0;
     virtual ~VRPlatformDisplay() = default;
-
-    WeakPtr<VRPlatformDisplay> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-private:
-    WeakPtrFactory<VRPlatformDisplay> m_weakPtrFactory;
 };
 
 }; // namespace WebCore
index 99a8f1d..d1dc673 100644 (file)
@@ -79,7 +79,7 @@ Vector<WeakPtr<VRPlatformDisplay>> VRPlatformManagerOpenVR::getVRDisplays()
     Vector<WeakPtr<VRPlatformDisplay>> displays;
     if (!m_display)
         m_display = std::make_unique<VRPlatformDisplayOpenVR>(m_system, chaperone, compositor);
-    displays.append(m_display->createWeakPtr());
+    displays.append(makeWeakPtr(*m_display));
     return displays;
 }
 
index 6661928..11e68a7 100644 (file)
@@ -85,7 +85,7 @@ public:
     // FIXME: Callers of these methods are dangerous and should be whitelisted explicitly or removed.
     RootInlineBox* originatingLine() const { return m_originatingLine.get(); }
     void clearOriginatingLine() { m_originatingLine = nullptr; }
-    void setOriginatingLine(RootInlineBox& line) { m_originatingLine = line.createWeakPtr(); }
+    void setOriginatingLine(RootInlineBox& line) { m_originatingLine = makeWeakPtr(line); }
 
     LayoutSize locationOffsetOfBorderBox() const
     {
index 83abfb8..ccd686e 100644 (file)
@@ -102,7 +102,7 @@ struct AnnotatedRegionValue {
 #endif
 
 // Base class for all rendering tree objects.
-class RenderObject : public CachedImageClient {
+class RenderObject : public CachedImageClient, public CanMakeWeakPtr<RenderObject> {
     WTF_MAKE_ISO_ALLOCATED(RenderObject);
     friend class RenderBlock;
     friend class RenderBlockFlow;
@@ -114,8 +114,6 @@ public:
     explicit RenderObject(Node&);
     virtual ~RenderObject();
 
-    auto& weakPtrFactory() const { return m_weakFactory; }
-
     RenderTheme& theme() const;
 
     virtual const char* renderName() const = 0;
@@ -838,8 +836,6 @@ private:
     RenderObject* m_previous;
     RenderObject* m_next;
 
-    WeakPtrFactory<RenderObject> m_weakFactory;
-
 #ifndef NDEBUG
     bool m_hasAXObject             : 1;
     bool m_setNeedsLayoutForbidden : 1;
index 08690b9..c8c0e54 100644 (file)
@@ -45,9 +45,9 @@ namespace WebCore {
 
 WTF_MAKE_ISO_ALLOCATED_IMPL(RootInlineBox);
 
-struct SameSizeAsRootInlineBox : public InlineFlowBox {
+struct SameSizeAsRootInlineBox : public InlineFlowBox, public CanMakeWeakPtr<RootInlineBox> {
     unsigned variables[7];
-    void* pointers[4];
+    void* pointers[3];
 };
 
 COMPILE_ASSERT(sizeof(RootInlineBox) == sizeof(SameSizeAsRootInlineBox), RootInlineBox_should_stay_small);
index 4eec009..dd9594f 100644 (file)
@@ -36,12 +36,11 @@ class RenderFragmentContainer;
 struct BidiStatus;
 struct GapRects;
 
-class RootInlineBox : public InlineFlowBox {
+class RootInlineBox : public InlineFlowBox, public CanMakeWeakPtr<RootInlineBox> {
     WTF_MAKE_ISO_ALLOCATED(RootInlineBox);
 public:
     explicit RootInlineBox(RenderBlockFlow&);
     virtual ~RootInlineBox();
-    WeakPtr<RootInlineBox> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
 
     RenderBlockFlow& blockFlow() const;
 
@@ -232,7 +231,6 @@ private:
     // Floats hanging off the line are pushed into this vector during layout. It is only
     // good for as long as the line has not been marked dirty.
     std::unique_ptr<CleanLineFloatList> m_floats;
-    WeakPtrFactory<RootInlineBox> m_weakPtrFactory;
 };
 
 inline RootInlineBox* RootInlineBox::nextRootBox() const
index bcdf148..1e4ec8f 100644 (file)
@@ -53,7 +53,7 @@ class SVGPathSegCurvetoQuadraticSmoothRel;
 class SVGPathSegList;
 class SVGPoint;
 
-class SVGPathElement final : public SVGGeometryElement, public SVGExternalResourcesRequired {
+class SVGPathElement final : public SVGGeometryElement, public SVGExternalResourcesRequired, public CanMakeWeakPtr<SVGPathElement> {
     WTF_MAKE_ISO_ALLOCATED(SVGPathElement);
 public:
     static Ref<SVGPathElement> create(const QualifiedName&, Document&);
@@ -99,8 +99,6 @@ public:
 
     bool isAnimValObserved() const { return m_isAnimValObserved; }
 
-    WeakPtr<SVGPathElement> createWeakPtr() const { return m_weakPtrFactory.createWeakPtr(*const_cast<SVGPathElement*>(this)); }
-
     void animatedPropertyWillBeDeleted();
 
     size_t approximateMemoryCost() const final;
@@ -135,7 +133,6 @@ private:
     SVGPathByteStream m_pathByteStream;
     mutable std::optional<Path> m_cachedPath;
     mutable SVGSynchronizableAnimatedProperty<SVGPathSegListValues> m_pathSegList;
-    WeakPtrFactory<SVGPathElement> m_weakPtrFactory;
     bool m_isAnimValObserved;
 };
 
index 60f3925..4e395b9 100644 (file)
@@ -27,7 +27,7 @@ class SVGPathSegWithContext : public SVGPathSeg {
 public:
     SVGPathSegWithContext(const SVGPathElement& element, SVGPathSegRole role)
         : m_role(role)
-        , m_element(element.createWeakPtr())
+        , m_element(makeWeakPtr(const_cast<SVGPathElement&>(element)))
     {
     }
 
@@ -55,7 +55,7 @@ public:
     void setContextAndRole(SVGPathElement* element, SVGPathSegRole role)
     {
         m_role = role;
-        m_element = element ? element->createWeakPtr() : WeakPtr<SVGPathElement>();
+        m_element = makeWeakPtr(element);
     }
 
 protected:
index 3b34333..c872fca 100644 (file)
@@ -61,7 +61,7 @@ public:
         detachListWrappers(0);
         
         RefPtr<SVGTransform> wrapper = m_values->consolidate();
-        m_wrappers->append(wrapper->createWeakPtr());
+        m_wrappers->append(makeWeakPtr(*wrapper));
 
         ASSERT(m_values->size() == m_wrappers->size());
         return WTFMove(wrapper);
index 60c4ba0..4298c6e 100644 (file)
@@ -51,7 +51,7 @@ public:
             return *static_cast<ListPropertyTearOff*>(m_baseVal.get());
 
         auto property = ListPropertyTearOff::create(*this, BaseValRole, m_values, m_wrappers);
-        m_baseVal = property->createWeakPtr();
+        m_baseVal = makeWeakPtr(property.get());
         return property;
     }
 
@@ -61,7 +61,7 @@ public:
             return *static_cast<ListPropertyTearOff*>(m_animVal.get());
 
         auto property = ListPropertyTearOff::create(*this, AnimValRole, m_values, m_wrappers);
-        m_animVal = property->createWeakPtr();
+        m_animVal = makeWeakPtr(property.get());
         return property;
     }
     
index 2e3d1f8..6732f9a 100644 (file)
@@ -43,7 +43,7 @@ public:
             return *static_cast<ListPropertyTearOff*>(m_baseVal.get());
 
         auto property = SVGPathSegList::create(*this, BaseValRole, PathSegUnalteredRole, m_values, m_wrappers);
-        m_baseVal = property->createWeakPtr();
+        m_baseVal = makeWeakPtr(property.get());
         return property;
     }
 
@@ -53,7 +53,7 @@ public:
             return *static_cast<ListPropertyTearOff*>(m_animVal.get());
 
         auto property = SVGPathSegList::create(*this, AnimValRole, PathSegUnalteredRole, m_values, m_wrappers);
-        m_animVal = property->createWeakPtr();
+        m_animVal = makeWeakPtr(property.get());
         return property;
     }
 
index ee5f06e..20ce5e5 100644 (file)
@@ -44,7 +44,7 @@ public:
             return *static_cast<PropertyTearOff*>(m_baseVal.get());
 
         auto property = PropertyTearOff::create(*this, BaseValRole, m_property);
-        m_baseVal = property->createWeakPtr();
+        m_baseVal = makeWeakPtr(property.get());
         return property;
     }
 
@@ -54,7 +54,7 @@ public:
             return *static_cast<PropertyTearOff*>(m_animVal.get());
 
         auto property = PropertyTearOff::create(*this, AnimValRole, m_property);
-        m_animVal = property->createWeakPtr();
+        m_animVal = makeWeakPtr(property.get());
         return property;
     }
 
index aa354d6..3397202 100644 (file)
@@ -38,7 +38,7 @@ public:
             return *static_cast<ListPropertyTearOff*>(m_baseVal.get());
 
         auto property = SVGTransformList::create(*this, BaseValRole, m_values, m_wrappers);
-        m_baseVal = property->createWeakPtr();
+        m_baseVal = makeWeakPtr(property.get());
         return property;
     }
 
@@ -48,7 +48,7 @@ public:
             return *static_cast<ListPropertyTearOff*>(m_animVal.get());
 
         auto property = SVGTransformList::create(*this, AnimValRole, m_values, m_wrappers);
-        m_animVal = property->createWeakPtr();
+        m_animVal = makeWeakPtr(property.get());
         return property;
     }
 
index 807492d..a00072d 100644 (file)
@@ -37,7 +37,7 @@ template<typename PropertyType>
 class SVGAnimatedListPropertyTearOff;
 
 template<typename PropertyType>
-class SVGListProperty : public SVGProperty {
+class SVGListProperty : public SVGProperty, public CanMakeWeakPtr<SVGListProperty<PropertyType>> {
 public:
     typedef SVGListProperty<PropertyType> Self;
 
@@ -162,7 +162,7 @@ public:
         m_values->clear();
 
         m_values->append(newItem->propertyReference());
-        m_wrappers->append(newItem->createWeakPtr());
+        m_wrappers->append(makeWeakPtr(newItem.get()));
 
         commitChange();
         return WTFMove(newItem);
@@ -206,7 +206,7 @@ public:
             // It is also associated with our animated property, so it can notify the SVG Element which holds the SVGAnimated*List
             // that it has been modified (and thus can call svgAttributeChanged(associatedAttributeName)).
             wrapper = ListItemTearOff::create(animatedList, UndefinedRole, m_values->at(index));
-            m_wrappers->at(index) = wrapper->createWeakPtr();
+            m_wrappers->at(index) = makeWeakPtr(*wrapper);
         }
 
         return wrapper.releaseNonNull();
@@ -264,7 +264,7 @@ public:
         m_values->insert(index, newItem->propertyReference());
 
         // Store new wrapper at position 'index', change its underlying value, so mutations of newItem, directly affect the item in the list.
-        m_wrappers->insert(index, newItem->createWeakPtr());
+        m_wrappers->insert(index, makeWeakPtr(newItem.get()));
 
         commitChange();
         return WTFMove(newItem);
@@ -341,7 +341,7 @@ public:
 
         // Update the value and the wrapper at the desired position 'index'. 
         m_values->at(index) = newItem->propertyReference();
-        m_wrappers->at(index) = newItem->createWeakPtr();
+        m_wrappers->at(index) = makeWeakPtr(newItem.get());
 
         commitChange();
         return WTFMove(newItem);
@@ -435,7 +435,7 @@ public:
 
         // Append the value and wrapper at the end of the list.
         m_values->append(newItem->propertyReference());
-        m_wrappers->append(newItem->createWeakPtr());
+        m_wrappers->append(makeWeakPtr(newItem.get()));
 
         commitChange(ListModificationAppend);
         return WTFMove(newItem);
@@ -453,11 +453,6 @@ public:
         return *m_wrappers;
     }
 
-    WeakPtr<SVGListProperty> createWeakPtr() const
-    {
-        return m_weakPtrFactory.createWeakPtr(*const_cast<SVGListProperty*>(this));
-    }
-
 protected:
     SVGListProperty(SVGPropertyRole role, PropertyType& values, ListWrapperCache* wrappers)
         : m_role(role)
@@ -486,7 +481,6 @@ protected:
     bool m_ownsValues;
     PropertyType* m_values;
     ListWrapperCache* m_wrappers;
-    WeakPtrFactory<SVGListProperty> m_weakPtrFactory;
 };
 
 }
index e0bf0d0..332260a 100644 (file)
@@ -29,8 +29,8 @@ public:
     static Ref<SVGMatrixTearOff> create(SVGTransform& parent, SVGMatrixValue& value)
     {
         ASSERT_UNUSED(value, &parent.propertyReference().svgMatrix() == &value);
-        Ref<SVGMatrixTearOff> result = adoptRef(*new SVGMatrixTearOff(parent));
-        parent.addChild(result->m_weakFactory.createWeakPtr(result));
+        auto result = adoptRef(*new SVGMatrixTearOff(parent));
+        parent.addChild(makeWeakPtr(result.get()));
         return result;
     }
 
@@ -52,7 +52,6 @@ private:
     }
 
     RefPtr<SVGTransform> m_parent;
-    WeakPtrFactory<SVGPropertyTearOffBase> m_weakFactory;
 };
 
 } // namespace WebCore
index ceb4bf3..9008f3b 100644 (file)
@@ -35,7 +35,7 @@ public:
 };
 
 template<typename T>
-class SVGPropertyTearOff : public SVGPropertyTearOffBase {
+class SVGPropertyTearOff : public SVGPropertyTearOffBase, public CanMakeWeakPtr<SVGPropertyTearOff<T>> {
 public:
     using PropertyType = T;
     using Self = SVGPropertyTearOff<PropertyType>;
@@ -125,11 +125,6 @@ public:
         return false;
     }
 
-    WeakPtr<SVGPropertyTearOff> createWeakPtr() const
-    {
-        return m_weakPtrFactory.createWeakPtr(*const_cast<SVGPropertyTearOff*>(this));
-    }
-
 protected:
     SVGPropertyTearOff(SVGAnimatedProperty* animatedProperty, SVGPropertyRole role, PropertyType& value)
         : m_animatedProperty(animatedProperty)
@@ -173,7 +168,6 @@ protected:
     SVGPropertyRole m_role;
     PropertyType* m_value;
     Vector<WeakPtr<SVGPropertyTearOffBase>> m_childTearOffs;
-    WeakPtrFactory<SVGPropertyTearOff> m_weakPtrFactory;
     bool m_valueIsCopy;
 };
 
index e2fdfbc..070a5e1 100644 (file)
@@ -98,7 +98,7 @@ void MockCDMFactory::setSupportedDataTypes(Vector<String>&& types)
 
 std::unique_ptr<CDMPrivate> MockCDMFactory::createCDM(const String&)
 {
-    return std::make_unique<MockCDM>(m_weakPtrFactory.createWeakPtr(*this));
+    return std::make_unique<MockCDM>(makeWeakPtr(*this));
 }
 
 MockCDM::MockCDM(WeakPtr<MockCDMFactory> factory)
@@ -166,7 +166,7 @@ RefPtr<CDMInstance> MockCDM::createInstance()
 {
     if (m_factory && !m_factory->canCreateInstances())
         return nullptr;
-    return adoptRef(new MockCDMInstance(m_weakPtrFactory.createWeakPtr(*this)));
+    return adoptRef(new MockCDMInstance(makeWeakPtr(*this)));
 }
 
 void MockCDM::loadAndInitialize()
index 418d390..216d29a 100644 (file)
@@ -39,7 +39,7 @@
 
 namespace WebCore {
 
-class MockCDMFactory : public RefCounted<MockCDMFactory>, private CDMFactory {
+class MockCDMFactory : public RefCounted<MockCDMFactory>, public CanMakeWeakPtr<MockCDMFactory>, private CDMFactory {
 public:
     static Ref<MockCDMFactory> create() { return adoptRef(*new MockCDMFactory); }
     ~MockCDMFactory();
@@ -90,11 +90,10 @@ private:
     bool m_canCreateInstances { true };
     bool m_supportsServerCertificates { true };
     bool m_supportsSessions { true };
-    WeakPtrFactory<MockCDMFactory> m_weakPtrFactory;
     HashMap<String, Vector<Ref<SharedBuffer>>> m_sessions;
 };
 
-class MockCDM : public CDMPrivate {
+class MockCDM : public CDMPrivate, public CanMakeWeakPtr<MockCDM> {
 public:
     MockCDM(WeakPtr<MockCDMFactory>);
 
@@ -120,7 +119,6 @@ private:
     std::optional<String> sanitizeSessionId(const String&) const final;
 
     WeakPtr<MockCDMFactory> m_factory;
-    WeakPtrFactory<MockCDM> m_weakPtrFactory;
 };
 
 class MockCDMInstance : public CDMInstance {
index f3a5442..9038caa 100644 (file)
@@ -35,7 +35,7 @@ namespace WebCore {
 
 class DOMPromise;
 
-class ExtendableEvent : public Event {
+class ExtendableEvent : public Event, public CanMakeWeakPtr<ExtendableEvent> {
 public:
     static Ref<ExtendableEvent> create(const AtomicString& type, const ExtendableEventInit& initializer, IsTrusted isTrusted = IsTrusted::No)
     {
@@ -55,14 +55,11 @@ protected:
     WEBCORE_EXPORT ExtendableEvent(const AtomicString&, const ExtendableEventInit&, IsTrusted);
     ExtendableEvent(const AtomicString&, bool bubbles, bool cancelable);
 
-    WeakPtr<ExtendableEvent> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
     void addExtendLifetimePromise(Ref<DOMPromise>&&);
 
 private:
     unsigned m_pendingPromiseCount { 0 };
     HashSet<Ref<DOMPromise>> m_extendLifetimePromises;
-    WeakPtrFactory<ExtendableEvent> m_weakPtrFactory;
     WTF::Function<void(HashSet<Ref<DOMPromise>>&&)> m_whenAllExtendLifetimePromisesAreSettledHandler;
 };
 
index 20e0c80..a054e84 100644 (file)
@@ -66,7 +66,7 @@ ExceptionOr<void> FetchEvent::respondWith(Ref<DOMPromise>&& promise)
     m_respondPromise = WTFMove(promise);
     addExtendLifetimePromise(*m_respondPromise);
 
-    m_respondPromise->whenSettled([this, weakThis = createWeakPtr()] () {
+    m_respondPromise->whenSettled([this, weakThis = makeWeakPtr(*this)] () {
         if (!weakThis)
             return;
         promiseIsSettled();
index cf5ecc1..49aec18 100644 (file)
@@ -65,7 +65,7 @@ class Timer;
 class SWServer {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    class Connection {
+    class Connection : public CanMakeWeakPtr<Connection> {
         WTF_MAKE_FAST_ALLOCATED;
         friend class SWServer;
     public:
@@ -74,8 +74,6 @@ public:
         using Identifier = SWServerConnectionIdentifier;
         Identifier identifier() const { return m_identifier; }
 
-        auto& weakPtrFactory() { return m_weakFactory; }
-
         WEBCORE_EXPORT void didResolveRegistrationPromise(const ServiceWorkerRegistrationKey&);
         SWServerRegistration* doRegistrationMatching(const SecurityOriginData& topOrigin, const URL& clientURL) { return m_server.doRegistrationMatching(topOrigin, clientURL); }
         void resolveRegistrationReadyRequests(SWServerRegistration&);
@@ -114,7 +112,6 @@ public:
 
         SWServer& m_server;
         Identifier m_identifier;
-        WeakPtrFactory<Connection> m_weakFactory;
         Vector<RegistrationReadyRequest> m_registrationReadyRequests;
     };
 
index daf2db6..2713e59 100644 (file)
@@ -25,7 +25,7 @@
 namespace WebCore {
 
 inline DOMParser::DOMParser(Document& contextDocument)
-    : m_contextDocument(contextDocument.createWeakPtr())
+    : m_contextDocument(makeWeakPtr(contextDocument))
 {
 }
 
index e84a2e1..d2fbb2d 100644 (file)
@@ -1,3 +1,70 @@
+2018-06-07  Chris Dumez  <cdumez@apple.com>
+
+        Add base class to get WeakPtrFactory member and avoid some boilerplate code
+        https://bugs.webkit.org/show_bug.cgi?id=186407
+
+        Reviewed by Brent Fulgham.
+
+        Add CanMakeWeakPtr base class to get WeakPtrFactory member and its getter, in
+        order to avoid some boilerplate code in every class needing a WeakPtrFactory.
+        This also gets rid of old-style createWeakPtr() methods in favor of the newer
+        makeWeakPtr().
+
+        * NetworkProcess/NetworkLoadChecker.h:
+        * NetworkProcess/NetworkProcess.cpp:
+        (WebKit::NetworkProcess::canAuthenticateAgainstProtectionSpace):
+        * NetworkProcess/PreconnectTask.h:
+        * NetworkProcess/cache/CacheStorageEngine.h:
+        * Shared/Authentication/AuthenticationManager.h:
+        * UIProcess/API/APIAttachment.cpp:
+        (API::Attachment::Attachment):
+        * UIProcess/ApplePay/WebPaymentCoordinatorProxy.cpp:
+        (WebKit::WebPaymentCoordinatorProxy::canMakePaymentsWithActiveCard):
+        (WebKit::WebPaymentCoordinatorProxy::openPaymentSetup):
+        * UIProcess/ApplePay/WebPaymentCoordinatorProxy.h:
+        * UIProcess/ApplePay/mac/WebPaymentCoordinatorProxyMac.mm:
+        (WebKit::WebPaymentCoordinatorProxy::platformShowPaymentUI):
+        * UIProcess/ApplicationStateTracker.h:
+        * UIProcess/ApplicationStateTracker.mm:
+        (WebKit::ApplicationStateTracker::ApplicationStateTracker):
+        * UIProcess/Cocoa/ViewGestureController.cpp:
+        (WebKit::ViewGestureController::setAlternateBackForwardListSourcePage):
+        * UIProcess/Cocoa/WebViewImpl.h:
+        * UIProcess/Cocoa/WebViewImpl.mm:
+        (WebKit::WebViewImpl::updateWindowAndViewFrames):
+        (WebKit::WebViewImpl::setTopContentInset):
+        (WebKit::WebViewImpl::viewDidMoveToWindow):
+        (WebKit::WebViewImpl::prepareForMoveToWindow):
+        (WebKit::WebViewImpl::validateUserInterfaceItem):
+        (WebKit::WebViewImpl::requestCandidatesForSelectionIfNeeded):
+        (WebKit::WebViewImpl::interpretKeyEvent):
+        (WebKit::WebViewImpl::firstRectForCharacterRange):
+        (WebKit::WebViewImpl::performKeyEquivalent):
+        (WebKit::WebViewImpl::keyUp):
+        (WebKit::WebViewImpl::keyDown):
+        * UIProcess/CredentialManagement/WebCredentialsMessengerProxy.cpp:
+        (WebKit::WebCredentialsMessengerProxy::makeCredential):
+        (WebKit::WebCredentialsMessengerProxy::getAssertion):
+        * UIProcess/CredentialManagement/WebCredentialsMessengerProxy.h:
+        * UIProcess/Downloads/DownloadProxy.cpp:
+        (WebKit::DownloadProxy::setOriginatingPage):
+        * UIProcess/Launcher/ProcessLauncher.h:
+        * UIProcess/Launcher/mac/ProcessLauncherMac.mm:
+        (WebKit::ProcessLauncher::launchProcess):
+        * UIProcess/ProcessAssertion.h:
+        * UIProcess/WebPageProxy.h:
+        * UIProcess/WebsiteData/WebsiteDataStore.h:
+        * UIProcess/gtk/WaylandCompositor.cpp:
+        (WebKit::WaylandCompositor::Surface::attachBuffer):
+        * UIProcess/gtk/WaylandCompositor.h:
+        * UIProcess/ios/ProcessAssertionIOS.mm:
+        (WebKit::ProcessAssertion::ProcessAssertion):
+        * UIProcess/mac/DisplayLink.cpp:
+        (WebKit::DisplayLink::displayLinkCallback):
+        * WebProcess/WebPage/RemoteLayerTree/RemoteLayerTreeDisplayRefreshMonitor.mm:
+        (WebKit::RemoteLayerTreeDisplayRefreshMonitor::RemoteLayerTreeDisplayRefreshMonitor):
+        * WebProcess/WebPage/RemoteLayerTree/RemoteLayerTreeDrawingArea.h:
+
 2018-06-07  Dan Bernstein  <mitz@apple.com>
 
         Don’t install process-webcontent-entitlements.sh into the built XPC services.
index ec74892..1442639 100644 (file)
@@ -44,7 +44,7 @@ namespace WebKit {
 class NetworkConnectionToWebProcess;
 class NetworkCORSPreflightChecker;
 
-class NetworkLoadChecker : public WebCore::ContentSecurityPolicyClient {
+class NetworkLoadChecker : public WebCore::ContentSecurityPolicyClient, public CanMakeWeakPtr<NetworkLoadChecker> {
 public:
     NetworkLoadChecker(NetworkConnectionToWebProcess&, uint64_t webPageID, uint64_t webFrameID, ResourceLoadIdentifier, WebCore::FetchOptions&&, PAL::SessionID, WebCore::HTTPHeaderMap&&, WebCore::URL&&, RefPtr<WebCore::SecurityOrigin>&&, WebCore::PreflightPolicy, String&& referrer);
     ~NetworkLoadChecker();
@@ -69,8 +69,6 @@ public:
     const WebCore::URL& url() const { return m_url; }
     WebCore::StoredCredentialsPolicy storedCredentialsPolicy() const { return m_storedCredentialsPolicy; }
 
-    WeakPtrFactory<NetworkLoadChecker>& weakPtrFactory() { return m_weakFactory; }
-
 private:
     WebCore::ContentSecurityPolicy* contentSecurityPolicy();
     bool isChecking() const { return !!m_corsPreflightChecker; }
@@ -134,7 +132,6 @@ private:
     WebCore::PreflightPolicy m_preflightPolicy;
     String m_dntHeaderValue;
     String m_referrer;
-    WeakPtrFactory<NetworkLoadChecker> m_weakFactory;
 };
 
 }
index 23652ba..3fb8164 100644 (file)
@@ -647,7 +647,7 @@ void NetworkProcess::canAuthenticateAgainstProtectionSpace(NetworkResourceLoader
 void NetworkProcess::canAuthenticateAgainstProtectionSpace(PreconnectTask& preconnectTask, const WebCore::ProtectionSpace& protectionSpace)
 {
     uint64_t loaderID = generateCanAuthenticateIdentifier();
-    m_waitingPreconnectTasks.set(loaderID, preconnectTask.createWeakPtr());
+    m_waitingPreconnectTasks.set(loaderID, makeWeakPtr(preconnectTask));
     parentProcessConnection()->send(Messages::NetworkProcessProxy::CanAuthenticateAgainstProtectionSpace(loaderID, preconnectTask.pageID(), preconnectTask.frameID(), protectionSpace), 0);
 }
 #endif
index 7af0188..fcef9da 100644 (file)
@@ -37,7 +37,7 @@ namespace WebKit {
 class NetworkLoad;
 class NetworkLoadParameters;
 
-class PreconnectTask final : public NetworkLoadClient {
+class PreconnectTask final : public NetworkLoadClient, public CanMakeWeakPtr<PreconnectTask> {
 public:
     explicit PreconnectTask(NetworkLoadParameters&&, WTF::CompletionHandler<void(const WebCore::ResourceError&)>&& completionHandler = { });
     ~PreconnectTask();
@@ -47,8 +47,6 @@ public:
 
     void continueCanAuthenticateAgainstProtectionSpace(bool);
 
-    WeakPtr<PreconnectTask> createWeakPtr() { return m_weakFactory.createWeakPtr(*this); }
-
 private:
     // NetworkLoadClient.
     bool isSynchronous() const final { return false; }
@@ -66,7 +64,6 @@ private:
     std::unique_ptr<NetworkLoad> m_networkLoad;
     WTF::CompletionHandler<void(const WebCore::ResourceError&)> m_completionHandler;
     WebCore::Timer m_timeoutTimer;
-    WeakPtrFactory<PreconnectTask> m_weakFactory;
 };
 
 } // namespace WebKit
index e2973b2..cdfc348 100644 (file)
@@ -53,7 +53,7 @@ namespace CacheStorage {
 using CacheIdentifier = uint64_t;
 using LockCount = uint64_t;
 
-class Engine : public RefCounted<Engine> {
+class Engine : public RefCounted<Engine>, public CanMakeWeakPtr<Engine> {
 public:
     ~Engine();
 
@@ -90,8 +90,6 @@ public:
     void clearAllCaches(WTF::CallbackAggregator&);
     void clearCachesForOrigin(const WebCore::SecurityOriginData&, WTF::CallbackAggregator&);
 
-    WeakPtrFactory<Engine>& weakPtrFactory() { return m_weakFactory; }
-
 private:
     static Engine& defaultEngine();
     explicit Engine(String&& rootPath);
@@ -119,7 +117,6 @@ private:
     std::optional<NetworkCache::Salt> m_salt;
     HashMap<CacheIdentifier, LockCount> m_cacheLocks;
     Vector<WebCore::DOMCacheEngine::CompletionCallback> m_initializationCallbacks;
-    WeakPtrFactory<Engine> m_weakFactory;
     HashMap<uint64_t, WebCore::DOMCacheEngine::CompletionCallback> m_pendingWriteCallbacks;
     HashMap<uint64_t, CompletionHandler<void(const NetworkCache::Data&, int error)>> m_pendingReadCallbacks;
     uint64_t m_pendingCallbacksCounter { 0 };
index 4b14dde..df54ceb 100644 (file)
@@ -59,7 +59,7 @@ enum class AuthenticationChallengeDisposition {
 };
 using ChallengeCompletionHandler = CompletionHandler<void(AuthenticationChallengeDisposition, const WebCore::Credential&)>;
 
-class AuthenticationManager : public NetworkProcessSupplement, public IPC::MessageReceiver {
+class AuthenticationManager : public NetworkProcessSupplement, public IPC::MessageReceiver, public CanMakeWeakPtr<AuthenticationManager> {
     WTF_MAKE_NONCOPYABLE(AuthenticationManager);
 public:
     explicit AuthenticationManager(ChildProcess&);
@@ -115,8 +115,6 @@ private:
     ChildProcess& m_process;
 
     HashMap<uint64_t, Challenge> m_challenges;
-
-    WeakPtrFactory<AuthenticationManager> m_weakPtrFactory;
 };
 
 } // namespace WebKit
index a2cf7ea..080c61e 100644 (file)
@@ -40,7 +40,7 @@ void AuthenticationManager::initializeConnection(IPC::Connection* connection)
 {
     ASSERT(isMainThread());
 
-    auto weakThis = m_weakPtrFactory.createWeakPtr(*this);
+    auto weakThis = makeWeakPtr(*this);
     // The following xpc event handler overwrites the boostrap event handler and is only used
     // to capture client certificate credential.
     xpc_connection_set_event_handler(connection->xpcConnection(), ^(xpc_object_t event) {
index 04e0717..7e009d6 100644 (file)
@@ -40,7 +40,7 @@ Ref<Attachment> Attachment::create(const WTF::String& identifier, WebKit::WebPag
 
 Attachment::Attachment(const WTF::String& identifier, WebKit::WebPageProxy& webPage)
     : m_identifier(identifier)
-    , m_webPage(webPage.createWeakPtr())
+    , m_webPage(makeWeakPtr(webPage))
 {
 }
 
index 914952e..780a15e 100644 (file)
@@ -69,7 +69,7 @@ void WebPaymentCoordinatorProxy::canMakePayments(bool& reply)
 
 void WebPaymentCoordinatorProxy::canMakePaymentsWithActiveCard(const String& merchantIdentifier, const String& domainName, uint64_t requestID)
 {
-    auto weakThis = m_weakPtrFactory.createWeakPtr(*this);
+    auto weakThis = makeWeakPtr(*this);
     platformCanMakePaymentsWithActiveCard(merchantIdentifier, domainName, [weakThis, requestID](bool canMakePayments) {
         auto paymentCoordinatorProxy = weakThis.get();
         if (!paymentCoordinatorProxy)
@@ -81,7 +81,7 @@ void WebPaymentCoordinatorProxy::canMakePaymentsWithActiveCard(const String& mer
 
 void WebPaymentCoordinatorProxy::openPaymentSetup(const String& merchantIdentifier, const String& domainName, uint64_t requestID)
 {
-    auto weakThis = m_weakPtrFactory.createWeakPtr(*this);
+    auto weakThis = makeWeakPtr(*this);
     platformOpenPaymentSetup(merchantIdentifier, domainName, [weakThis, requestID](bool result) {
         auto paymentCoordinatorProxy = weakThis.get();
         if (!paymentCoordinatorProxy)
index c820bd5..085019d 100644 (file)
@@ -55,7 +55,7 @@ namespace WebKit {
 
 class WebPageProxy;
 
-class WebPaymentCoordinatorProxy : private IPC::MessageReceiver {
+class WebPaymentCoordinatorProxy : private IPC::MessageReceiver, public CanMakeWeakPtr<WebPaymentCoordinatorProxy> {
 public:
     explicit WebPaymentCoordinatorProxy(WebPageProxy&);
     ~WebPaymentCoordinatorProxy();
@@ -107,7 +107,6 @@ private:
     void platformCompletePaymentSession(const std::optional<WebCore::PaymentAuthorizationResult>&);
 
     WebPageProxy& m_webPageProxy;
-    WeakPtrFactory<WebPaymentCoordinatorProxy> m_weakPtrFactory;
 
     enum class State {
         // Idle - Nothing's happening.
index dff8dec..7415938 100644 (file)
@@ -51,7 +51,7 @@ void WebPaymentCoordinatorProxy::platformShowPaymentUI(const WebCore::URL& origi
     auto paymentRequest = toPKPaymentRequest(m_webPageProxy, originatingURL, linkIconURLStrings, request);
 
     auto showPaymentUIRequestSeed = m_showPaymentUIRequestSeed;
-    auto weakThis = m_weakPtrFactory.createWeakPtr(*this);
+    auto weakThis = makeWeakPtr(*this);
     [getPKPaymentAuthorizationViewControllerClass() requestViewControllerWithPaymentRequest:paymentRequest.get() completion:BlockPtr<void (PKPaymentAuthorizationViewController *, NSError *)>::fromCallable([paymentRequest, showPaymentUIRequestSeed, weakThis, completionHandler = WTFMove(completionHandler)](PKPaymentAuthorizationViewController *viewController, NSError *error) {
         auto paymentCoordinatorProxy = weakThis.get();
         if (!paymentCoordinatorProxy)
index a0e93bd..4eb5b2b 100644 (file)
@@ -37,7 +37,7 @@ OBJC_CLASS UIView;
 
 namespace WebKit {
 
-class ApplicationStateTracker {
+class ApplicationStateTracker : public CanMakeWeakPtr<ApplicationStateTracker> {
 public:
     ApplicationStateTracker(UIView *, SEL didEnterBackgroundSelector, SEL didCreateWindowContextSelector, SEL didFinishSnapshottingAfterEnteringBackgroundSelector, SEL willEnterForegroundSelector);
     ~ApplicationStateTracker();
@@ -58,8 +58,6 @@ private:
 
     bool m_isInBackground;
 
-    WeakPtrFactory<ApplicationStateTracker> m_weakPtrFactory;
-
     RetainPtr<BKSApplicationStateMonitor> m_applicationStateMonitor;
 
     id m_didEnterBackgroundObserver;
index 1cfa080..7cf5ca7 100644 (file)
@@ -94,7 +94,7 @@ ApplicationStateTracker::ApplicationStateTracker(UIView *view, SEL didEnterBackg
     ASSERT(window);
 
     NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
-    auto weakThis = m_weakPtrFactory.createWeakPtr(*this);
+    auto weakThis = makeWeakPtr(*this);
     m_didCreateWindowContextObserver = [notificationCenter addObserverForName:@"_UIWindowDidCreateWindowContextNotification" object:window queue:nil usingBlock:[weakThis](NSNotification *) {
         auto applicationStateTracker = weakThis.get();
         if (!applicationStateTracker)
index 2b3ba77..35378b0 100644 (file)
@@ -108,10 +108,7 @@ void ViewGestureController::didEndGesture()
     
 void ViewGestureController::setAlternateBackForwardListSourcePage(WebPageProxy* page)
 {
-    if (page)
-        m_alternateBackForwardListSourcePage = page->createWeakPtr();
-    else
-        m_alternateBackForwardListSourcePage.clear();
+    m_alternateBackForwardListSourcePage = makeWeakPtr(page);
 }
     
 bool ViewGestureController::canSwipeInDirection(SwipeDirection direction) const
index e3994d3..164bac3 100644 (file)
@@ -124,7 +124,7 @@ typedef id <NSValidatedUserInterfaceItem> ValidationItem;
 typedef Vector<RetainPtr<ValidationItem>> ValidationVector;
 typedef HashMap<String, ValidationVector> ValidationMap;
 
-class WebViewImpl {
+class WebViewImpl : public CanMakeWeakPtr<WebViewImpl> {
     WTF_MAKE_FAST_ALLOCATED;
     WTF_MAKE_NONCOPYABLE(WebViewImpl);
 public:
@@ -578,8 +578,6 @@ private:
 #endif // ENABLE(WEB_PLAYBACK_CONTROLS_MANAGER)
 #endif // HAVE(TOUCH_BAR)
 
-    WeakPtr<WebViewImpl> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
     bool supportsArbitraryLayoutModes() const;
     float intrinsicDeviceScaleFactor() const;
     void dispatchSetTopContentInset();
@@ -613,8 +611,6 @@ private:
     std::unique_ptr<PageClient> m_pageClient;
     Ref<WebPageProxy> m_page;
 
-    WeakPtrFactory<WebViewImpl> m_weakPtrFactory;
-
     bool m_willBecomeFirstResponderAgain { false };
     bool m_inBecomeFirstResponder { false };
     bool m_inResignFirstResponder { false };
index 6f94bc6..b3fbba4 100644 (file)
@@ -1574,7 +1574,7 @@ void WebViewImpl::updateWindowAndViewFrames()
 
     m_didScheduleWindowAndViewFrameUpdate = true;
 
-    auto weakThis = createWeakPtr();
+    auto weakThis = makeWeakPtr(*this);
     dispatch_async(dispatch_get_main_queue(), [weakThis] {
         if (!weakThis)
             return;
@@ -1706,7 +1706,7 @@ void WebViewImpl::setTopContentInset(CGFloat contentInset)
 
     m_didScheduleSetTopContentInset = true;
 
-    auto weakThis = createWeakPtr();
+    auto weakThis = makeWeakPtr(*this);
     dispatch_async(dispatch_get_main_queue(), [weakThis] {
         if (!weakThis)
             return;
@@ -2069,7 +2069,7 @@ void WebViewImpl::viewDidMoveToWindow()
         m_page->layerHostingModeDidChange();
 
         if (!m_flagsChangedEventMonitor) {
-            auto weakThis = createWeakPtr();
+            auto weakThis = makeWeakPtr(*this);
             m_flagsChangedEventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskFlagsChanged handler:[weakThis] (NSEvent *flagsChangedEvent) {
                 if (weakThis)
                     weakThis->postFakeMouseMovedEventForFlagsChangedEvent(flagsChangedEvent);
@@ -2249,7 +2249,7 @@ void WebViewImpl::prepareForMoveToWindow(NSWindow *targetWindow, WTF::Function<v
 
     m_shouldDeferViewInWindowChanges = false;
 
-    auto weakThis = createWeakPtr();
+    auto weakThis = makeWeakPtr(*this);
     m_page->installActivityStateChangeCompletionHandler([weakThis, completionHandler = WTFMove(completionHandler)]() {
         completionHandler();
 
@@ -2786,7 +2786,7 @@ bool WebViewImpl::validateUserInterfaceItem(id <NSValidatedUserInterfaceItem> it
         // If we are not already awaiting validation for this command, start the asynchronous validation process.
         // FIXME: Theoretically, there is a race here; when we get the answer it might be old, from a previous time
         // we asked for the same command; there is no guarantee the answer is still valid.
-        auto weakThis = createWeakPtr();
+        auto weakThis = makeWeakPtr(*this);
         m_page->validateCommand(commandName, [weakThis](const String& commandName, bool isEnabled, int32_t state, WebKit::CallbackBase::Error error) {
             if (!weakThis)
                 return;
@@ -3036,7 +3036,7 @@ void WebViewImpl::requestCandidatesForSelectionIfNeeded()
 #if HAVE(ADVANCED_SPELL_CHECKING)
     NSRange selectedRange = NSMakeRange(postLayoutData.candidateRequestStartPosition, postLayoutData.selectedTextLength);
     NSTextCheckingTypes checkingTypes = NSTextCheckingTypeSpelling | NSTextCheckingTypeReplacement | NSTextCheckingTypeCorrection;
-    auto weakThis = createWeakPtr();
+    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(), ^{
             if (!weakThis)
@@ -4365,7 +4365,7 @@ void WebViewImpl::interpretKeyEvent(NSEvent *event, void(^completionHandler)(BOO
     }
 
     LOG(TextInput, "-> handleEventByInputMethod:%p %@", event, event);
-    [inputContext() handleEventByInputMethod:event completionHandler:[weakThis = createWeakPtr(), capturedEvent = retainPtr(event), capturedBlock = makeBlockPtr(completionHandler)](BOOL handled) {
+    [inputContext() handleEventByInputMethod:event completionHandler:[weakThis = makeWeakPtr(*this), capturedEvent = retainPtr(event), capturedBlock = makeBlockPtr(completionHandler)](BOOL handled) {
         if (!weakThis) {
             capturedBlock(NO, { });
             return;
@@ -4559,7 +4559,7 @@ void WebViewImpl::firstRectForCharacterRange(NSRange range, void(^completionHand
         return;
     }
 
-    auto weakThis = createWeakPtr();
+    auto weakThis = makeWeakPtr(*this);
     m_page->firstRectForCharacterRangeAsync(range, [weakThis, completionHandler](const WebCore::IntRect& rect, const EditingRange& actualRange, WebKit::CallbackBase::Error error) {
         auto completionHandlerBlock = (void (^)(NSRect, NSRange))completionHandler.get();
         if (!weakThis) {
@@ -4734,7 +4734,7 @@ bool WebViewImpl::performKeyEquivalent(NSEvent *event)
     // this event. This lets webpages have a crack at intercepting key-modified keypresses.
     // FIXME: Why is the firstResponder check needed?
     if (m_view.getAutoreleased() == [m_view window].firstResponder) {
-        interpretKeyEvent(event, [weakThis = createWeakPtr(), capturedEvent = retainPtr(event)](BOOL handledByInputMethod, const Vector<WebCore::KeypressCommand>& commands) {
+        interpretKeyEvent(event, [weakThis = makeWeakPtr(*this), capturedEvent = retainPtr(event)](BOOL handledByInputMethod, const Vector<WebCore::KeypressCommand>& commands) {
             if (weakThis)
                 weakThis->m_page->handleKeyboardEvent(NativeWebKeyboardEvent(capturedEvent.get(), handledByInputMethod, false, commands));
         });
@@ -4752,7 +4752,7 @@ void WebViewImpl::keyUp(NSEvent *event)
     LOG(TextInput, "keyUp:%p %@", event, event);
 
     m_isTextInsertionReplacingSoftSpace = false;
-    interpretKeyEvent(event, [weakThis = createWeakPtr(), capturedEvent = retainPtr(event)](BOOL handledByInputMethod, const Vector<WebCore::KeypressCommand>& commands) {
+    interpretKeyEvent(event, [weakThis = makeWeakPtr(*this), capturedEvent = retainPtr(event)](BOOL handledByInputMethod, const Vector<WebCore::KeypressCommand>& commands) {
         ASSERT(!handledByInputMethod || commands.isEmpty());
         if (weakThis)
             weakThis->m_page->handleKeyboardEvent(NativeWebKeyboardEvent(capturedEvent.get(), handledByInputMethod, weakThis->m_isTextInsertionReplacingSoftSpace, commands));
@@ -4781,7 +4781,7 @@ void WebViewImpl::keyDown(NSEvent *event)
     }
 
     m_isTextInsertionReplacingSoftSpace = false;
-    interpretKeyEvent(event, [weakThis = createWeakPtr(), capturedEvent = retainPtr(event)](BOOL handledByInputMethod, const Vector<WebCore::KeypressCommand>& commands) {
+    interpretKeyEvent(event, [weakThis = makeWeakPtr(*this), capturedEvent = retainPtr(event)](BOOL handledByInputMethod, const Vector<WebCore::KeypressCommand>& commands) {
         ASSERT(!handledByInputMethod || commands.isEmpty());
         if (weakThis)
             weakThis->m_page->handleKeyboardEvent(NativeWebKeyboardEvent(capturedEvent.get(), handledByInputMethod, weakThis->m_isTextInsertionReplacingSoftSpace, commands));
@@ -4810,7 +4810,7 @@ void WebViewImpl::flagsChanged(NSEvent *event)
         if (m_ignoresNonWheelEvents) \
             return; \
         if (NSTextInputContext *context = [m_view inputContext]) { \
-            auto weakThis = createWeakPtr(); \
+            auto weakThis = makeWeakPtr(*this); \
             RetainPtr<NSEvent> retainedEvent = event; \
             [context handleEvent:event completionHandler:[weakThis, retainedEvent] (BOOL handled) { \
                 if (!weakThis) \
@@ -4833,7 +4833,7 @@ void WebViewImpl::flagsChanged(NSEvent *event)
         if (m_ignoresNonWheelEvents) \
             return; \
         if (NSTextInputContext *context = [m_view inputContext]) { \
-            auto weakThis = createWeakPtr(); \
+            auto weakThis = makeWeakPtr(*this); \
             RetainPtr<NSEvent> retainedEvent = event; \
             [context handleEvent:event completionHandler:[weakThis, retainedEvent] (BOOL handled) { \
                 if (!weakThis) \
index 3afdd13..48a60eb 100644 (file)
@@ -58,7 +58,7 @@ void WebCredentialsMessengerProxy::makeCredential(uint64_t messageId, const Vect
     }
     // FIXME(183534): Weak pointers doesn't work in another thread because of race condition.
     // FIXME(183534): Unify callbacks.
-    auto weakThis = m_weakFactory.createWeakPtr(*this);
+    auto weakThis = makeWeakPtr(*this);
     auto callback = [weakThis, messageId] (const Vector<uint8_t>& credentialId, const Vector<uint8_t>& attestationObject) {
         if (!weakThis)
             return;
@@ -79,7 +79,7 @@ void WebCredentialsMessengerProxy::getAssertion(uint64_t messageId, const Vector
         exceptionReply(messageId, { WebCore::NotAllowedError, ASCIILiteral("No avaliable authenticators.") });
     // FIXME(183534): Weak pointers doesn't work in another thread because of race condition.
     // FIXME(183534): Unify callbacks.
-    auto weakThis = m_weakFactory.createWeakPtr(*this);
+    auto weakThis = makeWeakPtr(*this);
     auto callback = [weakThis, messageId] (const Vector<uint8_t>& credentialId, const Vector<uint8_t>& authenticatorData, const Vector<uint8_t>& signature, const Vector<uint8_t>& userHandle) {
         if (weakThis)
             weakThis->getAssertionReply(messageId, credentialId, authenticatorData, signature, userHandle);
index 0c2a4de..9d74c97 100644 (file)
@@ -44,7 +44,7 @@ namespace WebKit {
 
 class WebPageProxy;
 
-class WebCredentialsMessengerProxy : private IPC::MessageReceiver {
+class WebCredentialsMessengerProxy : private IPC::MessageReceiver, public CanMakeWeakPtr<WebCredentialsMessengerProxy> {
     WTF_MAKE_NONCOPYABLE(WebCredentialsMessengerProxy);
 public:
     explicit WebCredentialsMessengerProxy(WebPageProxy&);
@@ -67,7 +67,6 @@ private:
 
     WebPageProxy& m_webPageProxy;
     std::unique_ptr<WebCore::LocalAuthenticator> m_authenticator;
-    WeakPtrFactory<WebCredentialsMessengerProxy> m_weakFactory;
 };
 
 } // namespace WebKit
index 28dac21..96326eb 100644 (file)
@@ -99,7 +99,7 @@ WebPageProxy* DownloadProxy::originatingPage() const
 
 void DownloadProxy::setOriginatingPage(WebPageProxy* page)
 {
-    m_originatingPage = page ? page->createWeakPtr() : nullptr;
+    m_originatingPage = makeWeakPtr(page);
 }
 
 void DownloadProxy::didStart(const ResourceRequest& request, const String& suggestedFilename)
index 3ababbc..831b18d 100644 (file)
@@ -41,7 +41,7 @@
 
 namespace WebKit {
 
-class ProcessLauncher : public ThreadSafeRefCounted<ProcessLauncher> {
+class ProcessLauncher : public ThreadSafeRefCounted<ProcessLauncher>, public CanMakeWeakPtr<ProcessLauncher> {
 public:
     class Client {
     public:
@@ -101,7 +101,6 @@ private:
     WTF::Win32Handle m_hProcess;
 #endif
 
-    WeakPtrFactory<ProcessLauncher> m_weakPtrFactory;
     const LaunchOptions m_launchOptions;
     bool m_isLaunching;
     ProcessID m_processIdentifier;
index 31105e4..375a170 100644 (file)
@@ -201,7 +201,7 @@ void ProcessLauncher::launchProcess()
 
     xpc_dictionary_set_value(bootstrapMessage.get(), "extra-initialization-data", extraInitializationData.get());
 
-    auto weakProcessLauncher = m_weakPtrFactory.createWeakPtr(*this);
+    auto weakProcessLauncher = makeWeakPtr(*this);
     auto errorHandler = [weakProcessLauncher, listeningPort](xpc_object_t event) {
         ASSERT(!event || xpc_get_type(event) == XPC_TYPE_ERROR);
 
index dc9afd8..4c91947 100644 (file)
@@ -53,7 +53,11 @@ public:
     virtual void assertionWillExpireImminently() = 0;
 };
 
-class ProcessAssertion {
+class ProcessAssertion
+#if PLATFORM(IOS) && !PLATFORM(IOS_SIMULATOR)
+    : public CanMakeWeakPtr<ProcessAssertion>
+#endif
+{
 public:
     ProcessAssertion(ProcessID, AssertionState, Function<void()>&& invalidationCallback = { });
     virtual ~ProcessAssertion();
@@ -72,12 +76,10 @@ protected:
 
 private:
 #if PLATFORM(IOS) && !PLATFORM(IOS_SIMULATOR)
-    WeakPtr<ProcessAssertion> createWeakPtr() { return m_weakFactory.createWeakPtr(*this); }
     void markAsInvalidated();
 
     RetainPtr<BKSProcessAssertion> m_assertion;
     Validity m_validity { Validity::Unset };
-    WeakPtrFactory<ProcessAssertion> m_weakFactory;
     Function<void()> m_invalidationCallback;
 #endif
     AssertionState m_assertionState;
index 72db22b..a4d8d4c 100644 (file)
@@ -322,7 +322,8 @@ class WebPageProxy : public API::ObjectImpl<API::Object::Type::Page>
 #endif
     , public WebPopupMenuProxy::Client
     , public IPC::MessageReceiver
-    , public IPC::MessageSender {
+    , public IPC::MessageSender
+    , public CanMakeWeakPtr<WebPageProxy> {
 public:
     static Ref<WebPageProxy> create(PageClient&, WebProcessProxy&, uint64_t pageID, Ref<API::PageConfiguration>&&);
     virtual ~WebPageProxy();
@@ -1262,8 +1263,6 @@ public:
 #if ENABLE(GAMEPAD)
     void gamepadActivity(const Vector<GamepadData>&, bool shouldMakeGamepadsVisible);
 #endif
-        
-    WeakPtr<WebPageProxy> createWeakPtr() const { return m_weakPtrFactory.createWeakPtr(*const_cast<WebPageProxy*>(this)); }
 
     void isLoadingChanged() { activityStateDidChange(WebCore::ActivityState::IsLoading); }
 
@@ -2161,8 +2160,6 @@ private:
 
     bool m_isUsingHighPerformanceWebGL { false };
 
-    WeakPtrFactory<WebPageProxy> m_weakPtrFactory;
-
     HashMap<String, Ref<WebURLSchemeHandler>> m_urlSchemeHandlersByScheme;
     HashMap<uint64_t, Ref<WebURLSchemeHandler>> m_urlSchemeHandlersByIdentifier;
         
index 3abf8ff..978c3d9 100644 (file)
@@ -73,7 +73,7 @@ struct PluginModuleInfo;
 
 enum class ShouldClearFirst { No, Yes };
 
-class WebsiteDataStore : public RefCounted<WebsiteDataStore>, public WebProcessLifetimeObserver, public Identified<WebsiteDataStore>  {
+class WebsiteDataStore : public RefCounted<WebsiteDataStore>, public WebProcessLifetimeObserver, public Identified<WebsiteDataStore>, public CanMakeWeakPtr<WebsiteDataStore>  {
 public:
     constexpr static uint64_t defaultCacheStoragePerOriginQuota = 50 * 1024 * 1024;
 
@@ -183,8 +183,6 @@ public:
     void addSecKeyProxyStore(Ref<SecKeyProxyStore>&&);
 #endif
 
-    auto& weakPtrFactory() const { return m_weakFactory; }
-
 private:
     explicit WebsiteDataStore(PAL::SessionID);
     explicit WebsiteDataStore(Configuration, PAL::SessionID);
@@ -215,7 +213,6 @@ private:
 
     void maybeRegisterWithSessionIDMap();
 
-    WeakPtrFactory<WebsiteDataStore> m_weakFactory;
     const PAL::SessionID m_sessionID;
 
     const Configuration m_configuration;
index 6b339e0..8a8e697 100644 (file)
@@ -216,7 +216,7 @@ void WaylandCompositor::Surface::attachBuffer(struct wl_resource* buffer)
 
     if (buffer) {
         auto* compositorBuffer = WaylandCompositor::Buffer::getOrCreate(buffer);
-        m_pendingBuffer = compositorBuffer->createWeakPtr();
+        m_pendingBuffer = makeWeakPtr(*compositorBuffer);
     }
 }
 
index aa93334..6e51311 100644 (file)
@@ -55,7 +55,7 @@ class WaylandCompositor {
 public:
     static WaylandCompositor& singleton();
 
-    class Buffer {
+    class Buffer : public CanMakeWeakPtr<Buffer> {
         WTF_MAKE_NONCOPYABLE(Buffer); WTF_MAKE_FAST_ALLOCATED;
     public:
         static Buffer* getOrCreate(struct wl_resource*);
@@ -67,8 +67,6 @@ public:
         EGLImageKHR createImage() const;
         WebCore::IntSize size() const;
 
-        WeakPtr<Buffer> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
     private:
         Buffer(struct wl_resource*);
         static void destroyListenerCallback(struct wl_listener*, void*);
@@ -76,7 +74,6 @@ public:
         struct wl_resource* m_resource { nullptr };
         struct wl_listener m_destroyListener;
         uint32_t m_busyCount { 0 };
-        WeakPtrFactory<Buffer> m_weakPtrFactory;
     };
 
     class Surface {
index 0649d11..bfc6e75 100644 (file)
@@ -163,7 +163,7 @@ ProcessAssertion::ProcessAssertion(pid_t pid, AssertionState assertionState, Fun
     : m_invalidationCallback(WTFMove(invalidationCallback))
     , m_assertionState(assertionState)
 {
-    auto weakThis = createWeakPtr();
+    auto weakThis = makeWeakPtr(*this);
     BKSProcessAssertionAcquisitionHandler handler = ^(BOOL acquired) {
         if (!acquired) {
             RELEASE_LOG_ERROR(ProcessSuspension, " %p - ProcessAssertion() Unable to acquire assertion for process with PID %d", this, pid);
index bc68c30..bab075b 100644 (file)
@@ -98,7 +98,7 @@ void DisplayLink::resume()
 CVReturn DisplayLink::displayLinkCallback(CVDisplayLinkRef displayLinkRef, const CVTimeStamp*, const CVTimeStamp*, CVOptionFlags, CVOptionFlags*, void* data)
 {
     WebPageProxy* webPageProxy = reinterpret_cast<WebPageProxy*>(data);
-    RunLoop::main().dispatch([weakPtr = webPageProxy->createWeakPtr()] {
+    RunLoop::main().dispatch([weakPtr = makeWeakPtr(*webPageProxy)] {
         if (auto* proxy = weakPtr.get())
             proxy->process().send(Messages::DrawingArea::DisplayWasRefreshed(), proxy->pageID());
     });
index 9ca83b2..2263bc9 100644 (file)
@@ -34,7 +34,7 @@ namespace WebKit {
 
 RemoteLayerTreeDisplayRefreshMonitor::RemoteLayerTreeDisplayRefreshMonitor(PlatformDisplayID displayID, RemoteLayerTreeDrawingArea& drawingArea)
     : DisplayRefreshMonitor(displayID)
-    , m_drawingArea(drawingArea.createWeakPtr())
+    , m_drawingArea(makeWeakPtr(drawingArea))
 {
 }
 
index 9af5cb3..e9ee03e 100644 (file)
@@ -45,7 +45,7 @@ namespace WebKit {
 class RemoteLayerTreeContext;
 class RemoteLayerTreeDisplayRefreshMonitor;
 
-class RemoteLayerTreeDrawingArea : public DrawingArea, public WebCore::GraphicsLayerClient {
+class RemoteLayerTreeDrawingArea : public DrawingArea, public CanMakeWeakPtr<RemoteLayerTreeDrawingArea>, public WebCore::GraphicsLayerClient {
     friend class RemoteLayerTreeDisplayRefreshMonitor;
 public:
     RemoteLayerTreeDrawingArea(WebPage&, const WebPageCreationParameters&);
@@ -54,8 +54,6 @@ public:
     uint64_t nextTransactionID() const { return m_currentTransactionID + 1; }
     uint64_t lastCommittedTransactionID() const { return m_currentTransactionID; }
 
-    WeakPtr<RemoteLayerTreeDrawingArea> createWeakPtr() { return m_weakPtrFactory.createWeakPtr(*this); }
-
 private:
     // DrawingArea
     void setNeedsDisplay() override;
@@ -170,8 +168,6 @@ private:
 
     WebCore::GraphicsLayer* m_contentLayer { nullptr };
     WebCore::GraphicsLayer* m_viewOverlayRootLayer { nullptr };
-    
-    WeakPtrFactory<RemoteLayerTreeDrawingArea> m_weakPtrFactory;
 };
 
 } // namespace WebKit
index f8e309a..f4c5949 100644 (file)
@@ -1,3 +1,19 @@
+2018-06-07  Chris Dumez  <cdumez@apple.com>
+
+        Add base class to get WeakPtrFactory member and avoid some boilerplate code
+        https://bugs.webkit.org/show_bug.cgi?id=186407
+
+        Reviewed by Brent Fulgham.
+
+        Add CanMakeWeakPtr base class to get WeakPtrFactory member and its getter, in
+        order to avoid some boilerplate code in every class needing a WeakPtrFactory.
+        This also gets rid of old-style createWeakPtr() methods in favor of the newer
+        makeWeakPtr().
+
+        * WebCoreSupport/WebEditorClient.h:
+        * WebCoreSupport/WebEditorClient.mm:
+        (WebEditorClient::requestCandidatesForSelection):
+
 2018-06-05  Chris Dumez  <cdumez@apple.com>
 
         Regression(r232082): Websites get loaded inside of Messages App chat transcript
index fa2ed32..4f10ad3 100644 (file)
@@ -43,7 +43,7 @@
 @class WebView;
 @class WebEditorUndoTarget;
 
-class WebEditorClient final : public WebCore::EditorClient, public WebCore::TextCheckerClient {
+class WebEditorClient final : public WebCore::EditorClient, public WebCore::TextCheckerClient, public CanMakeWeakPtr<WebEditorClient> {
 public:
     WebEditorClient(WebView *);
     virtual ~WebEditorClient();
@@ -193,8 +193,6 @@ private:
 
     enum class EditorStateIsContentEditable { No, Yes, Unset };
     EditorStateIsContentEditable m_lastEditorStateWasContentEditable { EditorStateIsContentEditable::Unset };
-
-    WeakPtrFactory<WebEditorClient> m_weakPtrFactory;
 };
 
 inline NSSelectionAffinity kit(WebCore::EAffinity affinity)
index fce5d7a..610f8e0 100644 (file)
@@ -1213,7 +1213,7 @@ void WebEditorClient::requestCandidatesForSelection(const VisibleSelection& sele
     m_paragraphContextForCandidateRequest = plainText(frame->editor().contextRangeForCandidateRequest().get());
 
     NSTextCheckingTypes checkingTypes = NSTextCheckingTypeSpelling | NSTextCheckingTypeReplacement | NSTextCheckingTypeCorrection;
-    auto weakEditor = m_weakPtrFactory.createWeakPtr(*this);
+    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(), ^{
             if (!weakEditor)