Refactor to simplify broadcasting to all media elements
authordarin@apple.com <darin@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 27 Dec 2019 17:58:02 +0000 (17:58 +0000)
committerdarin@apple.com <darin@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 27 Dec 2019 17:58:02 +0000 (17:58 +0000)
https://bugs.webkit.org/show_bug.cgi?id=205567

Reviewed by Eric Carlson.

Source/WebCore:

Over time, we have accumulated many different sets of all the media elements.
With the goal of being a bit abstract and not building too much behavior into
the Document object, we ended up with unnecessary complexity, and many sets
of all the HTMLMediaElement objects. This is a first cut at reducing that complexity.
At the same time, the refactoring makes all the iteration use a safe algorithm that
builds a vector of Ref<HTMLMediaElement>, safe even if the work done for each
media element calls out to arbitrary DOM operations.

Separately, this patch also includes some name changes that still say "atomic"
instead of "atom" left over from our renaming of AtomicString to AtomString.

* Headers.cmake: Removed ApplicationStateChangeListener.h.
* WebCore.xcodeproj/project.pbxproj: Ditto.

* css/StyleSheetContents.cpp:
(WebCore::StyleSheetContents::estimatedSizeInBytes const): Reworded comment to
say "atom".

* dom/ContainerNode.cpp:
(WebCore::ContainerNode::getElementsByName): Updated for "atomic" -> "atom".
(WebCore::ContainerNode::radioNodeList): Ditto.

* dom/Document.cpp:
(WebCore::Document::visibilityStateChanged): Moved the code from
the notifyMediaCaptureOfVisibilityChanged in here. No need for a separate
function for the two lines of code.
(WebCore::Document::registerMediaElement): Added. Replaces the multiple registrations
that each media element would do.
(WebCore::Document::unregisterMediaElement): Ditto.
(WebCore::Document::forEachMediaElement): Added. Safely iterates the media elements
and calls a function on each of them.
(WebCore::Document::registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks): Deleted.
(WebCore::Document::unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks): Deleted.
(WebCore::Document::allowsMediaDocumentInlinePlaybackChanged): Deleted.
(WebCore::Document::mediaVolumeDidChange): Deleted.
(WebCore::Document::registerForMediaVolumeCallbacks): Deleted.
(WebCore::Document::unregisterForMediaVolumeCallbacks): Deleted.
(WebCore::Document::privateBrowsingStateDidChange): Use forEachMediaElement to call
privateBrowsingStateDidChange on each media element rather than keeping a separate registry.
(WebCore::Document::registerForPrivateBrowsingStateChangedCallbacks): Deleted.
(WebCore::Document::unregisterForPrivateBrowsingStateChangedCallbacks): Deleted.
(WebCore::Document::registerForCaptionPreferencesChangedCallbacks): Updated the type
to be HTMLMediaElement rather than just Element.
(WebCore::Document::unregisterForCaptionPreferencesChangedCallbacks): Ditto.
(WebCore::Document::registerForPageScaleFactorChangedCallbacks): Deleted.
(WebCore::Document::unregisterForPageScaleFactorChangedCallbacks): Deleted.
(WebCore::Document::pageScaleFactorChangedAndStable): Deleted.
(WebCore::Document::registerForUserInterfaceLayoutDirectionChangedCallbacks): Deleted.
(WebCore::Document::unregisterForUserInterfaceLayoutDirectionChangedCallbacks): Deleted.
(WebCore::Document::userInterfaceLayoutDirectionChanged): Deleted.
(WebCore::Document::notifyMediaCaptureOfVisibilityChanged): Deleted.
(WebCore::Document::registerForMediaStreamStateChangeCallbacks): Deleted.
(WebCore::Document::unregisterForMediaStreamStateChangeCallbacks): Deleted.
(WebCore::Document::mediaStreamCaptureStateChanged): Use forEachMediaElement to call
mediaStreamCaptureStarted on each media element rather than keeping a separate registry.
(WebCore::Document::addApplicationStateChangeListener): Deleted.
(WebCore::Document::removeApplicationStateChangeListener): Deleted.
(WebCore::Document::forEachApplicationStateChangeListener): Deleted.

* dom/Document.h: Clean up forward declarations a bit. Updated for above changes,
removing many function and data members.

* dom/Element.cpp:
(WebCore::Element::spellcheckAttributeState const): Deleted.
(WebCore::Element::isSpellCheckingEnabled const): Refactored to merge in the logic
from the spellcheckAttributeState function. The combined function is both a bit easier
to understand and smaller than the two functions were.

* dom/Element.h: Removed some unneeded includes. Removed SpellcheckAttributeState.
Made fastAttributeLookupAllowed private. Removed mediaVolumeDidChange,
privateBrowsingStateDidChange, captionPreferencesChanged, and spellcheckAttributeState.

* dom/FullscreenManager.cpp: Removed unneeded includes.
(WebCore::FullscreenManager::willEnterFullscreen): Use is<HTMLMediaElement> instead of
calling isMediaElement directly.

* dom/NameNodeList.cpp:
(WebCore::NameNodeList::~NameNodeList): Updated for "atomic" -> "atom".
* dom/Node.cpp:
(WebCore::NodeListsNodeData::invalidateCaches): Ditto.
(WebCore::NodeListsNodeData::invalidateCachesForAttribute): Ditto.

* dom/NodeRareData.h: Removed unneeded includes. Updated for "atomic" -> "atom".
Made a few coding style tweaks.

* dom/TreeScope.cpp:
(WebCore::TreeScope::getElementById const): Updated for "atomic" -> "atom".

* html/HTMLMediaElement.cpp:
(WebCore::documentToElementSetMap): Deleted.
(WebCore::addElementToDocumentMap): Deleted.
(WebCore::removeElementFromDocumentMap): Deleted.
(WebCore::HTMLMediaElement::registerWithDocument): Added call to registerMediaElement,
removed eight now-obsolete registrations.
(WebCore::HTMLMediaElement::unregisterWithDocument): Ditto.
(WebCore::HTMLMediaElement::mediaVolumeDidChange): Added an #if !PLATFORM(IOS_FAMILY)
to preserve the current behavior, since this was not registered for PLATFORM(IOS_FAMILY)
before. This should be revisited because it's not clear this platform difference is needed.
(WebCore::HTMLMediaElement::privateBrowsingStateDidChange): Ditto.
(WebCore::HTMLMediaElement::setMediaGroup): Change to use Document::forEachMediaElement
so we don't need to keep our own global set of media elements for each document. Required
a little bit of code structure change. Added a FIXME because the decision about which
media element is selected depends on hash table order as it always has; seems inappropriate.
(WebCore::HTMLMediaElement::setMediaControlsDependOnPageScaleFactor): Removed the code
to register/unregister.
(WebCore::HTMLMediaElement::pageScaleFactorChanged): Only do the work if it's needed;
this replicates the old behavior which was accomplished by registering/unregistering.

* html/HTMLMediaElement.h: Removed the overrides for various virtual member functions.
Instead these are now public functions. Also removed ApplicationStateChangeListener.

* html/LabelableElement.cpp:
(WebCore::LabelableElement::labels): Updated for "atomic" -> "atom".
* html/LabelsNodeList.cpp:
(WebCore::LabelsNodeList::~LabelsNodeList): Ditto.
* html/RadioNodeList.cpp:
(WebCore::RadioNodeList::~RadioNodeList): Ditto.
* html/parser/HTMLDocumentParser.cpp:
(WebCore::HTMLDocumentParser::constructTreeFromHTMLToken): Ditto.
* loader/appcache/ApplicationCacheStorage.cpp:
(WebCore::parseHeader): Ditto.

* page/ApplicationStateChangeListener.h: Removed.

* page/Page.cpp:
(WebCore::Page::renderTreeSize const): Use forEachDocument.
(WebCore::Page::setNeedsRecalcStyleInAllFrames): Ditto.
(WebCore::Page::unmarkAllTextMatches): Ditto.
(WebCore::Page::editableElementsInRect const): Ditto.
(WebCore::Page::setMediaVolume): Tweaked range check so it will reject
NaN values. Use forEachMediaElement to call mediaVolumeDidChange,
eliminating the need for Document::mediaVolumeDidChange.
(WebCore::Page::setPageScaleFactor): Refactored to eliminate large blocks
of repeated code. Use forEachMediaElement to call pageScaleFactorChanged,
eliminating the need for Document::pageScaleFactorChangedAndStable.
(WebCore::Page::setUserInterfaceLayoutDirection): Use forEachMediaElement
to call userInterfaceLayoutDirectionChanged, eliminating the need for
Document::userInterfaceLayoutDirectionChanged.
(WebCore::Page::updateMediaElementRateChangeRestrictions): Use
forEachMediaElement to call updateRateChangeRestrictionas. The old code
would call this on all media elements in the current web process, which
means the functions would be called many times for the same media element.
(WebCore::Page::updateRendering): Use forEachDocument consistently for
all the document iteration. Before it was used for half the function and not
used for the other half; no obvious reason for the differece.
(WebCore::Page::suspendScriptedAnimations): Use forEachDocument.
(WebCore::Page::resumeScriptedAnimations): Ditto.
(WebCore::updateScriptedAnimationsThrottlingReason): Ditto.
(WebCore::Page::userStyleSheetLocationChanged): Ditto.
(WebCore::Page::invalidateStylesForAllLinks): Ditto.
(WebCore::Page::invalidateStylesForLink): Ditto.
(WebCore::Page::invalidateInjectedStyleSheetCacheInAllFrames): Ditto.
(WebCore::Page::setTimerThrottlingState): Ditto.
(WebCore::Page::dnsPrefetchingStateChanged): Ditto.
(WebCore::Page::storageBlockingStateChanged): Ditto.
(WebCore::Page::updateIsPlayingMedia): Ditto.
(WebCore::Page::setMuted): Ditto.
(WebCore::Page::stopMediaCapture): Ditto.
(WebCore::Page::stopAllMediaPlayback): Ditto.
(WebCore::Page::suspendAllMediaPlayback): Ditto.
(WebCore::Page::resumeAllMediaPlayback): Ditto.
(WebCore::Page::suspendAllMediaBuffering): Ditto.
(WebCore::Page::resumeAllMediaBuffering): Ditto.
(WebCore::setSVGAnimationsState): Deleted.
(WebCore::Page::setIsVisibleInternal): Use forEachDocument to call
suspend/resumeDeviceMotionAndOrientationUpdates, obviating the need for
Page::suspend/resumeDeviceMotionAndOrientationUpdates. Use
forEachDocument to call pause/unpauseAnimations, obviating the need for
WebCore::setSVGAnimationsState. Use forEachDocument to call
visibilityStateChanged, removing the need to write out a loop that
gathers the documents into a vector.
(WebCore::Page::suspendDeviceMotionAndOrientationUpdates): Deleted.
(WebCore::Page::resumeDeviceMotionAndOrientationUpdates): Deleted.
(WebCore::Page::captionPreferencesChanged): Use forEachDocument.
(WebCore::Page::setSessionID): Ditto.
(WebCore::Page::setPlaybackTarget): Ditto.
(WebCore::Page::playbackTargetAvailabilityDidChange): Ditto.
(WebCore::Page::setShouldPlayToPlaybackTarget): Ditto.
(WebCore::Page::playbackTargetPickerWasDismissed): Ditto.
(WebCore::Page::setAllowsMediaDocumentInlinePlayback): Use
forEachMediaElement to call allowsMediaDocumentInlinePlaybackChanged,
obviating the need for Document::allowsMediaDocumentInlinePlaybackChanged.
(WebCore::Page::setUnobscuredSafeAreaInsets): Use forEachDocument.
(WebCore::Page::setUseSystemAppearance): Ditto.
(WebCore::Page::setFullscreenInsets): Ditto.
(WebCore::Page::setFullscreenAutoHideDuration): Ditto.
(WebCore::Page::setFullscreenControlsHidden): Ditto.
(WebCore::Page::forEachDocument): Merged the collectDocuments function
in since it's only used here.
(WebCore::Page::collectDocuments): Deleted.
(WebCore::Page::forEachMediaElement): Added.
(WebCore::Page::applicationWillResignActive): Use forEachMediaElement,
eliminating the need for forEachApplicationStateChangeListener.
(WebCore::Page::applicationDidBecomeActive): Ditto.
(WebCore::Page::recomputeTextAutoSizingInAllFrames): Use forEachDocument.

* page/Page.h: Removed unneeded forward declarations. Removed unused
FindDirection enum. Tweaked formatting. Use bool instead of uint8_t as
underlying type for enum class with only two values. Updated for changes above.

* platform/text/TextEncoding.cpp:
(WebCore::TextEncoding::TextEncoding): Updated for "atomic" -> "atom".
(WebCore::TextEncoding::domName const): Ditto.
(WebCore::TextEncoding::usesVisualOrdering const): Ditto.
* platform/text/TextEncodingRegistry.cpp:
(WebCore::addToTextEncodingNameMap): Ditto.
(WebCore::addToTextCodecMap): Ditto.
(WebCore::pruneBlacklistedCodecs): Ditto.
(WebCore::addEncodingName): Ditto.
(WebCore::atomCanonicalTextEncodingName): Ditto.
* platform/text/TextEncodingRegistry.h: Ditto.

* xml/XPathFunctions.cpp:
(WebCore::XPath::atomicSubstring): Deleted.
(WebCore::XPath::toStringView): Added. Later could make a StringBuilder member
function instead.
(WebCore::XPath::FunId::evaluate const): Use toStringView and StringView::substring
instead of "atomicSubstring", since getElementById can be called on a StringView
and there's no need to allocate/deallocate an AtomString just to check if it exists.

Source/WebKit:

* WebProcess/InjectedBundle/InjectedBundleHitTestResult.cpp:
(WebKit::InjectedBundleHitTestResult::mediaType const): Use is<HTMLMediaElement>.

Source/WebKitLegacy/win:

* AccessibleBase.cpp:
(AccessibleBase::get_attribute): Updated for "atomic" -> "atom".

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

33 files changed:
Source/WebCore/ChangeLog
Source/WebCore/Headers.cmake
Source/WebCore/WebCore.xcodeproj/project.pbxproj
Source/WebCore/css/StyleSheetContents.cpp
Source/WebCore/dom/ContainerNode.cpp
Source/WebCore/dom/Document.cpp
Source/WebCore/dom/Document.h
Source/WebCore/dom/Element.cpp
Source/WebCore/dom/Element.h
Source/WebCore/dom/EventPath.h
Source/WebCore/dom/FullscreenManager.cpp
Source/WebCore/dom/NameNodeList.cpp
Source/WebCore/dom/Node.cpp
Source/WebCore/dom/NodeRareData.h
Source/WebCore/dom/TreeScope.cpp
Source/WebCore/html/HTMLMediaElement.cpp
Source/WebCore/html/HTMLMediaElement.h
Source/WebCore/html/LabelableElement.cpp
Source/WebCore/html/LabelsNodeList.cpp
Source/WebCore/html/RadioNodeList.cpp
Source/WebCore/html/parser/HTMLDocumentParser.cpp
Source/WebCore/loader/appcache/ApplicationCacheStorage.cpp
Source/WebCore/page/ApplicationStateChangeListener.h [deleted file]
Source/WebCore/page/Page.cpp
Source/WebCore/page/Page.h
Source/WebCore/platform/text/TextEncoding.cpp
Source/WebCore/platform/text/TextEncodingRegistry.cpp
Source/WebCore/platform/text/TextEncodingRegistry.h
Source/WebCore/xml/XPathFunctions.cpp
Source/WebKit/ChangeLog
Source/WebKit/WebProcess/InjectedBundle/InjectedBundleHitTestResult.cpp
Source/WebKitLegacy/win/AccessibleBase.cpp
Source/WebKitLegacy/win/ChangeLog

