Remove PassRefPtr from "loader" directory of WebCore
authordarin@apple.com <darin@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Wed, 18 Jan 2017 05:17:17 +0000 (05:17 +0000)
committerdarin@apple.com <darin@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Wed, 18 Jan 2017 05:17:17 +0000 (05:17 +0000)
https://bugs.webkit.org/show_bug.cgi?id=167055

Reviewed by Alex Christensen.

Source/WebCore:

* dom/Document.cpp:
(WebCore::Document::processHttpEquiv): Pass a reference.
* editing/CompositeEditCommand.cpp:
(WebCore::EditCommandComposition::unapply): Ditto.
(WebCore::EditCommandComposition::reapply): Ditto.
(WebCore::CompositeEditCommand::ensureComposition): Return a reference.
(WebCore::CompositeEditCommand::applyCommandToComposite): Use a reference.
* editing/CompositeEditCommand.h: Updated for above changes.

* editing/Editor.cpp:
(WebCore::Editor::unappliedEditing): Take a reference instead of a PassRefPtr.
(WebCore::Editor::reappliedEditing): Ditto.
* editing/Editor.h: Updated for above changes. Also changed the
FragmentAndResources resources vector to hold Ref instead of RefPtr.

* editing/cocoa/EditorCocoa.mm:
(WebCore::Editor::createFragmentAndAddResources): Updated for change to
FragmentAndResources.

* editing/ios/EditorIOS.mm:
(WebCore::Editor::WebContentReader::readWebArchive): Pass a reference.

* editing/mac/EditorMac.mm:
(WebCore::Editor::WebContentReader::readWebArchive): Pass a reference.

* history/PageCache.cpp:
(WebCore::canCacheFrame): Use a reference.

* html/FileInputType.cpp:
(WebCore::FileInputType::handleDOMActivateEvent): Pass references.

* html/HTMLFormControlElement.cpp:
(WebCore::HTMLFormControlElement::formMethod): Use auto.

* html/HTMLFormElement.cpp:
(WebCore::HTMLFormElement::prepareForSubmission): Updated to use a return
values for textFieldValues intsead of an out argument with getTextFieldValues.
(WebCore::HTMLFormElement::textFieldValues): Renamed from getTextFieldValues
and changed to use a return value instead of an out argument.
(WebCore::HTMLFormElement::submit): Pass a reference.
(WebCore::HTMLFormElement::requestAutocomplete): Pass a Ref&&.
* html/HTMLFormElement.h: Updated for above changes.

* html/HTMLHtmlElement.cpp:
(WebCore::HTMLHtmlElement::insertedByParser): Use a reference.

* html/HTMLLinkElement.cpp:
(WebCore::HTMLLinkElement::process): Pass a reference.
(WebCore::HTMLLinkElement::setCSSStyleSheet): Use auto.

* html/HTMLMediaElement.cpp:
(WebCore::HTMLMediaElement::loadResource): Use a reference.

* inspector/InspectorApplicationCacheAgent.cpp:
(WebCore::InspectorApplicationCacheAgent::updateApplicationCacheStatus): Use a reference,
also update for struct-style member names withou m_ prefix.
(WebCore::InspectorApplicationCacheAgent::getFramesWithManifests): Ditto.
(WebCore::InspectorApplicationCacheAgent::getManifestForFrame): Ditto.
(WebCore::InspectorApplicationCacheAgent::getApplicationCacheForFrame): Ditto.
(WebCore::InspectorApplicationCacheAgent::buildObjectForApplicationCache): Ditto.
(WebCore::InspectorApplicationCacheAgent::buildArrayForApplicationCacheResources): Ditto.
(WebCore::InspectorApplicationCacheAgent::buildObjectForApplicationCacheResource): Ditto.
* inspector/InspectorApplicationCacheAgent.h: Updated for above changes.

* inspector/InspectorInstrumentation.cpp:
(WebCore::InspectorInstrumentation::updateApplicationCacheStatusImpl): Take a reference.
* inspector/InspectorInstrumentation.h: Updated for the above.

* loader/DocumentLoader.cpp:
(WebCore::DocumentLoader::DocumentLoader): Move much initialization to class definition.
(WebCore::DocumentLoader::originalRequest): Moved to header to make it inline.
(WebCore::DocumentLoader::originalRequestCopy): Ditto.
(WebCore::DocumentLoader::request): Ditto.
(WebCore::DocumentLoader::url): Ditto.
(WebCore::DocumentLoader::stopLoading): Pass a reference.
(WebCore::DocumentLoader::willSendRequest): Updated to take a raw pointer instead of a
PassRefPtr.
(WebCore::DocumentLoader::commitData): Call shouldUseMainResourceEncoding instead of
special casing WebArchive.
(WebCore::DocumentLoader::maybeCreateArchive): Pass references.
(WebCore::DocumentLoader::setArchive): Take Ref&& instead of PassRefPtr.
(WebCore::DocumentLoader::addAllArchiveResources): Take a reference instead
of a pointer.
(WebCore::DocumentLoader::popArchiveForSubframe): Return RefPtr instead of
PassRefPtr.
(WebCore::DocumentLoader::subresource): Ditto.
(WebCore::DocumentLoader::subresources): Return a Vector<Ref> instead of a
Vector<RefPtr>.
(WebCore::DocumentLoader::substituteResourceDeliveryTimerFired): Use move
instead of swap.
(WebCore::DocumentLoader::scheduleArchiveLoad): Use shouldLoadFromArchiveOnly
instead of a special case for each type of archive.
(WebCore::DocumentLoader::originalURL): Moved to header to make it inline.
(WebCore::DocumentLoader::responseURL): Ditto.
(WebCore::DocumentLoader::documentURL): Call shouldUseMainResourceURL instead of
special casing WebArchive.
(WebCore::DocumentLoader::responseMIMEType): Moved to header to make it inline.
(WebCore::DocumentLoader::currentContentType): Ditto.
(WebCore::DocumentLoader::contentFilter): Ditto.
(WebCore::DocumentLoader::getIconLoadDecisionForIconURL): Pass a reference.
(WebCore::DocumentLoader::getIconDataForIconURL): Ditto.
(WebCore::DocumentLoader::dispatchOnloadEvents): Use a reference.
(WebCore::DocumentLoader::unreachableURL): Moved to header to make it inline.
* loader/DocumentLoader.h: Updated for the above.

* loader/EmptyClients.cpp: Updated for changes to client interfaces.
* loader/EmptyClients.h: Ditto.

* loader/FormState.cpp:
(WebCore::FormState::FormState): Take references instead of PassRefPtr, also
take Vector&& instead of Vector& when we want to take ownership and use move
instead of swap to do that.
(WebCore::FormState::create): Ditto.
* loader/FormState.h: Updated for the above. Also changed return values to be
references instead of pointers and members to be Ref instead of RefPtr.

* loader/FormSubmission.cpp:
(WebCore::FormSubmission::Attributes::parseMethodType): Updated for change
to the Method enumeration.
(WebCore::FormSubmission::Attributes::copyFrom): Deleted.
(WebCore::FormSubmission::FormSubmission): Use Ref&& instead of PassRefPtr.
(WebCore::FormSubmission::create): Use reference instead of pointer and
raw pointer instead of PassRefPtr. Also copy attributes using copy constructor
instead of an explicit copyFrom function.
(WebCore::FormSubmission::requestURL): Updated for change to the Method
enumeration.
(WebCore::FormSubmission::populateFrameLoadRequest): Ditto.
* loader/FormSubmission.h: Updated for the above changes. Made the Attributes
class copyable, since we copy it. Changed some functions to return references
instead of pointers and use Ref instead of RefPtr for data members.

* loader/FrameLoader.cpp:
(WebCore::FrameLoader::submitForm): Updated for changes to FormSubmission
and FormState.
(WebCore::FrameLoader::receivedFirstData): Ditto.
(WebCore::FrameLoader::loadFrameRequest): Ditto.
(WebCore::FrameLoader::loadResourceSynchronously): Ditto.
(WebCore::FrameLoader::continueLoadAfterNavigationPolicy): Ditto.

* loader/FrameLoaderClient.h: Use references, pointers, RefPtr, and Ref
instead of PassRefPtr. Removed unused empty dispatchDidFailToStartPlugin.

* loader/HistoryController.cpp:
(WebCore::HistoryController::pushState): Take RefPtr&& instead of PassRefPtr.
(WebCore::HistoryController::replaceState): Ditto.
* loader/HistoryController.h: Updated for the above.

* loader/ImageLoader.cpp:
(WebCore::ImageLoader::updateFromElement): Pass a reference.

* loader/NavigationScheduler.cpp: Use refernces and Ref&& instead of
pointers and PassRefPtr.
(WebCore::ScheduledNavigation::ScheduledNavigation): Added an overload
that sests m_shouldOpenExternalURLsPolicy.
* loader/NavigationScheduler.h: Updated for the above.

* loader/ResourceLoader.cpp:
(WebCore::ResourceLoader::start): Use and pass references.
(WebCore::ResourceLoader::willSendRequest): Ditto.
(WebCore::ResourceLoader::didReceiveResponse): Ditto.
(WebCore::ResourceLoader::didFail): Ditto.

* loader/SubframeLoader.cpp:
(WebCore::SubframeLoader::createJavaAppletWidget): Return RefPtr instead
of PassRefPtr. Pass references instead of pointers.
(WebCore::SubframeLoader::loadOrRedirectSubframe): Ditto.
(WebCore::SubframeLoader::loadSubframe): Ditto.
(WebCore::SubframeLoader::document): Deleted. This was never really the
correct idiom for getting the appropriate document; hiding the dependency
on m_frame wasn't paing off.
(WebCore::SubframeLoader::loadPlugin): Pass reference instead of pointer.
(WebCore::SubframeLoader::shouldConvertInvalidURLsToBlank): Eliminated
unneeded null checking and complexity due to going through the document
instead of the frame for this check.
* loader/SubframeLoader.h: Updated for the above.

* loader/appcache/ApplicationCache.cpp:
(WebCore::ApplicationCache::ApplicationCache): Moved data member
initialization to the class definition.
(WebCore::ApplicationCache::~ApplicationCache): Pass a reference instead
of a pointer.
(WebCore::ApplicationCache::isComplete): Ditto.
(WebCore::ApplicationCache::setManifestResource): Take Ref&& instead of
PassRefPtr.
(WebCore::ApplicationCache::addResource): Ditto.
(WebCore::ApplicationCache::removeResource): Deleted. Was unused.
* loader/appcache/ApplicationCache.h: Updated for above changes.

* loader/appcache/ApplicationCacheGroup.cpp:
(WebCore::ApplicationCacheGroup::ApplicationCacheGroup): Moved most
member initialization to the class definition.
(WebCore::ApplicationCacheGroup::~ApplicationCacheGroup): Pass a reference.
(WebCore::ApplicationCacheGroup::cacheForMainRequest): Removed
unnecessary preflight for removeFragmentIdentifier, which efficiently
does nothing if there is no identifier. Use early return.
(WebCore::ApplicationCacheGroup::fallbackCacheForMainRequest): More of
the same.
(WebCore::ApplicationCacheGroup::selectCache): Ditto, also take a reference,
and use event names instead of a special enumeration to poast events.
(WebCore::ApplicationCacheGroup::selectCacheWithoutManifestURL): Ditto.
(WebCore::ApplicationCacheGroup::finishedLoadingMainResource): Ditto.
(WebCore::ApplicationCacheGroup::failedLoadingMainResource): Ditto.
(WebCore::ApplicationCacheGroup::disassociateDocumentLoader): Ditto.
(WebCore::ApplicationCacheGroup::cacheDestroyed): Ditto.
(WebCore::ApplicationCacheGroup::stopLoadingInFrame): Ditto.
(WebCore::ApplicationCacheGroup::setNewestCache): Use Ref&& instead of
PassRefPtr.
(WebCore::ApplicationCacheGroup::makeObsolete): More of the same.
(WebCore::ApplicationCacheGroup::update): Ditto.
(WebCore::ApplicationCacheGroup::abort): Ditto.
(WebCore::ApplicationCacheGroup::didReceiveResponse): Ditto.
(WebCore::ApplicationCacheGroup::didFinishLoading): Ditto.
(WebCore::ApplicationCacheGroup::didFail): Ditto.
(WebCore::ApplicationCacheGroup::didFinishLoadingManifest): Ditto.
(WebCore::ApplicationCacheGroup::manifestNotFound): Ditto.
(WebCore::ApplicationCacheGroup::checkIfLoadIsComplete): Ditto.
(WebCore::ApplicationCacheGroup::startLoadingEntry): Ditto.
(WebCore::ApplicationCacheGroup::deliverDelayedMainResources): Use a modern
for loop.
(WebCore::ApplicationCacheGroup::addEntry): Use auto and simplify logic
for adding.
(WebCore::ApplicationCacheGroup::associateDocumentLoaderWithCache): Update since
function result is a reference.
(WebCore::ApplicationCacheGroup::scheduleReachedMaxAppCacheSizeCallback):
Use auto.
(WebCore::ApplicationCacheGroup::postListenerTask): Take event type instead of
taking a special enumeration.
* loader/appcache/ApplicationCacheGroup.h: Updated for the above.

* loader/appcache/ApplicationCacheHost.cpp:
(WebCore::ApplicationCacheHost::ApplicationCacheHost): Move most member
initialization to the class definition.
(WebCore::ApplicationCacheHost::~ApplicationCacheHost): Use reference.
(WebCore::ApplicationCacheHost::selectCacheWithoutManifest): Ditto.
(WebCore::ApplicationCacheHost::selectCacheWithManifest): Ditto.
(WebCore::ApplicationCacheHost::mainResourceDataReceived): Ditto.
(WebCore::ApplicationCacheHost::failedLoadingMainResource): Ditto.
(WebCore::ApplicationCacheHost::finishedLoadingMainResource): Ditto.
(WebCore::ApplicationCacheHost::maybeLoadFallbackForRedirect): Ditto.
(WebCore::ApplicationCacheHost::maybeLoadFallbackForResponse): Ditto.
(WebCore::ApplicationCacheHost::createFileURL): Ditto.
(WebCore::ApplicationCacheHost::maybeLoadSynchronously): Ditto.
(WebCore::ApplicationCacheHost::notifyDOMApplicationCache): Take event
type instead of special enumeration.
(WebCore::ApplicationCacheHost::stopLoadingInFrame): Use reference.
(WebCore::ApplicationCacheHost::stopDeferringEvents): Updated to use
event types instead of special enumeration and also repaired possible
edge case where code in event handler somehow triggers additional events.
(WebCore::ApplicationCacheHost::resourceList): Renamed from fillResourceList
and changed to return a vector instead of populating one.
(WebCore::ApplicationCacheHost::applicationCacheInfo): Tweak coding style a bit.
(WebCore::createApplicationCacheEvent): Factored this helper out of
dispatchDOMEvent so we can use Ref instead of RefPtr.
(WebCore::ApplicationCacheHost::dispatchDOMEvent): Updated to recent event type
rather than receiving an event id and mapping it to a type.
(WebCore::ApplicationCacheHost::setApplicationCache): Take RefPtr&& instead of
PassRefPtr.
(WebCore::ApplicationCacheHost::update): Pass a reference.
(WebCore::ApplicationCacheHost::swapCache): Ditto.
(WebCore::ApplicationCacheHost::abort): Ditto.
* loader/appcache/ApplicationCacheHost.h: Updated for the above.

* loader/appcache/ApplicationCacheStorage.cpp:
(WebCore::ApplicationCacheStorage::loadCacheGroup): Pass a Ref instead of RefPtr.
(WebCore::ApplicationCacheStorage::cacheGroupForURL): Ditto.
(WebCore::ApplicationCacheStorage::fallbackCacheGroupForURL): Ditto.
(WebCore::ApplicationCacheStorage::cacheGroupDestroyed): Take a reference.
(WebCore::ApplicationCacheStorage::cacheGroupMadeObsolete): Ditto.
(WebCore::ApplicationCacheStorage::storeNewestCache): Ditto.
(WebCore::ApplicationCacheStorage::loadCache): Return RefPtr instead of PassRefPtr.
(WebCore::ApplicationCacheStorage::deleteCacheGroup): Pass a reference.
* loader/appcache/ApplicationCacheStorage.h: Updated for the above.

* loader/appcache/DOMApplicationCache.cpp:
(WebCore::DOMApplicationCache::DOMApplicationCache): Take a reference.
(WebCore::DOMApplicationCache::toEventType): Deleted.
* loader/appcache/DOMApplicationCache.h: Updated for the above. Made most
members private.

* loader/archive/Archive.cpp:
(WebCore::Archive::clearAllSubframeArchives): Use a set for the logic that
prevents us from walking the same archive more than once, rather than using
a vector. Left it recursive, though.
* loader/archive/Archive.h: Git rid of the type function, replacing it with
three functions for the four different policies we currently have about the
different archive types. Changed functions to take Ref&& instead of PassRefPtr
and return const Vector<Ref>& instead of const Vector<RefPtr>&, changing the
data members to match.

* loader/archive/ArchiveFactory.cpp:
(WebCore::createArchiveMIMETypesMap): Factored this out of the archiveMIMETypes
function so we don't need a boolean. Also use ASCIILiteral.
(WebCore::archiveMIMETypes): Updated to se the above.

* loader/archive/ArchiveResourceCollection.cpp:
(WebCore::ArchiveResourceCollection::addAllResources): Take a reference.
(WebCore::ArchiveResourceCollection::popSubframeArchive): Return RefPtr instead
of PassRefPtr.
* loader/archive/ArchiveResourceCollection.h: Updated for the above.

* loader/archive/cf/LegacyWebArchive.cpp:
(WebCore::LegacyWebArchive::createPropertyListRepresentation): Use auto and
fewer local variables, more references for argument types and return values.
(WebCore::LegacyWebArchive::createResourceResponseFromPropertyListData): Ditto.
(WebCore::LegacyWebArchive::createResource): Ditto.
(WebCore::LegacyWebArchive::create): Ditto.
(WebCore::LegacyWebArchive::extract): Ditto.
(WebCore::LegacyWebArchive::type): Deleted.
(WebCore::LegacyWebArchive::rawDataRepresentation): More of the same.
(WebCore::LegacyWebArchive::createFromSelection): Ditto.
* loader/archive/cf/LegacyWebArchive.h: Updated for the above. Also marked the
class final and added overrides for the four new policy member functions.

* loader/archive/mhtml/MHTMLArchive.cpp:
(WebCore::MHTMLArchive::create): Pass references.
(WebCore::MHTMLArchive::generateMHTMLData): Return RefPtr instead of
PassRefPtr.
* loader/archive/mhtml/MHTMLArchive.h: Updated for the above. Also marked the
class final and added overrides for the four new policy member functions.

* loader/archive/mhtml/MHTMLParser.cpp:
(WebCore::MHTMLParser::parseArchiveWithHeader): Pass Ref instead of RefPtr
to setMainResource and addSubframeArchive.
(WebCore::MHTMLParser::addResourceToArchive): Ditto.

* loader/cache/CachedCSSStyleSheet.cpp:
(WebCore::CachedCSSStyleSheet::restoreParsedStyleSheet): Return RefPtr instead
of PassRefPtr.
* loader/cache/CachedCSSStyleSheet.h: Updated for the above.

* loader/cache/CachedResourceRequest.cpp:
(WebCore::CachedResourceRequest::setInitiator): Take a reference instead of a
PassRefPtr.
* loader/cache/CachedResourceRequest.h: Updated for the above.

* loader/cocoa/DiskCacheMonitor.h: Removed. This is a duplicate, unused copy
of DiskCacheMonitorCocoa.h.

* loader/cocoa/DiskCacheMonitorCocoa.h: Removed unneeded exporting and virtual
member functions, made more things private, and changed return type to RefPtr
instead of PassRefPtr.
* loader/cocoa/DiskCacheMonitorCocoa.mm:
(WebCore::DiskCacheMonitor::tryGetFileBackedSharedBufferFromCFURLCachedResponse):
Changed return type to RefPtr instead of PassRefPtr.

* loader/icon/IconDatabase.cpp:
(WebCore::IconDatabase::setIconDataForIconURL): Take raw pointer instead of
PassRefPtr.
(WebCore::IconDatabase::getOrCreateIconRecord): Return Ref instead of PassRefPtr.
(WebCore::IconDatabase::getImageDataForIconURLFromSQLDatabase): Return RefPtr
instead of PassRefPtr.
* loader/icon/IconDatabase.h: Updated for the above. Also marked functions final
instead of override.
* loader/icon/IconDatabaseBase.h: Ditto.

* loader/icon/PageURLRecord.cpp:
(WebCore::PageURLRecord::PageURLRecord): Moved initialization to the header.
(WebCore::PageURLRecord::~PageURLRecord): Wrote code here instead of calling
setIconRecord(nullptr).
(WebCore::PageURLRecord::setIconRecord): Take RefPtr&& instead of PassRefPtr.
* loader/icon/PageURLRecord.h: Updatd for the above.

* page/Chrome.cpp:
(WebCore::Chrome::runOpenPanel): Updated to take two references.
* page/Chrome.h: Ditto.
* page/ChromeClient.h: ditto.

* page/DOMWindow.cpp:
(WebCore::DOMWindow::applicationCache): Pass a reference.
(WebCore::DOMWindow::setLocation): Ditto.
(WebCore::DOMWindow::createWindow): Ditto.
(WebCore::DOMWindow::open): Ditto.

* page/EditorClient.h: Changed arguments to references instead of PassRefPtr.

* page/History.cpp:
(WebCore::History::stateObjectAdded): Pass an rvalue reference.

* page/Location.cpp:
(WebCore::Location::reload): Pass reference instead of pointer.
(WebCore::Location::setLocation): Ditto.

* platform/URL.cpp:
(WebCore::URL::setFragmentIdentifier): Take a StringView rather than
a String, which is more flexible for callers. Also eliminated an unneeded
string allocation when the old string had a fragment that is being replaced.
* platform/URL.h: Updated for the above.

* replay/ReplayInputDispatchMethods.cpp:
(WebCore::InitialNavigation::dispatch): Pass reference.
* svg/SVGFEImageElement.cpp:
(WebCore::SVGFEImageElement::requestImageResource): Ditto.
* svg/SVGFontFaceUriElement.cpp:
(WebCore::SVGFontFaceUriElement::loadFont): Ditto.
* svg/SVGUseElement.cpp:
(WebCore::SVGUseElement::updateExternalDocument): Ditto.

Source/WebKit/ios:

* WebCoreSupport/WebChromeClientIOS.h: Updated runOpenPanel to take references.
Made class final and most functions private and final.
* WebCoreSupport/WebChromeClientIOS.mm:
(WebChromeClientIOS::runOpenPanel): Updated to take references.

Source/WebKit/mac:

* WebCoreSupport/WebChromeClient.h: Updated for changes to ChromeClient.
Also made class final and most functions private and final.
* WebCoreSupport/WebChromeClient.mm:
(WebChromeClient::runOpenPanel): Updated to take references.

* WebCoreSupport/WebEditorClient.h: Updated for changes to EditorClient.
* WebCoreSupport/WebEditorClient.mm:
(-[WebUndoStep initWithUndoStep:]): Take reference instead of PassRefPtr.
(+[WebUndoStep stepWithUndoStep:]): Ditto.
(-[WebUndoStep step]): Return reference instead of pointer.
(-[WebEditorUndoTarget undoEditing:]): Updated for the above.
(-[WebEditorUndoTarget redoEditing:]): Ditto.
(WebEditorClient::registerUndoOrRedoStep): Take reference instead of
PassRefPtr.
(WebEditorClient::registerUndoStep): Ditto.
(WebEditorClient::registerRedoStep): Ditto.

* WebCoreSupport/WebFrameLoaderClient.h: Updated for changes to
FrameLoaderClient, marked functions final instead of override.
* WebCoreSupport/WebFrameLoaderClient.mm:
(WebFrameLoaderClient::dispatchDecidePolicyForNewWindowAction): Take
pointer instead of PassRefPtr.
(WebFrameLoaderClient::dispatchDecidePolicyForNavigationAction): Ditto.
(makeFormFieldValuesDictionary): Take a reference.
(WebFrameLoaderClient::dispatchWillSendSubmitEvent): Take Ref&& instead
of PassRefPtr.
(WebFrameLoaderClient::dispatchWillSubmitForm): Take a reference instead
of PassRefPtr.
(WebFrameLoaderClient::actionDictionary): Take a pointer instead of PassRePtr.
(WebFrameLoaderClient::createFrame): Take a reference instead of a pointer.
(WebFrameLoaderClient::createPlugin): Ditto.
(WebFrameLoaderClient::createJavaAppletWidget): Ditto.
(WebFrameLoaderClient::createNetworkingContext): Ditto.
(WebFrameLoaderClient::didCreateQuickLookHandle): Pass a reference.

* WebCoreSupport/WebFrameNetworkingContext.h: Use Ref instead of PassRefPtr.
* WebCoreSupport/WebFrameNetworkingContext.mm: Tweak style a bit.

* WebCoreSupport/WebOpenPanelResultListener.h: Take a reference instead of
PassRefPtr. Use RefPtr for class field.
* WebCoreSupport/WebOpenPanelResultListener.mm:
(-[WebOpenPanelResultListener dealloc]): Deleted. Compiler will now do it
correctly without us declaring anything explicitly.
(-[WebOpenPanelResultListener cancel]): Get rid of hand-written deref code,
and let RefPtr do the work.
(-[WebOpenPanelResultListener chooseFilename:]): Ditto.
(-[WebOpenPanelResultListener chooseFilenames:]): Ditto.
(-[WebOpenPanelResultListener chooseFilenames:displayString:iconImage:]):
Rewrote to use a modern Objective-C for loop, reserveInitialCapacity,
and uncheckedAppend.

* WebView/WebArchive.mm:
(-[WebArchive initWithMainResource:subresources:subframeArchives:]):
Updated for changes to LegacyWebArchive.
(-[WebArchive mainResource]): Ditto.
(-[WebArchive subresources]): Ditto.
(-[WebArchive subframeArchives]): Ditto.

* WebView/WebDataSource.mm:
(-[WebDataSource _addSubframeArchives:]): Use a modern Objective-C for loop
instead of NSEnumerator.
(-[WebDataSource _fileWrapperForURL:]): Use auto.
(-[WebDataSource _documentFragmentWithArchive:]): Pass a reference.
(-[WebDataSource mainResource]): Ditto.
(-[WebDataSource subresources]): Ditto.
(-[WebDataSource subresourceForURL:]): Ditto.
(-[WebDataSource addSubresource:]): Ditto.

* WebView/WebResource.mm:
(-[WebResourcePrivate initWithCoreResource:]): Take Ref&& instead of PassRefPtr.
(-[WebResourcePrivate dealloc]): Remove explicit deref since RefPtr will now take
care of it
(-[WebResource initWithCoder:]): Pass a reference.
(-[WebResource encodeWithCoder:]): Updated since coreResource is now RefPtr.
(-[WebResource _initWithCoreResource:]): Take Ref&& instead of PassRefPtr.
(-[WebResource _coreResource]): Return reference rather than pointer.
(-[WebResource _initWithData:URL:MIMEType:textEncodingName:frameName:response:copyData:]):
Added code to handle the null case and pass a reference rather than a pointer.
* WebView/WebResourceInternal.h: Updated for the above.

Source/WebKit/win:

* Plugins/PluginView.cpp:
(WebCore::PluginView::mediaCanStart): Fix call to dispatchDidFailToStartPlugin
by calling it directly on WebFrameLoaderClient. If my theory is correct, the old
call has been broken and doing nothing since r177941, two years ago, which made
the argument types different between FrameLoaderClient and WebFrameLoaderClient,
leaving WebFrameLoaderClient::dispatchDidFailToStartPlugin as dead code.

* WebCoreSupport/WebChromeClient.cpp:
(WebChromeClient::runOpenPanel): Updated for change to ChromeClient.
* WebCoreSupport/WebChromeClient.h: Ditto.

* WebCoreSupport/WebEditorClient.cpp:
(WebEditorUndoCommand::WebEditorUndoCommand): Take a reference instead of
a PassRefPtr. Also use Ref instead of RefPtr.
(WebEditorClient::shouldChangeTypingStyle): Deleted. Empty function that was
never called.
(WebEditorClient::webViewDidChangeTypingStyle): Ditto.
(WebEditorClient::webViewDidChangeSelection): Ditto.
(WebEditorClient::registerUndoStep):  Take reference instead of PassRefPtr.
(WebEditorClient::registerRedoStep): Ditto.
* WebCoreSupport/WebEditorClient.h: Updated for the above. Also marked the
class and member functions final and made them all private, which will
help us catch if there are any that don't correctly match WebCore.

* WebCoreSupport/WebFrameLoaderClient.cpp:
(WebFrameLoaderClient::dispatchDecidePolicyForNewWindowAction): Updated
for change to ChromeClient.
(WebFrameLoaderClient::dispatchDecidePolicyForNavigationAction): Ditto.
(WebFrameLoaderClient::dispatchWillSendSubmitEvent): Ditto.
(WebFrameLoaderClient::dispatchWillSubmitForm): Ditto.
(WebFrameLoaderClient::createFrame): Ditto. Also merged two functions into
one because one was private and only called by the other.
(WebFrameLoaderClient::createPlugin): Ditto.
(WebFrameLoaderClient::createJavaAppletWidget): Ditto.
(WebFrameLoaderClient::createNetworkingContext): Ditto.
* WebCoreSupport/WebFrameLoaderClient.h: Ditto.

* WebCoreSupport/WebFrameNetworkingContext.h:
(WebFrameNetworkingContext::create): Return a Ref instead of a PassRefPtr.

Source/WebKit2:

* Shared/APIWebArchive.h: Use RefPtr&& instead of PassRefPtr.
* Shared/APIWebArchive.mm:
(API::WebArchive::create): Ditto.
(API::WebArchive::WebArchive): Ditto.
(API::WebArchive::subresources): Ditto.
(API::WebArchive::subframeArchives): Ditto.

* Shared/TextCheckerState.h: Initialize data members so classes
using this won't have to explicitly initalize them.

* UIProcess/WebIconDatabase.cpp:
(WebKit::WebIconDatabase::setIconDataForIconURL): Pass a raw
pointer to WebCore.

* UIProcess/WebPageProxy.h: Removed forward declaration of
StringPairVector, not needed here.

* WebProcess/IconDatabase/WebIconDatabaseProxy.cpp:
(WebKit::WebIconDatabaseProxy::WebIconDatabaseProxy): Take a reference.
(WebKit::WebIconDatabaseProxy::retainIconForPageURL): Updated for reference.
(WebKit::WebIconDatabaseProxy::releaseIconForPageURL): Ditto.
(WebKit::WebIconDatabaseProxy::synchronousIconForPageURL): Ditto.
(WebKit::WebIconDatabaseProxy::loadDecisionForIconURL): Ditto.
(WebKit::WebIconDatabaseProxy::receivedIconLoadDecision): Ditto.
(WebKit::WebIconDatabaseProxy::iconDataForIconURL): Ditto.
(WebKit::WebIconDatabaseProxy::setIconURLForPageURL): Ditto.
(WebKit::WebIconDatabaseProxy::setIconDataForIconURL): Ditto.
* WebProcess/IconDatabase/WebIconDatabaseProxy.h: Updated for the above.
Marked the class final, made most functions private and final.

* WebProcess/InjectedBundle/InjectedBundleNavigationAction.cpp:
(WebKit::InjectedBundleNavigationAction::InjectedBundleNavigationAction):
Removed assertion that a pointer is non-null since that pointer is now a
reference. Left use of PassRefPtr here for now.z

* WebProcess/Network/WebLoaderStrategy.cpp:
(WebKit::WebLoaderStrategy::scheduleLoad): Updated since application cache
host is now a reference rather thna a pointer.
* WebProcess/Network/WebResourceLoader.cpp:
(WebKit::WebResourceLoader::willSendRequest): Ditto.
(WebKit::WebResourceLoader::didReceiveResponse): Ditto.
(WebKit::WebResourceLoader::didFailResourceLoad): Ditto.

* WebProcess/Plugins/PluginView.cpp:
(WebKit::buildHTTPHeaders): Got rid of unneeded use of String::format.
(WebKit::PluginView::create): Take a reference instead of PassRefPtr.
(WebKit::PluginView::PluginView): Ditto. Also moved much of the data
member initialization to the class definition.
(WebKit::PluginView::recreateAndInitialize): Take Ref&& instead of PassRefPtr.
(WebKit::PluginView::manualLoadDidReceiveResponse): Updated for change to
ManualStreamState enumeration.
(WebKit::PluginView::manualLoadDidReceiveData): Ditto.
(WebKit::PluginView::manualLoadDidFinishLoading Ditto.):
(WebKit::PluginView::manualLoadDidFail): Ditto.
(WebKit::PluginView::liveResourceData): Return RefPtr insead of PassRefPtr.
(WebKit::PluginView::redeliverManualStream): Updated for ManualStreamState.
* WebProcess/Plugins/PluginView.h: Updated for the above. Also changed
ManualStreamState into an enum class.

* WebProcess/WebCoreSupport/WebChromeClient.cpp: Changed m_page to a reference.
(WebKit::WebChromeClient::runOpenPanel): Take both arguments as references.
* WebProcess/WebCoreSupport/WebChromeClient.h: Updated for the above.

* WebProcess/WebCoreSupport/WebEditorClient.cpp:
(WebKit::WebEditorClient::registerUndoStep): Take reference instead of PassRefPtr.
(WebKit::WebEditorClient::registerRedoStep): Ditto.
* WebProcess/WebCoreSupport/WebEditorClient.h: Updated for the above

* WebProcess/WebCoreSupport/WebFrameLoaderClient.cpp:
(WebKit::WebFrameLoaderClient::dispatchDecidePolicyForNewWindowAction):
Updated for change to FrameLoaderClient.
(WebKit::WebFrameLoaderClient::dispatchDecidePolicyForNavigationAction): Ditto.
(WebKit::WebFrameLoaderClient::dispatchWillSendSubmitEvent): Ditto.
(WebKit::WebFrameLoaderClient::dispatchWillSubmitForm): Ditto.
(WebKit::WebFrameLoaderClient::createFrame): Ditto.
(WebKit::WebFrameLoaderClient::createPlugin): Ditto.
(WebKit::WebFrameLoaderClient::recreatePlugin): Ditto.
(WebKit::WebFrameLoaderClient::createJavaAppletWidget): Ditto.
(WebKit::WebFrameLoaderClient::createNetworkingContext): Ditto.
(WebKit::WebFrameLoaderClient::didRequestAutocomplete): Ditto.
* WebProcess/WebCoreSupport/WebFrameLoaderClient.h: Updated for the above.

* WebProcess/WebCoreSupport/ios/WebChromeClientIOS.mm:
(WebKit::WebChromeClient::didReceiveMobileDocType): Updated since m_page is a
reference now.
(WebKit::WebChromeClient::observedContentChange): Ditto.
(WebKit::WebChromeClient::notifyRevealedSelectionByScrollingFrame): Ditto.
(WebKit::WebChromeClient::didLayout): Ditto.
(WebKit::WebChromeClient::didStartOverflowScroll): Ditto.
(WebKit::WebChromeClient::didEndOverflowScroll): Ditto.
(WebKit::WebChromeClient::hasStablePageScaleFactor): Ditto.
(WebKit::WebChromeClient::showPlaybackTargetPicker): Ditto.
(WebKit::WebChromeClient::eventThrottlingDelay): Ditto.
(WebKit::WebChromeClient::deviceOrientation): Ditto.

* WebProcess/WebPage/WebPage.cpp:
(WebKit::WebPage::WebPage): Pass reference.
(WebKit::WebPage::createPlugin): Return RefPtr instead of PassRefPtr.
(WebKit::WebPage::fromCorePage): Updated for change to WebChromeClient.
(WebKit::WebPage::setHeaderPageBanner): Take pointer instead of PassRefPtr.
(WebKit::WebPage::setFooterPageBanner): Ditto.
(WebKit::WebPage::setActiveOpenPanelResultListener): Take Ref&& instead of
PassRefPtr.
(WebKit::WebPage::currentSelectionAsRange): Return RefPtr instead of PassRefPtr.
(WebKit::WebPage::rangeFromEditingRange): Ditto.
* WebProcess/WebPage/WebPage.h: Updated for the above.

* WebProcess/WebPage/efl/WebPageEfl.cpp:
(WebKit::WebPage::cachedResponseDataForURL): Return RefPtr instead of PassRefPtr.
* WebProcess/WebPage/gtk/WebPageGtk.cpp:
(WebKit::WebPage::cachedResponseDataForURL): Ditto.
* WebProcess/WebPage/ios/WebPageIOS.mm:
(WebKit::WebPage::cachedResponseDataForURL): Ditto.
* WebProcess/WebPage/mac/WebPageMac.mm:
(WebKit::WebPage::cachedResponseDataForURL): Ditto.
(WebKit::WebPage::setTopOverhangImage): Take raw pointer instead of PassRefPtr.
(WebKit::WebPage::setBottomOverhangImage): Ditto.

* WebProcess/WebProcess.cpp:
(WebKit::WebProcess::WebProcess): Pass a reference. Move most initialization to
the class definition.
* WebProcess/WebProcess.h: Updaed for the above.

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

142 files changed:
Source/WebCore/ChangeLog
Source/WebCore/dom/Document.cpp
Source/WebCore/editing/CompositeEditCommand.cpp
Source/WebCore/editing/CompositeEditCommand.h
Source/WebCore/editing/Editor.cpp
Source/WebCore/editing/Editor.h
Source/WebCore/editing/cocoa/EditorCocoa.mm
Source/WebCore/editing/ios/EditorIOS.mm
Source/WebCore/editing/mac/EditorMac.mm
Source/WebCore/history/PageCache.cpp
Source/WebCore/html/FileInputType.cpp
Source/WebCore/html/HTMLFormControlElement.cpp
Source/WebCore/html/HTMLFormElement.cpp
Source/WebCore/html/HTMLFormElement.h
Source/WebCore/html/HTMLHtmlElement.cpp
Source/WebCore/html/HTMLLinkElement.cpp
Source/WebCore/html/HTMLMediaElement.cpp
Source/WebCore/inspector/InspectorApplicationCacheAgent.cpp
Source/WebCore/inspector/InspectorApplicationCacheAgent.h
Source/WebCore/inspector/InspectorInstrumentation.cpp
Source/WebCore/inspector/InspectorInstrumentation.h
Source/WebCore/loader/DocumentLoader.cpp
Source/WebCore/loader/DocumentLoader.h
Source/WebCore/loader/EmptyClients.cpp
Source/WebCore/loader/EmptyClients.h
Source/WebCore/loader/FormState.cpp
Source/WebCore/loader/FormState.h
Source/WebCore/loader/FormSubmission.cpp
Source/WebCore/loader/FormSubmission.h
Source/WebCore/loader/FrameLoader.cpp
Source/WebCore/loader/FrameLoaderClient.h
Source/WebCore/loader/HistoryController.cpp
Source/WebCore/loader/HistoryController.h
Source/WebCore/loader/ImageLoader.cpp
Source/WebCore/loader/NavigationScheduler.cpp
Source/WebCore/loader/NavigationScheduler.h
Source/WebCore/loader/ResourceLoader.cpp
Source/WebCore/loader/SubframeLoader.cpp
Source/WebCore/loader/SubframeLoader.h
Source/WebCore/loader/SubresourceLoader.cpp
Source/WebCore/loader/appcache/ApplicationCache.cpp
Source/WebCore/loader/appcache/ApplicationCache.h
Source/WebCore/loader/appcache/ApplicationCacheGroup.cpp
Source/WebCore/loader/appcache/ApplicationCacheGroup.h
Source/WebCore/loader/appcache/ApplicationCacheHost.cpp
Source/WebCore/loader/appcache/ApplicationCacheHost.h
Source/WebCore/loader/appcache/ApplicationCacheStorage.cpp
Source/WebCore/loader/appcache/ApplicationCacheStorage.h
Source/WebCore/loader/appcache/DOMApplicationCache.cpp
Source/WebCore/loader/appcache/DOMApplicationCache.h
Source/WebCore/loader/appcache/ManifestParser.cpp
Source/WebCore/loader/appcache/ManifestParser.h
Source/WebCore/loader/archive/Archive.cpp
Source/WebCore/loader/archive/Archive.h
Source/WebCore/loader/archive/ArchiveFactory.cpp
Source/WebCore/loader/archive/ArchiveResourceCollection.cpp
Source/WebCore/loader/archive/ArchiveResourceCollection.h
Source/WebCore/loader/archive/cf/LegacyWebArchive.cpp
Source/WebCore/loader/archive/cf/LegacyWebArchive.h
Source/WebCore/loader/archive/mhtml/MHTMLArchive.cpp
Source/WebCore/loader/archive/mhtml/MHTMLArchive.h
Source/WebCore/loader/archive/mhtml/MHTMLParser.cpp
Source/WebCore/loader/cache/CachedCSSStyleSheet.cpp
Source/WebCore/loader/cache/CachedCSSStyleSheet.h
Source/WebCore/loader/cache/CachedResourceRequest.cpp
Source/WebCore/loader/cache/CachedResourceRequest.h
Source/WebCore/loader/cocoa/DiskCacheMonitor.h [deleted file]
Source/WebCore/loader/cocoa/DiskCacheMonitorCocoa.h
Source/WebCore/loader/cocoa/DiskCacheMonitorCocoa.mm
Source/WebCore/loader/icon/IconDatabase.cpp
Source/WebCore/loader/icon/IconDatabase.h
Source/WebCore/loader/icon/IconDatabaseBase.h
Source/WebCore/loader/icon/PageURLRecord.cpp
Source/WebCore/loader/icon/PageURLRecord.h
Source/WebCore/page/Chrome.cpp
Source/WebCore/page/Chrome.h
Source/WebCore/page/ChromeClient.h
Source/WebCore/page/DOMWindow.cpp
Source/WebCore/page/EditorClient.h
Source/WebCore/page/History.cpp
Source/WebCore/page/Location.cpp
Source/WebCore/platform/URL.cpp
Source/WebCore/platform/URL.h
Source/WebCore/replay/ReplayInputDispatchMethods.cpp
Source/WebCore/svg/SVGFEImageElement.cpp
Source/WebCore/svg/SVGFontFaceUriElement.cpp
Source/WebCore/svg/SVGUseElement.cpp
Source/WebKit/ios/ChangeLog
Source/WebKit/ios/WebCoreSupport/WebChromeClientIOS.h
Source/WebKit/ios/WebCoreSupport/WebChromeClientIOS.mm
Source/WebKit/mac/ChangeLog
Source/WebKit/mac/WebCoreSupport/WebChromeClient.h
Source/WebKit/mac/WebCoreSupport/WebChromeClient.mm
Source/WebKit/mac/WebCoreSupport/WebEditorClient.h
Source/WebKit/mac/WebCoreSupport/WebEditorClient.mm
Source/WebKit/mac/WebCoreSupport/WebFrameLoaderClient.h
Source/WebKit/mac/WebCoreSupport/WebFrameLoaderClient.mm
Source/WebKit/mac/WebCoreSupport/WebFrameNetworkingContext.h
Source/WebKit/mac/WebCoreSupport/WebFrameNetworkingContext.mm
Source/WebKit/mac/WebCoreSupport/WebOpenPanelResultListener.h
Source/WebKit/mac/WebCoreSupport/WebOpenPanelResultListener.mm
Source/WebKit/mac/WebView/WebArchive.mm
Source/WebKit/mac/WebView/WebDataSource.mm
Source/WebKit/mac/WebView/WebResource.mm
Source/WebKit/mac/WebView/WebResourceInternal.h
Source/WebKit/win/ChangeLog
Source/WebKit/win/Plugins/PluginView.cpp
Source/WebKit/win/WebCoreSupport/WebChromeClient.cpp
Source/WebKit/win/WebCoreSupport/WebChromeClient.h
Source/WebKit/win/WebCoreSupport/WebEditorClient.cpp
Source/WebKit/win/WebCoreSupport/WebEditorClient.h
Source/WebKit/win/WebCoreSupport/WebFrameLoaderClient.cpp
Source/WebKit/win/WebCoreSupport/WebFrameLoaderClient.h
Source/WebKit/win/WebCoreSupport/WebFrameNetworkingContext.h
Source/WebKit2/ChangeLog
Source/WebKit2/Shared/APIWebArchive.h
Source/WebKit2/Shared/APIWebArchive.mm
Source/WebKit2/Shared/TextCheckerState.h
Source/WebKit2/UIProcess/WebIconDatabase.cpp
Source/WebKit2/UIProcess/WebPageProxy.h
Source/WebKit2/WebProcess/IconDatabase/WebIconDatabaseProxy.cpp
Source/WebKit2/WebProcess/IconDatabase/WebIconDatabaseProxy.h
Source/WebKit2/WebProcess/InjectedBundle/InjectedBundleNavigationAction.cpp
Source/WebKit2/WebProcess/Network/WebLoaderStrategy.cpp
Source/WebKit2/WebProcess/Network/WebResourceLoader.cpp
Source/WebKit2/WebProcess/Plugins/PluginView.cpp
Source/WebKit2/WebProcess/Plugins/PluginView.h
Source/WebKit2/WebProcess/WebCoreSupport/WebChromeClient.cpp
Source/WebKit2/WebProcess/WebCoreSupport/WebChromeClient.h
Source/WebKit2/WebProcess/WebCoreSupport/WebEditorClient.cpp
Source/WebKit2/WebProcess/WebCoreSupport/WebEditorClient.h
Source/WebKit2/WebProcess/WebCoreSupport/WebFrameLoaderClient.cpp
Source/WebKit2/WebProcess/WebCoreSupport/WebFrameLoaderClient.h
Source/WebKit2/WebProcess/WebCoreSupport/ios/WebChromeClientIOS.mm
Source/WebKit2/WebProcess/WebPage/WebPage.cpp
Source/WebKit2/WebProcess/WebPage/WebPage.h
Source/WebKit2/WebProcess/WebPage/efl/WebPageEfl.cpp
Source/WebKit2/WebProcess/WebPage/gtk/WebPageGtk.cpp
Source/WebKit2/WebProcess/WebPage/ios/WebPageIOS.mm
Source/WebKit2/WebProcess/WebPage/mac/WebPageMac.mm
Source/WebKit2/WebProcess/WebProcess.cpp
Source/WebKit2/WebProcess/WebProcess.h

index 232d561..28006d7 100644 (file)
@@ -1,3 +1,407 @@
+2017-01-15  Darin Adler  <darin@apple.com>
+
+        Remove PassRefPtr from "loader" directory of WebCore
+        https://bugs.webkit.org/show_bug.cgi?id=167055
+
+        Reviewed by Alex Christensen.
+
+        * dom/Document.cpp:
+        (WebCore::Document::processHttpEquiv): Pass a reference.
+        * editing/CompositeEditCommand.cpp:
+        (WebCore::EditCommandComposition::unapply): Ditto.
+        (WebCore::EditCommandComposition::reapply): Ditto.
+        (WebCore::CompositeEditCommand::ensureComposition): Return a reference.
+        (WebCore::CompositeEditCommand::applyCommandToComposite): Use a reference.
+        * editing/CompositeEditCommand.h: Updated for above changes.
+
+        * editing/Editor.cpp:
+        (WebCore::Editor::unappliedEditing): Take a reference instead of a PassRefPtr.
+        (WebCore::Editor::reappliedEditing): Ditto.
+        * editing/Editor.h: Updated for above changes. Also changed the
+        FragmentAndResources resources vector to hold Ref instead of RefPtr.
+
+        * editing/cocoa/EditorCocoa.mm:
+        (WebCore::Editor::createFragmentAndAddResources): Updated for change to
+        FragmentAndResources.
+
+        * editing/ios/EditorIOS.mm:
+        (WebCore::Editor::WebContentReader::readWebArchive): Pass a reference.
+
+        * editing/mac/EditorMac.mm:
+        (WebCore::Editor::WebContentReader::readWebArchive): Pass a reference.
+
+        * history/PageCache.cpp:
+        (WebCore::canCacheFrame): Use a reference.
+
+        * html/FileInputType.cpp:
+        (WebCore::FileInputType::handleDOMActivateEvent): Pass references.
+
+        * html/HTMLFormControlElement.cpp:
+        (WebCore::HTMLFormControlElement::formMethod): Use auto.
+
+        * html/HTMLFormElement.cpp:
+        (WebCore::HTMLFormElement::prepareForSubmission): Updated to use a return
+        values for textFieldValues intsead of an out argument with getTextFieldValues.
+        (WebCore::HTMLFormElement::textFieldValues): Renamed from getTextFieldValues
+        and changed to use a return value instead of an out argument.
+        (WebCore::HTMLFormElement::submit): Pass a reference.
+        (WebCore::HTMLFormElement::requestAutocomplete): Pass a Ref&&.
+        * html/HTMLFormElement.h: Updated for above changes.
+
+        * html/HTMLHtmlElement.cpp:
+        (WebCore::HTMLHtmlElement::insertedByParser): Use a reference.
+
+        * html/HTMLLinkElement.cpp:
+        (WebCore::HTMLLinkElement::process): Pass a reference.
+        (WebCore::HTMLLinkElement::setCSSStyleSheet): Use auto.
+
+        * html/HTMLMediaElement.cpp:
+        (WebCore::HTMLMediaElement::loadResource): Use a reference.
+
+        * inspector/InspectorApplicationCacheAgent.cpp:
+        (WebCore::InspectorApplicationCacheAgent::updateApplicationCacheStatus): Use a reference,
+        also update for struct-style member names withou m_ prefix.
+        (WebCore::InspectorApplicationCacheAgent::getFramesWithManifests): Ditto.
+        (WebCore::InspectorApplicationCacheAgent::getManifestForFrame): Ditto.
+        (WebCore::InspectorApplicationCacheAgent::getApplicationCacheForFrame): Ditto.
+        (WebCore::InspectorApplicationCacheAgent::buildObjectForApplicationCache): Ditto.
+        (WebCore::InspectorApplicationCacheAgent::buildArrayForApplicationCacheResources): Ditto.
+        (WebCore::InspectorApplicationCacheAgent::buildObjectForApplicationCacheResource): Ditto.
+        * inspector/InspectorApplicationCacheAgent.h: Updated for above changes.
+
+        * inspector/InspectorInstrumentation.cpp:
+        (WebCore::InspectorInstrumentation::updateApplicationCacheStatusImpl): Take a reference.
+        * inspector/InspectorInstrumentation.h: Updated for the above.
+
+        * loader/DocumentLoader.cpp:
+        (WebCore::DocumentLoader::DocumentLoader): Move much initialization to class definition.
+        (WebCore::DocumentLoader::originalRequest): Moved to header to make it inline.
+        (WebCore::DocumentLoader::originalRequestCopy): Ditto.
+        (WebCore::DocumentLoader::request): Ditto.
+        (WebCore::DocumentLoader::url): Ditto.
+        (WebCore::DocumentLoader::stopLoading): Pass a reference.
+        (WebCore::DocumentLoader::willSendRequest): Updated to take a raw pointer instead of a
+        PassRefPtr.
+        (WebCore::DocumentLoader::commitData): Call shouldUseMainResourceEncoding instead of
+        special casing WebArchive.
+        (WebCore::DocumentLoader::maybeCreateArchive): Pass references.
+        (WebCore::DocumentLoader::setArchive): Take Ref&& instead of PassRefPtr.
+        (WebCore::DocumentLoader::addAllArchiveResources): Take a reference instead
+        of a pointer.
+        (WebCore::DocumentLoader::popArchiveForSubframe): Return RefPtr instead of
+        PassRefPtr.
+        (WebCore::DocumentLoader::subresource): Ditto.
+        (WebCore::DocumentLoader::subresources): Return a Vector<Ref> instead of a
+        Vector<RefPtr>.
+        (WebCore::DocumentLoader::substituteResourceDeliveryTimerFired): Use move
+        instead of swap.
+        (WebCore::DocumentLoader::scheduleArchiveLoad): Use shouldLoadFromArchiveOnly
+        instead of a special case for each type of archive.
+        (WebCore::DocumentLoader::originalURL): Moved to header to make it inline.
+        (WebCore::DocumentLoader::responseURL): Ditto.
+        (WebCore::DocumentLoader::documentURL): Call shouldUseMainResourceURL instead of
+        special casing WebArchive.
+        (WebCore::DocumentLoader::responseMIMEType): Moved to header to make it inline.
+        (WebCore::DocumentLoader::currentContentType): Ditto.
+        (WebCore::DocumentLoader::contentFilter): Ditto.
+        (WebCore::DocumentLoader::getIconLoadDecisionForIconURL): Pass a reference.
+        (WebCore::DocumentLoader::getIconDataForIconURL): Ditto.
+        (WebCore::DocumentLoader::dispatchOnloadEvents): Use a reference.
+        (WebCore::DocumentLoader::unreachableURL): Moved to header to make it inline.
+        * loader/DocumentLoader.h: Updated for the above.
+
+        * loader/EmptyClients.cpp: Updated for changes to client interfaces.
+        * loader/EmptyClients.h: Ditto.
+
+        * loader/FormState.cpp:
+        (WebCore::FormState::FormState): Take references instead of PassRefPtr, also
+        take Vector&& instead of Vector& when we want to take ownership and use move
+        instead of swap to do that.
+        (WebCore::FormState::create): Ditto.
+        * loader/FormState.h: Updated for the above. Also changed return values to be
+        references instead of pointers and members to be Ref instead of RefPtr.
+
+        * loader/FormSubmission.cpp:
+        (WebCore::FormSubmission::Attributes::parseMethodType): Updated for change
+        to the Method enumeration.
+        (WebCore::FormSubmission::Attributes::copyFrom): Deleted.
+        (WebCore::FormSubmission::FormSubmission): Use Ref&& instead of PassRefPtr.
+        (WebCore::FormSubmission::create): Use reference instead of pointer and
+        raw pointer instead of PassRefPtr. Also copy attributes using copy constructor
+        instead of an explicit copyFrom function.
+        (WebCore::FormSubmission::requestURL): Updated for change to the Method
+        enumeration.
+        (WebCore::FormSubmission::populateFrameLoadRequest): Ditto.
+        * loader/FormSubmission.h: Updated for the above changes. Made the Attributes
+        class copyable, since we copy it. Changed some functions to return references
+        instead of pointers and use Ref instead of RefPtr for data members.
+
+        * loader/FrameLoader.cpp:
+        (WebCore::FrameLoader::submitForm): Updated for changes to FormSubmission
+        and FormState.
+        (WebCore::FrameLoader::receivedFirstData): Ditto.
+        (WebCore::FrameLoader::loadFrameRequest): Ditto.
+        (WebCore::FrameLoader::loadResourceSynchronously): Ditto.
+        (WebCore::FrameLoader::continueLoadAfterNavigationPolicy): Ditto.
+
+        * loader/FrameLoaderClient.h: Use references, pointers, RefPtr, and Ref
+        instead of PassRefPtr. Removed unused empty dispatchDidFailToStartPlugin.
+
+        * loader/HistoryController.cpp:
+        (WebCore::HistoryController::pushState): Take RefPtr&& instead of PassRefPtr.
+        (WebCore::HistoryController::replaceState): Ditto.
+        * loader/HistoryController.h: Updated for the above.
+
+        * loader/ImageLoader.cpp:
+        (WebCore::ImageLoader::updateFromElement): Pass a reference.
+
+        * loader/NavigationScheduler.cpp: Use refernces and Ref&& instead of
+        pointers and PassRefPtr.
+        (WebCore::ScheduledNavigation::ScheduledNavigation): Added an overload
+        that sests m_shouldOpenExternalURLsPolicy.
+        * loader/NavigationScheduler.h: Updated for the above.
+
+        * loader/ResourceLoader.cpp:
+        (WebCore::ResourceLoader::start): Use and pass references.
+        (WebCore::ResourceLoader::willSendRequest): Ditto.
+        (WebCore::ResourceLoader::didReceiveResponse): Ditto.
+        (WebCore::ResourceLoader::didFail): Ditto.
+
+        * loader/SubframeLoader.cpp:
+        (WebCore::SubframeLoader::createJavaAppletWidget): Return RefPtr instead
+        of PassRefPtr. Pass references instead of pointers.
+        (WebCore::SubframeLoader::loadOrRedirectSubframe): Ditto.
+        (WebCore::SubframeLoader::loadSubframe): Ditto.
+        (WebCore::SubframeLoader::document): Deleted. This was never really the
+        correct idiom for getting the appropriate document; hiding the dependency
+        on m_frame wasn't paing off.
+        (WebCore::SubframeLoader::loadPlugin): Pass reference instead of pointer.
+        (WebCore::SubframeLoader::shouldConvertInvalidURLsToBlank): Eliminated
+        unneeded null checking and complexity due to going through the document
+        instead of the frame for this check.
+        * loader/SubframeLoader.h: Updated for the above.
+
+        * loader/appcache/ApplicationCache.cpp:
+        (WebCore::ApplicationCache::ApplicationCache): Moved data member
+        initialization to the class definition.
+        (WebCore::ApplicationCache::~ApplicationCache): Pass a reference instead
+        of a pointer.
+        (WebCore::ApplicationCache::isComplete): Ditto.
+        (WebCore::ApplicationCache::setManifestResource): Take Ref&& instead of
+        PassRefPtr.
+        (WebCore::ApplicationCache::addResource): Ditto.
+        (WebCore::ApplicationCache::removeResource): Deleted. Was unused.
+        * loader/appcache/ApplicationCache.h: Updated for above changes.
+
+        * loader/appcache/ApplicationCacheGroup.cpp:
+        (WebCore::ApplicationCacheGroup::ApplicationCacheGroup): Moved most
+        member initialization to the class definition.
+        (WebCore::ApplicationCacheGroup::~ApplicationCacheGroup): Pass a reference.
+        (WebCore::ApplicationCacheGroup::cacheForMainRequest): Removed
+        unnecessary preflight for removeFragmentIdentifier, which efficiently
+        does nothing if there is no identifier. Use early return.
+        (WebCore::ApplicationCacheGroup::fallbackCacheForMainRequest): More of
+        the same.
+        (WebCore::ApplicationCacheGroup::selectCache): Ditto, also take a reference,
+        and use event names instead of a special enumeration to poast events.
+        (WebCore::ApplicationCacheGroup::selectCacheWithoutManifestURL): Ditto.
+        (WebCore::ApplicationCacheGroup::finishedLoadingMainResource): Ditto.
+        (WebCore::ApplicationCacheGroup::failedLoadingMainResource): Ditto.
+        (WebCore::ApplicationCacheGroup::disassociateDocumentLoader): Ditto.
+        (WebCore::ApplicationCacheGroup::cacheDestroyed): Ditto.
+        (WebCore::ApplicationCacheGroup::stopLoadingInFrame): Ditto.
+        (WebCore::ApplicationCacheGroup::setNewestCache): Use Ref&& instead of
+        PassRefPtr.
+        (WebCore::ApplicationCacheGroup::makeObsolete): More of the same.
+        (WebCore::ApplicationCacheGroup::update): Ditto.
+        (WebCore::ApplicationCacheGroup::abort): Ditto.
+        (WebCore::ApplicationCacheGroup::didReceiveResponse): Ditto.
+        (WebCore::ApplicationCacheGroup::didFinishLoading): Ditto.
+        (WebCore::ApplicationCacheGroup::didFail): Ditto.
+        (WebCore::ApplicationCacheGroup::didFinishLoadingManifest): Ditto.
+        (WebCore::ApplicationCacheGroup::manifestNotFound): Ditto.
+        (WebCore::ApplicationCacheGroup::checkIfLoadIsComplete): Ditto.
+        (WebCore::ApplicationCacheGroup::startLoadingEntry): Ditto.
+        (WebCore::ApplicationCacheGroup::deliverDelayedMainResources): Use a modern
+        for loop.
+        (WebCore::ApplicationCacheGroup::addEntry): Use auto and simplify logic
+        for adding.
+        (WebCore::ApplicationCacheGroup::associateDocumentLoaderWithCache): Update since
+        function result is a reference.
+        (WebCore::ApplicationCacheGroup::scheduleReachedMaxAppCacheSizeCallback):
+        Use auto.
+        (WebCore::ApplicationCacheGroup::postListenerTask): Take event type instead of
+        taking a special enumeration.
+        * loader/appcache/ApplicationCacheGroup.h: Updated for the above.
+
+        * loader/appcache/ApplicationCacheHost.cpp:
+        (WebCore::ApplicationCacheHost::ApplicationCacheHost): Move most member
+        initialization to the class definition.
+        (WebCore::ApplicationCacheHost::~ApplicationCacheHost): Use reference.
+        (WebCore::ApplicationCacheHost::selectCacheWithoutManifest): Ditto.
+        (WebCore::ApplicationCacheHost::selectCacheWithManifest): Ditto.
+        (WebCore::ApplicationCacheHost::mainResourceDataReceived): Ditto.
+        (WebCore::ApplicationCacheHost::failedLoadingMainResource): Ditto.
+        (WebCore::ApplicationCacheHost::finishedLoadingMainResource): Ditto.
+        (WebCore::ApplicationCacheHost::maybeLoadFallbackForRedirect): Ditto.
+        (WebCore::ApplicationCacheHost::maybeLoadFallbackForResponse): Ditto.
+        (WebCore::ApplicationCacheHost::createFileURL): Ditto.
+        (WebCore::ApplicationCacheHost::maybeLoadSynchronously): Ditto.
+        (WebCore::ApplicationCacheHost::notifyDOMApplicationCache): Take event
+        type instead of special enumeration.
+        (WebCore::ApplicationCacheHost::stopLoadingInFrame): Use reference.
+        (WebCore::ApplicationCacheHost::stopDeferringEvents): Updated to use
+        event types instead of special enumeration and also repaired possible
+        edge case where code in event handler somehow triggers additional events.
+        (WebCore::ApplicationCacheHost::resourceList): Renamed from fillResourceList
+        and changed to return a vector instead of populating one.
+        (WebCore::ApplicationCacheHost::applicationCacheInfo): Tweak coding style a bit.
+        (WebCore::createApplicationCacheEvent): Factored this helper out of
+        dispatchDOMEvent so we can use Ref instead of RefPtr.
+        (WebCore::ApplicationCacheHost::dispatchDOMEvent): Updated to recent event type
+        rather than receiving an event id and mapping it to a type.
+        (WebCore::ApplicationCacheHost::setApplicationCache): Take RefPtr&& instead of
+        PassRefPtr.
+        (WebCore::ApplicationCacheHost::update): Pass a reference.
+        (WebCore::ApplicationCacheHost::swapCache): Ditto.
+        (WebCore::ApplicationCacheHost::abort): Ditto.
+        * loader/appcache/ApplicationCacheHost.h: Updated for the above.
+
+        * loader/appcache/ApplicationCacheStorage.cpp:
+        (WebCore::ApplicationCacheStorage::loadCacheGroup): Pass a Ref instead of RefPtr.
+        (WebCore::ApplicationCacheStorage::cacheGroupForURL): Ditto.
+        (WebCore::ApplicationCacheStorage::fallbackCacheGroupForURL): Ditto.
+        (WebCore::ApplicationCacheStorage::cacheGroupDestroyed): Take a reference.
+        (WebCore::ApplicationCacheStorage::cacheGroupMadeObsolete): Ditto.
+        (WebCore::ApplicationCacheStorage::storeNewestCache): Ditto.
+        (WebCore::ApplicationCacheStorage::loadCache): Return RefPtr instead of PassRefPtr.
+        (WebCore::ApplicationCacheStorage::deleteCacheGroup): Pass a reference.
+        * loader/appcache/ApplicationCacheStorage.h: Updated for the above.
+
+        * loader/appcache/DOMApplicationCache.cpp:
+        (WebCore::DOMApplicationCache::DOMApplicationCache): Take a reference.
+        (WebCore::DOMApplicationCache::toEventType): Deleted.
+        * loader/appcache/DOMApplicationCache.h: Updated for the above. Made most
+        members private.
+
+        * loader/archive/Archive.cpp:
+        (WebCore::Archive::clearAllSubframeArchives): Use a set for the logic that
+        prevents us from walking the same archive more than once, rather than using
+        a vector. Left it recursive, though.
+        * loader/archive/Archive.h: Git rid of the type function, replacing it with
+        three functions for the four different policies we currently have about the
+        different archive types. Changed functions to take Ref&& instead of PassRefPtr
+        and return const Vector<Ref>& instead of const Vector<RefPtr>&, changing the
+        data members to match.
+
+        * loader/archive/ArchiveFactory.cpp:
+        (WebCore::createArchiveMIMETypesMap): Factored this out of the archiveMIMETypes
+        function so we don't need a boolean. Also use ASCIILiteral.
+        (WebCore::archiveMIMETypes): Updated to se the above.
+
+        * loader/archive/ArchiveResourceCollection.cpp:
+        (WebCore::ArchiveResourceCollection::addAllResources): Take a reference.
+        (WebCore::ArchiveResourceCollection::popSubframeArchive): Return RefPtr instead
+        of PassRefPtr.
+        * loader/archive/ArchiveResourceCollection.h: Updated for the above.
+
+        * loader/archive/cf/LegacyWebArchive.cpp:
+        (WebCore::LegacyWebArchive::createPropertyListRepresentation): Use auto and
+        fewer local variables, more references for argument types and return values.
+        (WebCore::LegacyWebArchive::createResourceResponseFromPropertyListData): Ditto.
+        (WebCore::LegacyWebArchive::createResource): Ditto.
+        (WebCore::LegacyWebArchive::create): Ditto.
+        (WebCore::LegacyWebArchive::extract): Ditto.
+        (WebCore::LegacyWebArchive::type): Deleted.
+        (WebCore::LegacyWebArchive::rawDataRepresentation): More of the same.
+        (WebCore::LegacyWebArchive::createFromSelection): Ditto.
+        * loader/archive/cf/LegacyWebArchive.h: Updated for the above. Also marked the
+        class final and added overrides for the four new policy member functions.
+
+        * loader/archive/mhtml/MHTMLArchive.cpp:
+        (WebCore::MHTMLArchive::create): Pass references.
+        (WebCore::MHTMLArchive::generateMHTMLData): Return RefPtr instead of
+        PassRefPtr.
+        * loader/archive/mhtml/MHTMLArchive.h: Updated for the above. Also marked the
+        class final and added overrides for the four new policy member functions.
+
+        * loader/archive/mhtml/MHTMLParser.cpp:
+        (WebCore::MHTMLParser::parseArchiveWithHeader): Pass Ref instead of RefPtr
+        to setMainResource and addSubframeArchive.
+        (WebCore::MHTMLParser::addResourceToArchive): Ditto.
+
+        * loader/cache/CachedCSSStyleSheet.cpp:
+        (WebCore::CachedCSSStyleSheet::restoreParsedStyleSheet): Return RefPtr instead
+        of PassRefPtr.
+        * loader/cache/CachedCSSStyleSheet.h: Updated for the above.
+
+        * loader/cache/CachedResourceRequest.cpp:
+        (WebCore::CachedResourceRequest::setInitiator): Take a reference instead of a
+        PassRefPtr.
+        * loader/cache/CachedResourceRequest.h: Updated for the above.
+
+        * loader/cocoa/DiskCacheMonitor.h: Removed. This is a duplicate, unused copy
+        of DiskCacheMonitorCocoa.h.
+
+        * loader/cocoa/DiskCacheMonitorCocoa.h: Removed unneeded exporting and virtual
+        member functions, made more things private, and changed return type to RefPtr
+        instead of PassRefPtr.
+        * loader/cocoa/DiskCacheMonitorCocoa.mm:
+        (WebCore::DiskCacheMonitor::tryGetFileBackedSharedBufferFromCFURLCachedResponse):
+        Changed return type to RefPtr instead of PassRefPtr.
+
+        * loader/icon/IconDatabase.cpp:
+        (WebCore::IconDatabase::setIconDataForIconURL): Take raw pointer instead of
+        PassRefPtr.
+        (WebCore::IconDatabase::getOrCreateIconRecord): Return Ref instead of PassRefPtr.
+        (WebCore::IconDatabase::getImageDataForIconURLFromSQLDatabase): Return RefPtr
+        instead of PassRefPtr.
+        * loader/icon/IconDatabase.h: Updated for the above. Also marked functions final
+        instead of override.
+        * loader/icon/IconDatabaseBase.h: Ditto.
+
+        * loader/icon/PageURLRecord.cpp:
+        (WebCore::PageURLRecord::PageURLRecord): Moved initialization to the header.
+        (WebCore::PageURLRecord::~PageURLRecord): Wrote code here instead of calling
+        setIconRecord(nullptr).
+        (WebCore::PageURLRecord::setIconRecord): Take RefPtr&& instead of PassRefPtr.
+        * loader/icon/PageURLRecord.h: Updatd for the above.
+
+        * page/Chrome.cpp:
+        (WebCore::Chrome::runOpenPanel): Updated to take two references.
+        * page/Chrome.h: Ditto.
+        * page/ChromeClient.h: ditto.
+
+        * page/DOMWindow.cpp:
+        (WebCore::DOMWindow::applicationCache): Pass a reference.
+        (WebCore::DOMWindow::setLocation): Ditto.
+        (WebCore::DOMWindow::createWindow): Ditto.
+        (WebCore::DOMWindow::open): Ditto.
+
+        * page/EditorClient.h: Changed arguments to references instead of PassRefPtr.
+
+        * page/History.cpp:
+        (WebCore::History::stateObjectAdded): Pass an rvalue reference.
+
+        * page/Location.cpp:
+        (WebCore::Location::reload): Pass reference instead of pointer.
+        (WebCore::Location::setLocation): Ditto.
+
+        * platform/URL.cpp:
+        (WebCore::URL::setFragmentIdentifier): Take a StringView rather than
+        a String, which is more flexible for callers. Also eliminated an unneeded
+        string allocation when the old string had a fragment that is being replaced.
+        * platform/URL.h: Updated for the above.
+
+        * replay/ReplayInputDispatchMethods.cpp:
+        (WebCore::InitialNavigation::dispatch): Pass reference.
+        * svg/SVGFEImageElement.cpp:
+        (WebCore::SVGFEImageElement::requestImageResource): Ditto.
+        * svg/SVGFontFaceUriElement.cpp:
+        (WebCore::SVGFontFaceUriElement::loadFont): Ditto.
+        * svg/SVGUseElement.cpp:
+        (WebCore::SVGUseElement::updateExternalDocument): Ditto.
+
 2017-01-16  Filip Pizlo  <fpizlo@apple.com>
 
         Make opaque root scanning truly constraint-based
index 3fc65b5..5e8edbe 100644 (file)
@@ -3136,7 +3136,7 @@ void Document::processHttpEquiv(const String& equiv, const String& content, bool
             else
                 completedURL = completeURL(urlString);
             if (!protocolIsJavaScript(completedURL))
-                frame->navigationScheduler().scheduleRedirect(this, delay, completedURL);
+                frame->navigationScheduler().scheduleRedirect(*this, delay, completedURL);
             else {
                 String message = "Refused to refresh " + m_url.stringCenterEllipsizedToLength() + " to a javascript: URL";
                 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
index cce9caa..f7fd484 100644 (file)
@@ -239,7 +239,7 @@ void EditCommandComposition::unapply()
     for (size_t i = size; i; --i)
         m_commands[i - 1]->doUnapply();
 
-    frame->editor().unappliedEditing(this);
+    frame->editor().unappliedEditing(*this);
 
     if (AXObjectCache::accessibilityEnabled())
         m_replacedText.postTextStateChangeNotificationForUnapply(m_document->existingAXObjectCache());
@@ -265,7 +265,7 @@ void EditCommandComposition::reapply()
     for (auto& command : m_commands)
         command->doReapply();
 
-    frame->editor().reappliedEditing(this);
+    frame->editor().reappliedEditing(*this);
 
     if (AXObjectCache::accessibilityEnabled())
         m_replacedText.postTextStateChangeNotificationForReapply(m_document->existingAXObjectCache());
@@ -416,14 +416,14 @@ EditCommandComposition* CompositeEditCommand::composition() const
     return nullptr;
 }
 
-EditCommandComposition* CompositeEditCommand::ensureComposition()
+EditCommandComposition& CompositeEditCommand::ensureComposition()
 {
-    CompositeEditCommand* command = this;
-    while (command && command->parent())
-        command = command->parent();
+    auto* command = this;
+    while (auto* parent = command->parent())
+        command = parent;
     if (!command->m_composition)
         command->m_composition = EditCommandComposition::create(document(), startingSelection(), endingSelection(), editingAction());
-    return command->m_composition.get();
+    return *command->m_composition;
 }
 
 bool CompositeEditCommand::isCreateLinkCommand() const
@@ -465,7 +465,7 @@ void CompositeEditCommand::applyCommandToComposite(PassRefPtr<EditCommand> prpCo
     command->doApply();
     if (command->isSimpleEditCommand()) {
         command->setParent(nullptr);
-        ensureComposition()->append(toSimpleEditCommand(command.get()));
+        ensureComposition().append(toSimpleEditCommand(command.get()));
     }
     m_commands.append(WTFMove(command));
 }
index 85f418f..0221dc9 100644 (file)
@@ -105,7 +105,7 @@ public:
     void apply();
     bool isFirstCommand(EditCommand* command) { return !m_commands.isEmpty() && m_commands.first() == command; }
     EditCommandComposition* composition() const;
-    EditCommandComposition* ensureComposition();
+    EditCommandComposition& ensureComposition();
 
     virtual bool isCreateLinkCommand() const;
     virtual bool isTypingCommand() const;
index 08e5391..fac6e65 100644 (file)
@@ -996,23 +996,23 @@ bool Editor::willUnapplyEditing(const EditCommandComposition& composition) const
     return dispatchBeforeInputEvents(composition.startingRootEditableElement(), composition.endingRootEditableElement(), "historyUndo");
 }
 
-void Editor::unappliedEditing(PassRefPtr<EditCommandComposition> cmd)
+void Editor::unappliedEditing(EditCommandComposition& composition)
 {
     document().updateLayout();
 
-    notifyTextFromControls(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
+    notifyTextFromControls(composition.startingRootEditableElement(), composition.endingRootEditableElement());
 
-    VisibleSelection newSelection(cmd->startingSelection());
+    VisibleSelection newSelection(composition.startingSelection());
     changeSelectionAfterCommand(newSelection, FrameSelection::defaultSetSelectionOptions());
-    dispatchInputEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement(), "historyUndo");
+    dispatchInputEvents(composition.startingRootEditableElement(), composition.endingRootEditableElement(), "historyUndo");
 
     updateEditorUINowIfScheduled();
 
-    m_alternativeTextController->respondToUnappliedEditing(cmd.get());
+    m_alternativeTextController->respondToUnappliedEditing(&composition);
 
     m_lastEditCommand = nullptr;
-    if (client())
-        client()->registerRedoStep(cmd);
+    if (auto* client = this->client())
+        client->registerRedoStep(composition);
     respondToChangedContents(newSelection);
 }
 
@@ -1021,21 +1021,21 @@ bool Editor::willReapplyEditing(const EditCommandComposition& composition) const
     return dispatchBeforeInputEvents(composition.startingRootEditableElement(), composition.endingRootEditableElement(), "historyRedo");
 }
 
-void Editor::reappliedEditing(PassRefPtr<EditCommandComposition> cmd)
+void Editor::reappliedEditing(EditCommandComposition& composition)
 {
     document().updateLayout();
 
-    notifyTextFromControls(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
+    notifyTextFromControls(composition.startingRootEditableElement(), composition.endingRootEditableElement());
 
-    VisibleSelection newSelection(cmd->endingSelection());
+    VisibleSelection newSelection(composition.endingSelection());
     changeSelectionAfterCommand(newSelection, FrameSelection::defaultSetSelectionOptions());
-    dispatchInputEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement(), "historyRedo");
+    dispatchInputEvents(composition.startingRootEditableElement(), composition.endingRootEditableElement(), "historyRedo");
     
     updateEditorUINowIfScheduled();
 
     m_lastEditCommand = nullptr;
-    if (client())
-        client()->registerUndoStep(cmd);
+    if (auto* client = this->client())
+        client->registerUndoStep(composition);
     respondToChangedContents(newSelection);
 }
 
index 2800c30..b8eaad0 100644 (file)
@@ -99,10 +99,12 @@ enum class MailBlockquoteHandling {
 };
 
 #if PLATFORM(COCOA)
+
 struct FragmentAndResources {
     RefPtr<DocumentFragment> fragment;
-    Vector<RefPtr<ArchiveResource>> resources;
+    Vector<Ref<ArchiveResource>> resources;
 };
+
 #endif
 
 class Editor {
@@ -206,8 +208,8 @@ public:
     bool willReapplyEditing(const EditCommandComposition&) const;
 
     void appliedEditing(PassRefPtr<CompositeEditCommand>);
-    void unappliedEditing(PassRefPtr<EditCommandComposition>);
-    void reappliedEditing(PassRefPtr<EditCommandComposition>);
+    void unappliedEditing(EditCommandComposition&);
+    void reappliedEditing(EditCommandComposition&);
     void unappliedSpellCorrection(const VisibleSelection& selectionOfCorrected, const String& corrected, const String& correction);
 
     // This is off by default, since most editors want this behavior (originally matched IE but not Firefox).
index 495e1f8..4754e77 100644 (file)
@@ -285,11 +285,9 @@ RefPtr<DocumentFragment> Editor::createFragmentAndAddResources(NSAttributedStrin
 
     auto fragmentAndResources = createFragment(string);
 
-    if (DocumentLoader* loader = m_frame.loader().documentLoader()) {
-        for (auto& resource : fragmentAndResources.resources) {
-            if (resource)
-                loader->addArchiveResource(resource.releaseNonNull());
-        }
+    if (auto* loader = m_frame.loader().documentLoader()) {
+        for (auto& resource : fragmentAndResources.resources)
+            loader->addArchiveResource(WTFMove(resource));
     }
 
     if (wasImagesEnabled)
index c7ef65b..faf44eb 100644 (file)
@@ -262,27 +262,25 @@ bool Editor::WebContentReader::readWebArchive(SharedBuffer* buffer)
     if (!buffer)
         return false;
 
-    RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(URL(), *buffer);
+    auto archive = LegacyWebArchive::create(URL(), *buffer);
     if (!archive)
         return false;
 
-    RefPtr<ArchiveResource> mainResource = archive->mainResource();
+    auto* mainResource = archive->mainResource();
     if (!mainResource)
         return false;
 
-    const String& type = mainResource->mimeType();
-
-    if (frame.loader().client().canShowMIMETypeAsHTML(type)) {
-        // FIXME: The code in createFragmentAndAddResources calls setDefersLoading(true). Don't we need that here?
-        if (DocumentLoader* loader = frame.loader().documentLoader())
-            loader->addAllArchiveResources(archive.get());
+    auto& type = mainResource->mimeType();
+    if (!frame.loader().client().canShowMIMETypeAsHTML(type))
+        return false;
 
-        String markupString = String::fromUTF8(mainResource->data().data(), mainResource->data().size());
-        addFragment(createFragmentFromMarkup(*frame.document(), markupString, mainResource->url(), DisallowScriptingAndPluginContent));
-        return true;
-    }
+    // FIXME: The code in createFragmentAndAddResources calls setDefersLoading(true). Don't we need that here?
+    if (auto* loader = frame.loader().documentLoader())
+        loader->addAllArchiveResources(*archive);
 
-    return false;
+    auto markupString = String::fromUTF8(mainResource->data().data(), mainResource->data().size());
+    addFragment(createFragmentFromMarkup(*frame.document(), markupString, mainResource->url(), DisallowScriptingAndPluginContent));
+    return true;
 }
 
 bool Editor::WebContentReader::readFilenames(const Vector<String>&)
index 74dcc24..edbc055 100644 (file)
@@ -328,7 +328,7 @@ bool Editor::WebContentReader::readWebArchive(SharedBuffer* buffer)
     if (!buffer)
         return false;
 
-    RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(URL(), *buffer);
+    auto archive = LegacyWebArchive::create(URL(), *buffer);
     if (!archive)
         return false;
 
@@ -341,7 +341,7 @@ bool Editor::WebContentReader::readWebArchive(SharedBuffer* buffer)
     if (frame.loader().client().canShowMIMETypeAsHTML(type)) {
         // FIXME: The code in createFragmentAndAddResources calls setDefersLoading(true). Don't we need that here?
         if (DocumentLoader* loader = frame.loader().documentLoader())
-            loader->addAllArchiveResources(archive.get());
+            loader->addAllArchiveResources(*archive);
 
         String markupString = String::fromUTF8(mainResource->data().data(), mainResource->data().size());
         fragment = createFragmentFromMarkup(*frame.document(), markupString, mainResource->url(), DisallowScriptingAndPluginContent);
index 27394c6..3ca6b07 100644 (file)
@@ -162,7 +162,7 @@ static bool canCacheFrame(Frame& frame, DiagnosticLoggingClient& diagnosticLoggi
     }
     // FIXME: We should investigating caching frames that have an associated
     // application cache. <rdar://problem/5917899> tracks that work.
-    if (!documentLoader->applicationCacheHost()->canCacheInPageCache()) {
+    if (!documentLoader->applicationCacheHost().canCacheInPageCache()) {
         PCLOG("   -The DocumentLoader uses an application cache");
         logPageCacheFailureDiagnosticMessage(diagnosticLoggingClient, DiagnosticLoggingKeys::applicationCacheKey());
         isCacheable = false;
index 57d0dc1..28b6c06 100644 (file)
@@ -191,7 +191,7 @@ void FileInputType::handleDOMActivateEvent(Event& event)
     if (!ScriptController::processingUserGesture())
         return;
 
-    if (Chrome* chrome = this->chrome()) {
+    if (auto* chrome = this->chrome()) {
         FileChooserSettings settings;
         HTMLInputElement& input = element();
         settings.allowsMultipleFiles = input.hasAttributeWithoutSynchronization(multipleAttr);
@@ -201,9 +201,8 @@ void FileInputType::handleDOMActivateEvent(Event& event)
 #if ENABLE(MEDIA_CAPTURE)
         settings.mediaCaptureType = input.mediaCaptureType();
 #endif
-
         applyFileChooserSettings(settings);
-        chrome->runOpenPanel(input.document().frame(), m_fileChooser);
+        chrome->runOpenPanel(*input.document().frame(), *m_fileChooser);
     }
 
     event.setDefaultHandled();
index 2e872aa..ea8a3b3 100644 (file)
@@ -89,7 +89,7 @@ void HTMLFormControlElement::setFormEnctype(const String& value)
 
 String HTMLFormControlElement::formMethod() const
 {
-    const AtomicString& formMethodAttr = attributeWithoutSynchronization(formmethodAttr);
+    auto& formMethodAttr = attributeWithoutSynchronization(formmethodAttr);
     if (formMethodAttr.isNull())
         return emptyString();
     return FormSubmission::Attributes::methodString(FormSubmission::Attributes::parseMethodType(formMethodAttr));
index 7475f64..640e33e 100644 (file)
@@ -289,12 +289,11 @@ void HTMLFormElement::prepareForSubmission(Event& event)
         return;
     }
 
-    StringPairVector controlNamesAndValues;
-    getTextFieldValues(controlNamesAndValues);
-    auto formState = FormState::create(this, controlNamesAndValues, &document(), NotSubmittedByJavaScript);
+    auto formState = FormState::create(*this, textFieldValues(), document(), NotSubmittedByJavaScript);
     frame->loader().client().dispatchWillSendSubmitEvent(WTFMove(formState));
 
     Ref<HTMLFormElement> protectedThis(*this);
+
     // Event handling can result in m_shouldSubmit becoming true, regardless of dispatchEvent() return value.
     if (dispatchEvent(Event::create(eventNames().submitEvent, true, true)))
         m_shouldSubmit = true;
@@ -315,20 +314,20 @@ void HTMLFormElement::submitFromJavaScript()
     submit(0, false, ScriptController::processingUserGesture(), SubmittedByJavaScript);
 }
 
-void HTMLFormElement::getTextFieldValues(StringPairVector& fieldNamesAndValues) const
+StringPairVector HTMLFormElement::textFieldValues() const
 {
-    ASSERT_ARG(fieldNamesAndValues, fieldNamesAndValues.isEmpty());
-
-    fieldNamesAndValues.reserveCapacity(m_associatedElements.size());
+    StringPairVector result;
+    result.reserveInitialCapacity(m_associatedElements.size());
     for (auto& associatedElement : m_associatedElements) {
-        HTMLElement& element = associatedElement->asHTMLElement();
+        auto& element = associatedElement->asHTMLElement();
         if (!is<HTMLInputElement>(element))
             continue;
-        HTMLInputElement& input = downcast<HTMLInputElement>(element);
+        auto& input = downcast<HTMLInputElement>(element);
         if (!input.isTextField())
             continue;
-        fieldNamesAndValues.append(std::make_pair(input.name().string(), input.value()));
+        result.uncheckedAppend({ input.name().string(), input.value() });
     }
+    return result;
 }
 
 void HTMLFormElement::submit(Event* event, bool activateSubmitButton, bool processingUserGesture, FormSubmissionTrigger formSubmissionTrigger)
@@ -364,9 +363,10 @@ void HTMLFormElement::submit(Event* event, bool activateSubmitButton, bool proce
     if (needButtonActivation && firstSuccessfulSubmitButton)
         firstSuccessfulSubmitButton->setActivatedSubmit(true);
 
-    LockHistory lockHistory = processingUserGesture ? LockHistory::No : LockHistory::Yes;
-    Ref<HTMLFormElement> protectedThis(*this); // Form submission can execute arbitary JavaScript.
-    frame->loader().submitForm(FormSubmission::create(this, m_attributes, event, lockHistory, formSubmissionTrigger));
+    auto protectedThis = makeRef(*this); // Form submission can execute arbitary JavaScript.
+
+    auto shouldLockHistory = processingUserGesture ? LockHistory::No : LockHistory::Yes;
+    frame->loader().submitForm(FormSubmission::create(*this, m_attributes, event, shouldLockHistory, formSubmissionTrigger));
 
     if (needButtonActivation && firstSuccessfulSubmitButton)
         firstSuccessfulSubmitButton->setActivatedSubmit(false);
@@ -439,8 +439,8 @@ void HTMLFormElement::requestAutocomplete()
     StringPairVector controlNamesAndValues;
     getTextFieldValues(controlNamesAndValues);
 
-    RefPtr<FormState> formState = FormState::create(this, controlNamesAndValues, &document(), SubmittedByJavaScript);
-    frame->loader().client().didRequestAutocomplete(formState.release());
+    auto formState = FormState::create(this, controlNamesAndValues, &document(), SubmittedByJavaScript);
+    frame->loader().client().didRequestAutocomplete(WTFMove(formState));
 }
 
 void HTMLFormElement::finishRequestAutocomplete(AutocompleteResult result)
index bb51798..5de195e 100644 (file)
@@ -128,7 +128,7 @@ public:
     const Vector<FormAssociatedElement*>& associatedElements() const { return m_associatedElements; }
     const Vector<HTMLImageElement*>& imageElements() const { return m_imageElements; }
 
-    void getTextFieldValues(StringPairVector& fieldNamesAndValues) const;
+    StringPairVector textFieldValues() const;
 
     static HTMLFormElement* findClosestFormAncestor(const Element&);
 
index 5846f56..49f8372 100644 (file)
@@ -66,15 +66,15 @@ void HTMLHtmlElement::insertedByParser()
     if (!document().frame())
         return;
 
-    DocumentLoader* documentLoader = document().frame()->loader().documentLoader();
+    auto* documentLoader = document().frame()->loader().documentLoader();
     if (!documentLoader)
         return;
 
-    const AtomicString& manifest = attributeWithoutSynchronization(manifestAttr);
+    auto& manifest = attributeWithoutSynchronization(manifestAttr);
     if (manifest.isEmpty())
-        documentLoader->applicationCacheHost()->selectCacheWithoutManifest();
+        documentLoader->applicationCacheHost().selectCacheWithoutManifest();
     else
-        documentLoader->applicationCacheHost()->selectCacheWithManifest(document().completeURL(manifest));
+        documentLoader->applicationCacheHost().selectCacheWithManifest(document().completeURL(manifest));
 }
 
 }
index d777a39..496aed6 100644 (file)
@@ -267,7 +267,7 @@ void HTMLLinkElement::process()
         if (!isActive)
             priority = ResourceLoadPriority::VeryLow;
         CachedResourceRequest request(url, CachedResourceLoader::defaultCachedResourceOptions(), priority, WTFMove(charset));
-        request.setInitiator(this);
+        request.setInitiator(*this);
 
         if (document().contentSecurityPolicy()->allowStyleWithNonce(attributeWithoutSynchronization(HTMLNames::nonceAttr))) {
             ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions();
@@ -367,7 +367,7 @@ void HTMLLinkElement::setCSSStyleSheet(const String& href, const URL& baseURL, c
     CSSParserContext parserContext(document(), baseURL, charset);
     auto cachePolicy = frame->loader().subresourceCachePolicy();
 
-    if (RefPtr<StyleSheetContents> restoredSheet = const_cast<CachedCSSStyleSheet*>(cachedStyleSheet)->restoreParsedStyleSheet(parserContext, cachePolicy)) {
+    if (auto restoredSheet = const_cast<CachedCSSStyleSheet*>(cachedStyleSheet)->restoreParsedStyleSheet(parserContext, cachePolicy)) {
         ASSERT(restoredSheet->isCacheable());
         ASSERT(!restoredSheet->isLoading());
         initializeStyleSheet(restoredSheet.releaseNonNull(), *cachedStyleSheet);
index 4c7dc97..3fc0c59 100644 (file)
@@ -1428,11 +1428,8 @@ void HTMLMediaElement::loadResource(const URL& initialURL, ContentType& contentT
     }
 
 #if ENABLE(CONTENT_EXTENSIONS)
-    DocumentLoader* documentLoader = frame->loader().documentLoader();
-
-    if (documentLoader) {
-        auto blockedStatus = page->userContentProvider().processContentExtensionRulesForLoad(url, ResourceType::Media, *documentLoader);
-        if (blockedStatus.blockedLoad) {
+    if (auto* documentLoader = frame->loader().documentLoader()) {
+        if (page->userContentProvider().processContentExtensionRulesForLoad(url, ResourceType::Media, *documentLoader).blockedLoad) {
             mediaLoadingFailed(MediaPlayer::FormatError);
             return;
         }
@@ -1442,11 +1439,9 @@ void HTMLMediaElement::loadResource(const URL& initialURL, ContentType& contentT
     // The resource fetch algorithm 
     m_networkState = NETWORK_LOADING;
 
-    // If the url should be loaded from the application cache, pass the url of the cached file
-    // to the media engine.
-    ApplicationCacheHost* cacheHost = frame->loader().documentLoader()->applicationCacheHost();
+    // If the URL should be loaded from the application cache, pass the URL of the cached file to the media engine.
     ApplicationCacheResource* resource = nullptr;
-    if (cacheHost && cacheHost->shouldLoadResourceFromApplicationCache(ResourceRequest(url), resource)) {
+    if (frame->loader().documentLoader()->applicationCacheHost().shouldLoadResourceFromApplicationCache(ResourceRequest(url), resource)) {
         // Resources that are not present in the manifest will always fail to load (at least, after the
         // cache has been primed the first time), making the testing of offline applications simpler.
         if (!resource || resource->path().isEmpty()) {
@@ -1460,7 +1455,7 @@ void HTMLMediaElement::loadResource(const URL& initialURL, ContentType& contentT
 
     m_firstTimePlaying = true;
 
-    // Set m_currentSrc *before* changing to the cache url, the fact that we are loading from the app
+    // Set m_currentSrc *before* changing to the cache URL, the fact that we are loading from the app
     // cache is an internal detail not exposed through the media element API.
     m_currentSrc = url;
 
index ff4ff31..6e39bcd 100644 (file)
@@ -68,16 +68,17 @@ void InspectorApplicationCacheAgent::enable(ErrorString&)
 
 void InspectorApplicationCacheAgent::updateApplicationCacheStatus(Frame* frame)
 {
-    DocumentLoader* documentLoader = frame->loader().documentLoader();
+    if (!frame)
+        return;
+    auto* documentLoader = frame->loader().documentLoader();
     if (!documentLoader)
         return;
 
-    ApplicationCacheHost* host = documentLoader->applicationCacheHost();
-    ApplicationCacheHost::Status status = host->status();
-    ApplicationCacheHost::CacheInfo info = host->applicationCacheInfo();
+    auto& host = documentLoader->applicationCacheHost();
+    int status = host.status();
+    auto manifestURL = host.applicationCacheInfo().manifest.string();
 
-    String manifestURL = info.m_manifest.string();
-    m_frontendDispatcher->applicationCacheStatusUpdated(m_pageAgent->frameId(frame), manifestURL, static_cast<int>(status));
+    m_frontendDispatcher->applicationCacheStatusUpdated(m_pageAgent->frameId(frame), manifestURL, status);
 }
 
 void InspectorApplicationCacheAgent::networkStateChanged()
@@ -91,20 +92,18 @@ void InspectorApplicationCacheAgent::getFramesWithManifests(ErrorString&, RefPtr
     result = Inspector::Protocol::Array<Inspector::Protocol::ApplicationCache::FrameWithManifest>::create();
 
     for (Frame* frame = &m_pageAgent->mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        DocumentLoader* documentLoader = frame->loader().documentLoader();
+        auto* documentLoader = frame->loader().documentLoader();
         if (!documentLoader)
             continue;
 
-        ApplicationCacheHost* host = documentLoader->applicationCacheHost();
-        ApplicationCacheHost::CacheInfo info = host->applicationCacheInfo();
-        String manifestURL = info.m_manifest.string();
+        auto& host = documentLoader->applicationCacheHost();
+        String manifestURL = host.applicationCacheInfo().manifest.string();
         if (!manifestURL.isEmpty()) {
-            Ref<Inspector::Protocol::ApplicationCache::FrameWithManifest> value = Inspector::Protocol::ApplicationCache::FrameWithManifest::create()
+            result->addItem(Inspector::Protocol::ApplicationCache::FrameWithManifest::create()
                 .setFrameId(m_pageAgent->frameId(frame))
                 .setManifestURL(manifestURL)
-                .setStatus(static_cast<int>(host->status()))
-                .release();
-            result->addItem(WTFMove(value));
+                .setStatus(static_cast<int>(host.status()))
+                .release());
         }
     }
 }
@@ -124,68 +123,60 @@ void InspectorApplicationCacheAgent::getManifestForFrame(ErrorString& errorStrin
     if (!documentLoader)
         return;
 
-    ApplicationCacheHost::CacheInfo info = documentLoader->applicationCacheHost()->applicationCacheInfo();
-    *manifestURL = info.m_manifest.string();
+    *manifestURL = documentLoader->applicationCacheHost().applicationCacheInfo().manifest.string();
 }
 
 void InspectorApplicationCacheAgent::getApplicationCacheForFrame(ErrorString& errorString, const String& frameId, RefPtr<Inspector::Protocol::ApplicationCache::ApplicationCache>& applicationCache)
 {
-    DocumentLoader* documentLoader = assertFrameWithDocumentLoader(errorString, frameId);
+    auto* documentLoader = assertFrameWithDocumentLoader(errorString, frameId);
     if (!documentLoader)
         return;
 
-    ApplicationCacheHost* host = documentLoader->applicationCacheHost();
-    ApplicationCacheHost::CacheInfo info = host->applicationCacheInfo();
-
-    ApplicationCacheHost::ResourceInfoList resources;
-    host->fillResourceList(&resources);
-
-    applicationCache = buildObjectForApplicationCache(resources, info);
+    auto& host = documentLoader->applicationCacheHost();
+    applicationCache = buildObjectForApplicationCache(host.resourceList(), host.applicationCacheInfo());
 }
 
-Ref<Inspector::Protocol::ApplicationCache::ApplicationCache> InspectorApplicationCacheAgent::buildObjectForApplicationCache(const ApplicationCacheHost::ResourceInfoList& applicationCacheResources, const ApplicationCacheHost::CacheInfo& applicationCacheInfo)
+Ref<Inspector::Protocol::ApplicationCache::ApplicationCache> InspectorApplicationCacheAgent::buildObjectForApplicationCache(const Vector<ApplicationCacheHost::ResourceInfo>& applicationCacheResources, const ApplicationCacheHost::CacheInfo& applicationCacheInfo)
 {
     return Inspector::Protocol::ApplicationCache::ApplicationCache::create()
-        .setManifestURL(applicationCacheInfo.m_manifest.string())
-        .setSize(applicationCacheInfo.m_size)
-        .setCreationTime(applicationCacheInfo.m_creationTime)
-        .setUpdateTime(applicationCacheInfo.m_updateTime)
+        .setManifestURL(applicationCacheInfo.manifest.string())
+        .setSize(applicationCacheInfo.size)
+        .setCreationTime(applicationCacheInfo.creationTime)
+        .setUpdateTime(applicationCacheInfo.updateTime)
         .setResources(buildArrayForApplicationCacheResources(applicationCacheResources))
         .release();
 }
 
-Ref<Inspector::Protocol::Array<Inspector::Protocol::ApplicationCache::ApplicationCacheResource>> InspectorApplicationCacheAgent::buildArrayForApplicationCacheResources(const ApplicationCacheHost::ResourceInfoList& applicationCacheResources)
+Ref<Inspector::Protocol::Array<Inspector::Protocol::ApplicationCache::ApplicationCacheResource>> InspectorApplicationCacheAgent::buildArrayForApplicationCacheResources(const Vector<ApplicationCacheHost::ResourceInfo>& applicationCacheResources)
 {
-    auto resources = Inspector::Protocol::Array<Inspector::Protocol::ApplicationCache::ApplicationCacheResource>::create();
-
-    for (const auto& resourceInfo : applicationCacheResources)
-        resources->addItem(buildObjectForApplicationCacheResource(resourceInfo));
-
-    return resources;
+    auto result = Inspector::Protocol::Array<Inspector::Protocol::ApplicationCache::ApplicationCacheResource>::create();
+    for (auto& info : applicationCacheResources)
+        result->addItem(buildObjectForApplicationCacheResource(info));
+    return result;
 }
 
 Ref<Inspector::Protocol::ApplicationCache::ApplicationCacheResource> InspectorApplicationCacheAgent::buildObjectForApplicationCacheResource(const ApplicationCacheHost::ResourceInfo& resourceInfo)
 {
     StringBuilder types;
 
-    if (resourceInfo.m_isMaster)
+    if (resourceInfo.isMaster)
         types.appendLiteral("Master ");
 
-    if (resourceInfo.m_isManifest)
+    if (resourceInfo.isManifest)
         types.appendLiteral("Manifest ");
 
-    if (resourceInfo.m_isFallback)
+    if (resourceInfo.isFallback)
         types.appendLiteral("Fallback ");
 
-    if (resourceInfo.m_isForeign)
+    if (resourceInfo.isForeign)
         types.appendLiteral("Foreign ");
 
-    if (resourceInfo.m_isExplicit)
+    if (resourceInfo.isExplicit)
         types.appendLiteral("Explicit ");
 
     return Inspector::Protocol::ApplicationCache::ApplicationCacheResource::create()
-        .setUrl(resourceInfo.m_resource.string())
-        .setSize(static_cast<int>(resourceInfo.m_size))
+        .setUrl(resourceInfo.resource.string())
+        .setSize(static_cast<int>(resourceInfo.size))
         .setType(types.toString())
         .release();
 }
index d5c579c..48752ef 100644 (file)
@@ -62,8 +62,8 @@ public:
     void getApplicationCacheForFrame(ErrorString&, const String& frameId, RefPtr<Inspector::Protocol::ApplicationCache::ApplicationCache>&) override;
 
 private:
-    Ref<Inspector::Protocol::ApplicationCache::ApplicationCache> buildObjectForApplicationCache(const ApplicationCacheHost::ResourceInfoList&, const ApplicationCacheHost::CacheInfo&);
-    Ref<Inspector::Protocol::Array<Inspector::Protocol::ApplicationCache::ApplicationCacheResource>> buildArrayForApplicationCacheResources(const ApplicationCacheHost::ResourceInfoList&);
+    Ref<Inspector::Protocol::ApplicationCache::ApplicationCache> buildObjectForApplicationCache(const Vector<ApplicationCacheHost::ResourceInfo>&, const ApplicationCacheHost::CacheInfo&);
+    Ref<Inspector::Protocol::Array<Inspector::Protocol::ApplicationCache::ApplicationCacheResource>> buildArrayForApplicationCacheResources(const Vector<ApplicationCacheHost::ResourceInfo>&);
     Ref<Inspector::Protocol::ApplicationCache::ApplicationCacheResource> buildObjectForApplicationCacheResource(const ApplicationCacheHost::ResourceInfo&);
 
     DocumentLoader* assertFrameWithDocumentLoader(ErrorString&, const String& frameId);
index 2e43379..d68c522 100644 (file)
@@ -1,6 +1,6 @@
 /*
 * Copyright (C) 2011 Google Inc. All rights reserved.
-* Copyright (C) 2014, 2015 Apple Inc. All rights reserved.
+* Copyright (C) 2014-2017 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
@@ -1073,10 +1073,10 @@ void InspectorInstrumentation::networkStateChangedImpl(InstrumentingAgents& inst
         applicationCacheAgent->networkStateChanged();
 }
 
-void InspectorInstrumentation::updateApplicationCacheStatusImpl(InstrumentingAgents& instrumentingAgents, Frame* frame)
+void InspectorInstrumentation::updateApplicationCacheStatusImpl(InstrumentingAgents& instrumentingAgents, Frame& frame)
 {
-    if (InspectorApplicationCacheAgent* applicationCacheAgent = instrumentingAgents.inspectorApplicationCacheAgent())
-        applicationCacheAgent->updateApplicationCacheStatus(frame);
+    if (auto* applicationCacheAgent = instrumentingAgents.inspectorApplicationCacheAgent())
+        applicationCacheAgent->updateApplicationCacheStatus(&frame);
 }
 
 bool InspectorInstrumentation::consoleAgentEnabled(ScriptExecutionContext* scriptExecutionContext)
index 9b60010..245cdc8 100644 (file)
@@ -407,7 +407,7 @@ private:
 #endif
 
     static void networkStateChangedImpl(InstrumentingAgents&);
-    static void updateApplicationCacheStatusImpl(InstrumentingAgents&, Frame*);
+    static void updateApplicationCacheStatusImpl(InstrumentingAgents&, Frame&);
 
     static void layerTreeDidChangeImpl(InstrumentingAgents&);
     static void renderLayerDestroyedImpl(InstrumentingAgents&, const RenderLayer&);
@@ -1181,8 +1181,8 @@ inline void InspectorInstrumentation::networkStateChanged(Page& page)
 inline void InspectorInstrumentation::updateApplicationCacheStatus(Frame* frame)
 {
     FAST_RETURN_IF_NO_FRONTENDS(void());
-    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsForFrame(frame))
-        updateApplicationCacheStatusImpl(*instrumentingAgents, frame);
+    if (auto* instrumentingAgents = instrumentingAgentsForFrame(frame))
+        updateApplicationCacheStatusImpl(*instrumentingAgents, *frame);
 }
 
 inline void InspectorInstrumentation::addMessageToConsole(Page& page, std::unique_ptr<Inspector::ConsoleMessage> message)
index 9b38c3b..ee659cb 100644 (file)
@@ -129,30 +129,16 @@ static bool areAllLoadersPageCacheAcceptable(const ResourceLoaderMap& loaders)
     return true;
 }
 
-DocumentLoader::DocumentLoader(const ResourceRequest& req, const SubstituteData& substituteData)
-    : m_deferMainResourceDataLoad(true)
-    , m_frame(nullptr)
-    , m_cachedResourceLoader(CachedResourceLoader::create(this))
+DocumentLoader::DocumentLoader(const ResourceRequest& request, const SubstituteData& substituteData)
+    : m_cachedResourceLoader(CachedResourceLoader::create(this))
     , m_writer(m_frame)
-    , m_originalRequest(req)
+    , m_originalRequest(request)
     , m_substituteData(substituteData)
-    , m_originalRequestCopy(req)
-    , m_request(req)
+    , m_originalRequestCopy(request)
+    , m_request(request)
     , m_originalSubstituteDataWasValid(substituteData.isValid())
-    , m_committed(false)
-    , m_isStopping(false)
-    , m_gotFirstByte(false)
-    , m_isClientRedirect(false)
-    , m_isLoadingMultipartContent(false)
-    , m_wasOnloadDispatched(false)
-    , m_stopRecordingResponses(false)
     , m_substituteResourceDeliveryTimer(*this, &DocumentLoader::substituteResourceDeliveryTimerFired)
-    , m_didCreateGlobalHistoryEntry(false)
-    , m_loadingMainResource(false)
-    , m_timeOfLastDataReceived(0.0)
-    , m_identifierForLoadWithoutResourceLoader(0)
     , m_dataLoadTimer(*this, &DocumentLoader::handleSubstituteDataLoadNow)
-    , m_subresourceLoadersArePageCacheAcceptable(false)
     , m_applicationCacheHost(std::make_unique<ApplicationCacheHost>(*this))
 {
 }
@@ -166,7 +152,9 @@ FrameLoader* DocumentLoader::frameLoader() const
 
 SubresourceLoader* DocumentLoader::mainResourceLoader() const
 {
-    return m_mainResource ? m_mainResource->loader() : 0;
+    if (!m_mainResource)
+        return nullptr;
+    return m_mainResource->loader();
 }
 
 DocumentLoader::~DocumentLoader()
@@ -179,7 +167,7 @@ DocumentLoader::~DocumentLoader()
     if (m_iconDataCallback)
         m_iconDataCallback->invalidate();
     m_cachedResourceLoader->clearDocumentLoader();
-    
+
     clearMainResource();
 }
 
@@ -199,31 +187,6 @@ Document* DocumentLoader::document() const
     return nullptr;
 }
 
-const ResourceRequest& DocumentLoader::originalRequest() const
-{
-    return m_originalRequest;
-}
-
-const ResourceRequest& DocumentLoader::originalRequestCopy() const
-{
-    return m_originalRequestCopy;
-}
-
-const ResourceRequest& DocumentLoader::request() const
-{
-    return m_request;
-}
-
-ResourceRequest& DocumentLoader::request()
-{
-    return m_request;
-}
-
-const URL& DocumentLoader::url() const
-{
-    return request().url();
-}
-
 void DocumentLoader::replaceRequestURLForSameDocumentNavigation(const URL& url)
 {
     m_originalRequestCopy.setURL(url);
@@ -319,7 +282,7 @@ void DocumentLoader::stopLoading()
     cancelAll(m_multipartSubresourceLoaders);
 
     // Appcache uses ResourceHandle directly, DocumentLoader doesn't count these loads.
-    m_applicationCacheHost->stopLoadingInFrame(m_frame);
+    m_applicationCacheHost->stopLoadingInFrame(*m_frame);
     
 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
     clearArchiveResources();
@@ -602,7 +565,7 @@ void DocumentLoader::willSendRequest(ResourceRequest& newRequest, const Resource
 
     ASSERT(!m_waitingForNavigationPolicy);
     m_waitingForNavigationPolicy = true;
-    frameLoader()->policyChecker().checkNavigationPolicy(newRequest, didReceiveRedirectResponse, [this](const ResourceRequest& request, PassRefPtr<FormState>, bool shouldContinue) {
+    frameLoader()->policyChecker().checkNavigationPolicy(newRequest, didReceiveRedirectResponse, [this] (const ResourceRequest& request, FormState*, bool shouldContinue) {
         continueAfterNavigationPolicy(request, shouldContinue);
     });
 }
@@ -900,12 +863,8 @@ void DocumentLoader::commitData(const char* bytes, size_t length)
         if (frameLoader()->stateMachine().creatingInitialEmptyDocument())
             return;
         
-#if ENABLE(MHTML)
-        // The origin is the MHTML file, we need to set the base URL to the document encoded in the MHTML so
-        // relative URLs are resolved properly.
-        if (m_archive && m_archive->type() == Archive::MHTML)
+        if (m_archive && m_archive->shouldOverrideBaseURL())
             m_frame->document()->setBaseURLOverride(m_archive->mainResource()->url());
-#endif
 
         // Call receivedFirstData() exactly once per load. We should only reach this point multiple times
         // for multipart loads, and FrameLoader::isReplacing() will be true after the first time.
@@ -921,10 +880,8 @@ void DocumentLoader::commitData(const char* bytes, size_t length)
         if (overrideEncoding().isNull()) {
             userChosen = false;
             encoding = response().textEncodingName();
-#if ENABLE(WEB_ARCHIVE)
-            if (m_archive && m_archive->type() == Archive::WebArchive)
+            if (m_archive && m_archive->shouldUseMainResourceEncoding())
                 encoding = m_archive->mainResource()->textEncoding();
-#endif
         } else {
             userChosen = true;
             encoding = overrideEncoding();
@@ -1083,15 +1040,16 @@ bool DocumentLoader::isLoadingInAPISense() const
     if (frameLoader()->state() != FrameStateComplete) {
         if (m_frame->settings().needsIsLoadingInAPISenseQuirk() && !m_subresourceLoaders.isEmpty())
             return true;
-    
-        Document* doc = m_frame->document();
-        if ((isLoadingMainResource() || !m_frame->document()->loadEventFinished()) && isLoading())
+
+        ASSERT(m_frame->document());
+        auto& document = *m_frame->document();
+        if ((isLoadingMainResource() || !document.loadEventFinished()) && isLoading())
             return true;
         if (m_cachedResourceLoader->requestCount())
             return true;
-        if (doc->processingLoadEvent())
+        if (document.processingLoadEvent())
             return true;
-        if (doc->hasActiveParser())
+        if (document.hasActiveParser())
             return true;
     }
     return frameLoader()->subframeIsLoading();
@@ -1102,40 +1060,35 @@ bool DocumentLoader::maybeCreateArchive()
 #if !ENABLE(WEB_ARCHIVE) && !ENABLE(MHTML)
     return false;
 #else
-    
     // Give the archive machinery a crack at this document. If the MIME type is not an archive type, it will return 0.
     m_archive = ArchiveFactory::create(m_response.url(), mainResourceData().get(), m_response.mimeType());
     if (!m_archive)
         return false;
     
-    addAllArchiveResources(m_archive.get());
-    ArchiveResource* mainResource = m_archive->mainResource();
-    m_parsedArchiveData = &mainResource->data();
-    m_writer.setMIMEType(mainResource->mimeType());
-    
+    addAllArchiveResources(*m_archive);
+    ASSERT(m_archive->mainResource());
+    auto& mainResource = *m_archive->mainResource();
+    m_parsedArchiveData = &mainResource.data();
+    m_writer.setMIMEType(mainResource.mimeType());
+
     ASSERT(m_frame->document());
-    commitData(mainResource->data().data(), mainResource->data().size());
+    commitData(mainResource.data().data(), mainResource.data().size());
     return true;
-#endif // !ENABLE(WEB_ARCHIVE) && !ENABLE(MHTML)
+#endif
 }
 
 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
 
-void DocumentLoader::setArchive(PassRefPtr<Archive> archive)
+void DocumentLoader::setArchive(Ref<Archive>&& archive)
 {
-    m_archive = archive;
-    addAllArchiveResources(m_archive.get());
+    m_archive = WTFMove(archive);
+    addAllArchiveResources(*m_archive);
 }
 
-void DocumentLoader::addAllArchiveResources(Archive* archive)
+void DocumentLoader::addAllArchiveResources(Archive& archive)
 {
     if (!m_archiveResourceCollection)
         m_archiveResourceCollection = std::make_unique<ArchiveResourceCollection>();
-        
-    ASSERT(archive);
-    if (!archive)
-        return;
-        
     m_archiveResourceCollection->addAllResources(archive);
 }
 
@@ -1145,13 +1098,12 @@ void DocumentLoader::addArchiveResource(Ref<ArchiveResource>&& resource)
 {
     if (!m_archiveResourceCollection)
         m_archiveResourceCollection = std::make_unique<ArchiveResourceCollection>();
-        
     m_archiveResourceCollection->addResource(WTFMove(resource));
 }
 
-PassRefPtr<Archive> DocumentLoader::popArchiveForSubframe(const String& frameName, const URL& url)
+RefPtr<Archive> DocumentLoader::popArchiveForSubframe(const String& frameName, const URL& url)
 {
-    return m_archiveResourceCollection ? m_archiveResourceCollection->popSubframeArchive(frameName, url) : PassRefPtr<Archive>(nullptr);
+    return m_archiveResourceCollection ? m_archiveResourceCollection->popSubframeArchive(frameName, url) : nullptr;
 }
 
 void DocumentLoader::clearArchiveResources()
@@ -1171,7 +1123,7 @@ ArchiveResource* DocumentLoader::archiveResourceForURL(const URL& url) const
 {
     if (!m_archiveResourceCollection)
         return nullptr;
-    ArchiveResource* resource = m_archiveResourceCollection->archiveResourceForURL(url);
+    auto* resource = m_archiveResourceCollection->archiveResourceForURL(url);
     if (!resource || resource->shouldIgnoreWhenUnarchiving())
         return nullptr;
     return resource;
@@ -1182,17 +1134,16 @@ RefPtr<ArchiveResource> DocumentLoader::mainResource() const
     RefPtr<SharedBuffer> data = mainResourceData();
     if (!data)
         data = SharedBuffer::create();
-        
     auto& response = this->response();
     return ArchiveResource::create(WTFMove(data), response.url(), response.mimeType(), response.textEncodingName(), frame()->tree().uniqueName());
 }
 
-PassRefPtr<ArchiveResource> DocumentLoader::subresource(const URL& url) const
+RefPtr<ArchiveResource> DocumentLoader::subresource(const URL& url) const
 {
     if (!isCommitted())
         return nullptr;
     
-    CachedResource* resource = m_cachedResourceLoader->cachedResource(url);
+    auto* resource = m_cachedResourceLoader->cachedResource(url);
     if (!resource || !resource->isLoaded())
         return archiveResourceForURL(url);
 
@@ -1206,18 +1157,16 @@ PassRefPtr<ArchiveResource> DocumentLoader::subresource(const URL& url) const
     return ArchiveResource::create(data, url, resource->response());
 }
 
-Vector<RefPtr<ArchiveResource>> DocumentLoader::subresources() const
+Vector<Ref<ArchiveResource>> DocumentLoader::subresources() const
 {
     if (!isCommitted())
         return { };
 
-    Vector<RefPtr<ArchiveResource>> subresources;
-
-    for (auto& cachedResourceHandle : m_cachedResourceLoader->allCachedResources().values()) {
-        if (RefPtr<ArchiveResource> subresource = this->subresource(URL(ParsedURLString, cachedResourceHandle->url())))
-            subresources.append(WTFMove(subresource));
+    Vector<Ref<ArchiveResource>> subresources;
+    for (auto& handle : m_cachedResourceLoader->allCachedResources().values()) {
+        if (auto subresource = this->subresource({ ParsedURLString, handle->url() }))
+            subresources.append(subresource.releaseNonNull());
     }
-
     return subresources;
 }
 
@@ -1225,9 +1174,11 @@ void DocumentLoader::deliverSubstituteResourcesAfterDelay()
 {
     if (m_pendingSubstituteResources.isEmpty())
         return;
-    ASSERT(m_frame && m_frame->page());
+    ASSERT(m_frame);
+    ASSERT(m_frame->page());
     if (m_frame->page()->defersLoading())
         return;
+
     if (!m_substituteResourceDeliveryTimer.isActive())
         m_substituteResourceDeliveryTimer.startOneShot(0);
 }
@@ -1236,18 +1187,15 @@ void DocumentLoader::substituteResourceDeliveryTimerFired()
 {
     if (m_pendingSubstituteResources.isEmpty())
         return;
-    ASSERT(m_frame && m_frame->page());
+    ASSERT(m_frame);
+    ASSERT(m_frame->page());
     if (m_frame->page()->defersLoading())
         return;
 
-    SubstituteResourceMap copy;
-    copy.swap(m_pendingSubstituteResources);
-
-    for (auto& entry : copy) {
-        auto& loader = entry.key;
-        SubstituteResource* resource = entry.value.get();
-
-        if (resource)
+    auto pendingSubstituteResources = WTFMove(m_pendingSubstituteResources);
+    for (auto& pendingSubstituteResource : pendingSubstituteResources) {
+        auto& loader = pendingSubstituteResource.key;
+        if (auto& resource = pendingSubstituteResource.value)
             resource->deliver(*loader);
         else {
             // A null resource means that we should fail the load.
@@ -1258,10 +1206,12 @@ void DocumentLoader::substituteResourceDeliveryTimerFired()
 }
 
 #ifndef NDEBUG
+
 bool DocumentLoader::isSubstituteLoadPending(ResourceLoader* loader) const
 {
     return m_pendingSubstituteResources.contains(loader);
 }
+
 #endif
 
 void DocumentLoader::cancelPendingSubstituteLoad(ResourceLoader* loader)
@@ -1274,9 +1224,10 @@ void DocumentLoader::cancelPendingSubstituteLoad(ResourceLoader* loader)
 }
 
 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
+
 bool DocumentLoader::scheduleArchiveLoad(ResourceLoader& loader, const ResourceRequest& request)
 {
-    if (ArchiveResource* resource = archiveResourceForURL(request.url())) {
+    if (auto* resource = archiveResourceForURL(request.url())) {
         scheduleSubstituteResourceLoad(loader, *resource);
         return true;
     }
@@ -1284,21 +1235,19 @@ bool DocumentLoader::scheduleArchiveLoad(ResourceLoader& loader, const ResourceR
     if (!m_archive)
         return false;
 
-    switch (m_archive->type()) {
 #if ENABLE(WEB_ARCHIVE)
-    case Archive::WebArchive:
-        // WebArchiveDebugMode means we fail loads instead of trying to fetch them from the network if they're not in the archive.
-        return m_frame->settings().webArchiveDebugModeEnabled() && ArchiveFactory::isArchiveMimeType(responseMIMEType());
-#endif
-#if ENABLE(MHTML)
-    case Archive::MHTML:
-        return true; // Always fail the load for resources not included in the MHTML.
+    // The idea of WebArchiveDebugMode is that we should fail instead of trying to fetch from the network.
+    // Returning true ensures the caller will not try to fetch from the network.
+    if (m_frame->settings().webArchiveDebugModeEnabled() && responseMIMEType() == "application/x-webarchive")
+        return true;
 #endif
-    default:
-        return false;
-    }
+
+    // If we want to load from the archive only, then we should always return true so that the caller
+    // does not try to fetch form the network.
+    return m_archive->shouldLoadFromArchiveOnly();
 }
-#endif // ENABLE(WEB_ARCHIVE)
+
+#endif
 
 void DocumentLoader::scheduleSubstituteResourceLoad(ResourceLoader& loader, SubstituteResource& resource)
 {
@@ -1306,10 +1255,10 @@ void DocumentLoader::scheduleSubstituteResourceLoad(ResourceLoader& loader, Subs
     deliverSubstituteResourcesAfterDelay();
 }
 
-void DocumentLoader::addResponse(const ResourceResponse& r)
+void DocumentLoader::addResponse(const ResourceResponse& response)
 {
     if (!m_stopRecordingResponses)
-        m_responses.append(r);
+        m_responses.append(response);
 }
 
 void DocumentLoader::stopRecordingResponses()
@@ -1344,21 +1293,11 @@ bool DocumentLoader::urlForHistoryReflectsFailure() const
     return m_substituteData.isValid() || m_response.httpStatusCode() >= 400;
 }
 
-const URL& DocumentLoader::originalURL() const
-{
-    return m_originalRequestCopy.url();
-}
-
-const URL& DocumentLoader::responseURL() const
-{
-    return m_response.url();
-}
-
 URL DocumentLoader::documentURL() const
 {
     URL url = substituteData().response().url();
 #if ENABLE(WEB_ARCHIVE)
-    if (url.isEmpty() && m_archive && m_archive->type() == Archive::WebArchive)
+    if (url.isEmpty() && m_archive && m_archive->shouldUseMainResourceURL())
         url = m_archive->mainResource()->url();
 #endif
     if (url.isEmpty())
@@ -1368,28 +1307,15 @@ URL DocumentLoader::documentURL() const
     return url;
 }
 
-const String& DocumentLoader::responseMIMEType() const
-{
-    return m_response.mimeType();
-}
-
-const String& DocumentLoader::currentContentType() const
-{
-    return m_writer.mimeType();
-}
-
 #if PLATFORM(IOS)
+
 // FIXME: This method seems to violate the encapsulation of this class.
 void DocumentLoader::setResponseMIMEType(const String& responseMimeType)
 {
     m_response.setMimeType(responseMimeType);
 }
-#endif
 
-const URL& DocumentLoader::unreachableURL() const
-{
-    return m_substituteData.failingURL();
-}
+#endif
 
 void DocumentLoader::setDefersLoading(bool defers)
 {
@@ -1682,7 +1608,7 @@ void DocumentLoader::getIconLoadDecisionForIconURL(const String& urlString)
     if (m_iconLoadDecisionCallback)
         m_iconLoadDecisionCallback->invalidate();
     m_iconLoadDecisionCallback = IconLoadDecisionCallback::create(this, iconLoadDecisionCallback);
-    iconDatabase().loadDecisionForIconURL(urlString, m_iconLoadDecisionCallback);
+    iconDatabase().loadDecisionForIconURL(urlString, *m_iconLoadDecisionCallback);
 }
 
 void DocumentLoader::continueIconLoadWithDecision(IconLoadDecision decision)
@@ -1703,7 +1629,7 @@ void DocumentLoader::getIconDataForIconURL(const String& urlString)
     if (m_iconDataCallback)
         m_iconDataCallback->invalidate();
     m_iconDataCallback = IconDataCallback::create(this, iconDataCallback);
-    iconDatabase().iconDataForIconURL(urlString, m_iconDataCallback);
+    iconDatabase().iconDataForIconURL(urlString, *m_iconDataCallback);
 }
 
 void DocumentLoader::startIconLoading()
@@ -1749,7 +1675,7 @@ void DocumentLoader::finishedLoadingIcon(IconLoader& loader, SharedBuffer* buffe
 void DocumentLoader::dispatchOnloadEvents()
 {
     m_wasOnloadDispatched = true;
-    applicationCacheHost()->stopDeferringEvents();
+    m_applicationCacheHost->stopDeferringEvents();
 }
 
 void DocumentLoader::setTriggeringAction(const NavigationAction& action)
@@ -1789,23 +1715,18 @@ void DocumentLoader::addPendingContentExtensionDisplayNoneSelector(const String&
 }
 #endif
 
-#if ENABLE(CONTENT_FILTERING)
-ContentFilter* DocumentLoader::contentFilter() const
-{
-    return m_contentFilter.get();
-}
-#endif
-
 bool DocumentLoader::isAlwaysOnLoggingAllowed() const
 {
-    return m_frame ? m_frame->isAlwaysOnLoggingAllowed() : true;
+    return !m_frame || m_frame->isAlwaysOnLoggingAllowed();
 }
 
 #if USE(QUICK_LOOK)
+
 void DocumentLoader::setQuickLookHandle(std::unique_ptr<QuickLookHandle> quickLookHandle)
 {
     m_quickLookHandle = WTFMove(quickLookHandle);
 }
+
 #endif
 
 } // namespace WebCore
index d70b39b..87e4eb7 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2016 Apple Inc. All rights reserved.
+ * Copyright (C) 2006-2017 Apple Inc. All rights reserved.
  * Copyright (C) 2011 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -76,8 +76,7 @@ class SharedBuffer;
 class SubresourceLoader;
 class SubstituteResource;
 
-typedef HashMap<unsigned long, RefPtr<ResourceLoader>> ResourceLoaderMap;
-typedef Vector<ResourceResponse> ResponseVector;
+using ResourceLoaderMap = HashMap<unsigned long, RefPtr<ResourceLoader>>;
 
 class DocumentLoader : public RefCounted<DocumentLoader>, private CachedRawResourceClient {
     WTF_MAKE_FAST_ALLOCATED;
@@ -150,14 +149,15 @@ public:
 #endif
 
 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
-    void setArchive(PassRefPtr<Archive>);
-    WEBCORE_EXPORT void addAllArchiveResources(Archive*);
+    void setArchive(Ref<Archive>&&);
+    WEBCORE_EXPORT void addAllArchiveResources(Archive&);
     WEBCORE_EXPORT void addArchiveResource(Ref<ArchiveResource>&&);
-    PassRefPtr<Archive> popArchiveForSubframe(const String& frameName, const URL&);
+    RefPtr<Archive> popArchiveForSubframe(const String& frameName, const URL&);
     WEBCORE_EXPORT SharedBuffer* parsedArchiveData() const;
 
     WEBCORE_EXPORT bool scheduleArchiveLoad(ResourceLoader&, const ResourceRequest&);
 #endif
+
     void scheduleSubstituteResourceLoad(ResourceLoader&, SubstituteResource&);
 
     // Return the ArchiveResource for the URL only when loading an Archive
@@ -166,9 +166,10 @@ public:
     WEBCORE_EXPORT RefPtr<ArchiveResource> mainResource() const;
 
     // Return an ArchiveResource for the URL, either creating from live data or
-    // pulling from the ArchiveResourceCollection
-    WEBCORE_EXPORT PassRefPtr<ArchiveResource> subresource(const URL&) const;
-    WEBCORE_EXPORT Vector<RefPtr<ArchiveResource>> subresources() const;
+    // pulling from the ArchiveResourceCollection.
+    WEBCORE_EXPORT RefPtr<ArchiveResource> subresource(const URL&) const;
+
+    WEBCORE_EXPORT Vector<Ref<ArchiveResource>> subresources() const;
 
 #ifndef NDEBUG
     bool isSubstituteLoadPending(ResourceLoader*) const;
@@ -176,7 +177,7 @@ public:
     void cancelPendingSubstituteLoad(ResourceLoader*);   
     
     void addResponse(const ResourceResponse&);
-    const ResponseVector& responses() const { return m_responses; }
+    const Vector<ResourceResponse>& responses() const { return m_responses; }
 
     const NavigationAction& triggeringAction() const { return m_triggeringAction; }
     void setTriggeringAction(const NavigationAction&);
@@ -240,17 +241,7 @@ public:
 
     void setDeferMainResourceDataLoad(bool defer) { m_deferMainResourceDataLoad = defer; }
     
-    void didTellClientAboutLoad(const String& url)
-    { 
-#if !PLATFORM(COCOA)
-        // Don't include data urls here, as if a lot of data is loaded
-        // that way, we hold on to the (large) url string for too long.
-        if (protocolIs(url, "data"))
-            return;
-#endif
-        if (!url.isEmpty())
-            m_resourcesClientKnowsAbout.add(url);
-    }
+    void didTellClientAboutLoad(const String& url);
     bool haveToldClientAboutLoad(const String& url) { return m_resourcesClientKnowsAbout.contains(url); }
     void recordMemoryCacheLoadForFutureClientNotification(const ResourceRequest&);
     void takeMemoryCacheLoadsForClientNotification(Vector<ResourceRequest>& loads);
@@ -258,11 +249,11 @@ public:
     LoadTiming& timing() { return m_loadTiming; }
     void resetTiming() { m_loadTiming = LoadTiming(); }
 
-    // The WebKit layer calls this function when it's ready for the data to
-    // actually be added to the document.
+    // The WebKit layer calls this function when it's ready for the data to actually be added to the document.
     WEBCORE_EXPORT void commitData(const char* bytes, size_t length);
 
-    ApplicationCacheHost* applicationCacheHost() const { return m_applicationCacheHost.get(); }
+    ApplicationCacheHost& applicationCacheHost() const;
+    ApplicationCacheHost* applicationCacheHostUnlessBeingDestroyed() const;
 
     void checkLoadComplete();
 
@@ -297,7 +288,7 @@ protected:
 
     WEBCORE_EXPORT virtual void attachToFrame();
 
-    bool m_deferMainResourceDataLoad;
+    bool m_deferMainResourceDataLoad { true };
 
 private:
     Document* document() const;
@@ -358,7 +349,7 @@ private:
     void cancelPolicyCheckIfNeeded();
     void becomeMainResourceClient();
 
-    Frame* m_frame;
+    Frame* m_frame { nullptr };
     Ref<CachedResourceLoader> m_cachedResourceLoader;
 
     CachedResourceHandle<CachedRawResource> m_mainResource;
@@ -390,15 +381,15 @@ private:
     ResourceError m_mainDocumentError;    
 
     bool m_originalSubstituteDataWasValid;
-    bool m_committed;
-    bool m_isStopping;
-    bool m_gotFirstByte;
-    bool m_isClientRedirect;
-    bool m_isLoadingMultipartContent;
+    bool m_committed { false };
+    bool m_isStopping { false };
+    bool m_gotFirstByte { false };
+    bool m_isClientRedirect { false };
+    bool m_isLoadingMultipartContent { false };
 
     // FIXME: Document::m_processingLoadEvent and DocumentLoader::m_wasOnloadDispatched are roughly the same
     // and should be merged.
-    bool m_wasOnloadDispatched;
+    bool m_wasOnloadDispatched { false };
 
     StringWithDirection m_pageTitle;
 
@@ -415,8 +406,8 @@ private:
     // We retain all the received responses so we can play back the
     // WebResourceLoadDelegate messages if the item is loaded from the
     // page cache.
-    ResponseVector m_responses;
-    bool m_stopRecordingResponses;
+    Vector<ResourceResponse> m_responses;
+    bool m_stopRecordingResponses { false };
     
     typedef HashMap<RefPtr<ResourceLoader>, RefPtr<SubstituteResource>> SubstituteResourceMap;
     SubstituteResourceMap m_pendingSubstituteResources;
@@ -432,13 +423,13 @@ private:
     Vector<ResourceRequest> m_resourcesLoadedFromMemoryCacheForClientNotification;
     
     String m_clientRedirectSourceForHistory;
-    bool m_didCreateGlobalHistoryEntry;
+    bool m_didCreateGlobalHistoryEntry { false };
 
-    bool m_loadingMainResource;
+    bool m_loadingMainResource { false };
     LoadTiming m_loadTiming;
 
-    double m_timeOfLastDataReceived;
-    unsigned long m_identifierForLoadWithoutResourceLoader;
+    double m_timeOfLastDataReceived { 0 };
+    unsigned long m_identifierForLoadWithoutResourceLoader { 0 };
 
     DocumentLoaderTimer m_dataLoadTimer;
     bool m_waitingForContentPolicy { false };
@@ -452,7 +443,7 @@ private:
     HashMap<uint64_t, LinkIcon> m_iconsPendingLoadDecision;
     HashMap<std::unique_ptr<IconLoader>, uint64_t> m_iconLoaders;
 
-    bool m_subresourceLoadersArePageCacheAcceptable;
+    bool m_subresourceLoadersArePageCacheAcceptable { false };
     ShouldOpenExternalURLsPolicy m_shouldOpenExternalURLsPolicy { ShouldOpenExternalURLsPolicy::ShouldNotAllow };
 
     std::unique_ptr<ApplicationCacheHost> m_applicationCacheHost;
@@ -487,4 +478,87 @@ inline void DocumentLoader::takeMemoryCacheLoadsForClientNotification(Vector<Res
     m_resourcesLoadedFromMemoryCacheForClientNotification.clear();
 }
 
+inline const ResourceRequest& DocumentLoader::originalRequest() const
+{
+    return m_originalRequest;
+}
+
+inline const ResourceRequest& DocumentLoader::originalRequestCopy() const
+{
+    return m_originalRequestCopy;
+}
+
+inline const ResourceRequest& DocumentLoader::request() const
+{
+    return m_request;
+}
+
+inline ResourceRequest& DocumentLoader::request()
+{
+    return m_request;
+}
+
+inline const URL& DocumentLoader::url() const
+{
+    return m_request.url();
+}
+
+inline const URL& DocumentLoader::originalURL() const
+{
+    return m_originalRequestCopy.url();
+}
+
+inline const URL& DocumentLoader::responseURL() const
+{
+    return m_response.url();
+}
+
+inline const String& DocumentLoader::responseMIMEType() const
+{
+    return m_response.mimeType();
+}
+
+inline const String& DocumentLoader::currentContentType() const
+{
+    return m_writer.mimeType();
+}
+
+inline const URL& DocumentLoader::unreachableURL() const
+{
+    return m_substituteData.failingURL();
+}
+
+inline ApplicationCacheHost& DocumentLoader::applicationCacheHost() const
+{
+    // For a short time while the document loader is being destroyed, m_applicationCacheHost is null.
+    // It's not acceptable to call this function during that time.
+    ASSERT(m_applicationCacheHost);
+    return *m_applicationCacheHost;
+}
+
+inline ApplicationCacheHost* DocumentLoader::applicationCacheHostUnlessBeingDestroyed() const
+{
+    return m_applicationCacheHost.get();
+}
+
+#if ENABLE(CONTENT_FILTERING)
+
+inline ContentFilter* DocumentLoader::contentFilter() const
+{
+    return m_contentFilter.get();
+}
+
+#endif
+
+inline void DocumentLoader::didTellClientAboutLoad(const String& url)
+{
+#if !PLATFORM(COCOA)
+    // Don't include data URLs here, as if a lot of data is loaded that way, we hold on to the (large) URL string for too long.
+    if (protocolIs(url, "data"))
+        return;
+#endif
+    if (!url.isEmpty())
+        m_resourcesClientKnowsAbout.add(url);
+}
+
 }
index e0f6e5b..eefc4aa 100644 (file)
@@ -46,6 +46,7 @@
 #include "HTMLFormElement.h"
 #include "InProcessIDBServer.h"
 #include "InspectorClient.h"
+#include "NetworkStorageSession.h"
 #include "Page.h"
 #include "PageConfiguration.h"
 #include "PaymentCoordinatorClient.h"
@@ -171,8 +172,8 @@ private:
     void requestCandidatesForSelection(const VisibleSelection&) final { }
     void handleAcceptedCandidateWithSoftSpaces(TextCheckingResult) final { }
 
-    void registerUndoStep(PassRefPtr<UndoStep>) final;
-    void registerRedoStep(PassRefPtr<UndoStep>) final;
+    void registerUndoStep(UndoStep&) final;
+    void registerRedoStep(UndoStep&) final;
     void clearUndoRedoOperations() final { }
 
     bool canCopyCut(Frame*, bool defaultValue) const final { return defaultValue; }
@@ -331,14 +332,14 @@ class EmptyFrameLoaderClient final : public FrameLoaderClient {
     void dispatchShow() final { }
 
     void dispatchDecidePolicyForResponse(const ResourceResponse&, const ResourceRequest&, FramePolicyFunction) final { }
-    void dispatchDecidePolicyForNewWindowAction(const NavigationAction&, const ResourceRequest&, PassRefPtr<FormState>, const String&, FramePolicyFunction) final;
-    void dispatchDecidePolicyForNavigationAction(const NavigationAction&, const ResourceRequest&, PassRefPtr<FormState>, FramePolicyFunction) final;
+    void dispatchDecidePolicyForNewWindowAction(const NavigationAction&, const ResourceRequest&, FormState*, const String&, FramePolicyFunction) final;
+    void dispatchDecidePolicyForNavigationAction(const NavigationAction&, const ResourceRequest&, FormState*, FramePolicyFunction) final;
     void cancelPolicyCheck() final { }
 
     void dispatchUnableToImplementPolicy(const ResourceError&) final { }
 
-    void dispatchWillSendSubmitEvent(PassRefPtr<FormState>) final;
-    void dispatchWillSubmitForm(PassRefPtr<FormState>, FramePolicyFunction) final;
+    void dispatchWillSendSubmitEvent(Ref<FormState>&&) final;
+    void dispatchWillSubmitForm(FormState&, FramePolicyFunction) final;
 
     void revertToProvisionalState(DocumentLoader*) final { }
     void setMainDocumentError(DocumentLoader*, const ResourceError&) final { }
@@ -410,10 +411,10 @@ class EmptyFrameLoaderClient final : public FrameLoaderClient {
     void didDisplayInsecureContent() final { }
     void didRunInsecureContent(SecurityOrigin*, const URL&) final { }
     void didDetectXSS(const URL&, bool) final { }
-    RefPtr<Frame> createFrame(const URL&, const String&, HTMLFrameOwnerElement*, const String&, bool, int, int) final;
-    RefPtr<Widget> createPlugin(const IntSize&, HTMLPlugInElement*, const URL&, const Vector<String>&, const Vector<String>&, const String&, bool) final;
+    RefPtr<Frame> createFrame(const URL&, const String&, HTMLFrameOwnerElement&, const String&, bool, int, int) final;
+    RefPtr<Widget> createPlugin(const IntSize&, HTMLPlugInElement&, const URL&, const Vector<String>&, const Vector<String>&, const String&, bool) final;
     void recreatePlugin(Widget*) final;
-    PassRefPtr<Widget> createJavaAppletWidget(const IntSize&, HTMLAppletElement*, const URL&, const Vector<String>&, const Vector<String>&) final;
+    RefPtr<Widget> createJavaAppletWidget(const IntSize&, HTMLAppletElement&, const URL&, const Vector<String>&, const Vector<String>&) final;
 
     ObjectContentType objectContentType(const URL&, const String&) final { return ObjectContentType::None; }
     String overrideMediaType() const final { return { }; }
@@ -432,16 +433,37 @@ class EmptyFrameLoaderClient final : public FrameLoaderClient {
     bool shouldCacheResponse(DocumentLoader*, unsigned long, const ResourceResponse&, const unsigned char*, unsigned long long) final { return true; }
 #endif
 
-    PassRefPtr<FrameNetworkingContext> createNetworkingContext() final;
+    Ref<FrameNetworkingContext> createNetworkingContext() final;
 
 #if ENABLE(REQUEST_AUTOCOMPLETE)
-    void didRequestAutocomplete(PassRefPtr<FormState>) final { }
+    void didRequestAutocomplete(Ref<FormState>&&) final { }
 #endif
 
     bool isEmptyFrameLoaderClient() final { return true; }
     void prefetchDNS(const String&) final { }
 };
 
+class EmptyFrameNetworkingContext final : public FrameNetworkingContext {
+public:
+    static Ref<EmptyFrameNetworkingContext> create() { return adoptRef(*new EmptyFrameNetworkingContext); }
+
+private:
+    EmptyFrameNetworkingContext();
+
+    bool shouldClearReferrerOnHTTPSToHTTPRedirect() const { return true; }
+    NetworkStorageSession& storageSession() const final { return NetworkStorageSession::defaultStorageSession(); }
+
+#if PLATFORM(COCOA)
+    bool localFileContentSniffingEnabled() const { return false; }
+    SchedulePairHashSet* scheduledRunLoopPairs() const { return nullptr; }
+    RetainPtr<CFDataRef> sourceApplicationAuditData() const { return nullptr; };
+#endif
+
+#if PLATFORM(COCOA) || PLATFORM(WIN)
+    ResourceError blockedError(const ResourceRequest&) const final { return { }; }
+#endif
+};
+
 class EmptyInspectorClient final : public InspectorClient {
     void inspectedPageDestroyed() final { }
     Inspector::FrontendChannel* openLocalFrontend(InspectorController*) final { return nullptr; }
@@ -569,23 +591,23 @@ std::unique_ptr<ColorChooser> EmptyChromeClient::createColorChooser(ColorChooser
 
 #endif
 
-void EmptyChromeClient::runOpenPanel(Frame*, PassRefPtr<FileChooser>)
+void EmptyChromeClient::runOpenPanel(Frame&, FileChooser&)
 {
 }
 
-void EmptyFrameLoaderClient::dispatchDecidePolicyForNewWindowAction(const NavigationAction&, const ResourceRequest&, PassRefPtr<FormState>, const String&, FramePolicyFunction)
+void EmptyFrameLoaderClient::dispatchDecidePolicyForNewWindowAction(const NavigationAction&, const ResourceRequest&, FormState*, const String&, FramePolicyFunction)
 {
 }
 
-void EmptyFrameLoaderClient::dispatchDecidePolicyForNavigationAction(const NavigationAction&, const ResourceRequest&, PassRefPtr<FormState>, FramePolicyFunction)
+void EmptyFrameLoaderClient::dispatchDecidePolicyForNavigationAction(const NavigationAction&, const ResourceRequest&, FormState*, FramePolicyFunction)
 {
 }
 
-void EmptyFrameLoaderClient::dispatchWillSendSubmitEvent(PassRefPtr<FormState>)
+void EmptyFrameLoaderClient::dispatchWillSendSubmitEvent(Ref<FormState>&&)
 {
 }
 
-void EmptyFrameLoaderClient::dispatchWillSubmitForm(PassRefPtr<FormState>, FramePolicyFunction)
+void EmptyFrameLoaderClient::dispatchWillSubmitForm(FormState&, FramePolicyFunction)
 {
 }
 
@@ -594,12 +616,12 @@ Ref<DocumentLoader> EmptyFrameLoaderClient::createDocumentLoader(const ResourceR
     return DocumentLoader::create(request, substituteData);
 }
 
-RefPtr<Frame> EmptyFrameLoaderClient::createFrame(const URL&, const String&, HTMLFrameOwnerElement*, const String&, bool, int, int)
+RefPtr<Frame> EmptyFrameLoaderClient::createFrame(const URL&, const String&, HTMLFrameOwnerElement&, const String&, bool, int, int)
 {
     return nullptr;
 }
 
-RefPtr<Widget> EmptyFrameLoaderClient::createPlugin(const IntSize&, HTMLPlugInElement*, const URL&, const Vector<String>&, const Vector<String>&, const String&, bool)
+RefPtr<Widget> EmptyFrameLoaderClient::createPlugin(const IntSize&, HTMLPlugInElement&, const URL&, const Vector<String>&, const Vector<String>&, const String&, bool)
 {
     return nullptr;
 }
@@ -608,25 +630,30 @@ void EmptyFrameLoaderClient::recreatePlugin(Widget*)
 {
 }
 
-PassRefPtr<Widget> EmptyFrameLoaderClient::createJavaAppletWidget(const IntSize&, HTMLAppletElement*, const URL&, const Vector<String>&, const Vector<String>&)
+RefPtr<Widget> EmptyFrameLoaderClient::createJavaAppletWidget(const IntSize&, HTMLAppletElement&, const URL&, const Vector<String>&, const Vector<String>&)
 {
     return nullptr;
 }
 
-PassRefPtr<FrameNetworkingContext> EmptyFrameLoaderClient::createNetworkingContext()
+inline EmptyFrameNetworkingContext::EmptyFrameNetworkingContext()
+    : FrameNetworkingContext { nullptr }
+{
+}
+
+Ref<FrameNetworkingContext> EmptyFrameLoaderClient::createNetworkingContext()
 {
-    return PassRefPtr<FrameNetworkingContext>();
+    return EmptyFrameNetworkingContext::create();
 }
 
 void EmptyEditorClient::EmptyTextCheckerClient::requestCheckingOfString(TextCheckingRequest&, const VisibleSelection&)
 {
 }
 
-void EmptyEditorClient::registerUndoStep(PassRefPtr<UndoStep>)
+void EmptyEditorClient::registerUndoStep(UndoStep&)
 {
 }
 
-void EmptyEditorClient::registerRedoStep(PassRefPtr<UndoStep>)
+void EmptyEditorClient::registerRedoStep(UndoStep&)
 {
 }
 
index fbb16d9..91c2d38 100644 (file)
@@ -138,7 +138,7 @@ class EmptyChromeClient : public ChromeClient {
     std::unique_ptr<ColorChooser> createColorChooser(ColorChooserClient*, const Color&) final;
 #endif
 
-    void runOpenPanel(Frame*, PassRefPtr<FileChooser>) final;
+    void runOpenPanel(Frame&, FileChooser&) final;
     void loadIconForFiles(const Vector<String>&, FileIconLoader&) final { }
 
     void elementDidFocus(const Node*) final { }
index 3510b80..5e896e7 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006, 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2006-2017 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 
 namespace WebCore {
 
-inline FormState::FormState(PassRefPtr<HTMLFormElement> form, StringPairVector& textFieldValuesToAdopt, PassRefPtr<Document> sourceDocument, FormSubmissionTrigger formSubmissionTrigger)
+inline FormState::FormState(HTMLFormElement& form, StringPairVector&& textFieldValues, Document& sourceDocument, FormSubmissionTrigger formSubmissionTrigger)
     : m_form(form)
+    , m_textFieldValues(WTFMove(textFieldValues))
     , m_sourceDocument(sourceDocument)
     , m_formSubmissionTrigger(formSubmissionTrigger)
 {
-    m_textFieldValues.swap(textFieldValuesToAdopt);
 }
 
-Ref<FormState> FormState::create(PassRefPtr<HTMLFormElement> form, StringPairVector& textFieldValuesToAdopt, PassRefPtr<Document> sourceDocument, FormSubmissionTrigger formSubmissionTrigger)
+Ref<FormState> FormState::create(HTMLFormElement& form, StringPairVector&& textFieldValues, Document& sourceDocument, FormSubmissionTrigger formSubmissionTrigger)
 {
-    return adoptRef(*new FormState(form, textFieldValuesToAdopt, sourceDocument, formSubmissionTrigger));
+    return adoptRef(*new FormState(form, WTFMove(textFieldValues), sourceDocument, formSubmissionTrigger));
 }
 
 }
index 95040f9..2dedd09 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006, 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2006-2017 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 
 #pragma once
 
-#include <wtf/RefCounted.h>
 #include <wtf/text/WTFString.h>
 
 namespace WebCore {
 
-    class Document;
-    class HTMLFormElement;
+class Document;
+class HTMLFormElement;
 
-    enum FormSubmissionTrigger {
-        SubmittedByJavaScript,
-        NotSubmittedByJavaScript
-    };
-    
-    typedef Vector<std::pair<String, String>> StringPairVector;
+enum FormSubmissionTrigger { SubmittedByJavaScript, NotSubmittedByJavaScript };
 
-    class FormState : public RefCounted<FormState> {
-    public:
-        static Ref<FormState> create(PassRefPtr<HTMLFormElement>, StringPairVector& textFieldValuesToAdopt, PassRefPtr<Document>, FormSubmissionTrigger);
+using StringPairVector = Vector<std::pair<String, String>>;
 
-        HTMLFormElement* form() const { return m_form.get(); }
-        const StringPairVector& textFieldValues() const { return m_textFieldValues; }
-        Document* sourceDocument() const { return m_sourceDocument.get(); }
-        FormSubmissionTrigger formSubmissionTrigger() const { return m_formSubmissionTrigger; }
+class FormState : public RefCounted<FormState> {
+public:
+    static Ref<FormState> create(HTMLFormElement&, StringPairVector&& textFieldValues, Document&, FormSubmissionTrigger);
 
-    private:
-        FormState(PassRefPtr<HTMLFormElement>, StringPairVector& textFieldValuesToAdopt, PassRefPtr<Document>, FormSubmissionTrigger);
+    HTMLFormElement& form() const { return m_form; }
+    const StringPairVector& textFieldValues() const { return m_textFieldValues; }
+    Document& sourceDocument() const { return m_sourceDocument; }
+    FormSubmissionTrigger formSubmissionTrigger() const { return m_formSubmissionTrigger; }
 
-        RefPtr<HTMLFormElement> m_form;
-        StringPairVector m_textFieldValues;
-        RefPtr<Document> m_sourceDocument;
-        FormSubmissionTrigger m_formSubmissionTrigger;
-    };
+private:
+    FormState(HTMLFormElement&, StringPairVector&& textFieldValues, Document&, FormSubmissionTrigger);
+
+    Ref<HTMLFormElement> m_form;
+    StringPairVector m_textFieldValues;
+    Ref<Document> m_sourceDocument;
+    FormSubmissionTrigger m_formSubmissionTrigger;
+};
 
 } // namespace WebCore
index 20aaf4c..7707343 100644 (file)
@@ -106,7 +106,7 @@ void FormSubmission::Attributes::updateEncodingType(const String& type)
 
 FormSubmission::Method FormSubmission::Attributes::parseMethodType(const String& type)
 {
-    return equalLettersIgnoringASCIICase(type, "post") ? FormSubmission::PostMethod : FormSubmission::GetMethod;
+    return equalLettersIgnoringASCIICase(type, "post") ? FormSubmission::Method::Post : FormSubmission::Method::Get;
 }
 
 void FormSubmission::Attributes::updateMethodType(const String& type)
@@ -114,24 +114,13 @@ void FormSubmission::Attributes::updateMethodType(const String& type)
     m_method = parseMethodType(type);
 }
 
-void FormSubmission::Attributes::copyFrom(const Attributes& other)
-{
-    m_method = other.m_method;
-    m_isMultiPartForm = other.m_isMultiPartForm;
-
-    m_action = other.m_action;
-    m_target = other.m_target;
-    m_encodingType = other.m_encodingType;
-    m_acceptCharset = other.m_acceptCharset;
-}
-
-inline FormSubmission::FormSubmission(Method method, const URL& action, const String& target, const String& contentType, PassRefPtr<FormState> state, PassRefPtr<FormData> data, const String& boundary, LockHistory lockHistory, PassRefPtr<Event> event)
+inline FormSubmission::FormSubmission(Method method, const URL& action, const String& target, const String& contentType, Ref<FormState>&& state, Ref<FormData>&& data, const String& boundary, LockHistory lockHistory, Event* event)
     : m_method(method)
     , m_action(action)
     , m_target(target)
     , m_contentType(contentType)
-    , m_formState(state)
-    , m_formData(data)
+    , m_formState(WTFMove(state))
+    , m_formData(WTFMove(data))
     , m_boundary(boundary)
     , m_lockHistory(lockHistory)
     , m_event(event)
@@ -155,10 +144,8 @@ static TextEncoding encodingFromAcceptCharset(const String& acceptCharset, Docum
     return document.textEncoding();
 }
 
-Ref<FormSubmission> FormSubmission::create(HTMLFormElement* form, const Attributes& attributes, PassRefPtr<Event> event, LockHistory lockHistory, FormSubmissionTrigger trigger)
+Ref<FormSubmission> FormSubmission::create(HTMLFormElement& form, const Attributes& attributes, Event* event, LockHistory lockHistory, FormSubmissionTrigger trigger)
 {
-    ASSERT(form);
-
     HTMLFormControlElement* submitButton = nullptr;
     if (event && event->target()) {
         for (Node* node = event->target()->toNode(); node; node = node->parentNode()) {
@@ -169,8 +156,7 @@ Ref<FormSubmission> FormSubmission::create(HTMLFormElement* form, const Attribut
         }
     }
 
-    FormSubmission::Attributes copiedAttributes;
-    copiedAttributes.copyFrom(attributes);
+    auto copiedAttributes = attributes;
     if (submitButton) {
         AtomicString attributeValue;
         if (!(attributeValue = submitButton->attributeWithoutSynchronization(formactionAttr)).isNull())
@@ -183,15 +169,15 @@ Ref<FormSubmission> FormSubmission::create(HTMLFormElement* form, const Attribut
             copiedAttributes.setTarget(attributeValue);
     }
     
-    Document& document = form->document();
-    URL actionURL = document.completeURL(copiedAttributes.action().isEmpty() ? document.url().string() : copiedAttributes.action());
+    auto& document = form.document();
+    auto actionURL = document.completeURL(copiedAttributes.action().isEmpty() ? document.url().string() : copiedAttributes.action());
     bool isMailtoForm = actionURL.protocolIs("mailto");
     bool isMultiPartForm = false;
-    String encodingType = copiedAttributes.encodingType();
+    auto encodingType = copiedAttributes.encodingType();
 
     document.contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(actionURL, ContentSecurityPolicy::InsecureRequestType::FormSubmission);
 
-    if (copiedAttributes.method() == PostMethod) {
+    if (copiedAttributes.method() == Method::Post) {
         isMultiPartForm = copiedAttributes.isMultiPartForm();
         if (isMultiPartForm && isMailtoForm) {
             encodingType = "application/x-www-form-urlencoded";
@@ -199,19 +185,19 @@ Ref<FormSubmission> FormSubmission::create(HTMLFormElement* form, const Attribut
         }
     }
 
-    TextEncoding dataEncoding = isMailtoForm ? UTF8Encoding() : encodingFromAcceptCharset(copiedAttributes.acceptCharset(), document);
-    RefPtr<DOMFormData> domFormData = DOMFormData::create(dataEncoding.encodingForFormSubmission());
-    Vector<std::pair<String, String>> formValues;
+    auto dataEncoding = isMailtoForm ? UTF8Encoding() : encodingFromAcceptCharset(copiedAttributes.acceptCharset(), document);
+    auto domFormData = DOMFormData::create(dataEncoding.encodingForFormSubmission());
+    StringPairVector formValues;
 
     bool containsPasswordData = false;
-    for (auto& control : form->associatedElements()) {
-        HTMLElement& element = control->asHTMLElement();
+    for (auto& control : form.associatedElements()) {
+        auto& element = control->asHTMLElement();
         if (!element.isDisabledFormControl())
-            control->appendFormData(*domFormData, isMultiPartForm);
+            control->appendFormData(domFormData, isMultiPartForm);
         if (is<HTMLInputElement>(element)) {
-            HTMLInputElement& input = downcast<HTMLInputElement>(element);
+            auto& input = downcast<HTMLInputElement>(element);
             if (input.isTextField()) {
-                formValues.append(std::pair<String, String>(input.name().string(), input.value()));
+                formValues.append({ input.name().string(), input.value() });
                 input.addSearchResult();
             }
             if (input.isPasswordField() && !input.value().isEmpty())
@@ -223,11 +209,11 @@ Ref<FormSubmission> FormSubmission::create(HTMLFormElement* form, const Attribut
     String boundary;
 
     if (isMultiPartForm) {
-        formData = FormData::createMultiPart(*(static_cast<FormDataList*>(domFormData.get())), domFormData->encoding(), &document);
+        formData = FormData::createMultiPart(domFormData, domFormData->encoding(), &document);
         boundary = formData->boundary().data();
     } else {
-        formData = FormData::create(*(static_cast<FormDataList*>(domFormData.get())), domFormData->encoding(), attributes.method() == GetMethod ? FormData::FormURLEncoded : FormData::parseEncodingType(encodingType));
-        if (copiedAttributes.method() == PostMethod && isMailtoForm) {
+        formData = FormData::create(domFormData, domFormData->encoding(), attributes.method() == Method::Get ? FormData::FormURLEncoded : FormData::parseEncodingType(encodingType));
+        if (copiedAttributes.method() == Method::Post && isMailtoForm) {
             // Convert the form data into a string that we put into the URL.
             appendMailtoPostFormDataToURL(actionURL, *formData, encodingType);
             formData = FormData::create();
@@ -236,14 +222,17 @@ Ref<FormSubmission> FormSubmission::create(HTMLFormElement* form, const Attribut
 
     formData->setIdentifier(generateFormDataIdentifier());
     formData->setContainsPasswordData(containsPasswordData);
+
     String targetOrBaseTarget = copiedAttributes.target().isEmpty() ? document.baseTarget() : copiedAttributes.target();
-    auto formState = FormState::create(form, formValues, &document, trigger);
-    return adoptRef(*new FormSubmission(copiedAttributes.method(), actionURL, targetOrBaseTarget, encodingType, WTFMove(formState), WTFMove(formData), boundary, lockHistory, event));
+
+    auto formState = FormState::create(form, WTFMove(formValues), document, trigger);
+
+    return adoptRef(*new FormSubmission(copiedAttributes.method(), actionURL, targetOrBaseTarget, encodingType, WTFMove(formState), formData.releaseNonNull(), boundary, lockHistory, event));
 }
 
 URL FormSubmission::requestURL() const
 {
-    if (m_method == FormSubmission::PostMethod)
+    if (m_method == Method::Post)
         return m_action;
 
     URL requestURL(m_action);
@@ -259,7 +248,7 @@ void FormSubmission::populateFrameLoadRequest(FrameLoadRequest& frameRequest)
     if (!m_referrer.isEmpty())
         frameRequest.resourceRequest().setHTTPReferrer(m_referrer);
 
-    if (m_method == FormSubmission::PostMethod) {
+    if (m_method == Method::Post) {
         frameRequest.resourceRequest().setHTTPMethod("POST");
         frameRequest.resourceRequest().setHTTPBody(m_formData.copyRef());
 
index 41b37e0..252412c 100644 (file)
 
 namespace WebCore {
 
-class Document;
 class Event;
 class FormData;
+
 struct FrameLoadRequest;
-class HTMLFormElement;
-class TextEncoding;
 
 class FormSubmission : public RefCounted<FormSubmission> {
 public:
-    enum Method { GetMethod, PostMethod };
+    enum class Method { Get, Post };
 
     class Attributes {
-        WTF_MAKE_NONCOPYABLE(Attributes);
     public:
-        Attributes()
-            : m_method(GetMethod)
-            , m_isMultiPartForm(false)
-            , m_encodingType("application/x-www-form-urlencoded")
-        {
-        }
-
         Method method() const { return m_method; }
         static Method parseMethodType(const String&);
         void updateMethodType(const String&);
-        static String methodString(Method method) { return method == PostMethod ? "post" : "get"; }
+        static ASCIILiteral methodString(Method method) { return ASCIILiteral { method == Method::Post ? "post" : "get" }; }
 
         const String& action() const { return m_action; }
         void parseAction(const String&);
@@ -76,50 +66,46 @@ public:
         const String& acceptCharset() const { return m_acceptCharset; }
         void setAcceptCharset(const String& value) { m_acceptCharset = value; }
 
-        void copyFrom(const Attributes&);
-
     private:
-        Method m_method;
-        bool m_isMultiPartForm;
-
+        Method m_method { Method::Get };
+        bool m_isMultiPartForm { false };
         String m_action;
         String m_target;
-        String m_encodingType;
+        String m_encodingType { ASCIILiteral { "application/x-www-form-urlencoded" } };
         String m_acceptCharset;
     };
 
-    static Ref<FormSubmission> create(HTMLFormElement*, const Attributes&, PassRefPtr<Event> event, LockHistory, FormSubmissionTrigger);
+    static Ref<FormSubmission> create(HTMLFormElement&, const Attributes&, Event*, LockHistory, FormSubmissionTrigger);
 
     void populateFrameLoadRequest(FrameLoadRequest&);
-    
     URL requestURL() const;
 
     Method method() const { return m_method; }
     const URL& action() const { return m_action; }
     const String& target() const { return m_target; }
-    void clearTarget() { m_target = String(); }
     const String& contentType() const { return m_contentType; }
-    FormState* state() const { return m_formState.get(); }
-    FormData* data() const { return m_formData.get(); }
+    FormState& state() const { return m_formState; }
+    FormData& data() const { return m_formData; }
     const String boundary() const { return m_boundary; }
     LockHistory lockHistory() const { return m_lockHistory; }
     Event* event() const { return m_event.get(); }
-
     const String& referrer() const { return m_referrer; }
-    void setReferrer(const String& referrer) { m_referrer = referrer; }
     const String& origin() const { return m_origin; }
+
+    void clearTarget() { m_target = { }; }
+    void setReferrer(const String& referrer) { m_referrer = referrer; }
     void setOrigin(const String& origin) { m_origin = origin; }
 
 private:
-    FormSubmission(Method, const URL& action, const String& target, const String& contentType, PassRefPtr<FormState>, PassRefPtr<FormData>, const String& boundary, LockHistory, PassRefPtr<Event>);
+    FormSubmission(Method, const URL& action, const String& target, const String& contentType, Ref<FormState>&&, Ref<FormData>&&, const String& boundary, LockHistory, Event*);
 
     // FIXME: Hold an instance of Attributes instead of individual members.
     Method m_method;
     URL m_action;
     String m_target;
     String m_contentType;
-    RefPtr<FormState> m_formState;
-    RefPtr<FormData> m_formData;
+    Ref<FormState> m_formState;
+    Ref<FormData> m_formData;
     String m_boundary;
     LockHistory m_lockHistory;
     RefPtr<Event> m_event;
index df1846a..496e72d 100644 (file)
@@ -364,17 +364,15 @@ void FrameLoader::urlSelected(const FrameLoadRequest& passedRequest, Event* trig
 
 void FrameLoader::submitForm(Ref<FormSubmission>&& submission)
 {
-    ASSERT(submission->method() == FormSubmission::PostMethod || submission->method() == FormSubmission::GetMethod);
+    ASSERT(submission->method() == FormSubmission::Method::Post || submission->method() == FormSubmission::Method::Get);
 
     // FIXME: Find a good spot for these.
-    ASSERT(submission->data());
-    ASSERT(submission->state());
-    ASSERT(!submission->state()->sourceDocument()->frame() || submission->state()->sourceDocument()->frame() == &m_frame);
+    ASSERT(!submission->state().sourceDocument().frame() || submission->state().sourceDocument().frame() == &m_frame);
 
     if (!m_frame.page())
         return;
 
-    if (submission->state()->sourceDocument()->pageCacheState() != Document::NotInPageCache)
+    if (submission->state().sourceDocument().pageCacheState() != Document::NotInPageCache)
         return;
 
     if (submission->action().isEmpty())
@@ -396,12 +394,12 @@ void FrameLoader::submitForm(Ref<FormSubmission>&& submission)
         return;
     }
 
-    Frame* targetFrame = findFrameForNavigation(submission->target(), submission->state()->sourceDocument());
+    Frame* targetFrame = findFrameForNavigation(submission->target(), &submission->state().sourceDocument());
     if (!targetFrame) {
         if (!DOMWindow::allowPopUp(&m_frame) && !ScriptController::processingUserGesture())
             return;
 
-        // FIXME: targetFrame can be 0 for two distinct reasons:
+        // FIXME: targetFrame can be null for two distinct reasons:
         // 1. The frame was not found by name, so we should try opening a new window.
         // 2. The frame was found, but navigating it was not allowed, e.g. by HTML5 sandbox or by origin checks.
         // Continuing form submission makes no sense in the latter case.
@@ -432,7 +430,7 @@ void FrameLoader::submitForm(Ref<FormSubmission>&& submission)
         m_submittedFormURL = submission->requestURL();
     }
 
-    submission->data()->generateFiles(m_frame.document());
+    submission->data().generateFiles(m_frame.document());
     submission->setReferrer(outgoingReferrer());
     submission->setOrigin(outgoingOrigin());
 
@@ -658,20 +656,18 @@ void FrameLoader::receivedFirstData()
     if (!m_documentLoader)
         return;
 
+    ASSERT(m_frame.document());
+    auto& document = *m_frame.document();
+
     double delay;
     String urlString;
     if (!parseHTTPRefresh(m_documentLoader->response().httpHeaderField(HTTPHeaderName::Refresh), delay, urlString))
         return;
-    URL completedURL;
-    if (urlString.isEmpty())
-        completedURL = m_frame.document()->url();
-    else
-        completedURL = m_frame.document()->completeURL(urlString);
-
+    auto completedURL = urlString.isEmpty() ? document.url() : document.completeURL(urlString);
     if (!protocolIsJavaScript(completedURL))
-        m_frame.navigationScheduler().scheduleRedirect(m_frame.document(), delay, completedURL);
+        m_frame.navigationScheduler().scheduleRedirect(document, delay, completedURL);
     else {
-        String message = "Refused to refresh " + m_frame.document()->url().stringCenterEllipsizedToLength() + " to a javascript: URL";
+        auto message = "Refused to refresh " + document.url().stringCenterEllipsizedToLength() + " to a javascript: URL";
         m_frame.document()->addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
     }
 }
@@ -1137,7 +1133,7 @@ void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, Event* event
         || event->target()->toNode()->document().pageCacheState() == Document::NotInPageCache);
 
     // Protect frame from getting blown away inside dispatchBeforeLoadEvent in loadWithDocumentLoader.
-    Ref<Frame> protect(m_frame);
+    auto protectFrame = makeRef(m_frame);
 
     URL url = request.resourceRequest().url();
 
@@ -1170,7 +1166,7 @@ void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, Event* event
 
     // FIXME: It's possible this targetFrame will not be the same frame that was targeted by the actual
     // load if frame names have changed.
-    Frame* sourceFrame = formState ? formState->sourceDocument()->frame() : &m_frame;
+    Frame* sourceFrame = formState ? formState->sourceDocument().frame() : &m_frame;
     if (!sourceFrame)
         sourceFrame = &m_frame;
     Frame* targetFrame = sourceFrame->loader().findFrameForNavigation(request.frameName());
@@ -1254,7 +1250,7 @@ void FrameLoader::loadURL(const FrameLoadRequest& frameLoadRequest, const String
         oldDocumentLoader->setLastCheckedRequest(ResourceRequest());
         policyChecker().stopCheck();
         policyChecker().setLoadType(newLoadType);
-        policyChecker().checkNavigationPolicy(request, false /* didReceiveRedirectResponse */, oldDocumentLoader.get(), formState, [this](const ResourceRequest& request, FormState*, bool shouldContinue) {
+        policyChecker().checkNavigationPolicy(request, false /* didReceiveRedirectResponse */, oldDocumentLoader.get(), formState, [this] (const ResourceRequest& request, FormState*, bool shouldContinue) {
             continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
         });
         return;
@@ -1450,7 +1446,7 @@ void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType t
         oldDocumentLoader->setTriggeringAction(action);
         oldDocumentLoader->setLastCheckedRequest(ResourceRequest());
         policyChecker().stopCheck();
-        policyChecker().checkNavigationPolicy(loader->request(), false /* didReceiveRedirectResponse */, oldDocumentLoader.get(), formState, [this](const ResourceRequest& request, FormState*, bool shouldContinue) {
+        policyChecker().checkNavigationPolicy(loader->request(), false /* didReceiveRedirectResponse */, oldDocumentLoader.get(), formState, [this] (const ResourceRequest& request, FormState*, bool shouldContinue) {
             continueFragmentScrollAfterNavigationPolicy(request, shouldContinue);
         });
         return;
@@ -1477,7 +1473,7 @@ void FrameLoader::loadWithDocumentLoader(DocumentLoader* loader, FrameLoadType t
         }
     }
 
-    policyChecker().checkNavigationPolicy(loader->request(), false /* didReceiveRedirectResponse */, loader, formState, [this, allowNavigationToInvalidURL](const ResourceRequest& request, FormState* formState, bool shouldContinue) {
+    policyChecker().checkNavigationPolicy(loader->request(), false /* didReceiveRedirectResponse */, loader, formState, [this, allowNavigationToInvalidURL] (const ResourceRequest& request, FormState* formState, bool shouldContinue) {
         continueLoadAfterNavigationPolicy(request, formState, shouldContinue, allowNavigationToInvalidURL);
     });
 }
@@ -2709,7 +2705,7 @@ void FrameLoader::loadPostRequest(const FrameLoadRequest& request, const String&
             return;
         }
 
-        policyChecker().checkNewWindowPolicy(action, workingResourceRequest, WTFMove(formState), frameName, [this, allowNavigationToInvalidURL, openerPolicy](const ResourceRequest& request, FormState* formState, const String& frameName, const NavigationAction& action, bool shouldContinue) {
+        policyChecker().checkNewWindowPolicy(action, workingResourceRequest, WTFMove(formState), frameName, [this, allowNavigationToInvalidURL, openerPolicy] (const ResourceRequest& request, FormState* formState, const String& frameName, const NavigationAction& action, bool shouldContinue) {
             continueLoadAfterNewWindowPolicy(request, formState, frameName, action, shouldContinue, allowNavigationToInvalidURL, openerPolicy);
         });
         return;
@@ -2767,11 +2763,11 @@ unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& requ
     if (error.isNull()) {
         ASSERT(!newRequest.isNull());
 
-        if (!documentLoader()->applicationCacheHost()->maybeLoadSynchronously(newRequest, error, response, data)) {
+        if (!documentLoader()->applicationCacheHost().maybeLoadSynchronously(newRequest, error, response, data)) {
             Vector<char> buffer;
             platformStrategies()->loaderStrategy()->loadResourceSynchronously(networkingContext(), identifier, newRequest, storedCredentials, clientCredentialPolicy, error, response, buffer);
             data = SharedBuffer::adoptVector(buffer);
-            documentLoader()->applicationCacheHost()->maybeLoadFallbackSynchronously(newRequest, error, response, data);
+            documentLoader()->applicationCacheHost().maybeLoadFallbackSynchronously(newRequest, error, response, data);
             ResourceLoadObserver::sharedObserver().logSubresourceLoading(&m_frame, newRequest, response);
         }
     }
@@ -3106,7 +3102,7 @@ void FrameLoader::continueLoadAfterNavigationPolicy(const ResourceRequest& reque
         return;
     }
 
-    m_client.dispatchWillSubmitForm(formState, [this](PolicyAction action) {
+    m_client.dispatchWillSubmitForm(*formState, [this] (PolicyAction action) {
         policyChecker().continueLoadAfterWillSubmitForm(action);
     });
 }
index d13b0a0..a80947b 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2016 Apple Inc. All rights reserved.
+ * Copyright (C) 2006-2017 Apple Inc. All rights reserved.
  * Copyright (C) 2012 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -177,14 +177,14 @@ public:
     virtual void dispatchShow() = 0;
 
     virtual void dispatchDecidePolicyForResponse(const ResourceResponse&, const ResourceRequest&, FramePolicyFunction) = 0;
-    virtual void dispatchDecidePolicyForNewWindowAction(const NavigationAction&, const ResourceRequest&, PassRefPtr<FormState>, const String& frameName, FramePolicyFunction) = 0;
-    virtual void dispatchDecidePolicyForNavigationAction(const NavigationAction&, const ResourceRequest&, PassRefPtr<FormState>, FramePolicyFunction) = 0;
+    virtual void dispatchDecidePolicyForNewWindowAction(const NavigationAction&, const ResourceRequest&, FormState*, const String& frameName, FramePolicyFunction) = 0;
+    virtual void dispatchDecidePolicyForNavigationAction(const NavigationAction&, const ResourceRequest&, FormState*, FramePolicyFunction) = 0;
     virtual void cancelPolicyCheck() = 0;
 
     virtual void dispatchUnableToImplementPolicy(const ResourceError&) = 0;
 
-    virtual void dispatchWillSendSubmitEvent(PassRefPtr<FormState>) = 0;
-    virtual void dispatchWillSubmitForm(PassRefPtr<FormState>, FramePolicyFunction) = 0;
+    virtual void dispatchWillSendSubmitEvent(Ref<FormState>&&) = 0;
+    virtual void dispatchWillSubmitForm(FormState&, FramePolicyFunction) = 0;
 
     virtual void revertToProvisionalState(DocumentLoader*) = 0;
     virtual void setMainDocumentError(DocumentLoader*, const ResourceError&) = 0;
@@ -272,14 +272,12 @@ public:
     virtual bool canCachePage() const = 0;
     virtual void convertMainResourceLoadToDownload(DocumentLoader*, SessionID, const ResourceRequest&, const ResourceResponse&) = 0;
 
-    virtual RefPtr<Frame> createFrame(const URL&, const String& name, HTMLFrameOwnerElement*, const String& referrer, bool allowsScrolling, int marginWidth, int marginHeight) = 0;
-    virtual RefPtr<Widget> createPlugin(const IntSize&, HTMLPlugInElement*, const URL&, const Vector<String>&, const Vector<String>&, const String&, bool loadManually) = 0;
+    virtual RefPtr<Frame> createFrame(const URL&, const String& name, HTMLFrameOwnerElement&, const String& referrer, bool allowsScrolling, int marginWidth, int marginHeight) = 0;
+    virtual RefPtr<Widget> createPlugin(const IntSize&, HTMLPlugInElement&, const URL&, const Vector<String>&, const Vector<String>&, const String&, bool loadManually) = 0;
     virtual void recreatePlugin(Widget*) = 0;
     virtual void redirectDataToPlugin(Widget* pluginWidget) = 0;
 
-    virtual PassRefPtr<Widget> createJavaAppletWidget(const IntSize&, HTMLAppletElement*, const URL& baseURL, const Vector<String>& paramNames, const Vector<String>& paramValues) = 0;
-
-    virtual void dispatchDidFailToStartPlugin(const PluginViewBase*) const { }
+    virtual RefPtr<Widget> createJavaAppletWidget(const IntSize&, HTMLAppletElement&, const URL& baseURL, const Vector<String>& paramNames, const Vector<String>& paramValues) = 0;
 
     virtual ObjectContentType objectContentType(const URL&, const String& mimeType) = 0;
     virtual String overrideMediaType() const = 0;
@@ -294,6 +292,7 @@ public:
     virtual NSCachedURLResponse* willCacheResponse(DocumentLoader*, unsigned long identifier, NSCachedURLResponse*) const = 0;
     virtual NSDictionary *dataDetectionContext() { return nullptr; }
 #endif
+
 #if PLATFORM(WIN) && USE(CFURLCONNECTION)
     // FIXME: Windows should use willCacheResponse - <https://bugs.webkit.org/show_bug.cgi?id=57257>.
     virtual bool shouldCacheResponse(DocumentLoader*, unsigned long identifier, const ResourceResponse&, const unsigned char* data, unsigned long long length) = 0;
@@ -309,10 +308,10 @@ public:
     // Clients that generally disallow universal access can make exceptions for particular URLs.
     virtual bool shouldForceUniversalAccessFromLocalURL(const URL&) { return false; }
 
-    virtual PassRefPtr<FrameNetworkingContext> createNetworkingContext() = 0;
+    virtual Ref<FrameNetworkingContext> createNetworkingContext() = 0;
 
 #if ENABLE(REQUEST_AUTOCOMPLETE)
-    virtual void didRequestAutocomplete(PassRefPtr<FormState>) = 0;
+    virtual void didRequestAutocomplete(Ref<FormState>&&) = 0;
 #endif
 
     virtual bool shouldPaintBrokenImage(const URL&) const { return true; }
index 071bb85..09b8d66 100644 (file)
@@ -845,7 +845,7 @@ void HistoryController::updateCurrentItem()
     }
 }
 
-void HistoryController::pushState(PassRefPtr<SerializedScriptValue> stateObject, const String& title, const String& urlString)
+void HistoryController::pushState(RefPtr<SerializedScriptValue>&& stateObject, const String& title, const String& urlString)
 {
     if (!m_currentItem)
         return;
@@ -859,7 +859,7 @@ void HistoryController::pushState(PassRefPtr<SerializedScriptValue> stateObject,
     // Override data in the current item (created by createItemTree) to reflect
     // the pushState() arguments.
     m_currentItem->setTitle(title);
-    m_currentItem->setStateObject(stateObject);
+    m_currentItem->setStateObject(WTFMove(stateObject));
     m_currentItem->setURLString(urlString);
 
     LOG(History, "HistoryController %p pushState: Adding top item %p, setting url of current item %p to %s", this, topItem.ptr(), m_currentItem.get(), urlString.ascii().data());
@@ -873,7 +873,7 @@ void HistoryController::pushState(PassRefPtr<SerializedScriptValue> stateObject,
     m_frame.loader().client().updateGlobalHistory();
 }
 
-void HistoryController::replaceState(PassRefPtr<SerializedScriptValue> stateObject, const String& title, const String& urlString)
+void HistoryController::replaceState(RefPtr<SerializedScriptValue>&& stateObject, const String& title, const String& urlString)
 {
     if (!m_currentItem)
         return;
@@ -883,7 +883,7 @@ void HistoryController::replaceState(PassRefPtr<SerializedScriptValue> stateObje
     if (!urlString.isEmpty())
         m_currentItem->setURLString(urlString);
     m_currentItem->setTitle(title);
-    m_currentItem->setStateObject(stateObject);
+    m_currentItem->setStateObject(WTFMove(stateObject));
     m_currentItem->setFormData(nullptr);
     m_currentItem->setFormContentType(String());
 
index 10ff1f1..3d25e28 100644 (file)
@@ -84,8 +84,8 @@ public:
     HistoryItem* provisionalItem() const { return m_provisionalItem.get(); }
     void setProvisionalItem(HistoryItem*);
 
-    void pushState(PassRefPtr<SerializedScriptValue>, const String& title, const String& url);
-    void replaceState(PassRefPtr<SerializedScriptValue>, const String& title, const String& url);
+    void pushState(RefPtr<SerializedScriptValue>&&, const String& title, const String& url);
+    void replaceState(RefPtr<SerializedScriptValue>&&, const String& title, const String& url);
 
     void setDefersLoading(bool);
 
index 1c3beab..57914ef 100644 (file)
@@ -177,7 +177,7 @@ void ImageLoader::updateFromElement()
         options.sameOriginDataURLFlag = SameOriginDataURLFlag::Set;
 
         CachedResourceRequest request(ResourceRequest(document.completeURL(sourceURI(attr))), options);
-        request.setInitiator(&element());
+        request.setInitiator(element());
 
         request.setAsPotentiallyCrossOrigin(element().attributeWithoutSynchronization(HTMLNames::crossoriginAttr), document);
 
index 7effad7..5697753 100644 (file)
@@ -68,6 +68,16 @@ public:
         , m_userGestureToForward(UserGestureIndicator::currentUserGesture())
     {
     }
+    ScheduledNavigation(double delay, LockHistory lockHistory, LockBackForwardList lockBackForwardList, bool wasDuringLoad, bool isLocationChange, ShouldOpenExternalURLsPolicy externalURLPolicy)
+        : m_delay(delay)
+        , m_lockHistory(lockHistory)
+        , m_lockBackForwardList(lockBackForwardList)
+        , m_wasDuringLoad(wasDuringLoad)
+        , m_isLocationChange(isLocationChange)
+        , m_userGestureToForward(UserGestureIndicator::currentUserGesture())
+        , m_shouldOpenExternalURLsPolicy(externalURLPolicy)
+    {
+    }
     virtual ~ScheduledNavigation() { }
 
     virtual void fire(Frame&) = 0;
@@ -81,12 +91,11 @@ public:
     LockBackForwardList lockBackForwardList() const { return m_lockBackForwardList; }
     bool wasDuringLoad() const { return m_wasDuringLoad; }
     bool isLocationChange() const { return m_isLocationChange; }
-    RefPtr<UserGestureToken> userGestureToForward() const { return m_userGestureToForward; }
+    UserGestureToken* userGestureToForward() const { return m_userGestureToForward.get(); }
 
 protected:
     void clearUserGesture() { m_userGestureToForward = nullptr; }
-
-    ShouldOpenExternalURLsPolicy m_shouldOpenExternalURLsPolicy { ShouldOpenExternalURLsPolicy::ShouldNotAllow };
+    ShouldOpenExternalURLsPolicy shouldOpenExternalURLs() const { return m_shouldOpenExternalURLsPolicy; }
 
 private:
     double m_delay;
@@ -95,19 +104,17 @@ private:
     bool m_wasDuringLoad;
     bool m_isLocationChange;
     RefPtr<UserGestureToken> m_userGestureToForward;
+    ShouldOpenExternalURLsPolicy m_shouldOpenExternalURLsPolicy { ShouldOpenExternalURLsPolicy::ShouldNotAllow };
 };
 
 class ScheduledURLNavigation : public ScheduledNavigation {
 protected:
-    ScheduledURLNavigation(Document* initiatingDocument, double delay, SecurityOrigin* securityOrigin, const URL& url, const String& referrer, LockHistory lockHistory, LockBackForwardList lockBackForwardList, bool duringLoad, bool isLocationChange)
-        : ScheduledNavigation(delay, lockHistory, lockBackForwardList, duringLoad, isLocationChange)
+    ScheduledURLNavigation(Document& initiatingDocument, double delay, SecurityOrigin* securityOrigin, const URL& url, const String& referrer, LockHistory lockHistory, LockBackForwardList lockBackForwardList, bool duringLoad, bool isLocationChange)
+        : ScheduledNavigation(delay, lockHistory, lockBackForwardList, duringLoad, isLocationChange, initiatingDocument.shouldOpenExternalURLsPolicyToPropagate())
         , m_securityOrigin(securityOrigin)
         , m_url(url)
         , m_referrer(referrer)
-        , m_haveToldClient(false)
     {
-        if (initiatingDocument)
-            m_shouldOpenExternalURLsPolicy = initiatingDocument->shouldOpenExternalURLsPolicyToPropagate();
     }
 
     void fire(Frame& frame) override
@@ -115,7 +122,7 @@ protected:
         UserGestureIndicator gestureIndicator(userGestureToForward());
 
         ResourceRequest resourceRequest(m_url, m_referrer, UseProtocolCachePolicy);
-        FrameLoadRequest frameRequest(m_securityOrigin.get(), resourceRequest, "_self", lockHistory(), lockBackForwardList(), MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Allow, m_shouldOpenExternalURLsPolicy);
+        FrameLoadRequest frameRequest(m_securityOrigin.get(), resourceRequest, "_self", lockHistory(), lockBackForwardList(), MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Allow, shouldOpenExternalURLs());
 
         frame.loader().changeLocation(frameRequest);
     }
@@ -152,12 +159,12 @@ private:
     RefPtr<SecurityOrigin> m_securityOrigin;
     URL m_url;
     String m_referrer;
-    bool m_haveToldClient;
+    bool m_haveToldClient { false };
 };
 
 class ScheduledRedirect : public ScheduledURLNavigation {
 public:
-    ScheduledRedirect(Document* initiatingDocument, double delay, SecurityOrigin* securityOrigin, const URL& url, LockHistory lockHistory, LockBackForwardList lockBackForwardList)
+    ScheduledRedirect(Document& initiatingDocument, double delay, SecurityOrigin* securityOrigin, const URL& url, LockHistory lockHistory, LockBackForwardList lockBackForwardList)
         : ScheduledURLNavigation(initiatingDocument, delay, securityOrigin, url, String(), lockHistory, lockBackForwardList, false, false)
     {
         clearUserGesture();
@@ -173,7 +180,7 @@ public:
         UserGestureIndicator gestureIndicator(userGestureToForward());
         bool refresh = equalIgnoringFragmentIdentifier(frame.document()->url(), url());
         ResourceRequest resourceRequest(url(), referrer(), refresh ? ReloadIgnoringCacheData : UseProtocolCachePolicy);
-        FrameLoadRequest frameRequest(securityOrigin(), resourceRequest, "_self", lockHistory(), lockBackForwardList(), MaybeSendReferrer, AllowNavigationToInvalidURL::No, NewFrameOpenerPolicy::Allow, m_shouldOpenExternalURLsPolicy);
+        FrameLoadRequest frameRequest(securityOrigin(), resourceRequest, "_self", lockHistory(), lockBackForwardList(), MaybeSendReferrer, AllowNavigationToInvalidURL::No, NewFrameOpenerPolicy::Allow, shouldOpenExternalURLs());
 
         frame.loader().changeLocation(frameRequest);
     }
@@ -181,7 +188,7 @@ public:
 
 class ScheduledLocationChange : public ScheduledURLNavigation {
 public:
-    ScheduledLocationChange(Document* initiatingDocument, SecurityOrigin* securityOrigin, const URL& url, const String& referrer, LockHistory lockHistory, LockBackForwardList lockBackForwardList, bool duringLoad)
+    ScheduledLocationChange(Document& initiatingDocument, SecurityOrigin* securityOrigin, const URL& url, const String& referrer, LockHistory lockHistory, LockBackForwardList lockBackForwardList, bool duringLoad)
         : ScheduledURLNavigation(initiatingDocument, 0.0, securityOrigin, url, referrer, lockHistory, lockBackForwardList, duringLoad, true) { }
 
     void fire(Frame& frame) override
@@ -189,14 +196,14 @@ public:
         UserGestureIndicator gestureIndicator(userGestureToForward());
 
         ResourceRequest resourceRequest(url(), referrer(), UseProtocolCachePolicy);
-        FrameLoadRequest frameRequest(securityOrigin(), resourceRequest, "_self", lockHistory(), lockBackForwardList(), MaybeSendReferrer, AllowNavigationToInvalidURL::No, NewFrameOpenerPolicy::Allow, m_shouldOpenExternalURLsPolicy);
+        FrameLoadRequest frameRequest(securityOrigin(), resourceRequest, "_self", lockHistory(), lockBackForwardList(), MaybeSendReferrer, AllowNavigationToInvalidURL::No, NewFrameOpenerPolicy::Allow, shouldOpenExternalURLs());
         frame.loader().changeLocation(frameRequest);
     }
 };
 
 class ScheduledRefresh : public ScheduledURLNavigation {
 public:
-    ScheduledRefresh(Document* initiatingDocument, SecurityOrigin* securityOrigin, const URL& url, const String& referrer)
+    ScheduledRefresh(Document& initiatingDocument, SecurityOrigin* securityOrigin, const URL& url, const String& referrer)
         : ScheduledURLNavigation(initiatingDocument, 0.0, securityOrigin, url, referrer, LockHistory::Yes, LockBackForwardList::Yes, false, true)
     {
     }
@@ -206,7 +213,7 @@ public:
         UserGestureIndicator gestureIndicator(userGestureToForward());
 
         ResourceRequest resourceRequest(url(), referrer(), ReloadIgnoringCacheData);
-        FrameLoadRequest frameRequest(securityOrigin(), resourceRequest, "_self", lockHistory(), lockBackForwardList(), MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Allow, m_shouldOpenExternalURLsPolicy);
+        FrameLoadRequest frameRequest(securityOrigin(), resourceRequest, "_self", lockHistory(), lockBackForwardList(), MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Allow, shouldOpenExternalURLs());
         frame.loader().changeLocation(frameRequest);
     }
 };
@@ -226,7 +233,7 @@ public:
         if (!m_historySteps) {
             // Special case for go(0) from a frame -> reload only the frame
             // To follow Firefox and IE's behavior, history reload can only navigate the self frame.
-            frame.loader().urlSelected(frame.document()->url(), "_self", 0, lockHistory(), lockBackForwardList(), MaybeSendReferrer, m_shouldOpenExternalURLsPolicy);
+            frame.loader().urlSelected(frame.document()->url(), "_self", 0, lockHistory(), lockBackForwardList(), MaybeSendReferrer, shouldOpenExternalURLs());
             return;
         }
         
@@ -241,15 +248,10 @@ private:
 
 class ScheduledFormSubmission : public ScheduledNavigation {
 public:
-    ScheduledFormSubmission(PassRefPtr<FormSubmission> submission, LockBackForwardList lockBackForwardList, bool duringLoad)
-        : ScheduledNavigation(0, submission->lockHistory(), lockBackForwardList, duringLoad, true)
-        , m_submission(submission)
-        , m_haveToldClient(false)
+    ScheduledFormSubmission(Ref<FormSubmission>&& submission, LockBackForwardList lockBackForwardList, bool duringLoad)
+        : ScheduledNavigation(0, submission->lockHistory(), lockBackForwardList, duringLoad, true, submission->state().sourceDocument().shouldOpenExternalURLsPolicyToPropagate())
+        , m_submission(WTFMove(submission))
     {
-        ASSERT(m_submission->state());
-
-        if (Document* document = m_submission->state()->sourceDocument())
-            m_shouldOpenExternalURLsPolicy = document->shouldOpenExternalURLsPolicyToPropagate();
     }
 
     void fire(Frame& frame) override
@@ -260,14 +262,14 @@ public:
         // Now that the timer has fired, we need to repeat the security check which normally is done when
         // selecting a target, in case conditions have changed. Other code paths avoid this by targeting
         // without leaving a time window. If we fail the check just silently drop the form submission.
-        Document* requestingDocument = m_submission->state()->sourceDocument();
-        if (!requestingDocument->canNavigate(&frame))
+        auto& requestingDocument = m_submission->state().sourceDocument();
+        if (!requestingDocument.canNavigate(&frame))
             return;
-        FrameLoadRequest frameRequest(requestingDocument->securityOrigin(), lockHistory(), lockBackForwardList(), MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Allow, m_shouldOpenExternalURLsPolicy);
+        FrameLoadRequest frameRequest(requestingDocument.securityOrigin(), lockHistory(), lockBackForwardList(), MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Allow, shouldOpenExternalURLs());
         m_submission->populateFrameLoadRequest(frameRequest);
-        frame.loader().loadFrameRequest(frameRequest, m_submission->event(), m_submission->state());
+        frame.loader().loadFrameRequest(frameRequest, m_submission->event(), &m_submission->state());
     }
-    
+
     void didStartTimer(Frame& frame, Timer& timer) override
     {
         if (m_haveToldClient)
@@ -293,8 +295,8 @@ public:
     }
 
 private:
-    RefPtr<FormSubmission> m_submission;
-    bool m_haveToldClient;
+    Ref<FormSubmission> m_submission;
+    bool m_haveToldClient { false };
 };
 
 class ScheduledPageBlock final : public ScheduledNavigation {
@@ -313,7 +315,7 @@ public:
         SubstituteData replacementData(SharedBuffer::create(), m_originDocument.url(), replacementResponse, SubstituteData::SessionHistoryVisibility::Hidden);
 
         ResourceRequest resourceRequest(m_originDocument.url(), emptyString(), ReloadIgnoringCacheData);
-        FrameLoadRequest frameRequest(m_originDocument.securityOrigin(), resourceRequest, lockHistory(), lockBackForwardList(), MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Allow, m_shouldOpenExternalURLsPolicy);
+        FrameLoadRequest frameRequest(m_originDocument.securityOrigin(), resourceRequest, lockHistory(), lockBackForwardList(), MaybeSendReferrer, AllowNavigationToInvalidURL::Yes, NewFrameOpenerPolicy::Allow, shouldOpenExternalURLs());
         frameRequest.setSubstituteData(replacementData);
         frame.loader().load(frameRequest);
     }
@@ -364,7 +366,7 @@ inline bool NavigationScheduler::shouldScheduleNavigation(const URL& url) const
     return NavigationDisablerForBeforeUnload::isNavigationAllowed();
 }
 
-void NavigationScheduler::scheduleRedirect(Document* initiatingDocument, double delay, const URL& url)
+void NavigationScheduler::scheduleRedirect(Document& initiatingDocument, double delay, const URL& url)
 {
     if (!shouldScheduleNavigation(url))
         return;
@@ -375,7 +377,7 @@ void NavigationScheduler::scheduleRedirect(Document* initiatingDocument, double
 
     // We want a new back/forward list item if the refresh timeout is > 1 second.
     if (!m_redirect || delay <= m_redirect->delay()) {
-        LockBackForwardList lockBackForwardList = delay <= 1 ? LockBackForwardList::Yes : LockBackForwardList::No;
+        auto lockBackForwardList = delay <= 1 ? LockBackForwardList::Yes : LockBackForwardList::No;
         schedule(std::make_unique<ScheduledRedirect>(initiatingDocument, delay, m_frame.document()->securityOrigin(), url, LockHistory::Yes, lockBackForwardList));
     }
 }
@@ -398,7 +400,7 @@ LockBackForwardList NavigationScheduler::mustLockBackForwardList(Frame& targetFr
     return LockBackForwardList::No;
 }
 
-void NavigationScheduler::scheduleLocationChange(Document* initiatingDocument, SecurityOrigin* securityOrigin, const URL& url, const String& referrer, LockHistory lockHistory, LockBackForwardList lockBackForwardList)
+void NavigationScheduler::scheduleLocationChange(Document& initiatingDocument, SecurityOrigin* securityOrigin, const URL& url, const String& referrer, LockHistory lockHistory, LockBackForwardList lockBackForwardList)
 {
     if (!shouldScheduleNavigation(url))
         return;
@@ -412,10 +414,7 @@ void NavigationScheduler::scheduleLocationChange(Document* initiatingDocument, S
     // fragment part, we don't need to schedule the location change.
     if (url.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(m_frame.document()->url(), url)) {
         ResourceRequest resourceRequest(m_frame.document()->completeURL(url), referrer, UseProtocolCachePolicy);
-        ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy = ShouldOpenExternalURLsPolicy::ShouldNotAllow;
-        if (initiatingDocument)
-            shouldOpenExternalURLsPolicy = initiatingDocument->shouldOpenExternalURLsPolicyToPropagate();
-        FrameLoadRequest frameRequest(securityOrigin, resourceRequest, "_self", lockHistory, lockBackForwardList, MaybeSendReferrer, AllowNavigationToInvalidURL::No, NewFrameOpenerPolicy::Allow, ReplaceDocumentIfJavaScriptURL, shouldOpenExternalURLsPolicy);
+        FrameLoadRequest frameRequest(securityOrigin, resourceRequest, "_self", lockHistory, lockBackForwardList, MaybeSendReferrer, AllowNavigationToInvalidURL::No, NewFrameOpenerPolicy::Allow, ReplaceDocumentIfJavaScriptURL, initiatingDocument.shouldOpenExternalURLsPolicyToPropagate());
         loader.changeLocation(frameRequest);
         return;
     }
@@ -427,7 +426,7 @@ void NavigationScheduler::scheduleLocationChange(Document* initiatingDocument, S
     schedule(std::make_unique<ScheduledLocationChange>(initiatingDocument, securityOrigin, url, referrer, lockHistory, lockBackForwardList, duringLoad));
 }
 
-void NavigationScheduler::scheduleFormSubmission(PassRefPtr<FormSubmission> submission)
+void NavigationScheduler::scheduleFormSubmission(Ref<FormSubmission>&& submission)
 {
     ASSERT(m_frame.page());
 
@@ -443,14 +442,14 @@ void NavigationScheduler::scheduleFormSubmission(PassRefPtr<FormSubmission> subm
     // See https://bugs.webkit.org/show_bug.cgi?id=32383 for the original motivation for this.
     LockBackForwardList lockBackForwardList = mustLockBackForwardList(m_frame);
     if (lockBackForwardList == LockBackForwardList::No
-        && (submission->state()->formSubmissionTrigger() == SubmittedByJavaScript && m_frame.tree().parent() && !UserGestureIndicator::processingUserGesture())) {
+        && (submission->state().formSubmissionTrigger() == SubmittedByJavaScript && m_frame.tree().parent() && !UserGestureIndicator::processingUserGesture())) {
         lockBackForwardList = LockBackForwardList::Yes;
     }
     
-    schedule(std::make_unique<ScheduledFormSubmission>(submission, lockBackForwardList, duringLoad));
+    schedule(std::make_unique<ScheduledFormSubmission>(WTFMove(submission), lockBackForwardList, duringLoad));
 }
 
-void NavigationScheduler::scheduleRefresh(Document* initiatingDocument)
+void NavigationScheduler::scheduleRefresh(Document& initiatingDocument)
 {
     if (!shouldScheduleNavigation())
         return;
index 49c43be..0ae1711 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2016 Apple Inc. All rights reserved.
+ * Copyright (C) 2006-2017 Apple Inc. All rights reserved.
  * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
  * Copyright (C) 2009 Adam Barth. All rights reserved.
  *
@@ -68,10 +68,10 @@ public:
     bool redirectScheduledDuringLoad();
     bool locationChangePending();
 
-    void scheduleRedirect(Document* initiatingDocument, double delay, const URL&);
-    void scheduleLocationChange(Document* initiatingDocument, SecurityOrigin*, const URL&, const String& referrer, LockHistory = LockHistory::Yes, LockBackForwardList = LockBackForwardList::Yes);
-    void scheduleFormSubmission(PassRefPtr<FormSubmission>);
-    void scheduleRefresh(Document* initiatingDocument);
+    void scheduleRedirect(Document& initiatingDocument, double delay, const URL&);
+    void scheduleLocationChange(Document& initiatingDocument, SecurityOrigin*, const URL&, const String& referrer, LockHistory = LockHistory::Yes, LockBackForwardList = LockBackForwardList::Yes);
+    void scheduleFormSubmission(Ref<FormSubmission>&&);
+    void scheduleRefresh(Document& initiatingDocument);
     void scheduleHistoryNavigation(int steps);
     void schedulePageBlock(Document& originDocument);
 
index bb6f9cc..cecd157 100644 (file)
@@ -191,7 +191,7 @@ void ResourceLoader::start()
         return;
 #endif
 
-    if (m_documentLoader->applicationCacheHost()->maybeLoadResource(*this, m_request, m_request.url()))
+    if (m_documentLoader->applicationCacheHost().maybeLoadResource(*this, m_request, m_request.url()))
         return;
 
     if (m_defersLoading) {
@@ -607,7 +607,7 @@ ResourceError ResourceLoader::cannotShowURLError()
 
 ResourceRequest ResourceLoader::willSendRequest(ResourceHandle*, ResourceRequest&& request, ResourceResponse&& redirectResponse)
 {
-    if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForRedirect(this, request, redirectResponse))
+    if (documentLoader()->applicationCacheHost().maybeLoadFallbackForRedirect(this, request, redirectResponse))
         return WTFMove(request);
     willSendRequestInternal(request, redirectResponse);
     return WTFMove(request);
@@ -620,7 +620,7 @@ void ResourceLoader::didSendData(ResourceHandle*, unsigned long long bytesSent,
 
 void ResourceLoader::didReceiveResponse(ResourceHandle*, ResourceResponse&& response)
 {
-    if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForResponse(this, response))
+    if (documentLoader()->applicationCacheHost().maybeLoadFallbackForResponse(this, response))
         return;
     didReceiveResponse(response);
 }
@@ -642,7 +642,7 @@ void ResourceLoader::didFinishLoading(ResourceHandle*, double finishTime)
 
 void ResourceLoader::didFail(ResourceHandle*, const ResourceError& error)
 {
-    if (documentLoader()->applicationCacheHost()->maybeLoadFallbackForError(this, error))
+    if (documentLoader()->applicationCacheHost().maybeLoadFallbackForError(this, error))
         return;
     didFail(error);
 }
index 7fd056d..30591bd 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2016 Apple Inc. All rights reserved.
+ * Copyright (C) 2006-2017 Apple Inc. All rights reserved.
  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
  * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
  * Copyright (C) 2008 Alp Toker <alp@atoker.com>
@@ -107,23 +107,25 @@ bool SubframeLoader::resourceWillUsePlugin(const String& url, const String& mime
 
 bool SubframeLoader::pluginIsLoadable(const URL& url, const String& mimeType)
 {
+    auto* document = m_frame.document();
+
     if (MIMETypeRegistry::isJavaAppletMIMEType(mimeType)) {
         if (!m_frame.settings().isJavaEnabled())
             return false;
-        if (document() && document()->securityOrigin()->isLocal() && !m_frame.settings().isJavaEnabledForLocalFiles())
+        if (document && document->securityOrigin()->isLocal() && !m_frame.settings().isJavaEnabledForLocalFiles())
             return false;
     }
 
-    if (document()) {
-        if (document()->isSandboxed(SandboxPlugins))
+    if (document) {
+        if (document->isSandboxed(SandboxPlugins))
             return false;
 
-        if (!document()->securityOrigin()->canDisplay(url)) {
+        if (!document->securityOrigin()->canDisplay(url)) {
             FrameLoader::reportLocalLoadFailed(&m_frame, url.string());
             return false;
         }
 
-        if (!m_frame.loader().mixedContentChecker().canRunInsecureContent(document()->securityOrigin(), url))
+        if (!m_frame.loader().mixedContentChecker().canRunInsecureContent(document->securityOrigin(), url))
             return false;
     }
 
@@ -204,18 +206,20 @@ bool SubframeLoader::requestObject(HTMLPlugInImageElement& ownerElement, const S
     if (url.isEmpty() && mimeType.isEmpty())
         return false;
 
+    auto& document = ownerElement.document();
+
     URL completedURL;
     if (!url.isEmpty())
         completedURL = completeURL(url);
 
-    document()->contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(completedURL, ContentSecurityPolicy::InsecureRequestType::Load);
+    document.contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(completedURL, ContentSecurityPolicy::InsecureRequestType::Load);
 
     bool hasFallbackContent = is<HTMLObjectElement>(ownerElement) && downcast<HTMLObjectElement>(ownerElement).hasFallbackContent();
 
     bool useFallback;
     if (shouldUsePlugin(completedURL, mimeType, hasFallbackContent, useFallback)) {
         bool success = requestPlugin(ownerElement, completedURL, mimeType, paramNames, paramValues, useFallback);
-        logPluginRequest(document()->page(), mimeType, completedURL, success);
+        logPluginRequest(document.page(), mimeType, completedURL, success);
         return success;
     }
 
@@ -225,7 +229,7 @@ bool SubframeLoader::requestObject(HTMLPlugInImageElement& ownerElement, const S
     return loadOrRedirectSubframe(ownerElement, completedURL, frameName, LockHistory::Yes, LockBackForwardList::Yes);
 }
 
-PassRefPtr<Widget> SubframeLoader::createJavaAppletWidget(const IntSize& size, HTMLAppletElement& element, const Vector<String>& paramNames, const Vector<String>& paramValues)
+RefPtr<Widget> SubframeLoader::createJavaAppletWidget(const IntSize& size, HTMLAppletElement& element, const Vector<String>& paramNames, const Vector<String>& paramValues)
 {
     String baseURLString;
     String codeBaseURLString;
@@ -254,14 +258,14 @@ PassRefPtr<Widget> SubframeLoader::createJavaAppletWidget(const IntSize& size, H
     }
 
     if (baseURLString.isEmpty())
-        baseURLString = m_frame.document()->baseURL().string();
+        baseURLString = element.document().baseURL().string();
     URL baseURL = completeURL(baseURLString);
 
     RefPtr<Widget> widget;
     if (allowPlugins())
-        widget = m_frame.loader().client().createJavaAppletWidget(size, &element, baseURL, paramNames, paramValues);
+        widget = m_frame.loader().client().createJavaAppletWidget(size, element, baseURL, paramNames, paramValues);
 
-    logPluginRequest(document()->page(), element.serviceType(), String(), widget);
+    logPluginRequest(m_frame.page(), element.serviceType(), String(), widget);
 
     if (!widget) {
         RenderEmbeddedObject* renderer = element.renderEmbeddedObject();
@@ -275,16 +279,18 @@ PassRefPtr<Widget> SubframeLoader::createJavaAppletWidget(const IntSize& size, H
     return widget;
 }
 
-Frame* SubframeLoader::loadOrRedirectSubframe(HTMLFrameOwnerElement& ownerElement, const URL& requestUrl, const AtomicString& frameName, LockHistory lockHistory, LockBackForwardList lockBackForwardList)
+Frame* SubframeLoader::loadOrRedirectSubframe(HTMLFrameOwnerElement& ownerElement, const URL& requestURL, const AtomicString& frameName, LockHistory lockHistory, LockBackForwardList lockBackForwardList)
 {
-    URL url = requestUrl;
-    ownerElement.document().contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(url, ContentSecurityPolicy::InsecureRequestType::Load);
+    auto& initiatingDocument = ownerElement.document();
+
+    URL upgradedRequestURL = requestURL;
+    initiatingDocument.contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(upgradedRequestURL, ContentSecurityPolicy::InsecureRequestType::Load);
 
-    Frame* frame = ownerElement.contentFrame();
+    auto* frame = ownerElement.contentFrame();
     if (frame)
-        frame->navigationScheduler().scheduleLocationChange(m_frame.document(), m_frame.document()->securityOrigin(), url, m_frame.loader().outgoingReferrer(), lockHistory, lockBackForwardList);
+        frame->navigationScheduler().scheduleLocationChange(initiatingDocument, initiatingDocument.securityOrigin(), upgradedRequestURL, m_frame.loader().outgoingReferrer(), lockHistory, lockBackForwardList);
     else
-        frame = loadSubframe(ownerElement, url, frameName, m_frame.loader().outgoingReferrer());
+        frame = loadSubframe(ownerElement, upgradedRequestURL, frameName, m_frame.loader().outgoingReferrer());
 
     if (!frame)
         return nullptr;
@@ -301,13 +307,15 @@ Frame* SubframeLoader::loadSubframe(HTMLFrameOwnerElement& ownerElement, const U
     int marginWidth = -1;
     int marginHeight = -1;
     if (is<HTMLFrameElementBase>(ownerElement)) {
-        HTMLFrameElementBase& frameElementBase = downcast<HTMLFrameElementBase>(ownerElement);
+        auto& frameElementBase = downcast<HTMLFrameElementBase>(ownerElement);
         allowsScrolling = frameElementBase.scrollingMode() != ScrollbarAlwaysOff;
         marginWidth = frameElementBase.marginWidth();
         marginHeight = frameElementBase.marginHeight();
     }
 
-    if (!ownerElement.document().securityOrigin()->canDisplay(url)) {
+    auto document = makeRef(ownerElement.document());
+
+    if (!document->securityOrigin()->canDisplay(url)) {
         FrameLoader::reportLocalLoadFailed(&m_frame, url.string());
         return nullptr;
     }
@@ -315,20 +323,20 @@ Frame* SubframeLoader::loadSubframe(HTMLFrameOwnerElement& ownerElement, const U
     if (!SubframeLoadingDisabler::canLoadFrame(ownerElement))
         return nullptr;
 
-    String referrerToUse = SecurityPolicy::generateReferrerHeader(ownerElement.document().referrerPolicy(), url, referrer);
+    String referrerToUse = SecurityPolicy::generateReferrerHeader(document->referrerPolicy(), url, referrer);
 
     // Prevent initial empty document load from triggering load events.
-    m_frame.document()->incrementLoadEventDelayCount();
+    document->incrementLoadEventDelayCount();
 
-    RefPtr<Frame> frame = m_frame.loader().client().createFrame(url, name, &ownerElement, referrerToUse, allowsScrolling, marginWidth, marginHeight);
+    auto frame = m_frame.loader().client().createFrame(url, name, ownerElement, referrerToUse, allowsScrolling, marginWidth, marginHeight);
 
-    m_frame.document()->decrementLoadEventDelayCount();
+    document->decrementLoadEventDelayCount();
 
     if (!frame)  {
         m_frame.loader().checkCallImplicitClose();
         return nullptr;
     }
-    
+
     // All new frames will have m_isComplete set to true at this point due to synchronously loading
     // an empty document in FrameLoader::init(). But many frames will now be starting an
     // asynchronous load of url, so we set m_isComplete to false and then check if the load is
@@ -338,12 +346,12 @@ Frame* SubframeLoader::loadSubframe(HTMLFrameOwnerElement& ownerElement, const U
     frame->loader().started();
    
     auto* renderer = ownerElement.renderer();
-    FrameView* view = frame->view();
+    auto* view = frame->view();
     if (is<RenderWidget>(renderer) && view)
         downcast<RenderWidget>(*renderer).setWidget(view);
-    
+
     m_frame.loader().checkCallImplicitClose();
-    
+
     // Some loads are performed synchronously (e.g., about:blank and loads
     // cancelled by returning a null ResourceRequest from requestFromDelegate).
     // In these cases, the synchronous load would have finished
@@ -379,17 +387,14 @@ bool SubframeLoader::shouldUsePlugin(const URL& url, const String& mimeType, boo
     return objectType == ObjectContentType::None || objectType == ObjectContentType::PlugIn;
 }
 
-Document* SubframeLoader::document() const
-{
-    return m_frame.document();
-}
-
 bool SubframeLoader::loadPlugin(HTMLPlugInImageElement& pluginElement, const URL& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback)
 {
     if (useFallback)
         return false;
 
-    RenderEmbeddedObject* renderer = pluginElement.renderEmbeddedObject();
+    auto& document = pluginElement.document();
+    auto* renderer = pluginElement.renderEmbeddedObject();
+
     // FIXME: This code should not depend on renderer!
     if (!renderer)
         return false;
@@ -397,17 +402,19 @@ bool SubframeLoader::loadPlugin(HTMLPlugInImageElement& pluginElement, const URL
     pluginElement.subframeLoaderWillCreatePlugIn(url);
 
     IntSize contentSize = roundedIntSize(LayoutSize(renderer->contentWidth(), renderer->contentHeight()));
-    bool loadManually = is<PluginDocument>(*document()) && !m_containsPlugins && downcast<PluginDocument>(*document()).shouldLoadPluginManually();
+    bool loadManually = is<PluginDocument>(document) && !m_containsPlugins && downcast<PluginDocument>(document).shouldLoadPluginManually();
 
 #if PLATFORM(IOS)
     // On iOS, we only tell the plugin to be in full page mode if the containing plugin document is the top level document.
-    if (document()->ownerElement())
+    if (document.ownerElement())
         loadManually = false;
 #endif
 
-    WeakPtr<RenderWidget> weakRenderer = renderer->createWeakPtr();
-    // createPlugin *may* cause this renderer to disappear from underneath.
-    RefPtr<Widget> widget = m_frame.loader().client().createPlugin(contentSize, &pluginElement, url, paramNames, paramValues, mimeType, loadManually);
+    auto weakRenderer = renderer->createWeakPtr();
+
+    auto widget = m_frame.loader().client().createPlugin(contentSize, pluginElement, url, paramNames, paramValues, mimeType, loadManually);
+
+    // The call to createPlugin *may* cause this renderer to disappear from underneath.
     if (!weakRenderer)
         return false;
 
@@ -431,9 +438,7 @@ URL SubframeLoader::completeURL(const String& url) const
 
 bool SubframeLoader::shouldConvertInvalidURLsToBlank() const
 {
-    if (Settings* settings = document() ? document()->settings() : nullptr)
-        return settings->shouldConvertInvalidURLsToBlank();
-    return true;
+    return m_frame.settings().shouldConvertInvalidURLsToBlank();
 }
 
 } // namespace WebCore
index 9513974..12bf771 100644 (file)
@@ -61,7 +61,7 @@ public:
     bool requestObject(HTMLPlugInImageElement&, const String& url, const AtomicString& frameName,
         const String& serviceType, const Vector<String>& paramNames, const Vector<String>& paramValues);
 
-    PassRefPtr<Widget> createJavaAppletWidget(const IntSize&, HTMLAppletElement&, const Vector<String>& paramNames, const Vector<String>& paramValues);
+    RefPtr<Widget> createJavaAppletWidget(const IntSize&, HTMLAppletElement&, const Vector<String>& paramNames, const Vector<String>& paramValues);
 
     WEBCORE_EXPORT bool allowPlugins();
 
@@ -78,14 +78,12 @@ private:
     bool shouldUsePlugin(const URL&, const String& mimeType, bool hasFallback, bool& useFallback);
     bool pluginIsLoadable(const URL&, const String& mimeType);
 
-    Document* document() const;
+    URL completeURL(const String&) const;
 
     bool shouldConvertInvalidURLsToBlank() const;
 
     bool m_containsPlugins;
     Frame& m_frame;
-
-    URL completeURL(const String&) const;
 };
 
 } // namespace WebCore
index 642940a..c189eb5 100644 (file)
@@ -256,6 +256,7 @@ void SubresourceLoader::didSendData(unsigned long long bytesSent, unsigned long
 }
 
 #if USE(QUICK_LOOK)
+
 bool SubresourceLoader::shouldCreateQuickLookHandleForResponse(const ResourceResponse& response) const
 {
     if (m_resource->type() != CachedResource::MainResource)
@@ -266,6 +267,7 @@ bool SubresourceLoader::shouldCreateQuickLookHandleForResponse(const ResourceRes
 
     return QuickLookHandle::shouldCreateForMIMEType(response.mimeType());
 }
+
 #endif
 
 void SubresourceLoader::didReceiveResponse(const ResourceResponse& response)
index c918d8b..a95ed2c 100644 (file)
@@ -42,17 +42,13 @@ static inline bool fallbackURLLongerThan(const std::pair<URL, URL>& lhs, const s
 }
 
 ApplicationCache::ApplicationCache()
-    : m_group(nullptr)
-    , m_manifest(nullptr)
-    , m_estimatedSizeInStorage(0)
-    , m_storageID(0)
 {
 }
 
 ApplicationCache::~ApplicationCache()
 {
     if (m_group)
-        m_group->cacheDestroyed(this);
+        m_group->cacheDestroyed(*this);
 }
     
 void ApplicationCache::setGroup(ApplicationCacheGroup* group)
@@ -63,57 +59,39 @@ void ApplicationCache::setGroup(ApplicationCacheGroup* group)
 
 bool ApplicationCache::isComplete()
 {
-    return m_group && m_group->cacheIsComplete(this);
+    return m_group && m_group->cacheIsComplete(*this);
 }
 
-void ApplicationCache::setManifestResource(PassRefPtr<ApplicationCacheResource> manifest)
+void ApplicationCache::setManifestResource(Ref<ApplicationCacheResource>&& manifest)
 {
-    ASSERT(manifest);
     ASSERT(!m_manifest);
     ASSERT(manifest->type() & ApplicationCacheResource::Manifest);
-    
-    m_manifest = manifest.get();
-    
-    addResource(manifest);
+
+    m_manifest = manifest.ptr();
+
+    addResource(WTFMove(manifest));
 }
     
-void ApplicationCache::addResource(PassRefPtr<ApplicationCacheResource> resource)
+void ApplicationCache::addResource(Ref<ApplicationCacheResource>&& resource)
 {
-    ASSERT(resource);
-    
-    const String& url = resource->url();
-    
+    auto& url = resource->url();
+
+    ASSERT(!URL(ParsedURLString, url).hasFragmentIdentifier());
     ASSERT(!m_resources.contains(url));
-    
+
     if (m_storageID) {
         ASSERT(!resource->storageID());
         ASSERT(resource->type() & ApplicationCacheResource::Master);
-        
+
         // Add the resource to the storage.
-        m_group->storage().store(resource.get(), this);
+        m_group->storage().store(resource.ptr(), this);
     }
 
     m_estimatedSizeInStorage += resource->estimatedSizeInStorage();
 
-    m_resources.set(url, resource);
+    m_resources.set(url, WTFMove(resource));
 }
 
-unsigned ApplicationCache::removeResource(const String& url)
-{
-    HashMap<String, RefPtr<ApplicationCacheResource>>::iterator it = m_resources.find(url);
-    if (it == m_resources.end())
-        return 0;
-
-    // The resource exists, get its type so we can return it.
-    unsigned type = it->value->type();
-
-    m_estimatedSizeInStorage -= it->value->estimatedSizeInStorage();
-
-    m_resources.remove(it);
-
-    return type;
-}    
-    
 ApplicationCacheResource* ApplicationCache::resourceForURL(const String& url)
 {
     ASSERT(!URL(ParsedURLString, url).hasFragmentIdentifier());
@@ -132,9 +110,7 @@ ApplicationCacheResource* ApplicationCache::resourceForRequest(const ResourceReq
         return nullptr;
 
     URL url(request.url());
-    if (url.hasFragmentIdentifier())
-        url.removeFragmentIdentifier();
-
+    url.removeFragmentIdentifier();
     return resourceForURL(url);
 }
 
index b6ae4ae..5df5f60 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2008-2017 Apple Inc. All Rights Reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #pragma once
 
 #include <wtf/HashMap.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
 #include <wtf/text/StringHash.h>
-#include <wtf/text/WTFString.h>
 
 namespace WebCore {
 
 class ApplicationCacheGroup;
 class ApplicationCacheResource;
-class URL;
 class ResourceRequest;
+class URL;
 
-typedef Vector<std::pair<URL, URL>> FallbackURLVector;
+using FallbackURLVector = Vector<std::pair<URL, URL>>;
 
 class ApplicationCache : public RefCounted<ApplicationCache> {
 public:
     static Ref<ApplicationCache> create() { return adoptRef(*new ApplicationCache); }
-    
+
     ~ApplicationCache();
 
-    void addResource(PassRefPtr<ApplicationCacheResource> resource);
-    unsigned removeResource(const String& url);
-    
-    void setManifestResource(PassRefPtr<ApplicationCacheResource> manifest);
+    void addResource(Ref<ApplicationCacheResource>&&);
+
+    void setManifestResource(Ref<ApplicationCacheResource>&&);
     ApplicationCacheResource* manifestResource() const { return m_manifest; }
-    
+
     void setGroup(ApplicationCacheGroup*);
     ApplicationCacheGroup* group() const { return m_group; }
 
@@ -69,39 +65,38 @@ public:
     void setFallbackURLs(const FallbackURLVector&);
     const FallbackURLVector& fallbackURLs() const { return m_fallbackURLs; }
     bool urlMatchesFallbackNamespace(const URL&, URL* fallbackURL = nullptr);
-    
+
 #ifndef NDEBUG
     void dump();
 #endif
 
-    typedef HashMap<String, RefPtr<ApplicationCacheResource>> ResourceMap;
+    using ResourceMap = HashMap<String, RefPtr<ApplicationCacheResource>>;
     const ResourceMap& resources() const { return m_resources; }
-    
+
     void setStorageID(unsigned storageID) { m_storageID = storageID; }
     unsigned storageID() const { return m_storageID; }
     void clearStorageID();
-    
+
     static bool requestIsHTTPOrHTTPSGet(const ResourceRequest&);
 
     int64_t estimatedSizeInStorage() const { return m_estimatedSizeInStorage; }
 
 private:
     ApplicationCache();
-    
-    ApplicationCacheGroup* m_group;
+
+    ApplicationCacheGroup* m_group { nullptr };
     ResourceMap m_resources;
-    ApplicationCacheResource* m_manifest;
+    ApplicationCacheResource* m_manifest { nullptr };
 
-    bool m_allowAllNetworkRequests;
+    bool m_allowAllNetworkRequests { false };
     Vector<URL> m_onlineWhitelist;
     FallbackURLVector m_fallbackURLs;
 
     // The total size of the resources belonging to this Application Cache instance.
-    // This is an estimation of the size this Application Cache occupies in the
-    // database file.
-    int64_t m_estimatedSizeInStorage;
+    // This is an estimation of the size this Application Cache occupies in the database file.
+    int64_t m_estimatedSizeInStorage { 0 };
 
-    unsigned m_storageID;
+    unsigned m_storageID { 0 };
 };
 
 } // namespace WebCore
index 86e9a5a..9881b25 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008, 2009, 2010 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2008-2017 Apple Inc. All Rights Reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -34,6 +34,7 @@
 #include "ChromeClient.h"
 #include "DOMApplicationCache.h"
 #include "DocumentLoader.h"
+#include "EventNames.h"
 #include "Frame.h"
 #include "FrameLoader.h"
 #include "FrameLoaderClient.h"
@@ -54,17 +55,7 @@ ApplicationCacheGroup::ApplicationCacheGroup(Ref<ApplicationCacheStorage>&& stor
     : m_storage(WTFMove(storage))
     , m_manifestURL(manifestURL)
     , m_origin(SecurityOrigin::create(manifestURL))
-    , m_updateStatus(Idle)
-    , m_downloadingPendingMasterResourceLoadersCount(0)
-    , m_progressTotal(0)
-    , m_progressDone(0)
-    , m_frame(nullptr)
-    , m_storageID(0)
-    , m_isObsolete(false)
-    , m_completionType(None)
-    , m_calledReachedMaxAppCacheSize(false)
     , m_availableSpaceInQuota(ApplicationCacheStorage::unknownQuota())
-    , m_originQuotaExceededPreviously(false)
 {
 }
 
@@ -72,10 +63,10 @@ ApplicationCacheGroup::~ApplicationCacheGroup()
 {
     ASSERT(!m_newestCache);
     ASSERT(m_caches.isEmpty());
-    
+
     stopLoading();
 
-    m_storage->cacheGroupDestroyed(this);
+    m_storage->cacheGroupDestroyed(*this);
 }
     
 ApplicationCache* ApplicationCacheGroup::cacheForMainRequest(const ResourceRequest& request, DocumentLoader* documentLoader)
@@ -84,21 +75,20 @@ ApplicationCache* ApplicationCacheGroup::cacheForMainRequest(const ResourceReque
         return nullptr;
 
     URL url(request.url());
-    if (url.hasFragmentIdentifier())
-        url.removeFragmentIdentifier();
+    url.removeFragmentIdentifier();
 
     auto* page = documentLoader->frame() ? documentLoader->frame()->page() : nullptr;
     if (!page || page->usesEphemeralSession())
         return nullptr;
 
-    if (ApplicationCacheGroup* group = page->applicationCacheStorage().cacheGroupForURL(url)) {
-        ASSERT(group->newestCache());
-        ASSERT(!group->isObsolete());
-        
-        return group->newestCache();
-    }
-    
-    return nullptr;
+    auto* group = page->applicationCacheStorage().cacheGroupForURL(url);
+    if (!group)
+        return nullptr;
+
+    ASSERT(group->newestCache());
+    ASSERT(!group->isObsolete());
+
+    return group->newestCache();
 }
     
 ApplicationCache* ApplicationCacheGroup::fallbackCacheForMainRequest(const ResourceRequest& request, DocumentLoader* documentLoader)
@@ -106,81 +96,87 @@ ApplicationCache* ApplicationCacheGroup::fallbackCacheForMainRequest(const Resou
     if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request))
         return nullptr;
 
-    URL url(request.url());
-    if (url.hasFragmentIdentifier())
-        url.removeFragmentIdentifier();
+    auto* frame = documentLoader->frame();
+    if (!frame)
+        return nullptr;
 
-    auto* page = documentLoader->frame() ? documentLoader->frame()->page() : nullptr;
+    auto* page = frame->page();
     if (!page)
         return nullptr;
 
-    if (ApplicationCacheGroup* group = page->applicationCacheStorage().fallbackCacheGroupForURL(url)) {
-        ASSERT(group->newestCache());
-        ASSERT(!group->isObsolete());
+    URL url(request.url());
+    url.removeFragmentIdentifier();
 
-        return group->newestCache();
-    }
-    
-    return nullptr;
+    auto* group = page->applicationCacheStorage().fallbackCacheGroupForURL(url);
+    if (!group)
+        return nullptr;
+
+    ASSERT(group->newestCache());
+    ASSERT(!group->isObsolete());
+
+    return group->newestCache();
 }
 
-void ApplicationCacheGroup::selectCache(Frame* frame, const URL& passedManifestURL)
+void ApplicationCacheGroup::selectCache(Frame& frame, const URL& passedManifestURL)
 {
-    ASSERT(frame && frame->page());
-    
-    if (!frame->settings().offlineWebApplicationCacheEnabled())
+    ASSERT(frame.document());
+    ASSERT(frame.page());
+    ASSERT(frame.loader().documentLoader());
+
+    if (!frame.settings().offlineWebApplicationCacheEnabled())
         return;
-    
-    DocumentLoader* documentLoader = frame->loader().documentLoader();
-    ASSERT(!documentLoader->applicationCacheHost()->applicationCache());
+
+    auto& documentLoader = *frame.loader().documentLoader();
+    ASSERT(!documentLoader.applicationCacheHost().applicationCache());
 
     if (passedManifestURL.isNull()) {
-        selectCacheWithoutManifestURL(frame);        
+        selectCacheWithoutManifestURL(frame);
         return;
     }
 
     // Don't access anything on disk if private browsing is enabled.
-    if (frame->page()->usesEphemeralSession() || !frame->document()->securityOrigin()->canAccessApplicationCache(frame->tree().top().document()->securityOrigin())) {
-        postListenerTask(ApplicationCacheHost::CHECKING_EVENT, documentLoader);
-        postListenerTask(ApplicationCacheHost::ERROR_EVENT, documentLoader);
+    if (frame.page()->usesEphemeralSession() || !frame.document()->securityOrigin()->canAccessApplicationCache(frame.tree().top().document()->securityOrigin())) {
+        postListenerTask(eventNames().checkingEvent, documentLoader);
+        postListenerTask(eventNames().errorEvent, documentLoader);
         return;
     }
 
     URL manifestURL(passedManifestURL);
-    if (manifestURL.hasFragmentIdentifier())
-        manifestURL.removeFragmentIdentifier();
+    manifestURL.removeFragmentIdentifier();
 
-    ApplicationCache* mainResourceCache = documentLoader->applicationCacheHost()->mainResourceApplicationCache();
+    auto* mainResourceCache = documentLoader.applicationCacheHost().mainResourceApplicationCache();
     
     if (mainResourceCache) {
+        ASSERT(mainResourceCache->group());
         if (manifestURL == mainResourceCache->group()->m_manifestURL) {
             // The cache may have gotten obsoleted after we've loaded from it, but before we parsed the document and saw cache manifest.
             if (mainResourceCache->group()->isObsolete())
                 return;
-            mainResourceCache->group()->associateDocumentLoaderWithCache(documentLoader, mainResourceCache);
+            mainResourceCache->group()->associateDocumentLoaderWithCache(&documentLoader, mainResourceCache);
             mainResourceCache->group()->update(frame, ApplicationCacheUpdateWithBrowsingContext);
         } else {
             // The main resource was loaded from cache, so the cache must have an entry for it. Mark it as foreign.
-            URL resourceURL(documentLoader->responseURL());
-            if (resourceURL.hasFragmentIdentifier())
-                resourceURL.removeFragmentIdentifier();
-            ApplicationCacheResource* resource = mainResourceCache->resourceForURL(resourceURL);
-            bool inStorage = resource->storageID();
-            resource->addType(ApplicationCacheResource::Foreign);
+            URL resourceURL { documentLoader.responseURL() };
+            resourceURL.removeFragmentIdentifier();
+
+            ASSERT(mainResourceCache->resourceForURL(resourceURL));
+            auto& resource = *mainResourceCache->resourceForURL(resourceURL);
+
+            bool inStorage = resource.storageID();
+            resource.addType(ApplicationCacheResource::Foreign);
             if (inStorage)
-                frame->page()->applicationCacheStorage().storeUpdatedType(resource, mainResourceCache);
+                frame.page()->applicationCacheStorage().storeUpdatedType(&resource, mainResourceCache);
 
             // Restart the current navigation from the top of the navigation algorithm, undoing any changes that were made
             // as part of the initial load.
             // The navigation will not result in the same resource being loaded, because "foreign" entries are never picked during navigation.
-            frame->navigationScheduler().scheduleLocationChange(frame->document(), frame->document()->securityOrigin(), documentLoader->url(), frame->loader().referrer());
+            frame.navigationScheduler().scheduleLocationChange(*frame.document(), frame.document()->securityOrigin(), documentLoader.url(), frame.loader().referrer());
         }
-        
         return;
     }
-    
+
     // The resource was loaded from the network, check if it is a HTTP/HTTPS GET.    
-    const ResourceRequest& request = frame->loader().activeDocumentLoader()->request();
+    auto& request = frame.loader().activeDocumentLoader()->request();
 
     if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request))
         return;
@@ -189,46 +185,48 @@ void ApplicationCacheGroup::selectCache(Frame* frame, const URL& passedManifestU
     if (!protocolHostAndPortAreEqual(manifestURL, request.url()))
         return;
 
-    ApplicationCacheGroup* group = frame->page()->applicationCacheStorage().findOrCreateCacheGroup(manifestURL);
+    auto& group = *frame.page()->applicationCacheStorage().findOrCreateCacheGroup(manifestURL);
 
-    documentLoader->applicationCacheHost()->setCandidateApplicationCacheGroup(group);
-    group->m_pendingMasterResourceLoaders.add(documentLoader);
-    group->m_downloadingPendingMasterResourceLoadersCount++;
+    documentLoader.applicationCacheHost().setCandidateApplicationCacheGroup(&group);
+    group.m_pendingMasterResourceLoaders.add(&documentLoader);
+    group.m_downloadingPendingMasterResourceLoadersCount++;
 
-    ASSERT(!group->m_cacheBeingUpdated || group->m_updateStatus != Idle);
-    group->update(frame, ApplicationCacheUpdateWithBrowsingContext);
+    ASSERT(!group.m_cacheBeingUpdated || group.m_updateStatus != Idle);
+    group.update(frame, ApplicationCacheUpdateWithBrowsingContext);
 }
 
-void ApplicationCacheGroup::selectCacheWithoutManifestURL(Frame* frame)
+void ApplicationCacheGroup::selectCacheWithoutManifestURL(Frame& frame)
 {
-    if (!frame->settings().offlineWebApplicationCacheEnabled())
+    if (!frame.settings().offlineWebApplicationCacheEnabled())
         return;
 
-    DocumentLoader* documentLoader = frame->loader().documentLoader();
-    ASSERT(!documentLoader->applicationCacheHost()->applicationCache());
+    ASSERT(frame.document());
+    ASSERT(frame.page());
+    ASSERT(frame.loader().documentLoader());
+    auto& documentLoader = *frame.loader().documentLoader();
+    ASSERT(!documentLoader.applicationCacheHost().applicationCache());
 
     // Don't access anything on disk if private browsing is enabled.
-    if (frame->page()->usesEphemeralSession() || !frame->document()->securityOrigin()->canAccessApplicationCache(frame->tree().top().document()->securityOrigin())) {
-        postListenerTask(ApplicationCacheHost::CHECKING_EVENT, documentLoader);
-        postListenerTask(ApplicationCacheHost::ERROR_EVENT, documentLoader);
+    if (frame.page()->usesEphemeralSession() || !frame.document()->securityOrigin()->canAccessApplicationCache(frame.tree().top().document()->securityOrigin())) {
+        postListenerTask(eventNames().checkingEvent, documentLoader);
+        postListenerTask(eventNames().errorEvent, documentLoader);
         return;
     }
 
-    ApplicationCache* mainResourceCache = documentLoader->applicationCacheHost()->mainResourceApplicationCache();
-
-    if (mainResourceCache) {
-        mainResourceCache->group()->associateDocumentLoaderWithCache(documentLoader, mainResourceCache);
-        mainResourceCache->group()->update(frame, ApplicationCacheUpdateWithBrowsingContext);
+    if (auto* mainResourceCache = documentLoader.applicationCacheHost().mainResourceApplicationCache()) {
+        ASSERT(mainResourceCache->group());
+        auto& group = *mainResourceCache->group();
+        group.associateDocumentLoaderWithCache(&documentLoader, mainResourceCache);
+        group.update(frame, ApplicationCacheUpdateWithBrowsingContext);
     }
 }
 
-void ApplicationCacheGroup::finishedLoadingMainResource(DocumentLoader* loader)
+void ApplicationCacheGroup::finishedLoadingMainResource(DocumentLoader& loader)
 {
-    ASSERT(m_pendingMasterResourceLoaders.contains(loader));
+    ASSERT(m_pendingMasterResourceLoaders.contains(&loader));
     ASSERT(m_completionType == None || m_pendingEntries.isEmpty());
-    URL url = loader->url();
-    if (url.hasFragmentIdentifier())
-        url.removeFragmentIdentifier();
+    URL url = loader.url();
+    url.removeFragmentIdentifier();
 
     switch (m_completionType) {
     case None:
@@ -236,34 +234,32 @@ void ApplicationCacheGroup::finishedLoadingMainResource(DocumentLoader* loader)
         return;
     case NoUpdate:
         ASSERT(!m_cacheBeingUpdated);
-        associateDocumentLoaderWithCache(loader, m_newestCache.get());
-
-        if (ApplicationCacheResource* resource = m_newestCache->resourceForURL(url)) {
+        associateDocumentLoaderWithCache(&loader, m_newestCache.get());
+        if (auto* resource = m_newestCache->resourceForURL(url)) {
             if (!(resource->type() & ApplicationCacheResource::Master)) {
                 resource->addType(ApplicationCacheResource::Master);
                 ASSERT(!resource->storageID());
             }
         } else
-            m_newestCache->addResource(ApplicationCacheResource::create(url, loader->response(), ApplicationCacheResource::Master, loader->mainResourceData()));
+            m_newestCache->addResource(ApplicationCacheResource::create(url, loader.response(), ApplicationCacheResource::Master, loader.mainResourceData()));
         break;
     case Failure:
         // Cache update has been a failure, so there is no reason to keep the document associated with the incomplete cache
         // (its main resource was not cached yet, so it is likely that the application changed significantly server-side).
         ASSERT(!m_cacheBeingUpdated); // Already cleared out by stopLoading().
-        loader->applicationCacheHost()->setApplicationCache(nullptr); // Will unset candidate, too.
-        m_associatedDocumentLoaders.remove(loader);
-        postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader);
+        loader.applicationCacheHost().setApplicationCache(nullptr); // Will unset candidate, too.
+        m_associatedDocumentLoaders.remove(&loader);
+        postListenerTask(eventNames().errorEvent, loader);
         break;
     case Completed:
-        ASSERT(m_associatedDocumentLoaders.contains(loader));
-
-        if (ApplicationCacheResource* resource = m_cacheBeingUpdated->resourceForURL(url)) {
+        ASSERT(m_associatedDocumentLoaders.contains(&loader));
+        if (auto* resource = m_cacheBeingUpdated->resourceForURL(url)) {
             if (!(resource->type() & ApplicationCacheResource::Master)) {
                 resource->addType(ApplicationCacheResource::Master);
                 ASSERT(!resource->storageID());
             }
         } else
-            m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, loader->response(), ApplicationCacheResource::Master, loader->mainResourceData()));
+            m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, loader.response(), ApplicationCacheResource::Master, loader.mainResourceData()));
         // The "cached" event will be posted to all associated documents once update is complete.
         break;
     }
@@ -273,9 +269,9 @@ void ApplicationCacheGroup::finishedLoadingMainResource(DocumentLoader* loader)
     checkIfLoadIsComplete();
 }
 
-void ApplicationCacheGroup::failedLoadingMainResource(DocumentLoader* loader)
+void ApplicationCacheGroup::failedLoadingMainResource(DocumentLoader& loader)
 {
-    ASSERT(m_pendingMasterResourceLoaders.contains(loader));
+    ASSERT(m_pendingMasterResourceLoaders.contains(&loader));
     ASSERT(m_completionType == None || m_pendingEntries.isEmpty());
 
     switch (m_completionType) {
@@ -284,32 +280,27 @@ void ApplicationCacheGroup::failedLoadingMainResource(DocumentLoader* loader)
         return;
     case NoUpdate:
         ASSERT(!m_cacheBeingUpdated);
-
         // The manifest didn't change, and we have a relevant cache - but the main resource download failed mid-way, so it cannot be stored to the cache,
         // and the loader does not get associated to it. If there are other main resources being downloaded for this cache group, they may still succeed.
-        postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader);
-
+        postListenerTask(eventNames().errorEvent, loader);
         break;
     case Failure:
         // Cache update failed, too.
         ASSERT(!m_cacheBeingUpdated); // Already cleared out by stopLoading().
-        ASSERT(!loader->applicationCacheHost()->applicationCache() || loader->applicationCacheHost()->applicationCache()->group() == this);
-
-        loader->applicationCacheHost()->setApplicationCache(nullptr); // Will unset candidate, too.
-        m_associatedDocumentLoaders.remove(loader);
-        postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader);
+        ASSERT(!loader.applicationCacheHost().applicationCache() || loader.applicationCacheHost().applicationCache()->group() == this);
+        loader.applicationCacheHost().setApplicationCache(nullptr); // Will unset candidate, too.
+        m_associatedDocumentLoaders.remove(&loader);
+        postListenerTask(eventNames().errorEvent, loader);
         break;
     case Completed:
         // The cache manifest didn't list this main resource, and all cache entries were already updated successfully - but the main resource failed to load,
         // so it cannot be stored to the cache. If there are other main resources being downloaded for this cache group, they may still succeed.
-        ASSERT(m_associatedDocumentLoaders.contains(loader));
-        ASSERT(loader->applicationCacheHost()->applicationCache() == m_cacheBeingUpdated);
-        ASSERT(!loader->applicationCacheHost()->candidateApplicationCacheGroup());
-        m_associatedDocumentLoaders.remove(loader);
-        loader->applicationCacheHost()->setApplicationCache(nullptr);
-
-        postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader);
-
+        ASSERT(m_associatedDocumentLoaders.contains(&loader));
+        ASSERT(loader.applicationCacheHost().applicationCache() == m_cacheBeingUpdated);
+        ASSERT(!loader.applicationCacheHost().candidateApplicationCacheGroup());
+        m_associatedDocumentLoaders.remove(&loader);
+        loader.applicationCacheHost().setApplicationCache(nullptr);
+        postListenerTask(eventNames().errorEvent, loader);
         break;
     }
 
@@ -346,12 +337,12 @@ void ApplicationCacheGroup::stopLoading()
     m_pendingEntries.clear();
 }    
 
-void ApplicationCacheGroup::disassociateDocumentLoader(DocumentLoader* loader)
+void ApplicationCacheGroup::disassociateDocumentLoader(DocumentLoader& loader)
 {
-    m_associatedDocumentLoaders.remove(loader);
-    m_pendingMasterResourceLoaders.remove(loader);
+    m_associatedDocumentLoaders.remove(&loader);
+    m_pendingMasterResourceLoaders.remove(&loader);
 
-    if (auto* host = loader->applicationCacheHost())
+    if (auto* host = loader.applicationCacheHostUnlessBeingDestroyed())
         host->setApplicationCache(nullptr); // Will set candidate group to null, too.
 
     if (!m_associatedDocumentLoaders.isEmpty() || !m_pendingMasterResourceLoaders.isEmpty())
@@ -372,26 +363,26 @@ void ApplicationCacheGroup::disassociateDocumentLoader(DocumentLoader* loader)
     m_newestCache = nullptr;
 }
 
-void ApplicationCacheGroup::cacheDestroyed(ApplicationCache* cache)
+void ApplicationCacheGroup::cacheDestroyed(ApplicationCache& cache)
 {
-    if (m_caches.remove(cache) && m_caches.isEmpty()) {
+    if (m_caches.remove(&cache) && m_caches.isEmpty()) {
         ASSERT(m_associatedDocumentLoaders.isEmpty());
         ASSERT(m_pendingMasterResourceLoaders.isEmpty());
         delete this;
     }
 }
 
-void ApplicationCacheGroup::stopLoadingInFrame(Frame* frame)
+void ApplicationCacheGroup::stopLoadingInFrame(Frame& frame)
 {
-    if (frame != m_frame)
+    if (&frame != m_frame)
         return;
 
     cacheUpdateFailed();
 }
 
-void ApplicationCacheGroup::setNewestCache(PassRefPtr<ApplicationCache> newestCache)
+void ApplicationCacheGroup::setNewestCache(Ref<ApplicationCache>&& newestCache)
 {
-    m_newestCache = newestCache;
+    m_newestCache = WTFMove(newestCache);
 
     m_caches.add(m_newestCache.get());
     m_newestCache->setGroup(this);
@@ -403,40 +394,43 @@ void ApplicationCacheGroup::makeObsolete()
         return;
 
     m_isObsolete = true;
-    m_storage->cacheGroupMadeObsolete(this);
+    m_storage->cacheGroupMadeObsolete(*this);
     ASSERT(!m_storageID);
 }
 
-void ApplicationCacheGroup::update(Frame* frame, ApplicationCacheUpdateOption updateOption)
+void ApplicationCacheGroup::update(Frame& frame, ApplicationCacheUpdateOption updateOption)
 {
+    ASSERT(frame.loader().documentLoader());
+    auto& documentLoader = *frame.loader().documentLoader();
+
     if (m_updateStatus == Checking || m_updateStatus == Downloading) {
         if (updateOption == ApplicationCacheUpdateWithBrowsingContext) {
-            postListenerTask(ApplicationCacheHost::CHECKING_EVENT, frame->loader().documentLoader());
+            postListenerTask(eventNames().checkingEvent, documentLoader);
             if (m_updateStatus == Downloading)
-                postListenerTask(ApplicationCacheHost::DOWNLOADING_EVENT, frame->loader().documentLoader());
+                postListenerTask(eventNames().downloadingEvent, documentLoader);
         }
         return;
     }
 
     // Don't access anything on disk if private browsing is enabled.
-    if (frame->page()->usesEphemeralSession() || !frame->document()->securityOrigin()->canAccessApplicationCache(frame->tree().top().document()->securityOrigin())) {
+    if (frame.page()->usesEphemeralSession() || !frame.document()->securityOrigin()->canAccessApplicationCache(frame.tree().top().document()->securityOrigin())) {
         ASSERT(m_pendingMasterResourceLoaders.isEmpty());
         ASSERT(m_pendingEntries.isEmpty());
         ASSERT(!m_cacheBeingUpdated);
-        postListenerTask(ApplicationCacheHost::CHECKING_EVENT, frame->loader().documentLoader());
-        postListenerTask(ApplicationCacheHost::ERROR_EVENT, frame->loader().documentLoader());
+        postListenerTask(eventNames().checkingEvent, documentLoader);
+        postListenerTask(eventNames().errorEvent, documentLoader);
         return;
     }
 
     ASSERT(!m_frame);
-    m_frame = frame;
+    m_frame = &frame;
 
     setUpdateStatus(Checking);
 
-    postListenerTask(ApplicationCacheHost::CHECKING_EVENT, m_associatedDocumentLoaders);
+    postListenerTask(eventNames().checkingEvent, m_associatedDocumentLoaders);
     if (!m_newestCache) {
         ASSERT(updateOption == ApplicationCacheUpdateWithBrowsingContext);
-        postListenerTask(ApplicationCacheHost::CHECKING_EVENT, frame->loader().documentLoader());
+        postListenerTask(eventNames().checkingEvent, documentLoader);
     }
     
     ASSERT(!m_manifestHandle);
@@ -449,7 +443,7 @@ void ApplicationCacheGroup::update(Frame* frame, ApplicationCacheUpdateOption up
     m_manifestHandle = createResourceHandle(m_manifestURL, m_newestCache ? m_newestCache->manifestResource() : 0);
 }
 
-void ApplicationCacheGroup::abort(Frame* frame)
+void ApplicationCacheGroup::abort(Frame& frame)
 {
     if (m_updateStatus == Idle)
         return;
@@ -458,7 +452,7 @@ void ApplicationCacheGroup::abort(Frame* frame)
     if (m_completionType != None)
         return;
 
-    frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Debug, ASCIILiteral("Application Cache download process was aborted."));
+    frame.document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Debug, ASCIILiteral("Application Cache download process was aborted."));
     cacheUpdateFailed();
 }
 
@@ -502,8 +496,7 @@ void ApplicationCacheGroup::didReceiveResponse(ResourceHandle* handle, ResourceR
     ASSERT(handle == m_currentHandle);
 
     URL url(handle->firstRequest().url());
-    if (url.hasFragmentIdentifier())
-        url.removeFragmentIdentifier();
+    url.removeFragmentIdentifier();
     
     ASSERT(!m_currentResource);
     ASSERT(m_pendingEntries.contains(url));
@@ -593,7 +586,7 @@ void ApplicationCacheGroup::didFinishLoading(ResourceHandle* handle, double fini
     
     ASSERT(m_cacheBeingUpdated);
 
-    m_cacheBeingUpdated->addResource(WTFMove(m_currentResource));
+    m_cacheBeingUpdated->addResource(m_currentResource.releaseNonNull());
     m_currentHandle = nullptr;
 
     // While downloading check to see if we have exceeded the available quota.
@@ -626,8 +619,7 @@ void ApplicationCacheGroup::didFail(ResourceHandle* handle, const ResourceError&
 
     unsigned type = m_currentResource ? m_currentResource->type() : m_pendingEntries.get(handle->firstRequest().url());
     URL url(handle->firstRequest().url());
-    if (url.hasFragmentIdentifier())
-        url.removeFragmentIdentifier();
+    url.removeFragmentIdentifier();
 
     ASSERT(!m_currentResource || !m_pendingEntries.contains(url));
     m_currentResource = nullptr;
@@ -734,7 +726,7 @@ void ApplicationCacheGroup::didFinishLoadingManifest()
     // We have the manifest, now download the resources.
     setUpdateStatus(Downloading);
     
-    postListenerTask(ApplicationCacheHost::DOWNLOADING_EVENT, m_associatedDocumentLoaders);
+    postListenerTask(eventNames().downloadingEvent, m_associatedDocumentLoaders);
 
     ASSERT(m_pendingEntries.isEmpty());
 
@@ -802,8 +794,8 @@ void ApplicationCacheGroup::manifestNotFound()
 {
     makeObsolete();
 
-    postListenerTask(ApplicationCacheHost::OBSOLETE_EVENT, m_associatedDocumentLoaders);
-    postListenerTask(ApplicationCacheHost::ERROR_EVENT, m_pendingMasterResourceLoaders);
+    postListenerTask(eventNames().obsoleteEvent, m_associatedDocumentLoaders);
+    postListenerTask(eventNames().errorEvent, m_pendingMasterResourceLoaders);
 
     stopLoading();
 
@@ -813,16 +805,16 @@ void ApplicationCacheGroup::manifestNotFound()
     while (!m_pendingMasterResourceLoaders.isEmpty()) {
         HashSet<DocumentLoader*>::iterator it = m_pendingMasterResourceLoaders.begin();
         
-        ASSERT((*it)->applicationCacheHost()->candidateApplicationCacheGroup() == this);
-        ASSERT(!(*it)->applicationCacheHost()->applicationCache());
-        (*it)->applicationCacheHost()->setCandidateApplicationCacheGroup(nullptr);
+        ASSERT((*it)->applicationCacheHost().candidateApplicationCacheGroup() == this);
+        ASSERT(!(*it)->applicationCacheHost().applicationCache());
+        (*it)->applicationCacheHost().setCandidateApplicationCacheGroup(nullptr);
         m_pendingMasterResourceLoaders.remove(it);
     }
 
     m_downloadingPendingMasterResourceLoadersCount = 0;
     setUpdateStatus(Idle);    
     m_frame = nullptr;
-    
+
     if (m_caches.isEmpty()) {
         ASSERT(m_associatedDocumentLoaders.isEmpty());
         ASSERT(!m_cacheBeingUpdated);
@@ -849,13 +841,13 @@ void ApplicationCacheGroup::checkIfLoadIsComplete()
 
         // The storage could have been manually emptied by the user.
         if (!m_storageID)
-            m_storage->storeNewestCache(this);
+            m_storage->storeNewestCache(*this);
 
-        postListenerTask(ApplicationCacheHost::NOUPDATE_EVENT, m_associatedDocumentLoaders);
+        postListenerTask(eventNames().noupdateEvent, m_associatedDocumentLoaders);
         break;
     case Failure:
         ASSERT(!m_cacheBeingUpdated);
-        postListenerTask(ApplicationCacheHost::ERROR_EVENT, m_associatedDocumentLoaders);
+        postListenerTask(eventNames().errorEvent, m_associatedDocumentLoaders);
         if (m_caches.isEmpty()) {
             ASSERT(m_associatedDocumentLoaders.isEmpty());
             delete this;
@@ -867,7 +859,7 @@ void ApplicationCacheGroup::checkIfLoadIsComplete()
 
         ASSERT(m_cacheBeingUpdated);
         if (m_manifestResource)
-            m_cacheBeingUpdated->setManifestResource(WTFMove(m_manifestResource));
+            m_cacheBeingUpdated->setManifestResource(m_manifestResource.releaseNonNull());
         else {
             // We can get here as a result of retrying the Complete step, following
             // a failure of the cache storage to save the newest cache due to hitting
@@ -887,18 +879,18 @@ void ApplicationCacheGroup::checkIfLoadIsComplete()
             didReachOriginQuota(totalSpaceNeeded);
 
         ApplicationCacheStorage::FailureReason failureReason;
-        setNewestCache(WTFMove(m_cacheBeingUpdated));
-        if (m_storage->storeNewestCache(this, oldNewestCache.get(), failureReason)) {
+        setNewestCache(m_cacheBeingUpdated.releaseNonNull());
+        if (m_storage->storeNewestCache(*this, oldNewestCache.get(), failureReason)) {
             // New cache stored, now remove the old cache.
             if (oldNewestCache)
                 m_storage->remove(oldNewestCache.get());
 
             // Fire the final progress event.
             ASSERT(m_progressDone == m_progressTotal);
-            postListenerTask(ApplicationCacheHost::PROGRESS_EVENT, m_progressTotal, m_progressDone, m_associatedDocumentLoaders);
+            postListenerTask(eventNames().progressEvent, m_progressTotal, m_progressDone, m_associatedDocumentLoaders);
 
             // Fire the success event.
-            postListenerTask(isUpgradeAttempt ? ApplicationCacheHost::UPDATEREADY_EVENT : ApplicationCacheHost::CACHED_EVENT, m_associatedDocumentLoaders);
+            postListenerTask(isUpgradeAttempt ? eventNames().updatereadyEvent : eventNames().cachedEvent, m_associatedDocumentLoaders);
             // It is clear that the origin quota was not reached, so clear the flag if it was set.
             m_originQuotaExceededPreviously = false;
         } else {
@@ -919,10 +911,8 @@ void ApplicationCacheGroup::checkIfLoadIsComplete()
 
                 // Save a reference to the new cache.
                 m_cacheBeingUpdated = WTFMove(m_newestCache);
-                if (oldNewestCache) {
-                    // Reinstate the oldNewestCache.
-                    setNewestCache(WTFMove(oldNewestCache));
-                }
+                if (oldNewestCache)
+                    setNewestCache(oldNewestCache.releaseNonNull());
                 scheduleReachedMaxAppCacheSizeCallback();
                 return;
             }
@@ -930,7 +920,7 @@ void ApplicationCacheGroup::checkIfLoadIsComplete()
             // Run the "cache failure steps"
             // Fire the error events to all pending master entries, as well any other cache hosts
             // currently associated with a cache in this group.
-            postListenerTask(ApplicationCacheHost::ERROR_EVENT, m_associatedDocumentLoaders);
+            postListenerTask(eventNames().errorEvent, m_associatedDocumentLoaders);
             // Disassociate the pending master entries from the failed new cache. Note that
             // all other loaders in the m_associatedDocumentLoaders are still associated with
             // some other cache in this group. They are not associated with the failed new cache.
@@ -939,12 +929,12 @@ void ApplicationCacheGroup::checkIfLoadIsComplete()
             Vector<DocumentLoader*> loaders;
             copyToVector(m_pendingMasterResourceLoaders, loaders);
             for (auto& loader : loaders)
-                disassociateDocumentLoader(loader); // This can delete this group.
+                disassociateDocumentLoader(*loader); // This can delete this group.
 
             // Reinstate the oldNewestCache, if there was one.
             if (oldNewestCache) {
                 // This will discard the failed new cache.
-                setNewestCache(WTFMove(oldNewestCache));
+                setNewestCache(oldNewestCache.releaseNonNull());
             } else {
                 // We must have been deleted by the last call to disassociateDocumentLoader().
                 return;
@@ -973,14 +963,13 @@ void ApplicationCacheGroup::startLoadingEntry()
         return;
     }
     
-    EntryMap::const_iterator it = m_pendingEntries.begin();
+    auto firstPendingEntryURL = m_pendingEntries.begin()->key;
 
-    postListenerTask(ApplicationCacheHost::PROGRESS_EVENT, m_progressTotal, m_progressDone, m_associatedDocumentLoaders);
+    postListenerTask(eventNames().progressEvent, m_progressTotal, m_progressDone, m_associatedDocumentLoaders);
     m_progressDone++;
 
     ASSERT(!m_currentHandle);
-    
-    m_currentHandle = createResourceHandle(URL(ParsedURLString, it->key), m_newestCache ? m_newestCache->resourceForURL(it->key) : 0);
+    m_currentHandle = createResourceHandle(URL(ParsedURLString, firstPendingEntryURL), m_newestCache ? m_newestCache->resourceForURL(firstPendingEntryURL) : 0);
 }
 
 void ApplicationCacheGroup::deliverDelayedMainResources()
@@ -988,19 +977,15 @@ void ApplicationCacheGroup::deliverDelayedMainResources()
     // Need to copy loaders, because the cache group may be destroyed at the end of iteration.
     Vector<DocumentLoader*> loaders;
     copyToVector(m_pendingMasterResourceLoaders, loaders);
-    size_t count = loaders.size();
-    for (size_t i = 0; i != count; ++i) {
-        DocumentLoader* loader = loaders[i];
+    for (auto* loader : loaders) {
         if (loader->isLoadingMainResource())
             continue;
-
-        const ResourceError& error = loader->mainDocumentError();
-        if (error.isNull())
-            finishedLoadingMainResource(loader);
+        if (loader->mainDocumentError().isNull())
+            finishedLoadingMainResource(*loader);
         else
-            failedLoadingMainResource(loader);
+            failedLoadingMainResource(*loader);
     }
-    if (!count)
+    if (loaders.isEmpty())
         checkIfLoadIsComplete();
 }
 
@@ -1008,13 +993,12 @@ void ApplicationCacheGroup::addEntry(const String& url, unsigned type)
 {
     ASSERT(m_cacheBeingUpdated);
     ASSERT(!URL(ParsedURLString, url).hasFragmentIdentifier());
-    
+
     // Don't add the URL if we already have an master resource in the cache
     // (i.e., the main resource finished loading before the manifest).
-    if (ApplicationCacheResource* resource = m_cacheBeingUpdated->resourceForURL(url)) {
+    if (auto* resource = m_cacheBeingUpdated->resourceForURL(url)) {
         ASSERT(resource->type() & ApplicationCacheResource::Master);
         ASSERT(!m_frame->loader().documentLoader()->isLoadingMainResource());
-    
         resource->addType(type);
         return;
     }
@@ -1025,11 +1009,8 @@ void ApplicationCacheGroup::addEntry(const String& url, unsigned type)
         m_manifestResource->addType(type);
         return;
     }
-    
-    EntryMap::AddResult result = m_pendingEntries.add(url, type);
-    
-    if (!result.isNewEntry)
-        result.iterator->value |= type;
+
+    m_pendingEntries.add(url, type).iterator->value |= type;
 }
 
 void ApplicationCacheGroup::associateDocumentLoaderWithCache(DocumentLoader* loader, ApplicationCache* cache)
@@ -1040,63 +1021,63 @@ void ApplicationCacheGroup::associateDocumentLoaderWithCache(DocumentLoader* loa
 
     ASSERT(!m_isObsolete);
 
-    loader->applicationCacheHost()->setApplicationCache(cache);
+    loader->applicationCacheHost().setApplicationCache(cache);
 
     ASSERT(!m_associatedDocumentLoaders.contains(loader));
     m_associatedDocumentLoaders.add(loader);
 }
 
-class ChromeClientCallbackTimer: public TimerBase {
+class ChromeClientCallbackTimer final : public TimerBase {
 public:
-    ChromeClientCallbackTimer(ApplicationCacheGroup* cacheGroup)
-        : m_cacheGroup(cacheGroup)
+    ChromeClientCallbackTimer(ApplicationCacheGroup& group)
+        : m_group(group)
     {
     }
 
 private:
-    void fired() override
+    void fired() final
     {
-        m_cacheGroup->didReachMaxAppCacheSize();
+        m_group.didReachMaxAppCacheSize();
         delete this;
     }
-    // Note that there is no need to use a RefPtr here. The ApplicationCacheGroup instance is guaranteed
-    // to be alive when the timer fires since invoking the ChromeClient callback is part of its normal
+
+    // Note that there is no need to use a Ref here. The ApplicationCacheGroup instance is guaranteed
+    // to be alive when the timer fires since invoking the callback is part of its normal
     // update machinery and nothing can yet cause it to get deleted.
-    ApplicationCacheGroup* m_cacheGroup;
+    ApplicationCacheGroup& m_group;
 };
 
 void ApplicationCacheGroup::scheduleReachedMaxAppCacheSizeCallback()
 {
     ASSERT(isMainThread());
-    ChromeClientCallbackTimer* timer = new ChromeClientCallbackTimer(this);
+    auto* timer = new ChromeClientCallbackTimer(*this);
     timer->startOneShot(0);
     // The timer will delete itself once it fires.
 }
 
-void ApplicationCacheGroup::postListenerTask(ApplicationCacheHost::EventID eventID, int progressTotal, int progressDone, const HashSet<DocumentLoader*>& loaderSet)
+void ApplicationCacheGroup::postListenerTask(const AtomicString& eventType, int progressTotal, int progressDone, const HashSet<DocumentLoader*>& loaderSet)
 {
     for (auto& loader : loaderSet)
-        postListenerTask(eventID, progressTotal, progressDone, loader);
+        postListenerTask(eventType, progressTotal, progressDone, *loader);
 }
 
-void ApplicationCacheGroup::postListenerTask(ApplicationCacheHost::EventID eventID, int progressTotal, int progressDone, DocumentLoader* loader)
+void ApplicationCacheGroup::postListenerTask(const AtomicString& eventType, int progressTotal, int progressDone, DocumentLoader& loader)
 {
-    Frame* frame = loader->frame();
+    auto* frame = loader.frame();
     if (!frame)
         return;
     
-    ASSERT(frame->loader().documentLoader() == loader);
+    ASSERT(frame->loader().documentLoader() == &loader);
 
-    RefPtr<DocumentLoader> loaderProtector(loader);
-    frame->document()->postTask([loaderProtector, eventID, progressTotal, progressDone] (ScriptExecutionContext& context) {
+    RefPtr<DocumentLoader> protectedLoader(&loader);
+    frame->document()->postTask([protectedLoader, &eventType, progressTotal, progressDone] (ScriptExecutionContext& context) {
         ASSERT_UNUSED(context, context.isDocument());
-        Frame* frame = loaderProtector->frame();
+        auto* frame = protectedLoader->frame();
         if (!frame)
             return;
 
-        ASSERT(frame->loader().documentLoader() == loaderProtector);
-
-        loaderProtector->applicationCacheHost()->notifyDOMApplicationCache(eventID, progressTotal, progressDone);
+        ASSERT(frame->loader().documentLoader() == protectedLoader);
+        protectedLoader->applicationCacheHost().notifyDOMApplicationCache(eventType, progressTotal, progressDone);
     });
 }
 
@@ -1108,8 +1089,7 @@ void ApplicationCacheGroup::setUpdateStatus(UpdateStatus status)
 void ApplicationCacheGroup::clearStorageID()
 {
     m_storageID = 0;
-    
-    for (const auto& cache : m_caches)
+    for (auto& cache : m_caches)
         cache->clearStorageID();
 }
 
index b0644c4..fc851da 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008, 2009, 2010 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2008-2017 Apple Inc. All Rights Reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -49,8 +49,9 @@ enum ApplicationCacheUpdateOption {
     ApplicationCacheUpdateWithoutBrowsingContext
 };
 
-class ApplicationCacheGroup : ResourceHandleClient {
-    WTF_MAKE_NONCOPYABLE(ApplicationCacheGroup); WTF_MAKE_FAST_ALLOCATED;
+class ApplicationCacheGroup final : private ResourceHandleClient {
+    WTF_MAKE_NONCOPYABLE(ApplicationCacheGroup);
+    WTF_MAKE_FAST_ALLOCATED;
 public:
     explicit ApplicationCacheGroup(Ref<ApplicationCacheStorage>&&, const URL& manifestURL);
     virtual ~ApplicationCacheGroup();
@@ -60,8 +61,8 @@ public:
     static ApplicationCache* cacheForMainRequest(const ResourceRequest&, DocumentLoader*);
     static ApplicationCache* fallbackCacheForMainRequest(const ResourceRequest&, DocumentLoader*);
     
-    static void selectCache(Frame*, const URL& manifestURL);
-    static void selectCacheWithoutManifestURL(Frame*);
+    static void selectCache(Frame&, const URL& manifestURL);
+    static void selectCacheWithoutManifestURL(Frame&);
 
     ApplicationCacheStorage& storage() { return m_storage; }
     const URL& manifestURL() const { return m_manifestURL; }
@@ -73,31 +74,31 @@ public:
     unsigned storageID() const { return m_storageID; }
     void clearStorageID();
     
-    void update(Frame*, ApplicationCacheUpdateOption); // FIXME: Frame should not be needed when updating without browsing context.
-    void cacheDestroyed(ApplicationCache*);
+    void update(Frame&, ApplicationCacheUpdateOption); // FIXME: Frame should not be needed when updating without browsing context.
+    void cacheDestroyed(ApplicationCache&);
     
-    void abort(Frame*);
+    void abort(Frame&);
 
-    bool cacheIsComplete(ApplicationCache* cache) { return m_caches.contains(cache); }
+    bool cacheIsComplete(ApplicationCache& cache) { return m_caches.contains(&cache); }
 
-    void stopLoadingInFrame(Frame*);
+    void stopLoadingInFrame(Frame&);
 
     ApplicationCache* newestCache() const { return m_newestCache.get(); }
-    void setNewestCache(PassRefPtr<ApplicationCache>);
+    void setNewestCache(Ref<ApplicationCache>&&);
 
     void makeObsolete();
     bool isObsolete() const { return m_isObsolete; }
 
-    void finishedLoadingMainResource(DocumentLoader*);
-    void failedLoadingMainResource(DocumentLoader*);
+    void finishedLoadingMainResource(DocumentLoader&);
+    void failedLoadingMainResource(DocumentLoader&);
 
-    void disassociateDocumentLoader(DocumentLoader*);
+    void disassociateDocumentLoader(DocumentLoader&);
 
 private:
-    static void postListenerTask(ApplicationCacheHost::EventID id, const HashSet<DocumentLoader*>& set) { postListenerTask(id, 0, 0, set); }
-    static void postListenerTask(ApplicationCacheHost::EventID id, DocumentLoader* loader)  { postListenerTask(id, 0, 0, loader); }
-    static void postListenerTask(ApplicationCacheHost::EventID, int progressTotal, int progressDone, const HashSet<DocumentLoader*>&);
-    static void postListenerTask(ApplicationCacheHost::EventID, int progressTotal, int progressDone, DocumentLoader*);
+    static void postListenerTask(const AtomicString& eventType, const HashSet<DocumentLoader*>& set) { postListenerTask(eventType, 0, 0, set); }
+    static void postListenerTask(const AtomicString& eventType, DocumentLoader& loader)  { postListenerTask(eventType, 0, 0, loader); }
+    static void postListenerTask(const AtomicString& eventType, int progressTotal, int progressDone, const HashSet<DocumentLoader*>&);
+    static void postListenerTask(const AtomicString& eventType, int progressTotal, int progressDone, DocumentLoader&);
 
     void scheduleReachedMaxAppCacheSizeCallback();
 
@@ -135,7 +136,7 @@ private:
 
     URL m_manifestURL;
     RefPtr<SecurityOrigin> m_origin;
-    UpdateStatus m_updateStatus;
+    UpdateStatus m_updateStatus { Idle };
     
     // This is the newest complete cache in the group.
     RefPtr<ApplicationCache> m_newestCache;
@@ -150,26 +151,25 @@ private:
     // List of pending master entries, used during the update process to ensure that new master entries are cached.
     HashSet<DocumentLoader*> m_pendingMasterResourceLoaders;
     // How many of the above pending master entries have not yet finished downloading.
-    int m_downloadingPendingMasterResourceLoadersCount;
+    int m_downloadingPendingMasterResourceLoadersCount { 0 };
     
     // These are all the document loaders that are associated with a cache in this group.
     HashSet<DocumentLoader*> m_associatedDocumentLoaders;
 
     // The URLs and types of pending cache entries.
-    typedef HashMap<String, unsigned> EntryMap;
-    EntryMap m_pendingEntries;
+    HashMap<String, unsigned> m_pendingEntries;
     
     // The total number of items to be processed to update the cache group and the number that have been done.
-    int m_progressTotal;
-    int m_progressDone;
+    int m_progressTotal { 0 };
+    int m_progressDone { 0 };
 
     // Frame used for fetching resources when updating.
     // FIXME: An update started by a particular frame should not stop if it is destroyed, but there are other frames associated with the same cache group.
-    Frame* m_frame;
+    Frame* m_frame { nullptr };
   
     // An obsolete cache group is never stored, but the opposite is not true - storing may fail for multiple reasons, such as exceeding disk quota.
-    unsigned m_storageID;
-    bool m_isObsolete;
+    unsigned m_storageID { 0 };
+    bool m_isObsolete { false };
 
     // During update, this is used to handle asynchronously arriving results.
     enum CompletionType {
@@ -178,12 +178,12 @@ private:
         Failure,
         Completed
     };
-    CompletionType m_completionType;
+    CompletionType m_completionType { None };
 
     // This flag is set immediately after the ChromeClient::reachedMaxAppCacheSize() callback is invoked as a result of the storage layer failing to save a cache
     // due to reaching the maximum size of the application cache database file. This flag is used by ApplicationCacheGroup::checkIfLoadIsComplete() to decide
     // the course of action in case of this failure (i.e. call the ChromeClient callback or run the failure steps).
-    bool m_calledReachedMaxAppCacheSize;
+    bool m_calledReachedMaxAppCacheSize { false };
     
     RefPtr<ResourceHandle> m_currentHandle;
     RefPtr<ApplicationCacheResource> m_currentResource;
@@ -193,7 +193,7 @@ private:
     RefPtr<ResourceHandle> m_manifestHandle;
 
     int64_t m_availableSpaceInQuota;
-    bool m_originQuotaExceededPreviously;
+    bool m_originQuotaExceededPreviously { false };
 
     friend class ChromeClientCallbackTimer;
 };
index 7f5004c..9114699 100644 (file)
@@ -32,6 +32,7 @@
 #include "ContentSecurityPolicy.h"
 #include "DocumentLoader.h"
 #include "DOMApplicationCache.h"
+#include "EventNames.h"
 #include "FileSystem.h"
 #include "Frame.h"
 #include "FrameLoader.h"
 namespace WebCore {
 
 ApplicationCacheHost::ApplicationCacheHost(DocumentLoader& documentLoader)
-    : m_domApplicationCache(nullptr)
-    , m_documentLoader(documentLoader)
-    , m_defersEvents(true)
-    , m_candidateApplicationCacheGroup(nullptr)
+    : m_documentLoader(documentLoader)
 {
 }
 
 ApplicationCacheHost::~ApplicationCacheHost()
 {
     ASSERT(!m_applicationCache || !m_candidateApplicationCacheGroup || m_applicationCache->group() == m_candidateApplicationCacheGroup);
-
     if (m_applicationCache)
-        m_applicationCache->group()->disassociateDocumentLoader(&m_documentLoader);
+        m_applicationCache->group()->disassociateDocumentLoader(m_documentLoader);
     else if (m_candidateApplicationCacheGroup)
-        m_candidateApplicationCacheGroup->disassociateDocumentLoader(&m_documentLoader);
+        m_candidateApplicationCacheGroup->disassociateDocumentLoader(m_documentLoader);
 }
 
 void ApplicationCacheHost::selectCacheWithoutManifest()
 {
-    ApplicationCacheGroup::selectCacheWithoutManifestURL(m_documentLoader.frame());
+    ASSERT(m_documentLoader.frame());
+    ApplicationCacheGroup::selectCacheWithoutManifestURL(*m_documentLoader.frame());
 }
 
 void ApplicationCacheHost::selectCacheWithManifest(const URL& manifestURL)
 {
-    ApplicationCacheGroup::selectCache(m_documentLoader.frame(), manifestURL);
+    ASSERT(m_documentLoader.frame());
+    ApplicationCacheGroup::selectCache(*m_documentLoader.frame(), manifestURL);
 }
 
 void ApplicationCacheHost::maybeLoadMainResource(ResourceRequest& request, SubstituteData& substituteData)
@@ -140,12 +139,11 @@ bool ApplicationCacheHost::maybeLoadFallbackForMainError(const ResourceRequest&
 
 void ApplicationCacheHost::mainResourceDataReceived(const char*, int, long long, bool)
 {
-    // This method is here to facilitate alternate implemetations of this interface by the host browser.
 }
 
 void ApplicationCacheHost::failedLoadingMainResource()
 {
-    ApplicationCacheGroup* group = m_candidateApplicationCacheGroup;
+    auto* group = m_candidateApplicationCacheGroup;
     if (!group && m_applicationCache) {
         if (mainResourceApplicationCache()) {
             // Even when the main resource is being loaded from an application cache, loading can fail if aborted.
@@ -155,17 +153,17 @@ void ApplicationCacheHost::failedLoadingMainResource()
     }
     
     if (group)
-        group->failedLoadingMainResource(&m_documentLoader);
+        group->failedLoadingMainResource(m_documentLoader);
 }
 
 void ApplicationCacheHost::finishedLoadingMainResource()
 {
-    ApplicationCacheGroup* group = candidateApplicationCacheGroup();
+    auto* group = candidateApplicationCacheGroup();
     if (!group && applicationCache() && !mainResourceApplicationCache())
         group = applicationCache()->group();
     
     if (group)
-        group->finishedLoadingMainResource(&m_documentLoader);
+        group->finishedLoadingMainResource(m_documentLoader);
 }
 
 bool ApplicationCacheHost::maybeLoadResource(ResourceLoader& loader, const ResourceRequest& request, const URL& originalURL)
@@ -186,17 +184,19 @@ bool ApplicationCacheHost::maybeLoadResource(ResourceLoader& loader, const Resou
 
 bool ApplicationCacheHost::maybeLoadFallbackForRedirect(ResourceLoader* resourceLoader, ResourceRequest& request, const ResourceResponse& redirectResponse)
 {
-    if (!redirectResponse.isNull() && !protocolHostAndPortAreEqual(request.url(), redirectResponse.url()))
+    if (!redirectResponse.isNull() && !protocolHostAndPortAreEqual(request.url(), redirectResponse.url())) {
         if (scheduleLoadFallbackResourceFromApplicationCache(resourceLoader))
             return true;
+    }
     return false;
 }
 
 bool ApplicationCacheHost::maybeLoadFallbackForResponse(ResourceLoader* resourceLoader, const ResourceResponse& response)
 {
-    if (response.httpStatusCode() / 100 == 4 || response.httpStatusCode() / 100 == 5)
+    if (response.httpStatusCode() / 100 == 4 || response.httpStatusCode() / 100 == 5) {
         if (scheduleLoadFallbackResourceFromApplicationCache(resourceLoader))
             return true;
+    }
     return false;
 }
 
@@ -220,11 +220,9 @@ URL ApplicationCacheHost::createFileURL(const String& path)
     // app cache media files are always created with encodeForFileName(createCanonicalUUIDString()).
 
 #if USE(CF) && PLATFORM(WIN)
-    RetainPtr<CFURLRef> cfURL = adoptCF(CFURLCreateWithFileSystemPath(0, path.createCFString().get(), kCFURLWindowsPathStyle, false));
-    URL url(cfURL.get());
+    URL url(adoptCF(CFURLCreateWithFileSystemPath(0, path.createCFString().get(), kCFURLWindowsPathStyle, false)).get());
 #else
     URL url;
-
     url.setProtocol(ASCIILiteral("file"));
     url.setPath(path);
 #endif
@@ -246,7 +244,7 @@ bool ApplicationCacheHost::maybeLoadSynchronously(ResourceRequest& request, Reso
     if (!shouldLoadResourceFromApplicationCache(request, resource))
         return false;
 
-    RefPtr<SharedBuffer> responseData = resource ? bufferFromResource(*resource) : nullptr;
+    auto responseData = resource ? bufferFromResource(*resource) : nullptr;
     if (!responseData) {
         error = m_documentLoader.frameLoader()->client().cannotShowURLError(request);
         return true;
@@ -286,20 +284,21 @@ void ApplicationCacheHost::setDOMApplicationCache(DOMApplicationCache* domApplic
     m_domApplicationCache = domApplicationCache;
 }
 
-void ApplicationCacheHost::notifyDOMApplicationCache(EventID id, int total, int done)
+void ApplicationCacheHost::notifyDOMApplicationCache(const AtomicString& eventType, int total, int done)
 {
-    if (id != PROGRESS_EVENT)
+    if (eventType != eventNames().progressEvent)
         InspectorInstrumentation::updateApplicationCacheStatus(m_documentLoader.frame());
 
     if (m_defersEvents) {
         // Event dispatching is deferred until document.onload has fired.
-        m_deferredEvents.append(DeferredEvent(id, total, done));
+        m_deferredEvents.append({ eventType, total, done });
         return;
     }
-    dispatchDOMEvent(id, total, done);
+
+    dispatchDOMEvent(eventType, total, done);
 }
 
-void ApplicationCacheHost::stopLoadingInFrame(Frame* frame)
+void ApplicationCacheHost::stopLoadingInFrame(Frame& frame)
 {
     ASSERT(!m_applicationCache || !m_candidateApplicationCacheGroup || m_applicationCache->group() == m_candidateApplicationCacheGroup);
 
@@ -312,53 +311,68 @@ void ApplicationCacheHost::stopLoadingInFrame(Frame* frame)
 void ApplicationCacheHost::stopDeferringEvents()
 {
     Ref<DocumentLoader> protect(m_documentLoader);
-    for (auto& event : m_deferredEvents)
-        dispatchDOMEvent(event.eventID, event.progressTotal, event.progressDone);
+
+    // Note, do not cache the size in a local variable.
+    // This code needs to properly handle the case where more events are added to
+    // m_deferredEvents while iterating it. This is why we don't use a modern for loop.
+    for (size_t i = 0; i < m_deferredEvents.size(); ++i) {
+        auto& event = m_deferredEvents[i];
+        dispatchDOMEvent(event.eventType, event.progressTotal, event.progressDone);
+    }
+
     m_deferredEvents.clear();
     m_defersEvents = false;
 }
 
-void ApplicationCacheHost::fillResourceList(ResourceInfoList* resources)
+Vector<ApplicationCacheHost::ResourceInfo> ApplicationCacheHost::resourceList()
 {
-    ApplicationCache* cache = applicationCache();
+    Vector<ResourceInfo> result;
+
+    auto* cache = applicationCache();
     if (!cache || !cache->isComplete())
-        return;
+        return result;
 
-    for (const auto& urlAndResource : cache->resources()) {
-        ApplicationCacheResource* resource = urlAndResource.value.get();
+    result.reserveInitialCapacity(cache->resources().size());
 
-        unsigned type = resource->type();
+    for (auto& urlAndResource : cache->resources()) {
+        ASSERT(urlAndResource.value);
+        auto& resource = *urlAndResource.value;
+
+        unsigned type = resource.type();
         bool isMaster = type & ApplicationCacheResource::Master;
         bool isManifest = type & ApplicationCacheResource::Manifest;
         bool isExplicit = type & ApplicationCacheResource::Explicit;
         bool isForeign = type & ApplicationCacheResource::Foreign;
         bool isFallback = type & ApplicationCacheResource::Fallback;
 
-        resources->append(ResourceInfo(resource->url(), isMaster, isManifest, isFallback, isForeign, isExplicit, resource->estimatedSizeInStorage()));
+        result.uncheckedAppend({ resource.url(), isMaster, isManifest, isFallback, isForeign, isExplicit, resource.estimatedSizeInStorage() });
     }
+
+    return result;
 }
 
 ApplicationCacheHost::CacheInfo ApplicationCacheHost::applicationCacheInfo()
 {
-    ApplicationCache* cache = applicationCache();
+    auto* cache = applicationCache();
     if (!cache || !cache->isComplete())
-        return CacheInfo(URL(), 0, 0, 0);
+        return { { }, 0, 0, 0 };
 
     // FIXME: Add "Creation Time" and "Update Time" to Application Caches.
-    return CacheInfo(cache->manifestResource()->url(), 0, 0, cache->estimatedSizeInStorage());
+    return { cache->manifestResource()->url(), 0, 0, cache->estimatedSizeInStorage() };
 }
 
-void ApplicationCacheHost::dispatchDOMEvent(EventID id, int total, int done)
+static Ref<Event> createApplicationCacheEvent(const AtomicString& eventType, int total, int done)
 {
-    if (m_domApplicationCache) {
-        const AtomicString& eventType = DOMApplicationCache::toEventType(id);
-        RefPtr<Event> event;
-        if (id == PROGRESS_EVENT)
-            event = ProgressEvent::create(eventType, true, done, total);
-        else
-            event = Event::create(eventType, false, false);
-        m_domApplicationCache->dispatchEvent(*event);
-    }
+    if (eventType == eventNames().progressEvent)
+        return ProgressEvent::create(eventType, true, done, total);
+    return Event::create(eventType, false, false);
+}
+
+void ApplicationCacheHost::dispatchDOMEvent(const AtomicString& eventType, int total, int done)
+{
+    if (!m_domApplicationCache)
+        return;
+    m_domApplicationCache->dispatchEvent(createApplicationCacheEvent(eventType, total, done));
 }
 
 void ApplicationCacheHost::setCandidateApplicationCacheGroup(ApplicationCacheGroup* group)
@@ -367,25 +381,24 @@ void ApplicationCacheHost::setCandidateApplicationCacheGroup(ApplicationCacheGro
     m_candidateApplicationCacheGroup = group;
 }
     
-void ApplicationCacheHost::setApplicationCache(PassRefPtr<ApplicationCache> applicationCache)
+void ApplicationCacheHost::setApplicationCache(RefPtr<ApplicationCache>&& applicationCache)
 {
     if (m_candidateApplicationCacheGroup) {
         ASSERT(!m_applicationCache);
         m_candidateApplicationCacheGroup = nullptr;
     }
-
-    m_applicationCache = applicationCache;
+    m_applicationCache = WTFMove(applicationCache);
 }
 
 bool ApplicationCacheHost::shouldLoadResourceFromApplicationCache(const ResourceRequest& originalRequest, ApplicationCacheResource*& resource)
 {
-    ApplicationCache* cache = applicationCache();
+    auto* cache = applicationCache();
     if (!cache || !cache->isComplete())
         return false;
 
     ResourceRequest request(originalRequest);
-    if (Frame* loaderFrame = m_documentLoader.frame()) {
-        if (Document* document = loaderFrame->document())
+    if (auto* loaderFrame = m_documentLoader.frame()) {
+        if (auto* document = loaderFrame->document())
             document->contentSecurityPolicy()->upgradeInsecureRequestIfNeeded(request, ContentSecurityPolicy::InsecureRequestType::Load);
     }
     
@@ -430,7 +443,6 @@ bool ApplicationCacheHost::getApplicationCacheFallbackResource(const ResourceReq
 
     resource = cache->resourceForURL(fallbackURL);
     ASSERT(resource);
-
     return true;
 }
 
@@ -444,30 +456,27 @@ bool ApplicationCacheHost::scheduleLoadFallbackResourceFromApplicationCache(Reso
         return false;
 
     loader->willSwitchToSubstituteResource();
-
     m_documentLoader.scheduleSubstituteResourceLoad(*loader, *resource);
-
     return true;
 }
 
 ApplicationCacheHost::Status ApplicationCacheHost::status() const
 {
-    ApplicationCache* cache = applicationCache();    
+    auto* cache = applicationCache();
     if (!cache)
         return UNCACHED;
 
     switch (cache->group()->updateStatus()) {
-        case ApplicationCacheGroup::Checking:
-            return CHECKING;
-        case ApplicationCacheGroup::Downloading:
-            return DOWNLOADING;
-        case ApplicationCacheGroup::Idle: {
-            if (cache->group()->isObsolete())
-                return OBSOLETE;
-            if (cache != cache->group()->newestCache())
-                return UPDATEREADY;
-            return IDLE;
-        }
+    case ApplicationCacheGroup::Checking:
+        return CHECKING;
+    case ApplicationCacheGroup::Downloading:
+        return DOWNLOADING;
+    case ApplicationCacheGroup::Idle:
+        if (cache->group()->isObsolete())
+            return OBSOLETE;
+        if (cache != cache->group()->newestCache())
+            return UPDATEREADY;
+        return IDLE;
     }
 
     ASSERT_NOT_REACHED();
@@ -476,27 +485,30 @@ ApplicationCacheHost::Status ApplicationCacheHost::status() const
 
 bool ApplicationCacheHost::update()
 {
-    ApplicationCache* cache = applicationCache();
+    auto* cache = applicationCache();
     if (!cache)
         return false;
-    cache->group()->update(m_documentLoader.frame(), ApplicationCacheUpdateWithoutBrowsingContext);
+    auto* frame = m_documentLoader.frame();
+    if (!frame)
+        return false;
+    cache->group()->update(*frame, ApplicationCacheUpdateWithoutBrowsingContext);
     return true;
 }
 
 bool ApplicationCacheHost::swapCache()
 {
-    ApplicationCache* cache = applicationCache();
+    auto* cache = applicationCache();
     if (!cache)
         return false;
 
     // If the group of application caches to which cache belongs has the lifecycle status obsolete, unassociate document from cache.
     if (cache->group()->isObsolete()) {
-        cache->group()->disassociateDocumentLoader(&m_documentLoader);
+        cache->group()->disassociateDocumentLoader(m_documentLoader);
         return true;
     }
 
     // If there is no newer cache, raise an INVALID_STATE_ERR exception.
-    ApplicationCache* newestCache = cache->group()->newestCache();
+    auto* newestCache = cache->group()->newestCache();
     if (cache == newestCache)
         return false;
     
@@ -508,14 +520,13 @@ bool ApplicationCacheHost::swapCache()
 
 void ApplicationCacheHost::abort()
 {
-    ApplicationCacheGroup* cacheGroup = candidateApplicationCacheGroup();
-    if (cacheGroup)
-        cacheGroup->abort(m_documentLoader.frame());
-    else {
-        ApplicationCache* cache = applicationCache();
-        if (cache)
-            cache->group()->abort(m_documentLoader.frame());
-    }
+    auto* frame = m_documentLoader.frame();
+    if (!frame)
+        return;
+    if (auto* cacheGroup = candidateApplicationCacheGroup())
+        cacheGroup->abort(*frame);
+    else if (auto* cache = applicationCache())
+        cache->group()->abort(*frame);
 }
 
 bool ApplicationCacheHost::isApplicationCacheEnabled()
@@ -525,15 +536,12 @@ bool ApplicationCacheHost::isApplicationCacheEnabled()
 
 bool ApplicationCacheHost::isApplicationCacheBlockedForRequest(const ResourceRequest& request)
 {
-    Frame* frame = m_documentLoader.frame();
+    auto* frame = m_documentLoader.frame();
     if (!frame)
         return false;
-
     if (frame->isMainFrame())
         return false;
-
-    Ref<SecurityOrigin> origin(SecurityOrigin::create(request.url()));
-    return !origin.get().canAccessApplicationCache(frame->document()->topOrigin());
+    return !SecurityOrigin::create(request.url())->canAccessApplicationCache(frame->document()->topOrigin());
 }
 
 }  // namespace WebCore
index c95b23b..2bfdc62 100644 (file)
@@ -1,6 +1,7 @@
 /*
- * Copyright (c) 2009, Google Inc.  All rights reserved.
- * 
+ * Copyright (c) 2009, Google Inc. All rights reserved.
+ * Copyright (c) 2017 Apple Inc. All rights reserved.
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
  * met:
 
 #pragma once
 
-#include "PlatformExportMacros.h"
 #include "URL.h"
 #include <wtf/Deque.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
 #include <wtf/Vector.h>
 
 namespace WebCore {
-    class DOMApplicationCache;
-    class DocumentLoader;
-    class Frame;
-    class ResourceError;
-    class ResourceLoader;
-    class ResourceRequest;
-    class ResourceResponse;
-    class SharedBuffer;
-    class SubstituteData;
-    class ApplicationCache;
-    class ApplicationCacheGroup;
-    class ApplicationCacheResource;
-    class ApplicationCacheStorage;
-
-    class ApplicationCacheHost {
-        WTF_MAKE_NONCOPYABLE(ApplicationCacheHost); WTF_MAKE_FAST_ALLOCATED;
-    public:
-        // The Status numeric values are specified in the HTML5 spec.
-        enum Status {
-            UNCACHED = 0,
-            IDLE = 1,
-            CHECKING = 2,
-            DOWNLOADING = 3,
-            UPDATEREADY = 4,
-            OBSOLETE = 5
-        };
-
-        enum EventID {
-            CHECKING_EVENT = 0,
-            ERROR_EVENT,
-            NOUPDATE_EVENT,
-            DOWNLOADING_EVENT,
-            PROGRESS_EVENT,
-            UPDATEREADY_EVENT,
-            CACHED_EVENT,
-            OBSOLETE_EVENT  // Must remain the last value, this is used to size arrays.
-        };
-
-        struct CacheInfo {
-            CacheInfo(const URL& manifest, double creationTime, double updateTime, long long size)
-                : m_manifest(manifest)
-                , m_creationTime(creationTime)
-                , m_updateTime(updateTime)
-                , m_size(size) { }
-            URL m_manifest;
-            double m_creationTime;
-            double m_updateTime;
-            long long m_size;
-        };
-
-        struct ResourceInfo {
-            ResourceInfo(const URL& resource, bool isMaster, bool isManifest, bool isFallback, bool isForeign, bool isExplicit, long long size)
-                : m_resource(resource)
-                , m_isMaster(isMaster)
-                , m_isManifest(isManifest)
-                , m_isFallback(isFallback)
-                , m_isForeign(isForeign)
-                , m_isExplicit(isExplicit)
-                , m_size(size) { }
-            URL m_resource;
-            bool m_isMaster;
-            bool m_isManifest;
-            bool m_isFallback;
-            bool m_isForeign;
-            bool m_isExplicit;
-            long long m_size;
-        };
-
-        typedef Vector<ResourceInfo> ResourceInfoList;
-
-        explicit ApplicationCacheHost(DocumentLoader&);
-        ~ApplicationCacheHost();
-
-        static URL createFileURL(const String&);
-
-        void selectCacheWithoutManifest();
-        void selectCacheWithManifest(const URL& manifestURL);
-
-        void maybeLoadMainResource(ResourceRequest&, SubstituteData&);
-        void maybeLoadMainResourceForRedirect(ResourceRequest&, SubstituteData&);
-        bool maybeLoadFallbackForMainResponse(const ResourceRequest&, const ResourceResponse&);
-        void mainResourceDataReceived(const char* data, int length, long long encodedDataLength, bool allAtOnce);
-        void finishedLoadingMainResource();
-        void failedLoadingMainResource();
-
-        WEBCORE_EXPORT bool maybeLoadResource(ResourceLoader&, const ResourceRequest&, const URL& originalURL);
-        WEBCORE_EXPORT bool maybeLoadFallbackForRedirect(ResourceLoader*, ResourceRequest&, const ResourceResponse&);
-        WEBCORE_EXPORT bool maybeLoadFallbackForResponse(ResourceLoader*, const ResourceResponse&);
-        WEBCORE_EXPORT bool maybeLoadFallbackForError(ResourceLoader*, const ResourceError&);
-
-        bool maybeLoadSynchronously(ResourceRequest&, ResourceError&, ResourceResponse&, RefPtr<SharedBuffer>&);
-        void maybeLoadFallbackSynchronously(const ResourceRequest&, ResourceError&, ResourceResponse&, RefPtr<SharedBuffer>&);
-
-        bool canCacheInPageCache();
-
-        Status status() const;  
-        bool update();
-        bool swapCache();
-        void abort();
-
-        void setDOMApplicationCache(DOMApplicationCache*);
-        void notifyDOMApplicationCache(EventID, int progressTotal, int progressDone);
-
-        void stopLoadingInFrame(Frame*);
-
-        void stopDeferringEvents(); // Also raises the events that have been queued up.
-
-        void fillResourceList(ResourceInfoList*);
-        CacheInfo applicationCacheInfo();
-
-        bool shouldLoadResourceFromApplicationCache(const ResourceRequest&, ApplicationCacheResource*&);
-        bool getApplicationCacheFallbackResource(const ResourceRequest&, ApplicationCacheResource*&, ApplicationCache* = nullptr);
-
-    private:
-        bool isApplicationCacheEnabled();
-        bool isApplicationCacheBlockedForRequest(const ResourceRequest&);
-
-        struct DeferredEvent {
-            EventID eventID;
-            int progressTotal;
-            int progressDone;
-            DeferredEvent(EventID id, int total, int done) : eventID(id), progressTotal(total), progressDone(done) { }
-        };
-
-        DOMApplicationCache* m_domApplicationCache;
-        DocumentLoader& m_documentLoader;
-        bool m_defersEvents; // Events are deferred until after document onload.
-        Vector<DeferredEvent> m_deferredEvents;
-
-        void dispatchDOMEvent(EventID, int progressTotal, int progressDone);
-
-        friend class ApplicationCacheGroup;
-        friend class ApplicationCacheStorage;
-
-        bool scheduleLoadFallbackResourceFromApplicationCache(ResourceLoader*, ApplicationCache* = nullptr);
-        void setCandidateApplicationCacheGroup(ApplicationCacheGroup* group);
-        ApplicationCacheGroup* candidateApplicationCacheGroup() const { return m_candidateApplicationCacheGroup; }
-        void setApplicationCache(PassRefPtr<ApplicationCache> applicationCache);
-        ApplicationCache* applicationCache() const { return m_applicationCache.get(); }
-        ApplicationCache* mainResourceApplicationCache() const { return m_mainResourceApplicationCache.get(); }
-        bool maybeLoadFallbackForMainError(const ResourceRequest&, const ResourceError&);
-
-        // The application cache that the document loader is associated with (if any).
-        RefPtr<ApplicationCache> m_applicationCache;
-
-        // Before an application cache has finished loading, this will be the candidate application
-        // group that the document loader is associated with.
-        ApplicationCacheGroup* m_candidateApplicationCacheGroup;
-
-        // This is the application cache the main resource was loaded from (if any).
-        RefPtr<ApplicationCache> m_mainResourceApplicationCache;
+
+class ApplicationCache;
+class ApplicationCacheGroup;
+class ApplicationCacheResource;
+class ApplicationCacheStorage;
+class DOMApplicationCache;
+class DocumentLoader;
+class Frame;
+class ResourceError;
+class ResourceLoader;
+class ResourceRequest;
+class ResourceResponse;
+class SharedBuffer;
+class SubstituteData;
+
+class ApplicationCacheHost {
+    WTF_MAKE_NONCOPYABLE(ApplicationCacheHost); WTF_MAKE_FAST_ALLOCATED;
+public:
+    // The Status numeric values are specified in the HTML5 spec.
+    enum Status {
+        UNCACHED = 0,
+        IDLE = 1,
+        CHECKING = 2,
+        DOWNLOADING = 3,
+        UPDATEREADY = 4,
+        OBSOLETE = 5
+    };
+
+    struct CacheInfo {
+        URL manifest;
+        double creationTime;
+        double updateTime;
+        long long size;
+    };
+
+    struct ResourceInfo {
+        URL resource;
+        bool isMaster;
+        bool isManifest;
+        bool isFallback;
+        bool isForeign;
+        bool isExplicit;
+        long long size;
+    };
+
+    explicit ApplicationCacheHost(DocumentLoader&);
+    ~ApplicationCacheHost();
+
+    static URL createFileURL(const String&);
+
+    void selectCacheWithoutManifest();
+    void selectCacheWithManifest(const URL& manifestURL);
+
+    void maybeLoadMainResource(ResourceRequest&, SubstituteData&);
+    void maybeLoadMainResourceForRedirect(ResourceRequest&, SubstituteData&);
+    bool maybeLoadFallbackForMainResponse(const ResourceRequest&, const ResourceResponse&);
+    void mainResourceDataReceived(const char* data, int length, long long encodedDataLength, bool allAtOnce);
+    void finishedLoadingMainResource();
+    void failedLoadingMainResource();
+
+    WEBCORE_EXPORT bool maybeLoadResource(ResourceLoader&, const ResourceRequest&, const URL& originalURL);
+    WEBCORE_EXPORT bool maybeLoadFallbackForRedirect(ResourceLoader*, ResourceRequest&, const ResourceResponse&);
+    WEBCORE_EXPORT bool maybeLoadFallbackForResponse(ResourceLoader*, const ResourceResponse&);
+    WEBCORE_EXPORT bool maybeLoadFallbackForError(ResourceLoader*, const ResourceError&);
+
+    bool maybeLoadSynchronously(ResourceRequest&, ResourceError&, ResourceResponse&, RefPtr<SharedBuffer>&);
+    void maybeLoadFallbackSynchronously(const ResourceRequest&, ResourceError&, ResourceResponse&, RefPtr<SharedBuffer>&);
+
+    bool canCacheInPageCache();
+
+    Status status() const;
+    bool update();
+    bool swapCache();
+    void abort();
+
+    void setDOMApplicationCache(DOMApplicationCache*);
+    void notifyDOMApplicationCache(const AtomicString& eventType, int progressTotal, int progressDone);
+
+    void stopLoadingInFrame(Frame&);
+
+    void stopDeferringEvents(); // Also raises the events that have been queued up.
+
+    Vector<ResourceInfo> resourceList();
+    CacheInfo applicationCacheInfo();
+
+    bool shouldLoadResourceFromApplicationCache(const ResourceRequest&, ApplicationCacheResource*&);
+    bool getApplicationCacheFallbackResource(const ResourceRequest&, ApplicationCacheResource*&, ApplicationCache* = nullptr);
+
+private:
+    friend class ApplicationCacheGroup;
+
+    struct DeferredEvent {
+        AtomicString eventType;
+        int progressTotal;
+        int progressDone;
     };
 
+    bool isApplicationCacheEnabled();
+    bool isApplicationCacheBlockedForRequest(const ResourceRequest&);
+
+    void dispatchDOMEvent(const AtomicString& eventType, int progressTotal, int progressDone);
+
+    bool scheduleLoadFallbackResourceFromApplicationCache(ResourceLoader*, ApplicationCache* = nullptr);
+    void setCandidateApplicationCacheGroup(ApplicationCacheGroup*);
+    ApplicationCacheGroup* candidateApplicationCacheGroup() const { return m_candidateApplicationCacheGroup; }
+    void setApplicationCache(RefPtr<ApplicationCache>&&);
+    ApplicationCache* applicationCache() const { return m_applicationCache.get(); }
+    ApplicationCache* mainResourceApplicationCache() const { return m_mainResourceApplicationCache.get(); }
+    bool maybeLoadFallbackForMainError(const ResourceRequest&, const ResourceError&);
+
+    DOMApplicationCache* m_domApplicationCache { nullptr };
+    DocumentLoader& m_documentLoader;
+
+    bool m_defersEvents { true }; // Events are deferred until after document onload.
+    Vector<DeferredEvent> m_deferredEvents;
+
+    // The application cache that the document loader is associated with (if any).
+    RefPtr<ApplicationCache> m_applicationCache;
+
+    // Before an application cache has finished loading, this will be the candidate application
+    // group that the document loader is associated with.
+    ApplicationCacheGroup* m_candidateApplicationCacheGroup { nullptr };
+
+    // This is the application cache the main resource was loaded from (if any).
+    RefPtr<ApplicationCache> m_mainResourceApplicationCache;
+};
+
 }  // namespace WebCore
index df103e4..f4fa95b 100644 (file)
@@ -126,36 +126,32 @@ ApplicationCacheGroup* ApplicationCacheStorage::loadCacheGroup(const URL& manife
     if (!cache)
         return nullptr;
         
-    ApplicationCacheGroup* group = new ApplicationCacheGroup(*this, manifestURL);
-      
-    group->setStorageID(static_cast<unsigned>(statement.getColumnInt64(0)));
-    group->setNewestCache(WTFMove(cache));
-
-    return group;
+    auto& group = *new ApplicationCacheGroup(*this, manifestURL);
+    group.setStorageID(static_cast<unsigned>(statement.getColumnInt64(0)));
+    group.setNewestCache(cache.releaseNonNull());
+    return &group;
 }    
 
 ApplicationCacheGroup* ApplicationCacheStorage::findOrCreateCacheGroup(const URL& manifestURL)
 {
     ASSERT(!manifestURL.hasFragmentIdentifier());
 
-    CacheGroupMap::AddResult result = m_cachesInMemory.add(manifestURL, nullptr);
-    
+    auto result = m_cachesInMemory.add(manifestURL, nullptr);
     if (!result.isNewEntry) {
         ASSERT(result.iterator->value);
         return result.iterator->value;
     }
 
     // Look up the group in the database
-    ApplicationCacheGroup* group = loadCacheGroup(manifestURL);
+    auto* group = loadCacheGroup(manifestURL);
     
     // If the group was not found we need to create it
     if (!group) {
         group = new ApplicationCacheGroup(*this, manifestURL);
         m_cacheHostSet.add(urlHostHash(manifestURL));
     }
-    
+
     result.iterator->value = group;
-    
     return group;
 }
 
@@ -244,20 +240,18 @@ ApplicationCacheGroup* ApplicationCacheStorage::cacheGroupForURL(const URL& url)
         if (!cache)
             continue;
 
-        ApplicationCacheResource* resource = cache->resourceForURL(url);
+        auto* resource = cache->resourceForURL(url);
         if (!resource)
             continue;
         if (resource->type() & ApplicationCacheResource::Foreign)
             continue;
 
-        ApplicationCacheGroup* group = new ApplicationCacheGroup(*this, manifestURL);
-        
-        group->setStorageID(static_cast<unsigned>(statement.getColumnInt64(0)));
-        group->setNewestCache(WTFMove(cache));
-        
-        m_cachesInMemory.set(group->manifestURL(), group);
-        
-        return group;
+        auto& group = *new ApplicationCacheGroup(*this, manifestURL);
+        group.setStorageID(static_cast<unsigned>(statement.getColumnInt64(0)));
+        group.setNewestCache(cache.releaseNonNull());
+        m_cachesInMemory.set(group.manifestURL(), &group);
+
+        return &group;
     }
 
     if (result != SQLITE_DONE)
@@ -320,14 +314,13 @@ ApplicationCacheGroup* ApplicationCacheStorage::fallbackCacheGroupForURL(const U
         if (cache->resourceForURL(fallbackURL)->type() & ApplicationCacheResource::Foreign)
             continue;
 
-        ApplicationCacheGroup* group = new ApplicationCacheGroup(*this, manifestURL);
-        
-        group->setStorageID(static_cast<unsigned>(statement.getColumnInt64(0)));
-        group->setNewestCache(WTFMove(cache));
-        
-        m_cachesInMemory.set(group->manifestURL(), group);
-        
-        return group;
+        auto& group = *new ApplicationCacheGroup(*this, manifestURL);
+        group.setStorageID(static_cast<unsigned>(statement.getColumnInt64(0)));
+        group.setNewestCache(cache.releaseNonNull());
+
+        m_cachesInMemory.set(group.manifestURL(), &group);
+
+        return &group;
     }
 
     if (result != SQLITE_DONE)
@@ -336,33 +329,33 @@ ApplicationCacheGroup* ApplicationCacheStorage::fallbackCacheGroupForURL(const U
     return nullptr;
 }
 
-void ApplicationCacheStorage::cacheGroupDestroyed(ApplicationCacheGroup* group)
+void ApplicationCacheStorage::cacheGroupDestroyed(ApplicationCacheGroup& group)
 {
-    if (group->isObsolete()) {
-        ASSERT(!group->storageID());
-        ASSERT(m_cachesInMemory.get(group->manifestURL()) != group);
+    if (group.isObsolete()) {
+        ASSERT(!group.storageID());
+        ASSERT(m_cachesInMemory.get(group.manifestURL()) != &group);
         return;
     }
 
-    ASSERT(m_cachesInMemory.get(group->manifestURL()) == group);
+    ASSERT(m_cachesInMemory.get(group.manifestURL()) == &group);
 
-    m_cachesInMemory.remove(group->manifestURL());
+    m_cachesInMemory.remove(group.manifestURL());
     
     // If the cache group is half-created, we don't want it in the saved set (as it is not stored in database).
-    if (!group->storageID())
-        m_cacheHostSet.remove(urlHostHash(group->manifestURL()));
+    if (!group.storageID())
+        m_cacheHostSet.remove(urlHostHash(group.manifestURL()));
 }
 
-void ApplicationCacheStorage::cacheGroupMadeObsolete(ApplicationCacheGroup* group)
+void ApplicationCacheStorage::cacheGroupMadeObsolete(ApplicationCacheGroup& group)
 {
-    ASSERT(m_cachesInMemory.get(group->manifestURL()) == group);
-    ASSERT(m_cacheHostSet.contains(urlHostHash(group->manifestURL())));
+    ASSERT(m_cachesInMemory.get(group.manifestURL()) == &group);
+    ASSERT(m_cacheHostSet.contains(urlHostHash(group.manifestURL())));
 
-    if (ApplicationCache* newestCache = group->newestCache())
+    if (auto* newestCache = group.newestCache())
         remove(newestCache);
 
-    m_cachesInMemory.remove(group->manifestURL());
-    m_cacheHostSet.remove(urlHostHash(group->manifestURL()));
+    m_cachesInMemory.remove(group.manifestURL());
+    m_cacheHostSet.remove(urlHostHash(group.manifestURL()));
 }
 
 const String& ApplicationCacheStorage::cacheDirectory() const
@@ -996,7 +989,7 @@ bool ApplicationCacheStorage::checkOriginQuota(ApplicationCacheGroup* group, App
     return true;
 }
 
-bool ApplicationCacheStorage::storeNewestCache(ApplicationCacheGroup* group, ApplicationCache* oldCache, FailureReason& failureReason)
+bool ApplicationCacheStorage::storeNewestCache(ApplicationCacheGroup& group, ApplicationCache* oldCache, FailureReason& failureReason)
 {
     openDatabase(true);
 
@@ -1012,24 +1005,24 @@ bool ApplicationCacheStorage::storeNewestCache(ApplicationCacheGroup* group, App
 
     // Check if this would reach the per-origin quota.
     int64_t totalSpaceNeededIgnored;
-    if (!checkOriginQuota(group, oldCache, group->newestCache(), totalSpaceNeededIgnored)) {
+    if (!checkOriginQuota(&group, oldCache, group.newestCache(), totalSpaceNeededIgnored)) {
         failureReason = OriginQuotaReached;
         return false;
     }
 
     GroupStorageIDJournal groupStorageIDJournal;
-    if (!group->storageID()) {
+    if (!group.storageID()) {
         // Store the group
-        if (!store(group, &groupStorageIDJournal)) {
+        if (!store(&group, &groupStorageIDJournal)) {
             checkForMaxSizeReached();
             failureReason = isMaximumSizeReached() ? TotalQuotaReached : DiskOrOperationFailure;
             return false;
         }
     }
     
-    ASSERT(group->newestCache());
-    ASSERT(!group->isObsolete());
-    ASSERT(!group->newestCache()->storageID());
+    ASSERT(group.newestCache());
+    ASSERT(!group.isObsolete());
+    ASSERT(!group.newestCache()->storageID());
     
     // Log the storageID changes to the in-memory resource objects. The journal
     // object will roll them back automatically in case a database operation
@@ -1037,7 +1030,7 @@ bool ApplicationCacheStorage::storeNewestCache(ApplicationCacheGroup* group, App
     ResourceStorageIDJournal resourceStorageIDJournal;
 
     // Store the newest cache
-    if (!store(group->newestCache(), &resourceStorageIDJournal)) {
+    if (!store(group.newestCache(), &resourceStorageIDJournal)) {
         checkForMaxSizeReached();
         failureReason = isMaximumSizeReached() ? TotalQuotaReached : DiskOrOperationFailure;
         return false;
@@ -1051,8 +1044,8 @@ bool ApplicationCacheStorage::storeNewestCache(ApplicationCacheGroup* group, App
         return false;
     }
     
-    statement.bindInt64(1, group->newestCache()->storageID());
-    statement.bindInt64(2, group->storageID());
+    statement.bindInt64(1, group.newestCache()->storageID());
+    statement.bindInt64(2, group.storageID());
     
     if (!executeStatement(statement)) {
         failureReason = DiskOrOperationFailure;
@@ -1065,22 +1058,24 @@ bool ApplicationCacheStorage::storeNewestCache(ApplicationCacheGroup* group, App
     return true;
 }
 
-bool ApplicationCacheStorage::storeNewestCache(ApplicationCacheGroup* group)
+bool ApplicationCacheStorage::storeNewestCache(ApplicationCacheGroup& group)
 {
     // Ignore the reason for failing, just attempt the store.
     FailureReason ignoredFailureReason;
-    return storeNewestCache(group, 0, ignoredFailureReason);
+    return storeNewestCache(group, nullptr, ignoredFailureReason);
 }
 
-template <typename CharacterType>
-static inline void parseHeader(const CharacterType* header, size_t headerLength, ResourceResponse& response)
+template<typename CharacterType>
+static inline void parseHeader(const CharacterType* header, unsigned headerLength, ResourceResponse& response)
 {
-    size_t pos = find(header, headerLength, ':');
-    ASSERT(pos != notFound);
-    
-    String headerName = AtomicString(header, pos);
-    String headerValue = String(header + pos + 1, headerLength - pos - 1);
-    
+    ASSERT(find(header, headerLength, ':') != notFound);
+    unsigned colonPosition = find(header, headerLength, ':');
+
+    // Save memory by putting the header names into atomic strings so each is stored only once,
+    // even though the setHTTPHeaderField function does not require an atomic string.
+    AtomicString headerName { header, colonPosition };
+    String headerValue { header + colonPosition + 1, headerLength - colonPosition - 1 };
+
     response.setHTTPHeaderField(headerName, headerValue);
 }
 
@@ -1107,7 +1102,7 @@ static inline void parseHeaders(const String& headers, ResourceResponse& respons
     }
 }
     
-PassRefPtr<ApplicationCache> ApplicationCacheStorage::loadCache(unsigned storageID)
+RefPtr<ApplicationCache> ApplicationCacheStorage::loadCache(unsigned storageID)
 {
     ASSERT(SQLiteDatabaseTracker::hasTransactionInProgress());
     SQLiteStatement cacheStatement(m_database,
@@ -1408,10 +1403,11 @@ bool ApplicationCacheStorage::deleteCacheGroup(const String& manifestURL)
     SQLiteTransactionInProgressAutoCounter transactionCounter;
 
     SQLiteTransaction deleteTransaction(m_database);
+
     // Check to see if the group is in memory.
-    ApplicationCacheGroup* group = m_cachesInMemory.get(manifestURL);
+    auto* group = m_cachesInMemory.get(manifestURL);
     if (group)
-        cacheGroupMadeObsolete(group);
+        cacheGroupMadeObsolete(*group);
     else {
         // The cache group is not in memory, so remove it from the disk.
         openDatabase(false);
@@ -1424,9 +1420,9 @@ bool ApplicationCacheStorage::deleteCacheGroup(const String& manifestURL)
     }
 
     deleteTransaction.commit();
-    
+
     checkForDeletedResources();
-    
+
     return true;
 }
 
index e48e866..9fa292e 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008, 2010, 2011 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2008-2017 Apple Inc. All Rights Reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -41,7 +41,7 @@ class ApplicationCacheResource;
 class URL;
 class SecurityOrigin;
 class SharedBuffer;
-template <class T> class StorageIDJournal;
+template<typename> class StorageIDJournal;
 
 class ApplicationCacheStorage : public RefCounted<ApplicationCacheStorage> {
 public:
@@ -73,19 +73,19 @@ public:
 
     ApplicationCacheGroup* findOrCreateCacheGroup(const URL& manifestURL);
     ApplicationCacheGroup* findInMemoryCacheGroup(const URL& manifestURL) const;
-    void cacheGroupDestroyed(ApplicationCacheGroup*);
-    void cacheGroupMadeObsolete(ApplicationCacheGroup*);
-        
-    bool storeNewestCache(ApplicationCacheGroup*, ApplicationCache* oldCache, FailureReason& failureReason);
-    bool storeNewestCache(ApplicationCacheGroup*); // Updates the cache group, but doesn't remove old cache.
+    void cacheGroupDestroyed(ApplicationCacheGroup&);
+    void cacheGroupMadeObsolete(ApplicationCacheGroup&);
+
+    bool storeNewestCache(ApplicationCacheGroup&, ApplicationCache* oldCache, FailureReason&);
+    bool storeNewestCache(ApplicationCacheGroup&); // Updates the cache group, but doesn't remove old cache.
     bool store(ApplicationCacheResource*, ApplicationCache*);
     bool storeUpdatedType(ApplicationCacheResource*, ApplicationCache*);
 
     // Removes the group if the cache to be removed is the newest one (so, storeNewestCache() needs to be called beforehand when updating).
     void remove(ApplicationCache*);
-    
+
     WEBCORE_EXPORT void empty();
-    
+
     bool getManifestURLs(Vector<URL>* urls);
     bool cacheGroupSize(const String& manifestURL, int64_t* size);
     bool deleteCacheGroup(const String& manifestURL);
@@ -105,14 +105,15 @@ public:
 
     static int64_t unknownQuota() { return -1; }
     static int64_t noQuota() { return std::numeric_limits<int64_t>::max(); }
+
 private:
     ApplicationCacheStorage(const String& cacheDirectory, const String& flatFileSubdirectoryName);
 
-    PassRefPtr<ApplicationCache> loadCache(unsigned storageID);
+    RefPtr<ApplicationCache> loadCache(unsigned storageID);
     ApplicationCacheGroup* loadCacheGroup(const URL& manifestURL);
     
-    typedef StorageIDJournal<ApplicationCacheResource> ResourceStorageIDJournal;
-    typedef StorageIDJournal<ApplicationCacheGroup> GroupStorageIDJournal;
+    using ResourceStorageIDJournal = StorageIDJournal<ApplicationCacheResource>;
+    using GroupStorageIDJournal = StorageIDJournal<ApplicationCacheGroup>;
 
     bool store(ApplicationCacheGroup*, GroupStorageIDJournal*);
     bool store(ApplicationCache*, ResourceStorageIDJournal*);
@@ -152,8 +153,7 @@ private:
     // we keep a hash set of the hosts of the manifest URLs of all non-obsolete cache groups.
     HashCountedSet<unsigned, AlreadyHashed> m_cacheHostSet;
     
-    typedef HashMap<String, ApplicationCacheGroup*> CacheGroupMap;
-    CacheGroupMap m_cachesInMemory; // Excludes obsolete cache groups.
+    HashMap<String, ApplicationCacheGroup*> m_cachesInMemory; // Excludes obsolete cache groups.
 
     friend class WTF::NeverDestroyed<ApplicationCacheStorage>;
 };
index 4d0eef2..ed8fad8 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008, 2009 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2008-2017 Apple Inc. All Rights Reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #include "ApplicationCacheHost.h"
 #include "Document.h"
 #include "DocumentLoader.h"
-#include "Event.h"
-#include "EventListener.h"
-#include "EventNames.h"
 #include "ExceptionCode.h"
 #include "Frame.h"
-#include "FrameLoader.h"
 
 namespace WebCore {
 
-DOMApplicationCache::DOMApplicationCache(Frame* frame)
-    : DOMWindowProperty(frame)
+DOMApplicationCache::DOMApplicationCache(Frame& frame)
+    : DOMWindowProperty(&frame)
 {
-    ApplicationCacheHost* cacheHost = applicationCacheHost();
-    if (cacheHost)
-        cacheHost->setDOMApplicationCache(this);
+    if (auto* host = applicationCacheHost())
+        host->setDOMApplicationCache(this);
 }
 
 void DOMApplicationCache::disconnectFrameForDocumentSuspension()
 {
-    if (ApplicationCacheHost* cacheHost = applicationCacheHost())
-        cacheHost->setDOMApplicationCache(nullptr);
+    if (auto* host = applicationCacheHost())
+        host->setDOMApplicationCache(nullptr);
     DOMWindowProperty::disconnectFrameForDocumentSuspension();
 }
 
 void DOMApplicationCache::reconnectFrameFromDocumentSuspension(Frame* frame)
 {
     DOMWindowProperty::reconnectFrameFromDocumentSuspension(frame);
-    if (ApplicationCacheHost* cacheHost = applicationCacheHost())
-        cacheHost->setDOMApplicationCache(this);
+    if (auto* host = applicationCacheHost())
+        host->setDOMApplicationCache(this);
 }
 
 void DOMApplicationCache::willDestroyGlobalObjectInFrame()
 {
-    if (ApplicationCacheHost* cacheHost = applicationCacheHost())
-        cacheHost->setDOMApplicationCache(nullptr);
+    if (auto* host = applicationCacheHost())
+        host->setDOMApplicationCache(nullptr);
     DOMWindowProperty::willDestroyGlobalObjectInFrame();
 }
 
 ApplicationCacheHost* DOMApplicationCache::applicationCacheHost() const
 {
-    if (!m_frame || !m_frame->loader().documentLoader())
+    if (!m_frame)
         return nullptr;
-    return m_frame->loader().documentLoader()->applicationCacheHost();
+    auto* documentLoader = m_frame->loader().documentLoader();
+    if (!documentLoader)
+        return nullptr;
+    return &documentLoader->applicationCacheHost();
 }
 
 unsigned short DOMApplicationCache::status() const
 {
-    ApplicationCacheHost* cacheHost = applicationCacheHost();
-    if (!cacheHost)
+    auto* host = applicationCacheHost();
+    if (!host)
         return ApplicationCacheHost::UNCACHED;
-    return cacheHost->status();
+    return host->status();
 }
 
 ExceptionOr<void> DOMApplicationCache::update()
 {
-    auto* cacheHost = applicationCacheHost();
-    if (!cacheHost || !cacheHost->update())
+    auto* host = applicationCacheHost();
+    if (!host || !host->update())
         return Exception { INVALID_STATE_ERR };
     return { };
 }
 
 ExceptionOr<void> DOMApplicationCache::swapCache()
 {
-    auto* cacheHost = applicationCacheHost();
-    if (!cacheHost || !cacheHost->swapCache())
+    auto* host = applicationCacheHost();
+    if (!host || !host->swapCache())
         return Exception { INVALID_STATE_ERR };
     return { };
 }
 
 void DOMApplicationCache::abort()
 {
-    ApplicationCacheHost* cacheHost = applicationCacheHost();
-    if (cacheHost)
-        cacheHost->abort();
+    if (auto* host = applicationCacheHost())
+        host->abort();
 }
 
 ScriptExecutionContext* DOMApplicationCache::scriptExecutionContext() const
 {
-    if (m_frame)
-        return m_frame->document();
-    return nullptr;
-}
-
-const AtomicString& DOMApplicationCache::toEventType(ApplicationCacheHost::EventID id)
-{
-    switch (id) {
-    case ApplicationCacheHost::CHECKING_EVENT:
-        return eventNames().checkingEvent;
-    case ApplicationCacheHost::ERROR_EVENT:
-        return eventNames().errorEvent;
-    case ApplicationCacheHost::NOUPDATE_EVENT:
-        return eventNames().noupdateEvent;
-    case ApplicationCacheHost::DOWNLOADING_EVENT:
-        return eventNames().downloadingEvent;
-    case ApplicationCacheHost::PROGRESS_EVENT:
-        return eventNames().progressEvent;
-    case ApplicationCacheHost::UPDATEREADY_EVENT:
-        return eventNames().updatereadyEvent;
-    case ApplicationCacheHost::CACHED_EVENT:
-        return eventNames().cachedEvent;
-    case ApplicationCacheHost::OBSOLETE_EVENT:            
-        return eventNames().obsoleteEvent;
-    }
-    ASSERT_NOT_REACHED();
-    return eventNames().errorEvent;
+    if (!m_frame)
+        return nullptr;
+    return m_frame->document();
 }
 
 } // namespace WebCore
index 3f20d8c..cf6d2a9 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008, 2009 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2008-2017 Apple Inc. All Rights Reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 
 #pragma once
 
-#include "ApplicationCacheHost.h"
 #include "DOMWindowProperty.h"
 #include "EventTarget.h"
-#include "ExceptionOr.h"
-#include "ScriptWrappable.h"
-#include <wtf/HashMap.h>
-#include <wtf/text/AtomicStringHash.h>
 
 namespace WebCore {
 
+class ApplicationCacheHost;
 class Frame;
-class URL;
 
 class DOMApplicationCache final : public RefCounted<DOMApplicationCache>, public EventTargetWithInlineData, public DOMWindowProperty {
 public:
-    static Ref<DOMApplicationCache> create(Frame* frame) { return adoptRef(*new DOMApplicationCache(frame)); }
+    static Ref<DOMApplicationCache> create(Frame& frame) { return adoptRef(*new DOMApplicationCache(frame)); }
     virtual ~DOMApplicationCache() { ASSERT(!m_frame); }
 
-    void disconnectFrameForDocumentSuspension() override;
-    void reconnectFrameFromDocumentSuspension(Frame*) override;
-    void willDestroyGlobalObjectInFrame() override;
-
     unsigned short status() const;
     ExceptionOr<void> update();
     ExceptionOr<void> swapCache();
     void abort();
 
-    using RefCounted<DOMApplicationCache>::ref;
-    using RefCounted<DOMApplicationCache>::deref;
+    using RefCounted::ref;
+    using RefCounted::deref;
 
-    EventTargetInterface eventTargetInterface() const override { return DOMApplicationCacheEventTargetInterfaceType; }
-    ScriptExecutionContext* scriptExecutionContext() const override;
+private:
+    explicit DOMApplicationCache(Frame&);
 
-    static const AtomicString& toEventType(ApplicationCacheHost::EventID id);
+    void refEventTarget() final { ref(); }
+    void derefEventTarget() final { deref(); }
 
-private:
-    explicit DOMApplicationCache(Frame*);
+    EventTargetInterface eventTargetInterface() const final { return DOMApplicationCacheEventTargetInterfaceType; }
+    ScriptExecutionContext* scriptExecutionContext() const final;
 
-    void refEventTarget() override { ref(); }
-    void derefEventTarget() override { deref(); }
+    void disconnectFrameForDocumentSuspension() final;
+    void reconnectFrameFromDocumentSuspension(Frame*) final;
+    void willDestroyGlobalObjectInFrame() final;
 
     ApplicationCacheHost* applicationCacheHost() const;
 };
index 601141d..5c15135 100644 (file)
@@ -119,8 +119,7 @@ bool parseManifest(const URL& manifestURL, const char* data, int length, Manifes
             if (!url.isValid())
                 continue;
 
-            if (url.hasFragmentIdentifier())
-                url.removeFragmentIdentifier();
+            url.removeFragmentIdentifier();
             
             if (!equalIgnoringASCIICase(url.protocol(), manifestURL.protocol()))
                 continue;
@@ -150,8 +149,7 @@ bool parseManifest(const URL& manifestURL, const char* data, int length, Manifes
             URL namespaceURL(manifestURL, line.substring(0, p - upconvertedLineCharacters));
             if (!namespaceURL.isValid())
                 continue;
-            if (namespaceURL.hasFragmentIdentifier())
-                namespaceURL.removeFragmentIdentifier();
+            namespaceURL.removeFragmentIdentifier();
 
             if (!protocolHostAndPortAreEqual(manifestURL, namespaceURL))
                 continue;
@@ -168,8 +166,7 @@ bool parseManifest(const URL& manifestURL, const char* data, int length, Manifes
             URL fallbackURL(manifestURL, String(fallbackStart, p - fallbackStart));
             if (!fallbackURL.isValid())
                 continue;
-            if (fallbackURL.hasFragmentIdentifier())
-                fallbackURL.removeFragmentIdentifier();
+            fallbackURL.removeFragmentIdentifier();
 
             if (!protocolHostAndPortAreEqual(manifestURL, fallbackURL))
                 continue;
index f833248..b28249e 100644 (file)
 
 namespace WebCore {
 
-    class URL;
+class URL;
 
-    struct Manifest {
-        Vector<URL> onlineWhitelistedURLs;
-        HashSet<String> explicitURLs;
-        FallbackURLVector fallbackURLs;
-        bool allowAllNetworkRequests; // Wildcard found in NETWORK section.
-    };
+struct Manifest {
+    Vector<URL> onlineWhitelistedURLs;
+    HashSet<String> explicitURLs;
+    FallbackURLVector fallbackURLs;
+    bool allowAllNetworkRequests; // Wildcard found in NETWORK section.
+};
 
-    bool parseManifest(const URL& manifestURL, const char* data, int length, Manifest&);
+bool parseManifest(const URL& manifestURL, const char* data, int length, Manifest&);
 
 } // namespace WebCore
index e89a499..5e05be2 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2008-2017 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -37,17 +37,17 @@ Archive::~Archive()
 
 void Archive::clearAllSubframeArchives()
 {
-    Vector<RefPtr<Archive>> clearedArchives;
-    clearAllSubframeArchivesImpl(&clearedArchives);
+    HashSet<Archive*> clearedArchives;
+    clearedArchives.add(this);
+    clearAllSubframeArchives(clearedArchives);
 }
 
-void Archive::clearAllSubframeArchivesImpl(Vector<RefPtr<Archive>>* clearedArchives)
+void Archive::clearAllSubframeArchives(HashSet<Archive*>& clearedArchives)
 {
+    ASSERT(clearedArchives.contains(this));
     for (auto& archive : m_subframeArchives) {
-        if (!clearedArchives->contains(archive)) {
-            clearedArchives->append(archive);
-            archive->clearAllSubframeArchivesImpl(clearedArchives);
-        }
+        if (clearedArchives.add(archive.ptr()))
+            archive->clearAllSubframeArchives(clearedArchives);
     }
     m_subframeArchives.clear();
 }
index f206549..ff74ce2 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2008-2017 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #pragma once
 
 #include "ArchiveResource.h"
-
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include <wtf/HashSet.h>
 
 namespace WebCore {
 
 class Archive : public RefCounted<Archive> {
 public:
-    enum Type {
-      WebArchive,
-      MHTML
-    };
     virtual ~Archive();
-    virtual Type type() const = 0;
+
+    virtual bool shouldLoadFromArchiveOnly() const = 0;
+    virtual bool shouldOverrideBaseURL() const = 0;
+    virtual bool shouldUseMainResourceEncoding() const = 0;
+    virtual bool shouldUseMainResourceURL() const = 0;
+
     ArchiveResource* mainResource() { return m_mainResource.get(); }
-    const Vector<RefPtr<ArchiveResource>>& subresources() const { return m_subresources; }
-    const Vector<RefPtr<Archive>>& subframeArchives() const { return m_subframeArchives; }
+    const Vector<Ref<ArchiveResource>>& subresources() const { return m_subresources; }
+    const Vector<Ref<Archive>>& subframeArchives() const { return m_subframeArchives; }
 
 protected:
     // These methods are meant for subclasses for different archive types to add resources in to the archive,
     // and should not be exposed as archives should be immutable to clients
-    void setMainResource(PassRefPtr<ArchiveResource> mainResource) { m_mainResource = mainResource; }
-    void addSubresource(PassRefPtr<ArchiveResource> subResource) { m_subresources.append(subResource); }
-    void addSubframeArchive(PassRefPtr<Archive> subframeArchive) { m_subframeArchives.append(subframeArchive); }
+    void setMainResource(Ref<ArchiveResource>&& mainResource) { m_mainResource = WTFMove(mainResource); }
+    void addSubresource(Ref<ArchiveResource>&& resource) { m_subresources.append(WTFMove(resource)); }
+    void addSubframeArchive(Ref<Archive>&& subframeArchive) { m_subframeArchives.append(WTFMove(subframeArchive)); }
 
     void clearAllSubframeArchives();
 
 private:
-    void clearAllSubframeArchivesImpl(Vector<RefPtr<Archive>>* clearedArchives);
+    void clearAllSubframeArchives(HashSet<Archive*>&);
 
     RefPtr<ArchiveResource> m_mainResource;
-    Vector<RefPtr<ArchiveResource>> m_subresources;
-    Vector<RefPtr<Archive>> m_subframeArchives;
+    Vector<Ref<ArchiveResource>> m_subresources;
+    Vector<Ref<Archive>> m_subframeArchives;
 };
 
 } // namespace WebCore
index 90b6799..417ac47 100644 (file)
@@ -49,31 +49,33 @@ namespace WebCore {
 typedef RefPtr<Archive> RawDataCreationFunction(const URL&, SharedBuffer&);
 typedef HashMap<String, RawDataCreationFunction*, ASCIICaseInsensitiveHash> ArchiveMIMETypesMap;
 
-// The create functions in the archive classes return PassRefPtr to concrete subclasses
+// The create functions in the archive classes return RefPtr to concrete subclasses
 // of Archive. This adaptor makes the functions have a uniform return type.
-template <typename ArchiveClass> static RefPtr<Archive> archiveFactoryCreate(const URL& url, SharedBuffer& buffer)
+template<typename ArchiveClass> static RefPtr<Archive> archiveFactoryCreate(const URL& url, SharedBuffer& buffer)
 {
     return ArchiveClass::create(url, buffer);
 }
 
-static ArchiveMIMETypesMap& archiveMIMETypes()
+static ArchiveMIMETypesMap createArchiveMIMETypesMap()
 {
-    static NeverDestroyed<ArchiveMIMETypesMap> mimeTypes;
-    static bool initialized = false;
-
-    if (initialized)
-        return mimeTypes;
+    ArchiveMIMETypesMap map;
 
 #if ENABLE(WEB_ARCHIVE) && USE(CF)
-    mimeTypes.get().set("application/x-webarchive", archiveFactoryCreate<LegacyWebArchive>);
+    map.add(ASCIILiteral { "application/x-webarchive" }, archiveFactoryCreate<LegacyWebArchive>);
 #endif
+
 #if ENABLE(MHTML)
-    mimeTypes.get().set("multipart/related", archiveFactoryCreate<MHTMLArchive>);
-    mimeTypes.get().set("application/x-mimearchive", archiveFactoryCreate<MHTMLArchive>);
+    map.add(ASCIILiteral { "multipart/related" }, archiveFactoryCreate<MHTMLArchive>);
+    map.add(ASCIILiteral { "application/x-mimearchive" }, archiveFactoryCreate<MHTMLArchive>);
 #endif
 
-    initialized = true;
-    return mimeTypes;
+    return map;
+}
+
+static ArchiveMIMETypesMap& archiveMIMETypes()
+{
+    static NeverDestroyed<ArchiveMIMETypesMap> map = createArchiveMIMETypesMap();
+    return map;
 }
 
 bool ArchiveFactory::isArchiveMimeType(const String& mimeType)
@@ -83,10 +85,14 @@ bool ArchiveFactory::isArchiveMimeType(const String& mimeType)
 
 RefPtr<Archive> ArchiveFactory::create(const URL& url, SharedBuffer* data, const String& mimeType)
 {
-    RawDataCreationFunction* function = mimeType.isEmpty() ? 0 : archiveMIMETypes().get(mimeType);
     if (!data)
         return nullptr;
-    return function ? function(url, *data) : RefPtr<Archive>(nullptr);
+    if (mimeType.isEmpty())
+        return nullptr;
+    auto* function = archiveMIMETypes().get(mimeType);
+    if (!function)
+        return nullptr;
+    return function(url, *data);
 }
 
 void ArchiveFactory::registerKnownArchiveMIMETypes()
index 98f6c1e..a3705ec 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2008-2017 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 #include "config.h"
 #include "ArchiveResourceCollection.h"
 
-namespace WebCore {
+#include "Archive.h"
 
-ArchiveResourceCollection::ArchiveResourceCollection()
-{
-}
+namespace WebCore {
 
-void ArchiveResourceCollection::addAllResources(Archive* archive)
+void ArchiveResourceCollection::addAllResources(Archive& archive)
 {
-    ASSERT(archive);
-    if (!archive)
-        return;
+    for (auto& subresource : archive.subresources())
+        m_subresources.set(subresource->url(), subresource.ptr());
 
-    for (auto& subresource : archive->subresources())
-        m_subresources.set(subresource->url(), subresource.get());
-
-    for (auto& subframeArchive : archive->subframeArchives()) {
+    for (auto& subframeArchive : archive.subframeArchives()) {
         ASSERT(subframeArchive->mainResource());
-
-        const String& frameName = subframeArchive->mainResource()->frameName();
-        if (!frameName.isNull())
-            m_subframes.set(frameName, subframeArchive.get());
-        else {
-            // In the MHTML case, frames don't have a name so we use the URL instead.
-            m_subframes.set(subframeArchive->mainResource()->url().string(), subframeArchive.get());
+        auto frameName = subframeArchive->mainResource()->frameName();
+        if (frameName.isNull()) {
+            // In the MHTML case, frames don't have a name, so we use the URL instead.
+            frameName = subframeArchive->mainResource()->url().string();
         }
+        m_subframes.set(frameName, subframeArchive.ptr());
     }
 }
 
@@ -61,25 +53,19 @@ void ArchiveResourceCollection::addAllResources(Archive* archive)
 // Can we change the design in a manner that will let us deprecate that API without reducing functionality of those apps?
 void ArchiveResourceCollection::addResource(Ref<ArchiveResource>&& resource)
 {
-    const URL& url = resource->url();
+    auto& url = resource->url();
     m_subresources.set(url, WTFMove(resource));
 }
 
 ArchiveResource* ArchiveResourceCollection::archiveResourceForURL(const URL& url)
 {
-    ArchiveResource* resource = m_subresources.get(url);
-    if (!resource)
-        return nullptr;
-        
-    return resource;
+    return m_subresources.get(url);
 }
 
-PassRefPtr<Archive> ArchiveResourceCollection::popSubframeArchive(const String& frameName, const URL& url)
+RefPtr<Archive> ArchiveResourceCollection::popSubframeArchive(const String& frameName, const URL& url)
 {
-    auto archive = m_subframes.take(frameName);
-    if (archive)
-        return WTFMove(archive);
-
+    if (auto archive = m_subframes.take(frameName))
+        return archive;
     return m_subframes.take(url.string());
 }
 
index 5c620b5..37df68b 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2008-2017 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
 
 #pragma once
 
-#include "Archive.h"
-#include "ArchiveResource.h"
-#include "URL.h"
+#include <wtf/Forward.h>
 #include <wtf/HashMap.h>
-#include <wtf/text/WTFString.h>
+#include <wtf/Noncopyable.h>
+#include <wtf/text/StringHash.h>
 
 namespace WebCore {
 
+class Archive;
+class ArchiveResource;
+class URL;
+
 class ArchiveResourceCollection {
-    WTF_MAKE_NONCOPYABLE(ArchiveResourceCollection); WTF_MAKE_FAST_ALLOCATED;
+    WTF_MAKE_NONCOPYABLE(ArchiveResourceCollection);
+    WTF_MAKE_FAST_ALLOCATED;
+
 public:
-    ArchiveResourceCollection();
+    ArchiveResourceCollection() = default;
 
     void addResource(Ref<ArchiveResource>&&);
-    void addAllResources(Archive*);
+    void addAllResources(Archive&);
     
     WEBCORE_EXPORT ArchiveResource* archiveResourceForURL(const URL&);
-    PassRefPtr<Archive> popSubframeArchive(const String& frameName, const URL&);
+    RefPtr<Archive> popSubframeArchive(const String& frameName, const URL&);
     
 private:    
     HashMap<String, RefPtr<ArchiveResource>> m_subresources;
index e049063..39d8352 100644 (file)
@@ -80,18 +80,16 @@ RetainPtr<CFDictionaryRef> LegacyWebArchive::createPropertyListRepresentation(Ar
         CFDictionarySetValue(propertyList.get(), LegacyWebArchiveResourceMIMETypeKey, 0);
         return propertyList;
     }
-    
-    RetainPtr<CFMutableDictionaryRef> propertyList = adoptCF(CFDictionaryCreateMutable(0, 6, 0, &kCFTypeDictionaryValueCallBacks));
-    
+
+    auto propertyList = adoptCF(CFDictionaryCreateMutable(0, 6, 0, &kCFTypeDictionaryValueCallBacks));
+
     // Resource data can be empty, but must be represented by an empty CFDataRef
-    SharedBuffer& data = resource->data();
-    RetainPtr<CFDataRef> cfData;
-    cfData = data.createCFData();
+    auto& data = resource->data();
+
+    CFDictionarySetValue(propertyList.get(), LegacyWebArchiveResourceDataKey, data.createCFData().get());
 
-    CFDictionarySetValue(propertyList.get(), LegacyWebArchiveResourceDataKey, cfData.get());
-    
     // Resource URL cannot be null
-    if (RetainPtr<CFStringRef> cfURL = resource->url().string().createCFString())
+    if (auto cfURL = resource->url().string().createCFString())
         CFDictionarySetValue(propertyList.get(), LegacyWebArchiveResourceURLKey, cfURL.get());
     else {
         LOG(Archives, "LegacyWebArchive - NULL resource URL is invalid - returning null property list");
@@ -99,42 +97,41 @@ RetainPtr<CFDictionaryRef> LegacyWebArchive::createPropertyListRepresentation(Ar
     }
 
     // FrameName should be left out if empty for subresources, but always included for main resources
-    const String& frameName(resource->frameName());
+    auto& frameName = resource->frameName();
     if (!frameName.isEmpty() || isMainResource)
         CFDictionarySetValue(propertyList.get(), LegacyWebArchiveResourceFrameNameKey, frameName.createCFString().get());
-    
+
     // Set MIMEType, TextEncodingName, and ResourceResponse only if they actually exist
-    const String& mimeType(resource->mimeType());
+    auto& mimeType = resource->mimeType();
     if (!mimeType.isEmpty())
         CFDictionarySetValue(propertyList.get(), LegacyWebArchiveResourceMIMETypeKey, mimeType.createCFString().get());
-    
-    const String& textEncoding(resource->textEncoding());
+
+    auto& textEncoding = resource->textEncoding();
     if (!textEncoding.isEmpty())
         CFDictionarySetValue(propertyList.get(), LegacyWebArchiveResourceTextEncodingNameKey, textEncoding.createCFString().get());
 
     // Don't include the resource response for the main resource
     if (!isMainResource) {
-        RetainPtr<CFDataRef> resourceResponseData = createPropertyListRepresentation(resource->response());
-        if (resourceResponseData)
+        if (auto resourceResponseData = createPropertyListRepresentation(resource->response()))
             CFDictionarySetValue(propertyList.get(), LegacyWebArchiveResourceResponseKey, resourceResponseData.get());    
     }
     
     return propertyList;
 }
 
-RetainPtr<CFDictionaryRef> LegacyWebArchive::createPropertyListRepresentation(Archive* archive)
+RetainPtr<CFDictionaryRef> LegacyWebArchive::createPropertyListRepresentation(Archive& archive)
 {
-    RetainPtr<CFMutableDictionaryRef> propertyList = adoptCF(CFDictionaryCreateMutable(0, 3, 0, &kCFTypeDictionaryValueCallBacks));
-    
-    RetainPtr<CFDictionaryRef> mainResourceDict = createPropertyListRepresentation(archive->mainResource(), MainResource);
+    auto propertyList = adoptCF(CFDictionaryCreateMutable(0, 3, 0, &kCFTypeDictionaryValueCallBacks));
+
+    auto mainResourceDict = createPropertyListRepresentation(archive.mainResource(), MainResource);
     ASSERT(mainResourceDict);
     if (!mainResourceDict)
         return nullptr;
     CFDictionarySetValue(propertyList.get(), LegacyWebArchiveMainResourceKey, mainResourceDict.get());
 
-    RetainPtr<CFMutableArrayRef> subresourcesArray = adoptCF(CFArrayCreateMutable(0, archive->subresources().size(), &kCFTypeArrayCallBacks));
-    for (auto& resource : archive->subresources()) {
-        if (RetainPtr<CFDictionaryRef> subresource = createPropertyListRepresentation(resource.get(), Subresource))
+    auto subresourcesArray = adoptCF(CFArrayCreateMutable(0, archive.subresources().size(), &kCFTypeArrayCallBacks));
+    for (auto& resource : archive.subresources()) {
+        if (auto subresource = createPropertyListRepresentation(resource.ptr(), Subresource))
             CFArrayAppendValue(subresourcesArray.get(), subresource.get());
         else
             LOG(Archives, "LegacyWebArchive - Failed to create property list for subresource");
@@ -142,9 +139,9 @@ RetainPtr<CFDictionaryRef> LegacyWebArchive::createPropertyListRepresentation(Ar
     if (CFArrayGetCount(subresourcesArray.get()))
         CFDictionarySetValue(propertyList.get(), LegacyWebArchiveSubresourcesKey, subresourcesArray.get());
 
-    RetainPtr<CFMutableArrayRef> subframesArray = adoptCF(CFArrayCreateMutable(0, archive->subframeArchives().size(), &kCFTypeArrayCallBacks));
-    for (auto& subframe : archive->subframeArchives()) {
-        if (RetainPtr<CFDictionaryRef> subframeArchive = createPropertyListRepresentation(subframe.get()))
+    auto subframesArray = adoptCF(CFArrayCreateMutable(0, archive.subframeArchives().size(), &kCFTypeArrayCallBacks));
+    for (auto& subframe : archive.subframeArchives()) {
+        if (auto subframeArchive = createPropertyListRepresentation(subframe.get()))
             CFArrayAppendValue(subframesArray.get(), subframeArchive.get());
         else
             LOG(Archives, "LegacyWebArchive - Failed to create property list for subframe archive");
@@ -160,13 +157,13 @@ ResourceResponse LegacyWebArchive::createResourceResponseFromPropertyListData(CF
     ASSERT(data);
     if (!data)
         return ResourceResponse();
-    
+
     // If the ResourceResponseVersion (passed in as responseDataType) exists at all, this is a "new" web archive that we
     // can parse well in a cross platform manner If it doesn't exist, we will assume this is an "old" web archive with,
     // NSURLResponse objects in it and parse the ResourceResponse as such.
     if (!responseDataType)
         return createResourceResponseFromMacArchivedData(data);
-        
+
     // FIXME: Parse the "new" format that the above comment references here. This format doesn't exist yet.
     return ResourceResponse();
 }
@@ -176,47 +173,46 @@ RefPtr<ArchiveResource> LegacyWebArchive::createResource(CFDictionaryRef diction
     ASSERT(dictionary);
     if (!dictionary)
         return nullptr;
-        
-    CFDataRef resourceData = static_cast<CFDataRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceDataKey));
+
+    auto resourceData = static_cast<CFDataRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceDataKey));
     if (resourceData && CFGetTypeID(resourceData) != CFDataGetTypeID()) {
         LOG(Archives, "LegacyWebArchive - Resource data is not of type CFData, cannot create invalid resource");
         return nullptr;
     }
-    
-    CFStringRef frameName = static_cast<CFStringRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceFrameNameKey));
+
+    auto frameName = static_cast<CFStringRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceFrameNameKey));
     if (frameName && CFGetTypeID(frameName) != CFStringGetTypeID()) {
         LOG(Archives, "LegacyWebArchive - Frame name is not of type CFString, cannot create invalid resource");
         return nullptr;
     }
-    
-    CFStringRef mimeType = static_cast<CFStringRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceMIMETypeKey));
+
+    auto mimeType = static_cast<CFStringRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceMIMETypeKey));
     if (mimeType && CFGetTypeID(mimeType) != CFStringGetTypeID()) {
         LOG(Archives, "LegacyWebArchive - MIME type is not of type CFString, cannot create invalid resource");
         return nullptr;
     }
-    
-    CFStringRef url = static_cast<CFStringRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceURLKey));
+
+    auto url = static_cast<CFStringRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceURLKey));
     if (url && CFGetTypeID(url) != CFStringGetTypeID()) {
         LOG(Archives, "LegacyWebArchive - URL is not of type CFString, cannot create invalid resource");
         return nullptr;
     }
-    
-    CFStringRef textEncoding = static_cast<CFStringRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceTextEncodingNameKey));
+
+    auto textEncoding = static_cast<CFStringRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceTextEncodingNameKey));
     if (textEncoding && CFGetTypeID(textEncoding) != CFStringGetTypeID()) {
         LOG(Archives, "LegacyWebArchive - Text encoding is not of type CFString, cannot create invalid resource");
         return nullptr;
     }
 
     ResourceResponse response;
-    
-    CFDataRef resourceResponseData = static_cast<CFDataRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceResponseKey));
-    if (resourceResponseData) {
+
+    if (auto resourceResponseData = static_cast<CFDataRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceResponseKey))) {
         if (CFGetTypeID(resourceResponseData) != CFDataGetTypeID()) {
             LOG(Archives, "LegacyWebArchive - Resource response data is not of type CFData, cannot create invalid resource");
             return nullptr;
         }
         
-        CFStringRef resourceResponseVersion = static_cast<CFStringRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceResponseVersionKey));
+        auto resourceResponseVersion = static_cast<CFStringRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceResponseVersionKey));
         if (resourceResponseVersion && CFGetTypeID(resourceResponseVersion) != CFStringGetTypeID()) {
             LOG(Archives, "LegacyWebArchive - Resource response version is not of type CFString, cannot create invalid resource");
             return nullptr;
@@ -224,7 +220,7 @@ RefPtr<ArchiveResource> LegacyWebArchive::createResource(CFDictionaryRef diction
         
         response = createResourceResponseFromPropertyListData(resourceResponseData, resourceResponseVersion);
     }
-    
+
     return ArchiveResource::create(SharedBuffer::wrapCFData(resourceData), URL(URL(), url), mimeType, textEncoding, frameName, response);
 }
 
@@ -233,21 +229,19 @@ Ref<LegacyWebArchive> LegacyWebArchive::create()
     return adoptRef(*new LegacyWebArchive);
 }
 
-RefPtr<LegacyWebArchive> LegacyWebArchive::create(RefPtr<ArchiveResource>&& mainResource, Vector<RefPtr<ArchiveResource>>&& subresources, Vector<RefPtr<LegacyWebArchive>>&& subframeArchives)
+Ref<LegacyWebArchive> LegacyWebArchive::create(Ref<ArchiveResource>&& mainResource, Vector<Ref<ArchiveResource>>&& subresources, Vector<Ref<LegacyWebArchive>>&& subframeArchives)
 {
-    if (!mainResource)
-        return nullptr;
-
     auto archive = create();
+
     archive->setMainResource(WTFMove(mainResource));
-    
+
     for (auto& subresource : subresources)
         archive->addSubresource(WTFMove(subresource));
 
     for (auto& subframeArchive : subframeArchives)
&