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 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.
29 #include "core/dom/Document.h"
31 #include "HTMLElementFactory.h"
32 #include "HTMLNames.h"
33 #include "RuntimeEnabledFeatures.h"
34 #include "SVGElementFactory.h"
36 #include "XMLNSNames.h"
38 #include "bindings/v8/CustomElementConstructorBuilder.h"
39 #include "bindings/v8/Dictionary.h"
40 #include "bindings/v8/ExceptionMessages.h"
41 #include "bindings/v8/ExceptionState.h"
42 #include "bindings/v8/ExceptionStatePlaceholder.h"
43 #include "bindings/v8/ScriptController.h"
44 #include "core/accessibility/AXObjectCache.h"
45 #include "core/animation/AnimationClock.h"
46 #include "core/animation/DocumentAnimations.h"
47 #include "core/animation/DocumentTimeline.h"
48 #include "core/animation/css/TransitionTimeline.h"
49 #include "core/css/CSSFontSelector.h"
50 #include "core/css/CSSStyleDeclaration.h"
51 #include "core/css/CSSStyleSheet.h"
52 #include "core/css/MediaQueryMatcher.h"
53 #include "core/css/StylePropertySet.h"
54 #include "core/css/StyleSheetContents.h"
55 #include "core/css/StyleSheetList.h"
56 #include "core/css/invalidation/StyleInvalidator.h"
57 #include "core/css/resolver/FontBuilder.h"
58 #include "core/css/resolver/StyleResolver.h"
59 #include "core/css/resolver/StyleResolverStats.h"
60 #include "core/dom/AddConsoleMessageTask.h"
61 #include "core/dom/Attr.h"
62 #include "core/dom/CDATASection.h"
63 #include "core/dom/Comment.h"
64 #include "core/dom/ContextFeatures.h"
65 #include "core/dom/DOMImplementation.h"
66 #include "core/dom/DocumentFragment.h"
67 #include "core/dom/DocumentLifecycleNotifier.h"
68 #include "core/dom/DocumentLifecycleObserver.h"
69 #include "core/dom/DocumentMarkerController.h"
70 #include "core/dom/DocumentType.h"
71 #include "core/dom/Element.h"
72 #include "core/dom/ElementDataCache.h"
73 #include "core/dom/ElementTraversal.h"
74 #include "core/dom/ExceptionCode.h"
75 #include "core/dom/ExecutionContextTask.h"
76 #include "core/dom/MainThreadTaskRunner.h"
77 #include "core/dom/MutationObserver.h"
78 #include "core/dom/NodeChildRemovalTracker.h"
79 #include "core/dom/NodeFilter.h"
80 #include "core/dom/NodeIterator.h"
81 #include "core/dom/NodeRareData.h"
82 #include "core/dom/NodeRenderStyle.h"
83 #include "core/dom/NodeRenderingTraversal.h"
84 #include "core/dom/NodeTraversal.h"
85 #include "core/dom/NodeWithIndex.h"
86 #include "core/dom/ProcessingInstruction.h"
87 #include "core/dom/RequestAnimationFrameCallback.h"
88 #include "core/dom/ScriptRunner.h"
89 #include "core/dom/ScriptedAnimationController.h"
90 #include "core/dom/SelectorQuery.h"
91 #include "core/dom/StyleEngine.h"
92 #include "core/dom/TouchList.h"
93 #include "core/dom/TransformSource.h"
94 #include "core/dom/TreeWalker.h"
95 #include "core/dom/VisitedLinkState.h"
96 #include "core/dom/XMLDocument.h"
97 #include "core/dom/custom/CustomElementRegistrationContext.h"
98 #include "core/dom/shadow/ElementShadow.h"
99 #include "core/dom/shadow/ShadowRoot.h"
100 #include "core/editing/Editor.h"
101 #include "core/editing/FrameSelection.h"
102 #include "core/editing/SpellChecker.h"
103 #include "core/events/BeforeUnloadEvent.h"
104 #include "core/events/Event.h"
105 #include "core/events/EventFactory.h"
106 #include "core/events/EventListener.h"
107 #include "core/events/HashChangeEvent.h"
108 #include "core/events/PageTransitionEvent.h"
109 #include "core/events/ScopedEventQueue.h"
110 #include "core/fetch/ResourceFetcher.h"
111 #include "core/frame/DOMWindow.h"
112 #include "core/frame/FrameHost.h"
113 #include "core/frame/FrameView.h"
114 #include "core/frame/History.h"
115 #include "core/frame/LocalFrame.h"
116 #include "core/frame/PageConsole.h"
117 #include "core/frame/Settings.h"
118 #include "core/frame/csp/ContentSecurityPolicy.h"
119 #include "core/html/HTMLAllCollection.h"
120 #include "core/html/HTMLAnchorElement.h"
121 #include "core/html/HTMLBaseElement.h"
122 #include "core/html/HTMLCanvasElement.h"
123 #include "core/html/HTMLCollection.h"
124 #include "core/html/HTMLDialogElement.h"
125 #include "core/html/HTMLDocument.h"
126 #include "core/html/HTMLFrameOwnerElement.h"
127 #include "core/html/HTMLHeadElement.h"
128 #include "core/html/HTMLIFrameElement.h"
129 #include "core/html/HTMLInputElement.h"
130 #include "core/html/HTMLLinkElement.h"
131 #include "core/html/HTMLMetaElement.h"
132 #include "core/html/HTMLNameCollection.h"
133 #include "core/html/HTMLScriptElement.h"
134 #include "core/html/HTMLStyleElement.h"
135 #include "core/html/HTMLTemplateElement.h"
136 #include "core/html/HTMLTitleElement.h"
137 #include "core/html/PluginDocument.h"
138 #include "core/html/canvas/CanvasRenderingContext.h"
139 #include "core/html/canvas/CanvasRenderingContext2D.h"
140 #include "core/html/canvas/WebGLRenderingContext.h"
141 #include "core/html/forms/FormController.h"
142 #include "core/html/imports/HTMLImport.h"
143 #include "core/html/parser/HTMLDocumentParser.h"
144 #include "core/html/parser/HTMLParserIdioms.h"
145 #include "core/html/parser/NestingLevelIncrementer.h"
146 #include "core/html/parser/TextResourceDecoder.h"
147 #include "core/inspector/InspectorCounters.h"
148 #include "core/inspector/InspectorInstrumentation.h"
149 #include "core/inspector/ScriptCallStack.h"
150 #include "core/loader/CookieJar.h"
151 #include "core/loader/DocumentLoader.h"
152 #include "core/loader/FrameLoader.h"
153 #include "core/loader/FrameLoaderClient.h"
154 #include "core/loader/ImageLoader.h"
155 #include "core/loader/appcache/ApplicationCacheHost.h"
156 #include "core/page/Chrome.h"
157 #include "core/page/ChromeClient.h"
158 #include "core/page/EventHandler.h"
159 #include "core/page/FocusController.h"
160 #include "core/page/FrameTree.h"
161 #include "core/page/MouseEventWithHitTestResults.h"
162 #include "core/page/Page.h"
163 #include "core/page/PointerLockController.h"
164 #include "core/page/scrolling/ScrollingCoordinator.h"
165 #include "core/rendering/FastTextAutosizer.h"
166 #include "core/rendering/HitTestResult.h"
167 #include "core/rendering/RenderView.h"
168 #include "core/rendering/RenderWidget.h"
169 #include "core/rendering/TextAutosizer.h"
170 #include "core/svg/SVGDocumentExtensions.h"
171 #include "core/svg/SVGFontFaceElement.h"
172 #include "core/svg/SVGStyleElement.h"
173 #include "core/svg/SVGUseElement.h"
174 #include "core/workers/SharedWorkerRepositoryClient.h"
175 #include "core/xml/XSLTProcessor.h"
176 #include "core/xml/parser/XMLDocumentParser.h"
177 #include "platform/DateComponents.h"
178 #include "platform/Language.h"
179 #include "platform/TraceEvent.h"
180 #include "platform/network/ContentSecurityPolicyParsers.h"
181 #include "platform/network/HTTPParsers.h"
182 #include "platform/scroll/ScrollbarTheme.h"
183 #include "platform/text/PlatformLocale.h"
184 #include "platform/text/SegmentedString.h"
185 #include "platform/weborigin/OriginAccessEntry.h"
186 #include "platform/weborigin/SchemeRegistry.h"
187 #include "platform/weborigin/SecurityOrigin.h"
188 #include "wtf/CurrentTime.h"
189 #include "wtf/HashFunctions.h"
190 #include "wtf/MainThread.h"
191 #include "wtf/StdLibExtras.h"
192 #include "wtf/TemporaryChange.h"
193 #include "wtf/text/StringBuffer.h"
194 #include "wtf/text/TextEncodingRegistry.h"
198 using namespace Unicode;
202 using namespace HTMLNames;
204 static const unsigned cMaxWriteRecursionDepth = 21;
206 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
207 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
209 static const int cLayoutScheduleThreshold = 250;
211 // DOM Level 2 says (letters added):
213 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
214 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
215 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
216 // 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.
217 // 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.
218 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
219 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
220 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
221 // i) Characters ':' and '_' are allowed as name-start characters.
222 // j) Characters '-' and '.' are allowed as name characters.
224 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
226 static inline bool isValidNameStart(UChar32 c)
229 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
233 if (c == ':' || c == '_')
236 // rules (a) and (f) above
237 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
238 if (!(Unicode::category(c) & nameStartMask))
242 if (c >= 0xF900 && c < 0xFFFE)
246 DecompositionType decompType = decompositionType(c);
247 if (decompType == DecompositionFont || decompType == DecompositionCompat)
253 static inline bool isValidNamePart(UChar32 c)
255 // rules (a), (e), and (i) above
256 if (isValidNameStart(c))
259 // rules (g) and (h) above
260 if (c == 0x00B7 || c == 0x0387)
264 if (c == '-' || c == '.')
267 // rules (b) and (f) above
268 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
269 if (!(Unicode::category(c) & otherNamePartMask))
273 if (c >= 0xF900 && c < 0xFFFE)
277 DecompositionType decompType = decompositionType(c);
278 if (decompType == DecompositionFont || decompType == DecompositionCompat)
284 static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
286 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
288 // If a Document has the address "about:blank"
289 // The origin of the Document is the origin it was assigned when its browsing context was created.
291 // Note: We generalize this to all "blank" URLs and invalid URLs because we
292 // treat all of these URLs as about:blank.
294 return url.isEmpty() || url.isBlankURL();
297 static Widget* widgetForElement(const Element& focusedElement)
299 RenderObject* renderer = focusedElement.renderer();
300 if (!renderer || !renderer->isWidget())
302 return toRenderWidget(renderer)->widget();
305 static bool acceptsEditingFocus(const Element& element)
307 ASSERT(element.rendererIsEditable());
309 return element.document().frame() && element.rootEditableElement();
312 static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, LocalFrame* targetFrame)
314 // targetFrame can be 0 when we're trying to navigate a top-level frame
315 // that has a 0 opener.
319 const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
320 for (LocalFrame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
321 Document* ancestorDocument = ancestorFrame->document();
322 // FIXME: Should be an ASSERT? Frames should alway have documents.
323 if (!ancestorDocument)
326 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
327 if (activeSecurityOrigin.canAccess(ancestorSecurityOrigin))
330 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
331 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
332 // something more general instead?
333 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
340 static void printNavigationErrorMessage(const LocalFrame& frame, const KURL& activeURL, const char* reason)
342 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame.document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
344 // FIXME: should we print to the console of the document performing the navigation instead?
345 frame.domWindow()->printErrorMessage(message);
348 uint64_t Document::s_globalTreeVersion = 0;
350 // This class doesn't work with non-Document ExecutionContext.
351 class AutofocusTask FINAL : public ExecutionContextTask {
353 static PassOwnPtr<AutofocusTask> create()
355 return adoptPtr(new AutofocusTask());
357 virtual ~AutofocusTask() { }
361 virtual void performTask(ExecutionContext* context) OVERRIDE
363 Document* document = toDocument(context);
364 if (RefPtr<Element> element = document->autofocusElement()) {
365 document->setAutofocusElement(0);
371 DocumentVisibilityObserver::DocumentVisibilityObserver(Document& document)
374 registerObserver(document);
377 DocumentVisibilityObserver::~DocumentVisibilityObserver()
379 unregisterObserver();
382 void DocumentVisibilityObserver::unregisterObserver()
385 m_document->unregisterVisibilityObserver(this);
390 void DocumentVisibilityObserver::registerObserver(Document& document)
393 m_document = &document;
395 m_document->registerVisibilityObserver(this);
398 void DocumentVisibilityObserver::setObservedDocument(Document& document)
400 unregisterObserver();
401 registerObserver(document);
404 Document::Document(const DocumentInit& initializer, DocumentClassFlags documentClasses)
405 : ContainerNode(0, CreateDocument)
407 , m_hasNodesWithPlaceholderStyle(false)
408 , m_needsNotifyRemoveAllPendingStylesheet(false)
409 , m_evaluateMediaQueriesOnStyleRecalc(false)
410 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
411 , m_frame(initializer.frame())
412 , m_domWindow(m_frame ? m_frame->domWindow() : 0)
413 , m_import(initializer.import())
414 , m_activeParserCount(0)
415 , m_contextFeatures(ContextFeatures::defaultSwitch())
416 , m_wellFormed(false)
418 , m_paginatedForScreen(false)
419 , m_compatibilityMode(NoQuirksMode)
420 , m_compatibilityModeLocked(false)
421 , m_hasAutofocused(false)
422 , m_clearFocusedElementTimer(this, &Document::clearFocusedElementTimerFired)
423 , m_domTreeVersion(++s_globalTreeVersion)
425 , m_mutationObserverTypes(0)
426 , m_visitedLinkState(VisitedLinkState::create(*this))
427 , m_visuallyOrdered(false)
428 , m_readyState(Complete)
430 , m_historyItemDocumentStateDirty(false)
431 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
432 , m_containsValidityStyleRules(false)
433 , m_updateFocusAppearanceRestoresSelection(false)
434 , m_containsPlugins(false)
435 , m_ignoreDestructiveWriteCount(0)
436 , m_titleSetExplicitly(false)
437 , m_markers(adoptPtr(new DocumentMarkerController))
438 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
440 , m_loadEventProgress(LoadEventNotRun)
441 , m_startTime(currentTime())
442 , m_scriptRunner(ScriptRunner::create(this))
443 , m_xmlVersion("1.0")
444 , m_xmlStandalone(StandaloneUnspecified)
445 , m_hasXMLDeclaration(0)
446 , m_designMode(inherit)
447 , m_hasAnnotatedRegions(false)
448 , m_annotatedRegionsDirty(false)
449 , m_useSecureKeyboardEntryWhenActive(false)
450 , m_documentClasses(documentClasses)
451 , m_isViewSource(false)
452 , m_sawElementsInKnownNamespaces(false)
453 , m_isSrcdocDocument(false)
454 , m_isMobileDocument(false)
456 , m_weakFactory(this)
457 , m_contextDocument(initializer.contextDocument())
458 , m_hasFullscreenElementStack(false)
459 , m_loadEventDelayCount(0)
460 , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
461 , m_pluginLoadingTimer(this, &Document::pluginLoadingTimerFired)
462 , m_didSetReferrerPolicy(false)
463 , m_referrerPolicy(ReferrerPolicyDefault)
464 , m_directionSetOnDocumentElement(false)
465 , m_writingModeSetOnDocumentElement(false)
466 , m_writeRecursionIsTooDeep(false)
467 , m_writeRecursionDepth(0)
468 , m_lastHandledUserGestureTimestamp(0)
469 , m_taskRunner(MainThreadTaskRunner::create(this))
470 , m_registrationContext(initializer.registrationContext(this))
471 , m_elementDataCacheClearTimer(this, &Document::elementDataCacheClearTimerFired)
473 , m_didDispatchViewportPropertiesChanged(false)
475 , m_animationClock(AnimationClock::create())
476 , m_timeline(DocumentTimeline::create(this))
477 , m_transitionTimeline(TransitionTimeline::create(this))
478 , m_templateDocumentHost(0)
479 , m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
480 , m_hasViewportUnits(false)
483 ScriptWrappable::init(this);
486 ASSERT(m_frame->page());
487 provideContextFeaturesToDocumentFrom(*this, *m_frame->page());
489 m_fetcher = m_frame->loader().documentLoader()->fetcher();
493 m_fetcher = ResourceFetcher::create(0);
494 m_fetcher->setDocument(this);
496 // We depend on the url getting immediately set in subframes, but we
497 // also depend on the url NOT getting immediately set in opened windows.
498 // See fast/dom/early-frame-url.html
499 // and fast/dom/location-new-window-no-crash.html, respectively.
500 // FIXME: Can/should we unify this behavior?
501 if (initializer.shouldSetURL())
502 setURL(initializer.url());
504 initSecurityContext(initializer);
507 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
508 m_nodeListCounts[i] = 0;
510 InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
512 m_lifecycle.advanceTo(DocumentLifecycle::Inactive);
514 // Since CSSFontSelector requires Document::m_fetcher and StyleEngine owns
515 // CSSFontSelector, need to initialize m_styleEngine after initializing
517 m_styleEngine = StyleEngine::create(*this);
520 Document::~Document()
522 ASSERT(!renderView());
523 ASSERT(m_ranges.isEmpty());
524 ASSERT(!parentTreeScope());
525 ASSERT(!hasGuardRefCount());
526 ASSERT(m_visibilityObservers.isEmpty());
528 if (m_templateDocument)
529 m_templateDocument->m_templateDocumentHost = 0; // balanced in ensureTemplateDocument().
531 m_scriptRunner.clear();
533 removeAllEventListeners();
535 // Currently we believe that Document can never outlive the parser.
536 // Although the Document may be replaced synchronously, DocumentParsers
537 // generally keep at least one reference to an Element which would in turn
538 // has a reference to the Document. If you hit this ASSERT, then that
539 // assumption is wrong. DocumentParser::detach() should ensure that even
540 // if the DocumentParser outlives the Document it won't cause badness.
541 ASSERT(!m_parser || m_parser->refCount() == 1);
544 if (this == topDocument())
545 clearAXObjectCache();
547 if (m_styleSheetList)
548 m_styleSheetList->detachFromDocument();
551 m_import->wasDetachedFromDocument();
555 m_timeline->detachFromDocument();
556 m_transitionTimeline->detachFromDocument();
558 // We need to destroy CSSFontSelector before destroying m_fetcher.
560 m_styleEngine->detachFromDocument();
563 m_elemSheet->clearOwnerNode();
565 // It's possible for multiple Documents to end up referencing the same ResourceFetcher (e.g., SVGImages
566 // load the initial empty document and the SVGDocument with the same DocumentLoader).
567 if (m_fetcher->document() == this)
568 m_fetcher->setDocument(0);
571 // We must call clearRareData() here since a Document class inherits TreeScope
572 // as well as Node. See a comment on TreeScope.h for the reason.
576 ASSERT(!m_listsInvalidatedAtDocument.size());
578 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
579 ASSERT(!m_nodeListCounts[i]);
583 InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
586 void Document::dispose()
588 ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
589 // We must make sure not to be retaining any of our children through
590 // these extra pointers or we will create a reference cycle.
592 m_focusedElement = nullptr;
593 m_hoverNode = nullptr;
594 m_activeHoverElement = nullptr;
595 m_titleElement = nullptr;
596 m_documentElement = nullptr;
597 m_contextFeatures = ContextFeatures::defaultSwitch();
598 m_userActionElements.documentDidRemoveLastRef();
599 m_associatedFormControls.clear();
603 m_registrationContext.clear();
606 m_import->wasDetachedFromDocument();
610 // removeDetachedChildren() doesn't always unregister IDs,
611 // so tear down scope information upfront to avoid having stale references in the map.
612 destroyTreeScopeData();
613 removeDetachedChildren();
614 // removeDetachedChildren() can access FormController.
615 m_formController.clear();
619 m_cssCanvasElements.clear();
621 // FIXME: consider using ActiveDOMObject.
622 if (m_scriptedAnimationController)
623 m_scriptedAnimationController->clearDocumentPointer();
624 m_scriptedAnimationController.clear();
627 accessSVGExtensions().pauseAnimations();
629 m_lifecycle.advanceTo(DocumentLifecycle::Disposed);
630 lifecycleNotifier().notifyDocumentWasDisposed();
633 SelectorQueryCache& Document::selectorQueryCache()
635 if (!m_selectorQueryCache)
636 m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
637 return *m_selectorQueryCache;
640 MediaQueryMatcher& Document::mediaQueryMatcher()
642 if (!m_mediaQueryMatcher)
643 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
644 return *m_mediaQueryMatcher;
647 void Document::mediaQueryAffectingValueChanged()
649 styleEngine()->clearMediaQueryRuleSetStyleSheets();
652 void Document::setCompatibilityMode(CompatibilityMode mode)
654 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
656 bool wasInQuirksMode = inQuirksMode();
657 m_compatibilityMode = mode;
658 selectorQueryCache().invalidate();
659 if (inQuirksMode() != wasInQuirksMode) {
660 // All injected stylesheets have to reparse using the different mode.
661 m_styleEngine->invalidateInjectedStyleSheetCache();
665 String Document::compatMode() const
667 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
670 void Document::setDoctype(PassRefPtr<DocumentType> docType)
672 // This should never be called more than once.
673 ASSERT(!m_docType || !docType);
676 this->adoptIfNeeded(*m_docType);
677 if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
678 m_isMobileDocument = true;
680 // Doctype affects the interpretation of the stylesheets.
681 clearStyleResolver();
684 DOMImplementation& Document::implementation()
686 if (!m_implementation)
687 m_implementation = DOMImplementation::create(*this);
688 return *m_implementation;
691 bool Document::hasManifest() const
693 return isHTMLHtmlElement(documentElement()) && documentElement()->hasAttribute(manifestAttr);
696 Location* Document::location() const
701 return &domWindow()->location();
704 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
706 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
707 m_documentElement = ElementTraversal::firstWithin(*this);
710 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& exceptionState)
712 if (!isValidName(name)) {
713 exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + name + "') is not a valid name.");
717 if (isXHTMLDocument() || isHTMLDocument())
718 return HTMLElementFactory::createHTMLElement(isHTMLDocument() ? name.lower() : name, *this, 0, false);
720 return Element::create(QualifiedName(nullAtom, name, nullAtom), this);
723 PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& exceptionState)
725 if (!isValidName(localName)) {
726 exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + localName + "') is not a valid name.");
730 RefPtr<Element> element;
732 if (CustomElement::isValidName(localName) && registrationContext()) {
733 element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI));
735 element = createElement(localName, exceptionState);
736 if (exceptionState.hadException())
740 if (!typeExtension.isEmpty())
741 CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
746 static inline QualifiedName createQualifiedName(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
748 AtomicString prefix, localName;
749 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
752 QualifiedName qName(prefix, localName, namespaceURI);
753 if (!Document::hasValidNamespaceForElements(qName)) {
754 exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
761 PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
763 QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
764 if (qName == nullQName())
767 return createElement(qName, false);
770 PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
772 QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
773 if (qName == nullQName())
776 RefPtr<Element> element;
777 if (CustomElement::isValidName(qName.localName()) && registrationContext())
778 element = registrationContext()->createCustomTagElement(*this, qName);
780 element = createElement(qName, false);
782 if (!typeExtension.isEmpty())
783 CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
788 ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, ExceptionState& exceptionState)
790 return registerElement(state, name, Dictionary(), exceptionState);
793 ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, const Dictionary& options, ExceptionState& exceptionState, CustomElement::NameSet validNames)
795 if (!registrationContext()) {
796 exceptionState.throwDOMException(NotSupportedError, "No element registration context is available.");
797 return ScriptValue();
800 CustomElementConstructorBuilder constructorBuilder(state, &options);
801 registrationContext()->registerElement(this, &constructorBuilder, name, validNames, exceptionState);
802 return constructorBuilder.bindingsReturnValue();
805 void Document::setImport(HTMLImport* import)
807 ASSERT(!m_import || !import);
811 bool Document::haveImportsLoaded() const
813 return !m_import || !m_import->state().shouldBlockScriptExecution();
816 DOMWindow* Document::executingWindow()
818 if (DOMWindow* owningWindow = domWindow())
820 if (HTMLImport* import = this->import())
821 return import->master()->domWindow();
825 LocalFrame* Document::executingFrame()
827 DOMWindow* window = executingWindow();
830 return window->frame();
833 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
835 return DocumentFragment::create(*this);
838 PassRefPtr<Text> Document::createTextNode(const String& data)
840 return Text::create(*this, data);
843 PassRefPtr<Comment> Document::createComment(const String& data)
845 return Comment::create(*this, data);
848 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& exceptionState)
850 if (isHTMLDocument()) {
851 exceptionState.throwDOMException(NotSupportedError, "This operation is not supported for HTML documents.");
854 if (data.contains("]]>")) {
855 exceptionState.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
858 return CDATASection::create(*this, data);
861 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& exceptionState)
863 if (!isValidName(target)) {
864 exceptionState.throwDOMException(InvalidCharacterError, "The target provided ('" + target + "') is not a valid name.");
867 if (data.contains("?>")) {
868 exceptionState.throwDOMException(InvalidCharacterError, "The data provided ('" + data + "') contains '?>'.");
871 return ProcessingInstruction::create(*this, target, data);
874 PassRefPtr<Text> Document::createEditingTextNode(const String& text)
876 return Text::createEditingText(*this, text);
879 bool Document::importContainerNodeChildren(ContainerNode* oldContainerNode, PassRefPtr<ContainerNode> newContainerNode, ExceptionState& exceptionState)
881 for (Node* oldChild = oldContainerNode->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
882 RefPtr<Node> newChild = importNode(oldChild, true, exceptionState);
883 if (exceptionState.hadException())
885 newContainerNode->appendChild(newChild.release(), exceptionState);
886 if (exceptionState.hadException())
893 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& exceptionState)
896 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
900 switch (importedNode->nodeType()) {
902 return createTextNode(importedNode->nodeValue());
903 case CDATA_SECTION_NODE:
904 return createCDATASection(importedNode->nodeValue(), exceptionState);
905 case PROCESSING_INSTRUCTION_NODE:
906 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), exceptionState);
908 return createComment(importedNode->nodeValue());
909 case DOCUMENT_TYPE_NODE: {
910 DocumentType* doctype = toDocumentType(importedNode);
911 return DocumentType::create(this, doctype->name(), doctype->publicId(), doctype->systemId());
914 Element* oldElement = toElement(importedNode);
915 // FIXME: The following check might be unnecessary. Is it possible that
916 // oldElement has mismatched prefix/namespace?
917 if (!hasValidNamespaceForElements(oldElement->tagQName())) {
918 exceptionState.throwDOMException(NamespaceError, "The imported node has an invalid namespace.");
921 RefPtr<Element> newElement = createElement(oldElement->tagQName(), false);
923 newElement->cloneDataFromElement(*oldElement);
926 if (!importContainerNodeChildren(oldElement, newElement, exceptionState))
928 if (isHTMLTemplateElement(*oldElement)
929 && !importContainerNodeChildren(toHTMLTemplateElement(oldElement)->content(), toHTMLTemplateElement(newElement)->content(), exceptionState))
933 return newElement.release();
936 return Attr::create(*this, QualifiedName(nullAtom, AtomicString(toAttr(importedNode)->name()), nullAtom), toAttr(importedNode)->value());
937 case DOCUMENT_FRAGMENT_NODE: {
938 if (importedNode->isShadowRoot()) {
939 // ShadowRoot nodes should not be explicitly importable.
940 // Either they are imported along with their host node, or created implicitly.
941 exceptionState.throwDOMException(NotSupportedError, "The node provided is a shadow root, which may not be imported.");
944 DocumentFragment* oldFragment = toDocumentFragment(importedNode);
945 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
946 if (deep && !importContainerNodeChildren(oldFragment, newFragment, exceptionState))
949 return newFragment.release();
952 exceptionState.throwDOMException(NotSupportedError, "The node provided is a document, which may not be imported.");
956 ASSERT_NOT_REACHED();
960 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionState& exceptionState)
963 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
967 EventQueueScope scope;
969 switch (source->nodeType()) {
971 case DOCUMENT_TYPE_NODE:
972 exceptionState.throwDOMException(NotSupportedError, "The node provided is of type '" + source->nodeName() + "', which may not be adopted.");
974 case ATTRIBUTE_NODE: {
975 Attr* attr = toAttr(source.get());
976 if (attr->ownerElement())
977 attr->ownerElement()->removeAttributeNode(attr, exceptionState);
981 if (source->isShadowRoot()) {
982 // ShadowRoot cannot disconnect itself from the host node.
983 exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a shadow root, which may not be adopted.");
987 if (source->isFrameOwnerElement()) {
988 HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
989 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement->contentFrame())) {
990 exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a frame which contains this document.");
994 if (source->parentNode()) {
995 source->parentNode()->removeChild(source.get(), exceptionState);
996 if (exceptionState.hadException())
1001 this->adoptIfNeeded(*source);
1006 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1008 // These checks are from DOM Core Level 2, createElementNS
1009 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1010 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1012 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1015 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1016 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1017 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1018 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1019 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1020 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1023 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1025 return hasValidNamespaceForElements(qName);
1028 // FIXME: This should really be in a possible ElementFactory class
1029 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
1033 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1034 if (qName.namespaceURI() == xhtmlNamespaceURI)
1035 e = HTMLElementFactory::createHTMLElement(qName.localName(), *this, 0, createdByParser);
1036 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
1037 e = SVGElementFactory::createSVGElement(qName.localName(), *this, createdByParser);
1040 m_sawElementsInKnownNamespaces = true;
1042 e = Element::create(qName, this);
1044 if (e->prefix() != qName.prefix())
1045 e->setTagNameForCreateElementNS(qName);
1047 ASSERT(qName == e->tagQName());
1052 bool Document::regionBasedColumnsEnabled() const
1054 return settings() && settings()->regionBasedColumnsEnabled();
1057 String Document::readyState() const
1059 DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
1060 DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
1061 DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
1063 switch (m_readyState) {
1072 ASSERT_NOT_REACHED();
1076 void Document::setReadyState(ReadyState readyState)
1078 if (readyState == m_readyState)
1081 switch (readyState) {
1083 if (!m_documentTiming.domLoading) {
1084 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1085 m_timeline->setZeroTime(m_documentTiming.domLoading);
1089 if (!m_documentTiming.domInteractive)
1090 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1093 if (!m_documentTiming.domComplete)
1094 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1098 m_readyState = readyState;
1099 dispatchEvent(Event::create(EventTypeNames::readystatechange));
1102 bool Document::isLoadCompleted()
1104 return m_readyState == Complete;
1107 AtomicString Document::encodingName() const
1109 // TextEncoding::name() returns a char*, no need to allocate a new
1110 // String for it each time.
1111 // FIXME: We should fix TextEncoding to speak AtomicString anyway.
1112 return AtomicString(encoding().name());
1115 String Document::defaultCharset() const
1117 if (Settings* settings = this->settings())
1118 return settings->defaultTextEncodingName();
1122 void Document::setCharset(const String& charset)
1124 if (DocumentLoader* documentLoader = loader())
1125 documentLoader->setUserChosenEncoding(charset);
1126 WTF::TextEncoding encoding(charset);
1127 // In case the encoding didn't exist, we keep the old one (helps some sites specifying invalid encodings).
1128 if (!encoding.isValid())
1130 DocumentEncodingData newEncodingData = m_encodingData;
1131 newEncodingData.setEncoding(encoding);
1132 setEncodingData(newEncodingData);
1135 void Document::setContentLanguage(const AtomicString& language)
1137 if (m_contentLanguage == language)
1139 m_contentLanguage = language;
1141 // Document's style depends on the content language.
1142 setNeedsStyleRecalc(SubtreeStyleChange);
1145 void Document::setXMLVersion(const String& version, ExceptionState& exceptionState)
1147 if (!implementation().hasFeature("XML", String())) {
1148 exceptionState.throwDOMException(NotSupportedError, "This document does not support XML.");
1152 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1153 exceptionState.throwDOMException(NotSupportedError, "This document does not support the XML version '" + version + "'.");
1157 m_xmlVersion = version;
1160 void Document::setXMLStandalone(bool standalone, ExceptionState& exceptionState)
1162 if (!implementation().hasFeature("XML", String())) {
1163 exceptionState.throwDOMException(NotSupportedError, "This document does not support XML.");
1167 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1170 KURL Document::baseURI() const
1175 void Document::setContent(const String& content)
1178 // FIXME: This should probably use insert(), but that's (intentionally)
1179 // not implemented for the XML parser as it's normally synonymous with
1180 // document.write(). append() will end up yielding, but close() will
1181 // pump the tokenizer syncrhonously and finish the parse.
1182 m_parser->pinToMainThread();
1183 m_parser->append(content.impl());
1187 String Document::suggestedMIMEType() const
1189 if (isXMLDocument()) {
1190 if (isXHTMLDocument())
1191 return "application/xhtml+xml";
1192 if (isSVGDocument())
1193 return "image/svg+xml";
1194 return "application/xml";
1196 if (xmlStandalone())
1198 if (isHTMLDocument())
1201 if (DocumentLoader* documentLoader = loader())
1202 return documentLoader->responseMIMEType();
1206 Element* Document::elementFromPoint(int x, int y) const
1211 return TreeScope::elementFromPoint(x, y);
1214 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1218 HitTestResult result = hitTestInDocument(this, x, y);
1219 RenderObject* renderer = result.renderer();
1223 Node* node = renderer->node();
1224 Node* shadowAncestorNode = ancestorInThisScope(node);
1225 if (shadowAncestorNode != node) {
1226 unsigned offset = shadowAncestorNode->nodeIndex();
1227 ContainerNode* container = shadowAncestorNode->parentNode();
1228 return Range::create(*this, container, offset, container, offset);
1231 PositionWithAffinity positionWithAffinity = renderer->positionForPoint(result.localPoint());
1232 if (positionWithAffinity.position().isNull())
1235 Position rangeCompliantPosition = positionWithAffinity.position().parentAnchoredEquivalent();
1236 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1240 * Performs three operations:
1241 * 1. Convert control characters to spaces
1242 * 2. Trim leading and trailing spaces
1243 * 3. Collapse internal whitespace.
1245 template <typename CharacterType>
1246 static inline String canonicalizedTitle(Document* document, const String& title)
1248 const CharacterType* characters = title.getCharacters<CharacterType>();
1249 unsigned length = title.length();
1252 StringBuffer<CharacterType> buffer(length);
1253 unsigned builderIndex = 0;
1255 // Skip leading spaces and leading characters that would convert to spaces
1256 for (i = 0; i < length; ++i) {
1257 CharacterType c = characters[i];
1258 if (!(c <= 0x20 || c == 0x7F))
1265 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1266 bool previousCharWasWS = false;
1267 for (; i < length; ++i) {
1268 CharacterType c = characters[i];
1269 if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1270 if (previousCharWasWS)
1272 buffer[builderIndex++] = ' ';
1273 previousCharWasWS = true;
1275 buffer[builderIndex++] = c;
1276 previousCharWasWS = false;
1280 // Strip trailing spaces
1281 while (builderIndex > 0) {
1283 if (buffer[builderIndex] != ' ')
1287 if (!builderIndex && buffer[builderIndex] == ' ')
1290 buffer.shrink(builderIndex + 1);
1292 return String::adopt(buffer);
1295 void Document::updateTitle(const String& title)
1297 if (m_rawTitle == title)
1302 String oldTitle = m_title;
1303 if (m_rawTitle.isEmpty())
1305 else if (m_rawTitle.is8Bit())
1306 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1308 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1310 if (!m_frame || oldTitle == m_title)
1312 m_frame->loader().client()->dispatchDidReceiveTitle(m_title);
1315 void Document::setTitle(const String& title)
1317 // Title set by JavaScript -- overrides any title elements.
1318 m_titleSetExplicitly = true;
1319 if (!isHTMLDocument() && !isXHTMLDocument())
1320 m_titleElement = nullptr;
1321 else if (!m_titleElement) {
1322 if (HTMLElement* headElement = head()) {
1323 m_titleElement = HTMLTitleElement::create(*this);
1324 headElement->appendChild(m_titleElement);
1328 if (isHTMLTitleElement(m_titleElement))
1329 toHTMLTitleElement(m_titleElement)->setText(title);
1334 void Document::setTitleElement(const String& title, Element* titleElement)
1336 if (titleElement != m_titleElement) {
1337 if (m_titleElement || m_titleSetExplicitly)
1338 // Only allow the first title element to change the title -- others have no effect.
1340 m_titleElement = titleElement;
1346 void Document::removeTitle(Element* titleElement)
1348 if (m_titleElement != titleElement)
1351 m_titleElement = nullptr;
1352 m_titleSetExplicitly = false;
1354 // FIXME: This is broken for SVG.
1355 // Update title based on first title element in the head, if one exists.
1356 if (HTMLElement* headElement = head()) {
1357 if (HTMLTitleElement* title = Traversal<HTMLTitleElement>::firstChild(*headElement))
1358 setTitleElement(title->text(), title);
1361 if (!m_titleElement)
1362 updateTitle(String());
1365 PageVisibilityState Document::pageVisibilityState() const
1367 // The visibility of the document is inherited from the visibility of the
1368 // page. If there is no page associated with the document, we will assume
1369 // that the page is hidden, as specified by the spec:
1370 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1371 if (!m_frame || !m_frame->page())
1372 return PageVisibilityStateHidden;
1373 return m_frame->page()->visibilityState();
1376 String Document::visibilityState() const
1378 return pageVisibilityStateString(pageVisibilityState());
1381 bool Document::hidden() const
1383 return pageVisibilityState() != PageVisibilityStateVisible;
1386 void Document::didChangeVisibilityState()
1388 dispatchEvent(Event::create(EventTypeNames::visibilitychange));
1389 // Also send out the deprecated version until it can be removed.
1390 dispatchEvent(Event::create(EventTypeNames::webkitvisibilitychange));
1392 PageVisibilityState state = pageVisibilityState();
1393 HashSet<DocumentVisibilityObserver*>::const_iterator observerEnd = m_visibilityObservers.end();
1394 for (HashSet<DocumentVisibilityObserver*>::const_iterator it = m_visibilityObservers.begin(); it != observerEnd; ++it)
1395 (*it)->didChangeVisibilityState(state);
1398 void Document::registerVisibilityObserver(DocumentVisibilityObserver* observer)
1400 ASSERT(!m_visibilityObservers.contains(observer));
1401 m_visibilityObservers.add(observer);
1404 void Document::unregisterVisibilityObserver(DocumentVisibilityObserver* observer)
1406 ASSERT(m_visibilityObservers.contains(observer));
1407 m_visibilityObservers.remove(observer);
1410 String Document::nodeName() const
1415 Node::NodeType Document::nodeType() const
1417 return DOCUMENT_NODE;
1420 FormController& Document::formController()
1422 if (!m_formController)
1423 m_formController = FormController::create();
1424 return *m_formController;
1427 Vector<String> Document::formElementsState() const
1429 if (!m_formController)
1430 return Vector<String>();
1431 return m_formController->formElementsState();
1434 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1436 if (!stateVector.size() && !m_formController)
1438 formController().setStateForNewFormElements(stateVector);
1441 FrameView* Document::view() const
1443 return m_frame ? m_frame->view() : 0;
1446 Page* Document::page() const
1448 return m_frame ? m_frame->page() : 0;
1451 FrameHost* Document::frameHost() const
1453 return m_frame ? m_frame->host() : 0;
1456 Settings* Document::settings() const
1458 return m_frame ? m_frame->settings() : 0;
1461 PassRefPtr<Range> Document::createRange()
1463 return Range::create(*this);
1466 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionState& exceptionState)
1468 // FIXME: Probably this should be handled within the bindings layer and TypeError should be thrown.
1470 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1473 return NodeIterator::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
1476 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
1479 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1482 // FIXME: It might be a good idea to emit a warning if |whatToShow| contains a bit that is not defined in
1484 return NodeIterator::create(root, whatToShow, PassRefPtr<NodeFilter>());
1487 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
1490 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1494 return NodeIterator::create(root, whatToShow, filter);
1497 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionState& exceptionState)
1500 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1503 return TreeWalker::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
1506 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
1509 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1512 return TreeWalker::create(root, whatToShow, PassRefPtr<NodeFilter>());
1515 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
1518 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1521 return TreeWalker::create(root, whatToShow, filter);
1524 bool Document::needsRenderTreeUpdate() const
1526 if (!isActive() || !view())
1528 if (needsStyleRecalc() || childNeedsStyleRecalc())
1530 if (childNeedsDistributionRecalc())
1532 if (!m_useElementsNeedingUpdate.isEmpty())
1534 if (!m_layerUpdateElements.isEmpty())
1536 if (childNeedsStyleInvalidation())
1541 bool Document::shouldScheduleRenderTreeUpdate() const
1545 if (hasPendingStyleRecalc())
1547 if (inStyleRecalc())
1549 // InPreLayout will recalc style itself. There's no reason to schedule another recalc.
1550 if (m_lifecycle.state() == DocumentLifecycle::InPreLayout)
1552 if (!shouldScheduleLayout())
1557 void Document::scheduleRenderTreeUpdate()
1559 if (!shouldScheduleRenderTreeUpdate())
1562 ASSERT(needsRenderTreeUpdate());
1564 page()->animator().scheduleVisualUpdate();
1565 m_lifecycle.advanceTo(DocumentLifecycle::StyleRecalcPending);
1567 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1570 bool Document::hasPendingForcedStyleRecalc() const
1572 return hasPendingStyleRecalc() && !inStyleRecalc() && styleChangeType() >= SubtreeStyleChange;
1575 void Document::updateDistributionIfNeeded()
1577 if (!childNeedsDistributionRecalc())
1579 TRACE_EVENT0("webkit", "Document::recalcDistribution");
1580 recalcDistribution();
1583 void Document::updateStyleInvalidationIfNeeded()
1587 if (!childNeedsStyleInvalidation())
1589 TRACE_EVENT0("webkit", "Document::computeNeedsStyleRecalcState");
1590 ASSERT(styleResolver());
1592 StyleInvalidator(*this).invalidate();
1595 void Document::updateDistributionForNodeIfNeeded(Node* node)
1597 if (node->inDocument()) {
1598 updateDistributionIfNeeded();
1602 while (Node* host = root->shadowHost())
1604 while (Node* ancestor = root->parentOrShadowHostNode())
1606 if (root->childNeedsDistributionRecalc())
1607 root->recalcDistribution();
1610 void Document::setupFontBuilder(RenderStyle* documentStyle)
1612 FontBuilder fontBuilder;
1613 fontBuilder.initForStyleResolve(*this, documentStyle, isSVGDocument());
1614 RefPtr<CSSFontSelector> selector = m_styleEngine->fontSelector();
1615 fontBuilder.createFontForDocument(selector, documentStyle);
1618 void Document::inheritHtmlAndBodyElementStyles(StyleRecalcChange change)
1620 ASSERT(inStyleRecalc());
1621 ASSERT(documentElement());
1623 RefPtr<RenderStyle> documentElementStyle = documentElement()->renderStyle();
1624 if (!documentElementStyle || documentElement()->needsStyleRecalc() || change == Force)
1625 documentElementStyle = ensureStyleResolver().styleForElement(documentElement());
1627 WritingMode rootWritingMode = documentElementStyle->writingMode();
1628 TextDirection rootDirection = documentElementStyle->direction();
1630 HTMLElement* body = this->body();
1631 RefPtr<RenderStyle> bodyStyle;
1633 bodyStyle = body->renderStyle();
1634 if (!bodyStyle || body->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
1635 bodyStyle = ensureStyleResolver().styleForElement(body, documentElementStyle.get());
1636 if (!writingModeSetOnDocumentElement())
1637 rootWritingMode = bodyStyle->writingMode();
1638 if (!directionSetOnDocumentElement())
1639 rootDirection = bodyStyle->direction();
1642 RefPtr<RenderStyle> overflowStyle;
1643 if (Element* element = viewportDefiningElement(documentElementStyle.get())) {
1644 if (element == body) {
1645 overflowStyle = bodyStyle;
1647 ASSERT(element == documentElement());
1648 overflowStyle = documentElementStyle;
1652 // Resolved rem units are stored in the matched properties cache so we need to make sure to
1653 // invalidate the cache if the documentElement needed to reattach or the font size changed
1654 // and then trigger a full document recalc. We also need to clear it here since the
1655 // call to styleForElement on the body above can cache bad values for rem units if the
1656 // documentElement's style was dirty. We could keep track of which elements depend on
1657 // rem units like we do for viewport styles, but we assume root font size changes are
1658 // rare and just invalidate the cache for now.
1659 if (styleEngine()->usesRemUnits() && (documentElement()->needsAttach() || documentElement()->computedStyle()->fontSize() != documentElementStyle->fontSize())) {
1660 ensureStyleResolver().invalidateMatchedPropertiesCache();
1661 documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
1664 EOverflow overflowX = OAUTO;
1665 EOverflow overflowY = OAUTO;
1666 float columnGap = 0;
1667 if (overflowStyle) {
1668 overflowX = overflowStyle->overflowX();
1669 overflowY = overflowStyle->overflowY();
1670 // Visible overflow on the viewport is meaningless, and the spec says to treat it as 'auto':
1671 if (overflowX == OVISIBLE)
1673 if (overflowY == OVISIBLE)
1675 // Column-gap is (ab)used by the current paged overflow implementation (in lack of other
1676 // ways to specify gaps between pages), so we have to propagate it too.
1677 columnGap = overflowStyle->columnGap();
1680 RefPtr<RenderStyle> documentStyle = renderView()->style();
1681 if (documentStyle->writingMode() != rootWritingMode
1682 || documentStyle->direction() != rootDirection
1683 || documentStyle->overflowX() != overflowX
1684 || documentStyle->overflowY() != overflowY
1685 || documentStyle->columnGap() != columnGap) {
1686 RefPtr<RenderStyle> newStyle = RenderStyle::clone(documentStyle.get());
1687 newStyle->setWritingMode(rootWritingMode);
1688 newStyle->setDirection(rootDirection);
1689 newStyle->setColumnGap(columnGap);
1690 newStyle->setOverflowX(overflowX);
1691 newStyle->setOverflowY(overflowY);
1692 renderView()->setStyle(newStyle);
1693 setupFontBuilder(newStyle.get());
1697 if (RenderStyle* style = body->renderStyle()) {
1698 if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
1699 body->setNeedsStyleRecalc(SubtreeStyleChange);
1703 if (RenderStyle* style = documentElement()->renderStyle()) {
1704 if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
1705 documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
1709 void Document::updateRenderTree(StyleRecalcChange change)
1711 ASSERT(isMainThread());
1713 if (change != Force && !needsRenderTreeUpdate())
1716 if (inStyleRecalc())
1719 // Entering here from inside layout or paint would be catastrophic since recalcStyle can
1720 // tear down the render tree or (unfortunately) run script. Kill the whole renderer if
1721 // someone managed to get into here from inside layout or paint.
1722 RELEASE_ASSERT(!view()->isInPerformLayout());
1723 RELEASE_ASSERT(!view()->isPainting());
1725 // Script can run below in WidgetUpdates, so protect the LocalFrame.
1726 RefPtr<LocalFrame> protect(m_frame);
1728 TRACE_EVENT0("webkit", "Document::updateRenderTree");
1729 TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "UpdateRenderTree");
1731 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1733 updateDistributionIfNeeded();
1734 updateUseShadowTreesIfNeeded();
1735 updateStyleInvalidationIfNeeded();
1737 // FIXME: This executes media query listeners which runs script, instead the script
1738 // should run at raf timing in ScriptedAnimationController just like resize events.
1739 evaluateMediaQueryListIfNeeded();
1741 // FIXME: We should update style on our ancestor chain before proceeding
1742 // however doing so currently causes several tests to crash, as LocalFrame::setDocument calls Document::attach
1743 // before setting the DOMWindow on the LocalFrame, or the SecurityOrigin on the document. The attach, in turn
1744 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1745 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1746 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1748 if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
1749 m_styleEngine->setUsesRemUnit(true);
1751 updateStyle(change);
1753 // As a result of the style recalculation, the currently hovered element might have been
1754 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1755 // to check if any other elements ended up under the mouse pointer due to re-layout.
1756 if (hoverNode() && !hoverNode()->renderer() && frame())
1757 frame()->eventHandler().dispatchFakeMouseMoveEventSoon();
1759 if (m_focusedElement && !m_focusedElement->isFocusable())
1760 clearFocusedElementSoon();
1762 #if ENABLE(SVG_FONTS)
1763 if (svgExtensions())
1764 accessSVGExtensions().removePendingSVGFontFaceElementsForRemoval();
1766 InspectorInstrumentation::didRecalculateStyle(cookie);
1769 void Document::updateStyle(StyleRecalcChange change)
1771 TRACE_EVENT0("webkit", "Document::updateStyle");
1773 RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
1774 m_lifecycle.advanceTo(DocumentLifecycle::InStyleRecalc);
1776 if (styleChangeType() >= SubtreeStyleChange)
1779 // FIXME: Cannot access the ensureStyleResolver() before calling styleForDocument below because
1780 // apparently the StyleResolver's constructor has side effects. We should fix it.
1781 // See printing/setPrinting.html, printing/width-overflow.html though they only fail on
1782 // mac when accessing the resolver by what appears to be a viewport size difference.
1784 if (change == Force) {
1785 m_hasNodesWithPlaceholderStyle = false;
1786 RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this, m_styleEngine->fontSelector());
1787 StyleRecalcChange localChange = RenderStyle::stylePropagationDiff(documentStyle.get(), renderView()->style());
1788 if (localChange != NoChange)
1789 renderView()->setStyle(documentStyle.release());
1792 clearNeedsStyleRecalc();
1794 // Uncomment to enable printing of statistics about style sharing and the matched property cache.
1795 // Optionally pass StyleResolver::ReportSlowStats to print numbers that require crawling the
1796 // entire DOM (where collecting them is very slow).
1797 // FIXME: Expose this as a runtime flag.
1798 // ensureStyleResolver().enableStats(/*StyleResolver::ReportSlowStats*/);
1800 if (StyleResolverStats* stats = ensureStyleResolver().stats())
1803 if (Element* documentElement = this->documentElement()) {
1804 inheritHtmlAndBodyElementStyles(change);
1805 dirtyElementsForLayerUpdate();
1806 if (documentElement->shouldCallRecalcStyle(change))
1807 documentElement->recalcStyle(change);
1808 while (dirtyElementsForLayerUpdate())
1809 documentElement->recalcStyle(NoChange);
1812 ensureStyleResolver().printStats();
1814 view()->updateCompositingLayersAfterStyleChange();
1816 clearChildNeedsStyleRecalc();
1818 if (m_styleEngine->hasResolver()) {
1819 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1820 StyleResolver& resolver = m_styleEngine->ensureResolver();
1821 m_styleEngine->resetCSSFeatureFlags(resolver.ensureUpdatedRuleFeatureSet());
1822 resolver.clearStyleSharingList();
1825 ASSERT(!needsStyleRecalc());
1826 ASSERT(!childNeedsStyleRecalc());
1827 ASSERT(inStyleRecalc());
1828 m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
1831 void Document::updateRenderTreeForNodeIfNeeded(Node* node)
1833 if (!needsRenderTreeUpdate())
1836 // At this point, we know that we need to recalc some style on the document in order to fully update styles.
1837 // However, style on 'node' only needs to be recalculated if a global recomputation is needed, or a node on
1838 // the path from 'node' to the root needs style recalc.
1841 bool needsRecalc = needsStyleRecalc() || childNeedsDistributionRecalc() || !m_useElementsNeedingUpdate.isEmpty() || childNeedsStyleInvalidation();
1844 for (Node* ancestor = node; ancestor && !needsRecalc; ancestor = ancestor->parentOrShadowHostNode())
1845 needsRecalc = ancestor->needsStyleRecalc();
1847 updateRenderTreeIfNeeded();
1850 void Document::updateLayout()
1852 ASSERT(isMainThread());
1854 RefPtr<FrameView> frameView = view();
1855 if (frameView && frameView->isInPerformLayout()) {
1856 // View layout should not be re-entrant.
1857 ASSERT_NOT_REACHED();
1861 if (Element* oe = ownerElement())
1862 oe->document().updateLayout();
1864 updateRenderTreeIfNeeded();
1866 // Only do a layout if changes have occurred that make it necessary.
1867 if (isActive() && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1868 frameView->layout();
1871 void Document::setNeedsFocusedElementCheck()
1873 setNeedsStyleRecalc(LocalStyleChange);
1876 void Document::clearFocusedElementSoon()
1878 if (!m_clearFocusedElementTimer.isActive())
1879 m_clearFocusedElementTimer.startOneShot(0, FROM_HERE);
1882 void Document::clearFocusedElementTimerFired(Timer<Document>*)
1884 updateRenderTreeIfNeeded();
1885 m_clearFocusedElementTimer.stop();
1887 if (m_focusedElement && !m_focusedElement->isFocusable())
1888 setFocusedElement(nullptr);
1891 // FIXME: This is a bad idea and needs to be removed eventually.
1892 // Other browsers load stylesheets before they continue parsing the web page.
1893 // Since we don't, we can run JavaScript code that needs answers before the
1894 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1895 // lets us get reasonable answers. The long term solution to this problem is
1896 // to instead suspend JavaScript execution.
1897 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
1899 StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
1901 if (m_styleEngine->hasPendingSheets()) {
1902 // FIXME: We are willing to attempt to suppress painting with outdated style info only once.
1903 // Our assumption is that it would be dangerous to try to stop it a second time, after page
1904 // content has already been loaded and displayed with accurate style information. (Our
1905 // suppression involves blanking the whole page at the moment. If it were more refined, we
1906 // might be able to do something better.) It's worth noting though that this entire method
1907 // is a hack, since what we really want to do is suspend JS instead of doing a layout with
1908 // inaccurate information.
1909 HTMLElement* bodyElement = body();
1910 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1911 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1912 styleResolverChanged(RecalcStyleImmediately);
1913 } else if (m_hasNodesWithPlaceholderStyle) {
1914 // If new nodes have been added or style recalc has been done with style sheets still
1915 // pending, some nodes may not have had their real style calculated yet. Normally this
1916 // gets cleaned when style sheets arrive but here we need up-to-date style immediately.
1917 updateRenderTree(Force);
1923 if (runPostLayoutTasks == RunPostLayoutTasksSynchronously && view())
1924 view()->flushAnyPendingPostLayoutTasks();
1927 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1929 ASSERT_ARG(element, element->document() == this);
1930 StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
1931 return ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
1934 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
1936 return ensureStyleResolver().styleForPage(pageIndex);
1939 bool Document::isPageBoxVisible(int pageIndex)
1941 return styleForPage(pageIndex)->visibility() != HIDDEN; // display property doesn't apply to @page.
1944 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1946 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1948 int width = pageSize.width();
1949 int height = pageSize.height();
1950 switch (style->pageSizeType()) {
1951 case PAGE_SIZE_AUTO:
1953 case PAGE_SIZE_AUTO_LANDSCAPE:
1955 std::swap(width, height);
1957 case PAGE_SIZE_AUTO_PORTRAIT:
1959 std::swap(width, height);
1961 case PAGE_SIZE_RESOLVED: {
1962 LengthSize size = style->pageSize();
1963 ASSERT(size.width().isFixed());
1964 ASSERT(size.height().isFixed());
1965 width = valueForLength(size.width(), 0);
1966 height = valueForLength(size.height(), 0);
1970 ASSERT_NOT_REACHED();
1972 pageSize = IntSize(width, height);
1974 // The percentage is calculated with respect to the width even for margin top and bottom.
1975 // http://www.w3.org/TR/CSS2/box.html#margin-properties
1976 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
1977 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
1978 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
1979 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
1982 void Document::setIsViewSource(bool isViewSource)
1984 m_isViewSource = isViewSource;
1985 if (!m_isViewSource)
1988 setSecurityOrigin(SecurityOrigin::createUnique());
1989 didUpdateSecurityOrigin();
1992 bool Document::dirtyElementsForLayerUpdate()
1994 if (m_layerUpdateElements.isEmpty())
1996 HashSet<Element*>::iterator end = m_layerUpdateElements.end();
1997 for (HashSet<Element*>::iterator it = m_layerUpdateElements.begin(); it != end; ++it)
1998 (*it)->setNeedsStyleRecalc(LocalStyleChange);
1999 m_layerUpdateElements.clear();
2003 void Document::scheduleLayerUpdate(Element& element)
2005 if (element.styleChangeType() == NeedsReattachStyleChange)
2007 element.setNeedsLayerUpdate();
2008 m_layerUpdateElements.add(&element);
2009 scheduleRenderTreeUpdate();
2012 void Document::unscheduleLayerUpdate(Element& element)
2014 element.clearNeedsLayerUpdate();
2015 m_layerUpdateElements.remove(&element);
2018 void Document::scheduleUseShadowTreeUpdate(SVGUseElement& element)
2020 m_useElementsNeedingUpdate.add(&element);
2021 scheduleRenderTreeUpdate();
2024 void Document::unscheduleUseShadowTreeUpdate(SVGUseElement& element)
2026 m_useElementsNeedingUpdate.remove(&element);
2029 void Document::updateUseShadowTreesIfNeeded()
2031 if (m_useElementsNeedingUpdate.isEmpty())
2034 Vector<SVGUseElement*> elements;
2035 copyToVector(m_useElementsNeedingUpdate, elements);
2036 m_useElementsNeedingUpdate.clear();
2038 Vector<SVGUseElement*>::iterator end = elements.end();
2039 for (Vector<SVGUseElement*>::iterator it = elements.begin(); it != end; ++it)
2040 (*it)->buildPendingResource();
2043 StyleResolver* Document::styleResolver() const
2045 return m_styleEngine->resolver();
2048 StyleResolver& Document::ensureStyleResolver() const
2050 return m_styleEngine->ensureResolver();
2053 void Document::clearStyleResolver()
2055 m_styleEngine->clearResolver();
2058 void Document::attach(const AttachContext& context)
2060 ASSERT(m_lifecycle.state() == DocumentLifecycle::Inactive);
2061 ASSERT(!m_axObjectCache || this != topDocument());
2063 m_renderView = new RenderView(this);
2064 setRenderer(m_renderView);
2066 m_renderView->setIsInWindow(true);
2067 m_renderView->setStyle(StyleResolver::styleForDocument(*this));
2068 view()->updateCompositingLayersAfterStyleChange();
2070 ContainerNode::attach(context);
2072 m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
2075 void Document::detach(const AttachContext& context)
2078 m_lifecycle.advanceTo(DocumentLifecycle::Stopping);
2081 page()->documentDetached(this);
2082 InspectorInstrumentation::documentDetached(this);
2084 if (m_frame->loader().client()->sharedWorkerRepositoryClient())
2085 m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this);
2087 if (this == topDocument())
2088 clearAXObjectCache();
2090 stopActiveDOMObjects();
2092 // FIXME: consider using ActiveDOMObject.
2093 if (m_scriptedAnimationController)
2094 m_scriptedAnimationController->clearDocumentPointer();
2095 m_scriptedAnimationController.clear();
2097 if (svgExtensions())
2098 accessSVGExtensions().pauseAnimations();
2100 // FIXME: This shouldn't be needed once DOMWindow becomes ExecutionContext.
2102 m_domWindow->clearEventQueue();
2104 RenderView* renderView = m_renderView;
2107 renderView->setIsInWindow(false);
2110 FrameView* view = m_frame->view();
2112 view->detachCustomScrollbars();
2115 // Indicate destruction mode by setting the renderer to null.
2116 // FIXME: Don't do this and use m_lifecycle.state() == Stopping instead.
2120 m_hoverNode = nullptr;
2121 m_focusedElement = nullptr;
2122 m_activeHoverElement = nullptr;
2123 m_autofocusElement = nullptr;
2125 ContainerNode::detach(context);
2127 m_styleEngine->didDetach();
2130 renderView->destroy();
2132 if (Document* parentDoc = parentDocument())
2133 parentDoc->didClearTouchEventHandlers(this);
2135 // This is required, as our LocalFrame might delete itself as soon as it detaches
2136 // us. However, this violates Node::detach() semantics, as it's never
2137 // possible to re-attach. Eventually Document::detach() should be renamed,
2138 // or this setting of the frame to 0 could be made explicit in each of the
2139 // callers of Document::detach().
2142 if (m_mediaQueryMatcher)
2143 m_mediaQueryMatcher->documentDestroyed();
2145 lifecycleNotifier().notifyDocumentWasDetached();
2146 m_lifecycle.advanceTo(DocumentLifecycle::Stopped);
2149 void Document::prepareForDestruction()
2151 m_markers->prepareForDestruction();
2152 disconnectDescendantFrames();
2154 // The process of disconnecting descendant frames could have already detached us.
2158 if (DOMWindow* window = this->domWindow())
2159 window->willDetachDocumentFromFrame();
2163 void Document::removeAllEventListeners()
2165 ContainerNode::removeAllEventListeners();
2167 if (DOMWindow* domWindow = this->domWindow())
2168 domWindow->removeAllEventListeners();
2169 for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
2170 node->removeAllEventListeners();
2173 void Document::clearAXObjectCache()
2175 ASSERT(topDocument() == this);
2176 // Clear the cache member variable before calling delete because attempts
2177 // are made to access it during destruction.
2178 m_axObjectCache.clear();
2181 AXObjectCache* Document::existingAXObjectCache() const
2183 if (!AXObjectCache::accessibilityEnabled())
2186 // If the renderer is gone then we are in the process of destruction.
2187 // This method will be called before m_frame = 0.
2188 if (!topDocument().renderView())
2191 return topDocument().m_axObjectCache.get();
2194 AXObjectCache* Document::axObjectCache() const
2196 if (!AXObjectCache::accessibilityEnabled())
2199 // The only document that actually has a AXObjectCache is the top-level
2200 // document. This is because we need to be able to get from any WebCoreAXObject
2201 // to any other WebCoreAXObject on the same page. Using a single cache allows
2202 // lookups across nested webareas (i.e. multiple documents).
2203 Document& topDocument = this->topDocument();
2205 // If the document has already been detached, do not make a new axObjectCache.
2206 if (!topDocument.renderView())
2209 ASSERT(topDocument == this || !m_axObjectCache);
2210 if (!topDocument.m_axObjectCache)
2211 topDocument.m_axObjectCache = adoptPtr(new AXObjectCache(topDocument));
2212 return topDocument.m_axObjectCache.get();
2215 PassRefPtr<DocumentParser> Document::createParser()
2217 if (isHTMLDocument()) {
2218 bool reportErrors = InspectorInstrumentation::collectingHTMLParseErrors(page());
2219 return HTMLDocumentParser::create(toHTMLDocument(this), reportErrors);
2221 // FIXME: this should probably pass the frame instead
2222 return XMLDocumentParser::create(this, view());
2225 bool Document::isFrameSet() const
2227 if (!isHTMLDocument())
2229 return isHTMLFrameSetElement(body());
2232 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2234 return parser() ? parser()->asScriptableDocumentParser() : 0;
2237 void Document::open(Document* ownerDocument)
2239 if (ownerDocument) {
2240 setURL(ownerDocument->url());
2241 m_cookieURL = ownerDocument->cookieURL();
2242 setSecurityOrigin(ownerDocument->securityOrigin());
2246 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2247 if (parser->isParsing()) {
2248 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2249 if (parser->isExecutingScript())
2252 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2257 if (m_frame->loader().state() == FrameStateProvisional)
2258 m_frame->loader().stopAllLoaders();
2261 removeAllEventListeners();
2263 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2264 parser->setWasCreatedByScript(true);
2267 m_frame->loader().didExplicitOpen();
2268 if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
2269 m_loadEventProgress = LoadEventNotRun;
2272 void Document::detachParser()
2280 void Document::cancelParsing()
2285 // We have to clear the parser to avoid possibly triggering
2286 // the onload handler when closing as a side effect of a cancel-style
2287 // change, such as opening a new document or closing the window while
2293 PassRefPtr<DocumentParser> Document::implicitOpen()
2298 ASSERT(!m_focusedElement);
2300 setCompatibilityMode(NoQuirksMode);
2302 m_parser = createParser();
2304 setReadyState(Loading);
2309 HTMLElement* Document::body() const
2311 if (!documentElement())
2314 for (HTMLElement* child = Traversal<HTMLElement>::firstWithin(*documentElement()); child; child = Traversal<HTMLElement>::nextSibling(*child)) {
2315 if (isHTMLFrameSetElement(*child) || isHTMLBodyElement(*child))
2322 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionState& exceptionState)
2324 RefPtr<HTMLElement> newBody = prpNewBody;
2327 exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::argumentNullOrIncorrectType(1, "HTMLElement"));
2330 if (!documentElement()) {
2331 exceptionState.throwDOMException(HierarchyRequestError, "No document element exists.");
2335 if (!isHTMLBodyElement(*newBody) && !isHTMLFrameSetElement(*newBody)) {
2336 exceptionState.throwDOMException(HierarchyRequestError, "The new body element is of type '" + newBody->tagName() + "'. It must be either a 'BODY' or 'FRAMESET' element.");
2340 HTMLElement* oldBody = body();
2341 if (oldBody == newBody)
2345 documentElement()->replaceChild(newBody.release(), oldBody, exceptionState);
2347 documentElement()->appendChild(newBody.release(), exceptionState);
2350 HTMLHeadElement* Document::head()
2352 Node* de = documentElement();
2356 return Traversal<HTMLHeadElement>::firstChild(*de);
2359 Element* Document::viewportDefiningElement(RenderStyle* rootStyle) const
2361 // If a BODY element sets non-visible overflow, it is to be propagated to the viewport, as long
2362 // as the following conditions are all met:
2363 // (1) The root element is HTML.
2364 // (2) It is the primary BODY element (we only assert for this, expecting callers to behave).
2365 // (3) The root element has visible overflow.
2366 // Otherwise it's the root element's properties that are to be propagated.
2367 Element* rootElement = documentElement();
2368 Element* bodyElement = body();
2372 rootStyle = rootElement->renderStyle();
2376 if (bodyElement && rootStyle->isOverflowVisible() && isHTMLHtmlElement(*rootElement))
2381 void Document::close()
2383 // FIXME: We should follow the specification more closely:
2384 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2386 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2392 void Document::explicitClose()
2394 if (RefPtr<DocumentParser> parser = m_parser)
2398 // Because we have no frame, we don't know if all loading has completed,
2399 // so we just call implicitClose() immediately. FIXME: This might fire
2400 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2405 m_frame->loader().checkCompleted();
2408 void Document::implicitClose()
2410 ASSERT(!inStyleRecalc());
2412 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2413 bool doload = !parsing() && m_parser && !processingLoadEvent() && !wasLocationChangePending;
2415 // If the load was blocked because of a pending location change and the location change triggers a same document
2416 // navigation, don't fire load events after the same document navigation completes (unless there's an explicit open).
2417 m_loadEventProgress = LoadEventTried;
2422 // The call to dispatchWindowLoadEvent can detach the DOMWindow and cause it (and its
2423 // attached Document) to be destroyed.
2424 RefPtrWillBeRawPtr<DOMWindow> protectedWindow(this->domWindow());
2426 m_loadEventProgress = LoadEventInProgress;
2428 ScriptableDocumentParser* parser = scriptableDocumentParser();
2429 m_wellFormed = parser && parser->wellFormed();
2431 // We have to clear the parser, in case someone document.write()s from the
2432 // onLoad event handler, as in Radar 3206524.
2435 if (frame() && frame()->script().canExecuteScripts(NotAboutToExecuteScript)) {
2436 ImageLoader::dispatchPendingLoadEvents();
2437 ImageLoader::dispatchPendingErrorEvents();
2439 HTMLLinkElement::dispatchPendingLoadEvents();
2440 HTMLStyleElement::dispatchPendingLoadEvents();
2443 // JS running below could remove the frame or destroy the RenderView so we call
2444 // those two functions repeatedly and don't save them on the stack.
2446 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2447 // here, instead of doing it from SVGElement::finishedParsingChildren.
2448 if (svgExtensions())
2449 accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2451 if (protectedWindow)
2452 protectedWindow->documentWasClosed();
2455 frame()->loader().client()->dispatchDidHandleOnloadEvents();
2456 loader()->applicationCacheHost()->stopDeferringEvents();
2460 m_loadEventProgress = LoadEventCompleted;
2464 // Make sure both the initial layout and reflow happen after the onload
2465 // fires. This will improve onload scores, and other browsers do it.
2466 // If they wanna cheat, we can too. -dwh
2468 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2469 // Just bail out. Before or during the onload we were shifted to another page.
2470 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2471 m_loadEventProgress = LoadEventCompleted;
2475 // We used to force a synchronous display and flush here. This really isn't
2476 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2477 // (if your platform is syncing flushes and limiting them to 60fps).
2478 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2479 updateRenderTreeIfNeeded();
2481 // Always do a layout after loading if needed.
2482 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2486 m_loadEventProgress = LoadEventCompleted;
2488 if (frame() && renderView() && AXObjectCache::accessibilityEnabled()) {
2489 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2490 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2491 // exists in the cache (we ignore the return value because we don't need it here). This is
2492 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2493 if (AXObjectCache* cache = axObjectCache()) {
2494 cache->getOrCreate(renderView());
2495 if (this == topDocument()) {
2496 cache->postNotification(renderView(), AXObjectCache::AXLoadComplete, true);
2498 // AXLoadComplete can only be posted on the top document, so if it's a document
2499 // in an iframe that just finished loading, post AXLayoutComplete instead.
2500 cache->postNotification(renderView(), AXObjectCache::AXLayoutComplete, true);
2505 if (svgExtensions())
2506 accessSVGExtensions().startAnimations();
2509 bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigation)
2517 RefPtr<Document> protect(this);
2519 RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2520 m_loadEventProgress = BeforeUnloadEventInProgress;
2521 m_domWindow->dispatchEvent(beforeUnloadEvent.get(), this);
2522 m_loadEventProgress = BeforeUnloadEventCompleted;
2523 if (!beforeUnloadEvent->defaultPrevented())
2524 defaultEventHandler(beforeUnloadEvent.get());
2525 if (beforeUnloadEvent->returnValue().isNull())
2528 if (didAllowNavigation) {
2529 addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation.");
2533 String text = beforeUnloadEvent->returnValue();
2534 if (chrome.runBeforeUnloadConfirmPanel(text, m_frame)) {
2535 didAllowNavigation = true;
2541 void Document::dispatchUnloadEvents()
2543 RefPtr<Document> protect(this);
2545 m_parser->stopParsing();
2547 if (m_loadEventProgress >= LoadEventTried && m_loadEventProgress <= UnloadEventInProgress) {
2548 Element* currentFocusedElement = focusedElement();
2549 if (isHTMLInputElement(currentFocusedElement))
2550 toHTMLInputElement(*currentFocusedElement).endEditing();
2551 if (m_loadEventProgress < PageHideInProgress) {
2552 m_loadEventProgress = PageHideInProgress;
2553 if (DOMWindow* window = domWindow())
2554 window->dispatchEvent(PageTransitionEvent::create(EventTypeNames::pagehide, false), this);
2558 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
2559 // while dispatching the event, so protect it to prevent writing the end
2560 // time into freed memory.
2561 RefPtr<DocumentLoader> documentLoader = m_frame->loader().provisionalDocumentLoader();
2562 m_loadEventProgress = UnloadEventInProgress;
2563 RefPtr<Event> unloadEvent(Event::create(EventTypeNames::unload));
2564 if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
2565 DocumentLoadTiming* timing = documentLoader->timing();
2566 ASSERT(timing->navigationStart());
2567 timing->markUnloadEventStart();
2568 m_frame->domWindow()->dispatchEvent(unloadEvent, this);
2569 timing->markUnloadEventEnd();
2571 m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
2574 m_loadEventProgress = UnloadEventHandled;
2580 // Don't remove event listeners from a transitional empty document (see https://bugs.webkit.org/show_bug.cgi?id=28716 for more information).
2581 bool keepEventListeners = m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader().provisionalDocumentLoader()
2582 && isSecureTransitionTo(m_frame->loader().provisionalDocumentLoader()->url());
2583 if (!keepEventListeners)
2584 removeAllEventListeners();
2587 Document::PageDismissalType Document::pageDismissalEventBeingDispatched() const
2589 if (m_loadEventProgress == BeforeUnloadEventInProgress)
2590 return BeforeUnloadDismissal;
2591 if (m_loadEventProgress == PageHideInProgress)
2592 return PageHideDismissal;
2593 if (m_loadEventProgress == UnloadEventInProgress)
2594 return UnloadDismissal;
2598 void Document::setParsing(bool b)
2602 if (m_isParsing && !m_elementDataCache)
2603 m_elementDataCache = ElementDataCache::create();
2606 bool Document::shouldScheduleLayout() const
2608 // This function will only be called when FrameView thinks a layout is needed.
2609 // This enforces a couple extra rules.
2611 // (a) Only schedule a layout once the stylesheets are loaded.
2612 // (b) Only schedule layout once we have a body element.
2614 return (haveStylesheetsAndImportsLoaded() && body())
2615 || (documentElement() && !isHTMLHtmlElement(*documentElement()));
2618 int Document::elapsedTime() const
2620 return static_cast<int>((currentTime() - m_startTime) * 1000);
2623 void Document::write(const SegmentedString& text, Document* ownerDocument)
2625 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2627 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2628 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2630 if (m_writeRecursionIsTooDeep)
2633 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2635 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount) {
2636 addConsoleMessage(JSMessageSource, WarningMessageLevel, ExceptionMessages::failedToExecute("write", "Document", "It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened."));
2640 if (!hasInsertionPoint)
2641 open(ownerDocument);
2644 m_parser->insert(text);
2647 void Document::write(const String& text, Document* ownerDocument)
2649 write(SegmentedString(text), ownerDocument);
2652 void Document::writeln(const String& text, Document* ownerDocument)
2654 write(text, ownerDocument);
2655 write("\n", ownerDocument);
2658 const KURL& Document::virtualURL() const
2663 KURL Document::virtualCompleteURL(const String& url) const
2665 return completeURL(url);
2668 double Document::timerAlignmentInterval() const
2672 return DOMTimer::visiblePageAlignmentInterval();
2673 return p->timerAlignmentInterval();
2676 EventTarget* Document::errorEventTarget()
2681 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
2683 internalAddMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack, 0);
2686 void Document::setURL(const KURL& url)
2688 const KURL& newURL = url.isEmpty() ? blankURL() : url;
2689 if (newURL == m_url)
2694 contextFeatures().urlDidChange(this);
2697 void Document::updateBaseURL()
2699 KURL oldBaseURL = m_baseURL;
2700 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2701 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2702 // from the Document interface otherwise (which we store, preparsed, in m_url).
2703 if (!m_baseElementURL.isEmpty())
2704 m_baseURL = m_baseElementURL;
2705 else if (!m_baseURLOverride.isEmpty())
2706 m_baseURL = m_baseURLOverride;
2710 selectorQueryCache().invalidate();
2712 if (!m_baseURL.isValid())
2716 // Element sheet is silly. It never contains anything.
2717 ASSERT(!m_elemSheet->contents()->ruleCount());
2718 bool usesRemUnits = m_elemSheet->contents()->usesRemUnits();
2719 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2720 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2721 m_elemSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
2724 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2725 // Base URL change changes any relative visited links.
2726 // 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.
2727 for (HTMLAnchorElement* anchor = Traversal<HTMLAnchorElement>::firstWithin(*this); anchor; anchor = Traversal<HTMLAnchorElement>::next(*anchor))
2728 anchor->invalidateCachedVisitedLinkHash();
2732 void Document::setBaseURLOverride(const KURL& url)
2734 m_baseURLOverride = url;
2738 void Document::processBaseElement()
2740 // Find the first href attribute in a base element and the first target attribute in a base element.
2741 const AtomicString* href = 0;
2742 const AtomicString* target = 0;
2743 for (HTMLBaseElement* base = Traversal<HTMLBaseElement>::firstWithin(*this); base && (!href || !target); base = Traversal<HTMLBaseElement>::next(*base)) {
2745 const AtomicString& value = base->fastGetAttribute(hrefAttr);
2746 if (!value.isNull())
2750 const AtomicString& value = base->fastGetAttribute(targetAttr);
2751 if (!value.isNull())
2754 if (contentSecurityPolicy()->isActive())
2755 UseCounter::count(*this, UseCounter::ContentSecurityPolicyWithBaseElement);
2758 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2759 KURL baseElementURL;
2761 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2762 if (!strippedHref.isEmpty())
2763 baseElementURL = KURL(url(), strippedHref);
2765 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
2766 m_baseElementURL = baseElementURL;
2770 m_baseTarget = target ? *target : nullAtom;
2773 String Document::userAgent(const KURL& url) const
2775 return frame() ? frame()->loader().userAgent(url) : String();
2778 void Document::disableEval(const String& errorMessage)
2783 frame()->script().disableEval(errorMessage);
2786 bool Document::canNavigate(LocalFrame* targetFrame)
2791 // FIXME: We shouldn't call this function without a target frame, but
2792 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2793 // returning true when supplied with a 0 targetFrame.
2797 // LocalFrame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
2798 if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
2801 if (isSandboxed(SandboxNavigation)) {
2802 if (targetFrame->tree().isDescendantOf(m_frame))
2805 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
2806 if (isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
2807 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
2809 printNavigationErrorMessage(*targetFrame, url(), reason);
2813 ASSERT(securityOrigin());
2814 SecurityOrigin& origin = *securityOrigin();
2816 // This is the normal case. A document can navigate its decendant frames,
2817 // or, more generally, a document can navigate a frame if the document is
2818 // in the same origin as any of that frame's ancestors (in the frame
2821 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2822 // historical information about this security check.
2823 if (canAccessAncestor(origin, targetFrame))
2826 // Top-level frames are easier to navigate than other frames because they
2827 // display their URLs in the address bar (in most browsers). However, there
2828 // are still some restrictions on navigation to avoid nuisance attacks.
2829 // Specifically, a document can navigate a top-level frame if that frame
2830 // opened the document or if the document is the same-origin with any of
2831 // the top-level frame's opener's ancestors (in the frame hierarchy).
2833 // In both of these cases, the document performing the navigation is in
2834 // some way related to the frame being navigate (e.g., by the "opener"
2835 // and/or "parent" relation). Requiring some sort of relation prevents a
2836 // document from navigating arbitrary, unrelated top-level frames.
2837 if (!targetFrame->tree().parent()) {
2838 if (targetFrame == m_frame->loader().opener())
2841 if (canAccessAncestor(origin, targetFrame->loader().opener()))
2845 printNavigationErrorMessage(*targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
2849 LocalFrame* Document::findUnsafeParentScrollPropagationBoundary()
2851 LocalFrame* currentFrame = m_frame;
2852 LocalFrame* ancestorFrame = currentFrame->tree().parent();
2854 while (ancestorFrame) {
2855 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
2856 return currentFrame;
2857 currentFrame = ancestorFrame;
2858 ancestorFrame = ancestorFrame->tree().parent();
2863 void Document::didLoadAllImports()
2865 if (!haveStylesheetsLoaded())
2868 didLoadAllScriptBlockingResources();
2871 void Document::didRemoveAllPendingStylesheet()
2873 m_needsNotifyRemoveAllPendingStylesheet = false;
2875 styleResolverChanged(RecalcStyleDeferred, hasNodesWithPlaceholderStyle() ? FullStyleUpdate : AnalyzedStyleUpdate);
2878 m_import->didRemoveAllPendingStylesheet();
2879 if (!haveImportsLoaded())
2882 didLoadAllScriptBlockingResources();
2885 void Document::didLoadAllScriptBlockingResources()
2887 executeScriptsWaitingForResourcesIfNeeded();
2889 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
2890 view()->scrollToFragment(m_url);
2894 void Document::executeScriptsWaitingForResourcesIfNeeded()
2896 if (!haveStylesheetsAndImportsLoaded())
2898 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2899 parser->executeScriptsWaitingForResources();
2903 CSSStyleSheet& Document::elementSheet()
2906 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2907 return *m_elemSheet;
2910 void Document::processHttpEquiv(const AtomicString& equiv, const AtomicString& content, bool inDocumentHeadElement)
2912 ASSERT(!equiv.isNull() && !content.isNull());
2914 if (equalIgnoringCase(equiv, "default-style")) {
2915 processHttpEquivDefaultStyle(content);
2916 } else if (equalIgnoringCase(equiv, "refresh")) {
2917 processHttpEquivRefresh(content);
2918 } else if (equalIgnoringCase(equiv, "set-cookie")) {
2919 processHttpEquivSetCookie(content);
2920 } else if (equalIgnoringCase(equiv, "content-language")) {
2921 setContentLanguage(content);
2922 } else if (equalIgnoringCase(equiv, "x-dns-prefetch-control")) {
2923 parseDNSPrefetchControlHeader(content);
2924 } else if (equalIgnoringCase(equiv, "x-frame-options")) {
2925 processHttpEquivXFrameOptions(content);
2926 } else if (equalIgnoringCase(equiv, "content-security-policy") || equalIgnoringCase(equiv, "content-security-policy-report-only")) {
2927 if (inDocumentHeadElement)
2928 processHttpEquivContentSecurityPolicy(equiv, content);
2930 contentSecurityPolicy()->reportMetaOutsideHead(content);
2934 void Document::processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content)
2936 if (import() && import()->isChild())
2938 if (equalIgnoringCase(equiv, "content-security-policy"))
2939 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeEnforce, ContentSecurityPolicyHeaderSourceMeta);
2940 else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
2941 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeReport, ContentSecurityPolicyHeaderSourceMeta);
2943 ASSERT_NOT_REACHED();
2946 void Document::processHttpEquivDefaultStyle(const AtomicString& content)
2948 // The preferred style set has been overridden as per section
2949 // 14.3.2 of the HTML4.0 specification. We need to update the
2950 // sheet used variable and then update our style selector.
2951 // For more info, see the test at:
2952 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
2954 m_styleEngine->setSelectedStylesheetSetName(content);
2955 m_styleEngine->setPreferredStylesheetSetName(content);
2956 styleResolverChanged(RecalcStyleDeferred);
2959 void Document::processHttpEquivRefresh(const AtomicString& content)
2961 maybeHandleHttpRefresh(content, HttpRefreshFromMetaTag);
2964 void Document::maybeHandleHttpRefresh(const String& content, HttpRefreshType httpRefreshType)
2966 if (m_isViewSource || !m_frame)
2971 if (!parseHTTPRefresh(content, httpRefreshType == HttpRefreshFromMetaTag, delay, refreshURL))
2973 if (refreshURL.isEmpty())
2974 refreshURL = url().string();
2976 refreshURL = completeURL(refreshURL).string();
2978 if (protocolIsJavaScript(refreshURL)) {
2979 String message = "Refused to refresh " + m_url.elidedString() + " to a javascript: URL";
2980 addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
2984 if (httpRefreshType == HttpRefreshFromMetaTag && isSandboxed(SandboxAutomaticFeatures)) {
2985 String message = "Refused to execute the redirect specified via '<meta http-equiv='refresh' content='...'>'. The document is sandboxed, and the 'allow-scripts' keyword is not set.";
2986 addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
2989 m_frame->navigationScheduler().scheduleRedirect(delay, refreshURL);
2992 void Document::processHttpEquivSetCookie(const AtomicString& content)
2994 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
2995 if (!isHTMLDocument())
2998 // Exception (for sandboxed documents) ignored.
2999 toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
3002 void Document::processHttpEquivXFrameOptions(const AtomicString& content)
3004 LocalFrame* frame = this->frame();
3008 FrameLoader& frameLoader = frame->loader();
3009 unsigned long requestIdentifier = loader()->mainResourceIdentifier();
3010 if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
3011 String message = "Refused to display '" + url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
3012 frameLoader.stopAllLoaders();
3013 // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
3014 // intent, we must navigate away from the possibly partially-rendered document to a location that
3015 // doesn't inherit the parent's SecurityOrigin.
3016 frame->navigationScheduler().scheduleLocationChange(this, SecurityOrigin::urlWithUniqueSecurityOrigin(), Referrer());
3017 addConsoleMessageWithRequestIdentifier(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
3021 bool Document::shouldMergeWithLegacyDescription(ViewportDescription::Type origin)
3023 return settings() && settings()->viewportMetaMergeContentQuirk() && m_legacyViewportDescription.isMetaViewportType() && m_legacyViewportDescription.type == origin;
3026 void Document::setViewportDescription(const ViewportDescription& viewportDescription)
3028 if (viewportDescription.isLegacyViewportType()) {
3029 if (settings() && !settings()->viewportMetaEnabled())
3032 m_legacyViewportDescription = viewportDescription;
3034 // When no author style for @viewport is present, and a meta tag for defining
3035 // the viewport is, apply the meta tag viewport instead of the UA styles.
3036 if (m_viewportDescription.type == ViewportDescription::AuthorStyleSheet)
3038 m_viewportDescription = viewportDescription;
3040 // If the legacy viewport tag has higher priority than the cascaded @viewport
3041 // descriptors, use the values from the legacy tag.
3042 if (!shouldOverrideLegacyDescription(viewportDescription.type))
3043 m_viewportDescription = m_legacyViewportDescription;
3045 m_viewportDescription = viewportDescription;
3048 updateViewportDescription();
3051 void Document::updateViewportDescription()
3053 if (frame() && frame()->isMainFrame()) {
3055 m_didDispatchViewportPropertiesChanged = true;
3057 frameHost()->chrome().dispatchViewportPropertiesDidChange(m_viewportDescription);
3061 void Document::processReferrerPolicy(const String& policy)
3063 ASSERT(!policy.isNull());
3065 if (equalIgnoringCase(policy, "never")) {
3066 setReferrerPolicy(ReferrerPolicyNever);
3067 } else if (equalIgnoringCase(policy, "always")) {
3068 setReferrerPolicy(ReferrerPolicyAlways);
3069 } else if (equalIgnoringCase(policy, "origin")) {
3070 setReferrerPolicy(ReferrerPolicyOrigin);
3071 } else if (equalIgnoringCase(policy, "default")) {
3072 setReferrerPolicy(ReferrerPolicyDefault);
3074 addConsoleMessage(RenderingMessageSource, ErrorMessageLevel, "Failed to set referrer policy: The value '" + policy + "' is not one of 'always', 'default', 'never', or 'origin'. Defaulting to 'never'.");
3075 setReferrerPolicy(ReferrerPolicyNever);
3079 void Document::setReferrerPolicy(ReferrerPolicy referrerPolicy)
3081 // FIXME: Can we adopt the CSP referrer policy merge algorithm? Or does the web rely on being able to modify the referrer policy in-flight?
3082 if (m_didSetReferrerPolicy)
3083 UseCounter::count(this, UseCounter::ResetReferrerPolicy);
3084 m_didSetReferrerPolicy = true;
3086 m_referrerPolicy = referrerPolicy;
3089 String Document::outgoingReferrer()
3091 // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
3092 // for why we walk the parent chain for srcdoc documents.
3093 Document* referrerDocument = this;
3094 if (LocalFrame* frame = m_frame) {
3095 while (frame->document()->isSrcdocDocument()) {
3096 frame = frame->tree().parent();
3097 // Srcdoc documents cannot be top-level documents, by definition,
3098 // because they need to be contained in iframes with the srcdoc.
3101 referrerDocument = frame->document();
3103 return referrerDocument->m_url.strippedForUseAsReferrer();
3106 String Document::outgoingOrigin() const
3108 return securityOrigin()->toString();
3111 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3113 ASSERT(!renderView() || renderView()->isRenderView());
3115 // RenderView::hitTest causes a layout, and we don't want to hit that until the first
3116 // layout because until then, there is nothing shown on the screen - the user can't
3117 // have intentionally clicked on something belonging to this page. Furthermore,
3118 // mousemove events before the first layout should not lead to a premature layout()
3119 // happening, which could show a flash of white.
3120 // See also the similar code in EventHandler::hitTestResultAtPoint.
3121 if (!renderView() || !view() || !view()->didFirstLayout())
3122 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3124 HitTestResult result(documentPoint);
3125 renderView()->hitTest(request, result);
3127 if (!request.readOnly())
3128 updateHoverActiveState(request, result.innerElement(), &event);
3130 return MouseEventWithHitTestResults(event, result);
3133 // DOM Section 1.1.1
3134 bool Document::childTypeAllowed(NodeType type) const
3137 case ATTRIBUTE_NODE:
3138 case CDATA_SECTION_NODE:
3139 case DOCUMENT_FRAGMENT_NODE:
3144 case PROCESSING_INSTRUCTION_NODE:
3146 case DOCUMENT_TYPE_NODE:
3148 // Documents may contain no more than one of each of these.
3149 // (One Element and one DocumentType.)
3150 for (Node* c = firstChild(); c; c = c->nextSibling())
3151 if (c->nodeType() == type)
3158 bool Document::canReplaceChild(const Node& newChild, const Node& oldChild) const
3160 if (oldChild.nodeType() == newChild.nodeType())
3163 int numDoctypes = 0;
3164 int numElements = 0;
3166 // First, check how many doctypes and elements we have, not counting
3167 // the child we're about to remove.
3168 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3172 switch (c->nodeType()) {
3173 case DOCUMENT_TYPE_NODE:
3184 // Then, see how many doctypes and elements might be added by the new child.
3185 if (newChild.nodeType() == DOCUMENT_FRAGMENT_NODE) {
3186 for (Node* c = newChild.firstChild(); c; c = c->nextSibling()) {
3187 switch (c->nodeType()) {
3188 case ATTRIBUTE_NODE:
3189 case CDATA_SECTION_NODE:
3190 case DOCUMENT_FRAGMENT_NODE:
3195 case PROCESSING_INSTRUCTION_NODE:
3197 case DOCUMENT_TYPE_NODE:
3206 switch (newChild.nodeType()) {
3207 case ATTRIBUTE_NODE:
3208 case CDATA_SECTION_NODE:
3209 case DOCUMENT_FRAGMENT_NODE:
3214 case PROCESSING_INSTRUCTION_NODE:
3216 case DOCUMENT_TYPE_NODE:
3225 if (numElements > 1 || numDoctypes > 1)
3231 PassRefPtr<Node> Document::cloneNode(bool deep)
3233 RefPtr<Document> clone = cloneDocumentWithoutChildren();
3234 clone->cloneDataFromDocument(*this);
3236 cloneChildNodes(clone.get());
3237 return clone.release();
3240 PassRefPtr<Document> Document::cloneDocumentWithoutChildren()
3242 DocumentInit init(url());
3243 if (isXMLDocument()) {
3244 if (isXHTMLDocument())
3245 return XMLDocument::createXHTML(init.withRegistrationContext(registrationContext()));
3246 return XMLDocument::create(init);
3248 return create(init);
3251 void Document::cloneDataFromDocument(const Document& other)
3253 setCompatibilityMode(other.compatibilityMode());
3254 setEncodingData(other.m_encodingData);
3255 setContextFeatures(other.contextFeatures());
3256 setSecurityOrigin(other.securityOrigin()->isolatedCopy());
3259 StyleSheetList* Document::styleSheets()
3261 if (!m_styleSheetList)
3262 m_styleSheetList = StyleSheetList::create(this);
3263 return m_styleSheetList.get();
3266 String Document::preferredStylesheetSet() const
3268 return m_styleEngine->preferredStylesheetSetName();
3271 String Document::selectedStylesheetSet() const
3273 return m_styleEngine->selectedStylesheetSetName();
3276 void Document::setSelectedStylesheetSet(const String& aString)
3278 m_styleEngine->setSelectedStylesheetSetName(aString);
3279 styleResolverChanged(RecalcStyleDeferred);
3282 void Document::evaluateMediaQueryListIfNeeded()
3284 if (!m_evaluateMediaQueriesOnStyleRecalc)
3286 evaluateMediaQueryList();
3287 m_evaluateMediaQueriesOnStyleRecalc = false;
3290 void Document::evaluateMediaQueryList()
3292 if (m_mediaQueryMatcher)
3293 m_mediaQueryMatcher->styleResolverChanged();
3296 void Document::notifyResizeForViewportUnits()
3298 if (!hasViewportUnits())
3300 ensureStyleResolver().notifyResizeForViewportUnits();
3301 setNeedsStyleRecalcForViewportUnits();
3304 void Document::styleResolverChanged(RecalcStyleTime updateTime, StyleResolverUpdateMode updateMode)
3306 // styleResolverChanged() can be invoked during Document destruction.
3307 // We just skip that case.
3311 StyleResolverChange change = m_styleEngine->resolverChanged(updateTime, updateMode);
3312 if (change.needsRepaint()) {
3313 // We need to manually repaint because we avoid doing all repaints in layout or style
3314 // recalc while sheets are still loading to avoid FOUC.
3315 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3316 renderView()->repaintViewAndCompositedLayers();
3319 if (!change.needsStyleRecalc())
3322 m_evaluateMediaQueriesOnStyleRecalc = true;
3323 setNeedsStyleRecalc(SubtreeStyleChange);
3325 if (updateTime == RecalcStyleImmediately)
3326 updateRenderTreeIfNeeded();
3329 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
3331 m_hoverNode = newHoverNode;
3334 void Document::setActiveHoverElement(PassRefPtr<Element> newActiveElement)
3336 if (!newActiveElement) {
3337 m_activeHoverElement.clear();
3341 m_activeHoverElement = newActiveElement;
3344 void Document::removeFocusedElementOfSubtree(Node* node, bool amongChildrenOnly)
3346 if (!m_focusedElement)
3349 // We can't be focused if we're not in the document.
3350 if (!node->inDocument())
3352 bool contains = node->containsIncludingShadowDOM(m_focusedElement.get());
3353 if (contains && (m_focusedElement != node || !amongChildrenOnly))
3354 setFocusedElement(nullptr);
3357 void Document::hoveredNodeDetached(Node* node)
3362 if (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != NodeRenderingTraversal::parent(m_hoverNode.get())))
3365 m_hoverNode = NodeRenderingTraversal::parent(node);
3366 while (m_hoverNode && !m_hoverNode->renderer())
3367 m_hoverNode = NodeRenderingTraversal::parent(m_hoverNode.get());
3369 // If the mouse cursor is not visible, do not clear existing
3370 // hover effects on the ancestors of |node| and do not invoke
3371 // new hover effects on any other element.
3372 if (!page()->isCursorVisible())
3376 frame()->eventHandler().scheduleHoverStateUpdate();
3379 void Document::activeChainNodeDetached(Node* node)
3381 if (!m_activeHoverElement)
3384 if (node != m_activeHoverElement && (!m_activeHoverElement->isTextNode() || node != NodeRenderingTraversal::parent(m_activeHoverElement.get())))
3387 Node* activeNode = NodeRenderingTraversal::parent(node);
3388 while (activeNode && activeNode->isElementNode() && !activeNode->renderer())
3389 activeNode = NodeRenderingTraversal::parent(activeNode);
3391 m_activeHoverElement = activeNode && activeNode->isElementNode() ? toElement(activeNode) : 0;
3394 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3396 return m_annotatedRegions;
3399 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3401 m_annotatedRegions = regions;
3402 setAnnotatedRegionsDirty(false);
3405 bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusType type)
3407 m_clearFocusedElementTimer.stop();
3409 RefPtr<Element> newFocusedElement = prpNewFocusedElement;
3411 // Make sure newFocusedNode is actually in this document
3412 if (newFocusedElement && (newFocusedElement->document() != this))
3415 if (NodeChildRemovalTracker::isBeingRemoved(newFocusedElement.get()))
3418 if (m_focusedElement == newFocusedElement)
3421 bool focusChangeBlocked = false;
3422 RefPtr<Element> oldFocusedElement = m_focusedElement;
3423 m_focusedElement = nullptr;
3425 // Remove focus from the existing focus node (if any)
3426 if (oldFocusedElement) {
3427 ASSERT(!oldFocusedElement->inDetach());
3429 if (oldFocusedElement->active())
3430 oldFocusedElement->setActive(false);
3432 oldFocusedElement->setFocus(false);
3434 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3435 // If page lost focus, blur event will have already been dispatched
3436 if (page() && (page()->focusController().isFocused())) {
3437 oldFocusedElement->dispatchBlurEvent(newFocusedElement.get());
3439 if (m_focusedElement) {
3440 // handler shifted focus
3441 focusChangeBlocked = true;
3442 newFocusedElement = nullptr;
3445 oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::focusout, newFocusedElement.get()); // DOM level 3 name for the bubbling blur event.
3446 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3447 // on it, probably when <rdar://problem/8503958> is resolved.
3448 oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, newFocusedElement.get()); // DOM level 2 name for compatibility.
3450 if (m_focusedElement) {
3451 // handler shifted focus
3452 focusChangeBlocked = true;
3453 newFocusedElement = nullptr;
3458 Widget* oldWidget = widgetForElement(*oldFocusedElement);
3460 oldWidget->setFocus(false);
3462 view()->setFocus(false);
3466 if (newFocusedElement && newFocusedElement->isFocusable()) {
3467 if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(*newFocusedElement)) {
3468 // delegate blocks focus change
3469 focusChangeBlocked = true;
3470 goto SetFocusedElementDone;
3472 // Set focus on the new node
3473 m_focusedElement = newFocusedElement;
3475 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3476 // If page lost focus, event will be dispatched on page focus, don't duplicate
3477 if (page() && (page()->focusController().isFocused())) {
3478 m_focusedElement->dispatchFocusEvent(oldFocusedElement.get(), type);
3481 if (m_focusedElement != newFocusedElement) {
3482 // handler shifted focus
3483 focusChangeBlocked = true;
3484 goto SetFocusedElementDone;
3487 m_focusedElement->dispatchFocusInEvent(EventTypeNames::focusin, oldFocusedElement.get()); // DOM level 3 bubbling focus event.
3489 if (m_focusedElement != newFocusedElement) {
3490 // handler shifted focus
3491 focusChangeBlocked = true;
3492 goto SetFocusedElementDone;
3495 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3496 // on it, probably when <rdar://problem/8503958> is m.
3497 m_focusedElement->dispatchFocusInEvent(EventTypeNames::DOMFocusIn, oldFocusedElement.get()); // DOM level 2 for compatibility.
3499 if (m_focusedElement != newFocusedElement) {
3500 // handler shifted focus
3501 focusChangeBlocked = true;
3502 goto SetFocusedElementDone;
3506 m_focusedElement->setFocus(true);
3508 if (m_focusedElement->isRootEditableElement())
3509 frame()->spellChecker().didBeginEditing(m_focusedElement.get());
3511 // eww, I suck. set the qt focus correctly
3512 // ### find a better place in the code for this
3514 Widget* focusWidget = widgetForElement(*m_focusedElement);
3516 // Make sure a widget has the right size before giving it focus.
3517 // Otherwise, we are testing edge cases of the Widget code.
3518 // Specifically, in WebCore this does not work well for text fields.
3520 // Re-get the widget in case updating the layout changed things.
3521 focusWidget = widgetForElement(*m_focusedElement);
3524 focusWidget->setFocus(true);
3526 view()->setFocus(true);
3530 if (!focusChangeBlocked && m_focusedElement) {
3531 // Create the AXObject cache in a focus change because Chromium relies on it.
3532 if (AXObjectCache* cache = axObjectCache())
3533 cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
3536 if (!focusChangeBlocked && frameHost())
3537 frameHost()->chrome().focusedNodeChanged(m_focusedElement.get());
3539 SetFocusedElementDone:
3540 updateRenderTreeIfNeeded();
3541 if (LocalFrame* frame = this->frame())
3542 frame->selection().didChangeFocus();
3543 return !focusChangeBlocked;
3546 void Document::setCSSTarget(Element* n)
3549 m_cssTarget->didAffectSelector(AffectedSelectorTarget);
3552 n->didAffectSelector(AffectedSelectorTarget);
3555 void Document::registerNodeList(LiveNodeListBase* list)
3557 m_nodeListCounts[list->invalidationType()]++;
3558 if (list->isRootedAtDocument())
3559 m_listsInvalidatedAtDocument.add(list);
3562 void Document::unregisterNodeList(LiveNodeListBase* list)
3564 m_nodeListCounts[list->invalidationType()]--;
3565 if (list->isRootedAtDocument()) {
3566 ASSERT(m_listsInvalidatedAtDocument.contains(list));
3567 m_listsInvalidatedAtDocument.remove(list);
3571 void Document::attachNodeIterator(NodeIterator* ni)
3573 m_nodeIterators.add(ni);
3576 void Document::detachNodeIterator(NodeIterator* ni)
3578 // The node iterator can be detached without having been attached if its root node didn't have a document
3579 // when the iterator was created, but has it now.
3580 m_nodeIterators.remove(ni);
3583 void Document::moveNodeIteratorsToNewDocument(Node& node, Document& newDocument)
3585 HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3586 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3587 for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3588 if ((*it)->root() == node) {
3589 detachNodeIterator(*it);
3590 newDocument.attachNodeIterator(*it);
3595 void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
3597 if (!m_ranges.isEmpty()) {
3598 HashSet<Range*>::const_iterator end = m_ranges.end();
3599 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3600 (*it)->nodeChildrenChanged(container);
3604 void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
3606 NoEventDispatchAssertion assertNoEventDispatch;
3607 if (!m_ranges.isEmpty()) {
3608 HashSet<Range*>::const_iterator end = m_ranges.end();
3609 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3610 (*it)->nodeChildrenWillBeRemoved(container);
3613 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3614 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
3615 for (Node* n = container.firstChild(); n; n = n->nextSibling())
3616 (*it)->nodeWillBeRemoved(*n);
3619 if (LocalFrame* frame = this->frame()) {
3620 for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
3621 frame->eventHandler().nodeWillBeRemoved(*n);
3622 frame->selection().nodeWillBeRemoved(*n);
3623 frame->page()->dragCaretController().nodeWillBeRemoved(*n);
3628 void Document::nodeWillBeRemoved(Node& n)
3630 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3631 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3632 (*it)->nodeWillBeRemoved(n);
3634 if (!m_ranges.isEmpty()) {
3635 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
3636 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3637 (*it)->nodeWillBeRemoved(n);
3640 if (LocalFrame* frame = this->frame()) {
3641 frame->eventHandler().nodeWillBeRemoved(n);
3642 frame->selection().nodeWillBeRemoved(n);
3643 frame->page()->dragCaretController().nodeWillBeRemoved(n);
3647 void Document::didInsertText(Node* text, unsigned offset, unsigned length)
3649 if (!m_ranges.isEmpty()) {
3650 HashSet<Range*>::const_iterator end = m_ranges.end();
3651 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3652 (*it)->didInsertText(text, offset, length);
3655 // Update the markers for spelling and grammar checking.
3656 m_markers->shiftMarkers(text, offset, length);
3659 void Document::didRemoveText(Node* text, unsigned offset, unsigned length)
3661 if (!m_ranges.isEmpty()) {
3662 HashSet<Range*>::const_iterator end = m_ranges.end();
3663 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3664 (*it)->didRemoveText(text, offset, length);
3667 // Update the markers for spelling and grammar checking.
3668 m_markers->removeMarkers(text, offset, length);
3669 m_markers->shiftMarkers(text, offset + length, 0 - length);
3672 void Document::didMergeTextNodes(Text& oldNode, unsigned offset)
3674 if (!m_ranges.isEmpty()) {
3675 NodeWithIndex oldNodeWithIndex(oldNode);
3676 HashSet<Range*>::const_iterator end = m_ranges.end();
3677 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3678 (*it)->didMergeTextNodes(oldNodeWithIndex, offset);
3682 m_frame->selection().didMergeTextNodes(oldNode, offset);
3684 // FIXME: This should update markers for spelling and grammar checking.
3687 void Document::didSplitTextNode(Text& oldNode)
3689 if (!m_ranges.isEmpty()) {
3690 HashSet<Range*>::const_iterator end = m_ranges.end();
3691 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3692 (*it)->didSplitTextNode(oldNode);
3696 m_frame->selection().didSplitTextNode(oldNode);
3698 // FIXME: This should update markers for spelling and grammar checking.
3701 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3703 DOMWindow* domWindow = this->domWindow();
3706 domWindow->setAttributeEventListener(eventType, listener);
3709 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3711 DOMWindow* domWindow = this->domWindow();
3714 return domWindow->getAttributeEventListener(eventType);
3717 EventQueue* Document::eventQueue() const
3721 return m_domWindow->eventQueue();
3724 void Document::enqueueAnimationFrameEvent(PassRefPtr<Event> event)
3726 ensureScriptedAnimationController().enqueueEvent(event);
3729 void Document::enqueueScrollEventForNode(Node* target)
3731 // Per the W3C CSSOM View Module only scroll events fired at the document should bubble.
3732 RefPtr<Event> scrollEvent = target->isDocumentNode() ? Event::createBubble(EventTypeNames::scroll) : Event::create(EventTypeNames::scroll);
3733 scrollEvent->setTarget(target);
3734 ensureScriptedAnimationController().enqueuePerFrameEvent(scrollEvent.release());
3737 void Document::enqueueResizeEvent()
3739 RefPtr<Event> event = Event::create(EventTypeNames::resize);
3740 event->setTarget(domWindow());
3741 ensureScriptedAnimationController().enqueuePerFrameEvent(event.release());
3744 PassRefPtrWillBeRawPtr<Event> Document::createEvent(const String& eventType, ExceptionState& exceptionState)
3746 RefPtrWillBeRawPtr<Event> event = EventFactory::create(eventType);
3748 return event.release();
3750 exceptionState.throwDOMException(NotSupportedError, "The provided event type ('" + eventType + "') is invalid.");
3754 PassRefPtrWillBeRawPtr<Event> Document::createEvent(ExceptionState& exceptionState)
3756 if (!isSVGDocument()) {
3757 exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(1, 0));
3761 UseCounter::count(this, UseCounter::DocumentCreateEventOptionalArgument);
3762 // Legacy SVGDocument behavior.
3763 return createEvent("undefined", exceptionState);
3766 void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
3768 if (ContextFeatures::mutationEventsEnabled(this))
3769 addListenerType(listenerType);
3772 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
3774 if (eventType == EventTypeNames::DOMSubtreeModified) {
3775 UseCounter::count(*this, UseCounter::DOMSubtreeModifiedEvent);
3776 addMutationEventListenerTypeIfEnabled(DOMSUBTREEMODIFIED_LISTENER);
3777 } else if (eventType == EventTypeNames::DOMNodeInserted) {
3778 UseCounter::count(*this, UseCounter::DOMNodeInsertedEvent);
3779 addMutationEventListenerTypeIfEnabled(DOMNODEINSERTED_LISTENER);
3780 } else if (eventType == EventTypeNames::DOMNodeRemoved) {
3781 UseCounter::count(*this, UseCounter::DOMNodeRemovedEvent);
3782 addMutationEventListenerTypeIfEnabled(DOMNODEREMOVED_LISTENER);
3783 } else if (eventType == EventTypeNames::DOMNodeRemovedFromDocument) {
3784 UseCounter::count(*this, UseCounter::DOMNodeRemovedFromDocumentEvent);
3785 addMutationEventListenerTypeIfEnabled(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
3786 } else if (eventType == EventTypeNames::DOMNodeInsertedIntoDocument) {
3787 UseCounter::count(*this, UseCounter::DOMNodeInsertedIntoDocumentEvent);
3788 addMutationEventListenerTypeIfEnabled(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
3789 } else if (eventType == EventTypeNames::DOMCharacterDataModified) {
3790 UseCounter::count(*this, UseCounter::DOMCharacterDataModifiedEvent);
3791 addMutationEventListenerTypeIfEnabled(DOMCHARACTERDATAMODIFIED_LISTENER);
3792 } else if (eventType == EventTypeNames::overflowchanged) {
3793 UseCounter::count(*this, UseCounter::OverflowChangedEvent);
3794 addListenerType(OVERFLOWCHANGED_LISTENER);
3795 } else if (eventType == EventTypeNames::webkitAnimationStart || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationstart)) {
3796 addListenerType(ANIMATIONSTART_LISTENER);
3797 } else if (eventType == EventTypeNames::webkitAnimationEnd || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationend)) {
3798 addListenerType(ANIMATIONEND_LISTENER);
3799 } else if (eventType == EventTypeNames::webkitAnimationIteration || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationiteration)) {
3800 addListenerType(ANIMATIONITERATION_LISTENER);
3801 } else if (eventType == EventTypeNames::webkitTransitionEnd || eventType == EventTypeNames::transitionend) {
3802 addListenerType(TRANSITIONEND_LISTENER);
3803 } else if (eventType == EventTypeNames::scroll) {
3804 addListenerType(SCROLL_LISTENER);
3805 } else if (eventType == EventTypeNames::DOMFocusIn || eventType == EventTypeNames::DOMFocusOut) {
3806 UseCounter::count(*this, UseCounter::DOMFocusInOutEvent);
3810 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
3815 HTMLFrameOwnerElement* Document::ownerElement() const
3819 return frame()->ownerElement();
3822 String Document::cookie(ExceptionState& exceptionState) const
3824 if (settings() && !settings()->cookieEnabled())
3827 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3828 // InvalidStateError exception on getting if the Document has no
3829 // browsing context.
3831 if (!securityOrigin()->canAccessCookies()) {
3832 if (isSandboxed(SandboxOrigin))
3833 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
3834 else if (url().protocolIs("data"))
3835 exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
3837 exceptionState.throwSecurityError("Access is denied for this document.");
3841 KURL cookieURL = this->cookieURL();
3842 if (cookieURL.isEmpty())
3845 return cookies(this, cookieURL);
3848 void Document::setCookie(const String& value, ExceptionState& exceptionState)
3850 if (settings() && !settings()->cookieEnabled())
3853 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3854 // InvalidStateError exception on setting if the Document has no
3855 // browsing context.
3857 if (!securityOrigin()->canAccessCookies()) {
3858 if (isSandboxed(SandboxOrigin))
3859 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
3860 else if (url().protocolIs("data"))
3861 exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
3863 exceptionState.throwSecurityError("Access is denied for this document.");
3867 KURL cookieURL = this->cookieURL();
3868 if (cookieURL.isEmpty())
3871 setCookies(this, cookieURL, value);
3874 const AtomicString& Document::referrer() const
3877 return loader()->request().httpReferrer();
3881 String Document::domain() const
3883 return securityOrigin()->domain();
3886 void Document::setDomain(const String& newDomain, ExceptionState& exceptionState)
3888 if (isSandboxed(SandboxDocumentDomain)) {
3889 exceptionState.throwSecurityError("Assignment is forbidden for sandboxed iframes.");
3893 if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
3894 exceptionState.throwSecurityError("Assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme.");
3898 if (newDomain.isEmpty()) {
3899 exceptionState.throwSecurityError("'" + newDomain + "' is an empty domain.");
3903 OriginAccessEntry::IPAddressSetting ipAddressSetting = settings() && settings()->treatIPAddressAsDomain() ? OriginAccessEntry::TreatIPAddressAsDomain : OriginAccessEntry::TreatIPAddressAsIPAddress;
3904 OriginAccessEntry accessEntry(securityOrigin()->protocol(), newDomain, OriginAccessEntry::AllowSubdomains, ipAddressSetting);
3905 OriginAccessEntry::MatchResult result = accessEntry.matchesOrigin(*securityOrigin());
3906 if (result == OriginAccessEntry::DoesNotMatchOrigin) {
3907 exceptionState.throwSecurityError("'" + newDomain + "' is not a suffix of '" + domain() + "'.");
3911 if (result == OriginAccessEntry::MatchesOriginButIsPublicSuffix) {
3912 exceptionState.throwSecurityError("'" + newDomain + "' is a top-level domain.");
3916 securityOrigin()->setDomainFromDOM(newDomain);
3918 m_frame->script().updateSecurityOrigin(securityOrigin());
3921 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
3922 String Document::lastModified() const
3924 DateComponents date;
3925 bool foundDate = false;
3927 if (DocumentLoader* documentLoader = loader()) {
3928 const AtomicString& httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
3929 if (!httpLastModified.isEmpty()) {
3930 date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
3935 // FIXME: If this document came from the file system, the HTML5
3936 // specificiation tells us to read the last modification date from the file
3939 date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
3940 return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
3943 const KURL& Document::firstPartyForCookies() const
3945 return topDocument().url();
3948 static bool isValidNameNonASCII(const LChar* characters, unsigned length)
3950 if (!isValidNameStart(characters[0]))
3953 for (unsigned i = 1; i < length; ++i) {
3954 if (!isValidNamePart(characters[i]))
3961 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
3966 U16_NEXT(characters, i, length, c)
3967 if (!isValidNameStart(c))
3970 while (i < length) {
3971 U16_NEXT(characters, i, length, c)
3972 if (!isValidNamePart(c))
3979 template<typename CharType>
3980 static inline bool isValidNameASCII(const CharType* characters, unsigned length)
3982 CharType c = characters[0];
3983 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
3986 for (unsigned i = 1; i < length; ++i) {
3988 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
3995 bool Document::isValidName(const String& name)
3997 unsigned length = name.length();
4001 if (name.is8Bit()) {
4002 const LChar* characters = name.characters8();
4004 if (isValidNameASCII(characters, length))
4007 return isValidNameNonASCII(characters, length);
4010 const UChar* characters = name.characters16();
4012 if (isValidNameASCII(characters, length))
4015 return isValidNameNonASCII(characters, length);
4018 template<typename CharType>
4019 static bool parseQualifiedNameInternal(const AtomicString& qualifiedName, const CharType* characters, unsigned length, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
4021 bool nameStart = true;
4022 bool sawColon = false;
4025 for (unsigned i = 0; i < length;) {
4027 U16_NEXT(characters, i, length, c)
4030 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') contains multiple colons.");
4031 return false; // multiple colons: not allowed
4036 } else if (nameStart) {
4037 if (!isValidNameStart(c)) {
4038 StringBuilder message;
4039 message.appendLiteral("The qualified name provided ('");
4040 message.append(qualifiedName);
4041 message.appendLiteral("') contains the invalid name-start character '");
4043 message.appendLiteral("'.");
4044 exceptionState.throwDOMException(InvalidCharacterError, message.toString());
4049 if (!isValidNamePart(c)) {
4050 StringBuilder message;
4051 message.appendLiteral("The qualified name provided ('");
4052 message.append(qualifiedName);
4053 message.appendLiteral("') contains the invalid character '");
4055 message.appendLiteral("'.");
4056 exceptionState.throwDOMException(InvalidCharacterError, message.toString());
4064 localName = qualifiedName;
4066 prefix = AtomicString(characters, colonPos);
4067 if (prefix.isEmpty()) {
4068 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty namespace prefix.");
4071 int prefixStart = colonPos + 1;
4072 localName = AtomicString(characters + prefixStart, length - prefixStart);
4075 if (localName.isEmpty()) {
4076 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty local name.");
4083 bool Document::parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
4085 unsigned length = qualifiedName.length();
4088 exceptionState.throwDOMException(InvalidCharacterError, "The qualified name provided is empty.");
4092 if (qualifiedName.is8Bit())
4093 return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName, exceptionState);
4094 return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName, exceptionState);
4097 void Document::setEncodingData(const DocumentEncodingData& newData)
4099 // It's possible for the encoding of the document to change while we're decoding
4100 // data. That can only occur while we're processing the <head> portion of the
4101 // document. There isn't much user-visible content in the <head>, but there is
4102 // the <title> element. This function detects that situation and re-decodes the
4103 // document's title so that the user doesn't see an incorrectly decoded title
4104 // in the title bar.
4106 && encoding() != newData.encoding()
4107 && !ElementTraversal::firstWithin(*m_titleElement)
4108 && encoding() == Latin1Encoding()
4109 && m_titleElement->textContent().containsOnlyLatin1()) {
4111 CString originalBytes = m_titleElement->textContent().latin1();
4112 OwnPtr<TextCodec> codec = newTextCodec(newData.encoding());
4113 String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), DataEOF);
4114 m_titleElement->setTextContent(correctlyDecodedTitle);
4117 m_encodingData = newData;
4119 // FIXME: Should be removed as part of https://code.google.com/p/chromium/issues/detail?id=319643
4120 bool shouldUseVisualOrdering = m_encodingData.encoding().usesVisualOrdering();
4121 if (shouldUseVisualOrdering != m_visuallyOrdered) {
4122 m_visuallyOrdered = shouldUseVisualOrdering;
4123 // FIXME: How is possible to not have a renderer here?
4125 renderView()->style()->setRTLOrdering(m_visuallyOrdered ? VisualOrder : LogicalOrder);
4126 setNeedsStyleRecalc(SubtreeStyleChange);
4130 KURL Document::completeURL(const String& url) const
4132 return completeURLWithOverride(url, m_baseURL);
4135 KURL Document::completeURLWithOverride(const String& url, const KURL& baseURLOverride) const
4137 // Always return a null URL when passed a null string.
4138 // FIXME: Should we change the KURL constructor to have this behavior?
4139 // See also [CSS]StyleSheet::completeURL(const String&)
4142 // This logic is deliberately spread over many statements in an attempt to track down http://crbug.com/312410.
4143 const KURL* baseURLFromParent = 0;
4144 bool shouldUseParentBaseURL = baseURLOverride.isEmpty();
4145 if (!shouldUseParentBaseURL) {
4146 const KURL& aboutBlankURL = blankURL();
4147 shouldUseParentBaseURL = (baseURLOverride == aboutBlankURL);
4149 if (shouldUseParentBaseURL) {
4150 if (Document* parent = parentDocument())
4151 baseURLFromParent = &parent->baseURL();
4153 const KURL& baseURL = baseURLFromParent ? *baseURLFromParent : baseURLOverride;
4154 if (!encoding().isValid())
4155 return KURL(baseURL, url);
4156 return KURL(baseURL, url, encoding());
4159 // Support for Javascript execCommand, and related methods
4161 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
4163 LocalFrame* frame = document->frame();
4164 if (!frame || frame->document() != document)
4165 return Editor::Command();
4167 document->updateRenderTreeIfNeeded();
4168 return frame->editor().command(commandName, userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
4171 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
4173 // We don't allow recusrive |execCommand()| to protect against attack code.
4174 // Recursive call of |execCommand()| could be happened by moving iframe
4175 // with script triggered by insertion, e.g. <iframe src="javascript:...">
4176 // <iframe onload="...">. This usage is valid as of the specification
4177 // although, it isn't common use case, rather it is used as attack code.
4178 static bool inExecCommand = false;
4179 if (inExecCommand) {
4180 String message = "We don't execute document.execCommand() this time, because it is called recursively.";
4181 addConsoleMessage(JSMessageSource, WarningMessageLevel, message);
4184 TemporaryChange<bool> executeScope(inExecCommand, true);
4186 // Postpone DOM mutation events, which can execute scripts and change
4187 // DOM tree against implementation assumption.
4188 EventQueueScope eventQueueScope;
4189 return command(this, commandName, userInterface).execute(value);
4192 bool Document::queryCommandEnabled(const String& commandName)
4194 return command(this, commandName).isEnabled();
4197 bool Document::queryCommandIndeterm(const String& commandName)
4199 return command(this, commandName).state() == MixedTriState;
4202 bool Document::queryCommandState(const String& commandName)
4204 return command(this, commandName).state() == TrueTriState;
4207 bool Document::queryCommandSupported(const String& commandName)
4209 return command(this, commandName).isSupported();
4212 String Document::queryCommandValue(const String& commandName)
4214 return command(this, commandName).value();
4217 KURL Document::openSearchDescriptionURL()
4219 static const char openSearchMIMEType[] = "application/opensearchdescription+xml";
4220 static const char openSearchRelation[] = "search";
4222 // FIXME: Why do only top-level frames have openSearchDescriptionURLs?
4223 if (!frame() || frame()->tree().parent())
4226 // FIXME: Why do we need to wait for FrameStateComplete?
4227 if (frame()->loader().state() != FrameStateComplete)
4233 for (HTMLLinkElement* linkElement = Traversal<HTMLLinkElement>::firstChild(*head()); linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4234 if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
4236 if (linkElement->href().isEmpty())
4238 return linkElement->href();
4244 void Document::pushCurrentScript(PassRefPtr<HTMLScriptElement> newCurrentScript)
4246 ASSERT(newCurrentScript);
4247 m_currentScriptStack.append(newCurrentScript);
4250 void Document::popCurrentScript()
4252 ASSERT(!m_currentScriptStack.isEmpty());
4253 m_currentScriptStack.removeLast();
4256 void Document::applyXSLTransform(ProcessingInstruction* pi)
4258 ASSERT(!pi->isLoading());
4259 UseCounter::count(*this, UseCounter::XSLProcessingInstruction);
4260 RefPtrWillBeRawPtr<XSLTProcessor> processor = XSLTProcessor::create();
4261 processor->setXSLStyleSheet(toXSLStyleSheet(pi->sheet()));
4262 String resultMIMEType;
4264 String resultEncoding;
4265 if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
4267 // FIXME: If the transform failed we should probably report an error (like Mozilla does).
4268 LocalFrame* ownerFrame = frame();
4269 processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, ownerFrame);
4270 InspectorInstrumentation::frameDocumentUpdated(ownerFrame);
4273 void Document::setTransformSource(PassOwnPtr<TransformSource> source)
4275 m_transformSource = source;
4278 void Document::setDesignMode(InheritedBool value)
4280 m_designMode = value;
4281 for (LocalFrame* frame = m_frame; frame && frame->document(); frame = frame->tree().traverseNext(m_frame))
4282 frame->document()->setNeedsStyleRecalc(SubtreeStyleChange);
4285 Document::InheritedBool Document::getDesignMode() const
4287 return m_designMode;
4290 bool Document::inDesignMode() const
4292 for (const Document* d = this; d; d = d->parentDocument()) {
4293 if (d->m_designMode != inherit)
4294 return d->m_designMode;
4299 Document* Document::parentDocument() const
4303 LocalFrame* parent = m_frame->tree().parent();
4306 return parent->document();
4309 Document& Document::topDocument() const
4311 Document* doc = const_cast<Document*>(this);
4313 while ((element = doc->ownerElement()))
4314 doc = &element->document();
4320 WeakPtr<Document> Document::contextDocument()
4322 if (m_contextDocument)
4323 return m_contextDocument;
4325 return m_weakFactory.createWeakPtr();
4326 return WeakPtr<Document>(nullptr);
4329 PassRefPtr<Attr> Document::createAttribute(const AtomicString& name, ExceptionState& exceptionState)
4331 return createAttributeNS(nullAtom, name, exceptionState, true);
4334 PassRefPtr<Attr> Document::createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState, bool shouldIgnoreNamespaceChecks)
4336 AtomicString prefix, localName;
4337 if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
4340 QualifiedName qName(prefix, localName, namespaceURI);
4342 if (!shouldIgnoreNamespaceChecks && !hasValidNamespaceForAttributes(qName)) {
4343 exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
4347 return Attr::create(*this, qName, emptyAtom);
4350 const SVGDocumentExtensions* Document::svgExtensions()
4352 return m_svgExtensions.get();
4355 SVGDocumentExtensions& Document::accessSVGExtensions()
4357 if (!m_svgExtensions)
4358 m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this));
4359 return *m_svgExtensions;
4362 bool Document::hasSVGRootNode() const
4364 return isSVGSVGElement(documentElement());
4367 PassRefPtr<HTMLCollection> Document::ensureCachedCollection(CollectionType type)
4369 return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(*this, type);
4372 PassRefPtr<HTMLCollection> Document::images()
4374 return ensureCachedCollection(DocImages);
4377 PassRefPtr<HTMLCollection> Document::applets()
4379 return ensureCachedCollection(DocApplets);
4382 PassRefPtr<HTMLCollection> Document::embeds()
4384 return ensureCachedCollection(DocEmbeds);
4387 PassRefPtr<HTMLCollection> Document::scripts()
4389 return ensureCachedCollection(DocScripts);
4392 PassRefPtr<HTMLCollection> Document::links()
4394 return ensureCachedCollection(DocLinks);
4397 PassRefPtr<HTMLCollection> Document::forms()
4399 return ensureCachedCollection(DocForms);
4402 PassRefPtr<HTMLCollection> Document::anchors()
4404 return ensureCachedCollection(DocAnchors);
4407 PassRefPtr<HTMLCollection> Document::allForBinding()
4409 UseCounter::count(*this, UseCounter::DocumentAll);
4413 PassRefPtr<HTMLCollection> Document::all()
4415 return ensureRareData().ensureNodeLists().addCache<HTMLAllCollection>(*this, DocAll);
4418 PassRefPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
4420 return ensureRareData().ensureNodeLists().addCache<HTMLNameCollection>(*this, WindowNamedItems, name);
4423 PassRefPtr<HTMLCollection> Document::documentNamedItems(const AtomicString& name)
4425 return ensureRareData().ensureNodeLists().addCache<HTMLNameCollection>(*this, DocumentNamedItems, name);
4428 void Document::finishedParsing()
4430 ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
4431 ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
4433 if (!m_documentTiming.domContentLoadedEventStart)
4434 m_documentTiming.domContentLoadedEventStart = monotonicallyIncreasingTime();
4435 dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
4436 if (!m_documentTiming.domContentLoadedEventEnd)
4437 m_documentTiming.domContentLoadedEventEnd = monotonicallyIncreasingTime();
4439 if (frame() && frame()->isMainFrame()) {
4440 // Reset the text autosizing multipliers on main frame when DOM is loaded.
4441 // This is to allow for a fresh text autosizing pass when the page layout
4442 // changes significantly in the end.
4443 if (TextAutosizer* textAutosizer = this->textAutosizer())
4444 textAutosizer->recalculateMultipliers();
4447 // The loader's finishedParsing() method may invoke script that causes this object to
4448 // be dereferenced (when this document is in an iframe and the onload causes the iframe's src to change).
4449 // Keep it alive until we are done.
4450 RefPtr<Document> protect(this);
4452 if (RefPtr<LocalFrame> f = frame()) {
4453 // FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
4454 // resource loads are complete. HTMLObjectElements can start loading their resources from
4455 // post attach callbacks triggered by recalcStyle(). This means if we parse out an <object>
4456 // tag and then reach the end of the document without updating styles, we might not have yet
4457 // started the resource load and might fire the window load event too early. To avoid this
4458 // we force the styles to be up to date before calling FrameLoader::finishedParsing().
4459 // See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
4460 updateRenderTreeIfNeeded();
4462 f->loader().finishedParsing();
4464 InspectorInstrumentation::domContentLoadedEventFired(f.get());
4467 // Schedule dropping of the ElementDataCache. We keep it alive for a while after parsing finishes
4468 // so that dynamically inserted content can also benefit from sharing optimizations.
4469 // Note that we don't refresh the timer on cache access since that could lead to huge caches being kept
4470 // alive indefinitely by something innocuous like JS setting .innerHTML repeatedly on a timer.
4471 m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
4473 // Parser should have picked up all preloads by now
4474 m_fetcher->clearPreloads();
4477 m_import->didFinishParsing();
4480 void Document::elementDataCacheClearTimerFired(Timer<Document>*)
4482 m_elementDataCache.clear();
4485 Vector<IconURL> Document::iconURLs(int iconTypesMask)
4487 IconURL firstFavicon;
4488 IconURL firstTouchIcon;
4489 IconURL firstTouchPrecomposedIcon;
4490 Vector<IconURL> secondaryIcons;
4492 // Start from the last child node so that icons seen later take precedence as required by the spec.
4493 for (HTMLLinkElement* linkElement = head() ? Traversal<HTMLLinkElement>::firstChild(*head()) : 0; linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4494 if (!(linkElement->iconType() & iconTypesMask))
4496 if (linkElement->href().isEmpty())
4498 if (!RuntimeEnabledFeatures::touchIconLoadingEnabled() && linkElement->iconType() != Favicon)
4501 IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
4502 if (linkElement->iconType() == Favicon) {
4503 if (firstFavicon.m_iconType != InvalidIcon)
4504 secondaryIcons.append(firstFavicon);
4505 firstFavicon = newURL;
4506 } else if (linkElement->iconType() == TouchIcon) {
4507 if (firstTouchIcon.m_iconType != InvalidIcon)
4508 secondaryIcons.append(firstTouchIcon);
4509 firstTouchIcon = newURL;
4510 } else if (linkElement->iconType() == TouchPrecomposedIcon) {
4511 if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4512 secondaryIcons.append(firstTouchPrecomposedIcon);
4513 firstTouchPrecomposedIcon = newURL;
4515 ASSERT_NOT_REACHED();
4519 Vector<IconURL> iconURLs;
4520 if (firstFavicon.m_iconType != InvalidIcon)
4521 iconURLs.append(firstFavicon);
4522 else if (m_url.protocolIsInHTTPFamily() && iconTypesMask & Favicon)
4523 iconURLs.append(IconURL::defaultFavicon(m_url));
4525 if (firstTouchIcon.m_iconType != InvalidIcon)
4526 iconURLs.append(firstTouchIcon);
4527 if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4528 iconURLs.append(firstTouchPrecomposedIcon);
4529 for (int i = secondaryIcons.size() - 1; i >= 0; --i)
4530 iconURLs.append(secondaryIcons[i]);
4534 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
4536 if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
4539 m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
4540 m_frame->selection().updateSecureKeyboardEntryIfActive();
4543 bool Document::useSecureKeyboardEntryWhenActive() const
4545 return m_useSecureKeyboardEntryWhenActive;
4548 void Document::initSecurityContext()
4550 initSecurityContext(DocumentInit(m_url, m_frame, contextDocument(), m_import));
4553 static PassRefPtr<ContentSecurityPolicy> contentSecurityPolicyFor(Document* document)
4555 if (document->import() && document->import()->isChild())
4556 return document->import()->master()->contentSecurityPolicy();
4557 return ContentSecurityPolicy::create(document);
4560 void Document::initSecurityContext(const DocumentInit& initializer)
4562 if (haveInitializedSecurityOrigin()) {
4563 ASSERT(securityOrigin());
4567 if (!initializer.hasSecurityContext()) {
4568 // No source for a security context.
4569 // This can occur via document.implementation.createDocument().
4570 m_cookieURL = KURL(ParsedURLString, emptyString());
4571 setSecurityOrigin(SecurityOrigin::createUnique());
4572 setContentSecurityPolicy(ContentSecurityPolicy::create(this));
4576 // In the common case, create the security context from the currently
4577 // loading URL with a fresh content security policy.
4578 m_cookieURL = m_url;
4579 enforceSandboxFlags(initializer.sandboxFlags());
4580 setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
4581 setContentSecurityPolicy(contentSecurityPolicyFor(this));
4583 if (Settings* settings = initializer.settings()) {
4584 if (!settings->webSecurityEnabled()) {
4585 // Web security is turned off. We should let this document access every other document. This is used primary by testing
4586 // harnesses for web sites.
4587 securityOrigin()->grantUniversalAccess();
4588 } else if (securityOrigin()->isLocal()) {
4589 if (settings->allowUniversalAccessFromFileURLs()) {
4590 // Some clients want local URLs to have universal access, but that setting is dangerous for other clients.
4591 securityOrigin()->grantUniversalAccess();
4592 } else if (!settings->allowFileAccessFromFileURLs()) {
4593 // Some clients want local URLs to have even tighter restrictions by default, and not be able to access other local files.
4594 // FIXME 81578: The naming of this is confusing. Files with restricted access to other local files
4595 // still can have other privileges that can be remembered, thereby not making them unique origins.
4596 securityOrigin()->enforceFilePathSeparation();
4601 if (initializer.shouldTreatURLAsSrcdocDocument()) {
4602 m_isSrcdocDocument = true;
4603 setBaseURLOverride(initializer.parentBaseURL());
4606 if (!shouldInheritSecurityOriginFromOwner(m_url))
4609 // If we do not obtain a meaningful origin from the URL, then we try to
4610 // find one via the frame hierarchy.
4612 if (!initializer.owner()) {
4613 didFailToInitializeSecurityOrigin();
4617 if (isSandboxed(SandboxOrigin)) {
4618 // If we're supposed to inherit our security origin from our owner,
4619 // but we're also sandboxed, the only thing we inherit is the ability
4620 // to load local resources. This lets about:blank iframes in file://
4621 // URL documents load images and other resources from the file system.
4622 if (initializer.owner()->securityOrigin()->canLoadLocalResources())
4623 securityOrigin()->grantLoadLocalResources();
4627 m_cookieURL = initializer.owner()->cookieURL();
4628 // We alias the SecurityOrigins to match Firefox, see Bug 15313
4629 // https://bugs.webkit.org/show_bug.cgi?id=15313
4630 setSecurityOrigin(initializer.owner()->securityOrigin());
4633 void Document::initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders& headers)
4635 if (m_frame && m_frame->tree().parent() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
4636 contentSecurityPolicy()->copyStateFrom(m_frame->tree().parent()->document()->contentSecurityPolicy());
4637 contentSecurityPolicy()->didReceiveHeaders(headers);
4640 bool Document::allowInlineEventHandlers(Node* node, EventListener* listener, const String& contextURL, const WTF::OrdinalNumber& contextLine)
4642 if (!contentSecurityPolicy()->allowInlineEventHandlers(contextURL, contextLine))
4645 // HTML says that inline script needs browsing context to create its execution environment.
4646 // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#event-handler-attributes
4647 // Also, if the listening node came from other document, which happens on context-less event dispatching,
4648 // we also need to ask the owner document of the node.
4649 LocalFrame* frame = executingFrame();
4652 if (!frame->script().canExecuteScripts(NotAboutToExecuteScript))
4654 if (node && node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
4660 bool Document::allowExecutingScripts(Node* node)
4662 // FIXME: Eventually we'd like to evaluate scripts which are inserted into a
4663 // viewless document but this'll do for now.
4664 // See http://bugs.webkit.org/show_bug.cgi?id=5727
4665 LocalFrame* frame = executingFrame();
4668 if (!node->document().executingFrame())
4670 if (!frame->script().canExecuteScripts(AboutToExecuteScript))
4675 void Document::updateSecurityOrigin(PassRefPtr<SecurityOrigin> origin)
4677 setSecurityOrigin(origin);
4678 didUpdateSecurityOrigin();
4681 void Document::didUpdateSecurityOrigin()
4685 m_frame->script().updateSecurityOrigin(securityOrigin());
4688 bool Document::isContextThread() const
4690 return isMainThread();
4693 void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
4695 m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
4696 if (!m_updateFocusAppearanceTimer.isActive())
4697 m_updateFocusAppearanceTimer.startOneShot(0, FROM_HERE);
4700 void Document::cancelFocusAppearanceUpdate()
4702 m_updateFocusAppearanceTimer.stop();
4705 void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
4707 Element* element = focusedElement();
4711 if (element->isFocusable())
4712 element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
4715 void Document::attachRange(Range* range)
4717 ASSERT(!m_ranges.contains(range));
4718 m_ranges.add(range);
4721 void Document::detachRange(Range* range)
4723 // We don't ASSERT m_ranges.contains(range) to allow us to call this
4724 // unconditionally to fix: https://bugs.webkit.org/show_bug.cgi?id=26044
4725 m_ranges.remove(range);
4728 void Document::getCSSCanvasContext(const String& type, const String& name, int width, int height, bool& is2d, RefPtr<CanvasRenderingContext2D>& context2d, bool& is3d, RefPtr<WebGLRenderingContext>& context3d)
4730 HTMLCanvasElement& element = getCSSCanvasElement(name);
4731 element.setSize(IntSize(width, height));
4732 CanvasRenderingContext* context = element.getContext(type);
4736 if (context->is2d()) {
4738 context2d = toCanvasRenderingContext2D(context);
4739 } else if (context->is3d()) {
4741 context3d = toWebGLRenderingContext(context);
4745 HTMLCanvasElement& Document::getCSSCanvasElement(const String& name)
4747 RefPtr<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, nullptr).storedValue->value;
4749 element = HTMLCanvasElement::create(*this);
4750 element->setAccelerationDisabled(true);
4755 void Document::initDNSPrefetch()
4757 Settings* settings = this->settings();
4759 m_haveExplicitlyDisabledDNSPrefetch = false;
4760 m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
4762 // Inherit DNS prefetch opt-out from parent frame
4763 if (Document* parent = parentDocument()) {
4764 if (!parent->isDNSPrefetchEnabled())
4765 m_isDNSPrefetchEnabled = false;
4769 void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
4771 if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
4772 m_isDNSPrefetchEnabled = true;
4776 m_isDNSPrefetchEnabled = false;
4777 m_haveExplicitlyDisabledDNSPrefetch = true;
4780 void Document::reportBlockedScriptExecutionToInspector(const String& directiveText)
4782 InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText);
4785 void Document::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* state)
4787 internalAddMessage(source, level, message, sourceURL, lineNumber, nullptr, state);
4790 void Document::internalAddMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state)
4792 if (!isContextThread()) {
4793 m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
4796 FrameHost* host = frameHost();
4800 String messageURL = sourceURL;
4801 if (!state && sourceURL.isNull() && !lineNumber) {
4802 messageURL = url().string();
4803 if (parsing() && !isInDocumentWrite() && scriptableDocumentParser()) {
4804 ScriptableDocumentParser* parser = scriptableDocumentParser();
4805 if (!parser->isWaitingForScripts() && !parser->isExecutingScript())
4806 lineNumber = parser->lineNumber().oneBasedInt();
4809 host->console().addMessage(source, level, message, messageURL, lineNumber, 0, callStack, state, 0);
4812 void Document::addConsoleMessageWithRequestIdentifier(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
4814 if (!isContextThread()) {
4815 m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
4819 if (FrameHost* host = frameHost())
4820 host->console().addMessage(source, level, message, String(), 0, 0, nullptr, 0, requestIdentifier);
4823 // FIXME(crbug.com/305497): This should be removed after ExecutionContext-DOMWindow migration.
4824 void Document::postTask(PassOwnPtr<ExecutionContextTask> task)
4826 m_taskRunner->postTask(task);
4829 void Document::tasksWereSuspended()
4831 scriptRunner()->suspend();
4834 m_parser->suspendScheduledTasks();
4835 if (m_scriptedAnimationController)
4836 m_scriptedAnimationController->suspend();
4839 void Document::tasksWereResumed()
4841 scriptRunner()->resume();
4844 m_parser->resumeScheduledTasks();
4845 if (m_scriptedAnimationController)
4846 m_scriptedAnimationController->resume();
4848 MutationObserver::resumeSuspendedObservers();
4851 // FIXME: suspendScheduledTasks(), resumeScheduledTasks(), tasksNeedSuspension()
4852 // should be moved to DOMWindow once it inherits ExecutionContext
4853 void Document::suspendScheduledTasks()
4855 ExecutionContext::suspendScheduledTasks();
4856 m_taskRunner->suspend();
4859 void Document::resumeScheduledTasks()
4861 ExecutionContext::resumeScheduledTasks();
4862 m_taskRunner->resume();
4865 bool Document::tasksNeedSuspension()
4867 Page* page = this->page();
4868 return page && page->defersLoading();
4871 void Document::addToTopLayer(Element* element, const Element* before)
4873 if (element->isInTopLayer())
4876 ASSERT(!m_topLayerElements.contains(element));
4877 ASSERT(!before || m_topLayerElements.contains(before));
4879 size_t beforePosition = m_topLayerElements.find(before);
4880 m_topLayerElements.insert(beforePosition, element);
4882 m_topLayerElements.append(element);
4884 element->setIsInTopLayer(true);
4887 void Document::removeFromTopLayer(Element* element)
4889 if (!element->isInTopLayer())
4891 size_t position = m_topLayerElements.find(element);
4892 ASSERT(position != kNotFound);
4893 m_topLayerElements.remove(position);
4894 element->setIsInTopLayer(false);
4897 HTMLDialogElement* Document::activeModalDialog() const
4899 if (m_topLayerElements.isEmpty())
4901 return toHTMLDialogElement(m_topLayerElements.last().get());
4904 void Document::webkitExitPointerLock()
4908 if (Element* target = page()->pointerLockController().element()) {
4909 if (target->document() != this)
4912 page()->pointerLockController().requestPointerUnlock();
4915 Element* Document::webkitPointerLockElement() const
4917 if (!page() || page()->pointerLockController().lockPending())
4919 if (Element* element = page()->pointerLockController().element()) {
4920 if (element->document() == this)
4926 void Document::decrementLoadEventDelayCount()
4928 ASSERT(m_loadEventDelayCount);
4929 --m_loadEventDelayCount;
4931 if (frame() && !m_loadEventDelayCount && !m_loadEventDelayTimer.isActive())
4932 m_loadEventDelayTimer.startOneShot(0, FROM_HERE);
4935 void Document::loadEventDelayTimerFired(Timer<Document>*)
4938 frame()->loader().checkCompleted();
4941 void Document::loadPluginsSoon()
4943 // FIXME: Remove this timer once we don't need to compute layout to load plugins.
4944 if (!m_pluginLoadingTimer.isActive())
4945 m_pluginLoadingTimer.startOneShot(0, FROM_HERE);
4948 void Document::pluginLoadingTimerFired(Timer<Document>*)
4953 ScriptedAnimationController& Document::ensureScriptedAnimationController()
4955 if (!m_scriptedAnimationController) {
4956 m_scriptedAnimationController = ScriptedAnimationController::create(this);
4957 // We need to make sure that we don't start up the animation controller on a background tab, for example.
4959 m_scriptedAnimationController->suspend();
4961 return *m_scriptedAnimationController;
4964 int Document::requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
4966 return ensureScriptedAnimationController().registerCallback(callback);
4969 void Document::cancelAnimationFrame(int id)
4971 if (!m_scriptedAnimationController)
4973 m_scriptedAnimationController->cancelCallback(id);
4976 void Document::serviceScriptedAnimations(double monotonicAnimationStartTime)
4978 if (!m_scriptedAnimationController)
4980 m_scriptedAnimationController->serviceScriptedAnimations(monotonicAnimationStartTime);
4983 PassRefPtrWillBeRawPtr<Touch> Document::createTouch(DOMWindow* window, EventTarget* target, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force) const
4985 // FIXME: It's not clear from the documentation at
4986 // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html
4987 // when this method should throw and nor is it by inspection of iOS behavior. It would be nice to verify any cases where it throws under iOS
4988 // and implement them here. See https://bugs.webkit.org/show_bug.cgi?id=47819
4989 LocalFrame* frame = window ? window->frame() : this->frame();
4990 return Touch::create(frame, target, identifier, screenX, screenY, pageX, pageY, radiusX, radiusY, rotationAngle, force);
4993 PassRefPtrWillBeRawPtr<TouchList> Document::createTouchList(WillBeHeapVector<RefPtrWillBeMember<Touch> >& touches) const
4995 return TouchList::create(touches);
4998 void Document::didAddTouchEventHandler(Node* handler)
5000 // The node should either be in this document, or be the Document node of a child
5001 // of this document.
5002 ASSERT(&handler->document() == this
5003 || (handler->isDocumentNode() && toDocument(handler)->parentDocument() == this));
5004 if (!m_touchEventTargets.get())
5005 m_touchEventTargets = adoptPtr(new TouchEventTargetSet);
5006 bool isFirstHandler = m_touchEventTargets->isEmpty();
5008 if (!m_touchEventTargets->add(handler).isNewEntry) {
5009 // Just incremented refcount, no real change.
5010 // If this is a child document node, then the count should never go above 1.
5011 ASSERT(!handler->isDocumentNode() || &handler->document() == this);
5015 if (isFirstHandler) {
5016 if (Document* parent = parentDocument()) {
5017 parent->didAddTouchEventHandler(this);
5019 // This is the first touch handler on the whole page.
5020 if (FrameHost* frameHost = this->frameHost())
5021 frameHost->chrome().client().needTouchEvents(true);
5025 // When we're all done with all frames, ensure touch hit rects are marked as dirty.
5026 if (!handler->isDocumentNode() || handler == this) {
5027 if (Page* page = this->page()) {
5028 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
5029 scrollingCoordinator->touchEventTargetRectsDidChange();
5034 void Document::didRemoveTouchEventHandler(Node* handler, bool clearAll)
5036 // Note that we can't assert that |handler| is in this document because it might be in
5037 // the process of moving out of it.
5038 ASSERT(clearAll || m_touchEventTargets->contains(handler));
5039 if (!m_touchEventTargets.get())
5043 if (!m_touchEventTargets->contains(handler))
5045 m_touchEventTargets->removeAll(handler);
5047 if (!m_touchEventTargets->remove(handler))
5048 // Just decremented refcount, no real update.
5052 if (m_touchEventTargets->isEmpty()) {
5053 if (Document* parent = parentDocument()) {
5054 // This was the last handler in this document, update the parent document too.
5055 parent->didRemoveTouchEventHandler(this, clearAll);
5057 // We just removed the last touch handler on the whole page.
5058 if (FrameHost* frameHost = this->frameHost())
5059 frameHost->chrome().client().needTouchEvents(false);
5063 // When we're all done with all frames, ensure touch hit rects are marked as dirty.
5064 if (!handler->isDocumentNode() || handler == this) {
5065 if (Page* page = this->page()) {
5066 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
5067 scrollingCoordinator->touchEventTargetRectsDidChange();
5072 void Document::resetLastHandledUserGestureTimestamp()
5074 m_lastHandledUserGestureTimestamp = currentTime();
5077 DocumentLoader* Document::loader() const
5082 DocumentLoader* loader = m_frame->loader().documentLoader();
5086 if (m_frame->document() != this)
5092 IntSize Document::initialViewportSize() const
5096 return view()->unscaledVisibleContentSize(IncludeScrollbars);
5099 Node* eventTargetNodeForDocument(Document* doc)
5103 Node* node = doc->focusedElement();
5104 if (!node && doc->isPluginDocument()) {
5105 PluginDocument* pluginDocument = toPluginDocument(doc);
5106 node = pluginDocument->pluginNode();
5108 if (!node && doc->isHTMLDocument())
5111 node = doc->documentElement();
5115 void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject& renderer)
5120 LayoutRect visibleContentRect = view()->visibleContentRect();
5121 for (size_t i = 0; i < quads.size(); ++i) {
5122 quads[i].move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
5123 adjustFloatQuadForAbsoluteZoom(quads[i], renderer);
5127 void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject& renderer)
5132 LayoutRect visibleContentRect = view()->visibleContentRect();
5133 rect.move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
5134 adjustFloatRectForAbsoluteZoom(rect, renderer);
5137 bool Document::hasActiveParser()
5139 return m_activeParserCount || (m_parser && m_parser->processingData());
5142 void Document::decrementActiveParserCount()
5144 --m_activeParserCount;
5147 // FIXME: This should always be enabled, but it seems to cause
5148 // http/tests/security/feed-urls-from-remote.html to timeout on Mac WK1
5149 // see http://webkit.org/b/110554 and http://webkit.org/b/110401
5150 loader()->checkLoadComplete();
5151 frame()->loader().checkLoadComplete();
5154 void Document::setContextFeatures(ContextFeatures& features)
5156 m_contextFeatures = PassRefPtr<ContextFeatures>(features);
5159 static RenderObject* nearestCommonHoverAncestor(RenderObject* obj1, RenderObject* obj2)
5164 for (RenderObject* currObj1 = obj1; currObj1; currObj1 = currObj1->hoverAncestor()) {
5165 for (RenderObject* currObj2 = obj2; currObj2; currObj2 = currObj2->hoverAncestor()) {
5166 if (currObj1 == currObj2)
5174 void Document::updateHoverActiveState(const HitTestRequest& request, Element* innerElement, const PlatformMouseEvent* event)
5176 ASSERT(!request.readOnly());
5178 if (request.active() && m_frame)
5179 m_frame->eventHandler().notifyElementActivated();
5181 Element* innerElementInDocument = innerElement;
5182 while (innerElementInDocument && innerElementInDocument->document() != this) {
5183 innerElementInDocument->document().updateHoverActiveState(request, innerElementInDocument, event);
5184 innerElementInDocument = innerElementInDocument->document().ownerElement();
5187 Element* oldActiveElement = activeHoverElement();
5188 if (oldActiveElement && !request.active()) {
5189 // We are clearing the :active chain because the mouse has been released.
5190 for (RenderObject* curr = oldActiveElement->renderer(); curr; curr = curr->parent()) {
5192 ASSERT(!curr->node()->isTextNode());
5193 curr->node()->setActive(false);
5194 m_userActionElements.setInActiveChain(curr->node(), false);
5197 setActiveHoverElement(nullptr);
5199 Element* newActiveElement = innerElementInDocument;
5200 if (!oldActiveElement && newActiveElement && request.active() && !request.touchMove()) {
5201 // We are setting the :active chain and freezing it. If future moves happen, they
5202 // will need to reference this chain.
5203 for (RenderObject* curr = newActiveElement->renderer(); curr; curr = curr->parent()) {
5204 if (curr->node() && !curr->isText())
5205 m_userActionElements.setInActiveChain(curr->node(), true);
5208 setActiveHoverElement(newActiveElement);
5211 // If the mouse has just been pressed, set :active on the chain. Those (and only those)
5212 // nodes should remain :active until the mouse is released.
5213 bool allowActiveChanges = !oldActiveElement && activeHoverElement();
5215 // If the mouse is down and if this is a mouse move event, we want to restrict changes in
5216 // :hover/:active to only apply to elements that are in the :active chain that we froze
5217 // at the time the mouse went down.
5218 bool mustBeInActiveChain = request.active() && request.move();
5220 RefPtr<Node> oldHoverNode = hoverNode();
5222 // Check to see if the hovered node has changed.
5223 // If it hasn't, we do not need to do anything.
5224 Node* newHoverNode = innerElementInDocument;
5225 while (newHoverNode && !newHoverNode->renderer())
5226 newHoverNode = newHoverNode->parentOrShadowHostNode();
5228 // Update our current hover node.
5229 setHoverNode(newHoverNode);
5231 // We have two different objects. Fetch their renderers.
5232 RenderObject* oldHoverObj = oldHoverNode ? oldHoverNode->renderer() : 0;
5233 RenderObject* newHoverObj = newHoverNode ? newHoverNode->renderer() : 0;
5235 // Locate the common ancestor render object for the two renderers.
5236 RenderObject* ancestor = nearestCommonHoverAncestor(oldHoverObj, newHoverObj);
5237 RefPtr<Node> ancestorNode(ancestor ? ancestor->node() : 0);
5239 Vector<RefPtr<Node>, 32> nodesToRemoveFromChain;
5240 Vector<RefPtr<Node>, 32> nodesToAddToChain;
5242 if (oldHoverObj != newHoverObj) {
5243 // If the old hovered node is not nil but it's renderer is, it was probably detached as part of the :hover style
5244 // (for instance by setting display:none in the :hover pseudo-class). In this case, the old hovered element (and its ancestors)
5245 // must be updated, to ensure it's normal style is re-applied.
5246 if (oldHoverNode && !oldHoverObj) {
5247 for (Node* node = oldHoverNode.get(); node; node = node->parentNode()) {
5248 if (!mustBeInActiveChain || (node->isElementNode() && toElement(node)->inActiveChain()))
5249 nodesToRemoveFromChain.append(node);
5254 // The old hover path only needs to be cleared up to (and not including) the common ancestor;
5255 for (RenderObject* curr = oldHoverObj; curr && curr != ancestor; curr = curr->hoverAncestor()) {
5256 if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5257 nodesToRemoveFromChain.append(curr->node());
5261 // Now set the hover state for our new object up to the root.
5262 for (RenderObject* curr = newHoverObj; curr; curr = curr->hoverAncestor()) {
5263 if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5264 nodesToAddToChain.append(curr->node());
5267 // mouseenter and mouseleave events do not bubble, so they are dispatched iff there is a capturing
5268 // event handler on an ancestor or a normal event handler on the element itself. This special
5269 // handling is necessary to avoid O(n^2) capturing event handler checks. We'll check the previously
5270 // hovered node's ancestor tree for 'mouseleave' handlers here, then check the newly hovered node's
5271 // ancestor tree for 'mouseenter' handlers after dispatching the 'mouseleave' events (as the handler
5272 // for 'mouseleave' might set a capturing 'mouseenter' handler, odd as that might be).
5273 bool ancestorHasCapturingMouseleaveListener = false;
5274 if (event && newHoverNode != oldHoverNode.get()) {
5275 for (Node* node = oldHoverNode.get(); node; node = node->parentOrShadowHostNode()) {
5276 if (node->hasCapturingEventListeners(EventTypeNames::mouseleave)) {
5277 ancestorHasCapturingMouseleaveListener = true;
5283 size_t removeCount = nodesToRemoveFromChain.size();
5284 for (size_t i = 0; i < removeCount; ++i) {
5285 nodesToRemoveFromChain[i]->setHovered(false);
5286 if (event && (ancestorHasCapturingMouseleaveListener || nodesToRemoveFromChain[i]->hasEventListeners(EventTypeNames::mouseleave)))
5287 nodesToRemoveFromChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseleave, 0, newHoverNode);
5290 bool ancestorHasCapturingMouseenterListener = false;
5291 if (event && newHoverNode != oldHoverNode.get()) {
5292 for (Node* node = newHoverNode; node; node = node->parentOrShadowHostNode()) {
5293 if (node->hasCapturingEventListeners(EventTypeNames::mouseenter)) {
5294 ancestorHasCapturingMouseenterListener = true;
5300 bool sawCommonAncestor = false;
5301 size_t addCount = nodesToAddToChain.size();
5302 for (size_t i = 0; i < addCount; ++i) {
5303 // Elements past the common ancestor do not change hover state, but might change active state.
5304 if (ancestorNode && nodesToAddToChain[i] == ancestorNode)
5305 sawCommonAncestor = true;
5306 if (allowActiveChanges)
5307 nodesToAddToChain[i]->setActive(true);
5308 if (!sawCommonAncestor) {
5309 nodesToAddToChain[i]->setHovered(true);
5310 if (event && (ancestorHasCapturingMouseenterListener || nodesToAddToChain[i]->hasEventListeners(EventTypeNames::mouseenter)))
5311 nodesToAddToChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseenter, 0, oldHoverNode.get());
5315 updateRenderTreeIfNeeded();
5318 bool Document::haveStylesheetsLoaded() const
5320 return m_styleEngine->haveStylesheetsLoaded();
5323 Locale& Document::getCachedLocale(const AtomicString& locale)
5325 AtomicString localeKey = locale;
5326 if (locale.isEmpty() || !RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
5327 return Locale::defaultLocale();
5328 LocaleIdentifierToLocaleMap::AddResult result = m_localeCache.add(localeKey, nullptr);
5329 if (result.isNewEntry)
5330 result.storedValue->value = Locale::create(localeKey);
5331 return *(result.storedValue->value);
5334 Document& Document::ensureTemplateDocument()
5336 if (isTemplateDocument())
5339 if (m_templateDocument)
5340 return *m_templateDocument;
5342 if (isHTMLDocument()) {
5343 DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL()).withNewRegistrationContext();
5344 m_templateDocument = HTMLDocument::create(init);
5346 m_templateDocument = Document::create(DocumentInit(blankURL()));
5349 m_templateDocument->m_templateDocumentHost = this; // balanced in dtor.
5351 return *m_templateDocument.get();
5354 void Document::didAssociateFormControl(Element* element)
5356 if (!frame() || !frame()->page())
5358 m_associatedFormControls.add(element);
5359 if (!m_didAssociateFormControlsTimer.isActive())
5360 m_didAssociateFormControlsTimer.startOneShot(0, FROM_HERE);
5363 void Document::didAssociateFormControlsTimerFired(Timer<Document>* timer)
5365 ASSERT_UNUSED(timer, timer == &m_didAssociateFormControlsTimer);
5366 if (!frame() || !frame()->page())
5369 Vector<RefPtr<Element> > associatedFormControls;
5370 copyToVector(m_associatedFormControls, associatedFormControls);
5372 frame()->page()->chrome().client().didAssociateFormControls(associatedFormControls);
5373 m_associatedFormControls.clear();
5376 float Document::devicePixelRatio() const
5378 return m_frame ? m_frame->devicePixelRatio() : 1.0;
5381 PassOwnPtr<LifecycleNotifier<Document> > Document::createLifecycleNotifier()
5383 return DocumentLifecycleNotifier::create(this);
5386 DocumentLifecycleNotifier& Document::lifecycleNotifier()
5388 return static_cast<DocumentLifecycleNotifier&>(LifecycleContext<Document>::lifecycleNotifier());
5391 void Document::removedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
5393 // If we're in document teardown, then we don't need this notification of our sheet's removal.
5394 // styleResolverChanged() is needed even when the document is inactive so that
5395 // imported docuements (which is inactive) notifies the change to the master document.
5397 styleEngine()->modifiedStyleSheet(sheet);
5398 styleResolverChanged(when, updateMode);
5401 void Document::modifiedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
5403 // If we're in document teardown, then we don't need this notification of our sheet's removal.
5404 // styleResolverChanged() is needed even when the document is inactive so that
5405 // imported docuements (which is inactive) notifies the change to the master document.
5407 styleEngine()->modifiedStyleSheet(sheet);
5408 styleResolverChanged(when, updateMode);
5411 TextAutosizer* Document::textAutosizer()
5413 if (!m_textAutosizer && !RuntimeEnabledFeatures::fastTextAutosizingEnabled())
5414 m_textAutosizer = TextAutosizer::create(this);
5415 return m_textAutosizer.get();
5418 FastTextAutosizer* Document::fastTextAutosizer()
5420 if (!m_fastTextAutosizer && RuntimeEnabledFeatures::fastTextAutosizingEnabled())
5421 m_fastTextAutosizer = FastTextAutosizer::create(this);
5422 return m_fastTextAutosizer.get();
5425 void Document::setAutofocusElement(Element* element)
5428 m_autofocusElement = nullptr;
5431 if (m_hasAutofocused)
5433 m_hasAutofocused = true;
5434 ASSERT(!m_autofocusElement);
5435 m_autofocusElement = element;
5436 m_taskRunner->postTask(AutofocusTask::create());
5439 Element* Document::activeElement() const
5441 if (Element* element = treeScope().adjustedFocusedElement())
5446 bool Document::hasFocus() const
5448 Page* page = this->page();
5451 if (!page->focusController().isActive() || !page->focusController().isFocused())
5453 if (LocalFrame* focusedFrame = page->focusController().focusedFrame()) {
5454 if (focusedFrame->tree().isDescendantOf(frame()))
5460 // FIXME: Remove this code once we have input routing in the browser
5461 // process. See http://crbug.com/339659.
5462 void Document::defaultEventHandler(Event* event)
5464 if (frame() && frame()->remotePlatformLayer()) {
5465 frame()->chromeClient().forwardInputEvent(this, event);
5468 Node::defaultEventHandler(event);
5471 template<unsigned type>
5472 bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
5474 if (nodeListCounts[type] && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
5476 return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
5480 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
5485 bool Document::shouldInvalidateNodeListCaches(const QualifiedName* attrName) const
5488 return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListCounts, *attrName);
5490 for (int type = 0; type < numNodeListInvalidationTypes; type++) {
5491 if (m_nodeListCounts[type])
5498 void Document::invalidateNodeListCaches(const QualifiedName* attrName)
5500 HashSet<LiveNodeListBase*>::iterator end = m_listsInvalidatedAtDocument.end();
5501 for (HashSet<LiveNodeListBase*>::iterator it = m_listsInvalidatedAtDocument.begin(); it != end; ++it)
5502 (*it)->invalidateCache(attrName);
5505 } // namespace WebCore