index c16952a..a55611f 100644 (file)
@@ -1,3 +1,230 @@
+2019-12-23  Darin Adler  <darin@apple.com>
+
+        Refactor to simplify broadcasting to all media elements
+        https://bugs.webkit.org/show_bug.cgi?id=205567
+
+        Reviewed by Eric Carlson.
+
+        Over time, we have accumulated many different sets of all the media elements.
+        With the goal of being a bit abstract and not building too much behavior into
+        the Document object, we ended up with unnecessary complexity, and many sets
+        of all the HTMLMediaElement objects. This is a first cut at reducing that complexity.
+        At the same time, the refactoring makes all the iteration use a safe algorithm that
+        builds a vector of Ref<HTMLMediaElement>, safe even if the work done for each
+        media element calls out to arbitrary DOM operations.
+
+        Separately, this patch also includes some name changes that still say "atomic"
+        instead of "atom" left over from our renaming of AtomicString to AtomString.
+
+        * Headers.cmake: Removed ApplicationStateChangeListener.h.
+        * WebCore.xcodeproj/project.pbxproj: Ditto.
+
+        * css/StyleSheetContents.cpp:
+        (WebCore::StyleSheetContents::estimatedSizeInBytes const): Reworded comment to
+        say "atom".
+
+        * dom/ContainerNode.cpp:
+        (WebCore::ContainerNode::getElementsByName): Updated for "atomic" -> "atom".
+        (WebCore::ContainerNode::radioNodeList): Ditto.
+
+        * dom/Document.cpp:
+        (WebCore::Document::visibilityStateChanged): Moved the code from
+        the notifyMediaCaptureOfVisibilityChanged in here. No need for a separate
+        function for the two lines of code.
+        (WebCore::Document::registerMediaElement): Added. Replaces the multiple registrations
+        that each media element would do.
+        (WebCore::Document::unregisterMediaElement): Ditto.
+        (WebCore::Document::forEachMediaElement): Added. Safely iterates the media elements
+        and calls a function on each of them.
+        (WebCore::Document::registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks): Deleted.
+        (WebCore::Document::unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks): Deleted.
+        (WebCore::Document::allowsMediaDocumentInlinePlaybackChanged): Deleted.
+        (WebCore::Document::mediaVolumeDidChange): Deleted.
+        (WebCore::Document::registerForMediaVolumeCallbacks): Deleted.
+        (WebCore::Document::unregisterForMediaVolumeCallbacks): Deleted.
+        (WebCore::Document::privateBrowsingStateDidChange): Use forEachMediaElement to call
+        privateBrowsingStateDidChange on each media element rather than keeping a separate registry.
+        (WebCore::Document::registerForPrivateBrowsingStateChangedCallbacks): Deleted.
+        (WebCore::Document::unregisterForPrivateBrowsingStateChangedCallbacks): Deleted.
+        (WebCore::Document::registerForCaptionPreferencesChangedCallbacks): Updated the type
+        to be HTMLMediaElement rather than just Element.
+        (WebCore::Document::unregisterForCaptionPreferencesChangedCallbacks): Ditto.
+        (WebCore::Document::registerForPageScaleFactorChangedCallbacks): Deleted.
+        (WebCore::Document::unregisterForPageScaleFactorChangedCallbacks): Deleted.
+        (WebCore::Document::pageScaleFactorChangedAndStable): Deleted.
+        (WebCore::Document::registerForUserInterfaceLayoutDirectionChangedCallbacks): Deleted.
+        (WebCore::Document::unregisterForUserInterfaceLayoutDirectionChangedCallbacks): Deleted.
+        (WebCore::Document::userInterfaceLayoutDirectionChanged): Deleted.
+        (WebCore::Document::notifyMediaCaptureOfVisibilityChanged): Deleted.
+        (WebCore::Document::registerForMediaStreamStateChangeCallbacks): Deleted.
+        (WebCore::Document::unregisterForMediaStreamStateChangeCallbacks): Deleted.
+        (WebCore::Document::mediaStreamCaptureStateChanged): Use forEachMediaElement to call
+        mediaStreamCaptureStarted on each media element rather than keeping a separate registry.
+        (WebCore::Document::addApplicationStateChangeListener): Deleted.
+        (WebCore::Document::removeApplicationStateChangeListener): Deleted.
+        (WebCore::Document::forEachApplicationStateChangeListener): Deleted.
+
+        * dom/Document.h: Clean up forward declarations a bit. Updated for above changes,
+        removing many function and data members.
+
+        * dom/Element.cpp:
+        (WebCore::Element::spellcheckAttributeState const): Deleted.
+        (WebCore::Element::isSpellCheckingEnabled const): Refactored to merge in the logic
+        from the spellcheckAttributeState function. The combined function is both a bit easier
+        to understand and smaller than the two functions were.
+
+        * dom/Element.h: Removed some unneeded includes. Removed SpellcheckAttributeState.
+        Made fastAttributeLookupAllowed private. Removed mediaVolumeDidChange,
+        privateBrowsingStateDidChange, captionPreferencesChanged, and spellcheckAttributeState.
+
+        * dom/FullscreenManager.cpp: Removed unneeded includes.
+        (WebCore::FullscreenManager::willEnterFullscreen): Use is<HTMLMediaElement> instead of
+        calling isMediaElement directly.
+
+        * dom/NameNodeList.cpp:
+        (WebCore::NameNodeList::~NameNodeList): Updated for "atomic" -> "atom".
+        * dom/Node.cpp:
+        (WebCore::NodeListsNodeData::invalidateCaches): Ditto.
+        (WebCore::NodeListsNodeData::invalidateCachesForAttribute): Ditto.
+
+        * dom/NodeRareData.h: Removed unneeded includes. Updated for "atomic" -> "atom".
+        Made a few coding style tweaks.
+
+        * dom/TreeScope.cpp:
+        (WebCore::TreeScope::getElementById const): Updated for "atomic" -> "atom".
+
+        * html/HTMLMediaElement.cpp:
+        (WebCore::documentToElementSetMap): Deleted.
+        (WebCore::addElementToDocumentMap): Deleted.
+        (WebCore::removeElementFromDocumentMap): Deleted.
+        (WebCore::HTMLMediaElement::registerWithDocument): Added call to registerMediaElement,
+        removed eight now-obsolete registrations.
+        (WebCore::HTMLMediaElement::unregisterWithDocument): Ditto.
+        (WebCore::HTMLMediaElement::mediaVolumeDidChange): Added an #if !PLATFORM(IOS_FAMILY)
+        to preserve the current behavior, since this was not registered for PLATFORM(IOS_FAMILY)
+        before. This should be revisited because it's not clear this platform difference is needed.
+        (WebCore::HTMLMediaElement::privateBrowsingStateDidChange): Ditto.
+        (WebCore::HTMLMediaElement::setMediaGroup): Change to use Document::forEachMediaElement
+        so we don't need to keep our own global set of media elements for each document. Required
+        a little bit of code structure change. Added a FIXME because the decision about which
+        media element is selected depends on hash table order as it always has; seems inappropriate.
+        (WebCore::HTMLMediaElement::setMediaControlsDependOnPageScaleFactor): Removed the code
+        to register/unregister.
+        (WebCore::HTMLMediaElement::pageScaleFactorChanged): Only do the work if it's needed;
+        this replicates the old behavior which was accomplished by registering/unregistering.
+
+        * html/HTMLMediaElement.h: Removed the overrides for various virtual member functions.
+        Instead these are now public functions. Also removed ApplicationStateChangeListener.
+
+        * html/LabelableElement.cpp:
+        (WebCore::LabelableElement::labels): Updated for "atomic" -> "atom".
+        * html/LabelsNodeList.cpp:
+        (WebCore::LabelsNodeList::~LabelsNodeList): Ditto.
+        * html/RadioNodeList.cpp:
+        (WebCore::RadioNodeList::~RadioNodeList): Ditto.
+        * html/parser/HTMLDocumentParser.cpp:
+        (WebCore::HTMLDocumentParser::constructTreeFromHTMLToken): Ditto.
+        * loader/appcache/ApplicationCacheStorage.cpp:
+        (WebCore::parseHeader): Ditto.
+
+        * page/ApplicationStateChangeListener.h: Removed.
+
+        * page/Page.cpp:
+        (WebCore::Page::renderTreeSize const): Use forEachDocument.
+        (WebCore::Page::setNeedsRecalcStyleInAllFrames): Ditto.
+        (WebCore::Page::unmarkAllTextMatches): Ditto.
+        (WebCore::Page::editableElementsInRect const): Ditto.
+        (WebCore::Page::setMediaVolume): Tweaked range check so it will reject
+        NaN values. Use forEachMediaElement to call mediaVolumeDidChange,
+        eliminating the need for Document::mediaVolumeDidChange.
+        (WebCore::Page::setPageScaleFactor): Refactored to eliminate large blocks
+        of repeated code. Use forEachMediaElement to call pageScaleFactorChanged,
+        eliminating the need for Document::pageScaleFactorChangedAndStable.
+        (WebCore::Page::setUserInterfaceLayoutDirection): Use forEachMediaElement
+        to call userInterfaceLayoutDirectionChanged, eliminating the need for
+        Document::userInterfaceLayoutDirectionChanged.
+        (WebCore::Page::updateMediaElementRateChangeRestrictions): Use
+        forEachMediaElement to call updateRateChangeRestrictionas. The old code
+        would call this on all media elements in the current web process, which
+        means the functions would be called many times for the same media element.
+        (WebCore::Page::updateRendering): Use forEachDocument consistently for
+        all the document iteration. Before it was used for half the function and not
+        used for the other half; no obvious reason for the differece.
+        (WebCore::Page::suspendScriptedAnimations): Use forEachDocument.
+        (WebCore::Page::resumeScriptedAnimations): Ditto.
+        (WebCore::updateScriptedAnimationsThrottlingReason): Ditto.
+        (WebCore::Page::userStyleSheetLocationChanged): Ditto.
+        (WebCore::Page::invalidateStylesForAllLinks): Ditto.
+        (WebCore::Page::invalidateStylesForLink): Ditto.
+        (WebCore::Page::invalidateInjectedStyleSheetCacheInAllFrames): Ditto.
+        (WebCore::Page::setTimerThrottlingState): Ditto.
+        (WebCore::Page::dnsPrefetchingStateChanged): Ditto.
+        (WebCore::Page::storageBlockingStateChanged): Ditto.
+        (WebCore::Page::updateIsPlayingMedia): Ditto.
+        (WebCore::Page::setMuted): Ditto.
+        (WebCore::Page::stopMediaCapture): Ditto.
+        (WebCore::Page::stopAllMediaPlayback): Ditto.
+        (WebCore::Page::suspendAllMediaPlayback): Ditto.
+        (WebCore::Page::resumeAllMediaPlayback): Ditto.
+        (WebCore::Page::suspendAllMediaBuffering): Ditto.
+        (WebCore::Page::resumeAllMediaBuffering): Ditto.
+        (WebCore::setSVGAnimationsState): Deleted.
+        (WebCore::Page::setIsVisibleInternal): Use forEachDocument to call
+        suspend/resumeDeviceMotionAndOrientationUpdates, obviating the need for
+        Page::suspend/resumeDeviceMotionAndOrientationUpdates. Use
+        forEachDocument to call pause/unpauseAnimations, obviating the need for
+        WebCore::setSVGAnimationsState. Use forEachDocument to call
+        visibilityStateChanged, removing the need to write out a loop that
+        gathers the documents into a vector.
+        (WebCore::Page::suspendDeviceMotionAndOrientationUpdates): Deleted.
+        (WebCore::Page::resumeDeviceMotionAndOrientationUpdates): Deleted.
+        (WebCore::Page::captionPreferencesChanged): Use forEachDocument.
+        (WebCore::Page::setSessionID): Ditto.
+        (WebCore::Page::setPlaybackTarget): Ditto.
+        (WebCore::Page::playbackTargetAvailabilityDidChange): Ditto.
+        (WebCore::Page::setShouldPlayToPlaybackTarget): Ditto.
+        (WebCore::Page::playbackTargetPickerWasDismissed): Ditto.
+        (WebCore::Page::setAllowsMediaDocumentInlinePlayback): Use
+        forEachMediaElement to call allowsMediaDocumentInlinePlaybackChanged,
+        obviating the need for Document::allowsMediaDocumentInlinePlaybackChanged.
+        (WebCore::Page::setUnobscuredSafeAreaInsets): Use forEachDocument.
+        (WebCore::Page::setUseSystemAppearance): Ditto.
+        (WebCore::Page::setFullscreenInsets): Ditto.
+        (WebCore::Page::setFullscreenAutoHideDuration): Ditto.
+        (WebCore::Page::setFullscreenControlsHidden): Ditto.
+        (WebCore::Page::forEachDocument): Merged the collectDocuments function
+        in since it's only used here.
+        (WebCore::Page::collectDocuments): Deleted.
+        (WebCore::Page::forEachMediaElement): Added.
+        (WebCore::Page::applicationWillResignActive): Use forEachMediaElement,
+        eliminating the need for forEachApplicationStateChangeListener.
+        (WebCore::Page::applicationDidBecomeActive): Ditto.
+        (WebCore::Page::recomputeTextAutoSizingInAllFrames): Use forEachDocument.
+
+        * page/Page.h: Removed unneeded forward declarations. Removed unused
+        FindDirection enum. Tweaked formatting. Use bool instead of uint8_t as
+        underlying type for enum class with only two values. Updated for changes above.
+
+        * platform/text/TextEncoding.cpp:
+        (WebCore::TextEncoding::TextEncoding): Updated for "atomic" -> "atom".
+        (WebCore::TextEncoding::domName const): Ditto.
+        (WebCore::TextEncoding::usesVisualOrdering const): Ditto.
+        * platform/text/TextEncodingRegistry.cpp:
+        (WebCore::addToTextEncodingNameMap): Ditto.
+        (WebCore::addToTextCodecMap): Ditto.
+        (WebCore::pruneBlacklistedCodecs): Ditto.
+        (WebCore::addEncodingName): Ditto.
+        (WebCore::atomCanonicalTextEncodingName): Ditto.
+        * platform/text/TextEncodingRegistry.h: Ditto.
+
+        * xml/XPathFunctions.cpp:
+        (WebCore::XPath::atomicSubstring): Deleted.
+        (WebCore::XPath::toStringView): Added. Later could make a StringBuilder member
+        function instead.
+        (WebCore::XPath::FunId::evaluate const): Use toStringView and StringView::substring
+        instead of "atomicSubstring", since getElementById can be called on a StringView
+        and there's no need to allocate/deallocate an AtomString just to check if it exists.
+
 2019-12-27  Antti Koivisto  <antti@apple.com>
 
         [LFC][Integration] Ensure layout boxes have expected display types
index 8c7e5c5..4583625 100644 (file)
@@ -750,7 +750,6 @@ set(WebCore_PRIVATE_FRAMEWORK_HEADERS
     page/ActivityStateChangeObserver.h
     page/AdjustViewSizeOrNot.h
     page/AlternativeTextClient.h
-    page/ApplicationStateChangeListener.h
     page/AutoplayEvent.h
     page/Base64Utilities.h
     page/CacheStorageProvider.h
index 88954e9..bce6cd2 100644 (file)
                07E9E13018F62B370011A3A4 /* InbandMetadataTextTrackPrivateAVF.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 07E9E12F18F62B370011A3A4 /* InbandMetadataTextTrackPrivateAVF.cpp */; };
                07EE76EC1BE96DB000F89133 /* MockRealtimeVideoSource.h in Headers */ = {isa = PBXBuildFile; fileRef = 07EE76EA1BE96DB000F89133 /* MockRealtimeVideoSource.h */; settings = {ATTRIBUTES = (Private, ); }; };
                07EE76EF1BEA619800F89133 /* MockRealtimeVideoSourceMac.h in Headers */ = {isa = PBXBuildFile; fileRef = 07EE76ED1BEA619800F89133 /* MockRealtimeVideoSourceMac.h */; };
-               07F04A942006B1E300AE2A0A /* ApplicationStateChangeListener.h in Headers */ = {isa = PBXBuildFile; fileRef = 07F04A92200684BC00AE2A0A /* ApplicationStateChangeListener.h */; settings = {ATTRIBUTES = (Private, ); }; };
                07F4E93320B3587F002E3803 /* AVAssetMIMETypeCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 07C8AD121D073D630087C5CE /* AVAssetMIMETypeCache.h */; settings = {ATTRIBUTES = (Private, ); }; };
                07F876841AD580F900905849 /* MediaPlaybackTargetContext.h in Headers */ = {isa = PBXBuildFile; fileRef = 07F876831AD4A94500905849 /* MediaPlaybackTargetContext.h */; settings = {ATTRIBUTES = (Private, ); }; };
                07F944161864D046005D31CB /* PlatformMediaSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = CDAE8C081746B95700532D78 /* PlatformMediaSessionManager.h */; settings = {ATTRIBUTES = (Private, ); }; };
                07EE76EA1BE96DB000F89133 /* MockRealtimeVideoSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MockRealtimeVideoSource.h; sourceTree = "<group>"; };
                07EE76ED1BEA619800F89133 /* MockRealtimeVideoSourceMac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MockRealtimeVideoSourceMac.h; sourceTree = "<group>"; };
                07EE76EE1BEA619800F89133 /* MockRealtimeVideoSourceMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MockRealtimeVideoSourceMac.mm; sourceTree = "<group>"; };
-               07F04A92200684BC00AE2A0A /* ApplicationStateChangeListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ApplicationStateChangeListener.h; sourceTree = "<group>"; };
                07F876831AD4A94500905849 /* MediaPlaybackTargetContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MediaPlaybackTargetContext.h; sourceTree = "<group>"; };
                07FE99DA18807A7D00256648 /* MediaElementSession.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MediaElementSession.cpp; sourceTree = "<group>"; };
                07FE99DB18807A7D00256648 /* MediaElementSession.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MediaElementSession.h; sourceTree = "<group>"; };
                                724EE54F1DC7F25B00A91FFB /* ActivityStateChangeObserver.h */,
                                BCF48CE61370D114004E87D6 /* AdjustViewSizeOrNot.h */,
                                CEDA12D6152CA1CB00D9E08D /* AlternativeTextClient.h */,
-                               07F04A92200684BC00AE2A0A /* ApplicationStateChangeListener.h */,
                                C9D467041E60C3EB008195FB /* AutoplayEvent.h */,
                                45830D4B1679B4F800ACF8C3 /* AutoscrollController.cpp */,
                                45830D4C1679B4F800ACF8C3 /* AutoscrollController.h */,
                                63BD4A5F1F778E9F00438722 /* ApplicationManifest.h in Headers */,
                                63152D191F9531EE007A5E4B /* ApplicationManifestLoader.h in Headers */,
                                6354F4C91F7AFC9400D89DF3 /* ApplicationManifestParser.h in Headers */,
-                               07F04A942006B1E300AE2A0A /* ApplicationStateChangeListener.h in Headers */,
                                9B417064125662B3006B28FC /* ApplyBlockElementCommand.h in Headers */,
                                93309DD9099E64920056E581 /* ApplyStyleCommand.h in Headers */,
                                512DD8F60D91E6AF000F89EE /* Archive.h in Headers */,
index e53ac8c..2db418c 100644 (file)
@@ -52,7 +52,7 @@ namespace WebCore {
 unsigned StyleSheetContents::estimatedSizeInBytes() const
 {
     // Note that this does not take into account size of the strings hanging from various objects. 
-    // The assumption is that nearly all of of them are atomic and would exist anyway.
+    // The assumption is that nearly all of of them are atoms that would exist anyway.
     unsigned size = sizeof(*this);
 
     // FIXME: This ignores the children of media and region rules.
index 1d12861..493b3ba 100644 (file)
@@ -891,7 +891,7 @@ Ref<HTMLCollection> ContainerNode::getElementsByTagNameNS(const AtomString& name
 
 Ref<NodeList> ContainerNode::getElementsByName(const String& elementName)
 {
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<NameNodeList>(*this, elementName);
+    return ensureRareData().ensureNodeLists().addCacheWithAtomName<NameNodeList>(*this, elementName);
 }
 
 Ref<HTMLCollection> ContainerNode::getElementsByClassName(const AtomString& classNames)
@@ -902,7 +902,7 @@ Ref<HTMLCollection> ContainerNode::getElementsByClassName(const AtomString& clas
 Ref<RadioNodeList> ContainerNode::radioNodeList(const AtomString& name)
 {
     ASSERT(hasTagName(HTMLNames::formTag) || hasTagName(HTMLNames::fieldsetTag));
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<RadioNodeList>(*this, name);
+    return ensureRareData().ensureNodeLists().addCacheWithAtomName<RadioNodeList>(*this, name);
 }
 
 Ref<HTMLCollection> ContainerNode::children()
index 3416d58..062f4ad 100644 (file)
@@ -29,7 +29,6 @@
 #include "Document.h"
 
 #include "AXObjectCache.h"
-#include "ApplicationStateChangeListener.h"
 #include "Attr.h"
 #include "BeforeUnloadEvent.h"
 #include "CDATASection.h"
@@ -1726,7 +1725,10 @@ void Document::visibilityStateChanged()
     for (auto* client : m_visibilityStateCallbackClients)
         client->visibilityStateChanged();
 
-    notifyMediaCaptureOfVisibilityChanged();
+#if ENABLE(MEDIA_STREAM)
+    if (auto* page = this->page())
+        RealtimeMediaSourceCenter::singleton().setCapturePageState(hidden(), page->isMediaCaptureMuted());
+#endif
 }
 
 VisibilityState Document::visibilityState() const
@@ -1747,20 +1749,23 @@ bool Document::hidden() const
 
 #if ENABLE(VIDEO)
 
-void Document::registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
+void Document::registerMediaElement(HTMLMediaElement& element)
 {
-    m_allowsMediaDocumentInlinePlaybackElements.add(&element);
+    m_mediaElements.add(&element);
 }
 
-void Document::unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
+void Document::unregisterMediaElement(HTMLMediaElement& element)
 {
-    m_allowsMediaDocumentInlinePlaybackElements.remove(&element);
+    m_mediaElements.remove(&element);
 }
 
-void Document::allowsMediaDocumentInlinePlaybackChanged()
+void Document::forEachMediaElement(const Function<void(HTMLMediaElement&)>& function)
 {
-    for (auto* element : m_allowsMediaDocumentInlinePlaybackElements)
-        element->allowsMediaDocumentInlinePlaybackChanged();
+    Vector<Ref<HTMLMediaElement>> elements;
+    for (auto* element : m_mediaElements)
+        elements.append(*element);
+    for (auto& element : elements)
+        function(element);
 }
 
 void Document::stopAllMediaPlayback()
@@ -1792,6 +1797,7 @@ void Document::resumeAllMediaBuffering()
     if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
         platformMediaSessionManager->resumeAllMediaBufferingForDocument(*this);
 }
+
 #endif
 
 String Document::nodeName() const
@@ -3706,7 +3712,7 @@ void Document::processColorScheme(const String& colorSchemeString)
     bool allowsTransformations = true;
     bool autoEncountered = false;
 
-    processColorSchemeString(colorSchemeString, [&](StringView key) {
+    processColorSchemeString(colorSchemeString, [&] (StringView key) {
         if (equalLettersIgnoringASCIICase(key, "auto")) {
             colorScheme = { };
             allowsTransformations = true;
@@ -5360,22 +5366,6 @@ void Document::unregisterForDocumentSuspensionCallbacks(Element& element)
     m_documentSuspensionCallbackElements.remove(&element);
 }
 
-void Document::mediaVolumeDidChange() 
-{
-    for (auto* element : m_mediaVolumeCallbackElements)
-        element->mediaVolumeDidChange();
-}
-
-void Document::registerForMediaVolumeCallbacks(Element& element)
-{
-    m_mediaVolumeCallbackElements.add(&element);
-}
-
-void Document::unregisterForMediaVolumeCallbacks(Element& element)
-{
-    m_mediaVolumeCallbackElements.remove(&element);
-}
-
 bool Document::audioPlaybackRequiresUserGesture() const
 {
     if (DocumentLoader* loader = this->loader()) {
@@ -5422,23 +5412,16 @@ void Document::privateBrowsingStateDidChange(PAL::SessionID sessionID)
     if (m_logger)
         m_logger->setEnabled(this, sessionID.isAlwaysOnLoggingAllowed());
 
-    for (auto* element : m_privateBrowsingStateChangedElements)
-        element->privateBrowsingStateDidChange(sessionID);
-}
-
-void Document::registerForPrivateBrowsingStateChangedCallbacks(Element& element)
-{
-    m_privateBrowsingStateChangedElements.add(&element);
-}
-
-void Document::unregisterForPrivateBrowsingStateChangedCallbacks(Element& element)
-{
-    m_privateBrowsingStateChangedElements.remove(&element);
+#if ENABLE(VIDEO)
+    forEachMediaElement([sessionID] (HTMLMediaElement& element) {
+        element.privateBrowsingStateDidChange(sessionID);
+    });
+#endif
 }
 
 #if ENABLE(VIDEO_TRACK)
 
-void Document::registerForCaptionPreferencesChangedCallbacks(Element& element)
+void Document::registerForCaptionPreferencesChangedCallbacks(HTMLMediaElement& element)
 {
     if (page())
         page()->group().captionPreferences().setInterestedInCaptionPreferenceChanges();
@@ -5446,7 +5429,7 @@ void Document::registerForCaptionPreferencesChangedCallbacks(Element& element)
     m_captionPreferencesChangedElements.add(&element);
 }
 
-void Document::unregisterForCaptionPreferencesChangedCallbacks(Element& element)
+void Document::unregisterForCaptionPreferencesChangedCallbacks(HTMLMediaElement& element)
 {
     m_captionPreferencesChangedElements.remove(&element);
 }
@@ -5459,42 +5442,6 @@ void Document::captionPreferencesChanged()
 
 #endif
 
-#if ENABLE(MEDIA_CONTROLS_SCRIPT)
-
-void Document::registerForPageScaleFactorChangedCallbacks(HTMLMediaElement& element)
-{
-    m_pageScaleFactorChangedElements.add(&element);
-}
-
-void Document::unregisterForPageScaleFactorChangedCallbacks(HTMLMediaElement& element)
-{
-    m_pageScaleFactorChangedElements.remove(&element);
-}
-
-void Document::pageScaleFactorChangedAndStable()
-{
-    for (HTMLMediaElement* mediaElement : m_pageScaleFactorChangedElements)
-        mediaElement->pageScaleFactorChanged();
-}
-
-void Document::registerForUserInterfaceLayoutDirectionChangedCallbacks(HTMLMediaElement& element)
-{
-    m_userInterfaceLayoutDirectionChangedElements.add(&element);
-}
-
-void Document::unregisterForUserInterfaceLayoutDirectionChangedCallbacks(HTMLMediaElement& element)
-{
-    m_userInterfaceLayoutDirectionChangedElements.remove(&element);
-}
-
-void Document::userInterfaceLayoutDirectionChanged()
-{
-    for (auto* mediaElement : m_userInterfaceLayoutDirectionChangedElements)
-        mediaElement->userInterfaceLayoutDirectionChanged();
-}
-
-#endif
-
 void Document::setShouldCreateRenderers(bool f)
 {
     m_createRenderers = f;
@@ -7356,6 +7303,7 @@ void Document::playbackTargetPickerWasDismissed(uint64_t clientId)
 
     it->value->playbackTargetPickerWasDismissed();
 }
+
 #endif // ENABLE(WIRELESS_PLAYBACK_TARGET)
 
 #if ENABLE(MEDIA_SESSION)
@@ -7386,6 +7334,7 @@ bool Document::shouldEnforceHTTP09Sandbox() const
 }
 
 #if USE(QUICK_LOOK)
+
 bool Document::shouldEnforceQuickLookSandbox() const
 {
     if (m_isSynthesized || !m_frame)
@@ -7415,6 +7364,7 @@ void Document::applyQuickLookSandbox()
 
     setReferrerPolicy(ReferrerPolicy::NoReferrer);
 }
+
 #endif
 
 bool Document::shouldEnforceContentDispositionAttachmentSandbox() const
@@ -7461,6 +7411,7 @@ void Document::scheduleTimedRenderingUpdate()
 }
 
 #if ENABLE(INTERSECTION_OBSERVER)
+
 void Document::addIntersectionObserver(IntersectionObserver& observer)
 {
     ASSERT(m_intersectionObservers.find(&observer) == notFound);
@@ -7690,9 +7641,11 @@ void Document::scheduleInitialIntersectionObservationUpdate()
     else if (!m_intersectionObserversInitialUpdateTimer.isActive())
         m_intersectionObserversInitialUpdateTimer.startOneShot(intersectionObserversInitialUpdateDelay);
 }
+
 #endif
 
 #if ENABLE(RESIZE_OBSERVER)
+
 void Document::addResizeObserver(ResizeObserver& observer)
 {
     if (!m_resizeObservers.contains(&observer))
@@ -7772,6 +7725,7 @@ void Document::updateResizeObservations(Page& page)
         scheduleTimedRenderingUpdate();
     }
 }
+
 #endif
 
 const AtomString& Document::dir() const
@@ -7814,39 +7768,21 @@ void Document::orientationChanged(int orientation)
     m_orientationNotifier.orientationChanged(orientation);
 }
 
-void Document::notifyMediaCaptureOfVisibilityChanged()
-{
 #if ENABLE(MEDIA_STREAM)
-    if (!page())
-        return;
-
-    RealtimeMediaSourceCenter::singleton().setCapturePageState(hidden(), page()->isMediaCaptureMuted());
-#endif
-}
 
-#if ENABLE(MEDIA_STREAM)
 void Document::stopMediaCapture()
 {
     MediaStreamTrack::endCapture(*this);
 }
 
-void Document::registerForMediaStreamStateChangeCallbacks(HTMLMediaElement& element)
-{
-    m_mediaStreamStateChangeElements.add(&element);
-}
-
-void Document::unregisterForMediaStreamStateChangeCallbacks(HTMLMediaElement& element)
-{
-    m_mediaStreamStateChangeElements.remove(&element);
-}
-
 void Document::mediaStreamCaptureStateChanged()
 {
     if (!MediaProducer::isCapturing(m_mediaState))
         return;
 
-    for (auto* mediaElement : m_mediaStreamStateChangeElements)
-        mediaElement->mediaStreamCaptureStarted();
+    forEachMediaElement([] (HTMLMediaElement& element) {
+        element.mediaStreamCaptureStarted();
+    });
 }
 
 void Document::setDeviceIDHashSalt(const String& salt)
@@ -7857,22 +7793,6 @@ void Document::setDeviceIDHashSalt(const String& salt)
 
 #endif
 
-void Document::addApplicationStateChangeListener(ApplicationStateChangeListener& listener)
-{
-    m_applicationStateChangeListeners.add(&listener);
-}
-
-void Document::removeApplicationStateChangeListener(ApplicationStateChangeListener& listener)
-{
-    m_applicationStateChangeListeners.remove(&listener);
-}
-
-void Document::forEachApplicationStateChangeListener(const Function<void(ApplicationStateChangeListener&)>& functor)
-{
-    for (auto* listener : m_applicationStateChangeListeners)
-        functor(*listener);
-}
-
 const AtomString& Document::bgColor() const
 {
     auto* bodyElement = body();
index 892b3b6..cd65a50 100644 (file)
@@ -87,8 +87,6 @@ class InputCursor;
 
 namespace WebCore {
 
-class EventLoop;
-class ApplicationStateChangeListener;
 class AXObjectCache;
 class Attr;
 class CDATASection;
@@ -120,6 +118,7 @@ class DocumentSharedObjectPool;
 class DocumentTimeline;
 class DocumentType;
 class EditingBehavior;
+class EventLoop;
 class EventLoopTaskGroup;
 class ExtensionStyleSheets;
 class FloatQuad;
@@ -217,9 +216,9 @@ class XPathResult;
 template<typename> class ExceptionOr;
 
 enum CollectionType;
-enum class ShouldOpenExternalURLsPolicy : uint8_t;
 
 enum class RouteSharingPolicy : uint8_t;
+enum class ShouldOpenExternalURLsPolicy : uint8_t;
 
 using PlatformDisplayID = uint32_t;
 
@@ -227,18 +226,14 @@ using PlatformDisplayID = uint32_t;
 class TransformSource;
 #endif
 
-#if ENABLE(TOUCH_EVENTS) || ENABLE(IOS_TOUCH_EVENTS)
-class Touch;
-class TouchList;
-#endif
-
-#if ENABLE(DEVICE_ORIENTATION)
-#if PLATFORM(IOS_FAMILY)
+#if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS_FAMILY)
 class DeviceMotionClient;
 class DeviceMotionController;
 class DeviceOrientationClient;
 class DeviceOrientationController;
 #endif
+
+#if ENABLE(DEVICE_ORIENTATION)
 class DeviceOrientationAndMotionAccessController;
 #endif
 
@@ -1073,8 +1068,8 @@ public:
     void suspendScriptedAnimationControllerCallbacks();
     void resumeScriptedAnimationControllerCallbacks();
 
-    void updateAnimationsAndSendEvents(DOMHighResTimeStamp timestamp);
-    void serviceRequestAnimationFrameCallbacks(DOMHighResTimeStamp timestamp);
+    void updateAnimationsAndSendEvents(DOMHighResTimeStamp);
+    void serviceRequestAnimationFrameCallbacks(DOMHighResTimeStamp);
 
     void windowScreenDidChange(PlatformDisplayID);
 
@@ -1092,9 +1087,8 @@ public:
     void suspend(ReasonForSuspension);
     void resume(ReasonForSuspension);
 
-    void registerForMediaVolumeCallbacks(Element&);
-    void unregisterForMediaVolumeCallbacks(Element&);
-    void mediaVolumeDidChange();
+    void registerMediaElement(HTMLMediaElement&);
+    void unregisterMediaElement(HTMLMediaElement&);
 
     bool audioPlaybackRequiresUserGesture() const;
     bool videoPlaybackRequiresUserGesture() const;
@@ -1104,34 +1098,20 @@ public:
     MediaSession& defaultMediaSession();
 #endif
 
-    void registerForPrivateBrowsingStateChangedCallbacks(Element&);
-    void unregisterForPrivateBrowsingStateChangedCallbacks(Element&);
-    void storageBlockingStateDidChange();
     void privateBrowsingStateDidChange(PAL::SessionID);
 
+    void storageBlockingStateDidChange();
+
 #if ENABLE(VIDEO_TRACK)
-    void registerForCaptionPreferencesChangedCallbacks(Element&);
-    void unregisterForCaptionPreferencesChangedCallbacks(Element&);
+    void registerForCaptionPreferencesChangedCallbacks(HTMLMediaElement&);
+    void unregisterForCaptionPreferencesChangedCallbacks(HTMLMediaElement&);
     void captionPreferencesChanged();
 #endif
 
-#if ENABLE(MEDIA_CONTROLS_SCRIPT)
-    void registerForPageScaleFactorChangedCallbacks(HTMLMediaElement&);
-    void unregisterForPageScaleFactorChangedCallbacks(HTMLMediaElement&);
-    void pageScaleFactorChangedAndStable();
-    void registerForUserInterfaceLayoutDirectionChangedCallbacks(HTMLMediaElement&);
-    void unregisterForUserInterfaceLayoutDirectionChangedCallbacks(HTMLMediaElement&);
-    void userInterfaceLayoutDirectionChanged();
-#endif
-
     void registerForVisibilityStateChangedCallbacks(VisibilityChangeClient&);
     void unregisterForVisibilityStateChangedCallbacks(VisibilityChangeClient&);
 
 #if ENABLE(VIDEO)
-    void registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement&);
-    void unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement&);
-    void allowsMediaDocumentInlinePlaybackChanged();
-
     void stopAllMediaPlayback();
     void suspendAllMediaPlayback();
     void resumeAllMediaPlayback();
@@ -1202,15 +1182,15 @@ public:
 #include <WebKitAdditions/DocumentIOS.h>
 #endif
 
-#if ENABLE(DEVICE_ORIENTATION)
-#if PLATFORM(IOS_FAMILY)
+#if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS_FAMILY)
     DeviceMotionController& deviceMotionController() const;
     DeviceOrientationController& deviceOrientationController() const;
     WEBCORE_EXPORT void simulateDeviceOrientationChange(double alpha, double beta, double gamma);
 #endif
 
+#if ENABLE(DEVICE_ORIENTATION)
     DeviceOrientationAndMotionAccessController& deviceOrientationAndMotionAccessController();
-#endif // ENABLE(DEVICE_ORIENTATION)
+#endif
 
     const DocumentTiming& timing() const { return m_documentTiming; }
 
@@ -1427,8 +1407,6 @@ public:
     void setDeviceIDHashSalt(const String&);
     String deviceIDHashSalt() const { return m_idHashSalt; }
     void stopMediaCapture();
-    void registerForMediaStreamStateChangeCallbacks(HTMLMediaElement&);
-    void unregisterForMediaStreamStateChangeCallbacks(HTMLMediaElement&);
     void mediaStreamCaptureStateChanged();
 #endif
 
@@ -1505,9 +1483,9 @@ public:
     void setServiceWorkerConnection(SWClientConnection*);
 #endif
 
-    void addApplicationStateChangeListener(ApplicationStateChangeListener&);
-    void removeApplicationStateChangeListener(ApplicationStateChangeListener&);
-    void forEachApplicationStateChangeListener(const Function<void(ApplicationStateChangeListener&)>&);
+#if ENABLE(VIDEO)
+    void forEachMediaElement(const Function<void(HTMLMediaElement&)>&);
+#endif
 
 #if ENABLE(IOS_TOUCH_EVENTS)
     bool handlingTouchEvent() const { return m_handlingTouchEvent; }
@@ -1674,6 +1652,8 @@ private:
 
     bool isBodyPotentiallyScrollable(HTMLBodyElement&);
 
+    void didLogMessage(const WTFLogChannel&, WTFLogLevel, Vector<JSONLogValue>&&) final;
+
     const Ref<Settings> m_settings;
 
     UniqueRef<Quirks> m_quirks;
@@ -1795,24 +1775,19 @@ private:
     HashMap<String, RefPtr<HTMLCanvasElement>> m_cssCanvasElements;
 
     HashSet<Element*> m_documentSuspensionCallbackElements;
-    HashSet<Element*> m_mediaVolumeCallbackElements;
-    HashSet<Element*> m_privateBrowsingStateChangedElements;
+
+#if ENABLE(VIDEO)
+    HashSet<HTMLMediaElement*> m_mediaElements;
+#endif
+
 #if ENABLE(VIDEO_TRACK)
-    HashSet<Element*> m_captionPreferencesChangedElements;
+    HashSet<HTMLMediaElement*> m_captionPreferencesChangedElements;
 #endif
 
     Element* m_mainArticleElement { nullptr };
     HashSet<Element*> m_articleElements;
 
-#if ENABLE(MEDIA_CONTROLS_SCRIPT)
-    HashSet<HTMLMediaElement*> m_pageScaleFactorChangedElements;
-    HashSet<HTMLMediaElement*> m_userInterfaceLayoutDirectionChangedElements;
-#endif
-
     HashSet<VisibilityChangeClient*> m_visibilityStateCallbackClients;
-#if ENABLE(VIDEO)
-    HashSet<HTMLMediaElement*> m_allowsMediaDocumentInlinePlaybackElements;
-#endif
 
     std::unique_ptr<HashMap<String, Element*, ASCIICaseInsensitiveHash>> m_accessKeyCache;
 
@@ -1868,17 +1843,14 @@ private:
 
     std::unique_ptr<IdleCallbackController> m_idleCallbackController;
 
-    void notifyMediaCaptureOfVisibilityChanged();
-
-    void didLogMessage(const WTFLogChannel&, WTFLogLevel, Vector<JSONLogValue>&&) final;
-
-#if ENABLE(DEVICE_ORIENTATION)
-#if PLATFORM(IOS_FAMILY)
+#if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS_FAMILY)
     std::unique_ptr<DeviceMotionClient> m_deviceMotionClient;
     std::unique_ptr<DeviceMotionController> m_deviceMotionController;
     std::unique_ptr<DeviceOrientationClient> m_deviceOrientationClient;
     std::unique_ptr<DeviceOrientationController> m_deviceOrientationController;
 #endif
+
+#if ENABLE(DEVICE_ORIENTATION)
     std::unique_ptr<DeviceOrientationAndMotionAccessController> m_deviceOrientationAndMotionAccessController;
 #endif
 
@@ -2069,8 +2041,6 @@ private:
     RefPtr<SWClientConnection> m_serviceWorkerConnection;
 #endif
 
-    HashSet<ApplicationStateChangeListener*> m_applicationStateChangeListeners;
-    
 #if ENABLE(RESOURCE_LOAD_STATISTICS)
     RegistrableDomain m_registrableDomainRequestedPageSpecificStorageAccessWithUserInteraction { };
     String m_referrerOverride;
index 3796204..537ed2b 100644 (file)
@@ -4,7 +4,7 @@
  *           (C) 2001 Peter Kelly (pmk@post.com)
  *           (C) 2001 Dirk Mueller (mueller@kde.org)
  *           (C) 2007 David Smith (catfish.man@gmail.com)
- * Copyright (C) 2004-2017 Apple Inc. All rights reserved.
+ * Copyright (C) 2004-2019 Apple Inc. All rights reserved.
  *           (C) 2007 Eric Seidel (eric@webkit.org)
  *
  * This library is free software; you can redistribute it and/or
@@ -75,6 +75,7 @@
 #include "InspectorInstrumentation.h"
 #include "JSLazyEventListener.h"
 #include "KeyboardEvent.h"
+#include "KeyframeAnimationOptions.h"
 #include "KeyframeEffect.h"
 #include "MutationObserverInterestGroup.h"
 #include "MutationRecord.h"
@@ -305,12 +306,14 @@ static bool isForceEvent(const PlatformMouseEvent& platformEvent)
 }
 
 #if ENABLE(POINTER_EVENTS)
+
 static bool isCompatibilityMouseEvent(const MouseEvent& mouseEvent)
 {
     // https://www.w3.org/TR/pointerevents/#compatibility-mapping-with-mouse-events
     const auto& type = mouseEvent.type();
     return type != eventNames().clickEvent && type != eventNames().mouseoverEvent && type != eventNames().mouseoutEvent && type != eventNames().mouseenterEvent && type != eventNames().mouseleaveEvent;
 }
+
 #endif
 
 enum class ShouldIgnoreMouseEvent : bool { No, Yes };
@@ -1887,6 +1890,7 @@ URL Element::absoluteLinkURL() const
 }
 
 #if ENABLE(TOUCH_EVENTS)
+
 bool Element::allowsDoubleTapGesture() const
 {
 #if ENABLE(POINTER_EVENTS)
@@ -1897,6 +1901,7 @@ bool Element::allowsDoubleTapGesture() const
     Element* parent = parentElement();
     return !parent || parent->allowsDoubleTapGesture();
 }
+
 #endif
 
 Style::Resolver& Element::styleResolver()
@@ -2631,6 +2636,7 @@ void Element::finishParsingChildren()
 }
 
 #if ENABLE(TREE_DEBUGGING)
