Improve use of NeverDestroyed
authordarin@apple.com <darin@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Tue, 18 Jul 2017 01:53:34 +0000 (01:53 +0000)
committerdarin@apple.com <darin@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Tue, 18 Jul 2017 01:53:34 +0000 (01:53 +0000)
https://bugs.webkit.org/show_bug.cgi?id=174348

Reviewed by Sam Weinig.

Source/JavaScriptCore:

* heap/MachineStackMarker.cpp:
* wasm/WasmMemory.cpp:
Removed unneeded includes of NeverDestroyed.h in files that do not make use
of NeverDestroyed.

Source/WebCore:

* Modules/encryptedmedia/MediaKeySession.cpp: Removed unneeded include of
NeverDestroyed.h.

* Modules/encryptedmedia/legacy/LegacyCDM.cpp:
(WebCore::installedCDMFactories): Use makeNeverDestroyed and a lambda rather
than a separate boolean for initialization.

* Modules/encryptedmedia/legacy/LegacyCDMSessionClearKey.cpp:
(WebCore::clearKeyVM): Removed unneeded use of NeverDestroyed to hold a
RefPtr. Simple to just use leakRef instead.

* Modules/gamepad/GamepadManager.cpp: Added an include of NeverDestroyed.h.

* Modules/indexeddb/IDBTransaction.cpp: Removed unneeded include of
NeverDestroyed.h.
* Modules/indexeddb/server/MemoryObjectStore.cpp: Ditto.

* Modules/mediasession/MediaSessionManager.cpp: Moved include of
NeverDestroyed.h here ...
* Modules/mediasession/MediaSessionManager.h: ... from here.

* Modules/mediasource/MediaSourceRegistry.cpp: Moved include of
NeverDestroyed.h here ...
* Modules/mediasource/MediaSourceRegistry.h: ... from here.

* Modules/mediasource/SourceBuffer.cpp: Removed unneeded include of
NeverDestroyed.h.

* Modules/plugins/QuickTimePluginReplacement.h: Initialize
m_scriptObject in the class definition.

* Modules/plugins/QuickTimePluginReplacement.mm:
(WebCore::QuickTimePluginReplacement::supportsMimeType): Use
makeNeverDestroyed and the HashSet constructor instead of a loop.
(WebCore::QuickTimePluginReplacement::supportsFileExtension): Ditto.
(WebCore::QuickTimePluginReplacement::QuickTimePluginReplacement): Did a
slight cleanup of the initializers.
(WebCore::QuickTimePluginReplacement::~QuickTimePluginReplacement): Added
a FIXME; unclear why there is code here at all.

* accessibility/AccessibilityRenderObject.cpp:
(WebCore::AccessibilityRenderObject::inheritsPresentationalRole): Use
makeNeverDestroyed and the Vector constructor instead of using empty
vector checks and Vector::add. Use std::any_of rather than Vector::contains
since we now are matching against pointers.

* bindings/scripts/CodeGeneratorJS.pm:
(GenerateEnumerationImplementationContent): Use const NeverDestroyed.

* bindings/scripts/test/JS/JSTestCallbackInterface.cpp:
* bindings/scripts/test/JS/JSTestObj.cpp:
* bindings/scripts/test/JS/JSTestStandaloneDictionary.cpp:
* bindings/scripts/test/JS/JSTestStandaloneEnumeration.cpp:
Regenerated.

* css/CSSProperty.cpp:
(WebCore::borderDirections): Removed unnecesssary use of NeverDestroyed
for a global object that has a trivial destructor.

* css/ElementRuleCollector.cpp:
(WebCore::leftToRightDeclaration): Removed unneeded use of NeverDestroyed to hold a
Ref. Simple to just use leakRef instead. Also use a lambda instead of an explicit
isEmpty check each time this is called.
(WebCore::rightToLeftDeclaration): Ditto.

* css/makeprop.pl: Removed unneeded include of NeverDestroyed.h and the
uneeded global emptyShorthand. Constructing an empty StylePropertyShorthand
is no less efficient than copying a global empty one was.

* dom/CustomElementReactionQueue.cpp: Added an include of NeverDestroyed.h.

* dom/DOMImplementation.cpp: Removed unneeded include of NeverDestroyed.h.
* dom/InputEvent.cpp: Ditto.

* dom/Microtasks.cpp: Moved include of NeverDestroyed.h here ...
* dom/Microtasks.h: ... from here.

* dom/MutationObserver.cpp: Added an include of NeverDestroyed.h.

* dom/ScopedEventQueue.cpp: Moved include of NeverDestroyed.h here ...
* dom/ScopedEventQueue.h: ... from here. Added Forward.h.

* dom/ScriptElement.cpp:
(WebCore::isLegacySupportedJavaScriptLanguage): Use makeNeverDestroyed
and the HashSet constructor rather than an isEmpty check and a lot of
add function calls. Also removed comments that don't have value any more,
with dubious no longer relevant claims about the behavior of old web browsers.
The function that calls this one already has sufficient comments about why we
hope some day this function can be eliminated.

* dom/SecurityContext.cpp: Removed unneeded include of NeverDestroyed.h.

* dom/make_names.pl:
(printFactoryCppFile): Instead of using a "populate" function, use a function
that creates as HashMap. Then use const auto and makeNeverDestroyed.
(printWrapperFactoryCppFile): Ditto.

* editing/AlternativeTextController.cpp:
(WebCore::markerTypesForAutocorrection): Use makeNeverDestroyed
and the Vector constructor rather than an isEmpty check and a lot of
append function calls.
(WebCore::markerTypesForReplacement): Ditto.
(WebCore::markerTypesForAppliedDictationAlternative): Ditto.

* editing/EditingStyle.cpp:
(WebCore::htmlElementEquivalents): Use const auto, makeNeverDestroyed,
the Vector constructor, and new rather than make_unique. Changed return
type to use const pointers rather than unique_ptr with non-const type.
(WebCore::EditingStyle::conflictsWithImplicitStyleOfElement): Updated
for the above change to htmlElementEquivalents.
(WebCore::htmlAttributeEquivalents): Same approach as above.
(WebCore::EditingStyle::conflictsWithImplicitStyleOfAttributes): Ditto.
(WebCore::elementMatchesAndPropertyIsNotInInlineStyleDecl): Take
references instead of pointers.
(WebCore::EditingStyle::mergeInlineAndImplicitStyleOfElement): Updated
for the above.

* editing/FormatBlockCommand.cpp:
(WebCore::isElementForFormatBlock): Use const auto, makeNeverDestroyed,
and the HashSet constructor rather than isEmpty and a lot of calls to add.
* editing/RemoveFormatCommand.cpp:
(WebCore::isElementForRemoveFormatCommand): Ditto.

* editing/ReplaceSelectionCommand.cpp:
(WebCore::isProhibitedParagraphChild): Use const auto, makeNeverDestroyed,
and a lambda, rather than isEmpty and a lot of calls to add.

* html/Autofill.cpp:
(WebCore::fieldNameMap): Changed return type to be const. Use const auto,
makeNeverDestroyed, a lambda, and an array of values rather than isEmpty
and a lot of calls to add. Stopped doing the ConstructFromLiteral
optimization here. (Easy to add it back if that is a mistake.)

* html/HTMLObjectElement.cpp:
(WebCore::isRecognizedTagName): Use const auto, makeNeverDestroyed, and
a lambda rather than isEmpty.

* html/HTMLStyleElement.cpp: Added include of NeverDestroyed.h.

* html/HTMLVideoElement.cpp: Removed uneeded include of NeverDestroyed.h.

* html/InputType.cpp:
(WebCore::createInputTypeFactoryMap): Replaced the populate function
with this create function.
(WebCore::InputType::create): Use const auto and makeNeverDestroyed
istead of isEmpty. Also put the map right where it is used so it's
not initialized in code path where not needed.

* html/parser/HTMLParserIdioms.cpp: Removed uneeded include of
NeverDestroyed.h.

* inspector/InspectorApplicationCacheAgent.cpp:
(WebCore::InspectorApplicationCacheAgent::networkStateChanged):
Merged into a single line.

* loader/ContentFilter.cpp:
(WebCore::blockedPageURL): Use const auto and makeNeverDestroyed
rather than std::call_once. Since this is a URL and has a non-thread-safe
reference count, this was not thread safe before, so no need to use the
more roundabout and less efficient idiom for its thread safety.

* loader/CrossOriginAccessControl.cpp:
(WebCore::isOnAccessControlResponseHeaderWhitelist): Deleted.
* loader/CrossOriginAccessControl.h: Deleted unused function
isOnAccessControlResponseHeaderWhitelist.

* loader/EmptyClients.cpp: Use leakRef instead of NeverDestroyed<Ref>.

* loader/appcache/ApplicationCacheStorage.cpp: Removed unneeded include of
NeverDestroyed.h.
* page/CaptionUserPreferences.cpp: Ditto.

* page/DebugPageOverlays.cpp:
(WebCore::touchEventRegionColors): Changed the return type to const, since
the callers do not modify the map. Use const auto, makeNeverDestroyed, and
a lambda rather than isEmpty and repeated calls to add.

* page/MainFrame.cpp: Removed unneeded include of NeverDestroyed.h.

* page/MemoryRelease.cpp:
(WebCore::releaseMemory): Use a function directly instead of calling it
inside a lambda.

* page/NavigatorBase.cpp:
(WebCore::NavigatorBase::onLine): Updated to call
NetworkStateNotifier::singleton.

* page/Page.cpp:
(WebCore::allPages): Made this a function instead of a global to use the
normal idiom for such globals.
(WebCore::Page::forEachPage): Updated for change to allPages.
(WebCore::networkStateChanged): Ditto. Also removed a bit of unnecessary
churn by using const AtomicString& instead of AtomicString.
(WebCore::Page::Page): Moved initialization of most data members to the
class definition. Removed initialiation of allPages. Updated the use of
NetworkStateNotifier for its new slightly changed  interface.
(WebCore::Page::~Page): Updated for change to allPages.
(WebCore::Page::clearPreviousItemFromAllPages): Ditto.
(WebCore::Page::updateStyleForAllPagesAfterGlobalChangeInEnvironment): Ditto.
(WebCore::Page::refreshPlugins): Ditto.

* page/Page.h: Moved initialization of most data members here.

* page/PerformanceUserTiming.cpp: Removed many unneded includes.
(WebCore::restrictedMarkFunction): Use const auto, makeNeverDestroyed, and
a lambda instead of isEmpty. Also use an array rather than std::array and
got rid fo the unneeded use of anonymous namespace since this is fine in
the top level WebCore namespace.
(WebCore::clearPerformanceEntries): Tweaked coding style.
(WebCore::UserTiming::mark): Ditto.
(WebCore::UserTiming::findExistingMarkStartTime): Got rid of double hash
table lookup by using find instead of using contains followed by get.
removed unneeded explicit cast to double. Tweaked coding style.
(WebCore::convertToEntrySequence): Tweaked coding style.
(WebCore::getEntrySequenceByName): Deleted.
(WebCore::UserTiming::getMarks): Call get directly instead of getEntrySequenceByName.
(WebCore::UserTiming::getMeasures): Ditto.

* page/RuntimeEnabledFeatures.cpp: Moved include of NeverDestroyed.h here ...
* page/RuntimeEnabledFeatures.h: ... from here. Added Forward.h and Noncopyable.h.

* platform/LocalizedStrings.cpp: Removed unneeded include of NeverDestroyed.h.

* platform/MIMETypeRegistry.cpp:
(WebCore::initializeSupportedImageMIMETypes): Added a missing const for a global
constant array.
(WebCore::initializeSupportedJavaScriptMIMETypes): Ditto.
(WebCore::initializeSupportedNonImageMimeTypes): Ditto.
(WebCore::typesForCommonExtension): Replaced the old mediaMIMETypeMap function
with this one. Moved the common media types array here since it's only used here.
Use const auto, makeNeverDestroyed, and a lambda instead of using an isEmpty check.
Iterate the array using a mdoern for loop. Use HashMap::ensure to avoid the
double hashing that the old code was doing. And moved the code to find an entry
in the map in here from the client functions.
(WebCore::MIMETypeRegistry::getMediaMIMETypeForExtension): Updated to use the
typesForCommonExtension, and changed logic to use this first, and only call
getMIMETypeForExtension for extensions not in the map. This gives the same
result but should be slightly more efficient.
(WebCore::MIMETypeRegistry::getMediaMIMETypesForExtension): Updated to use the
typesForCommonExtension function. Comment about strategy is now in there.
(WebCore::initializeUnsupportedTextMIMETypes): Added a missing const for a global
constant array. Also started using ASCIILiteral.

* platform/MainThreadSharedTimer.cpp: Moved include of NeverDestroyed.h here ...
* platform/MainThreadSharedTimer.h: ... from here. Added Forward.h.

* platform/SchemeRegistry.cpp:
(WebCore::add): Added helper functions to keep code below simpler.
(WebCore::makeNeverDestroyedSchemeSet): Ditto.
(WebCore::allBuiltinSchemes): Use const auto, makeNeverDestroyed, a lambda,
and the helper functions above, rather than isEmpty.
(WebCore::builtinLocalURLSchemes): Use const auto, makeNeverDestroyed, and
the HashSet constructor instead of isEmpty and add calls. Also changed the
return type to be const.
(WebCore::localURLSchemes): Copy the map using assignment instead of an
isEmpty function and a loop with calls to add.
(WebCore::builtinSecureSchemes): Use const auto, makeNeverDestroyed, and
the Vector constructor rather than isEmpty, repeated calls to append,
and shrinkToFit.
(WebCore::secureSchemes): Use auto and makeNeverDestroyedSchemeSet rather
than isEmpty and repeated calls to add.
(WebCore::builtinSchemesWithUniqueOrigins): More of the same.
(WebCore::schemesWithUniqueOrigins): Ditto.
(WebCore::builtinEmptyDocumentSchemes): Ditto.
(WebCore::emptyDocumentSchemes): Ditto.
(WebCore::schemesForbiddenFromDomainRelaxation): Ditto.
(WebCore::builtinCanDisplayOnlyIfCanRequestSchemes): Ditto.
(WebCore::canDisplayOnlyIfCanRequestSchemes): Ditto.
(WebCore::builtinCORSEnabledSchemes): Ditto.
(WebCore::CORSEnabledSchemes): Ditto.
(WebCore::SchemeRegistry::shouldTreatURLSchemeAsLocal): Replaced check for
empty string with check for null string, since that's slightly more efficient
for non-null, non-empty strings, and the hash table can handle empty strings
just fine.
(WebCore::SchemeRegistry::registerURLSchemeAsNoAccess): Added null check here.
(WebCore::SchemeRegistry::shouldTreatURLSchemeAsNoAccess): Ditto.
(WebCore::SchemeRegistry::registerURLSchemeAsDisplayIsolated): Ditto.
(WebCore::SchemeRegistry::shouldTreatURLSchemeAsDisplayIsolated): Ditto.
(WebCore::SchemeRegistry::registerURLSchemeAsSecure): Ditto.
(WebCore::SchemeRegistry::shouldTreatURLSchemeAsSecure): Ditto.
(WebCore::SchemeRegistry::registerURLSchemeAsEmptyDocument): Ditto.
(WebCore::SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument): Ditto.
(WebCore::SchemeRegistry::setDomainRelaxationForbiddenForURLScheme): Ditto.
(WebCore::SchemeRegistry::isDomainRelaxationForbiddenForURLScheme): Ditto.
(WebCore::SchemeRegistry::canDisplayOnlyIfCanRequest): Ditto.
(WebCore::SchemeRegistry::registerAsCanDisplayOnlyIfCanRequest): Ditto.
(WebCore::SchemeRegistry::registerURLSchemeAsNotAllowingJavascriptURLs): Ditto.
(WebCore::SchemeRegistry::shouldTreatURLSchemeAsNotAllowingJavascriptURLs): Ditto.
(WebCore::SchemeRegistry::registerURLSchemeAsAllowingLocalStorageAccessInPrivateBrowsing): Ditto.
(WebCore::SchemeRegistry::allowsLocalStorageAccessInPrivateBrowsing): Ditto.
(WebCore::SchemeRegistry::registerURLSchemeAsAllowingDatabaseAccessInPrivateBrowsing): Ditto.
(WebCore::SchemeRegistry::allowsDatabaseAccessInPrivateBrowsing): Ditto.
(WebCore::SchemeRegistry::registerURLSchemeAsCORSEnabled): Ditto.
(WebCore::SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled): Ditto.
(WebCore::SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy): Ditto.
(WebCore::SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy): Ditto.
(WebCore::SchemeRegistry::schemeShouldBypassContentSecurityPolicy): Ditto.
(WebCore::SchemeRegistry::registerURLSchemeAsAlwaysRevalidated): Ditto.
(WebCore::SchemeRegistry::shouldAlwaysRevalidateURLScheme): Ditto.
(WebCore::SchemeRegistry::registerURLSchemeAsCachePartitioned): Ditto.
(WebCore::SchemeRegistry::shouldPartitionCacheForURLScheme): Ditto.
(WebCore::SchemeRegistry::isUserExtensionScheme): Tweaked #if a bit.
(WebCore::SchemeRegistry::isBuiltinScheme): Added null check.

* platform/cocoa/WebVideoFullscreenModelVideoElement.mm:
(WebVideoFullscreenModelVideoElement::observedEventNames): Use const auto,
makeNeverDestroyed, and the Vector constructor rather than a call to size
and then append eacn time this funciton is called.

* platform/gamepad/cocoa/GameControllerGamepadProvider.h: Moved include of
NeverDestroyed.h from here ...
* platform/gamepad/cocoa/GameControllerGamepadProvider.mm: ... to here.

* platform/gamepad/mac/HIDGamepadProvider.cpp: Moved include of
NeverDestroyed.h here ...
* platform/gamepad/mac/HIDGamepadProvider.h: ... from here.

* platform/graphics/FontCascade.cpp:
(WebCore::FontCascade::hasValidAverageCharWidth): Use const auto,
makeNeverDestroyed, and the HashSet constructor.

* platform/graphics/ImageBuffer.cpp:
(WebCore::ImageBuffer::transformColorSpace): Removed unneeded use of
NeverDestroyed<Vector<int>> here, instead using const std::array.

* platform/graphics/ImageBuffer.h: Changed platformTransformColorSpace to take
const std::array<uint8_t, 256>& instead of const Vector<int>&, since the whole
pointer of the argument is that it's a table to map bytes onto other bytes.

* platform/graphics/MediaPlaybackTarget.h: Removed unneeded include of
NeverDestroyed.h, unneeded unused noMediaPlaybackTargetContext function,
and unneeded include of MediaPlaybackTargetContext.h, forward declaring instead.
Made most functions in this class pure virtual instead of having default
implementations.

* platform/graphics/avfoundation/MediaPlaybackTargetMac.h: Added include
of MediaPlaybackTargetContext.h now that it was removed above.

* platform/graphics/avfoundation/MediaPlayerPrivateAVFoundation.cpp:
(WebCore::MediaPlayerPrivateAVFoundation::staticMIMETypeList): Use const auto,
makeNeverDestroyed, and the HashSet constructor.

* platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.mm:
(WebCore::MediaPlayerPrivateMediaStreamAVFObjC::isAvailable): Reversed the sense
of the boolean logic here to make this simpler and easier to read.
(WebCore::MediaPlayerPrivateMediaStreamAVFObjC::getSupportedTypes): Changed
the implementation here, which empties out the passed in hash set, to use
the clear function rather than assignment from a global empty hash set. Added
a FIXME because it seems peculiar that this would be considered OK.
(WebCore::MediaPlayerPrivateMediaStreamAVFObjC::supportsType): Used ? : to make
this a little more terse; I think it's clearer.

* platform/graphics/cairo/ImageBufferCairo.cpp:
(WebCore::ImageBuffer::platformTransformColorSpace): Updated for change to
argument type.

* platform/graphics/cg/ImageDecoderCG.cpp: Removed unneeded include of
NeverDestroyed.h.
(WebCore::appendImageSourceOption): Streamlined code using auto with
adoptCF; there is no need to write out the type of the RetainPtr.
(WebCore::imageSourceOptions): Instead of NeverDestroyed<RetainPtr>, just use
const auto and leakRef.
(WebCore::imageSourceAsyncOptions): Ditto.

* platform/graphics/gtk/GdkCairoUtilities.cpp:
(WebCore::getDefaultCairoFontOptions): Instead of using LazyNeverDestroyed
on a pointer, just use a global pointer. There is no need to use any kind
of NeverDestroyed on a type with a trivial destructor such as a pointer.

* platform/graphics/ios/FontCacheIOS.mm:
(WebCore::platformFontWithFamilySpecialCase): Instead of using
NeverDestroyed<RetainPtr> just use a raw pointer global.
* platform/graphics/mac/FontCacheMac.mm:
(WebCore::platformFontWithFamilySpecialCase): Ditto.

* platform/graphics/mac/MediaPlayerPrivateQTKit.mm:
(WebCore::createFileTypesSet): Return the HashSet instead of adding to it.
Use Objective-C for/in syntax for an NSArray, not C++ for syntax, although
it seems the C++ syntax was working fine.
(WebCore::mimeCommonTypesCache): Fixed return type so we won't copy the
HashMap every time this function is called. Use const auto and makeNeverDestroyed
instead of using a boolean to do one time initialization.
(WebCore::mimeModernTypesCache): Ditto.
(WebCore::MediaPlayerPrivateQTKit::disableUnsupportedTracks): Marked a
constant array const.

* platform/ios/Device.cpp:
(WebCore::deviceClass): Use a lambda to initialize a variable here instead
of using std::call_once. This function does not need to be thread safe.
(WebCore::deviceName): Use const NeverDestroyed instead of LazyNeverDestroyed
and std::call_once. This function does not need to be thread safe.

* platform/ios/DragImageIOS.mm: Make defaultLinkIndicatorOptions be a
constant instead of a variable.
(WebCore::cascadeForSystemFont): Added helper function.
(WebCore::createDragImageForLink): Use const auto and makeNeverDestroyed
instead of LazyNeverDestroyed and dispatch_once. This code does not need
to be thread safe since its arguments include, for example, a DOM element.

* platform/ios/LegacyTileLayerPool.h: Removed unneeded include of
NeverDestroyed.h.

* platform/ios/QuickLook.mm:
(WebCore::QLPreviewGetSupportedMIMETypesSet): Use a global raw pointer
instead of NeverDestroyed<RetainPtr<NSSet>>.
(WebCore::createQLPreviewProtocol): Deleted.
(WebCore::QLPreviewProtocol): Use a global raw pointer instead of
a NeverDestroyed<Vector<char>>. It's cleaner to use fastStrdup instead
of appending to an array, and less wasteful of memory too.

* platform/ios/WebCoreMotionManager.mm: Removed unneeded include of
NeverDestroyed.h.
* platform/ios/WebSQLiteDatabaseTrackerClient.h: Ditto.
* platform/mac/DragImageMac.mm: Ditto.
* platform/mediastream/CaptureDeviceManager.cpp: Ditto.
* platform/mediastream/RealtimeMediaSourceSupportedConstraints.cpp: Ditto.

* platform/mock/MockRealtimeMediaSource.cpp:
(WebCore::MockRealtimeMediaSource::audioDevices): Use auto,
makeNeverDestroyed, and a lambda instead of checking size each time.
(WebCore::MockRealtimeMediaSource::videoDevices): Ditto.

* platform/mock/mediasource/MockMediaPlayerMediaSource.cpp:
(WebCore::mimeTypeCache): Use const auto, makeNeverDestroyed, and the
HashSet constructor instead of an explicit boolean to initialize.

* platform/network/BlobRegistryImpl.cpp:
(WebCore::blobUtilityQueue): Use a global with a raw reference instead
of a NeverDestroyed<Ref>.

* platform/network/NetworkStateNotifier.cpp:
(WebCore::NetworkStateNotifier::singleton): Renamed this from
networkStateNotifier. We must have missed this when we changed to use the
singleton idiom consistently. Also changed to use normal NeverDestroyed
rather than using LazyNeverDestroyed and call_once, because this is not
used from multiple threads and has no special thread safety requirements.
(WebCore::NetworkStateNotifier::NetworkStateNotifier): Moved the constructor
here and construct the timer. Before the timer was used only on the Mac
platform but now it is there for all platforms.
(WebCore::NetworkStateNotifier::onLine): Moved function here from the header.
It's a littlel less trivial than before because it now triggers a call to
updateState as needed.
(WebCore::NetworkStateNotifier::addListener): Renamed from
addNetworkStateChangeListener since there is only one kind of listener and
the old name was too wordy. Changed to call the new startObserving function,
and guaranteed to call it onlh once. The platform-specific logic for iOS is
now inside the iOS version of that function instead of here.
(WebCore::NetworkStateNotifier::updateState): Moved here now that it is the
same for all platforms. The actual state updating is done in a function named
updateStateWithoutNotifying, which is implemented for each platform.
(WebCore::NetworkStateNotifier::updateStateSoon): New function which takes
advantage of the timer to coalesce network state updates.
(WebCore::NetworkStateNotifier::updateStateWithoutNotifying): Empty stub
version of this function.
(WebCore::NetworkStateNotifier::startObserving): Ditto.
(WebCore::NetworkStateNotifier::notifyNetworkStateChange): Deleted. Code from
this has moved into updateState.

* platform/network/NetworkStateNotifier.h: Greatly cut down what part of this
class is platform-specific.

* platform/network/ios/NetworkStateNotifierIOS.mm:
(-[WebNetworkStateObserver initWithBlock:]): Simplified this class so it
takes a block, rather than using a pointer to the C++ notifier and doing
WebThreadRun.
(-[WebNetworkStateObserver dealloc]): Ditto.
(-[WebNetworkStateObserver networkStateChanged:]): Ditto.
(WebCore::NetworkStateNotifier::updateStateWithoutNotifying):
This now calls isNetworkReachable.
(WebCore::NetworkStateNotifier::startObserving): Check the
Settings::shouldOptOutOfNetworkStateObservation function, and if it's OK
to observe, then create the observer. This code now takes care of the
WebThreadRun and calls updateStateSoon.
(WebCore::NetworkStateNotifier::NetworkStateNotifier): Deleted. The
constructor is now platform independent.
(WebCore::NetworkStateNotifier::~NetworkStateNotifier): Deleted. This
object is never destroyed so we should not write a destructor for it.
(WebCore::NetworkStateNotifier::registerObserverIfNecessary): Deleted.
Replaced by startObserving.
(WebCore::NetworkStateNotifier::onLine): Deleted. This function is now
platform-independent.
(WebCore::setOnLine): Deleted. The logic from this is now in
updateState and updateStateWithoutNotifying.

* platform/network/mac/NetworkStateNotifierMac.cpp:
(WebCore::NetworkStateNotifier::updateStateWithoutNotifying): Renamed
this from updateState and tightened up the code a bit. Also changed
to not assume anything. If there is an error, we leave m_isOnLine alone.
Default behavior is now in the platform-independent code, and the default
is to treat things as on-line if updateStateWithoutNotifying was called
and it was never able to update the state even once.
(WebCore::NetworkStateNotifier::startObserving): Moved most of the code
from the constructor into this function.
(WebCore::NetworkStateNotifier::dynamicStoreCallback): Deleted. This is
now a lambda inside startObserving.
(WebCore::NetworkStateNotifier::networkStateChangeTimerFired): Deleted.
This function is now platform-independent and is named updateState.

* platform/network/win/NetworkStateNotifierWin.cpp:
(WebCore::NetworkStateNotifier::updateStateWithoutNotifying): Renamed
from updateState and tightened the code up a bit. Also changed
to not assume anything. If there is an error, we leave m_isOnLine alone.
Default behavior is now in the platform-independent code, and the default
is to treat things as on-line if updateStateWithoutNotifying was called
and it was never able to update the state even once.
(WebCore::NetworkStateNotifier::addressChanged): Deleted.
This function is now platform-independent and is named updateState.
(WebCore::NetworkStateNotifier::addressChangeCallback): Renamed from
addrChangeCallback. Simplified by using the singleton function instead
of relying on the context pointer.
(WebCore::NetworkStateNotifier::startObserving): Moved most of the code
from the constructor here.

* platform/text/LocaleToScriptMappingDefault.cpp:
(WebCore::scriptNameToCode): Use makeNeverDestroyed.
(WebCore::localeToScriptCodeForFontSelection): Ditto.

* platform/text/ios/LocalizedDateCache.h: Moved include of
NeverDestroyed.h from here ...
* platform/text/ios/LocalizedDateCache.mm: ... to here.

* platform/wpe/RenderThemeWPE.cpp:
(WebCore::RenderTheme::singleton): Use a theme that is never destroyed
rather than Ref that is never destroyed.

* platform/wpe/RenderThemeWPE.h: Use friend NeverDestroyed rather than
a create function since RenderTheme is no longer reference counted.

* rendering/RenderTheme.h: Made RenderTheme no longer reference counted.

* rendering/RenderThemeGtk.cpp:
(WebCore::RenderThemeGtk::create): Deleted.
(WebCore::RenderTheme::singleton): Use a theme that is never destroyed
rather than Ref that is never destroyed.

* rendering/RenderThemeGtk.h: Use friend NeverDestroyed rather than
a create function since RenderTheme is no longer reference counted.
* rendering/RenderThemeIOS.h: Ditto.

* rendering/RenderThemeIOS.mm:
(WebCore::RenderThemeIOS::create): Deleted.
(WebCore::RenderTheme::singleton): Use a theme that is never destroyed
rather than Ref that is never destroyed.

* rendering/RenderThemeMac.h: Use friend NeverDestroyed rather than
a create function since RenderTheme is no longer reference counted.
Also marked a lot of functions final rather than override and initialized
data members in the class deifnition.

* rendering/RenderThemeMac.mm: Moved some SPI interfaces to the top of the
file. They should really go into SPI headers.
(-[WebCoreRenderThemeNotificationObserver init]): Removed the theme argument
here because the theme is a singleton and we don't need a pointer to it.
Add the observer here instead of doing it in the caller.
(-[WebCoreRenderThemeNotificationObserver systemColorsDidChange:]): Call
platformColorsDidChange through the singleton rather than using a pointer.
(-[WebCoreTextFieldCell _coreUIDrawOptionsWithFrame:inView:includeFocus:]):
Tightened up the code a bit by using CFAutorelease instead of using a
combination of NSMakeCollectable, autorelease, and a typecast to accomplish
the same thing.
(WebCore::RenderTheme::singleton): Use a theme that is never destroyed
rather than Ref that is never destroyed.
(WebCore::RenderThemeMac::create): Deleted.
(WebCore::RenderThemeMac::RenderThemeMac): Moved initialization into the
class definition and observing into the WebCoreRenderThemeNotificationObserver
init function.
(WebCore::RenderThemeMac::~RenderThemeMac): Deleted. No need for this since
the object will never be destroyed.
(WebCore::RenderThemeMac::mediaControlsBase64StringForIconNameAndType):
Removed an unnecessary conversion from C string literal to WTF::String and
then to NSString. Instead, just use an NSString literal.

* rendering/RenderThemeWin.cpp:
(WebCore::RenderThemeWin::create): Deleted.
(WebCore::RenderTheme::singleton): Use a theme that is never destroyed
rather than Ref that is never destroyed.

* rendering/RenderThemeWin.h: Use friend NeverDestroyed rather than
a create function since RenderTheme is no longer reference counted.

* rendering/svg/RenderSVGResource.cpp:
(WebCore::removeFromCacheAndInvalidateDependencies): Moved a global into
the code where it is used.

* svg/SVGAnimatedLength.cpp: Removed unneeded include of NeverDestroyed.h.

* svg/SVGAnimationElement.cpp:
(WebCore::SVGAnimationElement::isSupportedAttribute): Use const auto,
makeNeverDestroyed, a lambda, and the new HashSet::add overload instead of
an isEmpty check and lots of separate add function calls.
* svg/SVGClipPathElement.cpp:
(WebCore::SVGClipPathElement::isSupportedAttribute): Ditto.
* svg/SVGComponentTransferFunctionElement.cpp:
(WebCore::SVGComponentTransferFunctionElement::isSupportedAttribute): Ditto.
* svg/SVGCursorElement.cpp:
(WebCore::SVGCursorElement::isSupportedAttribute): Ditto.

* svg/SVGElement.cpp:
(WebCore::createAttributeNameToCSSPropertyIDMap): Replaced the populate
function with this create function.
(WebCore::createAttributeNameToAnimatedPropertyTypeMap): Ditto.
(WebCore::attributeNameToAnimatedPropertyTypeMap): Changed return type to
const reference. Use const auto and makeNeverDestroyed instead of using
isEmpty and a populate function.
(WebCore::createCSSPropertyWithSVGDOMNameToAnimatedPropertyTypeMap):
More of the same.
(WebCore::cssPropertyWithSVGDOMNameToAnimatedPropertyTypeMap): Ditto.
(WebCore::SVGElement::childShouldCreateRenderer): Use an array instead of
a HashSet since we are checking against only 3 or 4 values.
(WebCore::addQualifiedName): Deleted.
(WebCore::SVGElement::animatableAttributeForName): Use const auto,
makeNeverDestroyed, and a lambda to efficiently build the map in this function.
(WebCore::SVGElement::cssPropertyIdForSVGAttributeName): Use const auto and
makeNeverDestroyed instead of using isEmpty and a populate function.

* svg/SVGFilterElement.cpp:
(WebCore::SVGFilterElement::isSupportedAttribute): Use const auto,
makeNeverDestroyed, a lambda, and the new HashSet::add overload instead of
an isEmpty check and lots of separate add function calls.
* svg/SVGFilterPrimitiveStandardAttributes.cpp:
(WebCore::SVGFilterPrimitiveStandardAttributes::isSupportedAttribute): Ditto.
* svg/SVGForeignObjectElement.cpp:
(WebCore::SVGForeignObjectElement::isSupportedAttribute): Ditto.
* svg/SVGGElement.cpp:
(WebCore::SVGGElement::isSupportedAttribute): Ditto.
* svg/SVGGradientElement.cpp:
(WebCore::SVGGradientElement::isSupportedAttribute): Ditto.
* svg/SVGGraphicsElement.cpp:
(WebCore::SVGGraphicsElement::isSupportedAttribute): Ditto.
* svg/SVGImageElement.cpp:
(WebCore::SVGImageElement::isSupportedAttribute): Ditto.
* svg/SVGLangSpace.cpp:
(WebCore::addWithAndWithoutXMLPrefix): Added helper. Uses xmlAtom instead
of making our own NeverDestroyed local xmlPrefix.
(WebCore::SVGLangSpace::addSupportedAttributes): Rewrote to use helper.
* svg/SVGLineElement.cpp:
(WebCore::SVGLineElement::isSupportedAttribute): Use const auto,
makeNeverDestroyed, a lambda, and the new HashSet::add overload instead of
an isEmpty check and lots of separate add function calls.
* svg/SVGLinearGradientElement.cpp:
(WebCore::SVGLinearGradientElement::isSupportedAttribute): Ditto.
* svg/SVGMarkerElement.cpp:
(WebCore::SVGMarkerElement::isSupportedAttribute): Ditto.
* svg/SVGMaskElement.cpp:
(WebCore::SVGMaskElement::isSupportedAttribute): Ditto.
* svg/SVGPathElement.cpp:
(WebCore::SVGPathElement::isSupportedAttribute): Ditto.
* svg/SVGPatternElement.cpp:
(WebCore::SVGPatternElement::isSupportedAttribute): Ditto.
* svg/SVGRadialGradientElement.cpp:
(WebCore::SVGRadialGradientElement::isSupportedAttribute): Ditto.
* svg/SVGTextContentElement.cpp:
(WebCore::SVGTextContentElement::isSupportedAttribute): Ditto.
* svg/SVGTextPathElement.cpp:
(WebCore::SVGTextPathElement::isSupportedAttribute): Ditto.
* svg/animation/SVGSMILElement.cpp:
(WebCore::SVGSMILElement::isSupportedAttribute): Ditto.

* testing/MockContentFilterSettings.h: Removed unneeded include of
NeverDestroyed.h.

* testing/MockGamepadProvider.cpp: Moved include of
NeverDestroyed.h here ...
* testing/MockGamepadProvider.h: ... from here.

* testing/MockPreviewLoaderClient.h: Removed unneeded include of
NeverDestroyed.h.

* workers/Worker.cpp:
(WebCore::allWorkers): Changed this from a global to a function.
(WebCore::Worker::networkStateChanged): Updated for above change and
made this a member function.
(WebCore::Worker::Worker): Updated for above change and
change to NetworkStateNotifier.
(WebCore::Worker::~Worker): Ditto.
* workers/Worker.h: Made networkStateChanged a static member instead of
a friend since that is a cleaner way to give it access to private member
functions.

* xml/XPathFunctions.cpp:
(WebCore::XPath::createFunctionMap): Use create instead of populate style.
(WebCore::XPath::Function::create): Use const auto and makeNeverDestroyed
instead of an isEmpty check.

* xml/XPathParser.cpp:
(WebCore::XPath::createAxisNamesMap): Use create instead of populate style.
(WebCore::XPath::parseAxisName): Use const auto and makeNeverDestroyed
instead of an isEmpty check.

Source/WebKit:

* DatabaseProcess/DatabaseProcess.h: Removed unneeded include of
NeverDestroyed.h.
* NetworkProcess/cache/NetworkCacheKey.cpp: Ditto.

* NetworkProcess/capture/NetworkCaptureManager.cpp: Moved include of
NeverDestroyed.h here ...
* NetworkProcess/capture/NetworkCaptureManager.h: ... from here.

* PluginProcess/PluginProcess.cpp: Moved include of NeverDestroyed.h
here ...
* PluginProcess/PluginProcess.h: ... from here.

* Shared/API/Cocoa/_WKRemoteObjectInterface.mm:
(isContainerClass): Removed trivial inefficient use of
LazyNeverDestroyed<HashSet> to check against two classes.
Instead wrote out the boolean expression.

* Shared/mac/SecItemShim.cpp: Removed unneeded include of
NeverDestroyed.h.

* UIProcess/Cocoa/WebProcessPoolCocoa.mm:
(WebKit::WebProcessPool::platformInitialize): Call
installMemoryPressureHandler instead of WebMemoryPressureHandler::singleton.

* UIProcess/Gamepad/UIGamepadProvider.h: Removed unneeded include
of NeverDestroyed.h.

* UIProcess/Plugins/PluginProcessManager.cpp: Moved include of
NeverDestroyed.h here ...
* UIProcess/Plugins/PluginProcessManager.h: ... from here.

* UIProcess/WebInspectorProxy.cpp: Removed unneeded include
of NeverDestroyed.h.

* UIProcess/WebPageProxy.h: Added now-needed include of
MediaPlaybackTargetContext.h.

* UIProcess/WebPasteboardProxy.cpp: Moved include of
NeverDestroyed.h here ...
* UIProcess/WebPasteboardProxy.h: ... from here.

* UIProcess/ios/WebMemoryPressureHandlerIOS.h: Removed the
WebMemoryPressureHandler class from this header. Callers don't need to
know if there is a class. They simply indicate when it's time to install
the handler. Another way to put it is that this class had no functions
other than the singleton function.

* UIProcess/ios/WebMemoryPressureHandlerIOS.mm:
(WebKit::installMemoryPressureHandler): Replaced the class with this function.
It creates a dispatch source and then resumes it. To avoid having the source
look like a leak, we keep it in a global variable.

* WebProcess/Gamepad/WebGamepadProvider.h: Include Forward.h instead of
NeverDestroyed.h.

* WebProcess/WebCoreSupport/WebPasteboardOverrides.cpp: Moved include of
NeverDestroyed.h here ...
* WebProcess/WebCoreSupport/WebPasteboardOverrides.h: ... from here.

