#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 "Console.h"
#include "ContentSecurityPolicy.h"
#include "CookieJar.h"
#include "DOMImplementation.h"
#include "DOMWindow.h"
#include "DateComponents.h"
#include "DeviceMotionController.h"
#include "DeviceMotionEvent.h"
#include "DeviceOrientationController.h"
#include "DeviceOrientationEvent.h"
#include "DocumentEventQueue.h"
#include "DocumentFragment.h"
#include "DocumentLoader.h"
#include "DocumentMarkerController.h"
#include "DocumentType.h"
#include "EditingText.h"
#include "Editor.h"
#include "Element.h"
#include "EntityReference.h"
#include "Event.h"
#include "EventFactory.h"
#include "EventHandler.h"
#include "EventListener.h"
#include "EventNames.h"
#include "ExceptionCode.h"
#include "FlowThreadController.h"
#include "FocusController.h"
#include "FormAssociatedElement.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 "HTMLInputElement.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 "ImageLoader.h"
#include "InspectorCounters.h"
#include "InspectorInstrumentation.h"
#include "Logging.h"
#include "MediaQueryList.h"
#include "MediaQueryMatcher.h"
#include "MouseEventWithHitTestResults.h"
#include "NameNodeList.h"
#include "NestingLevelIncrementer.h"
#include "NewXMLDocumentParser.h"
#include "NodeFilter.h"
#include "NodeIterator.h"
#include "NodeWithIndex.h"
#include "Page.h"
#include "PageGroup.h"
#include "PageTransitionEvent.h"
#include "PlatformKeyboardEvent.h"
#include "PluginDocument.h"
#include "PopStateEvent.h"
#include "ProcessingInstruction.h"
#include "RegisteredEventListener.h"
#include "RenderArena.h"
#include "RenderNamedFlowThread.h"
#include "RenderTextControl.h"
#include "RenderView.h"
#include "RenderWidget.h"
#include "SchemeRegistry.h"
#include "ScopedEventQueue.h"
#include "ScriptCallStack.h"
#include "ScriptController.h"
#include "ScriptElement.h"
#include "ScriptEventListener.h"
#include "ScriptRunner.h"
#include "ScrollingCoordinator.h"
#include "SecurityOrigin.h"
#include "SecurityPolicy.h"
#include "SegmentedString.h"
#include "Settings.h"
#include "ShadowRoot.h"
#include "ShadowTree.h"
#include "StaticHashSetNodeList.h"
#include "StyleResolver.h"
#include "StyleSheetList.h"
#include "TextResourceDecoder.h"
#include "Timer.h"
#include "TransformSource.h"
#include "TreeWalker.h"
#include "UserContentURLPattern.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 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
#include "GestureEvent.h"
#include "TouchList.h"
#include "DeviceMotionClient.h"
#include "DeviceMotionClientIOS.h"
#include "DeviceMotionController.h"
#include "DeviceOrientationClient.h"
#include "DeviceOrientationClientIOS.h"
#include "DeviceOrientationController.h"
#include "Geolocation.h"
#include "HTMLParserErrorCodes.h"
#include "Navigator.h"
#include "NavigatorGeolocation.h"
#include "WebCoreSystemInterface.h"
#include "WKContentObservation.h"
#include "WKUtilities.h"
#include <wtf/UnusedParam.h>
#include "CSSFontSelector.h"
#include "RenderText.h"
#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
using namespace std;
using namespace WTF;
using namespace Unicode;
namespace WebCore {
using namespace HTMLNames;
static const unsigned cMaxWriteRecursionDepth = 21;
const int cLayoutScheduleThreshold = 250;
static inline bool isValidNameStart(UChar32 c)
{
if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
return true;
if (c == ':' || c == '_')
return true;
const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
if (!(Unicode::category(c) & nameStartMask))
return false;
if (c >= 0xF900 && c < 0xFFFE)
return false;
DecompositionType decompType = decompositionType(c);
if (decompType == DecompositionFont || decompType == DecompositionCompat)
return false;
return true;
}
static inline bool isValidNamePart(UChar32 c)
{
if (isValidNameStart(c))
return true;
if (c == 0x00B7 || c == 0x0387)
return true;
if (c == '-' || c == '.')
return true;
const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
if (!(Unicode::category(c) & otherNamePartMask))
return false;
if (c >= 0xF900 && c < 0xFFFE)
return false;
DecompositionType decompType = decompositionType(c);
if (decompType == DecompositionFont || decompType == DecompositionCompat)
return false;
return true;
}
static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
{
return !url.isValid() || url.protocolIs("about");
}
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 disableRangeMutation(Page* page)
{
#ifdef TARGETING_LEOPARD
return page && page->settings()->needsLeopardMailQuirks();
#else
UNUSED_PARAM(page);
return false;
#endif
}
static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
{
if (!targetFrame)
return false;
const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree()->parent()) {
Document* ancestorDocument = ancestorFrame->document();
if (!ancestorDocument)
return true;
const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
return true;
if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
return true;
}
return false;
}
static void printNavigationErrorMessage(Frame* frame, const KURL& activeURL)
{
String message = "Unsafe JavaScript attempt to initiate a navigation change for frame with URL " +
frame->document()->url().string() + " from frame with URL " + activeURL.string() + ".\n";
frame->domWindow()->printErrorMessage(message);
}
static HashSet<Document*>* documentsThatNeedStyleRecalc = 0;
class DocumentWeakReference : public ThreadSafeRefCounted<DocumentWeakReference> {
public:
static PassRefPtr<DocumentWeakReference> create(Document* document)
{
return adoptRef(new DocumentWeakReference(document));
}
Document* document()
{
ASSERT(isMainThread() || pthread_main_np());
return m_document;
}
void clear()
{
ASSERT(isMainThread() || pthread_main_np());
m_document = 0;
}
private:
DocumentWeakReference(Document* document)
: m_document(document)
{
ASSERT(isMainThread() || pthread_main_np());
}
Document* m_document;
};
uint64_t Document::s_globalTreeVersion = 0;
Document::Document(Frame* frame, const KURL& url, bool isXHTML, bool isHTML, bool isSynthesized)
: ContainerNode(0, CreateDocument)
, TreeScope(this)
, m_handlingTouchEvent(false)
, m_touchEventRegionsDirty(false)
, m_touchEventsChangedTimer(this, &Document::touchEventsChangedTimerFired)
, m_guardRefCount(0)
, m_compatibilityMode(NoQuirksMode)
, m_compatibilityModeLocked(false)
, m_domTreeVersion(++s_globalTreeVersion)
#if ENABLE(MUTATION_OBSERVERS)
, m_mutationObserverTypes(0)
#endif
, m_styleSheets(StyleSheetList::create(this))
, m_hadActiveLoadingStylesheet(false)
, 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)
, m_hasDashboardRegions(false)
, m_dashboardRegionsDirty(false)
#endif
, m_createRenderers(true)
, m_inPageCache(false)
, m_accessKeyMapValid(false)
, m_useSecureKeyboardEntryWhenActive(false)
, m_isXHTML(isXHTML)
, m_isHTML(isHTML)
, m_isSynthesized(isSynthesized)
, m_isViewSource(false)
, m_sawElementsInKnownNamespaces(false)
, m_isSrcdocDocument(false)
, m_eventQueue(DocumentEventQueue::create(this))
, m_weakReference(DocumentWeakReference::create(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_touchEventHandlerCount(0)
, m_deviceMotionClient(DeviceMotionClientIOS::create())
, m_deviceMotionController(DeviceMotionController::create(m_deviceMotionClient.get()))
, m_deviceOrientationClient(DeviceOrientationClientIOS::create())
, m_deviceOrientationController(DeviceOrientationController::create(0, m_deviceOrientationClient.get()))
, m_isTelephoneNumberParsingAllowed(true)
, m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
, m_scheduledTasksAreSuspended(false)
, m_visualUpdatesAllowed(true)
, m_visualUpdatesSuppressionTimer(this, &Document::visualUpdatesSuppressionTimerFired)
#ifndef NDEBUG
, m_didDispatchViewportPropertiesChanged(false)
#endif
{
m_document = this;
m_pageGroupUserSheetCacheValid = false;
m_printing = false;
m_paginatedForScreen = false;
m_ignoreAutofocus = false;
m_frame = frame;
if ((frame && frame->ownerElement()) || !url.isEmpty())
setURL(url);
m_axObjectCache = 0;
m_markers = adoptPtr(new DocumentMarkerController);
m_cachedResourceLoader = adoptPtr(new CachedResourceLoader(this));
m_visuallyOrdered = false;
m_bParsing = false;
m_wellFormed = false;
m_textColor = Color::black;
m_listenerTypes = 0;
m_inStyleRecalc = false;
m_closeAfterStyleRecalc = false;
m_usesSiblingRules = false;
m_usesSiblingRulesOverride = false;
m_usesFirstLineRules = false;
m_usesFirstLetterRules = false;
m_usesBeforeAfterRules = false;
m_usesBeforeAfterRulesOverride = false;
m_usesRemUnits = false;
m_usesLinkRules = false;
m_gotoAnchorNeededAfterStylesheetsLoad = false;
m_didCalculateStyleResolver = false;
m_hasDirtyStyleResolver = false;
m_pendingStylesheets = 0;
m_ignorePendingStylesheets = 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++;
InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
if (m_frame && m_frame->timersPaused())
m_eventQueue->suspendPendingEventTimer();
}
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);
}
Document::~Document()
{
ASSERT(!renderer());
ASSERT(!m_inPageCache);
ASSERT(!m_savedRenderer);
ASSERT(m_ranges.isEmpty());
ASSERT(!m_styleRecalcTimer.isActive());
ASSERT(!m_parentTreeScope);
ASSERT(!m_guardRefCount);
m_deviceMotionClient->deviceMotionControllerDestroyed();
m_deviceOrientationClient->deviceOrientationControllerDestroyed();
m_scriptRunner.clear();
histogramMutationEventUsage(m_listenerTypes);
removeAllEventListeners();
ASSERT(!m_parser || m_parser->refCount() == 1);
detachParser();
m_document = 0;
m_renderArena.clear();
clearAXObjectCache();
m_decoder = 0;
if (m_styleSheets)
m_styleSheets->documentDestroyed();
if (m_elemSheet)
m_elemSheet->clearOwnerNode();
if (m_pageUserSheet)
m_pageUserSheet->clearOwnerNode();
if (m_pageGroupUserSheets) {
for (size_t i = 0; i < m_pageGroupUserSheets->size(); ++i)
(*m_pageGroupUserSheets)[i]->clearOwnerNode();
}
if (m_userSheets) {
for (size_t i = 0; i < m_userSheets->size(); ++i)
(*m_userSheets)[i]->clearOwnerNode();
}
deleteCustomFonts();
m_weakReference->clear();
if (m_mediaQueryMatcher)
m_mediaQueryMatcher->documentDestroyed();
clearStyleResolver(); m_cachedResourceLoader.clear();
if (hasRareData())
clearRareData();
InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
}
void Document::removedLastRef()
{
ASSERT(!m_deletionHasBegun);
if (m_guardRefCount) {
guardRef();
m_docType = 0;
m_focusedNode = 0;
m_hoverNode = 0;
m_activeNode = 0;
m_titleElement = 0;
m_documentElement = 0;
#if ENABLE(FULLSCREEN_API)
m_fullScreenElement = 0;
m_fullScreenElementStack.clear();
#endif
detachParser();
destroyTreeScopeData();
removeAllChildren();
m_markers->detach();
m_cssCanvasElements.clear();
#if ENABLE(REQUEST_ANIMATION_FRAME)
if (m_scriptedAnimationController)
m_scriptedAnimationController->clearDocumentPointer();
m_scriptedAnimationController.clear();
#endif
#ifndef NDEBUG
m_inRemovedLastRefFunction = false;
#endif
guardDeref();
} else {
#ifndef NDEBUG
m_deletionHasBegun = true;
#endif
delete this;
}
}
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 (Node* node = rootNode; node; node = node->traverseNextNode(rootNode)) {
if (!node->isElementNode())
continue;
Element* element = static_cast<Element*>(node);
const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
if (!accessKey.isEmpty())
m_elementsByAccessKey.set(accessKey.impl(), element);
if (element->hasShadowRoot()) {
for (ShadowRoot* root = element->shadowTree()->youngestShadowRoot(); root; root = root->olderShadowRoot())
buildAccessKeyMap(root);
}
}
}
void Document::invalidateAccessKeyMap()
{
m_accessKeyMapValid = false;
m_elementsByAccessKey.clear();
}
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;
ASSERT(!m_styleSheets->length());
bool wasInQuirksMode = inQuirksMode();
m_compatibilityMode = mode;
if (inQuirksMode() != wasInQuirksMode) {
clearPageUserSheet();
clearPageGroupUserSheets();
}
}
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)
{
ASSERT(!m_docType || !docType);
m_docType = docType;
if (m_docType)
this->adoptIfNeeded(m_docType.get());
clearStyleResolver();
if (page())
page()->chrome()->client()->didReceiveDocType(frame());
}
DOMImplementation* Document::implementation()
{
if (!m_implementation)
m_implementation = DOMImplementation::create(this);
return m_implementation.get();
}
void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
Element* newDocumentElement = firstElementChild(this);
if (newDocumentElement == m_documentElement)
return;
m_documentElement = newDocumentElement;
clearStyleResolver();
}
PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
{
if (!isValidName(name)) {
ec = INVALID_CHARACTER_ERR;
return 0;
}
if (m_isXHTML)
return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
return createElement(QualifiedName(nullAtom, name, nullAtom), false);
}
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<EditingText> Document::createEditingTextNode(const String& text)
{
return EditingText::create(this, text);
}
PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
{
return StylePropertySet::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 = static_cast<Element*>(importedNode);
if (!hasValidNamespaceForElements(oldElement->tagQName())) {
ec = NAMESPACE_ERR;
return 0;
}
RefPtr<Element> newElement = createElement(oldElement->tagQName(), ec);
if (ec)
return 0;
newElement->setAttributesFromElement(*oldElement);
newElement->copyNonAttributeProperties(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()) {
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:
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()) {
ec = HIERARCHY_REQUEST_ERR;
return 0;
}
if (source->hasTagName(iframeTag)) {
HTMLIFrameElement* iframe = static_cast<HTMLIFrameElement*>(source.get());
if (frame() && frame()->tree()->isDescendantOf(iframe->contentFrame())) {
ec = HIERARCHY_REQUEST_ERR;
return 0;
}
}
if (source->parentNode())
source->parentNode()->removeChild(source.get(), ec);
}
this->adoptIfNeeded(source.get());
return source;
}
bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
{
if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) return false;
if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) return false;
if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
return false;
return true;
}
bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
{
if (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom) {
return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
}
return hasValidNamespaceForElements(qName);
}
PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
{
RefPtr<Element> e;
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());
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::cssRegionsEnabled() const
{
return settings() && settings()->cssRegionsEnabled();
}
#if ENABLE(CSS_REGIONS)
static bool validFlowName(const String& flowName)
{
if (equalIgnoringCase(flowName, "auto")
|| equalIgnoringCase(flowName, "default")
|| equalIgnoringCase(flowName, "inherit")
|| equalIgnoringCase(flowName, "initial")
|| equalIgnoringCase(flowName, "none"))
return false;
return true;
}
PassRefPtr<WebKitNamedFlow> Document::webkitGetFlowByName(const String& flowName)
{
return webkitGetFlowByName(flowName, CheckFlowNameForInvalidValues);
}
PassRefPtr<WebKitNamedFlow> Document::webkitGetFlowByName(const String& flowName, FlowNameCheck flowNameCheck)
{
if (!cssRegionsEnabled() || !renderer())
return 0;
if (flowNameCheck == CheckFlowNameForInvalidValues) {
if (flowName.isEmpty() || !validFlowName(flowName))
return 0;
CSSParser parser(document());
if (!parser.parseFlowThread(flowName))
return 0;
}
if (RenderView* view = renderer()->view())
return view->flowThreadController()->ensureRenderFlowThreadWithName(flowName)->ensureNamedFlow();
return 0;
}
#endif
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, ("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();
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;
#if USE(ACCELERATED_COMPOSITING)
if (view())
view()->updateCompositingLayersAfterLayout();
#endif
if (renderer())
renderer()->repaint();
}
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;
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)
{
m_documentURI = uri;
updateBaseURL();
}
KURL Document::baseURI() const
{
return m_baseURL;
}
void Document::setContent(const String& content)
{
open();
m_parser->append(content);
close();
}
String Document::suggestedMIMEType() const
{
if (m_document->isXHTMLDocument())
return "application/xhtml+xml";
if (m_document->isSVGDocument())
return "image/svg+xml";
if (m_document->xmlStandalone())
return "text/xml";
if (m_document->isHTMLDocument())
return "text/html";
if (DocumentLoader* documentLoader = loader())
return documentLoader->responseMIMEType();
return String();
}
PassRefPtr<NodeList> Document::nodesFromRect(int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent) const
{
if (!renderer())
return 0;
Frame* frame = this->frame();
if (!frame)
return 0;
FrameView* frameView = frame->view();
if (!frameView)
return 0;
float zoomFactor = frame->pageZoomFactor();
LayoutPoint point = roundedLayoutPoint(FloatPoint(centerX * zoomFactor + view()->scrollX(), centerY * zoomFactor + view()->scrollY()));
int type = HitTestRequest::ReadOnly | HitTestRequest::Active;
if (ignoreClipping)
type |= HitTestRequest::IgnoreClipping;
else if (!frameView->visibleContentRect().intersects(HitTestResult::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
return 0;
HitTestRequest request(type);
if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) {
HitTestResult result(point);
return handleZeroPadding(request, result);
}
enum ShadowContentFilterPolicy shadowContentFilterPolicy = allowShadowContent ? AllowShadowContent : DoNotAllowShadowContent;
HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding, shadowContentFilterPolicy);
renderView()->hitTest(request, result);
return StaticHashSetNodeList::adopt(result.rectBasedTestResult());
}
PassRefPtr<NodeList> Document::handleZeroPadding(const HitTestRequest& request, HitTestResult& result) const
{
renderView()->hitTest(request, result);
Node* node = result.innerNode();
if (!node)
return 0;
node = node->shadowAncestorNode();
ListHashSet<RefPtr<Node> > list;
list.add(node);
return StaticHashSetNodeList::adopt(list);
}
static Node* nodeFromPoint(Frame* frame, RenderView* renderView, int x, int y, LayoutPoint* localPoint = 0)
{
if (!frame)
return 0;
FrameView* frameView = frame->view();
if (!frameView)
return 0;
float zoomFactor = frame->pageZoomFactor();
IntPoint point = roundedIntPoint(FloatPoint(x * zoomFactor + frameView->actualScrollX(), y * zoomFactor + frameView->actualScrollY()));
if (!frameView->actualVisibleContentRect().contains(point))
return 0;
HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
HitTestResult result(point);
renderView->hitTest(request, result);
if (localPoint)
*localPoint = result.localPoint();
return result.innerNode();
}
Element* Document::elementFromPoint(int x, int y) const
{
if (!renderer())
return 0;
Node* node = nodeFromPoint(frame(), renderView(), x, y);
while (node && !node->isElementNode())
node = node->parentNode();
if (node)
node = node->shadowAncestorNode();
return static_cast<Element*>(node);
}
PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
{
if (!renderer())
return 0;
LayoutPoint localPoint;
Node* node = nodeFromPoint(frame(), renderView(), x, y, &localPoint);
if (!node)
return 0;
Node* shadowAncestorNode = node->shadowAncestorNode();
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);
}
static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
{
const String& title = titleWithDirection.string();
const UChar* characters = title.characters();
unsigned length = title.length();
unsigned i;
StringBuffer<UChar> buffer(length);
unsigned builderIndex = 0;
for (i = 0; i < length; ++i) {
UChar c = characters[i];
if (!(c <= 0x20 || c == 0x7F))
break;
}
if (i == length)
return StringWithDirection();
bool previousCharWasWS = false;
for (; i < length; ++i) {
UChar c = characters[i];
if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
if (previousCharWasWS)
continue;
buffer[builderIndex++] = ' ';
previousCharWasWS = true;
} else {
buffer[builderIndex++] = c;
previousCharWasWS = false;
}
}
while (builderIndex > 0) {
--builderIndex;
if (buffer[builderIndex] != ' ')
break;
}
if (!builderIndex && buffer[builderIndex] == ' ')
return StringWithDirection();
buffer.shrink(builderIndex + 1);
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;
m_title = canonicalizedTitle(this, m_rawTitle);
if (Frame* f = frame())
f->loader()->setTitle(m_title);
}
void Document::setTitle(const String& title)
{
m_titleSetExplicitly = true;
if (!isHTMLDocument() && !isXHTMLDocument())
m_titleElement = 0;
else if (!m_titleElement) {
if (HTMLElement* headElement = head()) {
m_titleElement = createElement(titleTag, false);
ExceptionCode ec = 0;
headElement->appendChild(m_titleElement, ec);
ASSERT(!ec);
}
}
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)
return;
m_titleElement = titleElement;
}
updateTitle(title);
}
void Document::removeTitle(Element* titleElement)
{
if (m_titleElement != titleElement)
return;
m_titleElement = 0;
m_titleSetExplicitly = false;
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
{
if (!m_frame || !m_frame->page())
return PageVisibilityStateVisible;
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
String Document::nodeName() const
{
return "#document";
}
Node::NodeType Document::nodeType() const
{
return DOCUMENT_NODE;
}
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 (m_styleRecalcTimer.isActive() || inPageCache())
return;
ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
if (!documentsThatNeedStyleRecalc)
documentsThatNeedStyleRecalc = new HashSet<Document*>;
documentsThatNeedStyleRecalc->add(this);
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::isPendingStyleRecalc() const
{
return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
}
void Document::styleRecalcTimerFired(Timer<Document>*)
{
updateStyleIfNeeded();
}
bool Document::childNeedsAndNotInStyleRecalc()
{
return childNeedsStyleRecalc() && !m_inStyleRecalc;
}
void Document::recalcStyle(StyleChange change)
{
if (view() && view()->isPainting()) {
ASSERT(!view()->isPainting());
return;
}
if (m_inStyleRecalc)
return;
if (m_hasDirtyStyleResolver)
updateActiveStylesheets(RecalcStyleImmediately);
InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
if (m_elemSheet && m_elemSheet->internal()->usesRemUnits())
m_usesRemUnits = true;
m_inStyleRecalc = true;
suspendPostAttachCallbacks();
RenderWidget::suspendWidgetHierarchyUpdates();
RefPtr<FrameView> frameView = view();
if (frameView) {
frameView->pauseScheduledEvents();
frameView->beginDeferredRepaints();
}
ASSERT(!renderer() || renderArena());
if (!renderer() || !renderArena())
goto bail_out;
if (m_pendingStyleRecalcShouldForce)
change = Force;
if (change == Force) {
m_hasNodesWithPlaceholderStyle = false;
RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(this, m_styleResolver ? m_styleResolver->fontSelector() : 0);
if (Settings* settings = this->settings()) {
if (settings->fontFallbackPrefersPictographs() && m_styleResolver)
documentStyle->font().update(m_styleResolver->fontSelector());
}
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 = static_cast<Element*>(n);
if (change >= Inherit || element->childNeedsStyleRecalc() || element->needsStyleRecalc())
element->recalcStyle(change);
}
#if USE(ACCELERATED_COMPOSITING)
if (view()) {
bool layoutPending = view()->layoutPending() || renderer()->needsLayout();
if (!layoutPending)
view()->updateCompositingLayersAfterStyleChange();
}
#endif
bail_out:
clearNeedsStyleRecalc();
clearChildNeedsStyleRecalc();
unscheduleStyleRecalc();
if (m_styleResolver)
resetCSSFeatureFlags();
if (frameView) {
frameView->resumeScheduledEvents();
frameView->endDeferredRepaints();
}
RenderWidget::resumeWidgetHierarchyUpdates();
resumePostAttachCallbacks();
m_inStyleRecalc = false;
if (m_closeAfterStyleRecalc) {
m_closeAfterStyleRecalc = false;
implicitClose();
}
InspectorInstrumentation::didRecalculateStyle(cookie);
}
void Document::updateStyleIfNeeded()
{
ASSERT(isMainThread() || pthread_main_np());
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() || pthread_main_np());
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() || pthread_main_np());
if (Element* oe = ownerElement())
oe->document()->updateLayout();
updateStyleIfNeeded();
FrameView* v = view();
if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
v->layout();
}
void Document::updateLayoutIgnorePendingStylesheets()
{
bool oldIgnore = m_ignorePendingStylesheets;
if (!haveStylesheetsLoaded()) {
m_ignorePendingStylesheets = true;
HTMLElement* bodyElement = body();
if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
m_pendingSheetLayout = DidLayoutWithPendingSheets;
styleResolverChanged(RecalcStyleImmediately);
} else if (m_hasNodesWithPlaceholderStyle)
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 = styleResolver()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
m_ignorePendingStylesheets = oldIgnore;
return style.release();
}
PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
{
RefPtr<RenderStyle> style = styleResolver()->styleForPage(pageIndex);
return style.release();
}
void Document::registerCustomFont(PassOwnPtr<FontData> fontData)
{
m_customFonts.append(fontData);
}
void Document::deleteCustomFonts()
{
size_t size = m_customFonts.size();
for (size_t i = 0; i < size; ++i)
GlyphPageTreeNode::pruneTreeCustomFontData(m_customFonts[i].get());
m_customFonts.clear();
}
bool Document::isPageBoxVisible(int pageIndex)
{
RefPtr<RenderStyle> style = styleForPage(pageIndex);
return style->visibility() != HIDDEN; }
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);
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::combineCSSFeatureFlags()
{
m_usesSiblingRules = m_usesSiblingRules || m_styleResolver->usesSiblingRules();
m_usesFirstLineRules = m_usesFirstLineRules || m_styleResolver->usesFirstLineRules();
m_usesBeforeAfterRules = m_usesBeforeAfterRules || m_styleResolver->usesBeforeAfterRules();
m_usesLinkRules = m_usesLinkRules || m_styleResolver->usesLinkRules();
}
void Document::resetCSSFeatureFlags()
{
m_usesSiblingRules = m_styleResolver->usesSiblingRules();
m_usesFirstLineRules = m_styleResolver->usesFirstLineRules();
m_usesBeforeAfterRules = m_styleResolver->usesBeforeAfterRules();
m_usesLinkRules = m_styleResolver->usesLinkRules();
}
void Document::createStyleResolver()
{
bool matchAuthorAndUserStyles = true;
if (Settings* docSettings = settings())
matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
m_styleResolver = adoptPtr(new StyleResolver(this, matchAuthorAndUserStyles));
combineCSSFeatureFlags();
}
inline void Document::clearStyleResolver()
{
m_styleResolver.clear();
}
void Document::attach()
{
ASSERT(!attached());
ASSERT(!m_inPageCache);
ASSERT(!m_axObjectCache || this != topDocument());
if (!m_renderArena)
m_renderArena = adoptPtr(new RenderArena);
setRenderer(new (m_renderArena.get()) RenderView(this, view()));
#if USE(ACCELERATED_COMPOSITING)
renderView()->didMoveOnscreen();
#endif
recalcStyle(Force);
RenderObject* render = renderer();
setRenderer(0);
ContainerNode::attach();
setRenderer(render);
}
void Document::detach()
{
ASSERT(attached());
ASSERT(!m_inPageCache);
if (this == topDocument())
clearAXObjectCache();
stopActiveDOMObjects();
m_eventQueue->close();
#if ENABLE(FULLSCREEN_API)
m_fullScreenChangeEventTargetQueue.clear();
m_fullScreenErrorEventTargetQueue.clear();
#endif
#if ENABLE(REQUEST_ANIMATION_FRAME)
if (m_scriptedAnimationController)
m_scriptedAnimationController->clearDocumentPointer();
m_scriptedAnimationController.clear();
#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();
}
setRenderer(0);
#if ENABLE(FULLSCREEN_API)
if (m_fullScreenRenderer)
setFullScreenRenderer(0);
#endif
m_hoverNode = 0;
m_focusedNode = 0;
m_activeNode = 0;
ContainerNode::detach();
unscheduleStyleRecalc();
if (render)
render->destroy();
m_frame = 0;
m_textAutoSizedNodes.clear();
m_renderArena.clear();
}
void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
{
ScriptExecutionContext::suspendActiveDOMObjects(why);
#if ENABLE(DEVICE_ORIENTATION)
if (m_deviceMotionController)
m_deviceMotionController->suspendUpdates();
if (m_deviceOrientationController)
m_deviceOrientationController->suspendUpdates();
#endif
if (WebThreadCountOfObservedContentModifiers() > 0)
if (frame() && frame()->page() && frame()->page()->chrome() && frame()->page()->chrome()->client())
frame()->page()->chrome()->client()->clearContentChangeObservers(frame());
}
void Document::resumeActiveDOMObjects()
{
ScriptExecutionContext::resumeActiveDOMObjects();
#if ENABLE(DEVICE_ORIENTATION)
if (m_deviceMotionController)
m_deviceMotionController->resumeUpdates();
if (m_deviceOrientationController)
m_deviceOrientationController->resumeUpdates();
#endif
}
void Document::stopActiveDOMObjects()
{
ScriptExecutionContext::stopActiveDOMObjects();
#if ENABLE(DEVICE_ORIENTATION)
if (m_deviceMotionController)
m_deviceMotionController->suspendUpdates();
if (m_deviceOrientationController)
m_deviceOrientationController->suspendUpdates();
#endif
if (WebThreadCountOfObservedContentModifiers() > 0)
if (frame() && frame()->page() && frame()->page()->chrome() && frame()->page()->chrome()->client())
frame()->page()->chrome()->client()->clearContentChangeObservers(frame());
}
void Document::prepareForDestruction()
{
if (DOMWindow* window = this->domWindow())
window->willDetachDocumentFromFrame();
detach();
}
void Document::removeAllEventListeners()
{
EventTarget::removeAllEventListeners();
if (DOMWindow* domWindow = this->domWindow())
domWindow->removeAllEventListeners();
clearTouchEventListeners();
for (Node* node = firstChild(); node; node = node->traverseNextNode())
node->removeAllEventListeners();
}
RenderView* Document::renderView() const
{
return toRenderView(renderer());
}
void Document::clearAXObjectCache()
{
if (m_axObjectCache) {
AXObjectCache* axObjectCache = m_axObjectCache;
m_axObjectCache = 0;
delete axObjectCache;
return;
}
Document* doc = topDocument();
if (doc != this)
doc->clearAXObjectCache();
}
bool Document::axObjectCacheExists() const
{
if (m_axObjectCache)
return true;
Document* doc = topDocument();
if (doc != this)
return doc->axObjectCacheExists();
return false;
}
AXObjectCache* Document::axObjectCache() const
{
if (m_axObjectCache) {
if (!ownerElement())
return m_axObjectCache;
delete m_axObjectCache;
m_axObjectCache = 0;
}
Document* doc = topDocument();
if (doc != this)
return doc->axObjectCache();
m_axObjectCache = new AXObjectCache(this);
return m_axObjectCache;
}
void Document::setVisuallyOrdered()
{
m_visuallyOrdered = true;
if (renderer())
renderer()->style()->setRTLOrdering(VisualOrder);
}
PassRefPtr<DocumentParser> Document::createParser()
{
#if ENABLE(NEW_XML)
return NewXMLDocumentParser::create(this);
#else
return XMLDocumentParser::create(this, view());
#endif
}
ScriptableDocumentParser* Document::scriptableDocumentParser() const
{
return parser() ? parser()->asScriptableDocumentParser() : 0;
}
void Document::open(Document* ownerDocument)
{
if (ownerDocument) {
setURL(ownerDocument->url());
m_cookieURL = ownerDocument->cookieURL();
setSecurityOrigin(ownerDocument->securityOrigin());
}
if (m_frame) {
if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
if (parser->isParsing()) {
if (parser->isExecutingScript())
return;
if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
return;
}
}
if (m_frame->loader()->state() == FrameStateProvisional)
m_frame->loader()->stopAllLoaders();
}
removeAllEventListeners();
implicitOpen();
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->setWasCreatedByScript(true);
if (DOMWindow* domWindow = this->domWindow())
domWindow->removeAllEventListeners();
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;
detachParser();
explicitClose();
}
void Document::implicitOpen()
{
cancelParsing();
removeChildren();
setCompatibilityMode(NoQuirksMode);
m_parser = createParser();
setParsing(true);
setReadyState(Loading);
}
HTMLElement* Document::body() const
{
Node* de = documentElement();
if (!de)
return 0;
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()
{
if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
return;
explicitClose();
}
void Document::explicitClose()
{
if (m_parser)
m_parser->finish();
if (!m_frame) {
implicitClose();
return;
}
m_frame->loader()->checkCompleted();
}
void Document::implicitClose()
{
if (m_inStyleRecalc) {
m_closeAfterStyleRecalc = true;
return;
}
bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
if (!doload)
return;
m_processingLoadEvent = true;
ScriptableDocumentParser* parser = scriptableDocumentParser();
m_wellFormed = parser && parser->wellFormed();
detachParser();
m_cachedResourceLoader->clearPreloads();
Frame* f = frame();
if (f) {
f->loader()->icon()->startLoader();
f->animation()->resumeAnimationsForDocument(this);
}
ImageLoader::dispatchPendingBeforeLoadEvents();
ImageLoader::dispatchPendingLoadEvents();
ImageLoader::dispatchPendingErrorEvents();
HTMLLinkElement::dispatchPendingLoadEvents();
HTMLStyleElement::dispatchPendingLoadEvents();
#if ENABLE(SVG)
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
if (!frame()) {
m_processingLoadEvent = false;
return;
}
if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < settings()->layoutInterval())
{
m_processingLoadEvent = false;
view()->unscheduleRelayout();
return;
}
frame()->loader()->checkCallImplicitClose();
RenderObject* renderObject = renderer();
m_overMinimumLayoutThreshold = true;
if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
updateStyleIfNeeded();
if (view() && renderObject && (!renderObject->firstChild() || renderObject->needsLayout()))
view()->layout();
}
m_processingLoadEvent = false;
#if PLATFORM(MAC) || PLATFORM(CHROMIUM)
if (f && renderObject && AXObjectCache::accessibilityEnabled()) {
axObjectCache()->getOrCreate(renderObject);
if (this == topDocument())
axObjectCache()->postNotification(renderObject, AXObjectCache::AXLoadComplete, true);
else {
axObjectCache()->postNotification(renderObject, AXObjectCache::AXLayoutComplete, true);
}
}
#endif
#if ENABLE(SVG)
if (svgExtensions())
accessSVGExtensions()->startAnimations();
#endif
}
void Document::setParsing(bool b)
{
m_bParsing = b;
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()
{
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 > settings()->layoutInterval();
return max(0, settings()->layoutInterval() - 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();
}
EventTarget* Document::errorEventTarget()
{
return domWindow();
}
void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack> callStack)
{
addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, 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();
}
void Document::updateBaseURL()
{
KURL oldBaseURL = m_baseURL;
if (!m_baseElementURL.isEmpty())
m_baseURL = m_baseElementURL;
else if (!m_baseURLOverride.isEmpty())
m_baseURL = m_baseURLOverride;
else {
m_baseURL = KURL(KURL(), documentURI());
}
if (!m_baseURL.isValid())
m_baseURL = KURL();
if (m_elemSheet) {
ASSERT(!m_elemSheet->internal()->ruleCount());
bool usesRemUnits = m_elemSheet->internal()->usesRemUnits();
m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
m_elemSheet->internal()->parserSetUsesRemUnits(usesRemUnits);
}
if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
if (node->hasTagName(aTag))
static_cast<HTMLAnchorElement*>(node)->invalidateCachedVisitedLinkHash();
}
}
}
void Document::setBaseURLOverride(const KURL& url)
{
m_baseURLOverride = url;
updateBaseURL();
}
void Document::processBaseElement()
{
const AtomicString* href = 0;
const AtomicString* target = 0;
for (Node* node = document()->firstChild(); node && (!href || !target); node = node->traverseNextNode()) {
if (node->hasTagName(baseTag)) {
if (!href) {
const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(hrefAttr);
if (!value.isNull())
href = &value;
}
if (!target) {
const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(targetAttr);
if (!value.isNull())
target = &value;
}
}
}
KURL baseElementURL;
if (href) {
String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
if (!strippedHref.isEmpty())
baseElementURL = KURL(url(), strippedHref);
}
if (m_baseElementURL != 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()
{
if (!frame())
return;
frame()->script()->disableEval();
}
bool Document::canNavigate(Frame* targetFrame)
{
if (!m_frame)
return false;
if (!targetFrame)
return true;
if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
return true;
if (isSandboxed(SandboxNavigation)) {
if (targetFrame->tree()->isDescendantOf(m_frame))
return true;
printNavigationErrorMessage(targetFrame, url());
return false;
}
if (canAccessAncestor(securityOrigin(), targetFrame))
return true;
if (!targetFrame->tree()->parent()) {
if (targetFrame == m_frame->loader()->opener())
return true;
if (canAccessAncestor(securityOrigin(), targetFrame->loader()->opener()))
return true;
}
printNavigationErrorMessage(targetFrame, url());
return false;
}
Frame* Document::findUnsafeParentScrollPropagationBoundary()
{
Frame* currentFrame = m_frame;
Frame* ancestorFrame = currentFrame->tree()->parent();
while (ancestorFrame) {
if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
return currentFrame;
currentFrame = ancestorFrame;
ancestorFrame = ancestorFrame->tree()->parent();
}
return 0;
}
CSSStyleSheet* Document::pageUserSheet()
{
if (m_pageUserSheet)
return m_pageUserSheet.get();
Page* owningPage = page();
if (!owningPage)
return 0;
String userSheetText = owningPage->userStyleSheet();
if (userSheetText.isEmpty())
return 0;
m_pageUserSheet = CSSStyleSheet::createInline(this, settings()->userStyleSheetLocation());
m_pageUserSheet->internal()->setIsUserStyleSheet(true);
m_pageUserSheet->internal()->parseString(userSheetText);
return m_pageUserSheet.get();
}
void Document::clearPageUserSheet()
{
if (m_pageUserSheet) {
m_pageUserSheet = 0;
styleResolverChanged(DeferRecalcStyle);
}
}
void Document::updatePageUserSheet()
{
clearPageUserSheet();
if (pageUserSheet())
styleResolverChanged(RecalcStyleImmediately);
}
const Vector<RefPtr<CSSStyleSheet> >* Document::pageGroupUserSheets() const
{
if (m_pageGroupUserSheetCacheValid)
return m_pageGroupUserSheets.get();
m_pageGroupUserSheetCacheValid = true;
Page* owningPage = page();
if (!owningPage)
return 0;
const PageGroup& pageGroup = owningPage->group();
const UserStyleSheetMap* sheetsMap = pageGroup.userStyleSheets();
if (!sheetsMap)
return 0;
UserStyleSheetMap::const_iterator end = sheetsMap->end();
for (UserStyleSheetMap::const_iterator it = sheetsMap->begin(); it != end; ++it) {
const UserStyleSheetVector* sheets = it->second.get();
for (unsigned i = 0; i < sheets->size(); ++i) {
const UserStyleSheet* sheet = sheets->at(i).get();
if (sheet->injectedFrames() == InjectInTopFrameOnly && ownerElement())
continue;
if (!UserContentURLPattern::matchesPatterns(url(), sheet->whitelist(), sheet->blacklist()))
continue;
RefPtr<CSSStyleSheet> groupSheet = CSSStyleSheet::createInline(const_cast<Document*>(this), sheet->url());
if (!m_pageGroupUserSheets)
m_pageGroupUserSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
m_pageGroupUserSheets->append(groupSheet);
groupSheet->internal()->setIsUserStyleSheet(sheet->level() == UserStyleUserLevel);
groupSheet->internal()->parseString(sheet->source());
}
}
return m_pageGroupUserSheets.get();
}
void Document::clearPageGroupUserSheets()
{
m_pageGroupUserSheetCacheValid = false;
if (m_pageGroupUserSheets && m_pageGroupUserSheets->size()) {
m_pageGroupUserSheets->clear();
styleResolverChanged(DeferRecalcStyle);
}
}
void Document::updatePageGroupUserSheets()
{
clearPageGroupUserSheets();
if (pageGroupUserSheets() && pageGroupUserSheets()->size())
styleResolverChanged(RecalcStyleImmediately);
}
void Document::addUserSheet(PassRefPtr<StyleSheetInternal> userSheet)
{
if (!m_userSheets)
m_userSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
m_userSheets->append(CSSStyleSheet::create(userSheet, this));
styleResolverChanged(RecalcStyleImmediately);
}
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 = n->traversePreviousNode())
absIndex++;
return absIndex;
}
Node* Document::nodeWithAbsIndex(int absIndex)
{
Node* n = this;
for (int i = 0; n && (i < absIndex); i++)
n = n->traverseNextNode();
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")) {
m_selectedStylesheetSet = content;
m_preferredStylesheetSet = 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")) {
if (isHTMLDocument()) {
ExceptionCode ec; static_cast<HTMLDocument*>(this)->setCookie(content, ec);
}
} 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();
if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url())) {
frameLoader->stopAllLoaders();
frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), blankURL(), String());
DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to display document because display forbidden by X-Frame-Options.\n"));
addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, consoleMessage);
}
}
} else if (equalIgnoringCase(equiv, "x-webkit-csp"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::EnforcePolicy);
else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::ReportOnly);
}
void setParserFeature(const String& keyString, const String& valueString, Document *aDocument, void* userData)
{
UNUSED_PARAM(aDocument);
Document* document = (Document *)userData;
if ((keyString == "telephone") && equalIgnoringCase(valueString, "no"))
document->setIsTelephoneNumberParsingAllowed(false);
}
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)
{
int keyBegin, keyEnd;
int valueBegin, valueEnd;
int i = 0;
int length = features.length();
String buffer = features.lower();
while (i < length) {
while (isSeparator(buffer[i])) {
if (i >= length)
break;
i++;
}
keyBegin = i;
while (!isSeparator(buffer[i]))
i++;
keyEnd = i;
while (buffer[i] != '=') {
if (buffer[i] == ',' || i >= length)
break;
i++;
}
while (isSeparator(buffer[i])) {
if (buffer[i] == ',' || i >= length)
break;
i++;
}
valueBegin = i;
while (!isSeparator(buffer[i]))
i++;
valueEnd = i;
ASSERT(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)
{
ASSERT(!features.isNull());
m_viewportArguments = ViewportArguments(ViewportArguments::ViewportMeta);
processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
finializeViewportArguments(m_viewportArguments);
updateViewportArguments();
}
void Document::updateViewportArguments()
{
if (page() && page()->mainFrame() == frame()) {
#ifndef NDEBUG
m_didDispatchViewportPropertiesChanged = true;
#endif
page()->chrome()->dispatchViewportPropertiesDidChange(m_viewportArguments);
}
}
void Document::processFormatDetection(const String & features)
{
ASSERT(!features.isNull());
processArguments(features, this, setParserFeature);
}
void Document::processWebAppOrientations()
{
if (page())
page()->chrome()->client()->webAppOrientationsUpdated();
}
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())
updateStyleIfNeeded();
return MouseEventWithHitTestResults(event, result);
}
bool Document::childTypeAllowed(NodeType type) const
{
switch (type) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE:
case 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:
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)
return true;
if (oldChild->nodeType() == newChild->nodeType())
return true;
int numDoctypes = 0;
int numElements = 0;
for (Node* c = firstChild(); c; c = c->nextSibling()) {
if (c == oldChild)
continue;
switch (c->nodeType()) {
case DOCUMENT_TYPE_NODE:
numDoctypes++;
break;
case ELEMENT_NODE:
numElements++;
break;
default:
break;
}
}
if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
for (Node* c = firstChild(); c; c = c->nextSibling()) {
switch (c->nodeType()) {
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:
break;
case DOCUMENT_TYPE_NODE:
numDoctypes++;
break;
case ELEMENT_NODE:
numElements++;
break;
}
}
} else {
switch (newChild->nodeType()) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE:
case 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:
numDoctypes++;
break;
case ELEMENT_NODE:
numElements++;
break;
}
}
if (numElements > 1 || numDoctypes > 1)
return false;
return true;
}
PassRefPtr<Node> Document::cloneNode(bool )
{
return 0;
}
StyleSheetList* Document::styleSheets()
{
return m_styleSheets.get();
}
String Document::preferredStylesheetSet() const
{
return m_preferredStylesheetSet;
}
String Document::selectedStylesheetSet() const
{
return m_selectedStylesheetSet;
}
void Document::setSelectedStylesheetSet(const String& aString)
{
m_selectedStylesheetSet = aString;
styleResolverChanged(DeferRecalcStyle);
}
void Document::removePendingSheet()
{
ASSERT(m_pendingStylesheets > 0);
m_pendingStylesheets--;
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
#endif
if (m_pendingStylesheets)
return;
styleResolverChanged(RecalcStyleIfNeeded);
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->executeScriptsWaitingForStylesheets();
if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
view()->scrollToFragment(m_url);
}
void Document::evaluateMediaQueryList()
{
if (m_mediaQueryMatcher)
m_mediaQueryMatcher->styleResolverChanged();
}
void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
{
if (!attached() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
m_styleResolver.clear();
return;
}
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Beginning update of style selector at time %d.\n", elapsedTime());
#endif
bool stylesheetChangeRequiresStyleRecalc = updateActiveStylesheets(updateFlag);
if (updateFlag == DeferRecalcStyle) {
scheduleForcedStyleRecalc();
return;
}
if (didLayoutWithPendingStylesheets() && m_pendingStylesheets <= 0) {
m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
if (renderer())
renderer()->repaint();
}
if (!stylesheetChangeRequiresStyleRecalc)
return;
{
AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
recalcStyle(Force);
}
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Finished update of style selector at time %d\n", elapsedTime());
#endif
if (renderer()) {
renderer()->setNeedsLayoutAndPrefWidthsRecalc();
if (view())
view()->scheduleRelayout();
}
evaluateMediaQueryList();
}
void Document::addStyleSheetCandidateNode(Node* node, bool createdByParser)
{
if (!node->inDocument())
return;
if ((createdByParser && body()) || m_styleSheetCandidateNodes.isEmpty()) {
m_styleSheetCandidateNodes.add(node);
return;
}
StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
StyleSheetCandidateListHashSet::iterator it = end;
Node* followingNode = 0;
do {
--it;
Node* n = *it;
unsigned short position = n->compareDocumentPosition(node);
if (position == DOCUMENT_POSITION_FOLLOWING) {
m_styleSheetCandidateNodes.insertBefore(followingNode, node);
return;
}
followingNode = n;
} while (it != begin);
m_styleSheetCandidateNodes.insertBefore(followingNode, node);
}
void Document::removeStyleSheetCandidateNode(Node* node)
{
m_styleSheetCandidateNodes.remove(node);
}
void Document::collectActiveStylesheets(Vector<RefPtr<StyleSheet> >& sheets)
{
bool matchAuthorAndUserStyles = true;
if (Settings* settings = this->settings())
matchAuthorAndUserStyles = settings->authorAndUserStylesEnabled();
StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
if (!matchAuthorAndUserStyles)
end = begin;
for (StyleSheetCandidateListHashSet::iterator it = begin; it != end; ++it) {
Node* n = *it;
StyleSheet* sheet = 0;
if (n->nodeType() == PROCESSING_INSTRUCTION_NODE) {
ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
sheet = pi->sheet();
#if ENABLE(XSLT)
if (pi->isXSL() && !transformSourceDocument()) {
if (!parsing())
applyXSLTransform(pi);
return;
}
#endif
} else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag)))
#if ENABLE(SVG)
|| (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
#endif
) {
Element* e = static_cast<Element*>(n);
AtomicString title = e->getAttribute(titleAttr);
bool enabledViaScript = false;
if (e->hasLocalName(linkTag)) {
HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(n);
if (linkElement->isDisabled())
continue;
enabledViaScript = linkElement->isEnabledViaScript();
if (linkElement->styleSheetIsLoading()) {
if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSet.isEmpty()) {
const AtomicString& rel = e->getAttribute(relAttr);
if (!rel.contains("alternate")) {
m_preferredStylesheetSet = title;
m_selectedStylesheetSet = title;
}
}
continue;
}
if (!linkElement->sheet())
title = nullAtom;
}
#if ENABLE(SVG)
if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
sheet = static_cast<SVGStyleElement*>(n)->sheet();
else
#endif
if (e->hasLocalName(linkTag))
sheet = static_cast<HTMLLinkElement*>(n)->sheet();
else
sheet = static_cast<HTMLStyleElement*>(n)->sheet();
AtomicString rel = e->getAttribute(relAttr);
if (!enabledViaScript && !title.isEmpty()) {
if (m_preferredStylesheetSet.isEmpty()) {
if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
m_preferredStylesheetSet = m_selectedStylesheetSet = title;
}
if (title != m_preferredStylesheetSet)
sheet = 0;
}
if (rel.contains("alternate") && title.isEmpty())
sheet = 0;
}
if (sheet)
sheets.append(sheet);
}
}
bool Document::testAddedStylesheetRequiresStyleRecalc(StyleSheetInternal* stylesheet)
{
HashSet<AtomicStringImpl*> idScopes;
HashSet<AtomicStringImpl*> classScopes;
if (!StyleResolver::determineStylesheetSelectorScopes(stylesheet, idScopes, classScopes))
return true;
Node* node = firstChild();
while (node) {
if (!node->isStyledElement()) {
node = node->traverseNextNode();
continue;
}
StyledElement* element = static_cast<StyledElement*>(node);
if (SelectorChecker::elementMatchesSelectorScopes(element, idScopes, classScopes)) {
element->setNeedsStyleRecalc();
node = node->traverseNextSibling();
continue;
}
node = node->traverseNextNode();
}
return false;
}
void Document::analyzeStylesheetChange(StyleResolverUpdateFlag updateFlag, const Vector<RefPtr<StyleSheet> >& newStylesheets, bool& requiresStyleResolverReset, bool& requiresFullStyleRecalc)
{
requiresStyleResolverReset = true;
requiresFullStyleRecalc = true;
bool hasActiveLoadingStylesheet = false;
unsigned newStylesheetCount = newStylesheets.size();
for (unsigned i = 0; i < newStylesheetCount; ++i) {
if (newStylesheets[i]->isLoading())
hasActiveLoadingStylesheet = true;
}
if (m_hadActiveLoadingStylesheet && !hasActiveLoadingStylesheet) {
m_hadActiveLoadingStylesheet = false;
return;
}
m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet;
if (updateFlag != RecalcStyleIfNeeded)
return;
if (!m_styleResolver)
return;
unsigned oldStylesheetCount = m_styleSheets->length();
if (newStylesheetCount < oldStylesheetCount)
return;
for (unsigned i = 0; i < oldStylesheetCount; ++i) {
if (m_styleSheets->item(i) != newStylesheets[i])
return;
}
requiresStyleResolverReset = false;
if (!body() || m_hasNodesWithPlaceholderStyle)
return;
for (unsigned i = oldStylesheetCount; i < newStylesheetCount; ++i) {
if (!newStylesheets[i]->isCSSStyleSheet())
return;
if (newStylesheets[i]->disabled())
continue;
if (testAddedStylesheetRequiresStyleRecalc(static_cast<CSSStyleSheet*>(newStylesheets[i].get())->internal()))
return;
}
requiresFullStyleRecalc = false;
}
static bool styleSheetsUseRemUnits(const Vector<RefPtr<StyleSheet> >& sheets)
{
for (unsigned i = 0; i < sheets.size(); ++i) {
if (!sheets[i]->isCSSStyleSheet())
continue;
if (static_cast<CSSStyleSheet*>(sheets[i].get())->internal()->usesRemUnits())
return true;
}
return false;
}
bool Document::updateActiveStylesheets(StyleResolverUpdateFlag updateFlag)
{
if (m_inStyleRecalc) {
m_hasDirtyStyleResolver = true;
scheduleForcedStyleRecalc();
return false;
}
if (!renderer() || !attached())
return false;
StyleSheetVector newStylesheets;
collectActiveStylesheets(newStylesheets);
bool requiresStyleResolverReset;
bool requiresFullStyleRecalc;
analyzeStylesheetChange(updateFlag, newStylesheets, requiresStyleResolverReset, requiresFullStyleRecalc);
if (requiresStyleResolverReset)
clearStyleResolver();
else {
m_styleResolver->appendAuthorStylesheets(m_styleSheets->length(), newStylesheets);
resetCSSFeatureFlags();
}
m_styleSheets->swap(newStylesheets);
m_usesRemUnits = styleSheetsUseRemUnits(m_styleSheets->vector());
m_didCalculateStyleResolver = true;
m_hasDirtyStyleResolver = false;
return requiresFullStyleRecalc;
}
void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
{
m_hoverNode = newHoverNode;
}
void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
{
m_activeNode = newActiveNode;
}
void Document::focusedNodeRemoved()
{
setFocusedNode(0);
}
void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
{
if (!m_focusedNode || this->inPageCache()) return;
bool nodeInSubtree = false;
if (amongChildrenOnly)
nodeInSubtree = m_focusedNode->isDescendantOf(node);
else
nodeInSubtree = (m_focusedNode == node) || m_focusedNode->isDescendantOf(node);
if (nodeInSubtree)
document()->focusedNodeRemoved();
}
void Document::hoveredNodeDetached(Node* node)
{
if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parentNode())))
return;
m_hoverNode = node->parentNode();
while (m_hoverNode && !m_hoverNode->renderer())
m_hoverNode = m_hoverNode->parentNode();
if (frame())
frame()->eventHandler()->scheduleHoverStateUpdate();
}
void Document::activeChainNodeDetached(Node* node)
{
if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parentNode())))
return;
m_activeNode = node->parentNode();
while (m_activeNode && !m_activeNode->renderer())
m_activeNode = m_activeNode->parentNode();
}
#if ENABLE(DASHBOARD_SUPPORT)
const Vector<DashboardRegionValue>& Document::dashboardRegions() const
{
return m_dashboardRegions;
}
void Document::setDashboardRegions(const Vector<DashboardRegionValue>& regions)
{
m_dashboardRegions = regions;
setDashboardRegionsDirty(false);
}
#endif
bool Document::setFocusedNode(PassRefPtr<Node> prpNewFocusedNode)
{
RefPtr<Node> newFocusedNode = prpNewFocusedNode;
if (newFocusedNode && (newFocusedNode->document() != this))
return true;
if (m_focusedNode == newFocusedNode)
return true;
if (m_inPageCache)
return false;
bool focusChangeBlocked = false;
RefPtr<Node> oldFocusedNode = m_focusedNode;
m_focusedNode = 0;
if (oldFocusedNode && !oldFocusedNode->inDetach()) {
if (oldFocusedNode->active())
oldFocusedNode->setActive(false);
oldFocusedNode->setFocus(false);
if (oldFocusedNode->isElementNode()) {
Element* element = static_cast<Element*>(oldFocusedNode.get());
if (element->wasChangedSinceLastFormControlChangeEvent())
element->dispatchFormControlChangeEvent();
}
oldFocusedNode->dispatchBlurEvent(newFocusedNode);
if (m_focusedNode) {
focusChangeBlocked = true;
newFocusedNode = 0;
}
oldFocusedNode->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedNode); oldFocusedNode->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedNode);
if (m_focusedNode) {
focusChangeBlocked = true;
newFocusedNode = 0;
}
if (oldFocusedNode == this && oldFocusedNode->hasOneRef())
return true;
if (oldFocusedNode == oldFocusedNode->rootEditableElement())
frame()->editor()->didEndEditing();
if (view()) {
Widget* oldWidget = widgetForNode(oldFocusedNode.get());
if (oldWidget)
oldWidget->setFocus(false);
else
view()->setFocus(false);
}
}
if (newFocusedNode) {
if (newFocusedNode == newFocusedNode->rootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
focusChangeBlocked = true;
goto SetFocusedNodeDone;
}
m_focusedNode = newFocusedNode;
m_focusedNode->dispatchFocusEvent(oldFocusedNode);
if (m_focusedNode != newFocusedNode) {
focusChangeBlocked = true;
goto SetFocusedNodeDone;
}
m_focusedNode->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedNode);
if (m_focusedNode != newFocusedNode) {
focusChangeBlocked = true;
goto SetFocusedNodeDone;
}
m_focusedNode->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedNode);
if (m_focusedNode != newFocusedNode) {
focusChangeBlocked = true;
goto SetFocusedNodeDone;
}
m_focusedNode->setFocus(true);
if (m_focusedNode == m_focusedNode->rootEditableElement())
frame()->editor()->didBeginEditing();
if (view()) {
Widget* focusWidget = widgetForNode(m_focusedNode.get());
if (focusWidget) {
updateLayout();
focusWidget = widgetForNode(m_focusedNode.get());
}
if (focusWidget)
focusWidget->setFocus(true);
else
view()->setFocus(true);
}
}
if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled()) {
RenderObject* oldFocusedRenderer = 0;
RenderObject* newFocusedRenderer = 0;
if (oldFocusedNode)
oldFocusedRenderer = oldFocusedNode->renderer();
if (newFocusedNode)
newFocusedRenderer = newFocusedNode->renderer();
axObjectCache()->handleFocusedUIElementChanged(oldFocusedRenderer, newFocusedRenderer);
}
if (!focusChangeBlocked)
page()->chrome()->focusedNodeChanged(m_focusedNode.get());
SetFocusedNodeDone:
updateStyleIfNeeded();
return !focusChangeBlocked;
}
void Document::getFocusableNodes(Vector<RefPtr<Node> >& nodes)
{
updateLayout();
for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
if (node->isFocusable())
nodes.append(node);
}
}
void Document::setCSSTarget(Element* n)
{
if (m_cssTarget)
m_cssTarget->setNeedsStyleRecalc();
m_cssTarget = n;
if (n)
n->setNeedsStyleRecalc();
}
void Document::attachNodeIterator(NodeIterator* ni)
{
m_nodeIterators.add(ni);
}
void Document::detachNodeIterator(NodeIterator* ni)
{
m_nodeIterators.remove(ni);
}
void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
{
HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
if ((*it)->root() == node) {
detachNodeIterator(*it);
newDocument->attachNodeIterator(*it);
}
}
}
void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
{
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->nodeChildrenChanged(container);
}
}
void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
{
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->nodeChildrenWillBeRemoved(container);
}
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
for (Node* n = container->firstChild(); n; n = n->nextSibling())
(*it)->nodeWillBeRemoved(n);
}
if (Frame* frame = this->frame()) {
for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
frame->eventHandler()->nodeWillBeRemoved(n);
frame->selection()->nodeWillBeRemoved(n);
frame->page()->dragCaretController()->nodeWillBeRemoved(n);
}
}
}
void Document::nodeWillBeRemoved(Node* n)
{
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
(*it)->nodeWillBeRemoved(n);
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
(*it)->nodeWillBeRemoved(n);
}
if (Frame* frame = this->frame()) {
frame->eventHandler()->nodeWillBeRemoved(n);
frame->selection()->nodeWillBeRemoved(n);
frame->page()->dragCaretController()->nodeWillBeRemoved(n);
}
}
void Document::textInserted(Node* text, unsigned offset, unsigned length)
{
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->textInserted(text, offset, length);
}
m_markers->shiftMarkers(text, offset, length);
}
void Document::textRemoved(Node* text, unsigned offset, unsigned length)
{
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->textRemoved(text, offset, length);
}
m_markers->removeMarkers(text, offset, length);
m_markers->shiftMarkers(text, offset + length, 0 - length);
}
void Document::textNodesMerged(Text* oldNode, unsigned offset)
{
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
NodeWithIndex oldNodeWithIndex(oldNode);
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->textNodesMerged(oldNodeWithIndex, offset);
}
}
void Document::textNodeSplit(Text* oldNode)
{
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->textNodeSplit(oldNode);
}
}
DOMWindow* Document::domWindow() const
{
if (!frame())
return 0;
if (m_frame->document() != this)
return 0;
return frame()->domWindow();
}
void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
{
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return;
domWindow->setAttributeEventListener(eventType, listener);
}
EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
{
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return 0;
return domWindow->getAttributeEventListener(eventType);
}
void Document::dispatchWindowEvent(PassRefPtr<Event> event, PassRefPtr<EventTarget> target)
{
ASSERT(!eventDispatchForbidden());
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return;
domWindow->dispatchEvent(event, target);
}
void Document::dispatchWindowLoadEvent()
{
ASSERT(!eventDispatchForbidden());
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return;
domWindow->dispatchLoadEvent();
m_loadEventFinished = true;
}
void Document::enqueueWindowEvent(PassRefPtr<Event> event)
{
event->setTarget(domWindow());
m_eventQueue->enqueueEvent(event);
}
void Document::enqueueDocumentEvent(PassRefPtr<Event> event)
{
event->setTarget(this);
m_eventQueue->enqueueEvent(event);
}
PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionCode& ec)
{
RefPtr<Event> event = EventFactory::create(eventType);
if (event)
return event.release();
ec = NOT_SUPPORTED_ERR;
return 0;
}
void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
{
if (eventType == eventNames().DOMSubtreeModifiedEvent)
addListenerType(DOMSUBTREEMODIFIED_LISTENER);
else if (eventType == eventNames().DOMNodeInsertedEvent)
addListenerType(DOMNODEINSERTED_LISTENER);
else if (eventType == eventNames().DOMNodeRemovedEvent)
addListenerType(DOMNODEREMOVED_LISTENER);
else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
else if (eventType == eventNames().DOMAttrModifiedEvent)
addListenerType(DOMATTRMODIFIED_LISTENER);
else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
else if (eventType == eventNames().overflowchangedEvent)
addListenerType(OVERFLOWCHANGED_LISTENER);
else if (eventType == eventNames().webkitAnimationStartEvent)
addListenerType(ANIMATIONSTART_LISTENER);
else if (eventType == eventNames().webkitAnimationEndEvent)
addListenerType(ANIMATIONEND_LISTENER);
else if (eventType == eventNames().webkitAnimationIterationEvent)
addListenerType(ANIMATIONITERATION_LISTENER);
else if (eventType == eventNames().webkitTransitionEndEvent)
addListenerType(TRANSITIONEND_LISTENER);
else if (eventType == eventNames().beforeloadEvent)
addListenerType(BEFORELOAD_LISTENER);
else if (eventType == eventNames().touchstartEvent
|| eventType == eventNames().touchmoveEvent
|| eventType == eventNames().touchendEvent
|| eventType == eventNames().touchcancelEvent) {
addListenerType(TOUCH_LISTENER);
}
else if (eventType == eventNames().scrollEvent)
addListenerType(SCROLL_LISTENER);
else if (eventType == eventNames().webkitRegionLayoutUpdateEvent)
addListenerType(REGIONLAYOUTUPDATE_LISTENER);
}
CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
{
return 0;
}
HTMLFrameOwnerElement* Document::ownerElement() const
{
if (!frame())
return 0;
return frame()->ownerElement();
}
String Document::cookie(ExceptionCode& ec) const
{
if (page() && !page()->cookieEnabled())
return String();
if (!securityOrigin()->canAccessCookies()) {
ec = SECURITY_ERR;
return String();
}
KURL cookieURL = this->cookieURL();
if (cookieURL.isEmpty())
return String();
return cookies(this, cookieURL);
}
void Document::setCookie(const String& value, ExceptionCode& ec)
{
if (page() && !page()->cookieEnabled())
return;
if (!securityOrigin()->canAccessCookies()) {
ec = SECURITY_ERR;
return;
}
KURL cookieURL = this->cookieURL();
if (cookieURL.isEmpty())
return;
setCookies(this, cookieURL, value);
}
String Document::referrer() const
{
if (frame())
return frame()->loader()->referrer();
return String();
}
String Document::domain() const
{
return securityOrigin()->domain();
}
void Document::setDomain(const String& newDomain, ExceptionCode& ec)
{
if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
ec = SECURITY_ERR;
return;
}
if (equalIgnoringCase(domain(), newDomain)) {
securityOrigin()->setDomainFromDOM(newDomain);
if (m_frame)
m_frame->script()->updateSecurityOrigin();
return;
}
int oldLength = domain().length();
int newLength = newDomain.length();
if (newLength >= oldLength) {
ec = SECURITY_ERR;
return;
}
String test = domain();
if (test[oldLength - newLength - 1] != '.') {
ec = SECURITY_ERR;
return;
}
test.remove(0, oldLength - newLength);
if (test != newDomain) {
ec = SECURITY_ERR;
return;
}
securityOrigin()->setDomainFromDOM(newDomain);
if (m_frame)
m_frame->script()->updateSecurityOrigin();
}
String Document::lastModified() const
{
DateComponents date;
bool foundDate = false;
if (m_frame) {
String httpLastModified;
if (DocumentLoader* documentLoader = loader())
httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
if (!httpLastModified.isEmpty()) {
date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
foundDate = true;
}
}
if (!foundDate)
date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
}
static bool isValidNameNonASCII(const UChar* characters, unsigned length)
{
unsigned i = 0;
UChar32 c;
U16_NEXT(characters, i, length, c)
if (!isValidNameStart(c))
return false;
while (i < length) {
U16_NEXT(characters, i, length, c)
if (!isValidNamePart(c))
return false;
}
return true;
}
template<typename CharType>
static inline bool isValidNameASCII(const CharType* characters, unsigned length)
{
CharType c = characters[0];
if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
return false;
for (unsigned i = 1; i < length; ++i) {
c = characters[i];
if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
return false;
}
return true;
}
bool Document::isValidName(const String& name)
{
unsigned length = name.length();
if (!length)
return false;
const UChar* characters;
if (name.is8Bit()) {
if (isValidNameASCII(name.characters8(), length))
return true;
characters = name.characters();
} else {
characters = name.characters16();
if (isValidNameASCII(characters, length))
return true;
}
return isValidNameNonASCII(characters, length);
}
bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode& ec)
{
unsigned length = qualifiedName.length();
if (!length) {
ec = INVALID_CHARACTER_ERR;
return false;
}
bool nameStart = true;
bool sawColon = false;
int colonPos = 0;
const UChar* s = qualifiedName.characters();
for (unsigned i = 0; i < length;) {
UChar32 c;
U16_NEXT(s, i, length, c)
if (c == ':') {
if (sawColon) {
ec = NAMESPACE_ERR;
return false; }
nameStart = true;
sawColon = true;
colonPos = i - 1;
} else if (nameStart) {
if (!isValidNameStart(c)) {
ec = INVALID_CHARACTER_ERR;
return false;
}
nameStart = false;
} else {
if (!isValidNamePart(c)) {
ec = INVALID_CHARACTER_ERR;
return false;
}
}
}
if (!sawColon) {
prefix = String();
localName = qualifiedName;
} else {
prefix = qualifiedName.substring(0, colonPos);
if (prefix.isEmpty()) {
ec = NAMESPACE_ERR;
return false;
}
localName = qualifiedName.substring(colonPos + 1);
}
if (localName.isEmpty()) {
ec = NAMESPACE_ERR;
return false;
}
return true;
}
void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
{
m_decoder = decoder;
}
KURL Document::completeURL(const String& url, const KURL& baseURLOverride) const
{
if (url.isNull())
return KURL();
const KURL& baseURL = ((baseURLOverride.isEmpty() || baseURLOverride == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : baseURLOverride;
if (!m_decoder)
return KURL(baseURL, url);
return KURL(baseURL, url, m_decoder->encoding());
}
KURL Document::completeURL(const String& url) const
{
return completeURL(url, m_baseURL);
}
void Document::setInPageCache(bool flag)
{
if (m_inPageCache == flag)
return;
m_inPageCache = flag;
FrameView* v = view();
if (flag) {
ASSERT(!m_savedRenderer);
m_savedRenderer = renderer();
if (v) {
v->cacheCurrentScrollPosition();
if (page() && page()->mainFrame() == m_frame)
v->resetScrollbarsAndClearContentsSize();
else
v->resetScrollbars();
}
m_styleRecalcTimer.stop();
} else {
ASSERT(!renderer() || renderer() == m_savedRenderer);
ASSERT(m_renderArena);
setRenderer(m_savedRenderer);
m_savedRenderer = 0;
if (childNeedsStyleRecalc())
scheduleStyleRecalc();
}
}
void Document::documentWillBecomeInactive()
{
#if USE(ACCELERATED_COMPOSITING)
if (renderer())
renderView()->willMoveOffscreen();
#endif
}
void Document::documentWillSuspendForPageCache()
{
documentWillBecomeInactive();
HashSet<Element*>::iterator end = m_documentSuspensionCallbackElements.end();
for (HashSet<Element*>::iterator i = m_documentSuspensionCallbackElements.begin(); i != end; ++i)
(*i)->documentWillSuspendForPageCache();
#ifndef NDEBUG
m_didDispatchViewportPropertiesChanged = false;
#endif
}
void Document::documentDidResumeFromPageCache()
{
Vector<Element*> elements;
copyToVector(m_documentSuspensionCallbackElements, elements);
Vector<Element*>::iterator end = elements.end();
for (Vector<Element*>::iterator i = elements.begin(); i != end; ++i)
(*i)->documentDidResumeFromPageCache();
#if USE(ACCELERATED_COMPOSITING)
if (renderer())
renderView()->didMoveOnscreen();
#endif
if (FrameView* frameView = view())
frameView->setAnimatorsAreActive();
ASSERT(m_frame);
m_frame->loader()->client()->dispatchDidBecomeFrameset(isFrameSet());
}
void Document::registerForPageCacheSuspensionCallbacks(Element* e)
{
m_documentSuspensionCallbackElements.add(e);
}
void Document::unregisterForPageCacheSuspensionCallbacks(Element* e)
{
m_documentSuspensionCallbackElements.remove(e);
}
void Document::mediaVolumeDidChange()
{
HashSet<Element*>::iterator end = m_mediaVolumeCallbackElements.end();
for (HashSet<Element*>::iterator i = m_mediaVolumeCallbackElements.begin(); i != end; ++i)
(*i)->mediaVolumeDidChange();
}
void Document::registerForMediaVolumeCallbacks(Element* e)
{
m_mediaVolumeCallbackElements.add(e);
}
void Document::unregisterForMediaVolumeCallbacks(Element* e)
{
m_mediaVolumeCallbackElements.remove(e);
}
void Document::privateBrowsingStateDidChange()
{
HashSet<Element*>::iterator end = m_privateBrowsingStateChangedElements.end();
for (HashSet<Element*>::iterator it = m_privateBrowsingStateChangedElements.begin(); it != end; ++it)
(*it)->privateBrowsingStateDidChange();
}
void Document::registerForPrivateBrowsingStateChangedCallbacks(Element* e)
{
m_privateBrowsingStateChangedElements.add(e);
}
void Document::unregisterForPrivateBrowsingStateChangedCallbacks(Element* e)
{
m_privateBrowsingStateChangedElements.remove(e);
}
void Document::setShouldCreateRenderers(bool f)
{
m_createRenderers = f;
}
bool Document::shouldCreateRenderers()
{
return m_createRenderers;
}
static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
{
Frame* frame = document->frame();
if (!frame || frame->document() != document)
return Editor::Command();
document->updateStyleIfNeeded();
return frame->editor()->command(commandName,
userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
}
bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
{
return command(this, commandName, userInterface).execute(value);
}
bool Document::queryCommandEnabled(const String& commandName)
{
return command(this, commandName).isEnabled();
}
bool Document::queryCommandIndeterm(const String& commandName)
{
return command(this, commandName).state() == MixedTriState;
}
bool Document::queryCommandState(const String& commandName)
{
return command(this, commandName).state() == TrueTriState;
}
bool Document::queryCommandSupported(const String& commandName)
{
return command(this, commandName).isSupported();
}
String Document::queryCommandValue(const String& commandName)
{
return command(this, commandName).value();
}
KURL Document::openSearchDescriptionURL()
{
static const char* const openSearchMIMEType = "application/opensearchdescription+xml";
static const char* const openSearchRelation = "search";
if (!frame() || frame()->tree()->parent())
return KURL();
if (frame()->loader()->state() != FrameStateComplete)
return KURL();
if (!head())
return KURL();
HTMLCollection* children = head()->children();
for (Node* child = children->firstItem(); child; child = children->nextItem()) {
if (!child->hasTagName(linkTag))
continue;
HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(child);
if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
continue;
if (linkElement->href().isEmpty())
continue;
return linkElement->href();
}
return KURL();
}
#if ENABLE(XSLT)
void Document::applyXSLTransform(ProcessingInstruction* pi)
{
RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
processor->setXSLStyleSheet(static_cast<XSLStyleSheet*>(pi->sheet()));
String resultMIMEType;
String newSource;
String resultEncoding;
if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
return;
processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, frame());
}
void Document::setTransformSource(PassOwnPtr<TransformSource> source)
{
m_transformSource = source;
}
#endif
void Document::setDesignMode(InheritedBool value)
{
m_designMode = value;
for (Frame* frame = m_frame; frame && frame->document(); frame = frame->tree()->traverseNext(m_frame))
frame->document()->scheduleForcedStyleRecalc();
}
Document::InheritedBool Document::getDesignMode() const
{
return m_designMode;
}
bool Document::inDesignMode() const
{
for (const Document* d = this; d; d = d->parentDocument()) {
if (d->m_designMode != inherit)
return d->m_designMode;
}
return false;
}
Document* Document::parentDocument() const
{
if (!m_frame)
return 0;
Frame* parent = m_frame->tree()->parent();
if (!parent)
return 0;
return parent->document();
}
Document* Document::topDocument() const
{
Document* doc = const_cast<Document *>(this);
Element* element;
while ((element = doc->ownerElement()))
doc = element->document();
return doc;
}
PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionCode& ec)
{
return createAttributeNS(String(), name, ec, true);
}
PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec, bool shouldIgnoreNamespaceChecks)
{
String prefix, localName;
if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
return 0;
QualifiedName qName(prefix, localName, namespaceURI);
if (!shouldIgnoreNamespaceChecks && !hasValidNamespaceForAttributes(qName)) {
ec = NAMESPACE_ERR;
return 0;
}
return Attr::create(this, qName, emptyString());
}
#if ENABLE(SVG)
const SVGDocumentExtensions* Document::svgExtensions()
{
return m_svgExtensions.get();
}
SVGDocumentExtensions* Document::accessSVGExtensions()
{
if (!m_svgExtensions)
m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this));
return m_svgExtensions.get();
}
bool Document::hasSVGRootNode() const
{
return documentElement() && documentElement()->hasTagName(SVGNames::svgTag);
}
#endif
HTMLCollection* Document::cachedCollection(CollectionType type)
{
ASSERT(static_cast<unsigned>(type) < NumUnnamedDocumentCachedTypes);
if (!m_collections[type])
m_collections[type] = HTMLCollection::create(this, type);
return m_collections[type].get();
}
HTMLCollection* Document::images()
{
return cachedCollection(DocImages);
}
HTMLCollection* Document::applets()
{
return cachedCollection(DocApplets);
}
HTMLCollection* Document::embeds()
{
return cachedCollection(DocEmbeds);
}
HTMLCollection* Document::plugins()
{
return cachedCollection(DocEmbeds);
}
HTMLCollection* Document::objects()
{
return cachedCollection(DocObjects);
}
HTMLCollection* Document::scripts()
{
return cachedCollection(DocScripts);
}
HTMLCollection* Document::links()
{
return cachedCollection(DocLinks);
}
HTMLCollection* Document::forms()
{
return cachedCollection(DocForms);
}
HTMLCollection* Document::anchors()
{
return cachedCollection(DocAnchors);
}
HTMLAllCollection* Document::all()
{
if (!m_allCollection)
m_allCollection = HTMLAllCollection::create(this);
return m_allCollection.get();
}
HTMLCollection* Document::windowNamedItems(const AtomicString& name)
{
OwnPtr<HTMLNameCollection>& collection = m_windowNamedItemCollections.add(name.impl(), nullptr).iterator->second;
if (!collection)
collection = HTMLNameCollection::create(this, WindowNamedItems, name);
return collection.get();
}
HTMLCollection* Document::documentNamedItems(const AtomicString& name)
{
OwnPtr<HTMLNameCollection>& collection = m_documentNamedItemCollections.add(name.impl(), nullptr).iterator->second;
if (!collection)
collection = HTMLNameCollection::create(this, DocumentNamedItems, name);
return collection.get();
}
void Document::finishedParsing()
{
ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
setParsing(false);
if (!m_documentTiming.domContentLoadedEventStart)
m_documentTiming.domContentLoadedEventStart = monotonicallyIncreasingTime();
dispatchEvent(Event::create(eventNames().DOMContentLoadedEvent, true, false));
if (!m_documentTiming.domContentLoadedEventEnd)
m_documentTiming.domContentLoadedEventEnd = monotonicallyIncreasingTime();
if (RefPtr<Frame> f = frame()) {
updateStyleIfNeeded();
f->loader()->finishedParsing();
InspectorInstrumentation::domContentLoadedEventFired(f.get());
}
}
Vector<String> Document::formElementsState() const
{
Vector<String> stateVector;
stateVector.reserveInitialCapacity(m_formElementsWithState.size() * 3);
typedef FormElementListHashSet::const_iterator Iterator;
Iterator end = m_formElementsWithState.end();
for (Iterator it = m_formElementsWithState.begin(); it != end; ++it) {
HTMLFormControlElementWithState* elementWithState = *it;
if (!elementWithState->shouldSaveAndRestoreFormControlState())
continue;
String value;
if (!elementWithState->saveFormControlState(value))
continue;
stateVector.append(elementWithState->formControlName().string());
stateVector.append(elementWithState->formControlType().string());
stateVector.append(value);
}
return stateVector;
}
bool Document::isTelephoneNumberParsingEnabled() const
{
if (!page() || !page()->settings()->telephoneNumberParsingEnabled())
return false;
return m_isTelephoneNumberParsingAllowed;
}
void Document::setIsTelephoneNumberParsingAllowed(bool isTelephoneNumberParsingAllowed)
{
m_isTelephoneNumberParsingAllowed = isTelephoneNumberParsingAllowed;
}
bool Document::isTelephoneNumberParsingAllowed() const
{
return m_isTelephoneNumberParsingAllowed;
}
unsigned Document::formElementsCharacterCount() const
{
typedef FormElementListHashSet::const_iterator Iterator;
Iterator end = m_formElementsWithState.end();
unsigned charCount = 0;
for (Iterator it = m_formElementsWithState.begin(); it != end; ++it) {
HTMLFormControlElementWithState* e = *it;
String value;
if (e->saveFormControlState(value)) {
if (e->isTextFormControl()) {
charCount += value.length();
}
}
}
return charCount;
}
PassRefPtr<XPathExpression> Document::createExpression(const String& expression,
XPathNSResolver* resolver,
ExceptionCode& ec)
{
if (!m_xpathEvaluator)
m_xpathEvaluator = XPathEvaluator::create();
return m_xpathEvaluator->createExpression(expression, resolver, ec);
}
PassRefPtr<XPathNSResolver> Document::createNSResolver(Node* nodeResolver)
{
if (!m_xpathEvaluator)
m_xpathEvaluator = XPathEvaluator::create();
return m_xpathEvaluator->createNSResolver(nodeResolver);
}
PassRefPtr<XPathResult> Document::evaluate(const String& expression,
Node* contextNode,
XPathNSResolver* resolver,
unsigned short type,
XPathResult* result,
ExceptionCode& ec)
{
if (!m_xpathEvaluator)
m_xpathEvaluator = XPathEvaluator::create();
return m_xpathEvaluator->evaluate(expression, contextNode, resolver, type, result, ec);
}
void Document::setStateForNewFormElements(const Vector<String>& stateVector)
{
typedef FormElementStateMap::iterator Iterator;
m_formElementsWithState.clear();
for (size_t i = stateVector.size() / 3 * 3; i; i -= 3) {
AtomicString a = stateVector[i - 3];
AtomicString b = stateVector[i - 2];
const String& c = stateVector[i - 1];
FormElementKey key(a.impl(), b.impl());
Iterator it = m_stateForNewFormElements.find(key);
if (it != m_stateForNewFormElements.end())
it->second.append(c);
else {
Vector<String> v(1);
v[0] = c;
m_stateForNewFormElements.set(key, v);
}
}
}
bool Document::hasStateForNewFormElements() const
{
return !m_stateForNewFormElements.isEmpty();
}
bool Document::takeStateForFormElement(AtomicStringImpl* name, AtomicStringImpl* type, String& state)
{
typedef FormElementStateMap::iterator Iterator;
Iterator it = m_stateForNewFormElements.find(FormElementKey(name, type));
if (it == m_stateForNewFormElements.end())
return false;
ASSERT(it->second.size());
state = it->second.last();
if (it->second.size() > 1)
it->second.removeLast();
else
m_stateForNewFormElements.remove(it);
return true;
}
FormElementKey::FormElementKey(AtomicStringImpl* name, AtomicStringImpl* type)
: m_name(name), m_type(type)
{
ref();
}
FormElementKey::~FormElementKey()
{
deref();
}
FormElementKey::FormElementKey(const FormElementKey& other)
: m_name(other.name()), m_type(other.type())
{
ref();
}
FormElementKey& FormElementKey::operator=(const FormElementKey& other)
{
other.ref();
deref();
m_name = other.name();
m_type = other.type();
return *this;
}
void FormElementKey::ref() const
{
if (name())
name()->ref();
if (type())
type()->ref();
}
void FormElementKey::deref() const
{
if (name())
name()->deref();
if (type())
type()->deref();
}
unsigned FormElementKeyHash::hash(const FormElementKey& key)
{
return StringHasher::hashMemory<sizeof(FormElementKey)>(&key);
}
const Vector<IconURL>& Document::iconURLs() const
{
return m_iconURLs;
}
void Document::addIconURL(const String& url, const String& mimeType, const String& sizes, IconType iconType)
{
if (url.isEmpty())
return;
IconURL newURL(KURL(ParsedURLString, url), sizes, mimeType, iconType);
m_iconURLs.append(newURL);
if (Frame* f = frame()) {
IconURL iconURL = f->loader()->icon()->iconURL(iconType);
if (iconURL == newURL)
f->loader()->didChangeIcons(iconType);
}
}
void Document::registerFormElementWithFormAttribute(FormAssociatedElement* element)
{
ASSERT(toHTMLElement(element)->fastHasAttribute(formAttr));
m_formElementsWithFormAttribute.add(element);
}
void Document::unregisterFormElementWithFormAttribute(FormAssociatedElement* element)
{
m_formElementsWithFormAttribute.remove(element);
}
void Document::resetFormElementsOwner()
{
typedef FormAssociatedElementListHashSet::iterator Iterator;
Iterator end = m_formElementsWithFormAttribute.end();
for (Iterator it = m_formElementsWithFormAttribute.begin(); it != end; ++it)
(*it)->resetFormOwner();
}
void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
{
if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
return;
m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
m_frame->selection()->updateSecureKeyboardEntryIfActive();
}
bool Document::useSecureKeyboardEntryWhenActive() const
{
return m_useSecureKeyboardEntryWhenActive;
}
static bool isEligibleForSeamless(Document* parent, Document* child)
{
if (!parent)
return false;
if (parent->isSandboxed(SandboxSeamlessIframes))
return false;
if (child->isSrcdocDocument())
return true;
if (parent->securityOrigin()->canAccess(child->securityOrigin()))
return true;
return parent->securityOrigin()->canRequest(child->url());
}
void Document::initSecurityContext()
{
if (haveInitializedSecurityOrigin()) {
ASSERT(securityOrigin());
return;
}
if (!m_frame) {
m_cookieURL = KURL(ParsedURLString, emptyString());
setSecurityOrigin(SecurityOrigin::createUnique());
setContentSecurityPolicy(ContentSecurityPolicy::create(this));
return;
}
m_cookieURL = m_url;
enforceSandboxFlags(m_frame->loader()->effectiveSandboxFlags());
if (!m_isSynthesized && m_frame->loader()->activeDocumentLoader()->response().isAttachment())
enforceSandboxFlags(SandboxOrigin);
setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
setContentSecurityPolicy(ContentSecurityPolicy::create(this));
if (SecurityPolicy::allowSubstituteDataAccessToLocal()) {
DocumentLoader* documentLoader = loader();
if (documentLoader && documentLoader->substituteData().isValid())
securityOrigin()->grantLoadLocalResources();
}
if (Settings* settings = this->settings()) {
if (!settings->isWebSecurityEnabled()) {
securityOrigin()->grantUniversalAccess();
} else if (securityOrigin()->isLocal()) {
if (settings->allowUniversalAccessFromFileURLs() || m_frame->loader()->client()->shouldForceUniversalAccessFromLocalURL(m_url)) {
securityOrigin()->grantUniversalAccess();
} else if (!settings->allowFileAccessFromFileURLs()) {
securityOrigin()->enforceFilePathSeparation();
}
}
}
Document* parentDocument = ownerElement() ? ownerElement()->document() : 0;
if (parentDocument && m_frame->loader()->shouldTreatURLAsSrcdocDocument(url())) {
m_isSrcdocDocument = true;
setBaseURLOverride(parentDocument->baseURL());
}
m_mayDisplaySeamlessWithParent = isEligibleForSeamless(parentDocument, this);
if (!shouldInheritSecurityOriginFromOwner(m_url))
return;
Frame* ownerFrame = m_frame->tree()->parent();
if (!ownerFrame)
ownerFrame = m_frame->loader()->opener();
if (!ownerFrame) {
didFailToInitializeSecurityOrigin();
return;
}
if (isSandboxed(SandboxOrigin)) {
if (ownerFrame->document()->securityOrigin()->canLoadLocalResources())
securityOrigin()->grantLoadLocalResources();
return;
}
m_cookieURL = ownerFrame->document()->cookieURL();
setSecurityOrigin(ownerFrame->document()->securityOrigin());
}
void Document::initContentSecurityPolicy()
{
if (!m_frame->tree()->parent() || !shouldInheritSecurityOriginFromOwner(m_url))
return;
contentSecurityPolicy()->copyStateFrom(m_frame->tree()->parent()->document()->contentSecurityPolicy());
}
void Document::setSecurityOrigin(PassRefPtr<SecurityOrigin> origin)
{
SecurityContext::setSecurityOrigin(origin);
}
bool Document::isContextThread() const
{
return isMainThread() || pthread_main_np();
}
void Document::updateURLForPushOrReplaceState(const KURL& url)
{
Frame* f = frame();
if (!f)
return;
setURL(url);
f->loader()->setOutgoingReferrer(url);
if (DocumentLoader* documentLoader = loader())
documentLoader->replaceRequestURLForSameDocumentNavigation(url);
}
void Document::statePopped(SerializedScriptValue* stateObject)
{
if (!frame())
return;
if (m_readyState == Complete)
enqueuePopstateEvent(stateObject);
else
m_pendingStateObject = stateObject;
}
void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
{
m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
if (!m_updateFocusAppearanceTimer.isActive())
m_updateFocusAppearanceTimer.startOneShot(0);
}
void Document::cancelFocusAppearanceUpdate()
{
m_updateFocusAppearanceTimer.stop();
}
void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
{
Node* node = focusedNode();
if (!node)
return;
if (!node->isElementNode())
return;
updateLayout();
Element* element = static_cast<Element*>(node);
if (element->isFocusable())
element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
}
DOMSelection* Document::getSelection() const
{
return frame() ? frame()->domWindow()->getSelection() : 0;
}
void Document::attachRange(Range* range)
{
ASSERT(!m_ranges.contains(range));
m_ranges.add(range);
}
void Document::detachRange(Range* range)
{
m_ranges.remove(range);
}
CanvasRenderingContext* Document::getCSSCanvasContext(const String& type, const String& name, int width, int height)
{
HTMLCanvasElement* element = getCSSCanvasElement(name);
if (!element)
return 0;
element->setSize(IntSize(width, height));
return element->getContext(type);
}
HTMLCanvasElement* Document::getCSSCanvasElement(const String& name)
{
RefPtr<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, 0).iterator->second;
if (!element)
element = HTMLCanvasElement::create(this);
return element.get();
}
static PassRefPtr<RenderStyle> cloneRenderStyleWithState(const RenderStyle* currentStyle)
{
RefPtr<RenderStyle> newStyle = RenderStyle::clone(currentStyle);
if (currentStyle->childrenAffectedByForwardPositionalRules())
newStyle->setChildrenAffectedByForwardPositionalRules();
if (currentStyle->childrenAffectedByBackwardPositionalRules())
newStyle->setChildrenAffectedByBackwardPositionalRules();
if (currentStyle->childrenAffectedByFirstChildRules())
newStyle->setChildrenAffectedByFirstChildRules();
if (currentStyle->childrenAffectedByLastChildRules())
newStyle->setChildrenAffectedByLastChildRules();
if (currentStyle->childrenAffectedByDirectAdjacentRules())
newStyle->setChildrenAffectedByDirectAdjacentRules();
if (currentStyle->lastChildState())
newStyle->setLastChildState();
if (currentStyle->firstChildState())
newStyle->setFirstChildState();
newStyle->setChildIndex(currentStyle->childIndex());
if (currentStyle->affectedByEmpty())
newStyle->setEmptyState(currentStyle->emptyState());
return newStyle.release();
}
TextAutoSizingKey::TextAutoSizingKey() : m_style(0), m_doc(0)
{
}
TextAutoSizingKey::TextAutoSizingKey(RenderStyle* style, Document* doc)
: m_style(style), m_doc(doc)
{
ref();
}
TextAutoSizingKey::TextAutoSizingKey(const TextAutoSizingKey& other)
: m_style(other.m_style), m_doc(other.m_doc)
{
ref();
}
TextAutoSizingKey::~TextAutoSizingKey()
{
deref();
}
TextAutoSizingKey& TextAutoSizingKey::operator=(const TextAutoSizingKey& other)
{
other.ref();
deref();
m_style = other.m_style;
m_doc = other.m_doc;
return *this;
}
void TextAutoSizingKey::ref() const
{
if (isValidStyle())
m_style->ref();
}
void TextAutoSizingKey::deref() const
{
if (isValidStyle() && isValidDoc() && m_doc->renderArena())
m_style->deref();
}
void TextAutoSizingTraits::constructDeletedValue(TextAutoSizingKey& slot)
{
new (&slot) TextAutoSizingKey(TextAutoSizingKey::deletedKeyStyle(), TextAutoSizingKey::deletedKeyDoc());
}
bool TextAutoSizingTraits::isDeletedValue(const TextAutoSizingKey& value)
{
return value.style() == TextAutoSizingKey::deletedKeyStyle() && value.doc() == TextAutoSizingKey::deletedKeyDoc();
}
int TextAutoSizingValue::numNodes() const
{
return m_autoSizedNodes.size();
}
void TextAutoSizingValue::addNode(Node* node, float size)
{
ASSERT(node);
ASSERT(node->renderer());
RenderText* renderText = static_cast<RenderText*>(node->renderer());
renderText->setCandidateComputedTextSize(size);
m_autoSizedNodes.add(node);
}
#define MAX_SCALE_INCREASE 1.7f
bool TextAutoSizingValue::adjustNodeSizes()
{
bool objectsRemoved = false;
Vector<RefPtr<Node> > nodesForRemoval;
HashSet<RefPtr<Node> >::iterator end = m_autoSizedNodes.end();
for (HashSet<RefPtr<Node> >::iterator i = m_autoSizedNodes.begin(); i != end; ++i) {
RefPtr<Node> autoSizingNode = *i;
RenderText* text = static_cast<RenderText*>(autoSizingNode->renderer());
if (!text || (text->style() && !text->style()->textSizeAdjust().isAuto()) || !text->candidateComputedTextSize()) {
nodesForRemoval.append(autoSizingNode);
objectsRemoved = true;
}
}
unsigned count = nodesForRemoval.size();
for (unsigned i = 0; i < count; i++)
m_autoSizedNodes.remove(nodesForRemoval[i]);
if (m_autoSizedNodes.size() <= 1)
return objectsRemoved;
float cumulativeSize = 0;
end = m_autoSizedNodes.end();
for (HashSet<RefPtr<Node> >::iterator i = m_autoSizedNodes.begin(); i != end; ++i) {
RefPtr<Node> autoSizingNode = *i;
RenderText* renderText = static_cast<RenderText*>(autoSizingNode->renderer());
cumulativeSize += renderText->candidateComputedTextSize();
}
float averageSize = roundf(cumulativeSize / m_autoSizedNodes.size());
bool firstPass = true;
end = m_autoSizedNodes.end();
for (HashSet<RefPtr<Node> >::iterator i = m_autoSizedNodes.begin(); i != end; ++i) {
const RefPtr<Node>& autoSizingNode = *i;
RenderText* text = static_cast<RenderText*>(autoSizingNode->renderer());
if (text && text->style()->fontDescription().computedSize() != averageSize) {
float specifiedSize = text->style()->fontDescription().specifiedSize();
float scaleChange = averageSize / specifiedSize;
if (scaleChange > MAX_SCALE_INCREASE && firstPass) {
firstPass = false;
averageSize = roundf(specifiedSize * MAX_SCALE_INCREASE);
scaleChange = averageSize / specifiedSize;
}
RefPtr<RenderStyle> style = cloneRenderStyleWithState(text->style());
FontDescription fontDescription = style->fontDescription();
fontDescription.setComputedSize(averageSize);
style->setFontDescription(fontDescription);
style->font().update(autoSizingNode->document()->styleResolver()->fontSelector());
text->setStyle(style.release());
RenderObject* parentRenderer = text->parent();
if (parentRenderer->isAnonymousBlock())
parentRenderer = parentRenderer->parent();
RenderObject* listMarkerRenderer = parentRenderer->firstChild();
if (listMarkerRenderer->isListMarker()) {
RefPtr<RenderStyle> style = cloneRenderStyleWithState(listMarkerRenderer->style());
style->setFontDescription(fontDescription);
style->font().update(autoSizingNode->document()->styleResolver()->fontSelector());
listMarkerRenderer->setStyle(style.release());
}
const RenderStyle* parentStyle = parentRenderer->style();
Length lineHeightLength = parentStyle->specifiedLineHeight();
int specifiedLineHeight = 0;
if (lineHeightLength.isPercent())
specifiedLineHeight = minimumValueForLength(lineHeightLength, fontDescription.specifiedSize());
else
specifiedLineHeight = lineHeightLength.value();
int lineHeight = specifiedLineHeight * scaleChange;
if (!lineHeightLength.isFixed() || lineHeightLength.value() != lineHeight) {
RefPtr<RenderStyle> newParentStyle = cloneRenderStyleWithState(parentStyle);
newParentStyle->setLineHeight(Length(lineHeight, Fixed));
newParentStyle->setSpecifiedLineHeight(lineHeightLength);
newParentStyle->setFontDescription(fontDescription);
newParentStyle->font().update(autoSizingNode->document()->styleResolver()->fontSelector());
parentRenderer->setStyle(newParentStyle.release());
}
}
}
return objectsRemoved;
}
void TextAutoSizingValue::reset()
{
HashSet<RefPtr<Node> >::iterator end = m_autoSizedNodes.end();
for (HashSet<RefPtr<Node> >::iterator i = m_autoSizedNodes.begin(); i != end; ++i) {
const RefPtr<Node>& autoSizingNode = *i;
RenderText* text = static_cast<RenderText*>(autoSizingNode->renderer());
if (!text)
continue;
FontDescription fontDescription = text->style()->fontDescription();
float originalSize = fontDescription.specifiedSize();
if (fontDescription.computedSize() != originalSize) {
fontDescription.setComputedSize(originalSize);
RefPtr<RenderStyle> style = cloneRenderStyleWithState(text->style());
style->setFontDescription(fontDescription);
style->font().update(autoSizingNode->document()->styleResolver()->fontSelector());
text->setStyle(style.release());
}
RenderObject* parentRenderer = text->parent();
if (!parentRenderer)
continue;
if (parentRenderer->isAnonymousBlock())
parentRenderer = parentRenderer->parent();
const RenderStyle* parentStyle = parentRenderer->style();
Length originalLineHeight = parentStyle->specifiedLineHeight();
if (originalLineHeight != parentStyle->lineHeight()) {
RefPtr<RenderStyle> newParentStyle = cloneRenderStyleWithState(parentStyle);
newParentStyle->setLineHeight(originalLineHeight);
newParentStyle->setFontDescription(fontDescription);
newParentStyle->font().update(autoSizingNode->document()->styleResolver()->fontSelector());
parentRenderer->setStyle(newParentStyle.release());
}
}
}
void Document::addAutoSizingNode(Node* node, float candidateSize)
{
TextAutoSizingKey key(node->renderer()->style(), document());
RefPtr<TextAutoSizingValue> value;
if (m_textAutoSizedNodes.contains(key))
value = m_textAutoSizedNodes.get(key);
else {
value = TextAutoSizingValue::create();
m_textAutoSizedNodes.set(key, value);
}
value->addNode(node, candidateSize);
}
void Document::validateAutoSizingNodes ()
{
Vector<TextAutoSizingKey> nodesForRemoval;
TextAutoSizingMap::iterator end = m_textAutoSizedNodes.end();
for (TextAutoSizingMap::iterator i = m_textAutoSizedNodes.begin(); i != end; ++i) {
TextAutoSizingKey key = i->first;
RefPtr<TextAutoSizingValue> value = i->second;
if (!value)
continue;
value->adjustNodeSizes();
if (!value->numNodes())
nodesForRemoval.append(key);
}
unsigned count = nodesForRemoval.size();
for (unsigned i = 0; i < count; i++)
m_textAutoSizedNodes.remove(nodesForRemoval[i]);
}
void Document::resetAutoSizingNodes()
{
TextAutoSizingMap::iterator end = m_textAutoSizedNodes.end();
for (TextAutoSizingMap::iterator i = m_textAutoSizedNodes.begin(); i != end; ++i) {
RefPtr<TextAutoSizingValue> value = i->second;
if (value)
value->reset();
}
m_textAutoSizedNodes.clear();
}
void Document::initDNSPrefetch()
{
Settings* settings = this->settings();
m_haveExplicitlyDisabledDNSPrefetch = false;
m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
if (Document* parent = parentDocument()) {
if (!parent->isDNSPrefetchEnabled())
m_isDNSPrefetchEnabled = false;
}
}
void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
{
if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
m_isDNSPrefetchEnabled = true;
return;
}
m_isDNSPrefetchEnabled = false;
m_haveExplicitlyDisabledDNSPrefetch = true;
}
void Document::addMessage(MessageSource source, MessageType type, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack)
{
if (!isContextThread()) {
postTask(AddConsoleMessageTask::create(source, type, level, message));
return;
}
if (DOMWindow* window = domWindow())
window->console()->addMessage(source, type, level, message, sourceURL, lineNumber, callStack);
}
struct PerformTaskContext {
WTF_MAKE_NONCOPYABLE(PerformTaskContext); WTF_MAKE_FAST_ALLOCATED;
public:
PerformTaskContext(PassRefPtr<DocumentWeakReference> documentReference, PassOwnPtr<ScriptExecutionContext::Task> task)
: documentReference(documentReference)
, task(task)
{
}
RefPtr<DocumentWeakReference> documentReference;
OwnPtr<ScriptExecutionContext::Task> task;
};
void Document::didReceiveTask(void* untypedContext)
{
ASSERT(isMainThread() || pthread_main_np());
OwnPtr<PerformTaskContext> context = adoptPtr(static_cast<PerformTaskContext*>(untypedContext));
ASSERT(context);
Document* document = context->documentReference->document();
if (!document)
return;
Page* page = document->page();
if ((page && page->defersLoading()) || !document->m_pendingTasks.isEmpty()) {
document->m_pendingTasks.append(context->task.release());
return;
}
context->task->performTask(document);
}
void Document::postTask(PassOwnPtr<Task> task)
{
callOnMainThread(didReceiveTask, new PerformTaskContext(m_weakReference, task));
}
void Document::pendingTasksTimerFired(Timer<Document>*)
{
while (!m_pendingTasks.isEmpty()) {
OwnPtr<Task> task = m_pendingTasks[0].release();
m_pendingTasks.remove(0);
task->performTask(this);
}
}
void Document::suspendScheduledTasks(ActiveDOMObject::ReasonForSuspension reason)
{
ASSERT(!m_scheduledTasksAreSuspended);
suspendScriptedAnimationControllerCallbacks();
suspendActiveDOMObjects(reason);
scriptRunner()->suspend();
m_pendingTasksTimer.stop();
if (m_parser)
m_parser->suspendScheduledTasks();
m_scheduledTasksAreSuspended = true;
}
void Document::resumeScheduledTasks()
{
if (m_parser)
m_parser->resumeScheduledTasks();
if (!m_pendingTasks.isEmpty())
m_pendingTasksTimer.startOneShot(0);
scriptRunner()->resume();
resumeActiveDOMObjects();
resumeScriptedAnimationControllerCallbacks();
m_scheduledTasksAreSuspended = false;
}
void Document::suspendScriptedAnimationControllerCallbacks()
{
#if ENABLE(REQUEST_ANIMATION_FRAME)
if (m_scriptedAnimationController)
m_scriptedAnimationController->suspend();
#endif
}
void Document::resumeScriptedAnimationControllerCallbacks()
{
#if ENABLE(REQUEST_ANIMATION_FRAME)
if (m_scriptedAnimationController)
m_scriptedAnimationController->resume();
#endif
}
void Document::windowScreenDidChange(PlatformDisplayID displayID)
{
#if ENABLE(REQUEST_ANIMATION_FRAME)
if (m_scriptedAnimationController)
m_scriptedAnimationController->windowScreenDidChange(displayID);
#else
UNUSED_PARAM(displayID);
#endif
}
String Document::displayStringModifiedByEncoding(const String& str) const
{
if (m_decoder)
return m_decoder->encoding().displayString(str.impl());
return str;
}
PassRefPtr<StringImpl> Document::displayStringModifiedByEncoding(PassRefPtr<StringImpl> str) const
{
if (m_decoder)
return m_decoder->encoding().displayString(str);
return str;
}
void Document::displayBufferModifiedByEncoding(UChar* buffer, unsigned len) const
{
if (m_decoder)
m_decoder->encoding().displayBuffer(buffer, len);
}
void Document::enqueuePageshowEvent(PageshowEventPersistence persisted)
{
dispatchWindowEvent(PageTransitionEvent::create(eventNames().pageshowEvent, persisted), this);
}
void Document::enqueueHashchangeEvent(const String& oldURL, const String& newURL)
{
enqueueWindowEvent(HashChangeEvent::create(oldURL, newURL));
}
void Document::enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject)
{
dispatchWindowEvent(PopStateEvent::create(stateObject, domWindow() ? domWindow()->history() : 0));
}
void Document::addMediaCanStartListener(MediaCanStartListener* listener)
{
ASSERT(!m_mediaCanStartListeners.contains(listener));
m_mediaCanStartListeners.add(listener);
}
void Document::removeMediaCanStartListener(MediaCanStartListener* listener)
{
ASSERT(m_mediaCanStartListeners.contains(listener));
m_mediaCanStartListeners.remove(listener);
}
MediaCanStartListener* Document::takeAnyMediaCanStartListener()
{
HashSet<MediaCanStartListener*>::iterator slot = m_mediaCanStartListeners.begin();
if (slot == m_mediaCanStartListeners.end())
return 0;
MediaCanStartListener* listener = *slot;
m_mediaCanStartListeners.remove(slot);
return listener;
}
#if ENABLE(DEVICE_ORIENTATION)
DeviceMotionController* Document::deviceMotionController() const
{
return m_deviceMotionController.get();
}
DeviceOrientationController* Document::deviceOrientationController() const
{
return m_deviceOrientationController.get();
}
#endif
#if ENABLE(FULLSCREEN_API)
bool Document::fullScreenIsAllowedForElement(Element* element) const
{
ASSERT(element);
while (HTMLFrameOwnerElement* ownerElement = element->document()->ownerElement()) {
if (!ownerElement->isFrameElementBase())
continue;
if (!static_cast<HTMLFrameElementBase*>(ownerElement)->allowFullScreen())
return false;
element = ownerElement;
}
return true;
}
void Document::requestFullScreenForElement(Element* element, unsigned short flags, FullScreenCheckType checkType)
{
bool inLegacyMozillaMode = (flags & Element::LEGACY_MOZILLA_REQUEST);
do {
if (!element)
element = documentElement();
if (!element->inDocument())
break;
if (checkType == EnforceIFrameAllowFulScreenRequirement && !fullScreenIsAllowedForElement(element))
break;
if (!m_fullScreenElementStack.isEmpty() && !m_fullScreenElementStack.first()->contains(element) && !inLegacyMozillaMode)
break;
bool descendentHasNonEmptyStack = false;
for (Frame* descendant = frame() ? frame()->tree()->traverseNext() : 0; descendant; descendant = descendant->tree()->traverseNext()) {
if (descendant->document()->webkitFullscreenElement()) {
descendentHasNonEmptyStack = true;
break;
}
}
if (descendentHasNonEmptyStack && !inLegacyMozillaMode)
break;
if (!ScriptController::processingUserGesture())
break;
if (!page() || !page()->settings()->fullScreenEnabled())
break;
if (!page()->chrome()->client()->supportsFullScreenForElement(element, flags & Element::ALLOW_KEYBOARD_INPUT))
break;
Document* currentDoc = this;
Deque<Document*> docs;
do {
docs.prepend(currentDoc);
currentDoc = currentDoc->ownerElement() ? currentDoc->ownerElement()->document() : 0;
} while (currentDoc);
Deque<Document*>::iterator current = docs.begin(), following = docs.begin();
do {
++following;
Document* currentDoc = *current;
Document* followingDoc = following != docs.end() ? *following : 0;
if (!followingDoc) {
currentDoc->pushFullscreenElementStack(element);
addDocumentToFullScreenChangeEventQueue(currentDoc);
continue;
}
Element* topElement = currentDoc->webkitFullscreenElement();
if (!topElement || topElement != followingDoc->ownerElement()) {
currentDoc->pushFullscreenElementStack(followingDoc->ownerElement());
addDocumentToFullScreenChangeEventQueue(currentDoc);
continue;
}
} while (++current != docs.end());
m_areKeysEnabledInFullScreen = flags & Element::ALLOW_KEYBOARD_INPUT;
page()->chrome()->client()->enterFullScreenForElement(element);
return;
} while (0);
m_fullScreenErrorEventTargetQueue.append(element ? element : documentElement());
m_fullScreenChangeDelayTimer.startOneShot(0);
}
void Document::webkitCancelFullScreen()
{
if (!topDocument()->webkitFullscreenElement())
return;
Deque<RefPtr<Element> > replacementFullscreenElementStack;
replacementFullscreenElementStack.prepend(topDocument()->webkitFullscreenElement());
topDocument()->m_fullScreenElementStack.swap(replacementFullscreenElementStack);
topDocument()->webkitExitFullscreen();
}
void Document::webkitExitFullscreen()
{
Document* currentDoc = this;
if (m_fullScreenElementStack.isEmpty())
return;
Deque<RefPtr<Document> > descendants;
for (Frame* descendant = frame() ? frame()->tree()->traverseNext() : 0; descendant; descendant = descendant->tree()->traverseNext()) {
if (descendant->document()->webkitFullscreenElement())
descendants.prepend(descendant->document());
}
for (Deque<RefPtr<Document> >::iterator i = descendants.begin(); i != descendants.end(); ++i) {
(*i)->clearFullscreenElementStack();
addDocumentToFullScreenChangeEventQueue(i->get());
}
Element* newTop = 0;
while (currentDoc) {
currentDoc->popFullscreenElementStack();
newTop = currentDoc->webkitFullscreenElement();
if (newTop && (!newTop->inDocument() || newTop->document() != currentDoc))
continue;
Node* target = currentDoc->m_fullScreenElement.get();
if (!target)
target = currentDoc;
addDocumentToFullScreenChangeEventQueue(currentDoc);
if (!newTop && currentDoc->ownerElement())
currentDoc = currentDoc->ownerElement()->document();
currentDoc = 0;
}
if (!newTop) {
page()->chrome()->client()->exitFullScreenForElement(m_fullScreenElement.get());
return;
}
page()->chrome()->client()->enterFullScreenForElement(newTop);
}
bool Document::webkitFullscreenEnabled() const
{
HTMLFrameOwnerElement* owner = ownerElement();
if (!owner)
return true;
do {
if (!owner->isFrameElementBase())
continue;
if (!static_cast<HTMLFrameElementBase*>(owner)->allowFullScreen())
return false;
} while ((owner = owner->document()->ownerElement()));
return true;
}
void Document::webkitWillEnterFullScreenForElement(Element* element)
{
if (!attached() || inPageCache())
return;
ASSERT(element);
if (!page())
return;
ASSERT(page()->settings()->fullScreenEnabled());
if (m_fullScreenRenderer)
m_fullScreenRenderer->unwrapRenderer();
m_fullScreenElement = element;
#if USE(NATIVE_FULLSCREEN_VIDEO)
if (element && element->isMediaElement())
return;
#endif
RenderObject* renderer = m_fullScreenElement->renderer();
bool shouldCreatePlaceholder = renderer && renderer->isBox();
if (shouldCreatePlaceholder) {
m_savedPlaceholderFrameRect = toRenderBox(renderer)->frameRect();
m_savedPlaceholderRenderStyle = RenderStyle::clone(renderer->style());
}
if (m_fullScreenElement != documentElement())
RenderFullScreen::wrapRenderer(renderer, this);
m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
recalcStyle(Force);
}
void Document::webkitDidEnterFullScreenForElement(Element*)
{
if (!m_fullScreenElement)
return;
if (!attached() || inPageCache())
return;
m_fullScreenElement->didBecomeFullscreenElement();
m_fullScreenChangeDelayTimer.startOneShot(0);
}
void Document::webkitWillExitFullScreenForElement(Element*)
{
if (!m_fullScreenElement)
return;
if (!attached() || inPageCache())
return;
m_fullScreenElement->willStopBeingFullscreenElement();
}
void Document::webkitDidExitFullScreenForElement(Element*)
{
if (!m_fullScreenElement)
return;
if (!attached() || inPageCache())
return;
m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
m_areKeysEnabledInFullScreen = false;
if (m_fullScreenRenderer)
m_fullScreenRenderer->unwrapRenderer();
m_fullScreenElement = 0;
scheduleForcedStyleRecalc();
m_fullScreenChangeDelayTimer.startOneShot(0);
}
void Document::setFullScreenRenderer(RenderFullScreen* renderer)
{
if (renderer == m_fullScreenRenderer)
return;
if (renderer && m_savedPlaceholderRenderStyle)
renderer->createPlaceholder(m_savedPlaceholderRenderStyle.release(), m_savedPlaceholderFrameRect);
else if (renderer && m_fullScreenRenderer && m_fullScreenRenderer->placeholder()) {
RenderBlock* placeholder = m_fullScreenRenderer->placeholder();
renderer->createPlaceholder(RenderStyle::clone(placeholder->style()), placeholder->frameRect());
}
if (m_fullScreenRenderer)
m_fullScreenRenderer->destroy();
ASSERT(!m_fullScreenRenderer);
m_fullScreenRenderer = renderer;
if (page())
page()->chrome()->client()->fullScreenRendererChanged(m_fullScreenRenderer);
}
void Document::fullScreenRendererDestroyed()
{
m_fullScreenRenderer = 0;
if (page())
page()->chrome()->client()->fullScreenRendererChanged(0);
}
void Document::setFullScreenRendererSize(const IntSize& size)
{
ASSERT(m_fullScreenRenderer);
if (!m_fullScreenRenderer)
return;
if (m_fullScreenRenderer) {
RefPtr<RenderStyle> newStyle = RenderStyle::clone(m_fullScreenRenderer->style());
newStyle->setWidth(Length(size.width(), WebCore::Fixed));
newStyle->setHeight(Length(size.height(), WebCore::Fixed));
newStyle->setTop(Length(0, WebCore::Fixed));
newStyle->setLeft(Length(0, WebCore::Fixed));
m_fullScreenRenderer->setStyle(newStyle);
updateLayout();
}
}
void Document::setFullScreenRendererBackgroundColor(Color backgroundColor)
{
if (!m_fullScreenRenderer)
return;
RefPtr<RenderStyle> newStyle = RenderStyle::clone(m_fullScreenRenderer->style());
newStyle->setBackgroundColor(backgroundColor);
m_fullScreenRenderer->setStyle(newStyle);
}
void Document::fullScreenChangeDelayTimerFired(Timer<Document>*)
{
Deque<RefPtr<Node> > changeQueue;
m_fullScreenChangeEventTargetQueue.swap(changeQueue);
while (!changeQueue.isEmpty()) {
RefPtr<Node> node = changeQueue.takeFirst();
if (!node)
node = documentElement();
if (!contains(node.get()))
changeQueue.append(documentElement());
node->dispatchEvent(Event::create(eventNames().webkitfullscreenchangeEvent, true, false));
}
Deque<RefPtr<Node> > errorQueue;
m_fullScreenErrorEventTargetQueue.swap(errorQueue);
while (!errorQueue.isEmpty()) {
RefPtr<Node> node = errorQueue.takeFirst();
if (!node)
node = documentElement();
if (!contains(node.get()))
errorQueue.append(documentElement());
node->dispatchEvent(Event::create(eventNames().webkitfullscreenerrorEvent, true, false));
}
}
void Document::fullScreenElementRemoved()
{
m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
webkitCancelFullScreen();
}
void Document::removeFullScreenElementOfSubtree(Node* node, bool amongChildrenOnly)
{
if (!m_fullScreenElement)
return;
bool elementInSubtree = false;
if (amongChildrenOnly)
elementInSubtree = m_fullScreenElement->isDescendantOf(node);
else
elementInSubtree = (m_fullScreenElement == node) || m_fullScreenElement->isDescendantOf(node);
if (elementInSubtree)
fullScreenElementRemoved();
}
bool Document::isAnimatingFullScreen() const
{
return m_isAnimatingFullScreen;
}
void Document::setAnimatingFullScreen(bool flag)
{
if (m_isAnimatingFullScreen == flag)
return;
m_isAnimatingFullScreen = flag;
if (m_fullScreenElement && m_fullScreenElement->isDescendantOf(this)) {
m_fullScreenElement->setNeedsStyleRecalc();
scheduleForcedStyleRecalc();
}
}
void Document::clearFullscreenElementStack()
{
m_fullScreenElementStack.clear();
}
void Document::popFullscreenElementStack()
{
if (m_fullScreenElementStack.isEmpty())
return;
m_fullScreenElementStack.removeFirst();
}
void Document::pushFullscreenElementStack(Element* element)
{
m_fullScreenElementStack.prepend(element);
}
void Document::addDocumentToFullScreenChangeEventQueue(Document* doc)
{
ASSERT(doc);
Node* target = doc->webkitFullscreenElement();
if (!target)
target = doc->webkitCurrentFullScreenElement();
if (!target)
target = doc;
m_fullScreenChangeEventTargetQueue.append(target);
}
#endif
void Document::decrementLoadEventDelayCount()
{
ASSERT(m_loadEventDelayCount);
--m_loadEventDelayCount;
if (frame() && !m_loadEventDelayCount && !m_loadEventDelayTimer.isActive())
m_loadEventDelayTimer.startOneShot(0);
}
void Document::loadEventDelayTimerFired(Timer<Document>*)
{
if (frame())
frame()->loader()->checkCompleted();
}
#if ENABLE(REQUEST_ANIMATION_FRAME)
int Document::webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback)
{
if (!m_scriptedAnimationController) {
#if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
m_scriptedAnimationController = ScriptedAnimationController::create(this, page() ? page()->displayID() : 0);
#else
m_scriptedAnimationController = ScriptedAnimationController::create(this, 0);
#endif
if (!page() || page()->scriptedAnimationsSuspended())
m_scriptedAnimationController->suspend();
}
return m_scriptedAnimationController->registerCallback(callback);
}
void Document::webkitCancelAnimationFrame(int id)
{
if (!m_scriptedAnimationController)
return;
m_scriptedAnimationController->cancelCallback(id);
}
void Document::serviceScriptedAnimations(DOMTimeStamp time)
{
if (!m_scriptedAnimationController)
return;
m_scriptedAnimationController->serviceScriptedAnimations(time);
}
#endif
static void wheelEventHandlerCountChanged(Document* document)
{
Page* page = document->page();
if (!page)
return;
ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator();
if (!scrollingCoordinator)
return;
FrameView* frameView = document->view();
if (!frameView)
return;
scrollingCoordinator->frameViewWheelEventHandlerCountChanged(frameView);
}
void Document::didAddWheelEventHandler()
{
++m_wheelEventHandlerCount;
Frame* mainFrame = page() ? page()->mainFrame() : 0;
if (mainFrame)
mainFrame->notifyChromeClientWheelEventHandlerCountChanged();
wheelEventHandlerCountChanged(this);
}
void Document::didRemoveWheelEventHandler()
{
ASSERT(m_wheelEventHandlerCount > 0);
--m_wheelEventHandlerCount;
Frame* mainFrame = page() ? page()->mainFrame() : 0;
if (mainFrame)
mainFrame->notifyChromeClientWheelEventHandlerCountChanged();
wheelEventHandlerCountChanged(this);
}
void Document::didAddTouchEventHandler()
{
++m_touchEventHandlerCount;
Frame* mainFrame = page() ? page()->mainFrame() : 0;
if (mainFrame)
mainFrame->notifyChromeClientTouchEventHandlerCountChanged();
}
void Document::didRemoveTouchEventHandler()
{
ASSERT(m_touchEventHandlerCount > 0);
--m_touchEventHandlerCount;
Frame* mainFrame = page() ? page()->mainFrame() : 0;
if (mainFrame)
mainFrame->notifyChromeClientTouchEventHandlerCountChanged();
}
HTMLIFrameElement* Document::seamlessParentIFrame() const
{
if (!shouldDisplaySeamlesslyWithParent())
return 0;
HTMLFrameOwnerElement* ownerElement = this->ownerElement();
ASSERT(ownerElement->hasTagName(iframeTag));
return static_cast<HTMLIFrameElement*>(ownerElement);
}
bool Document::shouldDisplaySeamlesslyWithParent() const
{
#if ENABLE(IFRAME_SEAMLESS)
HTMLFrameOwnerElement* ownerElement = this->ownerElement();
if (!ownerElement)
return false;
return m_mayDisplaySeamlessWithParent && ownerElement->hasTagName(iframeTag) && ownerElement->fastHasAttribute(seamlessAttr);
#else
return false;
#endif
}
DocumentLoader* Document::loader() const
{
if (!m_frame)
return 0;
DocumentLoader* loader = m_frame->loader()->documentLoader();
if (!loader)
return 0;
if (m_frame->document() != this)
return 0;
return loader;
}
#if ENABLE(MICRODATA)
PassRefPtr<NodeList> Document::getItems(const String& typeNames)
{
NodeListsNodeData* nodeLists = ensureRareData()->ensureNodeLists(this);
String localTypeNames = typeNames.isNull() ? String("http://webkit.org/microdata/undefinedItemType") : typeNames;
NodeListsNodeData::MicroDataItemListCache::AddResult result = nodeLists->m_microDataItemListCache.add(localTypeNames, 0);
if (!result.isNewEntry)
return PassRefPtr<NodeList>(result.iterator->second);
RefPtr<MicroDataItemList> list = MicroDataItemList::create(this, typeNames);
result.iterator->second = list.get();
return list.release();
}
void Document::removeCachedMicroDataItemList(MicroDataItemList* list, const String& typeNames)
{
ASSERT(rareData());
ASSERT(rareData()->nodeLists());
NodeListsNodeData* data = rareData()->nodeLists();
String localTypeNames = typeNames.isNull() ? String("http://webkit.org/microdata/undefinedItemType") : typeNames;
ASSERT_UNUSED(list, list == data->m_microDataItemListCache.get(localTypeNames));
data->m_microDataItemListCache.remove(localTypeNames);
}
#endif
IntSize Document::viewportSize() const
{
if (!view())
return IntSize();
return view()->visibleContentRect( true).size();
}
Node* eventTargetNodeForDocument(Document* doc)
{
if (!doc)
return 0;
Node* node = doc->focusedNode();
if (!node && doc->isPluginDocument()) {
PluginDocument* pluginDocument = static_cast<PluginDocument*>(doc);
node = pluginDocument->pluginNode();
}
if (!node && doc->isHTMLDocument())
node = doc->body();
if (!node)
node = doc->documentElement();
return node;
}
}