+
 void Element::formatForDebugger(char* buffer, unsigned length) const
 {
     StringBuilder result;
@@ -2656,6 +2662,7 @@ void Element::formatForDebugger(char* buffer, unsigned length) const
 
     strncpy(buffer, result.toString().utf8().data(), length - 1);
 }
+
 #endif
 
 const Vector<RefPtr<Attr>>& Element::attrNodeList()
@@ -2991,12 +2998,12 @@ void Element::focus(bool restorePreviousSelection, FocusDirection direction)
     }
 
     SelectionRevealMode revealMode = SelectionRevealMode::Reveal;
+
 #if PLATFORM(IOS_FAMILY)
     // Focusing a form element triggers animation in UIKit to scroll to the right position.
     // Calling updateFocusAppearance() would generate an unnecessary call to ScrollView::setScrollPosition(),
     // which would jump us around during this animation. See <rdar://problem/6699741>.
-    bool isFormControl = is<HTMLFormControlElement>(newTarget);
-    if (isFormControl)
+    if (is<HTMLFormControlElement>(newTarget))
         revealMode = SelectionRevealMode::RevealUpToMainFrame;
 #endif
 
@@ -3599,6 +3606,7 @@ bool Element::childShouldCreateRenderer(const Node& child) const
 }
 
 #if ENABLE(FULLSCREEN_API)