* WebProcess/WebCoreSupport/WebPlatformStrategies.h: Removed unneeded
include of NeverDestroyed.h.

Source/WebKitLegacy:

* Storage/StorageThread.cpp:
(WebCore::StorageThread::releaseFastMallocFreeMemoryInAllThreads):
Simplify code by using a modern for loop and passing a function without wrapping
it in a lambda.

Source/WebKitLegacy/mac:

* Misc/WebStringTruncator.mm:
(+[WebStringTruncator centerTruncateString:toWidth:]): Replace
NeverDestroyed<RetainPtr> with just an NSFont * global.

* Plugins/Hosted/NetscapePluginHostManager.h: Removed unneeded include of
NeverDestroyed.h.
* Storage/WebDatabaseManager.mm: Ditto.
* WebCoreSupport/WebFrameNetworkingContext.mm: Ditto.
* WebCoreSupport/WebPlatformStrategies.mm: Ditto.

* WebView/WebView.mm: Removed unneeded include of NetworkStateNotifier.h.
(aeDescFromJSValue): Removed double hashing by using the return value from
add rather than calling contains before calling add.

Source/WTF:

* wtf/HashSet.h: Added an overload of HashSet::add that takes an initializer list of
const references. This is handy to add a bunch of values all at once. Later we can
consider optimizing to grow the hash table only once instead of deciding whether to
grow repeatedly as we add each value.
(WTF::copyToVector): Changed to use std::copy, removing 4 of the 6 lines of code here.

* wtf/MemoryPressureHandler.cpp: Include NeverDestroyed.h here ...
* wtf/MemoryPressureHandler.h: ... not here.

* wtf/NeverDestroyed.h: Added the ability to have a const NeverDestroyed.
Added a makeNeverDestroyed function that deduces the type from the argument.
With auto, this can be used to avoid writing out a long type twice.

* wtf/ThreadingPthreads.cpp: Removed unneeded include of NeverDestroyed.h.
* wtf/text/AtomicString.cpp: Ditto.

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

190 files changed:
Source/JavaScriptCore/ChangeLog
Source/JavaScriptCore/heap/MachineStackMarker.cpp
Source/JavaScriptCore/wasm/WasmMemory.cpp
Source/WTF/ChangeLog
Source/WTF/wtf/HashSet.h
Source/WTF/wtf/MemoryPressureHandler.cpp
Source/WTF/wtf/MemoryPressureHandler.h
Source/WTF/wtf/NeverDestroyed.h
Source/WTF/wtf/ThreadingPthreads.cpp
Source/WTF/wtf/text/AtomicString.cpp
Source/WebCore/ChangeLog
Source/WebCore/Modules/encryptedmedia/MediaKeySession.cpp
Source/WebCore/Modules/encryptedmedia/legacy/LegacyCDM.cpp
Source/WebCore/Modules/encryptedmedia/legacy/LegacyCDMSessionClearKey.cpp
Source/WebCore/Modules/gamepad/GamepadManager.cpp
Source/WebCore/Modules/indexeddb/IDBTransaction.cpp
Source/WebCore/Modules/indexeddb/server/MemoryObjectStore.cpp
Source/WebCore/Modules/mediasession/MediaSessionManager.cpp
Source/WebCore/Modules/mediasession/MediaSessionManager.h
Source/WebCore/Modules/mediasource/MediaSourceRegistry.cpp
Source/WebCore/Modules/mediasource/MediaSourceRegistry.h
Source/WebCore/Modules/mediasource/SourceBuffer.cpp
Source/WebCore/Modules/plugins/QuickTimePluginReplacement.h
Source/WebCore/Modules/plugins/QuickTimePluginReplacement.mm
Source/WebCore/accessibility/AccessibilityRenderObject.cpp
Source/WebCore/bindings/scripts/CodeGeneratorJS.pm
Source/WebCore/bindings/scripts/test/JS/JSTestCallbackInterface.cpp
Source/WebCore/bindings/scripts/test/JS/JSTestObj.cpp
Source/WebCore/bindings/scripts/test/JS/JSTestStandaloneDictionary.cpp
Source/WebCore/bindings/scripts/test/JS/JSTestStandaloneEnumeration.cpp
Source/WebCore/css/CSSProperty.cpp
Source/WebCore/css/ElementRuleCollector.cpp
Source/WebCore/css/makeprop.pl
Source/WebCore/dom/CustomElementReactionQueue.cpp
Source/WebCore/dom/DOMImplementation.cpp
Source/WebCore/dom/InputEvent.cpp
Source/WebCore/dom/Microtasks.cpp
Source/WebCore/dom/Microtasks.h
Source/WebCore/dom/MutationObserver.cpp
Source/WebCore/dom/ScopedEventQueue.cpp
Source/WebCore/dom/ScopedEventQueue.h
Source/WebCore/dom/ScriptElement.cpp
Source/WebCore/dom/SecurityContext.cpp
Source/WebCore/dom/make_names.pl
Source/WebCore/editing/AlternativeTextController.cpp
Source/WebCore/editing/EditingStyle.cpp
Source/WebCore/editing/FormatBlockCommand.cpp
Source/WebCore/editing/RemoveFormatCommand.cpp
Source/WebCore/editing/ReplaceSelectionCommand.cpp
Source/WebCore/html/Autofill.cpp
Source/WebCore/html/HTMLObjectElement.cpp
Source/WebCore/html/HTMLStyleElement.cpp
Source/WebCore/html/HTMLVideoElement.cpp
Source/WebCore/html/InputType.cpp
Source/WebCore/html/parser/HTMLParserIdioms.cpp
Source/WebCore/inspector/InspectorApplicationCacheAgent.cpp
Source/WebCore/loader/ContentFilter.cpp
Source/WebCore/loader/CrossOriginAccessControl.cpp
Source/WebCore/loader/CrossOriginAccessControl.h
Source/WebCore/loader/EmptyClients.cpp
Source/WebCore/loader/appcache/ApplicationCacheStorage.cpp
Source/WebCore/page/CaptionUserPreferences.cpp
Source/WebCore/page/DebugPageOverlays.cpp
Source/WebCore/page/MainFrame.cpp
Source/WebCore/page/MemoryRelease.cpp
Source/WebCore/page/NavigatorBase.cpp
Source/WebCore/page/Page.cpp
Source/WebCore/page/Page.h
Source/WebCore/page/PerformanceUserTiming.cpp
Source/WebCore/page/RuntimeEnabledFeatures.cpp
Source/WebCore/page/RuntimeEnabledFeatures.h
Source/WebCore/platform/LocalizedStrings.cpp
Source/WebCore/platform/MIMETypeRegistry.cpp
Source/WebCore/platform/MainThreadSharedTimer.cpp
Source/WebCore/platform/MainThreadSharedTimer.h
Source/WebCore/platform/SchemeRegistry.cpp
Source/WebCore/platform/cocoa/WebVideoFullscreenModelVideoElement.mm
Source/WebCore/platform/gamepad/cocoa/GameControllerGamepadProvider.h
Source/WebCore/platform/gamepad/cocoa/GameControllerGamepadProvider.mm
Source/WebCore/platform/gamepad/mac/HIDGamepadProvider.cpp
Source/WebCore/platform/gamepad/mac/HIDGamepadProvider.h
Source/WebCore/platform/graphics/FontCascade.cpp
Source/WebCore/platform/graphics/ImageBuffer.cpp
Source/WebCore/platform/graphics/ImageBuffer.h
Source/WebCore/platform/graphics/MediaPlaybackTarget.h
Source/WebCore/platform/graphics/avfoundation/MediaPlaybackTargetMac.h
Source/WebCore/platform/graphics/avfoundation/MediaPlayerPrivateAVFoundation.cpp
Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.mm
Source/WebCore/platform/graphics/cairo/ImageBufferCairo.cpp
Source/WebCore/platform/graphics/cg/ImageDecoderCG.cpp
Source/WebCore/platform/graphics/gtk/GdkCairoUtilities.cpp
Source/WebCore/platform/graphics/ios/FontCacheIOS.mm
Source/WebCore/platform/graphics/mac/FontCacheMac.mm
Source/WebCore/platform/graphics/mac/MediaPlayerPrivateQTKit.mm
Source/WebCore/platform/ios/Device.cpp
Source/WebCore/platform/ios/DragImageIOS.mm
Source/WebCore/platform/ios/LegacyTileLayerPool.h
Source/WebCore/platform/ios/QuickLook.mm
Source/WebCore/platform/ios/WebCoreMotionManager.mm
Source/WebCore/platform/ios/WebSQLiteDatabaseTrackerClient.h
Source/WebCore/platform/mac/DragImageMac.mm
Source/WebCore/platform/mediastream/CaptureDeviceManager.cpp
Source/WebCore/platform/mediastream/RealtimeMediaSourceSupportedConstraints.cpp
Source/WebCore/platform/mock/MockRealtimeMediaSource.cpp
Source/WebCore/platform/mock/mediasource/MockMediaPlayerMediaSource.cpp
Source/WebCore/platform/network/BlobRegistryImpl.cpp
Source/WebCore/platform/network/NetworkStateNotifier.cpp
Source/WebCore/platform/network/NetworkStateNotifier.h
Source/WebCore/platform/network/ios/NetworkStateNotifierIOS.mm
Source/WebCore/platform/network/mac/NetworkStateNotifierMac.cpp
Source/WebCore/platform/network/win/NetworkStateNotifierWin.cpp
Source/WebCore/platform/text/LocaleToScriptMappingDefault.cpp
Source/WebCore/platform/text/ios/LocalizedDateCache.h
Source/WebCore/platform/text/ios/LocalizedDateCache.mm
Source/WebCore/platform/wpe/RenderThemeWPE.cpp
Source/WebCore/platform/wpe/RenderThemeWPE.h
Source/WebCore/rendering/RenderTheme.h
Source/WebCore/rendering/RenderThemeGtk.cpp
Source/WebCore/rendering/RenderThemeGtk.h
Source/WebCore/rendering/RenderThemeIOS.h
Source/WebCore/rendering/RenderThemeIOS.mm
Source/WebCore/rendering/RenderThemeMac.h
Source/WebCore/rendering/RenderThemeMac.mm
Source/WebCore/rendering/RenderThemeWin.cpp
Source/WebCore/rendering/RenderThemeWin.h
Source/WebCore/rendering/svg/RenderSVGResource.cpp
Source/WebCore/svg/SVGAnimatedLength.cpp
Source/WebCore/svg/SVGAnimationElement.cpp
Source/WebCore/svg/SVGClipPathElement.cpp
Source/WebCore/svg/SVGComponentTransferFunctionElement.cpp
Source/WebCore/svg/SVGCursorElement.cpp
Source/WebCore/svg/SVGElement.cpp
Source/WebCore/svg/SVGFilterElement.cpp
Source/WebCore/svg/SVGFilterPrimitiveStandardAttributes.cpp
Source/WebCore/svg/SVGForeignObjectElement.cpp
Source/WebCore/svg/SVGGElement.cpp
Source/WebCore/svg/SVGGradientElement.cpp
Source/WebCore/svg/SVGGraphicsElement.cpp
Source/WebCore/svg/SVGImageElement.cpp
Source/WebCore/svg/SVGLangSpace.cpp
Source/WebCore/svg/SVGLineElement.cpp
Source/WebCore/svg/SVGLinearGradientElement.cpp
Source/WebCore/svg/SVGMarkerElement.cpp
Source/WebCore/svg/SVGMaskElement.cpp
Source/WebCore/svg/SVGPathElement.cpp
Source/WebCore/svg/SVGPatternElement.cpp
Source/WebCore/svg/SVGRadialGradientElement.cpp
Source/WebCore/svg/SVGTextContentElement.cpp
Source/WebCore/svg/SVGTextPathElement.cpp
Source/WebCore/svg/animation/SVGSMILElement.cpp
Source/WebCore/testing/MockContentFilterSettings.h
Source/WebCore/testing/MockGamepadProvider.cpp
Source/WebCore/testing/MockGamepadProvider.h
Source/WebCore/testing/MockPreviewLoaderClient.h
Source/WebCore/workers/Worker.cpp
Source/WebCore/workers/Worker.h
Source/WebCore/xml/XPathFunctions.cpp
Source/WebCore/xml/XPathParser.cpp
Source/WebKit/ChangeLog
Source/WebKit/DatabaseProcess/DatabaseProcess.h
Source/WebKit/NetworkProcess/cache/NetworkCacheKey.cpp
Source/WebKit/NetworkProcess/capture/NetworkCaptureManager.cpp
Source/WebKit/NetworkProcess/capture/NetworkCaptureManager.h
Source/WebKit/PluginProcess/PluginProcess.cpp
Source/WebKit/PluginProcess/PluginProcess.h
Source/WebKit/Shared/API/Cocoa/_WKRemoteObjectInterface.mm
Source/WebKit/Shared/mac/SecItemShim.cpp
Source/WebKit/UIProcess/Cocoa/WebProcessPoolCocoa.mm
Source/WebKit/UIProcess/Gamepad/UIGamepadProvider.h
Source/WebKit/UIProcess/Plugins/PluginProcessManager.cpp
Source/WebKit/UIProcess/Plugins/PluginProcessManager.h
Source/WebKit/UIProcess/WebInspectorProxy.cpp
Source/WebKit/UIProcess/WebPageProxy.h
Source/WebKit/UIProcess/WebPasteboardProxy.cpp
Source/WebKit/UIProcess/WebPasteboardProxy.h
Source/WebKit/UIProcess/ios/WebMemoryPressureHandlerIOS.h
Source/WebKit/UIProcess/ios/WebMemoryPressureHandlerIOS.mm
Source/WebKit/WebProcess/Gamepad/WebGamepadProvider.h
Source/WebKit/WebProcess/WebCoreSupport/WebPasteboardOverrides.cpp
Source/WebKit/WebProcess/WebCoreSupport/WebPasteboardOverrides.h
Source/WebKit/WebProcess/WebCoreSupport/WebPlatformStrategies.h
Source/WebKitLegacy/ChangeLog
Source/WebKitLegacy/Storage/StorageThread.cpp
Source/WebKitLegacy/mac/ChangeLog
Source/WebKitLegacy/mac/Misc/WebStringTruncator.mm
Source/WebKitLegacy/mac/Plugins/Hosted/NetscapePluginHostManager.h
Source/WebKitLegacy/mac/Storage/WebDatabaseManager.mm
Source/WebKitLegacy/mac/WebCoreSupport/WebFrameNetworkingContext.mm
Source/WebKitLegacy/mac/WebCoreSupport/WebPlatformStrategies.mm
Source/WebKitLegacy/mac/WebView/WebView.mm

index 3c54d958aa4025500b8b1179da8c695ac8810771..0a6584a337b798e2bb7c87c5b069a8979beb934a 100644 (file)
@@ -1,3 +1,15 @@
+2017-07-17  Darin Adler  <darin@apple.com>
+
+        Improve use of NeverDestroyed
+        https://bugs.webkit.org/show_bug.cgi?id=174348
+
+        Reviewed by Sam Weinig.
+
+        * heap/MachineStackMarker.cpp:
+        * wasm/WasmMemory.cpp:
+        Removed unneeded includes of NeverDestroyed.h in files that do not make use
+        of NeverDestroyed.
+
 2017-07-17  Michael Catanzaro  <mcatanzaro@igalia.com>
 
         [CMake] Macros in WebKitMacros.cmake should be prefixed with WEBKIT_ namespace
index 6763ea3ab1c2f4679c3771b191973c5316bf5f40..2e2d5af5895c589ef4975cc8cdab6ed7bbaf7beb 100644 (file)
@@ -33,7 +33,6 @@
 #include <setjmp.h>
 #include <stdlib.h>
 #include <wtf/MainThread.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/StdLibExtras.h>
 
 using namespace WTF;
index 2d36e80cd3b5050f4998bd71e586473fe5aef65e..ed8c5d7ce8518ea87534427e99ad27b5a2b4ea46 100644 (file)
@@ -33,7 +33,6 @@
 
 #include <atomic>
 #include <wtf/MonotonicTime.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/Platform.h>
 #include <wtf/PrintStream.h>
 #include <wtf/VMTags.h>
index 27d1cb55b02cbacf921d5ab42307efd89e9583a2..c3dde51fa5481dc5a7470ceaca014881b770f8e3 100644 (file)
@@ -1,3 +1,26 @@
+2017-07-17  Darin Adler  <darin@apple.com>
+
+        Improve use of NeverDestroyed
+        https://bugs.webkit.org/show_bug.cgi?id=174348
+
+        Reviewed by Sam Weinig.
+
+        * wtf/HashSet.h: Added an overload of HashSet::add that takes an initializer list of
+        const references. This is handy to add a bunch of values all at once. Later we can
+        consider optimizing to grow the hash table only once instead of deciding whether to
+        grow repeatedly as we add each value.
+        (WTF::copyToVector): Changed to use std::copy, removing 4 of the 6 lines of code here.
+
+        * wtf/MemoryPressureHandler.cpp: Include NeverDestroyed.h here ...
+        * wtf/MemoryPressureHandler.h: ... not here.
+
+        * wtf/NeverDestroyed.h: Added the ability to have a const NeverDestroyed.
+        Added a makeNeverDestroyed function that deduces the type from the argument.
+        With auto, this can be used to avoid writing out a long type twice.
+
+        * wtf/ThreadingPthreads.cpp: Removed unneeded include of NeverDestroyed.h.
+        * wtf/text/AtomicString.cpp: Ditto.
+
 2017-07-17  Konstantin Tokarev  <annulen@yandex.ru>
 
         [CMake] Create targets before WEBKIT_INCLUDE_CONFIG_FILES_IF_EXISTS is called
index 13ad1038bb8fa2190d30780e2daa23471a3001c7..e6141f51765983975d013b1d8a0d94bd14d3b20f 100644 (file)
@@ -22,7 +22,6 @@
 #define WTF_HashSet_h
 
 #include <initializer_list>
-#include <wtf/FastMalloc.h>
 #include <wtf/GetPtr.h>
 #include <wtf/HashTable.h>
 
@@ -86,7 +85,8 @@ namespace WTF {
         // and an isNewEntry bool that indicates if it is a new or existing entry in the set.
         AddResult add(const ValueType&);
         AddResult add(ValueType&&);
-        
+        void add(std::initializer_list<std::reference_wrapper<const ValueType>>);
+
         void addVoid(const ValueType&);
         void addVoid(ValueType&&);
 
@@ -358,15 +358,9 @@ namespace WTF {
     template<typename C, typename W>
     inline void copyToVector(const C& collection, W& vector)
     {
-        typedef typename C::const_iterator iterator;
-        
         vector.resize(collection.size());
-        
-        iterator it = collection.begin();
-        iterator end = collection.end();
-        for (unsigned i = 0; it != end; ++it, ++i)
-            vector[i] = *it;
-    }  
+        std::copy(collection.begin(), collection.end(), vector.begin());
+    }
 
     template<typename T, typename U, typename V>
     template<typename OtherCollection>
@@ -388,6 +382,13 @@ namespace WTF {
         return !(*this == otherCollection);
     }
 
+    template<typename T, typename U, typename V>
+    void HashSet<T, U, V>::add(std::initializer_list<std::reference_wrapper<const ValueType>> list)
+    {
+        for (auto& value : list)
+            add(value);
+    }
+
 } // namespace WTF
 
 using WTF::HashSet;
index 2947f55d44a46d2ad711f6e08381210eeb842360..36162865b802e4f5d5f7e142d2ac3bdb522a9ed5 100644 (file)
@@ -27,6 +27,7 @@
 #include "MemoryPressureHandler.h"
 
 #include <wtf/MemoryFootprint.h>
+#include <wtf/NeverDestroyed.h>
 
 #define LOG_CHANNEL_PREFIX Log
 
index c300a4036a188555ae29d12ff1b39cbccf767bf6..57894ca25399fc58f6d40ac5bbba05b5a8666aac 100644 (file)
@@ -31,7 +31,6 @@
 #include <wtf/FastMalloc.h>
 #include <wtf/Forward.h>
 #include <wtf/Function.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/Optional.h>
 #include <wtf/RunLoop.h>
 
index b824634f87740ab047027e26849d9c565897a05d..8784b6ed650f2775ed719fa2684c00860647ea36 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013 Apple Inc. All rights reserved.
+ * Copyright (C) 2013-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
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef NeverDestroyed_h
-#define NeverDestroyed_h
+#pragma once
 
 #include <type_traits>
 #include <utility>
-#include <wtf/Noncopyable.h>
 #include <wtf/RefCounted.h>
 
-// NeverDestroyed is a smart pointer like class who ensures that the destructor
+// NeverDestroyed is a smart-pointer-like class that ensures that the destructor
 // for the given object is never called, but doesn't use the heap to allocate it.
 // It's useful for static local variables, and can be used like so:
 //
