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 "bindings/v8/CustomElementConstructorBuilder.h"
32 #include "bindings/v8/Dictionary.h"
33 #include "bindings/v8/ExceptionMessages.h"
34 #include "bindings/v8/ExceptionState.h"
35 #include "bindings/v8/ExceptionStatePlaceholder.h"
36 #include "bindings/v8/ScriptController.h"
37 #include "core/HTMLElementFactory.h"
38 #include "core/HTMLNames.h"
39 #include "core/SVGElementFactory.h"
40 #include "core/SVGNames.h"
41 #include "core/XMLNSNames.h"
42 #include "core/XMLNames.h"
43 #include "core/accessibility/AXObjectCache.h"
44 #include "core/animation/AnimationTimeline.h"
45 #include "core/animation/DocumentAnimations.h"
46 #include "core/css/CSSFontSelector.h"
47 #include "core/css/CSSStyleDeclaration.h"
48 #include "core/css/CSSStyleSheet.h"
49 #include "core/css/MediaQueryMatcher.h"
50 #include "core/css/StylePropertySet.h"
51 #include "core/css/StyleSheetContents.h"
52 #include "core/css/StyleSheetList.h"
53 #include "core/css/invalidation/StyleInvalidator.h"
54 #include "core/css/parser/BisonCSSParser.h"
55 #include "core/css/resolver/FontBuilder.h"
56 #include "core/css/resolver/StyleResolver.h"
57 #include "core/css/resolver/StyleResolverStats.h"
58 #include "core/dom/AddConsoleMessageTask.h"
59 #include "core/dom/Attr.h"
60 #include "core/dom/CDATASection.h"
61 #include "core/dom/Comment.h"
62 #include "core/dom/ContextFeatures.h"
63 #include "core/dom/DOMImplementation.h"
64 #include "core/dom/DocumentFragment.h"
65 #include "core/dom/DocumentLifecycleNotifier.h"
66 #include "core/dom/DocumentLifecycleObserver.h"
67 #include "core/dom/DocumentMarkerController.h"
68 #include "core/dom/DocumentType.h"
69 #include "core/dom/Element.h"
70 #include "core/dom/ElementDataCache.h"
71 #include "core/dom/ElementTraversal.h"
72 #include "core/dom/ExceptionCode.h"
73 #include "core/dom/ExecutionContextTask.h"
74 #include "core/dom/MainThreadTaskRunner.h"
75 #include "core/dom/MutationObserver.h"
76 #include "core/dom/NoEventDispatchAssertion.h"
77 #include "core/dom/NodeChildRemovalTracker.h"
78 #include "core/dom/NodeFilter.h"
79 #include "core/dom/NodeIterator.h"
80 #include "core/dom/NodeRareData.h"
81 #include "core/dom/NodeRenderStyle.h"
82 #include "core/dom/NodeRenderingTraversal.h"
83 #include "core/dom/NodeTraversal.h"
84 #include "core/dom/NodeWithIndex.h"
85 #include "core/dom/ProcessingInstruction.h"
86 #include "core/dom/RequestAnimationFrameCallback.h"
87 #include "core/dom/ScriptForbiddenScope.h"
88 #include "core/dom/ScriptRunner.h"
89 #include "core/dom/ScriptedAnimationController.h"
90 #include "core/dom/SelectorQuery.h"
91 #include "core/dom/StyleEngine.h"
92 #include "core/dom/TouchList.h"
93 #include "core/dom/TransformSource.h"
94 #include "core/dom/TreeWalker.h"
95 #include "core/dom/VisitedLinkState.h"
96 #include "core/dom/XMLDocument.h"
97 #include "core/dom/custom/CustomElementRegistrationContext.h"
98 #include "core/dom/shadow/ElementShadow.h"
99 #include "core/dom/shadow/ShadowRoot.h"
100 #include "core/editing/Editor.h"
101 #include "core/editing/FrameSelection.h"
102 #include "core/editing/SpellChecker.h"
103 #include "core/events/BeforeUnloadEvent.h"
104 #include "core/events/Event.h"
105 #include "core/events/EventFactory.h"
106 #include "core/events/EventListener.h"
107 #include "core/events/HashChangeEvent.h"
108 #include "core/events/PageTransitionEvent.h"
109 #include "core/events/ScopedEventQueue.h"
110 #include "core/fetch/ResourceFetcher.h"
111 #include "core/frame/LocalDOMWindow.h"
112 #include "core/frame/FrameConsole.h"
113 #include "core/frame/FrameHost.h"
114 #include "core/frame/FrameView.h"
115 #include "core/frame/History.h"
116 #include "core/frame/LocalFrame.h"
117 #include "core/frame/Settings.h"
118 #include "core/frame/csp/ContentSecurityPolicy.h"
119 #include "core/html/DocumentNameCollection.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/HTMLScriptElement.h"
135 #include "core/html/HTMLStyleElement.h"
136 #include "core/html/HTMLTemplateElement.h"
137 #include "core/html/HTMLTitleElement.h"
138 #include "core/html/PluginDocument.h"
139 #include "core/html/WindowNameCollection.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/rendering/compositing/RenderLayerCompositor.h"
174 #include "core/svg/SVGDocumentExtensions.h"
175 #include "core/svg/SVGFontFaceElement.h"
176 #include "core/svg/SVGTitleElement.h"
177 #include "core/svg/SVGUseElement.h"
178 #include "core/workers/SharedWorkerRepositoryClient.h"
179 #include "core/xml/XSLTProcessor.h"
180 #include "core/xml/parser/XMLDocumentParser.h"
181 #include "platform/DateComponents.h"
182 #include "platform/Language.h"
183 #include "platform/RuntimeEnabledFeatures.h"
184 #include "platform/TraceEvent.h"
185 #include "platform/network/ContentSecurityPolicyParsers.h"
186 #include "platform/network/HTTPParsers.h"
187 #include "platform/scroll/ScrollbarTheme.h"
188 #include "platform/text/PlatformLocale.h"
189 #include "platform/text/SegmentedString.h"
190 #include "platform/weborigin/OriginAccessEntry.h"
191 #include "platform/weborigin/SchemeRegistry.h"
192 #include "platform/weborigin/SecurityOrigin.h"
193 #include "public/platform/Platform.h"
194 #include "wtf/CurrentTime.h"
195 #include "wtf/HashFunctions.h"
196 #include "wtf/MainThread.h"
197 #include "wtf/StdLibExtras.h"
198 #include "wtf/TemporaryChange.h"
199 #include "wtf/text/StringBuffer.h"
200 #include "wtf/text/TextEncodingRegistry.h"
203 using namespace Unicode;
207 using namespace HTMLNames;
209 static const unsigned cMaxWriteRecursionDepth = 21;
211 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
212 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
214 static const int cLayoutScheduleThreshold = 250;
216 // DOM Level 2 says (letters added):
218 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
219 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
220 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
221 // 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.
222 // 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.
223 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
224 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
225 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
226 // i) Characters ':' and '_' are allowed as name-start characters.
227 // j) Characters '-' and '.' are allowed as name characters.
229 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
231 static inline bool isValidNameStart(UChar32 c)
234 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
238 if (c == ':' || c == '_')
241 // rules (a) and (f) above
242 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
243 if (!(Unicode::category(c) & nameStartMask))
247 if (c >= 0xF900 && c < 0xFFFE)
251 DecompositionType decompType = decompositionType(c);
252 if (decompType == DecompositionFont || decompType == DecompositionCompat)
258 static inline bool isValidNamePart(UChar32 c)
260 // rules (a), (e), and (i) above
261 if (isValidNameStart(c))
264 // rules (g) and (h) above
265 if (c == 0x00B7 || c == 0x0387)
269 if (c == '-' || c == '.')
272 // rules (b) and (f) above
273 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
274 if (!(Unicode::category(c) & otherNamePartMask))
278 if (c >= 0xF900 && c < 0xFFFE)
282 DecompositionType decompType = decompositionType(c);
283 if (decompType == DecompositionFont || decompType == DecompositionCompat)
289 static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
291 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
293 // If a Document has the address "about:blank"
294 // The origin of the Document is the origin it was assigned when its browsing context was created.
296 // Note: We generalize this to all "blank" URLs and invalid URLs because we
297 // treat all of these URLs as about:blank.
299 return url.isEmpty() || url.protocolIsAbout();
302 static Widget* widgetForElement(const Element& focusedElement)
304 RenderObject* renderer = focusedElement.renderer();
305 if (!renderer || !renderer->isWidget())
307 return toRenderWidget(renderer)->widget();
310 static bool acceptsEditingFocus(const Element& element)
312 ASSERT(element.rendererIsEditable());
314 return element.document().frame() && element.rootEditableElement();
317 static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, const Frame* targetFrame)
319 // targetFrame can be 0 when we're trying to navigate a top-level frame
320 // that has a 0 opener.
324 const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
325 for (const Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
326 // FIXME: SecurityOrigins need to be refactored to work with out-of-process iframes.
327 // For now we prevent navigation between cross-process frames.
328 if (!ancestorFrame->isLocalFrame())
331 Document* ancestorDocument = toLocalFrame(ancestorFrame)->document();
332 // FIXME: Should be an ASSERT? Frames should alway have documents.
333 if (!ancestorDocument)
336 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
337 if (activeSecurityOrigin.canAccess(ancestorSecurityOrigin))
340 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
341 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
342 // something more general instead?
343 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
350 static void printNavigationErrorMessage(const LocalFrame& frame, const KURL& activeURL, const char* reason)
352 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame.document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
354 // FIXME: should we print to the console of the document performing the navigation instead?
355 frame.domWindow()->printErrorMessage(message);
358 uint64_t Document::s_globalTreeVersion = 0;
360 // This class doesn't work with non-Document ExecutionContext.
361 class AutofocusTask FINAL : public ExecutionContextTask {
363 static PassOwnPtr<AutofocusTask> create()
365 return adoptPtr(new AutofocusTask());
367 virtual ~AutofocusTask() { }
371 virtual void performTask(ExecutionContext* context) OVERRIDE
373 Document* document = toDocument(context);
374 if (RefPtrWillBeRawPtr<Element> element = document->autofocusElement()) {
375 document->setAutofocusElement(0);
381 DocumentVisibilityObserver::DocumentVisibilityObserver(Document& document)
382 : m_document(nullptr)
384 registerObserver(document);
387 DocumentVisibilityObserver::~DocumentVisibilityObserver()
390 unregisterObserver();
394 void DocumentVisibilityObserver::trace(Visitor* visitor)
396 visitor->trace(m_document);
399 void DocumentVisibilityObserver::unregisterObserver()
402 m_document->unregisterVisibilityObserver(this);
403 m_document = nullptr;
407 void DocumentVisibilityObserver::registerObserver(Document& document)
410 m_document = &document;
412 m_document->registerVisibilityObserver(this);
415 void DocumentVisibilityObserver::setObservedDocument(Document& document)
417 unregisterObserver();
418 registerObserver(document);
421 Document::Document(const DocumentInit& initializer, DocumentClassFlags documentClasses)
422 : ContainerNode(0, CreateDocument)
424 , m_hasNodesWithPlaceholderStyle(false)
425 , m_evaluateMediaQueriesOnStyleRecalc(false)
426 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
427 , m_frame(initializer.frame())
428 , m_domWindow(m_frame ? m_frame->domWindow() : 0)
429 , m_importsController(initializer.importsController())
430 , m_activeParserCount(0)
431 , m_contextFeatures(ContextFeatures::defaultSwitch())
432 , m_wellFormed(false)
434 , m_paginatedForScreen(false)
435 , m_compatibilityMode(NoQuirksMode)
436 , m_compatibilityModeLocked(false)
437 , m_executeScriptsWaitingForResourcesTimer(this, &Document::executeScriptsWaitingForResourcesTimerFired)
438 , m_hasAutofocused(false)
439 , m_clearFocusedElementTimer(this, &Document::clearFocusedElementTimerFired)
440 , m_domTreeVersion(++s_globalTreeVersion)
442 , m_mutationObserverTypes(0)
443 , m_visitedLinkState(VisitedLinkState::create(*this))
444 , m_visuallyOrdered(false)
445 , m_readyState(Complete)
447 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
448 , m_containsValidityStyleRules(false)
449 , m_updateFocusAppearanceRestoresSelection(false)
450 , m_containsPlugins(false)
451 , m_ignoreDestructiveWriteCount(0)
452 , m_markers(adoptPtrWillBeNoop(new DocumentMarkerController))
453 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
454 , m_cssTarget(nullptr)
455 , m_loadEventProgress(LoadEventNotRun)
456 , m_startTime(currentTime())
457 , m_scriptRunner(ScriptRunner::create(this))
458 , m_xmlVersion("1.0")
459 , m_xmlStandalone(StandaloneUnspecified)
460 , m_hasXMLDeclaration(0)
461 , m_designMode(inherit)
462 , m_hasAnnotatedRegions(false)
463 , m_annotatedRegionsDirty(false)
464 , m_useSecureKeyboardEntryWhenActive(false)
465 , m_documentClasses(documentClasses)
466 , m_isViewSource(false)
467 , m_sawElementsInKnownNamespaces(false)
468 , m_isSrcdocDocument(false)
469 , m_isMobileDocument(false)
470 , m_isTransitionDocument(false)
473 , m_weakFactory(this)
475 , m_contextDocument(initializer.contextDocument())
476 , m_hasFullscreenElementStack(false)
477 , m_loadEventDelayCount(0)
478 , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
479 , m_pluginLoadingTimer(this, &Document::pluginLoadingTimerFired)
480 , m_didSetReferrerPolicy(false)
481 , m_referrerPolicy(ReferrerPolicyDefault)
482 , m_directionSetOnDocumentElement(false)
483 , m_writingModeSetOnDocumentElement(false)
484 , m_writeRecursionIsTooDeep(false)
485 , m_writeRecursionDepth(0)
486 , m_taskRunner(MainThreadTaskRunner::create(this))
487 , m_registrationContext(initializer.registrationContext(this))
488 , m_elementDataCacheClearTimer(this, &Document::elementDataCacheClearTimerFired)
490 , m_didDispatchViewportPropertiesChanged(false)
492 , m_timeline(AnimationTimeline::create(this))
493 , m_templateDocumentHost(nullptr)
494 , m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
495 , m_hasViewportUnits(false)
496 , m_styleRecalcElementCounter(0)
499 ScriptWrappable::init(this);
502 ASSERT(m_frame->page());
503 provideContextFeaturesToDocumentFrom(*this, *m_frame->page());
505 m_fetcher = m_frame->loader().documentLoader()->fetcher();
509 m_fetcher = ResourceFetcher::create(0);
510 m_fetcher->setDocument(this);
512 // We depend on the url getting immediately set in subframes, but we
513 // also depend on the url NOT getting immediately set in opened windows.
514 // See fast/dom/early-frame-url.html
515 // and fast/dom/location-new-window-no-crash.html, respectively.
516 // FIXME: Can/should we unify this behavior?
517 if (initializer.shouldSetURL())
518 setURL(initializer.url());
520 initSecurityContext(initializer);
524 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); ++i)
525 m_nodeListCounts[i] = 0;
528 InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
530 m_lifecycle.advanceTo(DocumentLifecycle::Inactive);
532 // Since CSSFontSelector requires Document::m_fetcher and StyleEngine owns
533 // CSSFontSelector, need to initialize m_styleEngine after initializing
535 m_styleEngine = StyleEngine::create(*this);
538 Document::~Document()
540 ASSERT(!renderView());
541 ASSERT(!parentTreeScope());
543 ASSERT(m_ranges.isEmpty());
544 ASSERT(!hasGuardRefCount());
545 // With Oilpan, either the document outlives the visibility observers
546 // or the visibility observers and the document die in the same GC round.
547 // When they die in the same GC round, the list of visibility observers
548 // will not be empty on Document destruction.
549 ASSERT(m_visibilityObservers.isEmpty());
551 if (m_templateDocument)
552 m_templateDocument->m_templateDocumentHost = nullptr; // balanced in ensureTemplateDocument().
554 m_scriptRunner.clear();
556 // FIXME: Oilpan: Not removing event listeners here also means that we do
557 // not notify the inspector instrumentation that the event listeners are
558 // gone. The Document and all the nodes in the document are gone, so maybe
560 removeAllEventListenersRecursively();
562 // Currently we believe that Document can never outlive the parser.
563 // Although the Document may be replaced synchronously, DocumentParsers
564 // generally keep at least one reference to an Element which would in turn
565 // has a reference to the Document. If you hit this ASSERT, then that
566 // assumption is wrong. DocumentParser::detach() should ensure that even
567 // if the DocumentParser outlives the Document it won't cause badness.
568 ASSERT(!m_parser || m_parser->refCount() == 1);
572 if (this == topDocument())
573 clearAXObjectCache();
576 if (m_styleSheetList)
577 m_styleSheetList->detachFromDocument();
579 if (m_importsController)
580 HTMLImportsController::removeFrom(*this);
582 m_timeline->detachFromDocument();
584 // We need to destroy CSSFontSelector before destroying m_fetcher.
586 m_styleEngine->detachFromDocument();
589 m_elemSheet->clearOwnerNode();
591 // It's possible for multiple Documents to end up referencing the same ResourceFetcher (e.g., SVGImages
592 // load the initial empty document and the SVGDocument with the same DocumentLoader).
593 if (m_fetcher->document() == this)
594 m_fetcher->setDocument(nullptr);
597 // We must call clearRareData() here since a Document class inherits TreeScope
598 // as well as Node. See a comment on TreeScope.h for the reason.
602 ASSERT(m_listsInvalidatedAtDocument.isEmpty());
604 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); ++i)
605 ASSERT(!m_nodeListCounts[i]);
610 InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
614 void Document::dispose()
616 ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
618 // We must make sure not to be retaining any of our children through
619 // these extra pointers or we will create a reference cycle.
621 m_focusedElement = nullptr;
622 m_hoverNode = nullptr;
623 m_activeHoverElement = nullptr;
624 m_titleElement = nullptr;
625 m_documentElement = nullptr;
626 m_contextFeatures = ContextFeatures::defaultSwitch();
627 m_userActionElements.documentDidRemoveLastRef();
628 m_associatedFormControls.clear();
632 m_registrationContext.clear();
634 if (m_importsController)
635 HTMLImportsController::removeFrom(*this);
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();
650 // FIXME: consider using ActiveDOMObject.
651 if (m_scriptedAnimationController)
652 m_scriptedAnimationController->clearDocumentPointer();
653 m_scriptedAnimationController.clear();
656 accessSVGExtensions().pauseAnimations();
658 m_lifecycle.advanceTo(DocumentLifecycle::Disposed);
659 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 m_evaluateMediaQueriesOnStyleRecalc = true;
680 styleEngine()->clearMediaQueryRuleSetStyleSheets();
683 void Document::setCompatibilityMode(CompatibilityMode mode)
685 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
687 bool wasInQuirksMode = inQuirksMode();
688 m_compatibilityMode = mode;
689 selectorQueryCache().invalidate();
690 if (inQuirksMode() != wasInQuirksMode) {
691 // All injected stylesheets have to reparse using the different mode.
692 m_styleEngine->invalidateInjectedStyleSheetCache();
696 String Document::compatMode() const
698 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
701 void Document::setDoctype(PassRefPtrWillBeRawPtr<DocumentType> docType)
703 // This should never be called more than once.
704 ASSERT(!m_docType || !docType);
707 this->adoptIfNeeded(*m_docType);
708 if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
709 m_isMobileDocument = true;
711 // Doctype affects the interpretation of the stylesheets.
712 clearStyleResolver();
715 DOMImplementation& Document::implementation()
717 if (!m_implementation)
718 m_implementation = DOMImplementation::create(*this);
719 return *m_implementation;
722 bool Document::hasAppCacheManifest() const
724 return isHTMLHtmlElement(documentElement()) && documentElement()->hasAttribute(manifestAttr);
727 Location* Document::location() const
732 return &domWindow()->location();
735 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
737 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
738 m_documentElement = ElementTraversal::firstWithin(*this);
741 PassRefPtrWillBeRawPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& exceptionState)
743 if (!isValidName(name)) {
744 exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + name + "') is not a valid name.");
748 if (isXHTMLDocument() || isHTMLDocument())
749 return HTMLElementFactory::createHTMLElement(isHTMLDocument() ? name.lower() : name, *this, 0, false);
751 return Element::create(QualifiedName(nullAtom, name, nullAtom), this);
754 PassRefPtrWillBeRawPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& exceptionState)
756 if (!isValidName(localName)) {
757 exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + localName + "') is not a valid name.");
761 RefPtrWillBeRawPtr<Element> element;
763 if (CustomElement::isValidName(localName) && registrationContext()) {
764 element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI));
766 element = createElement(localName, exceptionState);
767 if (exceptionState.hadException())
771 if (!typeExtension.isEmpty())
772 CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
774 return element.release();
777 static inline QualifiedName createQualifiedName(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
779 AtomicString prefix, localName;
780 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
781 return QualifiedName::null();
783 QualifiedName qName(prefix, localName, namespaceURI);
784 if (!Document::hasValidNamespaceForElements(qName)) {
785 exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
786 return QualifiedName::null();
792 PassRefPtrWillBeRawPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
794 QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
795 if (qName == QualifiedName::null())
798 return createElement(qName, false);
801 PassRefPtrWillBeRawPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
803 QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
804 if (qName == QualifiedName::null())
807 RefPtrWillBeRawPtr<Element> element;
808 if (CustomElement::isValidName(qName.localName()) && registrationContext())
809 element = registrationContext()->createCustomTagElement(*this, qName);
811 element = createElement(qName, false);
813 if (!typeExtension.isEmpty())
814 CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
816 return element.release();
819 ScriptValue Document::registerElement(WebCore::ScriptState* scriptState, const AtomicString& name, ExceptionState& exceptionState)
821 return registerElement(scriptState, name, Dictionary(), exceptionState);
824 ScriptValue Document::registerElement(WebCore::ScriptState* scriptState, const AtomicString& name, const Dictionary& options, ExceptionState& exceptionState, CustomElement::NameSet validNames)
826 if (!registrationContext()) {
827 exceptionState.throwDOMException(NotSupportedError, "No element registration context is available.");
828 return ScriptValue();
831 CustomElementConstructorBuilder constructorBuilder(scriptState, &options);
832 registrationContext()->registerElement(this, &constructorBuilder, name, validNames, exceptionState);
833 return constructorBuilder.bindingsReturnValue();
836 void Document::setImportsController(HTMLImportsController* controller)
838 ASSERT(!m_importsController || !controller);
839 m_importsController = controller;
842 HTMLImportLoader* Document::importLoader() const
844 if (!m_importsController)
846 return m_importsController->loaderFor(*this);
849 bool Document::haveImportsLoaded() const
851 if (!m_importsController)
853 return !m_importsController->shouldBlockScriptExecution(*this);
856 LocalDOMWindow* Document::executingWindow()
858 if (LocalDOMWindow* owningWindow = domWindow())
860 if (HTMLImportsController* import = this->importsController())
861 return import->master()->domWindow();
865 LocalFrame* Document::executingFrame()
867 LocalDOMWindow* window = executingWindow();
870 return window->frame();
873 PassRefPtrWillBeRawPtr<DocumentFragment> Document::createDocumentFragment()
875 return DocumentFragment::create(*this);
878 PassRefPtrWillBeRawPtr<Text> Document::createTextNode(const String& data)
880 return Text::create(*this, data);
883 PassRefPtrWillBeRawPtr<Comment> Document::createComment(const String& data)
885 return Comment::create(*this, data);
888 PassRefPtrWillBeRawPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& exceptionState)
890 if (isHTMLDocument()) {
891 exceptionState.throwDOMException(NotSupportedError, "This operation is not supported for HTML documents.");
894 if (data.contains("]]>")) {
895 exceptionState.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
898 return CDATASection::create(*this, data);
901 PassRefPtrWillBeRawPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& exceptionState)
903 if (!isValidName(target)) {
904 exceptionState.throwDOMException(InvalidCharacterError, "The target provided ('" + target + "') is not a valid name.");
907 if (data.contains("?>")) {
908 exceptionState.throwDOMException(InvalidCharacterError, "The data provided ('" + data + "') contains '?>'.");
911 return ProcessingInstruction::create(*this, target, data);
914 PassRefPtrWillBeRawPtr<Text> Document::createEditingTextNode(const String& text)
916 return Text::createEditingText(*this, text);
919 bool Document::importContainerNodeChildren(ContainerNode* oldContainerNode, PassRefPtrWillBeRawPtr<ContainerNode> newContainerNode, ExceptionState& exceptionState)
921 for (Node* oldChild = oldContainerNode->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
922 RefPtrWillBeRawPtr<Node> newChild = importNode(oldChild, true, exceptionState);
923 if (exceptionState.hadException())
925 newContainerNode->appendChild(newChild.release(), exceptionState);
926 if (exceptionState.hadException())
933 PassRefPtrWillBeRawPtr<Node> Document::importNode(Node* importedNode, ExceptionState& ec)
935 UseCounter::countDeprecation(this, UseCounter::DocumentImportNodeOptionalArgument);
936 return importNode(importedNode, true, ec);
939 PassRefPtrWillBeRawPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& exceptionState)
942 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
946 switch (importedNode->nodeType()) {
948 return createTextNode(importedNode->nodeValue());
949 case CDATA_SECTION_NODE:
950 return CDATASection::create(*this, importedNode->nodeValue());
951 case PROCESSING_INSTRUCTION_NODE:
952 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), exceptionState);
954 return createComment(importedNode->nodeValue());
955 case DOCUMENT_TYPE_NODE: {
956 DocumentType* doctype = toDocumentType(importedNode);
957 return DocumentType::create(this, doctype->name(), doctype->publicId(), doctype->systemId());
960 Element* oldElement = toElement(importedNode);
961 // FIXME: The following check might be unnecessary. Is it possible that
962 // oldElement has mismatched prefix/namespace?
963 if (!hasValidNamespaceForElements(oldElement->tagQName())) {
964 exceptionState.throwDOMException(NamespaceError, "The imported node has an invalid namespace.");
967 RefPtrWillBeRawPtr<Element> newElement = createElement(oldElement->tagQName(), false);
969 newElement->cloneDataFromElement(*oldElement);
972 if (!importContainerNodeChildren(oldElement, newElement, exceptionState))
974 if (isHTMLTemplateElement(*oldElement)
975 && !importContainerNodeChildren(toHTMLTemplateElement(oldElement)->content(), toHTMLTemplateElement(newElement)->content(), exceptionState))
979 return newElement.release();
982 return Attr::create(*this, QualifiedName(nullAtom, AtomicString(toAttr(importedNode)->name()), nullAtom), toAttr(importedNode)->value());
983 case DOCUMENT_FRAGMENT_NODE: {
984 if (importedNode->isShadowRoot()) {
985 // ShadowRoot nodes should not be explicitly importable.
986 // Either they are imported along with their host node, or created implicitly.
987 exceptionState.throwDOMException(NotSupportedError, "The node provided is a shadow root, which may not be imported.");
990 DocumentFragment* oldFragment = toDocumentFragment(importedNode);
991 RefPtrWillBeRawPtr<DocumentFragment> newFragment = createDocumentFragment();
992 if (deep && !importContainerNodeChildren(oldFragment, newFragment, exceptionState))
995 return newFragment.release();
998 exceptionState.throwDOMException(NotSupportedError, "The node provided is a document, which may not be imported.");
1002 ASSERT_NOT_REACHED();
1006 PassRefPtrWillBeRawPtr<Node> Document::adoptNode(PassRefPtrWillBeRawPtr<Node> source, ExceptionState& exceptionState)
1009 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1013 EventQueueScope scope;
1015 switch (source->nodeType()) {
1017 case DOCUMENT_TYPE_NODE:
1018 exceptionState.throwDOMException(NotSupportedError, "The node provided is of type '" + source->nodeName() + "', which may not be adopted.");
1020 case ATTRIBUTE_NODE: {
1021 Attr* attr = toAttr(source.get());
1022 if (RefPtrWillBeRawPtr<Element> ownerElement = attr->ownerElement())
1023 ownerElement->removeAttributeNode(attr, exceptionState);
1027 if (source->isShadowRoot()) {
1028 // ShadowRoot cannot disconnect itself from the host node.
1029 exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a shadow root, which may not be adopted.");
1033 if (source->isFrameOwnerElement()) {
1034 HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
1035 // FIXME(kenrb): the downcast can be removed when the FrameTree supports RemoteFrames.
1036 if (frame() && frame()->tree().isDescendantOf(toLocalFrameTemporary(frameOwnerElement->contentFrame()))) {
1037 exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a frame which contains this document.");
1041 if (source->parentNode()) {
1042 source->parentNode()->removeChild(source.get(), exceptionState);
1043 if (exceptionState.hadException())
1048 this->adoptIfNeeded(*source);
1053 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1055 // These checks are from DOM Core Level 2, createElementNS
1056 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1057 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1059 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1062 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1063 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1064 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1065 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1066 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1067 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1070 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1072 return hasValidNamespaceForElements(qName);
1075 // FIXME: This should really be in a possible ElementFactory class
1076 PassRefPtrWillBeRawPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
1078 RefPtrWillBeRawPtr<Element> e = nullptr;
1080 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1081 if (qName.namespaceURI() == xhtmlNamespaceURI)
1082 e = HTMLElementFactory::createHTMLElement(qName.localName(), *this, 0, createdByParser);
1083 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
1084 e = SVGElementFactory::createSVGElement(qName.localName(), *this, createdByParser);
1087 m_sawElementsInKnownNamespaces = true;
1089 e = Element::create(qName, this);
1091 if (e->prefix() != qName.prefix())
1092 e->setTagNameForCreateElementNS(qName);
1094 ASSERT(qName == e->tagQName());
1099 bool Document::regionBasedColumnsEnabled() const
1101 return settings() && settings()->regionBasedColumnsEnabled();
1104 String Document::readyState() const
1106 DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
1107 DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
1108 DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
1110 switch (m_readyState) {
1119 ASSERT_NOT_REACHED();
1123 void Document::setReadyState(ReadyState readyState)
1125 if (readyState == m_readyState)
1128 switch (readyState) {
1130 if (!m_documentTiming.domLoading) {
1131 m_documentTiming.domLoading = monotonicallyIncreasingTime();
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 UseCounter::count(*this, UseCounter::DocumentSetCharset);
1171 if (DocumentLoader* documentLoader = loader())
1172 documentLoader->setUserChosenEncoding(charset);
1173 WTF::TextEncoding encoding(charset);
1174 // In case the encoding didn't exist, we keep the old one (helps some sites specifying invalid encodings).
1175 if (!encoding.isValid())
1177 DocumentEncodingData newEncodingData = m_encodingData;
1178 newEncodingData.setEncoding(encoding);
1179 setEncodingData(newEncodingData);
1182 void Document::setContentLanguage(const AtomicString& language)
1184 if (m_contentLanguage == language)
1186 m_contentLanguage = language;
1188 // Document's style depends on the content language.
1189 setNeedsStyleRecalc(SubtreeStyleChange);
1192 void Document::setXMLVersion(const String& version, ExceptionState& exceptionState)
1194 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1195 exceptionState.throwDOMException(NotSupportedError, "This document does not support the XML version '" + version + "'.");
1199 m_xmlVersion = version;
1202 void Document::setXMLStandalone(bool standalone, ExceptionState& exceptionState)
1204 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1207 KURL Document::baseURI() const
1212 void Document::setContent(const String& content)
1215 // FIXME: This should probably use insert(), but that's (intentionally)
1216 // not implemented for the XML parser as it's normally synonymous with
1217 // document.write(). append() will end up yielding, but close() will
1218 // pump the tokenizer syncrhonously and finish the parse.
1219 m_parser->pinToMainThread();
1220 m_parser->append(content.impl());
1224 String Document::suggestedMIMEType() const
1226 if (isXMLDocument()) {
1227 if (isXHTMLDocument())
1228 return "application/xhtml+xml";
1229 if (isSVGDocument())
1230 return "image/svg+xml";
1231 return "application/xml";
1233 if (xmlStandalone())
1235 if (isHTMLDocument())
1238 if (DocumentLoader* documentLoader = loader())
1239 return documentLoader->responseMIMEType();
1243 void Document::setMimeType(const AtomicString& mimeType)
1245 m_mimeType = mimeType;
1248 AtomicString Document::contentType() const
1250 if (!m_mimeType.isEmpty())
1253 if (DocumentLoader* documentLoader = loader())
1254 return documentLoader->mimeType();
1256 String mimeType = suggestedMIMEType();
1257 if (!mimeType.isEmpty())
1258 return AtomicString(mimeType);
1260 return AtomicString("application/xml");
1263 Element* Document::elementFromPoint(int x, int y) const
1268 return TreeScope::elementFromPoint(x, y);
1271 PassRefPtrWillBeRawPtr<Range> Document::caretRangeFromPoint(int x, int y)
1275 HitTestResult result = hitTestInDocument(this, x, y);
1276 RenderObject* renderer = result.renderer();
1280 Node* node = renderer->node();
1281 Node* shadowAncestorNode = ancestorInThisScope(node);
1282 if (shadowAncestorNode != node) {
1283 unsigned offset = shadowAncestorNode->nodeIndex();
1284 ContainerNode* container = shadowAncestorNode->parentNode();
1285 return Range::create(*this, container, offset, container, offset);
1288 PositionWithAffinity positionWithAffinity = renderer->positionForPoint(result.localPoint());
1289 if (positionWithAffinity.position().isNull())
1292 Position rangeCompliantPosition = positionWithAffinity.position().parentAnchoredEquivalent();
1293 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1297 * Performs three operations:
1298 * 1. Convert control characters to spaces
1299 * 2. Trim leading and trailing spaces
1300 * 3. Collapse internal whitespace.
1302 template <typename CharacterType>
1303 static inline String canonicalizedTitle(Document* document, const String& title)
1305 const CharacterType* characters = title.getCharacters<CharacterType>();
1306 unsigned length = title.length();
1309 StringBuffer<CharacterType> buffer(length);
1310 unsigned builderIndex = 0;
1312 // Skip leading spaces and leading characters that would convert to spaces
1313 for (i = 0; i < length; ++i) {
1314 CharacterType c = characters[i];
1315 if (!(c <= 0x20 || c == 0x7F))
1322 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1323 bool previousCharWasWS = false;
1324 for (; i < length; ++i) {
1325 CharacterType c = characters[i];
1326 if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1327 if (previousCharWasWS)
1329 buffer[builderIndex++] = ' ';
1330 previousCharWasWS = true;
1332 buffer[builderIndex++] = c;
1333 previousCharWasWS = false;
1337 // Strip trailing spaces
1338 while (builderIndex > 0) {
1340 if (buffer[builderIndex] != ' ')
1344 if (!builderIndex && buffer[builderIndex] == ' ')
1347 buffer.shrink(builderIndex + 1);
1349 return String::adopt(buffer);
1352 void Document::updateTitle(const String& title)
1354 if (m_rawTitle == title)
1359 String oldTitle = m_title;
1360 if (m_rawTitle.isEmpty())
1362 else if (m_rawTitle.is8Bit())
1363 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1365 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1367 if (!m_frame || oldTitle == m_title)
1369 m_frame->loader().client()->dispatchDidReceiveTitle(m_title);
1372 void Document::setTitle(const String& title)
1374 // Title set by JavaScript -- overrides any title elements.
1375 if (!isHTMLDocument() && !isXHTMLDocument())
1376 m_titleElement = nullptr;
1377 else if (!m_titleElement) {
1378 HTMLElement* headElement = head();
1381 m_titleElement = HTMLTitleElement::create(*this);
1382 headElement->appendChild(m_titleElement.get());
1385 if (isHTMLTitleElement(m_titleElement))
1386 toHTMLTitleElement(m_titleElement)->setText(title);
1391 void Document::setTitleElement(Element* titleElement)
1393 // Only allow the first title element to change the title -- others have no effect.
1394 if (m_titleElement && m_titleElement != titleElement) {
1395 if (isHTMLDocument() || isXHTMLDocument()) {
1396 m_titleElement = Traversal<HTMLTitleElement>::firstWithin(*this);
1397 } else if (isSVGDocument()) {
1398 m_titleElement = Traversal<SVGTitleElement>::firstWithin(*this);
1401 m_titleElement = titleElement;
1404 if (isHTMLTitleElement(m_titleElement))
1405 updateTitle(toHTMLTitleElement(m_titleElement)->text());
1406 else if (isSVGTitleElement(m_titleElement))
1407 updateTitle(toSVGTitleElement(m_titleElement)->textContent());
1410 void Document::removeTitle(Element* titleElement)
1412 if (m_titleElement != titleElement)
1415 m_titleElement = nullptr;
1417 // Update title based on first title element in the document, if one exists.
1418 if (isHTMLDocument() || isXHTMLDocument()) {
1419 if (HTMLTitleElement* title = Traversal<HTMLTitleElement>::firstWithin(*this))
1420 setTitleElement(title);
1421 } else if (isSVGDocument()) {
1422 if (SVGTitleElement* title = Traversal<SVGTitleElement>::firstWithin(*this))
1423 setTitleElement(title);
1426 if (!m_titleElement)
1427 updateTitle(String());
1430 const AtomicString& Document::dir()
1432 Element* rootElement = documentElement();
1433 if (isHTMLHtmlElement(rootElement))
1434 return toHTMLHtmlElement(rootElement)->dir();
1438 void Document::setDir(const AtomicString& value)
1440 Element* rootElement = documentElement();
1441 if (isHTMLHtmlElement(rootElement))
1442 toHTMLHtmlElement(rootElement)->setDir(value);
1445 PageVisibilityState Document::pageVisibilityState() const
1447 // The visibility of the document is inherited from the visibility of the
1448 // page. If there is no page associated with the document, we will assume
1449 // that the page is hidden, as specified by the spec:
1450 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1451 if (!m_frame || !m_frame->page())
1452 return PageVisibilityStateHidden;
1453 return m_frame->page()->visibilityState();
1456 String Document::visibilityState() const
1458 return pageVisibilityStateString(pageVisibilityState());
1461 bool Document::hidden() const
1463 return pageVisibilityState() != PageVisibilityStateVisible;
1466 void Document::didChangeVisibilityState()
1468 dispatchEvent(Event::create(EventTypeNames::visibilitychange));
1469 // Also send out the deprecated version until it can be removed.
1470 dispatchEvent(Event::create(EventTypeNames::webkitvisibilitychange));
1472 PageVisibilityState state = pageVisibilityState();
1473 DocumentVisibilityObserverSet::const_iterator observerEnd = m_visibilityObservers.end();
1474 for (DocumentVisibilityObserverSet::const_iterator it = m_visibilityObservers.begin(); it != observerEnd; ++it)
1475 (*it)->didChangeVisibilityState(state);
1478 void Document::registerVisibilityObserver(DocumentVisibilityObserver* observer)
1480 ASSERT(!m_visibilityObservers.contains(observer));
1481 m_visibilityObservers.add(observer);
1484 void Document::unregisterVisibilityObserver(DocumentVisibilityObserver* observer)
1486 ASSERT(m_visibilityObservers.contains(observer));
1487 m_visibilityObservers.remove(observer);
1490 String Document::nodeName() const
1495 Node::NodeType Document::nodeType() const
1497 return DOCUMENT_NODE;
1500 FormController& Document::formController()
1502 if (!m_formController) {
1503 m_formController = FormController::create();
1504 if (m_frame && m_frame->loader().currentItem() && m_frame->loader().currentItem()->isCurrentDocument(this))
1505 m_frame->loader().currentItem()->setDocumentState(m_formController->formElementsState());
1507 return *m_formController;
1510 DocumentState* Document::formElementsState() const
1512 if (!m_formController)
1514 return m_formController->formElementsState();
1517 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1519 if (!stateVector.size() && !m_formController)
1521 formController().setStateForNewFormElements(stateVector);
1524 FrameView* Document::view() const
1526 return m_frame ? m_frame->view() : 0;
1529 Page* Document::page() const
1531 return m_frame ? m_frame->page() : 0;
1534 FrameHost* Document::frameHost() const
1536 return m_frame ? m_frame->host() : 0;
1539 Settings* Document::settings() const
1541 return m_frame ? m_frame->settings() : 0;
1544 PassRefPtrWillBeRawPtr<Range> Document::createRange()
1546 return Range::create(*this);
1549 PassRefPtrWillBeRawPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionState& exceptionState)
1551 // FIXME: Probably this should be handled within the bindings layer and TypeError should be thrown.
1553 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1556 return NodeIterator::create(root, NodeFilter::SHOW_ALL, nullptr);
1559 PassRefPtrWillBeRawPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
1562 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1565 // FIXME: It might be a good idea to emit a warning if |whatToShow| contains a bit that is not defined in
1567 return NodeIterator::create(root, whatToShow, nullptr);
1570 PassRefPtrWillBeRawPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtrWillBeRawPtr<NodeFilter> filter, ExceptionState& exceptionState)
1573 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1577 return NodeIterator::create(root, whatToShow, filter);
1580 PassRefPtrWillBeRawPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionState& exceptionState)
1583 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1586 return TreeWalker::create(root, NodeFilter::SHOW_ALL, nullptr);
1589 PassRefPtrWillBeRawPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
1592 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1595 return TreeWalker::create(root, whatToShow, nullptr);
1598 PassRefPtrWillBeRawPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtrWillBeRawPtr<NodeFilter> filter, ExceptionState& exceptionState)
1601 exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1604 return TreeWalker::create(root, whatToShow, filter);
1607 bool Document::needsRenderTreeUpdate() const
1609 if (!isActive() || !view())
1611 if (needsFullRenderTreeUpdate())
1613 if (childNeedsStyleRecalc())
1615 if (childNeedsStyleInvalidation())
1620 bool Document::needsFullRenderTreeUpdate() const
1622 if (!isActive() || !view())
1624 if (!m_useElementsNeedingUpdate.isEmpty())
1626 if (!m_layerUpdateSVGFilterElements.isEmpty())
1628 if (needsStyleRecalc())
1630 if (needsStyleInvalidation())
1632 // FIXME: The childNeedsDistributionRecalc bit means either self or children, we should fix that.
1633 if (childNeedsDistributionRecalc())
1635 if (DocumentAnimations::needsOutdatedAnimationPlayerUpdate(*this))
1640 bool Document::shouldScheduleRenderTreeUpdate() const
1644 if (inStyleRecalc())
1646 // InPreLayout will recalc style itself. There's no reason to schedule another recalc.
1647 if (m_lifecycle.state() == DocumentLifecycle::InPreLayout)
1649 if (!shouldScheduleLayout())
1654 void Document::scheduleRenderTreeUpdate()
1656 ASSERT(!hasPendingStyleRecalc());
1657 ASSERT(shouldScheduleRenderTreeUpdate());
1658 ASSERT(needsRenderTreeUpdate());
1660 page()->animator().scheduleVisualUpdate();
1661 m_lifecycle.ensureStateAtMost(DocumentLifecycle::VisualUpdatePending);
1663 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ScheduleStyleRecalculation", "frame", frame());
1664 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
1665 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1666 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1669 bool Document::hasPendingForcedStyleRecalc() const
1671 return hasPendingStyleRecalc() && !inStyleRecalc() && styleChangeType() >= SubtreeStyleChange;
1674 void Document::updateDistributionIfNeeded()
1676 ScriptForbiddenScope forbidScript;
1678 if (!childNeedsDistributionRecalc())
1680 TRACE_EVENT0("webkit", "Document::updateDistributionIfNeeded");
1681 recalcDistribution();
1684 void Document::updateStyleInvalidationIfNeeded()
1686 ScriptForbiddenScope forbidScript;
1690 if (!childNeedsStyleInvalidation())
1692 TRACE_EVENT0("webkit", "Document::updateStyleInvalidationIfNeeded");
1693 ASSERT(styleResolver());
1695 styleResolver()->ruleFeatureSet().styleInvalidator().invalidate(*this);
1698 void Document::updateDistributionForNodeIfNeeded(Node* node)
1700 ScriptForbiddenScope forbidScript;
1702 if (node->inDocument()) {
1703 updateDistributionIfNeeded();
1707 while (Node* host = root->shadowHost())
1709 while (Node* ancestor = root->parentOrShadowHostNode())
1711 if (root->childNeedsDistributionRecalc())
1712 root->recalcDistribution();
1715 void Document::setupFontBuilder(RenderStyle* documentStyle)
1717 FontBuilder fontBuilder;
1718 fontBuilder.initForStyleResolve(*this, documentStyle);
1719 RefPtrWillBeRawPtr<CSSFontSelector> selector = m_styleEngine->fontSelector();
1720 fontBuilder.createFontForDocument(selector, documentStyle);
1723 void Document::inheritHtmlAndBodyElementStyles(StyleRecalcChange change)
1725 ASSERT(inStyleRecalc());
1726 ASSERT(documentElement());
1728 RefPtr<RenderStyle> documentElementStyle = documentElement()->renderStyle();
1729 if (!documentElementStyle || documentElement()->needsStyleRecalc() || change == Force)
1730 documentElementStyle = ensureStyleResolver().styleForElement(documentElement());
1732 WritingMode rootWritingMode = documentElementStyle->writingMode();
1733 TextDirection rootDirection = documentElementStyle->direction();
1735 HTMLElement* body = this->body();
1736 RefPtr<RenderStyle> bodyStyle;
1738 bodyStyle = body->renderStyle();
1739 if (!bodyStyle || body->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
1740 bodyStyle = ensureStyleResolver().styleForElement(body, documentElementStyle.get());
1741 if (!writingModeSetOnDocumentElement())
1742 rootWritingMode = bodyStyle->writingMode();
1743 if (!directionSetOnDocumentElement())
1744 rootDirection = bodyStyle->direction();
1747 RefPtr<RenderStyle> overflowStyle;
1748 if (Element* element = viewportDefiningElement(documentElementStyle.get())) {
1749 if (element == body) {
1750 overflowStyle = bodyStyle;
1752 ASSERT(element == documentElement());
1753 overflowStyle = documentElementStyle;
1757 // Resolved rem units are stored in the matched properties cache so we need to make sure to
1758 // invalidate the cache if the documentElement needed to reattach or the font size changed
1759 // and then trigger a full document recalc. We also need to clear it here since the
1760 // call to styleForElement on the body above can cache bad values for rem units if the
1761 // documentElement's style was dirty. We could keep track of which elements depend on
1762 // rem units like we do for viewport styles, but we assume root font size changes are
1763 // rare and just invalidate the cache for now.
1764 if (styleEngine()->usesRemUnits() && (documentElement()->needsAttach() || documentElement()->computedStyle()->fontSize() != documentElementStyle->fontSize())) {
1765 ensureStyleResolver().invalidateMatchedPropertiesCache();
1766 documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
1769 EOverflow overflowX = OAUTO;
1770 EOverflow overflowY = OAUTO;
1771 float columnGap = 0;
1772 if (overflowStyle) {
1773 overflowX = overflowStyle->overflowX();
1774 overflowY = overflowStyle->overflowY();
1775 // Visible overflow on the viewport is meaningless, and the spec says to treat it as 'auto':
1776 if (overflowX == OVISIBLE)
1778 if (overflowY == OVISIBLE)
1780 // Column-gap is (ab)used by the current paged overflow implementation (in lack of other
1781 // ways to specify gaps between pages), so we have to propagate it too.
1782 columnGap = overflowStyle->columnGap();
1785 RefPtr<RenderStyle> documentStyle = renderView()->style();
1786 if (documentStyle->writingMode() != rootWritingMode
1787 || documentStyle->direction() != rootDirection
1788 || documentStyle->overflowX() != overflowX
1789 || documentStyle->overflowY() != overflowY
1790 || documentStyle->columnGap() != columnGap) {
1791 RefPtr<RenderStyle> newStyle = RenderStyle::clone(documentStyle.get());
1792 newStyle->setWritingMode(rootWritingMode);
1793 newStyle->setDirection(rootDirection);
1794 newStyle->setColumnGap(columnGap);
1795 newStyle->setOverflowX(overflowX);
1796 newStyle->setOverflowY(overflowY);
1797 renderView()->setStyle(newStyle);
1798 setupFontBuilder(newStyle.get());
1802 if (RenderStyle* style = body->renderStyle()) {
1803 if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
1804 body->setNeedsStyleRecalc(SubtreeStyleChange);
1808 if (RenderStyle* style = documentElement()->renderStyle()) {
1809 if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
1810 documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
1814 void Document::updateRenderTree(StyleRecalcChange change)
1816 ASSERT(isMainThread());
1818 if (!view() || !isActive())
1821 if (change != Force && !needsRenderTreeUpdate())
1824 if (inStyleRecalc())
1827 // Entering here from inside layout or paint would be catastrophic since recalcStyle can
1828 // tear down the render tree or (unfortunately) run script. Kill the whole renderer if
1829 // someone managed to get into here from inside layout or paint.
1830 RELEASE_ASSERT(!view()->isInPerformLayout());
1831 RELEASE_ASSERT(!view()->isPainting());
1833 // Script can run below in WidgetUpdates, so protect the LocalFrame.
1834 RefPtr<LocalFrame> protect(m_frame);
1836 TRACE_EVENT0("webkit", "Document::updateRenderTree");
1837 TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "UpdateRenderTree");
1839 m_styleRecalcElementCounter = 0;
1840 TRACE_EVENT_BEGIN1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "RecalculateStyles", "frame", frame());
1841 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
1842 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1843 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1845 DocumentAnimations::updateOutdatedAnimationPlayersIfNeeded(*this);
1847 // FIXME: This executes media query listeners which runs script, instead the script
1848 // should run at raf timing in ScriptedAnimationController just like resize events.
1849 evaluateMediaQueryListIfNeeded();
1851 updateUseShadowTreesIfNeeded();
1852 updateDistributionIfNeeded();
1853 updateStyleInvalidationIfNeeded();
1855 // FIXME: We should update style on our ancestor chain before proceeding
1856 // however doing so currently causes several tests to crash, as LocalFrame::setDocument calls Document::attach
1857 // before setting the LocalDOMWindow on the LocalFrame, or the SecurityOrigin on the document. The attach, in turn
1858 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1859 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1860 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1862 if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
1863 m_styleEngine->setUsesRemUnit(true);
1865 updateStyle(change);
1867 // As a result of the style recalculation, the currently hovered element might have been
1868 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1869 // to check if any other elements ended up under the mouse pointer due to re-layout.
1870 if (hoverNode() && !hoverNode()->renderer() && frame())
1871 frame()->eventHandler().dispatchFakeMouseMoveEventSoon();
1873 if (m_focusedElement && !m_focusedElement->isFocusable())
1874 clearFocusedElementSoon();
1876 #if ENABLE(SVG_FONTS)
1877 if (svgExtensions())
1878 accessSVGExtensions().removePendingSVGFontFaceElementsForRemoval();
1881 ASSERT(!m_timeline->hasOutdatedAnimationPlayer());
1883 TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "RecalculateStyles", "elementCount", m_styleRecalcElementCounter);
1884 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1885 InspectorInstrumentation::didRecalculateStyle(cookie, m_styleRecalcElementCounter);
1888 void Document::updateStyle(StyleRecalcChange change)
1890 TRACE_EVENT0("webkit", "Document::updateStyle");
1892 ScriptForbiddenScope forbidScript;
1893 HTMLFrameOwnerElement::UpdateSuspendScope suspendWidgetHierarchyUpdates;
1894 m_lifecycle.advanceTo(DocumentLifecycle::InStyleRecalc);
1896 if (styleChangeType() >= SubtreeStyleChange)
1899 // FIXME: Cannot access the ensureStyleResolver() before calling styleForDocument below because
1900 // apparently the StyleResolver's constructor has side effects. We should fix it.
1901 // See printing/setPrinting.html, printing/width-overflow.html though they only fail on
1902 // mac when accessing the resolver by what appears to be a viewport size difference.
1904 if (change == Force) {
1905 m_hasNodesWithPlaceholderStyle = false;
1906 RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this);
1907 StyleRecalcChange localChange = RenderStyle::stylePropagationDiff(documentStyle.get(), renderView()->style());
1908 if (localChange != NoChange)
1909 renderView()->setStyle(documentStyle.release());
1912 clearNeedsStyleRecalc();
1914 // Uncomment to enable printing of statistics about style sharing and the matched property cache.
1915 // Optionally pass StyleResolver::ReportSlowStats to print numbers that require crawling the
1916 // entire DOM (where collecting them is very slow).
1917 // FIXME: Expose this as a runtime flag.
1918 // ensureStyleResolver().enableStats(/*StyleResolver::ReportSlowStats*/);
1920 if (StyleResolverStats* stats = ensureStyleResolver().stats())
1923 if (Element* documentElement = this->documentElement()) {
1924 inheritHtmlAndBodyElementStyles(change);
1925 dirtyElementsForLayerUpdate();
1926 if (documentElement->shouldCallRecalcStyle(change))
1927 documentElement->recalcStyle(change);
1928 while (dirtyElementsForLayerUpdate())
1929 documentElement->recalcStyle(NoChange);
1932 ensureStyleResolver().printStats();
1934 view()->recalcOverflowAfterStyleChange();
1935 renderView()->compositor()->setNeedsCompositingUpdate(CompositingUpdateAfterCompositingInputChange);
1937 clearChildNeedsStyleRecalc();
1939 if (m_styleEngine->hasResolver()) {
1940 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1941 StyleResolver& resolver = m_styleEngine->ensureResolver();
1942 m_styleEngine->resetCSSFeatureFlags(resolver.ensureUpdatedRuleFeatureSet());
1943 resolver.clearStyleSharingList();
1946 ASSERT(!needsStyleRecalc());
1947 ASSERT(!childNeedsStyleRecalc());
1948 ASSERT(inStyleRecalc());
1949 m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
1952 void Document::updateRenderTreeForNodeIfNeeded(Node* node)
1954 bool needsRecalc = needsFullRenderTreeUpdate();
1956 for (const Node* ancestor = node; ancestor && !needsRecalc; ancestor = NodeRenderingTraversal::parent(ancestor))
1957 needsRecalc = ancestor->needsStyleRecalc() || ancestor->needsStyleInvalidation();
1960 updateRenderTreeIfNeeded();
1963 void Document::updateLayout()
1965 ASSERT(isMainThread());
1967 RefPtr<FrameView> frameView = view();
1968 if (frameView && frameView->isInPerformLayout()) {
1969 // View layout should not be re-entrant.
1970 ASSERT_NOT_REACHED();
1974 if (Element* oe = ownerElement())
1975 oe->document().updateLayout();
1977 updateRenderTreeIfNeeded();
1982 if (frameView->needsLayout())
1983 frameView->layout();
1985 if (lifecycle().state() < DocumentLifecycle::LayoutClean)
1986 lifecycle().advanceTo(DocumentLifecycle::LayoutClean);
1989 void Document::setNeedsFocusedElementCheck()
1991 setNeedsStyleRecalc(LocalStyleChange);
1994 void Document::clearFocusedElementSoon()
1996 if (!m_clearFocusedElementTimer.isActive())
1997 m_clearFocusedElementTimer.startOneShot(0, FROM_HERE);
2000 void Document::clearFocusedElementTimerFired(Timer<Document>*)
2002 updateRenderTreeIfNeeded();
2003 m_clearFocusedElementTimer.stop();
2005 if (m_focusedElement && !m_focusedElement->isFocusable())
2006 m_focusedElement->blur();
2009 // FIXME: This is a bad idea and needs to be removed eventually.
2010 // Other browsers load stylesheets before they continue parsing the web page.
2011 // Since we don't, we can run JavaScript code that needs answers before the
2012 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
2013 // lets us get reasonable answers. The long term solution to this problem is
2014 // to instead suspend JavaScript execution.
2015 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
2017 StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
2019 if (m_styleEngine->hasPendingSheets()) {
2020 // FIXME: We are willing to attempt to suppress painting with outdated style info only once.
2021 // Our assumption is that it would be dangerous to try to stop it a second time, after page
2022 // content has already been loaded and displayed with accurate style information. (Our
2023 // suppression involves blanking the whole page at the moment. If it were more refined, we
2024 // might be able to do something better.) It's worth noting though that this entire method
2025 // is a hack, since what we really want to do is suspend JS instead of doing a layout with
2026 // inaccurate information.
2027 HTMLElement* bodyElement = body();
2028 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
2029 m_pendingSheetLayout = DidLayoutWithPendingSheets;
2030 styleResolverChanged();
2031 } else if (m_hasNodesWithPlaceholderStyle) {
2032 // If new nodes have been added or style recalc has been done with style sheets still
2033 // pending, some nodes may not have had their real style calculated yet. Normally this
2034 // gets cleaned when style sheets arrive but here we need up-to-date style immediately.
2035 updateRenderTree(Force);
2041 if (runPostLayoutTasks == RunPostLayoutTasksSynchronously && view())
2042 view()->flushAnyPendingPostLayoutTasks();
2045 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
2047 ASSERT_ARG(element, element->document() == this);
2048 StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
2049 return ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
2052 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
2054 return ensureStyleResolver().styleForPage(pageIndex);
2057 bool Document::isPageBoxVisible(int pageIndex)
2059 return styleForPage(pageIndex)->visibility() != HIDDEN; // display property doesn't apply to @page.
2062 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2064 RefPtr<RenderStyle> style = styleForPage(pageIndex);
2066 int width = pageSize.width();
2067 int height = pageSize.height();
2068 switch (style->pageSizeType()) {
2069 case PAGE_SIZE_AUTO:
2071 case PAGE_SIZE_AUTO_LANDSCAPE:
2073 std::swap(width, height);
2075 case PAGE_SIZE_AUTO_PORTRAIT:
2077 std::swap(width, height);
2079 case PAGE_SIZE_RESOLVED: {
2080 LengthSize size = style->pageSize();
2081 ASSERT(size.width().isFixed());
2082 ASSERT(size.height().isFixed());
2083 width = valueForLength(size.width(), 0);
2084 height = valueForLength(size.height(), 0);
2088 ASSERT_NOT_REACHED();
2090 pageSize = IntSize(width, height);
2092 // The percentage is calculated with respect to the width even for margin top and bottom.
2093 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2094 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2095 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2096 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2097 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2100 void Document::setIsViewSource(bool isViewSource)
2102 m_isViewSource = isViewSource;
2103 if (!m_isViewSource)
2106 setSecurityOrigin(SecurityOrigin::createUnique());
2107 didUpdateSecurityOrigin();
2110 bool Document::dirtyElementsForLayerUpdate()
2112 if (m_layerUpdateSVGFilterElements.isEmpty())
2115 for (WillBeHeapHashSet<RawPtrWillBeMember<Element> >::iterator it = m_layerUpdateSVGFilterElements.begin(), end = m_layerUpdateSVGFilterElements.end(); it != end; ++it)
2116 (*it)->setNeedsStyleRecalc(LocalStyleChange);
2117 m_layerUpdateSVGFilterElements.clear();
2121 void Document::scheduleSVGFilterLayerUpdateHack(Element& element)
2123 if (element.styleChangeType() == NeedsReattachStyleChange)
2125 element.setSVGFilterNeedsLayerUpdate();
2126 m_layerUpdateSVGFilterElements.add(&element);
2127 scheduleRenderTreeUpdateIfNeeded();
2130 void Document::unscheduleSVGFilterLayerUpdateHack(Element& element)
2132 element.clearSVGFilterNeedsLayerUpdate();
2133 m_layerUpdateSVGFilterElements.remove(&element);
2136 void Document::scheduleUseShadowTreeUpdate(SVGUseElement& element)
2138 m_useElementsNeedingUpdate.add(&element);
2139 scheduleRenderTreeUpdateIfNeeded();
2142 void Document::unscheduleUseShadowTreeUpdate(SVGUseElement& element)
2144 m_useElementsNeedingUpdate.remove(&element);
2147 void Document::updateUseShadowTreesIfNeeded()
2149 ScriptForbiddenScope forbidScript;
2151 if (m_useElementsNeedingUpdate.isEmpty())
2154 WillBeHeapVector<RawPtrWillBeMember<SVGUseElement> > elements;
2155 copyToVector(m_useElementsNeedingUpdate, elements);
2156 m_useElementsNeedingUpdate.clear();
2158 for (WillBeHeapVector<RawPtrWillBeMember<SVGUseElement> >::iterator it = elements.begin(), end = elements.end(); it != end; ++it)
2159 (*it)->buildPendingResource();
2162 StyleResolver* Document::styleResolver() const
2164 return m_styleEngine->resolver();
2167 StyleResolver& Document::ensureStyleResolver() const
2169 return m_styleEngine->ensureResolver();
2172 void Document::clearStyleResolver()
2174 m_styleEngine->clearResolver();
2177 void Document::attach(const AttachContext& context)
2179 ASSERT(m_lifecycle.state() == DocumentLifecycle::Inactive);
2180 ASSERT(!m_axObjectCache || this != topDocument());
2182 m_renderView = new RenderView(this);
2183 setRenderer(m_renderView);
2185 m_renderView->setIsInWindow(true);
2186 m_renderView->setStyle(StyleResolver::styleForDocument(*this));
2187 m_renderView->compositor()->setNeedsCompositingUpdate(CompositingUpdateAfterCompositingInputChange);
2189 ContainerNode::attach(context);
2191 // FastTextAutosizer can't update render view info while the Document is detached, so update now in case anything changed.
2192 if (FastTextAutosizer* textAutosizer = fastTextAutosizer())
2193 textAutosizer->updatePageInfo();
2195 m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
2198 void Document::detach(const AttachContext& context)
2201 m_lifecycle.advanceTo(DocumentLifecycle::Stopping);
2204 page()->documentDetached(this);
2205 InspectorInstrumentation::documentDetached(this);
2207 if (m_frame->loader().client()->sharedWorkerRepositoryClient())
2208 m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this);
2210 if (this == topDocument())
2211 clearAXObjectCache();
2213 stopActiveDOMObjects();
2215 // FIXME: consider using ActiveDOMObject.
2216 if (m_scriptedAnimationController)
2217 m_scriptedAnimationController->clearDocumentPointer();
2218 m_scriptedAnimationController.clear();
2220 if (svgExtensions())
2221 accessSVGExtensions().pauseAnimations();
2223 // FIXME: This shouldn't be needed once LocalDOMWindow becomes ExecutionContext.
2225 m_domWindow->clearEventQueue();
2228 m_renderView->setIsInWindow(false);
2231 FrameView* view = m_frame->view();
2233 view->detachCustomScrollbars();
2236 m_hoverNode = nullptr;
2237 m_focusedElement = nullptr;
2238 m_activeHoverElement = nullptr;
2239 m_autofocusElement = nullptr;
2242 ContainerNode::detach(context);
2244 m_styleEngine->didDetach();
2246 if (Document* parentDoc = parentDocument())
2247 parentDoc->didClearTouchEventHandlers(this);
2249 // This is required, as our LocalFrame might delete itself as soon as it detaches
2250 // us. However, this violates Node::detach() semantics, as it's never
2251 // possible to re-attach. Eventually Document::detach() should be renamed,
2252 // or this setting of the frame to 0 could be made explicit in each of the
2253 // callers of Document::detach().
2256 if (m_mediaQueryMatcher)
2257 m_mediaQueryMatcher->documentDestroyed();
2259 lifecycleNotifier().notifyDocumentWasDetached();
2260 m_lifecycle.advanceTo(DocumentLifecycle::Stopped);
2262 // This mirrors the clearing of the document object's touch
2263 // handlers that happens when the LocalDOMWindow is destructed in a
2264 // non-Oilpan setting (LocalDOMWindow::removeAllEventListeners()),
2265 // except that it is now done during detach instead.
2266 didClearTouchEventHandlers(this);
2268 // Done with the window, explicitly clear to hasten its
2274 void Document::prepareForDestruction()
2276 m_markers->prepareForDestruction();
2277 disconnectDescendantFrames();
2279 // The process of disconnecting descendant frames could have already detached us.
2283 if (LocalDOMWindow* window = this->domWindow())
2284 window->willDetachDocumentFromFrame();
2288 void Document::removeAllEventListeners()
2290 ContainerNode::removeAllEventListeners();
2292 if (LocalDOMWindow* domWindow = this->domWindow())
2293 domWindow->removeAllEventListeners();
2296 void Document::clearAXObjectCache()
2298 ASSERT(topDocument() == this);
2299 // Clear the cache member variable before calling delete because attempts
2300 // are made to access it during destruction.
2301 m_axObjectCache.clear();
2304 AXObjectCache* Document::existingAXObjectCache() const
2306 if (!AXObjectCache::accessibilityEnabled())
2309 // If the renderer is gone then we are in the process of destruction.
2310 // This method will be called before m_frame = 0.
2311 if (!topDocument().renderView())
2314 return topDocument().m_axObjectCache.get();
2317 AXObjectCache* Document::axObjectCache() const
2319 if (!AXObjectCache::accessibilityEnabled())
2322 // The only document that actually has a AXObjectCache is the top-level
2323 // document. This is because we need to be able to get from any WebCoreAXObject
2324 // to any other WebCoreAXObject on the same page. Using a single cache allows
2325 // lookups across nested webareas (i.e. multiple documents).
2326 Document& topDocument = this->topDocument();
2328 // If the document has already been detached, do not make a new axObjectCache.
2329 if (!topDocument.renderView())
2332 ASSERT(topDocument == this || !m_axObjectCache);
2333 if (!topDocument.m_axObjectCache)
2334 topDocument.m_axObjectCache = adoptPtr(new AXObjectCache(topDocument));
2335 return topDocument.m_axObjectCache.get();
2338 PassRefPtrWillBeRawPtr<DocumentParser> Document::createParser()
2340 if (isHTMLDocument()) {
2341 bool reportErrors = InspectorInstrumentation::collectingHTMLParseErrors(page());
2342 return HTMLDocumentParser::create(toHTMLDocument(*this), reportErrors);
2344 // FIXME: this should probably pass the frame instead
2345 return XMLDocumentParser::create(*this, view());
2348 bool Document::isFrameSet() const
2350 if (!isHTMLDocument())
2352 return isHTMLFrameSetElement(body());
2355 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2357 return parser() ? parser()->asScriptableDocumentParser() : 0;
2360 void Document::open(Document* ownerDocument, ExceptionState& exceptionState)
2362 if (importLoader()) {
2363 exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support open().");
2367 if (ownerDocument) {
2368 setURL(ownerDocument->url());
2369 m_cookieURL = ownerDocument->cookieURL();
2370 setSecurityOrigin(ownerDocument->securityOrigin());
2374 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2375 if (parser->isParsing()) {
2376 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2377 if (parser->isExecutingScript())
2380 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2385 if (m_frame->loader().state() == FrameStateProvisional)
2386 m_frame->loader().stopAllLoaders();
2389 removeAllEventListenersRecursively();
2391 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2392 parser->setWasCreatedByScript(true);
2395 m_frame->loader().didExplicitOpen();
2396 if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
2397 m_loadEventProgress = LoadEventNotRun;
2400 void Document::detachParser()
2408 void Document::cancelParsing()
2413 // We have to clear the parser to avoid possibly triggering
2414 // the onload handler when closing as a side effect of a cancel-style
2415 // change, such as opening a new document or closing the window while
2421 PassRefPtrWillBeRawPtr<DocumentParser> Document::implicitOpen()
2426 ASSERT(!m_focusedElement);
2428 setCompatibilityMode(NoQuirksMode);
2430 m_parser = createParser();
2432 setReadyState(Loading);
2437 HTMLElement* Document::body() const
2439 if (!documentElement())
2442 for (HTMLElement* child = Traversal<HTMLElement>::firstWithin(*documentElement()); child; child = Traversal<HTMLElement>::nextSibling(*child)) {
2443 if (isHTMLFrameSetElement(*child) || isHTMLBodyElement(*child))
2450 void Document::setBody(PassRefPtrWillBeRawPtr<HTMLElement> prpNewBody, ExceptionState& exceptionState)
2452 RefPtrWillBeRawPtr<HTMLElement> newBody = prpNewBody;
2455 exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::argumentNullOrIncorrectType(1, "HTMLElement"));
2458 if (!documentElement()) {
2459 exceptionState.throwDOMException(HierarchyRequestError, "No document element exists.");
2463 if (!isHTMLBodyElement(*newBody) && !isHTMLFrameSetElement(*newBody)) {
2464 exceptionState.throwDOMException(HierarchyRequestError, "The new body element is of type '" + newBody->tagName() + "'. It must be either a 'BODY' or 'FRAMESET' element.");
2468 HTMLElement* oldBody = body();
2469 if (oldBody == newBody)
2473 documentElement()->replaceChild(newBody.release(), oldBody, exceptionState);
2475 documentElement()->appendChild(newBody.release(), exceptionState);
2478 HTMLHeadElement* Document::head() const
2480 Node* de = documentElement();
2484 return Traversal<HTMLHeadElement>::firstChild(*de);
2487 Element* Document::viewportDefiningElement(RenderStyle* rootStyle) const
2489 // If a BODY element sets non-visible overflow, it is to be propagated to the viewport, as long
2490 // as the following conditions are all met:
2491 // (1) The root element is HTML.
2492 // (2) It is the primary BODY element (we only assert for this, expecting callers to behave).
2493 // (3) The root element has visible overflow.
2494 // Otherwise it's the root element's properties that are to be propagated.
2495 Element* rootElement = documentElement();
2496 Element* bodyElement = body();
2500 rootStyle = rootElement->renderStyle();
2504 if (bodyElement && rootStyle->isOverflowVisible() && isHTMLHtmlElement(*rootElement))
2509 void Document::close(ExceptionState& exceptionState)
2511 // FIXME: We should follow the specification more closely:
2512 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2514 if (importLoader()) {
2515 exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support close().");
2519 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2525 void Document::explicitClose()
2527 if (RefPtrWillBeRawPtr<DocumentParser> parser = m_parser)
2531 // Because we have no frame, we don't know if all loading has completed,
2532 // so we just call implicitClose() immediately. FIXME: This might fire
2533 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2538 m_frame->loader().checkCompleted();
2541 void Document::implicitClose()
2543 ASSERT(!inStyleRecalc());
2545 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2546 bool doload = !parsing() && m_parser && !processingLoadEvent() && !wasLocationChangePending;
2548 // If the load was blocked because of a pending location change and the location change triggers a same document
2549 // navigation, don't fire load events after the same document navigation completes (unless there's an explicit open).
2550 m_loadEventProgress = LoadEventTried;
2555 // The call to dispatchWindowLoadEvent can detach the LocalDOMWindow and cause it (and its
2556 // attached Document) to be destroyed.
2557 RefPtrWillBeRawPtr<LocalDOMWindow> protectedWindow(this->domWindow());
2559 m_loadEventProgress = LoadEventInProgress;
2561 ScriptableDocumentParser* parser = scriptableDocumentParser();
2562 m_wellFormed = parser && parser->wellFormed();
2564 // We have to clear the parser, in case someone document.write()s from the
2565 // onLoad event handler, as in Radar 3206524.
2568 if (frame() && frame()->script().canExecuteScripts(NotAboutToExecuteScript)) {
2569 ImageLoader::dispatchPendingLoadEvents();
2570 ImageLoader::dispatchPendingErrorEvents();
2572 HTMLLinkElement::dispatchPendingLoadEvents();
2573 HTMLStyleElement::dispatchPendingLoadEvents();
2576 // JS running below could remove the frame or destroy the RenderView so we call
2577 // those two functions repeatedly and don't save them on the stack.
2579 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2580 // here, instead of doing it from SVGElement::finishedParsingChildren.
2581 if (svgExtensions())
2582 accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2584 if (protectedWindow)
2585 protectedWindow->documentWasClosed();
2588 frame()->loader().client()->dispatchDidHandleOnloadEvents();
2589 loader()->applicationCacheHost()->stopDeferringEvents();
2593 m_loadEventProgress = LoadEventCompleted;
2597 // Make sure both the initial layout and reflow happen after the onload
2598 // fires. This will improve onload scores, and other browsers do it.
2599 // If they wanna cheat, we can too. -dwh
2601 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2602 // Just bail out. Before or during the onload we were shifted to another page.
2603 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2604 m_loadEventProgress = LoadEventCompleted;
2608 // We used to force a synchronous display and flush here. This really isn't
2609 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2610 // (if your platform is syncing flushes and limiting them to 60fps).
2611 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2612 updateRenderTreeIfNeeded();
2614 // Always do a layout after loading if needed.
2615 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2619 m_loadEventProgress = LoadEventCompleted;
2621 if (frame() && renderView() && AXObjectCache::accessibilityEnabled()) {
2622 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2623 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2624 // exists in the cache (we ignore the return value because we don't need it here). This is
2625 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2626 if (AXObjectCache* cache = axObjectCache()) {
2627 cache->getOrCreate(renderView());
2628 if (this == topDocument()) {
2629 cache->postNotification(renderView(), AXObjectCache::AXLoadComplete, true);
2631 // AXLoadComplete can only be posted on the top document, so if it's a document
2632 // in an iframe that just finished loading, post AXLayoutComplete instead.
2633 cache->postNotification(renderView(), AXObjectCache::AXLayoutComplete, true);
2638 if (svgExtensions())
2639 accessSVGExtensions().startAnimations();
2642 bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigation)
2650 RefPtrWillBeRawPtr<Document> protect(this);
2652 RefPtrWillBeRawPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2653 m_loadEventProgress = BeforeUnloadEventInProgress;
2654 m_domWindow->dispatchEvent(beforeUnloadEvent.get(), this);
2655 m_loadEventProgress = BeforeUnloadEventCompleted;
2656 if (!beforeUnloadEvent->defaultPrevented())
2657 defaultEventHandler(beforeUnloadEvent.get());
2658 if (beforeUnloadEvent->returnValue().isNull())
2661 if (didAllowNavigation) {
2662 addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation.");
2666 String text = beforeUnloadEvent->returnValue();
2667 if (chrome.runBeforeUnloadConfirmPanel(text, m_frame)) {
2668 didAllowNavigation = true;
2674 void Document::dispatchUnloadEvents()
2676 RefPtrWillBeRawPtr<Document> protect(this);
2678 m_parser->stopParsing();
2680 if (m_loadEventProgress >= LoadEventTried && m_loadEventProgress <= UnloadEventInProgress) {
2681 Element* currentFocusedElement = focusedElement();
2682 if (isHTMLInputElement(currentFocusedElement))
2683 toHTMLInputElement(*currentFocusedElement).endEditing();
2684 if (m_loadEventProgress < PageHideInProgress) {
2685 m_loadEventProgress = PageHideInProgress;
2686 if (LocalDOMWindow* window = domWindow())
2687 window->dispatchEvent(PageTransitionEvent::create(EventTypeNames::pagehide, false), this);
2691 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
2692 // while dispatching the event, so protect it to prevent writing the end
2693 // time into freed memory.
2694 RefPtr<DocumentLoader> documentLoader = m_frame->loader().provisionalDocumentLoader();
2695 m_loadEventProgress = UnloadEventInProgress;
2696 RefPtrWillBeRawPtr<Event> unloadEvent(Event::create(EventTypeNames::unload));
2697 if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
2698 DocumentLoadTiming* timing = documentLoader->timing();
2699 ASSERT(timing->navigationStart());
2700 timing->markUnloadEventStart();
2701 m_frame->domWindow()->dispatchEvent(unloadEvent, this);
2702 timing->markUnloadEventEnd();
2704 m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
2707 m_loadEventProgress = UnloadEventHandled;
2713 // Don't remove event listeners from a transitional empty document (see https://bugs.webkit.org/show_bug.cgi?id=28716 for more information).
2714 bool keepEventListeners = m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader().provisionalDocumentLoader()
2715 && isSecureTransitionTo(m_frame->loader().provisionalDocumentLoader()->url());
2716 if (!keepEventListeners)
2717 removeAllEventListenersRecursively();
2720 Document::PageDismissalType Document::pageDismissalEventBeingDispatched() const
2722 if (m_loadEventProgress == BeforeUnloadEventInProgress)
2723 return BeforeUnloadDismissal;
2724 if (m_loadEventProgress == PageHideInProgress)
2725 return PageHideDismissal;
2726 if (m_loadEventProgress == UnloadEventInProgress)
2727 return UnloadDismissal;
2731 void Document::setParsing(bool b)
2735 if (m_isParsing && !m_elementDataCache)
2736 m_elementDataCache = ElementDataCache::create();
2739 bool Document::shouldScheduleLayout() const
2741 // This function will only be called when FrameView thinks a layout is needed.
2742 // This enforces a couple extra rules.
2744 // (a) Only schedule a layout once the stylesheets are loaded.
2745 // (b) Only schedule layout once we have a body element.
2749 if (isRenderingReady() && body())
2752 if (documentElement() && !isHTMLHtmlElement(*documentElement()))
2758 int Document::elapsedTime() const
2760 return static_cast<int>((currentTime() - m_startTime) * 1000);
2763 void Document::write(const SegmentedString& text, Document* ownerDocument, ExceptionState& exceptionState)
2765 if (importLoader()) {
2766 exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support write().");
2770 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2772 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2773 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2775 if (m_writeRecursionIsTooDeep)
2778 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2780 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount) {
2781 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."));
2785 if (!hasInsertionPoint)
2786 open(ownerDocument);
2789 m_parser->insert(text);
2792 void Document::write(const String& text, Document* ownerDocument, ExceptionState& exceptionState)
2794 write(SegmentedString(text), ownerDocument, exceptionState);
2797 void Document::writeln(const String& text, Document* ownerDocument, ExceptionState& exceptionState)
2799 write(text, ownerDocument, exceptionState);
2800 if (exceptionState.hadException())
2802 write("\n", ownerDocument);
2805 const KURL& Document::virtualURL() const
2810 KURL Document::virtualCompleteURL(const String& url) const
2812 return completeURL(url);
2815 double Document::timerAlignmentInterval() const
2819 return DOMTimer::visiblePageAlignmentInterval();
2820 return p->timerAlignmentInterval();
2823 EventTarget* Document::errorEventTarget()
2828 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtrWillBeRawPtr<ScriptCallStack> callStack)
2830 internalAddMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack, 0);
2833 void Document::setURL(const KURL& url)
2835 const KURL& newURL = url.isEmpty() ? blankURL() : url;
2836 if (newURL == m_url)
2841 contextFeatures().urlDidChange(this);
2844 void Document::updateBaseURL()
2846 KURL oldBaseURL = m_baseURL;
2847 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2848 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2849 // from the Document interface otherwise (which we store, preparsed, in m_url).
2850 if (!m_baseElementURL.isEmpty())
2851 m_baseURL = m_baseElementURL;
2852 else if (!m_baseURLOverride.isEmpty())
2853 m_baseURL = m_baseURLOverride;
2857 selectorQueryCache().invalidate();
2859 if (!m_baseURL.isValid())
2863 // Element sheet is silly. It never contains anything.
2864 ASSERT(!m_elemSheet->contents()->ruleCount());
2865 bool usesRemUnits = m_elemSheet->contents()->usesRemUnits();
2866 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2867 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2868 m_elemSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
2871 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2872 // Base URL change changes any relative visited links.
2873 // 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.
2874 for (HTMLAnchorElement* anchor = Traversal<HTMLAnchorElement>::firstWithin(*this); anchor; anchor = Traversal<HTMLAnchorElement>::next(*anchor))
2875 anchor->invalidateCachedVisitedLinkHash();
2879 void Document::setBaseURLOverride(const KURL& url)
2881 m_baseURLOverride = url;
2885 void Document::processBaseElement()
2887 // Find the first href attribute in a base element and the first target attribute in a base element.
2888 const AtomicString* href = 0;
2889 const AtomicString* target = 0;
2890 for (HTMLBaseElement* base = Traversal<HTMLBaseElement>::firstWithin(*this); base && (!href || !target); base = Traversal<HTMLBaseElement>::next(*base)) {
2892 const AtomicString& value = base->fastGetAttribute(hrefAttr);
2893 if (!value.isNull())
2897 const AtomicString& value = base->fastGetAttribute(targetAttr);
2898 if (!value.isNull())
2901 if (contentSecurityPolicy()->isActive())
2902 UseCounter::count(*this, UseCounter::ContentSecurityPolicyWithBaseElement);
2905 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2906 KURL baseElementURL;
2908 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2909 if (!strippedHref.isEmpty())
2910 baseElementURL = KURL(url(), strippedHref);
2912 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
2913 m_baseElementURL = baseElementURL;
2917 m_baseTarget = target ? *target : nullAtom;
2920 String Document::userAgent(const KURL& url) const
2922 return frame() ? frame()->loader().userAgent(url) : String();
2925 void Document::disableEval(const String& errorMessage)
2930 frame()->script().disableEval(errorMessage);
2933 bool Document::canNavigate(const Frame& targetFrame)
2938 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
2939 if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
2942 if (isSandboxed(SandboxNavigation)) {
2943 if (targetFrame.tree().isDescendantOf(m_frame))
2946 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
2947 if (isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
2948 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
2950 printNavigationErrorMessage(toLocalFrameTemporary(targetFrame), url(), reason);
2954 ASSERT(securityOrigin());
2955 SecurityOrigin& origin = *securityOrigin();
2957 // This is the normal case. A document can navigate its decendant frames,
2958 // or, more generally, a document can navigate a frame if the document is
2959 // in the same origin as any of that frame's ancestors (in the frame
2962 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2963 // historical information about this security check.
2964 if (canAccessAncestor(origin, &targetFrame))
2967 // Top-level frames are easier to navigate than other frames because they
2968 // display their URLs in the address bar (in most browsers). However, there
2969 // are still some restrictions on navigation to avoid nuisance attacks.
2970 // Specifically, a document can navigate a top-level frame if that frame
2971 // opened the document or if the document is the same-origin with any of
2972 // the top-level frame's opener's ancestors (in the frame hierarchy).
2974 // In both of these cases, the document performing the navigation is in
2975 // some way related to the frame being navigate (e.g., by the "opener"
2976 // and/or "parent" relation). Requiring some sort of relation prevents a
2977 // document from navigating arbitrary, unrelated top-level frames.
2978 if (!targetFrame.tree().parent()) {
2979 if (targetFrame == m_frame->loader().opener())
2982 // FIXME: We don't have access to RemoteFrame's opener yet.
2983 if (targetFrame.isLocalFrame() && canAccessAncestor(origin, toLocalFrame(targetFrame).loader().opener()))
2987 printNavigationErrorMessage(toLocalFrameTemporary(targetFrame), url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
2991 LocalFrame* Document::findUnsafeParentScrollPropagationBoundary()
2993 LocalFrame* currentFrame = m_frame;
2994 Frame* ancestorFrame = currentFrame->tree().parent();
2996 while (ancestorFrame) {
2997 // FIXME: We don't yet have access to a RemoteFrame's security origin.
2998 if (!ancestorFrame->isLocalFrame())
2999 return currentFrame;
3000 if (!toLocalFrame(ancestorFrame)->document()->securityOrigin()->canAccess(securityOrigin()))
3001 return currentFrame;
3002 currentFrame = toLocalFrame(ancestorFrame);
3003 ancestorFrame = ancestorFrame->tree().parent();
3008 void Document::didLoadAllImports()
3010 if (!haveStylesheetsLoaded())
3012 if (!importLoader())
3013 styleResolverMayHaveChanged();
3014 didLoadAllScriptBlockingResources();
3017 void Document::didRemoveAllPendingStylesheet()
3019 styleResolverMayHaveChanged();
3021 // Only imports on master documents can trigger rendering.
3022 if (HTMLImportLoader* import = importLoader())
3023 import->didRemoveAllPendingStylesheet();
3024 if (!haveImportsLoaded())
3026 didLoadAllScriptBlockingResources();
3029 void Document::didLoadAllScriptBlockingResources()
3031 m_executeScriptsWaitingForResourcesTimer.startOneShot(0, FROM_HERE);
3033 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
3034 view()->scrollToFragment(m_url);
3037 void Document::executeScriptsWaitingForResourcesTimerFired(Timer<Document>*)
3039 if (!isRenderingReady())
3041 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
3042 parser->executeScriptsWaitingForResources();
3045 CSSStyleSheet& Document::elementSheet()
3048 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
3049 return *m_elemSheet;
3052 void Document::processHttpEquiv(const AtomicString& equiv, const AtomicString& content, bool inDocumentHeadElement)
3054 ASSERT(!equiv.isNull() && !content.isNull());
3056 if (equalIgnoringCase(equiv, "default-style")) {
3057 processHttpEquivDefaultStyle(content);
3058 } else if (equalIgnoringCase(equiv, "refresh")) {
3059 processHttpEquivRefresh(content);
3060 } else if (equalIgnoringCase(equiv, "set-cookie")) {
3061 processHttpEquivSetCookie(content);
3062 } else if (equalIgnoringCase(equiv, "content-language")) {
3063 setContentLanguage(content);
3064 } else if (equalIgnoringCase(equiv, "x-dns-prefetch-control")) {
3065 parseDNSPrefetchControlHeader(content);
3066 } else if (equalIgnoringCase(equiv, "x-frame-options")) {
3067 processHttpEquivXFrameOptions(content);
3068 } else if (equalIgnoringCase(equiv, "content-security-policy") || equalIgnoringCase(equiv, "content-security-policy-report-only")) {
3069 if (inDocumentHeadElement)
3070 processHttpEquivContentSecurityPolicy(equiv, content);
3072 contentSecurityPolicy()->reportMetaOutsideHead(content);
3076 void Document::processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content)
3080 if (equalIgnoringCase(equiv, "content-security-policy"))
3081 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeEnforce, ContentSecurityPolicyHeaderSourceMeta);
3082 else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
3083 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeReport, ContentSecurityPolicyHeaderSourceMeta);
3085 ASSERT_NOT_REACHED();
3088 void Document::processHttpEquivDefaultStyle(const AtomicString& content)
3090 // The preferred style set has been overridden as per section
3091 // 14.3.2 of the HTML4.0 specification. We need to update the
3092 // sheet used variable and then update our style selector.
3093 // For more info, see the test at:
3094 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3096 m_styleEngine->setSelectedStylesheetSetName(content);
3097 m_styleEngine->setPreferredStylesheetSetName(content);
3098 styleResolverChanged();
3101 void Document::processHttpEquivRefresh(const AtomicString& content)
3103 maybeHandleHttpRefresh(content, HttpRefreshFromMetaTag);
3106 void Document::maybeHandleHttpRefresh(const String& content, HttpRefreshType httpRefreshType)
3108 if (m_isViewSource || !m_frame)
3113 if (!parseHTTPRefresh(content, httpRefreshType == HttpRefreshFromMetaTag, delay, refreshURL))
3115 if (refreshURL.isEmpty())
3116 refreshURL = url().string();
3118 refreshURL = completeURL(refreshURL).string();
3120 if (protocolIsJavaScript(refreshURL)) {
3121 String message = "Refused to refresh " + m_url.elidedString() + " to a javascript: URL";
3122 addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
3126 if (httpRefreshType == HttpRefreshFromMetaTag && isSandboxed(SandboxAutomaticFeatures)) {
3127 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.";
3128 addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
3131 m_frame->navigationScheduler().scheduleRedirect(delay, refreshURL);
3134 void Document::processHttpEquivSetCookie(const AtomicString& content)
3136 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3137 if (!isHTMLDocument())
3140 // Exception (for sandboxed documents) ignored.
3141 toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
3144 void Document::processHttpEquivXFrameOptions(const AtomicString& content)
3146 LocalFrame* frame = this->frame();
3150 FrameLoader& frameLoader = frame->loader();
3151 unsigned long requestIdentifier = loader()->mainResourceIdentifier();
3152 if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
3153 String message = "Refused to display '" + url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
3154 frameLoader.stopAllLoaders();
3155 // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
3156 // intent, we must navigate away from the possibly partially-rendered document to a location that
3157 // doesn't inherit the parent's SecurityOrigin.
3158 frame->navigationScheduler().scheduleLocationChange(this, SecurityOrigin::urlWithUniqueSecurityOrigin(), Referrer());
3159 addConsoleMessageWithRequestIdentifier(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
3163 bool Document::shouldMergeWithLegacyDescription(ViewportDescription::Type origin)
3165 return settings() && settings()->viewportMetaMergeContentQuirk() && m_legacyViewportDescription.isMetaViewportType() && m_legacyViewportDescription.type == origin;
3168 void Document::setViewportDescription(const ViewportDescription& viewportDescription)
3170 // The UA-defined min-width is used by the processing of legacy meta tags.
3171 if (!viewportDescription.isSpecifiedByAuthor())
3172 m_viewportDefaultMinWidth = viewportDescription.minWidth;
3174 if (viewportDescription.isLegacyViewportType()) {
3175 if (settings() && !settings()->viewportMetaEnabled())
3178 m_legacyViewportDescription = viewportDescription;
3180 // When no author style for @viewport is present, and a meta tag for defining
3181 // the viewport is, apply the meta tag viewport instead of the UA styles.
3182 if (m_viewportDescription.type == ViewportDescription::AuthorStyleSheet)
3184 m_viewportDescription = viewportDescription;
3186 // If the legacy viewport tag has higher priority than the cascaded @viewport
3187 // descriptors, use the values from the legacy tag.
3188 if (!shouldOverrideLegacyDescription(viewportDescription.type))
3189 m_viewportDescription = m_legacyViewportDescription;
3191 m_viewportDescription = viewportDescription;
3194 updateViewportDescription();
3197 void Document::updateViewportDescription()
3199 if (frame() && frame()->isMainFrame()) {
3201 m_didDispatchViewportPropertiesChanged = true;
3203 frameHost()->chrome().dispatchViewportPropertiesDidChange(m_viewportDescription);
3207 void Document::processReferrerPolicy(const String& policy)
3209 ASSERT(!policy.isNull());
3211 if (equalIgnoringCase(policy, "never")) {
3212 setReferrerPolicy(ReferrerPolicyNever);
3213 } else if (equalIgnoringCase(policy, "always")) {
3214 setReferrerPolicy(ReferrerPolicyAlways);
3215 } else if (equalIgnoringCase(policy, "origin")) {
3216 setReferrerPolicy(ReferrerPolicyOrigin);
3217 } else if (equalIgnoringCase(policy, "default")) {
3218 setReferrerPolicy(ReferrerPolicyDefault);
3220 addConsoleMessage(RenderingMessageSource, ErrorMessageLevel, "Failed to set referrer policy: The value '" + policy + "' is not one of 'always', 'default', 'never', or 'origin'. Defaulting to 'never'.");
3221 setReferrerPolicy(ReferrerPolicyNever);
3225 void Document::setReferrerPolicy(ReferrerPolicy referrerPolicy)
3227 // 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?
3228 if (m_didSetReferrerPolicy)
3229 UseCounter::count(this, UseCounter::ResetReferrerPolicy);
3230 m_didSetReferrerPolicy = true;
3232 m_referrerPolicy = referrerPolicy;
3235 String Document::outgoingReferrer()
3237 // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
3238 // for why we walk the parent chain for srcdoc documents.
3239 Document* referrerDocument = this;
3240 if (LocalFrame* frame = m_frame) {
3241 while (frame->document()->isSrcdocDocument()) {
3242 // Srcdoc documents must be local within the containing frame.
3243 frame = toLocalFrame(frame->tree().parent());
3244 // Srcdoc documents cannot be top-level documents, by definition,
3245 // because they need to be contained in iframes with the srcdoc.
3248 referrerDocument = frame->document();
3250 return referrerDocument->m_url.strippedForUseAsReferrer();
3253 String Document::outgoingOrigin() const
3255 return securityOrigin()->toString();
3258 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3260 ASSERT(!renderView() || renderView()->isRenderView());
3262 // RenderView::hitTest causes a layout, and we don't want to hit that until the first
3263 // layout because until then, there is nothing shown on the screen - the user can't
3264 // have intentionally clicked on something belonging to this page. Furthermore,
3265 // mousemove events before the first layout should not lead to a premature layout()
3266 // happening, which could show a flash of white.
3267 // See also the similar code in EventHandler::hitTestResultAtPoint.
3268 if (!renderView() || !view() || !view()->didFirstLayout())
3269 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3271 HitTestResult result(documentPoint);
3272 renderView()->hitTest(request, result);
3274 if (!request.readOnly())
3275 updateHoverActiveState(request, result.innerElement(), &event);
3277 return MouseEventWithHitTestResults(event, result);
3280 // DOM Section 1.1.1
3281 bool Document::childTypeAllowed(NodeType type) const
3284 case ATTRIBUTE_NODE:
3285 case CDATA_SECTION_NODE:
3286 case DOCUMENT_FRAGMENT_NODE:
3291 case PROCESSING_INSTRUCTION_NODE:
3293 case DOCUMENT_TYPE_NODE:
3295 // Documents may contain no more than one of each of these.
3296 // (One Element and one DocumentType.)
3297 for (Node* c = firstChild(); c; c = c->nextSibling())
3298 if (c->nodeType() == type)
3305 bool Document::canReplaceChild(const Node& newChild, const Node& oldChild) const
3307 if (oldChild.nodeType() == newChild.nodeType())
3310 int numDoctypes = 0;
3311 int numElements = 0;
3313 // First, check how many doctypes and elements we have, not counting
3314 // the child we're about to remove.
3315 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3319 switch (c->nodeType()) {
3320 case DOCUMENT_TYPE_NODE:
3331 // Then, see how many doctypes and elements might be added by the new child.
3332 if (newChild.isDocumentFragment()) {
3333 for (Node* c = toDocumentFragment(newChild).firstChild(); c; c = c->nextSibling()) {
3334 switch (c->nodeType()) {
3335 case ATTRIBUTE_NODE:
3336 case CDATA_SECTION_NODE:
3337 case DOCUMENT_FRAGMENT_NODE:
3342 case PROCESSING_INSTRUCTION_NODE:
3344 case DOCUMENT_TYPE_NODE:
3353 switch (newChild.nodeType()) {
3354 case ATTRIBUTE_NODE:
3355 case CDATA_SECTION_NODE:
3356 case DOCUMENT_FRAGMENT_NODE:
3361 case PROCESSING_INSTRUCTION_NODE:
3363 case DOCUMENT_TYPE_NODE:
3372 if (numElements > 1 || numDoctypes > 1)
3378 PassRefPtrWillBeRawPtr<Node> Document::cloneNode(bool deep)
3380 RefPtrWillBeRawPtr<Document> clone = cloneDocumentWithoutChildren();
3381 clone->cloneDataFromDocument(*this);
3383 cloneChildNodes(clone.get());
3384 return clone.release();
3387 PassRefPtrWillBeRawPtr<Document> Document::cloneDocumentWithoutChildren()
3389 DocumentInit init(url());
3390 if (isXMLDocument()) {
3391 if (isXHTMLDocument())
3392 return XMLDocument::createXHTML(init.withRegistrationContext(registrationContext()));
3393 return XMLDocument::create(init);
3395 return create(init);
3398 void Document::cloneDataFromDocument(const Document& other)
3400 setCompatibilityMode(other.compatibilityMode());
3401 setEncodingData(other.m_encodingData);
3402 setContextFeatures(other.contextFeatures());
3403 setSecurityOrigin(other.securityOrigin()->isolatedCopy());
3404 setMimeType(other.contentType());
3407 StyleSheetList* Document::styleSheets()
3409 if (!m_styleSheetList)
3410 m_styleSheetList = StyleSheetList::create(this);
3411 return m_styleSheetList.get();
3414 String Document::preferredStylesheetSet() const
3416 return m_styleEngine->preferredStylesheetSetName();
3419 String Document::selectedStylesheetSet() const
3421 return m_styleEngine->selectedStylesheetSetName();
3424 void Document::setSelectedStylesheetSet(const String& aString)
3426 m_styleEngine->setSelectedStylesheetSetName(aString);
3427 styleResolverChanged();
3430 void Document::evaluateMediaQueryListIfNeeded()
3432 if (!m_evaluateMediaQueriesOnStyleRecalc)
3434 evaluateMediaQueryList();
3435 m_evaluateMediaQueriesOnStyleRecalc = false;
3438 void Document::evaluateMediaQueryList()
3440 if (m_mediaQueryMatcher)
3441 m_mediaQueryMatcher->styleResolverChanged();
3444 void Document::notifyResizeForViewportUnits()
3446 if (!hasViewportUnits())
3448 ensureStyleResolver().notifyResizeForViewportUnits();
3449 setNeedsStyleRecalcForViewportUnits();
3452 void Document::styleResolverChanged(StyleResolverUpdateMode updateMode)
3454 // styleResolverChanged() can be invoked during Document destruction.
3455 // We just skip that case.
3459 m_styleEngine->resolverChanged(updateMode);
3461 if (didLayoutWithPendingStylesheets() && !m_styleEngine->hasPendingSheets()) {
3462 // We need to manually repaint because we avoid doing all repaints in layout or style
3463 // recalc while sheets are still loading to avoid FOUC.
3464 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3465 renderView()->repaintViewAndCompositedLayers();
3469 void Document::styleResolverMayHaveChanged()
3471 styleResolverChanged(hasNodesWithPlaceholderStyle() ? FullStyleUpdate : AnalyzedStyleUpdate);
3474 void Document::setHoverNode(PassRefPtrWillBeRawPtr<Node> newHoverNode)
3476 m_hoverNode = newHoverNode;
3479 void Document::setActiveHoverElement(PassRefPtrWillBeRawPtr<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(PassRefPtrWillBeRawPtr<Element> prpNewFocusedElement, FocusType type)
3552 m_clearFocusedElementTimer.stop();
3554 RefPtrWillBeRawPtr<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* newTarget)
3694 m_cssTarget->didAffectSelector(AffectedSelectorTarget);
3695 m_cssTarget = newTarget;
3697 m_cssTarget->didAffectSelector(AffectedSelectorTarget);
3700 void Document::registerNodeList(const LiveNodeListBase* list)
3703 m_nodeLists[list->invalidationType()].add(list);
3705 m_nodeListCounts[list->invalidationType()]++;
3707 if (list->isRootedAtDocument())
3708 m_listsInvalidatedAtDocument.add(list);
3711 void Document::unregisterNodeList(const LiveNodeListBase* list)
3714 ASSERT(m_nodeLists[list->invalidationType()].contains(list));
3715 m_nodeLists[list->invalidationType()].remove(list);
3717 m_nodeListCounts[list->invalidationType()]--;
3719 if (list->isRootedAtDocument()) {
3720 ASSERT(m_listsInvalidatedAtDocument.contains(list));
3721 m_listsInvalidatedAtDocument.remove(list);
3725 void Document::registerNodeListWithIdNameCache(const LiveNodeListBase* list)
3728 m_nodeLists[InvalidateOnIdNameAttrChange].add(list);
3730 m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
3734 void Document::unregisterNodeListWithIdNameCache(const LiveNodeListBase* list)
3737 ASSERT(m_nodeLists[InvalidateOnIdNameAttrChange].contains(list));
3738 m_nodeLists[InvalidateOnIdNameAttrChange].remove(list);
3740 ASSERT(m_nodeListCounts[InvalidateOnIdNameAttrChange] > 0);
3741 m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
3745 void Document::attachNodeIterator(NodeIterator* ni)
3747 m_nodeIterators.add(ni);
3750 void Document::detachNodeIterator(NodeIterator* ni)
3752 // The node iterator can be detached without having been attached if its root node didn't have a document
3753 // when the iterator was created, but has it now.
3754 m_nodeIterators.remove(ni);
3757 void Document::moveNodeIteratorsToNewDocument(Node& node, Document& newDocument)
3759 WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> > nodeIteratorsList = m_nodeIterators;
3760 WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3761 for (WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3762 if ((*it)->root() == node) {
3763 detachNodeIterator(*it);
3764 newDocument.attachNodeIterator(*it);
3769 void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
3771 if (!m_ranges.isEmpty()) {
3772 AttachedRangeSet::const_iterator end = m_ranges.end();
3773 for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3774 (*it)->nodeChildrenChanged(container);
3778 void Document::updateRangesAfterNodeMovedToAnotherDocument(const Node& node)
3780 ASSERT(node.document() != this);
3781 if (m_ranges.isEmpty())
3783 AttachedRangeSet ranges = m_ranges;
3784 AttachedRangeSet::const_iterator end = ranges.end();
3785 for (AttachedRangeSet::const_iterator it = ranges.begin(); it != end; ++it)
3786 (*it)->updateOwnerDocumentIfNeeded();
3789 void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
3791 NoEventDispatchAssertion assertNoEventDispatch;
3792 if (!m_ranges.isEmpty()) {
3793 AttachedRangeSet::const_iterator end = m_ranges.end();
3794 for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3795 (*it)->nodeChildrenWillBeRemoved(container);
3798 WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3799 for (WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
3800 for (Node* n = container.firstChild(); n; n = n->nextSibling())
3801 (*it)->nodeWillBeRemoved(*n);
3804 if (LocalFrame* frame = this->frame()) {
3805 for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
3806 frame->eventHandler().nodeWillBeRemoved(*n);
3807 frame->selection().nodeWillBeRemoved(*n);
3808 frame->page()->dragCaretController().nodeWillBeRemoved(*n);
3813 void Document::nodeWillBeRemoved(Node& n)
3815 WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3816 for (WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3817 (*it)->nodeWillBeRemoved(n);
3819 if (!m_ranges.isEmpty()) {
3820 AttachedRangeSet::const_iterator rangesEnd = m_ranges.end();
3821 for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3822 (*it)->nodeWillBeRemoved(n);
3825 if (LocalFrame* frame = this->frame()) {
3826 frame->eventHandler().nodeWillBeRemoved(n);
3827 frame->selection().nodeWillBeRemoved(n);
3828 frame->page()->dragCaretController().nodeWillBeRemoved(n);
3832 void Document::didInsertText(Node* text, unsigned offset, unsigned length)
3834 if (!m_ranges.isEmpty()) {
3835 AttachedRangeSet::const_iterator end = m_ranges.end();
3836 for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3837 (*it)->didInsertText(text, offset, length);
3840 // Update the markers for spelling and grammar checking.
3841 m_markers->shiftMarkers(text, offset, length);
3844 void Document::didRemoveText(Node* text, unsigned offset, unsigned length)
3846 if (!m_ranges.isEmpty()) {
3847 AttachedRangeSet::const_iterator end = m_ranges.end();
3848 for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3849 (*it)->didRemoveText(text, offset, length);
3852 // Update the markers for spelling and grammar checking.
3853 m_markers->removeMarkers(text, offset, length);
3854 m_markers->shiftMarkers(text, offset + length, 0 - length);
3857 void Document::didMergeTextNodes(Text& oldNode, unsigned offset)
3859 if (!m_ranges.isEmpty()) {
3860 NodeWithIndex oldNodeWithIndex(oldNode);
3861 AttachedRangeSet::const_iterator end = m_ranges.end();
3862 for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3863 (*it)->didMergeTextNodes(oldNodeWithIndex, offset);
3867 m_frame->selection().didMergeTextNodes(oldNode, offset);
3869 // FIXME: This should update markers for spelling and grammar checking.
3872 void Document::didSplitTextNode(Text& oldNode)
3874 if (!m_ranges.isEmpty()) {
3875 AttachedRangeSet::const_iterator end = m_ranges.end();
3876 for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3877 (*it)->didSplitTextNode(oldNode);
3881 m_frame->selection().didSplitTextNode(oldNode);
3883 // FIXME: This should update markers for spelling and grammar checking.
3886 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3888 LocalDOMWindow* domWindow = this->domWindow();
3891 domWindow->setAttributeEventListener(eventType, listener);
3894 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3896 LocalDOMWindow* domWindow = this->domWindow();
3899 return domWindow->getAttributeEventListener(eventType);
3902 EventQueue* Document::eventQueue() const
3906 return m_domWindow->eventQueue();
3909 void Document::enqueueAnimationFrameEvent(PassRefPtrWillBeRawPtr<Event> event)
3911 ensureScriptedAnimationController().enqueueEvent(event);
3914 void Document::enqueueScrollEventForNode(Node* target)
3916 // Per the W3C CSSOM View Module only scroll events fired at the document should bubble.
3917 RefPtrWillBeRawPtr<Event> scrollEvent = target->isDocumentNode() ? Event::createBubble(EventTypeNames::scroll) : Event::create(EventTypeNames::scroll);
3918 scrollEvent->setTarget(target);
3919 ensureScriptedAnimationController().enqueuePerFrameEvent(scrollEvent.release());
3922 void Document::enqueueResizeEvent()
3924 RefPtrWillBeRawPtr<Event> event = Event::create(EventTypeNames::resize);
3925 event->setTarget(domWindow());
3926 ensureScriptedAnimationController().enqueuePerFrameEvent(event.release());
3929 Document::EventFactorySet& Document::eventFactories()
3931 DEFINE_STATIC_LOCAL(EventFactorySet, s_eventFactory, ());
3932 return s_eventFactory;
3935 void Document::registerEventFactory(PassOwnPtr<EventFactoryBase> eventFactory)
3937 ASSERT(!eventFactories().contains(eventFactory.get()));
3938 eventFactories().add(eventFactory);
3941 PassRefPtrWillBeRawPtr<Event> Document::createEvent(const String& eventType, ExceptionState& exceptionState)
3943 RefPtrWillBeRawPtr<Event> event = nullptr;
3944 for (EventFactorySet::const_iterator it = eventFactories().begin(); it != eventFactories().end(); ++it) {
3945 event = (*it)->create(eventType);
3947 return event.release();
3949 exceptionState.throwDOMException(NotSupportedError, "The provided event type ('" + eventType + "') is invalid.");
3953 void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
3955 if (ContextFeatures::mutationEventsEnabled(this))
3956 addListenerType(listenerType);
3959 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
3961 if (eventType == EventTypeNames::DOMSubtreeModified) {
3962 UseCounter::count(*this, UseCounter::DOMSubtreeModifiedEvent);
3963 addMutationEventListenerTypeIfEnabled(DOMSUBTREEMODIFIED_LISTENER);
3964 } else if (eventType == EventTypeNames::DOMNodeInserted) {
3965 UseCounter::count(*this, UseCounter::DOMNodeInsertedEvent);
3966 addMutationEventListenerTypeIfEnabled(DOMNODEINSERTED_LISTENER);
3967 } else if (eventType == EventTypeNames::DOMNodeRemoved) {
3968 UseCounter::count(*this, UseCounter::DOMNodeRemovedEvent);
3969 addMutationEventListenerTypeIfEnabled(DOMNODEREMOVED_LISTENER);
3970 } else if (eventType == EventTypeNames::DOMNodeRemovedFromDocument) {
3971 UseCounter::count(*this, UseCounter::DOMNodeRemovedFromDocumentEvent);
3972 addMutationEventListenerTypeIfEnabled(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
3973 } else if (eventType == EventTypeNames::DOMNodeInsertedIntoDocument) {
3974 UseCounter::count(*this, UseCounter::DOMNodeInsertedIntoDocumentEvent);
3975 addMutationEventListenerTypeIfEnabled(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
3976 } else if (eventType == EventTypeNames::DOMCharacterDataModified) {
3977 UseCounter::count(*this, UseCounter::DOMCharacterDataModifiedEvent);
3978 addMutationEventListenerTypeIfEnabled(DOMCHARACTERDATAMODIFIED_LISTENER);
3979 } else if (eventType == EventTypeNames::overflowchanged) {
3980 UseCounter::countDeprecation(*this, UseCounter::OverflowChangedEvent);
3981 addListenerType(OVERFLOWCHANGED_LISTENER);
3982 } else if (eventType == EventTypeNames::webkitAnimationStart || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationstart)) {
3983 addListenerType(ANIMATIONSTART_LISTENER);
3984 } else if (eventType == EventTypeNames::webkitAnimationEnd || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationend)) {
3985 addListenerType(ANIMATIONEND_LISTENER);
3986 } else if (eventType == EventTypeNames::webkitAnimationIteration || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationiteration)) {
3987 addListenerType(ANIMATIONITERATION_LISTENER);
3988 } else if (eventType == EventTypeNames::webkitTransitionEnd || eventType == EventTypeNames::transitionend) {
3989 addListenerType(TRANSITIONEND_LISTENER);
3990 } else if (eventType == EventTypeNames::scroll) {
3991 addListenerType(SCROLL_LISTENER);
3995 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
4000 HTMLFrameOwnerElement* Document::ownerElement() const
4004 // FIXME: This probably breaks the attempts to layout after a load is finished in implicitClose(), and probably tons of other things...
4005 return frame()->deprecatedLocalOwner();
4008 String Document::cookie(ExceptionState& exceptionState) const
4010 if (settings() && !settings()->cookieEnabled())
4013 // FIXME: The HTML5 DOM spec states that this attribute can raise an
4014 // InvalidStateError exception on getting if the Document has no
4015 // browsing context.
4017 if (!securityOrigin()->canAccessCookies()) {
4018 if (isSandboxed(SandboxOrigin))
4019 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
4020 else if (url().protocolIs("data"))
4021 exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
4023 exceptionState.throwSecurityError("Access is denied for this document.");
4027 KURL cookieURL = this->cookieURL();
4028 if (cookieURL.isEmpty())
4031 return cookies(this, cookieURL);
4034 void Document::setCookie(const String& value, ExceptionState& exceptionState)
4036 if (settings() && !settings()->cookieEnabled())
4039 // FIXME: The HTML5 DOM spec states that this attribute can raise an
4040 // InvalidStateError exception on setting if the Document has no
4041 // browsing context.
4043 if (!securityOrigin()->canAccessCookies()) {
4044 if (isSandboxed(SandboxOrigin))
4045 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
4046 else if (url().protocolIs("data"))
4047 exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
4049 exceptionState.throwSecurityError("Access is denied for this document.");
4053 KURL cookieURL = this->cookieURL();
4054 if (cookieURL.isEmpty())
4057 setCookies(this, cookieURL, value);
4060 const AtomicString& Document::referrer() const
4063 return loader()->request().httpReferrer();
4067 String Document::domain() const
4069 return securityOrigin()->domain();
4072 void Document::setDomain(const String& newDomain, ExceptionState& exceptionState)
4074 if (isSandboxed(SandboxDocumentDomain)) {
4075 exceptionState.throwSecurityError("Assignment is forbidden for sandboxed iframes.");
4079 if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
4080 exceptionState.throwSecurityError("Assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme.");
4084 if (newDomain.isEmpty()) {
4085 exceptionState.throwSecurityError("'" + newDomain + "' is an empty domain.");
4089 OriginAccessEntry::IPAddressSetting ipAddressSetting = settings() && settings()->treatIPAddressAsDomain() ? OriginAccessEntry::TreatIPAddressAsDomain : OriginAccessEntry::TreatIPAddressAsIPAddress;
4090 OriginAccessEntry accessEntry(securityOrigin()->protocol(), newDomain, OriginAccessEntry::AllowSubdomains, ipAddressSetting);
4091 OriginAccessEntry::MatchResult result = accessEntry.matchesOrigin(*securityOrigin());
4092 if (result == OriginAccessEntry::DoesNotMatchOrigin) {
4093 exceptionState.throwSecurityError("'" + newDomain + "' is not a suffix of '" + domain() + "'.");
4097 if (result == OriginAccessEntry::MatchesOriginButIsPublicSuffix) {
4098 exceptionState.throwSecurityError("'" + newDomain + "' is a top-level domain.");
4102 securityOrigin()->setDomainFromDOM(newDomain);
4104 m_frame->script().updateSecurityOrigin(securityOrigin());
4107 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
4108 String Document::lastModified() const
4110 DateComponents date;
4111 bool foundDate = false;
4113 if (DocumentLoader* documentLoader = loader()) {
4114 const AtomicString& httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
4115 if (!httpLastModified.isEmpty()) {
4116 date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
4121 // FIXME: If this document came from the file system, the HTML5
4122 // specificiation tells us to read the last modification date from the file
4125 date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
4126 return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
4129 const KURL& Document::firstPartyForCookies() const
4131 return topDocument().url();
4134 static bool isValidNameNonASCII(const LChar* characters, unsigned length)
4136 if (!isValidNameStart(characters[0]))
4139 for (unsigned i = 1; i < length; ++i) {
4140 if (!isValidNamePart(characters[i]))
4147 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
4152 U16_NEXT(characters, i, length, c)
4153 if (!isValidNameStart(c))
4156 while (i < length) {
4157 U16_NEXT(characters, i, length, c)
4158 if (!isValidNamePart(c))
4165 template<typename CharType>
4166 static inline bool isValidNameASCII(const CharType* characters, unsigned length)
4168 CharType c = characters[0];
4169 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
4172 for (unsigned i = 1; i < length; ++i) {
4174 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
4181 bool Document::isValidName(const String& name)
4183 unsigned length = name.length();
4187 if (name.is8Bit()) {
4188 const LChar* characters = name.characters8();
4190 if (isValidNameASCII(characters, length))
4193 return isValidNameNonASCII(characters, length);
4196 const UChar* characters = name.characters16();
4198 if (isValidNameASCII(characters, length))
4201 return isValidNameNonASCII(characters, length);
4204 template<typename CharType>
4205 static bool parseQualifiedNameInternal(const AtomicString& qualifiedName, const CharType* characters, unsigned length, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
4207 bool nameStart = true;
4208 bool sawColon = false;
4211 for (unsigned i = 0; i < length;) {
4213 U16_NEXT(characters, i, length, c)
4216 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') contains multiple colons.");
4217 return false; // multiple colons: not allowed
4222 } else if (nameStart) {
4223 if (!isValidNameStart(c)) {
4224 StringBuilder message;
4225 message.appendLiteral("The qualified name provided ('");
4226 message.append(qualifiedName);
4227 message.appendLiteral("') contains the invalid name-start character '");
4229 message.appendLiteral("'.");
4230 exceptionState.throwDOMException(InvalidCharacterError, message.toString());
4235 if (!isValidNamePart(c)) {
4236 StringBuilder message;
4237 message.appendLiteral("The qualified name provided ('");
4238 message.append(qualifiedName);
4239 message.appendLiteral("') contains the invalid character '");
4241 message.appendLiteral("'.");
4242 exceptionState.throwDOMException(InvalidCharacterError, message.toString());
4250 localName = qualifiedName;
4252 prefix = AtomicString(characters, colonPos);
4253 if (prefix.isEmpty()) {
4254 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty namespace prefix.");
4257 int prefixStart = colonPos + 1;
4258 localName = AtomicString(characters + prefixStart, length - prefixStart);
4261 if (localName.isEmpty()) {
4262 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty local name.");
4269 bool Document::parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
4271 unsigned length = qualifiedName.length();
4274 exceptionState.throwDOMException(InvalidCharacterError, "The qualified name provided is empty.");
4278 if (qualifiedName.is8Bit())
4279 return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName, exceptionState);
4280 return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName, exceptionState);
4283 void Document::setEncodingData(const DocumentEncodingData& newData)
4285 // It's possible for the encoding of the document to change while we're decoding
4286 // data. That can only occur while we're processing the <head> portion of the
4287 // document. There isn't much user-visible content in the <head>, but there is
4288 // the <title> element. This function detects that situation and re-decodes the
4289 // document's title so that the user doesn't see an incorrectly decoded title
4290 // in the title bar.
4292 && encoding() != newData.encoding()
4293 && !ElementTraversal::firstWithin(*m_titleElement)
4294 && encoding() == Latin1Encoding()
4295 && m_titleElement->textContent().containsOnlyLatin1()) {
4297 CString originalBytes = m_titleElement->textContent().latin1();
4298 OwnPtr<TextCodec> codec = newTextCodec(newData.encoding());
4299 String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), DataEOF);
4300 m_titleElement->setTextContent(correctlyDecodedTitle);
4303 m_encodingData = newData;
4305 // FIXME: Should be removed as part of https://code.google.com/p/chromium/issues/detail?id=319643
4306 bool shouldUseVisualOrdering = m_encodingData.encoding().usesVisualOrdering();
4307 if (shouldUseVisualOrdering != m_visuallyOrdered) {
4308 m_visuallyOrdered = shouldUseVisualOrdering;
4309 // FIXME: How is possible to not have a renderer here?
4311 renderView()->style()->setRTLOrdering(m_visuallyOrdered ? VisualOrder : LogicalOrder);
4312 setNeedsStyleRecalc(SubtreeStyleChange);
4316 KURL Document::completeURL(const String& url) const
4318 return completeURLWithOverride(url, m_baseURL);
4321 KURL Document::completeURLWithOverride(const String& url, const KURL& baseURLOverride) const
4323 // Always return a null URL when passed a null string.
4324 // FIXME: Should we change the KURL constructor to have this behavior?
4325 // See also [CSS]StyleSheet::completeURL(const String&)
4328 // This logic is deliberately spread over many statements in an attempt to track down http://crbug.com/312410.
4329 const KURL* baseURLFromParent = 0;
4330 bool shouldUseParentBaseURL = baseURLOverride.isEmpty();
4331 if (!shouldUseParentBaseURL) {
4332 const KURL& aboutBlankURL = blankURL();
4333 shouldUseParentBaseURL = (baseURLOverride == aboutBlankURL);
4335 if (shouldUseParentBaseURL) {
4336 if (Document* parent = parentDocument())
4337 baseURLFromParent = &parent->baseURL();
4339 const KURL& baseURL = baseURLFromParent ? *baseURLFromParent : baseURLOverride;
4340 if (!encoding().isValid())
4341 return KURL(baseURL, url);
4342 return KURL(baseURL, url, encoding());
4345 // Support for Javascript execCommand, and related methods
4347 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
4349 LocalFrame* frame = document->frame();
4350 if (!frame || frame->document() != document)
4351 return Editor::Command();
4353 document->updateRenderTreeIfNeeded();
4354 return frame->editor().command(commandName, userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
4357 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
4359 // We don't allow recusrive |execCommand()| to protect against attack code.
4360 // Recursive call of |execCommand()| could be happened by moving iframe
4361 // with script triggered by insertion, e.g. <iframe src="javascript:...">
4362 // <iframe onload="...">. This usage is valid as of the specification
4363 // although, it isn't common use case, rather it is used as attack code.
4364 static bool inExecCommand = false;
4365 if (inExecCommand) {
4366 String message = "We don't execute document.execCommand() this time, because it is called recursively.";
4367 addConsoleMessage(JSMessageSource, WarningMessageLevel, message);
4370 TemporaryChange<bool> executeScope(inExecCommand, true);
4372 // Postpone DOM mutation events, which can execute scripts and change
4373 // DOM tree against implementation assumption.
4374 EventQueueScope eventQueueScope;
4375 Editor::Command editorCommand = command(this, commandName, userInterface);
4376 blink::Platform::current()->histogramSparse("WebCore.Document.execCommand", editorCommand.idForHistogram());
4377 return editorCommand.execute(value);
4380 bool Document::queryCommandEnabled(const String& commandName)
4382 return command(this, commandName).isEnabled();
4385 bool Document::queryCommandIndeterm(const String& commandName)
4387 return command(this, commandName).state() == MixedTriState;
4390 bool Document::queryCommandState(const String& commandName)
4392 return command(this, commandName).state() == TrueTriState;
4395 bool Document::queryCommandSupported(const String& commandName)
4397 return command(this, commandName).isSupported();
4400 String Document::queryCommandValue(const String& commandName)
4402 return command(this, commandName).value();
4405 KURL Document::openSearchDescriptionURL()
4407 static const char openSearchMIMEType[] = "application/opensearchdescription+xml";
4408 static const char openSearchRelation[] = "search";
4410 // FIXME: Why do only top-level frames have openSearchDescriptionURLs?
4411 if (!frame() || frame()->tree().parent())
4414 // FIXME: Why do we need to wait for FrameStateComplete?
4415 if (frame()->loader().state() != FrameStateComplete)
4421 for (HTMLLinkElement* linkElement = Traversal<HTMLLinkElement>::firstChild(*head()); linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4422 if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
4424 if (linkElement->href().isEmpty())
4426 return linkElement->href();
4432 void Document::pushCurrentScript(PassRefPtrWillBeRawPtr<HTMLScriptElement> newCurrentScript)
4434 ASSERT(newCurrentScript);
4435 m_currentScriptStack.append(newCurrentScript);
4438 void Document::popCurrentScript()
4440 ASSERT(!m_currentScriptStack.isEmpty());
4441 m_currentScriptStack.removeLast();
4444 void Document::applyXSLTransform(ProcessingInstruction* pi)
4446 ASSERT(!pi->isLoading());
4447 UseCounter::count(*this, UseCounter::XSLProcessingInstruction);
4448 RefPtrWillBeRawPtr<XSLTProcessor> processor = XSLTProcessor::create();
4449 processor->setXSLStyleSheet(toXSLStyleSheet(pi->sheet()));
4450 String resultMIMEType;
4452 String resultEncoding;
4453 if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
4455 // FIXME: If the transform failed we should probably report an error (like Mozilla does).
4456 LocalFrame* ownerFrame = frame();
4457 processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, ownerFrame);
4458 InspectorInstrumentation::frameDocumentUpdated(ownerFrame);
4461 void Document::setTransformSource(PassOwnPtr<TransformSource> source)
4463 m_transformSource = source;
4466 void Document::setDesignMode(InheritedBool value)
4468 m_designMode = value;
4469 for (Frame* frame = m_frame; frame; frame = frame->tree().traverseNext(m_frame)) {
4470 if (!frame->isLocalFrame())
4472 if (!toLocalFrame(frame)->document())
4474 toLocalFrame(frame)->document()->setNeedsStyleRecalc(SubtreeStyleChange);
4478 Document::InheritedBool Document::getDesignMode() const
4480 return m_designMode;
4483 bool Document::inDesignMode() const
4485 for (const Document* d = this; d; d = d->parentDocument()) {
4486 if (d->m_designMode != inherit)
4487 return d->m_designMode;
4492 String Document::designMode() const
4494 return inDesignMode() ? "on" : "off";
4497 void Document::setDesignMode(const String& value)
4500 if (equalIgnoringCase(value, "on"))
4502 else if (equalIgnoringCase(value, "off"))
4506 setDesignMode(mode);
4509 Document* Document::parentDocument() const
4513 Frame* parent = m_frame->tree().parent();
4514 if (!parent || !parent->isLocalFrame())
4516 return toLocalFrame(parent)->document();
4519 Document& Document::topDocument() const
4521 // FIXME: Not clear what topDocument() should do in the OOPI case--should it return the topmost
4522 // available Document, or something else?
4523 Document* doc = const_cast<Document*>(this);
4525 while ((element = doc->ownerElement()))
4526 doc = &element->document();
4532 WeakPtrWillBeRawPtr<Document> Document::contextDocument()
4534 if (m_contextDocument)
4535 return m_contextDocument;
4540 return m_weakFactory.createWeakPtr();
4543 return WeakPtrWillBeRawPtr<Document>(nullptr);
4546 PassRefPtrWillBeRawPtr<Attr> Document::createAttribute(const AtomicString& name, ExceptionState& exceptionState)
4548 return createAttributeNS(nullAtom, name, exceptionState, true);
4551 PassRefPtrWillBeRawPtr<Attr> Document::createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState, bool shouldIgnoreNamespaceChecks)
4553 AtomicString prefix, localName;
4554 if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
4557 QualifiedName qName(prefix, localName, namespaceURI);
4559 if (!shouldIgnoreNamespaceChecks && !hasValidNamespaceForAttributes(qName)) {
4560 exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
4564 return Attr::create(*this, qName, emptyAtom);
4567 const SVGDocumentExtensions* Document::svgExtensions()
4569 return m_svgExtensions.get();
4572 SVGDocumentExtensions& Document::accessSVGExtensions()
4574 if (!m_svgExtensions)
4575 m_svgExtensions = adoptPtrWillBeNoop(new SVGDocumentExtensions(this));
4576 return *m_svgExtensions;
4579 bool Document::hasSVGRootNode() const
4581 return isSVGSVGElement(documentElement());
4584 PassRefPtrWillBeRawPtr<HTMLCollection> Document::ensureCachedCollection(CollectionType type)
4586 return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(*this, type);
4589 PassRefPtrWillBeRawPtr<HTMLCollection> Document::images()
4591 return ensureCachedCollection(DocImages);
4594 PassRefPtrWillBeRawPtr<HTMLCollection> Document::applets()
4596 return ensureCachedCollection(DocApplets);
4599 PassRefPtrWillBeRawPtr<HTMLCollection> Document::embeds()
4601 return ensureCachedCollection(DocEmbeds);
4604 PassRefPtrWillBeRawPtr<HTMLCollection> Document::scripts()
4606 return ensureCachedCollection(DocScripts);
4609 PassRefPtrWillBeRawPtr<HTMLCollection> Document::links()
4611 return ensureCachedCollection(DocLinks);
4614 PassRefPtrWillBeRawPtr<HTMLCollection> Document::forms()
4616 return ensureCachedCollection(DocForms);
4619 PassRefPtrWillBeRawPtr<HTMLCollection> Document::anchors()
4621 return ensureCachedCollection(DocAnchors);
4624 PassRefPtrWillBeRawPtr<HTMLAllCollection> Document::allForBinding()
4626 UseCounter::count(*this, UseCounter::DocumentAll);
4630 PassRefPtrWillBeRawPtr<HTMLAllCollection> Document::all()
4632 return ensureRareData().ensureNodeLists().addCache<HTMLAllCollection>(*this, DocAll);
4635 PassRefPtrWillBeRawPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
4637 return ensureRareData().ensureNodeLists().addCache<WindowNameCollection>(*this, WindowNamedItems, name);
4640 PassRefPtrWillBeRawPtr<HTMLCollection> Document::documentNamedItems(const AtomicString& name)
4642 return ensureRareData().ensureNodeLists().addCache<DocumentNameCollection>(*this, DocumentNamedItems, name);
4645 void Document::finishedParsing()
4647 ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
4648 ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
4650 if (!m_documentTiming.domContentLoadedEventStart)
4651 m_documentTiming.domContentLoadedEventStart = monotonicallyIncreasingTime();
4652 dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
4653 if (!m_documentTiming.domContentLoadedEventEnd)
4654 m_documentTiming.domContentLoadedEventEnd = monotonicallyIncreasingTime();
4656 if (frame() && frame()->isMainFrame()) {
4657 // Reset the text autosizing multipliers on main frame when DOM is loaded.
4658 // This is to allow for a fresh text autosizing pass when the page layout
4659 // changes significantly in the end.
4660 if (TextAutosizer* textAutosizer = this->textAutosizer())
4661 textAutosizer->recalculateMultipliers();
4664 // The loader's finishedParsing() method may invoke script that causes this object to
4665 // be dereferenced (when this document is in an iframe and the onload causes the iframe's src to change).
4666 // Keep it alive until we are done.
4667 RefPtrWillBeRawPtr<Document> protect(this);
4669 if (RefPtr<LocalFrame> f = frame()) {
4670 // Don't update the render tree if we haven't requested the main resource yet to avoid
4671 // adding extra latency. Note that the first render tree update can be expensive since it
4672 // triggers the parsing of the default stylesheets which are compiled-in.
4673 const bool mainResourceWasAlreadyRequested =
4674 m_frame->loader().stateMachine()->committedFirstRealDocumentLoad();
4676 // FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
4677 // resource loads are complete. HTMLObjectElements can start loading their resources from
4678 // post attach callbacks triggered by recalcStyle(). This means if we parse out an <object>
4679 // tag and then reach the end of the document without updating styles, we might not have yet
4680 // started the resource load and might fire the window load event too early. To avoid this
4681 // we force the styles to be up to date before calling FrameLoader::finishedParsing().
4682 // See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
4683 if (mainResourceWasAlreadyRequested)
4684 updateRenderTreeIfNeeded();
4686 f->loader().finishedParsing();
4688 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", "data", InspectorMarkLoadEvent::data(f.get()));
4689 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
4690 InspectorInstrumentation::domContentLoadedEventFired(f.get());
4693 // Schedule dropping of the ElementDataCache. We keep it alive for a while after parsing finishes
4694 // so that dynamically inserted content can also benefit from sharing optimizations.
4695 // Note that we don't refresh the timer on cache access since that could lead to huge caches being kept
4696 // alive indefinitely by something innocuous like JS setting .innerHTML repeatedly on a timer.
4697 m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
4699 // Parser should have picked up all preloads by now
4700 m_fetcher->clearPreloads();
4702 if (HTMLImportLoader* import = importLoader())
4703 import->didFinishParsing();
4706 void Document::elementDataCacheClearTimerFired(Timer<Document>*)
4708 m_elementDataCache.clear();
4711 Vector<IconURL> Document::iconURLs(int iconTypesMask)
4713 IconURL firstFavicon;
4714 IconURL firstTouchIcon;
4715 IconURL firstTouchPrecomposedIcon;
4716 Vector<IconURL> secondaryIcons;
4718 // Start from the last child node so that icons seen later take precedence as required by the spec.
4719 for (HTMLLinkElement* linkElement = head() ? Traversal<HTMLLinkElement>::firstChild(*head()) : 0; linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4720 if (!(linkElement->iconType() & iconTypesMask))
4722 if (linkElement->href().isEmpty())
4724 if (!RuntimeEnabledFeatures::touchIconLoadingEnabled() && linkElement->iconType() != Favicon)
4727 IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
4728 if (linkElement->iconType() == Favicon) {
4729 if (firstFavicon.m_iconType != InvalidIcon)
4730 secondaryIcons.append(firstFavicon);
4731 firstFavicon = newURL;
4732 } else if (linkElement->iconType() == TouchIcon) {
4733 if (firstTouchIcon.m_iconType != InvalidIcon)
4734 secondaryIcons.append(firstTouchIcon);
4735 firstTouchIcon = newURL;
4736 } else if (linkElement->iconType() == TouchPrecomposedIcon) {
4737 if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4738 secondaryIcons.append(firstTouchPrecomposedIcon);
4739 firstTouchPrecomposedIcon = newURL;
4741 ASSERT_NOT_REACHED();
4745 Vector<IconURL> iconURLs;
4746 if (firstFavicon.m_iconType != InvalidIcon)
4747 iconURLs.append(firstFavicon);
4748 else if (m_url.protocolIsInHTTPFamily() && iconTypesMask & Favicon)
4749 iconURLs.append(IconURL::defaultFavicon(m_url));
4751 if (firstTouchIcon.m_iconType != InvalidIcon)
4752 iconURLs.append(firstTouchIcon);
4753 if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4754 iconURLs.append(firstTouchPrecomposedIcon);
4755 for (int i = secondaryIcons.size() - 1; i >= 0; --i)
4756 iconURLs.append(secondaryIcons[i]);
4760 Color Document::themeColor() const
4762 if (!RuntimeEnabledFeatures::themeColorEnabled())
4765 for (HTMLMetaElement* metaElement = head() ? Traversal<HTMLMetaElement>::firstChild(*head()) : 0; metaElement; metaElement = Traversal<HTMLMetaElement>::nextSibling(*metaElement)) {
4767 if (equalIgnoringCase(metaElement->name(), "theme-color") && BisonCSSParser::parseColor(rgb, metaElement->content().string().stripWhiteSpace(), true))
4773 HTMLLinkElement* Document::linkManifest() const
4775 HTMLHeadElement* head = this->head();
4779 // The first link element with a manifest rel must be used. Others are ignored.
4780 for (HTMLLinkElement* linkElement = Traversal<HTMLLinkElement>::firstChild(*head); linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4781 if (!linkElement->relAttribute().isManifest())
4789 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
4791 if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
4794 m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
4795 m_frame->selection().updateSecureKeyboardEntryIfActive();
4798 bool Document::useSecureKeyboardEntryWhenActive() const
4800 return m_useSecureKeyboardEntryWhenActive;
4803 void Document::initSecurityContext()
4805 initSecurityContext(DocumentInit(m_url, m_frame, contextDocument(), m_importsController));
4808 static PassRefPtr<ContentSecurityPolicy> contentSecurityPolicyFor(Document* document)
4810 if (document->importsController())
4811 return document->importsController()->master()->contentSecurityPolicy();
4812 return ContentSecurityPolicy::create(document);
4815 void Document::initSecurityContext(const DocumentInit& initializer)
4817 if (haveInitializedSecurityOrigin()) {
4818 ASSERT(securityOrigin());
4822 if (!initializer.hasSecurityContext()) {
4823 // No source for a security context.
4824 // This can occur via document.implementation.createDocument().
4825 m_cookieURL = KURL(ParsedURLString, emptyString());
4826 setSecurityOrigin(SecurityOrigin::createUnique());
4827 setContentSecurityPolicy(ContentSecurityPolicy::create(this));
4831 // In the common case, create the security context from the currently
4832 // loading URL with a fresh content security policy.
4833 m_cookieURL = m_url;
4834 enforceSandboxFlags(initializer.sandboxFlags());
4835 setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
4836 setContentSecurityPolicy(contentSecurityPolicyFor(this));
4838 if (Settings* settings = initializer.settings()) {
4839 if (!settings->webSecurityEnabled()) {
4840 // Web security is turned off. We should let this document access every other document. This is used primary by testing
4841 // harnesses for web sites.
4842 securityOrigin()->grantUniversalAccess();
4843 } else if (securityOrigin()->isLocal()) {
4844 if (settings->allowUniversalAccessFromFileURLs()) {
4845 // Some clients want local URLs to have universal access, but that setting is dangerous for other clients.
4846 securityOrigin()->grantUniversalAccess();
4847 } else if (!settings->allowFileAccessFromFileURLs()) {
4848 // Some clients want local URLs to have even tighter restrictions by default, and not be able to access other local files.
4849 // FIXME 81578: The naming of this is confusing. Files with restricted access to other local files
4850 // still can have other privileges that can be remembered, thereby not making them unique origins.
4851 securityOrigin()->enforceFilePathSeparation();
4856 if (initializer.shouldTreatURLAsSrcdocDocument()) {
4857 m_isSrcdocDocument = true;
4858 setBaseURLOverride(initializer.parentBaseURL());
4861 if (!shouldInheritSecurityOriginFromOwner(m_url))
4864 // If we do not obtain a meaningful origin from the URL, then we try to
4865 // find one via the frame hierarchy.
4867 if (!initializer.owner()) {
4868 didFailToInitializeSecurityOrigin();
4872 if (isSandboxed(SandboxOrigin)) {
4873 // If we're supposed to inherit our security origin from our owner,
4874 // but we're also sandboxed, the only thing we inherit is the ability
4875 // to load local resources. This lets about:blank iframes in file://
4876 // URL documents load images and other resources from the file system.
4877 if (initializer.owner()->securityOrigin()->canLoadLocalResources())
4878 securityOrigin()->grantLoadLocalResources();
4882 m_cookieURL = initializer.owner()->cookieURL();
4883 // We alias the SecurityOrigins to match Firefox, see Bug 15313
4884 // https://bugs.webkit.org/show_bug.cgi?id=15313
4885 setSecurityOrigin(initializer.owner()->securityOrigin());
4888 void Document::initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders& headers)
4890 if (m_frame && m_frame->tree().parent() && m_frame->tree().parent()->isLocalFrame() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
4891 contentSecurityPolicy()->copyStateFrom(toLocalFrame(m_frame->tree().parent())->document()->contentSecurityPolicy());
4892 contentSecurityPolicy()->didReceiveHeaders(headers);
4895 bool Document::allowInlineEventHandlers(Node* node, EventListener* listener, const String& contextURL, const WTF::OrdinalNumber& contextLine)
4897 if (!contentSecurityPolicy()->allowInlineEventHandlers(contextURL, contextLine))
4900 // HTML says that inline script needs browsing context to create its execution environment.
4901 // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#event-handler-attributes
4902 // Also, if the listening node came from other document, which happens on context-less event dispatching,
4903 // we also need to ask the owner document of the node.
4904 LocalFrame* frame = executingFrame();
4907 if (!frame->script().canExecuteScripts(NotAboutToExecuteScript))
4909 if (node && node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
4915 bool Document::allowExecutingScripts(Node* node)
4917 // FIXME: Eventually we'd like to evaluate scripts which are inserted into a
4918 // viewless document but this'll do for now.
4919 // See http://bugs.webkit.org/show_bug.cgi?id=5727
4920 LocalFrame* frame = executingFrame();
4923 if (!node->document().executingFrame())
4925 if (!frame->script().canExecuteScripts(AboutToExecuteScript))
4930 void Document::updateSecurityOrigin(PassRefPtr<SecurityOrigin> origin)
4932 setSecurityOrigin(origin);
4933 didUpdateSecurityOrigin();
4936 void Document::didUpdateSecurityOrigin()
4940 m_frame->script().updateSecurityOrigin(securityOrigin());
4943 bool Document::isContextThread() const
4945 return isMainThread();
4948 void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
4950 m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
4951 if (!m_updateFocusAppearanceTimer.isActive())
4952 m_updateFocusAppearanceTimer.startOneShot(0, FROM_HERE);
4955 void Document::cancelFocusAppearanceUpdate()
4957 m_updateFocusAppearanceTimer.stop();
4960 void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
4962 Element* element = focusedElement();
4966 if (element->isFocusable())
4967 element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
4970 void Document::attachRange(Range* range)
4972 ASSERT(!m_ranges.contains(range));
4973 m_ranges.add(range);
4976 void Document::detachRange(Range* range)
4978 // We don't ASSERT m_ranges.contains(range) to allow us to call this
4979 // unconditionally to fix: https://bugs.webkit.org/show_bug.cgi?id=26044
4980 m_ranges.remove(range);
4983 void Document::getCSSCanvasContext(const String& type, const String& name, int width, int height, bool& is2d, RefPtrWillBeRawPtr<CanvasRenderingContext2D>& context2d, bool& is3d, RefPtrWillBeRawPtr<WebGLRenderingContext>& context3d)
4985 HTMLCanvasElement& element = getCSSCanvasElement(name);
4986 element.setSize(IntSize(width, height));
4987 CanvasRenderingContext* context = element.getContext(type);
4991 if (context->is2d()) {
4993 context2d = toCanvasRenderingContext2D(context);
4994 } else if (context->is3d()) {
4996 context3d = toWebGLRenderingContext(context);
5000 HTMLCanvasElement& Document::getCSSCanvasElement(const String& name)
5002 RefPtrWillBeMember<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, nullptr).storedValue->value;
5004 element = HTMLCanvasElement::create(*this);
5005 element->setAccelerationDisabled(true);
5010 void Document::initDNSPrefetch()
5012 Settings* settings = this->settings();
5014 m_haveExplicitlyDisabledDNSPrefetch = false;
5015 m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
5017 // Inherit DNS prefetch opt-out from parent frame
5018 if (Document* parent = parentDocument()) {
5019 if (!parent->isDNSPrefetchEnabled())
5020 m_isDNSPrefetchEnabled = false;
5024 void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
5026 if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
5027 m_isDNSPrefetchEnabled = true;
5031 m_isDNSPrefetchEnabled = false;
5032 m_haveExplicitlyDisabledDNSPrefetch = true;
5035 void Document::reportBlockedScriptExecutionToInspector(const String& directiveText)
5037 InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText);
5040 void Document::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* scriptState)
5042 internalAddMessage(source, level, message, sourceURL, lineNumber, nullptr, scriptState);
5045 void Document::internalAddMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtrWillBeRawPtr<ScriptCallStack> callStack, ScriptState* scriptState)
5047 if (!isContextThread()) {
5048 m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
5055 String messageURL = sourceURL;
5056 if (!scriptState && sourceURL.isNull() && !lineNumber) {
5057 messageURL = url().string();
5058 if (parsing() && !isInDocumentWrite() && scriptableDocumentParser()) {
5059 ScriptableDocumentParser* parser = scriptableDocumentParser();
5060 if (!parser->isWaitingForScripts() && !parser->isExecutingScript())
5061 lineNumber = parser->lineNumber().oneBasedInt();
5064 m_frame->console().addMessage(source, level, message, messageURL, lineNumber, 0, callStack, scriptState, 0);
5067 void Document::addConsoleMessageWithRequestIdentifier(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
5069 if (!isContextThread()) {
5070 m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
5075 m_frame->console().addMessage(source, level, message, String(), 0, 0, nullptr, 0, requestIdentifier);
5078 // FIXME(crbug.com/305497): This should be removed after ExecutionContext-LocalDOMWindow migration.
5079 void Document::postTask(PassOwnPtr<ExecutionContextTask> task)
5081 m_taskRunner->postTask(task);
5084 void Document::tasksWereSuspended()
5086 scriptRunner()->suspend();
5089 m_parser->suspendScheduledTasks();
5090 if (m_scriptedAnimationController)
5091 m_scriptedAnimationController->suspend();
5094 void Document::tasksWereResumed()
5096 scriptRunner()->resume();
5099 m_parser->resumeScheduledTasks();
5100 if (m_scriptedAnimationController)
5101 m_scriptedAnimationController->resume();
5103 MutationObserver::resumeSuspendedObservers();
5106 // FIXME: suspendScheduledTasks(), resumeScheduledTasks(), tasksNeedSuspension()
5107 // should be moved to LocalDOMWindow once it inherits ExecutionContext
5108 void Document::suspendScheduledTasks()
5110 ExecutionContext::suspendScheduledTasks();
5111 m_taskRunner->suspend();
5114 void Document::resumeScheduledTasks()
5116 ExecutionContext::resumeScheduledTasks();
5117 m_taskRunner->resume();
5120 bool Document::tasksNeedSuspension()
5122 Page* page = this->page();
5123 return page && page->defersLoading();
5126 void Document::addToTopLayer(Element* element, const Element* before)
5128 if (element->isInTopLayer())
5131 ASSERT(!m_topLayerElements.contains(element));
5132 ASSERT(!before || m_topLayerElements.contains(before));
5134 size_t beforePosition = m_topLayerElements.find(before);
5135 m_topLayerElements.insert(beforePosition, element);
5137 m_topLayerElements.append(element);
5139 element->setIsInTopLayer(true);
5142 void Document::removeFromTopLayer(Element* element)
5144 if (!element->isInTopLayer())
5146 size_t position = m_topLayerElements.find(element);
5147 ASSERT(position != kNotFound);
5148 m_topLayerElements.remove(position);
5149 element->setIsInTopLayer(false);
5152 HTMLDialogElement* Document::activeModalDialog() const
5154 if (m_topLayerElements.isEmpty())
5156 return toHTMLDialogElement(m_topLayerElements.last().get());
5159 void Document::exitPointerLock()
5163 if (Element* target = page()->pointerLockController().element()) {
5164 if (target->document() != this)
5167 page()->pointerLockController().requestPointerUnlock();
5170 Element* Document::pointerLockElement() const
5172 if (!page() || page()->pointerLockController().lockPending())
5174 if (Element* element = page()->pointerLockController().element()) {
5175 if (element->document() == this)
5181 void Document::decrementLoadEventDelayCount()
5183 ASSERT(m_loadEventDelayCount);
5184 --m_loadEventDelayCount;
5186 if (!m_loadEventDelayCount)
5187 checkLoadEventSoon();
5190 void Document::checkLoadEventSoon()
5192 if (frame() && !m_loadEventDelayTimer.isActive())
5193 m_loadEventDelayTimer.startOneShot(0, FROM_HERE);
5196 bool Document::isDelayingLoadEvent()
5199 // Always delay load events until after garbage collection.
5200 // This way we don't have to explicitly delay load events via
5201 // incrementLoadEventDelayCount and decrementLoadEventDelayCount in
5202 // Node destructors.
5203 if (ThreadState::current()->isSweepInProgress()) {
5204 if (!m_loadEventDelayCount)
5205 checkLoadEventSoon();
5209 return m_loadEventDelayCount;
5213 void Document::loadEventDelayTimerFired(Timer<Document>*)
5216 frame()->loader().checkCompleted();
5219 void Document::loadPluginsSoon()
5221 // FIXME: Remove this timer once we don't need to compute layout to load plugins.
5222 if (!m_pluginLoadingTimer.isActive())
5223 m_pluginLoadingTimer.startOneShot(0, FROM_HERE);
5226 void Document::pluginLoadingTimerFired(Timer<Document>*)
5231 ScriptedAnimationController& Document::ensureScriptedAnimationController()
5233 if (!m_scriptedAnimationController) {
5234 m_scriptedAnimationController = ScriptedAnimationController::create(this);
5235 // We need to make sure that we don't start up the animation controller on a background tab, for example.
5237 m_scriptedAnimationController->suspend();
5239 return *m_scriptedAnimationController;
5242 int Document::requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
5244 return ensureScriptedAnimationController().registerCallback(callback);
5247 void Document::cancelAnimationFrame(int id)
5249 if (!m_scriptedAnimationController)
5251 m_scriptedAnimationController->cancelCallback(id);
5254 void Document::serviceScriptedAnimations(double monotonicAnimationStartTime)
5256 if (!m_scriptedAnimationController)
5258 m_scriptedAnimationController->serviceScriptedAnimations(monotonicAnimationStartTime);
5261 PassRefPtrWillBeRawPtr<Touch> Document::createTouch(LocalDOMWindow* window, EventTarget* target, int identifier, double pageX, double pageY, double screenX, double screenY, double radiusX, double radiusY, float rotationAngle, float force) const
5263 // Match behavior from when these types were integers, and avoid surprises from someone explicitly
5264 // passing Infinity/NaN.
5265 if (!std::isfinite(pageX))
5267 if (!std::isfinite(pageY))
5269 if (!std::isfinite(screenX))
5271 if (!std::isfinite(screenY))
5273 if (!std::isfinite(radiusX))
5275 if (!std::isfinite(radiusY))
5277 if (!std::isfinite(rotationAngle))
5279 if (!std::isfinite(force))
5282 // FIXME: It's not clear from the documentation at
5283 // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html
5284 // 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
5285 // and implement them here. See https://bugs.webkit.org/show_bug.cgi?id=47819
5286 LocalFrame* frame = window ? window->frame() : this->frame();
5287 return Touch::create(frame, target, identifier, FloatPoint(screenX, screenY), FloatPoint(pageX, pageY), FloatSize(radiusX, radiusY), rotationAngle, force);
5290 PassRefPtrWillBeRawPtr<TouchList> Document::createTouchList(WillBeHeapVector<RefPtrWillBeMember<Touch> >& touches) const
5292 return TouchList::create(touches);
5295 void Document::didAddTouchEventHandler(Node* handler)
5297 // The node should either be in this document, or be the Document node of a child
5298 // of this document.
5299 ASSERT(&handler->document() == this
5300 || (handler->isDocumentNode() && toDocument(handler)->parentDocument() == this));
5301 if (!m_touchEventTargets.get())
5302 m_touchEventTargets = adoptPtr(new TouchEventTargetSet);
5303 bool isFirstHandler = m_touchEventTargets->isEmpty();
5305 if (!m_touchEventTargets->add(handler).isNewEntry) {
5306 // Just incremented refcount, no real change.
5307 // If this is a child document node, then the count should never go above 1.
5308 ASSERT(!handler->isDocumentNode() || &handler->document() == this);
5312 if (isFirstHandler) {
5313 if (Document* parent = parentDocument()) {
5314 parent->didAddTouchEventHandler(this);
5316 // This is the first touch handler on the whole page.
5317 if (FrameHost* frameHost = this->frameHost())
5318 frameHost->chrome().client().needTouchEvents(true);
5322 // When we're all done with all frames, ensure touch hit rects are marked as dirty.
5323 if (!handler->isDocumentNode() || handler == this) {
5324 if (Page* page = this->page()) {
5325 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
5326 scrollingCoordinator->touchEventTargetRectsDidChange();
5331 void Document::didRemoveTouchEventHandler(Node* handler, bool clearAll)
5333 // Note that we can't assert that |handler| is in this document because it might be in
5334 // the process of moving out of it.
5335 ASSERT(clearAll || m_touchEventTargets->contains(handler));
5336 if (!m_touchEventTargets.get())
5340 if (!m_touchEventTargets->contains(handler))
5342 m_touchEventTargets->removeAll(handler);
5344 if (!m_touchEventTargets->remove(handler))
5345 // Just decremented refcount, no real update.
5349 if (m_touchEventTargets->isEmpty()) {
5350 if (Document* parent = parentDocument()) {
5351 // This was the last handler in this document, update the parent document too.
5352 parent->didRemoveTouchEventHandler(this, clearAll);
5354 // We just removed the last touch handler on the whole page.
5355 if (FrameHost* frameHost = this->frameHost())
5356 frameHost->chrome().client().needTouchEvents(false);
5360 // When we're all done with all frames, ensure touch hit rects are marked as dirty.
5361 if (!handler->isDocumentNode() || handler == this) {
5362 if (Page* page = this->page()) {
5363 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
5364 scrollingCoordinator->touchEventTargetRectsDidChange();
5369 DocumentLoader* Document::loader() const
5374 DocumentLoader* loader = m_frame->loader().documentLoader();
5378 if (m_frame->document() != this)
5384 IntSize Document::initialViewportSize() const
5388 return view()->unscaledVisibleContentSize(IncludeScrollbars);
5391 Node* eventTargetNodeForDocument(Document* doc)
5395 Node* node = doc->focusedElement();
5396 if (!node && doc->isPluginDocument()) {
5397 PluginDocument* pluginDocument = toPluginDocument(doc);
5398 node = pluginDocument->pluginNode();
5400 if (!node && doc->isHTMLDocument())
5403 node = doc->documentElement();
5407 void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject& renderer)
5412 LayoutRect visibleContentRect = view()->visibleContentRect();
5413 for (size_t i = 0; i < quads.size(); ++i) {
5414 quads[i].move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
5415 adjustFloatQuadForAbsoluteZoom(quads[i], renderer);
5419 void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject& renderer)
5424 LayoutRect visibleContentRect = view()->visibleContentRect();
5425 rect.move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
5426 adjustFloatRectForAbsoluteZoom(rect, renderer);
5429 bool Document::hasActiveParser()
5431 return m_activeParserCount || (m_parser && m_parser->processingData());
5434 void Document::decrementActiveParserCount()
5436 --m_activeParserCount;
5439 // FIXME: This should always be enabled, but it seems to cause
5440 // http/tests/security/feed-urls-from-remote.html to timeout on Mac WK1
5441 // see http://webkit.org/b/110554 and http://webkit.org/b/110401
5442 frame()->loader().checkLoadComplete();
5445 void Document::setContextFeatures(ContextFeatures& features)
5447 m_contextFeatures = PassRefPtrWillBeRawPtr<ContextFeatures>(features);
5450 static RenderObject* nearestCommonHoverAncestor(RenderObject* obj1, RenderObject* obj2)
5455 for (RenderObject* currObj1 = obj1; currObj1; currObj1 = currObj1->hoverAncestor()) {
5456 for (RenderObject* currObj2 = obj2; currObj2; currObj2 = currObj2->hoverAncestor()) {
5457 if (currObj1 == currObj2)
5465 void Document::updateHoverActiveState(const HitTestRequest& request, Element* innerElement, const PlatformMouseEvent* event)
5467 ASSERT(!request.readOnly());
5469 if (request.active() && m_frame)
5470 m_frame->eventHandler().notifyElementActivated();
5472 Element* innerElementInDocument = innerElement;
5473 while (innerElementInDocument && innerElementInDocument->document() != this) {
5474 innerElementInDocument->document().updateHoverActiveState(request, innerElementInDocument, event);
5475 innerElementInDocument = innerElementInDocument->document().ownerElement();
5478 Element* oldActiveElement = activeHoverElement();
5479 if (oldActiveElement && !request.active()) {
5480 // We are clearing the :active chain because the mouse has been released.
5481 for (RenderObject* curr = oldActiveElement->renderer(); curr; curr = curr->parent()) {
5483 ASSERT(!curr->node()->isTextNode());
5484 curr->node()->setActive(false);
5485 m_userActionElements.setInActiveChain(curr->node(), false);
5488 setActiveHoverElement(nullptr);
5490 Element* newActiveElement = innerElementInDocument;
5491 if (!oldActiveElement && newActiveElement && !newActiveElement->isDisabledFormControl() && request.active() && !request.touchMove()) {
5492 // We are setting the :active chain and freezing it. If future moves happen, they
5493 // will need to reference this chain.
5494 for (RenderObject* curr = newActiveElement->renderer(); curr; curr = curr->parent()) {
5495 if (curr->node() && !curr->isText())
5496 m_userActionElements.setInActiveChain(curr->node(), true);
5499 setActiveHoverElement(newActiveElement);
5502 // If the mouse has just been pressed, set :active on the chain. Those (and only those)
5503 // nodes should remain :active until the mouse is released.
5504 bool allowActiveChanges = !oldActiveElement && activeHoverElement();
5506 // If the mouse is down and if this is a mouse move event, we want to restrict changes in
5507 // :hover/:active to only apply to elements that are in the :active chain that we froze
5508 // at the time the mouse went down.
5509 bool mustBeInActiveChain = request.active() && request.move();
5511 RefPtrWillBeRawPtr<Node> oldHoverNode = hoverNode();
5513 // Check to see if the hovered node has changed.
5514 // If it hasn't, we do not need to do anything.
5515 Node* newHoverNode = innerElementInDocument;
5516 while (newHoverNode && !newHoverNode->renderer())
5517 newHoverNode = newHoverNode->parentOrShadowHostNode();
5519 // Update our current hover node.
5520 setHoverNode(newHoverNode);
5522 // We have two different objects. Fetch their renderers.
5523 RenderObject* oldHoverObj = oldHoverNode ? oldHoverNode->renderer() : 0;
5524 RenderObject* newHoverObj = newHoverNode ? newHoverNode->renderer() : 0;
5526 // Locate the common ancestor render object for the two renderers.
5527 RenderObject* ancestor = nearestCommonHoverAncestor(oldHoverObj, newHoverObj);
5528 RefPtrWillBeRawPtr<Node> ancestorNode(ancestor ? ancestor->node() : 0);
5530 WillBeHeapVector<RefPtrWillBeMember<Node>, 32> nodesToRemoveFromChain;
5531 WillBeHeapVector<RefPtrWillBeMember<Node>, 32> nodesToAddToChain;
5533 if (oldHoverObj != newHoverObj) {
5534 // If the old hovered node is not nil but it's renderer is, it was probably detached as part of the :hover style
5535 // (for instance by setting display:none in the :hover pseudo-class). In this case, the old hovered element (and its ancestors)
5536 // must be updated, to ensure it's normal style is re-applied.
5537 if (oldHoverNode && !oldHoverObj) {
5538 for (Node* node = oldHoverNode.get(); node; node = node->parentNode()) {
5539 if (!mustBeInActiveChain || (node->isElementNode() && toElement(node)->inActiveChain()))
5540 nodesToRemoveFromChain.append(node);
5545 // The old hover path only needs to be cleared up to (and not including) the common ancestor;
5546 for (RenderObject* curr = oldHoverObj; curr && curr != ancestor; curr = curr->hoverAncestor()) {
5547 if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5548 nodesToRemoveFromChain.append(curr->node());
5552 // Now set the hover state for our new object up to the root.
5553 for (RenderObject* curr = newHoverObj; curr; curr = curr->hoverAncestor()) {
5554 if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5555 nodesToAddToChain.append(curr->node());
5558 // mouseenter and mouseleave events do not bubble, so they are dispatched iff there is a capturing
5559 // event handler on an ancestor or a normal event handler on the element itself. This special
5560 // handling is necessary to avoid O(n^2) capturing event handler checks. We'll check the previously
5561 // hovered node's ancestor tree for 'mouseleave' handlers here, then check the newly hovered node's
5562 // ancestor tree for 'mouseenter' handlers after dispatching the 'mouseleave' events (as the handler
5563 // for 'mouseleave' might set a capturing 'mouseenter' handler, odd as that might be).
5564 bool ancestorHasCapturingMouseleaveListener = false;
5565 if (event && newHoverNode != oldHoverNode.get()) {
5566 for (Node* node = oldHoverNode.get(); node; node = node->parentOrShadowHostNode()) {
5567 if (node->hasCapturingEventListeners(EventTypeNames::mouseleave)) {
5568 ancestorHasCapturingMouseleaveListener = true;
5574 size_t removeCount = nodesToRemoveFromChain.size();
5575 for (size_t i = 0; i < removeCount; ++i) {
5576 nodesToRemoveFromChain[i]->setHovered(false);
5577 if (event && (ancestorHasCapturingMouseleaveListener || nodesToRemoveFromChain[i]->hasEventListeners(EventTypeNames::mouseleave)))
5578 nodesToRemoveFromChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseleave, 0, newHoverNode);
5581 bool ancestorHasCapturingMouseenterListener = false;
5582 if (event && newHoverNode != oldHoverNode.get()) {
5583 for (Node* node = newHoverNode; node; node = node->parentOrShadowHostNode()) {
5584 if (node->hasCapturingEventListeners(EventTypeNames::mouseenter)) {
5585 ancestorHasCapturingMouseenterListener = true;
5591 bool sawCommonAncestor = false;
5592 size_t addCount = nodesToAddToChain.size();
5593 for (size_t i = 0; i < addCount; ++i) {
5594 // Elements past the common ancestor do not change hover state, but might change active state.
5595 if (ancestorNode && nodesToAddToChain[i] == ancestorNode)
5596 sawCommonAncestor = true;
5597 if (allowActiveChanges)
5598 nodesToAddToChain[i]->setActive(true);
5599 if (!sawCommonAncestor) {
5600 nodesToAddToChain[i]->setHovered(true);
5601 if (event && (ancestorHasCapturingMouseenterListener || nodesToAddToChain[i]->hasEventListeners(EventTypeNames::mouseenter)))
5602 nodesToAddToChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseenter, 0, oldHoverNode.get());
5607 bool Document::haveStylesheetsLoaded() const
5609 return m_styleEngine->haveStylesheetsLoaded();
5612 Locale& Document::getCachedLocale(const AtomicString& locale)
5614 AtomicString localeKey = locale;
5615 if (locale.isEmpty() || !RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
5616 return Locale::defaultLocale();
5617 LocaleIdentifierToLocaleMap::AddResult result = m_localeCache.add(localeKey, nullptr);
5618 if (result.isNewEntry)
5619 result.storedValue->value = Locale::create(localeKey);
5620 return *(result.storedValue->value);
5623 Document& Document::ensureTemplateDocument()
5625 if (isTemplateDocument())
5628 if (m_templateDocument)
5629 return *m_templateDocument;
5631 if (isHTMLDocument()) {
5632 DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL()).withNewRegistrationContext();
5633 m_templateDocument = HTMLDocument::create(init);
5635 m_templateDocument = Document::create(DocumentInit(blankURL()));
5638 m_templateDocument->m_templateDocumentHost = this; // balanced in dtor.
5640 return *m_templateDocument.get();
5643 void Document::didAssociateFormControl(Element* element)
5645 if (!frame() || !frame()->page())
5647 m_associatedFormControls.add(element);
5648 if (!m_didAssociateFormControlsTimer.isActive())
5649 m_didAssociateFormControlsTimer.startOneShot(0, FROM_HERE);
5652 void Document::didAssociateFormControlsTimerFired(Timer<Document>* timer)
5654 ASSERT_UNUSED(timer, timer == &m_didAssociateFormControlsTimer);
5655 if (!frame() || !frame()->page())
5658 WillBeHeapVector<RefPtrWillBeMember<Element> > associatedFormControls;
5659 copyToVector(m_associatedFormControls, associatedFormControls);
5661 frame()->page()->chrome().client().didAssociateFormControls(associatedFormControls);
5662 m_associatedFormControls.clear();
5665 float Document::devicePixelRatio() const
5667 return m_frame ? m_frame->devicePixelRatio() : 1.0;
5670 PassOwnPtr<LifecycleNotifier<Document> > Document::createLifecycleNotifier()
5672 return DocumentLifecycleNotifier::create(this);
5675 DocumentLifecycleNotifier& Document::lifecycleNotifier()
5677 return static_cast<DocumentLifecycleNotifier&>(LifecycleContext<Document>::lifecycleNotifier());
5680 void Document::removedStyleSheet(StyleSheet* sheet, StyleResolverUpdateMode updateMode)
5682 // If we're in document teardown, then we don't need this notification of our sheet's removal.
5683 // styleResolverChanged() is needed even when the document is inactive so that
5684 // imported docuements (which is inactive) notifies the change to the master document.
5686 styleEngine()->modifiedStyleSheet(sheet);
5687 styleResolverChanged(updateMode);
5690 void Document::modifiedStyleSheet(StyleSheet* sheet, StyleResolverUpdateMode updateMode)
5692 // If we're in document teardown, then we don't need this notification of our sheet's removal.
5693 // styleResolverChanged() is needed even when the document is inactive so that
5694 // imported docuements (which is inactive) notifies the change to the master document.
5696 styleEngine()->modifiedStyleSheet(sheet);
5697 styleResolverChanged(updateMode);
5700 TextAutosizer* Document::textAutosizer()
5702 if (!m_textAutosizer && !RuntimeEnabledFeatures::fastTextAutosizingEnabled())
5703 m_textAutosizer = TextAutosizer::create(this);
5704 return m_textAutosizer.get();
5707 FastTextAutosizer* Document::fastTextAutosizer()
5709 if (!m_fastTextAutosizer && RuntimeEnabledFeatures::fastTextAutosizingEnabled())
5710 m_fastTextAutosizer = FastTextAutosizer::create(this);
5711 return m_fastTextAutosizer.get();
5714 void Document::setAutofocusElement(Element* element)
5717 m_autofocusElement = nullptr;
5720 if (m_hasAutofocused)
5722 m_hasAutofocused = true;
5723 ASSERT(!m_autofocusElement);
5724 m_autofocusElement = element;
5725 m_taskRunner->postTask(AutofocusTask::create());
5728 Element* Document::activeElement() const
5730 if (Element* element = treeScope().adjustedFocusedElement())
5735 bool Document::hasFocus() const
5737 Page* page = this->page();
5740 if (!page->focusController().isActive() || !page->focusController().isFocused())
5742 Frame* focusedFrame = page->focusController().focusedFrame();
5743 if (focusedFrame && focusedFrame->isLocalFrame()) {
5744 if (toLocalFrame(focusedFrame)->tree().isDescendantOf(frame()))
5751 template<unsigned type>
5752 bool shouldInvalidateNodeListCachesForAttr(const HeapHashSet<WeakMember<const LiveNodeListBase> > nodeLists[], const QualifiedName& attrName)
5754 if (!nodeLists[type].isEmpty() && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
5756 return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeLists, attrName);
5760 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const HeapHashSet<WeakMember<const LiveNodeListBase> >[], const QualifiedName&)
5765 template<unsigned type>
5766 bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
5768 if (nodeListCounts[type] && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
5770 return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
5774 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
5780 bool Document::shouldInvalidateNodeListCaches(const QualifiedName* attrName) const
5784 return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeLists, *attrName);
5786 return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListCounts, *attrName);
5790 for (int type = 0; type < numNodeListInvalidationTypes; ++type) {
5792 if (!m_nodeLists[type].isEmpty())
5794 if (m_nodeListCounts[type])
5802 void Document::invalidateNodeListCaches(const QualifiedName* attrName)
5804 WillBeHeapHashSet<RawPtrWillBeWeakMember<const LiveNodeListBase> >::const_iterator end = m_listsInvalidatedAtDocument.end();
5805 for (WillBeHeapHashSet<RawPtrWillBeWeakMember<const LiveNodeListBase> >::const_iterator it = m_listsInvalidatedAtDocument.begin(); it != end; ++it)
5806 (*it)->invalidateCacheForAttribute(attrName);
5809 void Document::clearWeakMembers(Visitor* visitor)
5811 if (m_axObjectCache)
5812 m_axObjectCache->clearWeakMembers(visitor);
5814 // FIXME: Oilpan: Use a weak counted set instead.
5815 if (m_touchEventTargets) {
5816 Vector<Node*> deadNodes;
5817 for (TouchEventTargetSet::iterator it = m_touchEventTargets->begin(); it != m_touchEventTargets->end(); ++it) {
5818 if (!visitor->isAlive(it->key))
5819 deadNodes.append(it->key);
5821 for (unsigned i = 0; i < deadNodes.size(); ++i)
5822 didClearTouchEventHandlers(deadNodes[i]);
5826 void Document::trace(Visitor* visitor)
5828 visitor->trace(m_importsController);
5829 visitor->trace(m_docType);
5830 visitor->trace(m_implementation);
5831 visitor->trace(m_autofocusElement);
5832 visitor->trace(m_focusedElement);
5833 visitor->trace(m_hoverNode);
5834 visitor->trace(m_activeHoverElement);
5835 visitor->trace(m_documentElement);
5836 visitor->trace(m_titleElement);
5837 visitor->trace(m_markers);
5838 visitor->trace(m_cssTarget);
5839 visitor->trace(m_currentScriptStack);
5840 visitor->trace(m_scriptRunner);
5841 visitor->trace(m_transformSourceDocument);
5842 visitor->trace(m_listsInvalidatedAtDocument);
5844 for (int i = 0; i < numNodeListInvalidationTypes; ++i)
5845 visitor->trace(m_nodeLists[i]);
5847 visitor->trace(m_cssCanvasElements);
5848 visitor->trace(m_topLayerElements);
5849 visitor->trace(m_elemSheet);
5850 visitor->trace(m_nodeIterators);
5851 visitor->trace(m_ranges);
5852 visitor->trace(m_styleEngine);
5853 visitor->trace(m_formController);
5854 visitor->trace(m_domWindow);
5855 visitor->trace(m_fetcher);
5856 visitor->trace(m_parser);
5857 visitor->trace(m_contextFeatures);
5858 visitor->trace(m_styleSheetList);
5859 visitor->trace(m_mediaQueryMatcher);
5860 visitor->trace(m_scriptedAnimationController);
5861 visitor->trace(m_registrationContext);
5862 visitor->trace(m_associatedFormControls);
5863 visitor->trace(m_useElementsNeedingUpdate);
5864 visitor->trace(m_layerUpdateSVGFilterElements);
5865 visitor->trace(m_templateDocument);
5866 visitor->trace(m_templateDocumentHost);
5867 visitor->trace(m_visibilityObservers);
5868 visitor->trace(m_userActionElements);
5869 visitor->trace(m_svgExtensions);
5870 visitor->trace(m_timeline);
5871 visitor->trace(m_compositorPendingAnimations);
5872 visitor->trace(m_contextDocument);
5873 visitor->registerWeakMembers<Document, &Document::clearWeakMembers>(this);
5874 DocumentSupplementable::trace(visitor);
5875 TreeScope::trace(visitor);
5876 ContainerNode::trace(visitor);
5877 ExecutionContext::trace(visitor);
5880 } // namespace WebCore