+
 static Element* parentCrossingFrameBoundaries(const Element* element)
 {
     ASSERT(element);
@@ -3629,9 +3637,11 @@ void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(boo
     while ((element = parentCrossingFrameBoundaries(element)))
         element->setContainsFullScreenElement(flag);
 }
+
 #endif
 
 #if ENABLE(POINTER_EVENTS)
+
 ExceptionOr<void> Element::setPointerCapture(int32_t pointerId)
 {
     if (document().page())
@@ -3652,17 +3662,21 @@ bool Element::hasPointerCapture(int32_t pointerId)
         return document().page()->pointerCaptureController().hasPointerCapture(this, pointerId);
     return false;
 }
+
 #endif
 
 #if ENABLE(POINTER_LOCK)
+
 void Element::requestPointerLock()
 {
     if (document().page())
         document().page()->pointerLockController().requestPointerLock(this);
 }
+
 #endif
 
 #if ENABLE(INTERSECTION_OBSERVER)
+
 void Element::disconnectFromIntersectionObservers()
 {
     auto* observerData = intersectionObserverData();
@@ -3690,6 +3704,7 @@ IntersectionObserverData* Element::intersectionObserverData()
 {
     return hasRareData() ? elementRareData()->intersectionObserverData() : nullptr;
 }
+
 #endif
 
 KeyframeEffectStack& Element::ensureKeyframeEffectStack()
@@ -3725,6 +3740,7 @@ bool Element::applyKeyframeEffects(RenderStyle& targetStyle)
 }
 
 #if ENABLE(RESIZE_OBSERVER)
+
 void Element::disconnectFromResizeObservers()
 {
     auto* observerData = resizeObserverData();
@@ -3748,33 +3764,20 @@ ResizeObserverData* Element::resizeObserverData()
 {
     return hasRareData() ? elementRareData()->resizeObserverData() : nullptr;
 }
-#endif
 
-SpellcheckAttributeState Element::spellcheckAttributeState() const
-{
-    const AtomString& value = attributeWithoutSynchronization(HTMLNames::spellcheckAttr);
-    if (value.isNull())
-        return SpellcheckAttributeDefault;
-    if (value.isEmpty() || equalLettersIgnoringASCIICase(value, "true"))
-        return SpellcheckAttributeTrue;
-    if (equalLettersIgnoringASCIICase(value, "false"))
-        return SpellcheckAttributeFalse;
-    return SpellcheckAttributeDefault;
-}
+#endif
 
 bool Element::isSpellCheckingEnabled() const
 {
-    for (const Element* element = this; element; element = element->parentOrShadowHostElement()) {
-        switch (element->spellcheckAttributeState()) {
-        case SpellcheckAttributeTrue:
+    for (auto* ancestor = this; ancestor; ancestor = ancestor->parentOrShadowHostElement()) {
+        auto& value = ancestor->attributeWithoutSynchronization(HTMLNames::spellcheckAttr);
+        if (value.isNull())
+            continue;
+        if (value.isEmpty() || equalLettersIgnoringASCIICase(value, "true"))
             return true;
-        case SpellcheckAttributeFalse:
+        if (equalLettersIgnoringASCIICase(value, "false"))
             return false;
-        case SpellcheckAttributeDefault:
-            break;
-        }
     }
-
     return true;
 }
 
@@ -4401,6 +4404,7 @@ ElementIdentifier Element::createElementIdentifier()
 }
 
 #if ENABLE(CSS_TYPED_OM)
+
 StylePropertyMap* Element::attributeStyleMap()
 {
     if (!hasRareData())
@@ -4412,6 +4416,7 @@ void Element::setAttributeStyleMap(Ref<StylePropertyMap>&& map)
 {
     ensureElementRareData().setAttributeStyleMap(WTFMove(map));
 }
+
 #endif
 
 } // namespace WebCore
index d5e71e6..844ae22 100644 (file)
@@ -28,8 +28,6 @@
 #include "Document.h"
 #include "ElementData.h"
 #include "HTMLNames.h"
-#include "KeyframeAnimationOptions.h"
-#include "ScrollToOptions.h"
 #include "ScrollTypes.h"
 #include "ShadowRootMode.h"
 #include "SimulatedClickOptions.h"
@@ -58,7 +56,10 @@ class PseudoElement;
 class RenderTreePosition;
 class StylePropertyMap;
 class WebAnimation;
+
+struct KeyframeAnimationOptions;
 struct ScrollIntoViewOptions;
+struct ScrollToOptions;
 
 #if ENABLE(INTERSECTION_OBSERVER)
 struct IntersectionObserverData;
@@ -72,12 +73,6 @@ namespace Style {
 struct ElementStyle;
 }
 
-enum SpellcheckAttributeState {
-    SpellcheckAttributeTrue,
-    SpellcheckAttributeFalse,
-    SpellcheckAttributeDefault
-};
-
 class Element : public ContainerNode {
     WTF_MAKE_ISO_ALLOCATED(Element);
 public:
@@ -104,14 +99,13 @@ public:
     // attribute or one of the SVG animatable attributes.
     bool hasAttributeWithoutSynchronization(const QualifiedName&) const;
     const AtomString& attributeWithoutSynchronization(const QualifiedName&) const;
-#ifndef NDEBUG
-    WEBCORE_EXPORT bool fastAttributeLookupAllowed(const QualifiedName&) const;
-#endif
 
 #if DUMP_NODE_STATISTICS
     bool hasNamedNodeMap() const;
 #endif
+
     WEBCORE_EXPORT bool hasAttributes() const;
+
     // This variant will not update the potentially invalid attributes. To be used when not interested
     // in style attribute or one of the SVG animation attributes.
     bool hasAttributesWithoutUpdate() const;
@@ -199,6 +193,7 @@ public:
 
     // Returns the absolute bounding box translated into client coordinates.
     WEBCORE_EXPORT IntRect clientRect() const;
+
     // Returns the absolute bounding box translated into screen coordinates.
     WEBCORE_EXPORT IntRect screenRect() const;
 
@@ -222,14 +217,13 @@ public:
     const QualifiedName& tagQName() const { return m_tagName; }
 #if ENABLE(JIT)
     static ptrdiff_t tagQNameMemoryOffset() { return OBJECT_OFFSETOF(Element, m_tagName); }
-#endif // ENABLE(JIT)
+#endif
     String tagName() const { return nodeName(); }
     bool hasTagName(const QualifiedName& tagName) const { return m_tagName.matches(tagName); }
     bool hasTagName(const HTMLQualifiedName& tagName) const { return ContainerNode::hasTagName(tagName); }
     bool hasTagName(const MathMLQualifiedName& tagName) const { return ContainerNode::hasTagName(tagName); }
     bool hasTagName(const SVGQualifiedName& tagName) const { return ContainerNode::hasTagName(tagName); }
 
-    // A fast function for checking the local name against another atomic string.
     bool hasLocalName(const AtomString& other) const { return m_tagName.localName() == other; }
 
     const AtomString& localName() const final { return m_tagName.localName(); }
@@ -256,7 +250,7 @@ public:
         ModifiedByCloning
     };
 
-    // This method is called whenever an attribute is added, changed or removed.
+    // These functions are called whenever an attribute is added, changed or removed.
     virtual void attributeChanged(const QualifiedName&, const AtomString& oldValue, const AtomString& newValue, AttributeModificationReason = ModifiedDirectly);
     virtual void parseAttribute(const QualifiedName&, const AtomString&) { }
 
@@ -308,7 +302,7 @@ public:
     void enqueueToUpgrade(JSCustomElementInterface&);
     CustomElementReactionQueue* reactionQueue() const;
 
-    // FIXME: this should not be virtual, do not override this.
+    // FIXME: This should not be virtual. Please do not add additional overrides of this function.
     virtual const AtomString& shadowPseudoId() const;
 
     bool isInActiveChain() const { return isUserActionElement() && isUserActionElementInActiveChain(); }
@@ -422,21 +416,11 @@ public:
     virtual void prepareForDocumentSuspension() { }
     virtual void resumeFromDocumentSuspension() { }
 
-    // Use Document::registerForMediaVolumeCallbacks() to subscribe to this
-    virtual void mediaVolumeDidChange() { }
-
-    // Use Document::registerForPrivateBrowsingStateChangedCallbacks() to subscribe to this.
-    virtual void privateBrowsingStateDidChange(PAL::SessionID) { }
-
     virtual void willBecomeFullscreenElement();
     virtual void ancestorWillEnterFullscreen() { }
     virtual void didBecomeFullscreenElement() { }
     virtual void willStopBeingFullscreenElement() { }
 
-#if ENABLE(VIDEO_TRACK)
-    virtual void captionPreferencesChanged() { }
-#endif
-
     bool isFinishedParsingChildren() const { return isParsingChildrenFinished(); }
     void finishParsingChildren() override;
     void beginParsingChildren() final;
@@ -708,8 +692,6 @@ private:
 
     unsigned rareDataChildIndex() const;
 
-    SpellcheckAttributeState spellcheckAttributeState() const;
-
     void createUniqueElementData();
 
     ElementRareData* elementRareData() const;
@@ -725,6 +707,10 @@ private:
     
     void attachAttributeNodeIfNeeded(Attr&);
 
+#ifndef NDEBUG
+    WEBCORE_EXPORT bool fastAttributeLookupAllowed(const QualifiedName&) const;
+#endif
+
     QualifiedName m_tagName;
     RefPtr<ElementData> m_elementData;
 };
index 50a9415..b9452f3 100644 (file)
@@ -29,6 +29,8 @@
 
 namespace WebCore {
 
+class Touch;
+
 class EventPath {
 public:
     EventPath(Node& origin, Event&);
index 1e42871..e904c45 100644 (file)
@@ -30,8 +30,6 @@
 
 #include "Chrome.h"
 #include "ChromeClient.h"
-#include "Document.h"
-#include "Element.h"
 #include "EventNames.h"
 #include "Frame.h"
 #include "HTMLFrameOwnerElement.h"
@@ -388,7 +386,7 @@ void FullscreenManager::willEnterFullscreen(Element& element)
     m_fullscreenElement = &element;
 
 #if USE(NATIVE_FULLSCREEN_VIDEO)
-    if (element.isMediaElement())
+    if (is<HTMLMediaElement>(element))
         return;
 #endif
 
index 2a0afb8..f0add2a 100644 (file)
@@ -40,7 +40,7 @@ NameNodeList::NameNodeList(ContainerNode& rootNode, const AtomString& name)
 
 NameNodeList::~NameNodeList()
 {
-    ownerNode().nodeLists()->removeCacheWithAtomicName(this, m_name);
+    ownerNode().nodeLists()->removeCacheWithAtomName(*this, m_name);
 } 
 
 } // namespace WebCore
index f1b01e5..a5d26b5 100644 (file)
@@ -1914,8 +1914,8 @@ void Node::showTreeForThisAcrossFrame() const
 
 void NodeListsNodeData::invalidateCaches()
 {
-    for (auto& atomicName : m_atomicNameCaches)
-        atomicName.value->invalidateCache();
+    for (auto& atomName : m_atomNameCaches)
+        atomName.value->invalidateCache();
 
     for (auto& collection : m_cachedCollections)
         collection.value->invalidateCache();
@@ -1926,8 +1926,8 @@ void NodeListsNodeData::invalidateCaches()
 
 void NodeListsNodeData::invalidateCachesForAttribute(const QualifiedName& attrName)
 {
-    for (auto& atomicName : m_atomicNameCaches)
-        atomicName.value->invalidateCacheForAttribute(attrName);
+    for (auto& atomName : m_atomNameCaches)
+        atomName.value->invalidateCacheForAttribute(attrName);
 
     for (auto& collection : m_cachedCollections)
         collection.value->invalidateCacheForAttribute(attrName);
index bff975d..376412b 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2008-2019 Apple Inc. All rights reserved.
  * Copyright (C) 2008 David Smith <catfish.man@gmail.com>
  *
  * This library is free software; you can redistribute it and/or
 
 #include "ChildNodeList.h"
 #include "HTMLCollection.h"
-#include "HTMLNames.h"
-#include "LiveNodeList.h"
 #include "MutationObserverRegistration.h"
 #include "QualifiedName.h"
 #include "TagCollection.h"
 #include <wtf/HashSet.h>
 #include <wtf/StdLibExtras.h>
-#include <wtf/text/AtomString.h>
 
 namespace WebCore {
 
 class LabelsNodeList;
+class LiveNodeList;
 class NameNodeList;
 class RadioNodeList;
-class TreeScope;
 
-template <class ListType> struct NodeListTypeIdentifier;
-template <> struct NodeListTypeIdentifier<NameNodeList> { static int value() { return 0; } };
-template <> struct NodeListTypeIdentifier<RadioNodeList> { static int value() { return 1; } };
-template <> struct NodeListTypeIdentifier<LabelsNodeList> { static int value() { return 2; } };
+template<typename ListType> struct NodeListTypeIdentifier;
 
 class NodeListsNodeData {
-    WTF_MAKE_NONCOPYABLE(NodeListsNodeData); WTF_MAKE_FAST_ALLOCATED;
+    WTF_MAKE_NONCOPYABLE(NodeListsNodeData);
+    WTF_MAKE_FAST_ALLOCATED;
 public:
-    NodeListsNodeData()
-        : m_childNodeList(nullptr)
-        , m_emptyChildNodeList(nullptr)
-    {
-    }
+    NodeListsNodeData() = default;
 
     void clearChildNodeListCache()
     {
@@ -104,14 +95,14 @@ public:
         static const bool safeToCompareToEmptyOrDeleted = DefaultHash<AtomString>::Hash::safeToCompareToEmptyOrDeleted;
     };
 
-    typedef HashMap<std::pair<unsigned char, AtomString>, LiveNodeList*, NodeListCacheMapEntryHash> NodeListAtomicNameCacheMap;
-    typedef HashMap<std::pair<unsigned char, AtomString>, HTMLCollection*, NodeListCacheMapEntryHash> CollectionCacheMap;
-    typedef HashMap<QualifiedName, TagCollectionNS*> TagCollectionNSCache;
+    using NodeListCacheMap = HashMap<std::pair<unsigned char, AtomString>, LiveNodeList*, NodeListCacheMapEntryHash>;
+    using CollectionCacheMap = HashMap<std::pair<unsigned char, AtomString>, HTMLCollection*, NodeListCacheMapEntryHash>;
+    using TagCollectionNSCache = HashMap<QualifiedName, TagCollectionNS*>;
 
     template<typename T, typename ContainerType>
-    ALWAYS_INLINE Ref<T> addCacheWithAtomicName(ContainerType& container, const AtomString& name)
+    ALWAYS_INLINE Ref<T> addCacheWithAtomName(ContainerType& container, const AtomString& name)
     {
-        NodeListAtomicNameCacheMap::AddResult result = m_atomicNameCaches.fastAdd(namedNodeListKey<T>(name), nullptr);
+        auto result = m_atomNameCaches.fastAdd(namedNodeListKey<T>(name), nullptr);
         if (!result.isNewEntry)
             return static_cast<T&>(*result.iterator->value);
 
@@ -122,8 +113,7 @@ public:
 
     ALWAYS_INLINE Ref<TagCollectionNS> addCachedTagCollectionNS(ContainerNode& node, const AtomString& namespaceURI, const AtomString& localName)
     {
-        QualifiedName name(nullAtom(), localName, namespaceURI);
-        TagCollectionNSCache::AddResult result = m_tagCollectionNSCache.fastAdd(name, nullptr);
+        auto result = m_tagCollectionNSCache.fastAdd(QualifiedName { nullAtom(), localName, namespaceURI }, nullptr);
         if (!result.isNewEntry)
             return *result.iterator->value;
 
@@ -135,7 +125,7 @@ public:
     template<typename T, typename ContainerType>
     ALWAYS_INLINE Ref<T> addCachedCollection(ContainerType& container, CollectionType collectionType, const AtomString& name)
     {
-        CollectionCacheMap::AddResult result = m_cachedCollections.fastAdd(namedCollectionKey(collectionType, name), nullptr);
+        auto result = m_cachedCollections.fastAdd(namedCollectionKey(collectionType, name), nullptr);
         if (!result.isNewEntry)
             return static_cast<T&>(*result.iterator->value);
 
@@ -147,7 +137,7 @@ public:
     template<typename T, typename ContainerType>
     ALWAYS_INLINE Ref<T> addCachedCollection(ContainerType& container, CollectionType collectionType)
     {
-        CollectionCacheMap::AddResult result = m_cachedCollections.fastAdd(namedCollectionKey(collectionType, starAtom()), nullptr);
+        auto result = m_cachedCollections.fastAdd(namedCollectionKey(collectionType, starAtom()), nullptr);
         if (!result.isNewEntry)
             return static_cast<T&>(*result.iterator->value);
 
@@ -162,13 +152,13 @@ public:
         return static_cast<T*>(m_cachedCollections.get(namedCollectionKey(collectionType, starAtom())));
     }
 
-    template <class NodeListType>
-    void removeCacheWithAtomicName(NodeListType* list, const AtomString& name = starAtom())
+    template<typename NodeListType>
+    void removeCacheWithAtomName(NodeListType& list, const AtomString& name)
     {
-        ASSERT(list == m_atomicNameCaches.get(namedNodeListKey<NodeListType>(name)));
-        if (deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(list->ownerNode()))
+        ASSERT(&list == m_atomNameCaches.get(namedNodeListKey<NodeListType>(name)));
+        if (deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(list.ownerNode()))
             return;
-        m_atomicNameCaches.remove(namedNodeListKey<NodeListType>(name));
+        m_atomNameCaches.remove(namedNodeListKey<NodeListType>(name));
     }
 
     void removeCachedTagCollectionNS(HTMLCollection& collection, const AtomString& namespaceURI, const AtomString& localName)
@@ -203,7 +193,7 @@ public:
             return;
         }
 
-        for (auto& cache : m_atomicNameCaches.values())
+        for (auto& cache : m_atomNameCaches.values())
             cache->invalidateCacheForDocument(oldDocument);
 
         for (auto& list : m_tagCollectionNSCache.values()) {
@@ -221,7 +211,7 @@ private:
         return std::pair<unsigned char, AtomString>(type, name);
     }
 
-    template <class NodeListType>
+    template<typename NodeListType>
     std::pair<unsigned char, AtomString> namedNodeListKey(const AtomString& name)
     {
         return std::pair<unsigned char, AtomString>(NodeListTypeIdentifier<NodeListType>::value(), name);
@@ -230,10 +220,10 @@ private:
     bool deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(Node&);
 
     // These two are currently mutually exclusive and could be unioned. Not very important as this class is large anyway.
-    ChildNodeList* m_childNodeList;
-    EmptyNodeList* m_emptyChildNodeList;
+    ChildNodeList* m_childNodeList { nullptr };
+    EmptyNodeList* m_emptyChildNodeList { nullptr };
 
-    NodeListAtomicNameCacheMap m_atomicNameCaches;
+    NodeListCacheMap m_atomNameCaches;
     TagCollectionNSCache m_tagCollectionNSCache;
     CollectionCacheMap m_cachedCollections;
 };
@@ -331,11 +321,27 @@ private:
     std::unique_ptr<NodeMutationObserverData> m_mutationObserverData;
 };
 
+template<> struct NodeListTypeIdentifier<NameNodeList> {
+    static constexpr unsigned char value() { return 0; }
+};
+
+template<> struct NodeListTypeIdentifier<RadioNodeList> {
+    static constexpr unsigned char value() { return 1; }
+};
+
+template<> struct NodeListTypeIdentifier<LabelsNodeList> {
+    static constexpr unsigned char value() { return 2; }
+};
+
 inline bool NodeListsNodeData::deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(Node& ownerNode)
 {
     ASSERT(ownerNode.nodeLists() == this);
-    if ((m_childNodeList ? 1 : 0) + (m_emptyChildNodeList ? 1 : 0) + m_atomicNameCaches.size()
-        + m_tagCollectionNSCache.size() + m_cachedCollections.size() != 1)
+    size_t listsCount = (m_childNodeList ? 1 : 0)
+        + (m_emptyChildNodeList ? 1 : 0)
+        + m_atomNameCaches.size()
+        + m_tagCollectionNSCache.size()
+        + m_cachedCollections.size();
+    if (listsCount != 1)
         return false;
     ownerNode.clearNodeLists();
     return true;
index 21b15d5..44d7357 100644 (file)
@@ -112,8 +112,8 @@ Element* TreeScope::getElementById(const String& elementId) const
     if (!m_elementsById)
         return nullptr;
 
-    if (RefPtr<AtomStringImpl> atomicElementId = AtomStringImpl::lookUp(elementId.impl()))
-        return m_elementsById->getElementById(*atomicElementId, *this);
+    if (auto atomElementId = AtomStringImpl::lookUp(elementId.impl()))
+        return m_elementsById->getElementById(*atomElementId, *this);
 
     return nullptr;
 }
@@ -123,8 +123,8 @@ Element* TreeScope::getElementById(StringView elementId) const
     if (!m_elementsById)
         return nullptr;
 
-    if (auto atomicElementId = elementId.toExistingAtomString())
-        return m_elementsById->getElementById(*atomicElementId, *this);
+    if (auto atomElementId = elementId.toExistingAtomString())
+        return m_elementsById->getElementById(*atomElementId, *this);
 
     return nullptr;
 }
index 33690ea..cbf31eb 100644 (file)
@@ -274,30 +274,6 @@ String convertEnumerationToString(HTMLMediaElement::AutoplayEventPlaybackState e
     return values[static_cast<size_t>(enumerationValue)];
 }
 
-typedef HashMap<Document*, HashSet<HTMLMediaElement*>> DocumentElementSetMap;
-static DocumentElementSetMap& documentToElementSetMap()
-{
-    static NeverDestroyed<DocumentElementSetMap> map;
-    return map;
-}
-
-static void addElementToDocumentMap(HTMLMediaElement& element, Document& document)
-{
-    DocumentElementSetMap& map = documentToElementSetMap();
-    HashSet<HTMLMediaElement*> set = map.take(&document);
-    set.add(&element);
-    map.add(&document, set);
-}
-
-static void removeElementFromDocumentMap(HTMLMediaElement& element, Document& document)
-{
-    DocumentElementSetMap& map = documentToElementSetMap();
-    HashSet<HTMLMediaElement*> set = map.take(&document);
-    set.remove(&element);
-    if (!set.isEmpty())
-        map.add(&document, set);
-}
-
 #if ENABLE(VIDEO_TRACK)
 
 class TrackDisplayUpdateScope {
@@ -673,16 +649,13 @@ RefPtr<HTMLMediaElement> HTMLMediaElement::bestMediaElementForShowingPlaybackCon
 
 void HTMLMediaElement::registerWithDocument(Document& document)
 {
+    document.registerMediaElement(*this);
+
     m_mediaSession->registerWithDocument(document);
 
     if (m_isWaitingUntilMediaCanStart)
         document.addMediaCanStartListener(*this);
 
-#if !PLATFORM(IOS_FAMILY)
-    document.registerForMediaVolumeCallbacks(*this);
-    document.registerForPrivateBrowsingStateChangedCallbacks(*this);
-#endif
-
     document.registerForVisibilityStateChangedCallbacks(*this);
 
 #if ENABLE(VIDEO_TRACK)
@@ -690,40 +663,22 @@ void HTMLMediaElement::registerWithDocument(Document& document)
         document.registerForCaptionPreferencesChangedCallbacks(*this);
 #endif
 
-#if ENABLE(MEDIA_CONTROLS_SCRIPT)
-    if (m_mediaControlsDependOnPageScaleFactor)
-        document.registerForPageScaleFactorChangedCallbacks(*this);
-    document.registerForUserInterfaceLayoutDirectionChangedCallbacks(*this);
-#endif
-
 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
     document.registerForDocumentSuspensionCallbacks(*this);
 #endif
 
-    document.registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(*this);
-
     document.addAudioProducer(*this);
-    addElementToDocumentMap(*this, document);
-
-#if ENABLE(MEDIA_STREAM)
-    document.registerForMediaStreamStateChangeCallbacks(*this);
-#endif
-
-    document.addApplicationStateChangeListener(*this);
 }
 
 void HTMLMediaElement::unregisterWithDocument(Document& document)
 {
+    document.unregisterMediaElement(*this);
+
     m_mediaSession->unregisterWithDocument(document);
 
     if (m_isWaitingUntilMediaCanStart)
         document.removeMediaCanStartListener(*this);
 
-#if !PLATFORM(IOS_FAMILY)
-    document.unregisterForMediaVolumeCallbacks(*this);
-    document.unregisterForPrivateBrowsingStateChangedCallbacks(*this);
-#endif
-
     document.unregisterForVisibilityStateChangedCallbacks(*this);
 
 #if ENABLE(VIDEO_TRACK)
@@ -731,26 +686,11 @@ void HTMLMediaElement::unregisterWithDocument(Document& document)
         document.unregisterForCaptionPreferencesChangedCallbacks(*this);
 #endif
 
-#if ENABLE(MEDIA_CONTROLS_SCRIPT)
-    if (m_mediaControlsDependOnPageScaleFactor)
-        document.unregisterForPageScaleFactorChangedCallbacks(*this);
-    document.unregisterForUserInterfaceLayoutDirectionChangedCallbacks(*this);
-#endif
-
 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
     document.unregisterForDocumentSuspensionCallbacks(*this);
 #endif
 
-    document.unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(*this);
-
     document.removeAudioProducer(*this);
-    removeElementFromDocumentMap(*this, document);
-
-#if ENABLE(MEDIA_STREAM)
-    document.unregisterForMediaStreamStateChangeCallbacks(*this);
-#endif
-
-    document.removeApplicationStateChangeListener(*this);
 }
 
 void HTMLMediaElement::didMoveToNewDocument(Document& oldDocument, Document& newDocument)
@@ -769,6 +709,7 @@ void HTMLMediaElement::didMoveToNewDocument(Document& oldDocument, Document& new
 }
 
 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
+
 void HTMLMediaElement::prepareForDocumentSuspension()
 {
     m_mediaSession->unregisterWithDocument(document());
@@ -779,6 +720,7 @@ void HTMLMediaElement::resumeFromDocumentSuspension()
     m_mediaSession->registerWithDocument(document());
     updateShouldAutoplay();
 }
+
 #endif
 
 bool HTMLMediaElement::supportsFocus() const
@@ -5796,8 +5738,11 @@ bool HTMLMediaElement::hasPendingActivity() const
 
 void HTMLMediaElement::mediaVolumeDidChange()
 {
+    // FIXME: We should try to reconcile this so there's no difference for PLATFORM(IOS_FAMILY).
+#if !PLATFORM(IOS_FAMILY)
     INFO_LOG(LOGIDENTIFIER);
     updateVolume();
+#endif
 }
 
 void HTMLMediaElement::visibilityStateChanged()
@@ -6457,10 +6402,15 @@ void HTMLMediaElement::resetMediaEngines()
 
 void HTMLMediaElement::privateBrowsingStateDidChange(PAL::SessionID sessionID)
 {
+    // FIXME: We should try to reconcile this so there's no difference for PLATFORM(IOS_FAMILY).
+#if PLATFORM(IOS_FAMILY)
+    UNUSED_PARAM(sessionID);
+#else
     if (!m_player)
         return;
 
     m_player->setPrivateBrowsingMode(sessionID.isEphemeral());
+#endif
 }
 
 MediaControls* HTMLMediaElement::mediaControls() const
@@ -6729,6 +6679,7 @@ void HTMLMediaElement::createMediaPlayer()
 }
 
 #if ENABLE(WEB_AUDIO)
+
 void HTMLMediaElement::setAudioSourceNode(MediaElementAudioSourceNode* sourceNode)
 {
     m_audioSourceNode = sourceNode;
@@ -6742,8 +6693,9 @@ AudioSourceProvider* HTMLMediaElement::audioSourceProvider()
     if (m_player)
         return m_player->audioSourceProvider();
 
-    return 0;
+    return nullptr;
 }
+
 #endif
 
 const String& HTMLMediaElement::mediaGroup() const
@@ -6769,22 +6721,19 @@ void HTMLMediaElement::setMediaGroup(const String& group)
 
     // 4. If there is another media element whose Document is the same as m's Document (even if one or both
     // of these elements are not actually in the Document),
-    HashSet<HTMLMediaElement*> elements = documentToElementSetMap().get(&document());
-    for (auto& element : elements) {
-        if (element == this)
-            continue;
-
+    // FIXME: It does not seem OK that this algorithm iterates the media elements in a random order.
+    document().forEachMediaElement([&] (HTMLMediaElement& element) {
         // and which also has a mediagroup attribute, and whose mediagroup attribute has the same value as
         // the new value of m's mediagroup attribute,
-        if (element->mediaGroup() == group) {
+        if (&element != this && !controller() && element.mediaGroup() == group) {
             //  then let controller be that media element's current media controller.
-            setController(element->controller());
-            return;
+            setController(element.controller());
         }
-    }
+    });
 
     // Otherwise, let controller be a newly created MediaController.
-    setController(MediaController::create(document()));
+    if (!controller())
+        setController(MediaController::create(document()));
 }
 
 MediaController* HTMLMediaElement::controller() const
@@ -7139,6 +7088,7 @@ Vector<String> HTMLMediaElement::mediaPlayerPreferredAudioCharacteristics() cons
 }
 
 #if PLATFORM(IOS_FAMILY)
+
 String HTMLMediaElement::mediaPlayerNetworkInterfaceName() const
 {
     return DeprecatedGlobalSettings::networkInterfaceName();
@@ -7150,6 +7100,7 @@ bool HTMLMediaElement::mediaPlayerGetRawCookies(const URL& url, Vector<Cookie>&
         return page->cookieJar().getRawCookies(document(), url, cookies);
     return false;
 }
+
 #endif
 
 void HTMLMediaElement::mediaPlayerEngineFailedToLoad() const
@@ -7421,15 +7372,7 @@ void HTMLMediaElement::setMediaControlsDependOnPageScaleFactor(bool dependsOnPag
         return;
     }
 
-    if (m_mediaControlsDependOnPageScaleFactor == dependsOnPageScale)
-        return;
-
     m_mediaControlsDependOnPageScaleFactor = dependsOnPageScale;
-
-    if (m_mediaControlsDependOnPageScaleFactor)
-        document().registerForPageScaleFactorChangedCallbacks(*this);
-    else
-        document().unregisterForPageScaleFactorChangedCallbacks(*this);
 }
 
 void HTMLMediaElement::updateMediaControlsAfterPresentationModeChange()
@@ -7472,7 +7415,8 @@ void HTMLMediaElement::updateMediaControlsAfterPresentationModeChange()
 
 void HTMLMediaElement::pageScaleFactorChanged()
 {
-    updatePageScaleFactorJSProperty();
+    if (m_mediaControlsDependOnPageScaleFactor)
+        updatePageScaleFactorJSProperty();
 }
 
 void HTMLMediaElement::userInterfaceLayoutDirectionChanged()
@@ -7940,6 +7884,7 @@ bool HTMLMediaElement::canSaveMediaData() const
 }
 
 #if ENABLE(MEDIA_SESSION)
+
 double HTMLMediaElement::playerVolume() const
 {
     return m_player ? m_player->volume() : 0;
index eb91f3e..1d6dd2e 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2017 Apple Inc. All rights reserved.
+ * Copyright (C) 2007-2019 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -28,7 +28,6 @@
 #if ENABLE(VIDEO)
 
 #include "ActiveDOMObject.h"
-#include "ApplicationStateChangeListener.h"
 #include "AutoplayEvent.h"
 #include "DeferrableTask.h"
 #include "GenericEventQueue.h"
@@ -134,7 +133,6 @@ class HTMLMediaElement
     , private MediaPlayerClient
     , private MediaProducer
     , private VisibilityChangeClient
-    , private ApplicationStateChangeListener
 #if ENABLE(VIDEO_TRACK)
     , private AudioTrackClient
     , private TextTrackClient
@@ -405,6 +403,8 @@ public:
     bool requiresTextTrackRepresentation() const;
     void setTextTrackRepresentation(TextTrackRepresentation*);
     void syncTextTrackBounds();
+
+    void captionPreferencesChanged();
 #endif
 
 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
@@ -459,8 +459,6 @@ public:
     void sourceWasRemoved(HTMLSourceElement&);
     void sourceWasAdded(HTMLSourceElement&);
 
-    void privateBrowsingStateDidChange(PAL::SessionID) override;
-
     // Media cache management.
     WEBCORE_EXPORT static void setMediaCacheDirectory(const String&);
     WEBCORE_EXPORT static const String& mediaCacheDirectory();
@@ -590,6 +588,11 @@ public:
     void remoteHasAvailabilityCallbacksChanged();
 #endif
 
+    void privateBrowsingStateDidChange(PAL::SessionID);
+    void mediaVolumeDidChange();
+    void applicationWillResignActive();
+    void applicationDidBecomeActive();
+
 protected:
     HTMLMediaElement(const QualifiedName&, Document&, bool createdByParser);
     virtual void finishInitialization();
@@ -645,9 +648,7 @@ private:
     void stopWithoutDestroyingMediaPlayer();
     void contextDestroyed() override;
     
-    void mediaVolumeDidChange() override;
-
-    void visibilityStateChanged() override;
+    void visibilityStateChanged() final;
 
     virtual void updateDisplayState() { }
     
@@ -801,7 +802,6 @@ private:
 
     enum ReconfigureMode { Immediately, AfterDelay };
     void markCaptionAndSubtitleTracksAsUnconfigured(ReconfigureMode);
-    void captionPreferencesChanged() override;
     CaptionUserPreferences::CaptionDisplayMode captionDisplayMode();
 #endif
 
@@ -939,9 +939,6 @@ private:
     void handleSeekToPlaybackPosition(double);
     void seekToPlaybackPositionEndedTimerFired();
 
-    void applicationWillResignActive() final;
-    void applicationDidBecomeActive() final;
-
     void setInActiveDocument(bool);
 
 #if !RELEASE_LOG_DISABLED
index 738516f..c3f9bcd 100644 (file)
@@ -46,7 +46,7 @@ RefPtr<NodeList> LabelableElement::labels()
     if (!supportLabels())
         return nullptr;
 
-    return ensureRareData().ensureNodeLists().addCacheWithAtomicName<LabelsNodeList>(*this, starAtom());
+    return ensureRareData().ensureNodeLists().addCacheWithAtomName<LabelsNodeList>(*this, starAtom());
 }
 
 } // namespace Webcore
index b89c5b0..d410178 100644 (file)
@@ -43,7 +43,7 @@ LabelsNodeList::LabelsNodeList(LabelableElement& forNode)
 
 LabelsNodeList::~LabelsNodeList()
 {
-    ownerNode().nodeLists()->removeCacheWithAtomicName(this, starAtom());
+    ownerNode().nodeLists()->removeCacheWithAtomName(*this, starAtom());
 } 
     
 bool LabelsNodeList::elementMatches(Element& testNode) const
index 4c980fb..9470ea2 100644 (file)
@@ -49,7 +49,7 @@ RadioNodeList::RadioNodeList(ContainerNode& rootNode, const AtomString& name)
 
 RadioNodeList::~RadioNodeList()
 {
-    ownerNode().nodeLists()->removeCacheWithAtomicName(this, m_name);
+    ownerNode().nodeLists()->removeCacheWithAtomName(*this, m_name);
 }
 
 static inline RefPtr<HTMLInputElement> toRadioButtonInputElement(HTMLElement& element)
index 9b39816..5a632d8 100644 (file)
@@ -329,7 +329,7 @@ void HTMLDocumentParser::constructTreeFromHTMLToken(HTMLTokenizer::TokenPtr& raw
 {
     AtomicHTMLToken token(*rawToken);
 
-    // We clear the rawToken in case constructTreeFromAtomicToken
+    // We clear the rawToken in case constructTree
     // synchronously re-enters the parser. We don't clear the token immedately
     // for Character tokens because the AtomicHTMLToken avoids copying the
     // characters by keeping a pointer to the underlying buffer in the
index da62d66..23f31f1 100644 (file)
@@ -1059,8 +1059,8 @@ static inline void parseHeader(const CharacterType* header, unsigned headerLengt
     ASSERT(find(header, headerLength, ':') != notFound);
     unsigned colonPosition = find(header, headerLength, ':');
 
-    // Save memory by putting the header names into atomic strings so each is stored only once,
-    // even though the setHTTPHeaderField function does not require an atomic string.
+    // Save memory by putting the header names into atom strings so each is stored only once,
+    // even though the setHTTPHeaderField function does not require an atom string.
     AtomString headerName { header, colonPosition };
     String headerValue { header + colonPosition + 1, headerLength - colonPosition - 1 };
 
diff --git a/Source/WebCore/page/ApplicationStateChangeListener.h b/Source/WebCore/page/ApplicationStateChangeListener.h
deleted file mode 100644 (file)
index 318e052..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2017 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
- */
-
-#pragma once
-
-namespace WebCore {
-
-class Document;
-
-class ApplicationStateChangeListener {
-public:
-    virtual void applicationWillResignActive() { }
-    virtual void applicationDidBecomeActive() { }
-
-protected:
-    virtual ~ApplicationStateChangeListener() = default;
-};
-
-} // namespace WebCore
index a3765c4..95ff70f 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2017 Apple Inc. All rights reserved.
+ * Copyright (C) 2006-2019 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
@@ -23,7 +23,6 @@
 #include "ActivityStateChangeObserver.h"
 #include "AlternativeTextClient.h"
 #include "ApplicationCacheStorage.h"
-#include "ApplicationStateChangeListener.h"
 #include "AuthenticatorCoordinator.h"
 #include "BackForwardCache.h"
 #include "BackForwardClient.h"
@@ -385,11 +384,10 @@ void Page::clearPreviousItemFromAllPages(HistoryItem* item)
 uint64_t Page::renderTreeSize() const
 {
     uint64_t total = 0;
-    for (const Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document() || !frame->document()->renderView())
-            continue;
-        total += frame->document()->renderView()->rendererCount();
-    }
+    forEachDocument([&] (Document& document) {
+        if (auto* renderView = document.renderView())
+            total += renderView->rendererCount();
+    });
     return total;
 }
 
@@ -566,7 +564,7 @@ void Page::initGroup()
 
 void Page::updateStyleAfterChangeInEnvironment()
 {
-    forEachDocument([](Document& document) {
+    forEachDocument([] (Document& document) {
         if (auto* styleResolver = document.styleScope().resolverIfExists())
             styleResolver->invalidateMatchedDeclarationsCache();
         document.scheduleFullStyleRebuild();
@@ -584,10 +582,9 @@ void Page::updateStyleForAllPagesAfterGlobalChangeInEnvironment()
 void Page::setNeedsRecalcStyleInAllFrames()
 {
     // FIXME: Figure out what this function is actually trying to add in different call sites.
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (Document* document = frame->document())
-            document->styleScope().didChangeStyleSheetEnvironment();
-    }
+    forEachDocument([] (Document& document) {
+        document.styleScope().didChangeStyleSheetEnvironment();
+    });
 }
 
 void Page::refreshPlugins(bool reload)
@@ -906,11 +903,9 @@ uint32_t Page::replaceSelectionWithText(const String& replacementText)
 
 void Page::unmarkAllTextMatches()
 {
-    Frame* frame = &mainFrame();
-    do {
-        frame->document()->markers().removeMarkers(DocumentMarker::TextMatch);
-        frame = incrementFrame(frame, true, CanWrap::No);
-    } while (frame);
+    forEachDocument([] (Document& document) {
+        document.markers().removeMarkers(DocumentMarker::TextMatch);
+    });
 }
 
 static bool isEditableTextInputElement(const Element& element)
@@ -926,13 +921,9 @@ static bool isEditableTextInputElement(const Element& element)
 Vector<Ref<Element>> Page::editableElementsInRect(const FloatRect& searchRectInRootViewCoordinates) const
 {
     Vector<Ref<Element>> result;
-    for (auto* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        auto* document = frame->document();
-        if (!document)
-            continue;
-
+    forEachDocument([&] (Document& document) {
         Deque<Node*> nodesToSearch;
-        nodesToSearch.append(document);
+        nodesToSearch.append(&document);
         while (!nodesToSearch.isEmpty()) {
             auto* node = nodesToSearch.takeFirst();
 
@@ -948,7 +939,7 @@ Vector<Ref<Element>> Page::editableElementsInRect(const FloatRect& searchRectInR
             if (searchRectInRootViewCoordinates.intersects(element.clientRect()))
                 result.append(element);
         }
-    }
+    });
     return result;
 }
 
@@ -1003,18 +994,19 @@ DiagnosticLoggingClient& Page::diagnosticLoggingClient() const
 
 void Page::setMediaVolume(float volume)
 {
-    if (volume < 0 || volume > 1)
+    if (!(volume >= 0 && volume <= 1))
         return;
 
     if (m_mediaVolume == volume)
         return;
 
     m_mediaVolume = volume;
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->mediaVolumeDidChange();
-    }
+
+#if ENABLE(VIDEO)
+    forEachMediaElement([] (HTMLMediaElement& element) {
+        element.mediaVolumeDidChange();
+    });
+#endif
 }
 
 void Page::setZoomedOutPageScaleFactor(float scale)
@@ -1034,50 +1026,31 @@ void Page::setPageScaleFactor(float scale, const IntPoint& origin, bool inStable
     RefPtr<FrameView> view = document->view();
 
     if (scale == m_pageScaleFactor) {
-        if (view && view->scrollPosition() != origin) {
-            if (!view->delegatesPageScaling())
-                document->updateLayoutIgnorePendingStylesheets();
-
-            if (!view->delegatesScrolling())
-                view->setScrollPosition(origin);
-#if USE(COORDINATED_GRAPHICS)
-            else
-                view->requestScrollPositionUpdate(origin);
-#endif
-        }
-#if ENABLE(MEDIA_CONTROLS_SCRIPT)
-        if (inStableState) {
-            for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-                if (!frame->document())
-                    continue;
-                frame->document()->pageScaleFactorChangedAndStable();
-            }
-        }
-#endif
-        return;
-    }
-
-    m_pageScaleFactor = scale;
+        if (view && view->scrollPosition() != origin && !view->delegatesPageScaling())
+            document->updateLayoutIgnorePendingStylesheets();
+    } else {
+        m_pageScaleFactor = scale;
 
-    if (view && !view->delegatesPageScaling()) {
-        view->setNeedsLayoutAfterViewConfigurationChange();
-        view->setNeedsCompositingGeometryUpdate();
+        if (view && !view->delegatesPageScaling()) {
+            view->setNeedsLayoutAfterViewConfigurationChange();
+            view->setNeedsCompositingGeometryUpdate();
 
-        document->resolveStyle(Document::ResolveStyleType::Rebuild);
+            document->resolveStyle(Document::ResolveStyleType::Rebuild);
 
-        // Transform change on RenderView doesn't trigger repaint on non-composited contents.
-        mainFrame().view()->invalidateRect(IntRect(LayoutRect::infiniteRect()));
-    }
+            // Transform change on RenderView doesn't trigger repaint on non-composited contents.
+            mainFrame().view()->invalidateRect(IntRect(LayoutRect::infiniteRect()));
+        }
 
-    mainFrame().deviceOrPageScaleFactorChanged();
+        mainFrame().deviceOrPageScaleFactorChanged();
 
-    if (view && view->fixedElementsLayoutRelativeToFrame())
-        view->setViewportConstrainedObjectsNeedLayout();
+        if (view && view->fixedElementsLayoutRelativeToFrame())
+            view->setViewportConstrainedObjectsNeedLayout();
 
-    if (view && view->scrollPosition() != origin) {
-        if (!view->delegatesPageScaling() && document->renderView() && document->renderView()->needsLayout() && view->didFirstLayout())
+        if (view && view->scrollPosition() != origin && !view->delegatesPageScaling() && document->renderView() && document->renderView()->needsLayout() && view->didFirstLayout())
             view->layoutContext().layout();
+    }
 
+    if (view && view->scrollPosition() != origin) {
         if (!view->delegatesScrolling())
             view->setScrollPosition(origin);
 #if USE(COORDINATED_GRAPHICS)
@@ -1088,11 +1061,9 @@ void Page::setPageScaleFactor(float scale, const IntPoint& origin, bool inStable
 
 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
     if (inStableState) {
-        for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-            if (!frame->document())
-                continue;
-            frame->document()->pageScaleFactorChangedAndStable();
-        }
+        forEachMediaElement([] (HTMLMediaElement& element) {
+            element.pageScaleFactorChanged();
+        });
     }
 #else
     UNUSED_PARAM(inStableState);
@@ -1137,21 +1108,24 @@ void Page::setUserInterfaceLayoutDirection(UserInterfaceLayoutDirection userInte
         return;
 
     m_userInterfaceLayoutDirection = userInterfaceLayoutDirection;
+
 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->userInterfaceLayoutDirectionChanged();
-    }
+    forEachMediaElement([] (HTMLMediaElement& element) {
+        element.userInterfaceLayoutDirectionChanged();
+    });
 #endif
 }
 
 #if ENABLE(VIDEO)
+
 void Page::updateMediaElementRateChangeRestrictions()
 {
-    for (auto* mediaElement : HTMLMediaElement::allMediaElements())
-        mediaElement->updateRateChangeRestrictions();
+    // FIXME: This used to call this on all media elements, seemingly by accident. But was there some advantage to that for elements in the back/forward cache?
+    forEachMediaElement([] (HTMLMediaElement& element) {
+        element.updateRateChangeRestrictions();
+    });
 }
+
 #endif
 
 void Page::didStartProvisionalLoad()
@@ -1332,35 +1306,37 @@ void Page::updateRendering()
 
     // Flush autofocus candidates
 
-    forEachDocument([&](Document& document) {
+    forEachDocument([(Document& document) {
         document.runResizeSteps();
     });
 
-    forEachDocument([&](Document& document) {
+    forEachDocument([(Document& document) {
         document.runScrollSteps();
     });
 
-    forEachDocument([&](Document& document) {
+    forEachDocument([(Document& document) {
         document.evaluateMediaQueriesAndReportChanges();        
     });
 
-    Vector<Ref<Document>> documents = collectDocuments(); // The requestAnimationFrame callbacks may change the frame hierarchy of the page
-    for (auto& document : documents) {
-        DOMHighResTimeStamp timestamp = document->domWindow()->nowTimestamp();
-        document->updateAnimationsAndSendEvents(timestamp);
+    forEachDocument([] (Document& document) {
+        DOMHighResTimeStamp timestamp = document.domWindow()->nowTimestamp();
+        document.updateAnimationsAndSendEvents(timestamp);
         // FIXME: Run the fullscreen steps.
-        document->serviceRequestAnimationFrameCallbacks(timestamp);
-    }
+        document.serviceRequestAnimationFrameCallbacks(timestamp);
+    });
 
     layoutIfNeeded();
 
 #if ENABLE(INTERSECTION_OBSERVER)
-    for (auto& document : documents)
-        document->updateIntersectionObservations();
+    forEachDocument([] (Document& document) {
+        document.updateIntersectionObservations();
+    });
 #endif
+
 #if ENABLE(RESIZE_OBSERVER)
-    for (auto& document : documents)
-        document->updateResizeObservations(*this);
+    forEachDocument([&] (Document& document) {
+        document.updateResizeObservations(*this);
+    });
 #endif
 
     layoutIfNeeded();
@@ -1369,37 +1345,32 @@ void Page::updateRendering()
 void Page::suspendScriptedAnimations()
 {
     m_scriptedAnimationsSuspended = true;
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (frame->document())
-            frame->document()->suspendScriptedAnimationControllerCallbacks();
-    }
+
+    forEachDocument([] (Document& document) {
+        document.suspendScriptedAnimationControllerCallbacks();
+    });
 }
 
 void Page::resumeScriptedAnimations()
 {
     m_scriptedAnimationsSuspended = false;
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (frame->document())
-            frame->document()->resumeScriptedAnimationControllerCallbacks();
-    }
+
+    forEachDocument([] (Document& document) {
+        document.resumeScriptedAnimationControllerCallbacks();
+    });
 }
 
 enum class ThrottlingReasonOperation { Add, Remove };
 static void updateScriptedAnimationsThrottlingReason(Page& page, ThrottlingReasonOperation operation, ScriptedAnimationController::ThrottlingReason reason)
 {
-    for (Frame* frame = &page.mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        auto* document = frame->document();
-        if (!document)
-            continue;
-        auto* scriptedAnimationController = document->scriptedAnimationController();
-        if (!scriptedAnimationController)
-            continue;
-
-        if (operation == ThrottlingReasonOperation::Add)
-            scriptedAnimationController->addThrottlingReason(reason);
-        else
-            scriptedAnimationController->removeThrottlingReason(reason);
-    }
+    page.forEachDocument([&] (Document& document) {
+        if (auto* controller = document.scriptedAnimationController()) {
+            if (operation == ThrottlingReasonOperation::Add)
+                controller->addThrottlingReason(reason);
+            else
+                controller->removeThrottlingReason(reason);
+        }
+    });
 }
 
 void Page::setIsVisuallyIdleInternal(bool isVisuallyIdle)
@@ -1411,7 +1382,7 @@ void Page::handleLowModePowerChange(bool isLowPowerModeEnabled)
 {
     updateScriptedAnimationsThrottlingReason(*this, isLowPowerModeEnabled ? ThrottlingReasonOperation::Add : ThrottlingReasonOperation::Remove, ScriptedAnimationController::ThrottlingReason::LowPowerMode);
     if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
-        forEachDocument([&] (Document& document) {
+        forEachDocument([] (Document& document) {
             if (auto timeline = document.existingTimeline())
                 timeline->updateThrottlingState();
         });
@@ -1446,10 +1417,9 @@ void Page::userStyleSheetLocationChanged()
             m_userStyleSheet = String::fromUTF8(styleSheetAsUTF8.data(), styleSheetAsUTF8.size());
     }
 
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (frame->document())
-            frame->document()->extensionStyleSheets().updatePageUserSheet();
-    }
+    forEachDocument([] (Document& document) {
+        document.extensionStyleSheets().updatePageUserSheet();
+    });
 }
 
 const String& Page::userStyleSheet() const
@@ -1504,30 +1474,23 @@ void Page::userAgentChanged()
 
 void Page::invalidateStylesForAllLinks()
 {
-    for (Frame* frame = &m_mainFrame.get(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->visitedLinkState().invalidateStyleForAllLinks();
-    }
+    forEachDocument([] (Document& document) {
+        document.visitedLinkState().invalidateStyleForAllLinks();
+    });
 }
 
 void Page::invalidateStylesForLink(SharedStringHash linkHash)
 {
-    for (Frame* frame = &m_mainFrame.get(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->visitedLinkState().invalidateStyleForLink(linkHash);
-    }
+    forEachDocument([&] (Document& document) {
+        document.visitedLinkState().invalidateStyleForLink(linkHash);
+    });
 }
 
 void Page::invalidateInjectedStyleSheetCacheInAllFrames()
 {
-    for (Frame* frame = &m_mainFrame.get(); frame; frame = frame->tree().traverseNext()) {
-        Document* document = frame->document();
-        if (!document)
-            continue;
-        document->extensionStyleSheets().invalidateInjectedStyleSheetCache();
-    }
+    forEachDocument([] (Document& document) {
+        document.extensionStyleSheets().invalidateInjectedStyleSheetCache();
+    });
 }
 
 void Page::setDebugger(JSC::Debugger* debugger)
@@ -1617,10 +1580,9 @@ void Page::setTimerThrottlingState(TimerThrottlingState state)
 
     // When throttling is disabled, release all throttled timers.
     if (state == TimerThrottlingState::Disabled) {
-        for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-            if (auto* document = frame->document())
-                document->didChangeTimerAlignmentInterval();
-        }
+        forEachDocument([] (Document& document) {
+            document.didChangeTimerAlignmentInterval();
+        });
     }
 }
 
@@ -1679,18 +1641,16 @@ void Page::domTimerAlignmentIntervalIncreaseTimerFired()
     ASSERT(m_settings->hiddenPageDOMTimerThrottlingAutoIncreases());
     ASSERT(m_timerThrottlingState == TimerThrottlingState::EnabledIncreasing);
     ASSERT(m_domTimerAlignmentInterval < m_domTimerAlignmentIntervalIncreaseLimit);
-    
+
     // Alignment interval is increased to equal the time the page has been throttled, to a limit.
     updateDOMTimerAlignmentInterval();
 }
 
 void Page::dnsPrefetchingStateChanged()
 {
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->initDNSPrefetch();
-    }
+    forEachDocument([] (Document& document) {
+        document.initDNSPrefetch();
+    });
 }
 
 Vector<Ref<PluginViewBase>> Page::pluginViews()
@@ -1710,11 +1670,9 @@ Vector<Ref<PluginViewBase>> Page::pluginViews()
 
 void Page::storageBlockingStateChanged()
 {
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->storageBlockingStateDidChange();
-    }
+    forEachDocument([] (Document& document) {
+        document.storageBlockingStateDidChange();
+    });
 
     // Collect the PluginViews in to a vector to ensure that action the plug-in takes
     // from below storageBlockingStateChanged does not affect their lifetime.
@@ -1725,10 +1683,9 @@ void Page::storageBlockingStateChanged()
 void Page::updateIsPlayingMedia(uint64_t sourceElementID)
 {
     MediaProducer::MediaStateFlags state = MediaProducer::IsNotPlaying;
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (Document* document = frame->document())
-            state |= document->mediaState();
-    }
+    forEachDocument([&] (Document& document) {
+        state |= document.mediaState();
+    });
 
     if (state == m_mediaState)
         return;
@@ -1747,6 +1704,7 @@ void Page::schedulePlaybackControlsManagerUpdate()
 }
 
 #if ENABLE(VIDEO)
+
 void Page::playbackControlsManagerUpdateTimerFired()
 {
     if (auto bestMediaElement = HTMLMediaElement::bestMediaElementForShowingPlaybackControlsManager(MediaElementSession::PlaybackControlsPurpose::ControlsManager))
@@ -1754,6 +1712,7 @@ void Page::playbackControlsManagerUpdateTimerFired()
     else
         chrome().client().clearPlaybackControlsManager();
 }
+
 #endif
 
 void Page::setMuted(MediaProducer::MutedStateFlags muted)
@@ -1763,32 +1722,26 @@ void Page::setMuted(MediaProducer::MutedStateFlags muted)
 
     m_mutedState = muted;
 
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->pageMutedStateDidChange();
-    }
+    forEachDocument([] (Document& document) {
+        document.pageMutedStateDidChange();
+    });
 }
 
 void Page::stopMediaCapture()
 {
 #if ENABLE(MEDIA_STREAM)
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-
-        frame->document()->stopMediaCapture();
-    }
+    forEachDocument([] (Document& document) {
+        document.stopMediaCapture();
+    });
 #endif
 }
 
 void Page::stopAllMediaPlayback()
 {
 #if ENABLE(VIDEO)
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (auto* document = frame->document())
-            document->stopAllMediaPlayback();
-    }
+    forEachDocument([] (Document& document) {
+        document.stopAllMediaPlayback();
+    });
 #endif
 }
 
@@ -1799,10 +1752,9 @@ void Page::suspendAllMediaPlayback()
     if (m_mediaPlaybackIsSuspended)
         return;
 
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (auto* document = frame->document())
-            document->suspendAllMediaPlayback();
-    }
+    forEachDocument([] (Document& document) {
+        document.suspendAllMediaPlayback();
+    });
 
     m_mediaPlaybackIsSuspended = true;
 #endif
@@ -1816,10 +1768,9 @@ void Page::resumeAllMediaPlayback()
         return;
     m_mediaPlaybackIsSuspended = false;
 
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (auto* document = frame->document())
-            document->resumeAllMediaPlayback();
-    }
+    forEachDocument([] (Document& document) {
+        document.resumeAllMediaPlayback();
+    });
 #endif
 }
 
@@ -1831,10 +1782,9 @@ void Page::suspendAllMediaBuffering()
         return;
     m_mediaBufferingIsSuspended = true;
 
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (auto* document = frame->document())
-            document->suspendAllMediaBuffering();
-    }
+    forEachDocument([] (Document& document) {
+        document.suspendAllMediaBuffering();
+    });
 #endif
 }
 
@@ -1845,14 +1795,14 @@ void Page::resumeAllMediaBuffering()
         return;
     m_mediaBufferingIsSuspended = false;
 
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (auto* document = frame->document())
-            document->resumeAllMediaBuffering();
-    }
+    forEachDocument([] (Document& document) {
+        document.resumeAllMediaBuffering();
+    });
 #endif
 }
 
 #if ENABLE(MEDIA_SESSION)
+
 void Page::handleMediaEvent(MediaEventType eventType)
 {
     switch (eventType) {
@@ -1873,9 +1823,11 @@ void Page::setVolumeOfMediaElement(double volume, uint64_t elementID)
     if (HTMLMediaElement* element = HTMLMediaElement::elementWithID(elementID))
         element->setVolume(volume, ASSERT_NO_EXCEPTION);
 }
+
 #endif
 
 #if !ASSERT_DISABLED
+
 void Page::checkSubframeCountConsistency() const
 {
     ASSERT(m_subframeCount >= 0);
@@ -1886,6 +1838,7 @@ void Page::checkSubframeCountConsistency() const
 
     ASSERT(m_subframeCount + 1 == subframeCount);
 }
+
 #endif
 
 void Page::resumeAnimatingImages()
@@ -1957,24 +1910,6 @@ void Page::setIsVisible(bool isVisible)
     setActivityState(state);
 }
 
-enum class SVGAnimationsState { Paused, Resumed };
-static inline void setSVGAnimationsState(Page& page, SVGAnimationsState state)
-{
-    for (Frame* frame = &page.mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        auto* document = frame->document();
-        if (!document)
-            continue;
-
-        if (!document->svgExtensions())
-            continue;
-
-        if (state == SVGAnimationsState::Paused)
-            document->accessSVGExtensions().pauseAnimations();
-        else
-            document->accessSVGExtensions().unpauseAnimations();
-    }
-}
-
 void Page::setIsVisibleInternal(bool isVisible)
 {
     // FIXME: The visibility state should be stored on the top-level document.
@@ -1984,8 +1919,11 @@ void Page::setIsVisibleInternal(bool isVisible)
         m_isPrerender = false;
 
         resumeScriptedAnimations();
+
 #if PLATFORM(IOS_FAMILY)
-        resumeDeviceMotionAndOrientationUpdates();
+        forEachDocument([] (Document& document) {
+            document.resumeDeviceMotionAndOrientationUpdates();
+        });
 #endif
 
         if (FrameView* view = mainFrame().view())
@@ -1993,7 +1931,7 @@ void Page::setIsVisibleInternal(bool isVisible)
 
         if (m_settings->hiddenPageCSSAnimationSuspensionEnabled()) {
             if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
-                forEachDocument([&] (Document& document) {
+                forEachDocument([] (Document& document) {
                     if (auto* timeline = document.existingTimeline())
                         timeline->resumeAnimations();
                 });
@@ -2001,7 +1939,10 @@ void Page::setIsVisibleInternal(bool isVisible)
                 mainFrame().animation().resumeAnimations();
         }
 
-        setSVGAnimationsState(*this, SVGAnimationsState::Resumed);
+        forEachDocument([] (Document& document) {
+            if (document.svgExtensions())
+                document.accessSVGExtensions().unpauseAnimations();
+        });
 
         resumeAnimatingImages();
 
@@ -2014,7 +1955,7 @@ void Page::setIsVisibleInternal(bool isVisible)
     if (!isVisible) {
         if (m_settings->hiddenPageCSSAnimationSuspensionEnabled()) {
             if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
-                forEachDocument([&] (Document& document) {
+                forEachDocument([] (Document& document) {
                     if (auto* timeline = document.existingTimeline())
                         timeline->suspendAnimations();
                 });
@@ -2022,10 +1963,15 @@ void Page::setIsVisibleInternal(bool isVisible)
                 mainFrame().animation().suspendAnimations();
         }
 
-        setSVGAnimationsState(*this, SVGAnimationsState::Paused);
+        forEachDocument([] (Document& document) {
+            if (document.svgExtensions())
+                document.accessSVGExtensions().pauseAnimations();
+        });
 
 #if PLATFORM(IOS_FAMILY)
-        suspendDeviceMotionAndOrientationUpdates();
+        forEachDocument([] (Document& document) {
+            document.suspendDeviceMotionAndOrientationUpdates();
+        });
 #endif
 
         suspendScriptedAnimations();
@@ -2034,12 +1980,9 @@ void Page::setIsVisibleInternal(bool isVisible)
             view->hide();
     }
 
-    Vector<Ref<Document>> documents;
-    for (Frame* frame = &m_mainFrame.get(); frame; frame = frame->tree().traverseNext())
-        documents.append(*frame->document());
-
-    for (auto& document : documents)
-        document->visibilityStateChanged();
+    forEachDocument([] (Document& document) {
+        document.visibilityStateChanged();
+    });
 }
 
 void Page::setIsPrerender()
@@ -2130,6 +2073,7 @@ void Page::whenUnnested(WTF::Function<void()>&& callback)
 }
 
 #if ENABLE(REMOTE_INSPECTOR)
+
 bool Page::remoteInspectionAllowed() const
 {
     return m_inspectorDebuggable->remoteDebuggingAllowed();
@@ -2154,6 +2098,7 @@ void Page::remoteInspectorInformationDidChange() const
 {
     m_inspectorDebuggable->update();
 }
+
 #endif
 
 void Page::addLayoutMilestones(OptionSet<LayoutMilestone> milestones)
@@ -2303,22 +2248,6 @@ void Page::addRelevantUnpaintedObject(RenderObject* object, const LayoutRect& ob
     m_relevantUnpaintedRegion.unite(snappedIntRect(objectPaintRect));
 }
 
-void Page::suspendDeviceMotionAndOrientationUpdates()
-{
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (Document* document = frame->document())
-            document->suspendDeviceMotionAndOrientationUpdates();
-    }
-}
-
-void Page::resumeDeviceMotionAndOrientationUpdates()
-{
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (Document* document = frame->document())
-            document->resumeDeviceMotionAndOrientationUpdates();
-    }
-}
-
 void Page::suspendActiveDOMObjectsAndAnimations()
 {
     for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext())
@@ -2395,14 +2324,14 @@ void Page::hiddenPageCSSAnimationSuspensionStateChanged()
 }
 
 #if ENABLE(VIDEO_TRACK)
+
 void Page::captionPreferencesChanged()
 {
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->captionPreferencesChanged();
-    }
+    forEachDocument([] (Document& document) {
+        document.captionPreferencesChanged();
+    });
 }
+
 #endif
 
 void Page::forbidPrompts()
@@ -2550,11 +2479,9 @@ void Page::setSessionID(PAL::SessionID sessionID)
     if (!privateBrowsingStateChanged)
         return;
 
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->privateBrowsingStateDidChange(m_sessionID);
-    }
+    forEachDocument([&] (Document& document) {
+        document.privateBrowsingStateDidChange(m_sessionID);
+    });
 
     // Collect the PluginViews in to a vector to ensure that action the plug-in takes
     // from below privateBrowsingStateChanged does not affect their lifetime.
@@ -2610,39 +2537,32 @@ void Page::mockMediaPlaybackTargetPickerDismissPopup()
 
 void Page::setPlaybackTarget(uint64_t contextId, Ref<MediaPlaybackTarget>&& target)
 {
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->setPlaybackTarget(contextId, target.copyRef());
-    }
+    forEachDocument([&] (Document& document) {
+        document.setPlaybackTarget(contextId, target.copyRef());
+    });
 }
 
 void Page::playbackTargetAvailabilityDidChange(uint64_t contextId, bool available)
 {
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->playbackTargetAvailabilityDidChange(contextId, available);
-    }
+    forEachDocument([&] (Document& document) {
+        document.playbackTargetAvailabilityDidChange(contextId, available);
+    });
 }
 
 void Page::setShouldPlayToPlaybackTarget(uint64_t clientId, bool shouldPlay)
 {
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->setShouldPlayToPlaybackTarget(clientId, shouldPlay);
-    }
+    forEachDocument([&] (Document& document) {
+        document.setShouldPlayToPlaybackTarget(clientId, shouldPlay);
+    });
 }
 
 void Page::playbackTargetPickerWasDismissed(uint64_t clientId)
 {
-    for (auto* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->playbackTargetPickerWasDismissed(clientId);
-    }
+    forEachDocument([&] (Document& document) {
+        document.playbackTargetPickerWasDismissed(clientId);
+    });
 }
