This source file includes following definitions.
- isValidNameStart
- isValidNamePart
- shouldInheritSecurityOriginFromOwner
- widgetForElement
- acceptsEditingFocus
- canAccessAncestor
- printNavigationErrorMessage
- create
- performTask
- unregisterObserver
- registerObserver
- setObservedDocument
- m_hasViewportUnits
- dispose
- selectorQueryCache
- mediaQueryMatcher
- mediaQueryAffectingValueChanged
- setCompatibilityMode
- compatMode
- setDoctype
- implementation
- hasManifest
- location
- childrenChanged
- createElement
- createElement
- createQualifiedName
- createElementNS
- createElementNS
- registerElement
- registerElement
- setImport
- haveImportsLoaded
- executingWindow
- executingFrame
- createDocumentFragment
- createTextNode
- createComment
- createCDATASection
- createProcessingInstruction
- createEditingTextNode
- importContainerNodeChildren
- importNode
- adoptNode
- hasValidNamespaceForElements
- hasValidNamespaceForAttributes
- createElement
- regionBasedColumnsEnabled
- readyState
- setReadyState
- isLoadCompleted
- encodingName
- defaultCharset
- setCharset
- setContentLanguage
- setXMLVersion
- setXMLStandalone
- baseURI
- setContent
- suggestedMIMEType
- setMimeType
- contentType
- elementFromPoint
- caretRangeFromPoint
- canonicalizedTitle
- updateTitle
- setTitle
- setTitleElement
- removeTitle
- pageVisibilityState
- visibilityState
- hidden
- didChangeVisibilityState
- registerVisibilityObserver
- unregisterVisibilityObserver
- nodeName
- nodeType
- formController
- formElementsState
- setStateForNewFormElements
- view
- page
- frameHost
- settings
- createRange
- createNodeIterator
- createNodeIterator
- createNodeIterator
- createTreeWalker
- createTreeWalker
- createTreeWalker
- needsRenderTreeUpdate
- shouldScheduleRenderTreeUpdate
- scheduleRenderTreeUpdate
- hasPendingForcedStyleRecalc
- updateDistributionIfNeeded
- updateStyleInvalidationIfNeeded
- updateDistributionForNodeIfNeeded
- setupFontBuilder
- inheritHtmlAndBodyElementStyles
- updateRenderTree
- updateStyle
- updateRenderTreeForNodeIfNeeded
- updateLayout
- setNeedsFocusedElementCheck
- clearFocusedElementSoon
- clearFocusedElementTimerFired
- updateLayoutIgnorePendingStylesheets
- styleForElementIgnoringPendingStylesheets
- styleForPage
- isPageBoxVisible
- pageSizeAndMarginsInPixels
- setIsViewSource
- dirtyElementsForLayerUpdate
- scheduleLayerUpdate
- unscheduleLayerUpdate
- scheduleUseShadowTreeUpdate
- unscheduleUseShadowTreeUpdate
- updateUseShadowTreesIfNeeded
- styleResolver
- ensureStyleResolver
- clearStyleResolver
- attach
- detach
- prepareForDestruction
- removeAllEventListeners
- clearAXObjectCache
- existingAXObjectCache
- axObjectCache
- createParser
- isFrameSet
- scriptableDocumentParser
- open
- detachParser
- cancelParsing
- implicitOpen
- body
- setBody
- head
- viewportDefiningElement
- close
- explicitClose
- implicitClose
- dispatchBeforeUnloadEvent
- dispatchUnloadEvents
- pageDismissalEventBeingDispatched
- setParsing
- shouldScheduleLayout
- shouldParserYieldAgressivelyBeforeScriptExecution
- elapsedTime
- write
- write
- writeln
- virtualURL
- virtualCompleteURL
- timerAlignmentInterval
- errorEventTarget
- logExceptionToConsole
- setURL
- updateBaseURL
- setBaseURLOverride
- processBaseElement
- userAgent
- disableEval
- canNavigate
- findUnsafeParentScrollPropagationBoundary
- didLoadAllImports
- didRemoveAllPendingStylesheet
- didLoadAllScriptBlockingResources
- executeScriptsWaitingForResourcesIfNeeded
- elementSheet
- processHttpEquiv
- processHttpEquivContentSecurityPolicy
- processHttpEquivDefaultStyle
- processHttpEquivRefresh
- maybeHandleHttpRefresh
- processHttpEquivSetCookie
- processHttpEquivXFrameOptions
- shouldMergeWithLegacyDescription
- setViewportDescription
- updateViewportDescription
- processReferrerPolicy
- setReferrerPolicy
- outgoingReferrer
- outgoingOrigin
- prepareMouseEvent
- childTypeAllowed
- canReplaceChild
- cloneNode
- cloneDocumentWithoutChildren
- cloneDataFromDocument
- styleSheets
- preferredStylesheetSet
- selectedStylesheetSet
- setSelectedStylesheetSet
- evaluateMediaQueryListIfNeeded
- evaluateMediaQueryList
- notifyResizeForViewportUnits
- styleResolverChanged
- setHoverNode
- setActiveHoverElement
- removeFocusedElementOfSubtree
- hoveredNodeDetached
- activeChainNodeDetached
- annotatedRegions
- setAnnotatedRegions
- setFocusedElement
- setCSSTarget
- registerNodeList
- unregisterNodeList
- attachNodeIterator
- detachNodeIterator
- moveNodeIteratorsToNewDocument
- updateRangesAfterChildrenChanged
- nodeChildrenWillBeRemoved
- nodeWillBeRemoved
- didInsertText
- didRemoveText
- didMergeTextNodes
- didSplitTextNode
- setWindowAttributeEventListener
- getWindowAttributeEventListener
- eventQueue
- enqueueAnimationFrameEvent
- enqueueScrollEventForNode
- enqueueResizeEvent
- createEvent
- createEvent
- addMutationEventListenerTypeIfEnabled
- addListenerTypeIfNeeded
- getOverrideStyle
- ownerElement
- cookie
- setCookie
- referrer
- domain
- setDomain
- lastModified
- firstPartyForCookies
- isValidNameNonASCII
- isValidNameNonASCII
- isValidNameASCII
- isValidName
- parseQualifiedNameInternal
- parseQualifiedName
- setEncodingData
- completeURL
- completeURLWithOverride
- command
- execCommand
- queryCommandEnabled
- queryCommandIndeterm
- queryCommandState
- queryCommandSupported
- queryCommandValue
- openSearchDescriptionURL
- pushCurrentScript
- popCurrentScript
- applyXSLTransform
- setTransformSource
- setDesignMode
- getDesignMode
- inDesignMode
- parentDocument
- topDocument
- contextDocument
- createAttribute
- svgExtensions
- accessSVGExtensions
- hasSVGRootNode
- ensureCachedCollection
- images
- applets
- embeds
- scripts
- links
- forms
- anchors
- allForBinding
- all
- windowNamedItems
- documentNamedItems
- finishedParsing
- elementDataCacheClearTimerFired
- iconURLs
- setUseSecureKeyboardEntryWhenActive
- useSecureKeyboardEntryWhenActive
- initSecurityContext
- contentSecurityPolicyFor
- initSecurityContext
- initContentSecurityPolicy
- allowInlineEventHandlers
- allowExecutingScripts
- updateSecurityOrigin
- didUpdateSecurityOrigin
- isContextThread
- updateFocusAppearanceSoon
- cancelFocusAppearanceUpdate
- updateFocusAppearanceTimerFired
- attachRange
- detachRange
- getCSSCanvasContext
- getCSSCanvasElement
- initDNSPrefetch
- parseDNSPrefetchControlHeader
- reportBlockedScriptExecutionToInspector
- addMessage
- internalAddMessage
- addConsoleMessageWithRequestIdentifier
- postTask
- tasksWereSuspended
- tasksWereResumed
- suspendScheduledTasks
- resumeScheduledTasks
- tasksNeedSuspension
- addToTopLayer
- removeFromTopLayer
- activeModalDialog
- webkitExitPointerLock
- webkitPointerLockElement
- decrementLoadEventDelayCount
- loadEventDelayTimerFired
- loadPluginsSoon
- pluginLoadingTimerFired
- ensureScriptedAnimationController
- requestAnimationFrame
- cancelAnimationFrame
- serviceScriptedAnimations
- createTouch
- createTouchList
- didAddTouchEventHandler
- didRemoveTouchEventHandler
- loader
- initialViewportSize
- eventTargetNodeForDocument
- adjustFloatQuadsForScrollAndAbsoluteZoom
- adjustFloatRectForScrollAndAbsoluteZoom
- hasActiveParser
- decrementActiveParserCount
- setContextFeatures
- nearestCommonHoverAncestor
- updateHoverActiveState
- haveStylesheetsLoaded
- getCachedLocale
- ensureTemplateDocument
- didAssociateFormControl
- didAssociateFormControlsTimerFired
- devicePixelRatio
- createLifecycleNotifier
- lifecycleNotifier
- removedStyleSheet
- modifiedStyleSheet
- textAutosizer
- fastTextAutosizer
- setAutofocusElement
- activeElement
- hasFocus
- defaultEventHandler
- shouldInvalidateNodeListCachesForAttr
- shouldInvalidateNodeListCaches
- invalidateNodeListCaches
#include "config.h"
#include "core/dom/Document.h"
#include "HTMLElementFactory.h"
#include "HTMLNames.h"
#include "RuntimeEnabledFeatures.h"
#include "SVGElementFactory.h"
#include "SVGNames.h"
#include "XMLNSNames.h"
#include "XMLNames.h"
#include "bindings/v8/CustomElementConstructorBuilder.h"
#include "bindings/v8/Dictionary.h"
#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "bindings/v8/ScriptController.h"
#include "core/accessibility/AXObjectCache.h"
#include "core/animation/AnimationClock.h"
#include "core/animation/DocumentAnimations.h"
#include "core/animation/DocumentTimeline.h"
#include "core/animation/css/TransitionTimeline.h"
#include "core/css/CSSFontSelector.h"
#include "core/css/CSSStyleDeclaration.h"
#include "core/css/CSSStyleSheet.h"
#include "core/css/MediaQueryMatcher.h"
#include "core/css/StylePropertySet.h"
#include "core/css/StyleSheetContents.h"
#include "core/css/StyleSheetList.h"
#include "core/css/invalidation/StyleInvalidator.h"
#include "core/css/resolver/FontBuilder.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/css/resolver/StyleResolverStats.h"
#include "core/dom/AddConsoleMessageTask.h"
#include "core/dom/Attr.h"
#include "core/dom/CDATASection.h"
#include "core/dom/Comment.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/DOMImplementation.h"
#include "core/dom/DocumentFragment.h"
#include "core/dom/DocumentLifecycleNotifier.h"
#include "core/dom/DocumentLifecycleObserver.h"
#include "core/dom/DocumentMarkerController.h"
#include "core/dom/DocumentType.h"
#include "core/dom/Element.h"
#include "core/dom/ElementDataCache.h"
#include "core/dom/ElementTraversal.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/ExecutionContextTask.h"
#include "core/dom/MainThreadTaskRunner.h"
#include "core/dom/MutationObserver.h"
#include "core/dom/NodeChildRemovalTracker.h"
#include "core/dom/NodeFilter.h"
#include "core/dom/NodeIterator.h"
#include "core/dom/NodeRareData.h"
#include "core/dom/NodeRenderStyle.h"
#include "core/dom/NodeRenderingTraversal.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/NodeWithIndex.h"
#include "core/dom/ProcessingInstruction.h"
#include "core/dom/RequestAnimationFrameCallback.h"
#include "core/dom/ScriptRunner.h"
#include "core/dom/ScriptedAnimationController.h"
#include "core/dom/SelectorQuery.h"
#include "core/dom/StyleEngine.h"
#include "core/dom/TouchList.h"
#include "core/dom/TransformSource.h"
#include "core/dom/TreeWalker.h"
#include "core/dom/VisitedLinkState.h"
#include "core/dom/XMLDocument.h"
#include "core/dom/custom/CustomElementRegistrationContext.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/Editor.h"
#include "core/editing/FrameSelection.h"
#include "core/editing/SpellChecker.h"
#include "core/events/BeforeUnloadEvent.h"
#include "core/events/Event.h"
#include "core/events/EventFactory.h"
#include "core/events/EventListener.h"
#include "core/events/HashChangeEvent.h"
#include "core/events/PageTransitionEvent.h"
#include "core/events/ScopedEventQueue.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/frame/DOMWindow.h"
#include "core/frame/FrameHost.h"
#include "core/frame/FrameView.h"
#include "core/frame/History.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/PageConsole.h"
#include "core/frame/Settings.h"
#include "core/frame/csp/ContentSecurityPolicy.h"
#include "core/html/HTMLAllCollection.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLBaseElement.h"
#include "core/html/HTMLCanvasElement.h"
#include "core/html/HTMLCollection.h"
#include "core/html/HTMLDialogElement.h"
#include "core/html/HTMLDocument.h"
#include "core/html/HTMLFrameOwnerElement.h"
#include "core/html/HTMLHeadElement.h"
#include "core/html/HTMLIFrameElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLLinkElement.h"
#include "core/html/HTMLMetaElement.h"
#include "core/html/HTMLNameCollection.h"
#include "core/html/HTMLScriptElement.h"
#include "core/html/HTMLStyleElement.h"
#include "core/html/HTMLTemplateElement.h"
#include "core/html/HTMLTitleElement.h"
#include "core/html/PluginDocument.h"
#include "core/html/canvas/CanvasRenderingContext.h"
#include "core/html/canvas/CanvasRenderingContext2D.h"
#include "core/html/canvas/WebGLRenderingContext.h"
#include "core/html/forms/FormController.h"
#include "core/html/imports/HTMLImport.h"
#include "core/html/parser/HTMLDocumentParser.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/parser/NestingLevelIncrementer.h"
#include "core/html/parser/TextResourceDecoder.h"
#include "core/inspector/InspectorCounters.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/loader/CookieJar.h"
#include "core/loader/DocumentLoader.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
#include "core/loader/ImageLoader.h"
#include "core/loader/appcache/ApplicationCacheHost.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
#include "core/page/EventHandler.h"
#include "core/page/FocusController.h"
#include "core/page/FrameTree.h"
#include "core/page/MouseEventWithHitTestResults.h"
#include "core/page/Page.h"
#include "core/page/PointerLockController.h"
#include "core/page/scrolling/ScrollingCoordinator.h"
#include "core/rendering/FastTextAutosizer.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/TextAutosizer.h"
#include "core/svg/SVGDocumentExtensions.h"
#include "core/svg/SVGFontFaceElement.h"
#include "core/svg/SVGStyleElement.h"
#include "core/svg/SVGUseElement.h"
#include "core/workers/SharedWorkerRepositoryClient.h"
#include "core/xml/XSLTProcessor.h"
#include "core/xml/parser/XMLDocumentParser.h"
#include "platform/DateComponents.h"
#include "platform/Language.h"
#include "platform/TraceEvent.h"
#include "platform/network/ContentSecurityPolicyParsers.h"
#include "platform/network/HTTPParsers.h"
#include "platform/scroll/ScrollbarTheme.h"
#include "platform/text/PlatformLocale.h"
#include "platform/text/SegmentedString.h"
#include "platform/weborigin/OriginAccessEntry.h"
#include "platform/weborigin/SchemeRegistry.h"
#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/CurrentTime.h"
#include "wtf/HashFunctions.h"
#include "wtf/MainThread.h"
#include "wtf/StdLibExtras.h"
#include "wtf/TemporaryChange.h"
#include "wtf/text/StringBuffer.h"
#include "wtf/text/TextEncodingRegistry.h"
using namespace std;
using namespace WTF;
using namespace Unicode;
namespace WebCore {
using namespace HTMLNames;
static const unsigned cMaxWriteRecursionDepth = 21;
static const int cLayoutScheduleThreshold = 250;
static inline bool isValidNameStart(UChar32 c)
{
if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
return true;
if (c == ':' || c == '_')
return true;
const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
if (!(Unicode::category(c) & nameStartMask))
return false;
if (c >= 0xF900 && c < 0xFFFE)
return false;
DecompositionType decompType = decompositionType(c);
if (decompType == DecompositionFont || decompType == DecompositionCompat)
return false;
return true;
}
static inline bool isValidNamePart(UChar32 c)
{
if (isValidNameStart(c))
return true;
if (c == 0x00B7 || c == 0x0387)
return true;
if (c == '-' || c == '.')
return true;
const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
if (!(Unicode::category(c) & otherNamePartMask))
return false;
if (c >= 0xF900 && c < 0xFFFE)
return false;
DecompositionType decompType = decompositionType(c);
if (decompType == DecompositionFont || decompType == DecompositionCompat)
return false;
return true;
}
static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
{
return url.isEmpty() || url.isBlankURL();
}
static Widget* widgetForElement(const Element& focusedElement)
{
RenderObject* renderer = focusedElement.renderer();
if (!renderer || !renderer->isWidget())
return 0;
return toRenderWidget(renderer)->widget();
}
static bool acceptsEditingFocus(const Element& element)
{
ASSERT(element.rendererIsEditable());
return element.document().frame() && element.rootEditableElement();
}
static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, LocalFrame* targetFrame)
{
if (!targetFrame)
return false;
const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
for (LocalFrame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
Document* ancestorDocument = ancestorFrame->document();
if (!ancestorDocument)
return true;
const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
if (activeSecurityOrigin.canAccess(ancestorSecurityOrigin))
return true;
if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
return true;
}
return false;
}
static void printNavigationErrorMessage(const LocalFrame& frame, const KURL& activeURL, const char* reason)
{
String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame.document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
frame.domWindow()->printErrorMessage(message);
}
uint64_t Document::s_globalTreeVersion = 0;
class AutofocusTask FINAL : public ExecutionContextTask {
public:
static PassOwnPtr<AutofocusTask> create()
{
return adoptPtr(new AutofocusTask());
}
virtual ~AutofocusTask() { }
private:
AutofocusTask() { }
virtual void performTask(ExecutionContext* context) OVERRIDE
{
Document* document = toDocument(context);
if (RefPtr<Element> element = document->autofocusElement()) {
document->setAutofocusElement(0);
element->focus();
}
}
};
DocumentVisibilityObserver::DocumentVisibilityObserver(Document& document)
: m_document(0)
{
registerObserver(document);
}
DocumentVisibilityObserver::~DocumentVisibilityObserver()
{
unregisterObserver();
}
void DocumentVisibilityObserver::unregisterObserver()
{
if (m_document) {
m_document->unregisterVisibilityObserver(this);
m_document = 0;
}
}
void DocumentVisibilityObserver::registerObserver(Document& document)
{
ASSERT(!m_document);
m_document = &document;
if (m_document)
m_document->registerVisibilityObserver(this);
}
void DocumentVisibilityObserver::setObservedDocument(Document& document)
{
unregisterObserver();
registerObserver(document);
}
Document::Document(const DocumentInit& initializer, DocumentClassFlags documentClasses)
: ContainerNode(0, CreateDocument)
, TreeScope(*this)
, m_hasNodesWithPlaceholderStyle(false)
, m_needsNotifyRemoveAllPendingStylesheet(false)
, m_evaluateMediaQueriesOnStyleRecalc(false)
, m_pendingSheetLayout(NoLayoutWithPendingSheets)
, m_frame(initializer.frame())
, m_domWindow(m_frame ? m_frame->domWindow() : 0)
, m_import(initializer.import())
, m_activeParserCount(0)
, m_contextFeatures(ContextFeatures::defaultSwitch())
, m_wellFormed(false)
, m_printing(false)
, m_paginatedForScreen(false)
, m_compatibilityMode(NoQuirksMode)
, m_compatibilityModeLocked(false)
, m_hasAutofocused(false)
, m_clearFocusedElementTimer(this, &Document::clearFocusedElementTimerFired)
, m_domTreeVersion(++s_globalTreeVersion)
, m_listenerTypes(0)
, m_mutationObserverTypes(0)
, m_visitedLinkState(VisitedLinkState::create(*this))
, m_visuallyOrdered(false)
, m_readyState(Complete)
, m_isParsing(false)
, m_historyItemDocumentStateDirty(false)
, m_gotoAnchorNeededAfterStylesheetsLoad(false)
, m_containsValidityStyleRules(false)
, m_updateFocusAppearanceRestoresSelection(false)
, m_containsPlugins(false)
, m_ignoreDestructiveWriteCount(0)
, m_titleSetExplicitly(false)
, m_markers(adoptPtr(new DocumentMarkerController))
, m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
, m_cssTarget(0)
, m_loadEventProgress(LoadEventNotRun)
, m_startTime(currentTime())
, m_scriptRunner(ScriptRunner::create(this))
, m_xmlVersion("1.0")
, m_xmlStandalone(StandaloneUnspecified)
, m_hasXMLDeclaration(0)
, m_designMode(inherit)
, m_hasAnnotatedRegions(false)
, m_annotatedRegionsDirty(false)
, m_useSecureKeyboardEntryWhenActive(false)
, m_documentClasses(documentClasses)
, m_isViewSource(false)
, m_sawElementsInKnownNamespaces(false)
, m_isSrcdocDocument(false)
, m_isMobileDocument(false)
, m_renderView(0)
, m_weakFactory(this)
, m_contextDocument(initializer.contextDocument())
, m_hasFullscreenElementStack(false)
, m_loadEventDelayCount(0)
, m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
, m_pluginLoadingTimer(this, &Document::pluginLoadingTimerFired)
, m_didSetReferrerPolicy(false)
, m_referrerPolicy(ReferrerPolicyDefault)
, m_directionSetOnDocumentElement(false)
, m_writingModeSetOnDocumentElement(false)
, m_writeRecursionIsTooDeep(false)
, m_writeRecursionDepth(0)
, m_taskRunner(MainThreadTaskRunner::create(this))
, m_registrationContext(initializer.registrationContext(this))
, m_elementDataCacheClearTimer(this, &Document::elementDataCacheClearTimerFired)
#ifndef NDEBUG
, m_didDispatchViewportPropertiesChanged(false)
#endif
, m_animationClock(AnimationClock::create())
, m_timeline(DocumentTimeline::create(this))
, m_transitionTimeline(TransitionTimeline::create(this))
, m_templateDocumentHost(0)
, m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
, m_hasViewportUnits(false)
{
setClient(this);
ScriptWrappable::init(this);
if (m_frame) {
ASSERT(m_frame->page());
provideContextFeaturesToDocumentFrom(*this, *m_frame->page());
m_fetcher = m_frame->loader().documentLoader()->fetcher();
}
if (!m_fetcher)
m_fetcher = ResourceFetcher::create(0);
m_fetcher->setDocument(this);
if (initializer.shouldSetURL())
setURL(initializer.url());
initSecurityContext(initializer);
initDNSPrefetch();
for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
m_nodeListCounts[i] = 0;
InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
m_lifecycle.advanceTo(DocumentLifecycle::Inactive);
m_styleEngine = StyleEngine::create(*this);
}
Document::~Document()
{
ASSERT(!renderView());
ASSERT(m_ranges.isEmpty());
ASSERT(!parentTreeScope());
ASSERT(!hasGuardRefCount());
ASSERT(m_visibilityObservers.isEmpty());
if (m_templateDocument)
m_templateDocument->m_templateDocumentHost = 0;
m_scriptRunner.clear();
removeAllEventListeners();
ASSERT(!m_parser || m_parser->refCount() == 1);
detachParser();
if (this == topDocument())
clearAXObjectCache();
if (m_styleSheetList)
m_styleSheetList->detachFromDocument();
if (m_import) {
m_import->wasDetachedFromDocument();
m_import = 0;
}
m_timeline->detachFromDocument();
m_transitionTimeline->detachFromDocument();
if (m_styleEngine)
m_styleEngine->detachFromDocument();
if (m_elemSheet)
m_elemSheet->clearOwnerNode();
if (m_fetcher->document() == this)
m_fetcher->setDocument(0);
m_fetcher.clear();
if (hasRareData())
clearRareData();
ASSERT(!m_listsInvalidatedAtDocument.size());
for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
ASSERT(!m_nodeListCounts[i]);
setClient(0);
InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
}
void Document::dispose()
{
ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
m_docType = nullptr;
m_focusedElement = nullptr;
m_hoverNode = nullptr;
m_activeHoverElement = nullptr;
m_titleElement = nullptr;
m_documentElement = nullptr;
m_contextFeatures = ContextFeatures::defaultSwitch();
m_userActionElements.documentDidRemoveLastRef();
m_associatedFormControls.clear();
detachParser();
m_registrationContext.clear();
if (m_import) {
m_import->wasDetachedFromDocument();
m_import = 0;
}
destroyTreeScopeData();
removeDetachedChildren();
m_formController.clear();
m_markers->clear();
m_cssCanvasElements.clear();
if (m_scriptedAnimationController)
m_scriptedAnimationController->clearDocumentPointer();
m_scriptedAnimationController.clear();
if (svgExtensions())
accessSVGExtensions().pauseAnimations();
m_lifecycle.advanceTo(DocumentLifecycle::Disposed);
lifecycleNotifier().notifyDocumentWasDisposed();
}
SelectorQueryCache& Document::selectorQueryCache()
{
if (!m_selectorQueryCache)
m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
return *m_selectorQueryCache;
}
MediaQueryMatcher& Document::mediaQueryMatcher()
{
if (!m_mediaQueryMatcher)
m_mediaQueryMatcher = MediaQueryMatcher::create(this);
return *m_mediaQueryMatcher;
}
void Document::mediaQueryAffectingValueChanged()
{
styleEngine()->clearMediaQueryRuleSetStyleSheets();
}
void Document::setCompatibilityMode(CompatibilityMode mode)
{
if (m_compatibilityModeLocked || mode == m_compatibilityMode)
return;
bool wasInQuirksMode = inQuirksMode();
m_compatibilityMode = mode;
selectorQueryCache().invalidate();
if (inQuirksMode() != wasInQuirksMode) {
m_styleEngine->invalidateInjectedStyleSheetCache();
}
}
String Document::compatMode() const
{
return inQuirksMode() ? "BackCompat" : "CSS1Compat";
}
void Document::setDoctype(PassRefPtr<DocumentType> docType)
{
ASSERT(!m_docType || !docType);
m_docType = docType;
if (m_docType) {
this->adoptIfNeeded(*m_docType);
if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", false))
m_isMobileDocument = true;
}
clearStyleResolver();
}
DOMImplementation& Document::implementation()
{
if (!m_implementation)
m_implementation = DOMImplementation::create(*this);
return *m_implementation;
}
bool Document::hasManifest() const
{
return isHTMLHtmlElement(documentElement()) && documentElement()->hasAttribute(manifestAttr);
}
Location* Document::location() const
{
if (!frame())
return 0;
return &domWindow()->location();
}
void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
m_documentElement = ElementTraversal::firstWithin(*this);
}
PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& exceptionState)
{
if (!isValidName(name)) {
exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + name + "') is not a valid name.");
return nullptr;
}
if (isXHTMLDocument() || isHTMLDocument())
return HTMLElementFactory::createHTMLElement(isHTMLDocument() ? name.lower() : name, *this, 0, false);
return Element::create(QualifiedName(nullAtom, name, nullAtom), this);
}
PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& exceptionState)
{
if (!isValidName(localName)) {
exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + localName + "') is not a valid name.");
return nullptr;
}
RefPtr<Element> element;
if (CustomElement::isValidName(localName) && registrationContext()) {
element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI));
} else {
element = createElement(localName, exceptionState);
if (exceptionState.hadException())
return nullptr;
}
if (!typeExtension.isEmpty())
CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
return element;
}
static inline QualifiedName createQualifiedName(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
{
AtomicString prefix, localName;
if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
return nullQName();
QualifiedName qName(prefix, localName, namespaceURI);
if (!Document::hasValidNamespaceForElements(qName)) {
exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
return nullQName();
}
return qName;
}
PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
{
QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
if (qName == nullQName())
return nullptr;
return createElement(qName, false);
}
PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
{
QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
if (qName == nullQName())
return nullptr;
RefPtr<Element> element;
if (CustomElement::isValidName(qName.localName()) && registrationContext())
element = registrationContext()->createCustomTagElement(*this, qName);
else
element = createElement(qName, false);
if (!typeExtension.isEmpty())
CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
return element;
}
ScriptValue Document::registerElement(WebCore::NewScriptState* scriptState, const AtomicString& name, ExceptionState& exceptionState)
{
return registerElement(scriptState, name, Dictionary(), exceptionState);
}
ScriptValue Document::registerElement(WebCore::NewScriptState* scriptState, const AtomicString& name, const Dictionary& options, ExceptionState& exceptionState, CustomElement::NameSet validNames)
{
if (!registrationContext()) {
exceptionState.throwDOMException(NotSupportedError, "No element registration context is available.");
return ScriptValue();
}
CustomElementConstructorBuilder constructorBuilder(scriptState, &options);
registrationContext()->registerElement(this, &constructorBuilder, name, validNames, exceptionState);
return constructorBuilder.bindingsReturnValue();
}
void Document::setImport(HTMLImport* import)
{
ASSERT(!m_import || !import);
m_import = import;
}
bool Document::haveImportsLoaded() const
{
return !m_import || !m_import->state().shouldBlockScriptExecution();
}
DOMWindow* Document::executingWindow()
{
if (DOMWindow* owningWindow = domWindow())
return owningWindow;
if (HTMLImport* import = this->import())
return import->master()->domWindow();
return 0;
}
LocalFrame* Document::executingFrame()
{
DOMWindow* window = executingWindow();
if (!window)
return 0;
return window->frame();
}
PassRefPtr<DocumentFragment> Document::createDocumentFragment()
{
return DocumentFragment::create(*this);
}
PassRefPtr<Text> Document::createTextNode(const String& data)
{
return Text::create(*this, data);
}
PassRefPtr<Comment> Document::createComment(const String& data)
{
return Comment::create(*this, data);
}
PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& exceptionState)
{
if (isHTMLDocument()) {
exceptionState.throwDOMException(NotSupportedError, "This operation is not supported for HTML documents.");
return nullptr;
}
if (data.contains("]]>")) {
exceptionState.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
return nullptr;
}
return CDATASection::create(*this, data);
}
PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& exceptionState)
{
if (!isValidName(target)) {
exceptionState.throwDOMException(InvalidCharacterError, "The target provided ('" + target + "') is not a valid name.");
return nullptr;
}
if (data.contains("?>")) {
exceptionState.throwDOMException(InvalidCharacterError, "The data provided ('" + data + "') contains '?>'.");
return nullptr;
}
return ProcessingInstruction::create(*this, target, data);
}
PassRefPtr<Text> Document::createEditingTextNode(const String& text)
{
return Text::createEditingText(*this, text);
}
bool Document::importContainerNodeChildren(ContainerNode* oldContainerNode, PassRefPtr<ContainerNode> newContainerNode, ExceptionState& exceptionState)
{
for (Node* oldChild = oldContainerNode->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
RefPtr<Node> newChild = importNode(oldChild, true, exceptionState);
if (exceptionState.hadException())
return false;
newContainerNode->appendChild(newChild.release(), exceptionState);
if (exceptionState.hadException())
return false;
}
return true;
}
PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& exceptionState)
{
if (!importedNode) {
exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
return nullptr;
}
switch (importedNode->nodeType()) {
case TEXT_NODE:
return createTextNode(importedNode->nodeValue());
case CDATA_SECTION_NODE:
return createCDATASection(importedNode->nodeValue(), exceptionState);
case PROCESSING_INSTRUCTION_NODE:
return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), exceptionState);
case COMMENT_NODE:
return createComment(importedNode->nodeValue());
case DOCUMENT_TYPE_NODE: {
DocumentType* doctype = toDocumentType(importedNode);
return DocumentType::create(this, doctype->name(), doctype->publicId(), doctype->systemId());
}
case ELEMENT_NODE: {
Element* oldElement = toElement(importedNode);
if (!hasValidNamespaceForElements(oldElement->tagQName())) {
exceptionState.throwDOMException(NamespaceError, "The imported node has an invalid namespace.");
return nullptr;
}
RefPtr<Element> newElement = createElement(oldElement->tagQName(), false);
newElement->cloneDataFromElement(*oldElement);
if (deep) {
if (!importContainerNodeChildren(oldElement, newElement, exceptionState))
return nullptr;
if (isHTMLTemplateElement(*oldElement)
&& !importContainerNodeChildren(toHTMLTemplateElement(oldElement)->content(), toHTMLTemplateElement(newElement)->content(), exceptionState))
return nullptr;
}
return newElement.release();
}
case ATTRIBUTE_NODE:
return Attr::create(*this, QualifiedName(nullAtom, AtomicString(toAttr(importedNode)->name()), nullAtom), toAttr(importedNode)->value());
case DOCUMENT_FRAGMENT_NODE: {
if (importedNode->isShadowRoot()) {
exceptionState.throwDOMException(NotSupportedError, "The node provided is a shadow root, which may not be imported.");
return nullptr;
}
DocumentFragment* oldFragment = toDocumentFragment(importedNode);
RefPtr<DocumentFragment> newFragment = createDocumentFragment();
if (deep && !importContainerNodeChildren(oldFragment, newFragment, exceptionState))
return nullptr;
return newFragment.release();
}
case DOCUMENT_NODE:
exceptionState.throwDOMException(NotSupportedError, "The node provided is a document, which may not be imported.");
return nullptr;
}
ASSERT_NOT_REACHED();
return nullptr;
}
PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionState& exceptionState)
{
if (!source) {
exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
return nullptr;
}
EventQueueScope scope;
switch (source->nodeType()) {
case DOCUMENT_NODE:
case DOCUMENT_TYPE_NODE:
exceptionState.throwDOMException(NotSupportedError, "The node provided is of type '" + source->nodeName() + "', which may not be adopted.");
return nullptr;
case ATTRIBUTE_NODE: {
Attr* attr = toAttr(source.get());
if (attr->ownerElement())
attr->ownerElement()->removeAttributeNode(attr, exceptionState);
break;
}
default:
if (source->isShadowRoot()) {
exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a shadow root, which may not be adopted.");
return nullptr;
}
if (source->isFrameOwnerElement()) {
HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
if (frame() && frame()->tree().isDescendantOf(toLocalFrameTemporary(frameOwnerElement->contentFrame()))) {
exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a frame which contains this document.");
return nullptr;
}
}
if (source->parentNode()) {
source->parentNode()->removeChild(source.get(), exceptionState);
if (exceptionState.hadException())
return nullptr;
}
}
this->adoptIfNeeded(*source);
return source;
}
bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
{
if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull())
return false;
if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI)
return false;
if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
}
bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
{
return hasValidNamespaceForElements(qName);
}
PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
{
RefPtr<Element> e;
if (qName.namespaceURI() == xhtmlNamespaceURI)
e = HTMLElementFactory::createHTMLElement(qName.localName(), *this, 0, createdByParser);
else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
e = SVGElementFactory::createSVGElement(qName.localName(), *this, createdByParser);
if (e)
m_sawElementsInKnownNamespaces = true;
else
e = Element::create(qName, this);
if (e->prefix() != qName.prefix())
e->setTagNameForCreateElementNS(qName);
ASSERT(qName == e->tagQName());
return e.release();
}
bool Document::regionBasedColumnsEnabled() const
{
return settings() && settings()->regionBasedColumnsEnabled();
}
String Document::readyState() const
{
DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
switch (m_readyState) {
case Loading:
return loading;
case Interactive:
return interactive;
case Complete:
return complete;
}
ASSERT_NOT_REACHED();
return String();
}
void Document::setReadyState(ReadyState readyState)
{
if (readyState == m_readyState)
return;
switch (readyState) {
case Loading:
if (!m_documentTiming.domLoading) {
m_documentTiming.domLoading = monotonicallyIncreasingTime();
m_timeline->setZeroTime(m_documentTiming.domLoading);
}
break;
case Interactive:
if (!m_documentTiming.domInteractive)
m_documentTiming.domInteractive = monotonicallyIncreasingTime();
break;
case Complete:
if (!m_documentTiming.domComplete)
m_documentTiming.domComplete = monotonicallyIncreasingTime();
break;
}
m_readyState = readyState;
dispatchEvent(Event::create(EventTypeNames::readystatechange));
}
bool Document::isLoadCompleted()
{
return m_readyState == Complete;
}
AtomicString Document::encodingName() const
{
return AtomicString(encoding().name());
}
String Document::defaultCharset() const
{
if (Settings* settings = this->settings())
return settings->defaultTextEncodingName();
return String();
}
void Document::setCharset(const String& charset)
{
if (DocumentLoader* documentLoader = loader())
documentLoader->setUserChosenEncoding(charset);
WTF::TextEncoding encoding(charset);
if (!encoding.isValid())
return;
DocumentEncodingData newEncodingData = m_encodingData;
newEncodingData.setEncoding(encoding);
setEncodingData(newEncodingData);
}
void Document::setContentLanguage(const AtomicString& language)
{
if (m_contentLanguage == language)
return;
m_contentLanguage = language;
setNeedsStyleRecalc(SubtreeStyleChange);
}
void Document::setXMLVersion(const String& version, ExceptionState& exceptionState)
{
if (!implementation().hasFeature("XML", String())) {
exceptionState.throwDOMException(NotSupportedError, "This document does not support XML.");
return;
}
if (!XMLDocumentParser::supportsXMLVersion(version)) {
exceptionState.throwDOMException(NotSupportedError, "This document does not support the XML version '" + version + "'.");
return;
}
m_xmlVersion = version;
}
void Document::setXMLStandalone(bool standalone, ExceptionState& exceptionState)
{
if (!implementation().hasFeature("XML", String())) {
exceptionState.throwDOMException(NotSupportedError, "This document does not support XML.");
return;
}
m_xmlStandalone = standalone ? Standalone : NotStandalone;
}
KURL Document::baseURI() const
{
return m_baseURL;
}
void Document::setContent(const String& content)
{
open();
m_parser->pinToMainThread();
m_parser->append(content.impl());
close();
}
String Document::suggestedMIMEType() const
{
if (isXMLDocument()) {
if (isXHTMLDocument())
return "application/xhtml+xml";
if (isSVGDocument())
return "image/svg+xml";
return "application/xml";
}
if (xmlStandalone())
return "text/xml";
if (isHTMLDocument())
return "text/html";
if (DocumentLoader* documentLoader = loader())
return documentLoader->responseMIMEType();
return String();
}
void Document::setMimeType(const AtomicString& mimeType)
{
m_mimeType = mimeType;
}
AtomicString Document::contentType() const
{
if (!m_mimeType.isEmpty())
return m_mimeType;
if (DocumentLoader* documentLoader = loader())
return documentLoader->mimeType();
String mimeType = suggestedMIMEType();
if (!mimeType.isEmpty())
return AtomicString(mimeType);
return AtomicString("application/xml");
}
Element* Document::elementFromPoint(int x, int y) const
{
if (!renderView())
return 0;
return TreeScope::elementFromPoint(x, y);
}
PassRefPtrWillBeRawPtr<Range> Document::caretRangeFromPoint(int x, int y)
{
if (!renderView())
return nullptr;
HitTestResult result = hitTestInDocument(this, x, y);
RenderObject* renderer = result.renderer();
if (!renderer)
return nullptr;
Node* node = renderer->node();
Node* shadowAncestorNode = ancestorInThisScope(node);
if (shadowAncestorNode != node) {
unsigned offset = shadowAncestorNode->nodeIndex();
ContainerNode* container = shadowAncestorNode->parentNode();
return Range::create(*this, container, offset, container, offset);
}
PositionWithAffinity positionWithAffinity = renderer->positionForPoint(result.localPoint());
if (positionWithAffinity.position().isNull())
return nullptr;
Position rangeCompliantPosition = positionWithAffinity.position().parentAnchoredEquivalent();
return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
}
template <typename CharacterType>
static inline String canonicalizedTitle(Document* document, const String& title)
{
const CharacterType* characters = title.getCharacters<CharacterType>();
unsigned length = title.length();
unsigned i;
StringBuffer<CharacterType> buffer(length);
unsigned builderIndex = 0;
for (i = 0; i < length; ++i) {
CharacterType c = characters[i];
if (!(c <= 0x20 || c == 0x7F))
break;
}
if (i == length)
return String();
bool previousCharWasWS = false;
for (; i < length; ++i) {
CharacterType c = characters[i];
if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
if (previousCharWasWS)
continue;
buffer[builderIndex++] = ' ';
previousCharWasWS = true;
} else {
buffer[builderIndex++] = c;
previousCharWasWS = false;
}
}
while (builderIndex > 0) {
--builderIndex;
if (buffer[builderIndex] != ' ')
break;
}
if (!builderIndex && buffer[builderIndex] == ' ')
return String();
buffer.shrink(builderIndex + 1);
return String::adopt(buffer);
}
void Document::updateTitle(const String& title)
{
if (m_rawTitle == title)
return;
m_rawTitle = title;
String oldTitle = m_title;
if (m_rawTitle.isEmpty())
m_title = String();
else if (m_rawTitle.is8Bit())
m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
else
m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
if (!m_frame || oldTitle == m_title)
return;
m_frame->loader().client()->dispatchDidReceiveTitle(m_title);
}
void Document::setTitle(const String& title)
{
m_titleSetExplicitly = true;
if (!isHTMLDocument() && !isXHTMLDocument())
m_titleElement = nullptr;
else if (!m_titleElement) {
if (HTMLElement* headElement = head()) {
m_titleElement = HTMLTitleElement::create(*this);
headElement->appendChild(m_titleElement);
}
}
if (isHTMLTitleElement(m_titleElement))
toHTMLTitleElement(m_titleElement)->setText(title);
else
updateTitle(title);
}
void Document::setTitleElement(const String& title, Element* titleElement)
{
if (titleElement != m_titleElement) {
if (m_titleElement || m_titleSetExplicitly)
return;
m_titleElement = titleElement;
}
updateTitle(title);
}
void Document::removeTitle(Element* titleElement)
{
if (m_titleElement != titleElement)
return;
m_titleElement = nullptr;
m_titleSetExplicitly = false;
if (HTMLElement* headElement = head()) {
if (HTMLTitleElement* title = Traversal<HTMLTitleElement>::firstChild(*headElement))
setTitleElement(title->text(), title);
}
if (!m_titleElement)
updateTitle(String());
}
PageVisibilityState Document::pageVisibilityState() const
{
if (!m_frame || !m_frame->page())
return PageVisibilityStateHidden;
return m_frame->page()->visibilityState();
}
String Document::visibilityState() const
{
return pageVisibilityStateString(pageVisibilityState());
}
bool Document::hidden() const
{
return pageVisibilityState() != PageVisibilityStateVisible;
}
void Document::didChangeVisibilityState()
{
dispatchEvent(Event::create(EventTypeNames::visibilitychange));
dispatchEvent(Event::create(EventTypeNames::webkitvisibilitychange));
PageVisibilityState state = pageVisibilityState();
HashSet<DocumentVisibilityObserver*>::const_iterator observerEnd = m_visibilityObservers.end();
for (HashSet<DocumentVisibilityObserver*>::const_iterator it = m_visibilityObservers.begin(); it != observerEnd; ++it)
(*it)->didChangeVisibilityState(state);
}
void Document::registerVisibilityObserver(DocumentVisibilityObserver* observer)
{
ASSERT(!m_visibilityObservers.contains(observer));
m_visibilityObservers.add(observer);
}
void Document::unregisterVisibilityObserver(DocumentVisibilityObserver* observer)
{
ASSERT(m_visibilityObservers.contains(observer));
m_visibilityObservers.remove(observer);
}
String Document::nodeName() const
{
return "#document";
}
Node::NodeType Document::nodeType() const
{
return DOCUMENT_NODE;
}
FormController& Document::formController()
{
if (!m_formController)
m_formController = FormController::create();
return *m_formController;
}
Vector<String> Document::formElementsState() const
{
if (!m_formController)
return Vector<String>();
return m_formController->formElementsState();
}
void Document::setStateForNewFormElements(const Vector<String>& stateVector)
{
if (!stateVector.size() && !m_formController)
return;
formController().setStateForNewFormElements(stateVector);
}
FrameView* Document::view() const
{
return m_frame ? m_frame->view() : 0;
}
Page* Document::page() const
{
return m_frame ? m_frame->page() : 0;
}
FrameHost* Document::frameHost() const
{
return m_frame ? m_frame->host() : 0;
}
Settings* Document::settings() const
{
return m_frame ? m_frame->settings() : 0;
}
PassRefPtrWillBeRawPtr<Range> Document::createRange()
{
return Range::create(*this);
}
PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionState& exceptionState)
{
if (!root) {
exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
return nullptr;
}
return NodeIterator::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
}
PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
{
if (!root) {
exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
return nullptr;
}
return NodeIterator::create(root, whatToShow, PassRefPtr<NodeFilter>());
}
PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
{
if (!root) {
exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
return nullptr;
}
return NodeIterator::create(root, whatToShow, filter);
}
PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionState& exceptionState)
{
if (!root) {
exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
return nullptr;
}
return TreeWalker::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
}
PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
{
if (!root) {
exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
return nullptr;
}
return TreeWalker::create(root, whatToShow, PassRefPtr<NodeFilter>());
}
PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
{
if (!root) {
exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
return nullptr;
}
return TreeWalker::create(root, whatToShow, filter);
}
bool Document::needsRenderTreeUpdate() const
{
if (!isActive() || !view())
return false;
if (needsStyleRecalc() || childNeedsStyleRecalc())
return true;
if (childNeedsDistributionRecalc())
return true;
if (!m_useElementsNeedingUpdate.isEmpty())
return true;
if (!m_layerUpdateElements.isEmpty())
return true;
if (childNeedsStyleInvalidation())
return true;
return false;
}
bool Document::shouldScheduleRenderTreeUpdate() const
{
if (!isActive())
return false;
if (inStyleRecalc())
return false;
if (m_lifecycle.state() == DocumentLifecycle::InPreLayout)
return false;
if (!shouldScheduleLayout())
return false;
return true;
}
void Document::scheduleRenderTreeUpdate()
{
ASSERT(!hasPendingStyleRecalc());
ASSERT(shouldScheduleRenderTreeUpdate());
ASSERT(needsRenderTreeUpdate());
page()->animator().scheduleVisualUpdate();
m_lifecycle.advanceTo(DocumentLifecycle::StyleRecalcPending);
InspectorInstrumentation::didScheduleStyleRecalculation(this);
}
bool Document::hasPendingForcedStyleRecalc() const
{
return hasPendingStyleRecalc() && !inStyleRecalc() && styleChangeType() >= SubtreeStyleChange;
}
void Document::updateDistributionIfNeeded()
{
if (!childNeedsDistributionRecalc())
return;
TRACE_EVENT0("webkit", "Document::recalcDistribution");
recalcDistribution();
}
void Document::updateStyleInvalidationIfNeeded()
{
if (!isActive())
return;
if (!childNeedsStyleInvalidation())
return;
TRACE_EVENT0("webkit", "Document::computeNeedsStyleRecalcState");
ASSERT(styleResolver());
styleResolver()->ruleFeatureSet().styleInvalidator().invalidate(*this);
}
void Document::updateDistributionForNodeIfNeeded(Node* node)
{
if (node->inDocument()) {
updateDistributionIfNeeded();
return;
}
Node* root = node;
while (Node* host = root->shadowHost())
root = host;
while (Node* ancestor = root->parentOrShadowHostNode())
root = ancestor;
if (root->childNeedsDistributionRecalc())
root->recalcDistribution();
}
void Document::setupFontBuilder(RenderStyle* documentStyle)
{
FontBuilder fontBuilder;
fontBuilder.initForStyleResolve(*this, documentStyle, isSVGDocument());
RefPtr<CSSFontSelector> selector = m_styleEngine->fontSelector();
fontBuilder.createFontForDocument(selector, documentStyle);
}
void Document::inheritHtmlAndBodyElementStyles(StyleRecalcChange change)
{
ASSERT(inStyleRecalc());
ASSERT(documentElement());
RefPtr<RenderStyle> documentElementStyle = documentElement()->renderStyle();
if (!documentElementStyle || documentElement()->needsStyleRecalc() || change == Force)
documentElementStyle = ensureStyleResolver().styleForElement(documentElement());
WritingMode rootWritingMode = documentElementStyle->writingMode();
TextDirection rootDirection = documentElementStyle->direction();
HTMLElement* body = this->body();
RefPtr<RenderStyle> bodyStyle;
if (body) {
bodyStyle = body->renderStyle();
if (!bodyStyle || body->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
bodyStyle = ensureStyleResolver().styleForElement(body, documentElementStyle.get());
if (!writingModeSetOnDocumentElement())
rootWritingMode = bodyStyle->writingMode();
if (!directionSetOnDocumentElement())
rootDirection = bodyStyle->direction();
}
RefPtr<RenderStyle> overflowStyle;
if (Element* element = viewportDefiningElement(documentElementStyle.get())) {
if (element == body) {
overflowStyle = bodyStyle;
} else {
ASSERT(element == documentElement());
overflowStyle = documentElementStyle;
}
}
if (styleEngine()->usesRemUnits() && (documentElement()->needsAttach() || documentElement()->computedStyle()->fontSize() != documentElementStyle->fontSize())) {
ensureStyleResolver().invalidateMatchedPropertiesCache();
documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
}
EOverflow overflowX = OAUTO;
EOverflow overflowY = OAUTO;
float columnGap = 0;
if (overflowStyle) {
overflowX = overflowStyle->overflowX();
overflowY = overflowStyle->overflowY();
if (overflowX == OVISIBLE)
overflowX = OAUTO;
if (overflowY == OVISIBLE)
overflowY = OAUTO;
columnGap = overflowStyle->columnGap();
}
RefPtr<RenderStyle> documentStyle = renderView()->style();
if (documentStyle->writingMode() != rootWritingMode
|| documentStyle->direction() != rootDirection
|| documentStyle->overflowX() != overflowX
|| documentStyle->overflowY() != overflowY
|| documentStyle->columnGap() != columnGap) {
RefPtr<RenderStyle> newStyle = RenderStyle::clone(documentStyle.get());
newStyle->setWritingMode(rootWritingMode);
newStyle->setDirection(rootDirection);
newStyle->setColumnGap(columnGap);
newStyle->setOverflowX(overflowX);
newStyle->setOverflowY(overflowY);
renderView()->setStyle(newStyle);
setupFontBuilder(newStyle.get());
}
if (body) {
if (RenderStyle* style = body->renderStyle()) {
if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
body->setNeedsStyleRecalc(SubtreeStyleChange);
}
}
if (RenderStyle* style = documentElement()->renderStyle()) {
if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
}
}
void Document::updateRenderTree(StyleRecalcChange change)
{
ASSERT(isMainThread());
if (change != Force && !needsRenderTreeUpdate())
return;
if (inStyleRecalc())
return;
RELEASE_ASSERT(!view()->isInPerformLayout());
RELEASE_ASSERT(!view()->isPainting());
RefPtr<LocalFrame> protect(m_frame);
TRACE_EVENT0("webkit", "Document::updateRenderTree");
TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "UpdateRenderTree");
InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
updateDistributionIfNeeded();
updateUseShadowTreesIfNeeded();
updateStyleInvalidationIfNeeded();
evaluateMediaQueryListIfNeeded();
if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
m_styleEngine->setUsesRemUnit(true);
updateStyle(change);
if (hoverNode() && !hoverNode()->renderer() && frame())
frame()->eventHandler().dispatchFakeMouseMoveEventSoon();
if (m_focusedElement && !m_focusedElement->isFocusable())
clearFocusedElementSoon();
#if ENABLE(SVG_FONTS)
if (svgExtensions())
accessSVGExtensions().removePendingSVGFontFaceElementsForRemoval();
#endif
InspectorInstrumentation::didRecalculateStyle(cookie);
}
void Document::updateStyle(StyleRecalcChange change)
{
TRACE_EVENT0("webkit", "Document::updateStyle");
HTMLFrameOwnerElement::UpdateSuspendScope suspendWidgetHierarchyUpdates;
m_lifecycle.advanceTo(DocumentLifecycle::InStyleRecalc);
if (styleChangeType() >= SubtreeStyleChange)
change = Force;
if (change == Force) {
m_hasNodesWithPlaceholderStyle = false;
RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this, m_styleEngine->fontSelector());
StyleRecalcChange localChange = RenderStyle::stylePropagationDiff(documentStyle.get(), renderView()->style());
if (localChange != NoChange)
renderView()->setStyle(documentStyle.release());
}
clearNeedsStyleRecalc();
if (StyleResolverStats* stats = ensureStyleResolver().stats())
stats->reset();
if (Element* documentElement = this->documentElement()) {
inheritHtmlAndBodyElementStyles(change);
dirtyElementsForLayerUpdate();
if (documentElement->shouldCallRecalcStyle(change))
documentElement->recalcStyle(change);
while (dirtyElementsForLayerUpdate())
documentElement->recalcStyle(NoChange);
}
ensureStyleResolver().printStats();
view()->updateCompositingLayersAfterStyleChange();
clearChildNeedsStyleRecalc();
if (m_styleEngine->hasResolver()) {
StyleResolver& resolver = m_styleEngine->ensureResolver();
m_styleEngine->resetCSSFeatureFlags(resolver.ensureUpdatedRuleFeatureSet());
resolver.clearStyleSharingList();
}
ASSERT(!needsStyleRecalc());
ASSERT(!childNeedsStyleRecalc());
ASSERT(inStyleRecalc());
m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
}
void Document::updateRenderTreeForNodeIfNeeded(Node* node)
{
if (!needsRenderTreeUpdate())
return;
bool needsRecalc = needsStyleRecalc() || childNeedsDistributionRecalc() || !m_useElementsNeedingUpdate.isEmpty() || childNeedsStyleInvalidation();
for (Node* ancestor = node; ancestor && !needsRecalc; ancestor = ancestor->parentOrShadowHostNode())
needsRecalc = ancestor->needsStyleRecalc();
if (needsRecalc)
updateRenderTreeIfNeeded();
}
void Document::updateLayout()
{
ASSERT(isMainThread());
RefPtr<FrameView> frameView = view();
if (frameView && frameView->isInPerformLayout()) {
ASSERT_NOT_REACHED();
return;
}
if (Element* oe = ownerElement())
oe->document().updateLayout();
updateRenderTreeIfNeeded();
if (isActive() && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
frameView->layout();
}
void Document::setNeedsFocusedElementCheck()
{
setNeedsStyleRecalc(LocalStyleChange);
}
void Document::clearFocusedElementSoon()
{
if (!m_clearFocusedElementTimer.isActive())
m_clearFocusedElementTimer.startOneShot(0, FROM_HERE);
}
void Document::clearFocusedElementTimerFired(Timer<Document>*)
{
updateRenderTreeIfNeeded();
m_clearFocusedElementTimer.stop();
if (m_focusedElement && !m_focusedElement->isFocusable())
setFocusedElement(nullptr);
}
void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
{
StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
if (m_styleEngine->hasPendingSheets()) {
HTMLElement* bodyElement = body();
if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
m_pendingSheetLayout = DidLayoutWithPendingSheets;
styleResolverChanged(RecalcStyleImmediately);
} else if (m_hasNodesWithPlaceholderStyle) {
updateRenderTree(Force);
}
}
updateLayout();
if (runPostLayoutTasks == RunPostLayoutTasksSynchronously && view())
view()->flushAnyPendingPostLayoutTasks();
}
PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
{
ASSERT_ARG(element, element->document() == this);
StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
return ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
}
PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
{
return ensureStyleResolver().styleForPage(pageIndex);
}
bool Document::isPageBoxVisible(int pageIndex)
{
return styleForPage(pageIndex)->visibility() != HIDDEN;
}
void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
{
RefPtr<RenderStyle> style = styleForPage(pageIndex);
int width = pageSize.width();
int height = pageSize.height();
switch (style->pageSizeType()) {
case PAGE_SIZE_AUTO:
break;
case PAGE_SIZE_AUTO_LANDSCAPE:
if (width < height)
std::swap(width, height);
break;
case PAGE_SIZE_AUTO_PORTRAIT:
if (width > height)
std::swap(width, height);
break;
case PAGE_SIZE_RESOLVED: {
LengthSize size = style->pageSize();
ASSERT(size.width().isFixed());
ASSERT(size.height().isFixed());
width = valueForLength(size.width(), 0);
height = valueForLength(size.height(), 0);
break;
}
default:
ASSERT_NOT_REACHED();
}
pageSize = IntSize(width, height);
marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
}
void Document::setIsViewSource(bool isViewSource)
{
m_isViewSource = isViewSource;
if (!m_isViewSource)
return;
setSecurityOrigin(SecurityOrigin::createUnique());
didUpdateSecurityOrigin();
}
bool Document::dirtyElementsForLayerUpdate()
{
if (m_layerUpdateElements.isEmpty())
return false;
HashSet<Element*>::iterator end = m_layerUpdateElements.end();
for (HashSet<Element*>::iterator it = m_layerUpdateElements.begin(); it != end; ++it)
(*it)->setNeedsStyleRecalc(LocalStyleChange);
m_layerUpdateElements.clear();
return true;
}
void Document::scheduleLayerUpdate(Element& element)
{
if (element.styleChangeType() == NeedsReattachStyleChange)
return;
element.setNeedsLayerUpdate();
m_layerUpdateElements.add(&element);
scheduleRenderTreeUpdateIfNeeded();
}
void Document::unscheduleLayerUpdate(Element& element)
{
element.clearNeedsLayerUpdate();
m_layerUpdateElements.remove(&element);
}
void Document::scheduleUseShadowTreeUpdate(SVGUseElement& element)
{
m_useElementsNeedingUpdate.add(&element);
scheduleRenderTreeUpdateIfNeeded();
}
void Document::unscheduleUseShadowTreeUpdate(SVGUseElement& element)
{
m_useElementsNeedingUpdate.remove(&element);
}
void Document::updateUseShadowTreesIfNeeded()
{
if (m_useElementsNeedingUpdate.isEmpty())
return;
Vector<SVGUseElement*> elements;
copyToVector(m_useElementsNeedingUpdate, elements);
m_useElementsNeedingUpdate.clear();
Vector<SVGUseElement*>::iterator end = elements.end();
for (Vector<SVGUseElement*>::iterator it = elements.begin(); it != end; ++it)
(*it)->buildPendingResource();
}
StyleResolver* Document::styleResolver() const
{
return m_styleEngine->resolver();
}
StyleResolver& Document::ensureStyleResolver() const
{
return m_styleEngine->ensureResolver();
}
void Document::clearStyleResolver()
{
m_styleEngine->clearResolver();
}
void Document::attach(const AttachContext& context)
{
ASSERT(m_lifecycle.state() == DocumentLifecycle::Inactive);
ASSERT(!m_axObjectCache || this != topDocument());
m_renderView = new RenderView(this);
setRenderer(m_renderView);
m_renderView->setIsInWindow(true);
m_renderView->setStyle(StyleResolver::styleForDocument(*this));
view()->updateCompositingLayersAfterStyleChange();
ContainerNode::attach(context);
if (FastTextAutosizer* textAutosizer = fastTextAutosizer())
textAutosizer->updatePageInfo();
m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
}
void Document::detach(const AttachContext& context)
{
ASSERT(isActive());
m_lifecycle.advanceTo(DocumentLifecycle::Stopping);
if (page())
page()->documentDetached(this);
InspectorInstrumentation::documentDetached(this);
if (m_frame->loader().client()->sharedWorkerRepositoryClient())
m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this);
if (this == topDocument())
clearAXObjectCache();
stopActiveDOMObjects();
if (m_scriptedAnimationController)
m_scriptedAnimationController->clearDocumentPointer();
m_scriptedAnimationController.clear();
if (svgExtensions())
accessSVGExtensions().pauseAnimations();
if (m_domWindow)
m_domWindow->clearEventQueue();
RenderView* renderView = m_renderView;
if (renderView)
renderView->setIsInWindow(false);
if (m_frame) {
FrameView* view = m_frame->view();
if (view)
view->detachCustomScrollbars();
}
setRenderer(0);
m_renderView = 0;
m_hoverNode = nullptr;
m_focusedElement = nullptr;
m_activeHoverElement = nullptr;
m_autofocusElement = nullptr;
ContainerNode::detach(context);
m_styleEngine->didDetach();
if (renderView)
renderView->destroy();
if (Document* parentDoc = parentDocument())
parentDoc->didClearTouchEventHandlers(this);
m_frame = 0;
if (m_mediaQueryMatcher)
m_mediaQueryMatcher->documentDestroyed();
lifecycleNotifier().notifyDocumentWasDetached();
m_lifecycle.advanceTo(DocumentLifecycle::Stopped);
}
void Document::prepareForDestruction()
{
m_markers->prepareForDestruction();
disconnectDescendantFrames();
if (!isActive())
return;
if (DOMWindow* window = this->domWindow())
window->willDetachDocumentFromFrame();
detach();
}
void Document::removeAllEventListeners()
{
ContainerNode::removeAllEventListeners();
if (DOMWindow* domWindow = this->domWindow())
domWindow->removeAllEventListeners();
for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
node->removeAllEventListeners();
}
void Document::clearAXObjectCache()
{
ASSERT(topDocument() == this);
m_axObjectCache.clear();
}
AXObjectCache* Document::existingAXObjectCache() const
{
if (!AXObjectCache::accessibilityEnabled())
return 0;
if (!topDocument().renderView())
return 0;
return topDocument().m_axObjectCache.get();
}
AXObjectCache* Document::axObjectCache() const
{
if (!AXObjectCache::accessibilityEnabled())
return 0;
Document& topDocument = this->topDocument();
if (!topDocument.renderView())
return 0;
ASSERT(topDocument == this || !m_axObjectCache);
if (!topDocument.m_axObjectCache)
topDocument.m_axObjectCache = adoptPtr(new AXObjectCache(topDocument));
return topDocument.m_axObjectCache.get();
}
PassRefPtr<DocumentParser> Document::createParser()
{
if (isHTMLDocument()) {
bool reportErrors = InspectorInstrumentation::collectingHTMLParseErrors(page());
return HTMLDocumentParser::create(toHTMLDocument(this), reportErrors);
}
return XMLDocumentParser::create(this, view());
}
bool Document::isFrameSet() const
{
if (!isHTMLDocument())
return false;
return isHTMLFrameSetElement(body());
}
ScriptableDocumentParser* Document::scriptableDocumentParser() const
{
return parser() ? parser()->asScriptableDocumentParser() : 0;
}
void Document::open(Document* ownerDocument)
{
if (ownerDocument) {
setURL(ownerDocument->url());
m_cookieURL = ownerDocument->cookieURL();
setSecurityOrigin(ownerDocument->securityOrigin());
}
if (m_frame) {
if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
if (parser->isParsing()) {
if (parser->isExecutingScript())
return;
if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
return;
}
}
if (m_frame->loader().state() == FrameStateProvisional)
m_frame->loader().stopAllLoaders();
}
removeAllEventListeners();
implicitOpen();
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->setWasCreatedByScript(true);
if (m_frame)
m_frame->loader().didExplicitOpen();
if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
m_loadEventProgress = LoadEventNotRun;
}
void Document::detachParser()
{
if (!m_parser)
return;
m_parser->detach();
m_parser.clear();
}
void Document::cancelParsing()
{
if (!m_parser)
return;
detachParser();
explicitClose();
}
PassRefPtr<DocumentParser> Document::implicitOpen()
{
cancelParsing();
removeChildren();
ASSERT(!m_focusedElement);
setCompatibilityMode(NoQuirksMode);
m_parser = createParser();
setParsing(true);
setReadyState(Loading);
return m_parser;
}
HTMLElement* Document::body() const
{
if (!documentElement())
return 0;
for (HTMLElement* child = Traversal<HTMLElement>::firstWithin(*documentElement()); child; child = Traversal<HTMLElement>::nextSibling(*child)) {
if (isHTMLFrameSetElement(*child) || isHTMLBodyElement(*child))
return child;
}
return 0;
}
void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionState& exceptionState)
{
RefPtr<HTMLElement> newBody = prpNewBody;
if (!newBody) {
exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::argumentNullOrIncorrectType(1, "HTMLElement"));
return;
}
if (!documentElement()) {
exceptionState.throwDOMException(HierarchyRequestError, "No document element exists.");
return;
}
if (!isHTMLBodyElement(*newBody) && !isHTMLFrameSetElement(*newBody)) {
exceptionState.throwDOMException(HierarchyRequestError, "The new body element is of type '" + newBody->tagName() + "'. It must be either a 'BODY' or 'FRAMESET' element.");
return;
}
HTMLElement* oldBody = body();
if (oldBody == newBody)
return;
if (oldBody)
documentElement()->replaceChild(newBody.release(), oldBody, exceptionState);
else
documentElement()->appendChild(newBody.release(), exceptionState);
}
HTMLHeadElement* Document::head()
{
Node* de = documentElement();
if (!de)
return 0;
return Traversal<HTMLHeadElement>::firstChild(*de);
}
Element* Document::viewportDefiningElement(RenderStyle* rootStyle) const
{
Element* rootElement = documentElement();
Element* bodyElement = body();
if (!rootElement)
return 0;
if (!rootStyle) {
rootStyle = rootElement->renderStyle();
if (!rootStyle)
return 0;
}
if (bodyElement && rootStyle->isOverflowVisible() && isHTMLHtmlElement(*rootElement))
return bodyElement;
return rootElement;
}
void Document::close()
{
if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
return;
explicitClose();
}
void Document::explicitClose()
{
if (RefPtr<DocumentParser> parser = m_parser)
parser->finish();
if (!m_frame) {
implicitClose();
return;
}
m_frame->loader().checkCompleted();
}
void Document::implicitClose()
{
ASSERT(!inStyleRecalc());
bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
bool doload = !parsing() && m_parser && !processingLoadEvent() && !wasLocationChangePending;
m_loadEventProgress = LoadEventTried;
if (!doload)
return;
RefPtrWillBeRawPtr<DOMWindow> protectedWindow(this->domWindow());
m_loadEventProgress = LoadEventInProgress;
ScriptableDocumentParser* parser = scriptableDocumentParser();
m_wellFormed = parser && parser->wellFormed();
detachParser();
if (frame() && frame()->script().canExecuteScripts(NotAboutToExecuteScript)) {
ImageLoader::dispatchPendingLoadEvents();
ImageLoader::dispatchPendingErrorEvents();
HTMLLinkElement::dispatchPendingLoadEvents();
HTMLStyleElement::dispatchPendingLoadEvents();
}
if (svgExtensions())
accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
if (protectedWindow)
protectedWindow->documentWasClosed();
if (frame()) {
frame()->loader().client()->dispatchDidHandleOnloadEvents();
loader()->applicationCacheHost()->stopDeferringEvents();
}
if (!frame()) {
m_loadEventProgress = LoadEventCompleted;
return;
}
if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
m_loadEventProgress = LoadEventCompleted;
return;
}
if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
updateRenderTreeIfNeeded();
if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
view()->layout();
}
m_loadEventProgress = LoadEventCompleted;
if (frame() && renderView() && AXObjectCache::accessibilityEnabled()) {
if (AXObjectCache* cache = axObjectCache()) {
cache->getOrCreate(renderView());
if (this == topDocument()) {
cache->postNotification(renderView(), AXObjectCache::AXLoadComplete, true);
} else {
cache->postNotification(renderView(), AXObjectCache::AXLayoutComplete, true);
}
}
}
if (svgExtensions())
accessSVGExtensions().startAnimations();
}
bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigation)
{
if (!m_domWindow)
return true;
if (!body())
return true;
RefPtr<Document> protect(this);
RefPtrWillBeRawPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
m_loadEventProgress = BeforeUnloadEventInProgress;
m_domWindow->dispatchEvent(beforeUnloadEvent.get(), this);
m_loadEventProgress = BeforeUnloadEventCompleted;
if (!beforeUnloadEvent->defaultPrevented())
defaultEventHandler(beforeUnloadEvent.get());
if (beforeUnloadEvent->returnValue().isNull())
return true;
if (didAllowNavigation) {
addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation.");
return true;
}
String text = beforeUnloadEvent->returnValue();
if (chrome.runBeforeUnloadConfirmPanel(text, m_frame)) {
didAllowNavigation = true;
return true;
}
return false;
}
void Document::dispatchUnloadEvents()
{
RefPtr<Document> protect(this);
if (m_parser)
m_parser->stopParsing();
if (m_loadEventProgress >= LoadEventTried && m_loadEventProgress <= UnloadEventInProgress) {
Element* currentFocusedElement = focusedElement();
if (isHTMLInputElement(currentFocusedElement))
toHTMLInputElement(*currentFocusedElement).endEditing();
if (m_loadEventProgress < PageHideInProgress) {
m_loadEventProgress = PageHideInProgress;
if (DOMWindow* window = domWindow())
window->dispatchEvent(PageTransitionEvent::create(EventTypeNames::pagehide, false), this);
if (!m_frame)
return;
RefPtr<DocumentLoader> documentLoader = m_frame->loader().provisionalDocumentLoader();
m_loadEventProgress = UnloadEventInProgress;
RefPtrWillBeRawPtr<Event> unloadEvent(Event::create(EventTypeNames::unload));
if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
DocumentLoadTiming* timing = documentLoader->timing();
ASSERT(timing->navigationStart());
timing->markUnloadEventStart();
m_frame->domWindow()->dispatchEvent(unloadEvent, this);
timing->markUnloadEventEnd();
} else {
m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
}
}
m_loadEventProgress = UnloadEventHandled;
}
if (!m_frame)
return;
bool keepEventListeners = m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader().provisionalDocumentLoader()
&& isSecureTransitionTo(m_frame->loader().provisionalDocumentLoader()->url());
if (!keepEventListeners)
removeAllEventListeners();
}
Document::PageDismissalType Document::pageDismissalEventBeingDispatched() const
{
if (m_loadEventProgress == BeforeUnloadEventInProgress)
return BeforeUnloadDismissal;
if (m_loadEventProgress == PageHideInProgress)
return PageHideDismissal;
if (m_loadEventProgress == UnloadEventInProgress)
return UnloadDismissal;
return NoDismissal;
}
void Document::setParsing(bool b)
{
m_isParsing = b;
if (m_isParsing && !m_elementDataCache)
m_elementDataCache = ElementDataCache::create();
}
bool Document::shouldScheduleLayout() const
{
return (haveStylesheetsAndImportsLoaded() && body())
|| (documentElement() && !isHTMLHtmlElement(*documentElement()));
}
bool Document::shouldParserYieldAgressivelyBeforeScriptExecution()
{
return view() && view()->layoutPending();
}
int Document::elapsedTime() const
{
return static_cast<int>((currentTime() - m_startTime) * 1000);
}
void Document::write(const SegmentedString& text, Document* ownerDocument)
{
NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
if (m_writeRecursionIsTooDeep)
return;
bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
if (!hasInsertionPoint && m_ignoreDestructiveWriteCount) {
addConsoleMessage(JSMessageSource, WarningMessageLevel, ExceptionMessages::failedToExecute("write", "Document", "It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened."));
return;
}
if (!hasInsertionPoint)
open(ownerDocument);
ASSERT(m_parser);
m_parser->insert(text);
}
void Document::write(const String& text, Document* ownerDocument)
{
write(SegmentedString(text), ownerDocument);
}
void Document::writeln(const String& text, Document* ownerDocument)
{
write(text, ownerDocument);
write("\n", ownerDocument);
}
const KURL& Document::virtualURL() const
{
return m_url;
}
KURL Document::virtualCompleteURL(const String& url) const
{
return completeURL(url);
}
double Document::timerAlignmentInterval() const
{
Page* p = page();
if (!p)
return DOMTimer::visiblePageAlignmentInterval();
return p->timerAlignmentInterval();
}
EventTarget* Document::errorEventTarget()
{
return domWindow();
}
void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
{
internalAddMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack, 0);
}
void Document::setURL(const KURL& url)
{
const KURL& newURL = url.isEmpty() ? blankURL() : url;
if (newURL == m_url)
return;
m_url = newURL;
updateBaseURL();
contextFeatures().urlDidChange(this);
}
void Document::updateBaseURL()
{
KURL oldBaseURL = m_baseURL;
if (!m_baseElementURL.isEmpty())
m_baseURL = m_baseElementURL;
else if (!m_baseURLOverride.isEmpty())
m_baseURL = m_baseURLOverride;
else
m_baseURL = m_url;
selectorQueryCache().invalidate();
if (!m_baseURL.isValid())
m_baseURL = KURL();
if (m_elemSheet) {
ASSERT(!m_elemSheet->contents()->ruleCount());
bool usesRemUnits = m_elemSheet->contents()->usesRemUnits();
m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
m_elemSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
}
if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
for (HTMLAnchorElement* anchor = Traversal<HTMLAnchorElement>::firstWithin(*this); anchor; anchor = Traversal<HTMLAnchorElement>::next(*anchor))
anchor->invalidateCachedVisitedLinkHash();
}
}
void Document::setBaseURLOverride(const KURL& url)
{
m_baseURLOverride = url;
updateBaseURL();
}
void Document::processBaseElement()
{
const AtomicString* href = 0;
const AtomicString* target = 0;
for (HTMLBaseElement* base = Traversal<HTMLBaseElement>::firstWithin(*this); base && (!href || !target); base = Traversal<HTMLBaseElement>::next(*base)) {
if (!href) {
const AtomicString& value = base->fastGetAttribute(hrefAttr);
if (!value.isNull())
href = &value;
}
if (!target) {
const AtomicString& value = base->fastGetAttribute(targetAttr);
if (!value.isNull())
target = &value;
}
if (contentSecurityPolicy()->isActive())
UseCounter::count(*this, UseCounter::ContentSecurityPolicyWithBaseElement);
}
KURL baseElementURL;
if (href) {
String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
if (!strippedHref.isEmpty())
baseElementURL = KURL(url(), strippedHref);
}
if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
m_baseElementURL = baseElementURL;
updateBaseURL();
}
m_baseTarget = target ? *target : nullAtom;
}
String Document::userAgent(const KURL& url) const
{
return frame() ? frame()->loader().userAgent(url) : String();
}
void Document::disableEval(const String& errorMessage)
{
if (!frame())
return;
frame()->script().disableEval(errorMessage);
}
bool Document::canNavigate(LocalFrame* targetFrame)
{
if (!m_frame)
return false;
if (!targetFrame)
return true;
if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
return true;
if (isSandboxed(SandboxNavigation)) {
if (targetFrame->tree().isDescendantOf(m_frame))
return true;
const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
if (isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
printNavigationErrorMessage(*targetFrame, url(), reason);
return false;
}
ASSERT(securityOrigin());
SecurityOrigin& origin = *securityOrigin();
if (canAccessAncestor(origin, targetFrame))
return true;
if (!targetFrame->tree().parent()) {
if (targetFrame == m_frame->loader().opener())
return true;
if (canAccessAncestor(origin, targetFrame->loader().opener()))
return true;
}
printNavigationErrorMessage(*targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
return false;
}
LocalFrame* Document::findUnsafeParentScrollPropagationBoundary()
{
LocalFrame* currentFrame = m_frame;
LocalFrame* ancestorFrame = currentFrame->tree().parent();
while (ancestorFrame) {
if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
return currentFrame;
currentFrame = ancestorFrame;
ancestorFrame = ancestorFrame->tree().parent();
}
return 0;
}
void Document::didLoadAllImports()
{
if (!haveStylesheetsLoaded())
return;
didLoadAllScriptBlockingResources();
}
void Document::didRemoveAllPendingStylesheet()
{
m_needsNotifyRemoveAllPendingStylesheet = false;
styleResolverChanged(RecalcStyleDeferred, hasNodesWithPlaceholderStyle() ? FullStyleUpdate : AnalyzedStyleUpdate);
if (m_import)
m_import->didRemoveAllPendingStylesheet();
if (!haveImportsLoaded())
return;
didLoadAllScriptBlockingResources();
}
void Document::didLoadAllScriptBlockingResources()
{
executeScriptsWaitingForResourcesIfNeeded();
if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
view()->scrollToFragment(m_url);
}
void Document::executeScriptsWaitingForResourcesIfNeeded()
{
if (!haveStylesheetsAndImportsLoaded())
return;
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->executeScriptsWaitingForResources();
}
CSSStyleSheet& Document::elementSheet()
{
if (!m_elemSheet)
m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
return *m_elemSheet;
}
void Document::processHttpEquiv(const AtomicString& equiv, const AtomicString& content, bool inDocumentHeadElement)
{
ASSERT(!equiv.isNull() && !content.isNull());
if (equalIgnoringCase(equiv, "default-style")) {
processHttpEquivDefaultStyle(content);
} else if (equalIgnoringCase(equiv, "refresh")) {
processHttpEquivRefresh(content);
} else if (equalIgnoringCase(equiv, "set-cookie")) {
processHttpEquivSetCookie(content);
} else if (equalIgnoringCase(equiv, "content-language")) {
setContentLanguage(content);
} else if (equalIgnoringCase(equiv, "x-dns-prefetch-control")) {
parseDNSPrefetchControlHeader(content);
} else if (equalIgnoringCase(equiv, "x-frame-options")) {
processHttpEquivXFrameOptions(content);
} else if (equalIgnoringCase(equiv, "content-security-policy") || equalIgnoringCase(equiv, "content-security-policy-report-only")) {
if (inDocumentHeadElement)
processHttpEquivContentSecurityPolicy(equiv, content);
else
contentSecurityPolicy()->reportMetaOutsideHead(content);
}
}
void Document::processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content)
{
if (import() && import()->isChild())
return;
if (equalIgnoringCase(equiv, "content-security-policy"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeEnforce, ContentSecurityPolicyHeaderSourceMeta);
else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeReport, ContentSecurityPolicyHeaderSourceMeta);
else
ASSERT_NOT_REACHED();
}
void Document::processHttpEquivDefaultStyle(const AtomicString& content)
{
m_styleEngine->setSelectedStylesheetSetName(content);
m_styleEngine->setPreferredStylesheetSetName(content);
styleResolverChanged(RecalcStyleDeferred);
}
void Document::processHttpEquivRefresh(const AtomicString& content)
{
maybeHandleHttpRefresh(content, HttpRefreshFromMetaTag);
}
void Document::maybeHandleHttpRefresh(const String& content, HttpRefreshType httpRefreshType)
{
if (m_isViewSource || !m_frame)
return;
double delay;
String refreshURL;
if (!parseHTTPRefresh(content, httpRefreshType == HttpRefreshFromMetaTag, delay, refreshURL))
return;
if (refreshURL.isEmpty())
refreshURL = url().string();
else
refreshURL = completeURL(refreshURL).string();
if (protocolIsJavaScript(refreshURL)) {
String message = "Refused to refresh " + m_url.elidedString() + " to a javascript: URL";
addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
return;
}
if (httpRefreshType == HttpRefreshFromMetaTag && isSandboxed(SandboxAutomaticFeatures)) {
String message = "Refused to execute the redirect specified via '<meta http-equiv='refresh' content='...'>'. The document is sandboxed, and the 'allow-scripts' keyword is not set.";
addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
return;
}
m_frame->navigationScheduler().scheduleRedirect(delay, refreshURL);
}
void Document::processHttpEquivSetCookie(const AtomicString& content)
{
if (!isHTMLDocument())
return;
toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
}
void Document::processHttpEquivXFrameOptions(const AtomicString& content)
{
LocalFrame* frame = this->frame();
if (!frame)
return;
FrameLoader& frameLoader = frame->loader();
unsigned long requestIdentifier = loader()->mainResourceIdentifier();
if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
String message = "Refused to display '" + url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
frameLoader.stopAllLoaders();
frame->navigationScheduler().scheduleLocationChange(this, SecurityOrigin::urlWithUniqueSecurityOrigin(), Referrer());
addConsoleMessageWithRequestIdentifier(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
}
}
bool Document::shouldMergeWithLegacyDescription(ViewportDescription::Type origin)
{
return settings() && settings()->viewportMetaMergeContentQuirk() && m_legacyViewportDescription.isMetaViewportType() && m_legacyViewportDescription.type == origin;
}
void Document::setViewportDescription(const ViewportDescription& viewportDescription)
{
if (!viewportDescription.isSpecifiedByAuthor())
m_viewportDefaultMinWidth = viewportDescription.minWidth;
if (viewportDescription.isLegacyViewportType()) {
if (settings() && !settings()->viewportMetaEnabled())
return;
m_legacyViewportDescription = viewportDescription;
if (m_viewportDescription.type == ViewportDescription::AuthorStyleSheet)
return;
m_viewportDescription = viewportDescription;
} else {
if (!shouldOverrideLegacyDescription(viewportDescription.type))
m_viewportDescription = m_legacyViewportDescription;
else
m_viewportDescription = viewportDescription;
}
updateViewportDescription();
}
void Document::updateViewportDescription()
{
if (frame() && frame()->isMainFrame()) {
#ifndef NDEBUG
m_didDispatchViewportPropertiesChanged = true;
#endif
frameHost()->chrome().dispatchViewportPropertiesDidChange(m_viewportDescription);
}
}
void Document::processReferrerPolicy(const String& policy)
{
ASSERT(!policy.isNull());
if (equalIgnoringCase(policy, "never")) {
setReferrerPolicy(ReferrerPolicyNever);
} else if (equalIgnoringCase(policy, "always")) {
setReferrerPolicy(ReferrerPolicyAlways);
} else if (equalIgnoringCase(policy, "origin")) {
setReferrerPolicy(ReferrerPolicyOrigin);
} else if (equalIgnoringCase(policy, "default")) {
setReferrerPolicy(ReferrerPolicyDefault);
} else {
addConsoleMessage(RenderingMessageSource, ErrorMessageLevel, "Failed to set referrer policy: The value '" + policy + "' is not one of 'always', 'default', 'never', or 'origin'. Defaulting to 'never'.");
setReferrerPolicy(ReferrerPolicyNever);
}
}
void Document::setReferrerPolicy(ReferrerPolicy referrerPolicy)
{
if (m_didSetReferrerPolicy)
UseCounter::count(this, UseCounter::ResetReferrerPolicy);
m_didSetReferrerPolicy = true;
m_referrerPolicy = referrerPolicy;
}
String Document::outgoingReferrer()
{
Document* referrerDocument = this;
if (LocalFrame* frame = m_frame) {
while (frame->document()->isSrcdocDocument()) {
frame = frame->tree().parent();
ASSERT(frame);
}
referrerDocument = frame->document();
}
return referrerDocument->m_url.strippedForUseAsReferrer();
}
String Document::outgoingOrigin() const
{
return securityOrigin()->toString();
}
MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
{
ASSERT(!renderView() || renderView()->isRenderView());
if (!renderView() || !view() || !view()->didFirstLayout())
return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
HitTestResult result(documentPoint);
renderView()->hitTest(request, result);
if (!request.readOnly())
updateHoverActiveState(request, result.innerElement(), &event);
return MouseEventWithHitTestResults(event, result);
}
bool Document::childTypeAllowed(NodeType type) const
{
switch (type) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE:
case TEXT_NODE:
return false;
case COMMENT_NODE:
case PROCESSING_INSTRUCTION_NODE:
return true;
case DOCUMENT_TYPE_NODE:
case ELEMENT_NODE:
for (Node* c = firstChild(); c; c = c->nextSibling())
if (c->nodeType() == type)
return false;
return true;
}
return false;
}
bool Document::canReplaceChild(const Node& newChild, const Node& oldChild) const
{
if (oldChild.nodeType() == newChild.nodeType())
return true;
int numDoctypes = 0;
int numElements = 0;
for (Node* c = firstChild(); c; c = c->nextSibling()) {
if (c == oldChild)
continue;
switch (c->nodeType()) {
case DOCUMENT_TYPE_NODE:
numDoctypes++;
break;
case ELEMENT_NODE:
numElements++;
break;
default:
break;
}
}
if (newChild.nodeType() == DOCUMENT_FRAGMENT_NODE) {
for (Node* c = newChild.firstChild(); c; c = c->nextSibling()) {
switch (c->nodeType()) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE:
case TEXT_NODE:
return false;
case COMMENT_NODE:
case PROCESSING_INSTRUCTION_NODE:
break;
case DOCUMENT_TYPE_NODE:
numDoctypes++;
break;
case ELEMENT_NODE:
numElements++;
break;
}
}
} else {
switch (newChild.nodeType()) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE:
case TEXT_NODE:
return false;
case COMMENT_NODE:
case PROCESSING_INSTRUCTION_NODE:
return true;
case DOCUMENT_TYPE_NODE:
numDoctypes++;
break;
case ELEMENT_NODE:
numElements++;
break;
}
}
if (numElements > 1 || numDoctypes > 1)
return false;
return true;
}
PassRefPtr<Node> Document::cloneNode(bool deep)
{
RefPtr<Document> clone = cloneDocumentWithoutChildren();
clone->cloneDataFromDocument(*this);
if (deep)
cloneChildNodes(clone.get());
return clone.release();
}
PassRefPtr<Document> Document::cloneDocumentWithoutChildren()
{
DocumentInit init(url());
if (isXMLDocument()) {
if (isXHTMLDocument())
return XMLDocument::createXHTML(init.withRegistrationContext(registrationContext()));
return XMLDocument::create(init);
}
return create(init);
}
void Document::cloneDataFromDocument(const Document& other)
{
setCompatibilityMode(other.compatibilityMode());
setEncodingData(other.m_encodingData);
setContextFeatures(other.contextFeatures());
setSecurityOrigin(other.securityOrigin()->isolatedCopy());
setMimeType(other.contentType());
}
StyleSheetList* Document::styleSheets()
{
if (!m_styleSheetList)
m_styleSheetList = StyleSheetList::create(this);
return m_styleSheetList.get();
}
String Document::preferredStylesheetSet() const
{
return m_styleEngine->preferredStylesheetSetName();
}
String Document::selectedStylesheetSet() const
{
return m_styleEngine->selectedStylesheetSetName();
}
void Document::setSelectedStylesheetSet(const String& aString)
{
m_styleEngine->setSelectedStylesheetSetName(aString);
styleResolverChanged(RecalcStyleDeferred);
}
void Document::evaluateMediaQueryListIfNeeded()
{
if (!m_evaluateMediaQueriesOnStyleRecalc)
return;
evaluateMediaQueryList();
m_evaluateMediaQueriesOnStyleRecalc = false;
}
void Document::evaluateMediaQueryList()
{
if (m_mediaQueryMatcher)
m_mediaQueryMatcher->styleResolverChanged();
}
void Document::notifyResizeForViewportUnits()
{
if (!hasViewportUnits())
return;
ensureStyleResolver().notifyResizeForViewportUnits();
setNeedsStyleRecalcForViewportUnits();
}
void Document::styleResolverChanged(RecalcStyleTime updateTime, StyleResolverUpdateMode updateMode)
{
if (!m_styleEngine)
return;
StyleResolverChange change = m_styleEngine->resolverChanged(updateTime, updateMode);
if (change.needsRepaint()) {
m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
renderView()->repaintViewAndCompositedLayers();
}
if (!change.needsStyleRecalc())
return;
m_evaluateMediaQueriesOnStyleRecalc = true;
setNeedsStyleRecalc(SubtreeStyleChange);
if (updateTime == RecalcStyleImmediately)
updateRenderTreeIfNeeded();
}
void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
{
m_hoverNode = newHoverNode;
}
void Document::setActiveHoverElement(PassRefPtr<Element> newActiveElement)
{
if (!newActiveElement) {
m_activeHoverElement.clear();
return;
}
m_activeHoverElement = newActiveElement;
}
void Document::removeFocusedElementOfSubtree(Node* node, bool amongChildrenOnly)
{
if (!m_focusedElement)
return;
if (!node->inDocument())
return;
bool contains = node->containsIncludingShadowDOM(m_focusedElement.get());
if (contains && (m_focusedElement != node || !amongChildrenOnly))
setFocusedElement(nullptr);
}
void Document::hoveredNodeDetached(Node* node)
{
if (!m_hoverNode)
return;
if (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != NodeRenderingTraversal::parent(m_hoverNode.get())))
return;
m_hoverNode = NodeRenderingTraversal::parent(node);
while (m_hoverNode && !m_hoverNode->renderer())
m_hoverNode = NodeRenderingTraversal::parent(m_hoverNode.get());
if (!page()->isCursorVisible())
return;
if (frame())
frame()->eventHandler().scheduleHoverStateUpdate();
}
void Document::activeChainNodeDetached(Node* node)
{
if (!m_activeHoverElement)
return;
if (node != m_activeHoverElement && (!m_activeHoverElement->isTextNode() || node != NodeRenderingTraversal::parent(m_activeHoverElement.get())))
return;
Node* activeNode = NodeRenderingTraversal::parent(node);
while (activeNode && activeNode->isElementNode() && !activeNode->renderer())
activeNode = NodeRenderingTraversal::parent(activeNode);
m_activeHoverElement = activeNode && activeNode->isElementNode() ? toElement(activeNode) : 0;
}
const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
{
return m_annotatedRegions;
}
void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
{
m_annotatedRegions = regions;
setAnnotatedRegionsDirty(false);
}
bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusType type)
{
m_clearFocusedElementTimer.stop();
RefPtr<Element> newFocusedElement = prpNewFocusedElement;
if (newFocusedElement && (newFocusedElement->document() != this))
return true;
if (NodeChildRemovalTracker::isBeingRemoved(newFocusedElement.get()))
return true;
if (m_focusedElement == newFocusedElement)
return true;
bool focusChangeBlocked = false;
RefPtr<Element> oldFocusedElement = m_focusedElement;
m_focusedElement = nullptr;
if (oldFocusedElement) {
ASSERT(!oldFocusedElement->inDetach());
if (oldFocusedElement->active())
oldFocusedElement->setActive(false);
oldFocusedElement->setFocus(false);
if (page() && (page()->focusController().isFocused())) {
oldFocusedElement->dispatchBlurEvent(newFocusedElement.get());
if (m_focusedElement) {
focusChangeBlocked = true;
newFocusedElement = nullptr;
}
oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::focusout, newFocusedElement.get());
oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, newFocusedElement.get());
if (m_focusedElement) {
focusChangeBlocked = true;
newFocusedElement = nullptr;
}
}
if (view()) {
Widget* oldWidget = widgetForElement(*oldFocusedElement);
if (oldWidget)
oldWidget->setFocus(false);
else
view()->setFocus(false);
}
}
if (newFocusedElement && newFocusedElement->isFocusable()) {
if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(*newFocusedElement)) {
focusChangeBlocked = true;
goto SetFocusedElementDone;
}
m_focusedElement = newFocusedElement;
if (page() && (page()->focusController().isFocused())) {
m_focusedElement->dispatchFocusEvent(oldFocusedElement.get(), type);
if (m_focusedElement != newFocusedElement) {
focusChangeBlocked = true;
goto SetFocusedElementDone;
}
m_focusedElement->dispatchFocusInEvent(EventTypeNames::focusin, oldFocusedElement.get());
if (m_focusedElement != newFocusedElement) {
focusChangeBlocked = true;
goto SetFocusedElementDone;
}
m_focusedElement->dispatchFocusInEvent(EventTypeNames::DOMFocusIn, oldFocusedElement.get());
if (m_focusedElement != newFocusedElement) {
focusChangeBlocked = true;
goto SetFocusedElementDone;
}
}
m_focusedElement->setFocus(true);
if (m_focusedElement->isRootEditableElement())
frame()->spellChecker().didBeginEditing(m_focusedElement.get());
if (view()) {
Widget* focusWidget = widgetForElement(*m_focusedElement);
if (focusWidget) {
updateLayout();
focusWidget = widgetForElement(*m_focusedElement);
}
if (focusWidget)
focusWidget->setFocus(true);
else
view()->setFocus(true);
}
}
if (!focusChangeBlocked && m_focusedElement) {
if (AXObjectCache* cache = axObjectCache())
cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
}
if (!focusChangeBlocked && frameHost())
frameHost()->chrome().focusedNodeChanged(m_focusedElement.get());
SetFocusedElementDone:
updateRenderTreeIfNeeded();
if (LocalFrame* frame = this->frame())
frame->selection().didChangeFocus();
return !focusChangeBlocked;
}
void Document::setCSSTarget(Element* n)
{
if (m_cssTarget)
m_cssTarget->didAffectSelector(AffectedSelectorTarget);
m_cssTarget = n;
if (n)
n->didAffectSelector(AffectedSelectorTarget);
}
void Document::registerNodeList(LiveNodeListBase* list)
{
m_nodeListCounts[list->invalidationType()]++;
if (list->isRootedAtDocument())
m_listsInvalidatedAtDocument.add(list);
}
void Document::unregisterNodeList(LiveNodeListBase* list)
{
m_nodeListCounts[list->invalidationType()]--;
if (list->isRootedAtDocument()) {
ASSERT(m_listsInvalidatedAtDocument.contains(list));
m_listsInvalidatedAtDocument.remove(list);
}
}
void Document::attachNodeIterator(NodeIterator* ni)
{
m_nodeIterators.add(ni);
}
void Document::detachNodeIterator(NodeIterator* ni)
{
m_nodeIterators.remove(ni);
}
void Document::moveNodeIteratorsToNewDocument(Node& node, Document& newDocument)
{
HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
if ((*it)->root() == node) {
detachNodeIterator(*it);
newDocument.attachNodeIterator(*it);
}
}
}
void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
{
if (!m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->nodeChildrenChanged(container);
}
}
void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
{
NoEventDispatchAssertion assertNoEventDispatch;
if (!m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->nodeChildrenWillBeRemoved(container);
}
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
for (Node* n = container.firstChild(); n; n = n->nextSibling())
(*it)->nodeWillBeRemoved(*n);
}
if (LocalFrame* frame = this->frame()) {
for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
frame->eventHandler().nodeWillBeRemoved(*n);
frame->selection().nodeWillBeRemoved(*n);
frame->page()->dragCaretController().nodeWillBeRemoved(*n);
}
}
}
void Document::nodeWillBeRemoved(Node& n)
{
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
(*it)->nodeWillBeRemoved(n);
if (!m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
(*it)->nodeWillBeRemoved(n);
}
if (LocalFrame* frame = this->frame()) {
frame->eventHandler().nodeWillBeRemoved(n);
frame->selection().nodeWillBeRemoved(n);
frame->page()->dragCaretController().nodeWillBeRemoved(n);
}
}
void Document::didInsertText(Node* text, unsigned offset, unsigned length)
{
if (!m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->didInsertText(text, offset, length);
}
m_markers->shiftMarkers(text, offset, length);
}
void Document::didRemoveText(Node* text, unsigned offset, unsigned length)
{
if (!m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->didRemoveText(text, offset, length);
}
m_markers->removeMarkers(text, offset, length);
m_markers->shiftMarkers(text, offset + length, 0 - length);
}
void Document::didMergeTextNodes(Text& oldNode, unsigned offset)
{
if (!m_ranges.isEmpty()) {
NodeWithIndex oldNodeWithIndex(oldNode);
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->didMergeTextNodes(oldNodeWithIndex, offset);
}
if (m_frame)
m_frame->selection().didMergeTextNodes(oldNode, offset);
}
void Document::didSplitTextNode(Text& oldNode)
{
if (!m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->didSplitTextNode(oldNode);
}
if (m_frame)
m_frame->selection().didSplitTextNode(oldNode);
}
void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
{
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return;
domWindow->setAttributeEventListener(eventType, listener);
}
EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
{
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return 0;
return domWindow->getAttributeEventListener(eventType);
}
EventQueue* Document::eventQueue() const
{
if (!m_domWindow)
return 0;
return m_domWindow->eventQueue();
}
void Document::enqueueAnimationFrameEvent(PassRefPtrWillBeRawPtr<Event> event)
{
ensureScriptedAnimationController().enqueueEvent(event);
}
void Document::enqueueScrollEventForNode(Node* target)
{
RefPtrWillBeRawPtr<Event> scrollEvent = target->isDocumentNode() ? Event::createBubble(EventTypeNames::scroll) : Event::create(EventTypeNames::scroll);
scrollEvent->setTarget(target);
ensureScriptedAnimationController().enqueuePerFrameEvent(scrollEvent.release());
}
void Document::enqueueResizeEvent()
{
RefPtrWillBeRawPtr<Event> event = Event::create(EventTypeNames::resize);
event->setTarget(domWindow());
ensureScriptedAnimationController().enqueuePerFrameEvent(event.release());
}
PassRefPtrWillBeRawPtr<Event> Document::createEvent(const String& eventType, ExceptionState& exceptionState)
{
RefPtrWillBeRawPtr<Event> event = EventFactory::create(eventType);
if (event)
return event.release();
exceptionState.throwDOMException(NotSupportedError, "The provided event type ('" + eventType + "') is invalid.");
return nullptr;
}
PassRefPtrWillBeRawPtr<Event> Document::createEvent(ExceptionState& exceptionState)
{
if (!isSVGDocument()) {
exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(1, 0));
return nullptr;
}
UseCounter::count(this, UseCounter::DocumentCreateEventOptionalArgument);
return createEvent("undefined", exceptionState);
}
void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
{
if (ContextFeatures::mutationEventsEnabled(this))
addListenerType(listenerType);
}
void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
{
if (eventType == EventTypeNames::DOMSubtreeModified) {
UseCounter::count(*this, UseCounter::DOMSubtreeModifiedEvent);
addMutationEventListenerTypeIfEnabled(DOMSUBTREEMODIFIED_LISTENER);
} else if (eventType == EventTypeNames::DOMNodeInserted) {
UseCounter::count(*this, UseCounter::DOMNodeInsertedEvent);
addMutationEventListenerTypeIfEnabled(DOMNODEINSERTED_LISTENER);
} else if (eventType == EventTypeNames::DOMNodeRemoved) {
UseCounter::count(*this, UseCounter::DOMNodeRemovedEvent);
addMutationEventListenerTypeIfEnabled(DOMNODEREMOVED_LISTENER);
} else if (eventType == EventTypeNames::DOMNodeRemovedFromDocument) {
UseCounter::count(*this, UseCounter::DOMNodeRemovedFromDocumentEvent);
addMutationEventListenerTypeIfEnabled(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
} else if (eventType == EventTypeNames::DOMNodeInsertedIntoDocument) {
UseCounter::count(*this, UseCounter::DOMNodeInsertedIntoDocumentEvent);
addMutationEventListenerTypeIfEnabled(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
} else if (eventType == EventTypeNames::DOMCharacterDataModified) {
UseCounter::count(*this, UseCounter::DOMCharacterDataModifiedEvent);
addMutationEventListenerTypeIfEnabled(DOMCHARACTERDATAMODIFIED_LISTENER);
} else if (eventType == EventTypeNames::overflowchanged) {
UseCounter::count(*this, UseCounter::OverflowChangedEvent);
addListenerType(OVERFLOWCHANGED_LISTENER);
} else if (eventType == EventTypeNames::webkitAnimationStart || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationstart)) {
addListenerType(ANIMATIONSTART_LISTENER);
} else if (eventType == EventTypeNames::webkitAnimationEnd || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationend)) {
addListenerType(ANIMATIONEND_LISTENER);
} else if (eventType == EventTypeNames::webkitAnimationIteration || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationiteration)) {
addListenerType(ANIMATIONITERATION_LISTENER);
} else if (eventType == EventTypeNames::webkitTransitionEnd || eventType == EventTypeNames::transitionend) {
addListenerType(TRANSITIONEND_LISTENER);
} else if (eventType == EventTypeNames::scroll) {
addListenerType(SCROLL_LISTENER);
} else if (eventType == EventTypeNames::DOMFocusIn || eventType == EventTypeNames::DOMFocusOut) {
UseCounter::count(*this, UseCounter::DOMFocusInOutEvent);
}
}
CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
{
return 0;
}
HTMLFrameOwnerElement* Document::ownerElement() const
{
if (!frame())
return 0;
return frame()->ownerElement();
}
String Document::cookie(ExceptionState& exceptionState) const
{
if (settings() && !settings()->cookieEnabled())
return String();
if (!securityOrigin()->canAccessCookies()) {
if (isSandboxed(SandboxOrigin))
exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
else if (url().protocolIs("data"))
exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
else
exceptionState.throwSecurityError("Access is denied for this document.");
return String();
}
KURL cookieURL = this->cookieURL();
if (cookieURL.isEmpty())
return String();
return cookies(this, cookieURL);
}
void Document::setCookie(const String& value, ExceptionState& exceptionState)
{
if (settings() && !settings()->cookieEnabled())
return;
if (!securityOrigin()->canAccessCookies()) {
if (isSandboxed(SandboxOrigin))
exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
else if (url().protocolIs("data"))
exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
else
exceptionState.throwSecurityError("Access is denied for this document.");
return;
}
KURL cookieURL = this->cookieURL();
if (cookieURL.isEmpty())
return;
setCookies(this, cookieURL, value);
}
const AtomicString& Document::referrer() const
{
if (loader())
return loader()->request().httpReferrer();
return nullAtom;
}
String Document::domain() const
{
return securityOrigin()->domain();
}
void Document::setDomain(const String& newDomain, ExceptionState& exceptionState)
{
if (isSandboxed(SandboxDocumentDomain)) {
exceptionState.throwSecurityError("Assignment is forbidden for sandboxed iframes.");
return;
}
if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
exceptionState.throwSecurityError("Assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme.");
return;
}
if (newDomain.isEmpty()) {
exceptionState.throwSecurityError("'" + newDomain + "' is an empty domain.");
return;
}
OriginAccessEntry::IPAddressSetting ipAddressSetting = settings() && settings()->treatIPAddressAsDomain() ? OriginAccessEntry::TreatIPAddressAsDomain : OriginAccessEntry::TreatIPAddressAsIPAddress;
OriginAccessEntry accessEntry(securityOrigin()->protocol(), newDomain, OriginAccessEntry::AllowSubdomains, ipAddressSetting);
OriginAccessEntry::MatchResult result = accessEntry.matchesOrigin(*securityOrigin());
if (result == OriginAccessEntry::DoesNotMatchOrigin) {
exceptionState.throwSecurityError("'" + newDomain + "' is not a suffix of '" + domain() + "'.");
return;
}
if (result == OriginAccessEntry::MatchesOriginButIsPublicSuffix) {
exceptionState.throwSecurityError("'" + newDomain + "' is a top-level domain.");
return;
}
securityOrigin()->setDomainFromDOM(newDomain);
if (m_frame)
m_frame->script().updateSecurityOrigin(securityOrigin());
}
String Document::lastModified() const
{
DateComponents date;
bool foundDate = false;
if (m_frame) {
if (DocumentLoader* documentLoader = loader()) {
const AtomicString& httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
if (!httpLastModified.isEmpty()) {
date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
foundDate = true;
}
}
}
if (!foundDate)
date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
}
const KURL& Document::firstPartyForCookies() const
{
return topDocument().url();
}
static bool isValidNameNonASCII(const LChar* characters, unsigned length)
{
if (!isValidNameStart(characters[0]))
return false;
for (unsigned i = 1; i < length; ++i) {
if (!isValidNamePart(characters[i]))
return false;
}
return true;
}
static bool isValidNameNonASCII(const UChar* characters, unsigned length)
{
unsigned i = 0;
UChar32 c;
U16_NEXT(characters, i, length, c)
if (!isValidNameStart(c))
return false;
while (i < length) {
U16_NEXT(characters, i, length, c)
if (!isValidNamePart(c))
return false;
}
return true;
}
template<typename CharType>
static inline bool isValidNameASCII(const CharType* characters, unsigned length)
{
CharType c = characters[0];
if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
return false;
for (unsigned i = 1; i < length; ++i) {
c = characters[i];
if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
return false;
}
return true;
}
bool Document::isValidName(const String& name)
{
unsigned length = name.length();
if (!length)
return false;
if (name.is8Bit()) {
const LChar* characters = name.characters8();
if (isValidNameASCII(characters, length))
return true;
return isValidNameNonASCII(characters, length);
}
const UChar* characters = name.characters16();
if (isValidNameASCII(characters, length))
return true;
return isValidNameNonASCII(characters, length);
}
template<typename CharType>
static bool parseQualifiedNameInternal(const AtomicString& qualifiedName, const CharType* characters, unsigned length, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
{
bool nameStart = true;
bool sawColon = false;
int colonPos = 0;
for (unsigned i = 0; i < length;) {
UChar32 c;
U16_NEXT(characters, i, length, c)
if (c == ':') {
if (sawColon) {
exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') contains multiple colons.");
return false;
}
nameStart = true;
sawColon = true;
colonPos = i - 1;
} else if (nameStart) {
if (!isValidNameStart(c)) {
StringBuilder message;
message.appendLiteral("The qualified name provided ('");
message.append(qualifiedName);
message.appendLiteral("') contains the invalid name-start character '");
message.append(c);
message.appendLiteral("'.");
exceptionState.throwDOMException(InvalidCharacterError, message.toString());
return false;
}
nameStart = false;
} else {
if (!isValidNamePart(c)) {
StringBuilder message;
message.appendLiteral("The qualified name provided ('");
message.append(qualifiedName);
message.appendLiteral("') contains the invalid character '");
message.append(c);
message.appendLiteral("'.");
exceptionState.throwDOMException(InvalidCharacterError, message.toString());
return false;
}
}
}
if (!sawColon) {
prefix = nullAtom;
localName = qualifiedName;
} else {
prefix = AtomicString(characters, colonPos);
if (prefix.isEmpty()) {
exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty namespace prefix.");
return false;
}
int prefixStart = colonPos + 1;
localName = AtomicString(characters + prefixStart, length - prefixStart);
}
if (localName.isEmpty()) {
exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty local name.");
return false;
}
return true;
}
bool Document::parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
{
unsigned length = qualifiedName.length();
if (!length) {
exceptionState.throwDOMException(InvalidCharacterError, "The qualified name provided is empty.");
return false;
}
if (qualifiedName.is8Bit())
return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName, exceptionState);
return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName, exceptionState);
}
void Document::setEncodingData(const DocumentEncodingData& newData)
{
if (m_titleElement
&& encoding() != newData.encoding()
&& !ElementTraversal::firstWithin(*m_titleElement)
&& encoding() == Latin1Encoding()
&& m_titleElement->textContent().containsOnlyLatin1()) {
CString originalBytes = m_titleElement->textContent().latin1();
OwnPtr<TextCodec> codec = newTextCodec(newData.encoding());
String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), DataEOF);
m_titleElement->setTextContent(correctlyDecodedTitle);
}
m_encodingData = newData;
bool shouldUseVisualOrdering = m_encodingData.encoding().usesVisualOrdering();
if (shouldUseVisualOrdering != m_visuallyOrdered) {
m_visuallyOrdered = shouldUseVisualOrdering;
if (renderView())
renderView()->style()->setRTLOrdering(m_visuallyOrdered ? VisualOrder : LogicalOrder);
setNeedsStyleRecalc(SubtreeStyleChange);
}
}
KURL Document::completeURL(const String& url) const
{
return completeURLWithOverride(url, m_baseURL);
}
KURL Document::completeURLWithOverride(const String& url, const KURL& baseURLOverride) const
{
if (url.isNull())
return KURL();
const KURL* baseURLFromParent = 0;
bool shouldUseParentBaseURL = baseURLOverride.isEmpty();
if (!shouldUseParentBaseURL) {
const KURL& aboutBlankURL = blankURL();
shouldUseParentBaseURL = (baseURLOverride == aboutBlankURL);
}
if (shouldUseParentBaseURL) {
if (Document* parent = parentDocument())
baseURLFromParent = &parent->baseURL();
}
const KURL& baseURL = baseURLFromParent ? *baseURLFromParent : baseURLOverride;
if (!encoding().isValid())
return KURL(baseURL, url);
return KURL(baseURL, url, encoding());
}
static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
{
LocalFrame* frame = document->frame();
if (!frame || frame->document() != document)
return Editor::Command();
document->updateRenderTreeIfNeeded();
return frame->editor().command(commandName, userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
}
bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
{
static bool inExecCommand = false;
if (inExecCommand) {
String message = "We don't execute document.execCommand() this time, because it is called recursively.";
addConsoleMessage(JSMessageSource, WarningMessageLevel, message);
return false;
}
TemporaryChange<bool> executeScope(inExecCommand, true);
EventQueueScope eventQueueScope;
return command(this, commandName, userInterface).execute(value);
}
bool Document::queryCommandEnabled(const String& commandName)
{
return command(this, commandName).isEnabled();
}
bool Document::queryCommandIndeterm(const String& commandName)
{
return command(this, commandName).state() == MixedTriState;
}
bool Document::queryCommandState(const String& commandName)
{
return command(this, commandName).state() == TrueTriState;
}
bool Document::queryCommandSupported(const String& commandName)
{
return command(this, commandName).isSupported();
}
String Document::queryCommandValue(const String& commandName)
{
return command(this, commandName).value();
}
KURL Document::openSearchDescriptionURL()
{
static const char openSearchMIMEType[] = "application/opensearchdescription+xml";
static const char openSearchRelation[] = "search";
if (!frame() || frame()->tree().parent())
return KURL();
if (frame()->loader().state() != FrameStateComplete)
return KURL();
if (!head())
return KURL();
for (HTMLLinkElement* linkElement = Traversal<HTMLLinkElement>::firstChild(*head()); linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
continue;
if (linkElement->href().isEmpty())
continue;
return linkElement->href();
}
return KURL();
}
void Document::pushCurrentScript(PassRefPtr<HTMLScriptElement> newCurrentScript)
{
ASSERT(newCurrentScript);
m_currentScriptStack.append(newCurrentScript);
}
void Document::popCurrentScript()
{
ASSERT(!m_currentScriptStack.isEmpty());
m_currentScriptStack.removeLast();
}
void Document::applyXSLTransform(ProcessingInstruction* pi)
{
ASSERT(!pi->isLoading());
UseCounter::count(*this, UseCounter::XSLProcessingInstruction);
RefPtrWillBeRawPtr<XSLTProcessor> processor = XSLTProcessor::create();
processor->setXSLStyleSheet(toXSLStyleSheet(pi->sheet()));
String resultMIMEType;
String newSource;
String resultEncoding;
if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
return;
LocalFrame* ownerFrame = frame();
processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, ownerFrame);
InspectorInstrumentation::frameDocumentUpdated(ownerFrame);
}
void Document::setTransformSource(PassOwnPtr<TransformSource> source)
{
m_transformSource = source;
}
void Document::setDesignMode(InheritedBool value)
{
m_designMode = value;
for (LocalFrame* frame = m_frame; frame && frame->document(); frame = frame->tree().traverseNext(m_frame))
frame->document()->setNeedsStyleRecalc(SubtreeStyleChange);
}
Document::InheritedBool Document::getDesignMode() const
{
return m_designMode;
}
bool Document::inDesignMode() const
{
for (const Document* d = this; d; d = d->parentDocument()) {
if (d->m_designMode != inherit)
return d->m_designMode;
}
return false;
}
Document* Document::parentDocument() const
{
if (!m_frame)
return 0;
LocalFrame* parent = m_frame->tree().parent();
if (!parent)
return 0;
return parent->document();
}
Document& Document::topDocument() const
{
Document* doc = const_cast<Document*>(this);
Element* element;
while ((element = doc->ownerElement()))
doc = &element->document();
ASSERT(doc);
return *doc;
}
WeakPtr<Document> Document::contextDocument()
{
if (m_contextDocument)
return m_contextDocument;
if (m_frame)
return m_weakFactory.createWeakPtr();
return WeakPtr<Document>(nullptr);
}
PassRefPtr<Attr> Document::createAttribute(const AtomicString& name, ExceptionState& exceptionState)
{
AtomicString prefix, localName;
if (!parseQualifiedName(name, prefix, localName, exceptionState))
return nullptr;
QualifiedName qName(prefix, localName, nullAtom);
return Attr::create(*this, qName, emptyAtom);
}
const SVGDocumentExtensions* Document::svgExtensions()
{
return m_svgExtensions.get();
}
SVGDocumentExtensions& Document::accessSVGExtensions()
{
if (!m_svgExtensions)
m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this));
return *m_svgExtensions;
}
bool Document::hasSVGRootNode() const
{
return isSVGSVGElement(documentElement());
}
PassRefPtr<HTMLCollection> Document::ensureCachedCollection(CollectionType type)
{
return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(*this, type);
}
PassRefPtr<HTMLCollection> Document::images()
{
return ensureCachedCollection(DocImages);
}
PassRefPtr<HTMLCollection> Document::applets()
{
return ensureCachedCollection(DocApplets);
}
PassRefPtr<HTMLCollection> Document::embeds()
{
return ensureCachedCollection(DocEmbeds);
}
PassRefPtr<HTMLCollection> Document::scripts()
{
return ensureCachedCollection(DocScripts);
}
PassRefPtr<HTMLCollection> Document::links()
{
return ensureCachedCollection(DocLinks);
}
PassRefPtr<HTMLCollection> Document::forms()
{
return ensureCachedCollection(DocForms);
}
PassRefPtr<HTMLCollection> Document::anchors()
{
return ensureCachedCollection(DocAnchors);
}
PassRefPtr<HTMLCollection> Document::allForBinding()
{
UseCounter::count(*this, UseCounter::DocumentAll);
return all();
}
PassRefPtr<HTMLCollection> Document::all()
{
return ensureRareData().ensureNodeLists().addCache<HTMLAllCollection>(*this, DocAll);
}
PassRefPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
{
return ensureRareData().ensureNodeLists().addCache<HTMLNameCollection>(*this, WindowNamedItems, name);
}
PassRefPtr<HTMLCollection> Document::documentNamedItems(const AtomicString& name)
{
return ensureRareData().ensureNodeLists().addCache<HTMLNameCollection>(*this, DocumentNamedItems, name);
}
void Document::finishedParsing()
{
ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
setParsing(false);
if (!m_documentTiming.domContentLoadedEventStart)
m_documentTiming.domContentLoadedEventStart = monotonicallyIncreasingTime();
dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
if (!m_documentTiming.domContentLoadedEventEnd)
m_documentTiming.domContentLoadedEventEnd = monotonicallyIncreasingTime();
if (frame() && frame()->isMainFrame()) {
if (TextAutosizer* textAutosizer = this->textAutosizer())
textAutosizer->recalculateMultipliers();
}
RefPtr<Document> protect(this);
if (RefPtr<LocalFrame> f = frame()) {
const bool mainResourceWasAlreadyRequested =
m_frame->loader().stateMachine()->startedFirstRealLoad();
if (mainResourceWasAlreadyRequested)
updateRenderTreeIfNeeded();
f->loader().finishedParsing();
InspectorInstrumentation::domContentLoadedEventFired(f.get());
}
m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
m_fetcher->clearPreloads();
if (m_import)
m_import->didFinishParsing();
}
void Document::elementDataCacheClearTimerFired(Timer<Document>*)
{
m_elementDataCache.clear();
}
Vector<IconURL> Document::iconURLs(int iconTypesMask)
{
IconURL firstFavicon;
IconURL firstTouchIcon;
IconURL firstTouchPrecomposedIcon;
Vector<IconURL> secondaryIcons;
for (HTMLLinkElement* linkElement = head() ? Traversal<HTMLLinkElement>::firstChild(*head()) : 0; linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
if (!(linkElement->iconType() & iconTypesMask))
continue;
if (linkElement->href().isEmpty())
continue;
if (!RuntimeEnabledFeatures::touchIconLoadingEnabled() && linkElement->iconType() != Favicon)
continue;
IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
if (linkElement->iconType() == Favicon) {
if (firstFavicon.m_iconType != InvalidIcon)
secondaryIcons.append(firstFavicon);
firstFavicon = newURL;
} else if (linkElement->iconType() == TouchIcon) {
if (firstTouchIcon.m_iconType != InvalidIcon)
secondaryIcons.append(firstTouchIcon);
firstTouchIcon = newURL;
} else if (linkElement->iconType() == TouchPrecomposedIcon) {
if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
secondaryIcons.append(firstTouchPrecomposedIcon);
firstTouchPrecomposedIcon = newURL;
} else {
ASSERT_NOT_REACHED();
}
}
Vector<IconURL> iconURLs;
if (firstFavicon.m_iconType != InvalidIcon)
iconURLs.append(firstFavicon);
else if (m_url.protocolIsInHTTPFamily() && iconTypesMask & Favicon)
iconURLs.append(IconURL::defaultFavicon(m_url));
if (firstTouchIcon.m_iconType != InvalidIcon)
iconURLs.append(firstTouchIcon);
if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
iconURLs.append(firstTouchPrecomposedIcon);
for (int i = secondaryIcons.size() - 1; i >= 0; --i)
iconURLs.append(secondaryIcons[i]);
return iconURLs;
}
void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
{
if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
return;
m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
m_frame->selection().updateSecureKeyboardEntryIfActive();
}
bool Document::useSecureKeyboardEntryWhenActive() const
{
return m_useSecureKeyboardEntryWhenActive;
}
void Document::initSecurityContext()
{
initSecurityContext(DocumentInit(m_url, m_frame, contextDocument(), m_import));
}
static PassRefPtr<ContentSecurityPolicy> contentSecurityPolicyFor(Document* document)
{
if (document->import() && document->import()->isChild())
return document->import()->master()->contentSecurityPolicy();
return ContentSecurityPolicy::create(document);
}
void Document::initSecurityContext(const DocumentInit& initializer)
{
if (haveInitializedSecurityOrigin()) {
ASSERT(securityOrigin());
return;
}
if (!initializer.hasSecurityContext()) {
m_cookieURL = KURL(ParsedURLString, emptyString());
setSecurityOrigin(SecurityOrigin::createUnique());
setContentSecurityPolicy(ContentSecurityPolicy::create(this));
return;
}
m_cookieURL = m_url;
enforceSandboxFlags(initializer.sandboxFlags());
setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
setContentSecurityPolicy(contentSecurityPolicyFor(this));
if (Settings* settings = initializer.settings()) {
if (!settings->webSecurityEnabled()) {
securityOrigin()->grantUniversalAccess();
} else if (securityOrigin()->isLocal()) {
if (settings->allowUniversalAccessFromFileURLs()) {
securityOrigin()->grantUniversalAccess();
} else if (!settings->allowFileAccessFromFileURLs()) {
securityOrigin()->enforceFilePathSeparation();
}
}
}
if (initializer.shouldTreatURLAsSrcdocDocument()) {
m_isSrcdocDocument = true;
setBaseURLOverride(initializer.parentBaseURL());
}
if (!shouldInheritSecurityOriginFromOwner(m_url))
return;
if (!initializer.owner()) {
didFailToInitializeSecurityOrigin();
return;
}
if (isSandboxed(SandboxOrigin)) {
if (initializer.owner()->securityOrigin()->canLoadLocalResources())
securityOrigin()->grantLoadLocalResources();
return;
}
m_cookieURL = initializer.owner()->cookieURL();
setSecurityOrigin(initializer.owner()->securityOrigin());
}
void Document::initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders& headers)
{
if (m_frame && m_frame->tree().parent() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
contentSecurityPolicy()->copyStateFrom(m_frame->tree().parent()->document()->contentSecurityPolicy());
contentSecurityPolicy()->didReceiveHeaders(headers);
}
bool Document::allowInlineEventHandlers(Node* node, EventListener* listener, const String& contextURL, const WTF::OrdinalNumber& contextLine)
{
if (!contentSecurityPolicy()->allowInlineEventHandlers(contextURL, contextLine))
return false;
LocalFrame* frame = executingFrame();
if (!frame)
return false;
if (!frame->script().canExecuteScripts(NotAboutToExecuteScript))
return false;
if (node && node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
return false;
return true;
}
bool Document::allowExecutingScripts(Node* node)
{
LocalFrame* frame = executingFrame();
if (!frame)
return false;
if (!node->document().executingFrame())
return false;
if (!frame->script().canExecuteScripts(AboutToExecuteScript))
return false;
return true;
}
void Document::updateSecurityOrigin(PassRefPtr<SecurityOrigin> origin)
{
setSecurityOrigin(origin);
didUpdateSecurityOrigin();
}
void Document::didUpdateSecurityOrigin()
{
if (!m_frame)
return;
m_frame->script().updateSecurityOrigin(securityOrigin());
}
bool Document::isContextThread() const
{
return isMainThread();
}
void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
{
m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
if (!m_updateFocusAppearanceTimer.isActive())
m_updateFocusAppearanceTimer.startOneShot(0, FROM_HERE);
}
void Document::cancelFocusAppearanceUpdate()
{
m_updateFocusAppearanceTimer.stop();
}
void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
{
Element* element = focusedElement();
if (!element)
return;
updateLayout();
if (element->isFocusable())
element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
}
void Document::attachRange(Range* range)
{
ASSERT(!m_ranges.contains(range));
m_ranges.add(range);
}
void Document::detachRange(Range* range)
{
m_ranges.remove(range);
}
void Document::getCSSCanvasContext(const String& type, const String& name, int width, int height, bool& is2d, RefPtr<CanvasRenderingContext2D>& context2d, bool& is3d, RefPtr<WebGLRenderingContext>& context3d)
{
HTMLCanvasElement& element = getCSSCanvasElement(name);
element.setSize(IntSize(width, height));
CanvasRenderingContext* context = element.getContext(type);
if (!context)
return;
if (context->is2d()) {
is2d = true;
context2d = toCanvasRenderingContext2D(context);
} else if (context->is3d()) {
is3d = true;
context3d = toWebGLRenderingContext(context);
}
}
HTMLCanvasElement& Document::getCSSCanvasElement(const String& name)
{
RefPtr<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, nullptr).storedValue->value;
if (!element) {
element = HTMLCanvasElement::create(*this);
element->setAccelerationDisabled(true);
}
return *element;
}
void Document::initDNSPrefetch()
{
Settings* settings = this->settings();
m_haveExplicitlyDisabledDNSPrefetch = false;
m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
if (Document* parent = parentDocument()) {
if (!parent->isDNSPrefetchEnabled())
m_isDNSPrefetchEnabled = false;
}
}
void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
{
if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
m_isDNSPrefetchEnabled = true;
return;
}
m_isDNSPrefetchEnabled = false;
m_haveExplicitlyDisabledDNSPrefetch = true;
}
void Document::reportBlockedScriptExecutionToInspector(const String& directiveText)
{
InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText);
}
void Document::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* state)
{
internalAddMessage(source, level, message, sourceURL, lineNumber, nullptr, state);
}
void Document::internalAddMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state)
{
if (!isContextThread()) {
m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
return;
}
FrameHost* host = frameHost();
if (!host)
return;
String messageURL = sourceURL;
if (!state && sourceURL.isNull() && !lineNumber) {
messageURL = url().string();
if (parsing() && !isInDocumentWrite() && scriptableDocumentParser()) {
ScriptableDocumentParser* parser = scriptableDocumentParser();
if (!parser->isWaitingForScripts() && !parser->isExecutingScript())
lineNumber = parser->lineNumber().oneBasedInt();
}
}
host->console().addMessage(source, level, message, messageURL, lineNumber, 0, callStack, state, 0);
}
void Document::addConsoleMessageWithRequestIdentifier(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
{
if (!isContextThread()) {
m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
return;
}
if (FrameHost* host = frameHost())
host->console().addMessage(source, level, message, String(), 0, 0, nullptr, 0, requestIdentifier);
}
void Document::postTask(PassOwnPtr<ExecutionContextTask> task)
{
m_taskRunner->postTask(task);
}
void Document::tasksWereSuspended()
{
scriptRunner()->suspend();
if (m_parser)
m_parser->suspendScheduledTasks();
if (m_scriptedAnimationController)
m_scriptedAnimationController->suspend();
}
void Document::tasksWereResumed()
{
scriptRunner()->resume();
if (m_parser)
m_parser->resumeScheduledTasks();
if (m_scriptedAnimationController)
m_scriptedAnimationController->resume();
MutationObserver::resumeSuspendedObservers();
}
void Document::suspendScheduledTasks()
{
ExecutionContext::suspendScheduledTasks();
m_taskRunner->suspend();
}
void Document::resumeScheduledTasks()
{
ExecutionContext::resumeScheduledTasks();
m_taskRunner->resume();
}
bool Document::tasksNeedSuspension()
{
Page* page = this->page();
return page && page->defersLoading();
}
void Document::addToTopLayer(Element* element, const Element* before)
{
if (element->isInTopLayer())
return;
ASSERT(!m_topLayerElements.contains(element));
ASSERT(!before || m_topLayerElements.contains(before));
if (before) {
size_t beforePosition = m_topLayerElements.find(before);
m_topLayerElements.insert(beforePosition, element);
} else {
m_topLayerElements.append(element);
}
element->setIsInTopLayer(true);
}
void Document::removeFromTopLayer(Element* element)
{
if (!element->isInTopLayer())
return;
size_t position = m_topLayerElements.find(element);
ASSERT(position != kNotFound);
m_topLayerElements.remove(position);
element->setIsInTopLayer(false);
}
HTMLDialogElement* Document::activeModalDialog() const
{
if (m_topLayerElements.isEmpty())
return 0;
return toHTMLDialogElement(m_topLayerElements.last().get());
}
void Document::webkitExitPointerLock()
{
if (!page())
return;
if (Element* target = page()->pointerLockController().element()) {
if (target->document() != this)
return;
}
page()->pointerLockController().requestPointerUnlock();
}
Element* Document::webkitPointerLockElement() const
{
if (!page() || page()->pointerLockController().lockPending())
return 0;
if (Element* element = page()->pointerLockController().element()) {
if (element->document() == this)
return element;
}
return 0;
}
void Document::decrementLoadEventDelayCount()
{
ASSERT(m_loadEventDelayCount);
--m_loadEventDelayCount;
if (frame() && !m_loadEventDelayCount && !m_loadEventDelayTimer.isActive())
m_loadEventDelayTimer.startOneShot(0, FROM_HERE);
}
void Document::loadEventDelayTimerFired(Timer<Document>*)
{
if (frame())
frame()->loader().checkCompleted();
}
void Document::loadPluginsSoon()
{
if (!m_pluginLoadingTimer.isActive())
m_pluginLoadingTimer.startOneShot(0, FROM_HERE);
}
void Document::pluginLoadingTimerFired(Timer<Document>*)
{
updateLayout();
}
ScriptedAnimationController& Document::ensureScriptedAnimationController()
{
if (!m_scriptedAnimationController) {
m_scriptedAnimationController = ScriptedAnimationController::create(this);
if (!page())
m_scriptedAnimationController->suspend();
}
return *m_scriptedAnimationController;
}
int Document::requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
{
return ensureScriptedAnimationController().registerCallback(callback);
}
void Document::cancelAnimationFrame(int id)
{
if (!m_scriptedAnimationController)
return;
m_scriptedAnimationController->cancelCallback(id);
}
void Document::serviceScriptedAnimations(double monotonicAnimationStartTime)
{
if (!m_scriptedAnimationController)
return;
m_scriptedAnimationController->serviceScriptedAnimations(monotonicAnimationStartTime);
}
PassRefPtrWillBeRawPtr<Touch> Document::createTouch(DOMWindow* window, EventTarget* target, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force) const
{
LocalFrame* frame = window ? window->frame() : this->frame();
return Touch::create(frame, target, identifier, screenX, screenY, pageX, pageY, radiusX, radiusY, rotationAngle, force);
}
PassRefPtrWillBeRawPtr<TouchList> Document::createTouchList(WillBeHeapVector<RefPtrWillBeMember<Touch> >& touches) const
{
return TouchList::create(touches);
}
void Document::didAddTouchEventHandler(Node* handler)
{
ASSERT(&handler->document() == this
|| (handler->isDocumentNode() && toDocument(handler)->parentDocument() == this));
if (!m_touchEventTargets.get())
m_touchEventTargets = adoptPtr(new TouchEventTargetSet);
bool isFirstHandler = m_touchEventTargets->isEmpty();
if (!m_touchEventTargets->add(handler).isNewEntry) {
ASSERT(!handler->isDocumentNode() || &handler->document() == this);
return;
}
if (isFirstHandler) {
if (Document* parent = parentDocument()) {
parent->didAddTouchEventHandler(this);
} else {
if (FrameHost* frameHost = this->frameHost())
frameHost->chrome().client().needTouchEvents(true);
}
}
if (!handler->isDocumentNode() || handler == this) {
if (Page* page = this->page()) {
if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
scrollingCoordinator->touchEventTargetRectsDidChange();
}
}
}
void Document::didRemoveTouchEventHandler(Node* handler, bool clearAll)
{
ASSERT(clearAll || m_touchEventTargets->contains(handler));
if (!m_touchEventTargets.get())
return;
if (clearAll) {
if (!m_touchEventTargets->contains(handler))
return;
m_touchEventTargets->removeAll(handler);
} else {
if (!m_touchEventTargets->remove(handler))
return;
}
if (m_touchEventTargets->isEmpty()) {
if (Document* parent = parentDocument()) {
parent->didRemoveTouchEventHandler(this, clearAll);
} else {
if (FrameHost* frameHost = this->frameHost())
frameHost->chrome().client().needTouchEvents(false);
}
}
if (!handler->isDocumentNode() || handler == this) {
if (Page* page = this->page()) {
if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
scrollingCoordinator->touchEventTargetRectsDidChange();
}
}
}
DocumentLoader* Document::loader() const
{
if (!m_frame)
return 0;
DocumentLoader* loader = m_frame->loader().documentLoader();
if (!loader)
return 0;
if (m_frame->document() != this)
return 0;
return loader;
}
IntSize Document::initialViewportSize() const
{
if (!view())
return IntSize();
return view()->unscaledVisibleContentSize(IncludeScrollbars);
}
Node* eventTargetNodeForDocument(Document* doc)
{
if (!doc)
return 0;
Node* node = doc->focusedElement();
if (!node && doc->isPluginDocument()) {
PluginDocument* pluginDocument = toPluginDocument(doc);
node = pluginDocument->pluginNode();
}
if (!node && doc->isHTMLDocument())
node = doc->body();
if (!node)
node = doc->documentElement();
return node;
}
void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject& renderer)
{
if (!view())
return;
LayoutRect visibleContentRect = view()->visibleContentRect();
for (size_t i = 0; i < quads.size(); ++i) {
quads[i].move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
adjustFloatQuadForAbsoluteZoom(quads[i], renderer);
}
}
void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject& renderer)
{
if (!view())
return;
LayoutRect visibleContentRect = view()->visibleContentRect();
rect.move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
adjustFloatRectForAbsoluteZoom(rect, renderer);
}
bool Document::hasActiveParser()
{
return m_activeParserCount || (m_parser && m_parser->processingData());
}
void Document::decrementActiveParserCount()
{
--m_activeParserCount;
if (!frame())
return;
loader()->checkLoadComplete();
frame()->loader().checkLoadComplete();
}
void Document::setContextFeatures(ContextFeatures& features)
{
m_contextFeatures = PassRefPtr<ContextFeatures>(features);
}
static RenderObject* nearestCommonHoverAncestor(RenderObject* obj1, RenderObject* obj2)
{
if (!obj1 || !obj2)
return 0;
for (RenderObject* currObj1 = obj1; currObj1; currObj1 = currObj1->hoverAncestor()) {
for (RenderObject* currObj2 = obj2; currObj2; currObj2 = currObj2->hoverAncestor()) {
if (currObj1 == currObj2)
return currObj1;
}
}
return 0;
}
void Document::updateHoverActiveState(const HitTestRequest& request, Element* innerElement, const PlatformMouseEvent* event)
{
ASSERT(!request.readOnly());
if (request.active() && m_frame)
m_frame->eventHandler().notifyElementActivated();
Element* innerElementInDocument = innerElement;
while (innerElementInDocument && innerElementInDocument->document() != this) {
innerElementInDocument->document().updateHoverActiveState(request, innerElementInDocument, event);
innerElementInDocument = innerElementInDocument->document().ownerElement();
}
Element* oldActiveElement = activeHoverElement();
if (oldActiveElement && !request.active()) {
for (RenderObject* curr = oldActiveElement->renderer(); curr; curr = curr->parent()) {
if (curr->node()) {
ASSERT(!curr->node()->isTextNode());
curr->node()->setActive(false);
m_userActionElements.setInActiveChain(curr->node(), false);
}
}
setActiveHoverElement(nullptr);
} else {
Element* newActiveElement = innerElementInDocument;
if (!oldActiveElement && newActiveElement && request.active() && !request.touchMove()) {
for (RenderObject* curr = newActiveElement->renderer(); curr; curr = curr->parent()) {
if (curr->node() && !curr->isText())
m_userActionElements.setInActiveChain(curr->node(), true);
}
setActiveHoverElement(newActiveElement);
}
}
bool allowActiveChanges = !oldActiveElement && activeHoverElement();
bool mustBeInActiveChain = request.active() && request.move();
RefPtr<Node> oldHoverNode = hoverNode();
Node* newHoverNode = innerElementInDocument;
while (newHoverNode && !newHoverNode->renderer())
newHoverNode = newHoverNode->parentOrShadowHostNode();
setHoverNode(newHoverNode);
RenderObject* oldHoverObj = oldHoverNode ? oldHoverNode->renderer() : 0;
RenderObject* newHoverObj = newHoverNode ? newHoverNode->renderer() : 0;
RenderObject* ancestor = nearestCommonHoverAncestor(oldHoverObj, newHoverObj);
RefPtr<Node> ancestorNode(ancestor ? ancestor->node() : 0);
Vector<RefPtr<Node>, 32> nodesToRemoveFromChain;
Vector<RefPtr<Node>, 32> nodesToAddToChain;
if (oldHoverObj != newHoverObj) {
if (oldHoverNode && !oldHoverObj) {
for (Node* node = oldHoverNode.get(); node; node = node->parentNode()) {
if (!mustBeInActiveChain || (node->isElementNode() && toElement(node)->inActiveChain()))
nodesToRemoveFromChain.append(node);
}
}
for (RenderObject* curr = oldHoverObj; curr && curr != ancestor; curr = curr->hoverAncestor()) {
if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
nodesToRemoveFromChain.append(curr->node());
}
}
for (RenderObject* curr = newHoverObj; curr; curr = curr->hoverAncestor()) {
if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
nodesToAddToChain.append(curr->node());
}
bool ancestorHasCapturingMouseleaveListener = false;
if (event && newHoverNode != oldHoverNode.get()) {
for (Node* node = oldHoverNode.get(); node; node = node->parentOrShadowHostNode()) {
if (node->hasCapturingEventListeners(EventTypeNames::mouseleave)) {
ancestorHasCapturingMouseleaveListener = true;
break;
}
}
}
size_t removeCount = nodesToRemoveFromChain.size();
for (size_t i = 0; i < removeCount; ++i) {
nodesToRemoveFromChain[i]->setHovered(false);
if (event && (ancestorHasCapturingMouseleaveListener || nodesToRemoveFromChain[i]->hasEventListeners(EventTypeNames::mouseleave)))
nodesToRemoveFromChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseleave, 0, newHoverNode);
}
bool ancestorHasCapturingMouseenterListener = false;
if (event && newHoverNode != oldHoverNode.get()) {
for (Node* node = newHoverNode; node; node = node->parentOrShadowHostNode()) {
if (node->hasCapturingEventListeners(EventTypeNames::mouseenter)) {
ancestorHasCapturingMouseenterListener = true;
break;
}
}
}
bool sawCommonAncestor = false;
size_t addCount = nodesToAddToChain.size();
for (size_t i = 0; i < addCount; ++i) {
if (ancestorNode && nodesToAddToChain[i] == ancestorNode)
sawCommonAncestor = true;
if (allowActiveChanges)
nodesToAddToChain[i]->setActive(true);
if (!sawCommonAncestor) {
nodesToAddToChain[i]->setHovered(true);
if (event && (ancestorHasCapturingMouseenterListener || nodesToAddToChain[i]->hasEventListeners(EventTypeNames::mouseenter)))
nodesToAddToChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseenter, 0, oldHoverNode.get());
}
}
updateRenderTreeIfNeeded();
}
bool Document::haveStylesheetsLoaded() const
{
return m_styleEngine->haveStylesheetsLoaded();
}
Locale& Document::getCachedLocale(const AtomicString& locale)
{
AtomicString localeKey = locale;
if (locale.isEmpty() || !RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
return Locale::defaultLocale();
LocaleIdentifierToLocaleMap::AddResult result = m_localeCache.add(localeKey, nullptr);
if (result.isNewEntry)
result.storedValue->value = Locale::create(localeKey);
return *(result.storedValue->value);
}
Document& Document::ensureTemplateDocument()
{
if (isTemplateDocument())
return *this;
if (m_templateDocument)
return *m_templateDocument;
if (isHTMLDocument()) {
DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL()).withNewRegistrationContext();
m_templateDocument = HTMLDocument::create(init);
} else {
m_templateDocument = Document::create(DocumentInit(blankURL()));
}
m_templateDocument->m_templateDocumentHost = this;
return *m_templateDocument.get();
}
void Document::didAssociateFormControl(Element* element)
{
if (!frame() || !frame()->page())
return;
m_associatedFormControls.add(element);
if (!m_didAssociateFormControlsTimer.isActive())
m_didAssociateFormControlsTimer.startOneShot(0, FROM_HERE);
}
void Document::didAssociateFormControlsTimerFired(Timer<Document>* timer)
{
ASSERT_UNUSED(timer, timer == &m_didAssociateFormControlsTimer);
if (!frame() || !frame()->page())
return;
Vector<RefPtr<Element> > associatedFormControls;
copyToVector(m_associatedFormControls, associatedFormControls);
frame()->page()->chrome().client().didAssociateFormControls(associatedFormControls);
m_associatedFormControls.clear();
}
float Document::devicePixelRatio() const
{
return m_frame ? m_frame->devicePixelRatio() : 1.0;
}
PassOwnPtr<LifecycleNotifier<Document> > Document::createLifecycleNotifier()
{
return DocumentLifecycleNotifier::create(this);
}
DocumentLifecycleNotifier& Document::lifecycleNotifier()
{
return static_cast<DocumentLifecycleNotifier&>(LifecycleContext<Document>::lifecycleNotifier());
}
void Document::removedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
{
if (isActive())
styleEngine()->modifiedStyleSheet(sheet);
styleResolverChanged(when, updateMode);
}
void Document::modifiedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
{
if (isActive())
styleEngine()->modifiedStyleSheet(sheet);
styleResolverChanged(when, updateMode);
}
TextAutosizer* Document::textAutosizer()
{
if (!m_textAutosizer && !RuntimeEnabledFeatures::fastTextAutosizingEnabled())
m_textAutosizer = TextAutosizer::create(this);
return m_textAutosizer.get();
}
FastTextAutosizer* Document::fastTextAutosizer()
{
if (!m_fastTextAutosizer && RuntimeEnabledFeatures::fastTextAutosizingEnabled())
m_fastTextAutosizer = FastTextAutosizer::create(this);
return m_fastTextAutosizer.get();
}
void Document::setAutofocusElement(Element* element)
{
if (!element) {
m_autofocusElement = nullptr;
return;
}
if (m_hasAutofocused)
return;
m_hasAutofocused = true;
ASSERT(!m_autofocusElement);
m_autofocusElement = element;
m_taskRunner->postTask(AutofocusTask::create());
}
Element* Document::activeElement() const
{
if (Element* element = treeScope().adjustedFocusedElement())
return element;
return body();
}
bool Document::hasFocus() const
{
Page* page = this->page();
if (!page)
return false;
if (!page->focusController().isActive() || !page->focusController().isFocused())
return false;
Frame* focusedFrame = page->focusController().focusedFrame();
if (focusedFrame && focusedFrame->isLocalFrame()) {
if (toLocalFrame(focusedFrame)->tree().isDescendantOf(frame()))
return true;
}
return false;
}
void Document::defaultEventHandler(Event* event)
{
if (frame() && frame()->remotePlatformLayer()) {
frame()->chromeClient().forwardInputEvent(this, event);
return;
}
Node::defaultEventHandler(event);
}
template<unsigned type>
bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
{
if (nodeListCounts[type] && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
return true;
return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
}
template<>
bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
{
return false;
}
bool Document::shouldInvalidateNodeListCaches(const QualifiedName* attrName) const
{
if (attrName)
return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListCounts, *attrName);
for (int type = 0; type < numNodeListInvalidationTypes; type++) {
if (m_nodeListCounts[type])
return true;
}
return false;
}
void Document::invalidateNodeListCaches(const QualifiedName* attrName)
{
HashSet<LiveNodeListBase*>::iterator end = m_listsInvalidatedAtDocument.end();
for (HashSet<LiveNodeListBase*>::iterator it = m_listsInvalidatedAtDocument.begin(); it != end; ++it)
(*it)->invalidateCache(attrName);
}
}