blob: 69acf2ad06143ce7bc68424a4fc1d7de35bd9649 [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 "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/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/DOMNamedFlowCollection.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/NamedFlowCollection.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/PostAttachCallbacks.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/events/ThreadLocalEventNames.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/frame/ContentSecurityPolicy.h"
#include "core/frame/DOMWindow.h"
#include "core/frame/Frame.h"
#include "core/frame/FrameHost.h"
#include "core/frame/FrameView.h"
#include "core/frame/History.h"
#include "core/frame/PageConsole.h"
#include "core/frame/Settings.h"
#include "core/html/HTMLAllCollection.h"
#include "core/html/HTMLAnchorElement.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/HTMLImport.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLLinkElement.h"
#include "core/html/HTMLNameCollection.h"
#include "core/html/HTMLScriptElement.h"
#include "core/html/HTMLStyleElement.h"
#include "core/html/HTMLTitleElement.h"
#include "core/html/PluginDocument.h"
#include "core/html/forms/FormController.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/RenderWidget.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/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;
// 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* 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, 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(const 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.domWindow()->printErrorMessage(message);
}
uint64_t Document::s_globalTreeVersion = 0;
// This class doesn't work with non-Document ExecutionContext.
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_bParsing(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_overMinimumLayoutThreshold(false)
, 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_lastHandledUserGestureTimestamp(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) {
provideContextFeaturesToDocumentFrom(this, m_frame->page());
m_fetcher = m_frame->loader().documentLoader()->fetcher();
}
if (!m_fetcher)
m_fetcher = ResourceFetcher::create(0);
m_fetcher->setDocument(this);
// 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 (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);
// Since CSSFontSelector requires Document::m_fetcher and StyleEngine owns
// CSSFontSelector, need to initialize m_styleEngine after initializing
// m_fetcher.
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; // balanced in ensureTemplateDocument().
m_scriptRunner.clear();
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();
if (this == topDocument())
clearAXObjectCache();
if (m_styleSheetList)
m_styleSheetList->detachFromDocument();
if (m_import) {
m_import->wasDetachedFromDocument();
m_import = 0;
}
m_styleEngine.clear(); // We need to destory CSSFontSelector before destroying m_fetcher.
if (m_elemSheet)
m_elemSheet->clearOwnerNode();
// It's possible for multiple Documents to end up referencing the same ResourceFetcher (e.g., SVGImages
// load the initial empty document and the SVGDocument with the same DocumentLoader).
if (m_fetcher->document() == this)
m_fetcher->setDocument(0);
m_fetcher.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]);
setClient(0);
InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
}
void Document::dispose()
{
ASSERT_WITH_SECURITY_IMPLICATION(!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_focusedElement = 0;
m_hoverNode = 0;
m_activeHoverElement = 0;
m_titleElement = 0;
m_documentElement = 0;
m_contextFeatures = ContextFeatures::defaultSwitch();
m_userActionElements.documentDidRemoveLastRef();
m_associatedFormControls.clear();
detachParser();
m_registrationContext.clear();
if (m_import) {
m_import->wasDetachedFromDocument();
m_import = 0;
}
// removeDetachedChildren() doesn't always unregister IDs,
// so tear down scope information upfront to avoid having stale references in the map.
destroyTreeScopeData();
removeDetachedChildren();
// removeDetachedChildren() can access FormController.
m_formController.clear();
m_markers->clear();
m_cssCanvasElements.clear();
// FIXME: consider using ActiveDOMObject.
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) {
// All injected stylesheets have to reparse using the different mode.
m_styleEngine->invalidateInjectedStyleSheetCache();
}
}
String Document::compatMode() const
{
return inQuirksMode() ? "BackCompat" : "CSS1Compat";
}
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);
if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
m_isMobileDocument = true;
}
// 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);
}
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);
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, ExceptionState& exceptionState)
{
if (!isValidName(name)) {
exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + name + "') is not a valid name.");
return 0;
}
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 0;
}
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 0;
}
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 0;
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 0;
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::ScriptState* state, const AtomicString& name, ExceptionState& exceptionState)
{
return registerElement(state, name, Dictionary(), exceptionState);
}
ScriptValue Document::registerElement(WebCore::ScriptState* state, 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(state, &options);
registrationContext()->registerElement(this, &constructorBuilder, name, validNames, exceptionState);
return constructorBuilder.bindingsReturnValue();
}
void Document::setImport(HTMLImport* import)
{
ASSERT(!m_import || !import);
m_import = import;
}
void Document::didLoadAllImports()
{
executeScriptsWaitingForResourcesIfNeeded();
}
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;
}
Frame* 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 0;
}
if (data.contains("]]>")) {
exceptionState.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
return 0;
}
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 0;
}
if (data.contains("?>")) {
exceptionState.throwDOMException(InvalidCharacterError, "The data provided ('" + data + "') contains '?>'.");
return 0;
}
return ProcessingInstruction::create(*this, target, data);
}
PassRefPtr<Text> Document::createEditingTextNode(const String& text)
{
return Text::createEditingText(*this, text);
}
PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& exceptionState)
{
if (!importedNode) {
exceptionState.throwDOMException(NotSupportedError, "The node provided is invalid.");
return 0;
}
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);
// FIXME: The following check might be unnecessary. Is it possible that
// oldElement has mismatched prefix/namespace?
if (!hasValidNamespaceForElements(oldElement->tagQName())) {
exceptionState.throwDOMException(NamespaceError, "The imported node has an invalid namespace.");
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, exceptionState);
if (exceptionState.hadException())
return 0;
newElement->appendChild(newChild.release(), exceptionState);
if (exceptionState.hadException())
return 0;
}
}
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()) {
// ShadowRoot nodes should not be explicitly importable.
// Either they are imported along with their host node, or created implicitly.
exceptionState.throwDOMException(NotSupportedError, "The node provided is a shadow root, which may not be imported.");
return 0;
}
DocumentFragment* oldFragment = toDocumentFragment(importedNode);
RefPtr<DocumentFragment> newFragment = createDocumentFragment();
if (deep) {
for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
RefPtr<Node> newChild = importNode(oldChild, true, exceptionState);
if (exceptionState.hadException())
return 0;
newFragment->appendChild(newChild.release(), exceptionState);
if (exceptionState.hadException())
return 0;
}
}
return newFragment.release();
}
case DOCUMENT_NODE:
exceptionState.throwDOMException(NotSupportedError, "The node provided is a document, which may not be imported.");
return 0;
}
ASSERT_NOT_REACHED();
return 0;
}
PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionState& exceptionState)
{
if (!source) {
exceptionState.throwDOMException(NotSupportedError, "The node provided is invalid.");
return 0;
}
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 0;
case ATTRIBUTE_NODE: {
Attr* attr = toAttr(source.get());
if (attr->ownerElement())
attr->ownerElement()->removeAttributeNode(attr, exceptionState);
break;
}
default:
if (source->isShadowRoot()) {
// ShadowRoot cannot disconnect itself from the host node.
exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a shadow root, which may not be adopted.");
return 0;
}
if (source->isFrameOwnerElement()) {
HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
if (frame() && frame()->tree().isDescendantOf(frameOwnerElement->contentFrame())) {
exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a frame which contains this document.");
return 0;
}
}
if (source->parentNode()) {
source->parentNode()->removeChild(source.get(), exceptionState);
if (exceptionState.hadException())
return 0;
}
}
this->adoptIfNeeded(*source);
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"), createElementNS(null, "xmlns")
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);
}
// 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.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();
}
PassRefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
{
if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderView())
return 0;
updateStyleIfNeeded();
return namedFlows()->createCSSOMSnapshot();
}
NamedFlowCollection* Document::namedFlows()
{
if (!m_namedFlows)
m_namedFlows = NamedFlowCollection::create(this);
return m_namedFlows.get();
}
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
{
// TextEncoding::name() returns a char*, no need to allocate a new
// String for it each time.
// FIXME: We should fix TextEncoding to speak AtomicString anyway.
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);
// In case the encoding didn't exist, we keep the old one (helps some sites specifying invalid encodings).
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;
// Document's style depends on the content 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();
// 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 (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();
}
Element* Document::elementFromPoint(int x, int y) const
{
if (!renderView())
return 0;
return TreeScope::elementFromPoint(x, y);
}
PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
{
if (!renderView())
return 0;
HitTestResult result = hitTestInDocument(this, x, y);
RenderObject* renderer = result.renderer();
if (!renderer)
return 0;
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 0;
Position rangeCompliantPosition = positionWithAffinity.position().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 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;
// 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 String();
// 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 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)
{
// 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 = HTMLTitleElement::create(*this);
headElement->appendChild(m_titleElement);
}
}
if (m_titleElement && m_titleElement->hasTagName(titleTag))
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)
// 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;
// FIXME: This is broken for SVG.
// Update title based on first title element in the head, if one exists.
if (HTMLElement* headElement = head()) {
for (Element* element = headElement->firstElementChild(); element; element = element->nextElementSibling()) {
if (!element->hasTagName(titleTag))
continue;
HTMLTitleElement* title = toHTMLTitleElement(element);
setTitleElement(title->text(), title);
break;
}
}
if (!m_titleElement)
updateTitle(String());
}
PageVisibilityState Document::pageVisibilityState() 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::visibilityState() const
{
return pageVisibilityStateString(pageVisibilityState());
}
bool Document::hidden() const
{
return pageVisibilityState() != PageVisibilityStateVisible;
}
void Document::didChangeVisibilityState()
{
dispatchEvent(Event::create(EventTypeNames::visibilitychange));
// Also send out the deprecated version until it can be removed.
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.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;
}
FrameHost* Document::frameHost() const
{
return m_frame ? m_frame->host() : 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, ExceptionState& exceptionState)
{
// FIXME: Probably this should be handled within the bindings layer and TypeError should be thrown.
if (!root) {
exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
return 0;
}
return NodeIterator::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
}
PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
{
if (!root) {
exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
return 0;
}
// FIXME: It might be a good idea to emit a warning if |whatToShow| contains a bit that is not defined in
// NodeFilter.
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, "The provided node is invalid.");
return 0;
}
// FIXME: Ditto.
return NodeIterator::create(root, whatToShow, filter);
}
PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionState& exceptionState)
{
if (!root) {
exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
return 0;
}
return TreeWalker::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
}
PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
{
if (!root) {
exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
return 0;
}
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, "The provided node is invalid.");
return 0;
}
return TreeWalker::create(root, whatToShow, filter);
}
bool Document::shouldCallRecalcStyleForDocument()
{
if (!isActive() || !view())
return false;
return needsStyleRecalc() || childNeedsStyleRecalc() || childNeedsDistributionRecalc() || !m_useElementsNeedingUpdate.isEmpty() || childNeedsStyleInvalidation();
}
bool Document::shouldScheduleStyleRecalc()
{
if (!isActive())
return false;
if (hasPendingStyleRecalc())
return false;
if (inStyleRecalc())
return false;
// InPreLayout will recalc style itself. There's no reason to schedule another recalc.
if (m_lifecycle.state() == DocumentLifecycle::InPreLayout)
return false;
if (!shouldScheduleLayout())
return false;
return true;
}
void Document::scheduleStyleRecalc()
{
if (!shouldScheduleStyleRecalc())
return;
ASSERT(shouldCallRecalcStyleForDocument());
if (!view()->isServicingAnimations())
view()->scheduleAnimation();
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 (!childNeedsStyleInvalidation())
return;
TRACE_EVENT0("webkit", "Document::computeNeedsStyleRecalcState");
if (!styleResolver()) {
clearChildNeedsStyleInvalidation();
return;
}
// FIXME: the style resolver can be deleted at present. Either resolve
// crbug.com/335964 or move the invalidation data elsewhere.
styleResolver()->ensureRuleFeatureSet().computeStyleInvalidation(*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;
}
}
// Resolved rem units are stored in the matched properties cache so we need to make sure to
// invalidate the cache if the documentElement needed to reattach or the font size changed
// and then trigger a full document recalc. We also need to clear it here since the
// call to styleForElement on the body above can cache bad values for rem units if the
// documentElement's style was dirty. We could keep track of which elements depend on
// rem units like we do for viewport styles, but we assume root font size changes are
// rare and just invalidate the cache for now.
if (styleEngine()->usesRemUnits() && (documentElement()->needsAttach() || documentElement()->computedStyle()->fontSize() != documentElementStyle->fontSize())) {
ensureStyleResolver().invalidateMatchedPropertiesCache();
documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
}
RefPtr<RenderStyle> documentStyle = renderView()->style();
if (documentStyle->writingMode() != rootWritingMode
|| documentStyle->direction() != rootDirection
|| (overflowStyle && (documentStyle->overflowX() != overflowStyle->overflowX() || documentStyle->overflowY() != overflowStyle->overflowY()))) {
RefPtr<RenderStyle> newStyle = RenderStyle::clone(documentStyle.get());
newStyle->setWritingMode(rootWritingMode);
newStyle->setDirection(rootDirection);
EOverflow overflowX = OAUTO;
EOverflow overflowY = OAUTO;
if (overflowStyle) {
overflowX = overflowStyle->overflowX();
overflowY = overflowStyle->overflowY();
// Visible overflow on the viewport is meaningless, and the spec says to treat it as 'auto':
if (overflowX == OVISIBLE)
overflowX = OAUTO;
if (overflowY == OVISIBLE)
overflowY = OAUTO;
// Column-gap is (ab)used by the current paged overflow implementation (in lack of other
// ways to specify gaps between pages), so we have to propagate it too.
newStyle->setColumnGap(overflowStyle->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);
}
}
// FIXME: We need a better name than updateStyleIfNeeded. It's performing style invalidation,
// style recalc, distribution and <use> shadow tree creation.
void Document::updateStyleIfNeeded()
{
ASSERT(isMainThread());
if (!shouldCallRecalcStyleForDocument())
return;
if (inStyleRecalc())
return;
// Entering here from inside layout or paint would be catastrophic since recalcStyle can
// tear down the render tree or (unfortunately) run script. Kill the whole renderer if
// someone managed to get into here from inside layout or paint.
RELEASE_ASSERT(!view()->isInPerformLayout());
RELEASE_ASSERT(!view()->isPainting());
// Script can run below in PostAttachCallbacks or WidgetUpdates, so protect the Frame.
RefPtr<Frame> protect(m_frame);
TRACE_EVENT0("webkit", "Document::recalcStyle");
TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "RecalcStyle");
InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
updateDistributionIfNeeded();
updateUseShadowTreesIfNeeded();
updateStyleInvalidationIfNeeded();
if (m_evaluateMediaQueriesOnStyleRecalc) {
m_evaluateMediaQueriesOnStyleRecalc = false;
evaluateMediaQueryList();
}
// FIXME: We should update style on our ancestor chain before proceeding
// 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_elemSheet && m_elemSheet->contents()->usesRemUnits())
m_styleEngine->setUsesRemUnit(true);
{
PostAttachCallbacks::SuspendScope suspendPostAttachCallbacks;
RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
m_lifecycle.advanceTo(DocumentLifecycle::InStyleRecalc);
StyleRecalcChange change = NoChange;
if (styleChangeType() >= SubtreeStyleChange)
change = Force;
// FIXME: Cannot access the ensureStyleResolver() before calling styleForDocument below because
// apparently the StyleResolver's constructor has side effects. We should fix it.
// See printing/setPrinting.html, printing/width-overflow.html though they only fail on
// mac when accessing the resolver by what appears to be a viewport size difference.
if (change == Force) {
m_hasNodesWithPlaceholderStyle = false;
RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this, m_styleEngine->fontSelector());
StyleRecalcChange localChange = RenderStyle::compare(documentStyle.get(), renderView()->style());
if (localChange != NoChange)
renderView()->setStyle(documentStyle.release());
}
clearNeedsStyleRecalc();
// Uncomment to enable printing of statistics about style sharing and the matched property cache.
// Optionally pass StyleResolver::ReportSlowStats to print numbers that require crawling the
// entire DOM (where collecting them is very slow).
// FIXME: Expose this as a runtime flag.
// ensureStyleResolver().enableStats(/*StyleResolver::ReportSlowStats*/);
if (StyleResolverStats* stats = ensureStyleResolver().stats())
stats->reset();
if (Element* documentElement = this->documentElement()) {
inheritHtmlAndBodyElementStyles(change);
if (documentElement->shouldCallRecalcStyle(change))
documentElement->recalcStyle(change);
}
ensureStyleResolver().printStats();
view()->updateCompositingLayersAfterStyleChange();
clearChildNeedsStyleRecalc();
if (m_styleEngine->hasResolver()) {
// Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
StyleResolver& resolver = m_styleEngine->ensureResolver();
m_styleEngine->resetCSSFeatureFlags(resolver.ensureRuleFeatureSet());
resolver.clearStyleSharingList();
}
ASSERT(!needsStyleRecalc());
ASSERT(!childNeedsStyleRecalc());
ASSERT(inStyleRecalc());
m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
}
// As a result of the style recalculation, the currently hovered element might have been
// detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
// to check if any other elements ended up under the mouse pointer due to re-layout.
if (hoverNode() && !hoverNode()->renderer() && frame())
frame()->eventHandler().dispatchFakeMouseMoveEventSoon();
if (m_focusedElement && !m_focusedElement->isFocusable())
clearFocusedElementSoon();
DocumentAnimations::serviceAfterStyleRecalc(*this);
InspectorInstrumentation::didRecalculateStyle(cookie);
}
void Document::updateStyleForNodeIfNeeded(Node* node)
{
if (!shouldCallRecalcStyleForDocument())
return;
// At this point, we know that we need to recalc some style on the document in order to fully update styles.
// However, style on 'node' only needs to be recalculated if a global recomputation is needed, or a node on
// the path from 'node' to the root needs style recalc.
// Global needed.
bool needsRecalc = needsStyleRecalc() || childNeedsDistributionRecalc() || !m_useElementsNeedingUpdate.isEmpty() || childNeedsStyleInvalidation();
// On the path.
for (Node* ancestor = node; ancestor && !needsRecalc; ancestor = ancestor->parentOrShadowHostNode())
needsRecalc = ancestor->needsStyleRecalc();
if (needsRecalc)
updateStyleIfNeeded();
}
void Document::updateLayout()
{
ASSERT(isMainThread());
RefPtr<FrameView> frameView = view();
if (frameView && frameView->isInPerformLayout()) {
// View layout should not be re-entrant.
ASSERT_NOT_REACHED();
return;
}
if (Element* oe = ownerElement())
oe->document().updateLayout();
updateStyleIfNeeded();
// Only do a layout if changes have occurred that make it necessary.
if (isActive() && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
frameView->layout();
if (isActive() && frameView)
frameView->partialLayout().reset();
}
void Document::setNeedsFocusedElementCheck()
{
setNeedsStyleRecalc(LocalStyleChange);
}
void Document::clearFocusedElementSoon()
{
if (!m_clearFocusedElementTimer.isActive())
m_clearFocusedElementTimer.startOneShot(0);
}
void Document::clearFocusedElementTimerFired(Timer<Document>*)
{
updateStyleIfNeeded();
m_clearFocusedElementTimer.stop();
if (m_focusedElement && !m_focusedElement->isFocusable())
setFocusedElement(0);
}
void Document::recalcStyleForLayoutIgnoringPendingStylesheets()
{
ASSERT(m_styleEngine->ignoringPendingStylesheets());
if (!m_styleEngine->hasPendingSheets())
return;
// 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.
setNeedsStyleRecalc(SubtreeStyleChange);
updateStyleIfNeeded();
}
}
// 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(Document::RunPostLayoutTasks runPostLayoutTasks)
{
StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
recalcStyleForLayoutIgnoringPendingStylesheets();
updateLayout();
if (runPostLayoutTasks == RunPostLayoutTasksSynchronously && view())
view()->flushAnyPendingPostLayoutTasks();
}
void Document::partialUpdateLayoutIgnorePendingStylesheets(Node* stopLayoutAtNode)
{
// Non-overlay scrollbars can cause a second layout that is dependent
// on a first layout. This is disabled for partial layout for now.
if (!RuntimeEnabledFeatures::partialLayoutEnabled() || !ScrollbarTheme::theme()->usesOverlayScrollbars()) {
updateLayoutIgnorePendingStylesheets();
return;
}
StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
recalcStyleForLayoutIgnoringPendingStylesheets();
if (stopLayoutAtNode) {
RenderObject* renderer = stopLayoutAtNode->renderer();
bool canPartialLayout = renderer;
while (renderer) {
if (!renderer->supportsPartialLayout()) {
canPartialLayout = false;
break;
}
renderer = renderer->parent();
}
if (canPartialLayout && view())
view()->partialLayout().setStopAtRenderer(stopLayoutAtNode->renderer());
}
updateLayout();
if (view())
view()->partialLayout().reset();
}
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; // 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);
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);
// 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);
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();
}
void Document::scheduleUseShadowTreeUpdate(SVGUseElement& element)
{
m_useElementsNeedingUpdate.add(&element);
scheduleStyleRecalc();
}
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);
m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
}
void Document::detach(const AttachContext& context)
{
ASSERT(isActive());
m_lifecycle.advanceTo(DocumentLifecycle::Stopping);
if (page())
page()->documentDetached(this);
if (m_frame->loader().client()->sharedWorkerRepositoryClient())
m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this);
if (this == topDocument())
clearAXObjectCache();
stopActiveDOMObjects();
// FIXME: consider using ActiveDOMObject.
if (m_scriptedAnimationController)
m_scriptedAnimationController->clearDocumentPointer();
m_scriptedAnimationController.clear();
if (svgExtensions())
accessSVGExtensions()->pauseAnimations();
// FIXME: This shouldn't be needed once DOMWindow becomes ExecutionContext.
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();
}
// Indicate destruction mode by setting the renderer to null.
// FIXME: Don't do this and use m_lifecycle.state() == Stopping instead.
setRenderer(0);
m_renderView = 0;
m_hoverNode = 0;
m_focusedElement = 0;
m_activeHoverElement = 0;
m_autofocusElement = 0;
ContainerNode::detach(context);
m_styleEngine->didDetach();
if (renderView)
renderView->destroy();
if (Document* parentDoc = parentDocument())
parentDoc->didClearTouchEventHandlers(this);
// 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;
if (m_mediaQueryMatcher)
m_mediaQueryMatcher->documentDestroyed();
lifecycleNotifier().notifyDocumentWasDetached();
m_lifecycle.advanceTo(DocumentLifecycle::Stopped);
}
void Document::prepareForDestruction()
{
m_markers->prepareForDestruction();
disconnectDescendantFrames();
// The process of disconnecting descendant frames could have already detached us.
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);
// 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()->renderView())
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->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);
}
// FIXME: this should probably pass the frame instead
return XMLDocumentParser::create(this, view());
}
bool Document::isFrameSet() const
{
if (!isHTMLDocument())
return false;
HTMLElement* bodyElement = body();
return bodyElement && bodyElement->hasTagName(framesetTag);
}
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();
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;
// 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();
}
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 (Node* child = documentElement()->firstChild(); child; child = child->nextSibling()) {
if (child->hasTagName(framesetTag) || child->hasTagName(bodyTag))
return toHTMLElement(child);
}
return 0;
}
void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionState& exceptionState)
{
RefPtr<HTMLElement> newBody = prpNewBody;
if (!newBody) {
exceptionState.throwDOMException(HierarchyRequestError, "The node provided is invalid.");
return;
}
if (!documentElement()) {
exceptionState.throwDOMException(HierarchyRequestError, "No document element exists.");
return;
}
if (!newBody->hasTagName(bodyTag) && !newBody->hasTagName(framesetTag)) {
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;
for (Node* node = de->firstChild(); node; node = node->nextSibling()) {
if (node->hasTagName(headTag))
return toHTMLHeadElement(node);
}
return 0;
}
Element* Document::viewportDefiningElement(RenderStyle* rootStyle) const
{
// If a BODY element sets non-visible overflow, it is to be propagated to the viewport, as long
// as the following conditions are all met:
// (1) The root element is HTML.
// (2) It is the primary BODY element (we only assert for this, expecting callers to behave).
// (3) The root element has visible overflow.
// Otherwise it's the root element's properties that are to be propagated.
Element* rootElement = documentElement();
Element* bodyElement = body();
if (!rootElement)
return 0;
if (!rootStyle) {
rootStyle = rootElement->renderStyle();
if (!rootStyle)
return 0;
}
if (bodyElement && rootStyle->isOverflowVisible() && rootElement->hasTagName(htmlTag))
return bodyElement;
return rootElement;
}
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()
{
ASSERT(!inStyleRecalc());
bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
bool doload = !parsing() && m_parser && !processingLoadEvent() && !wasLocationChangePending;
// If the load was blocked because of a pending location change and the location change triggers a same document
// navigation, don't fire load events after the same document navigation completes (unless there's an explicit open).
m_loadEventProgress = LoadEventTried;
if (!doload)
return;
// The call to dispatchWindowLoadEvent can detach the DOMWindow and cause it (and its
// attached Document) to be destroyed.
RefPtr<DOMWindow> protectedWindow(this->domWindow());
m_loadEventProgress = LoadEventInProgress;
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();
if (frame() && frame()->script().canExecuteScripts(NotAboutToExecuteScript)) {
ImageLoader::dispatchPendingBeforeLoadEvents();
ImageLoader::dispatchPendingLoadEvents();
ImageLoader::dispatchPendingErrorEvents();
HTMLLinkElement::dispatchPendingLoadEvents();
HTMLStyleElement::dispatchPendingLoadEvents();
}
// JS running below could remove the frame or destroy the RenderView so we call
// those two functions repeatedly and don't save them on the stack.
// 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 (svgExtensions())
accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
if (protectedWindow)
protectedWindow->documentWasClosed();
if (frame()) {
frame()->loader().client()->dispatchDidHandleOnloadEvents();
loader()->applicationCacheHost()->stopDeferringEvents();
}
if (!frame()) {
m_loadEventProgress = LoadEventCompleted;
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_loadEventProgress = LoadEventCompleted;
return;
}
// 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() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
view()->layout();
}
m_loadEventProgress = LoadEventCompleted;
if (frame() && renderView() && 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.
if (AXObjectCache* cache = axObjectCache()) {
cache->getOrCreate(renderView());
if (this == topDocument()) {
cache->postNotification(renderView(), 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.
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);
RefPtr<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 (currentFocusedElement && currentFocusedElement->hasTagName(inputTag))
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;
// The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
// while dispatching the event, so protect it to prevent writing the end
// time into freed memory.
RefPtr<DocumentLoader> documentLoader = m_frame->loader().provisionalDocumentLoader();
m_loadEventProgress = UnloadEventInProgress;
RefPtr<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;
// Don't remove event listeners from a transitional empty document (see https://bugs.webkit.org/show_bug.cgi?id=28716 for more information).
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_bParsing = b;
if (m_bParsing && !m_elementDataCache)
m_elementDataCache = ElementDataCache::create();
if (!m_bParsing && view())
view()->scheduleRelayout();
}
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::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);
}