+
 #endif
 
 WheelEventTestMonitor& Page::ensureWheelEventTestMonitor()
@@ -2660,19 +2580,18 @@ WheelEventTestMonitor& Page::ensureWheelEventTestMonitor()
 }
 
 #if ENABLE(VIDEO)
+
 void Page::setAllowsMediaDocumentInlinePlayback(bool flag)
 {
     if (m_allowsMediaDocumentInlinePlayback == flag)
         return;
     m_allowsMediaDocumentInlinePlayback = flag;
 
-    Vector<Ref<Document>> documents;
-    for (Frame* frame = &m_mainFrame.get(); frame; frame = frame->tree().traverseNext())
-        documents.append(*frame->document());
-
-    for (auto& document : documents)
-        document->allowsMediaDocumentInlinePlaybackChanged();
+    forEachMediaElement([] (HTMLMediaElement& element) {
+        element.allowsMediaDocumentInlinePlaybackChanged();
+    });
 }
+
 #endif
 
 #if ENABLE(INDEXED_DATABASE)
@@ -2728,7 +2647,7 @@ void Page::setCaptionUserPreferencesStyleSheet(const String& styleSheet)
 
 void Page::accessibilitySettingsDidChange()
 {
-    forEachDocument([](auto& document) {
+    forEachDocument([] (auto& document) {
         document.styleScope().evaluateMediaQueriesForAccessibilitySettingsChange();
         document.updateElementsAffectedByMediaQueries();
         document.scheduleTimedRenderingUpdate();
@@ -2737,7 +2656,7 @@ void Page::accessibilitySettingsDidChange()
 
 void Page::appearanceDidChange()
 {
-    forEachDocument([](auto& document) {
+    forEachDocument([] (auto& document) {
         document.styleScope().didChangeStyleSheetEnvironment();
         document.styleScope().evaluateMediaQueriesForAppearanceChange();
         document.updateElementsAffectedByMediaQueries();
@@ -2752,11 +2671,9 @@ void Page::setUnobscuredSafeAreaInsets(const FloatBoxExtent& insets)
 
     m_unobscuredSafeAreaInsets = insets;
 
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->constantProperties().didChangeSafeAreaInsets();
-    }
+    forEachDocument([&] (Document& document) {
+        document.constantProperties().didChangeSafeAreaInsets();
+    });
 }
 
 void Page::setUseSystemAppearance(bool value)
@@ -2768,15 +2685,11 @@ void Page::setUseSystemAppearance(bool value)
 
     appearanceDidChange();
 
-    for (auto* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        auto* document = frame->document();
-        if (!document)
-            continue;
-
+    forEachDocument([&] (Document& document) {
         // System apperance change may affect stylesheet parsing. We need to reparse.
-        document->extensionStyleSheets().clearPageUserSheet();
-        document->extensionStyleSheets().invalidateInjectedStyleSheetCache();
-    }
+        document.extensionStyleSheets().clearPageUserSheet();
+        document.extensionStyleSheets().invalidateInjectedStyleSheetCache();
+    });
 }
 
 void Page::effectiveAppearanceDidChange(bool useDarkAppearance, bool useElevatedUserInterfaceLevel)
@@ -2835,35 +2748,32 @@ void Page::setFullscreenInsets(const FloatBoxExtent& insets)
 {
     if (insets == m_fullscreenInsets)
         return;
+
     m_fullscreenInsets = insets;
 
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->constantProperties().didChangeFullscreenInsets();
-    }
+    forEachDocument([] (Document& document) {
+        document.constantProperties().didChangeFullscreenInsets();
+    });
 }
 
 void Page::setFullscreenAutoHideDuration(Seconds duration)
 {
     if (duration == m_fullscreenAutoHideDuration)
         return;
+
     m_fullscreenAutoHideDuration = duration;
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->constantProperties().setFullscreenAutoHideDuration(duration);
-    }
+
+    forEachDocument([&] (Document& document) {
+        document.constantProperties().setFullscreenAutoHideDuration(duration);
+    });
 }
 
 void Page::setFullscreenControlsHidden(bool hidden)
 {
 #if ENABLE(FULLSCREEN_API)
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        frame->document()->fullscreenManager().setFullscreenControlsHidden(hidden);
-    }
+    forEachDocument([&] (Document& document) {
+        document.fullscreenManager().setFullscreenControlsHidden(hidden);
+    });
 #else
     UNUSED_PARAM(hidden);
 #endif
@@ -2924,31 +2834,33 @@ RenderingUpdateScheduler& Page::renderingUpdateScheduler()
     return *m_renderingUpdateScheduler;
 }
 
-void Page::forEachDocument(const Function<void(Document&)>& functor)
-{
-    for (auto& document : collectDocuments())
-        functor(document);
-}
-
-Vector<Ref<Document>> Page::collectDocuments()
+void Page::forEachDocument(const Function<void(Document&)>& functor) const
 {
     Vector<Ref<Document>> documents;
-    for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
+    for (auto* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
         auto* document = frame->document();
         if (!document)
             continue;
         documents.append(*document);
     }
-    return documents;
+    for (auto& document : documents)
+        functor(document);
 }
 
-void Page::applicationWillResignActive()
+void Page::forEachMediaElement(const Function<void(HTMLMediaElement&)>& functor)
 {
     forEachDocument([&] (Document& document) {
-        document.forEachApplicationStateChangeListener([&] (ApplicationStateChangeListener& listener) {
-            listener.applicationWillResignActive();
-        });
+        document.forEachMediaElement(functor);
+    });
+}
+
+void Page::applicationWillResignActive()
+{
+#if ENABLE(VIDEO)
+    forEachMediaElement([] (HTMLMediaElement& element) {
+        element.applicationWillResignActive();
     });
+#endif
 }
 
 void Page::applicationDidEnterBackground()
@@ -2963,11 +2875,11 @@ void Page::applicationWillEnterForeground()
 
 void Page::applicationDidBecomeActive()
 {
-    forEachDocument([&] (Document& document) {
-        document.forEachApplicationStateChangeListener([&] (ApplicationStateChangeListener& listener) {
-            listener.applicationDidBecomeActive();
-        });
+#if ENABLE(VIDEO)
+    forEachMediaElement([] (HTMLMediaElement& element) {
+        element.applicationDidBecomeActive();
     });
+#endif
 }
 
 #if PLATFORM(MAC)
@@ -3068,25 +2980,22 @@ void Page::didFinishLoadingImageForElement(HTMLImageElement& element)
 }
 
 #if ENABLE(TEXT_AUTOSIZING)
+
 void Page::recomputeTextAutoSizingInAllFrames()
 {
     ASSERT(settings().textAutosizingEnabled() && settings().textAutosizingUsesIdempotentMode());
-    for (auto* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
-        if (!frame->document())
-            continue;
-        auto& document = *frame->document();
-        if (!document.renderView())
-            continue;
-
-        for (auto& renderer : descendantsOfType<RenderElement>(*document.renderView())) {
-            if (auto* element = renderer.element()) {
-                auto needsLayout = Style::Adjuster::adjustForTextAutosizing(renderer.mutableStyle(), *element);
-                if (needsLayout)
-                    renderer.setNeedsLayout();
+    forEachDocument([] (Document& document) {
+        if (auto* renderView = document.renderView()) {
+            for (auto& renderer : descendantsOfType<RenderElement>(*renderView)) {
+                if (auto* element = renderer.element()) {
+                    if (Style::Adjuster::adjustForTextAutosizing(renderer.mutableStyle(), *element))
+                        renderer.setNeedsLayout();
+                }
             }
         }
-    }
+    });
 }
+
 #endif
 
 } // namespace WebCore
index 5f4ceb0..48f5688 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2017 Apple Inc. All rights reserved.
+ * Copyright (C) 2006-2019 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
@@ -83,33 +83,27 @@ namespace IDBClient {
 class IDBConnectionToServer;
 }
 
+class ActivityStateChangeObserver;
 class AlternativeTextClient;
 class ApplicationCacheStorage;
 class AuthenticatorCoordinator;
 class BackForwardController;
-class BackForwardClient;
 class CacheStorageProvider;
 class Chrome;
-class ChromeClient;
 class Color;
-class ContextMenuClient;
 class ContextMenuController;
 class CookieJar;
-class DOMRect;
 class DOMRectList;
 class DatabaseProvider;
 class DiagnosticLoggingClient;
 class DragCaretController;
-class DragClient;
 class DragController;
 class EditorClient;
 class Element;
 class FocusController;
 class Frame;
-class FrameLoaderClient;
-class HistoryItem;
 class HTMLMediaElement;
-class UserInputBridge;
+class HistoryItem;
 class InspectorClient;
 class InspectorController;
 class LibWebRTCProvider;
@@ -132,50 +126,39 @@ class PluginViewBase;
 class PointerCaptureController;
 class PointerLockController;
 class ProgressTracker;
-class ProgressTrackerClient;
 class Range;
 class RenderObject;
-class RenderTheme;
 class ResourceUsageOverlay;
-class VisibleSelection;
 class ScrollLatchingState;
-class ScrollableArea;
 class ScrollingCoordinator;
 class ServicesOverlayController;
 class Settings;
 class SocketProvider;
+class SpeechSynthesisClient;
 class StorageNamespace;
 class StorageNamespaceProvider;
 class UserContentProvider;
+class UserInputBridge;
 class ValidationMessageClient;
-class ActivityStateChangeObserver;
+class VisibleSelection;
 class VisitedLinkStore;
 class WebGLStateTracker;
-class SpeechSynthesisClient;
 class WheelEventDeltaFilter;
 
-typedef uint64_t SharedStringHash;
+using SharedStringHash = uint64_t;
 
-enum FindDirection {
-    FindDirectionForward,
-    FindDirectionBackward
-};
+enum class CanWrap : bool;
+enum class DidWrap : bool;
+enum class RouteSharingPolicy : uint8_t;
+enum class ShouldTreatAsContinuingLoad : bool;
 
-enum class EventThrottlingBehavior {
-    Responsive,
-    Unresponsive
-};
+enum class EventThrottlingBehavior : bool { Responsive, Unresponsive };
 
-enum class CompositingPolicy : uint8_t {
+enum class CompositingPolicy : bool {
     Normal,
     Conservative, // Used in low memory situations.
 };
 
-enum class CanWrap : bool;
-enum class DidWrap : bool;
-enum class RouteSharingPolicy : uint8_t;
-enum class ShouldTreatAsContinuingLoad : bool;
-
 class Page : public Supplementable<Page>, public CanMakeWeakPtr<Page> {
     WTF_MAKE_NONCOPYABLE(Page);
     WTF_MAKE_FAST_ALLOCATED;
@@ -309,13 +292,14 @@ public:
     WEBCORE_EXPORT void dispatchBeforePrintEvent();
     WEBCORE_EXPORT void dispatchAfterPrintEvent();
 
-    // find all the Ranges for the matching text.
+    // Find all the Ranges for the matching text.
     // Upon return, indexForSelection will be one of the following:
     // 0 if there is no user selection
     // the index of the first range after the user selection
     // NoMatchAfterUserSelection if there is no matching text after the user selection.
     enum { NoMatchAfterUserSelection = -1 };
     WEBCORE_EXPORT void findStringMatchingRanges(const String&, FindOptions, int maxCount, Vector<RefPtr<Range>>&, int& indexForSelection);
+
 #if PLATFORM(COCOA)
     void platformInitialize();
     WEBCORE_EXPORT void addSchedulePair(Ref<SchedulePair>&&);
@@ -379,10 +363,10 @@ public:
     bool enclosedInScrollableAncestorView() const { return m_enclosedInScrollableAncestorView; }
     void setEnclosedInScrollableAncestorView(bool f) { m_enclosedInScrollableAncestorView = f; }
 #endif
-    
+
     bool useSystemAppearance() const { return m_useSystemAppearance; }
     WEBCORE_EXPORT void setUseSystemAppearance(bool);
-    
+
     WEBCORE_EXPORT bool useDarkAppearance() const;
     bool useElevatedUserInterfaceLevel() const { return m_useElevatedUserInterfaceLevel; }
     WEBCORE_EXPORT void effectiveAppearanceDidChange(bool useDarkAppearance, bool useElevatedUserInterfaceLevel);
@@ -433,11 +417,11 @@ public:
     WheelEventDeltaFilter* wheelEventDeltaFilter() { return m_recentWheelEventDeltaFilter.get(); }
     PageOverlayController& pageOverlayController() { return *m_pageOverlayController; }
 
-#if PLATFORM(MAC)
-#if ENABLE(SERVICE_CONTROLS) || ENABLE(TELEPHONE_NUMBER_DETECTION)
+#if PLATFORM(MAC) && (ENABLE(SERVICE_CONTROLS) || ENABLE(TELEPHONE_NUMBER_DETECTION))
     ServicesOverlayController& servicesOverlayController() { return *m_servicesOverlayController; }
-#endif // ENABLE(SERVICE_CONTROLS) || ENABLE(TELEPHONE_NUMBER_DETECTION)
+#endif
 
+#if PLATFORM(MAC)
     ScrollLatchingState* latchingState();
     void pushNewLatchingState();
     void popLatchingState();
@@ -552,8 +536,6 @@ public:
 
     WEBCORE_EXPORT void suspendActiveDOMObjectsAndAnimations();
     WEBCORE_EXPORT void resumeActiveDOMObjectsAndAnimations();
-    void suspendDeviceMotionAndOrientationUpdates();
-    void resumeDeviceMotionAndOrientationUpdates();
 
 #ifndef NDEBUG
     void setIsPainting(bool painting) { m_isPainting = painting; }
@@ -728,6 +710,9 @@ public:
     DeviceOrientationUpdateProvider* deviceOrientationUpdateProvider() const { return m_deviceOrientationUpdateProvider.get(); }
 #endif
 
+    void forEachDocument(const WTF::Function<void(Document&)>&) const;
+    void forEachMediaElement(const WTF::Function<void(HTMLMediaElement&)>&);
+
 private:
     struct Navigation {
         RegistrableDomain domain;
@@ -741,11 +726,7 @@ private:
     void setIsVisibleInternal(bool);
     void setIsVisuallyIdleInternal(bool);
 
-#if ASSERT_DISABLED
-    void checkSubframeCountConsistency() const { }
-#else
     void checkSubframeCountConsistency() const;
-#endif
 
     enum ShouldHighlightMatches { DoNotHighlightMatches, HighlightMatches };
     enum ShouldMarkMatches { DoNotMarkMatches, MarkMatches };
@@ -762,9 +743,6 @@ private:
 
     void handleLowModePowerChange(bool);
 
-    void forEachDocument(const WTF::Function<void(Document&)>&);
-    Vector<Ref<Document>> collectDocuments();
-
     enum class TimerThrottlingState { Disabled, Enabled, EnabledIncreasing };
     void hiddenPageDOMTimerThrottlingStateChanged();
     void setTimerThrottlingState(TimerThrottlingState);
@@ -978,9 +956,9 @@ private:
     std::unique_ptr<PerformanceLogging> m_performanceLogging;
 #if PLATFORM(MAC)
     Vector<ScrollLatchingState> m_latchingState;
-#if ENABLE(SERVICE_CONTROLS) || ENABLE(TELEPHONE_NUMBER_DETECTION)
-    std::unique_ptr<ServicesOverlayController> m_servicesOverlayController;
 #endif
+#if PLATFORM(MAC) && (ENABLE(SERVICE_CONTROLS) || ENABLE(TELEPHONE_NUMBER_DETECTION))
+    std::unique_ptr<ServicesOverlayController> m_servicesOverlayController;
 #endif
 
     std::unique_ptr<WheelEventDeltaFilter> m_recentWheelEventDeltaFilter;
@@ -1017,4 +995,12 @@ inline PageGroup& Page::group()
     return *m_group;
 }
 
+#if ASSERT_DISABLED
+
+inline void Page::checkSubframeCountConsistency() const
+{
+}
+
+#endif
+
 } // namespace WebCore
index 2831570..e5b3723 100644 (file)
@@ -44,7 +44,7 @@ static const TextEncoding& UTF7Encoding()
 }
 
 TextEncoding::TextEncoding(const char* name)
-    : m_name(atomicCanonicalTextEncodingName(name))
+    : m_name(atomCanonicalTextEncodingName(name))
     , m_backslashAsCurrencySymbol(backslashAsCurrencySymbol())
 {
     // Aliases are valid, but not "replacement" itself.
@@ -53,7 +53,7 @@ TextEncoding::TextEncoding(const char* name)
 }
 
 TextEncoding::TextEncoding(const String& name)
-    : m_name(atomicCanonicalTextEncodingName(name))
+    : m_name(atomCanonicalTextEncodingName(name))
     , m_backslashAsCurrencySymbol(backslashAsCurrencySymbol())
 {
     // Aliases are valid, but not "replacement" itself.
@@ -93,7 +93,7 @@ const char* TextEncoding::domName() const
     // FIXME: This is not thread-safe. At the moment, this function is
     // only accessed in a single thread, but eventually has to be made
     // thread-safe along with usesVisualOrdering().
-    static const char* const a = atomicCanonicalTextEncodingName("windows-949");
+    static const char* const a = atomCanonicalTextEncodingName("windows-949");
     if (m_name == a)
         return "EUC-KR";
     return m_name;
@@ -104,7 +104,7 @@ bool TextEncoding::usesVisualOrdering() const
     if (noExtendedTextEncodingNameUsed())
         return false;
 
-    static const char* const a = atomicCanonicalTextEncodingName("ISO-8859-8");
+    static const char* const a = atomCanonicalTextEncodingName("ISO-8859-8");
     return m_name == a;
 }
 
index 5444f02..c9e150e 100644 (file)
@@ -118,40 +118,40 @@ static void addToTextEncodingNameMap(const char* alias, const char* name)
     ASSERT(strlen(alias) <= maxEncodingNameLength);
     if (isUndesiredAlias(alias))
         return;
-    const char* atomicName = textEncodingNameMap->get(name);
-    ASSERT(strcmp(alias, name) == 0 || atomicName);
-    if (!atomicName)
-        atomicName = name;
+    const char* atomName = textEncodingNameMap->get(name);
+    ASSERT(!strcmp(alias, name) || atomName);
+    if (!atomName)
+        atomName = name;
 
-    ASSERT_WITH_MESSAGE(!textEncodingNameMap->get(alias), "Duplicate text encoding name %s for %s (previously registered as %s)", alias, atomicName, textEncodingNameMap->get(alias));
+    ASSERT_WITH_MESSAGE(!textEncodingNameMap->get(alias), "Duplicate text encoding name %s for %s (previously registered as %s)", alias, atomName, textEncodingNameMap->get(alias));
 
-    textEncodingNameMap->add(alias, atomicName);
+    textEncodingNameMap->add(alias, atomName);
 }
 
 static void addToTextCodecMap(const char* name, NewTextCodecFunction&& function)
 {
-    const char* atomicName = textEncodingNameMap->get(name);
-    ASSERT(atomicName);
-    textCodecMap->add(atomicName, WTFMove(function));
+    const char* atomName = textEncodingNameMap->get(name);
+    ASSERT(atomName);
+    textCodecMap->add(atomName, WTFMove(function));
 }
 
 static void pruneBlacklistedCodecs()
 {
     for (auto& nameFromBlacklist : textEncodingNameBlacklist) {
-        auto* atomicName = textEncodingNameMap->get(nameFromBlacklist);
-        if (!atomicName)
+        auto* atomName = textEncodingNameMap->get(nameFromBlacklist);
+        if (!atomName)
             continue;
 
         Vector<const char*> names;
         for (auto& entry : *textEncodingNameMap) {
-            if (entry.value == atomicName)
+            if (entry.value == atomName)
                 names.append(entry.key);
         }
 
         for (auto* name : names)
             textEncodingNameMap->remove(name);
 
-        textCodecMap->remove(atomicName);
+        textCodecMap->remove(atomName);
     }
 }
 
@@ -178,10 +178,10 @@ static void buildBaseTextCodecMaps(const std::lock_guard<Lock>&)
 
 static void addEncodingName(HashSet<const char*>* set, const char* name)
 {
-    // We must not use atomicCanonicalTextEncodingName() because this function is called in it.
-    const char* atomicName = textEncodingNameMap->get(name);
-    if (atomicName)
-        set->add(atomicName);
+    // We must not use atomCanonicalTextEncodingName() because this function is called in it.
+    const char* atomName = textEncodingNameMap->get(name);
+    if (atomName)
+        set->add(atomName);
 }
 
 static void buildQuirksSets()
@@ -251,7 +251,7 @@ std::unique_ptr<TextCodec> newTextCodec(const TextEncoding& encoding)
     return result->value();
 }
 
-const char* atomicCanonicalTextEncodingName(const char* name)
+const char* atomCanonicalTextEncodingName(const char* name)
 {
     if (!name || !name[0])
         return nullptr;
@@ -261,8 +261,8 @@ const char* atomicCanonicalTextEncodingName(const char* name)
     if (!textEncodingNameMap)
         buildBaseTextCodecMaps(lock);
 
-    if (const char* atomicName = textEncodingNameMap->get(name))
-        return atomicName;
+    if (const char* atomName = textEncodingNameMap->get(name))
+        return atomName;
     if (didExtendTextCodecMaps)
         return nullptr;
 
@@ -271,7 +271,7 @@ const char* atomicCanonicalTextEncodingName(const char* name)
     return textEncodingNameMap->get(name);
 }
 
-template<typename CharacterType> static const char* atomicCanonicalTextEncodingName(const CharacterType* characters, size_t length)
+template<typename CharacterType> static const char* atomCanonicalTextEncodingName(const CharacterType* characters, size_t length)
 {
     char buffer[maxEncodingNameLength + 1];
     size_t j = 0;
@@ -281,18 +281,18 @@ template<typename CharacterType> static const char* atomicCanonicalTextEncodingN
         buffer[j++] = characters[i];
     }
     buffer[j] = 0;
-    return atomicCanonicalTextEncodingName(buffer);
+    return atomCanonicalTextEncodingName(buffer);
 }
 
-const char* atomicCanonicalTextEncodingName(const String& alias)
+const char* atomCanonicalTextEncodingName(const String& alias)
 {
     if (alias.isEmpty() || !alias.isAllASCII())
         return nullptr;
 
     if (alias.is8Bit())
-        return atomicCanonicalTextEncodingName(alias.characters8(), alias.length());
+        return atomCanonicalTextEncodingName(alias.characters8(), alias.length());
 
-    return atomicCanonicalTextEncodingName(alias.characters16(), alias.length());
+    return atomCanonicalTextEncodingName(alias.characters16(), alias.length());
 }
 
 bool noExtendedTextEncodingNameUsed()
index 9fc3969..40faefc 100644 (file)
@@ -38,8 +38,8 @@ class TextEncoding;
 WEBCORE_EXPORT std::unique_ptr<TextCodec> newTextCodec(const TextEncoding&);
 
 // Only TextEncoding should use the following functions directly.
-const char* atomicCanonicalTextEncodingName(const char* alias);
-const char* atomicCanonicalTextEncodingName(const String&);
+const char* atomCanonicalTextEncodingName(const char* alias);
+const char* atomCanonicalTextEncodingName(const String&);
 bool noExtendedTextEncodingNameUsed();
 bool isJapaneseEncoding(const char* canonicalEncodingName);
 bool shouldShowBackslashAsCurrencySymbolIn(const char* canonicalEncodingName);
index a924409..9fdfba8 100644 (file)
@@ -304,13 +304,12 @@ Value FunPosition::evaluate() const
     return Expression::evaluationContext().position;
 }
 
-static AtomString atomicSubstring(StringBuilder& builder, unsigned start, unsigned length)
+// FIXME: Should StringBuilder offer this as a member function?
+static StringView toStringView(StringBuilder& builder)
 {
-    ASSERT(start <= builder.length());
-    ASSERT(length <= builder.length() - start);
     if (builder.is8Bit())
-        return AtomString(builder.characters8() + start, length);
-    return AtomString(builder.characters16() + start, length);
+        return { builder.characters8(), builder.length() };
+    return { builder.characters16(), builder.length() };
 }
 
 Value FunId::evaluate() const
@@ -346,7 +345,7 @@ Value FunId::evaluate() const
 
         // If there are several nodes with the same id, id() should return the first one.
         // In WebKit, getElementById behaves so, too, although its behavior in this case is formally undefined.
-        Node* node = contextScope.getElementById(atomicSubstring(idList, startPos, endPos - startPos));
+        Node* node = contextScope.getElementById(toStringView(idList).substring(startPos, endPos - startPos));
         if (node && resultSet.add(node).isNewEntry)
             result.append(node);
         
index 6f616c7..e4272c2 100644 (file)
@@ -1,3 +1,13 @@
+2019-12-23  Darin Adler  <darin@apple.com>
+
+        Refactor to simplify broadcasting to all media elements
+        https://bugs.webkit.org/show_bug.cgi?id=205567
+
+        Reviewed by Eric Carlson.
+
+        * WebProcess/InjectedBundle/InjectedBundleHitTestResult.cpp:
+        (WebKit::InjectedBundleHitTestResult::mediaType const): Use is<HTMLMediaElement>.
+
 2019-12-26  Carlos Garcia Campos  <cgarcia@igalia.com>
 
         [GTK][WPE] Remove duplicated code
index 4121579..df8e55d 100644 (file)
 #include "WebImage.h"
 #include <WebCore/BitmapImage.h>
 #include <WebCore/Document.h>
-#include <WebCore/Element.h>
 #include <WebCore/Frame.h>
 #include <WebCore/FrameLoader.h>
 #include <WebCore/FrameView.h>
 #include <WebCore/GraphicsContext.h>
+#include <WebCore/HTMLMediaElement.h>
 #include <wtf/URL.h>
-#include <wtf/text/WTFString.h>
 
 namespace WebKit {
 using namespace WebCore;
@@ -120,14 +119,9 @@ BundleHitTestResultMediaType InjectedBundleHitTestResult::mediaType() const
 #if !ENABLE(VIDEO)
     return BundleHitTestResultMediaTypeNone;
 #else
-    Node* node = m_hitTestResult.innerNonSharedNode();
-    if (!is<Element>(*node))
-        return BundleHitTestResultMediaTypeNone;
-    
-    if (!downcast<Element>(*node).isMediaElement())
+    if (!is<HTMLMediaElement>(m_hitTestResult.innerNonSharedNode()))
         return BundleHitTestResultMediaTypeNone;
-    
-    return m_hitTestResult.mediaIsVideo() ? BundleHitTestResultMediaTypeVideo : BundleHitTestResultMediaTypeAudio;    
+    return m_hitTestResult.mediaIsVideo() ? BundleHitTestResultMediaTypeVideo : BundleHitTestResultMediaTypeAudio;
 #endif
 }
 
index 9935e7f..ffc0833 100644 (file)
@@ -143,9 +143,9 @@ HRESULT AccessibleBase::get_attribute(_In_ BSTR key, _Out_ VARIANT* value)
     if (!value)
         return E_POINTER;
 
-    AtomString keyAtomic(key, ::SysStringLen(key));
+    AtomString keyAtom(key, ::SysStringLen(key));
 
-    accessibilityAttributeValue(keyAtomic, value);
+    accessibilityAttributeValue(keyAtom, value);
 
     return S_OK;
 }
index 42b7576..be27ab8 100644 (file)
@@ -1,3 +1,13 @@
+2019-12-23  Darin Adler  <darin@apple.com>
+
+        Refactor to simplify broadcasting to all media elements
+        https://bugs.webkit.org/show_bug.cgi?id=205567
+
+        Reviewed by Eric Carlson.
+
+        * AccessibleBase.cpp:
+        (AccessibleBase::get_attribute): Updated for "atomic" -> "atom".
+
 2019-12-21  Brian Burg  <bburg@apple.com>
 
         Web Inspector: add InspectedTargetTypes diagnostic event and related hooks