2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Dirk Mueller (mueller@kde.org)
5 * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
6 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2011, 2012, 2013 Apple Inc. All rights reserved.
7 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8 * Copyright (C) 2008, 2009, 2011, 2012 Google Inc. All rights reserved.
9 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
10 * Copyright (C) Research In Motion Limited 2010-2011. All rights reserved.
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public License
23 * along with this library; see the file COPYING.LIB. If not, write to
24 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 * Boston, MA 02110-1301, USA.
31 #include "AXObjectCache.h"
32 #include "AnimationController.h"
34 #include "CDATASection.h"
35 #include "CSSStyleDeclaration.h"
36 #include "CSSStyleSheet.h"
37 #include "CachedCSSStyleSheet.h"
38 #include "CachedResourceLoader.h"
40 #include "ChromeClient.h"
42 #include "ContentSecurityPolicy.h"
43 #include "CookieJar.h"
44 #include "DOMImplementation.h"
45 #include "DOMNamedFlowCollection.h"
46 #include "DOMWindow.h"
47 #include "DateComponents.h"
48 #include "Dictionary.h"
49 #include "DocumentLoader.h"
50 #include "DocumentMarkerController.h"
51 #include "DocumentSharedObjectPool.h"
52 #include "DocumentType.h"
54 #include "ElementIterator.h"
55 #include "EntityReference.h"
56 #include "EventFactory.h"
57 #include "EventHandler.h"
58 #include "FocusController.h"
59 #include "FontLoader.h"
60 #include "FormController.h"
61 #include "FrameLoader.h"
62 #include "FrameLoaderClient.h"
63 #include "FrameView.h"
64 #include "HTMLAllCollection.h"
65 #include "HTMLAnchorElement.h"
66 #include "HTMLBaseElement.h"
67 #include "HTMLBodyElement.h"
68 #include "HTMLCanvasElement.h"
69 #include "HTMLCollection.h"
70 #include "HTMLDocument.h"
71 #include "HTMLElementFactory.h"
72 #include "HTMLFormControlElement.h"
73 #include "HTMLFrameOwnerElement.h"
74 #include "HTMLFrameSetElement.h"
75 #include "HTMLHeadElement.h"
76 #include "HTMLIFrameElement.h"
77 #include "HTMLImageElement.h"
78 #include "HTMLLinkElement.h"
79 #include "HTMLMediaElement.h"
80 #include "HTMLNameCollection.h"
81 #include "HTMLParserIdioms.h"
82 #include "HTMLPlugInElement.h"
83 #include "HTMLScriptElement.h"
84 #include "HTMLStyleElement.h"
85 #include "HTMLTitleElement.h"
86 #include "HTTPHeaderNames.h"
87 #include "HTTPParsers.h"
88 #include "HashChangeEvent.h"
90 #include "HitTestResult.h"
91 #include "IconController.h"
92 #include "ImageLoader.h"
93 #include "InspectorInstrumentation.h"
94 #include "JSLazyEventListener.h"
96 #include "LoaderStrategy.h"
98 #include "MainFrame.h"
99 #include "MediaCanStartListener.h"
100 #include "MediaQueryList.h"
101 #include "MediaQueryMatcher.h"
102 #include "MouseEventWithHitTestResults.h"
103 #include "NameNodeList.h"
104 #include "NestingLevelIncrementer.h"
105 #include "NodeIterator.h"
106 #include "NodeRareData.h"
107 #include "NodeWithIndex.h"
108 #include "PageConsoleClient.h"
109 #include "PageGroup.h"
110 #include "PageTransitionEvent.h"
111 #include "PlatformLocale.h"
112 #include "PlatformStrategies.h"
113 #include "PlugInsResources.h"
114 #include "PluginDocument.h"
115 #include "PointerLockController.h"
116 #include "PopStateEvent.h"
117 #include "ProcessingInstruction.h"
118 #include "RenderChildIterator.h"
119 #include "RenderLayerCompositor.h"
120 #include "RenderView.h"
121 #include "RenderWidget.h"
122 #include "ResourceLoadScheduler.h"
123 #include "ResourceLoader.h"
124 #include "RuntimeEnabledFeatures.h"
125 #include "SVGDocumentExtensions.h"
126 #include "SVGElementFactory.h"
127 #include "SVGNames.h"
128 #include "SVGSVGElement.h"
129 #include "SchemeRegistry.h"
130 #include "ScopedEventQueue.h"
131 #include "ScriptController.h"
132 #include "ScriptRunner.h"
133 #include "ScriptSourceCode.h"
134 #include "ScrollingCoordinator.h"
135 #include "SecurityOrigin.h"
136 #include "SecurityPolicy.h"
137 #include "SegmentedString.h"
138 #include "SelectorQuery.h"
139 #include "Settings.h"
140 #include "ShadowRoot.h"
141 #include "StyleProperties.h"
142 #include "StyleResolver.h"
143 #include "StyleSheetContents.h"
144 #include "StyleSheetList.h"
145 #include "TextResourceDecoder.h"
146 #include "TransformSource.h"
147 #include "TreeWalker.h"
148 #include "VisitedLinkState.h"
149 #include "XMLDocumentParser.h"
150 #include "XMLNSNames.h"
151 #include "XMLNames.h"
152 #include "XPathEvaluator.h"
153 #include "XPathExpression.h"
154 #include "XPathNSResolver.h"
155 #include "XPathResult.h"
156 #include "htmlediting.h"
157 #include <inspector/ScriptCallStack.h>
158 #include <wtf/CurrentTime.h>
159 #include <wtf/TemporaryChange.h>
160 #include <wtf/text/StringBuffer.h>
161 #include <yarr/RegularExpression.h>
163 #if ENABLE(SHARED_WORKERS)
164 #include "SharedWorkerRepository.h"
168 #include "XSLTProcessor.h"
172 #if ENABLE(TOUCH_EVENTS)
173 #include "TouchList.h"
177 #include "CSSFontSelector.h"
178 #include "DeviceMotionClientIOS.h"
179 #include "DeviceMotionController.h"
180 #include "DeviceOrientationClientIOS.h"
181 #include "DeviceOrientationController.h"
182 #include "Geolocation.h"
183 #include "Navigator.h"
184 #include "NavigatorGeolocation.h"
185 #include "WKContentObservation.h"
186 #include "WebCoreSystemInterface.h"
189 #if ENABLE(IOS_GESTURE_EVENTS)
190 #include "GestureEvent.h"
194 #include "MathMLElement.h"
195 #include "MathMLElementFactory.h"
196 #include "MathMLNames.h"
199 #if ENABLE(FULLSCREEN_API)
200 #include "RenderFullScreen.h"
203 #if ENABLE(REQUEST_ANIMATION_FRAME)
204 #include "RequestAnimationFrameCallback.h"
205 #include "ScriptedAnimationController.h"
208 #if ENABLE(IOS_TEXT_AUTOSIZING)
209 #include "TextAutoSizing.h"
212 #if ENABLE(TEXT_AUTOSIZING)
213 #include "TextAutosizer.h"
217 #include "DOMSecurityPolicy.h"
220 #if ENABLE(VIDEO_TRACK)
221 #include "CaptionUserPreferences.h"
224 #if ENABLE(WEB_REPLAY)
225 #include "WebReplayInputs.h"
226 #include <replay/EmptyInputCursor.h>
227 #include <replay/InputCursor.h>
231 using namespace Unicode;
235 using namespace HTMLNames;
237 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
239 static const unsigned cMaxWriteRecursionDepth = 21;
241 // DOM Level 2 says (letters added):
243 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
244 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
245 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
246 // d) Characters which have a font or compatibility decomposition (i.e. those with a "compatibility formatting tag" in field 5 of the database -- marked by field 5 beginning with a "<") are not allowed.
247 // e) The following characters are treated as name-start characters rather than name characters, because the property file classifies them as Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.
248 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
249 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
250 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
251 // i) Characters ':' and '_' are allowed as name-start characters.
252 // j) Characters '-' and '.' are allowed as name characters.
254 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
256 static inline bool isValidNameStart(UChar32 c)
259 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
263 if (c == ':' || c == '_')
266 // rules (a) and (f) above
267 if (!(U_GET_GC_MASK(c) & (U_GC_LL_MASK | U_GC_LU_MASK | U_GC_LO_MASK | U_GC_LT_MASK | U_GC_NL_MASK)))
271 if (c >= 0xF900 && c < 0xFFFE)
275 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
276 if (type == U_DT_FONT || type == U_DT_COMPAT)
282 static inline bool isValidNamePart(UChar32 c)
284 // rules (a), (e), and (i) above
285 if (isValidNameStart(c))
288 // rules (g) and (h) above
289 if (c == 0x00B7 || c == 0x0387)
293 if (c == '-' || c == '.')
296 // rules (b) and (f) above
297 if (!(U_GET_GC_MASK(c) & (U_GC_M_MASK | U_GC_LM_MASK | U_GC_ND_MASK)))
301 if (c >= 0xF900 && c < 0xFFFE)
305 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
306 if (type == U_DT_FONT || type == U_DT_COMPAT)
312 static bool shouldInheritSecurityOriginFromOwner(const URL& url)
314 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
316 // If a Document has the address "about:blank"
317 // The origin of the Document is the origin it was assigned when its browsing context was created.
319 // Note: We generalize this to all "blank" URLs and invalid URLs because we
320 // treat all of these URLs as about:blank.
322 return url.isEmpty() || url.isBlankURL();
325 static Widget* widgetForElement(Element* focusedElement)
329 auto renderer = focusedElement->renderer();
330 if (!renderer || !renderer->isWidget())
332 return toRenderWidget(renderer)->widget();
335 static bool acceptsEditingFocus(Node* node)
338 ASSERT(node->hasEditableStyle());
340 Node* root = node->rootEditableElement();
341 Frame* frame = node->document().frame();
345 return frame->editor().shouldBeginEditing(rangeOfContents(*root).get());
348 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
350 // targetFrame can be 0 when we're trying to navigate a top-level frame
351 // that has a 0 opener.
355 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
356 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
357 Document* ancestorDocument = ancestorFrame->document();
358 // FIXME: Should be an ASSERT? Frames should alway have documents.
359 if (!ancestorDocument)
362 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
363 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
366 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
367 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
368 // something more general instead?
369 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
376 static void printNavigationErrorMessage(Frame* frame, const URL& activeURL, const char* reason)
378 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
380 // FIXME: should we print to the console of the document performing the navigation instead?
381 frame->document()->domWindow()->printErrorMessage(message);
384 uint64_t Document::s_globalTreeVersion = 0;
386 #if ENABLE(IOS_TEXT_AUTOSIZING)
387 void TextAutoSizingTraits::constructDeletedValue(TextAutoSizingKey& slot)
389 new (&slot) TextAutoSizingKey(TextAutoSizingKey::deletedKeyStyle(), TextAutoSizingKey::deletedKeyDoc());
392 bool TextAutoSizingTraits::isDeletedValue(const TextAutoSizingKey& value)
394 return value.style() == TextAutoSizingKey::deletedKeyStyle() && value.doc() == TextAutoSizingKey::deletedKeyDoc();
398 HashSet<Document*>& Document::allDocuments()
400 static NeverDestroyed<HashSet<Document*>> documents;
404 Document::Document(Frame* frame, const URL& url, unsigned documentClasses, unsigned constructionFlags)
405 : ContainerNode(*this, CreateDocument)
407 #if ENABLE(IOS_TOUCH_EVENTS)
408 , m_handlingTouchEvent(false)
409 , m_touchEventRegionsDirty(false)
410 , m_touchEventsChangedTimer(this, &Document::touchEventsChangedTimerFired)
412 , m_referencingNodeCount(0)
413 , m_didCalculateStyleResolver(false)
414 , m_hasNodesWithPlaceholderStyle(false)
415 , m_needsNotifyRemoveAllPendingStylesheet(false)
416 , m_ignorePendingStylesheets(false)
417 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
419 , m_activeParserCount(0)
420 , m_wellFormed(false)
422 , m_paginatedForScreen(false)
423 , m_ignoreAutofocus(false)
424 , m_compatibilityMode(DocumentCompatibilityMode::NoQuirksMode)
425 , m_compatibilityModeLocked(false)
426 , m_textColor(Color::black)
427 , m_domTreeVersion(++s_globalTreeVersion)
429 , m_mutationObserverTypes(0)
430 , m_styleSheetCollection(*this)
431 , m_visitedLinkState(std::make_unique<VisitedLinkState>(*this))
432 , m_visuallyOrdered(false)
433 , m_readyState(Complete)
435 , m_optimizedStyleSheetUpdateTimer(this, &Document::optimizedStyleSheetUpdateTimerFired)
436 , m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
437 , m_pendingStyleRecalcShouldForce(false)
438 , m_inStyleRecalc(false)
439 , m_closeAfterStyleRecalc(false)
440 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
441 , m_frameElementsShouldIgnoreScrolling(false)
442 , m_containsValidityStyleRules(false)
443 , m_updateFocusAppearanceRestoresSelection(false)
444 , m_ignoreDestructiveWriteCount(0)
445 , m_titleSetExplicitly(false)
446 , m_markers(std::make_unique<DocumentMarkerController>())
447 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
448 , m_cssTarget(nullptr)
449 , m_processingLoadEvent(false)
450 , m_loadEventFinished(false)
451 , m_startTime(std::chrono::steady_clock::now())
452 , m_overMinimumLayoutThreshold(false)
453 , m_scriptRunner(std::make_unique<ScriptRunner>(*this))
454 , m_xmlVersion(ASCIILiteral("1.0"))
455 , m_xmlStandalone(StandaloneUnspecified)
456 , m_hasXMLDeclaration(false)
457 , m_designMode(inherit)
459 , m_inInvalidateNodeListAndCollectionCaches(false)
461 #if ENABLE(DASHBOARD_SUPPORT)
462 , m_hasAnnotatedRegions(false)
463 , m_annotatedRegionsDirty(false)
465 , m_createRenderers(true)
466 , m_inPageCache(false)
467 , m_accessKeyMapValid(false)
468 , m_documentClasses(documentClasses)
469 , m_isSynthesized(constructionFlags & Synthesized)
470 , m_isNonRenderedPlaceholder(constructionFlags & NonRenderedPlaceholder)
471 , m_sawElementsInKnownNamespaces(false)
472 , m_isSrcdocDocument(false)
473 , m_eventQueue(*this)
474 , m_weakFactory(this)
475 #if ENABLE(FULLSCREEN_API)
476 , m_areKeysEnabledInFullScreen(0)
477 , m_fullScreenRenderer(nullptr)
478 , m_fullScreenChangeDelayTimer(this, &Document::fullScreenChangeDelayTimerFired)
479 , m_isAnimatingFullScreen(false)
481 , m_loadEventDelayCount(0)
482 , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
483 , m_referrerPolicy(ReferrerPolicyDefault)
484 , m_directionSetOnDocumentElement(false)
485 , m_writingModeSetOnDocumentElement(false)
486 , m_writeRecursionIsTooDeep(false)
487 , m_writeRecursionDepth(0)
488 , m_wheelEventHandlerCount(0)
489 , m_lastHandledUserGestureTimestamp(0)
491 #if ENABLE(DEVICE_ORIENTATION)
492 , m_deviceMotionClient(std::make_unique<DeviceMotionClientIOS>())
493 , m_deviceMotionController(std::make_unique<DeviceMotionController>(m_deviceMotionClient.get()))
494 , m_deviceOrientationClient(std::make_unique<DeviceOrientationClientIOS>())
495 , m_deviceOrientationController(std::make_unique<DeviceOrientationController>(m_deviceOrientationClient.get()))
498 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
499 , m_isTelephoneNumberParsingAllowed(true)
501 , m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
502 , m_scheduledTasksAreSuspended(false)
503 , m_visualUpdatesAllowed(true)
504 , m_visualUpdatesSuppressionTimer(this, &Document::visualUpdatesSuppressionTimerFired)
505 , m_sharedObjectPoolClearTimer(this, &Document::sharedObjectPoolClearTimerFired)
507 , m_didDispatchViewportPropertiesChanged(false)
509 #if ENABLE(TEMPLATE_ELEMENT)
510 , m_templateDocumentHost(nullptr)
512 #if ENABLE(WEB_REPLAY)
513 , m_inputCursor(EmptyInputCursor::create())
515 , m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
516 , m_disabledFieldsetElementsCount(0)
517 , m_hasInjectedPlugInsScript(false)
518 , m_renderTreeBeingDestroyed(false)
519 , m_hasPreparedForDestruction(false)
520 , m_hasStyleWithViewportUnits(false)
522 allDocuments().add(this);
524 // We depend on the url getting immediately set in subframes, but we
525 // also depend on the url NOT getting immediately set in opened windows.
526 // See fast/dom/early-frame-url.html
527 // and fast/dom/location-new-window-no-crash.html, respectively.
528 // FIXME: Can/should we unify this behavior?
529 if ((frame && frame->ownerElement()) || !url.isEmpty())
533 m_cachedResourceLoader = &m_frame->loader().activeDocumentLoader()->cachedResourceLoader();
534 if (!m_cachedResourceLoader)
535 m_cachedResourceLoader = CachedResourceLoader::create(nullptr);
536 m_cachedResourceLoader->setDocument(this);
538 #if ENABLE(TEXT_AUTOSIZING)
539 m_textAutosizer = std::make_unique<TextAutosizer>(this);
543 resetVisitedLinkColor();
544 resetActiveLinkColor();
546 initSecurityContext();
549 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListAndCollectionCounts); ++i)
550 m_nodeListAndCollectionCounts[i] = 0;
553 #if ENABLE(FULLSCREEN_API)
554 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
559 if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
561 } while ((owner = owner->document().ownerElement()));
566 PassRefPtr<Document> Document::create(ScriptExecutionContext& context)
568 RefPtr<Document> document = adoptRef(new Document(nullptr, URL()));
569 document->setSecurityOrigin(context.securityOrigin());
570 return document.release();
573 Document::~Document()
575 allDocuments().remove(this);
577 ASSERT(!renderView());
578 ASSERT(!m_inPageCache);
579 ASSERT(m_ranges.isEmpty());
580 ASSERT(!m_parentTreeScope);
581 ASSERT(!m_disabledFieldsetElementsCount);
583 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
584 m_deviceMotionClient->deviceMotionControllerDestroyed();
585 m_deviceOrientationClient->deviceOrientationControllerDestroyed();
588 #if ENABLE(TEMPLATE_ELEMENT)
589 if (m_templateDocument)
590 m_templateDocument->setTemplateDocumentHost(nullptr); // balanced in templateDocument().
593 // FIXME: Should we reset m_domWindow when we detach from the Frame?
595 m_domWindow->resetUnlessSuspendedForPageCache();
597 m_scriptRunner = nullptr;
599 removeAllEventListeners();
601 // Currently we believe that Document can never outlive the parser.
602 // Although the Document may be replaced synchronously, DocumentParsers
603 // generally keep at least one reference to an Element which would in turn
604 // has a reference to the Document. If you hit this ASSERT, then that
605 // assumption is wrong. DocumentParser::detach() should ensure that even
606 // if the DocumentParser outlives the Document it won't cause badness.
607 ASSERT(!m_parser || m_parser->refCount() == 1);
610 if (this == &topDocument())
611 clearAXObjectCache();
615 if (m_styleSheetList)
616 m_styleSheetList->detachFromDocument();
619 m_elementSheet->detachFromDocument();
620 m_styleSheetCollection.detachFromDocument();
622 clearStyleResolver(); // We need to destroy CSSFontSelector before destroying m_cachedResourceLoader.
624 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
625 // load the initial empty document and the SVGDocument with the same DocumentLoader).
626 if (m_cachedResourceLoader->document() == this)
627 m_cachedResourceLoader->setDocument(nullptr);
628 m_cachedResourceLoader.clear();
630 // We must call clearRareData() here since a Document class inherits TreeScope
631 // as well as Node. See a comment on TreeScope.h for the reason.
635 ASSERT(!m_listsInvalidatedAtDocument.size());
636 ASSERT(!m_collectionsInvalidatedAtDocument.size());
638 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListAndCollectionCounts); ++i)
639 ASSERT(!m_nodeListAndCollectionCounts[i]);
642 void Document::removedLastRef()
644 ASSERT(!m_deletionHasBegun);
645 if (m_referencingNodeCount) {
646 // If removing a child removes the last node reference, we don't want the scope to be destroyed
647 // until after removeDetachedChildren returns, so we protect ourselves.
648 incrementReferencingNodeCount();
650 // We must make sure not to be retaining any of our children through
651 // these extra pointers or we will create a reference cycle.
652 m_focusedElement = nullptr;
653 m_hoveredElement = nullptr;
654 m_activeElement = nullptr;
655 m_titleElement = nullptr;
656 m_documentElement = nullptr;
657 m_userActionElements.documentDidRemoveLastRef();
658 #if ENABLE(FULLSCREEN_API)
659 m_fullScreenElement = nullptr;
660 m_fullScreenElementStack.clear();
665 // removeDetachedChildren() doesn't always unregister IDs,
666 // so tear down scope information up front to avoid having
667 // stale references in the map.
669 destroyTreeScopeData();
670 removeDetachedChildren();
671 m_formController = nullptr;
675 m_cssCanvasElements.clear();
680 // We need to do this right now since selfOnlyDeref() can delete this.
681 m_inRemovedLastRefFunction = false;
683 decrementReferencingNodeCount();
686 m_inRemovedLastRefFunction = false;
687 m_deletionHasBegun = true;
693 void Document::commonTeardown()
696 accessSVGExtensions()->pauseAnimations();
698 #if ENABLE(REQUEST_ANIMATION_FRAME)
699 clearScriptedAnimationController();
703 Element* Document::getElementByAccessKey(const String& key)
707 if (!m_accessKeyMapValid) {
708 buildAccessKeyMap(this);
709 m_accessKeyMapValid = true;
711 return m_elementsByAccessKey.get(key.impl());
714 void Document::buildAccessKeyMap(TreeScope* scope)
717 for (auto& element : descendantsOfType<Element>(scope->rootNode())) {
718 const AtomicString& accessKey = element.fastGetAttribute(accesskeyAttr);
719 if (!accessKey.isEmpty())
720 m_elementsByAccessKey.set(accessKey.impl(), &element);
722 if (ShadowRoot* root = element.shadowRoot())
723 buildAccessKeyMap(root);
727 void Document::invalidateAccessKeyMap()
729 m_accessKeyMapValid = false;
730 m_elementsByAccessKey.clear();
733 void Document::addImageElementByLowercasedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
735 return m_imagesByUsemap.add(name, element, *this);
738 void Document::removeImageElementByLowercasedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
740 return m_imagesByUsemap.remove(name, element);
743 HTMLImageElement* Document::imageElementByLowercasedUsemap(const AtomicStringImpl& name) const
745 return m_imagesByUsemap.getElementByLowercasedUsemap(name, *this);
748 SelectorQuery* Document::selectorQueryForString(const String& selectorString, ExceptionCode& ec)
750 if (selectorString.isEmpty()) {
755 if (!m_selectorQueryCache)
756 m_selectorQueryCache = std::make_unique<SelectorQueryCache>();
757 return m_selectorQueryCache->add(selectorString, *this, ec);
760 void Document::clearSelectorQueryCache()
762 m_selectorQueryCache = nullptr;
765 MediaQueryMatcher& Document::mediaQueryMatcher()
767 if (!m_mediaQueryMatcher)
768 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
769 return *m_mediaQueryMatcher;
772 void Document::setCompatibilityMode(DocumentCompatibilityMode mode)
774 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
776 bool wasInQuirksMode = inQuirksMode();
777 m_compatibilityMode = mode;
779 clearSelectorQueryCache();
781 if (inQuirksMode() != wasInQuirksMode) {
782 // All user stylesheets have to reparse using the different mode.
783 m_styleSheetCollection.clearPageUserSheet();
784 m_styleSheetCollection.invalidateInjectedStyleSheetCache();
788 String Document::compatMode() const
790 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
793 void Document::resetLinkColor()
795 m_linkColor = Color(0, 0, 238);
798 void Document::resetVisitedLinkColor()
800 m_visitedLinkColor = Color(85, 26, 139);
803 void Document::resetActiveLinkColor()
805 m_activeLinkColor.setNamedColor("red");
808 DOMImplementation& Document::implementation()
810 if (!m_implementation)
811 m_implementation = std::make_unique<DOMImplementation>(*this);
812 return *m_implementation;
815 bool Document::hasManifest() const
817 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->fastHasAttribute(manifestAttr);
820 DocumentType* Document::doctype() const
822 for (Node* node = firstChild(); node; node = node->nextSibling()) {
823 if (node->isDocumentTypeNode())
824 return static_cast<DocumentType*>(node);
829 void Document::childrenChanged(const ChildChange& change)
831 ContainerNode::childrenChanged(change);
834 // FIXME: Chrome::didReceiveDocType() used to be called only when the doctype changed. We need to check the
835 // impact of calling this systematically. If the overhead is negligible, we need to rename didReceiveDocType,
836 // otherwise, we need to detect the doc type changes before updating the viewport.
837 if (Page* page = this->page())
838 page->chrome().didReceiveDocType(frame());
841 Element* newDocumentElement = childrenOfType<Element>(*this).first();
842 if (newDocumentElement == m_documentElement)
844 m_documentElement = newDocumentElement;
845 // The root style used for media query matching depends on the document element.
846 clearStyleResolver();
849 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
851 if (!isValidName(name)) {
852 ec = INVALID_CHARACTER_ERR;
856 if (isXHTMLDocument())
857 return HTMLElementFactory::createElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), *this);
859 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
862 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
864 return DocumentFragment::create(document());
867 PassRefPtr<Text> Document::createTextNode(const String& data)
869 return Text::create(*this, data);
872 PassRefPtr<Comment> Document::createComment(const String& data)
874 return Comment::create(*this, data);
877 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
879 if (isHTMLDocument()) {
880 ec = NOT_SUPPORTED_ERR;
883 return CDATASection::create(*this, data);
886 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
888 if (!isValidName(target)) {
889 ec = INVALID_CHARACTER_ERR;
892 if (isHTMLDocument()) {
893 ec = NOT_SUPPORTED_ERR;
896 return ProcessingInstruction::create(*this, target, data);
899 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
901 if (!isValidName(name)) {
902 ec = INVALID_CHARACTER_ERR;
905 if (isHTMLDocument()) {
906 ec = NOT_SUPPORTED_ERR;
909 return EntityReference::create(*this, name);
912 PassRefPtr<Text> Document::createEditingTextNode(const String& text)
914 return Text::createEditingText(*this, text);
917 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
919 Ref<MutableStyleProperties> propertySet(MutableStyleProperties::create());
920 return propertySet->ensureCSSStyleDeclaration();
923 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
928 ec = NOT_SUPPORTED_ERR;
932 switch (importedNode->nodeType()) {
934 return createTextNode(importedNode->nodeValue());
935 case CDATA_SECTION_NODE:
936 return createCDATASection(importedNode->nodeValue(), ec);
937 case ENTITY_REFERENCE_NODE:
938 return createEntityReference(importedNode->nodeName(), ec);
939 case PROCESSING_INSTRUCTION_NODE:
940 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
942 return createComment(importedNode->nodeValue());
944 Element& oldElement = toElement(*importedNode);
945 // FIXME: The following check might be unnecessary. Is it possible that
946 // oldElement has mismatched prefix/namespace?
947 if (!hasValidNamespaceForElements(oldElement.tagQName())) {
952 RefPtr<Element> newElement = createElement(oldElement.tagQName(), false);
953 newElement->cloneDataFromElement(oldElement);
956 for (Node* oldChild = oldElement.firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
957 RefPtr<Node> newChild = importNode(oldChild, true, ec);
960 newElement->appendChild(newChild.release(), ec);
966 return newElement.release();
969 return Attr::create(*this, QualifiedName(nullAtom, toAttr(*importedNode).name(), nullAtom), toAttr(*importedNode).value());
970 case DOCUMENT_FRAGMENT_NODE: {
971 if (importedNode->isShadowRoot()) {
972 // ShadowRoot nodes should not be explicitly importable.
973 // Either they are imported along with their host node, or created implicitly.
976 DocumentFragment& oldFragment = toDocumentFragment(*importedNode);
977 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
979 for (Node* oldChild = oldFragment.firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
980 RefPtr<Node> newChild = importNode(oldChild, true, ec);
983 newFragment->appendChild(newChild.release(), ec);
989 return newFragment.release();
993 // FIXME: It should be possible to import these node types, however in DOM3 the DocumentType is readonly, so there isn't much sense in doing that.
994 // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
996 case DOCUMENT_TYPE_NODE:
997 case XPATH_NAMESPACE_NODE:
1000 ec = NOT_SUPPORTED_ERR;
1005 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
1008 ec = NOT_SUPPORTED_ERR;
1012 if (source->isReadOnlyNode()) {
1013 ec = NO_MODIFICATION_ALLOWED_ERR;
1017 EventQueueScope scope;
1019 switch (source->nodeType()) {
1023 case DOCUMENT_TYPE_NODE:
1024 case XPATH_NAMESPACE_NODE:
1025 ec = NOT_SUPPORTED_ERR;
1027 case ATTRIBUTE_NODE: {
1028 Attr& attr = toAttr(*source);
1029 if (attr.ownerElement())
1030 attr.ownerElement()->removeAttributeNode(&attr, ec);
1034 if (source->isShadowRoot()) {
1035 // ShadowRoot cannot disconnect itself from the host node.
1036 ec = HIERARCHY_REQUEST_ERR;
1039 if (source->isFrameOwnerElement()) {
1040 HTMLFrameOwnerElement& frameOwnerElement = toHTMLFrameOwnerElement(*source);
1041 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement.contentFrame())) {
1042 ec = HIERARCHY_REQUEST_ERR;
1046 if (source->parentNode()) {
1047 source->parentNode()->removeChild(source.get(), ec);
1053 adoptIfNeeded(source.get());
1058 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1060 // These checks are from DOM Core Level 2, createElementNS
1061 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1062 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1064 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1067 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1068 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1069 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1070 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1071 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1072 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1075 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1077 return hasValidNamespaceForElements(qName);
1080 // FIXME: This should really be in a possible ElementFactory class.
1081 PassRefPtr<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1083 RefPtr<Element> element;
1085 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1086 if (name.namespaceURI() == xhtmlNamespaceURI)
1087 element = HTMLElementFactory::createElement(name, *this, nullptr, createdByParser);
1088 else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1089 element = SVGElementFactory::createElement(name, *this, createdByParser);
1091 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1092 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1096 m_sawElementsInKnownNamespaces = true;
1098 element = Element::create(name, document());
1100 // <image> uses imgTag so we need a special rule.
1101 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1103 return element.release();
1106 bool Document::cssRegionsEnabled() const
1108 return RuntimeEnabledFeatures::sharedFeatures().cssRegionsEnabled();
1111 bool Document::cssCompositingEnabled() const
1113 return RuntimeEnabledFeatures::sharedFeatures().cssCompositingEnabled();
1116 #if ENABLE(CSS_REGIONS)
1118 PassRefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
1120 if (!cssRegionsEnabled() || !renderView())
1123 updateStyleIfNeeded();
1125 return namedFlows().createCSSOMSnapshot();
1130 NamedFlowCollection& Document::namedFlows()
1133 m_namedFlows = NamedFlowCollection::create(this);
1135 return *m_namedFlows;
1138 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
1140 String prefix, localName;
1141 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
1144 QualifiedName qName(prefix, localName, namespaceURI);
1145 if (!hasValidNamespaceForElements(qName)) {
1150 return createElement(qName, false);
1153 String Document::readyState() const
1155 DEPRECATED_DEFINE_STATIC_LOCAL(const String, loading, (ASCIILiteral("loading")));
1156 DEPRECATED_DEFINE_STATIC_LOCAL(const String, interactive, (ASCIILiteral("interactive")));
1157 DEPRECATED_DEFINE_STATIC_LOCAL(const String, complete, (ASCIILiteral("complete")));
1159 switch (m_readyState) {
1168 ASSERT_NOT_REACHED();
1172 void Document::setReadyState(ReadyState readyState)
1174 if (readyState == m_readyState)
1177 #if ENABLE(WEB_TIMING)
1178 switch (readyState) {
1180 if (!m_documentTiming.domLoading)
1181 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1184 if (!m_documentTiming.domInteractive)
1185 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1188 if (!m_documentTiming.domComplete)
1189 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1194 m_readyState = readyState;
1195 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1197 if (settings() && settings()->suppressesIncrementalRendering())
1198 setVisualUpdatesAllowed(readyState);
1201 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1203 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1204 switch (readyState) {
1206 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1207 ASSERT(m_visualUpdatesAllowed);
1208 setVisualUpdatesAllowed(false);
1211 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1214 if (m_visualUpdatesSuppressionTimer.isActive()) {
1215 ASSERT(!m_visualUpdatesAllowed);
1217 if (!view()->visualUpdatesAllowedByClient())
1220 setVisualUpdatesAllowed(true);
1222 ASSERT(m_visualUpdatesAllowed);
1227 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1229 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1232 m_visualUpdatesAllowed = visualUpdatesAllowed;
1234 if (visualUpdatesAllowed)
1235 m_visualUpdatesSuppressionTimer.stop();
1237 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1239 if (!visualUpdatesAllowed)
1242 FrameView* frameView = view();
1243 bool needsLayout = frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout());
1247 if (Page* page = this->page()) {
1248 if (frame()->isMainFrame()) {
1249 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1250 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1251 frame()->loader().didLayout(DidFirstLayoutAfterSuppressedIncrementalRendering);
1256 view()->updateCompositingLayersAfterLayout();
1258 if (RenderView* renderView = this->renderView())
1259 renderView->repaintViewAndCompositedLayers();
1261 if (Frame* frame = this->frame())
1262 frame->loader().forcePageTransitionIfNeeded();
1265 void Document::visualUpdatesSuppressionTimerFired(Timer<Document>&)
1267 ASSERT(!m_visualUpdatesAllowed);
1269 // If the client is extending the visual update suppression period explicitly, the
1270 // watchdog should not re-enable visual updates itself, but should wait for the client.
1271 if (!view()->visualUpdatesAllowedByClient())
1274 setVisualUpdatesAllowed(true);
1277 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1279 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1280 // both of which we can determine by looking at the timer.
1282 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1283 setVisualUpdatesAllowed(true);
1286 AtomicString Document::encoding() const
1288 if (TextResourceDecoder* d = decoder())
1289 return d->encoding().domName();
1293 String Document::defaultCharset() const
1295 if (Settings* settings = this->settings())
1296 return settings->defaultTextEncodingName();
1300 void Document::setCharset(const String& charset)
1304 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1307 void Document::setContentLanguage(const String& language)
1309 if (m_contentLanguage == language)
1311 m_contentLanguage = language;
1313 // Recalculate style so language is used when selecting the initial font.
1314 styleResolverChanged(DeferRecalcStyle);
1317 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1319 if (!implementation().hasFeature("XML", String())) {
1320 ec = NOT_SUPPORTED_ERR;
1324 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1325 ec = NOT_SUPPORTED_ERR;
1329 m_xmlVersion = version;
1332 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1334 if (!implementation().hasFeature("XML", String())) {
1335 ec = NOT_SUPPORTED_ERR;
1339 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1342 void Document::setDocumentURI(const String& uri)
1344 // This property is read-only from JavaScript, but writable from Objective-C.
1345 m_documentURI = uri;
1349 URL Document::baseURI() const
1354 void Document::setContent(const String& content)
1357 // FIXME: This should probably use insert(), but that's (intentionally)
1358 // not implemented for the XML parser as it's normally synonymous with
1359 // document.write(). append() will end up yielding, but close() will
1360 // pump the tokenizer syncrhonously and finish the parse.
1361 m_parser->append(content.impl());
1365 String Document::suggestedMIMEType() const
1367 if (isXHTMLDocument())
1368 return ASCIILiteral("application/xhtml+xml");
1369 if (isSVGDocument())
1370 return ASCIILiteral("image/svg+xml");
1371 if (xmlStandalone())
1372 return ASCIILiteral("text/xml");
1373 if (isHTMLDocument())
1374 return ASCIILiteral("text/html");
1375 if (DocumentLoader* loader = this->loader())
1376 return loader->responseMIMEType();
1380 Node* Document::nodeFromPoint(const LayoutPoint& clientPoint, LayoutPoint* localPoint)
1382 if (!frame() || !view())
1385 Frame& frame = *this->frame();
1387 float scaleFactor = frame.pageZoomFactor() * frame.frameScaleFactor();
1389 LayoutPoint contentsPoint = clientPoint;
1390 contentsPoint.scale(scaleFactor, scaleFactor);
1391 contentsPoint.moveBy(view()->contentsScrollPosition());
1393 LayoutRect visibleRect;
1395 visibleRect = view()->unobscuredContentRect();
1397 visibleRect = view()->visibleContentRect();
1399 if (!visibleRect.contains(contentsPoint))
1402 HitTestResult result(contentsPoint);
1403 renderView()->hitTest(HitTestRequest(), result);
1406 *localPoint = result.localPoint();
1408 return result.innerNode();
1411 Element* Document::elementFromPoint(const LayoutPoint& clientPoint)
1413 if (!hasLivingRenderTree())
1416 Node* node = nodeFromPoint(clientPoint);
1417 while (node && !node->isElementNode())
1418 node = node->parentNode();
1421 node = ancestorInThisScope(node);
1423 return toElement(node);
1426 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1428 return caretRangeFromPoint(LayoutPoint(x, y));
1431 PassRefPtr<Range> Document::caretRangeFromPoint(const LayoutPoint& clientPoint)
1433 if (!hasLivingRenderTree())
1436 LayoutPoint localPoint;
1437 Node* node = nodeFromPoint(clientPoint, &localPoint);
1441 Node* shadowAncestorNode = ancestorInThisScope(node);
1442 if (shadowAncestorNode != node) {
1443 unsigned offset = shadowAncestorNode->computeNodeIndex();
1444 ContainerNode* container = shadowAncestorNode->parentNode();
1445 return Range::create(*this, container, offset, container, offset);
1448 RenderObject* renderer = node->renderer();
1451 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint, nullptr);
1452 if (visiblePosition.isNull())
1455 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1456 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1460 * Performs three operations:
1461 * 1. Convert control characters to spaces
1462 * 2. Trim leading and trailing spaces
1463 * 3. Collapse internal whitespace.
1465 template <typename CharacterType>
1466 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1468 const String& title = titleWithDirection.string();
1469 const CharacterType* characters = title.characters<CharacterType>();
1470 unsigned length = title.length();
1473 StringBuffer<CharacterType> buffer(length);
1474 unsigned builderIndex = 0;
1476 // Skip leading spaces and leading characters that would convert to spaces
1477 for (i = 0; i < length; ++i) {
1478 CharacterType c = characters[i];
1479 if (!(c <= 0x20 || c == 0x7F))
1484 return StringWithDirection();
1486 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1487 bool previousCharWasWS = false;
1488 for (; i < length; ++i) {
1489 CharacterType c = characters[i];
1490 if (c <= 0x20 || c == 0x7F || (U_GET_GC_MASK(c) & (U_GC_ZL_MASK | U_GC_ZP_MASK))) {
1491 if (previousCharWasWS)
1493 buffer[builderIndex++] = ' ';
1494 previousCharWasWS = true;
1496 buffer[builderIndex++] = c;
1497 previousCharWasWS = false;
1501 // Strip trailing spaces
1502 while (builderIndex > 0) {
1504 if (buffer[builderIndex] != ' ')
1508 if (!builderIndex && buffer[builderIndex] == ' ')
1509 return StringWithDirection();
1511 buffer.shrink(builderIndex + 1);
1513 // Replace the backslashes with currency symbols if the encoding requires it.
1514 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1516 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1519 void Document::updateTitle(const StringWithDirection& title)
1521 if (m_rawTitle == title)
1526 if (m_rawTitle.string().isEmpty())
1527 m_title = StringWithDirection();
1529 if (m_rawTitle.string().is8Bit())
1530 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1532 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1534 if (DocumentLoader* loader = this->loader())
1535 loader->setTitle(m_title);
1538 void Document::setTitle(const String& title)
1540 // Title set by JavaScript -- overrides any title elements.
1541 m_titleSetExplicitly = true;
1542 if (!isHTMLDocument() && !isXHTMLDocument())
1543 m_titleElement = nullptr;
1544 else if (!m_titleElement) {
1545 if (HTMLElement* headElement = head()) {
1546 m_titleElement = createElement(titleTag, false);
1547 headElement->appendChild(m_titleElement, ASSERT_NO_EXCEPTION);
1551 // The DOM API has no method of specifying direction, so assume LTR.
1552 updateTitle(StringWithDirection(title, LTR));
1554 if (m_titleElement && isHTMLTitleElement(m_titleElement.get()))
1555 toHTMLTitleElement(m_titleElement.get())->setText(title);
1558 void Document::setTitleElement(const StringWithDirection& title, Element* titleElement)
1560 if (titleElement != m_titleElement) {
1561 if (m_titleElement || m_titleSetExplicitly) {
1562 // Only allow the first title element to change the title -- others have no effect.
1565 m_titleElement = titleElement;
1571 void Document::removeTitle(Element* titleElement)
1573 if (m_titleElement != titleElement)
1576 m_titleElement = nullptr;
1577 m_titleSetExplicitly = false;
1579 // Update title based on first title element in the head, if one exists.
1580 if (HTMLElement* headElement = head()) {
1581 if (auto firstTitle = childrenOfType<HTMLTitleElement>(*headElement).first())
1582 setTitleElement(firstTitle->textWithDirection(), firstTitle);
1585 if (!m_titleElement)
1586 updateTitle(StringWithDirection());
1589 void Document::registerForVisibilityStateChangedCallbacks(Element* element)
1591 m_visibilityStateCallbackElements.add(element);
1594 void Document::unregisterForVisibilityStateChangedCallbacks(Element* element)
1596 m_visibilityStateCallbackElements.remove(element);
1599 void Document::visibilityStateChanged()
1601 dispatchEvent(Event::create(eventNames().visibilitychangeEvent, false, false));
1602 for (auto it = m_visibilityStateCallbackElements.begin(); it != m_visibilityStateCallbackElements.end(); ++it)
1603 (*it)->visibilityStateChanged();
1606 PageVisibilityState Document::pageVisibilityState() const
1608 // The visibility of the document is inherited from the visibility of the
1609 // page. If there is no page associated with the document, we will assume
1610 // that the page is hidden, as specified by the spec:
1611 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1612 if (!m_frame || !m_frame->page())
1613 return PageVisibilityStateHidden;
1614 return m_frame->page()->visibilityState();
1617 String Document::visibilityState() const
1619 return pageVisibilityStateString(pageVisibilityState());
1622 bool Document::hidden() const
1624 return pageVisibilityState() != PageVisibilityStateVisible;
1627 #if ENABLE(CSP_NEXT)
1628 DOMSecurityPolicy& Document::securityPolicy()
1630 if (!m_domSecurityPolicy)
1631 m_domSecurityPolicy = DOMSecurityPolicy::create(this);
1632 return *m_domSecurityPolicy;
1636 String Document::nodeName() const
1641 Node::NodeType Document::nodeType() const
1643 return DOCUMENT_NODE;
1646 FormController& Document::formController()
1648 if (!m_formController)
1649 m_formController = std::make_unique<FormController>();
1650 return *m_formController;
1653 Vector<String> Document::formElementsState() const
1655 if (!m_formController)
1656 return Vector<String>();
1657 return m_formController->formElementsState();
1660 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1662 if (!stateVector.size() && !m_formController)
1664 formController().setStateForNewFormElements(stateVector);
1667 FrameView* Document::view() const
1669 return m_frame ? m_frame->view() : nullptr;
1672 Page* Document::page() const
1674 return m_frame ? m_frame->page() : nullptr;
1677 Settings* Document::settings() const
1679 return m_frame ? &m_frame->settings() : nullptr;
1682 PassRefPtr<Range> Document::createRange()
1684 return Range::create(*this);
1687 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1688 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1691 ec = NOT_SUPPORTED_ERR;
1694 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1697 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
1698 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1701 ec = NOT_SUPPORTED_ERR;
1704 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1707 void Document::scheduleForcedStyleRecalc()
1709 m_pendingStyleRecalcShouldForce = true;
1710 scheduleStyleRecalc();
1713 void Document::scheduleStyleRecalc()
1715 if (m_styleRecalcTimer.isActive() || inPageCache())
1718 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1720 // FIXME: Why on earth is this here? This is clearly misplaced.
1721 invalidateAccessKeyMap();
1723 m_styleRecalcTimer.startOneShot(0);
1725 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1728 void Document::unscheduleStyleRecalc()
1730 ASSERT(!childNeedsStyleRecalc());
1732 m_styleRecalcTimer.stop();
1733 m_pendingStyleRecalcShouldForce = false;
1736 bool Document::hasPendingStyleRecalc() const
1738 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1741 bool Document::hasPendingForcedStyleRecalc() const
1743 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1746 void Document::styleRecalcTimerFired(Timer<Document>&)
1748 updateStyleIfNeeded();
1751 void Document::recalcStyle(Style::Change change)
1753 ASSERT(!view() || !view()->isPainting());
1755 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1759 FrameView& frameView = m_renderView->frameView();
1760 if (frameView.isPainting())
1763 if (m_inStyleRecalc)
1764 return; // Guard against re-entrancy. -dwh
1766 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1768 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1769 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1770 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1771 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1772 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1773 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1775 m_styleSheetCollection.flushPendingUpdates();
1777 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1779 if (m_elementSheet && m_elementSheet->contents().usesRemUnits())
1780 m_styleSheetCollection.setUsesRemUnit(true);
1782 m_inStyleRecalc = true;
1784 Style::PostResolutionCallbackDisabler disabler(*this);
1785 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1787 if (m_pendingStyleRecalcShouldForce)
1788 change = Style::Force;
1790 if (change == Style::Force) {
1791 // This may get set again during style resolve.
1792 m_hasNodesWithPlaceholderStyle = false;
1795 Style::resolveTree(*this, change);
1797 frameView.updateCompositingLayersAfterStyleChange();
1799 clearNeedsStyleRecalc();
1800 clearChildNeedsStyleRecalc();
1801 unscheduleStyleRecalc();
1803 m_inStyleRecalc = false;
1805 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1806 if (m_styleResolver)
1807 m_styleSheetCollection.resetCSSFeatureFlags();
1810 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1811 if (m_closeAfterStyleRecalc) {
1812 m_closeAfterStyleRecalc = false;
1816 InspectorInstrumentation::didRecalculateStyle(cookie);
1818 // As a result of the style recalculation, the currently hovered element might have been
1819 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1820 // to check if any other elements ended up under the mouse pointer due to re-layout.
1821 if (m_hoveredElement && !m_hoveredElement->renderer())
1822 frameView.frame().mainFrame().eventHandler().dispatchFakeMouseMoveEventSoon();
1825 void Document::updateStyleIfNeeded()
1827 ASSERT(isMainThread());
1828 ASSERT(!view() || !view()->isPainting());
1830 if (!view() || view()->isInLayout())
1833 if (m_optimizedStyleSheetUpdateTimer.isActive())
1834 styleResolverChanged(RecalcStyleIfNeeded);
1836 if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
1839 AnimationUpdateBlock animationUpdateBlock(m_frame ? &m_frame->animation() : nullptr);
1840 recalcStyle(Style::NoChange);
1843 void Document::updateLayout()
1845 ASSERT(isMainThread());
1847 FrameView* frameView = view();
1848 if (frameView && frameView->isInLayout()) {
1849 // View layout should not be re-entrant.
1850 ASSERT_NOT_REACHED();
1854 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1856 if (HTMLFrameOwnerElement* owner = ownerElement())
1857 owner->document().updateLayout();
1859 updateStyleIfNeeded();
1861 StackStats::LayoutCheckPoint layoutCheckPoint;
1863 // Only do a layout if changes have occurred that make it necessary.
1864 if (frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1865 frameView->layout();
1868 // FIXME: This is a bad idea and needs to be removed eventually.
1869 // Other browsers load stylesheets before they continue parsing the web page.
1870 // Since we don't, we can run JavaScript code that needs answers before the
1871 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1872 // lets us get reasonable answers. The long term solution to this problem is
1873 // to instead suspend JavaScript execution.
1874 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
1876 bool oldIgnore = m_ignorePendingStylesheets;
1878 if (!haveStylesheetsLoaded()) {
1879 m_ignorePendingStylesheets = true;
1880 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1881 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1882 // with accurate style information. (Our suppression involves blanking the whole page at the
1883 // moment. If it were more refined, we might be able to do something better.)
1884 // It's worth noting though that this entire method is a hack, since what we really want to do is
1885 // suspend JS instead of doing a layout with inaccurate information.
1886 HTMLElement* bodyElement = body();
1887 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1888 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1889 styleResolverChanged(RecalcStyleImmediately);
1890 } else if (m_hasNodesWithPlaceholderStyle)
1891 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1892 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1893 // but here we need up-to-date style immediately.
1894 recalcStyle(Style::Force);
1899 if (runPostLayoutTasks == RunPostLayoutTasks::Synchronously && view())
1900 view()->flushAnyPendingPostLayoutTasks();
1902 m_ignorePendingStylesheets = oldIgnore;
1905 PassRef<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1907 ASSERT_ARG(element, &element->document() == this);
1909 // On iOS request delegates called during styleForElement may result in re-entering WebKit and killing the style resolver.
1910 ResourceLoadScheduler::Suspender suspender(*platformStrategies()->loaderStrategy()->resourceLoadScheduler());
1912 TemporaryChange<bool> change(m_ignorePendingStylesheets, true);
1913 return ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : nullptr);
1916 bool Document::isPageBoxVisible(int pageIndex)
1918 Ref<RenderStyle> pageStyle(ensureStyleResolver().styleForPage(pageIndex));
1919 return pageStyle->visibility() != HIDDEN; // display property doesn't apply to @page.
1922 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1924 RefPtr<RenderStyle> style = ensureStyleResolver().styleForPage(pageIndex);
1926 int width = pageSize.width();
1927 int height = pageSize.height();
1928 switch (style->pageSizeType()) {
1929 case PAGE_SIZE_AUTO:
1931 case PAGE_SIZE_AUTO_LANDSCAPE:
1933 std::swap(width, height);
1935 case PAGE_SIZE_AUTO_PORTRAIT:
1937 std::swap(width, height);
1939 case PAGE_SIZE_RESOLVED: {
1940 LengthSize size = style->pageSize();
1941 ASSERT(size.width().isFixed());
1942 ASSERT(size.height().isFixed());
1943 width = valueForLength(size.width(), 0);
1944 height = valueForLength(size.height(), 0);
1948 ASSERT_NOT_REACHED();
1950 pageSize = IntSize(width, height);
1952 // The percentage is calculated with respect to the width even for margin top and bottom.
1953 // http://www.w3.org/TR/CSS2/box.html#margin-properties
1954 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
1955 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
1956 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
1957 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
1960 void Document::createStyleResolver()
1962 bool matchAuthorAndUserStyles = true;
1963 if (Settings* settings = this->settings())
1964 matchAuthorAndUserStyles = settings->authorAndUserStylesEnabled();
1965 m_styleResolver = std::make_unique<StyleResolver>(*this, matchAuthorAndUserStyles);
1966 m_styleSheetCollection.combineCSSFeatureFlags();
1969 void Document::clearStyleResolver()
1971 m_styleResolver = nullptr;
1974 void Document::createRenderTree()
1976 ASSERT(!renderView());
1977 ASSERT(!m_inPageCache);
1978 ASSERT(!m_axObjectCache || this != &topDocument());
1980 if (m_isNonRenderedPlaceholder)
1983 // FIXME: It would be better if we could pass the resolved document style directly here.
1984 m_renderView = createRenderer<RenderView>(*this, RenderStyle::create());
1985 Node::setRenderer(m_renderView.get());
1987 renderView()->setIsInWindow(true);
1989 recalcStyle(Style::Force);
1992 static void pageWheelEventHandlerCountChanged(Page& page)
1995 for (const Frame* frame = &page.mainFrame(); frame; frame = frame->tree().traverseNext()) {
1996 if (Document* document = frame->document())
1997 count += document->wheelEventHandlerCount();
1999 page.chrome().client().numWheelEventHandlersChanged(count);
2002 void Document::didBecomeCurrentDocumentInFrame()
2004 // FIXME: Are there cases where the document can be dislodged from the frame during the event handling below?
2005 // If so, then m_frame could become 0, and we need to do something about that.
2007 m_frame->script().updateDocument();
2009 if (!hasLivingRenderTree())
2012 updateViewportArguments();
2014 // FIXME: Doing this only for the main frame is insufficient.
2015 // Changing a subframe can also change the wheel event handler count.
2016 // FIXME: Doing this only when a document goes into the frame is insufficient.
2017 // Removing a document can also change the wheel event handler count.
2018 // FIXME: Doing this every time is a waste. If the current document and its
2019 // subframes' documents have no wheel event handlers, then the count did not change,
2020 // unless the documents they are replacing had wheel event handlers.
2021 if (page() && m_frame->isMainFrame())
2022 pageWheelEventHandlerCountChanged(*page());
2024 #if ENABLE(TOUCH_EVENTS)
2025 // FIXME: Doing this only for the main frame is insufficient.
2026 // A subframe could have touch event handlers.
2027 if (hasTouchEventHandlers() && page() && m_frame->isMainFrame())
2028 page()->chrome().client().needTouchEvents(true);
2032 // Ensure that document scheduled task state matches frame timer state. It can be out of sync
2033 // if timers state changed while the document was not in the frame (possibly in page cache,
2034 // or simply newly created).
2035 // FIXME: How does this interact with cross-platform code below?
2036 if (m_frame->timersPaused())
2037 suspendScheduledTasks(ActiveDOMObject::DocumentWillBePaused);
2039 resumeScheduledTasks(ActiveDOMObject::DocumentWillBePaused);
2042 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2043 suspendScriptedAnimationControllerCallbacks();
2044 m_frame->animation().suspendAnimationsForDocument(this);
2045 suspendActiveDOMObjects(ActiveDOMObject::PageWillBeSuspended);
2049 void Document::disconnectFromFrame()
2054 void Document::destroyRenderTree()
2056 ASSERT(hasLivingRenderTree());
2057 ASSERT(!m_inPageCache);
2059 TemporaryChange<bool> change(m_renderTreeBeingDestroyed, true);
2061 if (this == &topDocument())
2062 clearAXObjectCache();
2064 documentWillBecomeInactive();
2066 if (FrameView* frameView = view())
2067 frameView->detachCustomScrollbars();
2069 #if ENABLE(FULLSCREEN_API)
2070 if (m_fullScreenRenderer)
2071 setFullScreenRenderer(nullptr);
2074 m_hoveredElement = nullptr;
2075 m_focusedElement = nullptr;
2076 m_activeElement = nullptr;
2078 if (m_documentElement)
2079 Style::detachRenderTree(*m_documentElement);
2081 clearChildNeedsStyleRecalc();
2083 unscheduleStyleRecalc();
2085 m_renderView = nullptr;
2086 Node::setRenderer(nullptr);
2088 #if ENABLE(IOS_TEXT_AUTOSIZING)
2089 // Do this before the arena is cleared, which is needed to deref the RenderStyle on TextAutoSizingKey.
2090 m_textAutoSizedNodes.clear();
2094 void Document::prepareForDestruction()
2096 if (m_hasPreparedForDestruction)
2099 #if ENABLE(IOS_TOUCH_EVENTS)
2100 clearTouchEventListeners();
2103 disconnectDescendantFrames();
2104 if (m_domWindow && m_frame)
2105 m_domWindow->willDetachDocumentFromFrame();
2107 if (hasLivingRenderTree())
2108 destroyRenderTree();
2110 if (isPluginDocument())
2111 toPluginDocument(this)->detachFromPluginElement();
2113 #if ENABLE(POINTER_LOCK)
2115 page()->pointerLockController().documentDetached(this);
2118 stopActiveDOMObjects();
2119 m_eventQueue.close();
2120 #if ENABLE(FULLSCREEN_API)
2121 m_fullScreenChangeEventTargetQueue.clear();
2122 m_fullScreenErrorEventTargetQueue.clear();
2127 #if ENABLE(SHARED_WORKERS)
2128 SharedWorkerRepository::documentDetached(this);
2131 #if ENABLE(TOUCH_EVENTS)
2132 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2133 parentDocument()->didRemoveEventTargetNode(this);
2136 if (m_mediaQueryMatcher)
2137 m_mediaQueryMatcher->documentDestroyed();
2139 disconnectFromFrame();
2141 m_hasPreparedForDestruction = true;
2144 void Document::removeAllEventListeners()
2146 EventTarget::removeAllEventListeners();
2149 m_domWindow->removeAllEventListeners();
2150 #if ENABLE(IOS_TOUCH_EVENTS)
2151 clearTouchEventListeners();
2153 for (Node* node = firstChild(); node; node = NodeTraversal::next(node))
2154 node->removeAllEventListeners();
2157 void Document::platformSuspendOrStopActiveDOMObjects()
2160 #if ENABLE(DEVICE_ORIENTATION)
2161 if (m_deviceMotionController)
2162 m_deviceMotionController->suspendUpdates();
2163 if (m_deviceOrientationController)
2164 m_deviceOrientationController->suspendUpdates();
2167 if (WebThreadCountOfObservedContentModifiers() > 0) {
2168 Frame* frame = this->frame();
2169 if (Page* page = frame ? frame->page() : nullptr)
2170 page->chrome().client().clearContentChangeObservers(frame);
2175 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2177 ScriptExecutionContext::suspendActiveDOMObjects(why);
2178 platformSuspendOrStopActiveDOMObjects();
2181 void Document::resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2183 ScriptExecutionContext::resumeActiveDOMObjects(why);
2185 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2186 if (m_deviceMotionController)
2187 m_deviceMotionController->resumeUpdates();
2188 if (m_deviceOrientationController)
2189 m_deviceOrientationController->resumeUpdates();
2191 // FIXME: For iOS, do we need to add content change observers that were removed in Document::suspendActiveDOMObjects()?
2194 void Document::stopActiveDOMObjects()
2196 ScriptExecutionContext::stopActiveDOMObjects();
2197 platformSuspendOrStopActiveDOMObjects();
2200 void Document::clearAXObjectCache()
2202 ASSERT(&topDocument() == this);
2203 // Clear the cache member variable before calling delete because attempts
2204 // are made to access it during destruction.
2205 m_axObjectCache = nullptr;
2208 AXObjectCache* Document::existingAXObjectCache() const
2210 Document& topDocument = this->topDocument();
2211 if (!topDocument.hasLivingRenderTree())
2213 return topDocument.m_axObjectCache.get();
2216 AXObjectCache* Document::axObjectCache() const
2218 if (!AXObjectCache::accessibilityEnabled())
2221 // The only document that actually has a AXObjectCache is the top-level
2222 // document. This is because we need to be able to get from any WebCoreAXObject
2223 // to any other WebCoreAXObject on the same page. Using a single cache allows
2224 // lookups across nested webareas (i.e. multiple documents).
2225 Document& topDocument = this->topDocument();
2227 // If the document has already been detached, do not make a new axObjectCache.
2228 if (!topDocument.hasLivingRenderTree())
2231 ASSERT(&topDocument == this || !m_axObjectCache);
2232 if (!topDocument.m_axObjectCache)
2233 topDocument.m_axObjectCache = std::make_unique<AXObjectCache>(topDocument);
2234 return topDocument.m_axObjectCache.get();
2237 void Document::setVisuallyOrdered()
2239 m_visuallyOrdered = true;
2241 renderView()->style().setRTLOrdering(VisualOrder);
2244 PassRefPtr<DocumentParser> Document::createParser()
2246 // FIXME: this should probably pass the frame instead
2247 return XMLDocumentParser::create(*this, view());
2250 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2252 return parser() ? parser()->asScriptableDocumentParser() : nullptr;
2255 void Document::open(Document* ownerDocument)
2257 if (ownerDocument) {
2258 setURL(ownerDocument->url());
2259 m_cookieURL = ownerDocument->cookieURL();
2260 setSecurityOrigin(ownerDocument->securityOrigin());
2264 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2265 if (parser->isParsing()) {
2266 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2267 if (parser->isExecutingScript())
2270 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2275 if (m_frame->loader().state() == FrameStateProvisional)
2276 m_frame->loader().stopAllLoaders();
2279 removeAllEventListeners();
2281 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2282 parser->setWasCreatedByScript(true);
2285 m_frame->loader().didExplicitOpen();
2288 void Document::detachParser()
2296 void Document::cancelParsing()
2301 // We have to clear the parser to avoid possibly triggering
2302 // the onload handler when closing as a side effect of a cancel-style
2303 // change, such as opening a new document or closing the window while
2309 void Document::implicitOpen()
2315 setCompatibilityMode(DocumentCompatibilityMode::NoQuirksMode);
2317 m_parser = createParser();
2319 setReadyState(Loading);
2322 HTMLElement* Document::body() const
2324 // If the document element contains both a frameset and a body, the frameset wins.
2325 auto element = documentElement();
2328 if (auto frameset = childrenOfType<HTMLFrameSetElement>(*element).first())
2330 return childrenOfType<HTMLBodyElement>(*element).first();
2333 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2335 RefPtr<HTMLElement> newBody = prpNewBody;
2337 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2338 ec = HIERARCHY_REQUEST_ERR;
2342 if (&newBody->document() != this) {
2344 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2348 newBody = toHTMLElement(node.get());
2351 HTMLElement* b = body();
2353 documentElement()->appendChild(newBody.release(), ec);
2355 documentElement()->replaceChild(newBody.release(), b, ec);
2358 HTMLHeadElement* Document::head()
2360 if (auto element = documentElement())
2361 return childrenOfType<HTMLHeadElement>(*element).first();
2365 void Document::close()
2367 // FIXME: We should follow the specification more closely:
2368 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2370 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2376 void Document::explicitClose()
2378 if (RefPtr<DocumentParser> parser = m_parser)
2382 // Because we have no frame, we don't know if all loading has completed,
2383 // so we just call implicitClose() immediately. FIXME: This might fire
2384 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2389 m_frame->loader().checkCompleted();
2392 void Document::implicitClose()
2394 // If we're in the middle of recalcStyle, we need to defer the close until the style information is accurate and all elements are re-attached.
2395 if (m_inStyleRecalc) {
2396 m_closeAfterStyleRecalc = true;
2400 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2401 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2406 // Call to dispatchWindowLoadEvent can blow us from underneath.
2407 Ref<Document> protect(*this);
2409 m_processingLoadEvent = true;
2411 ScriptableDocumentParser* parser = scriptableDocumentParser();
2412 m_wellFormed = parser && parser->wellFormed();
2414 // We have to clear the parser, in case someone document.write()s from the
2415 // onLoad event handler, as in Radar 3206524.
2418 // FIXME: We kick off the icon loader when the Document is done parsing.
2419 // There are earlier opportunities we could start it:
2420 // -When the <head> finishes parsing
2421 // -When any new HTMLLinkElement is inserted into the document
2422 // But those add a dynamic component to the favicon that has UI
2423 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2426 f->loader().icon().startLoader();
2427 f->animation().startAnimationsIfNotSuspended(this);
2429 // FIXME: We shouldn't be dispatching pending events globally on all Documents here.
2430 // For now, only do this when there is a Frame, otherwise this could cause JS reentrancy
2431 // below SVG font parsing, for example. <https://webkit.org/b/136269>
2432 ImageLoader::dispatchPendingBeforeLoadEvents();
2433 ImageLoader::dispatchPendingLoadEvents();
2434 ImageLoader::dispatchPendingErrorEvents();
2435 HTMLLinkElement::dispatchPendingLoadEvents();
2436 HTMLStyleElement::dispatchPendingLoadEvents();
2439 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2440 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2441 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2442 if (svgExtensions())
2443 accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
2445 dispatchWindowLoadEvent();
2446 enqueuePageshowEvent(PageshowEventNotPersisted);
2447 enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
2450 f->loader().handledOnloadEvents();
2451 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2452 if (!ownerElement())
2453 printf("onload fired at %lld\n", elapsedTime().count());
2456 // An event handler may have removed the frame
2458 m_processingLoadEvent = false;
2462 // Make sure both the initial layout and reflow happen after the onload
2463 // fires. This will improve onload scores, and other browsers do it.
2464 // If they wanna cheat, we can too. -dwh
2466 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < settings()->layoutInterval()) {
2467 // Just bail out. Before or during the onload we were shifted to another page.
2468 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2469 m_processingLoadEvent = false;
2470 view()->unscheduleRelayout();
2474 frame()->loader().checkCallImplicitClose();
2476 // We used to force a synchronous display and flush here. This really isn't
2477 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2478 // (if your platform is syncing flushes and limiting them to 60fps).
2479 m_overMinimumLayoutThreshold = true;
2480 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2481 updateStyleIfNeeded();
2483 // Always do a layout after loading if needed.
2484 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2488 m_processingLoadEvent = false;
2490 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
2491 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
2492 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2493 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2494 // exists in the cache (we ignore the return value because we don't need it here). This is
2495 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2496 axObjectCache()->getOrCreate(renderView());
2497 if (this == &topDocument())
2498 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLoadComplete);
2500 // AXLoadComplete can only be posted on the top document, so if it's a document
2501 // in an iframe that just finished loading, post AXLayoutComplete instead.
2502 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
2507 if (svgExtensions())
2508 accessSVGExtensions()->startAnimations();
2511 void Document::setParsing(bool b)
2515 if (m_bParsing && !m_sharedObjectPool)
2516 m_sharedObjectPool = std::make_unique<DocumentSharedObjectPool>();
2518 if (!m_bParsing && view() && !view()->needsLayout())
2519 view()->fireLayoutRelatedMilestonesIfNeeded();
2521 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2522 if (!ownerElement() && !m_bParsing)
2523 printf("Parsing finished at %lld\n", elapsedTime().count());
2527 bool Document::shouldScheduleLayout()
2529 // This function will only be called when FrameView thinks a layout is needed.
2530 // This enforces a couple extra rules.
2532 // (a) Only schedule a layout once the stylesheets are loaded.
2533 // (b) Only schedule layout once we have a body element.
2535 return (haveStylesheetsLoaded() && body())
2536 || (documentElement() && !documentElement()->hasTagName(htmlTag));
2539 bool Document::isLayoutTimerActive()
2541 return view() && view()->layoutPending() && !minimumLayoutDelay().count();
2544 std::chrono::milliseconds Document::minimumLayoutDelay()
2546 if (m_overMinimumLayoutThreshold)
2547 return std::chrono::milliseconds(0);
2549 std::chrono::milliseconds elapsed = elapsedTime();
2550 m_overMinimumLayoutThreshold = elapsed > settings()->layoutInterval();
2552 // We'll want to schedule the timer to fire at the minimum layout threshold.
2553 return std::max(std::chrono::milliseconds(0), settings()->layoutInterval() - elapsed);
2556 std::chrono::milliseconds Document::elapsedTime() const
2558 auto elapsedTime = std::chrono::steady_clock::now() - m_startTime;
2560 return std::chrono::duration_cast<std::chrono::milliseconds>(elapsedTime);
2563 void Document::write(const SegmentedString& text, Document* ownerDocument)
2565 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2567 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2568 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2570 if (m_writeRecursionIsTooDeep)
2573 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2574 if (!ownerElement())
2575 printf("Beginning a document.write at %lld\n", elapsedTime().count());
2578 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2579 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2582 if (!hasInsertionPoint)
2583 open(ownerDocument);
2586 m_parser->insert(text);
2588 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2589 if (!ownerElement())
2590 printf("Ending a document.write at %lld\n", elapsedTime().count());
2594 void Document::write(const String& text, Document* ownerDocument)
2596 write(SegmentedString(text), ownerDocument);
2599 void Document::writeln(const String& text, Document* ownerDocument)
2601 write(text, ownerDocument);
2602 write("\n", ownerDocument);
2605 double Document::minimumTimerInterval() const
2609 return ScriptExecutionContext::minimumTimerInterval();
2610 return p->settings().minDOMTimerInterval();
2613 double Document::timerAlignmentInterval() const
2617 return ScriptExecutionContext::timerAlignmentInterval();
2618 return p->settings().domTimerAlignmentInterval();
2621 EventTarget* Document::errorEventTarget()
2623 return m_domWindow.get();
2626 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<Inspector::ScriptCallStack> callStack)
2628 addMessage(MessageSource::JS, MessageLevel::Error, errorMessage, sourceURL, lineNumber, columnNumber, callStack);
2631 void Document::setURL(const URL& url)
2633 const URL& newURL = url.isEmpty() ? blankURL() : url;
2634 if (newURL == m_url)
2638 m_documentURI = m_url.string();
2642 void Document::updateBaseURL()
2644 URL oldBaseURL = m_baseURL;
2645 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2646 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2647 // from the Document interface otherwise.
2648 if (!m_baseElementURL.isEmpty())
2649 m_baseURL = m_baseElementURL;
2650 else if (!m_baseURLOverride.isEmpty())
2651 m_baseURL = m_baseURLOverride;
2653 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2654 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2655 // and DOM 3 Core does not specify how it should be resolved.
2656 m_baseURL = URL(ParsedURLString, documentURI());
2659 clearSelectorQueryCache();
2661 if (!m_baseURL.isValid())
2664 if (m_elementSheet) {
2665 // Element sheet is silly. It never contains anything.
2666 ASSERT(!m_elementSheet->contents().ruleCount());
2667 bool usesRemUnits = m_elementSheet->contents().usesRemUnits();
2668 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
2669 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2670 m_elementSheet->contents().parserSetUsesRemUnits(usesRemUnits);
2673 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2674 // Base URL change changes any relative visited links.
2675 // FIXME: There are other URLs in the tree that would need to be re-evaluated on dynamic base URL change. Style should be invalidated too.
2676 for (auto& anchor : descendantsOfType<HTMLAnchorElement>(*this))
2677 anchor.invalidateCachedVisitedLinkHash();
2681 void Document::setBaseURLOverride(const URL& url)
2683 m_baseURLOverride = url;
2687 void Document::processBaseElement()
2689 // Find the first href attribute in a base element and the first target attribute in a base element.
2690 const AtomicString* href = nullptr;
2691 const AtomicString* target = nullptr;
2692 auto baseDescendants = descendantsOfType<HTMLBaseElement>(*this);
2693 for (auto base = baseDescendants.begin(), end = baseDescendants.end(); base != end && (!href || !target); ++base) {
2695 const AtomicString& value = base->fastGetAttribute(hrefAttr);
2696 if (!value.isNull())
2700 const AtomicString& value = base->fastGetAttribute(targetAttr);
2701 if (!value.isNull())
2706 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2709 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2710 if (!strippedHref.isEmpty())
2711 baseElementURL = URL(url(), strippedHref);
2713 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
2714 m_baseElementURL = baseElementURL;
2718 m_baseTarget = target ? *target : nullAtom;
2721 String Document::userAgent(const URL& url) const
2723 return frame() ? frame()->loader().userAgent(url) : String();
2726 void Document::disableEval(const String& errorMessage)
2731 frame()->script().disableEval(errorMessage);
2734 bool Document::canNavigate(Frame* targetFrame)
2739 // FIXME: We shouldn't call this function without a target frame, but
2740 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2741 // returning true when supplied with a 0 targetFrame.
2745 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
2746 if (!isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
2749 if (isSandboxed(SandboxNavigation)) {
2750 if (targetFrame->tree().isDescendantOf(m_frame))
2753 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
2754 if (isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
2755 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
2757 printNavigationErrorMessage(targetFrame, url(), reason);
2761 // This is the normal case. A document can navigate its decendant frames,
2762 // or, more generally, a document can navigate a frame if the document is
2763 // in the same origin as any of that frame's ancestors (in the frame
2766 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2767 // historical information about this security check.
2768 if (canAccessAncestor(securityOrigin(), targetFrame))
2771 // Top-level frames are easier to navigate than other frames because they
2772 // display their URLs in the address bar (in most browsers). However, there
2773 // are still some restrictions on navigation to avoid nuisance attacks.
2774 // Specifically, a document can navigate a top-level frame if that frame
2775 // opened the document or if the document is the same-origin with any of
2776 // the top-level frame's opener's ancestors (in the frame hierarchy).
2778 // In both of these cases, the document performing the navigation is in
2779 // some way related to the frame being navigate (e.g., by the "opener"
2780 // and/or "parent" relation). Requiring some sort of relation prevents a
2781 // document from navigating arbitrary, unrelated top-level frames.
2782 if (!targetFrame->tree().parent()) {
2783 if (targetFrame == m_frame->loader().opener())
2786 if (canAccessAncestor(securityOrigin(), targetFrame->loader().opener()))
2790 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
2794 Frame* Document::findUnsafeParentScrollPropagationBoundary()
2796 Frame* currentFrame = m_frame;
2800 Frame* ancestorFrame = currentFrame->tree().parent();
2802 while (ancestorFrame) {
2803 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
2804 return currentFrame;
2805 currentFrame = ancestorFrame;
2806 ancestorFrame = ancestorFrame->tree().parent();
2811 void Document::didRemoveAllPendingStylesheet()
2813 m_needsNotifyRemoveAllPendingStylesheet = false;
2815 styleResolverChanged(DeferRecalcStyleIfNeeded);
2817 if (m_pendingSheetLayout == DidLayoutWithPendingSheets) {
2818 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
2820 renderView()->repaintViewAndCompositedLayers();
2823 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2824 parser->executeScriptsWaitingForStylesheets();
2826 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
2827 view()->scrollToFragment(m_url);
2830 CSSStyleSheet& Document::elementSheet()
2832 if (!m_elementSheet)
2833 m_elementSheet = CSSStyleSheet::createInline(*this, m_baseURL);
2834 return *m_elementSheet;
2837 void Document::processHttpEquiv(const String& equiv, const String& content)
2839 ASSERT(!equiv.isNull() && !content.isNull());
2841 Frame* frame = this->frame();
2843 HTTPHeaderName headerName;
2844 if (!findHTTPHeaderName(equiv, headerName))
2847 switch (headerName) {
2848 case HTTPHeaderName::DefaultStyle:
2849 // The preferred style set has been overridden as per section
2850 // 14.3.2 of the HTML4.0 specification. We need to update the
2851 // sheet used variable and then update our style selector.
2852 // For more info, see the test at:
2853 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
2855 m_styleSheetCollection.setSelectedStylesheetSetName(content);
2856 m_styleSheetCollection.setPreferredStylesheetSetName(content);
2857 styleResolverChanged(DeferRecalcStyle);
2860 case HTTPHeaderName::Refresh: {
2863 if (frame && parseHTTPRefresh(content, true, delay, urlString)) {
2865 if (urlString.isEmpty())
2866 completedURL = m_url;
2868 completedURL = completeURL(urlString);
2869 if (!protocolIsJavaScript(completedURL))
2870 frame->navigationScheduler().scheduleRedirect(delay, completedURL);
2872 String message = "Refused to refresh " + m_url.stringCenterEllipsizedToLength() + " to a javascript: URL";
2873 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
2880 case HTTPHeaderName::SetCookie:
2881 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
2882 if (isHTMLDocument()) {
2883 // Exception (for sandboxed documents) ignored.
2884 toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
2888 case HTTPHeaderName::ContentLanguage:
2889 setContentLanguage(content);
2892 case HTTPHeaderName::XDNSPrefetchControl:
2893 parseDNSPrefetchControlHeader(content);
2896 case HTTPHeaderName::XFrameOptions:
2898 FrameLoader& frameLoader = frame->loader();
2899 unsigned long requestIdentifier = 0;
2900 if (frameLoader.activeDocumentLoader() && frameLoader.activeDocumentLoader()->mainResourceLoader())
2901 requestIdentifier = frameLoader.activeDocumentLoader()->mainResourceLoader()->identifier();
2902 if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
2903 String message = "Refused to display '" + url().stringCenterEllipsizedToLength() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
2904 frameLoader.stopAllLoaders();
2905 // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
2906 // intent, we must navigate away from the possibly partially-rendered document to a location that
2907 // doesn't inherit the parent's SecurityOrigin.
2908 frame->navigationScheduler().scheduleLocationChange(securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
2909 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, requestIdentifier);
2914 case HTTPHeaderName::ContentSecurityPolicy:
2915 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
2918 case HTTPHeaderName::ContentSecurityPolicyReportOnly:
2919 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report);
2922 case HTTPHeaderName::XWebKitCSP:
2923 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedEnforce);
2926 case HTTPHeaderName::XWebKitCSPReportOnly:
2927 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedReport);
2935 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
2936 static bool isSeparator(UChar c)
2938 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
2941 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
2943 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
2944 unsigned keyBegin, keyEnd;
2945 unsigned valueBegin, valueEnd;
2947 String buffer = features.lower();
2948 unsigned length = buffer.length();
2949 for (unsigned i = 0; i < length; ) {
2950 // skip to first non-separator, but don't skip past the end of the string
2951 while (isSeparator(buffer[i])) {
2958 // skip to first separator
2959 while (!isSeparator(buffer[i]))
2963 // skip to first '=', but don't skip past a ',' or the end of the string
2964 while (buffer[i] != '=') {
2965 if (buffer[i] == ',' || i >= length)
2970 // skip to first non-separator, but don't skip past a ',' or the end of the string
2971 while (isSeparator(buffer[i])) {
2972 if (buffer[i] == ',' || i >= length)
2978 // skip to first separator
2979 while (!isSeparator(buffer[i]))
2983 ASSERT_WITH_SECURITY_IMPLICATION(i <= length);
2985 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
2986 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
2987 callback(keyString, valueString, this, data);
2991 void Document::processViewport(const String& features, ViewportArguments::Type origin)
2993 ASSERT(!features.isNull());
2995 if (origin < m_viewportArguments.type)
2998 m_viewportArguments = ViewportArguments(origin);
2999 processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
3002 // FIXME: <rdar://problem/8955959> Investigate moving to ToT WebKit's extended Viewport Implementation
3003 // Moving to ToT's implementation would mean calling findConfigurationForViewportData, which does
3004 // bounds checking and determining concrete values for ValueAuto which we already do in UIKit.
3005 // To maintain old behavior, we just need to update a few values, leaving Auto's for UIKit.
3006 if (Page* page = this->page())
3007 finalizeViewportArguments(m_viewportArguments, page->chrome().screenSize());
3010 updateViewportArguments();
3013 void Document::updateViewportArguments()
3015 if (page() && frame()->isMainFrame()) {
3017 m_didDispatchViewportPropertiesChanged = true;
3019 page()->chrome().dispatchViewportPropertiesDidChange(m_viewportArguments);
3021 page()->chrome().didReceiveDocType(frame());
3027 // FIXME: Find a better place for this functionality.
3028 void setParserFeature(const String& key, const String& value, Document* document, void*)
3030 if (key == "telephone" && equalIgnoringCase(value, "no"))
3031 document->setIsTelephoneNumberParsingAllowed(false);
3034 void Document::processFormatDetection(const String& features)
3036 ASSERT(!features.isNull());
3037 processArguments(features, nullptr, &setParserFeature);
3040 void Document::processWebAppOrientations()
3042 if (Page* page = this->page())
3043 page->chrome().client().webAppOrientationsUpdated();
3047 void Document::processReferrerPolicy(const String& policy)
3049 ASSERT(!policy.isNull());
3051 if (equalIgnoringCase(policy, "never"))
3052 m_referrerPolicy = ReferrerPolicyNever;
3053 else if (equalIgnoringCase(policy, "always"))
3054 m_referrerPolicy = ReferrerPolicyAlways;
3055 else if (equalIgnoringCase(policy, "origin"))
3056 m_referrerPolicy = ReferrerPolicyOrigin;
3057 else if (equalIgnoringCase(policy, "default"))
3058 m_referrerPolicy = ReferrerPolicyDefault;
3060 addConsoleMessage(MessageSource::Rendering, MessageLevel::Error, "Failed to set referrer policy: The value '" + policy + "' is not one of 'always', 'default', 'never', or 'origin'. Defaulting to 'never'.");
3061 m_referrerPolicy = ReferrerPolicyNever;
3065 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3067 if (!hasLivingRenderTree())
3068 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3070 HitTestResult result(documentPoint);
3071 renderView()->hitTest(request, result);
3073 if (!request.readOnly())
3074 updateHoverActiveState(request, result.innerElement());
3076 return MouseEventWithHitTestResults(event, result);
3079 // DOM Section 1.1.1
3080 bool Document::childTypeAllowed(NodeType type) const
3083 case ATTRIBUTE_NODE:
3084 case CDATA_SECTION_NODE:
3085 case DOCUMENT_FRAGMENT_NODE:
3088 case ENTITY_REFERENCE_NODE:
3091 case XPATH_NAMESPACE_NODE:
3094 case PROCESSING_INSTRUCTION_NODE:
3096 case DOCUMENT_TYPE_NODE:
3098 // Documents may contain no more than one of each of these.
3099 // (One Element and one DocumentType.)
3100 for (Node* c = firstChild(); c; c = c->nextSibling())
3101 if (c->nodeType() == type)
3108 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
3111 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
3114 if (oldChild->nodeType() == newChild->nodeType())
3117 int numDoctypes = 0;
3118 int numElements = 0;
3120 // First, check how many doctypes and elements we have, not counting
3121 // the child we're about to remove.
3122 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3126 switch (c->nodeType()) {
3127 case DOCUMENT_TYPE_NODE:
3138 // Then, see how many doctypes and elements might be added by the new child.
3139 if (newChild->isDocumentFragment()) {
3140 for (Node* c = newChild->firstChild(); c; c = c->nextSibling()) {
3141 switch (c->nodeType()) {
3142 case ATTRIBUTE_NODE:
3143 case CDATA_SECTION_NODE:
3144 case DOCUMENT_FRAGMENT_NODE:
3147 case ENTITY_REFERENCE_NODE:
3150 case XPATH_NAMESPACE_NODE:
3153 case PROCESSING_INSTRUCTION_NODE:
3155 case DOCUMENT_TYPE_NODE:
3164 switch (newChild->nodeType()) {
3165 case ATTRIBUTE_NODE:
3166 case CDATA_SECTION_NODE:
3167 case DOCUMENT_FRAGMENT_NODE:
3170 case ENTITY_REFERENCE_NODE:
3173 case XPATH_NAMESPACE_NODE:
3176 case PROCESSING_INSTRUCTION_NODE:
3178 case DOCUMENT_TYPE_NODE:
3187 if (numElements > 1 || numDoctypes > 1)
3193 PassRefPtr<Node> Document::cloneNode(bool deep)
3195 RefPtr<Document> clone = cloneDocumentWithoutChildren();
3196 clone->cloneDataFromDocument(*this);
3198 cloneChildNodes(clone.get());
3199 return clone.release();
3202 PassRefPtr<Document> Document::cloneDocumentWithoutChildren() const
3204 return isXHTMLDocument() ? createXHTML(nullptr, url()) : create(nullptr, url());
3207 void Document::cloneDataFromDocument(const Document& other)
3209 ASSERT(m_url == other.url());
3210 m_baseURL = other.baseURL();
3211 m_baseURLOverride = other.baseURLOverride();
3212 m_documentURI = other.documentURI();
3214 setCompatibilityMode(other.m_compatibilityMode);
3215 setSecurityOrigin(other.securityOrigin());
3216 setDecoder(other.decoder());
3219 StyleSheetList& Document::styleSheets()
3221 if (!m_styleSheetList)
3222 m_styleSheetList = StyleSheetList::create(this);
3223 return *m_styleSheetList;
3226 String Document::preferredStylesheetSet() const
3228 return m_styleSheetCollection.preferredStylesheetSetName();
3231 String Document::selectedStylesheetSet() const
3233 return m_styleSheetCollection.selectedStylesheetSetName();
3236 void Document::setSelectedStylesheetSet(const String& aString)
3238 m_styleSheetCollection.setSelectedStylesheetSetName(aString);
3239 styleResolverChanged(DeferRecalcStyle);
3242 void Document::evaluateMediaQueryList()
3244 if (m_mediaQueryMatcher)
3245 m_mediaQueryMatcher->styleResolverChanged();
3248 void Document::optimizedStyleSheetUpdateTimerFired(Timer<Document>&)
3250 styleResolverChanged(RecalcStyleIfNeeded);
3253 void Document::scheduleOptimizedStyleSheetUpdate()
3255 if (m_optimizedStyleSheetUpdateTimer.isActive())
3257 m_styleSheetCollection.setPendingUpdateType(DocumentStyleSheetCollection::OptimizedUpdate);
3258 m_optimizedStyleSheetUpdateTimer.startOneShot(0);
3261 void Document::updateViewportUnitsOnResize()
3263 if (!hasStyleWithViewportUnits())
3266 ensureStyleResolver().clearCachedPropertiesAffectedByViewportUnits();
3268 // FIXME: Ideally, we should save the list of elements that have viewport units and only iterate over those.
3269 for (Element* element = ElementTraversal::firstWithin(&rootNode()); element; element = ElementTraversal::nextIncludingPseudo(element)) {
3270 auto* renderer = element->renderer();
3271 if (renderer && renderer->style().hasViewportUnits())
3272 element->setNeedsStyleRecalc(InlineStyleChange);
3276 void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
3278 if (m_optimizedStyleSheetUpdateTimer.isActive())
3279 m_optimizedStyleSheetUpdateTimer.stop();
3281 // Don't bother updating, since we haven't loaded all our style info yet
3282 // and haven't calculated the style selector for the first time.
3283 if (!hasLivingRenderTree() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
3284 m_styleResolver = nullptr;
3287 m_didCalculateStyleResolver = true;
3289 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3290 if (!ownerElement())
3291 printf("Beginning update of style selector at time %lld.\n", elapsedTime().count());
3294 DocumentStyleSheetCollection::UpdateFlag styleSheetUpdate = (updateFlag == RecalcStyleIfNeeded || updateFlag == DeferRecalcStyleIfNeeded)
3295 ? DocumentStyleSheetCollection::OptimizedUpdate
3296 : DocumentStyleSheetCollection::FullUpdate;
3297 bool stylesheetChangeRequiresStyleRecalc = m_styleSheetCollection.updateActiveStyleSheets(styleSheetUpdate);
3299 if (updateFlag == DeferRecalcStyle) {
3300 scheduleForcedStyleRecalc();
3304 if (updateFlag == DeferRecalcStyleIfNeeded) {
3305 if (stylesheetChangeRequiresStyleRecalc)
3306 scheduleForcedStyleRecalc();
3310 if (!stylesheetChangeRequiresStyleRecalc)
3313 // This recalcStyle initiates a new recalc cycle. We need to bracket it to
3314 // make sure animations get the correct update time
3316 AnimationUpdateBlock animationUpdateBlock(m_frame ? &m_frame->animation() : nullptr);
3317 recalcStyle(Style::Force);
3320 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3321 if (!ownerElement())
3322 printf("Finished update of style selector at time %lld\n", elapsedTime().count());
3326 renderView()->setNeedsLayoutAndPrefWidthsRecalc();
3328 view()->scheduleRelayout();
3331 evaluateMediaQueryList();
3334 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3336 if (!m_focusedElement || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
3339 Element* focusedElement = node->treeScope().focusedElement();
3340 if (!focusedElement)
3343 bool nodeInSubtree = false;
3344 if (amongChildrenOnly)
3345 nodeInSubtree = focusedElement->isDescendantOf(node);
3347 nodeInSubtree = (focusedElement == node) || focusedElement->isDescendantOf(node);
3350 setFocusedElement(nullptr);
3353 void Document::hoveredElementDidDetach(Element* element)
3355 if (!m_hoveredElement || element != m_hoveredElement)
3358 m_hoveredElement = element->parentElement();
3359 while (m_hoveredElement && !m_hoveredElement->renderer())
3360 m_hoveredElement = m_hoveredElement->parentElement();
3362 frame()->eventHandler().scheduleHoverStateUpdate();
3365 void Document::elementInActiveChainDidDetach(Element* element)
3367 if (!m_activeElement || element != m_activeElement)
3370 m_activeElement = element->parentElement();
3371 while (m_activeElement && !m_activeElement->renderer())
3372 m_activeElement = m_activeElement->parentElement();
3375 #if ENABLE(DASHBOARD_SUPPORT)
3376 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3378 return m_annotatedRegions;
3381 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3383 m_annotatedRegions = regions;
3384 setAnnotatedRegionsDirty(false);
3388 bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusDirection direction)
3390 RefPtr<Element> newFocusedElement = prpNewFocusedElement;
3392 // Make sure newFocusedElement is actually in this document
3393 if (newFocusedElement && (&newFocusedElement->document() != this))
3396 if (m_focusedElement == newFocusedElement)
3402 bool focusChangeBlocked = false;
3403 RefPtr<Element> oldFocusedElement = m_focusedElement.release();
3405 // Remove focus from the existing focus node (if any)
3406 if (oldFocusedElement) {
3407 if (oldFocusedElement->active())
3408 oldFocusedElement->setActive(false);
3410 oldFocusedElement->setFocus(false);
3412 // Dispatch a change event for form control elements that have been edited.
3413 if (oldFocusedElement->isFormControlElement()) {
3414 HTMLFormControlElement* formControlElement = toHTMLFormControlElement(oldFocusedElement.get());
3415 if (formControlElement->wasChangedSinceLastFormControlChangeEvent())
3416 formControlElement->dispatchFormControlChangeEvent();
3419 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3420 oldFocusedElement->dispatchBlurEvent(newFocusedElement);
3422 if (m_focusedElement) {
3423 // handler shifted focus
3424 focusChangeBlocked = true;
3425 newFocusedElement = nullptr;
3428 oldFocusedElement->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedElement); // DOM level 3 name for the bubbling blur event.
3429 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3430 // on it, probably when <rdar://problem/8503958> is resolved.
3431 oldFocusedElement->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedElement); // DOM level 2 name for compatibility.
3433 if (m_focusedElement) {
3434 // handler shifted focus
3435 focusChangeBlocked = true;
3436 newFocusedElement = nullptr;
3439 if (oldFocusedElement->isRootEditableElement())
3440 frame()->editor().didEndEditing();
3443 if (Widget* oldWidget = widgetForElement(oldFocusedElement.get()))
3444 oldWidget->setFocus(false);
3446 view()->setFocus(false);
3450 if (newFocusedElement && newFocusedElement->isFocusable()) {
3451 if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(newFocusedElement.get())) {
3452 // delegate blocks focus change
3453 focusChangeBlocked = true;
3454 goto SetFocusedNodeDone;
3456 // Set focus on the new node
3457 m_focusedElement = newFocusedElement;
3459 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3460 m_focusedElement->dispatchFocusEvent(oldFocusedElement, direction);
3462 if (m_focusedElement != newFocusedElement) {
3463 // handler shifted focus
3464 focusChangeBlocked = true;
3465 goto SetFocusedNodeDone;
3468 m_focusedElement->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedElement); // DOM level 3 bubbling focus event.
3470 if (m_focusedElement != newFocusedElement) {
3471 // handler shifted focus
3472 focusChangeBlocked = true;
3473 goto SetFocusedNodeDone;
3476 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3477 // on it, probably when <rdar://problem/8503958> is m.
3478 m_focusedElement->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedElement); // DOM level 2 for compatibility.
3480 if (m_focusedElement != newFocusedElement) {
3481 // handler shifted focus
3482 focusChangeBlocked = true;
3483 goto SetFocusedNodeDone;
3486 m_focusedElement->setFocus(true);
3488 if (m_focusedElement->isRootEditableElement())
3489 frame()->editor().didBeginEditing();
3491 // eww, I suck. set the qt focus correctly
3492 // ### find a better place in the code for this
3494 Widget* focusWidget = widgetForElement(m_focusedElement.get());
3496 // Make sure a widget has the right size before giving it focus.
3497 // Otherwise, we are testing edge cases of the Widget code.
3498 // Specifically, in WebCore this does not work well for text fields.
3500 // Re-get the widget in case updating the layout changed things.
3501 focusWidget = widgetForElement(m_focusedElement.get());
3504 focusWidget->setFocus(true);
3506 view()->setFocus(true);
3510 if (!focusChangeBlocked && m_focusedElement) {
3511 // Create the AXObject cache in a focus change because GTK relies on it.
3512 if (AXObjectCache* cache = axObjectCache())
3513 cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
3516 if (!focusChangeBlocked && page())
3517 page()->chrome().focusedElementChanged(m_focusedElement.get());
3520 updateStyleIfNeeded();
3521 return !focusChangeBlocked;
3524 void Document::setCSSTarget(Element* n)
3527 m_cssTarget->didAffectSelector(AffectedSelectorTarget);
3530 n->didAffectSelector(AffectedSelectorTarget);
3533 void Document::registerNodeListForInvalidation(LiveNodeList& list)
3535 m_nodeListAndCollectionCounts[list.invalidationType()]++;
3536 if (!list.isRootedAtDocument())
3538 ASSERT(!list.isRegisteredForInvalidationAtDocument());
3539 list.setRegisteredForInvalidationAtDocument(true);
3540 m_listsInvalidatedAtDocument.add(&list);
3543 void Document::unregisterNodeListForInvalidation(LiveNodeList& list)
3545 m_nodeListAndCollectionCounts[list.invalidationType()]--;
3546 if (!list.isRegisteredForInvalidationAtDocument())
3549 list.setRegisteredForInvalidationAtDocument(false);
3550 ASSERT(m_inInvalidateNodeListAndCollectionCaches
3551 ? m_listsInvalidatedAtDocument.isEmpty()
3552 : m_listsInvalidatedAtDocument.contains(&list));
3553 m_listsInvalidatedAtDocument.remove(&list);
3556 void Document::registerCollection(HTMLCollection& collection)
3558 m_nodeListAndCollectionCounts[collection.invalidationType()]++;
3559 if (collection.isRootedAtDocument())
3560 m_collectionsInvalidatedAtDocument.add(&collection);
3563 void Document::unregisterCollection(HTMLCollection& collection)
3565 ASSERT(m_nodeListAndCollectionCounts[collection.invalidationType()]);
3566 m_nodeListAndCollectionCounts[collection.invalidationType()]--;
3567 if (!collection.isRootedAtDocument())
3570 m_collectionsInvalidatedAtDocument.remove(&collection);
3573 void Document::collectionCachedIdNameMap(const HTMLCollection& collection)
3575 ASSERT_UNUSED(collection, collection.hasNamedElementCache());
3576 m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]++;
3579 void Document::collectionWillClearIdNameMap(const HTMLCollection& collection)
3581 ASSERT_UNUSED(collection, collection.hasNamedElementCache());
3582 ASSERT(m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]);
3583 m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]--;
3586 void Document::attachNodeIterator(NodeIterator* ni)
3588 m_nodeIterators.add(ni);
3591 void Document::detachNodeIterator(NodeIterator* ni)
3593 // The node iterator can be detached without having been attached if its root node didn't have a document
3594 // when the iterator was created, but has it now.
3595 m_nodeIterators.remove(ni);
3598 void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
3600 HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3601 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3602 for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3603 if ((*it)->root() == node) {
3604 detachNodeIterator(*it);
3605 newDocument->attachNodeIterator(*it);
3610 void Document::updateRangesAfterChildrenChanged(ContainerNode& container)
3612 if (!m_ranges.isEmpty()) {
3613 for (auto it = m_ranges.begin(), end = m_ranges.end(); it != end; ++it)
3614 (*it)->nodeChildrenChanged(container);
3618 void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
3620 if (!m_ranges.isEmpty()) {
3621 for (auto it = m_ranges.begin(), end = m_ranges.end(); it != end; ++it)
3622 (*it)->nodeChildrenWillBeRemoved(container);
3625 for (auto it = m_nodeIterators.begin(), end = m_nodeIterators.end(); it != end; ++it) {
3626 for (Node* n = container.firstChild(); n; n = n->nextSibling())
3627 (*it)->nodeWillBeRemoved(n);
3630 if (Frame* frame = this->frame()) {
3631 for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
3632 frame->eventHandler().nodeWillBeRemoved(n);
3633 frame->selection().nodeWillBeRemoved(n);
3634 frame->page()->dragCaretController().nodeWillBeRemoved(n);
3639 void Document::nodeWillBeRemoved(Node* n)
3641 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3642 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3643 (*it)->nodeWillBeRemoved(n);
3645 if (!m_ranges.isEmpty()) {
3646 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
3647 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3648 (*it)->nodeWillBeRemoved(n);
3651 if (Frame* frame = this->frame()) {
3652 frame->eventHandler().nodeWillBeRemoved(n);
3653 frame->selection().nodeWillBeRemoved(n);
3654 frame->page()->dragCaretController().nodeWillBeRemoved(n);
3658 void Document::textInserted(Node* text, unsigned offset, unsigned length)
3660 if (!m_ranges.isEmpty()) {
3661 for (auto& range : m_ranges)
3662 range->textInserted(text, offset, length);
3665 // Update the markers for spelling and grammar checking.
3666 m_markers->shiftMarkers(text, offset, length);
3669 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
3671 if (!m_ranges.isEmpty()) {
3672 for (auto& range : m_ranges)
3673 range->textRemoved(text, offset, length);
3676 // Update the markers for spelling and grammar checking.
3677 m_markers->removeMarkers(text, offset, length);
3678 m_markers->shiftMarkers(text, offset + length, 0 - length);
3681 void Document::textNodesMerged(Text* oldNode, unsigned offset)
3683 if (!m_ranges.isEmpty()) {
3684 NodeWithIndex oldNodeWithIndex(oldNode);
3685 for (auto& range : m_ranges)
3686 range->textNodesMerged(oldNodeWithIndex, offset);
3689 // FIXME: This should update markers for spelling and grammar checking.
3692 void Document::textNodeSplit(Text* oldNode)
3694 if (!m_ranges.isEmpty()) {
3695 HashSet<Range*>::const_iterator end = m_ranges.end();
3696 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3697 (*it)->textNodeSplit(oldNode);
3700 // FIXME: This should update markers for spelling and grammar checking.
3703 void Document::createDOMWindow()
3706 ASSERT(!m_domWindow);
3708 m_domWindow = DOMWindow::create(this);
3710 ASSERT(m_domWindow->document() == this);
3711 ASSERT(m_domWindow->frame() == m_frame);
3714 void Document::takeDOMWindowFrom(Document* document)
3717 ASSERT(!m_domWindow);
3718 ASSERT(document->m_domWindow);
3719 // A valid DOMWindow is needed by CachedFrame for its documents.
3720 ASSERT(!document->inPageCache());
3722 m_domWindow = document->m_domWindow.release();
3723 m_domWindow->didSecureTransitionTo(this);
3725 ASSERT(m_domWindow->document() == this);
3726 ASSERT(m_domWindow->frame() == m_frame);
3729 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3733 m_domWindow->setAttributeEventListener(eventType, listener);
3736 void Document::setWindowAttributeEventListener(const AtomicString& eventType, const QualifiedName& attributeName, const AtomicString& attributeValue)
3740 setWindowAttributeEventListener(eventType, JSLazyEventListener::createForDOMWindow(*m_frame, attributeName, attributeValue));
3743 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3747 return m_domWindow->getAttributeEventListener(eventType);
3750 void Document::dispatchWindowEvent(PassRefPtr<Event> event, PassRefPtr<EventTarget> target)
3752 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
3755 m_domWindow->dispatchEvent(event, target);
3758 void Document::dispatchWindowLoadEvent()
3760 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
3763 m_domWindow->dispatchLoadEvent();
3764 m_loadEventFinished = true;
3765 if (m_cachedResourceLoader)
3766 m_cachedResourceLoader->documentDidFinishLoadEvent();
3769 void Document::enqueueWindowEvent(PassRefPtr<Event> event)
3771 event->setTarget(m_domWindow.get());
3772 m_eventQueue.enqueueEvent(event);
3775 void Document::enqueueDocumentEvent(PassRefPtr<Event> event)
3777 event->setTarget(this);
3778 m_eventQueue.enqueueEvent(event);
3781 void Document::enqueueOverflowEvent(PassRefPtr<Event> event)
3783 m_eventQueue.enqueueEvent(event);
3786 PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionCode& ec)
3788 RefPtr<Event> event = EventFactory::create(eventType);
3790 return event.release();
3792 ec = NOT_SUPPORTED_ERR;
3796 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
3798 if (eventType == eventNames().DOMSubtreeModifiedEvent)
3799 addListenerType(DOMSUBTREEMODIFIED_LISTENER);
3800 else if (eventType == eventNames().DOMNodeInsertedEvent)
3801 addListenerType(DOMNODEINSERTED_LISTENER);
3802 else if (eventType == eventNames().DOMNodeRemovedEvent)
3803 addListenerType(DOMNODEREMOVED_LISTENER);
3804 else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
3805 addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
3806 else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
3807 addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
3808 else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
3809 addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
3810 else if (eventType == eventNames().overflowchangedEvent)
3811 addListenerType(OVERFLOWCHANGED_LISTENER);
3812 else if (eventType == eventNames().webkitAnimationStartEvent)
3813 addListenerType(ANIMATIONSTART_LISTENER);
3814 else if (eventType == eventNames().webkitAnimationEndEvent)
3815 addListenerType(ANIMATIONEND_LISTENER);
3816 else if (eventType == eventNames().webkitAnimationIterationEvent)
3817 addListenerType(ANIMATIONITERATION_LISTENER);
3818 else if (eventType == eventNames().webkitTransitionEndEvent || eventType == eventNames().transitionendEvent)
3819 addListenerType(TRANSITIONEND_LISTENER);
3820 else if (eventType == eventNames().beforeloadEvent)
3821 addListenerType(BEFORELOAD_LISTENER);
3822 else if (eventType == eventNames().scrollEvent)
3823 addListenerType(SCROLL_LISTENER);
3826 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
3831 HTMLFrameOwnerElement* Document::ownerElement() const
3835 return frame()->ownerElement();
3838 String Document::cookie(ExceptionCode& ec) const
3840 if (page() && !page()->settings().cookieEnabled())
3843 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3844 // INVALID_STATE_ERR exception on getting if the Document has no
3845 // browsing context.
3847 if (!securityOrigin()->canAccessCookies()) {
3852 URL cookieURL = this->cookieURL();
3853 if (cookieURL.isEmpty())
3856 return cookies(this, cookieURL);
3859 void Document::setCookie(const String& value, ExceptionCode& ec)
3861 if (page() && !page()->settings().cookieEnabled())
3864 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3865 // INVALID_STATE_ERR exception on setting if the Document has no
3866 // browsing context.
3868 if (!securityOrigin()->canAccessCookies()) {
3873 URL cookieURL = this->cookieURL();
3874 if (cookieURL.isEmpty())
3877 setCookies(this, cookieURL, value);
3880 String Document::referrer() const
3883 return frame()->loader().referrer();
3887 String Document::origin() const
3889 return securityOrigin()->databaseIdentifier();
3892 String Document::domain() const
3894 return securityOrigin()->domain();
3897 void Document::setDomain(const String& newDomain, ExceptionCode& ec)
3899 if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
3904 // Both NS and IE specify that changing the domain is only allowed when
3905 // the new domain is a suffix of the old domain.
3907 // FIXME: We should add logging indicating why a domain was not allowed.
3909 // If the new domain is the same as the old domain, still call
3910 // securityOrigin()->setDomainForDOM. This will change the
3911 // security check behavior. For example, if a page loaded on port 8000
3912 // assigns its current domain using document.domain, the page will
3913 // allow other pages loaded on different ports in the same domain that
3914 // have also assigned to access this page.
3915 if (equalIgnoringCase(domain(), newDomain)) {
3916 securityOrigin()->setDomainFromDOM(newDomain);
3920 int oldLength = domain().length();
3921 int newLength = newDomain.length();
3922 // e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
3923 if (newLength >= oldLength) {
3928 String test = domain();
3929 // Check that it's a subdomain, not e.g. "ebkit.org"
3930 if (test[oldLength - newLength - 1] != '.') {
3935 // Now test is "webkit.org" from domain()
3936 // and we check that it's the same thing as newDomain
3937 test.remove(0, oldLength - newLength);
3938 if (test != newDomain) {
3943 securityOrigin()->setDomainFromDOM(newDomain);
3946 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
3947 String Document::lastModified() const
3949 DateComponents date;
3950 bool foundDate = false;
3952 String httpLastModified;
3953 if (DocumentLoader* documentLoader = loader())
3954 httpLastModified = documentLoader->response().httpHeaderField(HTTPHeaderName::LastModified);
3955 if (!httpLastModified.isEmpty()) {
3956 date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
3960 // FIXME: If this document came from the file system, the HTML5
3961 // specificiation tells us to read the last modification date from the file
3964 double fallbackDate = currentTimeMS();
3965 #if ENABLE(WEB_REPLAY)
3966 InputCursor& cursor = inputCursor();
3967 if (cursor.isCapturing())
3968 cursor.appendInput<DocumentLastModifiedDate>(fallbackDate);
3969 else if (cursor.isReplaying()) {
3970 if (DocumentLastModifiedDate* input = cursor.fetchInput<DocumentLastModifiedDate>())
3971 fallbackDate = input->fallbackValue();
3974 date.setMillisecondsSinceEpochForDateTime(fallbackDate);
3977 return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
3980 static bool isValidNameNonASCII(const LChar* characters, unsigned length)
3982 if (!isValidNameStart(characters[0]))
3985 for (unsigned i = 1; i < length; ++i) {
3986 if (!isValidNamePart(characters[i]))
3993 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
3998 U16_NEXT(characters, i, length, c)
3999 if (!isValidNameStart(c))
4002 while (i < length) {
4003 U16_NEXT(characters, i, length, c)
4004 if (!isValidNamePart(c))
4011 template<typename CharType>
4012 static inline bool isValidNameASCII(const CharType* characters, unsigned length)
4014 CharType c = characters[0];
4015 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
4018 for (unsigned i = 1; i < length; ++i) {
4020 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
4027 bool Document::isValidName(const String& name)
4029 unsigned length = name.length();
4033 if (name.is8Bit()) {
4034 const LChar* characters = name.characters8();
4036 if (isValidNameASCII(characters, length))
4039 return isValidNameNonASCII(characters, length);
4042 const UChar* characters = name.characters16();
4044 if (isValidNameASCII(characters, length))
4047 return isValidNameNonASCII(characters, length);
4050 bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode& ec)
4052 unsigned length = qualifiedName.length();
4055 ec = INVALID_CHARACTER_ERR;
4059 bool nameStart = true;
4060 bool sawColon = false;
4063 for (unsigned i = 0; i < length;) {
4065 U16_NEXT(qualifiedName, i, length, c)
4069 return false; // multiple colons: not allowed
4074 } else if (nameStart) {
4075 if (!isValidNameStart(c)) {
4076 ec = INVALID_CHARACTER_ERR;
4081 if (!isValidNamePart(c)) {
4082 ec = INVALID_CHARACTER_ERR;
4090 localName = qualifiedName;
4092 prefix = qualifiedName.substring(0, colonPos);
4093 if (prefix.isEmpty()) {
4097 localName = qualifiedName.substring(colonPos + 1);
4100 if (localName.isEmpty()) {
4108 void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
4110 m_decoder = decoder;
4113 URL Document::completeURL(const String& url, const URL& baseURLOverride) const
4115 // Always return a null URL when passed a null string.
4116 // FIXME: Should we change the URL constructor to have this behavior?
4117 // See also [CSS]StyleSheet::completeURL(const String&)
4120 const URL& baseURL = ((baseURLOverride.isEmpty() || baseURLOverride == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : baseURLOverride;
4122 return URL(baseURL, url);
4123 return URL(baseURL, url, m_decoder->encoding());
4126 URL Document::completeURL(const String& url) const
4128 return completeURL(url, m_baseURL);
4131 void Document::setInPageCache(bool flag)
4133 if (m_inPageCache == flag)
4136 m_inPageCache = flag;
4138 FrameView* v = view();
4139 Page* page = this->page();
4142 page->lockAllOverlayScrollbarsToHidden(flag);
4146 // FIXME: There is some scrolling related work that needs to happen whenever a page goes into the
4147 // page cache and similar work that needs to occur when it comes out. This is where we do the work
4148 // that needs to happen when we enter, and the work that needs to happen when we exit is in
4149 // HistoryController::restoreScrollPositionAndViewState(). It can't be here because this function is
4150 // called too early on in the process of a page exiting the cache for that work to be possible in this
4151 // function. It would be nice if there was more symmetry here.
4152 // https://bugs.webkit.org/show_bug.cgi?id=98698
4153 v->cacheCurrentScrollPosition();
4154 if (page && m_frame->isMainFrame()) {
4155 v->resetScrollbarsAndClearContentsSize();
4156 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
4157 scrollingCoordinator->clearStateTree();
4159 v->resetScrollbars();
4161 m_styleRecalcTimer.stop();
4163 if (childNeedsStyleRecalc())
4164 scheduleStyleRecalc();
4168 void Document::documentWillBecomeInactive()
4171 renderView()->setIsInWindow(false);
4174 void Document::documentWillSuspendForPageCache()
4176 documentWillBecomeInactive();
4178 HashSet<Element*>::iterator end = m_documentSuspensionCallbackElements.end();
4179 for (HashSet<Element*>::iterator i = m_documentSuspensionCallbackElements.begin(); i != end; ++i)
4180 (*i)->documentWillSuspendForPageCache();
4183 // Clear the update flag to be able to check if the viewport arguments update
4184 // is dispatched, after the document is restored from the page cache.
4185 m_didDispatchViewportPropertiesChanged = false;
4188 if (RenderView* view = renderView()) {
4189 if (view->usesCompositing())
4190 view->compositor().cancelCompositingLayerUpdate();
4194 void Document::documentDidResumeFromPageCache()
4196 Vector<Element*> elements;
4197 copyToVector(m_documentSuspensionCallbackElements, elements);
4198 Vector<Element*>::iterator end = elements.end();
4199 for (Vector<Element*>::iterator i = elements.begin(); i != end; ++i)
4200 (*i)->documentDidResumeFromPageCache();
4203 renderView()->setIsInWindow(true);
4206 page()->lockAllOverlayScrollbarsToHidden(false);
4209 m_frame->loader().client().dispatchDidBecomeFrameset(isFrameSet());
4212 void Document::registerForPageCacheSuspensionCallbacks(Element* e)
4214 m_documentSuspensionCallbackElements.add(e);
4217 void Document::unregisterForPageCacheSuspensionCallbacks(Element* e)
4219 m_documentSuspensionCallbackElements.remove(e);
4222 void Document::mediaVolumeDidChange()
4224 HashSet<Element*>::iterator end = m_mediaVolumeCallbackElements.end();
4225 for (HashSet<Element*>::iterator i = m_mediaVolumeCallbackElements.begin(); i != end; ++i)
4226 (*i)->mediaVolumeDidChange();
4229 void Document::registerForMediaVolumeCallbacks(Element* e)
4231 m_mediaVolumeCallbackElements.add(e);
4234 void Document::unregisterForMediaVolumeCallbacks(Element* e)
4236 m_mediaVolumeCallbackElements.remove(e);
4239 void Document::storageBlockingStateDidChange()
4241 if (Settings* settings = this->settings())
4242 securityOrigin()->setStorageBlockingPolicy(settings->storageBlockingPolicy());
4245 void Document::privateBrowsingStateDidChange()
4247 HashSet<Element*>::iterator end = m_privateBrowsingStateChangedElements.end();
4248 for (HashSet<Element*>::iterator it = m_privateBrowsingStateChangedElements.begin(); it != end; ++it)
4249 (*it)->privateBrowsingStateDidChange();
4252 void Document::registerForPrivateBrowsingStateChangedCallbacks(Element* e)
4254 m_privateBrowsingStateChangedElements.add(e);
4257 void Document::unregisterForPrivateBrowsingStateChangedCallbacks(Element* e)
4259 m_privateBrowsingStateChangedElements.remove(e);
4262 #if ENABLE(VIDEO_TRACK)
4263 void Document::registerForCaptionPreferencesChangedCallbacks(Element* e)
4266 page()->group().captionPreferences()->setInterestedInCaptionPreferenceChanges();
4268 m_captionPreferencesChangedElements.add(e);
4271 void Document::unregisterForCaptionPreferencesChangedCallbacks(Element* e)
4273 m_captionPreferencesChangedElements.remove(e);
4276 void Document::captionPreferencesChanged()
4278 HashSet<Element*>::iterator end = m_captionPreferencesChangedElements.end();
4279 for (HashSet<Element*>::iterator it = m_captionPreferencesChangedElements.begin(); it != end; ++it)
4280 (*it)->captionPreferencesChanged();
4284 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
4285 void Document::registerForPageScaleFactorChangedCallbacks(HTMLMediaElement* element)
4287 m_pageScaleFactorChangedElements.add(element);
4290 void Document::unregisterForPageScaleFactorChangedCallbacks(HTMLMediaElement* element)
4292 m_pageScaleFactorChangedElements.remove(element);
4295 void Document::pageScaleFactorChangedAndStable()
4297 for (HTMLMediaElement* mediaElement : m_pageScaleFactorChangedElements)
4298 mediaElement->pageScaleFactorChanged();
4302 void Document::setShouldCreateRenderers(bool f)
4304 m_createRenderers = f;
4307 bool Document::shouldCreateRenderers()
4309 return m_createRenderers;
4312 // Support for Javascript execCommand, and related methods
4314 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
4316 Frame* frame = document->frame();
4317 if (!frame || frame->document() != document)
4318 return Editor::Command();
4320 document->updateStyleIfNeeded();
4322 return frame->editor().command(commandName,
4323 userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
4326 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
4328 return command(this, commandName, userInterface).execute(value);
4331 bool Document::queryCommandEnabled(const String& commandName)
4333 return command(this, commandName).isEnabled();
4336 bool Document::queryCommandIndeterm(const String& commandName)
4338 return command(this, commandName).state() == MixedTriState;