blob: 11cf856eed5c5096fdebed3b2fc955f694e4dc4f [file] [log] [blame]
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* (C) 2006 Alexey Proskuryakov (ap@webkit.org)
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2011, 2012 Apple Inc. All rights reserved.
* Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
* Copyright (C) 2008, 2009, 2011, 2012 Google Inc. All rights reserved.
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
* Copyright (C) Research In Motion Limited 2010-2011. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "Document.h"
#include "AXObjectCache.h"
#include "AnimationController.h"
#include "Attr.h"
#include "Attribute.h"
#include "CDATASection.h"
#include "CSSParser.h"
#include "CSSStyleDeclaration.h"
#include "CSSStyleSheet.h"
#include "CSSValueKeywords.h"
#include "CachedCSSStyleSheet.h"
#include "CachedResourceLoader.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "Comment.h"
#include "ContentSecurityPolicy.h"
#include "ContextFeatures.h"
#include "CookieJar.h"
#include "CustomElementConstructor.h"
#include "CustomElementRegistry.h"
#include "DOMImplementation.h"
#include "DOMNamedFlowCollection.h"
#include "DOMSelection.h"
#include "DOMWindow.h"
#include "DateComponents.h"
#include "Dictionary.h"
#include "DocumentEventQueue.h"
#include "DocumentFragment.h"
#include "DocumentLoader.h"
#include "DocumentMarkerController.h"
#include "DocumentSharedObjectPool.h"
#include "DocumentStyleSheetCollection.h"
#include "DocumentType.h"
#include "Editor.h"
#include "Element.h"
#include "ElementShadow.h"
#include "EntityReference.h"
#include "Event.h"
#include "EventFactory.h"
#include "EventHandler.h"
#include "EventListener.h"
#include "EventNames.h"
#include "ExceptionCode.h"
#include "ExceptionCodePlaceholder.h"
#include "FlowThreadController.h"
#include "FocusController.h"
#include "FontLoader.h"
#include "FormController.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameLoaderClient.h"
#include "FrameSelection.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "GeolocationController.h"
#include "HashChangeEvent.h"
#include "HistogramSupport.h"
#include "History.h"
#include "HTMLAllCollection.h"
#include "HTMLAnchorElement.h"
#include "HTMLBodyElement.h"
#include "HTMLCanvasElement.h"
#include "HTMLCollection.h"
#include "HTMLDocument.h"
#include "HTMLElementFactory.h"
#include "HTMLFrameOwnerElement.h"
#include "HTMLHeadElement.h"
#include "HTMLIFrameElement.h"
#include "HTMLLinkElement.h"
#include "HTMLMapElement.h"
#include "HTMLNameCollection.h"
#include "HTMLNames.h"
#include "HTMLParserIdioms.h"
#include "HTMLStyleElement.h"
#include "HTMLTitleElement.h"
#include "HTTPParsers.h"
#include "HitTestRequest.h"
#include "HitTestResult.h"
#include "IconController.h"
#include "ImageLoader.h"
#include "InspectorCounters.h"
#include "InspectorInstrumentation.h"
#include "Language.h"
#include "Logging.h"
#include "MediaCanStartListener.h"
#include "MediaQueryList.h"
#include "MediaQueryMatcher.h"
#include "MouseEventWithHitTestResults.h"
#include "NameNodeList.h"
#include "NamedFlowCollection.h"
#include "NestingLevelIncrementer.h"
#include "NodeFilter.h"
#include "NodeIterator.h"
#include "NodeRareData.h"
#include "NodeTraversal.h"
#include "NodeWithIndex.h"
#include "Page.h"
#include "PageConsole.h"
#include "PageGroup.h"
#include "PageTransitionEvent.h"
#include "PlatformKeyboardEvent.h"
#include "PlatformLocale.h"
#include "PlugInsResources.h"
#include "PluginDocument.h"
#include "PointerLockController.h"
#include "PopStateEvent.h"
#include "ProcessingInstruction.h"
#include "QualifiedName.h"
#include "RegisteredEventListener.h"
#include "RenderArena.h"
#include "RenderNamedFlowThread.h"
#include "RenderTextControl.h"
#include "RenderView.h"
#include "RenderWidget.h"
#include "ResourceLoader.h"
#include "RuntimeEnabledFeatures.h"
#include "SchemeRegistry.h"
#include "ScopedEventQueue.h"
#include "ScriptCallStack.h"
#include "ScriptController.h"
#include "ScriptElement.h"
#include "ScriptEventListener.h"
#include "ScriptRunner.h"
#include "ScriptSourceCode.h"
#include "ScriptValue.h"
#include "ScrollingCoordinator.h"
#include "SecurityOrigin.h"
#include "SecurityPolicy.h"
#include "SegmentedString.h"
#include "SelectorQuery.h"
#include "Settings.h"
#include "ShadowRoot.h"
#include "StylePropertySet.h"
#include "StyleResolver.h"
#include "StyleSheetContents.h"
#include "StyleSheetList.h"
#include "TextResourceDecoder.h"
#include "Timer.h"
#include "TransformSource.h"
#include "TreeWalker.h"
#include "UserActionElementSet.h"
#include "UserContentURLPattern.h"
#include "VisitedLinkState.h"
#include "WebKitNamedFlow.h"
#include "XMLDocumentParser.h"
#include "XMLHttpRequest.h"
#include "XMLNSNames.h"
#include "XMLNames.h"
#include "XPathEvaluator.h"
#include "XPathExpression.h"
#include "XPathNSResolver.h"
#include "XPathResult.h"
#include "htmlediting.h"
#include <wtf/CurrentTime.h>
#include <wtf/HashFunctions.h>
#include <wtf/MainThread.h>
#include <wtf/PassRefPtr.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/StringBuffer.h>
#if USE(ACCELERATED_COMPOSITING)
#include "RenderLayerCompositor.h"
#endif
#if ENABLE(SHARED_WORKERS)
#include "SharedWorkerRepository.h"
#endif
#if ENABLE(XSLT)
#include "XSLTProcessor.h"
#endif
#if ENABLE(SVG)
#include "SVGDocumentExtensions.h"
#include "SVGElementFactory.h"
#include "SVGNames.h"
#include "SVGSVGElement.h"
#include "SVGStyleElement.h"
#endif
#if ENABLE(TOUCH_EVENTS)
#include "TouchList.h"
#endif
#if ENABLE(MATHML)
#include "MathMLElement.h"
#include "MathMLElementFactory.h"
#include "MathMLNames.h"
#endif
#if ENABLE(FULLSCREEN_API)
#include "RenderFullScreen.h"
#endif
#if ENABLE(REQUEST_ANIMATION_FRAME)
#include "RequestAnimationFrameCallback.h"
#include "ScriptedAnimationController.h"
#endif
#if ENABLE(MICRODATA)
#include "MicroDataItemList.h"
#include "NodeRareData.h"
#endif
#if ENABLE(LINK_PRERENDER)
#include "Prerenderer.h"
#endif
#if ENABLE(TEXT_AUTOSIZING)
#include "TextAutosizer.h"
#endif
#if ENABLE(CSP_NEXT)
#include "DOMSecurityPolicy.h"
#endif
#if ENABLE(VIDEO_TRACK)
#include "CaptionUserPreferences.h"
#endif
using namespace std;
using namespace WTF;
using namespace Unicode;
namespace WebCore {
using namespace HTMLNames;
// #define INSTRUMENT_LAYOUT_SCHEDULING 1
static const unsigned cMaxWriteRecursionDepth = 21;
// This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
// FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
// for dual G5s. :)
static const int cLayoutScheduleThreshold = 250;
// DOM Level 2 says (letters added):
//
// a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
// b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
// c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
// d) Characters which have a font or compatibility decomposition (i.e. those with a "compatibility formatting tag" in field 5 of the database -- marked by field 5 beginning with a "<") are not allowed.
// e) The following characters are treated as name-start characters rather than name characters, because the property file classifies them as Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.
// f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
// g) Character #x00B7 is classified as an extender, because the property list so identifies it.
// h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
// i) Characters ':' and '_' are allowed as name-start characters.
// j) Characters '-' and '.' are allowed as name characters.
//
// It also contains complete tables. If we decide it's better, we could include those instead of the following code.
static inline bool isValidNameStart(UChar32 c)
{
// rule (e) above
if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
return true;
// rule (i) above
if (c == ':' || c == '_')
return true;
// rules (a) and (f) above
const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
if (!(Unicode::category(c) & nameStartMask))
return false;
// rule (c) above
if (c >= 0xF900 && c < 0xFFFE)
return false;
// rule (d) above
DecompositionType decompType = decompositionType(c);
if (decompType == DecompositionFont || decompType == DecompositionCompat)
return false;
return true;
}
static inline bool isValidNamePart(UChar32 c)
{
// rules (a), (e), and (i) above
if (isValidNameStart(c))
return true;
// rules (g) and (h) above
if (c == 0x00B7 || c == 0x0387)
return true;
// rule (j) above
if (c == '-' || c == '.')
return true;
// rules (b) and (f) above
const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
if (!(Unicode::category(c) & otherNamePartMask))
return false;
// rule (c) above
if (c >= 0xF900 && c < 0xFFFE)
return false;
// rule (d) above
DecompositionType decompType = decompositionType(c);
if (decompType == DecompositionFont || decompType == DecompositionCompat)
return false;
return true;
}
static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
{
// http://www.whatwg.org/specs/web-apps/current-work/#origin-0
//
// If a Document has the address "about:blank"
// The origin of the Document is the origin it was assigned when its browsing context was created.
//
// Note: We generalize this to all "blank" URLs and invalid URLs because we
// treat all of these URLs as about:blank.
//
return url.isEmpty() || url.isBlankURL();
}
static Widget* widgetForNode(Node* focusedNode)
{
if (!focusedNode)
return 0;
RenderObject* renderer = focusedNode->renderer();
if (!renderer || !renderer->isWidget())
return 0;
return toRenderWidget(renderer)->widget();
}
static bool acceptsEditingFocus(Node* node)
{
ASSERT(node);
ASSERT(node->rendererIsEditable());
Node* root = node->rootEditableElement();
Frame* frame = node->document()->frame();
if (!frame || !root)
return false;
return frame->editor().shouldBeginEditing(rangeOfContents(root).get());
}
static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
{
// targetFrame can be 0 when we're trying to navigate a top-level frame
// that has a 0 opener.
if (!targetFrame)
return false;
const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree()->parent()) {
Document* ancestorDocument = ancestorFrame->document();
// FIXME: Should be an ASSERT? Frames should alway have documents.
if (!ancestorDocument)
return true;
const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
return true;
// Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
// FIXME: It's a bit strange to special-case local origins here. Should we be doing
// something more general instead?
if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
return true;
}
return false;
}
static void printNavigationErrorMessage(Frame* 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";
// FIXME: should we print to the console of the document performing the navigation instead?
frame->document()->domWindow()->printErrorMessage(message);
}
static HashSet<Document*>* documentsThatNeedStyleRecalc = 0;
uint64_t Document::s_globalTreeVersion = 0;
static const double timeBeforeThrowingAwayStyleResolverAfterLastUseInSeconds = 30;
Document::Document(Frame* frame, const KURL& url, unsigned documentClasses)
: ContainerNode(0, CreateDocument)
, TreeScope(this)
, m_styleResolverThrowawayTimer(this, &Document::styleResolverThrowawayTimerFired, timeBeforeThrowingAwayStyleResolverAfterLastUseInSeconds)
, m_activeParserCount(0)
, m_contextFeatures(ContextFeatures::defaultSwitch())
, m_compatibilityMode(NoQuirksMode)
, m_compatibilityModeLocked(false)
, m_domTreeVersion(++s_globalTreeVersion)
, m_mutationObserverTypes(0)
, m_styleSheetCollection(DocumentStyleSheetCollection::create(this))
, m_visitedLinkState(VisitedLinkState::create(this))
, m_readyState(Complete)
, m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
, m_pendingStyleRecalcShouldForce(false)
, m_frameElementsShouldIgnoreScrolling(false)
, m_containsValidityStyleRules(false)
, m_updateFocusAppearanceRestoresSelection(false)
, m_ignoreDestructiveWriteCount(0)
, m_titleSetExplicitly(false)
, m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
, m_loadEventFinished(false)
, m_startTime(currentTime())
, m_overMinimumLayoutThreshold(false)
, m_scriptRunner(ScriptRunner::create(this))
, m_xmlVersion("1.0")
, m_xmlStandalone(StandaloneUnspecified)
, m_hasXMLDeclaration(0)
, m_savedRenderer(0)
, m_designMode(inherit)
#if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
, m_hasAnnotatedRegions(false)
, m_annotatedRegionsDirty(false)
#endif
, m_createRenderers(true)
, m_inPageCache(false)
, m_accessKeyMapValid(false)
, m_documentClasses(documentClasses)
, m_isViewSource(false)
, m_sawElementsInKnownNamespaces(false)
, m_isSrcdocDocument(false)
, m_renderer(0)
, m_eventQueue(DocumentEventQueue::create(this))
, m_weakFactory(this)
, m_idAttributeName(idAttr)
#if ENABLE(FULLSCREEN_API)
, m_areKeysEnabledInFullScreen(0)
, m_fullScreenRenderer(0)
, m_fullScreenChangeDelayTimer(this, &Document::fullScreenChangeDelayTimerFired)
, m_isAnimatingFullScreen(false)
#endif
, m_loadEventDelayCount(0)
, m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
, m_referrerPolicy(ReferrerPolicyDefault)
, m_directionSetOnDocumentElement(false)
, m_writingModeSetOnDocumentElement(false)
, m_writeRecursionIsTooDeep(false)
, m_writeRecursionDepth(0)
, m_wheelEventHandlerCount(0)
, m_lastHandledUserGestureTimestamp(0)
, m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
, m_scheduledTasksAreSuspended(false)
, m_visualUpdatesAllowed(true)
, m_visualUpdatesSuppressionTimer(this, &Document::visualUpdatesSuppressionTimerFired)
, m_sharedObjectPoolClearTimer(this, &Document::sharedObjectPoolClearTimerFired)
#ifndef NDEBUG
, m_didDispatchViewportPropertiesChanged(false)
#endif
#if ENABLE(TEMPLATE_ELEMENT)
, m_templateDocumentHost(0)
#endif
#if ENABLE(FONT_LOAD_EVENTS)
, m_fontloader(0)
#endif
, m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
, m_hasInjectedPlugInsScript(false)
{
m_printing = false;
m_paginatedForScreen = false;
m_ignoreAutofocus = false;
m_frame = frame;
if (m_frame)
provideContextFeaturesToDocumentFrom(this, m_frame->page());
// We depend on the url getting immediately set in subframes, but we
// also depend on the url NOT getting immediately set in opened windows.
// See fast/dom/early-frame-url.html
// and fast/dom/location-new-window-no-crash.html, respectively.
// FIXME: Can/should we unify this behavior?
if ((frame && frame->ownerElement()) || !url.isEmpty())
setURL(url);
m_markers = adoptPtr(new DocumentMarkerController);
if (m_frame)
m_cachedResourceLoader = m_frame->loader()->activeDocumentLoader()->cachedResourceLoader();
if (!m_cachedResourceLoader)
m_cachedResourceLoader = CachedResourceLoader::create(0);
m_cachedResourceLoader->setDocument(this);
#if ENABLE(LINK_PRERENDER)
m_prerenderer = Prerenderer::create(this);
#endif
#if ENABLE(TEXT_AUTOSIZING)
m_textAutosizer = TextAutosizer::create(this);
#endif
m_visuallyOrdered = false;
m_bParsing = false;
m_wellFormed = false;
m_textColor = Color::black;
m_listenerTypes = 0;
m_inStyleRecalc = false;
m_closeAfterStyleRecalc = false;
m_gotoAnchorNeededAfterStylesheetsLoad = false;
m_didCalculateStyleResolver = false;
m_ignorePendingStylesheets = false;
m_needsNotifyRemoveAllPendingStylesheet = false;
m_hasNodesWithPlaceholderStyle = false;
m_pendingSheetLayout = NoLayoutWithPendingSheets;
m_cssTarget = 0;
resetLinkColor();
resetVisitedLinkColor();
resetActiveLinkColor();
m_processingLoadEvent = false;
initSecurityContext();
initDNSPrefetch();
static int docID = 0;
m_docID = docID++;
for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
m_nodeListCounts[i] = 0;
InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
}
static void histogramMutationEventUsage(const unsigned short& listenerTypes)
{
HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMSubtreeModified", static_cast<bool>(listenerTypes & Document::DOMSUBTREEMODIFIED_LISTENER), 2);
HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInserted", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTED_LISTENER), 2);
HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemoved", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVED_LISTENER), 2);
HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemovedFromDocument", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER), 2);
HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInsertedIntoDocument", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER), 2);
HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMCharacterDataModified", static_cast<bool>(listenerTypes & Document::DOMCHARACTERDATAMODIFIED_LISTENER), 2);
}
#if ENABLE(FULLSCREEN_API)
static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
{
if (!owner)
return true;
do {
if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
return false;
} while ((owner = owner->document()->ownerElement()));
return true;
}
#endif
Document::~Document()
{
ASSERT(!renderer());
ASSERT(!m_inPageCache);
ASSERT(!m_savedRenderer);
ASSERT(m_ranges.isEmpty());
ASSERT(!m_styleRecalcTimer.isActive());
ASSERT(!m_parentTreeScope);
ASSERT(!hasGuardRefCount());
#if ENABLE(TEMPLATE_ELEMENT)
if (m_templateDocument)
m_templateDocument->setTemplateDocumentHost(0); // balanced in templateDocument().
#endif
#if ENABLE(TOUCH_EVENT_TRACKING)
if (Document* ownerDocument = this->ownerDocument())
ownerDocument->didRemoveEventTargetNode(this);
#endif
// FIXME: Should we reset m_domWindow when we detach from the Frame?
if (m_domWindow)
m_domWindow->resetUnlessSuspendedForPageCache();
m_scriptRunner.clear();
histogramMutationEventUsage(m_listenerTypes);
removeAllEventListeners();
// Currently we believe that Document can never outlive the parser.
// Although the Document may be replaced synchronously, DocumentParsers
// generally keep at least one reference to an Element which would in turn
// has a reference to the Document. If you hit this ASSERT, then that
// assumption is wrong. DocumentParser::detach() should ensure that even
// if the DocumentParser outlives the Document it won't cause badness.
ASSERT(!m_parser || m_parser->refCount() == 1);
detachParser();
m_renderArena.clear();
if (this == topDocument())
clearAXObjectCache();
m_decoder = 0;
if (m_styleSheetList)
m_styleSheetList->detachFromDocument();
m_styleSheetCollection.clear();
if (m_elemSheet)
m_elemSheet->clearOwnerNode();
clearStyleResolver(); // We need to destory CSSFontSelector before destroying m_cachedResourceLoader.
// It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
// load the initial empty document and the SVGDocument with the same DocumentLoader).
if (m_cachedResourceLoader->document() == this)
m_cachedResourceLoader->setDocument(0);
m_cachedResourceLoader.clear();
// We must call clearRareData() here since a Document class inherits TreeScope
// as well as Node. See a comment on TreeScope.h for the reason.
if (hasRareData())
clearRareData();
ASSERT(!m_listsInvalidatedAtDocument.size());
for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
ASSERT(!m_nodeListCounts[i]);
clearDocumentScope();
InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
}
void Document::dispose()
{
ASSERT(!m_deletionHasBegun);
// We must make sure not to be retaining any of our children through
// these extra pointers or we will create a reference cycle.
m_docType = 0;
m_focusedNode = 0;
m_hoverNode = 0;
m_activeElement = 0;
m_titleElement = 0;
m_documentElement = 0;
m_contextFeatures = ContextFeatures::defaultSwitch();
m_userActionElements.documentDidRemoveLastRef();
#if ENABLE(FULLSCREEN_API)
m_fullScreenElement = 0;
m_fullScreenElementStack.clear();
#endif
detachParser();
#if ENABLE(CUSTOM_ELEMENTS)
m_registry.clear();
#endif
// removeDetachedChildren() doesn't always unregister IDs,
// so tear down scope information upfront to avoid having stale references in the map.
destroyTreeScopeData();
removeDetachedChildren();
m_markers->detach();
m_cssCanvasElements.clear();
#if ENABLE(REQUEST_ANIMATION_FRAME)
clearScriptedAnimationController();
#endif
}
Element* Document::getElementById(const AtomicString& id) const
{
return TreeScope::getElementById(id);
}
Element* Document::getElementByAccessKey(const String& key)
{
if (key.isEmpty())
return 0;
if (!m_accessKeyMapValid) {
buildAccessKeyMap(this);
m_accessKeyMapValid = true;
}
return m_elementsByAccessKey.get(key.impl());
}
void Document::buildAccessKeyMap(TreeScope* scope)
{
ASSERT(scope);
Node* rootNode = scope->rootNode();
for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(element, rootNode)) {
const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
if (!accessKey.isEmpty())
m_elementsByAccessKey.set(accessKey.impl(), element);
if (ShadowRoot* root = element->shadowRoot())
buildAccessKeyMap(root);
}
}
void Document::invalidateAccessKeyMap()
{
m_accessKeyMapValid = false;
m_elementsByAccessKey.clear();
}
SelectorQueryCache* Document::selectorQueryCache()
{
if (!m_selectorQueryCache)
m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
return m_selectorQueryCache.get();
}
MediaQueryMatcher* Document::mediaQueryMatcher()
{
if (!m_mediaQueryMatcher)
m_mediaQueryMatcher = MediaQueryMatcher::create(this);
return m_mediaQueryMatcher.get();
}
void Document::setCompatibilityMode(CompatibilityMode mode)
{
if (m_compatibilityModeLocked || mode == m_compatibilityMode)
return;
bool wasInQuirksMode = inQuirksMode();
m_compatibilityMode = mode;
selectorQueryCache()->invalidate();
if (inQuirksMode() != wasInQuirksMode) {
// All user stylesheets have to reparse using the different mode.
m_styleSheetCollection->clearPageUserSheet();
m_styleSheetCollection->invalidateInjectedStyleSheetCache();
}
}
String Document::compatMode() const
{
return inQuirksMode() ? "BackCompat" : "CSS1Compat";
}
void Document::resetLinkColor()
{
m_linkColor = Color(0, 0, 238);
}
void Document::resetVisitedLinkColor()
{
m_visitedLinkColor = Color(85, 26, 139);
}
void Document::resetActiveLinkColor()
{
m_activeLinkColor.setNamedColor("red");
}
void Document::setDocType(PassRefPtr<DocumentType> docType)
{
// This should never be called more than once.
ASSERT(!m_docType || !docType);
m_docType = docType;
if (m_docType) {
this->adoptIfNeeded(m_docType.get());
#if ENABLE(LEGACY_VIEWPORT_ADAPTION)
if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
processViewport("width=device-width, height=device-height", ViewportArguments::XHTMLMobileProfile);
#endif
}
// Doctype affects the interpretation of the stylesheets.
clearStyleResolver();
}
DOMImplementation* Document::implementation()
{
if (!m_implementation)
m_implementation = DOMImplementation::create(this);
return m_implementation.get();
}
bool Document::hasManifest() const
{
return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->hasAttribute(manifestAttr);
}
void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
Element* newDocumentElement = ElementTraversal::firstWithin(this);
if (newDocumentElement == m_documentElement)
return;
m_documentElement = newDocumentElement;
// The root style used for media query matching depends on the document element.
clearStyleResolver();
}
PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
{
if (!isValidName(name)) {
ec = INVALID_CHARACTER_ERR;
return 0;
}
if (isXHTMLDocument())
return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
return createElement(QualifiedName(nullAtom, name, nullAtom), false);
}
#if ENABLE(CUSTOM_ELEMENTS)
PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionCode& ec)
{
if (!isValidName(localName)) {
ec = INVALID_CHARACTER_ERR;
return 0;
}
if (m_registry) {
if (PassRefPtr<Element> created = m_registry->createElement(QualifiedName(nullAtom, localName, xhtmlNamespaceURI), typeExtension))
return created;
}
return setTypeExtension(createElement(localName, ec), typeExtension);
}
PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const String& qualifiedName, const AtomicString& typeExtension, ExceptionCode& ec)
{
String prefix, localName;
if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
return 0;
QualifiedName qName(prefix, localName, namespaceURI);
if (!hasValidNamespaceForElements(qName)) {
ec = NAMESPACE_ERR;
return 0;
}
if (m_registry) {
if (PassRefPtr<Element> created = m_registry->createElement(qName, typeExtension))
return created;
}
return setTypeExtension(createElementNS(namespaceURI, qualifiedName, ec), typeExtension);
}
PassRefPtr<CustomElementConstructor> Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, ExceptionCode& ec)
{
return registerElement(state, name, Dictionary(), ec);
}
PassRefPtr<CustomElementConstructor> Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, const Dictionary& options, ExceptionCode& ec)
{
if (!isHTMLDocument() && !isXHTMLDocument()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
if (!m_registry)
m_registry = adoptRef(new CustomElementRegistry(this));
return m_registry->registerElement(state, name, options, ec);
}
void Document::didCreateCustomElement(Element* element, CustomElementConstructor* constructor)
{
// m_registry is cleared Document::dispose() and can be null here.
if (m_registry)
m_registry->didCreateElement(element);
}
#endif // ENABLE(CUSTOM_ELEMENTS)
PassRefPtr<DocumentFragment> Document::createDocumentFragment()
{
return DocumentFragment::create(document());
}
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, ExceptionCode& ec)
{
if (isHTMLDocument()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return CDATASection::create(this, data);
}
PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
{
if (!isValidName(target)) {
ec = INVALID_CHARACTER_ERR;
return 0;
}
if (isHTMLDocument()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return ProcessingInstruction::create(this, target, data);
}
PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
{
if (!isValidName(name)) {
ec = INVALID_CHARACTER_ERR;
return 0;
}
if (isHTMLDocument()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return EntityReference::create(this, name);
}
PassRefPtr<Text> Document::createEditingTextNode(const String& text)
{
return Text::createEditingText(this, text);
}
PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
{
return MutableStylePropertySet::create()->ensureCSSStyleDeclaration();
}
PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
{
ec = 0;
if (!importedNode) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
switch (importedNode->nodeType()) {
case TEXT_NODE:
return createTextNode(importedNode->nodeValue());
case CDATA_SECTION_NODE:
return createCDATASection(importedNode->nodeValue(), ec);
case ENTITY_REFERENCE_NODE:
return createEntityReference(importedNode->nodeName(), ec);
case PROCESSING_INSTRUCTION_NODE:
return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
case COMMENT_NODE:
return createComment(importedNode->nodeValue());
case ELEMENT_NODE: {
Element* oldElement = toElement(importedNode);
// FIXME: The following check might be unnecessary. Is it possible that
// oldElement has mismatched prefix/namespace?
if (!hasValidNamespaceForElements(oldElement->tagQName())) {
ec = NAMESPACE_ERR;
return 0;
}
RefPtr<Element> newElement = createElement(oldElement->tagQName(), false);
newElement->cloneDataFromElement(*oldElement);
if (deep) {
for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
RefPtr<Node> newChild = importNode(oldChild, true, ec);
if (ec)
return 0;
newElement->appendChild(newChild.release(), ec);
if (ec)
return 0;
}
}
return newElement.release();
}
case ATTRIBUTE_NODE:
return Attr::create(this, QualifiedName(nullAtom, static_cast<Attr*>(importedNode)->name(), nullAtom), static_cast<Attr*>(importedNode)->value());
case DOCUMENT_FRAGMENT_NODE: {
if (importedNode->isShadowRoot()) {
// ShadowRoot nodes should not be explicitly importable.
// Either they are imported along with their host node, or created implicitly.
break;
}
DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
RefPtr<DocumentFragment> newFragment = createDocumentFragment();
if (deep) {
for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
RefPtr<Node> newChild = importNode(oldChild, true, ec);
if (ec)
return 0;
newFragment->appendChild(newChild.release(), ec);
if (ec)
return 0;
}
}
return newFragment.release();
}
case ENTITY_NODE:
case NOTATION_NODE:
// FIXME: It should be possible to import these node types, however in DOM3 the DocumentType is readonly, so there isn't much sense in doing that.
// Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
case DOCUMENT_NODE:
case DOCUMENT_TYPE_NODE:
case XPATH_NAMESPACE_NODE:
break;
}
ec = NOT_SUPPORTED_ERR;
return 0;
}
PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
{
if (!source) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
if (source->isReadOnlyNode()) {
ec = NO_MODIFICATION_ALLOWED_ERR;
return 0;
}
EventQueueScope scope;
switch (source->nodeType()) {
case ENTITY_NODE:
case NOTATION_NODE:
case DOCUMENT_NODE:
case DOCUMENT_TYPE_NODE:
case XPATH_NAMESPACE_NODE:
ec = NOT_SUPPORTED_ERR;
return 0;
case ATTRIBUTE_NODE: {
Attr* attr = static_cast<Attr*>(source.get());
if (attr->ownerElement())
attr->ownerElement()->removeAttributeNode(attr, ec);
attr->setSpecified(true);
break;
}
default:
if (source->isShadowRoot()) {
// ShadowRoot cannot disconnect itself from the host node.
ec = HIERARCHY_REQUEST_ERR;
return 0;
}
if (source->isFrameOwnerElement()) {
HTMLFrameOwnerElement* frameOwnerElement = toFrameOwnerElement(source.get());
if (frame() && frame()->tree()->isDescendantOf(frameOwnerElement->contentFrame())) {
ec = HIERARCHY_REQUEST_ERR;
return 0;
}
}
if (source->parentNode()) {
source->parentNode()->removeChild(source.get(), ec);
if (ec)
return 0;
}
}
this->adoptIfNeeded(source.get());
return source;
}
bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
{
// These checks are from DOM Core Level 2, createElementNS
// http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
return false;
if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
return false;
// Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
// http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
// createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
return false;
return true;
}
bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
{
// Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS
if (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom) {
// Note: The case of an "xmlns" qualified name with a namespace of
// xmlnsNamespaceURI is specifically allowed (See <http://www.w3.org/2000/xmlns/>).
return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
}
return hasValidNamespaceForElements(qName);
}
// FIXME: This should really be in a possible ElementFactory class
PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
{
RefPtr<Element> e;
// FIXME: Use registered namespaces and look up in a hash to find the right factory.
if (qName.namespaceURI() == xhtmlNamespaceURI)
e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
#if ENABLE(SVG)
else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
#endif
#if ENABLE(MATHML)
else if (qName.namespaceURI() == MathMLNames::mathmlNamespaceURI)
e = MathMLElementFactory::createMathMLElement(qName, this, createdByParser);
#endif
if (e)
m_sawElementsInKnownNamespaces = true;
else
e = Element::create(qName, document());
// <image> uses imgTag so we need a special rule.
ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
return e.release();
}
bool Document::regionBasedColumnsEnabled() const
{
return settings() && settings()->regionBasedColumnsEnabled();
}
bool Document::cssStickyPositionEnabled() const
{
return settings() && settings()->cssStickyPositionEnabled();
}
bool Document::cssRegionsEnabled() const
{
return RuntimeEnabledFeatures::cssRegionsEnabled();
}
bool Document::cssCompositingEnabled() const
{
return RuntimeEnabledFeatures::cssCompositingEnabled();
}
bool Document::cssGridLayoutEnabled() const
{
return settings() && settings()->cssGridLayoutEnabled();
}
#if ENABLE(CSS_REGIONS)
PassRefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
{
if (!cssRegionsEnabled() || !renderer())
return 0;
updateStyleIfNeeded();
return namedFlows()->createCSSOMSnapshot();
}
#endif
NamedFlowCollection* Document::namedFlows()
{
if (!m_namedFlows)
m_namedFlows = NamedFlowCollection::create(this);
return m_namedFlows.get();
}
PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
{
String prefix, localName;
if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
return 0;
QualifiedName qName(prefix, localName, namespaceURI);
if (!hasValidNamespaceForElements(qName)) {
ec = NAMESPACE_ERR;
return 0;
}
return createElement(qName, false);
}
String Document::readyState() const
{
DEFINE_STATIC_LOCAL(const String, loading, (ASCIILiteral("loading")));
DEFINE_STATIC_LOCAL(const String, interactive, (ASCIILiteral("interactive")));
DEFINE_STATIC_LOCAL(const String, complete, (ASCIILiteral("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();
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(eventNames().readystatechangeEvent, false, false));
if (settings() && settings()->suppressesIncrementalRendering())
setVisualUpdatesAllowed(readyState);
}
void Document::setVisualUpdatesAllowed(ReadyState readyState)
{
ASSERT(settings() && settings()->suppressesIncrementalRendering());
switch (readyState) {
case Loading:
ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
ASSERT(m_visualUpdatesAllowed);
m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
setVisualUpdatesAllowed(false);
break;
case Interactive:
ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
break;
case Complete:
if (m_visualUpdatesSuppressionTimer.isActive()) {
ASSERT(!m_visualUpdatesAllowed);
m_visualUpdatesSuppressionTimer.stop();
setVisualUpdatesAllowed(true);
} else
ASSERT(m_visualUpdatesAllowed);
break;
}
}
void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
{
if (m_visualUpdatesAllowed == visualUpdatesAllowed)
return;
m_visualUpdatesAllowed = visualUpdatesAllowed;
if (!visualUpdatesAllowed)
return;
FrameView* frameView = view();
bool needsLayout = frameView && renderer() && (frameView->layoutPending() || renderer()->needsLayout());
if (needsLayout)
updateLayout();
if (Page* page = this->page()) {
if (frame() == page->mainFrame())
frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
frame()->loader()->didLayout(DidFirstLayoutAfterSuppressedIncrementalRendering);
}
#if USE(ACCELERATED_COMPOSITING)
if (view())
view()->updateCompositingLayersAfterLayout();
#endif
if (RenderView* renderView = this->renderView())
renderView->repaintViewAndCompositedLayers();
}
void Document::visualUpdatesSuppressionTimerFired(Timer<Document>*)
{
ASSERT(!m_visualUpdatesAllowed);
setVisualUpdatesAllowed(true);
}
String Document::encoding() const
{
if (TextResourceDecoder* d = decoder())
return d->encoding().domName();
return String();
}
String Document::defaultCharset() const
{
if (Settings* settings = this->settings())
return settings->defaultTextEncodingName();
return String();
}
void Document::setCharset(const String& charset)
{
if (!decoder())
return;
decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
}
void Document::setContentLanguage(const String& language)
{
if (m_contentLanguage == language)
return;
m_contentLanguage = language;
// Recalculate style so language is used when selecting the initial font.
styleResolverChanged(DeferRecalcStyle);
}
void Document::setXMLVersion(const String& version, ExceptionCode& ec)
{
if (!implementation()->hasFeature("XML", String())) {
ec = NOT_SUPPORTED_ERR;
return;
}
if (!XMLDocumentParser::supportsXMLVersion(version)) {
ec = NOT_SUPPORTED_ERR;
return;
}
m_xmlVersion = version;
}
void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
{
if (!implementation()->hasFeature("XML", String())) {
ec = NOT_SUPPORTED_ERR;
return;
}
m_xmlStandalone = standalone ? Standalone : NotStandalone;
}
void Document::setDocumentURI(const String& uri)
{
// This property is read-only from JavaScript, but writable from Objective-C.
m_documentURI = uri;
updateBaseURL();
}
KURL Document::baseURI() const
{
return m_baseURL;
}
void Document::setContent(const String& content)
{
open();
// FIXME: This should probably use insert(), but that's (intentionally)
// not implemented for the XML parser as it's normally synonymous with
// document.write(). append() will end up yielding, but close() will
// pump the tokenizer syncrhonously and finish the parse.
m_parser->pinToMainThread();
m_parser->append(content.impl());
close();
}
String Document::suggestedMIMEType() const
{
if (isXHTMLDocument())
return "application/xhtml+xml";
if (isSVGDocument())
return "image/svg+xml";
if (xmlStandalone())
return "text/xml";
if (isHTMLDocument())
return "text/html";
if (DocumentLoader* documentLoader = loader())
return documentLoader->responseMIMEType();
return String();
}
Element* Document::elementFromPoint(int x, int y) const
{
if (!renderer())
return 0;
return TreeScope::elementFromPoint(x, y);
}
PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
{
if (!renderer())
return 0;
LayoutPoint localPoint;
Node* node = nodeFromPoint(this, x, y, &localPoint);
if (!node)
return 0;
Node* shadowAncestorNode = ancestorInThisScope(node);
if (shadowAncestorNode != node) {
unsigned offset = shadowAncestorNode->nodeIndex();
ContainerNode* container = shadowAncestorNode->parentNode();
return Range::create(this, container, offset, container, offset);
}
RenderObject* renderer = node->renderer();
if (!renderer)
return 0;
VisiblePosition visiblePosition = renderer->positionForPoint(localPoint);
if (visiblePosition.isNull())
return 0;
Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
return Range::create(this, rangeCompliantPosition, rangeCompliantPosition);
}
/*
* Performs three operations:
* 1. Convert control characters to spaces
* 2. Trim leading and trailing spaces
* 3. Collapse internal whitespace.
*/
template <typename CharacterType>
static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
{
const String& title = titleWithDirection.string();
const CharacterType* characters = title.getCharacters<CharacterType>();
unsigned length = title.length();
unsigned i;
StringBuffer<CharacterType> buffer(length);
unsigned builderIndex = 0;
// Skip leading spaces and leading characters that would convert to spaces
for (i = 0; i < length; ++i) {
CharacterType c = characters[i];
if (!(c <= 0x20 || c == 0x7F))
break;
}
if (i == length)
return StringWithDirection();
// Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
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;
}
}
// Strip trailing spaces
while (builderIndex > 0) {
--builderIndex;
if (buffer[builderIndex] != ' ')
break;
}
if (!builderIndex && buffer[builderIndex] == ' ')
return StringWithDirection();
buffer.shrink(builderIndex + 1);
// Replace the backslashes with currency symbols if the encoding requires it.
document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
}
void Document::updateTitle(const StringWithDirection& title)
{
if (m_rawTitle == title)
return;
m_rawTitle = title;
if (m_rawTitle.string().isEmpty())
m_title = StringWithDirection();
else {
if (m_rawTitle.string().is8Bit())
m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
else
m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
}
if (Frame* f = frame())
f->loader()->setTitle(m_title);
}
void Document::setTitle(const String& title)
{
// Title set by JavaScript -- overrides any title elements.
m_titleSetExplicitly = true;
if (!isHTMLDocument() && !isXHTMLDocument())
m_titleElement = 0;
else if (!m_titleElement) {
if (HTMLElement* headElement = head()) {
m_titleElement = createElement(titleTag, false);
headElement->appendChild(m_titleElement, ASSERT_NO_EXCEPTION);
}
}
// The DOM API has no method of specifying direction, so assume LTR.
updateTitle(StringWithDirection(title, LTR));
if (m_titleElement) {
ASSERT(m_titleElement->hasTagName(titleTag));
if (m_titleElement->hasTagName(titleTag))
static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(title);
}
}
void Document::setTitleElement(const StringWithDirection& title, Element* titleElement)
{
if (titleElement != m_titleElement) {
if (m_titleElement || m_titleSetExplicitly)
// Only allow the first title element to change the title -- others have no effect.
return;
m_titleElement = titleElement;
}
updateTitle(title);
}
void Document::removeTitle(Element* titleElement)
{
if (m_titleElement != titleElement)
return;
m_titleElement = 0;
m_titleSetExplicitly = false;
// Update title based on first title element in the head, if one exists.
if (HTMLElement* headElement = head()) {
for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
if (e->hasTagName(titleTag)) {
HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
setTitleElement(titleElement->textWithDirection(), titleElement);
break;
}
}
if (!m_titleElement)
updateTitle(StringWithDirection());
}
#if ENABLE(PAGE_VISIBILITY_API)
PageVisibilityState Document::visibilityState() const
{
// The visibility of the document is inherited from the visibility of the
// page. If there is no page associated with the document, we will assume
// that the page is hidden, as specified by the spec:
// http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
if (!m_frame || !m_frame->page())
return PageVisibilityStateHidden;
return m_frame->page()->visibilityState();
}
String Document::webkitVisibilityState() const
{
return pageVisibilityStateString(visibilityState());
}
bool Document::webkitHidden() const
{
return visibilityState() != PageVisibilityStateVisible;
}
void Document::dispatchVisibilityStateChangeEvent()
{
dispatchEvent(Event::create(eventNames().webkitvisibilitychangeEvent, false, false));
}
#endif
#if ENABLE(CSP_NEXT)
DOMSecurityPolicy* Document::securityPolicy()
{
if (!m_domSecurityPolicy)
m_domSecurityPolicy = DOMSecurityPolicy::create(this);
return m_domSecurityPolicy.get();
}
#endif
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.get();
}
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;
}
Settings* Document::settings() const
{
return m_frame ? m_frame->settings() : 0;
}
PassRefPtr<Range> Document::createRange()
{
return Range::create(this);
}
PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
{
if (!root) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
}
PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
{
if (!root) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
}
void Document::scheduleForcedStyleRecalc()
{
m_pendingStyleRecalcShouldForce = true;
scheduleStyleRecalc();
}
void Document::scheduleStyleRecalc()
{
if (shouldDisplaySeamlesslyWithParent()) {
// When we're seamless, our parent document manages our style recalcs.
ownerElement()->setNeedsStyleRecalc();
ownerElement()->document()->scheduleStyleRecalc();
return;
}
if (m_styleRecalcTimer.isActive() || inPageCache())
return;
ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
if (!documentsThatNeedStyleRecalc)
documentsThatNeedStyleRecalc = new HashSet<Document*>;
documentsThatNeedStyleRecalc->add(this);
// FIXME: Why on earth is this here? This is clearly misplaced.
invalidateAccessKeyMap();
m_styleRecalcTimer.startOneShot(0);
InspectorInstrumentation::didScheduleStyleRecalculation(this);
}
void Document::unscheduleStyleRecalc()
{
ASSERT(!childNeedsStyleRecalc());
if (documentsThatNeedStyleRecalc)
documentsThatNeedStyleRecalc->remove(this);
m_styleRecalcTimer.stop();
m_pendingStyleRecalcShouldForce = false;
}
bool Document::hasPendingStyleRecalc() const
{
return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
}
bool Document::hasPendingForcedStyleRecalc() const
{
return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
}
void Document::styleRecalcTimerFired(Timer<Document>*)
{
updateStyleIfNeeded();
}
bool Document::childNeedsAndNotInStyleRecalc()
{
return childNeedsStyleRecalc() && !m_inStyleRecalc;
}
void Document::recalcStyle(StyleChange change)
{
// we should not enter style recalc while painting
ASSERT(!view() || !view()->isPainting());
if (view() && view()->isPainting())
return;
if (m_inStyleRecalc)
return; // Guard against re-entrancy. -dwh
// FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
// however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
// before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
// resolves style (here) and then when we resolve style on the parent chain, we may end up
// re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
// hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
if (m_styleSheetCollection->needsUpdateActiveStylesheetsOnStyleRecalc())
m_styleSheetCollection->updateActiveStyleSheets(DocumentStyleSheetCollection::FullUpdate);
InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
m_styleSheetCollection->setUsesRemUnit(true);
m_inStyleRecalc = true;
{
PostAttachCallbackDisabler disabler(this);
WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
RefPtr<FrameView> frameView = view();
if (frameView) {
frameView->pauseScheduledEvents();
frameView->beginDeferredRepaints();
}
ASSERT(!renderer() || renderArena());
if (!renderer() || !renderArena())
goto bailOut;
if (m_pendingStyleRecalcShouldForce)
change = Force;
// Recalculating the root style (on the document) is not needed in the common case.
if ((change == Force) || (shouldDisplaySeamlesslyWithParent() && (change >= Inherit))) {
// style selector may set this again during recalc
m_hasNodesWithPlaceholderStyle = false;
RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(this, m_styleResolver ? m_styleResolver->fontSelector() : 0);
StyleChange ch = Node::diff(documentStyle.get(), renderer()->style(), this);
if (ch != NoChange)
renderer()->setStyle(documentStyle.release());
}
for (Node* n = firstChild(); n; n = n->nextSibling()) {
if (!n->isElementNode())
continue;
Element* element = toElement(n);
if (change >= Inherit || element->childNeedsStyleRecalc() || element->needsStyleRecalc())
element->recalcStyle(change);
}
#if USE(ACCELERATED_COMPOSITING)
if (view())
view()->updateCompositingLayersAfterStyleChange();
#endif
bailOut:
clearNeedsStyleRecalc();
clearChildNeedsStyleRecalc();
unscheduleStyleRecalc();
m_inStyleRecalc = false;
// Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
if (m_styleResolver)
m_styleSheetCollection->resetCSSFeatureFlags();
if (frameView) {
frameView->resumeScheduledEvents();
frameView->endDeferredRepaints();
}
}
// If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
if (m_closeAfterStyleRecalc) {
m_closeAfterStyleRecalc = false;
implicitClose();
}
InspectorInstrumentation::didRecalculateStyle(cookie);
}
void Document::updateStyleIfNeeded()
{
ASSERT(isMainThread());
ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
return;
AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
recalcStyle(NoChange);
}
void Document::updateStyleForAllDocuments()
{
ASSERT(isMainThread());
if (!documentsThatNeedStyleRecalc)
return;
while (documentsThatNeedStyleRecalc->size()) {
HashSet<Document*>::iterator it = documentsThatNeedStyleRecalc->begin();
Document* doc = *it;
documentsThatNeedStyleRecalc->remove(doc);
doc->updateStyleIfNeeded();
}
}
void Document::updateLayout()
{
ASSERT(isMainThread());
FrameView* frameView = view();
if (frameView && frameView->isInLayout()) {
// View layout should not be re-entrant.
ASSERT_NOT_REACHED();
return;
}
if (Element* oe = ownerElement())
oe->document()->updateLayout();
updateStyleIfNeeded();
StackStats::LayoutCheckPoint layoutCheckPoint;
// Only do a layout if changes have occurred that make it necessary.
if (frameView && renderer() && (frameView->layoutPending() || renderer()->needsLayout()))
frameView->layout();
}
// FIXME: This is a bad idea and needs to be removed eventually.
// Other browsers load stylesheets before they continue parsing the web page.
// Since we don't, we can run JavaScript code that needs answers before the
// stylesheets are loaded. Doing a layout ignoring the pending stylesheets
// lets us get reasonable answers. The long term solution to this problem is
// to instead suspend JavaScript execution.
void Document::updateLayoutIgnorePendingStylesheets()
{
bool oldIgnore = m_ignorePendingStylesheets;
if (!haveStylesheetsLoaded()) {
m_ignorePendingStylesheets = true;
// FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
// dangerous to try to stop it a second time, after page content has already been loaded and displayed
// with accurate style information. (Our suppression involves blanking the whole page at the
// moment. If it were more refined, we might be able to do something better.)
// It's worth noting though that this entire method is a hack, since what we really want to do is
// suspend JS instead of doing a layout with inaccurate information.
HTMLElement* bodyElement = body();
if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
m_pendingSheetLayout = DidLayoutWithPendingSheets;
styleResolverChanged(RecalcStyleImmediately);
} else if (m_hasNodesWithPlaceholderStyle)
// If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
// may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
// but here we need up-to-date style immediately.
recalcStyle(Force);
}
updateLayout();
m_ignorePendingStylesheets = oldIgnore;
}
PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
{
ASSERT_ARG(element, element->document() == this);
bool oldIgnore = m_ignorePendingStylesheets;
m_ignorePendingStylesheets = true;
RefPtr<RenderStyle> style = ensureStyleResolver()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
m_ignorePendingStylesheets = oldIgnore;
return style.release();
}
PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
{
RefPtr<RenderStyle> style = ensureStyleResolver()->styleForPage(pageIndex);
return style.release();
}
bool Document::isPageBoxVisible(int pageIndex)
{
RefPtr<RenderStyle> style = styleForPage(pageIndex);
return style->visibility() != HIDDEN; // display property doesn't apply to @page.
}
void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
{
RefPtr<RenderStyle> style = styleForPage(pageIndex);
RenderView* view = renderView();
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, view);
height = valueForLength(size.height(), 0, view);
break;
}
default:
ASSERT_NOT_REACHED();
}
pageSize = IntSize(width, height);
// The percentage is calculated with respect to the width even for margin top and bottom.
// http://www.w3.org/TR/CSS2/box.html#margin-properties
marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width, view);
marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width, view);
marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width, view);
marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width, view);
}
void Document::setIsViewSource(bool isViewSource)
{
m_isViewSource = isViewSource;
if (!m_isViewSource)
return;
setSecurityOrigin(SecurityOrigin::createUnique());
}
void Document::createStyleResolver()
{
bool matchAuthorAndUserStyles = true;
if (Settings* docSettings = settings())
matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
m_styleResolver = adoptPtr(new StyleResolver(this, matchAuthorAndUserStyles));
m_styleSheetCollection->combineCSSFeatureFlags();
}
void Document::clearStyleResolver()
{
m_styleResolver.clear();
}
void Document::attach()
{
ASSERT(!attached());
ASSERT(!m_inPageCache);
ASSERT(!m_axObjectCache || this != topDocument());
if (!m_renderArena)
m_renderArena = RenderArena::create();
// Create the rendering tree
setRenderer(new (m_renderArena.get()) RenderView(this));
#if USE(ACCELERATED_COMPOSITING)
renderView()->setIsInWindow(true);
#endif
recalcStyle(Force);
RenderObject* render = renderer();
setRenderer(0);
ContainerNode::attach();
setRenderer(render);
}
void Document::detach()
{
ASSERT(attached());
ASSERT(!m_inPageCache);
#if ENABLE(POINTER_LOCK)
if (page())
page()->pointerLockController()->documentDetached(this);
#endif
if (this == topDocument())
clearAXObjectCache();
stopActiveDOMObjects();
m_eventQueue->close();
#if ENABLE(FULLSCREEN_API)
m_fullScreenChangeEventTargetQueue.clear();
m_fullScreenErrorEventTargetQueue.clear();
#endif
#if ENABLE(REQUEST_ANIMATION_FRAME)
clearScriptedAnimationController();
#endif
RenderObject* render = renderer();
documentWillBecomeInactive();
#if ENABLE(SHARED_WORKERS)
SharedWorkerRepository::documentDetached(this);
#endif
if (m_frame) {
FrameView* view = m_frame->view();
if (view)
view->detachCustomScrollbars();
}
// indicate destruction mode, i.e. attached() but renderer == 0
setRenderer(0);
#if ENABLE(FULLSCREEN_API)
if (m_fullScreenRenderer)
setFullScreenRenderer(0);
#endif
m_hoverNode = 0;
m_focusedNode = 0;
m_activeElement = 0;
ContainerNode::detach();
unscheduleStyleRecalc();
if (render)
render->destroy();
#if ENABLE(TOUCH_EVENTS)
if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
parentDocument()->didRemoveEventTargetNode(this);
#endif
// This is required, as our Frame might delete itself as soon as it detaches
// us. However, this violates Node::detach() semantics, as it's never
// possible to re-attach. Eventually Document::detach() should be renamed,
// or this setting of the frame to 0 could be made explicit in each of the
// callers of Document::detach().
m_frame = 0;
m_renderArena.clear();
if (m_mediaQueryMatcher)
m_mediaQueryMatcher->documentDestroyed();
}
void Document::prepareForDestruction()
{
disconnectDescendantFrames();
if (DOMWindow* window = this->domWindow())
window->willDetachDocumentFromFrame();
detach();
}
void Document::removeAllEventListeners()
{
EventTarget::removeAllEventListeners();
if (DOMWindow* domWindow = this->domWindow())
domWindow->removeAllEventListeners();
for (Node* node = firstChild(); node; node = NodeTraversal::next(node))
node->removeAllEventListeners();
}
void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
{
ScriptExecutionContext::suspendActiveDOMObjects(why);
}
void Document::resumeActiveDOMObjects()
{
ScriptExecutionContext::resumeActiveDOMObjects();
}
void Document::clearAXObjectCache()
{
ASSERT(topDocument() == this);
// Clear the cache member variable before calling delete because attempts
// are made to access it during destruction.
m_axObjectCache.clear();
}
AXObjectCache* Document::existingAXObjectCache() const
{
if (!AXObjectCache::accessibilityEnabled())
return 0;
// If the renderer is gone then we are in the process of destruction.
// This method will be called before m_frame = 0.
if (!topDocument()->renderer())
return 0;
return topDocument()->m_axObjectCache.get();
}
AXObjectCache* Document::axObjectCache() const
{
if (!AXObjectCache::accessibilityEnabled())
return 0;
// The only document that actually has a AXObjectCache is the top-level
// document. This is because we need to be able to get from any WebCoreAXObject
// to any other WebCoreAXObject on the same page. Using a single cache allows
// lookups across nested webareas (i.e. multiple documents).
Document* topDocument = this->topDocument();
// If the document has already been detached, do not make a new axObjectCache.
if (!topDocument->renderer())
return 0;
ASSERT(topDocument == this || !m_axObjectCache);
if (!topDocument->m_axObjectCache)
topDocument->m_axObjectCache = adoptPtr(new AXObjectCache(topDocument));
return topDocument->m_axObjectCache.get();
}
void Document::setVisuallyOrdered()
{
m_visuallyOrdered = true;
if (renderer())
renderer()->style()->setRTLOrdering(VisualOrder);
}
PassRefPtr<DocumentParser> Document::createParser()
{
// FIXME: this should probably pass the frame instead
return XMLDocumentParser::create(this, view());
}
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()) {
// FIXME: HTML5 doesn't tell us to check this, it might not be correct.
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();
}
void Document::detachParser()
{
if (!m_parser)
return;
m_parser->detach();
m_parser.clear();
}
void Document::cancelParsing()
{
if (!m_parser)
return;
// We have to clear the parser to avoid possibly triggering
// the onload handler when closing as a side effect of a cancel-style
// change, such as opening a new document or closing the window while
// still parsing
detachParser();
explicitClose();
}
void Document::implicitOpen()
{
cancelParsing();
removeChildren();
setCompatibilityMode(NoQuirksMode);
// Documents rendered seamlessly should start out requiring a stylesheet
// collection update in order to ensure they inherit all the relevant data
// from their parent.
if (shouldDisplaySeamlesslyWithParent())
styleResolverChanged(DeferRecalcStyle);
m_parser = createParser();
setParsing(true);
setReadyState(Loading);
}
HTMLElement* Document::body() const
{
Node* de = documentElement();
if (!de)
return 0;
// try to prefer a FRAMESET element over BODY
Node* body = 0;
for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
if (i->hasTagName(framesetTag))
return toHTMLElement(i);
if (i->hasTagName(bodyTag) && !body)
body = i;
}
return toHTMLElement(body);
}
void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
{
RefPtr<HTMLElement> newBody = prpNewBody;
if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
ec = HIERARCHY_REQUEST_ERR;
return;
}
if (newBody->document() && newBody->document() != this) {
ec = 0;
RefPtr<Node> node = importNode(newBody.get(), true, ec);
if (ec)
return;
newBody = toHTMLElement(node.get());
}
HTMLElement* b = body();
if (!b)
documentElement()->appendChild(newBody.release(), ec);
else
documentElement()->replaceChild(newBody.release(), b, ec);
}
HTMLHeadElement* Document::head()
{
Node* de = documentElement();
if (!de)
return 0;
for (Node* e = de->firstChild(); e; e = e->nextSibling())
if (e->hasTagName(headTag))
return static_cast<HTMLHeadElement*>(e);
return 0;
}
void Document::close()
{
// FIXME: We should follow the specification more closely:
// http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
return;
explicitClose();
}
void Document::explicitClose()
{
if (RefPtr<DocumentParser> parser = m_parser)
parser->finish();
if (!m_frame) {
// Because we have no frame, we don't know if all loading has completed,
// so we just call implicitClose() immediately. FIXME: This might fire
// the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
implicitClose();
return;
}
m_frame->loader()->checkCompleted();
}
void Document::implicitClose()
{
// If we're in the middle of recalcStyle, we need to defer the close until the style information is accurate and all elements are re-attached.
if (m_inStyleRecalc) {
m_closeAfterStyleRecalc = true;
return;
}
bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
if (!doload)
return;
// Call to dispatchWindowLoadEvent can blow us from underneath.
RefPtr<Document> protect(this);
m_processingLoadEvent = true;
ScriptableDocumentParser* parser = scriptableDocumentParser();
m_wellFormed = parser && parser->wellFormed();
// We have to clear the parser, in case someone document.write()s from the
// onLoad event handler, as in Radar 3206524.
detachParser();
// FIXME: We kick off the icon loader when the Document is done parsing.
// There are earlier opportunities we could start it:
// -When the <head> finishes parsing
// -When any new HTMLLinkElement is inserted into the document
// But those add a dynamic component to the favicon that has UI
// ramifications, and we need to decide what is the Right Thing To Do(tm)
Frame* f = frame();
if (f) {
f->loader()->icon()->startLoader();
f->animation()->startAnimationsIfNotSuspended(this);
}
ImageLoader::dispatchPendingBeforeLoadEvents();
ImageLoader::dispatchPendingLoadEvents();
ImageLoader::dispatchPendingErrorEvents();
HTMLLinkElement::dispatchPendingLoadEvents();
HTMLStyleElement::dispatchPendingLoadEvents();
#if ENABLE(SVG)
// To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
// here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
// which is the default, for ='true' its fired at a later time, once all external resources finished loading).
if (svgExtensions())
accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
#endif
dispatchWindowLoadEvent();
enqueuePageshowEvent(PageshowEventNotPersisted);
enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
if (f)
f->loader()->handledOnloadEvents();
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("onload fired at %d\n", elapsedTime());
#endif
// An event handler may have removed the frame
if (!frame()) {
m_processingLoadEvent = false;
return;
}
// Make sure both the initial layout and reflow happen after the onload
// fires. This will improve onload scores, and other browsers do it.
// If they wanna cheat, we can too. -dwh
if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
// Just bail out. Before or during the onload we were shifted to another page.
// The old i-Bench suite does this. When this happens don't bother painting or laying out.
m_processingLoadEvent = false;
view()->unscheduleRelayout();
return;
}
frame()->loader()->checkCallImplicitClose();
// We used to force a synchronous display and flush here. This really isn't
// necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
// (if your platform is syncing flushes and limiting them to 60fps).
m_overMinimumLayoutThreshold = true;
if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
updateStyleIfNeeded();
// Always do a layout after loading if needed.
if (view() && renderer() && (!renderer()->firstChild() || renderer()->needsLayout()))
view()->layout();
}
m_processingLoadEvent = false;
#if PLATFORM(MAC)
if (f && renderer() && AXObjectCache::accessibilityEnabled()) {
// The AX cache may have been cleared at this point, but we need to make sure it contains an
// AX object to send the notification to. getOrCreate will make sure that an valid AX object
// exists in the cache (we ignore the return value because we don't need it here). This is
// only safe to call when a layout is not in progress, so it can not be used in postNotification.
axObjectCache()->getOrCreate(renderer());
if (this == topDocument())
axObjectCache()->postNotification(renderer(), AXObjectCache::AXLoadComplete, true);
else {
// AXLoadComplete can only be posted on the top document, so if it's a document
// in an iframe that just finished loading, post AXLayoutComplete instead.
axObjectCache()->postNotification(renderer(), AXObjectCache::AXLayoutComplete, true);
}
}
#endif
#if ENABLE(SVG)
if (svgExtensions())
accessSVGExtensions()->startAnimations();
#endif
}
void Document::setParsing(bool b)
{
m_bParsing = b;
if (m_bParsing && !m_sharedObjectPool)
m_sharedObjectPool = DocumentSharedObjectPool::create();
if (!m_bParsing && view())
view()->scheduleRelayout();
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement() && !m_bParsing)
printf("Parsing finished at %d\n", elapsedTime());
#endif
}
bool Document::shouldScheduleLayout()
{
// This function will only be called when FrameView thinks a layout is needed.
// This enforces a couple extra rules.
//
// (a) Only schedule a layout once the stylesheets are loaded.
// (b) Only schedule layout once we have a body element.
return (haveStylesheetsLoaded() && body())
|| (documentElement() && !documentElement()->hasTagName(htmlTag));
}
bool Document::isLayoutTimerActive()
{
return view() && view()->layoutPending() && !minimumLayoutDelay();
}
int Document::minimumLayoutDelay()
{
if (m_overMinimumLayoutThreshold)
return 0;
int elapsed = elapsedTime();
m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
// We'll want to schedule the timer to fire at the minimum layout threshold.
return max(0, cLayoutScheduleThreshold - elapsed);
}
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;
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Beginning a document.write at %d\n", elapsedTime());
#endif
bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
return;
if (!hasInsertionPoint)
open(ownerDocument);
ASSERT(m_parser);
m_parser->insert(text);
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Ending a document.write at %d\n", elapsedTime());
#endif
}
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::minimumTimerInterval() const
{
Page* p = page();
if (!p)
return ScriptExecutionContext::minimumTimerInterval();
return p->settings()->minDOMTimerInterval();
}
double Document::timerAlignmentInterval() const
{
Page* p = page();
if (!p)
return ScriptExecutionContext::timerAlignmentInterval();
return p->settings()->domTimerAlignmentInterval();
}
EventTarget* Document::errorEventTarget()
{
return domWindow();
}
void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
{
addMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, columnNumber, callStack);
}
void Document::setURL(const KURL& url)
{
const KURL& newURL = url.isEmpty() ? blankURL() : url;
if (newURL == m_url)
return;
m_url = newURL;
m_documentURI = m_url.string();
updateBaseURL();
contextFeatures()->urlDidChange(this);
}
void Document::updateBaseURL()
{
KURL oldBaseURL = m_baseURL;
// DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
// first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
// from the Document interface otherwise.
if (!m_baseElementURL.isEmpty())
m_baseURL = m_baseElementURL;
else if (!m_baseURLOverride.isEmpty())
m_baseURL = m_baseURLOverride;
else {
// The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
// this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
// and DOM 3 Core does not specify how it should be resolved.
m_baseURL = KURL(ParsedURLString, documentURI());
}
selectorQueryCache()->invalidate();
if (!m_baseURL.isValid())
m_baseURL = KURL();
if (m_elemSheet) {
// Element sheet is silly. It never contains anything.
ASSERT(!m_elemSheet->contents()->ruleCount());
bool usesRemUnits = m_elemSheet->contents()->usesRemUnits();
m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
// FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
m_elemSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
}
if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
// Base URL change changes any relative visited links.
// FIXME: There are other URLs in the tree that would need to be re-evaluated on dynamic base URL change. Style should be invalidated too.
for (Element* element = ElementTraversal::firstWithin(this); element; element = ElementTraversal::next(element)) {
if (element->hasTagName(aTag))
static_cast<HTMLAnchorElement*>(element)->invalidateCachedVisitedLinkHash();
}
}
}
void Document::setBaseURLOverride(const KURL& url)
{
m_baseURLOverride = url;
updateBaseURL();
}
void Document::processBaseElement()
{
// Find the first href attribute in a base element and the first target attribute in a base element.
const AtomicString* href = 0;
const AtomicString* target = 0;
for (Element* element = ElementTraversal::firstWithin(this); element && (!href || !target); element = ElementTraversal::next(element)) {
if (element->hasTagName(baseTag)) {
if (!href) {
const AtomicString& value = element->fastGetAttribute(hrefAttr);
if (!value.isNull())
href = &value;
}
if (!target) {
const AtomicString& value = element->fastGetAttribute(targetAttr);
if (!value.isNull())
target = &value;
}
}
}
// FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
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(Frame* targetFrame)
{
if (!m_frame)
return false;
// FIXME: We shouldn't call this function without a target frame, but
// fast/forms/submit-to-blank-multiple-times.html depends on this function
// returning true when supplied with a 0 targetFrame.
if (!targetFrame)
return true;
// Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
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;
}
// This is the normal case. A document can navigate its decendant frames,
// or, more generally, a document can navigate a frame if the document is
// in the same origin as any of that frame's ancestors (in the frame
// hierarchy).
//
// See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
// historical information about this security check.
if (canAccessAncestor(securityOrigin(), targetFrame))
return true;
// Top-level frames are easier to navigate than other frames because they
// display their URLs in the address bar (in most browsers). However, there
// are still some restrictions on navigation to avoid nuisance attacks.
// Specifically, a document can navigate a top-level frame if that frame
// opened the document or if the document is the same-origin with any of
// the top-level frame's opener's ancestors (in the frame hierarchy).
//
// In both of these cases, the document performing the navigation is in
// some way related to the frame being navigate (e.g., by the "opener"
// and/or "parent" relation). Requiring some sort of relation prevents a
// document from navigating arbitrary, unrelated top-level frames.
if (!targetFrame->tree()->parent()) {
if (targetFrame == m_frame->loader()->opener())
return true;
if (canAccessAncestor(securityOrigin(), 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;
}
Frame* Document::findUnsafeParentScrollPropagationBoundary()
{
Frame* currentFrame = m_frame;
if (!currentFrame)
return 0;
Frame* ancestorFrame = currentFrame->tree()->parent();
while (ancestorFrame) {
if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
return currentFrame;
currentFrame = ancestorFrame;
ancestorFrame = ancestorFrame->tree()->parent();
}
return 0;
}
void Document::seamlessParentUpdatedStylesheets()
{
styleResolverChanged(RecalcStyleImmediately);
}
void Document::didRemoveAllPendingStylesheet()
{
m_needsNotifyRemoveAllPendingStylesheet = false;
styleResolverChanged(RecalcStyleIfNeeded);
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->executeScriptsWaitingForStylesheets();
if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
view()->scrollToFragment(m_url);
}
CSSStyleSheet* Document::elementSheet()
{
if (!m_elemSheet)
m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
return m_elemSheet.get();
}
int Document::nodeAbsIndex(Node *node)
{
ASSERT(node->document() == this);
int absIndex = 0;
for (Node* n = node; n && n != this; n = NodeTraversal::previous(n))
absIndex++;
return absIndex;
}
Node* Document::nodeWithAbsIndex(int absIndex)
{
Node* n = this;
for (int i = 0; n && (i < absIndex); i++)
n = NodeTraversal::next(n);
return n;
}
void Document::processHttpEquiv(const String& equiv, const String& content)
{
ASSERT(!equiv.isNull() && !content.isNull());
Frame* frame = this->frame();
if (equalIgnoringCase(equiv, "default-style")) {
// The preferred style set has been overridden as per section
// 14.3.2 of the HTML4.0 specification. We need to update the
// sheet used variable and then update our style selector.
// For more info, see the test at:
// http://www.hixie.ch/tests/evil/css/import/main/preferred.html
// -dwh
m_styleSheetCollection->setSelectedStylesheetSetName(content);
m_styleSheetCollection->setPreferredStylesheetSetName(content);
styleResolverChanged(DeferRecalcStyle);
} else if (equalIgnoringCase(equiv, "refresh")) {
double delay;
String url;
if (frame && parseHTTPRefresh(content, true, delay, url)) {
if (url.isEmpty())
url = m_url.string();
else
url = completeURL(url).string();
frame->navigationScheduler()->scheduleRedirect(delay, url);
}
} else if (equalIgnoringCase(equiv, "set-cookie")) {
// FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
if (isHTMLDocument()) {
// Exception (for sandboxed documents) ignored.
toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
}
} 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")) {
if (frame) {
FrameLoader* frameLoader = frame->loader();
unsigned long requestIdentifier = 0;
if (frameLoader->activeDocumentLoader() && frameLoader->activeDocumentLoader()->mainResourceLoader())
requestIdentifier = frameLoader->activeDocumentLoader()->mainResourceLoader()->identifier();
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();
// Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
// intent, we must navigate away from the possibly partially-rendered document to a location that
// doesn't inherit the parent's SecurityOrigin.
frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
}
}
} else if (equalIgnoringCase(equiv, "content-security-policy"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report);
else if (equalIgnoringCase(equiv, "x-webkit-csp"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedEnforce);
else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedReport);
}
// Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
static bool isSeparator(UChar c)
{
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
}
void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
{
// Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
int keyBegin, keyEnd;
int valueBegin, valueEnd;
int i = 0;
int length = features.length();
String buffer = features.lower();
while (i < length) {
// skip to first non-separator, but don't skip past the end of the string
while (isSeparator(buffer[i])) {
if (i >= length)
break;
i++;
}
keyBegin = i;
// skip to first separator
while (!isSeparator(buffer[i]))
i++;
keyEnd = i;
// skip to first '=', but don't skip past a ',' or the end of the string
while (buffer[i] != '=') {
if (buffer[i] == ',' || i >= length)
break;
i++;
}
// skip to first non-separator, but don't skip past a ',' or the end of the string
while (isSeparator(buffer[i])) {
if (buffer[i] == ',' || i >= length)
break;
i++;
}
valueBegin = i;
// skip to first separator
while (!isSeparator(buffer[i]))
i++;
valueEnd = i;
ASSERT_WITH_SECURITY_IMPLICATION(i <= length);
String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
callback(keyString, valueString, this, data);
}
}
void Document::processViewport(const String& features, ViewportArguments::Type origin)
{
ASSERT(!features.isNull());
if (origin < m_viewportArguments.type)
return;
m_viewportArguments = ViewportArguments(origin);
processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
updateViewportArguments();
}
void Document::updateViewportArguments()
{
if (page() && page()->mainFrame() == frame()) {
#ifndef NDEBUG
m_didDispatchViewportPropertiesChanged = true;
#endif
page()->chrome()->dispatchViewportPropertiesDidChange(m_viewportArguments);
}
}
void Document::processReferrerPolicy(const String& policy)
{
ASSERT(!policy.isNull());
m_referrerPolicy = ReferrerPolicyDefault;
if (equalIgnoringCase(policy, "never"))
m_referrerPolicy = ReferrerPolicyNever;
else if (equalIgnoringCase(policy, "always"))
m_referrerPolicy = ReferrerPolicyAlways;
else if (equalIgnoringCase(policy, "origin"))
m_referrerPolicy = ReferrerPolicyOrigin;
}
MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
{
ASSERT(!renderer() || renderer()->isRenderView());
if (!renderer())
return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
HitTestResult result(documentPoint);
renderView()->hitTest(request, result);
if (!request.readOnly())
updateHoverActiveState(request, result.innerElement(), &event);
return MouseEventWithHitTestResults(event, result);
}
// DOM Section 1.1.1
bool Document::childTypeAllowed(NodeType type) const
{
switch (type) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE:
case ENTITY_NODE:
case ENTITY_REFERENCE_NODE:
case NOTATION_NODE:
case TEXT_NODE:
case XPATH_NAMESPACE_NODE:
return false;
case COMMENT_NODE:
case PROCESSING_INSTRUCTION_NODE:
return true;
case DOCUMENT_TYPE_NODE:
case ELEMENT_NODE:
// Documents may contain no more than one of each of these.
// (One Element and one DocumentType.)
for (Node* c = firstChild(); c; c = c->nextSibling())
if (c->nodeType() == type)
return false;
return true;
}
return false;
}
bool Document::canReplaceChild(Node* newChild, Node* oldChild)
{
if (!oldChild)
// ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
return true;
if (oldChild->nodeType() == newChild->nodeType())
return true;
int numDoctypes = 0;
int numElements = 0;
// First, check how many doctypes and elements we have, not counting
// the child we're about to remove.
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;
}
}
// Then, see how many doctypes and elements might be added by the new child.
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: