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/ScriptForbiddenScope.h"
89 #include "core/dom/ScriptRunner.h"
90 #include "core/dom/ScriptedAnimationController.h"
91 #include "core/dom/SelectorQuery.h"
92 #include "core/dom/StyleEngine.h"
93 #include "core/dom/TouchList.h"
94 #include "core/dom/TransformSource.h"
95 #include "core/dom/TreeWalker.h"
96 #include "core/dom/VisitedLinkState.h"
97 #include "core/dom/XMLDocument.h"
98 #include "core/dom/custom/CustomElementRegistrationContext.h"
99 #include "core/dom/shadow/ElementShadow.h"
100 #include "core/dom/shadow/ShadowRoot.h"
101 #include "core/editing/Editor.h"
102 #include "core/editing/FrameSelection.h"
103 #include "core/editing/SpellChecker.h"
104 #include "core/events/BeforeUnloadEvent.h"
105 #include "core/events/Event.h"
106 #include "core/events/EventFactory.h"
107 #include "core/events/EventListener.h"
108 #include "core/events/HashChangeEvent.h"
109 #include "core/events/PageTransitionEvent.h"
110 #include "core/events/ScopedEventQueue.h"
111 #include "core/fetch/ResourceFetcher.h"
112 #include "core/frame/DOMWindow.h"
113 #include "core/frame/FrameConsole.h"
114 #include "core/frame/FrameHost.h"
115 #include "core/frame/FrameView.h"
116 #include "core/frame/History.h"
117 #include "core/frame/LocalFrame.h"
118 #include "core/frame/Settings.h"
119 #include "core/frame/csp/ContentSecurityPolicy.h"
120 #include "core/html/HTMLAllCollection.h"
121 #include "core/html/HTMLAnchorElement.h"
122 #include "core/html/HTMLBaseElement.h"
123 #include "core/html/HTMLCanvasElement.h"
124 #include "core/html/HTMLCollection.h"
125 #include "core/html/HTMLDialogElement.h"
126 #include "core/html/HTMLDocument.h"
127 #include "core/html/HTMLFrameOwnerElement.h"
128 #include "core/html/HTMLHeadElement.h"
129 #include "core/html/HTMLHtmlElement.h"
130 #include "core/html/HTMLIFrameElement.h"
131 #include "core/html/HTMLInputElement.h"
132 #include "core/html/HTMLLinkElement.h"
133 #include "core/html/HTMLMetaElement.h"
134 #include "core/html/HTMLNameCollection.h"
135 #include "core/html/HTMLScriptElement.h"
136 #include "core/html/HTMLStyleElement.h"
137 #include "core/html/HTMLTemplateElement.h"
138 #include "core/html/HTMLTitleElement.h"
139 #include "core/html/PluginDocument.h"
140 #include "core/html/canvas/CanvasRenderingContext.h"
141 #include "core/html/canvas/CanvasRenderingContext2D.h"
142 #include "core/html/canvas/WebGLRenderingContext.h"
143 #include "core/html/forms/FormController.h"
144 #include "core/html/imports/HTMLImportLoader.h"
145 #include "core/html/imports/HTMLImportsController.h"
146 #include "core/html/parser/HTMLDocumentParser.h"
147 #include "core/html/parser/HTMLParserIdioms.h"
148 #include "core/html/parser/NestingLevelIncrementer.h"
149 #include "core/html/parser/TextResourceDecoder.h"
150 #include "core/inspector/InspectorCounters.h"
151 #include "core/inspector/InspectorInstrumentation.h"
152 #include "core/inspector/InspectorTraceEvents.h"
153 #include "core/inspector/ScriptCallStack.h"
154 #include "core/loader/CookieJar.h"
155 #include "core/loader/DocumentLoader.h"
156 #include "core/loader/FrameLoader.h"
157 #include "core/loader/FrameLoaderClient.h"
158 #include "core/loader/ImageLoader.h"
159 #include "core/loader/appcache/ApplicationCacheHost.h"
160 #include "core/page/Chrome.h"
161 #include "core/page/ChromeClient.h"
162 #include "core/page/EventHandler.h"
163 #include "core/page/FocusController.h"
164 #include "core/page/FrameTree.h"
165 #include "core/page/MouseEventWithHitTestResults.h"
166 #include "core/page/Page.h"
167 #include "core/page/PointerLockController.h"
168 #include "core/page/scrolling/ScrollingCoordinator.h"
169 #include "core/rendering/FastTextAutosizer.h"
170 #include "core/rendering/HitTestResult.h"
171 #include "core/rendering/RenderView.h"
172 #include "core/rendering/TextAutosizer.h"
173 #include "core/svg/SVGDocumentExtensions.h"
174 #include "core/svg/SVGFontFaceElement.h"
175 #include "core/svg/SVGStyleElement.h"
176 #include "core/svg/SVGUseElement.h"
177 #include "core/workers/SharedWorkerRepositoryClient.h"
178 #include "core/xml/XSLTProcessor.h"
179 #include "core/xml/parser/XMLDocumentParser.h"
180 #include "platform/DateComponents.h"
181 #include "platform/Language.h"
182 #include "platform/TraceEvent.h"
183 #include "platform/network/ContentSecurityPolicyParsers.h"
184 #include "platform/network/HTTPParsers.h"
185 #include "platform/scroll/ScrollbarTheme.h"
186 #include "platform/text/PlatformLocale.h"
187 #include "platform/text/SegmentedString.h"
188 #include "platform/weborigin/OriginAccessEntry.h"
189 #include "platform/weborigin/SchemeRegistry.h"
190 #include "platform/weborigin/SecurityOrigin.h"
191 #include "public/platform/Platform.h"
192 #include "wtf/CurrentTime.h"
193 #include "wtf/HashFunctions.h"
194 #include "wtf/MainThread.h"
195 #include "wtf/StdLibExtras.h"
196 #include "wtf/TemporaryChange.h"
197 #include "wtf/text/StringBuffer.h"
198 #include "wtf/text/TextEncodingRegistry.h"
202 using namespace Unicode;
206 using namespace HTMLNames;
208 static const unsigned cMaxWriteRecursionDepth = 21;
210 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
211 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
213 static const int cLayoutScheduleThreshold = 250;
215 // DOM Level 2 says (letters added):
217 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
218 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
219 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
220 // 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.
221 // 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.
222 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
223 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
224 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
225 // i) Characters ':' and '_' are allowed as name-start characters.
226 // j) Characters '-' and '.' are allowed as name characters.
228 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
230 static inline bool isValidNameStart(UChar32 c)
233 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
237 if (c == ':' || c == '_')
240 // rules (a) and (f) above
241 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
242 if (!(Unicode::category(c) & nameStartMask))
246 if (c >= 0xF900 && c < 0xFFFE)
250 DecompositionType decompType = decompositionType(c);
251 if (decompType == DecompositionFont || decompType == DecompositionCompat)
257 static inline bool isValidNamePart(UChar32 c)
259 // rules (a), (e), and (i) above
260 if (isValidNameStart(c))
263 // rules (g) and (h) above
264 if (c == 0x00B7 || c == 0x0387)
268 if (c == '-' || c == '.')
271 // rules (b) and (f) above
272 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
273 if (!(Unicode::category(c) & otherNamePartMask))
277 if (c >= 0xF900 && c < 0xFFFE)
281 DecompositionType decompType = decompositionType(c);
282 if (decompType == DecompositionFont || decompType == DecompositionCompat)
288 static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
290 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
292 // If a Document has the address "about:blank"
293 // The origin of the Document is the origin it was assigned when its browsing context was created.
295 // Note: We generalize this to all "blank" URLs and invalid URLs because we
296 // treat all of these URLs as about:blank.
298 return url.isEmpty() || url.protocolIsAbout();
301 static Widget* widgetForElement(const Element& focusedElement)
303 RenderObject* renderer = focusedElement.renderer();
304 if (!renderer || !renderer->isWidget())
306 return toRenderWidget(renderer)->widget();
309 static bool acceptsEditingFocus(const Element& element)
311 ASSERT(element.rendererIsEditable());
313 return element.document().frame() && element.rootEditableElement();
316 static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, LocalFrame* targetFrame)
318 // targetFrame can be 0 when we're trying to navigate a top-level frame
319 // that has a 0 opener.
323 const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
324 for (LocalFrame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
325 Document* ancestorDocument = ancestorFrame->document();
326 // FIXME: Should be an ASSERT? Frames should alway have documents.
327 if (!ancestorDocument)
330 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
331 if (activeSecurityOrigin.canAccess(ancestorSecurityOrigin))
334 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
335 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
336 // something more general instead?
337 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
344 static void printNavigationErrorMessage(const LocalFrame& frame, const KURL& activeURL, const char* reason)
346 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame.document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
348 // FIXME: should we print to the console of the document performing the navigation instead?
349 frame.domWindow()->printErrorMessage(message);
352 uint64_t Document::s_globalTreeVersion = 0;
354 // This class doesn't work with non-Document ExecutionContext.
355 class AutofocusTask FINAL : public ExecutionContextTask {
357 static PassOwnPtr<AutofocusTask> create()
359 return adoptPtr(new AutofocusTask());
361 virtual ~AutofocusTask() { }
365 virtual void performTask(ExecutionContext* context) OVERRIDE
367 Document* document = toDocument(context);
368 if (RefPtr<Element> element = document->autofocusElement()) {
369 document->setAutofocusElement(0);
375 DocumentVisibilityObserver::DocumentVisibilityObserver(Document& document)
378 registerObserver(document);
381 DocumentVisibilityObserver::~DocumentVisibilityObserver()
384 unregisterObserver();
388 void DocumentVisibilityObserver::unregisterObserver()
391 m_document->unregisterVisibilityObserver(this);
396 void DocumentVisibilityObserver::registerObserver(Document& document)
399 m_document = &document;
401 m_document->registerVisibilityObserver(this);
404 void DocumentVisibilityObserver::setObservedDocument(Document& document)
406 unregisterObserver();
407 registerObserver(document);
410 Document::Document(const DocumentInit& initializer, DocumentClassFlags documentClasses)
411 : ContainerNode(0, CreateDocument)
413 , m_hasNodesWithPlaceholderStyle(false)
414 , m_needsNotifyRemoveAllPendingStylesheet(false)
415 , m_evaluateMediaQueriesOnStyleRecalc(false)
416 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
417 , m_frame(initializer.frame())
418 , m_domWindow(m_frame ? m_frame->domWindow() : 0)
419 , m_importsController(initializer.importsController())
420 , m_activeParserCount(0)
421 , m_contextFeatures(ContextFeatures::defaultSwitch())
422 , m_wellFormed(false)
424 , m_paginatedForScreen(false)
425 , m_compatibilityMode(NoQuirksMode)
426 , m_compatibilityModeLocked(false)
427 , m_hasAutofocused(false)
428 , m_clearFocusedElementTimer(this, &Document::clearFocusedElementTimerFired)
429 , m_domTreeVersion(++s_globalTreeVersion)
431 , m_mutationObserverTypes(0)
432 , m_visitedLinkState(VisitedLinkState::create(*this))
433 , m_visuallyOrdered(false)
434 , m_readyState(Complete)
436 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
437 , m_containsValidityStyleRules(false)
438 , m_updateFocusAppearanceRestoresSelection(false)
439 , m_containsPlugins(false)
440 , m_ignoreDestructiveWriteCount(0)
441 , m_titleSetExplicitly(false)
442 , m_markers(adoptPtr(new DocumentMarkerController))
443 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
445 , m_loadEventProgress(LoadEventNotRun)
446 , m_startTime(currentTime())
447 , m_scriptRunner(ScriptRunner::create(this))
448 , m_xmlVersion("1.0")
449 , m_xmlStandalone(StandaloneUnspecified)
450 , m_hasXMLDeclaration(0)
451 , m_designMode(inherit)
452 , m_hasAnnotatedRegions(false)
453 , m_annotatedRegionsDirty(false)
454 , m_useSecureKeyboardEntryWhenActive(false)
455 , m_documentClasses(documentClasses)
456 , m_isViewSource(false)
457 , m_sawElementsInKnownNamespaces(false)
458 , m_isSrcdocDocument(false)
459 , m_isMobileDocument(false)
461 , m_weakFactory(this)
462 , m_contextDocument(initializer.contextDocument())
463 , m_hasFullscreenElementStack(false)
464 , m_loadEventDelayCount(0)
465 , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
466 , m_pluginLoadingTimer(this, &Document::pluginLoadingTimerFired)
467 , m_didSetReferrerPolicy(false)
468 , m_referrerPolicy(ReferrerPolicyDefault)
469 , m_directionSetOnDocumentElement(false)
470 , m_writingModeSetOnDocumentElement(false)
471 , m_writeRecursionIsTooDeep(false)
472 , m_writeRecursionDepth(0)
473 , m_taskRunner(MainThreadTaskRunner::create(this))
474 , m_registrationContext(initializer.registrationContext(this))
475 , m_elementDataCacheClearTimer(this, &Document::elementDataCacheClearTimerFired)
477 , m_didDispatchViewportPropertiesChanged(false)
479 , m_animationClock(AnimationClock::create())
480 , m_timeline(DocumentTimeline::create(this))
481 , m_transitionTimeline(TransitionTimeline::create(this))
482 , m_templateDocumentHost(nullptr)
483 , m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
484 , m_hasViewportUnits(false)
485 , m_styleRecalcElementCounter(0)
488 ScriptWrappable::init(this);
491 ASSERT(m_frame->page());
492 provideContextFeaturesToDocumentFrom(*this, *m_frame->page());
494 m_fetcher = m_frame->loader().documentLoader()->fetcher();
498 m_fetcher = ResourceFetcher::create(0);
499 m_fetcher->setDocument(this);
501 // We depend on the url getting immediately set in subframes, but we
502 // also depend on the url NOT getting immediately set in opened windows.
503 // See fast/dom/early-frame-url.html
504 // and fast/dom/location-new-window-no-crash.html, respectively.
505 // FIXME: Can/should we unify this behavior?
506 if (initializer.shouldSetURL())
507 setURL(initializer.url());
509 initSecurityContext(initializer);
512 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
513 m_nodeListCounts[i] = 0;
515 InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
517 m_lifecycle.advanceTo(DocumentLifecycle::Inactive);
519 // Since CSSFontSelector requires Document::m_fetcher and StyleEngine owns
520 // CSSFontSelector, need to initialize m_styleEngine after initializing
522 m_styleEngine = StyleEngine::create(*this);
525 Document::~Document()
527 ASSERT(!renderView());
528 ASSERT(m_ranges.isEmpty());
529 ASSERT(!parentTreeScope());
531 ASSERT(!hasGuardRefCount());
532 // With Oilpan, either the document outlives the visibility observers
533 // or the visibility observers and the document die in the same GC round.
534 // When they die in the same GC round, the list of visibility observers
535 // will not be empty on Document destruction.
536 ASSERT(m_visibilityObservers.isEmpty());
538 if (m_templateDocument)
539 m_templateDocument->m_templateDocumentHost = nullptr; // balanced in ensureTemplateDocument().
542 m_scriptRunner.clear();
544 // FIXME: Oilpan: Not removing event listeners here also means that we do
545 // not notify the inspector instrumentation that the event listeners are
546 // gone. The Document and all the nodes in the document are gone, so maybe
549 removeAllEventListenersRecursively();
552 // Currently we believe that Document can never outlive the parser.
553 // Although the Document may be replaced synchronously, DocumentParsers
554 // generally keep at least one reference to an Element which would in turn
555 // has a reference to the Document. If you hit this ASSERT, then that
556 // assumption is wrong. DocumentParser::detach() should ensure that even
557 // if the DocumentParser outlives the Document it won't cause badness.
558 ASSERT(!m_parser || m_parser->refCount() == 1);
561 if (this == topDocument())
562 clearAXObjectCache();
565 if (m_styleSheetList)
566 m_styleSheetList->detachFromDocument();
569 if (m_importsController) {
570 m_importsController->wasDetachedFrom(*this);
571 m_importsController = 0;
574 m_timeline->detachFromDocument();
575 m_transitionTimeline->detachFromDocument();
578 // We need to destroy CSSFontSelector before destroying m_fetcher.
580 m_styleEngine->detachFromDocument();
583 m_elemSheet->clearOwnerNode();
585 // It's possible for multiple Documents to end up referencing the same ResourceFetcher (e.g., SVGImages
586 // load the initial empty document and the SVGDocument with the same DocumentLoader).
587 if (m_fetcher->document() == this)
588 m_fetcher->setDocument(nullptr);
592 // We must call clearRareData() here since a Document class inherits TreeScope
593 // as well as Node. See a comment on TreeScope.h for the reason.
599 ASSERT(!m_listsInvalidatedAtDocument.size());
601 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
602 ASSERT(!m_nodeListCounts[i]);
606 InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
609 void Document::dispose()
612 ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
614 // We must make sure not to be retaining any of our children through
615 // these extra pointers or we will create a reference cycle.
617 m_focusedElement = nullptr;
618 m_hoverNode = nullptr;
619 m_activeHoverElement = nullptr;
620 m_titleElement = nullptr;
621 m_documentElement = nullptr;
622 m_contextFeatures = ContextFeatures::defaultSwitch();
623 m_userActionElements.documentDidRemoveLastRef();
624 m_associatedFormControls.clear();
629 m_registrationContext.clear();
631 if (m_importsController) {
632 m_importsController->wasDetachedFrom(*this);
633 m_importsController = 0;
637 // removeDetachedChildren() doesn't always unregister IDs,
638 // so tear down scope information upfront to avoid having stale references in the map.
639 destroyTreeScopeData();
641 removeDetachedChildren();
643 // removeDetachedChildren() can access FormController.
644 m_formController.clear();
648 m_cssCanvasElements.clear();
651 // FIXME: consider using ActiveDOMObject.
652 if (m_scriptedAnimationController)
653 m_scriptedAnimationController->clearDocumentPointer();
654 m_scriptedAnimationController.clear();
657 accessSVGExtensions().pauseAnimations();
659 m_lifecycle.advanceTo(DocumentLifecycle::Disposed);
660 lifecycleNotifier().notifyDocumentWasDisposed();
663 SelectorQueryCache& Document::selectorQueryCache()
665 if (!m_selectorQueryCache)
666 m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
667 return *m_selectorQueryCache;
670 MediaQueryMatcher& Document::mediaQueryMatcher()
672 if (!m_mediaQueryMatcher)
673 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
674 return *m_mediaQueryMatcher;
677 void Document::mediaQueryAffectingValueChanged()
679 styleEngine()->clearMediaQueryRuleSetStyleSheets();
682 void Document::setCompatibilityMode(CompatibilityMode mode)
684 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
686 bool wasInQuirksMode = inQuirksMode();
687 m_compatibilityMode = mode;
688 selectorQueryCache().invalidate();
689 if (inQuirksMode() != wasInQuirksMode) {
690 // All injected stylesheets have to reparse using the different mode.
691 m_styleEngine->invalidateInjectedStyleSheetCache();
695 String Document::compatMode() const
697 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
700 void Document::setDoctype(PassRefPtr<DocumentType> docType)
702 // This should never be called more than once.
703 ASSERT(!m_docType || !docType);
706 this->adoptIfNeeded(*m_docType);
707 if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
708 m_isMobileDocument = true;
710 // Doctype affects the interpretation of the stylesheets.
711 clearStyleResolver();
714 DOMImplementation& Document::implementation()
716 if (!m_implementation)
717 m_implementation = DOMImplementation::create(*this);
718 return *m_implementation;
721 bool Document::hasManifest() const
723 return isHTMLHtmlElement(documentElement()) && documentElement()->hasAttribute(manifestAttr);
726 Location* Document::location() const
731 return &domWindow()->location();
734 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
736 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
737 m_documentElement = ElementTraversal::firstWithin(*this);
740 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& exceptionState)
742 if (!isValidName(name)) {
743 exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + name + "') is not a valid name.");
747 if (isXHTMLDocument() || isHTMLDocument())
748 return HTMLElementFactory::createHTMLElement(isHTMLDocument() ? name.lower() : name, *this, 0, false);
750 return Element::create(QualifiedName(nullAtom, name, nullAtom), this);
753 PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& exceptionState)
755 if (!isValidName(localName)) {
756 exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + localName + "') is not a valid name.");
760 RefPtr<Element> element;
762 if (CustomElement::isValidName(localName) && registrationContext()) {
763 element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI));
765 element = createElement(localName, exceptionState);
766 if (exceptionState.hadException())
770 if (!typeExtension.isEmpty())
771 CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
776 static inline QualifiedName createQualifiedName(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
778 AtomicString prefix, localName;
779 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
782 QualifiedName qName(prefix, localName, namespaceURI);
783 if (!Document::hasValidNamespaceForElements(qName)) {
784 exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
791 PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
793 QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
794 if (qName == nullQName())
797 return createElement(qName, false);
800 PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
802 QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
803 if (qName == nullQName())
806 RefPtr<Element> element;
807 if (CustomElement::isValidName(qName.localName()) && registrationContext())
808 element = registrationContext()->createCustomTagElement(*this, qName);
810 element = createElement(qName, false);
812 if (!typeExtension.isEmpty())
813 CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
818 ScriptValue Document::registerElement(WebCore::ScriptState* scriptState, const AtomicString& name, ExceptionState& exceptionState)
820 return registerElement(scriptState, name, Dictionary(), exceptionState);
823 ScriptValue Document::registerElement(WebCore::ScriptState* scriptState, const AtomicString& name, const Dictionary& options, ExceptionState& exceptionState, CustomElement::NameSet validNames)
825 if (!registrationContext()) {
826 exceptionState.throwDOMException(NotSupportedError, "No element registration context is available.");
827 return ScriptValue();
830 CustomElementConstructorBuilder constructorBuilder(scriptState, &options);
831 registrationContext()->registerElement(this, &constructorBuilder, name, validNames, exceptionState);
832 return constructorBuilder.bindingsReturnValue();
835 void Document::setImportsController(HTMLImportsController* controller)
837 ASSERT(!m_importsController || !controller);
838 m_importsController = controller;
841 HTMLImportLoader* Document::importLoader() const
843 if (!m_importsController)
845 return m_importsController->loaderFor(*this);
848 bool Document::haveImportsLoaded() const
850 if (!m_importsController)
852 return !m_importsController->shouldBlockScriptExecution(*this);
855 DOMWindow* Document::executingWindow()
857 if (DOMWindow* owningWindow = domWindow())
859 if (HTMLImportsController* import = this->importsController())
860 return import->master()->domWindow();
864 LocalFrame* Document::executingFrame()
866 DOMWindow* window = executingWindow();
869 return window->frame();
872 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
874 return DocumentFragment::create(*this);
877 PassRefPtr<Text> Document::createTextNode(const String& data)
879 return Text::create(*this, data);
882 PassRefPtr<Comment> Document::createComment(const String& data)
884 return Comment::create(*this, data);
887 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& exceptionState)
889 if (isHTMLDocument()) {
890 exceptionState.throwDOMException(NotSupportedError, "This operation is not supported for HTML documents.");
893 if (data.contains("]]>")) {
894 exceptionState.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
897 return CDATASection::create(*this, data);
900 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& exceptionState)
902 if (!isValidName(target)) {
903 exceptionState.throwDOMException(InvalidCharacterError, "The target provided ('" + target + "') is not a valid name.");
906 if (data.contains("?>")) {
907 exceptionState.throwDOMException(InvalidCharacterError, "The data provided ('" + data + "') contains '?>'.");
910 return ProcessingInstruction::create(*this, target, data);
913 PassRefPtr<Text> Document::createEditingTextNode(const String& text)
915 return Text::createEditingText(*this, text);
918 bool Document::importContainerNodeChildren(ContainerNode* oldContainerNode, PassRefPtr<ContainerNode> newContainerNode, ExceptionState& exceptionState)
920 for (Node* oldChild = oldContainerNode->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
921 RefPtr<Node> newChild = importNode(oldChild, true, exceptionState);
922 if (exceptionState.hadException())
924 newContainerNode->appendChild(newChild.release(), exceptionState);
925 if (exceptionState.hadException())
932 PassRefPtr<Node> Document::importNode(Node* importedNode, ExceptionState& ec)
934 UseCounter::countDeprecation(this, UseCounter::DocumentImportNodeOptionalArgument);
935 return importNode(importedNode, true, ec);
938 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& exceptionState)
941 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
945 switch (importedNode->nodeType()) {
947 return createTextNode(importedNode->nodeValue());
948 case CDATA_SECTION_NODE:
949 return createCDATASection(importedNode->nodeValue(), exceptionState);
950 case PROCESSING_INSTRUCTION_NODE:
951 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), exceptionState);
953 return createComment(importedNode->nodeValue());
954 case DOCUMENT_TYPE_NODE: {
955 DocumentType* doctype = toDocumentType(importedNode);
956 return DocumentType::create(this, doctype->name(), doctype->publicId(), doctype->systemId());
959 Element* oldElement = toElement(importedNode);
960 // FIXME: The following check might be unnecessary. Is it possible that
961 // oldElement has mismatched prefix/namespace?
962 if (!hasValidNamespaceForElements(oldElement->tagQName())) {
963 exceptionState.throwDOMException(NamespaceError, "The imported node has an invalid namespace.");
966 RefPtr<Element> newElement = createElement(oldElement->tagQName(), false);
968 newElement->cloneDataFromElement(*oldElement);
971 if (!importContainerNodeChildren(oldElement, newElement, exceptionState))
973 if (isHTMLTemplateElement(*oldElement)
974 && !importContainerNodeChildren(toHTMLTemplateElement(oldElement)->content(), toHTMLTemplateElement(newElement)->content(), exceptionState))
978 return newElement.release();
981 return Attr::create(*this, QualifiedName(nullAtom, AtomicString(toAttr(importedNode)->name()), nullAtom), toAttr(importedNode)->value());
982 case DOCUMENT_FRAGMENT_NODE: {
983 if (importedNode->isShadowRoot()) {
984 // ShadowRoot nodes should not be explicitly importable.
985 // Either they are imported along with their host node, or created implicitly.
986 exceptionState.throwDOMException(NotSupportedError, "The node provided is a shadow root, which may not be imported.");
989 DocumentFragment* oldFragment = toDocumentFragment(importedNode);
990 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
991 if (deep && !importContainerNodeChildren(oldFragment, newFragment, exceptionState))
994 return newFragment.release();
997 exceptionState.throwDOMException(NotSupportedError, "The node provided is a document, which may not be imported.");
1001 ASSERT_NOT_REACHED();
1005 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionState& exceptionState)
1008 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1012 EventQueueScope scope;
1014 switch (source->nodeType()) {
1016 case DOCUMENT_TYPE_NODE:
1017 exceptionState.throwDOMException(NotSupportedError, "The node provided is of type '" + source->nodeName() + "', which may not be adopted.");
1019 case ATTRIBUTE_NODE: {
1020 Attr* attr = toAttr(source.get());
1021 if (attr->ownerElement())
1022 attr->ownerElement()->removeAttributeNode(attr, exceptionState);
1026 if (source->isShadowRoot()) {
1027 // ShadowRoot cannot disconnect itself from the host node.
1028 exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a shadow root, which may not be adopted.");
1032 if (source->isFrameOwnerElement()) {
1033 HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
1034 // FIXME(kenrb): the downcast can be removed when the FrameTree supports RemoteFrames.
1035 if (frame() && frame()->tree().isDescendantOf(toLocalFrameTemporary(frameOwnerElement->contentFrame()))) {
1036 exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a frame which contains this document.");
1040 if (source->parentNode()) {
1041 source->parentNode()->removeChild(source.get(), exceptionState);
1042 if (exceptionState.hadException())
1047 this->adoptIfNeeded(*source);
1052 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1054 // These checks are from DOM Core Level 2, createElementNS
1055 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1056 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1058 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1061 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1062 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1063 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1064 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1065 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1066 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1069 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1071 return hasValidNamespaceForElements(qName);
1074 // FIXME: This should really be in a possible ElementFactory class
1075 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
1079 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1080 if (qName.namespaceURI() == xhtmlNamespaceURI)
1081 e = HTMLElementFactory::createHTMLElement(qName.localName(), *this, 0, createdByParser);
1082 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
1083 e = SVGElementFactory::createSVGElement(qName.localName(), *this, createdByParser);
1086 m_sawElementsInKnownNamespaces = true;
1088 e = Element::create(qName, this);
1090 if (e->prefix() != qName.prefix())
1091 e->setTagNameForCreateElementNS(qName);
1093 ASSERT(qName == e->tagQName());
1098 bool Document::regionBasedColumnsEnabled() const
1100 return settings() && settings()->regionBasedColumnsEnabled();
1103 String Document::readyState() const
1105 DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
1106 DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
1107 DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
1109 switch (m_readyState) {
1118 ASSERT_NOT_REACHED();
1122 void Document::setReadyState(ReadyState readyState)
1124 if (readyState == m_readyState)
1127 switch (readyState) {
1129 if (!m_documentTiming.domLoading) {
1130 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1131 m_timeline->setZeroTime(m_documentTiming.domLoading);
1135 if (!m_documentTiming.domInteractive)
1136 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1139 if (!m_documentTiming.domComplete)
1140 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1144 m_readyState = readyState;
1145 dispatchEvent(Event::create(EventTypeNames::readystatechange));
1148 bool Document::isLoadCompleted()
1150 return m_readyState == Complete;
1153 AtomicString Document::encodingName() const
1155 // TextEncoding::name() returns a char*, no need to allocate a new
1156 // String for it each time.
1157 // FIXME: We should fix TextEncoding to speak AtomicString anyway.
1158 return AtomicString(encoding().name());
1161 String Document::defaultCharset() const
1163 if (Settings* settings = this->settings())
1164 return settings->defaultTextEncodingName();
1168 void Document::setCharset(const String& charset)
1170 if (DocumentLoader* documentLoader = loader())
1171 documentLoader->setUserChosenEncoding(charset);
1172 WTF::TextEncoding encoding(charset);
1173 // In case the encoding didn't exist, we keep the old one (helps some sites specifying invalid encodings).
1174 if (!encoding.isValid())
1176 DocumentEncodingData newEncodingData = m_encodingData;
1177 newEncodingData.setEncoding(encoding);
1178 setEncodingData(newEncodingData);
1181 void Document::setContentLanguage(const AtomicString& language)
1183 if (m_contentLanguage == language)
1185 m_contentLanguage = language;
1187 // Document's style depends on the content language.
1188 setNeedsStyleRecalc(SubtreeStyleChange);
1191 void Document::setXMLVersion(const String& version, ExceptionState& exceptionState)
1193 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1194 exceptionState.throwDOMException(NotSupportedError, "This document does not support the XML version '" + version + "'.");
1198 m_xmlVersion = version;
1201 void Document::setXMLStandalone(bool standalone, ExceptionState& exceptionState)
1203 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1206 KURL Document::baseURI() const
1211 void Document::setContent(const String& content)
1214 // FIXME: This should probably use insert(), but that's (intentionally)
1215 // not implemented for the XML parser as it's normally synonymous with
1216 // document.write(). append() will end up yielding, but close() will
1217 // pump the tokenizer syncrhonously and finish the parse.
1218 m_parser->pinToMainThread();
1219 m_parser->append(content.impl());
1223 String Document::suggestedMIMEType() const
1225 if (isXMLDocument()) {
1226 if (isXHTMLDocument())
1227 return "application/xhtml+xml";
1228 if (isSVGDocument())
1229 return "image/svg+xml";
1230 return "application/xml";
1232 if (xmlStandalone())
1234 if (isHTMLDocument())
1237 if (DocumentLoader* documentLoader = loader())
1238 return documentLoader->responseMIMEType();
1242 void Document::setMimeType(const AtomicString& mimeType)
1244 m_mimeType = mimeType;
1247 AtomicString Document::contentType() const
1249 if (!m_mimeType.isEmpty())
1252 if (DocumentLoader* documentLoader = loader())
1253 return documentLoader->mimeType();
1255 String mimeType = suggestedMIMEType();
1256 if (!mimeType.isEmpty())
1257 return AtomicString(mimeType);
1259 return AtomicString("application/xml");
1262 Element* Document::elementFromPoint(int x, int y) const
1267 return TreeScope::elementFromPoint(x, y);
1270 PassRefPtrWillBeRawPtr<Range> Document::caretRangeFromPoint(int x, int y)
1274 HitTestResult result = hitTestInDocument(this, x, y);
1275 RenderObject* renderer = result.renderer();
1279 Node* node = renderer->node();
1280 Node* shadowAncestorNode = ancestorInThisScope(node);
1281 if (shadowAncestorNode != node) {
1282 unsigned offset = shadowAncestorNode->nodeIndex();
1283 ContainerNode* container = shadowAncestorNode->parentNode();
1284 return Range::create(*this, container, offset, container, offset);
1287 PositionWithAffinity positionWithAffinity = renderer->positionForPoint(result.localPoint());
1288 if (positionWithAffinity.position().isNull())
1291 Position rangeCompliantPosition = positionWithAffinity.position().parentAnchoredEquivalent();
1292 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1296 * Performs three operations:
1297 * 1. Convert control characters to spaces
1298 * 2. Trim leading and trailing spaces
1299 * 3. Collapse internal whitespace.
1301 template <typename CharacterType>
1302 static inline String canonicalizedTitle(Document* document, const String& title)
1304 const CharacterType* characters = title.getCharacters<CharacterType>();
1305 unsigned length = title.length();
1308 StringBuffer<CharacterType> buffer(length);
1309 unsigned builderIndex = 0;
1311 // Skip leading spaces and leading characters that would convert to spaces
1312 for (i = 0; i < length; ++i) {
1313 CharacterType c = characters[i];
1314 if (!(c <= 0x20 || c == 0x7F))
1321 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1322 bool previousCharWasWS = false;
1323 for (; i < length; ++i) {
1324 CharacterType c = characters[i];
1325 if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1326 if (previousCharWasWS)
1328 buffer[builderIndex++] = ' ';
1329 previousCharWasWS = true;
1331 buffer[builderIndex++] = c;
1332 previousCharWasWS = false;
1336 // Strip trailing spaces
1337 while (builderIndex > 0) {
1339 if (buffer[builderIndex] != ' ')
1343 if (!builderIndex && buffer[builderIndex] == ' ')
1346 buffer.shrink(builderIndex + 1);
1348 return String::adopt(buffer);
1351 void Document::updateTitle(const String& title)
1353 if (m_rawTitle == title)
1358 String oldTitle = m_title;
1359 if (m_rawTitle.isEmpty())
1361 else if (m_rawTitle.is8Bit())
1362 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1364 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1366 if (!m_frame || oldTitle == m_title)
1368 m_frame->loader().client()->dispatchDidReceiveTitle(m_title);
1371 void Document::setTitle(const String& title)
1373 // Title set by JavaScript -- overrides any title elements.
1374 m_titleSetExplicitly = true;
1375 if (!isHTMLDocument() && !isXHTMLDocument())
1376 m_titleElement = nullptr;
1377 else if (!m_titleElement) {
1378 if (HTMLElement* headElement = head()) {
1379 m_titleElement = HTMLTitleElement::create(*this);
1380 headElement->appendChild(m_titleElement.get());
1384 if (isHTMLTitleElement(m_titleElement))
1385 toHTMLTitleElement(m_titleElement)->setText(title);
1390 void Document::setTitleElement(const String& title, Element* titleElement)
1392 if (titleElement != m_titleElement) {
1393 if (m_titleElement || m_titleSetExplicitly)
1394 // Only allow the first title element to change the title -- others have no effect.
1396 m_titleElement = titleElement;
1402 void Document::removeTitle(Element* titleElement)
1404 if (m_titleElement != titleElement)
1407 m_titleElement = nullptr;
1408 m_titleSetExplicitly = false;
1410 // FIXME: This is broken for SVG.
1411 // Update title based on first title element in the head, if one exists.
1412 if (HTMLElement* headElement = head()) {
1413 if (HTMLTitleElement* title = Traversal<HTMLTitleElement>::firstChild(*headElement))
1414 setTitleElement(title->text(), title);
1417 if (!m_titleElement)
1418 updateTitle(String());
1421 const AtomicString& Document::dir()
1423 Element* rootElement = documentElement();
1424 if (isHTMLHtmlElement(rootElement))
1425 return toHTMLHtmlElement(rootElement)->dir();
1429 void Document::setDir(const AtomicString& value)
1431 Element* rootElement = documentElement();
1432 if (isHTMLHtmlElement(rootElement))
1433 toHTMLHtmlElement(rootElement)->setDir(value);
1436 PageVisibilityState Document::pageVisibilityState() const
1438 // The visibility of the document is inherited from the visibility of the
1439 // page. If there is no page associated with the document, we will assume
1440 // that the page is hidden, as specified by the spec:
1441 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1442 if (!m_frame || !m_frame->page())
1443 return PageVisibilityStateHidden;
1444 return m_frame->page()->visibilityState();
1447 String Document::visibilityState() const
1449 return pageVisibilityStateString(pageVisibilityState());
1452 bool Document::hidden() const
1454 return pageVisibilityState() != PageVisibilityStateVisible;
1457 void Document::didChangeVisibilityState()
1459 dispatchEvent(Event::create(EventTypeNames::visibilitychange));
1460 // Also send out the deprecated version until it can be removed.
1461 dispatchEvent(Event::create(EventTypeNames::webkitvisibilitychange));
1463 PageVisibilityState state = pageVisibilityState();
1464 DocumentVisibilityObserverSet::const_iterator observerEnd = m_visibilityObservers.end();
1465 for (DocumentVisibilityObserverSet::const_iterator it = m_visibilityObservers.begin(); it != observerEnd; ++it)
1466 (*it)->didChangeVisibilityState(state);
1469 void Document::registerVisibilityObserver(DocumentVisibilityObserver* observer)
1471 ASSERT(!m_visibilityObservers.contains(observer));
1472 m_visibilityObservers.add(observer);
1475 void Document::unregisterVisibilityObserver(DocumentVisibilityObserver* observer)
1477 ASSERT(m_visibilityObservers.contains(observer));
1478 m_visibilityObservers.remove(observer);
1481 String Document::nodeName() const
1486 Node::NodeType Document::nodeType() const
1488 return DOCUMENT_NODE;
1491 FormController& Document::formController()
1493 if (!m_formController) {
1494 m_formController = FormController::create();
1495 if (m_frame && m_frame->loader().currentItem() && m_frame->loader().currentItem()->isCurrentDocument(this))
1496 m_frame->loader().currentItem()->setDocumentState(m_formController->formElementsState());
1498 return *m_formController;
1501 DocumentState* Document::formElementsState() const
1503 if (!m_formController)
1505 return m_formController->formElementsState();
1508 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1510 if (!stateVector.size() && !m_formController)
1512 formController().setStateForNewFormElements(stateVector);
1515 FrameView* Document::view() const
1517 return m_frame ? m_frame->view() : 0;
1520 Page* Document::page() const
1522 return m_frame ? m_frame->page() : 0;
1525 FrameHost* Document::frameHost() const
1527 return m_frame ? m_frame->host() : 0;
1530 Settings* Document::settings() const
1532 return m_frame ? m_frame->settings() : 0;
1535 PassRefPtrWillBeRawPtr<Range> Document::createRange()
1537 return Range::create(*this);
1540 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionState& exceptionState)
1542 // FIXME: Probably this should be handled within the bindings layer and TypeError should be thrown.
1544 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1547 return NodeIterator::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
1550 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
1553 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1556 // FIXME: It might be a good idea to emit a warning if |whatToShow| contains a bit that is not defined in
1558 return NodeIterator::create(root, whatToShow, PassRefPtr<NodeFilter>());
1561 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
1564 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1568 return NodeIterator::create(root, whatToShow, filter);
1571 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionState& exceptionState)
1574 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1577 return TreeWalker::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
1580 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
1583 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1586 return TreeWalker::create(root, whatToShow, PassRefPtr<NodeFilter>());
1589 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
1592 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1595 return TreeWalker::create(root, whatToShow, filter);
1598 bool Document::needsRenderTreeUpdate() const
1600 if (!isActive() || !view())
1602 if (needsFullRenderTreeUpdate())
1604 if (childNeedsStyleRecalc())
1606 if (childNeedsStyleInvalidation())
1611 bool Document::needsFullRenderTreeUpdate() const
1613 if (!isActive() || !view())
1615 if (!m_useElementsNeedingUpdate.isEmpty())
1617 if (!m_layerUpdateElements.isEmpty())
1619 if (needsStyleRecalc())
1621 if (needsStyleInvalidation())
1623 // FIXME: The childNeedsDistributionRecalc bit means either self or children, we should fix that.
1624 if (childNeedsDistributionRecalc())
1626 if (DocumentAnimations::needsOutdatedAnimationPlayerUpdate(*this))
1631 bool Document::shouldScheduleRenderTreeUpdate() const
1635 if (inStyleRecalc())
1637 // InPreLayout will recalc style itself. There's no reason to schedule another recalc.
1638 if (m_lifecycle.state() == DocumentLifecycle::InPreLayout)
1640 if (!shouldScheduleLayout())
1645 void Document::scheduleRenderTreeUpdate()
1647 ASSERT(!hasPendingStyleRecalc());
1648 ASSERT(shouldScheduleRenderTreeUpdate());
1649 ASSERT(needsRenderTreeUpdate());
1651 page()->animator().scheduleVisualUpdate();
1652 m_lifecycle.ensureStateAtMost(DocumentLifecycle::VisualUpdatePending);
1654 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ScheduleStyleRecalculation", "frame", frame());
1655 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
1656 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1657 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1660 bool Document::hasPendingForcedStyleRecalc() const
1662 return hasPendingStyleRecalc() && !inStyleRecalc() && styleChangeType() >= SubtreeStyleChange;
1665 void Document::updateDistributionIfNeeded()
1667 ScriptForbiddenScope forbidScript;
1669 if (!childNeedsDistributionRecalc())
1671 TRACE_EVENT0("webkit", "Document::updateDistributionIfNeeded");
1672 recalcDistribution();
1675 void Document::updateStyleInvalidationIfNeeded()
1677 ScriptForbiddenScope forbidScript;
1681 if (!childNeedsStyleInvalidation())
1683 TRACE_EVENT0("webkit", "Document::updateStyleInvalidationIfNeeded");
1684 ASSERT(styleResolver());
1686 styleResolver()->ruleFeatureSet().styleInvalidator().invalidate(*this);
1689 void Document::updateDistributionForNodeIfNeeded(Node* node)
1691 ScriptForbiddenScope forbidScript;
1693 if (node->inDocument()) {
1694 updateDistributionIfNeeded();
1698 while (Node* host = root->shadowHost())
1700 while (Node* ancestor = root->parentOrShadowHostNode())
1702 if (root->childNeedsDistributionRecalc())
1703 root->recalcDistribution();
1706 void Document::setupFontBuilder(RenderStyle* documentStyle)
1708 FontBuilder fontBuilder;
1709 fontBuilder.initForStyleResolve(*this, documentStyle, isSVGDocument());
1710 RefPtrWillBeRawPtr<CSSFontSelector> selector = m_styleEngine->fontSelector();
1711 fontBuilder.createFontForDocument(selector, documentStyle);
1714 void Document::inheritHtmlAndBodyElementStyles(StyleRecalcChange change)
1716 ASSERT(inStyleRecalc());
1717 ASSERT(documentElement());
1719 RefPtr<RenderStyle> documentElementStyle = documentElement()->renderStyle();
1720 if (!documentElementStyle || documentElement()->needsStyleRecalc() || change == Force)
1721 documentElementStyle = ensureStyleResolver().styleForElement(documentElement());
1723 WritingMode rootWritingMode = documentElementStyle->writingMode();
1724 TextDirection rootDirection = documentElementStyle->direction();
1726 HTMLElement* body = this->body();
1727 RefPtr<RenderStyle> bodyStyle;
1729 bodyStyle = body->renderStyle();
1730 if (!bodyStyle || body->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
1731 bodyStyle = ensureStyleResolver().styleForElement(body, documentElementStyle.get());
1732 if (!writingModeSetOnDocumentElement())
1733 rootWritingMode = bodyStyle->writingMode();
1734 if (!directionSetOnDocumentElement())
1735 rootDirection = bodyStyle->direction();
1738 RefPtr<RenderStyle> overflowStyle;
1739 if (Element* element = viewportDefiningElement(documentElementStyle.get())) {
1740 if (element == body) {
1741 overflowStyle = bodyStyle;
1743 ASSERT(element == documentElement());
1744 overflowStyle = documentElementStyle;
1748 // Resolved rem units are stored in the matched properties cache so we need to make sure to
1749 // invalidate the cache if the documentElement needed to reattach or the font size changed
1750 // and then trigger a full document recalc. We also need to clear it here since the
1751 // call to styleForElement on the body above can cache bad values for rem units if the
1752 // documentElement's style was dirty. We could keep track of which elements depend on
1753 // rem units like we do for viewport styles, but we assume root font size changes are
1754 // rare and just invalidate the cache for now.
1755 if (styleEngine()->usesRemUnits() && (documentElement()->needsAttach() || documentElement()->computedStyle()->fontSize() != documentElementStyle->fontSize())) {
1756 ensureStyleResolver().invalidateMatchedPropertiesCache();
1757 documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
1760 EOverflow overflowX = OAUTO;
1761 EOverflow overflowY = OAUTO;
1762 float columnGap = 0;
1763 if (overflowStyle) {
1764 overflowX = overflowStyle->overflowX();
1765 overflowY = overflowStyle->overflowY();
1766 // Visible overflow on the viewport is meaningless, and the spec says to treat it as 'auto':
1767 if (overflowX == OVISIBLE)
1769 if (overflowY == OVISIBLE)
1771 // Column-gap is (ab)used by the current paged overflow implementation (in lack of other
1772 // ways to specify gaps between pages), so we have to propagate it too.
1773 columnGap = overflowStyle->columnGap();
1776 RefPtr<RenderStyle> documentStyle = renderView()->style();
1777 if (documentStyle->writingMode() != rootWritingMode
1778 || documentStyle->direction() != rootDirection
1779 || documentStyle->overflowX() != overflowX
1780 || documentStyle->overflowY() != overflowY
1781 || documentStyle->columnGap() != columnGap) {
1782 RefPtr<RenderStyle> newStyle = RenderStyle::clone(documentStyle.get());
1783 newStyle->setWritingMode(rootWritingMode);
1784 newStyle->setDirection(rootDirection);
1785 newStyle->setColumnGap(columnGap);
1786 newStyle->setOverflowX(overflowX);
1787 newStyle->setOverflowY(overflowY);
1788 renderView()->setStyle(newStyle);
1789 setupFontBuilder(newStyle.get());
1793 if (RenderStyle* style = body->renderStyle()) {
1794 if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
1795 body->setNeedsStyleRecalc(SubtreeStyleChange);
1799 if (RenderStyle* style = documentElement()->renderStyle()) {
1800 if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
1801 documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
1805 void Document::updateRenderTree(StyleRecalcChange change)
1807 ASSERT(isMainThread());
1809 if (change != Force && !needsRenderTreeUpdate())
1812 if (inStyleRecalc())
1815 // Entering here from inside layout or paint would be catastrophic since recalcStyle can
1816 // tear down the render tree or (unfortunately) run script. Kill the whole renderer if
1817 // someone managed to get into here from inside layout or paint.
1818 RELEASE_ASSERT(!view()->isInPerformLayout());
1819 RELEASE_ASSERT(!view()->isPainting());
1821 // Script can run below in WidgetUpdates, so protect the LocalFrame.
1822 RefPtr<LocalFrame> protect(m_frame);
1824 TRACE_EVENT0("webkit", "Document::updateRenderTree");
1825 TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "UpdateRenderTree");
1827 m_styleRecalcElementCounter = 0;
1828 TRACE_EVENT_BEGIN1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "RecalculateStyles", "frame", frame());
1829 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
1830 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1831 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1833 DocumentAnimations::updateOutdatedAnimationPlayersIfNeeded(*this);
1834 updateDistributionIfNeeded();
1835 updateUseShadowTreesIfNeeded();
1836 updateStyleInvalidationIfNeeded();
1838 // FIXME: This executes media query listeners which runs script, instead the script
1839 // should run at raf timing in ScriptedAnimationController just like resize events.
1840 evaluateMediaQueryListIfNeeded();
1842 // FIXME: We should update style on our ancestor chain before proceeding
1843 // however doing so currently causes several tests to crash, as LocalFrame::setDocument calls Document::attach
1844 // before setting the DOMWindow on the LocalFrame, or the SecurityOrigin on the document. The attach, in turn
1845 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1846 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1847 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1849 if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
1850 m_styleEngine->setUsesRemUnit(true);
1852 updateStyle(change);
1854 // As a result of the style recalculation, the currently hovered element might have been
1855 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1856 // to check if any other elements ended up under the mouse pointer due to re-layout.
1857 if (hoverNode() && !hoverNode()->renderer() && frame())
1858 frame()->eventHandler().dispatchFakeMouseMoveEventSoon();
1860 if (m_focusedElement && !m_focusedElement->isFocusable())
1861 clearFocusedElementSoon();
1863 #if ENABLE(SVG_FONTS)
1864 if (svgExtensions())
1865 accessSVGExtensions().removePendingSVGFontFaceElementsForRemoval();
1868 ASSERT(!m_timeline->hasOutdatedAnimationPlayer());
1869 ASSERT(!m_transitionTimeline->hasOutdatedAnimationPlayer());
1871 TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "RecalculateStyles", "elementCount", m_styleRecalcElementCounter);
1872 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1873 InspectorInstrumentation::didRecalculateStyle(cookie, m_styleRecalcElementCounter);
1876 void Document::updateStyle(StyleRecalcChange change)
1878 TRACE_EVENT0("webkit", "Document::updateStyle");
1880 ScriptForbiddenScope forbidScript;
1881 HTMLFrameOwnerElement::UpdateSuspendScope suspendWidgetHierarchyUpdates;
1882 m_lifecycle.advanceTo(DocumentLifecycle::InStyleRecalc);
1884 if (styleChangeType() >= SubtreeStyleChange)
1887 // FIXME: Cannot access the ensureStyleResolver() before calling styleForDocument below because
1888 // apparently the StyleResolver's constructor has side effects. We should fix it.
1889 // See printing/setPrinting.html, printing/width-overflow.html though they only fail on
1890 // mac when accessing the resolver by what appears to be a viewport size difference.
1892 if (change == Force) {
1893 m_hasNodesWithPlaceholderStyle = false;
1894 RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this);
1895 StyleRecalcChange localChange = RenderStyle::stylePropagationDiff(documentStyle.get(), renderView()->style());
1896 if (localChange != NoChange)
1897 renderView()->setStyle(documentStyle.release());
1900 clearNeedsStyleRecalc();
1902 // Uncomment to enable printing of statistics about style sharing and the matched property cache.
1903 // Optionally pass StyleResolver::ReportSlowStats to print numbers that require crawling the
1904 // entire DOM (where collecting them is very slow).
1905 // FIXME: Expose this as a runtime flag.
1906 // ensureStyleResolver().enableStats(/*StyleResolver::ReportSlowStats*/);
1908 if (StyleResolverStats* stats = ensureStyleResolver().stats())
1911 if (Element* documentElement = this->documentElement()) {
1912 inheritHtmlAndBodyElementStyles(change);
1913 dirtyElementsForLayerUpdate();
1914 if (documentElement->shouldCallRecalcStyle(change))
1915 documentElement->recalcStyle(change);
1916 while (dirtyElementsForLayerUpdate())
1917 documentElement->recalcStyle(NoChange);
1920 ensureStyleResolver().printStats();
1922 view()->recalcOverflowAfterStyleChange();
1923 view()->updateCompositingLayersAfterStyleChange();
1925 clearChildNeedsStyleRecalc();
1927 if (m_styleEngine->hasResolver()) {
1928 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1929 StyleResolver& resolver = m_styleEngine->ensureResolver();
1930 m_styleEngine->resetCSSFeatureFlags(resolver.ensureUpdatedRuleFeatureSet());
1931 resolver.clearStyleSharingList();
1934 ASSERT(!needsStyleRecalc());
1935 ASSERT(!childNeedsStyleRecalc());
1936 ASSERT(inStyleRecalc());
1937 m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
1940 void Document::updateRenderTreeForNodeIfNeeded(Node* node)
1942 bool needsRecalc = needsFullRenderTreeUpdate();
1944 for (const Node* ancestor = node; ancestor && !needsRecalc; ancestor = NodeRenderingTraversal::parent(ancestor))
1945 needsRecalc = ancestor->needsStyleRecalc() || ancestor->needsStyleInvalidation();
1948 updateRenderTreeIfNeeded();
1951 void Document::updateLayout()
1953 ASSERT(isMainThread());
1955 RefPtr<FrameView> frameView = view();
1956 if (frameView && frameView->isInPerformLayout()) {
1957 // View layout should not be re-entrant.
1958 ASSERT_NOT_REACHED();
1962 if (Element* oe = ownerElement())
1963 oe->document().updateLayout();
1965 updateRenderTreeIfNeeded();
1970 if (frameView->needsLayout())
1971 frameView->layout();
1973 if (lifecycle().state() < DocumentLifecycle::LayoutClean)
1974 lifecycle().advanceTo(DocumentLifecycle::LayoutClean);
1977 void Document::setNeedsFocusedElementCheck()
1979 setNeedsStyleRecalc(LocalStyleChange);
1982 void Document::clearFocusedElementSoon()
1984 if (!m_clearFocusedElementTimer.isActive())
1985 m_clearFocusedElementTimer.startOneShot(0, FROM_HERE);
1988 void Document::clearFocusedElementTimerFired(Timer<Document>*)
1990 updateRenderTreeIfNeeded();
1991 m_clearFocusedElementTimer.stop();
1993 if (m_focusedElement && !m_focusedElement->isFocusable())
1994 m_focusedElement->blur();
1997 // FIXME: This is a bad idea and needs to be removed eventually.
1998 // Other browsers load stylesheets before they continue parsing the web page.
1999 // Since we don't, we can run JavaScript code that needs answers before the
2000 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
2001 // lets us get reasonable answers. The long term solution to this problem is
2002 // to instead suspend JavaScript execution.
2003 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
2005 StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
2007 if (m_styleEngine->hasPendingSheets()) {
2008 // FIXME: We are willing to attempt to suppress painting with outdated style info only once.
2009 // Our assumption is that it would be dangerous to try to stop it a second time, after page
2010 // content has already been loaded and displayed with accurate style information. (Our
2011 // suppression involves blanking the whole page at the moment. If it were more refined, we
2012 // might be able to do something better.) It's worth noting though that this entire method
2013 // is a hack, since what we really want to do is suspend JS instead of doing a layout with
2014 // inaccurate information.
2015 HTMLElement* bodyElement = body();
2016 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
2017 m_pendingSheetLayout = DidLayoutWithPendingSheets;
2018 styleResolverChanged(RecalcStyleImmediately);
2019 } else if (m_hasNodesWithPlaceholderStyle) {
2020 // If new nodes have been added or style recalc has been done with style sheets still
2021 // pending, some nodes may not have had their real style calculated yet. Normally this
2022 // gets cleaned when style sheets arrive but here we need up-to-date style immediately.
2023 updateRenderTree(Force);
2029 if (runPostLayoutTasks == RunPostLayoutTasksSynchronously && view())
2030 view()->flushAnyPendingPostLayoutTasks();
2033 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
2035 ASSERT_ARG(element, element->document() == this);
2036 StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
2037 return ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
2040 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
2042 return ensureStyleResolver().styleForPage(pageIndex);
2045 bool Document::isPageBoxVisible(int pageIndex)
2047 return styleForPage(pageIndex)->visibility() != HIDDEN; // display property doesn't apply to @page.
2050 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2052 RefPtr<RenderStyle> style = styleForPage(pageIndex);
2054 int width = pageSize.width();
2055 int height = pageSize.height();
2056 switch (style->pageSizeType()) {
2057 case PAGE_SIZE_AUTO:
2059 case PAGE_SIZE_AUTO_LANDSCAPE:
2061 std::swap(width, height);
2063 case PAGE_SIZE_AUTO_PORTRAIT:
2065 std::swap(width, height);
2067 case PAGE_SIZE_RESOLVED: {
2068 LengthSize size = style->pageSize();
2069 ASSERT(size.width().isFixed());
2070 ASSERT(size.height().isFixed());
2071 width = valueForLength(size.width(), 0);
2072 height = valueForLength(size.height(), 0);
2076 ASSERT_NOT_REACHED();
2078 pageSize = IntSize(width, height);
2080 // The percentage is calculated with respect to the width even for margin top and bottom.
2081 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2082 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2083 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2084 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2085 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2088 void Document::setIsViewSource(bool isViewSource)
2090 m_isViewSource = isViewSource;
2091 if (!m_isViewSource)
2094 setSecurityOrigin(SecurityOrigin::createUnique());
2095 didUpdateSecurityOrigin();
2098 bool Document::dirtyElementsForLayerUpdate()
2100 if (m_layerUpdateElements.isEmpty())
2102 HashSet<Element*>::iterator end = m_layerUpdateElements.end();
2103 for (HashSet<Element*>::iterator it = m_layerUpdateElements.begin(); it != end; ++it)
2104 (*it)->setNeedsStyleRecalc(LocalStyleChange);
2105 m_layerUpdateElements.clear();
2109 void Document::scheduleLayerUpdate(Element& element)
2111 if (element.styleChangeType() == NeedsReattachStyleChange)
2113 element.setNeedsLayerUpdate();
2114 m_layerUpdateElements.add(&element);
2115 scheduleRenderTreeUpdateIfNeeded();
2118 void Document::unscheduleLayerUpdate(Element& element)
2120 element.clearNeedsLayerUpdate();
2121 m_layerUpdateElements.remove(&element);
2124 void Document::scheduleUseShadowTreeUpdate(SVGUseElement& element)
2126 m_useElementsNeedingUpdate.add(&element);
2127 scheduleRenderTreeUpdateIfNeeded();
2130 void Document::unscheduleUseShadowTreeUpdate(SVGUseElement& element)
2132 m_useElementsNeedingUpdate.remove(&element);
2135 void Document::updateUseShadowTreesIfNeeded()
2137 ScriptForbiddenScope forbidScript;
2139 if (m_useElementsNeedingUpdate.isEmpty())
2142 Vector<SVGUseElement*> elements;
2143 copyToVector(m_useElementsNeedingUpdate, elements);
2144 m_useElementsNeedingUpdate.clear();
2146 Vector<SVGUseElement*>::iterator end = elements.end();
2147 for (Vector<SVGUseElement*>::iterator it = elements.begin(); it != end; ++it)
2148 (*it)->buildPendingResource();
2151 StyleResolver* Document::styleResolver() const
2153 return m_styleEngine->resolver();
2156 StyleResolver& Document::ensureStyleResolver() const
2158 return m_styleEngine->ensureResolver();
2161 void Document::clearStyleResolver()
2163 m_styleEngine->clearResolver();
2166 void Document::attach(const AttachContext& context)
2168 ASSERT(m_lifecycle.state() == DocumentLifecycle::Inactive);
2169 ASSERT(!m_axObjectCache || this != topDocument());
2171 m_renderView = new RenderView(this);
2172 setRenderer(m_renderView);
2174 m_renderView->setIsInWindow(true);
2175 m_renderView->setStyle(StyleResolver::styleForDocument(*this));
2176 view()->updateCompositingLayersAfterStyleChange();
2178 ContainerNode::attach(context);
2180 // FastTextAutosizer can't update render view info while the Document is detached, so update now in case anything changed.
2181 if (FastTextAutosizer* textAutosizer = fastTextAutosizer())
2182 textAutosizer->updatePageInfo();
2184 m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
2187 void Document::detach(const AttachContext& context)
2190 m_lifecycle.advanceTo(DocumentLifecycle::Stopping);
2193 page()->documentDetached(this);
2194 InspectorInstrumentation::documentDetached(this);
2196 if (m_frame->loader().client()->sharedWorkerRepositoryClient())
2197 m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this);
2199 if (this == topDocument())
2200 clearAXObjectCache();
2202 stopActiveDOMObjects();
2204 // FIXME: consider using ActiveDOMObject.
2205 if (m_scriptedAnimationController)
2206 m_scriptedAnimationController->clearDocumentPointer();
2207 m_scriptedAnimationController.clear();
2209 if (svgExtensions())
2210 accessSVGExtensions().pauseAnimations();
2212 // FIXME: This shouldn't be needed once DOMWindow becomes ExecutionContext.
2214 m_domWindow->clearEventQueue();
2217 m_renderView->setIsInWindow(false);
2220 FrameView* view = m_frame->view();
2222 view->detachCustomScrollbars();
2225 m_hoverNode = nullptr;
2226 m_focusedElement = nullptr;
2227 m_activeHoverElement = nullptr;
2228 m_autofocusElement = nullptr;
2231 ContainerNode::detach(context);
2233 m_styleEngine->didDetach();
2235 if (Document* parentDoc = parentDocument())
2236 parentDoc->didClearTouchEventHandlers(this);
2238 // This is required, as our LocalFrame might delete itself as soon as it detaches
2239 // us. However, this violates Node::detach() semantics, as it's never
2240 // possible to re-attach. Eventually Document::detach() should be renamed,
2241 // or this setting of the frame to 0 could be made explicit in each of the
2242 // callers of Document::detach().
2245 if (m_mediaQueryMatcher)
2246 m_mediaQueryMatcher->documentDestroyed();
2248 lifecycleNotifier().notifyDocumentWasDetached();
2249 m_lifecycle.advanceTo(DocumentLifecycle::Stopped);
2251 // FIXME: Oilpan: With Oilpan dispose should not be needed. At
2252 // this point we still have dispose in order to clear out some
2253 // RefPtrs that would otherwise cause leaks. However, when the
2254 // Document is detached the document can still be alive, so we
2255 // really shouldn't clear anything at this point. It should just
2256 // die with the document when the document is no longer reachable.
2261 void Document::prepareForDestruction()
2263 m_markers->prepareForDestruction();
2264 disconnectDescendantFrames();
2266 // The process of disconnecting descendant frames could have already detached us.
2270 if (DOMWindow* window = this->domWindow())
2271 window->willDetachDocumentFromFrame();
2275 void Document::removeAllEventListeners()
2277 ContainerNode::removeAllEventListeners();
2279 if (DOMWindow* domWindow = this->domWindow())
2280 domWindow->removeAllEventListeners();
2283 void Document::clearAXObjectCache()
2285 ASSERT(topDocument() == this);
2286 // Clear the cache member variable before calling delete because attempts
2287 // are made to access it during destruction.
2288 m_axObjectCache.clear();
2291 AXObjectCache* Document::existingAXObjectCache() const
2293 if (!AXObjectCache::accessibilityEnabled())
2296 // If the renderer is gone then we are in the process of destruction.
2297 // This method will be called before m_frame = 0.
2298 if (!topDocument().renderView())
2301 return topDocument().m_axObjectCache.get();
2304 AXObjectCache* Document::axObjectCache() const
2306 if (!AXObjectCache::accessibilityEnabled())
2309 // The only document that actually has a AXObjectCache is the top-level
2310 // document. This is because we need to be able to get from any WebCoreAXObject
2311 // to any other WebCoreAXObject on the same page. Using a single cache allows
2312 // lookups across nested webareas (i.e. multiple documents).
2313 Document& topDocument = this->topDocument();
2315 // If the document has already been detached, do not make a new axObjectCache.
2316 if (!topDocument.renderView())
2319 ASSERT(topDocument == this || !m_axObjectCache);
2320 if (!topDocument.m_axObjectCache)
2321 topDocument.m_axObjectCache = adoptPtr(new AXObjectCache(topDocument));
2322 return topDocument.m_axObjectCache.get();
2325 PassRefPtr<DocumentParser> Document::createParser()
2327 if (isHTMLDocument()) {
2328 bool reportErrors = InspectorInstrumentation::collectingHTMLParseErrors(page());
2329 return HTMLDocumentParser::create(toHTMLDocument(this), reportErrors);
2331 // FIXME: this should probably pass the frame instead
2332 return XMLDocumentParser::create(this, view());
2335 bool Document::isFrameSet() const
2337 if (!isHTMLDocument())
2339 return isHTMLFrameSetElement(body());
2342 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2344 return parser() ? parser()->asScriptableDocumentParser() : 0;
2347 void Document::open(Document* ownerDocument, ExceptionState& exceptionState)
2349 if (importLoader()) {
2350 exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support open().");
2354 if (ownerDocument) {
2355 setURL(ownerDocument->url());
2356 m_cookieURL = ownerDocument->cookieURL();
2357 setSecurityOrigin(ownerDocument->securityOrigin());
2361 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2362 if (parser->isParsing()) {
2363 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2364 if (parser->isExecutingScript())
2367 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2372 if (m_frame->loader().state() == FrameStateProvisional)
2373 m_frame->loader().stopAllLoaders();
2376 removeAllEventListenersRecursively();
2378 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2379 parser->setWasCreatedByScript(true);
2382 m_frame->loader().didExplicitOpen();
2383 if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
2384 m_loadEventProgress = LoadEventNotRun;
2387 void Document::detachParser()
2395 void Document::cancelParsing()
2400 // We have to clear the parser to avoid possibly triggering
2401 // the onload handler when closing as a side effect of a cancel-style
2402 // change, such as opening a new document or closing the window while
2408 PassRefPtr<DocumentParser> Document::implicitOpen()
2413 ASSERT(!m_focusedElement);
2415 setCompatibilityMode(NoQuirksMode);
2417 m_parser = createParser();
2419 setReadyState(Loading);
2424 HTMLElement* Document::body() const
2426 if (!documentElement())
2429 for (HTMLElement* child = Traversal<HTMLElement>::firstWithin(*documentElement()); child; child = Traversal<HTMLElement>::nextSibling(*child)) {
2430 if (isHTMLFrameSetElement(*child) || isHTMLBodyElement(*child))
2437 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionState& exceptionState)
2439 RefPtr<HTMLElement> newBody = prpNewBody;
2442 exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::argumentNullOrIncorrectType(1, "HTMLElement"));
2445 if (!documentElement()) {
2446 exceptionState.throwDOMException(HierarchyRequestError, "No document element exists.");
2450 if (!isHTMLBodyElement(*newBody) && !isHTMLFrameSetElement(*newBody)) {
2451 exceptionState.throwDOMException(HierarchyRequestError, "The new body element is of type '" + newBody->tagName() + "'. It must be either a 'BODY' or 'FRAMESET' element.");
2455 HTMLElement* oldBody = body();
2456 if (oldBody == newBody)
2460 documentElement()->replaceChild(newBody.release(), oldBody, exceptionState);
2462 documentElement()->appendChild(newBody.release(), exceptionState);
2465 HTMLHeadElement* Document::head()
2467 Node* de = documentElement();
2471 return Traversal<HTMLHeadElement>::firstChild(*de);
2474 Element* Document::viewportDefiningElement(RenderStyle* rootStyle) const
2476 // If a BODY element sets non-visible overflow, it is to be propagated to the viewport, as long
2477 // as the following conditions are all met:
2478 // (1) The root element is HTML.
2479 // (2) It is the primary BODY element (we only assert for this, expecting callers to behave).
2480 // (3) The root element has visible overflow.
2481 // Otherwise it's the root element's properties that are to be propagated.
2482 Element* rootElement = documentElement();
2483 Element* bodyElement = body();
2487 rootStyle = rootElement->renderStyle();
2491 if (bodyElement && rootStyle->isOverflowVisible() && isHTMLHtmlElement(*rootElement))
2496 void Document::close(ExceptionState& exceptionState)
2498 // FIXME: We should follow the specification more closely:
2499 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2501 if (importLoader()) {
2502 exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support close().");
2506 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2512 void Document::explicitClose()
2514 if (RefPtr<DocumentParser> parser = m_parser)
2518 // Because we have no frame, we don't know if all loading has completed,
2519 // so we just call implicitClose() immediately. FIXME: This might fire
2520 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2525 m_frame->loader().checkCompleted();
2528 void Document::implicitClose()
2530 ASSERT(!inStyleRecalc());
2532 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2533 bool doload = !parsing() && m_parser && !processingLoadEvent() && !wasLocationChangePending;
2535 // If the load was blocked because of a pending location change and the location change triggers a same document
2536 // navigation, don't fire load events after the same document navigation completes (unless there's an explicit open).
2537 m_loadEventProgress = LoadEventTried;
2542 // The call to dispatchWindowLoadEvent can detach the DOMWindow and cause it (and its
2543 // attached Document) to be destroyed.
2544 RefPtrWillBeRawPtr<DOMWindow> protectedWindow(this->domWindow());
2546 m_loadEventProgress = LoadEventInProgress;
2548 ScriptableDocumentParser* parser = scriptableDocumentParser();
2549 m_wellFormed = parser && parser->wellFormed();
2551 // We have to clear the parser, in case someone document.write()s from the
2552 // onLoad event handler, as in Radar 3206524.
2555 if (frame() && frame()->script().canExecuteScripts(NotAboutToExecuteScript)) {
2556 ImageLoader::dispatchPendingLoadEvents();
2557 ImageLoader::dispatchPendingErrorEvents();
2559 HTMLLinkElement::dispatchPendingLoadEvents();
2560 HTMLStyleElement::dispatchPendingLoadEvents();
2563 // JS running below could remove the frame or destroy the RenderView so we call
2564 // those two functions repeatedly and don't save them on the stack.
2566 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2567 // here, instead of doing it from SVGElement::finishedParsingChildren.
2568 if (svgExtensions())
2569 accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2571 if (protectedWindow)
2572 protectedWindow->documentWasClosed();
2575 frame()->loader().client()->dispatchDidHandleOnloadEvents();
2576 loader()->applicationCacheHost()->stopDeferringEvents();
2580 m_loadEventProgress = LoadEventCompleted;
2584 // Make sure both the initial layout and reflow happen after the onload
2585 // fires. This will improve onload scores, and other browsers do it.
2586 // If they wanna cheat, we can too. -dwh
2588 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2589 // Just bail out. Before or during the onload we were shifted to another page.
2590 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2591 m_loadEventProgress = LoadEventCompleted;
2595 // We used to force a synchronous display and flush here. This really isn't
2596 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2597 // (if your platform is syncing flushes and limiting them to 60fps).
2598 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2599 updateRenderTreeIfNeeded();
2601 // Always do a layout after loading if needed.
2602 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2606 m_loadEventProgress = LoadEventCompleted;
2608 if (frame() && renderView() && AXObjectCache::accessibilityEnabled()) {
2609 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2610 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2611 // exists in the cache (we ignore the return value because we don't need it here). This is
2612 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2613 if (AXObjectCache* cache = axObjectCache()) {
2614 cache->getOrCreate(renderView());
2615 if (this == topDocument()) {
2616 cache->postNotification(renderView(), AXObjectCache::AXLoadComplete, true);
2618 // AXLoadComplete can only be posted on the top document, so if it's a document
2619 // in an iframe that just finished loading, post AXLayoutComplete instead.
2620 cache->postNotification(renderView(), AXObjectCache::AXLayoutComplete, true);
2625 if (svgExtensions())
2626 accessSVGExtensions().startAnimations();
2629 bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigation)
2637 RefPtr<Document> protect(this);
2639 RefPtrWillBeRawPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2640 m_loadEventProgress = BeforeUnloadEventInProgress;
2641 m_domWindow->dispatchEvent(beforeUnloadEvent.get(), this);
2642 m_loadEventProgress = BeforeUnloadEventCompleted;
2643 if (!beforeUnloadEvent->defaultPrevented())
2644 defaultEventHandler(beforeUnloadEvent.get());
2645 if (beforeUnloadEvent->returnValue().isNull())
2648 if (didAllowNavigation) {
2649 addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation.");
2653 String text = beforeUnloadEvent->returnValue();
2654 if (chrome.runBeforeUnloadConfirmPanel(text, m_frame)) {
2655 didAllowNavigation = true;
2661 void Document::dispatchUnloadEvents()
2663 RefPtr<Document> protect(this);
2665 m_parser->stopParsing();
2667 if (m_loadEventProgress >= LoadEventTried && m_loadEventProgress <= UnloadEventInProgress) {
2668 Element* currentFocusedElement = focusedElement();
2669 if (isHTMLInputElement(currentFocusedElement))
2670 toHTMLInputElement(*currentFocusedElement).endEditing();
2671 if (m_loadEventProgress < PageHideInProgress) {
2672 m_loadEventProgress = PageHideInProgress;
2673 if (DOMWindow* window = domWindow())
2674 window->dispatchEvent(PageTransitionEvent::create(EventTypeNames::pagehide, false), this);
2678 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
2679 // while dispatching the event, so protect it to prevent writing the end
2680 // time into freed memory.
2681 RefPtr<DocumentLoader> documentLoader = m_frame->loader().provisionalDocumentLoader();
2682 m_loadEventProgress = UnloadEventInProgress;
2683 RefPtrWillBeRawPtr<Event> unloadEvent(Event::create(EventTypeNames::unload));
2684 if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
2685 DocumentLoadTiming* timing = documentLoader->timing();
2686 ASSERT(timing->navigationStart());
2687 timing->markUnloadEventStart();
2688 m_frame->domWindow()->dispatchEvent(unloadEvent, this);
2689 timing->markUnloadEventEnd();
2691 m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
2694 m_loadEventProgress = UnloadEventHandled;
2700 // Don't remove event listeners from a transitional empty document (see https://bugs.webkit.org/show_bug.cgi?id=28716 for more information).
2701 bool keepEventListeners = m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader().provisionalDocumentLoader()
2702 && isSecureTransitionTo(m_frame->loader().provisionalDocumentLoader()->url());
2703 if (!keepEventListeners)
2704 removeAllEventListenersRecursively();
2707 Document::PageDismissalType Document::pageDismissalEventBeingDispatched() const
2709 if (m_loadEventProgress == BeforeUnloadEventInProgress)
2710 return BeforeUnloadDismissal;
2711 if (m_loadEventProgress == PageHideInProgress)
2712 return PageHideDismissal;
2713 if (m_loadEventProgress == UnloadEventInProgress)
2714 return UnloadDismissal;
2718 void Document::setParsing(bool b)
2722 if (m_isParsing && !m_elementDataCache)
2723 m_elementDataCache = ElementDataCache::create();
2726 bool Document::shouldScheduleLayout() const
2728 // This function will only be called when FrameView thinks a layout is needed.
2729 // This enforces a couple extra rules.
2731 // (a) Only schedule a layout once the stylesheets are loaded.
2732 // (b) Only schedule layout once we have a body element.
2736 if (isRenderingReady() && body())
2739 if (documentElement() && !isHTMLHtmlElement(*documentElement()))
2745 int Document::elapsedTime() const
2747 return static_cast<int>((currentTime() - m_startTime) * 1000);
2750 void Document::write(const SegmentedString& text, Document* ownerDocument, ExceptionState& exceptionState)
2752 if (importLoader()) {
2753 exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support write().");
2757 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2759 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2760 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2762 if (m_writeRecursionIsTooDeep)
2765 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2767 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount) {
2768 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."));
2772 if (!hasInsertionPoint)
2773 open(ownerDocument);
2776 m_parser->insert(text);
2779 void Document::write(const String& text, Document* ownerDocument, ExceptionState& exceptionState)
2781 write(SegmentedString(text), ownerDocument, exceptionState);
2784 void Document::writeln(const String& text, Document* ownerDocument, ExceptionState& exceptionState)
2786 write(text, ownerDocument, exceptionState);
2787 if (exceptionState.hadException())
2789 write("\n", ownerDocument);
2792 const KURL& Document::virtualURL() const
2797 KURL Document::virtualCompleteURL(const String& url) const
2799 return completeURL(url);
2802 double Document::timerAlignmentInterval() const
2806 return DOMTimer::visiblePageAlignmentInterval();
2807 return p->timerAlignmentInterval();
2810 EventTarget* Document::errorEventTarget()
2815 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
2817 internalAddMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack, 0);
2820 void Document::setURL(const KURL& url)
2822 const KURL& newURL = url.isEmpty() ? blankURL() : url;
2823 if (newURL == m_url)
2828 contextFeatures().urlDidChange(this);
2831 void Document::updateBaseURL()
2833 KURL oldBaseURL = m_baseURL;
2834 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2835 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2836 // from the Document interface otherwise (which we store, preparsed, in m_url).
2837 if (!m_baseElementURL.isEmpty())
2838 m_baseURL = m_baseElementURL;
2839 else if (!m_baseURLOverride.isEmpty())
2840 m_baseURL = m_baseURLOverride;
2844 selectorQueryCache().invalidate();
2846 if (!m_baseURL.isValid())
2850 // Element sheet is silly. It never contains anything.
2851 ASSERT(!m_elemSheet->contents()->ruleCount());
2852 bool usesRemUnits = m_elemSheet->contents()->usesRemUnits();
2853 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2854 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2855 m_elemSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
2858 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2859 // Base URL change changes any relative visited links.
2860 // 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.
2861 for (HTMLAnchorElement* anchor = Traversal<HTMLAnchorElement>::firstWithin(*this); anchor; anchor = Traversal<HTMLAnchorElement>::next(*anchor))
2862 anchor->invalidateCachedVisitedLinkHash();
2866 void Document::setBaseURLOverride(const KURL& url)
2868 m_baseURLOverride = url;
2872 void Document::processBaseElement()
2874 // Find the first href attribute in a base element and the first target attribute in a base element.
2875 const AtomicString* href = 0;
2876 const AtomicString* target = 0;
2877 for (HTMLBaseElement* base = Traversal<HTMLBaseElement>::firstWithin(*this); base && (!href || !target); base = Traversal<HTMLBaseElement>::next(*base)) {
2879 const AtomicString& value = base->fastGetAttribute(hrefAttr);
2880 if (!value.isNull())
2884 const AtomicString& value = base->fastGetAttribute(targetAttr);
2885 if (!value.isNull())
2888 if (contentSecurityPolicy()->isActive())
2889 UseCounter::count(*this, UseCounter::ContentSecurityPolicyWithBaseElement);
2892 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2893 KURL baseElementURL;
2895 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2896 if (!strippedHref.isEmpty())
2897 baseElementURL = KURL(url(), strippedHref);
2899 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
2900 m_baseElementURL = baseElementURL;
2904 m_baseTarget = target ? *target : nullAtom;
2907 String Document::userAgent(const KURL& url) const
2909 return frame() ? frame()->loader().userAgent(url) : String();
2912 void Document::disableEval(const String& errorMessage)
2917 frame()->script().disableEval(errorMessage);
2920 bool Document::canNavigate(LocalFrame* targetFrame)
2925 // FIXME: We shouldn't call this function without a target frame, but
2926 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2927 // returning true when supplied with a 0 targetFrame.
2931 // LocalFrame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
2932 if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
2935 if (isSandboxed(SandboxNavigation)) {
2936 if (targetFrame->tree().isDescendantOf(m_frame))
2939 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
2940 if (isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
2941 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
2943 printNavigationErrorMessage(*targetFrame, url(), reason);
2947 ASSERT(securityOrigin());
2948 SecurityOrigin& origin = *securityOrigin();
2950 // This is the normal case. A document can navigate its decendant frames,
2951 // or, more generally, a document can navigate a frame if the document is
2952 // in the same origin as any of that frame's ancestors (in the frame
2955 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2956 // historical information about this security check.
2957 if (canAccessAncestor(origin, targetFrame))
2960 // Top-level frames are easier to navigate than other frames because they
2961 // display their URLs in the address bar (in most browsers). However, there
2962 // are still some restrictions on navigation to avoid nuisance attacks.
2963 // Specifically, a document can navigate a top-level frame if that frame
2964 // opened the document or if the document is the same-origin with any of
2965 // the top-level frame's opener's ancestors (in the frame hierarchy).
2967 // In both of these cases, the document performing the navigation is in
2968 // some way related to the frame being navigate (e.g., by the "opener"
2969 // and/or "parent" relation). Requiring some sort of relation prevents a
2970 // document from navigating arbitrary, unrelated top-level frames.
2971 if (!targetFrame->tree().parent()) {
2972 if (targetFrame == m_frame->loader().opener())
2975 if (canAccessAncestor(origin, targetFrame->loader().opener()))
2979 printNavigationErrorMessage(*targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
2983 LocalFrame* Document::findUnsafeParentScrollPropagationBoundary()
2985 LocalFrame* currentFrame = m_frame;
2986 LocalFrame* ancestorFrame = currentFrame->tree().parent();
2988 while (ancestorFrame) {
2989 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
2990 return currentFrame;
2991 currentFrame = ancestorFrame;
2992 ancestorFrame = ancestorFrame->tree().parent();
2997 void Document::didLoadAllImports()
2999 if (!haveStylesheetsLoaded())
3001 if (!importLoader())
3002 styleResolverMayHaveChanged();
3003 didLoadAllScriptBlockingResources();
3006 void Document::didRemoveAllPendingStylesheet()
3008 m_needsNotifyRemoveAllPendingStylesheet = false;
3010 styleResolverMayHaveChanged();
3012 // Only imports on master documents can trigger rendering.
3013 if (HTMLImportLoader* import = importLoader())
3014 import->didRemoveAllPendingStylesheet();
3015 if (!haveImportsLoaded())
3017 didLoadAllScriptBlockingResources();
3020 void Document::didLoadAllScriptBlockingResources()
3022 executeScriptsWaitingForResourcesIfNeeded();
3024 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
3025 view()->scrollToFragment(m_url);
3029 void Document::executeScriptsWaitingForResourcesIfNeeded()
3031 if (!isRenderingReady())
3033 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
3034 parser->executeScriptsWaitingForResources();
3038 CSSStyleSheet& Document::elementSheet()
3041 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
3042 return *m_elemSheet;
3045 void Document::processHttpEquiv(const AtomicString& equiv, const AtomicString& content, bool inDocumentHeadElement)
3047 ASSERT(!equiv.isNull() && !content.isNull());
3049 if (equalIgnoringCase(equiv, "default-style")) {
3050 processHttpEquivDefaultStyle(content);
3051 } else if (equalIgnoringCase(equiv, "refresh")) {
3052 processHttpEquivRefresh(content);
3053 } else if (equalIgnoringCase(equiv, "set-cookie")) {
3054 processHttpEquivSetCookie(content);
3055 } else if (equalIgnoringCase(equiv, "content-language")) {
3056 setContentLanguage(content);
3057 } else if (equalIgnoringCase(equiv, "x-dns-prefetch-control")) {
3058 parseDNSPrefetchControlHeader(content);
3059 } else if (equalIgnoringCase(equiv, "x-frame-options")) {
3060 processHttpEquivXFrameOptions(content);
3061 } else if (equalIgnoringCase(equiv, "content-security-policy") || equalIgnoringCase(equiv, "content-security-policy-report-only")) {
3062 if (inDocumentHeadElement)
3063 processHttpEquivContentSecurityPolicy(equiv, content);
3065 contentSecurityPolicy()->reportMetaOutsideHead(content);
3069 void Document::processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content)
3073 if (equalIgnoringCase(equiv, "content-security-policy"))
3074 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeEnforce, ContentSecurityPolicyHeaderSourceMeta);
3075 else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
3076 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeReport, ContentSecurityPolicyHeaderSourceMeta);
3078 ASSERT_NOT_REACHED();
3081 void Document::processHttpEquivDefaultStyle(const AtomicString& content)
3083 // The preferred style set has been overridden as per section
3084 // 14.3.2 of the HTML4.0 specification. We need to update the
3085 // sheet used variable and then update our style selector.
3086 // For more info, see the test at:
3087 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3089 m_styleEngine->setSelectedStylesheetSetName(content);
3090 m_styleEngine->setPreferredStylesheetSetName(content);
3091 styleResolverChanged(RecalcStyleDeferred);
3094 void Document::processHttpEquivRefresh(const AtomicString& content)
3096 maybeHandleHttpRefresh(content, HttpRefreshFromMetaTag);
3099 void Document::maybeHandleHttpRefresh(const String& content, HttpRefreshType httpRefreshType)
3101 if (m_isViewSource || !m_frame)
3106 if (!parseHTTPRefresh(content, httpRefreshType == HttpRefreshFromMetaTag, delay, refreshURL))
3108 if (refreshURL.isEmpty())
3109 refreshURL = url().string();
3111 refreshURL = completeURL(refreshURL).string();
3113 if (protocolIsJavaScript(refreshURL)) {
3114 String message = "Refused to refresh " + m_url.elidedString() + " to a javascript: URL";
3115 addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
3119 if (httpRefreshType == HttpRefreshFromMetaTag && isSandboxed(SandboxAutomaticFeatures)) {
3120 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.";
3121 addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
3124 m_frame->navigationScheduler().scheduleRedirect(delay, refreshURL);
3127 void Document::processHttpEquivSetCookie(const AtomicString& content)
3129 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3130 if (!isHTMLDocument())
3133 // Exception (for sandboxed documents) ignored.
3134 toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
3137 void Document::processHttpEquivXFrameOptions(const AtomicString& content)
3139 LocalFrame* frame = this->frame();
3143 FrameLoader& frameLoader = frame->loader();
3144 unsigned long requestIdentifier = loader()->mainResourceIdentifier();
3145 if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
3146 String message = "Refused to display '" + url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
3147 frameLoader.stopAllLoaders();
3148 // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
3149 // intent, we must navigate away from the possibly partially-rendered document to a location that
3150 // doesn't inherit the parent's SecurityOrigin.
3151 frame->navigationScheduler().scheduleLocationChange(this, SecurityOrigin::urlWithUniqueSecurityOrigin(), Referrer());
3152 addConsoleMessageWithRequestIdentifier(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
3156 bool Document::shouldMergeWithLegacyDescription(ViewportDescription::Type origin)
3158 return settings() && settings()->viewportMetaMergeContentQuirk() && m_legacyViewportDescription.isMetaViewportType() && m_legacyViewportDescription.type == origin;
3161 void Document::setViewportDescription(const ViewportDescription& viewportDescription)
3163 // The UA-defined min-width is used by the processing of legacy meta tags.
3164 if (!viewportDescription.isSpecifiedByAuthor())
3165 m_viewportDefaultMinWidth = viewportDescription.minWidth;
3167 if (viewportDescription.isLegacyViewportType()) {
3168 if (settings() && !settings()->viewportMetaEnabled())
3171 m_legacyViewportDescription = viewportDescription;
3173 // When no author style for @viewport is present, and a meta tag for defining
3174 // the viewport is, apply the meta tag viewport instead of the UA styles.
3175 if (m_viewportDescription.type == ViewportDescription::AuthorStyleSheet)
3177 m_viewportDescription = viewportDescription;
3179 // If the legacy viewport tag has higher priority than the cascaded @viewport
3180 // descriptors, use the values from the legacy tag.
3181 if (!shouldOverrideLegacyDescription(viewportDescription.type))
3182 m_viewportDescription = m_legacyViewportDescription;
3184 m_viewportDescription = viewportDescription;
3187 updateViewportDescription();
3190 void Document::updateViewportDescription()
3192 if (frame() && frame()->isMainFrame()) {
3194 m_didDispatchViewportPropertiesChanged = true;
3196 frameHost()->chrome().dispatchViewportPropertiesDidChange(m_viewportDescription);
3200 void Document::processReferrerPolicy(const String& policy)
3202 ASSERT(!policy.isNull());
3204 if (equalIgnoringCase(policy, "never")) {
3205 setReferrerPolicy(ReferrerPolicyNever);
3206 } else if (equalIgnoringCase(policy, "always")) {
3207 setReferrerPolicy(ReferrerPolicyAlways);
3208 } else if (equalIgnoringCase(policy, "origin")) {
3209 setReferrerPolicy(ReferrerPolicyOrigin);
3210 } else if (equalIgnoringCase(policy, "default")) {
3211 setReferrerPolicy(ReferrerPolicyDefault);
3213 addConsoleMessage(RenderingMessageSource, ErrorMessageLevel, "Failed to set referrer policy: The value '" + policy + "' is not one of 'always', 'default', 'never', or 'origin'. Defaulting to 'never'.");
3214 setReferrerPolicy(ReferrerPolicyNever);
3218 void Document::setReferrerPolicy(ReferrerPolicy referrerPolicy)
3220 // 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?
3221 if (m_didSetReferrerPolicy)
3222 UseCounter::count(this, UseCounter::ResetReferrerPolicy);
3223 m_didSetReferrerPolicy = true;
3225 m_referrerPolicy = referrerPolicy;
3228 String Document::outgoingReferrer()
3230 // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
3231 // for why we walk the parent chain for srcdoc documents.
3232 Document* referrerDocument = this;
3233 if (LocalFrame* frame = m_frame) {
3234 while (frame->document()->isSrcdocDocument()) {
3235 frame = frame->tree().parent();
3236 // Srcdoc documents cannot be top-level documents, by definition,
3237 // because they need to be contained in iframes with the srcdoc.
3240 referrerDocument = frame->document();
3242 return referrerDocument->m_url.strippedForUseAsReferrer();
3245 String Document::outgoingOrigin() const
3247 return securityOrigin()->toString();
3250 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3252 ASSERT(!renderView() || renderView()->isRenderView());
3254 // RenderView::hitTest causes a layout, and we don't want to hit that until the first
3255 // layout because until then, there is nothing shown on the screen - the user can't
3256 // have intentionally clicked on something belonging to this page. Furthermore,
3257 // mousemove events before the first layout should not lead to a premature layout()
3258 // happening, which could show a flash of white.
3259 // See also the similar code in EventHandler::hitTestResultAtPoint.
3260 if (!renderView() || !view() || !view()->didFirstLayout())
3261 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3263 HitTestResult result(documentPoint);
3264 renderView()->hitTest(request, result);
3266 if (!request.readOnly())
3267 updateHoverActiveState(request, result.innerElement(), &event);
3269 return MouseEventWithHitTestResults(event, result);
3272 // DOM Section 1.1.1
3273 bool Document::childTypeAllowed(NodeType type) const
3276 case ATTRIBUTE_NODE:
3277 case CDATA_SECTION_NODE:
3278 case DOCUMENT_FRAGMENT_NODE:
3283 case PROCESSING_INSTRUCTION_NODE:
3285 case DOCUMENT_TYPE_NODE:
3287 // Documents may contain no more than one of each of these.
3288 // (One Element and one DocumentType.)
3289 for (Node* c = firstChild(); c; c = c->nextSibling())
3290 if (c->nodeType() == type)
3297 bool Document::canReplaceChild(const Node& newChild, const Node& oldChild) const
3299 if (oldChild.nodeType() == newChild.nodeType())
3302 int numDoctypes = 0;
3303 int numElements = 0;
3305 // First, check how many doctypes and elements we have, not counting
3306 // the child we're about to remove.
3307 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3311 switch (c->nodeType()) {
3312 case DOCUMENT_TYPE_NODE:
3323 // Then, see how many doctypes and elements might be added by the new child.
3324 if (newChild.nodeType() == DOCUMENT_FRAGMENT_NODE) {
3325 for (Node* c = newChild.firstChild(); c; c = c->nextSibling()) {
3326 switch (c->nodeType()) {
3327 case ATTRIBUTE_NODE:
3328 case CDATA_SECTION_NODE:
3329 case DOCUMENT_FRAGMENT_NODE:
3334 case PROCESSING_INSTRUCTION_NODE:
3336 case DOCUMENT_TYPE_NODE:
3345 switch (newChild.nodeType()) {
3346 case ATTRIBUTE_NODE:
3347 case CDATA_SECTION_NODE:
3348 case DOCUMENT_FRAGMENT_NODE:
3353 case PROCESSING_INSTRUCTION_NODE:
3355 case DOCUMENT_TYPE_NODE:
3364 if (numElements > 1 || numDoctypes > 1)
3370 PassRefPtr<Node> Document::cloneNode(bool deep)
3372 RefPtr<Document> clone = cloneDocumentWithoutChildren();
3373 clone->cloneDataFromDocument(*this);
3375 cloneChildNodes(clone.get());
3376 return clone.release();
3379 PassRefPtr<Document> Document::cloneDocumentWithoutChildren()
3381 DocumentInit init(url());
3382 if (isXMLDocument()) {
3383 if (isXHTMLDocument())
3384 return XMLDocument::createXHTML(init.withRegistrationContext(registrationContext()));
3385 return XMLDocument::create(init);
3387 return create(init);
3390 void Document::cloneDataFromDocument(const Document& other)
3392 setCompatibilityMode(other.compatibilityMode());
3393 setEncodingData(other.m_encodingData);
3394 setContextFeatures(other.contextFeatures());
3395 setSecurityOrigin(other.securityOrigin()->isolatedCopy());
3396 setMimeType(other.contentType());
3399 StyleSheetList* Document::styleSheets()
3401 if (!m_styleSheetList)
3402 m_styleSheetList = StyleSheetList::create(this);
3403 return m_styleSheetList.get();
3406 String Document::preferredStylesheetSet() const
3408 return m_styleEngine->preferredStylesheetSetName();
3411 String Document::selectedStylesheetSet() const
3413 return m_styleEngine->selectedStylesheetSetName();
3416 void Document::setSelectedStylesheetSet(const String& aString)
3418 m_styleEngine->setSelectedStylesheetSetName(aString);
3419 styleResolverChanged(RecalcStyleDeferred);
3422 void Document::evaluateMediaQueryListIfNeeded()
3424 if (!m_evaluateMediaQueriesOnStyleRecalc)
3426 evaluateMediaQueryList();
3427 m_evaluateMediaQueriesOnStyleRecalc = false;
3430 void Document::evaluateMediaQueryList()
3432 if (m_mediaQueryMatcher)
3433 m_mediaQueryMatcher->styleResolverChanged();
3436 void Document::notifyResizeForViewportUnits()
3438 if (!hasViewportUnits())
3440 ensureStyleResolver().notifyResizeForViewportUnits();
3441 setNeedsStyleRecalcForViewportUnits();
3444 void Document::styleResolverChanged(RecalcStyleTime updateTime, StyleResolverUpdateMode updateMode)
3446 // styleResolverChanged() can be invoked during Document destruction.
3447 // We just skip that case.
3451 StyleResolverChange change = m_styleEngine->resolverChanged(updateTime, updateMode);
3452 if (change.needsRepaint()) {
3453 // We need to manually repaint because we avoid doing all repaints in layout or style
3454 // recalc while sheets are still loading to avoid FOUC.
3455 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3456 renderView()->repaintViewAndCompositedLayers();
3459 if (!change.needsStyleRecalc())
3462 m_evaluateMediaQueriesOnStyleRecalc = true;
3463 setNeedsStyleRecalc(SubtreeStyleChange);
3465 if (updateTime == RecalcStyleImmediately)
3466 updateRenderTreeIfNeeded();
3469 void Document::styleResolverMayHaveChanged()
3471 styleResolverChanged(RecalcStyleDeferred, hasNodesWithPlaceholderStyle() ? FullStyleUpdate : AnalyzedStyleUpdate);
3474 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
3476 m_hoverNode = newHoverNode;
3479 void Document::setActiveHoverElement(PassRefPtr<Element> newActiveElement)
3481 if (!newActiveElement) {
3482 m_activeHoverElement.clear();
3486 m_activeHoverElement = newActiveElement;
3489 void Document::removeFocusedElementOfSubtree(Node* node, bool amongChildrenOnly)
3491 if (!m_focusedElement)
3494 // We can't be focused if we're not in the document.
3495 if (!node->inDocument())
3497 bool contains = node->containsIncludingShadowDOM(m_focusedElement.get());
3498 if (contains && (m_focusedElement != node || !amongChildrenOnly))
3499 setFocusedElement(nullptr);
3502 void Document::hoveredNodeDetached(Node* node)
3507 if (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != NodeRenderingTraversal::parent(m_hoverNode.get())))
3510 m_hoverNode = NodeRenderingTraversal::parent(node);
3511 while (m_hoverNode && !m_hoverNode->renderer())
3512 m_hoverNode = NodeRenderingTraversal::parent(m_hoverNode.get());
3514 // If the mouse cursor is not visible, do not clear existing
3515 // hover effects on the ancestors of |node| and do not invoke
3516 // new hover effects on any other element.
3517 if (!page()->isCursorVisible())
3521 frame()->eventHandler().scheduleHoverStateUpdate();
3524 void Document::activeChainNodeDetached(Node* node)
3526 if (!m_activeHoverElement)
3529 if (node != m_activeHoverElement && (!m_activeHoverElement->isTextNode() || node != NodeRenderingTraversal::parent(m_activeHoverElement.get())))
3532 Node* activeNode = NodeRenderingTraversal::parent(node);
3533 while (activeNode && activeNode->isElementNode() && !activeNode->renderer())
3534 activeNode = NodeRenderingTraversal::parent(activeNode);
3536 m_activeHoverElement = activeNode && activeNode->isElementNode() ? toElement(activeNode) : 0;
3539 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3541 return m_annotatedRegions;
3544 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3546 m_annotatedRegions = regions;
3547 setAnnotatedRegionsDirty(false);
3550 bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusType type)
3552 m_clearFocusedElementTimer.stop();
3554 RefPtr<Element> newFocusedElement = prpNewFocusedElement;
3556 // Make sure newFocusedNode is actually in this document
3557 if (newFocusedElement && (newFocusedElement->document() != this))
3560 if (NodeChildRemovalTracker::isBeingRemoved(newFocusedElement.get()))
3563 if (m_focusedElement == newFocusedElement)
3566 bool focusChangeBlocked = false;
3567 RefPtrWillBeRawPtr<Element> oldFocusedElement = m_focusedElement;
3568 m_focusedElement = nullptr;
3570 // Remove focus from the existing focus node (if any)
3571 if (oldFocusedElement) {
3572 ASSERT(!oldFocusedElement->inDetach());
3574 if (oldFocusedElement->active())
3575 oldFocusedElement->setActive(false);
3577 oldFocusedElement->setFocus(false);
3579 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3580 // If page lost focus, blur event will have already been dispatched
3581 if (page() && (page()->focusController().isFocused())) {
3582 oldFocusedElement->dispatchBlurEvent(newFocusedElement.get());
3584 if (m_focusedElement) {
3585 // handler shifted focus
3586 focusChangeBlocked = true;
3587 newFocusedElement = nullptr;
3590 oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::focusout, newFocusedElement.get()); // DOM level 3 name for the bubbling blur event.
3591 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3592 // on it, probably when <rdar://problem/8503958> is resolved.
3593 oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, newFocusedElement.get()); // DOM level 2 name for compatibility.
3595 if (m_focusedElement) {
3596 // handler shifted focus
3597 focusChangeBlocked = true;
3598 newFocusedElement = nullptr;
3603 Widget* oldWidget = widgetForElement(*oldFocusedElement);
3605 oldWidget->setFocus(false);
3607 view()->setFocus(false);
3611 if (newFocusedElement && newFocusedElement->isFocusable()) {
3612 if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(*newFocusedElement)) {
3613 // delegate blocks focus change
3614 focusChangeBlocked = true;
3615 goto SetFocusedElementDone;
3617 // Set focus on the new node
3618 m_focusedElement = newFocusedElement;
3620 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3621 // If page lost focus, event will be dispatched on page focus, don't duplicate
3622 if (page() && (page()->focusController().isFocused())) {
3623 m_focusedElement->dispatchFocusEvent(oldFocusedElement.get(), type);
3626 if (m_focusedElement != newFocusedElement) {
3627 // handler shifted focus
3628 focusChangeBlocked = true;
3629 goto SetFocusedElementDone;
3632 m_focusedElement->dispatchFocusInEvent(EventTypeNames::focusin, oldFocusedElement.get()); // DOM level 3 bubbling focus event.
3634 if (m_focusedElement != newFocusedElement) {
3635 // handler shifted focus
3636 focusChangeBlocked = true;
3637 goto SetFocusedElementDone;
3640 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3641 // on it, probably when <rdar://problem/8503958> is m.
3642 m_focusedElement->dispatchFocusInEvent(EventTypeNames::DOMFocusIn, oldFocusedElement.get()); // DOM level 2 for compatibility.
3644 if (m_focusedElement != newFocusedElement) {
3645 // handler shifted focus
3646 focusChangeBlocked = true;
3647 goto SetFocusedElementDone;
3651 m_focusedElement->setFocus(true);
3653 if (m_focusedElement->isRootEditableElement())
3654 frame()->spellChecker().didBeginEditing(m_focusedElement.get());
3656 // eww, I suck. set the qt focus correctly
3657 // ### find a better place in the code for this
3659 Widget* focusWidget = widgetForElement(*m_focusedElement);
3661 // Make sure a widget has the right size before giving it focus.
3662 // Otherwise, we are testing edge cases of the Widget code.
3663 // Specifically, in WebCore this does not work well for text fields.
3665 // Re-get the widget in case updating the layout changed things.
3666 focusWidget = widgetForElement(*m_focusedElement);
3669 focusWidget->setFocus(true);
3671 view()->setFocus(true);
3675 if (!focusChangeBlocked && m_focusedElement) {
3676 // Create the AXObject cache in a focus change because Chromium relies on it.
3677 if (AXObjectCache* cache = axObjectCache())
3678 cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
3681 if (!focusChangeBlocked && frameHost())
3682 frameHost()->chrome().focusedNodeChanged(m_focusedElement.get());
3684 SetFocusedElementDone:
3685 updateRenderTreeIfNeeded();
3686 if (LocalFrame* frame = this->frame())
3687 frame->selection().didChangeFocus();
3688 return !focusChangeBlocked;
3691 void Document::setCSSTarget(Element* n)
3694 m_cssTarget->didAffectSelector(AffectedSelectorTarget);
3697 n->didAffectSelector(AffectedSelectorTarget);
3700 void Document::registerNodeList(LiveNodeListBase* list)
3702 m_nodeListCounts[list->invalidationType()]++;
3703 if (list->isRootedAtDocument())
3704 m_listsInvalidatedAtDocument.add(list);
3707 void Document::unregisterNodeList(LiveNodeListBase* list)
3709 m_nodeListCounts[list->invalidationType()]--;
3710 if (list->isRootedAtDocument()) {
3711 ASSERT(m_listsInvalidatedAtDocument.contains(list));
3712 m_listsInvalidatedAtDocument.remove(list);
3716 void Document::attachNodeIterator(NodeIterator* ni)
3718 m_nodeIterators.add(ni);
3721 void Document::detachNodeIterator(NodeIterator* ni)
3723 // The node iterator can be detached without having been attached if its root node didn't have a document
3724 // when the iterator was created, but has it now.
3725 m_nodeIterators.remove(ni);
3728 void Document::moveNodeIteratorsToNewDocument(Node& node, Document& newDocument)
3730 HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3731 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3732 for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3733 if ((*it)->root() == node) {
3734 detachNodeIterator(*it);
3735 newDocument.attachNodeIterator(*it);
3740 void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
3742 if (!m_ranges.isEmpty()) {
3743 HashSet<Range*>::const_iterator end = m_ranges.end();
3744 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3745 (*it)->nodeChildrenChanged(container);
3749 void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
3751 NoEventDispatchAssertion assertNoEventDispatch;
3752 if (!m_ranges.isEmpty()) {
3753 HashSet<Range*>::const_iterator end = m_ranges.end();
3754 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3755 (*it)->nodeChildrenWillBeRemoved(container);
3758 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3759 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
3760 for (Node* n = container.firstChild(); n; n = n->nextSibling())
3761 (*it)->nodeWillBeRemoved(*n);
3764 if (LocalFrame* frame = this->frame()) {
3765 for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
3766 frame->eventHandler().nodeWillBeRemoved(*n);
3767 frame->selection().nodeWillBeRemoved(*n);
3768 frame->page()->dragCaretController().nodeWillBeRemoved(*n);
3773 void Document::nodeWillBeRemoved(Node& n)
3775 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3776 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3777 (*it)->nodeWillBeRemoved(n);
3779 if (!m_ranges.isEmpty()) {
3780 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
3781 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3782 (*it)->nodeWillBeRemoved(n);
3785 if (LocalFrame* frame = this->frame()) {
3786 frame->eventHandler().nodeWillBeRemoved(n);
3787 frame->selection().nodeWillBeRemoved(n);
3788 frame->page()->dragCaretController().nodeWillBeRemoved(n);
3792 void Document::didInsertText(Node* text, unsigned offset, unsigned length)
3794 if (!m_ranges.isEmpty()) {
3795 HashSet<Range*>::const_iterator end = m_ranges.end();
3796 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3797 (*it)->didInsertText(text, offset, length);
3800 // Update the markers for spelling and grammar checking.
3801 m_markers->shiftMarkers(text, offset, length);
3804 void Document::didRemoveText(Node* text, unsigned offset, unsigned length)
3806 if (!m_ranges.isEmpty()) {
3807 HashSet<Range*>::const_iterator end = m_ranges.end();
3808 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3809 (*it)->didRemoveText(text, offset, length);
3812 // Update the markers for spelling and grammar checking.
3813 m_markers->removeMarkers(text, offset, length);
3814 m_markers->shiftMarkers(text, offset + length, 0 - length);
3817 void Document::didMergeTextNodes(Text& oldNode, unsigned offset)
3819 if (!m_ranges.isEmpty()) {
3820 NodeWithIndex oldNodeWithIndex(oldNode);
3821 HashSet<Range*>::const_iterator end = m_ranges.end();
3822 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3823 (*it)->didMergeTextNodes(oldNodeWithIndex, offset);
3827 m_frame->selection().didMergeTextNodes(oldNode, offset);
3829 // FIXME: This should update markers for spelling and grammar checking.
3832 void Document::didSplitTextNode(Text& oldNode)
3834 if (!m_ranges.isEmpty()) {
3835 HashSet<Range*>::const_iterator end = m_ranges.end();
3836 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3837 (*it)->didSplitTextNode(oldNode);
3841 m_frame->selection().didSplitTextNode(oldNode);
3843 // FIXME: This should update markers for spelling and grammar checking.
3846 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3848 DOMWindow* domWindow = this->domWindow();
3851 domWindow->setAttributeEventListener(eventType, listener);
3854 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3856 DOMWindow* domWindow = this->domWindow();
3859 return domWindow->getAttributeEventListener(eventType);
3862 EventQueue* Document::eventQueue() const
3866 return m_domWindow->eventQueue();
3869 void Document::enqueueAnimationFrameEvent(PassRefPtrWillBeRawPtr<Event> event)
3871 ensureScriptedAnimationController().enqueueEvent(event);
3874 void Document::enqueueScrollEventForNode(Node* target)
3876 // Per the W3C CSSOM View Module only scroll events fired at the document should bubble.
3877 RefPtrWillBeRawPtr<Event> scrollEvent = target->isDocumentNode() ? Event::createBubble(EventTypeNames::scroll) : Event::create(EventTypeNames::scroll);
3878 scrollEvent->setTarget(target);
3879 ensureScriptedAnimationController().enqueuePerFrameEvent(scrollEvent.release());
3882 void Document::enqueueResizeEvent()
3884 RefPtrWillBeRawPtr<Event> event = Event::create(EventTypeNames::resize);
3885 event->setTarget(domWindow());
3886 ensureScriptedAnimationController().enqueuePerFrameEvent(event.release());
3889 PassRefPtrWillBeRawPtr<Event> Document::createEvent(const String& eventType, ExceptionState& exceptionState)
3891 RefPtrWillBeRawPtr<Event> event = EventFactory::create(eventType);
3893 return event.release();
3895 exceptionState.throwDOMException(NotSupportedError, "The provided event type ('" + eventType + "') is invalid.");
3899 void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
3901 if (ContextFeatures::mutationEventsEnabled(this))
3902 addListenerType(listenerType);
3905 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
3907 if (eventType == EventTypeNames::DOMSubtreeModified) {
3908 UseCounter::count(*this, UseCounter::DOMSubtreeModifiedEvent);
3909 addMutationEventListenerTypeIfEnabled(DOMSUBTREEMODIFIED_LISTENER);
3910 } else if (eventType == EventTypeNames::DOMNodeInserted) {
3911 UseCounter::count(*this, UseCounter::DOMNodeInsertedEvent);
3912 addMutationEventListenerTypeIfEnabled(DOMNODEINSERTED_LISTENER);
3913 } else if (eventType == EventTypeNames::DOMNodeRemoved) {
3914 UseCounter::count(*this, UseCounter::DOMNodeRemovedEvent);
3915 addMutationEventListenerTypeIfEnabled(DOMNODEREMOVED_LISTENER);
3916 } else if (eventType == EventTypeNames::DOMNodeRemovedFromDocument) {
3917 UseCounter::count(*this, UseCounter::DOMNodeRemovedFromDocumentEvent);
3918 addMutationEventListenerTypeIfEnabled(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
3919 } else if (eventType == EventTypeNames::DOMNodeInsertedIntoDocument) {
3920 UseCounter::count(*this, UseCounter::DOMNodeInsertedIntoDocumentEvent);
3921 addMutationEventListenerTypeIfEnabled(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
3922 } else if (eventType == EventTypeNames::DOMCharacterDataModified) {
3923 UseCounter::count(*this, UseCounter::DOMCharacterDataModifiedEvent);
3924 addMutationEventListenerTypeIfEnabled(DOMCHARACTERDATAMODIFIED_LISTENER);
3925 } else if (eventType == EventTypeNames::overflowchanged) {
3926 UseCounter::count(*this, UseCounter::OverflowChangedEvent);
3927 addListenerType(OVERFLOWCHANGED_LISTENER);
3928 } else if (eventType == EventTypeNames::webkitAnimationStart || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationstart)) {
3929 addListenerType(ANIMATIONSTART_LISTENER);
3930 } else if (eventType == EventTypeNames::webkitAnimationEnd || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationend)) {
3931 addListenerType(ANIMATIONEND_LISTENER);
3932 } else if (eventType == EventTypeNames::webkitAnimationIteration || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationiteration)) {
3933 addListenerType(ANIMATIONITERATION_LISTENER);
3934 } else if (eventType == EventTypeNames::webkitTransitionEnd || eventType == EventTypeNames::transitionend) {
3935 addListenerType(TRANSITIONEND_LISTENER);
3936 } else if (eventType == EventTypeNames::scroll) {
3937 addListenerType(SCROLL_LISTENER);
3938 } else if (eventType == EventTypeNames::DOMFocusIn || eventType == EventTypeNames::DOMFocusOut) {
3939 UseCounter::count(*this, UseCounter::DOMFocusInOutEvent);
3943 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
3948 HTMLFrameOwnerElement* Document::ownerElement() const
3952 return frame()->ownerElement();
3955 String Document::cookie(ExceptionState& exceptionState) const
3957 if (settings() && !settings()->cookieEnabled())
3960 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3961 // InvalidStateError exception on getting if the Document has no
3962 // browsing context.
3964 if (!securityOrigin()->canAccessCookies()) {
3965 if (isSandboxed(SandboxOrigin))
3966 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
3967 else if (url().protocolIs("data"))
3968 exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
3970 exceptionState.throwSecurityError("Access is denied for this document.");
3974 KURL cookieURL = this->cookieURL();
3975 if (cookieURL.isEmpty())
3978 return cookies(this, cookieURL);
3981 void Document::setCookie(const String& value, ExceptionState& exceptionState)
3983 if (settings() && !settings()->cookieEnabled())
3986 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3987 // InvalidStateError exception on setting if the Document has no
3988 // browsing context.
3990 if (!securityOrigin()->canAccessCookies()) {
3991 if (isSandboxed(SandboxOrigin))
3992 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
3993 else if (url().protocolIs("data"))
3994 exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
3996 exceptionState.throwSecurityError("Access is denied for this document.");
4000 KURL cookieURL = this->cookieURL();
4001 if (cookieURL.isEmpty())
4004 setCookies(this, cookieURL, value);
4007 const AtomicString& Document::referrer() const
4010 return loader()->request().httpReferrer();
4014 String Document::domain() const
4016 return securityOrigin()->domain();
4019 void Document::setDomain(const String& newDomain, ExceptionState& exceptionState)
4021 if (isSandboxed(SandboxDocumentDomain)) {
4022 exceptionState.throwSecurityError("Assignment is forbidden for sandboxed iframes.");
4026 if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
4027 exceptionState.throwSecurityError("Assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme.");
4031 if (newDomain.isEmpty()) {
4032 exceptionState.throwSecurityError("'" + newDomain + "' is an empty domain.");
4036 OriginAccessEntry::IPAddressSetting ipAddressSetting = settings() && settings()->treatIPAddressAsDomain() ? OriginAccessEntry::TreatIPAddressAsDomain : OriginAccessEntry::TreatIPAddressAsIPAddress;
4037 OriginAccessEntry accessEntry(securityOrigin()->protocol(), newDomain, OriginAccessEntry::AllowSubdomains, ipAddressSetting);
4038 OriginAccessEntry::MatchResult result = accessEntry.matchesOrigin(*securityOrigin());
4039 if (result == OriginAccessEntry::DoesNotMatchOrigin) {
4040 exceptionState.throwSecurityError("'" + newDomain + "' is not a suffix of '" + domain() + "'.");
4044 if (result == OriginAccessEntry::MatchesOriginButIsPublicSuffix) {
4045 exceptionState.throwSecurityError("'" + newDomain + "' is a top-level domain.");
4049 securityOrigin()->setDomainFromDOM(newDomain);
4051 m_frame->script().updateSecurityOrigin(securityOrigin());
4054 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
4055 String Document::lastModified() const
4057 DateComponents date;
4058 bool foundDate = false;
4060 if (DocumentLoader* documentLoader = loader()) {
4061 const AtomicString& httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
4062 if (!httpLastModified.isEmpty()) {
4063 date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
4068 // FIXME: If this document came from the file system, the HTML5
4069 // specificiation tells us to read the last modification date from the file
4072 date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
4073 return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
4076 const KURL& Document::firstPartyForCookies() const
4078 return topDocument().url();
4081 static bool isValidNameNonASCII(const LChar* characters, unsigned length)
4083 if (!isValidNameStart(characters[0]))
4086 for (unsigned i = 1; i < length; ++i) {
4087 if (!isValidNamePart(characters[i]))
4094 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
4099 U16_NEXT(characters, i, length, c)
4100 if (!isValidNameStart(c))
4103 while (i < length) {
4104 U16_NEXT(characters, i, length, c)
4105 if (!isValidNamePart(c))
4112 template<typename CharType>
4113 static inline bool isValidNameASCII(const CharType* characters, unsigned length)
4115 CharType c = characters[0];
4116 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
4119 for (unsigned i = 1; i < length; ++i) {
4121 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
4128 bool Document::isValidName(const String& name)
4130 unsigned length = name.length();
4134 if (name.is8Bit()) {
4135 const LChar* characters = name.characters8();
4137 if (isValidNameASCII(characters, length))
4140 return isValidNameNonASCII(characters, length);
4143 const UChar* characters = name.characters16();
4145 if (isValidNameASCII(characters, length))
4148 return isValidNameNonASCII(characters, length);
4151 template<typename CharType>
4152 static bool parseQualifiedNameInternal(const AtomicString& qualifiedName, const CharType* characters, unsigned length, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
4154 bool nameStart = true;
4155 bool sawColon = false;
4158 for (unsigned i = 0; i < length;) {
4160 U16_NEXT(characters, i, length, c)
4163 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') contains multiple colons.");
4164 return false; // multiple colons: not allowed
4169 } else if (nameStart) {
4170 if (!isValidNameStart(c)) {
4171 StringBuilder message;
4172 message.appendLiteral("The qualified name provided ('");
4173 message.append(qualifiedName);
4174 message.appendLiteral("') contains the invalid name-start character '");
4176 message.appendLiteral("'.");
4177 exceptionState.throwDOMException(InvalidCharacterError, message.toString());
4182 if (!isValidNamePart(c)) {
4183 StringBuilder message;
4184 message.appendLiteral("The qualified name provided ('");
4185 message.append(qualifiedName);
4186 message.appendLiteral("') contains the invalid character '");
4188 message.appendLiteral("'.");
4189 exceptionState.throwDOMException(InvalidCharacterError, message.toString());
4197 localName = qualifiedName;
4199 prefix = AtomicString(characters, colonPos);
4200 if (prefix.isEmpty()) {
4201 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty namespace prefix.");
4204 int prefixStart = colonPos + 1;
4205 localName = AtomicString(characters + prefixStart, length - prefixStart);
4208 if (localName.isEmpty()) {
4209 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty local name.");
4216 bool Document::parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
4218 unsigned length = qualifiedName.length();
4221 exceptionState.throwDOMException(InvalidCharacterError, "The qualified name provided is empty.");
4225 if (qualifiedName.is8Bit())
4226 return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName, exceptionState);
4227 return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName, exceptionState);
4230 void Document::setEncodingData(const DocumentEncodingData& newData)
4232 // It's possible for the encoding of the document to change while we're decoding
4233 // data. That can only occur while we're processing the <head> portion of the
4234 // document. There isn't much user-visible content in the <head>, but there is
4235 // the <title> element. This function detects that situation and re-decodes the
4236 // document's title so that the user doesn't see an incorrectly decoded title
4237 // in the title bar.
4239 && encoding() != newData.encoding()
4240 && !ElementTraversal::firstWithin(*m_titleElement)
4241 && encoding() == Latin1Encoding()
4242 && m_titleElement->textContent().containsOnlyLatin1()) {
4244 CString originalBytes = m_titleElement->textContent().latin1();
4245 OwnPtr<TextCodec> codec = newTextCodec(newData.encoding());
4246 String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), DataEOF);
4247 m_titleElement->setTextContent(correctlyDecodedTitle);
4250 m_encodingData = newData;
4252 // FIXME: Should be removed as part of https://code.google.com/p/chromium/issues/detail?id=319643
4253 bool shouldUseVisualOrdering = m_encodingData.encoding().usesVisualOrdering();
4254 if (shouldUseVisualOrdering != m_visuallyOrdered) {
4255 m_visuallyOrdered = shouldUseVisualOrdering;
4256 // FIXME: How is possible to not have a renderer here?
4258 renderView()->style()->setRTLOrdering(m_visuallyOrdered ? VisualOrder : LogicalOrder);
4259 setNeedsStyleRecalc(SubtreeStyleChange);
4263 KURL Document::completeURL(const String& url) const
4265 return completeURLWithOverride(url, m_baseURL);
4268 KURL Document::completeURLWithOverride(const String& url, const KURL& baseURLOverride) const
4270 // Always return a null URL when passed a null string.
4271 // FIXME: Should we change the KURL constructor to have this behavior?
4272 // See also [CSS]StyleSheet::completeURL(const String&)
4275 // This logic is deliberately spread over many statements in an attempt to track down http://crbug.com/312410.
4276 const KURL* baseURLFromParent = 0;
4277 bool shouldUseParentBaseURL = baseURLOverride.isEmpty();
4278 if (!shouldUseParentBaseURL) {
4279 const KURL& aboutBlankURL = blankURL();
4280 shouldUseParentBaseURL = (baseURLOverride == aboutBlankURL);
4282 if (shouldUseParentBaseURL) {
4283 if (Document* parent = parentDocument())
4284 baseURLFromParent = &parent->baseURL();
4286 const KURL& baseURL = baseURLFromParent ? *baseURLFromParent : baseURLOverride;
4287 if (!encoding().isValid())
4288 return KURL(baseURL, url);
4289 return KURL(baseURL, url, encoding());
4292 // Support for Javascript execCommand, and related methods
4294 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
4296 LocalFrame* frame = document->frame();
4297 if (!frame || frame->document() != document)
4298 return Editor::Command();
4300 document->updateRenderTreeIfNeeded();
4301 return frame->editor().command(commandName, userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
4304 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
4306 // We don't allow recusrive |execCommand()| to protect against attack code.
4307 // Recursive call of |execCommand()| could be happened by moving iframe
4308 // with script triggered by insertion, e.g. <iframe src="javascript:...">
4309 // <iframe onload="...">. This usage is valid as of the specification
4310 // although, it isn't common use case, rather it is used as attack code.
4311 static bool inExecCommand = false;
4312 if (inExecCommand) {
4313 String message = "We don't execute document.execCommand() this time, because it is called recursively.";
4314 addConsoleMessage(JSMessageSource, WarningMessageLevel, message);
4317 TemporaryChange<bool> executeScope(inExecCommand, true);
4319 // Postpone DOM mutation events, which can execute scripts and change
4320 // DOM tree against implementation assumption.
4321 EventQueueScope eventQueueScope;
4322 Editor::Command editorCommand = command(this, commandName, userInterface);
4323 blink::Platform::current()->histogramSparse("WebCore.Document.execCommand", editorCommand.idForHistogram());
4324 return editorCommand.execute(value);
4327 bool Document::queryCommandEnabled(const String& commandName)
4329 return command(this, commandName).isEnabled();
4332 bool Document::queryCommandIndeterm(const String& commandName)
4334 return command(this, commandName).state() == MixedTriState;
4337 bool Document::queryCommandState(const String& commandName)
4339 return command(this, commandName).state() == TrueTriState;
4342 bool Document::queryCommandSupported(const String& commandName)
4344 return command(this, commandName).isSupported();
4347 String Document::queryCommandValue(const String& commandName)
4349 return command(this, commandName).value();
4352 KURL Document::openSearchDescriptionURL()
4354 static const char openSearchMIMEType[] = "application/opensearchdescription+xml";
4355 static const char openSearchRelation[] = "search";
4357 // FIXME: Why do only top-level frames have openSearchDescriptionURLs?
4358 if (!frame() || frame()->tree().parent())
4361 // FIXME: Why do we need to wait for FrameStateComplete?
4362 if (frame()->loader().state() != FrameStateComplete)
4368 for (HTMLLinkElement* linkElement = Traversal<HTMLLinkElement>::firstChild(*head()); linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4369 if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
4371 if (linkElement->href().isEmpty())
4373 return linkElement->href();
4379 void Document::pushCurrentScript(PassRefPtr<HTMLScriptElement> newCurrentScript)
4381 ASSERT(newCurrentScript);
4382 m_currentScriptStack.append(newCurrentScript);
4385 void Document::popCurrentScript()
4387 ASSERT(!m_currentScriptStack.isEmpty());
4388 m_currentScriptStack.removeLast();
4391 void Document::applyXSLTransform(ProcessingInstruction* pi)
4393 ASSERT(!pi->isLoading());
4394 UseCounter::count(*this, UseCounter::XSLProcessingInstruction);
4395 RefPtrWillBeRawPtr<XSLTProcessor> processor = XSLTProcessor::create();
4396 processor->setXSLStyleSheet(toXSLStyleSheet(pi->sheet()));
4397 String resultMIMEType;
4399 String resultEncoding;
4400 if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
4402 // FIXME: If the transform failed we should probably report an error (like Mozilla does).
4403 LocalFrame* ownerFrame = frame();
4404 processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, ownerFrame);
4405 InspectorInstrumentation::frameDocumentUpdated(ownerFrame);
4408 void Document::setTransformSource(PassOwnPtr<TransformSource> source)
4410 m_transformSource = source;
4413 void Document::setDesignMode(InheritedBool value)
4415 m_designMode = value;
4416 for (LocalFrame* frame = m_frame; frame && frame->document(); frame = frame->tree().traverseNext(m_frame))
4417 frame->document()->setNeedsStyleRecalc(SubtreeStyleChange);
4420 Document::InheritedBool Document::getDesignMode() const
4422 return m_designMode;
4425 bool Document::inDesignMode() const
4427 for (const Document* d = this; d; d = d->parentDocument()) {
4428 if (d->m_designMode != inherit)
4429 return d->m_designMode;
4434 String Document::designMode() const
4436 return inDesignMode() ? "on" : "off";
4439 void Document::setDesignMode(const String& value)
4442 if (equalIgnoringCase(value, "on"))
4444 else if (equalIgnoringCase(value, "off"))
4448 setDesignMode(mode);
4451 Document* Document::parentDocument() const
4455 LocalFrame* parent = m_frame->tree().parent();
4458 return parent->document();
4461 Document& Document::topDocument() const
4463 Document* doc = const_cast<Document*>(this);
4465 while ((element = doc->ownerElement()))
4466 doc = &element->document();
4472 WeakPtr<Document> Document::contextDocument()
4474 if (m_contextDocument)
4475 return m_contextDocument;
4477 return m_weakFactory.createWeakPtr();
4478 return WeakPtr<Document>(nullptr);
4481 PassRefPtr<Attr> Document::createAttribute(const AtomicString& name, ExceptionState& exceptionState)
4483 return createAttributeNS(nullAtom, name, exceptionState, true);
4486 PassRefPtr<Attr> Document::createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState, bool shouldIgnoreNamespaceChecks)
4488 AtomicString prefix, localName;
4489 if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
4492 QualifiedName qName(prefix, localName, namespaceURI);
4494 if (!shouldIgnoreNamespaceChecks && !hasValidNamespaceForAttributes(qName)) {
4495 exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
4499 return Attr::create(*this, qName, emptyAtom);
4502 const SVGDocumentExtensions* Document::svgExtensions()
4504 return m_svgExtensions.get();
4507 SVGDocumentExtensions& Document::accessSVGExtensions()
4509 if (!m_svgExtensions)
4510 m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this));
4511 return *m_svgExtensions;
4514 bool Document::hasSVGRootNode() const
4516 return isSVGSVGElement(documentElement());
4519 PassRefPtr<HTMLCollection> Document::ensureCachedCollection(CollectionType type)
4521 return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(*this, type);
4524 PassRefPtr<HTMLCollection> Document::images()
4526 return ensureCachedCollection(DocImages);
4529 PassRefPtr<HTMLCollection> Document::applets()
4531 return ensureCachedCollection(DocApplets);
4534 PassRefPtr<HTMLCollection> Document::embeds()
4536 return ensureCachedCollection(DocEmbeds);
4539 PassRefPtr<HTMLCollection> Document::scripts()
4541 return ensureCachedCollection(DocScripts);
4544 PassRefPtr<HTMLCollection> Document::links()
4546 return ensureCachedCollection(DocLinks);
4549 PassRefPtr<HTMLCollection> Document::forms()
4551 return ensureCachedCollection(DocForms);
4554 PassRefPtr<HTMLCollection> Document::anchors()
4556 return ensureCachedCollection(DocAnchors);
4559 PassRefPtr<HTMLAllCollection> Document::allForBinding()
4561 UseCounter::count(*this, UseCounter::DocumentAll);
4565 PassRefPtr<HTMLAllCollection> Document::all()
4567 return ensureRareData().ensureNodeLists().addCache<HTMLAllCollection>(*this, DocAll);
4570 PassRefPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
4572 return ensureRareData().ensureNodeLists().addCache<HTMLNameCollection>(*this, WindowNamedItems, name);
4575 PassRefPtr<HTMLCollection> Document::documentNamedItems(const AtomicString& name)
4577 return ensureRareData().ensureNodeLists().addCache<HTMLNameCollection>(*this, DocumentNamedItems, name);
4580 void Document::finishedParsing()
4582 ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
4583 ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
4585 if (!m_documentTiming.domContentLoadedEventStart)
4586 m_documentTiming.domContentLoadedEventStart = monotonicallyIncreasingTime();
4587 dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
4588 if (!m_documentTiming.domContentLoadedEventEnd)
4589 m_documentTiming.domContentLoadedEventEnd = monotonicallyIncreasingTime();
4591 if (frame() && frame()->isMainFrame()) {
4592 // Reset the text autosizing multipliers on main frame when DOM is loaded.
4593 // This is to allow for a fresh text autosizing pass when the page layout
4594 // changes significantly in the end.
4595 if (TextAutosizer* textAutosizer = this->textAutosizer())
4596 textAutosizer->recalculateMultipliers();
4599 // The loader's finishedParsing() method may invoke script that causes this object to
4600 // be dereferenced (when this document is in an iframe and the onload causes the iframe's src to change).
4601 // Keep it alive until we are done.
4602 RefPtr<Document> protect(this);
4604 if (RefPtr<LocalFrame> f = frame()) {
4605 // Don't update the render tree if we haven't requested the main resource yet to avoid
4606 // adding extra latency. Note that the first render tree update can be expensive since it
4607 // triggers the parsing of the default stylesheets which are compiled-in.
4608 const bool mainResourceWasAlreadyRequested =
4609 m_frame->loader().stateMachine()->committedFirstRealDocumentLoad();
4611 // FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
4612 // resource loads are complete. HTMLObjectElements can start loading their resources from
4613 // post attach callbacks triggered by recalcStyle(). This means if we parse out an <object>
4614 // tag and then reach the end of the document without updating styles, we might not have yet
4615 // started the resource load and might fire the window load event too early. To avoid this
4616 // we force the styles to be up to date before calling FrameLoader::finishedParsing().
4617 // See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
4618 if (mainResourceWasAlreadyRequested)
4619 updateRenderTreeIfNeeded();
4621 f->loader().finishedParsing();
4623 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", "data", InspectorMarkLoadEvent::data(f.get()));
4624 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
4625 InspectorInstrumentation::domContentLoadedEventFired(f.get());
4628 // Schedule dropping of the ElementDataCache. We keep it alive for a while after parsing finishes
4629 // so that dynamically inserted content can also benefit from sharing optimizations.
4630 // Note that we don't refresh the timer on cache access since that could lead to huge caches being kept
4631 // alive indefinitely by something innocuous like JS setting .innerHTML repeatedly on a timer.
4632 m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
4634 // Parser should have picked up all preloads by now
4635 m_fetcher->clearPreloads();
4637 if (HTMLImportLoader* import = importLoader())
4638 import->didFinishParsing();
4641 void Document::elementDataCacheClearTimerFired(Timer<Document>*)
4643 m_elementDataCache.clear();
4646 Vector<IconURL> Document::iconURLs(int iconTypesMask)
4648 IconURL firstFavicon;
4649 IconURL firstTouchIcon;
4650 IconURL firstTouchPrecomposedIcon;
4651 Vector<IconURL> secondaryIcons;
4653 // Start from the last child node so that icons seen later take precedence as required by the spec.
4654 for (HTMLLinkElement* linkElement = head() ? Traversal<HTMLLinkElement>::firstChild(*head()) : 0; linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4655 if (!(linkElement->iconType() & iconTypesMask))
4657 if (linkElement->href().isEmpty())
4659 if (!RuntimeEnabledFeatures::touchIconLoadingEnabled() && linkElement->iconType() != Favicon)
4662 IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
4663 if (linkElement->iconType() == Favicon) {
4664 if (firstFavicon.m_iconType != InvalidIcon)
4665 secondaryIcons.append(firstFavicon);
4666 firstFavicon = newURL;
4667 } else if (linkElement->iconType() == TouchIcon) {
4668 if (firstTouchIcon.m_iconType != InvalidIcon)
4669 secondaryIcons.append(firstTouchIcon);
4670 firstTouchIcon = newURL;
4671 } else if (linkElement->iconType() == TouchPrecomposedIcon) {
4672 if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4673 secondaryIcons.append(firstTouchPrecomposedIcon);
4674 firstTouchPrecomposedIcon = newURL;
4676 ASSERT_NOT_REACHED();
4680 Vector<IconURL> iconURLs;
4681 if (firstFavicon.m_iconType != InvalidIcon)
4682 iconURLs.append(firstFavicon);
4683 else if (m_url.protocolIsInHTTPFamily() && iconTypesMask & Favicon)
4684 iconURLs.append(IconURL::defaultFavicon(m_url));
4686 if (firstTouchIcon.m_iconType != InvalidIcon)
4687 iconURLs.append(firstTouchIcon);
4688 if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4689 iconURLs.append(firstTouchPrecomposedIcon);
4690 for (int i = secondaryIcons.size() - 1; i >= 0; --i)
4691 iconURLs.append(secondaryIcons[i]);
4695 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
4697 if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
4700 m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
4701 m_frame->selection().updateSecureKeyboardEntryIfActive();
4704 bool Document::useSecureKeyboardEntryWhenActive() const
4706 return m_useSecureKeyboardEntryWhenActive;
4709 void Document::initSecurityContext()
4711 initSecurityContext(DocumentInit(m_url, m_frame, contextDocument(), m_importsController));
4714 static PassRefPtr<ContentSecurityPolicy> contentSecurityPolicyFor(Document* document)
4716 if (document->importsController())
4717 return document->importsController()->master()->contentSecurityPolicy();
4718 return ContentSecurityPolicy::create(document);
4721 void Document::initSecurityContext(const DocumentInit& initializer)
4723 if (haveInitializedSecurityOrigin()) {
4724 ASSERT(securityOrigin());
4728 if (!initializer.hasSecurityContext()) {
4729 // No source for a security context.
4730 // This can occur via document.implementation.createDocument().
4731 m_cookieURL = KURL(ParsedURLString, emptyString());
4732 setSecurityOrigin(SecurityOrigin::createUnique());
4733 setContentSecurityPolicy(ContentSecurityPolicy::create(this));
4737 // In the common case, create the security context from the currently
4738 // loading URL with a fresh content security policy.
4739 m_cookieURL = m_url;
4740 enforceSandboxFlags(initializer.sandboxFlags());
4741 setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
4742 setContentSecurityPolicy(contentSecurityPolicyFor(this));
4744 if (Settings* settings = initializer.settings()) {
4745 if (!settings->webSecurityEnabled()) {
4746 // Web security is turned off. We should let this document access every other document. This is used primary by testing
4747 // harnesses for web sites.
4748 securityOrigin()->grantUniversalAccess();
4749 } else if (securityOrigin()->isLocal()) {
4750 if (settings->allowUniversalAccessFromFileURLs()) {
4751 // Some clients want local URLs to have universal access, but that setting is dangerous for other clients.
4752 securityOrigin()->grantUniversalAccess();
4753 } else if (!settings->allowFileAccessFromFileURLs()) {
4754 // Some clients want local URLs to have even tighter restrictions by default, and not be able to access other local files.
4755 // FIXME 81578: The naming of this is confusing. Files with restricted access to other local files
4756 // still can have other privileges that can be remembered, thereby not making them unique origins.
4757 securityOrigin()->enforceFilePathSeparation();
4762 if (initializer.shouldTreatURLAsSrcdocDocument()) {
4763 m_isSrcdocDocument = true;
4764 setBaseURLOverride(initializer.parentBaseURL());
4767 if (!shouldInheritSecurityOriginFromOwner(m_url))
4770 // If we do not obtain a meaningful origin from the URL, then we try to
4771 // find one via the frame hierarchy.
4773 if (!initializer.owner()) {
4774 didFailToInitializeSecurityOrigin();
4778 if (isSandboxed(SandboxOrigin)) {
4779 // If we're supposed to inherit our security origin from our owner,
4780 // but we're also sandboxed, the only thing we inherit is the ability
4781 // to load local resources. This lets about:blank iframes in file://
4782 // URL documents load images and other resources from the file system.
4783 if (initializer.owner()->securityOrigin()->canLoadLocalResources())
4784 securityOrigin()->grantLoadLocalResources();
4788 m_cookieURL = initializer.owner()->cookieURL();
4789 // We alias the SecurityOrigins to match Firefox, see Bug 15313
4790 // https://bugs.webkit.org/show_bug.cgi?id=15313
4791 setSecurityOrigin(initializer.owner()->securityOrigin());
4794 void Document::initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders& headers)
4796 if (m_frame && m_frame->tree().parent() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
4797 contentSecurityPolicy()->copyStateFrom(m_frame->tree().parent()->document()->contentSecurityPolicy());
4798 contentSecurityPolicy()->didReceiveHeaders(headers);
4801 bool Document::allowInlineEventHandlers(Node* node, EventListener* listener, const String& contextURL, const WTF::OrdinalNumber& contextLine)
4803 if (!contentSecurityPolicy()->allowInlineEventHandlers(contextURL, contextLine))
4806 // HTML says that inline script needs browsing context to create its execution environment.
4807 // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#event-handler-attributes
4808 // Also, if the listening node came from other document, which happens on context-less event dispatching,
4809 // we also need to ask the owner document of the node.
4810 LocalFrame* frame = executingFrame();
4813 if (!frame->script().canExecuteScripts(NotAboutToExecuteScript))
4815 if (node && node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
4821 bool Document::allowExecutingScripts(Node* node)
4823 // FIXME: Eventually we'd like to evaluate scripts which are inserted into a
4824 // viewless document but this'll do for now.
4825 // See http://bugs.webkit.org/show_bug.cgi?id=5727
4826 LocalFrame* frame = executingFrame();
4829 if (!node->document().executingFrame())
4831 if (!frame->script().canExecuteScripts(AboutToExecuteScript))
4836 void Document::updateSecurityOrigin(PassRefPtr<SecurityOrigin> origin)
4838 setSecurityOrigin(origin);
4839 didUpdateSecurityOrigin();
4842 void Document::didUpdateSecurityOrigin()
4846 m_frame->script().updateSecurityOrigin(securityOrigin());
4849 bool Document::isContextThread() const
4851 return isMainThread();
4854 void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
4856 m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
4857 if (!m_updateFocusAppearanceTimer.isActive())
4858 m_updateFocusAppearanceTimer.startOneShot(0, FROM_HERE);
4861 void Document::cancelFocusAppearanceUpdate()
4863 m_updateFocusAppearanceTimer.stop();
4866 void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
4868 Element* element = focusedElement();
4872 if (element->isFocusable())
4873 element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
4876 void Document::attachRange(Range* range)
4878 ASSERT(!m_ranges.contains(range));
4879 m_ranges.add(range);
4882 void Document::detachRange(Range* range)
4884 // We don't ASSERT m_ranges.contains(range) to allow us to call this
4885 // unconditionally to fix: https://bugs.webkit.org/show_bug.cgi?id=26044
4886 m_ranges.remove(range);
4889 void Document::getCSSCanvasContext(const String& type, const String& name, int width, int height, bool& is2d, RefPtrWillBeRawPtr<CanvasRenderingContext2D>& context2d, bool& is3d, RefPtrWillBeRawPtr<WebGLRenderingContext>& context3d)
4891 HTMLCanvasElement& element = getCSSCanvasElement(name);
4892 element.setSize(IntSize(width, height));
4893 CanvasRenderingContext* context = element.getContext(type);
4897 if (context->is2d()) {
4899 context2d = toCanvasRenderingContext2D(context);
4900 } else if (context->is3d()) {
4902 context3d = toWebGLRenderingContext(context);
4906 HTMLCanvasElement& Document::getCSSCanvasElement(const String& name)
4908 RefPtrWillBeMember<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, nullptr).storedValue->value;
4910 element = HTMLCanvasElement::create(*this);
4911 element->setAccelerationDisabled(true);
4916 void Document::initDNSPrefetch()
4918 Settings* settings = this->settings();
4920 m_haveExplicitlyDisabledDNSPrefetch = false;
4921 m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
4923 // Inherit DNS prefetch opt-out from parent frame
4924 if (Document* parent = parentDocument()) {
4925 if (!parent->isDNSPrefetchEnabled())
4926 m_isDNSPrefetchEnabled = false;
4930 void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
4932 if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
4933 m_isDNSPrefetchEnabled = true;
4937 m_isDNSPrefetchEnabled = false;
4938 m_haveExplicitlyDisabledDNSPrefetch = true;
4941 void Document::reportBlockedScriptExecutionToInspector(const String& directiveText)
4943 InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText);
4946 void Document::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* scriptState)
4948 internalAddMessage(source, level, message, sourceURL, lineNumber, nullptr, scriptState);
4951 void Document::internalAddMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* scriptState)
4953 if (!isContextThread()) {
4954 m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
4961 String messageURL = sourceURL;
4962 if (!scriptState && sourceURL.isNull() && !lineNumber) {
4963 messageURL = url().string();
4964 if (parsing() && !isInDocumentWrite() && scriptableDocumentParser()) {
4965 ScriptableDocumentParser* parser = scriptableDocumentParser();
4966 if (!parser->isWaitingForScripts() && !parser->isExecutingScript())
4967 lineNumber = parser->lineNumber().oneBasedInt();
4970 m_frame->console().addMessage(source, level, message, messageURL, lineNumber, 0, callStack, scriptState, 0);
4973 void Document::addConsoleMessageWithRequestIdentifier(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
4975 if (!isContextThread()) {
4976 m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
4981 m_frame->console().addMessage(source, level, message, String(), 0, 0, nullptr, 0, requestIdentifier);
4984 // FIXME(crbug.com/305497): This should be removed after ExecutionContext-DOMWindow migration.
4985 void Document::postTask(PassOwnPtr<ExecutionContextTask> task)
4987 m_taskRunner->postTask(task);
4990 void Document::tasksWereSuspended()
4992 scriptRunner()->suspend();
4995 m_parser->suspendScheduledTasks();
4996 if (m_scriptedAnimationController)
4997 m_scriptedAnimationController->suspend();
5000 void Document::tasksWereResumed()
5002 scriptRunner()->resume();
5005 m_parser->resumeScheduledTasks();
5006 if (m_scriptedAnimationController)
5007 m_scriptedAnimationController->resume();
5009 MutationObserver::resumeSuspendedObservers();
5012 // FIXME: suspendScheduledTasks(), resumeScheduledTasks(), tasksNeedSuspension()
5013 // should be moved to DOMWindow once it inherits ExecutionContext
5014 void Document::suspendScheduledTasks()
5016 ExecutionContext::suspendScheduledTasks();
5017 m_taskRunner->suspend();
5020 void Document::resumeScheduledTasks()
5022 ExecutionContext::resumeScheduledTasks();
5023 m_taskRunner->resume();
5026 bool Document::tasksNeedSuspension()
5028 Page* page = this->page();
5029 return page && page->defersLoading();
5032 void Document::addToTopLayer(Element* element, const Element* before)
5034 if (element->isInTopLayer())
5037 ASSERT(!m_topLayerElements.contains(element));
5038 ASSERT(!before || m_topLayerElements.contains(before));
5040 size_t beforePosition = m_topLayerElements.find(before);
5041 m_topLayerElements.insert(beforePosition, element);
5043 m_topLayerElements.append(element);
5045 element->setIsInTopLayer(true);
5048 void Document::removeFromTopLayer(Element* element)
5050 if (!element->isInTopLayer())
5052 size_t position = m_topLayerElements.find(element);
5053 ASSERT(position != kNotFound);
5054 m_topLayerElements.remove(position);
5055 element->setIsInTopLayer(false);
5058 HTMLDialogElement* Document::activeModalDialog() const
5060 if (m_topLayerElements.isEmpty())
5062 return toHTMLDialogElement(m_topLayerElements.last().get());
5065 void Document::webkitExitPointerLock()
5069 if (Element* target = page()->pointerLockController().element()) {
5070 if (target->document() != this)
5073 page()->pointerLockController().requestPointerUnlock();
5076 Element* Document::webkitPointerLockElement() const
5078 if (!page() || page()->pointerLockController().lockPending())
5080 if (Element* element = page()->pointerLockController().element()) {
5081 if (element->document() == this)
5087 void Document::decrementLoadEventDelayCount()
5089 ASSERT(m_loadEventDelayCount);
5090 --m_loadEventDelayCount;
5092 if (!m_loadEventDelayCount)
5093 checkLoadEventSoon();
5096 void Document::checkLoadEventSoon()
5098 if (frame() && !m_loadEventDelayTimer.isActive())
5099 m_loadEventDelayTimer.startOneShot(0, FROM_HERE);
5102 bool Document::isDelayingLoadEvent()
5105 // Always delay load events until after garbage collection.
5106 // This way we don't have to explicitly delay load events via
5107 // incrementLoadEventDelayCount and decrementLoadEventDelayCount in
5108 // Node destructors.
5109 if (ThreadState::current()->isSweepInProgress()) {
5110 if (!m_loadEventDelayCount)
5111 checkLoadEventSoon();
5115 return m_loadEventDelayCount;
5119 void Document::loadEventDelayTimerFired(Timer<Document>*)
5122 frame()->loader().checkCompleted();
5125 void Document::loadPluginsSoon()
5127 // FIXME: Remove this timer once we don't need to compute layout to load plugins.
5128 if (!m_pluginLoadingTimer.isActive())
5129 m_pluginLoadingTimer.startOneShot(0, FROM_HERE);
5132 void Document::pluginLoadingTimerFired(Timer<Document>*)
5137 ScriptedAnimationController& Document::ensureScriptedAnimationController()
5139 if (!m_scriptedAnimationController) {
5140 m_scriptedAnimationController = ScriptedAnimationController::create(this);
5141 // We need to make sure that we don't start up the animation controller on a background tab, for example.
5143 m_scriptedAnimationController->suspend();
5145 return *m_scriptedAnimationController;
5148 int Document::requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
5150 return ensureScriptedAnimationController().registerCallback(callback);
5153 void Document::cancelAnimationFrame(int id)
5155 if (!m_scriptedAnimationController)
5157 m_scriptedAnimationController->cancelCallback(id);
5160 void Document::serviceScriptedAnimations(double monotonicAnimationStartTime)
5162 if (!m_scriptedAnimationController)
5164 m_scriptedAnimationController->serviceScriptedAnimations(monotonicAnimationStartTime);
5167 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
5169 // FIXME: It's not clear from the documentation at
5170 // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html
5171 // 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
5172 // and implement them here. See https://bugs.webkit.org/show_bug.cgi?id=47819
5173 LocalFrame* frame = window ? window->frame() : this->frame();
5174 return Touch::create(frame, target, identifier, screenX, screenY, pageX, pageY, radiusX, radiusY, rotationAngle, force);
5177 PassRefPtrWillBeRawPtr<TouchList> Document::createTouchList(WillBeHeapVector<RefPtrWillBeMember<Touch> >& touches) const
5179 return TouchList::create(touches);
5182 void Document::didAddTouchEventHandler(Node* handler)
5184 // The node should either be in this document, or be the Document node of a child
5185 // of this document.
5186 ASSERT(&handler->document() == this
5187 || (handler->isDocumentNode() && toDocument(handler)->parentDocument() == this));
5188 if (!m_touchEventTargets.get())
5189 m_touchEventTargets = adoptPtr(new TouchEventTargetSet);
5190 bool isFirstHandler = m_touchEventTargets->isEmpty();
5192 if (!m_touchEventTargets->add(handler).isNewEntry) {
5193 // Just incremented refcount, no real change.
5194 // If this is a child document node, then the count should never go above 1.
5195 ASSERT(!handler->isDocumentNode() || &handler->document() == this);
5199 if (isFirstHandler) {
5200 if (Document* parent = parentDocument()) {
5201 parent->didAddTouchEventHandler(this);
5203 // This is the first touch handler on the whole page.
5204 if (FrameHost* frameHost = this->frameHost())
5205 frameHost->chrome().client().needTouchEvents(true);
5209 // When we're all done with all frames, ensure touch hit rects are marked as dirty.
5210 if (!handler->isDocumentNode() || handler == this) {
5211 if (Page* page = this->page()) {
5212 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
5213 scrollingCoordinator->touchEventTargetRectsDidChange();
5218 void Document::didRemoveTouchEventHandler(Node* handler, bool clearAll)
5220 // Note that we can't assert that |handler| is in this document because it might be in
5221 // the process of moving out of it.
5222 ASSERT(clearAll || m_touchEventTargets->contains(handler));
5223 if (!m_touchEventTargets.get())
5227 if (!m_touchEventTargets->contains(handler))
5229 m_touchEventTargets->removeAll(handler);
5231 if (!m_touchEventTargets->remove(handler))
5232 // Just decremented refcount, no real update.
5236 if (m_touchEventTargets->isEmpty()) {
5237 if (Document* parent = parentDocument()) {
5238 // This was the last handler in this document, update the parent document too.
5239 parent->didRemoveTouchEventHandler(this, clearAll);
5241 // We just removed the last touch handler on the whole page.
5242 if (FrameHost* frameHost = this->frameHost())
5243 frameHost->chrome().client().needTouchEvents(false);
5247 // When we're all done with all frames, ensure touch hit rects are marked as dirty.
5248 if (!handler->isDocumentNode() || handler == this) {
5249 if (Page* page = this->page()) {
5250 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
5251 scrollingCoordinator->touchEventTargetRectsDidChange();
5256 DocumentLoader* Document::loader() const
5261 DocumentLoader* loader = m_frame->loader().documentLoader();
5265 if (m_frame->document() != this)
5271 IntSize Document::initialViewportSize() const
5275 return view()->unscaledVisibleContentSize(IncludeScrollbars);
5278 Node* eventTargetNodeForDocument(Document* doc)
5282 Node* node = doc->focusedElement();
5283 if (!node && doc->isPluginDocument()) {
5284 PluginDocument* pluginDocument = toPluginDocument(doc);
5285 node = pluginDocument->pluginNode();
5287 if (!node && doc->isHTMLDocument())
5290 node = doc->documentElement();
5294 void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject& renderer)
5299 LayoutRect visibleContentRect = view()->visibleContentRect();
5300 for (size_t i = 0; i < quads.size(); ++i) {
5301 quads[i].move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
5302 adjustFloatQuadForAbsoluteZoom(quads[i], renderer);
5306 void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject& renderer)
5311 LayoutRect visibleContentRect = view()->visibleContentRect();
5312 rect.move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
5313 adjustFloatRectForAbsoluteZoom(rect, renderer);
5316 bool Document::hasActiveParser()
5318 return m_activeParserCount || (m_parser && m_parser->processingData());
5321 void Document::decrementActiveParserCount()
5323 --m_activeParserCount;
5326 // FIXME: This should always be enabled, but it seems to cause
5327 // http/tests/security/feed-urls-from-remote.html to timeout on Mac WK1
5328 // see http://webkit.org/b/110554 and http://webkit.org/b/110401
5329 frame()->loader().checkLoadComplete();
5332 void Document::setContextFeatures(ContextFeatures& features)
5334 m_contextFeatures = PassRefPtrWillBeRawPtr<ContextFeatures>(features);
5337 static RenderObject* nearestCommonHoverAncestor(RenderObject* obj1, RenderObject* obj2)
5342 for (RenderObject* currObj1 = obj1; currObj1; currObj1 = currObj1->hoverAncestor()) {
5343 for (RenderObject* currObj2 = obj2; currObj2; currObj2 = currObj2->hoverAncestor()) {
5344 if (currObj1 == currObj2)
5352 void Document::updateHoverActiveState(const HitTestRequest& request, Element* innerElement, const PlatformMouseEvent* event)
5354 ASSERT(!request.readOnly());
5356 if (request.active() && m_frame)
5357 m_frame->eventHandler().notifyElementActivated();
5359 Element* innerElementInDocument = innerElement;
5360 while (innerElementInDocument && innerElementInDocument->document() != this) {
5361 innerElementInDocument->document().updateHoverActiveState(request, innerElementInDocument, event);
5362 innerElementInDocument = innerElementInDocument->document().ownerElement();
5365 Element* oldActiveElement = activeHoverElement();
5366 if (oldActiveElement && !request.active()) {
5367 // We are clearing the :active chain because the mouse has been released.
5368 for (RenderObject* curr = oldActiveElement->renderer(); curr; curr = curr->parent()) {
5370 ASSERT(!curr->node()->isTextNode());
5371 curr->node()->setActive(false);
5372 m_userActionElements.setInActiveChain(curr->node(), false);
5375 setActiveHoverElement(nullptr);
5377 Element* newActiveElement = innerElementInDocument;
5378 if (!oldActiveElement && newActiveElement && request.active() && !request.touchMove()) {
5379 // We are setting the :active chain and freezing it. If future moves happen, they
5380 // will need to reference this chain.
5381 for (RenderObject* curr = newActiveElement->renderer(); curr; curr = curr->parent()) {
5382 if (curr->node() && !curr->isText())
5383 m_userActionElements.setInActiveChain(curr->node(), true);
5386 setActiveHoverElement(newActiveElement);
5389 // If the mouse has just been pressed, set :active on the chain. Those (and only those)
5390 // nodes should remain :active until the mouse is released.
5391 bool allowActiveChanges = !oldActiveElement && activeHoverElement();
5393 // If the mouse is down and if this is a mouse move event, we want to restrict changes in
5394 // :hover/:active to only apply to elements that are in the :active chain that we froze
5395 // at the time the mouse went down.
5396 bool mustBeInActiveChain = request.active() && request.move();
5398 RefPtr<Node> oldHoverNode = hoverNode();
5400 // Check to see if the hovered node has changed.
5401 // If it hasn't, we do not need to do anything.
5402 Node* newHoverNode = innerElementInDocument;
5403 while (newHoverNode && !newHoverNode->renderer())
5404 newHoverNode = newHoverNode->parentOrShadowHostNode();
5406 // Update our current hover node.
5407 setHoverNode(newHoverNode);
5409 // We have two different objects. Fetch their renderers.
5410 RenderObject* oldHoverObj = oldHoverNode ? oldHoverNode->renderer() : 0;
5411 RenderObject* newHoverObj = newHoverNode ? newHoverNode->renderer() : 0;
5413 // Locate the common ancestor render object for the two renderers.
5414 RenderObject* ancestor = nearestCommonHoverAncestor(oldHoverObj, newHoverObj);
5415 RefPtr<Node> ancestorNode(ancestor ? ancestor->node() : 0);
5417 Vector<RefPtr<Node>, 32> nodesToRemoveFromChain;
5418 Vector<RefPtr<Node>, 32> nodesToAddToChain;
5420 if (oldHoverObj != newHoverObj) {
5421 // If the old hovered node is not nil but it's renderer is, it was probably detached as part of the :hover style
5422 // (for instance by setting display:none in the :hover pseudo-class). In this case, the old hovered element (and its ancestors)
5423 // must be updated, to ensure it's normal style is re-applied.
5424 if (oldHoverNode && !oldHoverObj) {
5425 for (Node* node = oldHoverNode.get(); node; node = node->parentNode()) {
5426 if (!mustBeInActiveChain || (node->isElementNode() && toElement(node)->inActiveChain()))
5427 nodesToRemoveFromChain.append(node);
5432 // The old hover path only needs to be cleared up to (and not including) the common ancestor;
5433 for (RenderObject* curr = oldHoverObj; curr && curr != ancestor; curr = curr->hoverAncestor()) {
5434 if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5435 nodesToRemoveFromChain.append(curr->node());
5439 // Now set the hover state for our new object up to the root.
5440 for (RenderObject* curr = newHoverObj; curr; curr = curr->hoverAncestor()) {
5441 if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5442 nodesToAddToChain.append(curr->node());
5445 // mouseenter and mouseleave events do not bubble, so they are dispatched iff there is a capturing
5446 // event handler on an ancestor or a normal event handler on the element itself. This special
5447 // handling is necessary to avoid O(n^2) capturing event handler checks. We'll check the previously
5448 // hovered node's ancestor tree for 'mouseleave' handlers here, then check the newly hovered node's
5449 // ancestor tree for 'mouseenter' handlers after dispatching the 'mouseleave' events (as the handler
5450 // for 'mouseleave' might set a capturing 'mouseenter' handler, odd as that might be).
5451 bool ancestorHasCapturingMouseleaveListener = false;
5452 if (event && newHoverNode != oldHoverNode.get()) {
5453 for (Node* node = oldHoverNode.get(); node; node = node->parentOrShadowHostNode()) {
5454 if (node->hasCapturingEventListeners(EventTypeNames::mouseleave)) {
5455 ancestorHasCapturingMouseleaveListener = true;
5461 size_t removeCount = nodesToRemoveFromChain.size();
5462 for (size_t i = 0; i < removeCount; ++i) {
5463 nodesToRemoveFromChain[i]->setHovered(false);
5464 if (event && (ancestorHasCapturingMouseleaveListener || nodesToRemoveFromChain[i]->hasEventListeners(EventTypeNames::mouseleave)))
5465 nodesToRemoveFromChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseleave, 0, newHoverNode);
5468 bool ancestorHasCapturingMouseenterListener = false;
5469 if (event && newHoverNode != oldHoverNode.get()) {
5470 for (Node* node = newHoverNode; node; node = node->parentOrShadowHostNode()) {
5471 if (node->hasCapturingEventListeners(EventTypeNames::mouseenter)) {
5472 ancestorHasCapturingMouseenterListener = true;
5478 bool sawCommonAncestor = false;
5479 size_t addCount = nodesToAddToChain.size();
5480 for (size_t i = 0; i < addCount; ++i) {
5481 // Elements past the common ancestor do not change hover state, but might change active state.
5482 if (ancestorNode && nodesToAddToChain[i] == ancestorNode)
5483 sawCommonAncestor = true;
5484 if (allowActiveChanges)
5485 nodesToAddToChain[i]->setActive(true);
5486 if (!sawCommonAncestor) {
5487 nodesToAddToChain[i]->setHovered(true);
5488 if (event && (ancestorHasCapturingMouseenterListener || nodesToAddToChain[i]->hasEventListeners(EventTypeNames::mouseenter)))
5489 nodesToAddToChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseenter, 0, oldHoverNode.get());
5494 bool Document::haveStylesheetsLoaded() const
5496 return m_styleEngine->haveStylesheetsLoaded();
5499 Locale& Document::getCachedLocale(const AtomicString& locale)
5501 AtomicString localeKey = locale;
5502 if (locale.isEmpty() || !RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
5503 return Locale::defaultLocale();
5504 LocaleIdentifierToLocaleMap::AddResult result = m_localeCache.add(localeKey, nullptr);
5505 if (result.isNewEntry)
5506 result.storedValue->value = Locale::create(localeKey);
5507 return *(result.storedValue->value);
5510 Document& Document::ensureTemplateDocument()
5512 if (isTemplateDocument())
5515 if (m_templateDocument)
5516 return *m_templateDocument;
5518 if (isHTMLDocument()) {
5519 DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL()).withNewRegistrationContext();
5520 m_templateDocument = HTMLDocument::create(init);
5522 m_templateDocument = Document::create(DocumentInit(blankURL()));
5525 m_templateDocument->m_templateDocumentHost = this; // balanced in dtor.
5527 return *m_templateDocument.get();
5530 void Document::didAssociateFormControl(Element* element)
5532 if (!frame() || !frame()->page())
5534 m_associatedFormControls.add(element);
5535 if (!m_didAssociateFormControlsTimer.isActive())
5536 m_didAssociateFormControlsTimer.startOneShot(0, FROM_HERE);
5539 void Document::didAssociateFormControlsTimerFired(Timer<Document>* timer)
5541 ASSERT_UNUSED(timer, timer == &m_didAssociateFormControlsTimer);
5542 if (!frame() || !frame()->page())
5545 Vector<RefPtr<Element> > associatedFormControls;
5546 copyToVector(m_associatedFormControls, associatedFormControls);
5548 frame()->page()->chrome().client().didAssociateFormControls(associatedFormControls);
5549 m_associatedFormControls.clear();
5552 float Document::devicePixelRatio() const
5554 return m_frame ? m_frame->devicePixelRatio() : 1.0;
5557 PassOwnPtr<LifecycleNotifier<Document> > Document::createLifecycleNotifier()
5559 return DocumentLifecycleNotifier::create(this);
5562 DocumentLifecycleNotifier& Document::lifecycleNotifier()
5564 return static_cast<DocumentLifecycleNotifier&>(LifecycleContext<Document>::lifecycleNotifier());
5567 void Document::removedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
5569 // If we're in document teardown, then we don't need this notification of our sheet's removal.
5570 // styleResolverChanged() is needed even when the document is inactive so that
5571 // imported docuements (which is inactive) notifies the change to the master document.
5573 styleEngine()->modifiedStyleSheet(sheet);
5574 styleResolverChanged(when, updateMode);
5577 void Document::modifiedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
5579 // If we're in document teardown, then we don't need this notification of our sheet's removal.
5580 // styleResolverChanged() is needed even when the document is inactive so that
5581 // imported docuements (which is inactive) notifies the change to the master document.
5583 styleEngine()->modifiedStyleSheet(sheet);
5584 styleResolverChanged(when, updateMode);
5587 TextAutosizer* Document::textAutosizer()
5589 if (!m_textAutosizer && !RuntimeEnabledFeatures::fastTextAutosizingEnabled())
5590 m_textAutosizer = TextAutosizer::create(this);
5591 return m_textAutosizer.get();
5594 FastTextAutosizer* Document::fastTextAutosizer()
5596 if (!m_fastTextAutosizer && RuntimeEnabledFeatures::fastTextAutosizingEnabled())
5597 m_fastTextAutosizer = FastTextAutosizer::create(this);
5598 return m_fastTextAutosizer.get();
5601 void Document::setAutofocusElement(Element* element)
5604 m_autofocusElement = nullptr;
5607 if (m_hasAutofocused)
5609 m_hasAutofocused = true;
5610 ASSERT(!m_autofocusElement);
5611 m_autofocusElement = element;
5612 m_taskRunner->postTask(AutofocusTask::create());
5615 Element* Document::activeElement() const
5617 if (Element* element = treeScope().adjustedFocusedElement())
5622 bool Document::hasFocus() const
5624 Page* page = this->page();
5627 if (!page->focusController().isActive() || !page->focusController().isFocused())
5629 Frame* focusedFrame = page->focusController().focusedFrame();
5630 if (focusedFrame && focusedFrame->isLocalFrame()) {
5631 if (toLocalFrame(focusedFrame)->tree().isDescendantOf(frame()))
5637 template<unsigned type>
5638 bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
5640 if (nodeListCounts[type] && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
5642 return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
5646 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
5651 bool Document::shouldInvalidateNodeListCaches(const QualifiedName* attrName) const
5654 return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListCounts, *attrName);
5656 for (int type = 0; type < numNodeListInvalidationTypes; type++) {
5657 if (m_nodeListCounts[type])
5664 void Document::invalidateNodeListCaches(const QualifiedName* attrName)
5666 HashSet<LiveNodeListBase*>::iterator end = m_listsInvalidatedAtDocument.end();
5667 for (HashSet<LiveNodeListBase*>::iterator it = m_listsInvalidatedAtDocument.begin(); it != end; ++it)
5668 (*it)->invalidateCacheForAttribute(attrName);
5671 void Document::clearWeakMembers(Visitor* visitor)
5673 if (m_axObjectCache)
5674 m_axObjectCache->clearWeakMembers(visitor);
5677 m_markers->clearWeakMembers(visitor);
5679 // FIXME: Oilpan: Use a weak counted set instead.
5680 if (m_touchEventTargets) {
5681 Vector<Node*> deadNodes;
5682 for (TouchEventTargetSet::iterator it = m_touchEventTargets->begin(); it != m_touchEventTargets->end(); ++it) {
5683 if (!visitor->isAlive(it->key))
5684 deadNodes.append(it->key);
5686 for (unsigned i = 0; i < deadNodes.size(); ++i)
5687 didClearTouchEventHandlers(deadNodes[i]);
5691 void Document::trace(Visitor* visitor)
5693 visitor->trace(m_docType);
5694 visitor->trace(m_implementation);
5695 visitor->trace(m_autofocusElement);
5696 visitor->trace(m_focusedElement);
5697 visitor->trace(m_hoverNode);
5698 visitor->trace(m_activeHoverElement);
5699 visitor->trace(m_documentElement);
5700 visitor->trace(m_titleElement);
5701 visitor->trace(m_currentScriptStack);
5702 visitor->trace(m_transformSourceDocument);
5703 visitor->trace(m_cssCanvasElements);
5704 visitor->trace(m_topLayerElements);
5705 visitor->trace(m_elemSheet);
5706 visitor->trace(m_styleEngine);
5707 visitor->trace(m_formController);
5708 visitor->trace(m_fetcher);
5709 visitor->trace(m_contextFeatures);
5710 visitor->trace(m_styleSheetList);
5711 visitor->trace(m_mediaQueryMatcher);
5712 visitor->trace(m_associatedFormControls);
5713 visitor->trace(m_templateDocument);
5714 visitor->trace(m_templateDocumentHost);
5715 visitor->trace(m_visibilityObservers);
5716 visitor->trace(m_userActionElements);
5717 visitor->registerWeakMembers<Document, &Document::clearWeakMembers>(this);
5718 DocumentSupplementable::trace(visitor);
5719 TreeScope::trace(visitor);
5720 ContainerNode::trace(visitor);
5721 ExecutionContext::trace(visitor);
5724 } // namespace WebCore