@@ -47,32 +45,39 @@ template<typename T> class NeverDestroyed {
     WTF_MAKE_NONCOPYABLE(NeverDestroyed);
 
 public:
-    template<typename... Args>
-    NeverDestroyed(Args&&... args)
+    template<typename... Args> NeverDestroyed(Args&&... args)
     {
-        MaybeRelax<T>(new (asPtr()) T(std::forward<Args>(args)...));
+        MaybeRelax<T>(new (storagePointer()) T(std::forward<Args>(args)...));
     }
 
-    operator T&() { return *asPtr(); }
-    T& get() { return *asPtr(); }
+    operator T&() { return *storagePointer(); }
+    T& get() { return *storagePointer(); }
+
+    operator const T&() const { return *storagePointer(); }
+    const T& get() const { return *storagePointer(); }
 
 private:
-    typedef typename std::remove_const<T>::type* PointerType;
+    using PointerType = typename std::remove_const<T>::type*;
 
-    PointerType asPtr() { return reinterpret_cast<PointerType>(&m_storage); }
+    PointerType storagePointer() const { return const_cast<PointerType>(reinterpret_cast<const T*>(&m_storage)); }
 
     // FIXME: Investigate whether we should allocate a hunk of virtual memory
     // and hand out chunks of it to NeverDestroyed instead, to reduce fragmentation.
     typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type m_storage;
 
-    template <typename PtrType, bool ShouldRelax = std::is_base_of<RefCountedBase, PtrType>::value> struct MaybeRelax {
+    template<typename PtrType, bool ShouldRelax = std::is_base_of<RefCountedBase, PtrType>::value> struct MaybeRelax {
         explicit MaybeRelax(PtrType*) { }
     };
-    template <typename PtrType> struct MaybeRelax<PtrType, true> {
+    template<typename PtrType> struct MaybeRelax<PtrType, true> {
         explicit MaybeRelax(PtrType* ptr) { ptr->relaxAdoptionRequirement(); }
     };
 };
 
+template<typename T> NeverDestroyed<T> makeNeverDestroyed(T&&);
+
+// FIXME: It's messy to have to repeat the whole class just to make this "lazy" version.
+// Should revisit clients to see if we really need this, and perhaps use templates to
+// share more of the code with the main NeverDestroyed above.
 template<typename T> class LazyNeverDestroyed {
     WTF_MAKE_NONCOPYABLE(LazyNeverDestroyed);
 
@@ -88,45 +93,53 @@ public:
         m_isConstructed = true;
 #endif
 
-        MaybeRelax<T>(new (asPtr()) T(std::forward<Args>(args)...));
+        MaybeRelax<T>(new (storagePointer()) T(std::forward<Args>(args)...));
     }
 
-    operator T&() { return *asPtr(); }
-    T& get() { return *asPtr(); }
+    operator T&() { return *storagePointer(); }
+    T& get() { return *storagePointer(); }
+
+    T* operator->() { return storagePointer(); }
 
-    T* operator->() { return asPtr(); }
+    operator const T&() const { return *storagePointer(); }
+    const T& get() const { return *storagePointer(); }
+
+    const T* operator->() const { return storagePointer(); }
 
 private:
-    typedef typename std::remove_const<T>::type* PointerType;
+    using PointerType = typename std::remove_const<T>::type*;
 
-    PointerType asPtr()
+    PointerType storagePointer() const
     {
         ASSERT(m_isConstructed);
-
-        return reinterpret_cast<PointerType>(&m_storage);
+        return const_cast<PointerType>(reinterpret_cast<const T*>(&m_storage));
     }
 
     // FIXME: Investigate whether we should allocate a hunk of virtual memory
     // and hand out chunks of it to NeverDestroyed instead, to reduce fragmentation.
     typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type m_storage;
 
-    template <typename PtrType, bool ShouldRelax = std::is_base_of<RefCountedBase, PtrType>::value> struct MaybeRelax {
+    template<typename PtrType, bool ShouldRelax = std::is_base_of<RefCountedBase, PtrType>::value> struct MaybeRelax {
         explicit MaybeRelax(PtrType*) { }
     };
-    template <typename PtrType> struct MaybeRelax<PtrType, true> {
+    template<typename PtrType> struct MaybeRelax<PtrType, true> {
         explicit MaybeRelax(PtrType* ptr) { ptr->relaxAdoptionRequirement(); }
     };
 
 #if !ASSERT_DISABLED
     // LazyNeverDestroyed objects are always static, so this variable is initialized to false.
-    // It must not be initialized dynamically, because that would not be thread safe.
+    // It must not be initialized dynamically; that would not be thread safe.
     bool m_isConstructed;
 #endif
 };
 
+template<typename T> inline NeverDestroyed<T> makeNeverDestroyed(T&& argument)
+{
+    return WTFMove(argument);
+}
+
 } // namespace WTF;
 
 using WTF::LazyNeverDestroyed;
 using WTF::NeverDestroyed;
-
-#endif // NeverDestroyed_h
+using WTF::makeNeverDestroyed;
index 35be845b3da699ffe0105cd78fb9a9f70d1a2775..ffa58b2b474f501d0b06af9309b86a8955c0db38 100644 (file)
@@ -37,7 +37,6 @@
 #include <errno.h>
 #include <wtf/CurrentTime.h>
 #include <wtf/DataLog.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/RawPointer.h>
 #include <wtf/StdLibExtras.h>
 #include <wtf/ThreadFunctionInvocation.h>
index 980056481a522561ba4b63e88e28938c39b686b0..a4e03de3af657c69f74d16251f000739136a5344 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2008, 2013-2014, 2016 Apple Inc. All rights reserved.
+ * Copyright (C) 2004-2017 Apple Inc. All rights reserved.
  * Copyright (C) 2010 Patrick Gansterer <paroga@paroga.com>
  * Copyright (C) 2012 Google Inc. All rights reserved.
  *
@@ -25,7 +25,6 @@
 
 #include "IntegerToStringConversion.h"
 #include "MainThread.h"
-#include "NeverDestroyed.h"
 #include "dtoa.h"
 
 namespace WTF {
index 310ab2282f16c6853d943da396e0c7209b762a62..c3e62238d640405c22d3e15553bb615f33083953 100644 (file)
@@ -1,3 +1,699 @@
+2017-07-17  Darin Adler  <darin@apple.com>
+
+        Improve use of NeverDestroyed
+        https://bugs.webkit.org/show_bug.cgi?id=174348
+
+        Reviewed by Sam Weinig.
+
+        * Modules/encryptedmedia/MediaKeySession.cpp: Removed unneeded include of
+        NeverDestroyed.h.
+
+        * Modules/encryptedmedia/legacy/LegacyCDM.cpp:
+        (WebCore::installedCDMFactories): Use makeNeverDestroyed and a lambda rather
+        than a separate boolean for initialization.
+
+        * Modules/encryptedmedia/legacy/LegacyCDMSessionClearKey.cpp:
+        (WebCore::clearKeyVM): Removed unneeded use of NeverDestroyed to hold a
+        RefPtr. Simple to just use leakRef instead.
+
+        * Modules/gamepad/GamepadManager.cpp: Added an include of NeverDestroyed.h.
+
+        * Modules/indexeddb/IDBTransaction.cpp: Removed unneeded include of
+        NeverDestroyed.h.
+        * Modules/indexeddb/server/MemoryObjectStore.cpp: Ditto.
+
+        * Modules/mediasession/MediaSessionManager.cpp: Moved include of
+        NeverDestroyed.h here ...
+        * Modules/mediasession/MediaSessionManager.h: ... from here.
+
+        * Modules/mediasource/MediaSourceRegistry.cpp: Moved include of
+        NeverDestroyed.h here ...
+        * Modules/mediasource/MediaSourceRegistry.h: ... from here.
+
+        * Modules/mediasource/SourceBuffer.cpp: Removed unneeded include of
+        NeverDestroyed.h.
+
+        * Modules/plugins/QuickTimePluginReplacement.h: Initialize
+        m_scriptObject in the class definition.
+
+        * Modules/plugins/QuickTimePluginReplacement.mm:
+        (WebCore::QuickTimePluginReplacement::supportsMimeType): Use
+        makeNeverDestroyed and the HashSet constructor instead of a loop.
+        (WebCore::QuickTimePluginReplacement::supportsFileExtension): Ditto.
+        (WebCore::QuickTimePluginReplacement::QuickTimePluginReplacement): Did a
+        slight cleanup of the initializers.
+        (WebCore::QuickTimePluginReplacement::~QuickTimePluginReplacement): Added
+        a FIXME; unclear why there is code here at all.
+
+        * accessibility/AccessibilityRenderObject.cpp:
+        (WebCore::AccessibilityRenderObject::inheritsPresentationalRole): Use
+        makeNeverDestroyed and the Vector constructor instead of using empty
+        vector checks and Vector::add. Use std::any_of rather than Vector::contains
+        since we now are matching against pointers.
+
+        * bindings/scripts/CodeGeneratorJS.pm:
+        (GenerateEnumerationImplementationContent): Use const NeverDestroyed.
+
+        * bindings/scripts/test/JS/JSTestCallbackInterface.cpp:
+        * bindings/scripts/test/JS/JSTestObj.cpp:
+        * bindings/scripts/test/JS/JSTestStandaloneDictionary.cpp:
+        * bindings/scripts/test/JS/JSTestStandaloneEnumeration.cpp:
+        Regenerated.
+
+        * css/CSSProperty.cpp:
+        (WebCore::borderDirections): Removed unnecesssary use of NeverDestroyed
+        for a global object that has a trivial destructor.
+
+        * css/ElementRuleCollector.cpp:
+        (WebCore::leftToRightDeclaration): Removed unneeded use of NeverDestroyed to hold a
+        Ref. Simple to just use leakRef instead. Also use a lambda instead of an explicit
+        isEmpty check each time this is called.
+        (WebCore::rightToLeftDeclaration): Ditto.
+
+        * css/makeprop.pl: Removed unneeded include of NeverDestroyed.h and the
+        uneeded global emptyShorthand. Constructing an empty StylePropertyShorthand
+        is no less efficient than copying a global empty one was.
+
+        * dom/CustomElementReactionQueue.cpp: Added an include of NeverDestroyed.h.
+
+        * dom/DOMImplementation.cpp: Removed unneeded include of NeverDestroyed.h.
+        * dom/InputEvent.cpp: Ditto.
+
+        * dom/Microtasks.cpp: Moved include of NeverDestroyed.h here ...
+        * dom/Microtasks.h: ... from here.
+
+        * dom/MutationObserver.cpp: Added an include of NeverDestroyed.h.
+
+        * dom/ScopedEventQueue.cpp: Moved include of NeverDestroyed.h here ...
+        * dom/ScopedEventQueue.h: ... from here. Added Forward.h.
+
+        * dom/ScriptElement.cpp:
+        (WebCore::isLegacySupportedJavaScriptLanguage): Use makeNeverDestroyed
+        and the HashSet constructor rather than an isEmpty check and a lot of
+        add function calls. Also removed comments that don't have value any more,
+        with dubious no longer relevant claims about the behavior of old web browsers.
+        The function that calls this one already has sufficient comments about why we
+        hope some day this function can be eliminated.
+
+        * dom/SecurityContext.cpp: Removed unneeded include of NeverDestroyed.h.
+
+        * dom/make_names.pl:
+        (printFactoryCppFile): Instead of using a "populate" function, use a function
+        that creates as HashMap. Then use const auto and makeNeverDestroyed.
+        (printWrapperFactoryCppFile): Ditto.
+
+        * editing/AlternativeTextController.cpp:
+        (WebCore::markerTypesForAutocorrection): Use makeNeverDestroyed
+        and the Vector constructor rather than an isEmpty check and a lot of
+        append function calls.
+        (WebCore::markerTypesForReplacement): Ditto.
+        (WebCore::markerTypesForAppliedDictationAlternative): Ditto.
+
+        * editing/EditingStyle.cpp:
+        (WebCore::htmlElementEquivalents): Use const auto, makeNeverDestroyed,
+        the Vector constructor, and new rather than make_unique. Changed return
+        type to use const pointers rather than unique_ptr with non-const type.
+        (WebCore::EditingStyle::conflictsWithImplicitStyleOfElement): Updated
+        for the above change to htmlElementEquivalents.
+        (WebCore::htmlAttributeEquivalents): Same approach as above.
+        (WebCore::EditingStyle::conflictsWithImplicitStyleOfAttributes): Ditto.
+        (WebCore::elementMatchesAndPropertyIsNotInInlineStyleDecl): Take
+        references instead of pointers.
+        (WebCore::EditingStyle::mergeInlineAndImplicitStyleOfElement): Updated
+        for the above.
+
+        * editing/FormatBlockCommand.cpp:
+        (WebCore::isElementForFormatBlock): Use const auto, makeNeverDestroyed,
+        and the HashSet constructor rather than isEmpty and a lot of calls to add.
+        * editing/RemoveFormatCommand.cpp:
+        (WebCore::isElementForRemoveFormatCommand): Ditto.
+
+        * editing/ReplaceSelectionCommand.cpp:
+        (WebCore::isProhibitedParagraphChild): Use const auto, makeNeverDestroyed,
+        and a lambda, rather than isEmpty and a lot of calls to add.
+
+        * html/Autofill.cpp:
+        (WebCore::fieldNameMap): Changed return type to be const. Use const auto,
+        makeNeverDestroyed, a lambda, and an array of values rather than isEmpty
+        and a lot of calls to add. Stopped doing the ConstructFromLiteral
+        optimization here. (Easy to add it back if that is a mistake.)
+
+        * html/HTMLObjectElement.cpp:
+        (WebCore::isRecognizedTagName): Use const auto, makeNeverDestroyed, and
+        a lambda rather than isEmpty.
+
+        * html/HTMLStyleElement.cpp: Added include of NeverDestroyed.h.
+
+        * html/HTMLVideoElement.cpp: Removed uneeded include of NeverDestroyed.h.
+
+        * html/InputType.cpp:
+        (WebCore::createInputTypeFactoryMap): Replaced the populate function
+        with this create function.
+        (WebCore::InputType::create): Use const auto and makeNeverDestroyed
+        istead of isEmpty. Also put the map right where it is used so it's
+        not initialized in code path where not needed.
+
+        * html/parser/HTMLParserIdioms.cpp: Removed uneeded include of
+        NeverDestroyed.h.
+
+        * inspector/InspectorApplicationCacheAgent.cpp:
+        (WebCore::InspectorApplicationCacheAgent::networkStateChanged):
+        Merged into a single line.
+
+        * loader/ContentFilter.cpp:
+        (WebCore::blockedPageURL): Use const auto and makeNeverDestroyed
+        rather than std::call_once. Since this is a URL and has a non-thread-safe
+        reference count, this was not thread safe before, so no need to use the
+        more roundabout and less efficient idiom for its thread safety.
+
+        * loader/CrossOriginAccessControl.cpp:
+        (WebCore::isOnAccessControlResponseHeaderWhitelist): Deleted.
+        * loader/CrossOriginAccessControl.h: Deleted unused function
+        isOnAccessControlResponseHeaderWhitelist.
+
+        * loader/EmptyClients.cpp: Use leakRef instead of NeverDestroyed<Ref>.
+
+        * loader/appcache/ApplicationCacheStorage.cpp: Removed unneeded include of
+        NeverDestroyed.h.
+        * page/CaptionUserPreferences.cpp: Ditto.
+
+        * page/DebugPageOverlays.cpp:
+        (WebCore::touchEventRegionColors): Changed the return type to const, since
+        the callers do not modify the map. Use const auto, makeNeverDestroyed, and
+        a lambda rather than isEmpty and repeated calls to add.
+
+        * page/MainFrame.cpp: Removed unneeded include of NeverDestroyed.h.
+
+        * page/MemoryRelease.cpp:
+        (WebCore::releaseMemory): Use a function directly instead of calling it
+        inside a lambda.
+
+        * page/NavigatorBase.cpp:
+        (WebCore::NavigatorBase::onLine): Updated to call
+        NetworkStateNotifier::singleton.
+
+        * page/Page.cpp:
+        (WebCore::allPages): Made this a function instead of a global to use the
+        normal idiom for such globals.
+        (WebCore::Page::forEachPage): Updated for change to allPages.
+        (WebCore::networkStateChanged): Ditto. Also removed a bit of unnecessary
+        churn by using const AtomicString& instead of AtomicString.
+        (WebCore::Page::Page): Moved initialization of most data members to the
+        class definition. Removed initialiation of allPages. Updated the use of
+        NetworkStateNotifier for its new slightly changed  interface.
+        (WebCore::Page::~Page): Updated for change to allPages.
+        (WebCore::Page::clearPreviousItemFromAllPages): Ditto.
+        (WebCore::Page::updateStyleForAllPagesAfterGlobalChangeInEnvironment): Ditto.
+        (WebCore::Page::refreshPlugins): Ditto.
+
+        * page/Page.h: Moved initialization of most data members here.
+
+        * page/PerformanceUserTiming.cpp: Removed many unneded includes.
+        (WebCore::restrictedMarkFunction): Use const auto, makeNeverDestroyed, and
+        a lambda instead of isEmpty. Also use an array rather than std::array and
+        got rid fo the unneeded use of anonymous namespace since this is fine in
+        the top level WebCore namespace.
+        (WebCore::clearPerformanceEntries): Tweaked coding style.
+        (WebCore::UserTiming::mark): Ditto.
+        (WebCore::UserTiming::findExistingMarkStartTime): Got rid of double hash
+        table lookup by using find instead of using contains followed by get.
+        removed unneeded explicit cast to double. Tweaked coding style.
+        (WebCore::convertToEntrySequence): Tweaked coding style.
+        (WebCore::getEntrySequenceByName): Deleted.
+        (WebCore::UserTiming::getMarks): Call get directly instead of getEntrySequenceByName.
+        (WebCore::UserTiming::getMeasures): Ditto.
+
+        * page/RuntimeEnabledFeatures.cpp: Moved include of NeverDestroyed.h here ...
+        * page/RuntimeEnabledFeatures.h: ... from here. Added Forward.h and Noncopyable.h.
+
+        * platform/LocalizedStrings.cpp: Removed unneeded include of NeverDestroyed.h.
+
+        * platform/MIMETypeRegistry.cpp:
+        (WebCore::initializeSupportedImageMIMETypes): Added a missing const for a global
+        constant array.
+        (WebCore::initializeSupportedJavaScriptMIMETypes): Ditto.
+        (WebCore::initializeSupportedNonImageMimeTypes): Ditto.
+        (WebCore::typesForCommonExtension): Replaced the old mediaMIMETypeMap function
+        with this one. Moved the common media types array here since it's only used here.
+        Use const auto, makeNeverDestroyed, and a lambda instead of using an isEmpty check.
+        Iterate the array using a mdoern for loop. Use HashMap::ensure to avoid the
+        double hashing that the old code was doing. And moved the code to find an entry
+        in the map in here from the client functions.
+        (WebCore::MIMETypeRegistry::getMediaMIMETypeForExtension): Updated to use the
+        typesForCommonExtension, and changed logic to use this first, and only call
+        getMIMETypeForExtension for extensions not in the map. This gives the same
+        result but should be slightly more efficient.
+        (WebCore::MIMETypeRegistry::getMediaMIMETypesForExtension): Updated to use the
+        typesForCommonExtension function. Comment about strategy is now in there.
+        (WebCore::initializeUnsupportedTextMIMETypes): Added a missing const for a global
+        constant array. Also started using ASCIILiteral.
+
+        * platform/MainThreadSharedTimer.cpp: Moved include of NeverDestroyed.h here ...
+        * platform/MainThreadSharedTimer.h: ... from here. Added Forward.h.
+
+        * platform/SchemeRegistry.cpp:
+        (WebCore::add): Added helper functions to keep code below simpler.
+        (WebCore::makeNeverDestroyedSchemeSet): Ditto.
+        (WebCore::allBuiltinSchemes): Use const auto, makeNeverDestroyed, a lambda,
+        and the helper functions above, rather than isEmpty.
+        (WebCore::builtinLocalURLSchemes): Use const auto, makeNeverDestroyed, and
+        the HashSet constructor instead of isEmpty and add calls. Also changed the
+        return type to be const.
+        (WebCore::localURLSchemes): Copy the map using assignment instead of an
+        isEmpty function and a loop with calls to add.
+        (WebCore::builtinSecureSchemes): Use const auto, makeNeverDestroyed, and
+        the Vector constructor rather than isEmpty, repeated calls to append,
+        and shrinkToFit.
+        (WebCore::secureSchemes): Use auto and makeNeverDestroyedSchemeSet rather
+        than isEmpty and repeated calls to add.
+        (WebCore::builtinSchemesWithUniqueOrigins): More of the same.
+        (WebCore::schemesWithUniqueOrigins): Ditto.
+        (WebCore::builtinEmptyDocumentSchemes): Ditto.
+        (WebCore::emptyDocumentSchemes): Ditto.
+        (WebCore::schemesForbiddenFromDomainRelaxation): Ditto.
+        (WebCore::builtinCanDisplayOnlyIfCanRequestSchemes): Ditto.
+        (WebCore::canDisplayOnlyIfCanRequestSchemes): Ditto.
+        (WebCore::builtinCORSEnabledSchemes): Ditto.
+        (WebCore::CORSEnabledSchemes): Ditto.
+        (WebCore::SchemeRegistry::shouldTreatURLSchemeAsLocal): Replaced check for
+        empty string with check for null string, since that's slightly more efficient
+        for non-null, non-empty strings, and the hash table can handle empty strings
+        just fine.
+        (WebCore::SchemeRegistry::registerURLSchemeAsNoAccess): Added null check here.
+        (WebCore::SchemeRegistry::shouldTreatURLSchemeAsNoAccess): Ditto.
+        (WebCore::SchemeRegistry::registerURLSchemeAsDisplayIsolated): Ditto.
+        (WebCore::SchemeRegistry::shouldTreatURLSchemeAsDisplayIsolated): Ditto.
+        (WebCore::SchemeRegistry::registerURLSchemeAsSecure): Ditto.
+        (WebCore::SchemeRegistry::shouldTreatURLSchemeAsSecure): Ditto.
+        (WebCore::SchemeRegistry::registerURLSchemeAsEmptyDocument): Ditto.
+        (WebCore::SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument): Ditto.
+        (WebCore::SchemeRegistry::setDomainRelaxationForbiddenForURLScheme): Ditto.
+        (WebCore::SchemeRegistry::isDomainRelaxationForbiddenForURLScheme): Ditto.
+        (WebCore::SchemeRegistry::canDisplayOnlyIfCanRequest): Ditto.
+        (WebCore::SchemeRegistry::registerAsCanDisplayOnlyIfCanRequest): Ditto.
+        (WebCore::SchemeRegistry::registerURLSchemeAsNotAllowingJavascriptURLs): Ditto.
+        (WebCore::SchemeRegistry::shouldTreatURLSchemeAsNotAllowingJavascriptURLs): Ditto.
+        (WebCore::SchemeRegistry::registerURLSchemeAsAllowingLocalStorageAccessInPrivateBrowsing): Ditto.
+        (WebCore::SchemeRegistry::allowsLocalStorageAccessInPrivateBrowsing): Ditto.
+        (WebCore::SchemeRegistry::registerURLSchemeAsAllowingDatabaseAccessInPrivateBrowsing): Ditto.
+        (WebCore::SchemeRegistry::allowsDatabaseAccessInPrivateBrowsing): Ditto.
+        (WebCore::SchemeRegistry::registerURLSchemeAsCORSEnabled): Ditto.
+        (WebCore::SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled): Ditto.
+        (WebCore::SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy): Ditto.
+        (WebCore::SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy): Ditto.
+        (WebCore::SchemeRegistry::schemeShouldBypassContentSecurityPolicy): Ditto.
+        (WebCore::SchemeRegistry::registerURLSchemeAsAlwaysRevalidated): Ditto.
+        (WebCore::SchemeRegistry::shouldAlwaysRevalidateURLScheme): Ditto.
+        (WebCore::SchemeRegistry::registerURLSchemeAsCachePartitioned): Ditto.
+        (WebCore::SchemeRegistry::shouldPartitionCacheForURLScheme): Ditto.
+        (WebCore::SchemeRegistry::isUserExtensionScheme): Tweaked #if a bit.
+        (WebCore::SchemeRegistry::isBuiltinScheme): Added null check.
+
+        * platform/cocoa/WebVideoFullscreenModelVideoElement.mm:
+        (WebVideoFullscreenModelVideoElement::observedEventNames): Use const auto,
+        makeNeverDestroyed, and the Vector constructor rather than a call to size
+        and then append eacn time this funciton is called.
+
+        * platform/gamepad/cocoa/GameControllerGamepadProvider.h: Moved include of
+        NeverDestroyed.h from here ...
+        * platform/gamepad/cocoa/GameControllerGamepadProvider.mm: ... to here.
+
+        * platform/gamepad/mac/HIDGamepadProvider.cpp: Moved include of
+        NeverDestroyed.h here ...
+        * platform/gamepad/mac/HIDGamepadProvider.h: ... from here.
+
+        * platform/graphics/FontCascade.cpp:
+        (WebCore::FontCascade::hasValidAverageCharWidth): Use const auto,
+        makeNeverDestroyed, and the HashSet constructor.
+
+        * platform/graphics/ImageBuffer.cpp:
+        (WebCore::ImageBuffer::transformColorSpace): Removed unneeded use of
+        NeverDestroyed<Vector<int>> here, instead using const std::array.
+
+        * platform/graphics/ImageBuffer.h: Changed platformTransformColorSpace to take
+        const std::array<uint8_t, 256>& instead of const Vector<int>&, since the whole
+        pointer of the argument is that it's a table to map bytes onto other bytes.
+
+        * platform/graphics/MediaPlaybackTarget.h: Removed unneeded include of
+        NeverDestroyed.h, unneeded unused noMediaPlaybackTargetContext function,
+        and unneeded include of MediaPlaybackTargetContext.h, forward declaring instead.
+        Made most functions in this class pure virtual instead of having default
+        implementations.
+
+        * platform/graphics/avfoundation/MediaPlaybackTargetMac.h: Added include
+        of MediaPlaybackTargetContext.h now that it was removed above.
+
+        * platform/graphics/avfoundation/MediaPlayerPrivateAVFoundation.cpp:
+        (WebCore::MediaPlayerPrivateAVFoundation::staticMIMETypeList): Use const auto,
+        makeNeverDestroyed, and the HashSet constructor.
+
+        * platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.mm:
+        (WebCore::MediaPlayerPrivateMediaStreamAVFObjC::isAvailable): Reversed the sense
+        of the boolean logic here to make this simpler and easier to read.
+        (WebCore::MediaPlayerPrivateMediaStreamAVFObjC::getSupportedTypes): Changed
+        the implementation here, which empties out the passed in hash set, to use
+        the clear function rather than assignment from a global empty hash set. Added
+        a FIXME because it seems peculiar that this would be considered OK.
+        (WebCore::MediaPlayerPrivateMediaStreamAVFObjC::supportsType): Used ? : to make
+        this a little more terse; I think it's clearer.
+
+        * platform/graphics/cairo/ImageBufferCairo.cpp:
+        (WebCore::ImageBuffer::platformTransformColorSpace): Updated for change to
+        argument type.
+
+        * platform/graphics/cg/ImageDecoderCG.cpp: Removed unneeded include of
+        NeverDestroyed.h.
+        (WebCore::appendImageSourceOption): Streamlined code using auto with
+        adoptCF; there is no need to write out the type of the RetainPtr.
+        (WebCore::imageSourceOptions): Instead of NeverDestroyed<RetainPtr>, just use
+        const auto and leakRef.
+        (WebCore::imageSourceAsyncOptions): Ditto.
+
+        * platform/graphics/gtk/GdkCairoUtilities.cpp:
+        (WebCore::getDefaultCairoFontOptions): Instead of using LazyNeverDestroyed
+        on a pointer, just use a global pointer. There is no need to use any kind
+        of NeverDestroyed on a type with a trivial destructor such as a pointer.
+
+        * platform/graphics/ios/FontCacheIOS.mm:
+        (WebCore::platformFontWithFamilySpecialCase): Instead of using
+        NeverDestroyed<RetainPtr> just use a raw pointer global.
+        * platform/graphics/mac/FontCacheMac.mm:
+        (WebCore::platformFontWithFamilySpecialCase): Ditto.
+
+        * platform/graphics/mac/MediaPlayerPrivateQTKit.mm:
+        (WebCore::createFileTypesSet): Return the HashSet instead of adding to it.
+        Use Objective-C for/in syntax for an NSArray, not C++ for syntax, although
+        it seems the C++ syntax was working fine.
+        (WebCore::mimeCommonTypesCache): Fixed return type so we won't copy the
+        HashMap every time this function is called. Use const auto and makeNeverDestroyed
+        instead of using a boolean to do one time initialization.
+        (WebCore::mimeModernTypesCache): Ditto.
+        (WebCore::MediaPlayerPrivateQTKit::disableUnsupportedTracks): Marked a
+        constant array const.
+
+        * platform/ios/Device.cpp:
+        (WebCore::deviceClass): Use a lambda to initialize a variable here instead
+        of using std::call_once. This function does not need to be thread safe.
+        (WebCore::deviceName): Use const NeverDestroyed instead of LazyNeverDestroyed
+        and std::call_once. This function does not need to be thread safe.
+
+        * platform/ios/DragImageIOS.mm: Make defaultLinkIndicatorOptions be a
+        constant instead of a variable.
+        (WebCore::cascadeForSystemFont): Added helper function.
+        (WebCore::createDragImageForLink): Use const auto and makeNeverDestroyed
+        instead of LazyNeverDestroyed and dispatch_once. This code does not need
+        to be thread safe since its arguments include, for example, a DOM element.
+
+        * platform/ios/LegacyTileLayerPool.h: Removed unneeded include of
+        NeverDestroyed.h.
+
+        * platform/ios/QuickLook.mm:
+        (WebCore::QLPreviewGetSupportedMIMETypesSet): Use a global raw pointer
+        instead of NeverDestroyed<RetainPtr<NSSet>>.
+        (WebCore::createQLPreviewProtocol): Deleted.
+        (WebCore::QLPreviewProtocol): Use a global raw pointer instead of
+        a NeverDestroyed<Vector<char>>. It's cleaner to use fastStrdup instead
+        of appending to an array, and less wasteful of memory too.
+
+        * platform/ios/WebCoreMotionManager.mm: Removed unneeded include of
+        NeverDestroyed.h.
+        * platform/ios/WebSQLiteDatabaseTrackerClient.h: Ditto.
+        * platform/mac/DragImageMac.mm: Ditto.
+        * platform/mediastream/CaptureDeviceManager.cpp: Ditto.
+        * platform/mediastream/RealtimeMediaSourceSupportedConstraints.cpp: Ditto.
+
+        * platform/mock/MockRealtimeMediaSource.cpp:
+        (WebCore::MockRealtimeMediaSource::audioDevices): Use auto,
+        makeNeverDestroyed, and a lambda instead of checking size each time.
+        (WebCore::MockRealtimeMediaSource::videoDevices): Ditto.
+
+        * platform/mock/mediasource/MockMediaPlayerMediaSource.cpp:
+        (WebCore::mimeTypeCache): Use const auto, makeNeverDestroyed, and the
+        HashSet constructor instead of an explicit boolean to initialize.
+
+        * platform/network/BlobRegistryImpl.cpp:
+        (WebCore::blobUtilityQueue): Use a global with a raw reference instead
+        of a NeverDestroyed<Ref>.
+
+        * platform/network/NetworkStateNotifier.cpp:
+        (WebCore::NetworkStateNotifier::singleton): Renamed this from
+        networkStateNotifier. We must have missed this when we changed to use the
+        singleton idiom consistently. Also changed to use normal NeverDestroyed
+        rather than using LazyNeverDestroyed and call_once, because this is not
+        used from multiple threads and has no special thread safety requirements.
+        (WebCore::NetworkStateNotifier::NetworkStateNotifier): Moved the constructor
+        here and construct the timer. Before the timer was used only on the Mac
+        platform but now it is there for all platforms.
+        (WebCore::NetworkStateNotifier::onLine): Moved function here from the header.
+        It's a littlel less trivial than before because it now triggers a call to
+        updateState as needed.
+        (WebCore::NetworkStateNotifier::addListener): Renamed from
+        addNetworkStateChangeListener since there is only one kind of listener and
+        the old name was too wordy. Changed to call the new startObserving function,
+        and guaranteed to call it onlh once. The platform-specific logic for iOS is
+        now inside the iOS version of that function instead of here.
+        (WebCore::NetworkStateNotifier::updateState): Moved here now that it is the
+        same for all platforms. The actual state updating is done in a function named
+        updateStateWithoutNotifying, which is implemented for each platform.
+        (WebCore::NetworkStateNotifier::updateStateSoon): New function which takes
+        advantage of the timer to coalesce network state updates.
+        (WebCore::NetworkStateNotifier::updateStateWithoutNotifying): Empty stub
+        version of this function.
+        (WebCore::NetworkStateNotifier::startObserving): Ditto.
+        (WebCore::NetworkStateNotifier::notifyNetworkStateChange): Deleted. Code from
+        this has moved into updateState.
+
+        * platform/network/NetworkStateNotifier.h: Greatly cut down what part of this
+        class is platform-specific.
+
+        * platform/network/ios/NetworkStateNotifierIOS.mm:
+        (-[WebNetworkStateObserver initWithBlock:]): Simplified this class so it
+        takes a block, rather than using a pointer to the C++ notifier and doing
+        WebThreadRun.
+        (-[WebNetworkStateObserver dealloc]): Ditto.
+        (-[WebNetworkStateObserver networkStateChanged:]): Ditto.
+        (WebCore::NetworkStateNotifier::updateStateWithoutNotifying):
+        This now calls isNetworkReachable.
+        (WebCore::NetworkStateNotifier::startObserving): Check the
+        Settings::shouldOptOutOfNetworkStateObservation function, and if it's OK
+        to observe, then create the observer. This code now takes care of the
+        WebThreadRun and calls updateStateSoon.
+        (WebCore::NetworkStateNotifier::NetworkStateNotifier): Deleted. The
+        constructor is now platform independent.
+        (WebCore::NetworkStateNotifier::~NetworkStateNotifier): Deleted. This
+        object is never destroyed so we should not write a destructor for it.
+        (WebCore::NetworkStateNotifier::registerObserverIfNecessary): Deleted.
+        Replaced by startObserving.
+        (WebCore::NetworkStateNotifier::onLine): Deleted. This function is now
+        platform-independent.
+        (WebCore::setOnLine): Deleted. The logic from this is now in
+        updateState and updateStateWithoutNotifying.
+
+        * platform/network/mac/NetworkStateNotifierMac.cpp:
+        (WebCore::NetworkStateNotifier::updateStateWithoutNotifying): Renamed
+        this from updateState and tightened up the code a bit. Also changed
+        to not assume anything. If there is an error, we leave m_isOnLine alone.
+        Default behavior is now in the platform-independent code, and the default
+        is to treat things as on-line if updateStateWithoutNotifying was called
+        and it was never able to update the state even once.
+        (WebCore::NetworkStateNotifier::startObserving): Moved most of the code
+        from the constructor into this function.
+        (WebCore::NetworkStateNotifier::dynamicStoreCallback): Deleted. This is
+        now a lambda inside startObserving.
+        (WebCore::NetworkStateNotifier::networkStateChangeTimerFired): Deleted.
+        This function is now platform-independent and is named updateState.
+
+        * platform/network/win/NetworkStateNotifierWin.cpp:
+        (WebCore::NetworkStateNotifier::updateStateWithoutNotifying): Renamed
+        from updateState and tightened the code up a bit. Also changed
+        to not assume anything. If there is an error, we leave m_isOnLine alone.
+        Default behavior is now in the platform-independent code, and the default
+        is to treat things as on-line if updateStateWithoutNotifying was called
+        and it was never able to update the state even once.
+        (WebCore::NetworkStateNotifier::addressChanged): Deleted.
+        This function is now platform-independent and is named updateState.
+        (WebCore::NetworkStateNotifier::addressChangeCallback): Renamed from
+        addrChangeCallback. Simplified by using the singleton function instead
+        of relying on the context pointer.
+        (WebCore::NetworkStateNotifier::startObserving): Moved most of the code
+        from the constructor here.
+
+        * platform/text/LocaleToScriptMappingDefault.cpp:
+        (WebCore::scriptNameToCode): Use makeNeverDestroyed.
+        (WebCore::localeToScriptCodeForFontSelection): Ditto.
+
+        * platform/text/ios/LocalizedDateCache.h: Moved include of
+        NeverDestroyed.h from here ...
+        * platform/text/ios/LocalizedDateCache.mm: ... to here.
+
+        * platform/wpe/RenderThemeWPE.cpp:
+        (WebCore::RenderTheme::singleton): Use a theme that is never destroyed
+        rather than Ref that is never destroyed.
+
+        * platform/wpe/RenderThemeWPE.h: Use friend NeverDestroyed rather than
+        a create function since RenderTheme is no longer reference counted.
+
+        * rendering/RenderTheme.h: Made RenderTheme no longer reference counted.
+
+        * rendering/RenderThemeGtk.cpp:
+        (WebCore::RenderThemeGtk::create): Deleted.
+        (WebCore::RenderTheme::singleton): Use a theme that is never destroyed
+        rather than Ref that is never destroyed.
+
+        * rendering/RenderThemeGtk.h: Use friend NeverDestroyed rather than
+        a create function since RenderTheme is no longer reference counted.
+        * rendering/RenderThemeIOS.h: Ditto.
+
+        * rendering/RenderThemeIOS.mm:
+        (WebCore::RenderThemeIOS::create): Deleted.
+        (WebCore::RenderTheme::singleton): Use a theme that is never destroyed
+        rather than Ref that is never destroyed.
+
+        * rendering/RenderThemeMac.h: Use friend NeverDestroyed rather than
+        a create function since RenderTheme is no longer reference counted.
+        Also marked a lot of functions final rather than override and initialized
+        data members in the class deifnition.
+
+        * rendering/RenderThemeMac.mm: Moved some SPI interfaces to the top of the
+        file. They should really go into SPI headers.
+        (-[WebCoreRenderThemeNotificationObserver init]): Removed the theme argument
+        here because the theme is a singleton and we don't need a pointer to it.
+        Add the observer here instead of doing it in the caller.
+        (-[WebCoreRenderThemeNotificationObserver systemColorsDidChange:]): Call
+        platformColorsDidChange through the singleton rather than using a pointer.
+        (-[WebCoreTextFieldCell _coreUIDrawOptionsWithFrame:inView:includeFocus:]):
+        Tightened up the code a bit by using CFAutorelease instead of using a
+        combination of NSMakeCollectable, autorelease, and a typecast to accomplish
+        the same thing.
+        (WebCore::RenderTheme::singleton): Use a theme that is never destroyed
+        rather than Ref that is never destroyed.
+        (WebCore::RenderThemeMac::create): Deleted.
+        (WebCore::RenderThemeMac::RenderThemeMac): Moved initialization into the
+        class definition and observing into the WebCoreRenderThemeNotificationObserver
+        init function.
+        (WebCore::RenderThemeMac::~RenderThemeMac): Deleted. No need for this since
+        the object will never be destroyed.
+        (WebCore::RenderThemeMac::mediaControlsBase64StringForIconNameAndType):
+        Removed an unnecessary conversion from C string literal to WTF::String and
+        then to NSString. Instead, just use an NSString literal.
+
+        * rendering/RenderThemeWin.cpp:
+        (WebCore::RenderThemeWin::create): Deleted.
+        (WebCore::RenderTheme::singleton): Use a theme that is never destroyed
+        rather than Ref that is never destroyed.
+
+        * rendering/RenderThemeWin.h: Use friend NeverDestroyed rather than
+        a create function since RenderTheme is no longer reference counted.
+
+        * rendering/svg/RenderSVGResource.cpp:
+        (WebCore::removeFromCacheAndInvalidateDependencies): Moved a global into
+        the code where it is used.
+
+        * svg/SVGAnimatedLength.cpp: Removed unneeded include of NeverDestroyed.h.
+
+        * svg/SVGAnimationElement.cpp:
+        (WebCore::SVGAnimationElement::isSupportedAttribute): Use const auto,
+        makeNeverDestroyed, a lambda, and the new HashSet::add overload instead of
+        an isEmpty check and lots of separate add function calls.
+        * svg/SVGClipPathElement.cpp:
+        (WebCore::SVGClipPathElement::isSupportedAttribute): Ditto.
+        * svg/SVGComponentTransferFunctionElement.cpp:
+        (WebCore::SVGComponentTransferFunctionElement::isSupportedAttribute): Ditto.
+        * svg/SVGCursorElement.cpp:
+        (WebCore::SVGCursorElement::isSupportedAttribute): Ditto.
+
+        * svg/SVGElement.cpp:
+        (WebCore::createAttributeNameToCSSPropertyIDMap): Replaced the populate
+        function with this create function.
+        (WebCore::createAttributeNameToAnimatedPropertyTypeMap): Ditto.
+        (WebCore::attributeNameToAnimatedPropertyTypeMap): Changed return type to
+        const reference. Use const auto and makeNeverDestroyed instead of using
+        isEmpty and a populate function.
+        (WebCore::createCSSPropertyWithSVGDOMNameToAnimatedPropertyTypeMap):
+        More of the same.
+        (WebCore::cssPropertyWithSVGDOMNameToAnimatedPropertyTypeMap): Ditto.
+        (WebCore::SVGElement::childShouldCreateRenderer): Use an array instead of
+        a HashSet since we are checking against only 3 or 4 values.
+        (WebCore::addQualifiedName): Deleted.
+        (WebCore::SVGElement::animatableAttributeForName): Use const auto,
+        makeNeverDestroyed, and a lambda to efficiently build the map in this function.
+        (WebCore::SVGElement::cssPropertyIdForSVGAttributeName): Use const auto and
+        makeNeverDestroyed instead of using isEmpty and a populate function.
+
+        * svg/SVGFilterElement.cpp:
+        (WebCore::SVGFilterElement::isSupportedAttribute): Use const auto,
+        makeNeverDestroyed, a lambda, and the new HashSet::add overload instead of
+        an isEmpty check and lots of separate add function calls.
+        * svg/SVGFilterPrimitiveStandardAttributes.cpp:
+        (WebCore::SVGFilterPrimitiveStandardAttributes::isSupportedAttribute): Ditto.
+        * svg/SVGForeignObjectElement.cpp:
+        (WebCore::SVGForeignObjectElement::isSupportedAttribute): Ditto.
+        * svg/SVGGElement.cpp:
+        (WebCore::SVGGElement::isSupportedAttribute): Ditto.
+        * svg/SVGGradientElement.cpp:
+        (WebCore::SVGGradientElement::isSupportedAttribute): Ditto.
+        * svg/SVGGraphicsElement.cpp:
+        (WebCore::SVGGraphicsElement::isSupportedAttribute): Ditto.
+        * svg/SVGImageElement.cpp:
+        (WebCore::SVGImageElement::isSupportedAttribute): Ditto.
+        * svg/SVGLangSpace.cpp:
+        (WebCore::addWithAndWithoutXMLPrefix): Added helper. Uses xmlAtom instead
+        of making our own NeverDestroyed local xmlPrefix.
+        (WebCore::SVGLangSpace::addSupportedAttributes): Rewrote to use helper.
+        * svg/SVGLineElement.cpp:
+        (WebCore::SVGLineElement::isSupportedAttribute): Use const auto,
+        makeNeverDestroyed, a lambda, and the new HashSet::add overload instead of
+        an isEmpty check and lots of separate add function calls.
+        * svg/SVGLinearGradientElement.cpp:
+        (WebCore::SVGLinearGradientElement::isSupportedAttribute): Ditto.
+        * svg/SVGMarkerElement.cpp:
+        (WebCore::SVGMarkerElement::isSupportedAttribute): Ditto.
+        * svg/SVGMaskElement.cpp:
+        (WebCore::SVGMaskElement::isSupportedAttribute): Ditto.
+        * svg/SVGPathElement.cpp:
+        (WebCore::SVGPathElement::isSupportedAttribute): Ditto.
+        * svg/SVGPatternElement.cpp:
+        (WebCore::SVGPatternElement::isSupportedAttribute): Ditto.
+        * svg/SVGRadialGradientElement.cpp:
+        (WebCore::SVGRadialGradientElement::isSupportedAttribute): Ditto.
+        * svg/SVGTextContentElement.cpp:
+        (WebCore::SVGTextContentElement::isSupportedAttribute): Ditto.
+        * svg/SVGTextPathElement.cpp:
+        (WebCore::SVGTextPathElement::isSupportedAttribute): Ditto.
+        * svg/animation/SVGSMILElement.cpp:
+        (WebCore::SVGSMILElement::isSupportedAttribute): Ditto.
+
+        * testing/MockContentFilterSettings.h: Removed unneeded include of
+        NeverDestroyed.h.
+
+        * testing/MockGamepadProvider.cpp: Moved include of
+        NeverDestroyed.h here ...
+        * testing/MockGamepadProvider.h: ... from here.
+
+        * testing/MockPreviewLoaderClient.h: Removed unneeded include of
+        NeverDestroyed.h.
+
+        * workers/Worker.cpp:
+        (WebCore::allWorkers): Changed this from a global to a function.
+        (WebCore::Worker::networkStateChanged): Updated for above change and
+        made this a member function.
+        (WebCore::Worker::Worker): Updated for above change and
+        change to NetworkStateNotifier.
+        (WebCore::Worker::~Worker): Ditto.
+        * workers/Worker.h: Made networkStateChanged a static member instead of
+        a friend since that is a cleaner way to give it access to private member
+        functions.
+
+        * xml/XPathFunctions.cpp:
+        (WebCore::XPath::createFunctionMap): Use create instead of populate style.
+        (WebCore::XPath::Function::create): Use const auto and makeNeverDestroyed
+        instead of an isEmpty check.
+
+        * xml/XPathParser.cpp:
+        (WebCore::XPath::createAxisNamesMap): Use create instead of populate style.
+        (WebCore::XPath::parseAxisName): Use const auto and makeNeverDestroyed
+        instead of an isEmpty check.
+
 2017-07-17  Brady Eidson  <beidson@apple.com>
 
         REGRESSION(r219298): imported/w3c/IndexedDB-private-browsing/idbfactory_open.html is crashing occassionaly (UniqueIDBDatabase being taken from the IDBServer set twice).
index bd55768b7826f700f4aad3cc6a59fdfb63ad1aa9..c49de50c109cd2cd1d6c2adecfae3a11649ec73c 100644 (file)
@@ -41,7 +41,6 @@
 #include "NotImplemented.h"
 #include "SecurityOrigin.h"
 #include "SharedBuffer.h"
-#include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
index f09b5458b9bad63ad21a9bb441dfb602bd5ba8c1..f557fa61b6a71aea2880dfd8914c6dc4fb7a444d 100644 (file)
@@ -60,24 +60,19 @@ public:
 
 static Vector<CDMFactory*>& installedCDMFactories()
 {
-    static NeverDestroyed<Vector<CDMFactory*>> cdms;
-    static bool queriedCDMs = false;
-    if (!queriedCDMs) {
-        queriedCDMs = true;
-
-        cdms.get().append(new CDMFactory([](CDM* cdm) { return std::make_unique<CDMPrivateClearKey>(cdm); },
-            CDMPrivateClearKey::supportsKeySystem, CDMPrivateClearKey::supportsKeySystemAndMimeType));
+    static auto cdms = makeNeverDestroyed(Vector<CDMFactory*> {
+        new CDMFactory([](CDM* cdm) { return std::make_unique<CDMPrivateClearKey>(cdm); },
+            CDMPrivateClearKey::supportsKeySystem, CDMPrivateClearKey::supportsKeySystemAndMimeType),
 
         // FIXME: initialize specific UA CDMs. http://webkit.org/b/109318, http://webkit.org/b/109320
-        cdms.get().append(new CDMFactory([](CDM* cdm) { return std::make_unique<CDMPrivateMediaPlayer>(cdm); },
-            CDMPrivateMediaPlayer::supportsKeySystem, CDMPrivateMediaPlayer::supportsKeySystemAndMimeType));
+        new CDMFactory([](CDM* cdm) { return std::make_unique<CDMPrivateMediaPlayer>(cdm); },
+            CDMPrivateMediaPlayer::supportsKeySystem, CDMPrivateMediaPlayer::supportsKeySystemAndMimeType),
 
 #if PLATFORM(MAC) && ENABLE(MEDIA_SOURCE)
-        cdms.get().append(new CDMFactory([](CDM* cdm) { return std::make_unique<CDMPrivateMediaSourceAVFObjC>(cdm); },
-            CDMPrivateMediaSourceAVFObjC::supportsKeySystem, CDMPrivateMediaSourceAVFObjC::supportsKeySystemAndMimeType));
+        new CDMFactory([](CDM* cdm) { return std::make_unique<CDMPrivateMediaSourceAVFObjC>(cdm); },
+            CDMPrivateMediaSourceAVFObjC::supportsKeySystem, CDMPrivateMediaSourceAVFObjC::supportsKeySystemAndMimeType),
 #endif
-    }
-
+    });
     return cdms;
 }
 
@@ -92,7 +87,7 @@ static CDMFactory* CDMFactoryForKeySystem(const String& keySystem)
         if (factory->supportsKeySystem(keySystem))
             return factory;
     }
-    return 0;
+    return nullptr;
 }
 
 bool CDM::supportsKeySystem(const String& keySystem)
index 8eacfd5649febc9dc745e252ca0d305d28fb933e..fd910e09c0d8cf91ebb914d6f1a12d85b5f0b423 100644 (file)
@@ -34,7 +34,6 @@
 #include <runtime/JSLock.h>
 #include <runtime/JSONObject.h>
 #include <runtime/VM.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/UUID.h>
 #include <wtf/text/Base64.h>
 
@@ -46,11 +45,8 @@ namespace WebCore {
 
 static VM& clearKeyVM()
 {
-    static NeverDestroyed<RefPtr<VM>> vm;
-    if (!vm.get())
-        vm.get() = VM::create();
-
-    return *vm.get();
+    static VM& vm = VM::create().leakRef();
+    return vm;
 }
 
 CDMSessionClearKey::CDMSessionClearKey(CDMSessionClient* client)
index b2ecba19621fc8b14158ca2935a202e09c2668bc..b21a0d57d6ddba75ac0e5e512b1f798c388cd137 100644 (file)
@@ -22,6 +22,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 #include "config.h"
 #include "GamepadManager.h"
 
@@ -36,6 +37,7 @@
 #include "Logging.h"
 #include "NavigatorGamepad.h"
 #include "PlatformGamepad.h"
+#include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
index 4a5094cdf62d9b9832161a4143aac45cc28ad615..8b6488a515fa9a1246dbb3ade7cb5b6a7262c75c 100644 (file)
@@ -55,7 +55,6 @@
 #include "ScriptState.h"
 #include "SerializedScriptValue.h"
 #include "TransactionOperation.h"
-#include <wtf/NeverDestroyed.h>
 
 using namespace JSC;
 
index 05660e264f1efa82746af9f5ae9470aaade67f06..1ebd588a83dd9585ceeac17c6a787bcc8d2c973d 100644 (file)
@@ -41,7 +41,6 @@
 #include <runtime/JSCJSValue.h>
 #include <runtime/JSCJSValueInlines.h>
 #include <runtime/JSLock.h>
-#include <wtf/NeverDestroyed.h>
 
 using namespace JSC;
 
index dd901a2ec049b9cd485f5143435aca80515f05b4..c55be460b0bb2f7bcc2779c8cbfd65132f327345 100644 (file)
@@ -30,6 +30,7 @@
 
 #include "MediaSession.h"
 #include "MediaSessionInterruptionProviderMac.h"
+#include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
index 4cde38abc1234d98ae87bde35f7c0a00a411230c..6abc2f6a425df3846b99e80473e7add7f0a90602 100644 (file)
@@ -29,7 +29,6 @@
 
 #include "MediaSessionInterruptionProvider.h"
 #include <wtf/HashSet.h>
-#include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
index b6974c2cab4a49b7bdf23cfc6ee8dfa99e5005d3..8d9f1a2d7620eaee889424dd1177b618c958f7ea 100644 (file)
@@ -36,6 +36,7 @@
 #include "MediaSource.h"
 #include "URL.h"
 #include <wtf/MainThread.h>
+#include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
index eb87b40dc395cdff536239152c965c1c3751b693..2b894e0ca43be41b5b10f4d19891343487928306 100644 (file)
@@ -34,7 +34,6 @@
 
 #include "URLRegistry.h"
 #include <wtf/HashMap.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/text/StringHash.h>
 
 namespace WebCore {
index b563d7716ef287685bb7c73626be3f6c1bc5ae7a..77addd3ce1cbd31da60fcdae399b87d63e7b9aeb 100644 (file)
@@ -58,7 +58,6 @@
 #include <runtime/JSLock.h>
 #include <runtime/VM.h>
 #include <wtf/CurrentTime.h>
-#include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
index d574aa0d32ff3b14151e73cc32ba8c110fb1bcec..e38c723cec42cf397adbd0ec6eb3495ad14aaa89 100644 (file)
@@ -64,7 +64,7 @@ private:
     RefPtr<HTMLVideoElement> m_mediaElement;
     const Vector<String> m_names;
     const Vector<String> m_values;
-    JSC::JSObject* m_scriptObject; // FIXME: Why is it safe to have this pointer here? What keeps it alive during GC?
+    JSC::JSObject* m_scriptObject { nullptr }; // FIXME: Why is it safe to have this pointer here? What keeps it alive during GC?
 };
 
 }
index 32267b5f6079c700260c02a3945455fb1889a651..862cfb25efbb06eacc8f91bcbc58ef10c5f47a88 100644 (file)
@@ -88,35 +88,23 @@ Ref<PluginReplacement> QuickTimePluginReplacement::create(HTMLPlugInElement& plu
 
 bool QuickTimePluginReplacement::supportsMimeType(const String& mimeType)
 {
-    static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> typeHash = []() {
-        static const char* const types[] = {
-            "application/vnd.apple.mpegurl", "application/x-mpegurl", "audio/3gpp", "audio/3gpp2", "audio/aac", "audio/aiff",
-            "audio/amr", "audio/basic", "audio/mp3", "audio/mp4", "audio/mpeg", "audio/mpeg3", "audio/mpegurl", "audio/scpls",
-            "audio/wav", "audio/x-aac", "audio/x-aiff", "audio/x-caf", "audio/x-m4a", "audio/x-m4b", "audio/x-m4p",
-            "audio/x-m4r", "audio/x-mp3", "audio/x-mpeg", "audio/x-mpeg3", "audio/x-mpegurl", "audio/x-scpls", "audio/x-wav",
-            "video/3gpp", "video/3gpp2", "video/mp4", "video/quicktime", "video/x-m4v"
-        };
-        HashSet<String, ASCIICaseInsensitiveHash> set;
-        for (auto& type : types)
-            set.add(type);
-        return set;
-    }();
+    static const auto typeHash = makeNeverDestroyed(HashSet<String, ASCIICaseInsensitiveHash> {
+        "application/vnd.apple.mpegurl", "application/x-mpegurl", "audio/3gpp", "audio/3gpp2", "audio/aac", "audio/aiff",
+        "audio/amr", "audio/basic", "audio/mp3", "audio/mp4", "audio/mpeg", "audio/mpeg3", "audio/mpegurl", "audio/scpls",
+        "audio/wav", "audio/x-aac", "audio/x-aiff", "audio/x-caf", "audio/x-m4a", "audio/x-m4b", "audio/x-m4p",
+        "audio/x-m4r", "audio/x-mp3", "audio/x-mpeg", "audio/x-mpeg3", "audio/x-mpegurl", "audio/x-scpls", "audio/x-wav",
+        "video/3gpp", "video/3gpp2", "video/mp4", "video/quicktime", "video/x-m4v"
+    });
     return typeHash.get().contains(mimeType);
 }
 
 bool QuickTimePluginReplacement::supportsFileExtension(const String& extension)
 {
-    static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> extensionSet = []() {
-        static const char* const extensions[] = {
-            "3g2", "3gp", "3gp2", "3gpp", "aac", "adts", "aif", "aifc", "aiff", "AMR", "au", "bwf", "caf", "cdda", "m3u",
-            "m3u8", "m4a", "m4b", "m4p", "m4r", "m4v", "mov", "mp3", "mp3", "mp4", "mpeg", "mpg", "mqv", "pls", "qt",
-            "snd", "swa", "ts", "ulw", "wav"
-        };
-        HashSet<String, ASCIICaseInsensitiveHash> set;
-        for (auto& extension : extensions)
-            set.add(extension);
-        return set;
-    }();
+    static const auto extensionSet = makeNeverDestroyed(HashSet<String, ASCIICaseInsensitiveHash> {
+        "3g2", "3gp", "3gp2", "3gpp", "aac", "adts", "aif", "aifc", "aiff", "AMR", "au", "bwf", "caf", "cdda", "m3u",
+        "m3u8", "m4a", "m4b", "m4p", "m4r", "m4v", "mov", "mp3", "mp3", "mp4", "mpeg", "mpg", "mqv", "pls", "qt",
+        "snd", "swa", "ts", "ulw", "wav"
+    });
     return extensionSet.get().contains(extension);
 }
 
@@ -126,16 +114,15 @@ bool QuickTimePluginReplacement::isEnabledBySettings(const Settings& settings)
 }
 
 QuickTimePluginReplacement::QuickTimePluginReplacement(HTMLPlugInElement& plugin, const Vector<String>& paramNames, const Vector<String>& paramValues)
-    :PluginReplacement()
-    , m_parentElement(&plugin)
+    : m_parentElement(&plugin)
     , m_names(paramNames)
     , m_values(paramValues)
-    , m_scriptObject(nullptr)
 {
 }
 
 QuickTimePluginReplacement::~QuickTimePluginReplacement()
 {
+    // FIXME: Why is it useful to null out pointers in an object that is being destroyed?
     m_parentElement = nullptr;
     m_scriptObject = nullptr;
     m_mediaElement = nullptr;
index 6e83cfa31eda6711705e8ea6920c712d50c5632f..e4155d18d51dd00de7f8a40cebeef323609de6b8 100644 (file)
@@ -2858,7 +2858,7 @@ AccessibilityOrientation AccessibilityRenderObject::orientation() const
     
     return AccessibilityObject::orientation();
 }
-    
+
 bool AccessibilityRenderObject::inheritsPresentationalRole() const
 {
     // ARIA states if an item can get focus, it should not be presentational.
@@ -2868,48 +2868,41 @@ bool AccessibilityRenderObject::inheritsPresentationalRole() const
     // ARIA spec says that when a parent object is presentational, and it has required child elements,
     // those child elements are also presentational. For example, <li> becomes presentational from <ul>.
     // http://www.w3.org/WAI/PF/aria/complete#presentation
-    static NeverDestroyed<HashSet<QualifiedName>> listItemParents;
-    static NeverDestroyed<HashSet<QualifiedName>> tableCellParents;
 
-    HashSet<QualifiedName>* possibleParentTagNames = nullptr;
+    const Vector<const HTMLQualifiedName*>* parentTags;
     switch (roleValue()) {
     case ListItemRole:
-    case ListMarkerRole:
-        if (listItemParents.get().isEmpty()) {
-            listItemParents.get().add(ulTag);
-            listItemParents.get().add(olTag);
-            listItemParents.get().add(dlTag);
-        }
-        possibleParentTagNames = &listItemParents.get();
+    case ListMarkerRole: {
+        static const auto listItemParents = makeNeverDestroyed(Vector<const HTMLQualifiedName*> { &dlTag, &olTag, &ulTag });
+        parentTags = &listItemParents.get();
         break;
+    }
     case GridCellRole:
-    case CellRole:
-        if (tableCellParents.get().isEmpty())
-            tableCellParents.get().add(tableTag);
-        possibleParentTagNames = &tableCellParents.get();
-        break;
-    default:
+    case CellRole: {
+        static const auto tableCellParents = makeNeverDestroyed(Vector<const HTMLQualifiedName*> { &tableTag });
+        parentTags = &tableCellParents.get();
         break;
     }
-    
-    // Not all elements need to check for this, only ones that are required children.
-    if (!possibleParentTagNames)
+    default:
+        // Not all elements need to do the following check, only ones that are required children.
         return false;
-    
-    for (AccessibilityObject* parent = parentObject(); parent; parent = parent->parentObject()) { 
+    }
+
+    for (auto* parent = parentObject(); parent; parent = parent->parentObject()) {
         if (!is<AccessibilityRenderObject>(*parent))
             continue;
-        
+
         Node* node = downcast<AccessibilityRenderObject>(*parent).node();
         if (!is<Element>(node))
             continue;
-        
+
         // If native tag of the parent element matches an acceptable name, then return
         // based on its presentational status.
-        if (possibleParentTagNames->contains(downcast<Element>(node)->tagQName()))
+        auto& name = downcast<Element>(*node).tagQName();
+        if (std::any_of(parentTags->begin(), parentTags->end(), [&name] (auto* possibleName) { return *possibleName == name; }))
             return parent->roleValue() == PresentationalRole;
     }
-    
+
     return false;
 }
     
index 9503b84e17f74eb67a1f2891d56a604016744831..0fd49bf0e7b6f2af867c4125849ad41fd532af0c 100644 (file)
@@ -54,7 +54,7 @@ my $numCachedAttributes = 0;
 my $beginAppleCopyrightForHeaderFiles = <<END;
 // ------- Begin Apple Copyright -------
 /*
- * Copyright (C) 2008, Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
  *
  * Permission is granted by Apple to use this file to the extent
  * necessary to relink with LGPL WebKit files.
@@ -72,7 +72,7 @@ END
 my $beginAppleCopyrightForSourceFiles = <<END;
 // ------- Begin Apple Copyright -------
 /*
- * Copyright (C) 2008, Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
  *
  * No license or rights are granted by Apple expressly or by implication,
  * estoppel, or otherwise, to Apple copyrights, patents, trademarks, trade
@@ -2021,10 +2021,8 @@ sub GenerateEnumerationImplementationContent
     # FIXME: Change to take VM& instead of ExecState*.
     $result .= "template<> JSString* convertEnumerationToJS(ExecState& state, $className enumerationValue)\n";
     $result .= "{\n";
-    # FIXME: Might be nice to make this global be "const", but NeverDestroyed does not currently support that.
-    # FIXME: Might be nice to make the entire array be NeverDestroyed instead of each value, but not sure what the syntax for that is.
     AddToImplIncludes("<wtf/NeverDestroyed.h>");
-    $result .= "    static NeverDestroyed<const String> values[] = {\n";
+    $result .= "    static const NeverDestroyed<String> values[] = {\n";
     foreach my $value (@{$enumeration->values}) {
         if ($value eq "") {
             $result .= "        emptyString(),\n";
index 06c0e6fbc0371866a917c1f34fb4d4cda4fc9fbc..9359d819d492cf59fdd147394837e89fb504a284 100644 (file)
@@ -49,7 +49,7 @@ namespace WebCore {
 
 template<> JSString* convertEnumerationToJS(ExecState& state, TestCallbackInterface::Enum enumerationValue)
 {
-    static NeverDestroyed<const String> values[] = {
+    static const NeverDestroyed<String> values[] = {
         MAKE_STATIC_STRING_IMPL("value1"),
         MAKE_STATIC_STRING_IMPL("value2"),
     };
index 41260c960836fd47fd17fce1fc1e200aca65aa40..cf069900f16a5c36d3003060c51bac53920a8d45 100644 (file)
@@ -113,7 +113,7 @@ namespace WebCore {
 
 template<> JSString* convertEnumerationToJS(ExecState& state, TestObj::EnumType enumerationValue)
 {
-    static NeverDestroyed<const String> values[] = {
+    static const NeverDestroyed<String> values[] = {
         emptyString(),
         MAKE_STATIC_STRING_IMPL("enumValue1"),
         MAKE_STATIC_STRING_IMPL("EnumValue2"),
@@ -148,7 +148,7 @@ template<> const char* expectedEnumerationValues<TestObj::EnumType>()
 
 template<> JSString* convertEnumerationToJS(ExecState& state, TestObj::Optional enumerationValue)
 {
-    static NeverDestroyed<const String> values[] = {
+    static const NeverDestroyed<String> values[] = {
         emptyString(),
         MAKE_STATIC_STRING_IMPL("OptionalValue1"),
         MAKE_STATIC_STRING_IMPL("OptionalValue2"),
@@ -183,7 +183,7 @@ template<> const char* expectedEnumerationValues<TestObj::Optional>()
 
 template<> JSString* convertEnumerationToJS(ExecState& state, AlternateEnumName enumerationValue)
 {
-    static NeverDestroyed<const String> values[] = {
+    static const NeverDestroyed<String> values[] = {
         MAKE_STATIC_STRING_IMPL("enumValue1"),
         MAKE_STATIC_STRING_IMPL("EnumValue2"),
     };
@@ -212,7 +212,7 @@ template<> const char* expectedEnumerationValues<AlternateEnumName>()
 
 template<> JSString* convertEnumerationToJS(ExecState& state, TestObj::EnumA enumerationValue)
 {
-    static NeverDestroyed<const String> values[] = {
+    static const NeverDestroyed<String> values[] = {
         MAKE_STATIC_STRING_IMPL("A"),
     };
     static_assert(static_cast<size_t>(TestObj::EnumA::A) == 0, "TestObj::EnumA::A is not 0 as expected");
@@ -239,7 +239,7 @@ template<> const char* expectedEnumerationValues<TestObj::EnumA>()
 
 template<> JSString* convertEnumerationToJS(ExecState& state, TestObj::EnumB enumerationValue)
 {
-    static NeverDestroyed<const String> values[] = {
+    static const NeverDestroyed<String> values[] = {
         MAKE_STATIC_STRING_IMPL("B"),
     };
     static_assert(static_cast<size_t>(TestObj::EnumB::B) == 0, "TestObj::EnumB::B is not 0 as expected");
@@ -266,7 +266,7 @@ template<> const char* expectedEnumerationValues<TestObj::EnumB>()
 
 template<> JSString* convertEnumerationToJS(ExecState& state, TestObj::EnumC enumerationValue)
 {
-    static NeverDestroyed<const String> values[] = {
+    static const NeverDestroyed<String> values[] = {
         MAKE_STATIC_STRING_IMPL("C"),
     };
     static_assert(static_cast<size_t>(TestObj::EnumC::C) == 0, "TestObj::EnumC::C is not 0 as expected");
@@ -291,7 +291,7 @@ template<> const char* expectedEnumerationValues<TestObj::EnumC>()
 
 template<> JSString* convertEnumerationToJS(ExecState& state, TestObj::Kind enumerationValue)
 {
-    static NeverDestroyed<const String> values[] = {
+    static const NeverDestroyed<String> values[] = {
         MAKE_STATIC_STRING_IMPL("quick"),
         MAKE_STATIC_STRING_IMPL("dead"),
     };
@@ -318,7 +318,7 @@ template<> const char* expectedEnumerationValues<TestObj::Kind>()
 
 template<> JSString* convertEnumerationToJS(ExecState& state, TestObj::Size enumerationValue)
 {
-    static NeverDestroyed<const String> values[] = {
+    static const NeverDestroyed<String> values[] = {
         MAKE_STATIC_STRING_IMPL("small"),
         MAKE_STATIC_STRING_IMPL("much-much-larger"),
     };
@@ -345,7 +345,7 @@ template<> const char* expectedEnumerationValues<TestObj::Size>()
 
 template<> JSString* convertEnumerationToJS(ExecState& state, TestObj::Confidence enumerationValue)
 {
-    static NeverDestroyed<const String> values[] = {
+    static const NeverDestroyed<String> values[] = {
         MAKE_STATIC_STRING_IMPL("high"),
         MAKE_STATIC_STRING_IMPL("kinda-low"),
     };
index 7c816de08d82abd4f4a7922b9f878c481869393b..9684439f1d6aeb85ea8833308cfed1776b6a76db 100644 (file)
@@ -69,7 +69,7 @@ template<> DictionaryImplName convertDictionary<DictionaryImplName>(ExecState& s
 
 template<> JSString* convertEnumerationToJS(ExecState& state, TestStandaloneDictionary::EnumInStandaloneDictionaryFile enumerationValue)
 {
-    static NeverDestroyed<const String> values[] = {
+    static const NeverDestroyed<String> values[] = {
         MAKE_STATIC_STRING_IMPL("enumValue1"),
         MAKE_STATIC_STRING_IMPL("enumValue2"),
     };
index a21133321bf2157032972435376627def6ce3ae5..110729312b3dc7d93ab127660c95f1984543da91 100644 (file)
@@ -34,7 +34,7 @@ namespace WebCore {
 
 template<> JSString* convertEnumerationToJS(ExecState& state, TestStandaloneEnumeration enumerationValue)
 {
-    static NeverDestroyed<const String> values[] = {
+    static const NeverDestroyed<String> values[] = {
         MAKE_STATIC_STRING_IMPL("enumValue1"),
         MAKE_STATIC_STRING_IMPL("enumValue2"),
     };
index f62183156b26bb3550445cec349b4e410e75ef31..8a91a391514eb5423c76d0048f20f4a5ce489634 100644 (file)
@@ -69,7 +69,7 @@ static CSSPropertyID resolveToPhysicalProperty(WritingMode writingMode, LogicalE
 static const StylePropertyShorthand& borderDirections()
 {
     static const CSSPropertyID properties[4] = { CSSPropertyBorderTop, CSSPropertyBorderRight, CSSPropertyBorderBottom, CSSPropertyBorderLeft };
-    static NeverDestroyed<StylePropertyShorthand> borderDirections(CSSPropertyBorder, properties);
+    static const StylePropertyShorthand borderDirections(CSSPropertyBorder, properties);
     return borderDirections;
 }
 
index 425297dadc2704242d9a16b9483d6b9c0457ee38..d5ba46a77eb955fad4c017126309fd8fcccab248 100644 (file)
@@ -49,18 +49,22 @@ namespace WebCore {
 
 static const StyleProperties& leftToRightDeclaration()
 {
-    static NeverDestroyed<Ref<MutableStyleProperties>> leftToRightDecl(MutableStyleProperties::create());
-    if (leftToRightDecl.get()->isEmpty())
-        leftToRightDecl.get()->setProperty(CSSPropertyDirection, CSSValueLtr);
-    return leftToRightDecl.get();
+    static auto& declaration = [] () -> const StyleProperties& {
+        auto properties = MutableStyleProperties::create();
+        properties->setProperty(CSSPropertyDirection, CSSValueLtr);
+        return properties.leakRef();
+    }();
+    return declaration;
 }
 
 static const StyleProperties& rightToLeftDeclaration()
 {
-    static NeverDestroyed<Ref<MutableStyleProperties>> rightToLeftDecl(MutableStyleProperties::create());
-    if (rightToLeftDecl.get()->isEmpty())
-        rightToLeftDecl.get()->setProperty(CSSPropertyDirection, CSSValueRtl);
-    return rightToLeftDecl.get();
+    static auto& declaration = [] () -> const StyleProperties& {
+        auto properties = MutableStyleProperties::create();
+        properties->setProperty(CSSPropertyDirection, CSSValueRtl);
+        return properties.leakRef();
+    }();
+    return declaration;
 }
 
 class MatchRequest {
index 7b3c4f9942d3f3507aba208b7ab34b1016b78670..f66e179b8a844a4b99e80e760dfa62411f54236d 100755 (executable)
@@ -3,7 +3,7 @@
 #   This file is part of the WebKit project
 #
 #   Copyright (C) 1999 Waldo Bastian (bastian@kde.org)
-#   Copyright (C) 2007-2016 Apple Inc. All rights reserved.
+#   Copyright (C) 2007-2017 Apple Inc. All rights reserved.
 #   Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
 #   Copyright (C) 2010 Andras Becsi (abecsi@inf.u-szeged.hu), University of Szeged
 #   Copyright (C) 2013 Google Inc. All rights reserved.
@@ -1046,9 +1046,9 @@ EOF
 close STYLEBUILDER;
 
 # Generate StylePropertyShorthandsFunctions.
-open SHORTHANDS_H, ">StylePropertyShorthandFunctions.h" || die "Could not open StylePropertyShorthandFunctions.h for writing";
+open SHORTHANDS_H, ">", "StylePropertyShorthandFunctions.h" or die "Could not open StylePropertyShorthandFunctions.h for writing\n";
 print SHORTHANDS_H << "EOF";
-/* This file is automatically generated from $inputFile by makeprop, do not edit */
+// This file is automatically generated from $inputFile by the makeprop.pl script. Do not edit it.
 
 #pragma once
 
@@ -1072,15 +1072,14 @@ EOF
 
 close SHORTHANDS_H;
 
-open SHORTHANDS_CPP, ">StylePropertyShorthandFunctions.cpp" || die "Could not open StylePropertyShorthandFunctions.cpp for writing";
+open SHORTHANDS_CPP, ">", "StylePropertyShorthandFunctions.cpp" or die "Could not open StylePropertyShorthandFunctions.cpp for writing\n";
 print SHORTHANDS_CPP << "EOF";
-/* This file is automatically generated from $inputFile by makeprop, do not edit */
+// This file is automatically generated from $inputFile by the makeprop.pl script. Do not edit it.
 
 #include "config.h"
 #include "StylePropertyShorthandFunctions.h"
 
 #include "StylePropertyShorthand.h"
-#include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
@@ -1121,8 +1120,6 @@ foreach my $name (@names) {
 print SHORTHANDS_CPP << "EOF";
 StylePropertyShorthand shorthandForProperty(CSSPropertyID propertyID)
 {
-    static NeverDestroyed<StylePropertyShorthand> emptyShorthand;
-
     switch (propertyID) {
 EOF
 
@@ -1136,7 +1133,7 @@ foreach my $name (@names) {
 
 print SHORTHANDS_CPP << "EOF";
     default:
-        return emptyShorthand;
+        return { };
     }
 }
 EOF
index eb4646ba08507f8e6c37c7d87806f8ad42c5e332..84962066eb13cc4efd681462c58266fa5fa1bb26 100644 (file)
@@ -35,6 +35,7 @@
 #include "JSDOMBinding.h"
 #include "Microtasks.h"
 #include <heap/Heap.h>
+#include <wtf/NeverDestroyed.h>
 #include <wtf/Optional.h>
 #include <wtf/Ref.h>
 #include <wtf/SetForScope.h>
index 9f32aa01575e0e3a53f05afef8198e5ee81e884c..76dd36eb40e16d049fde23895c76d6b75a124904 100644 (file)
@@ -56,7 +56,6 @@
 #include "Text.h"
 #include "TextDocument.h"
 #include "XMLDocument.h"
-#include <wtf/NeverDestroyed.h>
 #include <wtf/StdLibExtras.h>
 
 namespace WebCore {
index 722778d049ad328c0a701005e12e42a9934a4e57..d449294fec6bc7970d6c42c4b97ab161c4f5b1f0 100644 (file)
@@ -29,7 +29,6 @@
 #include "DOMWindow.h"
 #include "DataTransfer.h"
 #include "Node.h"
-#include <wtf/NeverDestroyed.h>
 #include <wtf/Vector.h>
 
 namespace WebCore {
index 38e4fe6a35d76d8fcfaa0539b61e1a39a8aea43b..b87da165011ff3c17792365792c33617e118f3bf 100644 (file)
@@ -23,6 +23,7 @@
 #include "Microtasks.h"
 
 #include <wtf/MainThread.h>
+#include <wtf/NeverDestroyed.h>
 #include <wtf/SetForScope.h>
 
 namespace WebCore {
index c6a08386823917d0679042dd98b4ede8a18112a5..51ed51f3d8214d6487d3c6bdf047b758e8144fb6 100644 (file)
@@ -22,7 +22,7 @@
 #pragma once
 
 #include "Timer.h"
-#include <wtf/NeverDestroyed.h>
+#include <wtf/Forward.h>
 #include <wtf/Vector.h>
 
 namespace WebCore {
index 0b4b1f90d68291d8a4f9206b80a9c69df1c80921..44ae85deb3e7b6b06148b38adb47ceb897036e5d 100644 (file)
@@ -41,6 +41,7 @@
 #include "MutationRecord.h"
 #include <algorithm>
 #include <wtf/MainThread.h>
+#include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
index 8fb659f8e85c1e0dc900d486364c63fa9302c4bb..0feead6a18258ba118b643318d14eefe3c5916ab 100644 (file)
@@ -34,6 +34,7 @@
 #include "Event.h"
 #include "EventDispatcher.h"
 #include "EventTarget.h"
+#include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
index 311326e642c664e62d6d51729eaec25b8ab6d6e0..3ab89928e2d4598443033161aa35dd80cb17cfbb 100644 (file)
@@ -30,7 +30,7 @@
 
 #pragma once
 
-#include <wtf/NeverDestroyed.h>
+#include <wtf/Forward.h>
 #include <wtf/Noncopyable.h>
 #include <wtf/Ref.h>
 #include <wtf/Vector.h>
index aef8ef6f68b17876fd2fa5d162c77399ec898da6..824f7aa8db647a0b52117bbbba281e706df48f87 100644 (file)
@@ -104,34 +104,22 @@ void ScriptElement::handleAsyncAttribute()
     m_forceAsync = false;
 }
 
-// Helper function
 static bool isLegacySupportedJavaScriptLanguage(const String& language)
 {
-    // Mozilla 1.8 accepts javascript1.0 - javascript1.7, but WinIE 7 accepts only javascript1.1 - javascript1.3.
-    // Mozilla 1.8 and WinIE 7 both accept javascript and livescript.
-    // WinIE 7 accepts ecmascript and jscript, but Mozilla 1.8 doesn't.
-    // Neither Mozilla 1.8 nor WinIE 7 accept leading or trailing whitespace.
-    // We want to accept all the values that either of these browsers accept, but not other values.
-
-    // FIXME: This function is not HTML5 compliant. These belong in the MIME registry as "text/javascript<version>" entries.
-    typedef HashSet<String, ASCIICaseInsensitiveHash> LanguageSet;
-    static NeverDestroyed<LanguageSet> languages;
-    if (languages.get().isEmpty()) {
-        languages.get().add("javascript");
-        languages.get().add("javascript");
-        languages.get().add("javascript1.0");
-        languages.get().add("javascript1.1");
-        languages.get().add("javascript1.2");
-        languages.get().add("javascript1.3");
-        languages.get().add("javascript1.4");
-        languages.get().add("javascript1.5");
-        languages.get().add("javascript1.6");
-        languages.get().add("javascript1.7");
-        languages.get().add("livescript");
-        languages.get().add("ecmascript");
-        languages.get().add("jscript");
-    }
-
+    static const auto languages = makeNeverDestroyed(HashSet<String, ASCIICaseInsensitiveHash> {
+        "javascript",
+        "javascript1.0",
+        "javascript1.1",
+        "javascript1.2",
+        "javascript1.3",
+        "javascript1.4",
+        "javascript1.5",
+        "javascript1.6",
+        "javascript1.7",
+        "livescript",
+        "ecmascript",
+        "jscript",
+    });
     return languages.get().contains(language);
 }
 
index 1bef22ae74f6709eedfc6ef67d021779d01290c9..ac6125bd2c89123f0d650e6018b22b084c613053 100644 (file)
@@ -31,7 +31,6 @@
 #include "HTMLParserIdioms.h"
 #include "SecurityOrigin.h"
 #include "SecurityOriginPolicy.h"
-#include <wtf/NeverDestroyed.h>
 #include <wtf/text/StringBuilder.h>
 
 namespace WebCore {
index 82bcc5ed3321d50cf05ac4e546740144d465c0ac..f1f3cf77443f7cda7ffd34ff7099ac8213b4b278 100755 (executable)
@@ -1008,7 +1008,7 @@ struct ConstructorFunctionMapEntry {
     const QualifiedName* qualifiedName; // Use pointer instead of reference so that emptyValue() in HashMap is cheap to create.
 };
 
-static NEVER_INLINE void populate$parameters{namespace}FactoryMap(HashMap<AtomicStringImpl*, ConstructorFunctionMapEntry>& map)
+static NEVER_INLINE HashMap<AtomicStringImpl*, ConstructorFunctionMapEntry> create$parameters{namespace}FactoryMap()
 {
     struct TableEntry {
         const QualifiedName& name;
@@ -1024,15 +1024,15 @@ END
     print F <<END
     };
 
+    HashMap<AtomicStringImpl*, ConstructorFunctionMapEntry> map;
     for (auto& entry : table)
         map.add(entry.name.localName().impl(), ConstructorFunctionMapEntry(entry.function, entry.name));
+    return map;
 }
 
 static ConstructorFunctionMapEntry find$parameters{namespace}ElementConstructorFunction(const AtomicString& localName)
 {
-    static NeverDestroyed<HashMap<AtomicStringImpl*, ConstructorFunctionMapEntry>> map;
-    if (map.get().isEmpty())
-        populate$parameters{namespace}FactoryMap(map);
+    static const auto map = makeNeverDestroyed(create$parameters{namespace}FactoryMap());
     return map.get().get(localName.impl());
 }
 
@@ -1267,7 +1267,7 @@ END
 
 print F <<END
 
-static NEVER_INLINE void populate$parameters{namespace}WrapperMap(HashMap<AtomicStringImpl*, Create$parameters{namespace}ElementWrapperFunction>& map)
+static NEVER_INLINE HashMap<AtomicStringImpl*, Create$parameters{namespace}ElementWrapperFunction> create$parameters{namespace}WrapperMap()
 {
     struct TableEntry {
         const QualifiedName& name;
@@ -1305,15 +1305,15 @@ END
     print F <<END
     };
 
+    HashMap<AtomicStringImpl*, Create$parameters{namespace}ElementWrapperFunction> map;
     for (auto& entry : table)
         map.add(entry.name.localName().impl(), entry.function);
+    return map;
 }
 
 JSDOMObject* createJS$parameters{namespace}Wrapper(JSDOMGlobalObject* globalObject, Ref<$parameters{namespace}Element>&& element)
 {
-    static NeverDestroyed<HashMap<AtomicStringImpl*, Create$parameters{namespace}ElementWrapperFunction>> functions;
-    if (functions.get().isEmpty())
-        populate$parameters{namespace}WrapperMap(functions);
+    static const auto functions = makeNeverDestroyed(create$parameters{namespace}WrapperMap());
     if (auto function = functions.get().get(element->localName().impl()))
         return function(globalObject, WTFMove(element));
 END
index 52144d268dab6df005004e445077f34aaa347cac..f8f24163370afd021b4da02ccf17a233bffc71f5 100644 (file)
@@ -86,31 +86,29 @@ private:
 
 static const Vector<DocumentMarker::MarkerType>& markerTypesForAutocorrection()
 {
-    static NeverDestroyed<Vector<DocumentMarker::MarkerType>> markerTypesForAutoCorrection;
-    if (markerTypesForAutoCorrection.get().isEmpty()) {
-        markerTypesForAutoCorrection.get().append(DocumentMarker::Replacement);
-        markerTypesForAutoCorrection.get().append(DocumentMarker::CorrectionIndicator);
-        markerTypesForAutoCorrection.get().append(DocumentMarker::SpellCheckingExemption);
-        markerTypesForAutoCorrection.get().append(DocumentMarker::Autocorrected);
-    }
+    static const auto markerTypesForAutoCorrection = makeNeverDestroyed(Vector<DocumentMarker::MarkerType> {
+        DocumentMarker::Autocorrected,
+        DocumentMarker::CorrectionIndicator,
+        DocumentMarker::Replacement,
+        DocumentMarker::SpellCheckingExemption,
+    });
     return markerTypesForAutoCorrection;
 }
 
 static const Vector<DocumentMarker::MarkerType>& markerTypesForReplacement()
 {
-    static NeverDestroyed<Vector<DocumentMarker::MarkerType>> markerTypesForReplacement;
-    if (markerTypesForReplacement.get().isEmpty()) {
-        markerTypesForReplacement.get().append(DocumentMarker::Replacement);
-        markerTypesForReplacement.get().append(DocumentMarker::SpellCheckingExemption);
-    }
+    static const auto markerTypesForReplacement = makeNeverDestroyed(Vector<DocumentMarker::MarkerType> {
+        DocumentMarker::Replacement,
+        DocumentMarker::SpellCheckingExemption,
+    });
     return markerTypesForReplacement;
 }
 
 static const Vector<DocumentMarker::MarkerType>& markerTypesForAppliedDictationAlternative()
 {
-    static NeverDestroyed<Vector<DocumentMarker::MarkerType>> markerTypesForAppliedDictationAlternative;
-    if (markerTypesForAppliedDictationAlternative.get().isEmpty())
-        markerTypesForAppliedDictationAlternative.get().append(DocumentMarker::SpellCheckingExemption);
+    static const auto markerTypesForAppliedDictationAlternative = makeNeverDestroyed(Vector<DocumentMarker::MarkerType> {
+        DocumentMarker::SpellCheckingExemption,
+    });
     return markerTypesForAppliedDictationAlternative;
 }
 
index c369573ec49f13e221a20485fa09c9359b974518..e34aa78d0f63295cfc35fdd6bc17aee31139a98b 100644 (file)
@@ -898,24 +898,21 @@ bool EditingStyle::conflictsWithInlineStyleOfElement(StyledElement* element, Ref
     return conflicts;
 }
 
-static const Vector<std::unique_ptr<HTMLElementEquivalent>>& htmlElementEquivalents()
+static const Vector<const HTMLElementEquivalent*>& htmlElementEquivalents()
 {
-    static NeverDestroyed<Vector<std::unique_ptr<HTMLElementEquivalent>>> HTMLElementEquivalents;
+    static const auto equivalents = makeNeverDestroyed(Vector<const HTMLElementEquivalent*> {
+        new HTMLElementEquivalent(CSSPropertyFontWeight, CSSValueBold, HTMLNames::bTag),
+        new HTMLElementEquivalent(CSSPropertyFontWeight, CSSValueBold, HTMLNames::strongTag),
+        new HTMLElementEquivalent(CSSPropertyVerticalAlign, CSSValueSub, HTMLNames::subTag),
+        new HTMLElementEquivalent(CSSPropertyVerticalAlign, CSSValueSuper, HTMLNames::supTag),
+        new HTMLElementEquivalent(CSSPropertyFontStyle, CSSValueItalic, HTMLNames::iTag),
+        new HTMLElementEquivalent(CSSPropertyFontStyle, CSSValueItalic, HTMLNames::emTag),
 
-    if (!HTMLElementEquivalents.get().size()) {
-        HTMLElementEquivalents.get().append(std::make_unique<HTMLElementEquivalent>(CSSPropertyFontWeight, CSSValueBold, HTMLNames::bTag));
-        HTMLElementEquivalents.get().append(std::make_unique<HTMLElementEquivalent>(CSSPropertyFontWeight, CSSValueBold, HTMLNames::strongTag));
-        HTMLElementEquivalents.get().append(std::make_unique<HTMLElementEquivalent>(CSSPropertyVerticalAlign, CSSValueSub, HTMLNames::subTag));
-        HTMLElementEquivalents.get().append(std::make_unique<HTMLElementEquivalent>(CSSPropertyVerticalAlign, CSSValueSuper, HTMLNames::supTag));
-        HTMLElementEquivalents.get().append(std::make_unique<HTMLElementEquivalent>(CSSPropertyFontStyle, CSSValueItalic, HTMLNames::iTag));
-        HTMLElementEquivalents.get().append(std::make_unique<HTMLElementEquivalent>(CSSPropertyFontStyle, CSSValueItalic, HTMLNames::emTag));
-
-        HTMLElementEquivalents.get().append(std::make_unique<HTMLTextDecorationEquivalent>(CSSValueUnderline, HTMLNames::uTag));
-        HTMLElementEquivalents.get().append(std::make_unique<HTMLTextDecorationEquivalent>(CSSValueLineThrough, HTMLNames::sTag));
-        HTMLElementEquivalents.get().append(std::make_unique<HTMLTextDecorationEquivalent>(CSSValueLineThrough, HTMLNames::strikeTag));
-    }
-
-    return HTMLElementEquivalents;
+        new HTMLTextDecorationEquivalent(CSSValueUnderline, HTMLNames::uTag),
+        new HTMLTextDecorationEquivalent(CSSValueLineThrough, HTMLNames::sTag),
+        new HTMLTextDecorationEquivalent(CSSValueLineThrough, HTMLNames::strikeTag),
+    });
+    return equivalents;
 }
 
 
@@ -924,8 +921,7 @@ bool EditingStyle::conflictsWithImplicitStyleOfElement(HTMLElement* element, Edi
     if (isEmpty())
         return false;
 
-    const Vector<std::unique_ptr<HTMLElementEquivalent>>& HTMLElementEquivalents = htmlElementEquivalents();
-    for (auto& equivalent : HTMLElementEquivalents) {
+    for (auto& equivalent : htmlElementEquivalents()) {
         if (equivalent->matches(*element) && equivalent->propertyExistsInStyle(*this)
             && (shouldExtractMatchingStyle == ExtractMatchingStyle || !equivalent->valueIsPresentInStyle(*element, *this))) {
             if (extractedStyle)
@@ -936,22 +932,19 @@ bool EditingStyle::conflictsWithImplicitStyleOfElement(HTMLElement* element, Edi
     return false;
 }
 
-static const Vector<std::unique_ptr<HTMLAttributeEquivalent>>& htmlAttributeEquivalents()
+static const Vector<const HTMLAttributeEquivalent*>& htmlAttributeEquivalents()
 {
-    static NeverDestroyed<Vector<std::unique_ptr<HTMLAttributeEquivalent>>> HTMLAttributeEquivalents;
-
-    if (!HTMLAttributeEquivalents.get().size()) {
+    static const auto equivalents = makeNeverDestroyed(Vector<const HTMLAttributeEquivalent*> {
         // elementIsStyledSpanOrHTMLEquivalent depends on the fact each HTMLAttriuteEquivalent matches exactly one attribute
         // of exactly one element except dirAttr.
-        HTMLAttributeEquivalents.get().append(std::make_unique<HTMLAttributeEquivalent>(CSSPropertyColor, HTMLNames::fontTag, HTMLNames::colorAttr));
-        HTMLAttributeEquivalents.get().append(std::make_unique<HTMLAttributeEquivalent>(CSSPropertyFontFamily, HTMLNames::fontTag, HTMLNames::faceAttr));
-        HTMLAttributeEquivalents.get().append(std::make_unique<HTMLFontSizeEquivalent>());
-
-        HTMLAttributeEquivalents.get().append(std::make_unique<HTMLAttributeEquivalent>(CSSPropertyDirection, HTMLNames::dirAttr));
-        HTMLAttributeEquivalents.get().append(std::make_unique<HTMLAttributeEquivalent>(CSSPropertyUnicodeBidi, HTMLNames::dirAttr));
-    }
+        new HTMLAttributeEquivalent(CSSPropertyColor, HTMLNames::fontTag, HTMLNames::colorAttr),
+        new HTMLAttributeEquivalent(CSSPropertyFontFamily, HTMLNames::fontTag, HTMLNames::faceAttr),
+        new HTMLFontSizeEquivalent,
 
-    return HTMLAttributeEquivalents;
+        new HTMLAttributeEquivalent(CSSPropertyDirection, HTMLNames::dirAttr),
+        new HTMLAttributeEquivalent(CSSPropertyUnicodeBidi, HTMLNames::dirAttr),
+    });
+    return equivalents;
 }
 
 bool EditingStyle::conflictsWithImplicitStyleOfAttributes(HTMLElement* element) const
@@ -960,8 +953,7 @@ bool EditingStyle::conflictsWithImplicitStyleOfAttributes(HTMLElement* element)
     if (isEmpty())
         return false;
 
-    const Vector<std::unique_ptr<HTMLAttributeEquivalent>>& HTMLAttributeEquivalents = htmlAttributeEquivalents();
-    for (auto& equivalent : HTMLAttributeEquivalents) {
+    for (auto& equivalent : htmlAttributeEquivalents()) {
         if (equivalent->matches(*element) && equivalent->propertyExistsInStyle(*this) && !equivalent->valueIsPresentInStyle(*element, *this))
             return true;
     }
@@ -1133,15 +1125,15 @@ void EditingStyle::mergeInlineStyleOfElement(StyledElement* element, CSSProperty
     }
 }
 
-static inline bool elementMatchesAndPropertyIsNotInInlineStyleDecl(const HTMLElementEquivalent* equivalent, const StyledElement& element,
+static inline bool elementMatchesAndPropertyIsNotInInlineStyleDecl(const HTMLElementEquivalent& equivalent, const StyledElement& element,
     EditingStyle::CSSPropertyOverrideMode mode, EditingStyle& style)
 {
-    if (!equivalent->matches(element))
+    if (!equivalent.matches(element))
         return false;
-    if (mode != EditingStyle::OverrideValues && equivalent->propertyExistsInStyle(style))
+    if (mode != EditingStyle::OverrideValues && equivalent.propertyExistsInStyle(style))
         return false;
 
-    return !element.inlineStyle() || !equivalent->propertyExistsInStyle(EditingStyle::create(element.inlineStyle()).get());
+    return !element.inlineStyle() || !equivalent.propertyExistsInStyle(EditingStyle::create(element.inlineStyle()).get());
 }
 
 static RefPtr<MutableStyleProperties> extractEditingProperties(const StyleProperties* style, EditingStyle::PropertiesToInclude propertiesToInclude)
@@ -1171,14 +1163,14 @@ void EditingStyle::mergeInlineAndImplicitStyleOfElement(StyledElement& element,
     mergeStyle(styleFromRules->m_mutableStyle.get(), mode);
 
     for (auto& equivalent : htmlElementEquivalents()) {
-        if (elementMatchesAndPropertyIsNotInInlineStyleDecl(equivalent.get(), element, mode, *this))
+        if (elementMatchesAndPropertyIsNotInInlineStyleDecl(*equivalent, element, mode, *this))
             equivalent->addToStyle(&element, this);
     }
 
     for (auto& equivalent : htmlAttributeEquivalents()) {
         if (equivalent->attributeName() == HTMLNames::dirAttr)
             continue; // We don't want to include directionality
-        if (elementMatchesAndPropertyIsNotInInlineStyleDecl(equivalent.get(), element, mode, *this))
+        if (elementMatchesAndPropertyIsNotInInlineStyleDecl(*equivalent, element, mode, *this))
             equivalent->addToStyle(&element, this);
     }
 }
index ce5189da782dbd0e7539c63599657ffcfbf11075..6f53208fe6c2148a025637b610eb32adc6f01872 100644 (file)
@@ -120,31 +120,30 @@ Element* FormatBlockCommand::elementForFormatBlockCommand(Range* range)
 
 bool isElementForFormatBlock(const QualifiedName& tagName)
 {
-    static NeverDestroyed<HashSet<QualifiedName>> blockTags;
-    if (blockTags.get().isEmpty()) {
-        blockTags.get().add(addressTag);
-        blockTags.get().add(articleTag);
-        blockTags.get().add(asideTag);
-        blockTags.get().add(blockquoteTag);
-        blockTags.get().add(ddTag);
-        blockTags.get().add(divTag);
-        blockTags.get().add(dlTag);
-        blockTags.get().add(dtTag);
-        blockTags.get().add(footerTag);
-        blockTags.get().add(h1Tag);
-        blockTags.get().add(h2Tag);
-        blockTags.get().add(h3Tag);
-        blockTags.get().add(h4Tag);
-        blockTags.get().add(h5Tag);
-        blockTags.get().add(h6Tag);
-        blockTags.get().add(headerTag);
-        blockTags.get().add(hgroupTag);
-        blockTags.get().add(mainTag);
-        blockTags.get().add(navTag);
-        blockTags.get().add(pTag);
-        blockTags.get().add(preTag);
-        blockTags.get().add(sectionTag);
-    }
+    static const auto blockTags = makeNeverDestroyed(HashSet<QualifiedName> {
+        addressTag,
+        articleTag,
+        asideTag,
+        blockquoteTag,
+        ddTag,
+        divTag,
+        dlTag,
+        dtTag,
+        footerTag,
+        h1Tag,
+        h2Tag,
+        h3Tag,
+        h4Tag,
+        h5Tag,
+        h6Tag,
+        headerTag,
+        hgroupTag,
+        mainTag,
+        navTag,
+        pTag,
+        preTag,
+        sectionTag,
+    });
     return blockTags.get().contains(tagName);
 }
 
index d8b82cf1ae77b54ae886e5c5b442a5a465029d0e..c19b774ad6b303b3950c6a1157405f948baccac2 100644 (file)
@@ -46,33 +46,32 @@ RemoveFormatCommand::RemoveFormatCommand(Document& document)
 
 static bool isElementForRemoveFormatCommand(const Element* element)
 {
-    static NeverDestroyed<HashSet<QualifiedName>> elements;
-    if (elements.get().isEmpty()) {
-        elements.get().add(acronymTag);
-        elements.get().add(bTag);
-        elements.get().add(bdoTag);
-        elements.get().add(bigTag);
-        elements.get().add(citeTag);
-        elements.get().add(codeTag);
-        elements.get().add(dfnTag);
-        elements.get().add(emTag);
-        elements.get().add(fontTag);
-        elements.get().add(iTag);
-        elements.get().add(insTag);
-        elements.get().add(kbdTag);
-        elements.get().add(nobrTag);
-        elements.get().add(qTag);
-        elements.get().add(sTag);
-        elements.get().add(sampTag);
-        elements.get().add(smallTag);
-        elements.get().add(strikeTag);
-        elements.get().add(strongTag);
-        elements.get().add(subTag);
-        elements.get().add(supTag);
-        elements.get().add(ttTag);
-        elements.get().add(uTag);
-        elements.get().add(varTag);
-    }
+    static const auto elements = makeNeverDestroyed(HashSet<QualifiedName> {
+        acronymTag,
+        bTag,
+        bdoTag,
+        bigTag,
+        citeTag,
+        codeTag,
+        dfnTag,
+        emTag,
+        fontTag,
+        iTag,
+        insTag,
+        kbdTag,
+        nobrTag,
+        qTag,
+        sTag,
+        sampTag,
+        smallTag,
+        strikeTag,
+        strongTag,
+        subTag,
+        supTag,
+        ttTag,
+        uTag,
+        varTag,
+    });
     return elements.get().contains(element->tagQName());
 }
 
index 270f85042094c1f37b6b7abb40263971616e2ee1..b2a99051822b9db2b6e9a5d7a9f602ed70a55d90 100644 (file)
@@ -566,58 +566,63 @@ void ReplaceSelectionCommand::removeRedundantStylesAndKeepStyleSpanInline(Insert
 static bool isProhibitedParagraphChild(const AtomicString& name)
 {
     // https://dvcs.w3.org/hg/editing/raw-file/57abe6d3cb60/editing.html#prohibited-paragraph-child
-    static NeverDestroyed<HashSet<AtomicString>> elements;
-    if (elements.get().isEmpty()) {
-        elements.get().add(addressTag.localName());
-        elements.get().add(articleTag.localName());
-        elements.get().add(asideTag.localName());
-        elements.get().add(blockquoteTag.localName());
-        elements.get().add(captionTag.localName());
-        elements.get().add(centerTag.localName());
-        elements.get().add(colTag.localName());
-        elements.get().add(colgroupTag.localName());
-        elements.get().add(ddTag.localName());
-        elements.get().add(detailsTag.localName());
-        elements.get().add(dirTag.localName());
-        elements.get().add(divTag.localName());
-        elements.get().add(dlTag.localName());
-        elements.get().add(dtTag.localName());
-        elements.get().add(fieldsetTag.localName());
-        elements.get().add(figcaptionTag.localName());
-        elements.get().add(figureTag.localName());
-        elements.get().add(footerTag.localName());
-        elements.get().add(formTag.localName());
-        elements.get().add(h1Tag.localName());
-        elements.get().add(h2Tag.localName());
-        elements.get().add(h3Tag.localName());
-        elements.get().add(h4Tag.localName());
-        elements.get().add(h5Tag.localName());
-        elements.get().add(h6Tag.localName());
-        elements.get().add(headerTag.localName());
-        elements.get().add(hgroupTag.localName());
-        elements.get().add(hrTag.localName());
-        elements.get().add(liTag.localName());
-        elements.get().add(listingTag.localName());
-        elements.get().add(mainTag.localName()); // Missing in the specification.
-        elements.get().add(menuTag.localName());
-        elements.get().add(navTag.localName());
-        elements.get().add(olTag.localName());
-        elements.get().add(pTag.localName());
-        elements.get().add(plaintextTag.localName());
-        elements.get().add(preTag.localName());
-        elements.get().add(sectionTag.localName());
-        elements.get().add(summaryTag.localName());
-        elements.get().add(tableTag.localName());
-        elements.get().add(tbodyTag.localName());
-        elements.get().add(tdTag.localName());
-        elements.get().add(tfootTag.localName());
-        elements.get().add(thTag.localName());
-        elements.get().add(theadTag.localName());
-        elements.get().add(trTag.localName());
-        elements.get().add(ulTag.localName());
-        elements.get().add(xmpTag.localName());
-    }
-    return elements.get().contains(name);
+    static const auto localNames = makeNeverDestroyed([] {
+        static const HTMLQualifiedName* const tags[] = {
+            &addressTag,
+            &articleTag,
+            &asideTag,
+            &blockquoteTag,
+            &captionTag,
+            &centerTag,
+            &colTag,
+            &colgroupTag,
+            &ddTag,
+            &detailsTag,
+            &dirTag,
+            &divTag,
+            &dlTag,
+            &dtTag,
+            &fieldsetTag,
+            &figcaptionTag,
+            &figureTag,
+            &footerTag,
+            &formTag,
+            &h1Tag,
+            &h2Tag,
+            &h3Tag,
+            &h4Tag,
+            &h5Tag,
+            &h6Tag,
+            &headerTag,
+            &hgroupTag,
+            &hrTag,
+            &liTag,
+            &listingTag,
+            &mainTag, // Missing in the specification.
+            &menuTag,
+            &navTag,
+            &olTag,
+            &pTag,
+            &plaintextTag,
+            &preTag,
+            &sectionTag,
+            &summaryTag,
+            &tableTag,
+            &tbodyTag,
+            &tdTag,
+            &tfootTag,
+            &thTag,
+            &theadTag,
+            &trTag,
+            &ulTag,
+            &xmpTag,
+        };
+        HashSet<AtomicString> set;
+        for (auto& tag : tags)
+            set.add(tag->localName());
+        return set;
+    }());
+    return localNames.get().contains(name);
 }
 
 void ReplaceSelectionCommand::makeInsertedContentRoundTrippableWithHTMLTreeBuilder(InsertedNodes& insertedNodes)
index 16118a83070e13125b9cd1693a899b1f66cdfc46..5a1aad346e2363df4956ae6d7a7409cff01a7f6c 100644 (file)
@@ -48,68 +48,76 @@ struct AutofillInfo {
     AutofillCategory category;
 };
 
-static HashMap<AtomicString, AutofillInfo>& fieldNameMap()
+static const HashMap<AtomicString, AutofillInfo>& fieldNameMap()
 {
-    static NeverDestroyed<HashMap<AtomicString, AutofillInfo>> map;
-    if (map.get().isEmpty()) {
-        map.get().add(AtomicString("off", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::None, AutofillCategory::Off });
-        map.get().add(AtomicString("on", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::None,  AutofillCategory::Automatic });
-        map.get().add(AtomicString("name", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::Name, AutofillCategory::Normal });
-        map.get().add(AtomicString("honorific-prefix", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::HonorificPrefix, AutofillCategory::Normal });
-        map.get().add(AtomicString("given-name", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::GivenName, AutofillCategory::Normal });
-        map.get().add(AtomicString("additional-name", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::AdditionalName, AutofillCategory::Normal });
-        map.get().add(AtomicString("family-name", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::FamilyName, AutofillCategory::Normal });
-        map.get().add(AtomicString("honorific-suffix", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::HonorificSuffix, AutofillCategory::Normal });
-        map.get().add(AtomicString("nickname", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::Nickname, AutofillCategory::Normal });
-        map.get().add(AtomicString("username", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::Username, AutofillCategory::Normal });
-        map.get().add(AtomicString("new-password", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::NewPassword, AutofillCategory::Normal });
-        map.get().add(AtomicString("current-password", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::CurrentPassword, AutofillCategory::Normal });
-        map.get().add(AtomicString("organization-title", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::OrganizationTitle, AutofillCategory::Normal });
-        map.get().add(AtomicString("organization", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::Organization, AutofillCategory::Normal });
-        map.get().add(AtomicString("street-address", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::StreetAddress, AutofillCategory::Normal });
-        map.get().add(AtomicString("address-line1", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::AddressLine1, AutofillCategory::Normal });
-        map.get().add(AtomicString("address-line2", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::AddressLine2, AutofillCategory::Normal });
-        map.get().add(AtomicString("address-line3", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::AddressLine3, AutofillCategory::Normal });
-        map.get().add(AtomicString("address-level4", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::AddressLevel4, AutofillCategory::Normal });
-        map.get().add(AtomicString("address-level3", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::AddressLevel3, AutofillCategory::Normal });
-        map.get().add(AtomicString("address-level2", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::AddressLevel2, AutofillCategory::Normal });
-        map.get().add(AtomicString("address-level1", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::AddressLevel1, AutofillCategory::Normal });
-        map.get().add(AtomicString("country", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::Country, AutofillCategory::Normal });
-        map.get().add(AtomicString("country-name", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::CountryName, AutofillCategory::Normal });
-        map.get().add(AtomicString("postal-code", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::PostalCode, AutofillCategory::Normal });
-        map.get().add(AtomicString("cc-name", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::CcName, AutofillCategory::Normal });
-        map.get().add(AtomicString("cc-given-name", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::CcGivenName, AutofillCategory::Normal });
-        map.get().add(AtomicString("cc-additional-name", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::CcAdditionalName, AutofillCategory::Normal });
-        map.get().add(AtomicString("cc-family-name", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::CcFamilyName, AutofillCategory::Normal });
-        map.get().add(AtomicString("cc-number", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::CcNumber, AutofillCategory::Normal });
-        map.get().add(AtomicString("cc-exp", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::CcExp, AutofillCategory::Normal });
-        map.get().add(AtomicString("cc-exp-month", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::CcExpMonth, AutofillCategory::Normal });
-        map.get().add(AtomicString("cc-exp-year", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::CcExpYear, AutofillCategory::Normal });
-        map.get().add(AtomicString("cc-csc", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::CcCsc, AutofillCategory::Normal });
-        map.get().add(AtomicString("cc-type", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::CcType, AutofillCategory::Normal });
-        map.get().add(AtomicString("transaction-currency", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::TransactionCurrency, AutofillCategory::Normal });
-        map.get().add(AtomicString("transaction-amount", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::TransactionAmount, AutofillCategory::Normal });
-        map.get().add(AtomicString("language", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::Language, AutofillCategory::Normal });
-        map.get().add(AtomicString("bday", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::Bday, AutofillCategory::Normal });
-        map.get().add(AtomicString("bday-day", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::BdayDay, AutofillCategory::Normal });
-        map.get().add(AtomicString("bday-month", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::BdayMonth, AutofillCategory::Normal });
-        map.get().add(AtomicString("bday-year", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::BdayYear, AutofillCategory::Normal });
-        map.get().add(AtomicString("sex", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::Sex, AutofillCategory::Normal });
-        map.get().add(AtomicString("url", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::URL, AutofillCategory::Normal });
-        map.get().add(AtomicString("photo", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::Photo, AutofillCategory::Normal });
-
-        map.get().add(AtomicString("tel", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::Tel, AutofillCategory::Contact });
-        map.get().add(AtomicString("tel-country-code", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::TelCountryCode, AutofillCategory::Contact });
-        map.get().add(AtomicString("tel-national", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::TelNational, AutofillCategory::Contact });
-        map.get().add(AtomicString("tel-area-code", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::TelAreaCode, AutofillCategory::Contact });
-        map.get().add(AtomicString("tel-local", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::TelLocal, AutofillCategory::Contact });
-        map.get().add(AtomicString("tel-local-prefix", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::TelLocalPrefix, AutofillCategory::Contact });
-        map.get().add(AtomicString("tel-local-suffix", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::TelLocalSuffix, AutofillCategory::Contact });
-        map.get().add(AtomicString("tel-extension", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::TelExtension, AutofillCategory::Contact });
-        map.get().add(AtomicString("email", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::Email, AutofillCategory::Contact });
-        map.get().add(AtomicString("impp", AtomicString::ConstructFromLiteral), AutofillInfo{ AutofillFieldName::Impp, AutofillCategory::Contact });
-    }
-
+    static const auto map = makeNeverDestroyed([] {
+        struct MapEntry {
+            const char* name;
+            AutofillInfo value;
+        };
+        static const MapEntry entries[] = {
+            { "off", { AutofillFieldName::None, AutofillCategory::Off } },
+            { "on", { AutofillFieldName::None,  AutofillCategory::Automatic } },
+            { "name", { AutofillFieldName::Name, AutofillCategory::Normal } },
+            { "honorific-prefix", { AutofillFieldName::HonorificPrefix, AutofillCategory::Normal } },
+            { "given-name", { AutofillFieldName::GivenName, AutofillCategory::Normal } },
+            { "additional-name", { AutofillFieldName::AdditionalName, AutofillCategory::Normal } },
+            { "family-name", { AutofillFieldName::FamilyName, AutofillCategory::Normal } },
+            { "honorific-suffix", { AutofillFieldName::HonorificSuffix, AutofillCategory::Normal } },
+            { "nickname", { AutofillFieldName::Nickname, AutofillCategory::Normal } },
+            { "username", { AutofillFieldName::Username, AutofillCategory::Normal } },
+            { "new-password", { AutofillFieldName::NewPassword, AutofillCategory::Normal } },
+            { "current-password", { AutofillFieldName::CurrentPassword, AutofillCategory::Normal } },
+            { "organization-title", { AutofillFieldName::OrganizationTitle, AutofillCategory::Normal } },
+            { "organization", { AutofillFieldName::Organization, AutofillCategory::Normal } },
+            { "street-address", { AutofillFieldName::StreetAddress, AutofillCategory::Normal } },
+            { "address-line1", { AutofillFieldName::AddressLine1, AutofillCategory::Normal } },
+            { "address-line2", { AutofillFieldName::AddressLine2, AutofillCategory::Normal } },
+            { "address-line3", { AutofillFieldName::AddressLine3, AutofillCategory::Normal } },
+            { "address-level4", { AutofillFieldName::AddressLevel4, AutofillCategory::Normal } },
+            { "address-level3", { AutofillFieldName::AddressLevel3, AutofillCategory::Normal } },
+            { "address-level2", { AutofillFieldName::AddressLevel2, AutofillCategory::Normal } },
+            { "address-level1", { AutofillFieldName::AddressLevel1, AutofillCategory::Normal } },
+            { "country", { AutofillFieldName::Country, AutofillCategory::Normal } },
+            { "country-name", { AutofillFieldName::CountryName, AutofillCategory::Normal } },
+            { "postal-code", { AutofillFieldName::PostalCode, AutofillCategory::Normal } },
+            { "cc-name", { AutofillFieldName::CcName, AutofillCategory::Normal } },
+            { "cc-given-name", { AutofillFieldName::CcGivenName, AutofillCategory::Normal } },
+            { "cc-additional-name", { AutofillFieldName::CcAdditionalName, AutofillCategory::Normal } },
+            { "cc-family-name", { AutofillFieldName::CcFamilyName, AutofillCategory::Normal } },
+            { "cc-number", { AutofillFieldName::CcNumber, AutofillCategory::Normal } },
+            { "cc-exp", { AutofillFieldName::CcExp, AutofillCategory::Normal } },
+            { "cc-exp-month", { AutofillFieldName::CcExpMonth, AutofillCategory::Normal } },
+            { "cc-exp-year", { AutofillFieldName::CcExpYear, AutofillCategory::Normal } },
+            { "cc-csc", { AutofillFieldName::CcCsc, AutofillCategory::Normal } },
+            { "cc-type", { AutofillFieldName::CcType, AutofillCategory::Normal } },
+            { "transaction-currency", { AutofillFieldName::TransactionCurrency, AutofillCategory::Normal } },
+            { "transaction-amount", { AutofillFieldName::TransactionAmount, AutofillCategory::Normal } },
+            { "language", { AutofillFieldName::Language, AutofillCategory::Normal } },
+            { "bday", { AutofillFieldName::Bday, AutofillCategory::Normal } },
+            { "bday-day", { AutofillFieldName::BdayDay, AutofillCategory::Normal } },
+            { "bday-month", { AutofillFieldName::BdayMonth, AutofillCategory::Normal } },
+            { "bday-year", { AutofillFieldName::BdayYear, AutofillCategory::Normal } },
+            { "sex", { AutofillFieldName::Sex, AutofillCategory::Normal } },
+            { "url", { AutofillFieldName::URL, AutofillCategory::Normal } },
+            { "photo", { AutofillFieldName::Photo, AutofillCategory::Normal } },
+
+            { "tel", { AutofillFieldName::Tel, AutofillCategory::Contact } },
+            { "tel-country-code", { AutofillFieldName::TelCountryCode, AutofillCategory::Contact } },
+            { "tel-national", { AutofillFieldName::TelNational, AutofillCategory::Contact } },
+            { "tel-area-code", { AutofillFieldName::TelAreaCode, AutofillCategory::Contact } },
+            { "tel-local", { AutofillFieldName::TelLocal, AutofillCategory::Contact } },
+            { "tel-local-prefix", { AutofillFieldName::TelLocalPrefix, AutofillCategory::Contact } },
+            { "tel-local-suffix", { AutofillFieldName::TelLocalSuffix, AutofillCategory::Contact } },
+            { "tel-extension", { AutofillFieldName::TelExtension, AutofillCategory::Contact } },
+            { "email", { AutofillFieldName::Email, AutofillCategory::Contact } },
+            { "impp", { AutofillFieldName::Impp, AutofillCategory::Contact } },
+        };
+        HashMap<AtomicString, AutofillInfo> map;
+        for (auto& entry : entries)
+            map.add(entry.name, entry.value);
+        return map;
+    }());
     return map;
 }
 
index 1cb120c48263677cc3f18afe905f730c4e9cf85a..43abc02ed79420bc067c5c09cadd2e46ceab93fb 100644 (file)
@@ -388,8 +388,8 @@ void HTMLObjectElement::renderFallbackContent()
 // FIXME: This should be removed, all callers are almost certainly wrong.
 static bool isRecognizedTagName(const QualifiedName& tagName)
 {
-    static NeverDestroyed<HashSet<AtomicStringImpl*>> tagList;
-    if (tagList.get().isEmpty()) {
+    static const auto tagList = makeNeverDestroyed([] {
+        HashSet<AtomicStringImpl*> map;
         auto* tags = HTMLNames::getHTMLTags();
         for (size_t i = 0; i < HTMLNames::HTMLTagsCount; i++) {
             if (*tags[i] == bgsoundTag
@@ -404,9 +404,10 @@ static bool isRecognizedTagName(const QualifiedName& tagName)
                 // because that changes how we parse documents.
                 continue;
             }
-            tagList.get().add(tags[i]->localName().impl());
+            map.add(tags[i]->localName().impl());
         }
-    }
+        return map;
+    }());
     return tagList.get().contains(tagName.localName().impl());
 }
 
index f7e9d5e8a871bdf17d9a802e2563d53dc1f1fe30..fdf0cdb5f5c751e272885ae77d3a0c30e2ae1868 100644 (file)
@@ -36,6 +36,7 @@
 #include "ShadowRoot.h"
 #include "StyleScope.h"
 #include "StyleSheetContents.h"
+#include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
index 4b5fd58bbb1a95c8bf3eddcdd013d00349948de4..7fd13faeb638285147ada34b747d1c1093ccf3f6 100644 (file)
@@ -45,7 +45,6 @@
 #include "ScriptController.h"
 #include "Settings.h"
 #include "TextStream.h"
-#include <wtf/NeverDestroyed.h>
 
 #if ENABLE(VIDEO_PRESENTATION_MODE)
 #include "WebVideoFullscreenModel.h"
index ee47a576b186de62adfe94b61de92961c397dbcb..de0e779016e7b2343a886fc1b6d92fd037d24b61 100644 (file)
@@ -94,7 +94,7 @@ static std::unique_ptr<InputType> createInputType(HTMLInputElement& element)
     return std::make_unique<T>(element);
 }
 
-static void populateInputTypeFactoryMap(InputTypeFactoryMap& map)
+static InputTypeFactoryMap createInputTypeFactoryMap()
 {
     static const struct InputTypes {
         InputTypeConditionalFunction conditionalFunction;
@@ -140,20 +140,19 @@ static void populateInputTypeFactoryMap(InputTypeFactoryMap& map)
         // No need to register "text" because it is the default type.
     };
 
+    InputTypeFactoryMap map;
     for (auto& inputType : inputTypes) {
         auto conditionalFunction = inputType.conditionalFunction;
         if (!conditionalFunction || (RuntimeEnabledFeatures::sharedFeatures().*conditionalFunction)())
             map.add(inputType.nameFunction(), inputType.factoryFunction);
     }
+    return map;
 }
 
 std::unique_ptr<InputType> InputType::create(HTMLInputElement& element, const AtomicString& typeName)
 {
-    static NeverDestroyed<InputTypeFactoryMap> factoryMap;
-    if (factoryMap.get().isEmpty())
-        populateInputTypeFactoryMap(factoryMap);
-
     if (!typeName.isEmpty()) {
+        static const auto factoryMap = makeNeverDestroyed(createInputTypeFactoryMap());
         if (auto factory = factoryMap.get().get(typeName))
             return factory(element);
     }
index 47c19661134993df0ea719f088a8b7391f65804f..490e2a844d359d5f245d203037cd6d6abcac1f78 100644 (file)
@@ -30,7 +30,6 @@
 #include "URL.h"
 #include <limits>
 #include <wtf/MathExtras.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/dtoa.h>
 
 namespace WebCore {
index 6e39bcdad0d84f0427a92c2710ffcf2f1e0b00c4..6b22803e8db97cfbcb187e8ce4cf87fcd9119175 100644 (file)
@@ -83,8 +83,7 @@ void InspectorApplicationCacheAgent::updateApplicationCacheStatus(Frame* frame)
 
 void InspectorApplicationCacheAgent::networkStateChanged()
 {
-    bool isNowOnline = networkStateNotifier().onLine();
-    m_frontendDispatcher->networkStateUpdated(isNowOnline);
+    m_frontendDispatcher->networkStateUpdated(NetworkStateNotifier::singleton().onLine());
 }
 
 void InspectorApplicationCacheAgent::getFramesWithManifests(ErrorString&, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::ApplicationCache::FrameWithManifest>>& result)
index 85c527180d04d61ba4c5fc67c7fb23a505e587a5..c1a8c85a5fe88cfb688cf8fbb4abf5ebe6d81f6e 100644 (file)
@@ -253,14 +253,10 @@ void ContentFilter::deliverResourceData(CachedResource& resource)
 
 static const URL& blockedPageURL()
 {
-    static LazyNeverDestroyed<URL> blockedPageURL;
-    static std::once_flag onceFlag;
-    std::call_once(onceFlag, [] {
+    static const auto blockedPageURL = makeNeverDestroyed([] () -> URL {
         auto webCoreBundle = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.WebCore"));
-        auto blockedPageCFURL = adoptCF(CFBundleCopyResourceURL(webCoreBundle, CFSTR("ContentFilterBlockedPage"), CFSTR("html"), nullptr));
-        blockedPageURL.construct(blockedPageCFURL.get());
-    });
-
+        return adoptCF(CFBundleCopyResourceURL(webCoreBundle, CFSTR("ContentFilterBlockedPage"), CFSTR("html"), nullptr)).get();
+    }());
     return blockedPageURL;
 }
 
index 36b55a12d2db8b05607c8cde5656031a23cdd308..18bcea45bc215cb259ad52f33e4869fdeeda2918 100644 (file)
@@ -58,25 +58,6 @@ bool isSimpleCrossOriginAccessRequest(const String& method, const HTTPHeaderMap&
     return true;
 }
 
-bool isOnAccessControlResponseHeaderWhitelist(const String& name)
-{
-    static std::once_flag onceFlag;
-    static LazyNeverDestroyed<HTTPHeaderSet> allowedCrossOriginResponseHeaders;
-
-    std::call_once(onceFlag, []{
-        allowedCrossOriginResponseHeaders.construct<std::initializer_list<String>>({
-            "cache-control",
-            "content-language",
-            "content-type",
-            "expires",
-            "last-modified",
-            "pragma"
-        });
-    });
-
-    return allowedCrossOriginResponseHeaders.get().contains(name);
-}
-
 void updateRequestForAccessControl(ResourceRequest& request, SecurityOrigin& securityOrigin, StoredCredentials allowCredentials)
 {
     request.removeCredentials();
index 8a710437d076dbe761f8a578ad3b0e99c36207ce..0d684b3fbc13a65dd3a5edc6019c1a1e66028926 100644 (file)
@@ -32,7 +32,6 @@
 namespace WebCore {
 
 class HTTPHeaderMap;
-enum class HTTPHeaderName;
 class ResourceRequest;
 class ResourceResponse;
 class SecurityOrigin;
@@ -40,7 +39,6 @@ class URL;
 
 bool isSimpleCrossOriginAccessRequest(const String& method, const HTTPHeaderMap&);
 bool isOnAccessControlSimpleRequestMethodWhitelist(const String&);
-bool isOnAccessControlResponseHeaderWhitelist(const String&);
 
 void updateRequestForAccessControl(ResourceRequest&, SecurityOrigin&, StoredCredentials);
 ResourceRequest createAccessControlPreflightRequest(const ResourceRequest&, SecurityOrigin&, const String&);
index 7780875a5a40c000967d19a6d89b8669240a2f23..05fdf11a20694834f15c9713f0465120e6472b0a 100644 (file)
@@ -112,8 +112,8 @@ class EmptyDatabaseProvider final : public DatabaseProvider {
 #if ENABLE(INDEXED_DATABASE)
     IDBClient::IDBConnectionToServer& idbConnectionToServerForSession(const SessionID&) final
     {
-        static NeverDestroyed<Ref<InProcessIDBServer>> sharedConnection(InProcessIDBServer::create());
-        return sharedConnection.get()->connectionToServer();
+        static auto& sharedConnection = InProcessIDBServer::create().leakRef();
+        return sharedConnection.connectionToServer();
     }
 #endif
 };
index 8e7892e6b2d1146bd49f4621745d5ca7358b8d3f..aff86992e50c5bc5fd11347ad7d23972c4317eea 100644 (file)
@@ -37,7 +37,6 @@
 #include "SecurityOrigin.h"
 #include "SecurityOriginData.h"
 #include "URL.h"
-#include <wtf/NeverDestroyed.h>
 #include <wtf/StdLibExtras.h>
 #include <wtf/StringExtras.h>
 #include <wtf/UUID.h>
index a6e33a3debdbff108abfe12647300db1926f234e..7d5ab1e1518959e45c44e68a29d2430637904236 100644 (file)
@@ -44,7 +44,6 @@
 #include <heap/HeapInlines.h>
 #include <runtime/JSCellInlines.h>
 #include <runtime/StructureInlines.h>
-#include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
index 910c8e5a9bd6cbc91790cd522c50e0202592796d..09296566e46e99b97f2a48e454689cd6f467bfb4 100644 (file)
@@ -143,18 +143,27 @@ bool NonFastScrollableRegionOverlay::updateRegion()
     return regionChanged;
 }
 
-static HashMap<String, Color>& touchEventRegionColors()
+static const HashMap<String, Color>& touchEventRegionColors()
 {
-    static NeverDestroyed<HashMap<String, Color>> regionColors;
-
-    if (regionColors.get().isEmpty()) {
-        regionColors.get().add("touchstart", Color(191, 191, 63, 80));
-        regionColors.get().add("touchmove", Color(63, 191, 191, 80));
-        regionColors.get().add("touchend", Color(191, 63, 127, 80));
-        regionColors.get().add("touchforcechange", Color(63, 63, 191, 80));
-        regionColors.get().add("wheel", Color(255, 128, 0, 80));
-    }
-    
+    static const auto regionColors = makeNeverDestroyed([] {
+        struct MapEntry {
+            const char* name;
+            int r;
+            int g;
+            int b;
+        };
+        static const MapEntry entries[] = {
+            { "touchstart", 191, 191, 63 },
+            { "touchmove", 63, 191, 191 },
+            { "touchend", 191, 63, 127 },
+            { "touchforcechange", 63, 63, 191 },
+            { "wheel", 255, 128, 0 },
+        };
+        HashMap<String, Color> map;
+        for (auto& entry : entries)
+            map.add(ASCIILiteral { entry.name }, Color { entry.r, entry.g, entry.b, 80 });
+        return map;
+    }());
     return regionColors;
 }
 
index 48a54b73e4754dd50e9b6762a63709c25f312286..5544ab003d1f5adc3731b6313a3233cd538ebded 100644 (file)
@@ -33,7 +33,6 @@
 #include "PerformanceLogging.h"
 #include "ScrollLatchingState.h"
 #include "WheelEventDeltaFilter.h"
-#include <wtf/NeverDestroyed.h>
 
 #if PLATFORM(MAC)
 #include "ServicesOverlayController.h"
index c16f9c04aac1c87ccce6c35f93b965fdca1dbeda..1089db04667e56e24cdc23b401005845f1f7b5f7 100644 (file)
@@ -128,9 +128,7 @@ void releaseMemory(Critical critical, Synchronous synchronous)
         // FastMalloc has lock-free thread specific caches that can only be cleared from the thread itself.
         WorkerThread::releaseFastMallocFreeMemoryInAllThreads();
 #if ENABLE(ASYNC_SCROLLING) && !PLATFORM(IOS)
-        ScrollingThread::dispatch([]() {
-            WTF::releaseFastMallocFreeMemory();
-        });
+        ScrollingThread::dispatch(WTF::releaseFastMallocFreeMemory);
 #endif
         WTF::releaseFastMallocFreeMemory();
     }
index 9e2f02a9351f919b924250eba65c37400aa60f26..3e9d511b29d3a529ae56ddb017f9ae50187b8e2e 100644 (file)
@@ -131,7 +131,7 @@ String NavigatorBase::vendorSub()
 
 bool NavigatorBase::onLine()
 {
-    return networkStateNotifier().onLine();
+    return NetworkStateNotifier::singleton().onLine();
 }
 
 String NavigatorBase::language()
index fbf48d6ce4a6ed49a1c709f25950d333a550f210..c26987f8dcb2e9e9606daa972d2cfcc7becc5fb7 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2015  Apple Inc. All Rights Reserved.
+ * Copyright (C) 2006-2017 Apple Inc. All rights reserved.
  * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
  *
  * This library is free software; you can redistribute it and/or
 
 namespace WebCore {
 
-static HashSet<Page*>* allPages;
+static HashSet<Page*>& allPages()
+{
+    static NeverDestroyed<HashSet<Page*>> set;
+    return set;
+}
+
 static unsigned nonUtilityPageCount { 0 };
 
 static inline bool isUtilityPageChromeClient(ChromeClient& chromeClient)
@@ -148,9 +153,7 @@ DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, pageCounter, ("Page"));
 
 void Page::forEachPage(const WTF::Function<void(Page&)>& function)
 {
-    if (!allPages)
-        return;
-    for (Page* page : *allPages)
+    for (auto* page : allPages())
         function(*page);
 }
 
@@ -163,15 +166,15 @@ void Page::updateValidationBubbleStateIfNeeded()
 static void networkStateChanged(bool isOnLine)
 {
     Vector<Ref<Frame>> frames;
-    
+
     // Get all the frames of all the pages in all the page groups
-    for (auto& page : *allPages) {
+    for (auto* page : allPages()) {
         for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext())
             frames.append(*frame);
         InspectorInstrumentation::networkStateChanged(*page);
     }
 
-    AtomicString eventName = isOnLine ? eventNames().onlineEvent : eventNames().offlineEvent;
+    auto& eventName = isOnLine ? eventNames().onlineEvent : eventNames().offlineEvent;
     for (auto& frame : frames) {
         if (!frame->document())
             continue;
@@ -207,50 +210,16 @@ Page::Page(PageConfiguration&& pageConfiguration)
     , m_performanceLoggingClient(WTFMove(pageConfiguration.performanceLoggingClient))
     , m_webGLStateTracker(WTFMove(pageConfiguration.webGLStateTracker))
     , m_libWebRTCProvider(WTFMove(pageConfiguration.libWebRTCProvider))
-    , m_openedByDOM(false)
-    , m_tabKeyCyclesThroughElements(true)
-    , m_defersLoading(false)
-    , m_defersLoadingCallCount(0)
-    , m_inLowQualityInterpolationMode(false)
-    , m_areMemoryCacheClientCallsEnabled(true)
-    , m_mediaVolume(1)
-    , m_pageScaleFactor(1)
-    , m_zoomedOutPageScaleFactor(0)
-    , m_topContentInset(0)
-#if ENABLE(TEXT_AUTOSIZING)
-    , m_textAutosizingWidth(0)
-#endif
-    , m_suppressScrollbarAnimations(false)
     , m_verticalScrollElasticity(ScrollElasticityAllowed)
     , m_horizontalScrollElasticity(ScrollElasticityAllowed)
-    , m_didLoadUserStyleSheet(false)
-    , m_userStyleSheetModificationTime(0)
-    , m_group(nullptr)
-    , m_debugger(nullptr)
-    , m_canStartMedia(true)
-#if ENABLE(VIEW_MODE_CSS_MEDIA)
-    , m_viewMode(ViewModeWindowed)
-#endif // ENABLE(VIEW_MODE_CSS_MEDIA)
     , m_domTimerAlignmentInterval(DOMTimer::defaultAlignmentInterval())
     , m_domTimerAlignmentIntervalIncreaseTimer(*this, &Page::domTimerAlignmentIntervalIncreaseTimerFired)
-    , m_isEditable(false)
-    , m_isPrerender(false)
     , m_activityState(PageInitialActivityState)
-    , m_requestedLayoutMilestones(0)
-    , m_headerHeight(0)
-    , m_footerHeight(0)
-    , m_isCountingRelevantRepaintedObjects(false)
-#ifndef NDEBUG
-    , m_isPainting(false)
-#endif
     , m_alternativeTextClient(pageConfiguration.alternativeTextClient)
-    , m_scriptedAnimationsSuspended(false)
     , m_consoleClient(std::make_unique<PageConsoleClient>(*this))
 #if ENABLE(REMOTE_INSPECTOR)
     , m_inspectorDebuggable(std::make_unique<PageDebuggable>(*this))
 #endif
-    , m_lastSpatialNavigationCandidatesCount(0) // NOTE: Only called from Internals for Spatial Navigation testing.
-    , m_forbidPromptsDepth(0)
     , m_socketProvider(WTFMove(pageConfiguration.socketProvider))
     , m_applicationCacheStorage(*WTFMove(pageConfiguration.applicationCacheStorage))
     , m_databaseProvider(*WTFMove(pageConfiguration.databaseProvider))
@@ -259,7 +228,6 @@ Page::Page(PageConfiguration&& pageConfiguration)
     , m_userContentProvider(*WTFMove(pageConfiguration.userContentProvider))
     , m_visitedLinkStore(*WTFMove(pageConfiguration.visitedLinkStore))
     , m_sessionID(SessionID::defaultSessionID())
-    , m_isClosing(false)
     , m_isUtilityPage(isUtilityPageChromeClient(chrome().client()))
     , m_performanceMonitor(isUtilityPage() ? nullptr : std::make_unique<PerformanceMonitor>(*this))
     , m_lowPowerModeNotifier(std::make_unique<LowPowerModeNotifier>([this](bool isLowPowerModeEnabled) { handleLowModePowerChange(isLowPowerModeEnabled); }))
@@ -271,14 +239,15 @@ Page::Page(PageConfiguration&& pageConfiguration)
     m_userContentProvider->addPage(*this);
     m_visitedLinkStore->addPage(*this);
 
-    if (!allPages) {
-        allPages = new HashSet<Page*>;
-        
-        networkStateNotifier().addNetworkStateChangeListener(WTF::Function<void (bool)> { networkStateChanged });
+    static bool addedListener;
+    if (!addedListener) {
+        NetworkStateNotifier::singleton().addListener(&networkStateChanged);
+        addedListener = true;
     }
 
-    ASSERT(!allPages->contains(this));
-    allPages->add(this);
+    ASSERT(!allPages().contains(this));
+    allPages().add(this);
+
     if (!isUtilityPage()) {
         ++nonUtilityPageCount;
         MemoryPressureHandler::setPageCount(nonUtilityPageCount);
@@ -307,7 +276,7 @@ Page::~Page()
     m_performanceLoggingClient = nullptr;
     m_mainFrame->setView(nullptr);
     setGroupName(String());
-    allPages->remove(this);
+    allPages().remove(this);
     if (!isUtilityPage()) {
         --nonUtilityPageCount;
         MemoryPressureHandler::setPageCount(nonUtilityPageCount);
@@ -346,11 +315,8 @@ Page::~Page()
 
 void Page::clearPreviousItemFromAllPages(HistoryItem* item)
 {
-    if (!allPages)
-        return;
-
-    for (auto& page : *allPages) {
-        HistoryController& controller = page->mainFrame().loader().history();
+    for (auto* page : allPages()) {
+        auto& controller = page->mainFrame().loader().history();
         if (item == controller.previousItem()) {
             controller.clearPreviousItem();
             return;
@@ -562,9 +528,7 @@ void Page::initGroup()
 
 void Page::updateStyleForAllPagesAfterGlobalChangeInEnvironment()
 {
-    if (!allPages)
-        return;
-    for (auto& page : *allPages) {
+    for (auto* page : allPages()) {
         for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
             // If a change in the global environment has occurred, we need to
             // make sure all the properties a recomputed, therefore we invalidate
@@ -589,12 +553,9 @@ void Page::setNeedsRecalcStyleInAllFrames()
 
 void Page::refreshPlugins(bool reload)
 {
-    if (!allPages)
-        return;
-
     HashSet<PluginInfoProvider*> pluginInfoProviders;
 
-    for (auto& page : *allPages)
+    for (auto* page : allPages())
         pluginInfoProviders.add(&page->pluginInfoProvider());
 
     for (auto& pluginInfoProvider : pluginInfoProviders)
index 478b82317ae2435d79dc64bc5e3e90a3b781bd22..909f37902d33e1d0ef3e5a9b4f64bab4dfa5ff0b 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2010, 2013, 2015 Apple Inc. All rights reserved.
+ * Copyright (C) 2006-2017 Apple Inc. All rights reserved.
  * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
  *
  * This library is free software; you can redistribute it and/or
@@ -683,23 +683,23 @@ private:
 
     int m_subframeCount { 0 };
     String m_groupName;
-    bool m_openedByDOM;
+    bool m_openedByDOM { false };
 
-    bool m_tabKeyCyclesThroughElements;
-    bool m_defersLoading;
-    unsigned m_defersLoadingCallCount;
+    bool m_tabKeyCyclesThroughElements { true };
+    bool m_defersLoading { false };
+    unsigned m_defersLoadingCallCount { 0 };
 
-    bool m_inLowQualityInterpolationMode;
-    bool m_areMemoryCacheClientCallsEnabled;
-    float m_mediaVolume;
+    bool m_inLowQualityInterpolationMode { false };
+    bool m_areMemoryCacheClientCallsEnabled { true };
+    float m_mediaVolume { 1 };
     MediaProducer::MutedStateFlags m_mutedState { MediaProducer::NoneMuted };
 
-    float m_pageScaleFactor;
-    float m_zoomedOutPageScaleFactor;
+    float m_pageScaleFactor { 1 };
+    float m_zoomedOutPageScaleFactor { 0 };
     float m_deviceScaleFactor { 1 };
     float m_viewScaleFactor { 1 };
 
-    float m_topContentInset;
+    float m_topContentInset { 0 };
     FloatBoxExtent m_obscuredInsets;
     FloatBoxExtent m_unobscuredSafeAreaInsets;
 
@@ -708,10 +708,10 @@ private:
 #endif
 
 #if ENABLE(TEXT_AUTOSIZING)
-    float m_textAutosizingWidth;
+    float m_textAutosizingWidth { 0 };
 #endif
     
-    bool m_suppressScrollbarAnimations;
+    bool m_suppressScrollbarAnimations { false };
     
     unsigned m_verticalScrollElasticity : 2; // ScrollElasticity
     unsigned m_horizontalScrollElasticity : 2; // ScrollElasticity    
@@ -721,24 +721,24 @@ private:
 
     String m_userStyleSheetPath;
     mutable String m_userStyleSheet;
-    mutable bool m_didLoadUserStyleSheet;
-    mutable time_t m_userStyleSheetModificationTime;
+    mutable bool m_didLoadUserStyleSheet { false };
+    mutable time_t m_userStyleSheetModificationTime { 0 };
 
     String m_captionUserPreferencesStyleSheet;
 
     std::unique_ptr<PageGroup> m_singlePageGroup;
-    PageGroup* m_group;
+    PageGroup* m_group { nullptr };
 
-    JSC::Debugger* m_debugger;
+    JSC::Debugger* m_debugger { nullptr };
 
-    bool m_canStartMedia;
+    bool m_canStartMedia { true };
 
     RefPtr<StorageNamespace> m_sessionStorage;
     RefPtr<StorageNamespace> m_ephemeralLocalStorage;
 
 #if ENABLE(VIEW_MODE_CSS_MEDIA)
-    ViewMode m_viewMode;
-#endif // ENABLE(VIEW_MODE_CSS_MEDIA)
+    ViewMode m_viewMode { ViewModeWindowed };
+#endif
 
     TimerThrottlingState m_timerThrottlingState { TimerThrottlingState::Disabled };
     MonotonicTime m_timerThrottlingStateLastChangedTime;
@@ -746,26 +746,26 @@ private:
     Timer m_domTimerAlignmentIntervalIncreaseTimer;
     Seconds m_domTimerAlignmentIntervalIncreaseLimit;
 
-    bool m_isEditable;
-    bool m_isPrerender;
+    bool m_isEditable { false };
+    bool m_isPrerender { false };
     ActivityState::Flags m_activityState;
 
-    LayoutMilestones m_requestedLayoutMilestones;
+    LayoutMilestones m_requestedLayoutMilestones { 0 };
 
-    int m_headerHeight;
-    int m_footerHeight;
+    int m_headerHeight { 0 };
+    int m_footerHeight { 0 };
 
     HashSet<RenderObject*> m_relevantUnpaintedRenderObjects;
     Region m_topRelevantPaintedRegion;
     Region m_bottomRelevantPaintedRegion;
     Region m_relevantUnpaintedRegion;
-    bool m_isCountingRelevantRepaintedObjects;
+    bool m_isCountingRelevantRepaintedObjects { false };
 #ifndef NDEBUG
-    bool m_isPainting;
+    bool m_isPainting { false };
 #endif
     AlternativeTextClient* m_alternativeTextClient;
 
-    bool m_scriptedAnimationsSuspended;
+    bool m_scriptedAnimationsSuspended { false };
     const std::unique_ptr<PageConsoleClient> m_consoleClient;
 
 #if ENABLE(REMOTE_INSPECTOR)
@@ -779,8 +779,8 @@ private:
     HashSet<String> m_seenPlugins;
     HashSet<String> m_seenMediaEngines;
 
-    unsigned m_lastSpatialNavigationCandidatesCount;
-    unsigned m_forbidPromptsDepth;
+    unsigned m_lastSpatialNavigationCandidatesCount { 0 };
+    unsigned m_forbidPromptsDepth { 0 };
 
     Ref<SocketProvider> m_socketProvider;
     Ref<ApplicationCacheStorage> m_applicationCacheStorage;
@@ -799,7 +799,7 @@ private:
 
     SessionID m_sessionID;
 
-    bool m_isClosing;
+    bool m_isClosing { false };
 
     MediaProducer::MediaStateFlags m_mediaState { MediaProducer::IsNotPlaying };
     
index 016c9a21eae4328bf38f10ab45de2baae58507ac..ca3610db9ac9d097aee0223dd509f95f4e644382 100644 (file)
@@ -1,5 +1,6 @@
 /*
  * Copyright (C) 2012 Intel 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
 
 #include "Document.h"
 #include "ExceptionCode.h"
-#include "Performance.h"
 #include "PerformanceTiming.h"
-#include <array>
-#include <wtf/MainThread.h>
 #include <wtf/NeverDestroyed.h>
-#include <wtf/dtoa/utils.h>
 
 namespace WebCore {
 
-namespace {
-
-typedef unsigned long long (PerformanceTiming::*NavigationTimingFunction)() const;
+using NavigationTimingFunction = unsigned long long (PerformanceTiming::*)() const;
 
 static NavigationTimingFunction restrictedMarkFunction(const String& markName)
 {
     ASSERT(isMainThread());
 
-    using MapPair = std::pair<ASCIILiteral, NavigationTimingFunction>;
-    static const std::array<MapPair, 21> pairs = { {
-        MapPair { ASCIILiteral("navigationStart"), &PerformanceTiming::navigationStart },
-        MapPair { ASCIILiteral("unloadEventStart"), &PerformanceTiming::unloadEventStart },
-        MapPair { ASCIILiteral("unloadEventEnd"), &PerformanceTiming::unloadEventEnd },
-        MapPair { ASCIILiteral("redirectStart"), &PerformanceTiming::redirectStart },
-        MapPair { ASCIILiteral("redirectEnd"), &PerformanceTiming::redirectEnd },
-        MapPair { ASCIILiteral("fetchStart"), &PerformanceTiming::fetchStart },
-        MapPair { ASCIILiteral("domainLookupStart"), &PerformanceTiming::domainLookupStart },
-        MapPair { ASCIILiteral("domainLookupEnd"), &PerformanceTiming::domainLookupEnd },
-        MapPair { ASCIILiteral("connectStart"), &PerformanceTiming::connectStart },
-        MapPair { ASCIILiteral("connectEnd"), &PerformanceTiming::connectEnd },
-        MapPair { ASCIILiteral("secureConnectionStart"), &PerformanceTiming::secureConnectionStart },
-        MapPair { ASCIILiteral("requestStart"), &PerformanceTiming::requestStart },
-        MapPair { ASCIILiteral("responseStart"), &PerformanceTiming::responseStart },
-        MapPair { ASCIILiteral("responseEnd"), &PerformanceTiming::responseEnd },
-        MapPair { ASCIILiteral("domLoading"), &PerformanceTiming::domLoading },
-        MapPair { ASCIILiteral("domInteractive"), &PerformanceTiming::domInteractive },
-        MapPair { ASCIILiteral("domContentLoadedEventStart"), &PerformanceTiming::domContentLoadedEventStart },
-        MapPair { ASCIILiteral("domContentLoadedEventEnd"), &PerformanceTiming::domContentLoadedEventEnd },
-        MapPair { ASCIILiteral("domComplete"), &PerformanceTiming::domComplete },
-        MapPair { ASCIILiteral("loadEventStart"), &PerformanceTiming::loadEventStart },
-        MapPair { ASCIILiteral("loadEventEnd"), &PerformanceTiming::loadEventEnd },
-    } };
-
-    static NeverDestroyed<HashMap<String, NavigationTimingFunction>> map;
-    if (map.get().isEmpty()) {
+    static const auto map = makeNeverDestroyed([] {
+        static const std::pair<const char*, NavigationTimingFunction> pairs[] = {
+            { "connectEnd", &PerformanceTiming::connectEnd },
+            { "connectStart", &PerformanceTiming::connectStart },
+            { "domComplete", &PerformanceTiming::domComplete },
+            { "domContentLoadedEventEnd", &PerformanceTiming::domContentLoadedEventEnd },
+            { "domContentLoadedEventStart", &PerformanceTiming::domContentLoadedEventStart },
+            { "domInteractive", &PerformanceTiming::domInteractive },
+            { "domLoading", &PerformanceTiming::domLoading },
+            { "domainLookupEnd", &PerformanceTiming::domainLookupEnd },
+            { "domainLookupStart", &PerformanceTiming::domainLookupStart },
+            { "fetchStart", &PerformanceTiming::fetchStart },
+            { "loadEventEnd", &PerformanceTiming::loadEventEnd },
+            { "loadEventStart", &PerformanceTiming::loadEventStart },
+            { "navigationStart", &PerformanceTiming::navigationStart },
+            { "redirectEnd", &PerformanceTiming::redirectEnd },
+            { "redirectStart", &PerformanceTiming::redirectStart },
+            { "requestStart", &PerformanceTiming::requestStart },
+            { "responseEnd", &PerformanceTiming::responseEnd },
+            { "responseStart", &PerformanceTiming::responseStart },
+            { "secureConnectionStart", &PerformanceTiming::secureConnectionStart },
+            { "unloadEventEnd", &PerformanceTiming::unloadEventEnd },
+            { "unloadEventStart", &PerformanceTiming::unloadEventStart },
+        };
+        HashMap<String, NavigationTimingFunction> map;
         for (auto& pair : pairs)
-            map.get().add(pair.first, pair.second);
-    }
+            map.add(ASCIILiteral { pair.first }, pair.second);
+        return map;
+    }());
 
     return map.get().get(markName);
 }
 
-} // namespace anonymous
-
 UserTiming::UserTiming(Performance& performance)
     : m_performance(performance)
 {
 }
 
-static void clearPerformanceEntries(PerformanceEntryMap& performanceEntryMap, const String& name)
+static void clearPerformanceEntries(PerformanceEntryMap& map, const String& name)
 {
-    if (name.isNull()) {
-        performanceEntryMap.clear();
-        return;
-    }
-
-    performanceEntryMap.remove(name);
+    if (name.isNull())
+        map.clear();
+    else
+        map.remove(name);
 }
 
 ExceptionOr<Ref<PerformanceMark>> UserTiming::mark(const String& markName)
 {
-    if (is<Document>(m_performance.scriptExecutionContext())) {
-        if (restrictedMarkFunction(markName))
-            return Exception { SYNTAX_ERR };
-    }
+    if (is<Document>(m_performance.scriptExecutionContext()) && restrictedMarkFunction(markName))
+        return Exception { SYNTAX_ERR };
 
     auto& performanceEntryList = m_marksMap.ensure(markName, [] { return Vector<RefPtr<PerformanceEntry>>(); }).iterator->value;
     auto entry = PerformanceMark::create(markName, m_performance.now());
@@ -118,15 +106,16 @@ void UserTiming::clearMarks(const String& markName)
 
 ExceptionOr<double> UserTiming::findExistingMarkStartTime(const String& markName)
 {
-    if (m_marksMap.contains(markName))
-        return m_marksMap.get(markName).last()->startTime();
+    auto iterator = m_marksMap.find(markName);
+    if (iterator != m_marksMap.end())
+        return iterator->value.last()->startTime();
 
-    PerformanceTiming* timing = m_performance.timing();
+    auto* timing = m_performance.timing();
     if (!timing)
         return Exception { SYNTAX_ERR, makeString("No mark named '", markName, "' exists") };
 
     if (auto function = restrictedMarkFunction(markName)) {
-        double value = static_cast<double>(((*timing).*(function))());
+        double value = ((*timing).*(function))();
         if (!value)
             return Exception { INVALID_ACCESS_ERR };
         return value - timing->navigationStart();
@@ -170,19 +159,14 @@ void UserTiming::clearMeasures(const String& measureName)
     clearPerformanceEntries(m_measuresMap, measureName);
 }
 
-static Vector<RefPtr<PerformanceEntry>> convertToEntrySequence(const PerformanceEntryMap& performanceEntryMap)
+static Vector<RefPtr<PerformanceEntry>> convertToEntrySequence(const PerformanceEntryMap& map)
 {
     Vector<RefPtr<PerformanceEntry>> entries;
-    for (auto& entry : performanceEntryMap.values())
+    for (auto& entry : map.values())
         entries.appendVector(entry);
     return entries;
 }
 
-static Vector<RefPtr<PerformanceEntry>> getEntrySequenceByName(const PerformanceEntryMap& performanceEntryMap, const String& name)
-{
-    return performanceEntryMap.get(name);
-}
-
 Vector<RefPtr<PerformanceEntry>> UserTiming::getMarks() const
 {
     return convertToEntrySequence(m_marksMap);
@@ -190,7 +174,7 @@ Vector<RefPtr<PerformanceEntry>> UserTiming::getMarks() const
 
 Vector<RefPtr<PerformanceEntry>> UserTiming::getMarks(const String& name) const
 {
-    return getEntrySequenceByName(m_marksMap, name);
+    return m_marksMap.get(name);
 }
 
 Vector<RefPtr<PerformanceEntry>> UserTiming::getMeasures() const
@@ -200,7 +184,7 @@ Vector<RefPtr<PerformanceEntry>> UserTiming::getMeasures() const
 
 Vector<RefPtr<PerformanceEntry>> UserTiming::getMeasures(const String& name) const
 {
-    return getEntrySequenceByName(m_measuresMap, name);
+    return m_measuresMap.get(name);
 }
 
 } // namespace WebCore
index 88202310263c1619c46a8cca6ad7d837c985ddd4..a5b78cd7ce812d9cea0e53572466da847e46b5f8 100644 (file)
@@ -34,6 +34,7 @@
 
 #include "MediaPlayer.h"
 #include "WebSocket.h"
+#include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
index 35c80377c4e8afe26e7be5879e29b39d85ce4983..e2d5fba6c2c7e28d8c5242f3227a5d12285137ed 100644 (file)
@@ -32,7 +32,8 @@
 #pragma once
 
 #include "PlatformExportMacros.h"
-#include <wtf/NeverDestroyed.h>
+#include <wtf/Forward.h>
+#include <wtf/Noncopyable.h>
 
 namespace WebCore {
 
index e424502c9e9ba570408fcba4e030b8507e2f436f..cc42c794ec26904ef4f10f45cc65935dc0e218fa 100644 (file)
@@ -30,7 +30,6 @@
 #include "IntSize.h"
 #include "NotImplemented.h"
 #include <wtf/MathExtras.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/text/TextBreakIterator.h>
 #include <wtf/unicode/CharacterNames.h>
 
@@ -1015,6 +1014,4 @@ String webCryptoMasterKeyKeychainComment()
 
 #endif
 
-
-
 } // namespace WebCore
index 925728b67781000d47fbd25c4635b7c5f2f8c3b3..a2a4d038d5d8e6b4ab5e14925cf46ca5a8933a6e 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2017 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/)
  *
  * Redistribution and use in source and binary forms, with or without
 
 namespace WebCore {
 
-namespace {
-struct TypeExtensionPair {
-    const char* type;
-    const char* extension;
-};
-}
-
-// A table of common media MIME types and file extenstions used when a platform's
-// specific MIME type lookup doesn't have a match for a media file extension.
-static const TypeExtensionPair commonMediaTypes[] = {
-
-    // Ogg
-    { "application/ogg", "ogx" },
-    { "audio/ogg", "ogg" },
-    { "audio/ogg", "oga" },
-    { "video/ogg", "ogv" },
-
-    // Annodex
-    { "application/annodex", "anx" },
-    { "audio/annodex", "axa" },
-    { "video/annodex", "axv" },
-    { "audio/speex", "spx" },
-
-    // WebM
-    { "video/webm", "webm" },
-    { "audio/webm", "webm" },
-
-    // MPEG
-    { "audio/mpeg", "m1a" },
-    { "audio/mpeg", "m2a" },
-    { "audio/mpeg", "m1s" },
-    { "audio/mpeg", "mpa" },
-    { "video/mpeg", "mpg" },
-    { "video/mpeg", "m15" },
-    { "video/mpeg", "m1s" },
-    { "video/mpeg", "m1v" },
-    { "video/mpeg", "m75" },
-    { "video/mpeg", "mpa" },
-    { "video/mpeg", "mpeg" },
-    { "video/mpeg", "mpm" },
-    { "video/mpeg", "mpv" },
-
-    // MPEG playlist
-    { "application/vnd.apple.mpegurl", "m3u8" },
-    { "application/mpegurl", "m3u8" },
-    { "application/x-mpegurl", "m3u8" },
-    { "audio/mpegurl", "m3url" },
-    { "audio/x-mpegurl", "m3url" },
-    { "audio/mpegurl", "m3u" },
-    { "audio/x-mpegurl", "m3u" },
-
-    // MPEG-4
-    { "video/x-m4v", "m4v" },
-    { "audio/x-m4a", "m4a" },
-    { "audio/x-m4b", "m4b" },
-    { "audio/x-m4p", "m4p" },
-    { "audio/mp4", "m4a" },
-
-    // MP3
-    { "audio/mp3", "mp3" },
-    { "audio/x-mp3", "mp3" },
-    { "audio/x-mpeg", "mp3" },
-
-    // MPEG-2
-    { "video/x-mpeg2", "mp2" },
-    { "video/mpeg2", "vob" },
-    { "video/mpeg2", "mod" },
-    { "video/m2ts", "m2ts" },
-    { "video/x-m2ts", "m2t" },
-    { "video/x-m2ts", "ts" },
-
-    // 3GP/3GP2
-    { "audio/3gpp", "3gpp" }, 
-    { "audio/3gpp2", "3g2" }, 
-    { "application/x-mpeg", "amc" },
-
-    // AAC
-    { "audio/aac", "aac" },
-    { "audio/aac", "adts" },
-    { "audio/x-aac", "m4r" },
-
-    // CoreAudio File
-    { "audio/x-caf", "caf" },
-    { "audio/x-gsm", "gsm" },
-
-    // ADPCM
-    { "audio/x-wav", "wav" },
-    { "audio/vnd.wave", "wav" }
-};
-
 static HashSet<String, ASCIICaseInsensitiveHash>* supportedImageResourceMIMETypes;
 static HashSet<String, ASCIICaseInsensitiveHash>* supportedImageMIMETypes;
 static HashSet<String, ASCIICaseInsensitiveHash>* supportedImageMIMETypesForEncoding;
@@ -153,8 +63,6 @@ static HashSet<String, ASCIICaseInsensitiveHash>* pdfMIMETypes;
 static HashSet<String, ASCIICaseInsensitiveHash>* pdfAndPostScriptMIMETypes;
 static HashSet<String, ASCIICaseInsensitiveHash>* unsupportedTextMIMETypes;
 
-typedef HashMap<String, Vector<String>*, ASCIICaseInsensitiveHash> MediaMIMETypeMap;
-    
 static void initializeSupportedImageMIMETypes()
 {
 #if USE(CG)
@@ -196,7 +104,7 @@ static void initializeSupportedImageMIMETypes()
     // This can be removed when Mail addresses:
     // <rdar://problem/7879510> Mail should use standard image mimetypes 
     // and we fix sniffing so that it corrects items such as image/jpg -> image/jpeg.
-    static const char* malformedMIMETypes[] = {
+    static const char* const malformedMIMETypes[] = {
         // JPEG (image/jpeg)
         "image/jpg", "image/jp_", "image/jpe_", "application/jpg", "application/x-jpg", "image/pipeg",
         "image/vnd.switfview-jpeg", "image/x-xbitmap",
@@ -220,7 +128,7 @@ static void initializeSupportedImageMIMETypes()
 #else
     // assume that all implementations at least support the following standard
     // image types:
-    static const char* types[] = {
+    static const char* const types[] = {
         "image/jpeg",
         "image/png",
         "image/gif",
@@ -277,7 +185,7 @@ static void initializeSupportedImageMIMETypesForEncoding()
 static void initializeSupportedJavaScriptMIMETypes()
 {
     // https://html.spec.whatwg.org/multipage/scripting.html#javascript-mime-type
-    static const char* types[] = {
+    static const char* const types[] = {
         "text/javascript",
         "text/ecmascript",
         "application/javascript",
@@ -316,7 +224,7 @@ static void initializePostScriptMIMETypes()
 
 static void initializeSupportedNonImageMimeTypes()
 {
-    static const char* types[] = {
+    static const char* const types[] = {
         "text/html",
         "text/xml",
         "text/xsl",
@@ -347,65 +255,135 @@ static void initializeSupportedNonImageMimeTypes()
 #endif
 }
 
-static MediaMIMETypeMap& mediaMIMETypeMap()
-{
-    static NeverDestroyed<MediaMIMETypeMap> mediaMIMETypeForExtensionMap;
-
-    if (!mediaMIMETypeForExtensionMap.get().isEmpty())
-        return mediaMIMETypeForExtensionMap;
-
-    const unsigned numPairs = sizeof(commonMediaTypes) / sizeof(commonMediaTypes[0]);
-    for (unsigned ndx = 0; ndx < numPairs; ++ndx) {
-
-        if (mediaMIMETypeForExtensionMap.get().contains(commonMediaTypes[ndx].extension))
-            mediaMIMETypeForExtensionMap.get().get(commonMediaTypes[ndx].extension)->append(commonMediaTypes[ndx].type);
-        else {
-            Vector<String>* synonyms = new Vector<String>;
-
-            // If there is a system specific type for this extension, add it as the first type so
-            // getMediaMIMETypeForExtension will always return it.
-            String systemType = MIMETypeRegistry::getMIMETypeForExtension(commonMediaTypes[ndx].extension);
-            if (!systemType.isEmpty() && commonMediaTypes[ndx].type != systemType)
-                synonyms->append(systemType);
-            synonyms->append(commonMediaTypes[ndx].type);
-            mediaMIMETypeForExtensionMap.get().add(commonMediaTypes[ndx].extension, synonyms);
+static const Vector<String>* typesForCommonExtension(const String& extension)
+{
+    static const auto map = makeNeverDestroyed([] {
+        struct TypeExtensionPair {
+            const char* type;
+            const char* extension;
+        };
+
+        // A table of common media MIME types and file extentions used when a platform's
+        // specific MIME type lookup doesn't have a match for a media file extension.
+        static const TypeExtensionPair commonMediaTypes[] = {
+            // Ogg
+            { "application/ogg", "ogx" },
+            { "audio/ogg", "ogg" },
+            { "audio/ogg", "oga" },
+            { "video/ogg", "ogv" },
+
+            // Annodex
+            { "application/annodex", "anx" },
+            { "audio/annodex", "axa" },
+            { "video/annodex", "axv" },
+            { "audio/speex", "spx" },
+
+            // WebM
+            { "video/webm", "webm" },
+            { "audio/webm", "webm" },
+
+            // MPEG
+            { "audio/mpeg", "m1a" },
+            { "audio/mpeg", "m2a" },
+            { "audio/mpeg", "m1s" },
+            { "audio/mpeg", "mpa" },
+            { "video/mpeg", "mpg" },
+            { "video/mpeg", "m15" },
+            { "video/mpeg", "m1s" },
+            { "video/mpeg", "m1v" },
+            { "video/mpeg", "m75" },
+            { "video/mpeg", "mpa" },
+            { "video/mpeg", "mpeg" },
+            { "video/mpeg", "mpm" },
+            { "video/mpeg", "mpv" },
+
+            // MPEG playlist
+            { "application/vnd.apple.mpegurl", "m3u8" },
+            { "application/mpegurl", "m3u8" },
+            { "application/x-mpegurl", "m3u8" },
+            { "audio/mpegurl", "m3url" },
+            { "audio/x-mpegurl", "m3url" },
+            { "audio/mpegurl", "m3u" },
+            { "audio/x-mpegurl", "m3u" },
+
+            // MPEG-4
+            { "video/x-m4v", "m4v" },
+            { "audio/x-m4a", "m4a" },
+            { "audio/x-m4b", "m4b" },
+            { "audio/x-m4p", "m4p" },
+            { "audio/mp4", "m4a" },
+
+            // MP3
+            { "audio/mp3", "mp3" },
+            { "audio/x-mp3", "mp3" },
+            { "audio/x-mpeg", "mp3" },
+
+            // MPEG-2
+            { "video/x-mpeg2", "mp2" },
+            { "video/mpeg2", "vob" },
+            { "video/mpeg2", "mod" },
+            { "video/m2ts", "m2ts" },
+            { "video/x-m2ts", "m2t" },
+            { "video/x-m2ts", "ts" },
+
+            // 3GP/3GP2
+            { "audio/3gpp", "3gpp" },
+            { "audio/3gpp2", "3g2" },
+            { "application/x-mpeg", "amc" },
+
+            // AAC
+            { "audio/aac", "aac" },
+            { "audio/aac", "adts" },
+            { "audio/x-aac", "m4r" },
+
+            // CoreAudio File
+            { "audio/x-caf", "caf" },
+            { "audio/x-gsm", "gsm" },
+
+            // ADPCM
+            { "audio/x-wav", "wav" },
+            { "audio/vnd.wave", "wav" },
+        };
+
+        HashMap<String, Vector<String>, ASCIICaseInsensitiveHash> map;
+        for (auto& pair : commonMediaTypes) {
+            const char* type = pair.type;
+            const char* extension = pair.extension;
+            map.ensure(ASCIILiteral { extension }, [type, extension] {
+                // First type in the vector must always be the one from getMIMETypeForExtension,
+                // so we can use the map without also calling getMIMETypeForExtension each time.
+                Vector<String> synonyms;
+                String systemType = MIMETypeRegistry::getMIMETypeForExtension(extension);
+                if (!systemType.isEmpty() && type != systemType)
+                    synonyms.append(systemType);
+                return synonyms;
+            }).iterator->value.append(ASCIILiteral { type });
         }
-    }
-
-    return mediaMIMETypeForExtensionMap;
+        return map;
+    }());
+    auto mapEntry = map.get().find(extension);
+    if (mapEntry == map.get().end())
+        return nullptr;
+    return &mapEntry->value;
 }
 
-String MIMETypeRegistry::getMediaMIMETypeForExtension(const String& ext)
+String MIMETypeRegistry::getMediaMIMETypeForExtension(const String& extension)
 {
-    // Look in the system-specific registry first.
-    String type = getMIMETypeForExtension(ext);
-    if (!type.isEmpty())
-        return type;
-
-    Vector<String>* typeList = mediaMIMETypeMap().get(ext);
-    if (typeList)
-        return (*typeList)[0];
-    
-    return String();
+    auto* vector = typesForCommonExtension(extension);
+    if (vector)
+        return (*vector)[0];
+    return getMIMETypeForExtension(extension);
 }
-    
-Vector<String> MIMETypeRegistry::getMediaMIMETypesForExtension(const String& ext)
-{
-    Vector<String>* typeList = mediaMIMETypeMap().get(ext);
-    if (typeList)
-        return *typeList;
 
-    // Only need to look in the system-specific registry if mediaMIMETypeMap() doesn't contain
-    // the extension at all, because it always contains the system-specific type if the
-    // extension is in the static mapping table.
-    String type = getMIMETypeForExtension(ext);
-    if (!type.isEmpty()) {
-        Vector<String> typeList;
-        typeList.append(type);
-        return typeList;
-    }
-    
-    return Vector<String>();
+Vector<String> MIMETypeRegistry::getMediaMIMETypesForExtension(const String& extension)
+{
+    auto* vector = typesForCommonExtension(extension);
+    if (vector)
+        return *vector;
+    String type = getMIMETypeForExtension(extension);
+    if (!type.isNull())
+        return { { type } };
+    return { };
 }
 
 static void initializeSupportedMediaMIMETypes()
@@ -418,7 +396,7 @@ static void initializeSupportedMediaMIMETypes()
 
 static void initializeUnsupportedTextMIMETypes()
 {
-    static const char* types[] = {
+    static const char* const types[] = {
         "text/calendar",
         "text/x-calendar",
         "text/x-vcalendar",
@@ -438,7 +416,7 @@ static void initializeUnsupportedTextMIMETypes()
 #endif
     };
     for (auto& type : types)
-        unsupportedTextMIMETypes->add(type);
+        unsupportedTextMIMETypes->add(ASCIILiteral { type });
 }
 
 static void initializeMIMETypeRegistry()
index 68ff043897bbca9339bf23dc4dd13c5204ce30e2..79233503aa75d22e87009eeeecef56acc4a1ed03 100644 (file)
@@ -26,6 +26,8 @@
 #include "config.h"
 #include "MainThreadSharedTimer.h"
 
+#include <wtf/NeverDestroyed.h>
+
 namespace WebCore {
 
 MainThreadSharedTimer& MainThreadSharedTimer::singleton()
index 94a190d37799f2946cd56e97d903f7c85d564ff1..05bde476ba5f33c25a0db2b00d398703bf9b32f7 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Copyright (C) 2015 Igalia S.L.
- * Copyright (C) 2006-2016 Apple Inc.  All rights reserved.
+ * Copyright (C) 2006-2016 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef MainThreadSharedTimer_h
-#define MainThreadSharedTimer_h
+#pragma once
 
 #include "SharedTimer.h"
-#include <wtf/NeverDestroyed.h>
+#include <wtf/Forward.h>
 
 #if PLATFORM(GTK) || PLATFORM(WPE)
 #include <wtf/RunLoop.h>
@@ -60,5 +59,3 @@ private:
 };
 
 } // namespace WebCore
-
-#endif // MainThreadSharedTimer
index 60761580af4f0b128445c9e05c927fbc40869b99..9d48421fc521b7eeeec67c77527acafa451ba404 100644 (file)
@@ -39,6 +39,8 @@
 
 namespace WebCore {
 
+// FIXME: URLSchemesMap is a peculiar type name given that it is a set.
+
 static const URLSchemesMap& builtinLocalURLSchemes();
 static const Vector<String>& builtinSecureSchemes();
 static const Vector<String>& builtinSchemesWithUniqueOrigins();
@@ -46,61 +48,72 @@ static const Vector<String>& builtinEmptyDocumentSchemes();
 static const Vector<String>& builtinCanDisplayOnlyIfCanRequestSchemes();
 static const Vector<String>& builtinCORSEnabledSchemes();
 
+using StringVectorFunction = const Vector<String>& (*)();
+
+static void add(URLSchemesMap& set, StringVectorFunction function)
+{
+    for (auto& scheme : function())
+        set.add(scheme);
+}
+
+static NeverDestroyed<URLSchemesMap> makeNeverDestroyedSchemeSet(const Vector<String>& (*function)())
+{
+    URLSchemesMap set;
+    add(set, function);
+    return set;
+}
+
 static const URLSchemesMap& allBuiltinSchemes()
 {
-    static NeverDestroyed<URLSchemesMap> schemes;
-    if (schemes.get().isEmpty()) {
-        for (const auto& scheme : builtinLocalURLSchemes())
-            schemes.get().add(scheme);
-        for (const auto& scheme : builtinSecureSchemes())
-            schemes.get().add(scheme);
-        for (const auto& scheme : builtinSchemesWithUniqueOrigins())
-            schemes.get().add(scheme);
-        for (const auto& scheme : builtinEmptyDocumentSchemes())
-            schemes.get().add(scheme);
-        for (const auto& scheme : builtinCanDisplayOnlyIfCanRequestSchemes())
-            schemes.get().add(scheme);
-        for (const auto& scheme : builtinCORSEnabledSchemes())
-            schemes.get().add(scheme);
+    static const auto schemes = makeNeverDestroyed([] {
+        static const StringVectorFunction functions[] {
+            builtinSecureSchemes,
+            builtinSchemesWithUniqueOrigins,
+            builtinEmptyDocumentSchemes,
+            builtinCanDisplayOnlyIfCanRequestSchemes,
+            builtinCORSEnabledSchemes,
+        };
 
         // Other misc schemes that the SchemeRegistry doesn't know about.
-        schemes.get().add("webkit-fake-url");
+        static const char* const otherSchemes[] = {
+            "webkit-fake-url",
 #if PLATFORM(MAC)
-        schemes.get().add("safari-extension");
+            "safari-extension",
 #endif
 #if USE(QUICK_LOOK)
-        schemes.get().add(QLPreviewProtocol());
+            QLPreviewProtocol(),
 #endif
 #if ENABLE(CONTENT_FILTERING)
-        schemes.get().add(ContentFilter::urlScheme());
+            ContentFilter::urlScheme(),
 #endif
-    }
-
+        };
+
+        URLSchemesMap set;
+        for (auto& scheme : builtinLocalURLSchemes())
+            set.add(scheme);
+        for (auto& function : functions)
+            add(set, function);
+        for (auto& scheme : otherSchemes)
+            set.add(scheme);
+        return set;
+    }());
     return schemes;
 }
 
-const URLSchemesMap& builtinLocalURLSchemes()
+static const URLSchemesMap& builtinLocalURLSchemes()
 {
-    static NeverDestroyed<URLSchemesMap> schemes;
-    if (schemes.get().isEmpty()) {
-        schemes.get().add("file");
+    static const auto schemes = makeNeverDestroyed(URLSchemesMap {
+        "file",
 #if PLATFORM(COCOA)
-        schemes.get().add("applewebdata");
+        "applewebdata",
 #endif
-    }
-
+    });
     return schemes;
 }
 
 static URLSchemesMap& localURLSchemes()
 {
-    static NeverDestroyed<URLSchemesMap> localSchemes;
-
-    if (localSchemes.get().isEmpty()) {
-        for (const auto& scheme : builtinLocalURLSchemes())
-            localSchemes.get().add(scheme);
-    }
-
+    static NeverDestroyed<URLSchemesMap> localSchemes = builtinLocalURLSchemes();
     return localSchemes;
 }
 
@@ -112,109 +125,69 @@ static URLSchemesMap& displayIsolatedURLSchemes()
 
 const Vector<String>& builtinSecureSchemes()
 {
-    static NeverDestroyed<Vector<String>> schemes;
-    if (schemes.get().isEmpty()) {
-        schemes.get().append("https");
-        schemes.get().append("about");
-        schemes.get().append("data");
-        schemes.get().append("wss");
+    static const auto schemes = makeNeverDestroyed(Vector<String> {
+        "https",
+        "about",
+        "data",
+        "wss",
 #if PLATFORM(GTK) || PLATFORM(WPE)
-        schemes.get().append("resource");
+        "resource",
 #endif
-        schemes.get().shrinkToFit();
-    }
-
+    });
     return schemes;
 }
 
 static URLSchemesMap& secureSchemes()
 {
-    static NeverDestroyed<URLSchemesMap> secureSchemes;
-
-    if (secureSchemes.get().isEmpty()) {
-        for (const auto& scheme : builtinSecureSchemes())
-            secureSchemes.get().add(scheme);
-    }
-
+    static auto secureSchemes = makeNeverDestroyedSchemeSet(builtinSecureSchemes);
     return secureSchemes;
 }
 
 const Vector<String>& builtinSchemesWithUniqueOrigins()
 {
-    static NeverDestroyed<Vector<String>> schemes;
-    if (schemes.get().isEmpty()) {
-        schemes.get().append("about");
-        schemes.get().append("javascript");
-        // This is a willful violation of HTML5.
+    static const auto schemes = makeNeverDestroyed(Vector<String> {
+        "about",
+        "javascript",
+        // This is an intentional difference from the behavior the HTML specification calls for.
         // See https://bugs.webkit.org/show_bug.cgi?id=11885
-        schemes.get().append("data");
-        schemes.get().shrinkToFit();
-    }
-
+        "data",
+    });
     return schemes;
 }
 
 static URLSchemesMap& schemesWithUniqueOrigins()
 {
-    static NeverDestroyed<URLSchemesMap> schemesWithUniqueOrigins;
-
-    if (schemesWithUniqueOrigins.get().isEmpty()) {
-        for (const auto& scheme : builtinSchemesWithUniqueOrigins())
-            schemesWithUniqueOrigins.get().add(scheme);
-    }
-
+    static auto schemesWithUniqueOrigins = makeNeverDestroyedSchemeSet(builtinSchemesWithUniqueOrigins);
     return schemesWithUniqueOrigins;
 }
 
 const Vector<String>& builtinEmptyDocumentSchemes()
 {
-    static NeverDestroyed<Vector<String>> schemes;
-    if (schemes.get().isEmpty()) {
-        schemes.get().append("about");
-        schemes.get().shrinkToFit();
-    }
-
+    static const auto schemes = makeNeverDestroyed(Vector<String> { "about" });
     return schemes;
 }
 
 static URLSchemesMap& emptyDocumentSchemes()
 {
-    static NeverDestroyed<URLSchemesMap> emptyDocumentSchemes;
-
-    if (emptyDocumentSchemes.get().isEmpty()) {
-        for (const auto& scheme : builtinEmptyDocumentSchemes())
-            emptyDocumentSchemes.get().add(scheme);
-    }
-
+    static auto emptyDocumentSchemes = makeNeverDestroyedSchemeSet(builtinEmptyDocumentSchemes);
     return emptyDocumentSchemes;
 }
 
-static HashSet<String, ASCIICaseInsensitiveHash>& schemesForbiddenFromDomainRelaxation()
+static URLSchemesMap& schemesForbiddenFromDomainRelaxation()
 {
-    static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> schemes;
+    static NeverDestroyed<URLSchemesMap> schemes;
     return schemes;
 }
 
 const Vector<String>& builtinCanDisplayOnlyIfCanRequestSchemes()
 {
-    static NeverDestroyed<Vector<String>> schemes;
-    if (schemes.get().isEmpty()) {
-        schemes.get().append("blob");
-        schemes.get().shrinkToFit();
-    }
-
+    static const auto schemes = makeNeverDestroyed(Vector<String> { "blob" });
     return schemes;
 }
 
 static URLSchemesMap& canDisplayOnlyIfCanRequestSchemes()
 {
-    static NeverDestroyed<URLSchemesMap> canDisplayOnlyIfCanRequestSchemes;
-
-    if (canDisplayOnlyIfCanRequestSchemes.get().isEmpty()) {
-        for (const auto& scheme : builtinCanDisplayOnlyIfCanRequestSchemes())
-            canDisplayOnlyIfCanRequestSchemes.get().add(scheme);
-    }
-
+    static auto canDisplayOnlyIfCanRequestSchemes = makeNeverDestroyedSchemeSet(builtinCanDisplayOnlyIfCanRequestSchemes);
     return canDisplayOnlyIfCanRequestSchemes;
 }
 
@@ -256,27 +229,15 @@ static URLSchemesMap& schemesAllowingDatabaseAccessInPrivateBrowsing()
 
 const Vector<String>& builtinCORSEnabledSchemes()
 {
-    static NeverDestroyed<Vector<String>> schemes;
-    if (schemes.get().isEmpty()) {
-        schemes.get().append("http");
-        schemes.get().append("https");
-        schemes.get().shrinkToFit();
-    }
-
+    static const auto schemes = makeNeverDestroyed(Vector<String> { "http", "https" });
     return schemes;
 }
 
 static URLSchemesMap& CORSEnabledSchemes()
 {
     // FIXME: http://bugs.webkit.org/show_bug.cgi?id=77160
-    static NeverDestroyed<URLSchemesMap> CORSEnabledSchemes;
-
-    if (CORSEnabledSchemes.get().isEmpty()) {
-        for (const auto& scheme : builtinCORSEnabledSchemes())
-            CORSEnabledSchemes.get().add(scheme);
-    }
-
-    return CORSEnabledSchemes;
+    static auto schemes = makeNeverDestroyedSchemeSet(builtinCORSEnabledSchemes);
+    return schemes;
 }
 
 static URLSchemesMap& ContentSecurityPolicyBypassingSchemes()
@@ -299,62 +260,60 @@ static URLSchemesMap& alwaysRevalidatedSchemes()
 
 bool SchemeRegistry::shouldTreatURLSchemeAsLocal(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return localURLSchemes().contains(scheme);
+    return !scheme.isNull() && localURLSchemes().contains(scheme);
 }
 
 void SchemeRegistry::registerURLSchemeAsNoAccess(const String& scheme)
 {
+    if (scheme.isNull())
+        return;
     schemesWithUniqueOrigins().add(scheme);
 }
 
 bool SchemeRegistry::shouldTreatURLSchemeAsNoAccess(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return schemesWithUniqueOrigins().contains(scheme);
+    return !scheme.isNull() && schemesWithUniqueOrigins().contains(scheme);
 }
 
 void SchemeRegistry::registerURLSchemeAsDisplayIsolated(const String& scheme)
 {
+    if (scheme.isNull())
+        return;
     displayIsolatedURLSchemes().add(scheme);
 }
 
 bool SchemeRegistry::shouldTreatURLSchemeAsDisplayIsolated(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return displayIsolatedURLSchemes().contains(scheme);
+    return !scheme.isNull() && displayIsolatedURLSchemes().contains(scheme);
 }
 
 void SchemeRegistry::registerURLSchemeAsSecure(const String& scheme)
 {
+    if (scheme.isNull())
+        return;
     secureSchemes().add(scheme);
 }
 
 bool SchemeRegistry::shouldTreatURLSchemeAsSecure(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return secureSchemes().contains(scheme);
+    return !scheme.isNull() && secureSchemes().contains(scheme);
 }
 
 void SchemeRegistry::registerURLSchemeAsEmptyDocument(const String& scheme)
 {
+    if (scheme.isNull())
+        return;
     emptyDocumentSchemes().add(scheme);
 }
 
 bool SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return emptyDocumentSchemes().contains(scheme);
+    return !scheme.isNull() && emptyDocumentSchemes().contains(scheme);
 }
 
 void SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(bool forbidden, const String& scheme)
 {
-    if (scheme.isEmpty())
+    if (scheme.isNull())
         return;
 
     if (forbidden)
@@ -365,125 +324,126 @@ void SchemeRegistry::setDomainRelaxationForbiddenForURLScheme(bool forbidden, co
 
 bool SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return schemesForbiddenFromDomainRelaxation().contains(scheme);
+    return !scheme.isNull() && schemesForbiddenFromDomainRelaxation().contains(scheme);
 }
 
 bool SchemeRegistry::canDisplayOnlyIfCanRequest(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return canDisplayOnlyIfCanRequestSchemes().contains(scheme);
+    return !scheme.isNull() && canDisplayOnlyIfCanRequestSchemes().contains(scheme);
 }
 
 void SchemeRegistry::registerAsCanDisplayOnlyIfCanRequest(const String& scheme)
 {
+    if (scheme.isNull())
+        return;
     canDisplayOnlyIfCanRequestSchemes().add(scheme);
 }
 
 void SchemeRegistry::registerURLSchemeAsNotAllowingJavascriptURLs(const String& scheme)
 {
+    if (scheme.isNull())
+        return;
     notAllowingJavascriptURLsSchemes().add(scheme);
 }
 
 bool SchemeRegistry::shouldTreatURLSchemeAsNotAllowingJavascriptURLs(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return notAllowingJavascriptURLsSchemes().contains(scheme);
+    return !scheme.isNull() && notAllowingJavascriptURLsSchemes().contains(scheme);
 }
 
 void SchemeRegistry::registerURLSchemeAsAllowingLocalStorageAccessInPrivateBrowsing(const String& scheme)
 {
+    if (scheme.isNull())
+        return;
     schemesAllowingLocalStorageAccessInPrivateBrowsing().add(scheme);
 }
 
 bool SchemeRegistry::allowsLocalStorageAccessInPrivateBrowsing(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return schemesAllowingLocalStorageAccessInPrivateBrowsing().contains(scheme);
+    return !scheme.isNull() && schemesAllowingLocalStorageAccessInPrivateBrowsing().contains(scheme);
 }
 
 void SchemeRegistry::registerURLSchemeAsAllowingDatabaseAccessInPrivateBrowsing(const String& scheme)
 {
+    if (scheme.isNull())
+        return;
     schemesAllowingDatabaseAccessInPrivateBrowsing().add(scheme);
 }
 
 bool SchemeRegistry::allowsDatabaseAccessInPrivateBrowsing(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return schemesAllowingDatabaseAccessInPrivateBrowsing().contains(scheme);
+    return !scheme.isNull() && schemesAllowingDatabaseAccessInPrivateBrowsing().contains(scheme);
 }
 
 void SchemeRegistry::registerURLSchemeAsCORSEnabled(const String& scheme)
 {
+    if (scheme.isNull())
+        return;
     CORSEnabledSchemes().add(scheme);
 }
 
 bool SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return CORSEnabledSchemes().contains(scheme);
+    return !scheme.isNull() && CORSEnabledSchemes().contains(scheme);
 }
 
 void SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme)
 {
+    if (scheme.isNull())
+        return;
     ContentSecurityPolicyBypassingSchemes().add(scheme);
 }
 
 void SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(const String& scheme)
 {
+    if (scheme.isNull())
+        return;
     ContentSecurityPolicyBypassingSchemes().remove(scheme);
 }
 
 bool SchemeRegistry::schemeShouldBypassContentSecurityPolicy(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return ContentSecurityPolicyBypassingSchemes().contains(scheme);
+    return !scheme.isNull() && ContentSecurityPolicyBypassingSchemes().contains(scheme);
 }
 
 void SchemeRegistry::registerURLSchemeAsAlwaysRevalidated(const String& scheme)
 {
+    if (scheme.isNull())
+        return;
     alwaysRevalidatedSchemes().add(scheme);
 }
 
 bool SchemeRegistry::shouldAlwaysRevalidateURLScheme(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return alwaysRevalidatedSchemes().contains(scheme);
+    return !scheme.isNull() && alwaysRevalidatedSchemes().contains(scheme);
 }
 
 void SchemeRegistry::registerURLSchemeAsCachePartitioned(const String& scheme)
 {
+    if (scheme.isNull())
+        return;
     cachePartitioningSchemes().add(scheme);
 }
 
 bool SchemeRegistry::shouldPartitionCacheForURLScheme(const String& scheme)
 {
-    if (scheme.isEmpty())
-        return false;
-    return cachePartitioningSchemes().contains(scheme);
+    return !scheme.isNull() && cachePartitioningSchemes().contains(scheme);
 }
 
 bool SchemeRegistry::isUserExtensionScheme(const String& scheme)
 {
-    UNUSED_PARAM(scheme);
 #if PLATFORM(MAC)
     if (scheme == "safari-extension")
         return true;
+#else
+    UNUSED_PARAM(scheme);
 #endif
     return false;
 }
 
 bool SchemeRegistry::isBuiltinScheme(const String& scheme)
 {
-    return allBuiltinSchemes().contains(scheme) || URLParser::isSpecialScheme(scheme);
+    return !scheme.isNull() && (allBuiltinSchemes().contains(scheme) || URLParser::isSpecialScheme(scheme));
 }
 
 } // namespace WebCore
index ca4fbe01702cc50e4a439f8685d642b79cd9a407..9b8078c1f489ea1f02c9bd8c3df5c343fc293d2b 100644 (file)
@@ -173,11 +173,8 @@ void WebVideoFullscreenModelVideoElement::setVideoLayerGravity(WebVideoFullscree
 
 const Vector<AtomicString>& WebVideoFullscreenModelVideoElement::observedEventNames()
 {
-    static NeverDestroyed<Vector<AtomicString>> sEventNames;
-
-    if (!sEventNames.get().size())
-        sEventNames.get().append(eventNames().resizeEvent);
-    return sEventNames.get();
+    static const auto names = makeNeverDestroyed(Vector<AtomicString> { eventNames().resizeEvent });
+    return names;
 }
 
 const AtomicString& WebVideoFullscreenModelVideoElement::eventNameAll()
index 520d5c133311e2aa3ca3b136b921e2e9f9b1c67f..c7250745ad0d82367d85a3254c3106e746224ea3 100644 (file)
@@ -29,7 +29,6 @@
 
 #include "GamepadProvider.h"
 #include <wtf/HashMap.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/RetainPtr.h>
 #include <wtf/RunLoop.h>
 
index cda66d152243f0fac47e94670d33af1bc5662457..dccd439dbdcafbc86f96e3b241207f81dc492976 100644 (file)
@@ -22,6 +22,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 #import "config.h"
 #import "GameControllerGamepadProvider.h"
 
@@ -31,6 +32,7 @@
 #import "GamepadProviderClient.h"
 #import "Logging.h"
 #import <GameController/GameController.h>
+#import <wtf/NeverDestroyed.h>
 #import <wtf/SoftLinking.h>
 
 SOFT_LINK_FRAMEWORK_OPTIONAL(GameController)
index 2e2299269c2ac62dea07d493630d8e0448f5ae4d..07c3e99c6312b4b08b068135ff6f4699e68062c1 100644 (file)
 
 #if ENABLE(GAMEPAD) && PLATFORM(MAC)
 
-#include "GamepadProviderClient.h"
-#include "Logging.h"
-#include "PlatformGamepad.h"
+#import "GamepadProviderClient.h"
+#import "Logging.h"
+#import "PlatformGamepad.h"
+#import <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
index 27859be2804ce3313416c2684b9f01b86508cf86..fd5fde91b649200fc41ecdfcb6fe9894b4068450 100644 (file)
@@ -33,7 +33,6 @@
 #include <IOKit/hid/IOHIDManager.h>
 #include <wtf/Deque.h>
 #include <wtf/HashMap.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/RetainPtr.h>
 
 namespace WebCore {
index afbcbdb875e044b4deb20270547d76c4348c38a9..d7c9d424a2bfa22616604bad458f6fbb422872dd 100644 (file)
@@ -476,43 +476,6 @@ GlyphData FontCascade::glyphDataForCharacter(UChar32 c, bool mirror, FontVariant
     return m_fonts->glyphDataForCharacter(c, m_fontDescription, variant);
 }
 
-static const char* const fontFamiliesWithInvalidCharWidth[] = {
-    "American Typewriter",
-    "Arial Hebrew",
-    "Chalkboard",
-    "Cochin",
-    "Corsiva Hebrew",
-    "Courier",
-    "Euphemia UCAS",
-    "Geneva",
-    "Gill Sans",
-    "Hei",
-    "Helvetica",
-    "Hoefler Text",
-    "InaiMathi",
-    "Kai",
-    "Lucida Grande",
-    "Marker Felt",
-    "Monaco",
-    "Mshtakan",
-    "New Peninim MT",
-    "Osaka",
-    "Raanana",
-    "STHeiti",
-    "Symbol",
-    "Times",
-    "Apple Braille",
-    "Apple LiGothic",
-    "Apple LiSung",
-    "Apple Symbols",
-    "AppleGothic",
-    "AppleMyungjo",
-    "#GungSeo",
-    "#HeadLineA",
-    "#PCMyungjo",
-    "#PilGi",
-};
-
 // For font families where any of the fonts don't have a valid entry in the OS/2 table
 // for avgCharWidth, fallback to the legacy webkit behavior of getting the avgCharWidth
 // from the width of a '0'. This only seems to apply to a fixed number of Mac fonts,
@@ -520,7 +483,7 @@ static const char* const fontFamiliesWithInvalidCharWidth[] = {
 // all platforms.
 bool FontCascade::hasValidAverageCharWidth() const
 {
-    AtomicString family = firstFamily();
+    const AtomicString& family = firstFamily();
     if (family.isEmpty())
         return false;
 
@@ -530,14 +493,43 @@ bool FontCascade::hasValidAverageCharWidth() const
         return false;
 #endif
 
-    static NeverDestroyed<const HashSet<AtomicString>> fontFamiliesWithInvalidCharWidthMap = [] {
-        HashSet<AtomicString> map;
-        for (auto* family : fontFamiliesWithInvalidCharWidth)
-            map.add(family);
-        return map;
-    }();
-
-    return !fontFamiliesWithInvalidCharWidthMap.get().contains(family);
+    static const auto map = makeNeverDestroyed(HashSet<AtomicString> {
+        "American Typewriter",
+        "Arial Hebrew",
+        "Chalkboard",
+        "Cochin",
+        "Corsiva Hebrew",
+        "Courier",
+        "Euphemia UCAS",
+        "Geneva",
+        "Gill Sans",
+        "Hei",
+        "Helvetica",
+        "Hoefler Text",
+        "InaiMathi",
+        "Kai",
+        "Lucida Grande",
+        "Marker Felt",
+        "Monaco",
+        "Mshtakan",
+        "New Peninim MT",
+        "Osaka",
+        "Raanana",
+        "STHeiti",
+        "Symbol",
+        "Times",
+        "Apple Braille",
+        "Apple LiGothic",
+        "Apple LiSung",
+        "Apple Symbols",
+        "AppleGothic",
+        "AppleMyungjo",
+        "#GungSeo",
+        "#HeadLineA",
+        "#PCMyungjo",
+        "#PilGi",
+    });
+    return !map.get().contains(family);
 }
 
 bool FontCascade::fastAverageCharWidthIfAvailable(float& width) const
index 72e88e0084de239a167bcb57ce57f624a4719ba9..ea2dd5d5892a5cd2bbdbab8457b212e8ec7857a7 100644 (file)
@@ -31,7 +31,6 @@
 #include "GraphicsContext.h"
 #include "IntRect.h"
 #include <wtf/MathExtras.h>
-#include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
@@ -115,6 +114,7 @@ Vector<uint8_t> ImageBuffer::toBGRAData() const
 }
 
 #if !(USE(CG) || USE(DIRECT2D))
+
 FloatSize ImageBuffer::sizeForDestinationSize(FloatSize size) const
 {
     return size;
@@ -122,9 +122,6 @@ FloatSize ImageBuffer::sizeForDestinationSize(FloatSize size) const
 
 void ImageBuffer::transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstColorSpace)
 {
-    static NeverDestroyed<Vector<int>> deviceRgbLUT;
-    static NeverDestroyed<Vector<int>> linearRgbLUT;
-
     if (srcColorSpace == dstColorSpace)
         return;
 
@@ -134,29 +131,34 @@ void ImageBuffer::transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstCo
         return;
 
     if (dstColorSpace == ColorSpaceLinearRGB) {
-        if (linearRgbLUT.get().isEmpty()) {
+        static const std::array<uint8_t, 256> linearRgbLUT = [] {
+            std::array<uint8_t, 256> array;
             for (unsigned i = 0; i < 256; i++) {
-                float color = i  / 255.0f;
+                float color = i / 255.0f;
                 color = (color <= 0.04045f ? color / 12.92f : pow((color + 0.055f) / 1.055f, 2.4f));
                 color = std::max(0.0f, color);
                 color = std::min(1.0f, color);
-                linearRgbLUT.get().append(static_cast<int>(round(color * 255)));
+                array[i] = static_cast<uint8_t>(round(color * 255));
             }
-        }
-        platformTransformColorSpace(linearRgbLUT.get());
+            return array;
+        }();
+        platformTransformColorSpace(linearRgbLUT);
     } else if (dstColorSpace == ColorSpaceDeviceRGB) {
-        if (deviceRgbLUT.get().isEmpty()) {
+        static const std::array<uint8_t, 256> deviceRgbLUT= [] {
+            std::array<uint8_t, 256> array;
             for (unsigned i = 0; i < 256; i++) {
                 float color = i / 255.0f;
                 color = (powf(color, 1.0f / 2.4f) * 1.055f) - 0.055f;
                 color = std::max(0.0f, color);
                 color = std::min(1.0f, color);
-                deviceRgbLUT.get().append(static_cast<int>(round(color * 255)));
+                array[i] = static_cast<uint8_t>(round(color * 255));
             }
-        }
-        platformTransformColorSpace(deviceRgbLUT.get());
+            return array;
+        }();
+        platformTransformColorSpace(deviceRgbLUT);
     }
 }
+
 #endif // USE(CG)
 
 inline void ImageBuffer::genericConvertToLuminanceMask()
index 963f5153cd795ad3563d5c9f594ca00a27916c2e..512d673f0b3e1adf53a45062634ca912373e0c19 100644 (file)
@@ -118,7 +118,7 @@ public:
 #if !USE(CG)
     AffineTransform baseTransform() const { return AffineTransform(); }
     void transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstColorSpace);
-    void platformTransformColorSpace(const Vector<int>&);
+    void platformTransformColorSpace(const std::array<uint8_t, 256>&);
 #else
     AffineTransform baseTransform() const { return AffineTransform(1, 0, 0, -1, 0, m_data.backingStoreSize.height()); }
 #endif
index 1619aff3798df341278ed25d8eae1d35a014632a..3c8175c7a8c2cf86d1eaaf244f435914f1296fd6 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2015 Apple Inc. All rights reserved.
+ * Copyright (C) 2015-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
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-#ifndef MediaPlaybackTarget_h
-#define MediaPlaybackTarget_h
+#pragma once
 
 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
 
-#include "MediaPlaybackTargetContext.h"
-#include <wtf/NeverDestroyed.h>
+#include <wtf/Forward.h>
 #include <wtf/RefCounted.h>
 
 namespace WebCore {
 
-static const MediaPlaybackTargetContext& noMediaPlaybackTargetContext()
-{
-    static NeverDestroyed<MediaPlaybackTargetContext> context;
-    return context;
-}
+class MediaPlaybackTargetContext;
 
 class MediaPlaybackTarget : public RefCounted<MediaPlaybackTarget> {
 public:
     virtual ~MediaPlaybackTarget() { }
 
-    enum TargetType {
-        None,
-        AVFoundation,
-        Mock,
-    };
-    virtual TargetType targetType() const { return None; }
-
-    virtual const MediaPlaybackTargetContext& targetContext() const { return noMediaPlaybackTargetContext(); }
-    virtual bool hasActiveRoute() const { return false; }
-    virtual String deviceName() const { return emptyString(); }
+    enum TargetType { AVFoundation, Mock };
+    virtual TargetType targetType() const = 0;
 
-protected:
-    MediaPlaybackTarget() { }
+    virtual const MediaPlaybackTargetContext& targetContext() const = 0;
+    virtual bool hasActiveRoute() const = 0;
+    virtual String deviceName() const = 0;
 };
 
 }
 
 #endif // ENABLE(WIRELESS_PLAYBACK_TARGET)
-
-#endif
index 7861db68d2ec3a58ef84df487aefc86914adde62..515f4e722082ffac3b98798ee4177c0682674e22 100644 (file)
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-#ifndef MediaPlaybackTargetMac_h
-#define MediaPlaybackTargetMac_h
+#pragma once
 
 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
 
 #include "MediaPlaybackTarget.h"
+#include "MediaPlaybackTargetContext.h"
 #include <wtf/RetainPtr.h>
 
 namespace WebCore {
@@ -62,5 +62,3 @@ const MediaPlaybackTargetMac* toMediaPlaybackTargetMac(const MediaPlaybackTarget
 }
 
 #endif // ENABLE(WIRELESS_PLAYBACK_TARGET)
-
-#endif
index 96cc4f11dc21304c754ee6020bbcd6616e4e4222..bac237afb6cc582efe8ad468d5ee9313898521af 100644 (file)
@@ -1124,48 +1124,39 @@ bool MediaPlayerPrivateAVFoundation::isUnsupportedMIMEType(const String& type)
 
 const HashSet<String, ASCIICaseInsensitiveHash>& MediaPlayerPrivateAVFoundation::staticMIMETypeList()
 {
-    static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> cache = []() {
-        HashSet<String, ASCIICaseInsensitiveHash> types;
-
-        static const char* const typeNames[] = {
-            "application/vnd.apple.mpegurl",
-            "application/x-mpegurl",
-            "audio/3gpp",
-            "audio/aac",
-            "audio/aacp",
-            "audio/aiff",
-            "audio/basic",
-            "audio/mp3",
-            "audio/mp4",
-            "audio/mpeg",
-            "audio/mpeg3",
-            "audio/mpegurl",
-            "audio/mpg",
-            "audio/vnd.wave",
-            "audio/wav",
-            "audio/wave",
-            "audio/x-aac",
-            "audio/x-aiff",
-            "audio/x-m4a",
-            "audio/x-mpegurl",
-            "audio/x-wav",
-            "video/3gpp",
-            "video/3gpp2",
-            "video/mp4",
-            "video/mpeg",
-            "video/mpeg2",
-            "video/mpg",
-            "video/quicktime",
-            "video/x-m4v",
-            "video/x-mpeg",
-            "video/x-mpg",
-        };
-        for (auto& type : typeNames)
-            types.add(type);
-
-        return types;
-    }();
-
+    static const auto cache = makeNeverDestroyed(HashSet<String, ASCIICaseInsensitiveHash> {
+        "application/vnd.apple.mpegurl",
+        "application/x-mpegurl",
+        "audio/3gpp",
+        "audio/aac",
+        "audio/aacp",
+        "audio/aiff",
+        "audio/basic",
+        "audio/mp3",
+        "audio/mp4",
+        "audio/mpeg",
+        "audio/mpeg3",
+        "audio/mpegurl",
+        "audio/mpg",
+        "audio/vnd.wave",
+        "audio/wav",
+        "audio/wave",
+        "audio/x-aac",
+        "audio/x-aiff",
+        "audio/x-m4a",
+        "audio/x-mpegurl",
+        "audio/x-wav",
+        "video/3gpp",
+        "video/3gpp2",
+        "video/mp4",
+        "video/mpeg",
+        "video/mpeg2",
+        "video/mpg",
+        "video/quicktime",
+        "video/x-m4v",
+        "video/x-mpeg",
+        "video/x-mpg",
+    });
     return cache;
 }
 
index f39fcd2f3043f4d3fead5dffddddc8bdd0296970..17c1e636ce24daa51c162ce878bc75dd7102453a 100644 (file)
@@ -232,24 +232,18 @@ void MediaPlayerPrivateMediaStreamAVFObjC::registerMediaEngine(MediaEngineRegist
 
 bool MediaPlayerPrivateMediaStreamAVFObjC::isAvailable()
 {
-    if (!AVFoundationLibrary() || !isCoreMediaFrameworkAvailable() || !getAVSampleBufferDisplayLayerClass())
-        return false;
-
-    return true;
+    return AVFoundationLibrary() && isCoreMediaFrameworkAvailable() && getAVSampleBufferDisplayLayerClass();
 }
 
 void MediaPlayerPrivateMediaStreamAVFObjC::getSupportedTypes(HashSet<String, ASCIICaseInsensitiveHash>& types)
 {
-    static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> cache;
-    types = cache;
+    // FIXME: Is it really correct to list no supported types?
+    types.clear();
 }
 
 MediaPlayer::SupportsType MediaPlayerPrivateMediaStreamAVFObjC::supportsType(const MediaEngineSupportParameters& parameters)
 {
-    if (parameters.isMediaStream)
-        return MediaPlayer::IsSupported;
-
-    return MediaPlayer::IsNotSupported;
+    return parameters.isMediaStream ? MediaPlayer::IsSupported : MediaPlayer::IsNotSupported;
 }
 
 #pragma mark -
index 1a51cf54e7336f873437a31c380d226007a2d062..f04c5a56af67ebc63716c8faea678ba3f53e26c7 100644 (file)
@@ -297,7 +297,7 @@ void ImageBuffer::drawPattern(GraphicsContext& context, const FloatRect& destRec
         image->drawPattern(context, destRect, srcRect, patternTransform, phase, spacing, op);
 }
 
-void ImageBuffer::platformTransformColorSpace(const Vector<int>& lookUpTable)
+void ImageBuffer::platformTransformColorSpace(const std::array<uint8_t, 256>& lookUpTable)
 {
     // FIXME: Enable color space conversions on accelerated canvases.
     if (cairo_surface_get_type(m_data.m_surface.get()) != CAIRO_SURFACE_TYPE_IMAGE)
index c7e114ef127eebb809fb4f526214343e38257a2c..85254ad5e9bc3ddf45eb07d2bf8207b32df6714b 100644 (file)
@@ -35,7 +35,6 @@
 #include "IntSize.h"
 #include "Logging.h"
 #include "SharedBuffer.h"
-#include <wtf/NeverDestroyed.h>
 
 #if !PLATFORM(IOS)
 #include <ApplicationServices/ApplicationServices.h>
@@ -76,10 +75,9 @@ static RetainPtr<CFMutableDictionaryRef> createImageSourceAsyncOptions()
 
 static RetainPtr<CFMutableDictionaryRef> appendImageSourceOption(RetainPtr<CFMutableDictionaryRef>&& options, SubsamplingLevel subsamplingLevel)
 {
-    RetainPtr<CFNumberRef> subsampleNumber;
     subsamplingLevel = std::min(SubsamplingLevel::Last, std::max(SubsamplingLevel::First, subsamplingLevel));
     int subsampleInt = 1 << static_cast<int>(subsamplingLevel); // [0..3] => [1, 2, 4, 8]
-    subsampleNumber = adoptCF(CFNumberCreate(nullptr,  kCFNumberIntType,  &subsampleInt));
+    auto subsampleNumber = adoptCF(CFNumberCreate(nullptr,  kCFNumberIntType,  &subsampleInt));
     CFDictionarySetValue(options.get(), kCGImageSourceSubsampleFactor, subsampleNumber.get());
     return WTFMove(options);
 }
@@ -103,16 +101,16 @@ static RetainPtr<CFMutableDictionaryRef> appendImageSourceOptions(RetainPtr<CFMu
     
 static RetainPtr<CFDictionaryRef> imageSourceOptions(SubsamplingLevel subsamplingLevel = SubsamplingLevel::Default)
 {
-    static NeverDestroyed<RetainPtr<CFMutableDictionaryRef>> options = createImageSourceOptions();
+    static const auto options = createImageSourceOptions().leakRef();
     if (subsamplingLevel == SubsamplingLevel::Default)
-        return options.get();
-    return appendImageSourceOption(adoptCF(CFDictionaryCreateMutableCopy(nullptr, 0, options.get().get())), subsamplingLevel);
+        return options;
+    return appendImageSourceOption(adoptCF(CFDictionaryCreateMutableCopy(nullptr, 0, options)), subsamplingLevel);
 }
 
 static RetainPtr<CFDictionaryRef> imageSourceAsyncOptions(SubsamplingLevel subsamplingLevel, const IntSize& sizeForDrawing)
 {
-    static NeverDestroyed<RetainPtr<CFMutableDictionaryRef>> options = createImageSourceAsyncOptions();
-    return appendImageSourceOptions(adoptCF(CFDictionaryCreateMutableCopy(nullptr, 0, options.get().get())), subsamplingLevel, sizeForDrawing);
+    static const auto options = createImageSourceAsyncOptions().leakRef();
+    return appendImageSourceOptions(adoptCF(CFDictionaryCreateMutableCopy(nullptr, 0, options)), subsamplingLevel, sizeForDrawing);
 }
     
 static ImageOrientation orientationFromProperties(CFDictionaryRef imageProperties)
index 819441efa67f8f7d7df2baa94ead900bbc080077..683d8f5ae51ffbf5810219e18c87f5b74ec24d52 100644 (file)
@@ -43,10 +43,10 @@ const cairo_font_options_t* getDefaultCairoFontOptions()
             return options;
     }
 
-    static LazyNeverDestroyed<cairo_font_options_t*> options;
+    static cairo_font_options_t* options;
     static std::once_flag flag;
     std::call_once(flag, [] {
-        options.construct(cairo_font_options_create());
+        options = cairo_font_options_create();
     });
     return options;
 }
index ffcdea1f7c467867ea17a3a5338eef70a30fe1e6..eebed1393521752e1110aea5ca7a85ea936fad56 100644 (file)
@@ -160,8 +160,8 @@ RetainPtr<CTFontRef> platformFontWithFamilySpecialCase(const AtomicString& famil
 
     if (equalLettersIgnoringASCIICase(family, "lastresort")) {
 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
-        static NeverDestroyed<RetainPtr<CTFontDescriptorRef>> lastResort = adoptCF(CTFontDescriptorCreateLastResort());
-        return adoptCF(CTFontCreateWithFontDescriptor(lastResort.get().get(), size, nullptr));
+        static const CTFontDescriptorRef lastResort = CTFontDescriptorCreateLastResort();
+        return adoptCF(CTFontCreateWithFontDescriptor(lastResort, size, nullptr));
 #else
         // LastResort is special, so it's important to look this exact string up, and not some case-folded version.
         // We handle this here so any caching and case folding we do in our general text codepath is bypassed.
index 0fb1c8a4318ca93c7560c71f6ebc7d28002a73c8..daa0a88537c12fc01cd0a0642d85f6e7f8e04a0f 100644 (file)
@@ -116,8 +116,8 @@ RetainPtr<CTFontRef> platformFontWithFamilySpecialCase(const AtomicString& famil
 
     if (equalLettersIgnoringASCIICase(family, "lastresort")) {
 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
-        static NeverDestroyed<RetainPtr<CTFontDescriptorRef>> lastResort = adoptCF(CTFontDescriptorCreateLastResort());
-        return adoptCF(CTFontCreateWithFontDescriptor(lastResort.get().get(), size, nullptr));
+        static const CTFontDescriptorRef lastResort = CTFontDescriptorCreateLastResort();
+        return adoptCF(CTFontCreateWithFontDescriptor(lastResort, size, nullptr));
 #else
         // LastResort is special, so it's important to look this exact string up, and not some case-folded version.
         // We handle this here so any caching and case folding we do in our general text codepath is bypassed.
index a26ea62d29278303ff1d8cac7ff1f937a4b44f4b..ade36c8e025b897a80eb3806b727b615595f990e 100644 (file)
@@ -1235,18 +1235,19 @@ static bool shouldRejectMIMEType(const String& type)
     return !type.startsWith("video/", false) && !type.startsWith("audio/", false);
 }
 
-static void addFileTypesToCache(NSArray *fileTypes, HashSet<String, ASCIICaseInsensitiveHash> &cache)
+static HashSet<String, ASCIICaseInsensitiveHash> createFileTypesSet(NSArray *fileTypes)
 {
-    for (NSString *fileType : fileTypes) {
+    HashSet<String, ASCIICaseInsensitiveHash> set;
+    for (NSString *fileType in fileTypes) {
         CFStringRef ext = reinterpret_cast<CFStringRef>(fileType);
-        RetainPtr<CFStringRef> uti = adoptCF(UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext, NULL));
+        auto uti = adoptCF(UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext, NULL));
         if (!uti)
             continue;
-        RetainPtr<CFStringRef> mime = adoptCF(UTTypeCopyPreferredTagWithClass(uti.get(), kUTTagClassMIMEType));
+        auto mime = adoptCF(UTTypeCopyPreferredTagWithClass(uti.get(), kUTTagClassMIMEType));
         if (shouldRejectMIMEType(mime.get()))
             continue;
         if (mime)
-            cache.add(mime.get());
+            set.add(mime.get());
 
         // -movieFileTypes: returns both file extensions and OSTypes. The later are surrounded by single
         // quotes, eg. 'MooV', so don't bother looking at those.
@@ -1256,37 +1257,22 @@ static void addFileTypesToCache(NSArray *fileTypes, HashSet<String, ASCIICaseIns
             // has a type for this extension add any types in hard coded table in the MIME type registry.
             for (auto& type : MIMETypeRegistry::getMediaMIMETypesForExtension(ext)) {
                 if (!shouldRejectMIMEType(type))
-                    cache.add(type);
+                    set.add(type);
             }
         }
-    }    
+    }
+    return set;
 }
 
-static HashSet<String, ASCIICaseInsensitiveHash> mimeCommonTypesCache()
+static const HashSet<String, ASCIICaseInsensitiveHash>& mimeCommonTypesCache()
 {
-    static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> cache;
-    static bool typeListInitialized = false;
-
-    if (!typeListInitialized) {
-        typeListInitialized = true;
-        NSArray* fileTypes = [QTMovie movieFileTypes:QTIncludeCommonTypes];
-        addFileTypesToCache(fileTypes, cache);
-    }
-    
+    static const auto cache = makeNeverDestroyed(createFileTypesSet([QTMovie movieFileTypes:QTIncludeCommonTypes]));
     return cache;
 } 
 
-static HashSet<String, ASCIICaseInsensitiveHash> mimeModernTypesCache()
+static const HashSet<String, ASCIICaseInsensitiveHash>& mimeModernTypesCache()
 {
-    static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> cache;
-    static bool typeListInitialized = false;
-    
-    if (!typeListInitialized) {
-        typeListInitialized = true;
-        NSArray* fileTypes = [QTMovie movieFileTypes:(QTMovieFileTypeOptions)wkQTIncludeOnlyModernMediaFileTypes()];
-        addFileTypesToCache(fileTypes, cache);
-    }
-    
+    static const auto cache = makeNeverDestroyed(createFileTypesSet([QTMovie movieFileTypes:(QTMovieFileTypeOptions)wkQTIncludeOnlyModernMediaFileTypes()]));
     return cache;
 }
 
@@ -1370,8 +1356,8 @@ void MediaPlayerPrivateQTKit::disableUnsupportedTracks()
         return;
     }
     
-    static NeverDestroyed<HashSet<String>> allowedTrackTypes = []() {
-        NSString *types[] = {
+    static NeverDestroyed<HashSet<String>> allowedTrackTypes = [] {
+        static NSString * const types[] = {
             QTMediaTypeVideo,
             QTMediaTypeSound,
             QTMediaTypeText,
index e15d479259497084c7992b58fa6520b7a9c189de..c8e12d73944f0807d6fdc90144206eebd803e49a 100644 (file)
@@ -28,7 +28,6 @@
 
 #if PLATFORM(IOS)
 
-#include <mutex>
 #include <wtf/NeverDestroyed.h>
 #include <wtf/RetainPtr.h>
 #include <wtf/text/WTFString.h>
@@ -37,9 +36,7 @@ namespace WebCore {
 
 MGDeviceClass deviceClass()
 {
-    static MGDeviceClass deviceClass;
-    static std::once_flag onceFlag;
-    std::call_once(onceFlag, [] {
+    static MGDeviceClass deviceClass = [] {
         int deviceClassNumber = MGGetSInt32Answer(kMGQDeviceClassNumber, MGDeviceClassInvalid);
         switch (deviceClassNumber) {
         case MGDeviceClassInvalid:
@@ -48,27 +45,22 @@ MGDeviceClass deviceClass()
         case MGDeviceClassiPad:
         case MGDeviceClassAppleTV:
         case MGDeviceClassWatch:
-            deviceClass = static_cast<MGDeviceClass>(deviceClassNumber);
-            return;
+            break;
+        default:
+            ASSERT_NOT_REACHED();
         }
-        ASSERT_NOT_REACHED();
-    });
+        return static_cast<MGDeviceClass>(deviceClassNumber);
+    }();
     return deviceClass;
 }
 
 const String& deviceName()
 {
-    static LazyNeverDestroyed<String> deviceName;
-    static std::once_flag onceFlag;
-    std::call_once(onceFlag, [] {
 #if TARGET_OS_IOS
-        auto cfDeviceName = adoptCF(static_cast<CFStringRef>(MGCopyAnswer(kMGQDeviceName, nullptr)));
+    static const NeverDestroyed<String> deviceName = adoptCF(static_cast<CFStringRef>(MGCopyAnswer(kMGQDeviceName, nullptr))).get();
 #else
-        auto cfDeviceName = retainPtr(CFSTR("iPhone"));
+    static const NeverDestroyed<String> deviceName = ASCIILiteral { "iPhone" };
 #endif
-        ASSERT(!cfDeviceName || CFGetTypeID(cfDeviceName.get()) == CFStringGetTypeID());
-        deviceName.construct(cfDeviceName.get());
-    });
     return deviceName;
 }
 
index 4fd4aa0d25e9c673744c66e51a8b4263d83a1792..a84e11dcd7f20437b1f18fef88ce08ee068ef173 100644 (file)
@@ -120,21 +120,20 @@ void deleteDragImage(DragImageRef)
 {
 }
 
-static TextIndicatorOptions defaultLinkIndicatorOptions = TextIndicatorOptionTightlyFitContent | TextIndicatorOptionRespectTextColor | TextIndicatorOptionUseBoundingRectAndPaintAllContentForComplexRanges | TextIndicatorOptionExpandClipBeyondVisibleRect | TextIndicatorOptionComputeEstimatedBackgroundColor;
+static const TextIndicatorOptions defaultLinkIndicatorOptions = TextIndicatorOptionTightlyFitContent | TextIndicatorOptionRespectTextColor | TextIndicatorOptionUseBoundingRectAndPaintAllContentForComplexRanges | TextIndicatorOptionExpandClipBeyondVisibleRect | TextIndicatorOptionComputeEstimatedBackgroundColor;
+
+static FontCascade cascadeForSystemFont(CGFloat size)
+{
+    UIFont *font = [getUIFontClass() systemFontOfSize:16];
+    return FontPlatformData(CTFontCreateWithName((CFStringRef)font.fontName, font.pointSize, nil), font.pointSize), AutoSmoothing);
+}
 
 DragImageRef createDragImageForLink(Element& linkElement, URL& url, const String& title, TextIndicatorData& indicatorData, FontRenderingMode, float)
 {
     // FIXME: Most of this can go away once we can use UIURLDragPreviewView unconditionally.
-    static CGFloat dragImagePadding = 10;
-    static LazyNeverDestroyed<FontCascade> titleFontCascade;
-    static LazyNeverDestroyed<FontCascade> urlFontCascade;
-    static dispatch_once_t onceToken;
-    dispatch_once(&onceToken, ^ {
-        UIFont *titleFont = [getUIFontClass() systemFontOfSize:16];
-        UIFont *urlFont = [getUIFontClass() systemFontOfSize:14];
-        titleFontCascade.construct(FontPlatformData(CTFontCreateWithName((CFStringRef)titleFont.fontName, titleFont.pointSize, nil), titleFont.pointSize), AutoSmoothing);
-        urlFontCascade.construct(FontPlatformData(CTFontCreateWithName((CFStringRef)urlFont.fontName, urlFont.pointSize, nil), urlFont.pointSize), AutoSmoothing);
-    });
+    static const CGFloat dragImagePadding = 10;
+    static const auto titleFontCascade = makeNeverDestroyed(cascadeForSystemFont(16));
+    static const auto urlFontCascade = makeNeverDestroyed(cascadeForSystemFont(14));
 
     String topString(title.stripWhiteSpace());
     String bottomString([(NSURL *)url absoluteString]);
index 1bb2db7d444086a6aed7460b0a945904633d0aaf..537c9edf658f6a9b9efdab7dc237ada2726c1f4d 100644 (file)
@@ -23,8 +23,7 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef LegacyTileLayerPool_h
-#define LegacyTileLayerPool_h
+#pragma once
 
 #if PLATFORM(IOS)
 
@@ -32,9 +31,9 @@
 #include "IntSizeHash.h"
 #include "Timer.h"
 #include <wtf/Deque.h>
+#include <wtf/Forward.h>
 #include <wtf/HashMap.h>
 #include <wtf/Lock.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/RetainPtr.h>
 #include <wtf/Threading.h>
 #include <wtf/Vector.h>
@@ -87,4 +86,3 @@ private:
 } // namespace WebCore
 
 #endif // PLATFORM(IOS)
-#endif // TileLayerPool_h
index be053f724a96d19a31b8dd014222eaf8d04ad4d8..951da310719a7dd9e454e4261ac9a3479d7c2e5f 100644 (file)
@@ -42,8 +42,8 @@ namespace WebCore {
 
 NSSet *QLPreviewGetSupportedMIMETypesSet()
 {
-    static NeverDestroyed<RetainPtr<NSSet>> set = QLPreviewGetSupportedMIMETypes();
-    return set.get().get();
+    static NSSet *set = [QLPreviewGetSupportedMIMETypes() retain];
+    return set;
 }
 
 static Lock& qlPreviewConverterDictionaryMutex()
@@ -100,18 +100,10 @@ RetainPtr<NSURLRequest> registerQLPreviewConverterIfNeeded(NSURL *url, NSString
     return nil;
 }
 
-static Vector<char> createQLPreviewProtocol()
-{
-    Vector<char> previewProtocol;
-    const char* qlPreviewScheme = [QLPreviewScheme UTF8String];
-    previewProtocol.append(qlPreviewScheme, strlen(qlPreviewScheme) + 1);
-    return previewProtocol;
-}
-
 const char* QLPreviewProtocol()
 {
-    static NeverDestroyed<Vector<char>> previewProtocol(createQLPreviewProtocol());
-    return previewProtocol.get().data();
+    static const char* const previewProtocol = fastStrDup([QLPreviewScheme UTF8String]);
+    return previewProtocol;
 }
 
 bool isQuickLookPreviewURL(const URL& url)
index dd91bf96d8aacc6d0364ac840050bc80332e4dd1..19229d1902f8431dcec555986a2130dcf1388c0f 100644 (file)
 #import "config.h"
 #import "WebCoreMotionManager.h"
 
+#if PLATFORM(IOS)
+
 #import "WebCoreObjCExtras.h"
+#import "WebCoreThreadRun.h"
 #import <CoreLocation/CoreLocation.h>
+#import <CoreMotion/CoreMotion.h>
 #import <objc/objc-runtime.h>
 #import <wtf/MathExtras.h>
-#import <wtf/NeverDestroyed.h>
 #import <wtf/SoftLinking.h>
 
-#if PLATFORM(IOS)
-
-#import "WebCoreThreadRun.h"
-#import <CoreMotion/CoreMotion.h>
-
 // Get CoreLocation classes
 SOFT_LINK_FRAMEWORK(CoreLocation)
 
index b79f0a767fbcc263290a9f5b07a1a00c153b95f6..7b2d24226da2d9dcd7bb1861eaa4f0d6c9cd1ddc 100644 (file)
 
 #pragma once
 
-#include "PlatformExportMacros.h"
-
 #if PLATFORM(IOS)
 
 #include "HysteresisActivity.h"
 #include "SQLiteDatabaseTrackerClient.h"
-#include <wtf/NeverDestroyed.h>
+#include <wtf/Forward.h>
 #include <wtf/Noncopyable.h>
 
 namespace WebCore {
index 9728bd5ed41697f7c2e9d70449f5c71d2b7296b2..c146147f1dcb218440b88e790490ab5b70311fb2 100644 (file)
@@ -43,7 +43,6 @@
 #import "TextIndicator.h"
 #import "TextRun.h"
 #import "URL.h"
-#import <wtf/NeverDestroyed.h>
 #import <wtf/SoftLinking.h>
 
 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
index 6e0916618f29554360f1d8ebe187ab8bedd253dd..9225912cc16fe7320022e97c82c2b8986e100857 100644 (file)
@@ -34,7 +34,6 @@
 #include "RealtimeMediaSourceCenter.h"
 #include "RealtimeMediaSourceSettings.h"
 #include <wtf/MainThread.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/text/StringHash.h>
 
 using namespace WebCore;
index ecbf935a27f060e62864f587a485b8adecd0d0af..57156d5e9b1104ec415b85c845167347da65b9bb 100644 (file)
@@ -29,7 +29,6 @@
 #if ENABLE(MEDIA_STREAM)
 
 #include <wtf/HashMap.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/text/AtomicString.h>
 #include <wtf/text/AtomicStringHash.h>
 
index 440bb98d6d28607d4b6f902d93fabd0d374c9300..b42427b7cdd7d89e020d6a5f62f47eca747f02e8 100644 (file)
@@ -32,6 +32,7 @@
 #include "MockRealtimeMediaSource.h"
 
 #if ENABLE(MEDIA_STREAM)
+
 #include "CaptureDevice.h"
 #include "Logging.h"
 #include "MediaConstraints.h"
@@ -46,31 +47,37 @@ namespace WebCore {
 
 Vector<CaptureDevice>& MockRealtimeMediaSource::audioDevices()
 {
-    static NeverDestroyed<Vector<CaptureDevice>> info;
-    if (!info.get().size()) {
+    static auto info = makeNeverDestroyed([] {
+        Vector<CaptureDevice> vector;
+
         auto captureDevice = CaptureDevice("239c24b0-2b15-11e3-8224-0800200c9a66", CaptureDevice::DeviceType::Audio, "Mock audio device 1");
         captureDevice.setEnabled(true);
-        info.get().append(captureDevice);
+        vector.append(WTFMove(captureDevice));
 
         captureDevice = CaptureDevice("239c24b1-2b15-11e3-8224-0800200c9a66", CaptureDevice::DeviceType::Audio, "Mock audio device 2");
         captureDevice.setEnabled(true);
-        info.get().append(captureDevice);
-    }
+        vector.append(WTFMove(captureDevice));
+
+        return vector;
+    }());
     return info;
 }
 
 Vector<CaptureDevice>& MockRealtimeMediaSource::videoDevices()
 {
-    static NeverDestroyed<Vector<CaptureDevice>> info;
-    if (!info.get().size()) {
+    static auto info = makeNeverDestroyed([] {
+        Vector<CaptureDevice> vector;
+
         auto captureDevice = CaptureDevice("239c24b2-2b15-11e3-8224-0800200c9a66", CaptureDevice::DeviceType::Video, "Mock video device 1");
         captureDevice.setEnabled(true);
-        info.get().append(captureDevice);
+        vector.append(WTFMove(captureDevice));
 
         captureDevice = CaptureDevice("239c24b3-2b15-11e3-8224-0800200c9a66", CaptureDevice::DeviceType::Video, "Mock video device 2");
         captureDevice.setEnabled(true);
-        info.get().append(captureDevice);
-    }
+        vector.append(WTFMove(captureDevice));
+
+        return vector;
+    }());
     return info;
 }
 
index 8a253b1999a8d9617004aaf13b58d936a281040c..a5468b3bd76bc58ae616613e5d33128e697c6f9f 100644 (file)
@@ -40,21 +40,17 @@ namespace WebCore {
 // MediaPlayer Enigne Support
 void MockMediaPlayerMediaSource::registerMediaEngine(MediaEngineRegistrar registrar)
 {
-    registrar([](MediaPlayer* player) { return std::make_unique<MockMediaPlayerMediaSource>(player); }, getSupportedTypes,
+    registrar([] (MediaPlayer* player) { return std::make_unique<MockMediaPlayerMediaSource>(player); }, getSupportedTypes,
         supportsType, 0, 0, 0, 0);
 }
 
+// FIXME: What does the word "cache" mean here?
 static const HashSet<String, ASCIICaseInsensitiveHash>& mimeTypeCache()
 {
-    static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> cache;
-    static bool isInitialized = false;
-
-    if (!isInitialized) {
-        isInitialized = true;
-        cache.get().add(ASCIILiteral("video/mock"));
-        cache.get().add(ASCIILiteral("audio/mock"));
-    }
-
+    static const auto cache = makeNeverDestroyed(HashSet<String, ASCIICaseInsensitiveHash> {
+        "video/mock",
+        "audio/mock",
+    });
     return cache;
 }
 
index c8c28cf70c8e8bc561086e0cea7b17c2cdd1bcce..dc47c0de4718a1a92bf6fd51837b82bd49302597 100644 (file)
@@ -243,8 +243,8 @@ unsigned long long BlobRegistryImpl::blobSize(const URL& url)
 
 static WorkQueue& blobUtilityQueue()
 {
-    static NeverDestroyed<Ref<WorkQueue>> queue(WorkQueue::create("org.webkit.BlobUtility", WorkQueue::Type::Serial, WorkQueue::QOS::Background));
-    return queue.get();
+    static auto& queue = WorkQueue::create("org.webkit.BlobUtility", WorkQueue::Type::Serial, WorkQueue::QOS::Background).leakRef();
+    return queue;
 }
 
 struct BlobForFileWriting {
index ad15e5cf3c3fd1526f7a64485040b5d9982c930d..aa25bb0cbfdf2934d3ca35e71d428cc1370c4253 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 "NetworkStateNotifier.h"
 
-#if PLATFORM(IOS)
-#include "Settings.h"
-#endif
-
-#include <mutex>
-#include <wtf/Assertions.h>
 #include <wtf/NeverDestroyed.h>
 
 namespace WebCore {
 
-NetworkStateNotifier& networkStateNotifier()
+static const Seconds updateStateSoonInterval { 2_s };
+
+NetworkStateNotifier& NetworkStateNotifier::singleton()
 {
-    static std::once_flag onceFlag;
-    static LazyNeverDestroyed<NetworkStateNotifier> networkStateNotifier;
+    static NeverDestroyed<NetworkStateNotifier> networkStateNotifier;
+    return networkStateNotifier;
+}
 
-    std::call_once(onceFlag, []{
-        networkStateNotifier.construct();
-    });
+NetworkStateNotifier::NetworkStateNotifier()
+    : m_updateStateTimer([] {
+        singleton().updateState();
+    })
+{
+}
 
-    return networkStateNotifier;
+bool NetworkStateNotifier::onLine()
+{
+    if (!m_isOnLine)
+        updateState();
+    return m_isOnLine.value_or(true);
 }
 
-void NetworkStateNotifier::addNetworkStateChangeListener(WTF::Function<void (bool)>&& listener)
+void NetworkStateNotifier::addListener(WTF::Function<void(bool)>&& listener)
 {
     ASSERT(listener);
-#if PLATFORM(IOS)
-    if (Settings::shouldOptOutOfNetworkStateObservation())
+    if (m_listeners.isEmpty())
+        startObserving();
+    m_listeners.append(WTFMove(listener));
+}
+
+void NetworkStateNotifier::updateState()
+{
+    auto wasOnLine = m_isOnLine;
+    updateStateWithoutNotifying();
+    if (m_isOnLine == wasOnLine)
         return;
-    registerObserverIfNecessary();
-#endif
+    for (auto& listener : m_listeners)
+        listener(m_isOnLine.value());
+}
 
-    m_listeners.append(WTFMove(listener));
+void NetworkStateNotifier::updateStateSoon()
+{
+    m_updateStateTimer.startOneShot(updateStateSoonInterval);
+}
+
+#if !PLATFORM(IOS) && !PLATFORM(MAC) && !PLATFORM(WIN)
+
+// Empty stubs for platforms where monitoring of network state is not yet implemented.
+
+void NetworkStateNotifier::updateStateWithoutNotifying()
+{
 }
 
-void NetworkStateNotifier::notifyNetworkStateChange() const
+void NetworkStateNotifier::startObserving()
 {
-    for (const auto& listener : m_listeners)
-        listener(m_isOnLine);
 }
 
+#endif
+
 } // namespace WebCore
index c3a42903cd0b89ca62a1b1852613eed0ae86a181..f5e79b44512cc582b04502cdae42e1db7f90fa8b 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008, 2014 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
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-#ifndef NetworkStateNotifier_h
-#define NetworkStateNotifier_h
-
-#include <wtf/FastMalloc.h>
-#include <wtf/Function.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/Vector.h>
-
-#if PLATFORM(MAC)
+#pragma once
 
+#include <wtf/Forward.h>
 #include <wtf/RetainPtr.h>
 #include "Timer.h"
 
-typedef const struct __CFArray * CFArrayRef;
-typedef const struct __SCDynamicStore * SCDynamicStoreRef;
+#if PLATFORM(IOS)
+OBJC_CLASS WebNetworkStateObserver;
+#endif
 
-#elif PLATFORM(WIN)
+#if PLATFORM(MAC)
+typedef const struct __SCDynamicStore * SCDynamicStoreRef;
+#endif
 
+#if PLATFORM(WIN)
 #include <windows.h>
-
-#elif PLATFORM(IOS)
-
-#include <wtf/RetainPtr.h>
-OBJC_CLASS WebNetworkStateObserver;
-
 #endif
 
 namespace WebCore {
 
 class NetworkStateNotifier {
-    WTF_MAKE_NONCOPYABLE(NetworkStateNotifier); WTF_MAKE_FAST_ALLOCATED;
+    WTF_MAKE_NONCOPYABLE(NetworkStateNotifier);
+
 public:
-    NetworkStateNotifier();
-#if PLATFORM(IOS)
-    ~NetworkStateNotifier();
-#endif
-    void addNetworkStateChangeListener(WTF::Function<void (bool isOnLine)>&&);
+    static NetworkStateNotifier& singleton();
 
-    bool onLine() const;
+    bool onLine();
+    void addListener(WTF::Function<void(bool isOnLine)>&&);
 
 private:
-#if !PLATFORM(IOS)
-    bool m_isOnLine;
-#endif
-    Vector<WTF::Function<void (bool)>> m_listeners;
-
-    void notifyNetworkStateChange() const;
-    void updateState();
+    friend NeverDestroyed<NetworkStateNotifier>;
 
-#if PLATFORM(MAC)
-    void networkStateChangeTimerFired();
-
-    static void dynamicStoreCallback(SCDynamicStoreRef, CFArrayRef changedKeys, void *info); 
-
-    RetainPtr<SCDynamicStoreRef> m_store;
-    Timer m_networkStateChangeTimer;
+    NetworkStateNotifier();
 
-#elif PLATFORM(WIN)
-    static void CALLBACK addrChangeCallback(void*, BOOLEAN timedOut);
-    void addressChanged();
+    void updateStateWithoutNotifying();
+    void updateState();
+    void updateStateSoon();
+    void startObserving();
 
+#if PLATFORM(WIN)
     void registerForAddressChange();
-    HANDLE m_waitHandle;
-    OVERLAPPED m_overlapped;
-
-#elif PLATFORM(IOS)
-    void registerObserverIfNecessary() const;
-    friend void setOnLine(const NetworkStateNotifier*, bool);
-
-    mutable bool m_isOnLine;
-    mutable bool m_isOnLineInitialized;
-    mutable RetainPtr<WebNetworkStateObserver> m_observer;
+    static void CALLBACK addressChangeCallback(void*, BOOLEAN timedOut);
 #endif
-};
 
-#if !PLATFORM(COCOA) && !PLATFORM(WIN)
-
-inline NetworkStateNotifier::NetworkStateNotifier()
-    : m_isOnLine(true)
-{
-}
-
-inline void NetworkStateNotifier::updateState() { }
+    std::optional<bool> m_isOnLine;
+    Vector<WTF::Function<void(bool)>> m_listeners;
+    Timer m_updateStateTimer;
 
+#if PLATFORM(IOS)
+    RetainPtr<WebNetworkStateObserver> m_observer;
 #endif
 
-#if !PLATFORM(IOS)
-inline bool NetworkStateNotifier::onLine() const
-{
-    return m_isOnLine;
-}
+#if PLATFORM(MAC)
+    RetainPtr<SCDynamicStoreRef> m_store;
 #endif
 
-WEBCORE_EXPORT NetworkStateNotifier& networkStateNotifier();
+#if PLATFORM(WIN)
+    HANDLE m_waitHandle;
+    OVERLAPPED m_overlapped;
+#endif
+};
 
 } // namespace WebCore
-
-#endif // NetworkStateNotifier_h
index 21fe180db08c7931f922bd43ffc347abad4248a1..9571fe5cb0169774440f6b256b9e11d24efcea0e 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008, 2014 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
 #import "config.h"
 #import "NetworkStateNotifier.h"
 
+#import "Settings.h"
 #import "WebCoreThreadRun.h"
 #import <wtf/SoftLinking.h>
 
 #if USE(APPLE_INTERNAL_SDK)
 #import <AppSupport/CPNetworkObserver.h>
 #else
-extern NSString * const CPNetworkObserverReachable;
 @interface CPNetworkObserver : NSObject
 + (CPNetworkObserver *)sharedNetworkObserver;
 - (void)addNetworkReachableObserver:(id)observer selector:(SEL)selector;
-- (void)removeNetworkReachableObserver:(id)observer;
 - (BOOL)isNetworkReachable;
 @end
 #endif
 
 SOFT_LINK_PRIVATE_FRAMEWORK(AppSupport);
 SOFT_LINK_CLASS(AppSupport, CPNetworkObserver);
-SOFT_LINK_POINTER(AppSupport, CPNetworkObserverReachable, NSString *);
 
-@interface WebNetworkStateObserver : NSObject
-@property (nonatomic) const WebCore::NetworkStateNotifier* notifier;
-- (id)initWithNotifier:(const WebCore::NetworkStateNotifier*)notifier;
-- (void)networkStateChanged:(NSNotification *)notification;
+@interface WebNetworkStateObserver : NSObject {
+    void (^block)();
+}
+- (id)initWithBlock:(void (^)())block;
 @end
 
 @implementation WebNetworkStateObserver
 
-- (id)initWithNotifier:(const WebCore::NetworkStateNotifier*)notifier
+- (id)initWithBlock:(void (^)())observerBlock
 {
-    ASSERT_ARG(notifier, notifier);
     if (!(self = [super init]))
         return nil;
-    _notifier = notifier;
     [[getCPNetworkObserverClass() sharedNetworkObserver] addNetworkReachableObserver:self selector:@selector(networkStateChanged:)];
+    block = [observerBlock copy];
     return self;
 }
 
 - (void)dealloc
 {
-    [[getCPNetworkObserverClass() sharedNetworkObserver] removeNetworkReachableObserver:self];
+    [block release];
     [super dealloc];
 }
 
-- (void)networkStateChanged:(NSNotification *)notification
+- (void)networkStateChanged:(NSNotification *)unusedNotification
 {
-    ASSERT_ARG(notification, notification);
-    WebThreadRun(^{
-        setOnLine(_notifier, [[[notification userInfo] objectForKey:getCPNetworkObserverReachable()] boolValue]);
-    });
+    UNUSED_PARAM(unusedNotification);
+    block();
 }
 
 @end
 
 namespace WebCore {
 
-NetworkStateNotifier::NetworkStateNotifier()
-    : m_isOnLine(false)
-    , m_isOnLineInitialized(false)
-{
-}
-    
-NetworkStateNotifier::~NetworkStateNotifier()
-{
-    [m_observer setNotifier:nullptr];
-}
-
-void NetworkStateNotifier::registerObserverIfNecessary() const
-{
-    if (!m_observer)
-        m_observer = adoptNS([[WebNetworkStateObserver alloc] initWithNotifier:this]);
-}
-
-bool NetworkStateNotifier::onLine() const
+void NetworkStateNotifier::updateStateWithoutNotifying()
 {
-    registerObserverIfNecessary();
-    if (!m_isOnLineInitialized) {
-        m_isOnLine = [[getCPNetworkObserverClass() sharedNetworkObserver] isNetworkReachable];
-        m_isOnLineInitialized = true;
-    }
-    return m_isOnLine;
+    m_isOnLine = [[getCPNetworkObserverClass() sharedNetworkObserver] isNetworkReachable];
 }
 
-void setOnLine(const NetworkStateNotifier* notifier, bool onLine)
+void NetworkStateNotifier::startObserving()
 {
-    ASSERT_ARG(notifier, notifier);
-    notifier->m_isOnLineInitialized = true;
-    if (onLine == notifier->m_isOnLine)
+    if (Settings::shouldOptOutOfNetworkStateObservation())
         return;
-    notifier->m_isOnLine = onLine;
-    notifier->notifyNetworkStateChange();
+    m_observer = adoptNS([[WebNetworkStateObserver alloc] initWithBlock:^ {
+        WebThreadRun(^ {
+            NetworkStateNotifier::singleton().updateStateSoon();
+        });
+    }]);
 }
 
 } // namespace WebCore
index 912f67bf1866d446cdee5f788fcc63289ce1e515..1e9d1c853577aebbcf6ceb213c069723b8378d79 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 <SystemConfiguration/SystemConfiguration.h>
 
-
 namespace WebCore {
 
-static const Seconds StateChangeTimerInterval { 2_s };
-
-void NetworkStateNotifier::updateState()
+void NetworkStateNotifier::updateStateWithoutNotifying()
 {
-    // Assume that we're offline until proven otherwise.
-    m_isOnLine = false;
-    
-    RetainPtr<CFStringRef> str = adoptCF(SCDynamicStoreKeyCreateNetworkInterface(0, kSCDynamicStoreDomainState));
-    
-    RetainPtr<CFPropertyListRef> propertyList = adoptCF(SCDynamicStoreCopyValue(m_store.get(), str.get()));
-    
-    if (!propertyList)
-        return;
-    
-    if (CFGetTypeID(propertyList.get()) != CFDictionaryGetTypeID())
+    auto key = adoptCF(SCDynamicStoreKeyCreateNetworkInterface(0, kSCDynamicStoreDomainState));
+    auto propertyList = adoptCF(SCDynamicStoreCopyValue(m_store.get(), key.get()));
+    if (!propertyList || CFGetTypeID(propertyList.get()) != CFDictionaryGetTypeID())
         return;
-    
-    CFArrayRef netInterfaces = (CFArrayRef)CFDictionaryGetValue((CFDictionaryRef)propertyList.get(), kSCDynamicStorePropNetInterfaces);
-    if (CFGetTypeID(netInterfaces) != CFArrayGetTypeID())
+
+    auto netInterfaces = CFDictionaryGetValue((CFDictionaryRef)propertyList.get(), kSCDynamicStorePropNetInterfaces);
+    if (!netInterfaces || CFGetTypeID(netInterfaces) != CFArrayGetTypeID())
         return;
-    
-    for (CFIndex i = 0; i < CFArrayGetCount(netInterfaces); i++) {
-        CFStringRef interface = (CFStringRef)CFArrayGetValueAtIndex(netInterfaces, i);
+
+    for (CFIndex i = 0; i < CFArrayGetCount((CFArrayRef)netInterfaces); i++) {
+        auto interface = CFArrayGetValueAtIndex((CFArrayRef)netInterfaces, i);
         if (CFGetTypeID(interface) != CFStringGetTypeID())
             continue;
-        
+
         // Ignore the loopback interface.
-        if (CFStringFind(interface, CFSTR("lo"), kCFCompareAnchored).location != kCFNotFound)
+        if (CFStringFind((CFStringRef)interface, CFSTR("lo"), kCFCompareAnchored).location != kCFNotFound)
             continue;
 
-        RetainPtr<CFStringRef> key = adoptCF(SCDynamicStoreKeyCreateNetworkInterfaceEntity(0, kSCDynamicStoreDomainState, interface, kSCEntNetIPv4));
-
-        RetainPtr<CFArrayRef> keyList = adoptCF(SCDynamicStoreCopyKeyList(m_store.get(), key.get()));
-    
+        auto key = adoptCF(SCDynamicStoreKeyCreateNetworkInterfaceEntity(0, kSCDynamicStoreDomainState, (CFStringRef)interface, kSCEntNetIPv4));
+        auto keyList = adoptCF(SCDynamicStoreCopyKeyList(m_store.get(), key.get()));
         if (keyList && CFArrayGetCount(keyList.get())) {
             m_isOnLine = true;
-            break;
+            return;
         }
     }
-}
 
-void NetworkStateNotifier::dynamicStoreCallback(SCDynamicStoreRef, CFArrayRef, void* info) 
-{
-    NetworkStateNotifier* notifier = static_cast<NetworkStateNotifier*>(info);
-    
-    // Calling updateState() could be expensive so we schedule a timer that will do it 
-    // when things have cooled down.
-    notifier->m_networkStateChangeTimer.startOneShot(StateChangeTimerInterval);
-}
-
-void NetworkStateNotifier::networkStateChangeTimerFired()
-{
-    bool oldOnLine = m_isOnLine;
-    
-    updateState();
-    
-    if (m_isOnLine == oldOnLine)
-        return;
-
-    notifyNetworkStateChange();
+    m_isOnLine = false;
 }
 
-NetworkStateNotifier::NetworkStateNotifier()
-    : m_isOnLine(false)
-    , m_networkStateChangeTimer(*this, &NetworkStateNotifier::networkStateChangeTimerFired)
+void NetworkStateNotifier::startObserving()
 {
     SCDynamicStoreContext context = { 0, this, 0, 0, 0 };
-    
-    m_store = adoptCF(SCDynamicStoreCreate(0, CFSTR("com.apple.WebCore"), dynamicStoreCallback, &context));
+    m_store = adoptCF(SCDynamicStoreCreate(0, CFSTR("com.apple.WebCore"), [] (SCDynamicStoreRef, CFArrayRef, void*) {
+        // Calling updateState() could be expensive so we coalesce calls with a timer.
+        singleton().updateStateSoon();
+    }, &context));
     if (!m_store)
         return;
 
-    RetainPtr<CFRunLoopSourceRef> configSource = adoptCF(SCDynamicStoreCreateRunLoopSource(0, m_store.get(), 0));
-    if (!configSource)
+    auto source = adoptCF(SCDynamicStoreCreateRunLoopSource(0, m_store.get(), 0));
+    if (!source)
         return;
 
-    CFRunLoopAddSource(CFRunLoopGetMain(), configSource.get(), kCFRunLoopCommonModes);
-    
-    RetainPtr<CFMutableArrayRef> keys = adoptCF(CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));
-    RetainPtr<CFMutableArrayRef> patterns = adoptCF(CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));
+    CFRunLoopAddSource(CFRunLoopGetMain(), source.get(), kCFRunLoopCommonModes);
 
-    RetainPtr<CFStringRef> key;
-    RetainPtr<CFStringRef> pattern;
+    auto keys = adoptCF(CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));
+    CFArrayAppendValue(keys.get(), adoptCF(SCDynamicStoreKeyCreateNetworkGlobalEntity(0, kSCDynamicStoreDomainState, kSCEntNetIPv4)).get());
+    CFArrayAppendValue(keys.get(), adoptCF(SCDynamicStoreKeyCreateNetworkGlobalEntity(0, kSCDynamicStoreDomainState, kSCEntNetDNS)).get());
 
-    key = adoptCF(SCDynamicStoreKeyCreateNetworkGlobalEntity(0, kSCDynamicStoreDomainState, kSCEntNetIPv4));
-    CFArrayAppendValue(keys.get(), key.get());
-
-    pattern = adoptCF(SCDynamicStoreKeyCreateNetworkInterfaceEntity(0, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4));
-    CFArrayAppendValue(patterns.get(), pattern.get());
-
-    key = adoptCF(SCDynamicStoreKeyCreateNetworkGlobalEntity(0, kSCDynamicStoreDomainState, kSCEntNetDNS));
-    CFArrayAppendValue(keys.get(), key.get());
+    auto patterns = adoptCF(CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));
+    CFArrayAppendValue(patterns.get(), adoptCF(SCDynamicStoreKeyCreateNetworkInterfaceEntity(0, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4)).get());
 
     SCDynamicStoreSetNotificationKeys(m_store.get(), keys.get(), patterns.get());
-    
-    updateState();
 }
     
 }
index 4bb457c0dc9f94bcf88c0dab7aabbea20e0fa7ba..b6c6ee6b1ba55e761991870371437552cdf78c28 100644 (file)
 
 namespace WebCore {
 
-void NetworkStateNotifier::updateState()
+void NetworkStateNotifier::updateStateWithoutNotifying()
 {
-    // Assume that we're online until proven otherwise.
-    m_isOnLine = true;
-    
-    Vector<char> buffer;
     DWORD size = 0;
-
     if (::GetAdaptersAddresses(AF_UNSPEC, 0, 0, 0, &size) != ERROR_BUFFER_OVERFLOW)
         return;
 
-    buffer.resize(size);
-    PIP_ADAPTER_ADDRESSES addresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(buffer.data());
-
-    if (::GetAdaptersAddresses(AF_UNSPEC, 0, 0, addresses, &size) != ERROR_SUCCESS) {
-        // We couldn't determine whether we're online or not, so assume that we are.
+    Vector<char> buffer(size);
+    auto addresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(buffer.data());
+    if (::GetAdaptersAddresses(AF_UNSPEC, 0, 0, addresses, &size) != ERROR_SUCCESS)
         return;
-    }
 
     for (; addresses; addresses = addresses->Next) {
-        if (addresses->IfType == MIB_IF_TYPE_LOOPBACK)
-            continue;
-
-        if (addresses->OperStatus != IfOperStatusUp)
-            continue;
-
-        // We found an interface that was up.
-        return;
+        if (addresses->IfType != MIB_IF_TYPE_LOOPBACK && addresses->OperStatus == IfOperStatusUp) {
+            // We found an interface that was up.
+            m_isOnLine = true;
+            return;
+        }
     }
-    
-    // We didn't find any valid interfaces, so we must be offline.
-    m_isOnLine = false;
-}
-
-void NetworkStateNotifier::addressChanged()
-{
-    bool oldOnLine = m_isOnLine;
-    
-    updateState();
-
-    if (m_isOnLine == oldOnLine)
-        return;
 
-    notifyNetworkStateChange();
+    m_isOnLine = false;
 }
 
-void CALLBACK NetworkStateNotifier::addrChangeCallback(void* context, BOOLEAN timedOut)
+void CALLBACK NetworkStateNotifier::addressChangeCallback(void*, BOOLEAN timedOut)
 {
-    NetworkStateNotifier* notifier = static_cast<NetworkStateNotifier*>(context);
-
     // NotifyAddrChange only notifies us of a single address change. Now that we've been notified,
     // we need to call it again so we'll get notified the *next* time.
-    notifier->registerForAddressChange();
+    singleton().registerForAddressChange();
 
-    callOnMainThread([notifier] {
-        notifier->addressChanged();
+    callOnMainThread([] {
+        singleton().updateStateSoon();
     });
 }
 
@@ -99,17 +73,11 @@ void NetworkStateNotifier::registerForAddressChange()
     ::NotifyAddrChange(&handle, &m_overlapped);
 }
 
-NetworkStateNotifier::NetworkStateNotifier()
-    : m_isOnLine(false)
+void NetworkStateNotifier::startObserving()
 {
-    updateState();
-
     memset(&m_overlapped, 0, sizeof(m_overlapped));
-
     m_overlapped.hEvent = ::CreateEvent(0, false, false, 0);
-
-    ::RegisterWaitForSingleObject(&m_waitHandle, m_overlapped.hEvent, addrChangeCallback, this, INFINITE, 0);
-
+    ::RegisterWaitForSingleObject(&m_waitHandle, m_overlapped.hEvent, addressChangeCallback, nullptr, INFINITE, 0);
     registerForAddressChange();
 }
 
index 461bf27f833656e1582d35ae841541b198b40473..c706955957c7095bd8ab0c582f01c24f08a005c8 100644 (file)
@@ -159,16 +159,14 @@ struct ScriptNameCodeMapHashTraits : public HashTraits<String> {
     static const int minimumTableSize = WTF::HashTableCapacityForSize<WTF_ARRAY_LENGTH(scriptNameCodeList)>::value;
 };
 
-typedef HashMap<String, UScriptCode, ASCIICaseInsensitiveHash, ScriptNameCodeMapHashTraits> ScriptNameCodeMap;
-
 UScriptCode scriptNameToCode(const String& scriptName)
 {
-    static NeverDestroyed<ScriptNameCodeMap> scriptNameCodeMap = []() {
-        ScriptNameCodeMap map;
+    static const auto scriptNameCodeMap = makeNeverDestroyed([] {
+        HashMap<String, UScriptCode, ASCIICaseInsensitiveHash, ScriptNameCodeMapHashTraits> map;
         for (auto& nameAndCode : scriptNameCodeList)
             map.add(ASCIILiteral(nameAndCode.name), nameAndCode.code);
         return map;
-    }();
+    }());
 
     auto it = scriptNameCodeMap.get().find(scriptName);
     if (it != scriptNameCodeMap.get().end())
@@ -386,16 +384,14 @@ struct LocaleScriptMapHashTraits : public HashTraits<String> {
     static const int minimumTableSize = WTF::HashTableCapacityForSize<WTF_ARRAY_LENGTH(localeScriptList)>::value;
 };
 
-typedef HashMap<String, UScriptCode, ASCIICaseInsensitiveHash, LocaleScriptMapHashTraits> LocaleScriptMap;
-
 UScriptCode localeToScriptCodeForFontSelection(const String& locale)
 {
-    static NeverDestroyed<LocaleScriptMap> localeScriptMap = []() {
-        LocaleScriptMap map;
+    static const auto localeScriptMap = makeNeverDestroyed([] {
+        HashMap<String, UScriptCode, ASCIICaseInsensitiveHash, LocaleScriptMapHashTraits> map;
         for (auto& localeAndScript : localeScriptList)
             map.add(ASCIILiteral(localeAndScript.locale), localeAndScript.script);
         return map;
-    }();
+    }());
 
     String canonicalLocale = locale;
     canonicalLocale.replace('-', '_');
index 91053b4003d84e6efb2155ba733ce3b1d902d88c..29334326b9dd63e0044976e518ea7d8f3f804742 100644 (file)
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef LocalizedDateCache_h
-#define LocalizedDateCache_h
+#pragma once
+
+// FIXME: Rename this file to LocalizedDataCacheIOS.h and remove this guard.
+#if PLATFORM(IOS)
 
 #include "DateComponents.h"
 #include "FontCascade.h"
 #include <wtf/HashMap.h>
-#include <wtf/NeverDestroyed.h>
 #include <wtf/RetainPtr.h>
 
-// FIXME: Rename this file to LocalizedDataCacheIOS.mm and remove this guard.
-#if PLATFORM(IOS)
-
 namespace WebCore {
     
 class MeasureTextClient {
@@ -75,4 +73,3 @@ LocalizedDateCache& localizedDateCache();
 } // namespace WebCore
 
 #endif // PLATFORM(IOS)
-#endif // LocalizedDateCache_h
index aba58c1ec305605a4af0dbc100f7d5644e6db1c0..b5d5cb0d84ed20577428ecc3d62799375852ad57 100644 (file)
 #import "config.h"
 #import "LocalizedDateCache.h"
 
+// FIXME: Rename this file to LocalizedDataCacheIOS.mm and consider removing this guard.
+#if PLATFORM(IOS)
+
 #import "FontCascade.h"
 #import "TextRun.h"
+#import <CoreFoundation/CFNotificationCenter.h>
 #import <math.h>
 #import <wtf/Assertions.h>
+#import <wtf/NeverDestroyed.h>
 #import <wtf/StdLibExtras.h>
-#import <CoreFoundation/CFNotificationCenter.h>
-
-// FIXME: Rename this file to LocalizedDataCacheIOS.mm and remove this guard.
-#if PLATFORM(IOS)
 
 using namespace std;
 
index 4d293d81f2c1d9298472484ef31a39928e19e2a3..e5d80272176f99dccde7e2ccb7756069294b833f 100644 (file)
@@ -35,8 +35,8 @@ namespace WebCore {
 
 RenderTheme& RenderTheme::singleton()
 {
-    static NeverDestroyed<Ref<RenderTheme>> theme(RenderThemeWPE::create());
-    return theme.get();
+    static NeverDestroyed<RenderThemeWPE> theme;
+    return theme;
 }
 
 void RenderThemeWPE::updateCachedSystemFontDescription(CSSValueID, FontCascadeDescription&) const
index 602491a1de3b561e06fd56d238b0d0b180112b17..b21460bbb5411eefbea175d6fb0ac363eca77f21 100644 (file)
 #pragma once
 
 #include "RenderTheme.h"
-#include <wtf/Ref.h>
 
 namespace WebCore {
 
 class RenderThemeWPE final : public RenderTheme {
 public:
-    static Ref<RenderTheme> create()
-    {
-        return adoptRef(*new RenderThemeWPE);
-    }
+    friend NeverDestroyed<RenderThemeWPE>;
 
     String extraDefaultStyleSheet() override;
 #if ENABLE(VIDEO)
index e457e152715dc6bb5d89f38dc1c7b4de62416ead..c72801ddf035af3f6e62e039675cc7fbadd6851c 100644 (file)
@@ -1,7 +1,5 @@
 /*
- * This file is part of the theme implementation for form controls in WebCore.
- *
- * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc.
+ * Copyright (C) 2005-2017 Apple Inc. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
 
 #pragma once
 
-#include "BorderData.h"
 #include "ControlStates.h"
-#include "FillLayer.h"
+#include "PaintInfo.h"
+#include "PopupMenuStyle.h"
+#include "ScrollTypes.h"
+
 #if USE(NEW_THEME)
 #include "Theme.h"
 #else
 #include "ThemeTypes.h"
 #endif
-#include "PaintInfo.h"
-#include "PopupMenuStyle.h"
-#include "ScrollTypes.h"
-#include <wtf/RefCounted.h>
 
 namespace WebCore {
 
-class CSSStyleSheet;
+class BorderData;
 class Element;
 class FileList;
+class FillLayer;
 class HTMLInputElement;
 class Icon;
-class Page;
-class PopupMenu;
 class RenderAttachment;
 class RenderBox;
-class RenderMenuList;
 class RenderMeter;
 class RenderObject;
 class RenderProgress;
-class RenderSnapshottedPlugIn;
+class RenderStyle;
 class StyleResolver;
 
-class RenderTheme : public RefCounted<RenderTheme> {
+class RenderTheme {
 protected:
     RenderTheme();
 
-public:
     virtual ~RenderTheme() { }
 
-    // This function is to be implemented in your platform-specific theme implementation to hand back the
+public:
+    // This function is to be implemented in platform-specific theme implementations to hand back the
     // appropriate platform theme.
     WEBCORE_EXPORT static RenderTheme& singleton();
 
index 18a24521dcc0f6a401f21cee1062715c7a428887..d9c216fc3149d3f6c9acbb4546ff4fc2aed6c3bc 100644 (file)
 
 namespace WebCore {
 
-Ref<RenderTheme> RenderThemeGtk::create()
-{
-    return adoptRef(*new RenderThemeGtk());
-}
-
 RenderTheme& RenderTheme::singleton()
 {
-    static NeverDestroyed<Ref<RenderTheme>> theme(RenderThemeGtk::create());
-    return theme.get();
+    static NeverDestroyed<RenderThemeGtk> theme;
+    return theme;
 }
 
 static double getScreenDPI()
index 64a4d89ff452bb623fd808a569500aa6ccea4cf5..012fdde0f8932878cb01cf9da96cf2c77dcc4ebd 100644 (file)
@@ -33,7 +33,7 @@ namespace WebCore {
 
 class RenderThemeGtk final : public RenderTheme {
 public:
-    static Ref<RenderTheme> create();
+    friend NeverDestroyed<RenderThemeGtk>;
 
 #if ENABLE(DATALIST_ELEMENT)
     // Returns size of one slider tick mark for a horizontal track.
index b507e376918736f3e87ca78fe9ea862c10853b8f..d15243d718c69943dc4a9bc6fbc8d0c91a673dbb 100644 (file)
@@ -33,11 +33,12 @@ namespace WebCore {
     
 class RenderStyle;
 class GraphicsContext;
+
 struct AttachmentLayout;
 
 class RenderThemeIOS final : public RenderThemeCocoa {
 public:
-    static Ref<RenderTheme> create();
+    friend NeverDestroyed<RenderThemeIOS>;
 
     static void adjustRoundBorderRadius(RenderStyle&, RenderBox&);
 
index c7016f62286c21f6262997190cc4b7fb7410ea17..d7c8bc50f331e6e60ee1d06d5f2366cdf5d87310 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2005-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
@@ -24,6 +24,7 @@
  */
 
 #import "config.h"
+#import "RenderThemeIOS.h"
 
 #if PLATFORM(IOS)
 
@@ -60,7 +61,6 @@
 #import "RenderObject.h"
 #import "RenderProgress.h"
 #import "RenderStyle.h"
-#import "RenderThemeIOS.h"
 #import "RenderView.h"
 #import "RuntimeEnabledFeatures.h"
 #import "UIKitSPI.h"
@@ -297,13 +297,8 @@ RenderThemeIOS::RenderThemeIOS()
 
 RenderTheme& RenderTheme::singleton()
 {
-    static NeverDestroyed<Ref<RenderTheme>> theme(RenderThemeIOS::create());
-    return theme.get();
-}
-
-Ref<RenderTheme> RenderThemeIOS::create()
-{
-    return adoptRef(*new RenderThemeIOS);
+    static NeverDestroyed<RenderThemeIOS> theme;
+    return theme;
 }
 
 static String& _contentSizeCategory()
index 1d4532d924ea15d063d008710c43d310f11d8fa0..a4874a0116c7dcf1385fa313b517b3b23fa6aa8d 100644 (file)
@@ -1,7 +1,5 @@
 /*
- * This file is part of the theme implementation for form controls in WebCore.
- *
- * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc.
+ * Copyright (C) 2005-2017 Apple Inc. All rights reserved.
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -38,142 +36,142 @@ namespace WebCore {
 
 class RenderProgress;
 class RenderStyle;
+
 struct AttachmentLayout;
 
 class RenderThemeMac final : public RenderThemeCocoa {
 public:
-    static Ref<RenderTheme> create();
+    friend NeverDestroyed<RenderThemeMac>;
 
     // A method asking if the control changes its tint when the window has focus or not.
-    bool controlSupportsTints(const RenderObject&) const override;
+    bool controlSupportsTints(const RenderObject&) const final;
 
     // A general method asking if any control tinting is supported at all.
-    bool supportsControlTints() const override { return true; }
+    bool supportsControlTints() const final { return true; }
 
-    void adjustRepaintRect(const RenderObject&, FloatRect&) override;
+    void adjustRepaintRect(const RenderObject&, FloatRect&) final;
 
-    bool isControlStyled(const RenderStyl