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/core/v8/CustomElementConstructorBuilder.h"
32 #include "bindings/core/v8/DOMDataStore.h"
33 #include "bindings/core/v8/Dictionary.h"
34 #include "bindings/core/v8/ExceptionMessages.h"
35 #include "bindings/core/v8/ExceptionState.h"
36 #include "bindings/core/v8/ExceptionStatePlaceholder.h"
37 #include "bindings/core/v8/ScriptController.h"
38 #include "bindings/core/v8/V8DOMWrapper.h"
39 #include "bindings/core/v8/WindowProxy.h"
40 #include "core/HTMLElementFactory.h"
41 #include "core/HTMLNames.h"
42 #include "core/SVGElementFactory.h"
43 #include "core/SVGNames.h"
44 #include "core/XMLNSNames.h"
45 #include "core/XMLNames.h"
46 #include "core/accessibility/AXObjectCache.h"
47 #include "core/animation/AnimationTimeline.h"
48 #include "core/animation/DocumentAnimations.h"
49 #include "core/css/CSSFontSelector.h"
50 #include "core/css/CSSStyleDeclaration.h"
51 #include "core/css/CSSStyleSheet.h"
52 #include "core/css/MediaQueryMatcher.h"
53 #include "core/css/StylePropertySet.h"
54 #include "core/css/StyleSheetContents.h"
55 #include "core/css/StyleSheetList.h"
56 #include "core/css/invalidation/StyleInvalidator.h"
57 #include "core/css/parser/CSSParser.h"
58 #include "core/css/resolver/FontBuilder.h"
59 #include "core/css/resolver/StyleResolver.h"
60 #include "core/css/resolver/StyleResolverStats.h"
61 #include "core/dom/AddConsoleMessageTask.h"
62 #include "core/dom/Attr.h"
63 #include "core/dom/CDATASection.h"
64 #include "core/dom/Comment.h"
65 #include "core/dom/ContextFeatures.h"
66 #include "core/dom/DOMImplementation.h"
67 #include "core/dom/DocumentFragment.h"
68 #include "core/dom/DocumentLifecycleNotifier.h"
69 #include "core/dom/DocumentLifecycleObserver.h"
70 #include "core/dom/DocumentMarkerController.h"
71 #include "core/dom/DocumentType.h"
72 #include "core/dom/Element.h"
73 #include "core/dom/ElementDataCache.h"
74 #include "core/dom/ElementTraversal.h"
75 #include "core/dom/ExceptionCode.h"
76 #include "core/dom/ExecutionContextTask.h"
77 #include "core/dom/MainThreadTaskRunner.h"
78 #include "core/dom/MutationObserver.h"
79 #include "core/dom/NodeChildRemovalTracker.h"
80 #include "core/dom/NodeFilter.h"
81 #include "core/dom/NodeIterator.h"
82 #include "core/dom/NodeRareData.h"
83 #include "core/dom/NodeRenderStyle.h"
84 #include "core/dom/NodeRenderingTraversal.h"
85 #include "core/dom/NodeTraversal.h"
86 #include "core/dom/NodeWithIndex.h"
87 #include "core/dom/ProcessingInstruction.h"
88 #include "core/dom/RequestAnimationFrameCallback.h"
89 #include "core/dom/ScriptRunner.h"
90 #include "core/dom/ScriptedAnimationController.h"
91 #include "core/dom/SelectorQuery.h"
92 #include "core/dom/StaticNodeList.h"
93 #include "core/dom/StyleEngine.h"
94 #include "core/dom/TouchList.h"
95 #include "core/dom/TransformSource.h"
96 #include "core/dom/TreeWalker.h"
97 #include "core/dom/VisitedLinkState.h"
98 #include "core/dom/XMLDocument.h"
99 #include "core/dom/custom/CustomElementMicrotaskRunQueue.h"
100 #include "core/dom/custom/CustomElementRegistrationContext.h"
101 #include "core/dom/shadow/ElementShadow.h"
102 #include "core/dom/shadow/ShadowRoot.h"
103 #include "core/editing/Editor.h"
104 #include "core/editing/FrameSelection.h"
105 #include "core/editing/SpellChecker.h"
106 #include "core/editing/markup.h"
107 #include "core/events/BeforeUnloadEvent.h"
108 #include "core/events/Event.h"
109 #include "core/events/EventFactory.h"
110 #include "core/events/EventListener.h"
111 #include "core/events/HashChangeEvent.h"
112 #include "core/events/PageTransitionEvent.h"
113 #include "core/events/ScopedEventQueue.h"
114 #include "core/fetch/ResourceFetcher.h"
115 #include "core/frame/EventHandlerRegistry.h"
116 #include "core/frame/FrameConsole.h"
117 #include "core/frame/FrameHost.h"
118 #include "core/frame/FrameView.h"
119 #include "core/frame/History.h"
120 #include "core/frame/LocalDOMWindow.h"
121 #include "core/frame/LocalFrame.h"
122 #include "core/frame/Settings.h"
123 #include "core/frame/csp/ContentSecurityPolicy.h"
124 #include "core/html/DocumentNameCollection.h"
125 #include "core/html/HTMLAllCollection.h"
126 #include "core/html/HTMLAnchorElement.h"
127 #include "core/html/HTMLBaseElement.h"
128 #include "core/html/HTMLCanvasElement.h"
129 #include "core/html/HTMLCollection.h"
130 #include "core/html/HTMLDialogElement.h"
131 #include "core/html/HTMLDocument.h"
132 #include "core/html/HTMLFrameOwnerElement.h"
133 #include "core/html/HTMLHeadElement.h"
134 #include "core/html/HTMLHtmlElement.h"
135 #include "core/html/HTMLIFrameElement.h"
136 #include "core/html/HTMLInputElement.h"
137 #include "core/html/HTMLLinkElement.h"
138 #include "core/html/HTMLMetaElement.h"
139 #include "core/html/HTMLScriptElement.h"
140 #include "core/html/HTMLStyleElement.h"
141 #include "core/html/HTMLTemplateElement.h"
142 #include "core/html/HTMLTitleElement.h"
143 #include "core/html/PluginDocument.h"
144 #include "core/html/WindowNameCollection.h"
145 #include "core/html/canvas/CanvasRenderingContext.h"
146 #include "core/html/canvas/CanvasRenderingContext2D.h"
147 #include "core/html/canvas/WebGLRenderingContext.h"
148 #include "core/html/forms/FormController.h"
149 #include "core/html/imports/HTMLImportLoader.h"
150 #include "core/html/imports/HTMLImportsController.h"
151 #include "core/html/parser/HTMLDocumentParser.h"
152 #include "core/html/parser/HTMLParserIdioms.h"
153 #include "core/html/parser/NestingLevelIncrementer.h"
154 #include "core/html/parser/TextResourceDecoder.h"
155 #include "core/inspector/ConsoleMessage.h"
156 #include "core/inspector/InspectorCounters.h"
157 #include "core/inspector/InspectorInstrumentation.h"
158 #include "core/inspector/InspectorTraceEvents.h"
159 #include "core/inspector/ScriptCallStack.h"
160 #include "core/loader/CookieJar.h"
161 #include "core/loader/DocumentLoader.h"
162 #include "core/loader/FrameLoader.h"
163 #include "core/loader/FrameLoaderClient.h"
164 #include "core/loader/ImageLoader.h"
165 #include "core/loader/appcache/ApplicationCacheHost.h"
166 #include "core/page/Chrome.h"
167 #include "core/page/ChromeClient.h"
168 #include "core/page/EventHandler.h"
169 #include "core/page/EventWithHitTestResults.h"
170 #include "core/page/FocusController.h"
171 #include "core/page/FrameTree.h"
172 #include "core/page/Page.h"
173 #include "core/page/PointerLockController.h"
174 #include "core/page/scrolling/ScrollingCoordinator.h"
175 #include "core/rendering/HitTestResult.h"
176 #include "core/rendering/RenderView.h"
177 #include "core/rendering/RenderWidget.h"
178 #include "core/rendering/TextAutosizer.h"
179 #include "core/rendering/compositing/RenderLayerCompositor.h"
180 #include "core/svg/SVGDocumentExtensions.h"
181 #include "core/svg/SVGFontFaceElement.h"
182 #include "core/svg/SVGTitleElement.h"
183 #include "core/svg/SVGUseElement.h"
184 #include "core/workers/SharedWorkerRepositoryClient.h"
185 #include "core/xml/XSLTProcessor.h"
186 #include "core/xml/parser/XMLDocumentParser.h"
187 #include "platform/DateComponents.h"
188 #include "platform/EventDispatchForbiddenScope.h"
189 #include "platform/Language.h"
190 #include "platform/Logging.h"
191 #include "platform/RuntimeEnabledFeatures.h"
192 #include "platform/ScriptForbiddenScope.h"
193 #include "platform/TraceEvent.h"
194 #include "platform/network/ContentSecurityPolicyParsers.h"
195 #include "platform/network/HTTPParsers.h"
196 #include "platform/scroll/ScrollbarTheme.h"
197 #include "platform/text/PlatformLocale.h"
198 #include "platform/text/SegmentedString.h"
199 #include "platform/weborigin/OriginAccessEntry.h"
200 #include "platform/weborigin/SchemeRegistry.h"
201 #include "platform/weborigin/SecurityOrigin.h"
202 #include "public/platform/Platform.h"
203 #include "wtf/CurrentTime.h"
204 #include "wtf/DateMath.h"
205 #include "wtf/HashFunctions.h"
206 #include "wtf/MainThread.h"
207 #include "wtf/StdLibExtras.h"
208 #include "wtf/TemporaryChange.h"
209 #include "wtf/text/StringBuffer.h"
210 #include "wtf/text/TextEncodingRegistry.h"
213 using namespace Unicode;
217 using namespace HTMLNames;
219 static const unsigned cMaxWriteRecursionDepth = 21;
221 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
222 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
224 static const int cLayoutScheduleThreshold = 250;
226 // DOM Level 2 says (letters added):
228 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
229 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
230 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
231 // 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.
232 // 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.
233 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
234 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
235 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
236 // i) Characters ':' and '_' are allowed as name-start characters.
237 // j) Characters '-' and '.' are allowed as name characters.
239 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
241 static inline bool isValidNameStart(UChar32 c)
244 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
248 if (c == ':' || c == '_')
251 // rules (a) and (f) above
252 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
253 if (!(Unicode::category(c) & nameStartMask))
257 if (c >= 0xF900 && c < 0xFFFE)
261 DecompositionType decompType = decompositionType(c);
262 if (decompType == DecompositionFont || decompType == DecompositionCompat)
268 static inline bool isValidNamePart(UChar32 c)
270 // rules (a), (e), and (i) above
271 if (isValidNameStart(c))
274 // rules (g) and (h) above
275 if (c == 0x00B7 || c == 0x0387)
279 if (c == '-' || c == '.')
282 // rules (b) and (f) above
283 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
284 if (!(Unicode::category(c) & otherNamePartMask))
288 if (c >= 0xF900 && c < 0xFFFE)
292 DecompositionType decompType = decompositionType(c);
293 if (decompType == DecompositionFont || decompType == DecompositionCompat)
299 static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
301 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
303 // If a Document has the address "about:blank"
304 // The origin of the Document is the origin it was assigned when its browsing context was created.
306 // Note: We generalize this to all "blank" URLs and invalid URLs because we
307 // treat all of these URLs as about:blank.
309 return url.isEmpty() || url.protocolIsAbout();
312 static Widget* widgetForElement(const Element& focusedElement)
314 RenderObject* renderer = focusedElement.renderer();
315 if (!renderer || !renderer->isWidget())
317 return toRenderWidget(renderer)->widget();
320 static bool acceptsEditingFocus(const Element& element)
322 ASSERT(element.hasEditableStyle());
324 return element.document().frame() && element.rootEditableElement();
327 static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, const Frame* targetFrame)
329 // targetFrame can be 0 when we're trying to navigate a top-level frame
330 // that has a 0 opener.
334 const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
335 for (const Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
336 // FIXME: SecurityOrigins need to be refactored to work with out-of-process iframes.
337 // For now we prevent navigation between cross-process frames.
338 if (!ancestorFrame->isLocalFrame())
341 Document* ancestorDocument = toLocalFrame(ancestorFrame)->document();
342 // FIXME: Should be an ASSERT? Frames should alway have documents.
343 if (!ancestorDocument)
346 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
347 if (activeSecurityOrigin.canAccess(ancestorSecurityOrigin))
350 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
351 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
352 // something more general instead?
353 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
360 static void printNavigationErrorMessage(const LocalFrame& frame, const KURL& activeURL, const char* reason)
362 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame.document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
364 // FIXME: should we print to the console of the document performing the navigation instead?
365 frame.domWindow()->printErrorMessage(message);
368 uint64_t Document::s_globalTreeVersion = 0;
371 typedef WillBeHeapHashSet<RawPtrWillBeWeakMember<Document> > WeakDocumentSet;
372 static WeakDocumentSet& liveDocumentSet()
374 DEFINE_STATIC_LOCAL(OwnPtrWillBePersistent<WeakDocumentSet>, set, (adoptPtrWillBeNoop(new WeakDocumentSet())));
379 // This class doesn't work with non-Document ExecutionContext.
380 class AutofocusTask FINAL : public ExecutionContextTask {
382 static PassOwnPtr<AutofocusTask> create()
384 return adoptPtr(new AutofocusTask());
386 virtual ~AutofocusTask() { }
390 virtual void performTask(ExecutionContext* context) OVERRIDE
392 Document* document = toDocument(context);
393 if (RefPtrWillBeRawPtr<Element> element = document->autofocusElement()) {
394 document->setAutofocusElement(0);
400 DocumentVisibilityObserver::DocumentVisibilityObserver(Document& document)
401 : m_document(nullptr)
403 registerObserver(document);
406 DocumentVisibilityObserver::~DocumentVisibilityObserver()
409 unregisterObserver();
413 void DocumentVisibilityObserver::trace(Visitor* visitor)
415 visitor->trace(m_document);
418 void DocumentVisibilityObserver::unregisterObserver()
421 m_document->unregisterVisibilityObserver(this);
422 m_document = nullptr;
426 void DocumentVisibilityObserver::registerObserver(Document& document)
429 m_document = &document;
431 m_document->registerVisibilityObserver(this);
434 void DocumentVisibilityObserver::setObservedDocument(Document& document)
436 unregisterObserver();
437 registerObserver(document);
440 Document::Document(const DocumentInit& initializer, DocumentClassFlags documentClasses)
441 : ContainerNode(0, CreateDocument)
443 , m_hasNodesWithPlaceholderStyle(false)
444 , m_evaluateMediaQueriesOnStyleRecalc(false)
445 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
446 , m_frame(initializer.frame())
447 , m_domWindow(m_frame ? m_frame->domWindow() : 0)
448 , m_importsController(initializer.importsController())
449 , m_activeParserCount(0)
450 , m_contextFeatures(ContextFeatures::defaultSwitch())
451 , m_wellFormed(false)
453 , m_paginatedForScreen(false)
454 , m_compatibilityMode(NoQuirksMode)
455 , m_compatibilityModeLocked(false)
456 , m_executeScriptsWaitingForResourcesTimer(this, &Document::executeScriptsWaitingForResourcesTimerFired)
457 , m_hasAutofocused(false)
458 , m_clearFocusedElementTimer(this, &Document::clearFocusedElementTimerFired)
459 , m_domTreeVersion(++s_globalTreeVersion)
461 , m_mutationObserverTypes(0)
462 , m_visitedLinkState(VisitedLinkState::create(*this))
463 , m_visuallyOrdered(false)
464 , m_readyState(Complete)
466 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
467 , m_containsValidityStyleRules(false)
468 , m_updateFocusAppearanceRestoresSelection(false)
469 , m_containsPlugins(false)
470 , m_ignoreDestructiveWriteCount(0)
471 , m_markers(adoptPtrWillBeNoop(new DocumentMarkerController))
472 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
473 , m_cssTarget(nullptr)
474 , m_loadEventProgress(LoadEventNotRun)
475 , m_startTime(currentTime())
476 , m_scriptRunner(ScriptRunner::create(this))
477 , m_xmlVersion("1.0")
478 , m_xmlStandalone(StandaloneUnspecified)
479 , m_hasXMLDeclaration(0)
480 , m_designMode(inherit)
481 , m_hasAnnotatedRegions(false)
482 , m_annotatedRegionsDirty(false)
483 , m_useSecureKeyboardEntryWhenActive(false)
484 , m_documentClasses(documentClasses)
485 , m_isViewSource(false)
486 , m_sawElementsInKnownNamespaces(false)
487 , m_isSrcdocDocument(false)
488 , m_isMobileDocument(false)
489 , m_isTransitionDocument(false)
492 , m_weakFactory(this)
494 , m_contextDocument(initializer.contextDocument())
495 , m_hasFullscreenSupplement(false)
496 , m_loadEventDelayCount(0)
497 , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
498 , m_pluginLoadingTimer(this, &Document::pluginLoadingTimerFired)
499 , m_didSetReferrerPolicy(false)
500 , m_referrerPolicy(ReferrerPolicyDefault)
501 , m_directionSetOnDocumentElement(false)
502 , m_writingModeSetOnDocumentElement(false)
503 , m_writeRecursionIsTooDeep(false)
504 , m_writeRecursionDepth(0)
505 , m_taskRunner(MainThreadTaskRunner::create(this))
506 , m_registrationContext(initializer.registrationContext(this))
507 , m_elementDataCacheClearTimer(this, &Document::elementDataCacheClearTimerFired)
508 , m_timeline(AnimationTimeline::create(this))
509 , m_templateDocumentHost(nullptr)
510 , m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
511 , m_hasViewportUnits(false)
512 , m_styleRecalcElementCounter(0)
515 ASSERT(m_frame->page());
516 provideContextFeaturesToDocumentFrom(*this, *m_frame->page());
518 m_fetcher = m_frame->loader().documentLoader()->fetcher();
522 m_fetcher = ResourceFetcher::create(0);
523 m_fetcher->setDocument(this);
525 // We depend on the url getting immediately set in subframes, but we
526 // also depend on the url NOT getting immediately set in opened windows.
527 // See fast/dom/early-frame-url.html
528 // and fast/dom/location-new-window-no-crash.html, respectively.
529 // FIXME: Can/should we unify this behavior?
530 if (initializer.shouldSetURL())
531 setURL(initializer.url());
533 initSecurityContext(initializer);
537 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); ++i)
538 m_nodeListCounts[i] = 0;
541 InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
543 m_lifecycle.advanceTo(DocumentLifecycle::Inactive);
545 // Since CSSFontSelector requires Document::m_fetcher and StyleEngine owns
546 // CSSFontSelector, need to initialize m_styleEngine after initializing
548 m_styleEngine = StyleEngine::create(*this);
551 liveDocumentSet().add(this);
555 Document::~Document()
557 ASSERT(!renderView());
558 ASSERT(!parentTreeScope());
560 ASSERT(m_ranges.isEmpty());
561 ASSERT(!hasGuardRefCount());
562 // With Oilpan, either the document outlives the visibility observers
563 // or the visibility observers and the document die in the same GC round.
564 // When they die in the same GC round, the list of visibility observers
565 // will not be empty on Document destruction.
566 ASSERT(m_visibilityObservers.isEmpty());
568 if (m_templateDocument)
569 m_templateDocument->m_templateDocumentHost = nullptr; // balanced in ensureTemplateDocument().
571 m_scriptRunner.clear();
573 // FIXME: Oilpan: Not removing event listeners here also means that we do
574 // not notify the inspector instrumentation that the event listeners are
575 // gone. The Document and all the nodes in the document are gone, so maybe
577 removeAllEventListenersRecursively();
579 // Currently we believe that Document can never outlive the parser.
580 // Although the Document may be replaced synchronously, DocumentParsers
581 // generally keep at least one reference to an Element which would in turn
582 // has a reference to the Document. If you hit this ASSERT, then that
583 // assumption is wrong. DocumentParser::detach() should ensure that even
584 // if the DocumentParser outlives the Document it won't cause badness.
585 ASSERT(!m_parser || m_parser->refCount() == 1);
589 if (this == &axObjectCacheOwner())
590 clearAXObjectCache();
593 if (m_styleSheetList)
594 m_styleSheetList->detachFromDocument();
596 if (m_importsController)
597 HTMLImportsController::removeFrom(*this);
599 m_timeline->detachFromDocument();
601 // We need to destroy CSSFontSelector before destroying m_fetcher.
603 m_styleEngine->detachFromDocument();
606 m_elemSheet->clearOwnerNode();
608 // It's possible for multiple Documents to end up referencing the same ResourceFetcher (e.g., SVGImages
609 // load the initial empty document and the SVGDocument with the same DocumentLoader).
610 if (m_fetcher->document() == this)
611 m_fetcher->setDocument(nullptr);
614 // We must call clearRareData() here since a Document class inherits TreeScope
615 // as well as Node. See a comment on TreeScope.h for the reason.
619 ASSERT(m_listsInvalidatedAtDocument.isEmpty());
621 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); ++i)
622 ASSERT(!m_nodeListCounts[i]);
625 liveDocumentSet().remove(this);
629 InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
633 void Document::dispose()
635 ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
637 // We must make sure not to be retaining any of our children through
638 // these extra pointers or we will create a reference cycle.
640 m_focusedElement = nullptr;
641 m_hoverNode = nullptr;
642 m_activeHoverElement = nullptr;
643 m_titleElement = nullptr;
644 m_documentElement = nullptr;
645 m_contextFeatures = ContextFeatures::defaultSwitch();
646 m_userActionElements.documentDidRemoveLastRef();
647 m_associatedFormControls.clear();
651 m_registrationContext.clear();
653 if (m_importsController)
654 HTMLImportsController::removeFrom(*this);
656 // removeDetachedChildren() doesn't always unregister IDs,
657 // so tear down scope information upfront to avoid having stale references in the map.
658 destroyTreeScopeData();
660 removeDetachedChildren();
662 // removeDetachedChildren() can access FormController.
663 m_formController.clear();
667 m_cssCanvasElements.clear();
669 // FIXME: consider using ActiveDOMObject.
670 if (m_scriptedAnimationController)
671 m_scriptedAnimationController->clearDocumentPointer();
672 m_scriptedAnimationController.clear();
675 accessSVGExtensions().pauseAnimations();
677 m_lifecycle.advanceTo(DocumentLifecycle::Disposed);
678 lifecycleNotifier().notifyDocumentWasDisposed();
682 SelectorQueryCache& Document::selectorQueryCache()
684 if (!m_selectorQueryCache)
685 m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
686 return *m_selectorQueryCache;
689 MediaQueryMatcher& Document::mediaQueryMatcher()
691 if (!m_mediaQueryMatcher)
692 m_mediaQueryMatcher = MediaQueryMatcher::create(*this);
693 return *m_mediaQueryMatcher;
696 void Document::mediaQueryAffectingValueChanged()
698 m_evaluateMediaQueriesOnStyleRecalc = true;
699 styleEngine()->clearMediaQueryRuleSetStyleSheets();
702 void Document::setCompatibilityMode(CompatibilityMode mode)
704 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
706 bool wasInQuirksMode = inQuirksMode();
707 m_compatibilityMode = mode;
708 selectorQueryCache().invalidate();
709 if (inQuirksMode() != wasInQuirksMode) {
710 // All injected stylesheets have to reparse using the different mode.
711 m_styleEngine->compatibilityModeChanged();
715 String Document::compatMode() const
717 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
720 void Document::setDoctype(PassRefPtrWillBeRawPtr<DocumentType> docType)
722 // This should never be called more than once.
723 ASSERT(!m_docType || !docType);
726 this->adoptIfNeeded(*m_docType);
727 if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
728 m_isMobileDocument = true;
730 // Doctype affects the interpretation of the stylesheets.
731 clearStyleResolver();
734 DOMImplementation& Document::implementation()
736 if (!m_implementation)
737 m_implementation = DOMImplementation::create(*this);
738 return *m_implementation;
741 bool Document::hasAppCacheManifest() const
743 return isHTMLHtmlElement(documentElement()) && documentElement()->hasAttribute(manifestAttr);
746 Location* Document::location() const
751 return &domWindow()->location();
754 void Document::childrenChanged(const ChildrenChange& change)
756 ContainerNode::childrenChanged(change);
757 m_documentElement = ElementTraversal::firstWithin(*this);
760 AtomicString Document::convertLocalName(const AtomicString& name)
762 return isHTMLDocument() ? name.lower() : name;
765 PassRefPtrWillBeRawPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& exceptionState)
767 if (!isValidName(name)) {
768 exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + name + "') is not a valid name.");
772 if (isXHTMLDocument() || isHTMLDocument())
773 return HTMLElementFactory::createHTMLElement(convertLocalName(name), *this, 0, false);
775 return Element::create(QualifiedName(nullAtom, name, nullAtom), this);
778 PassRefPtrWillBeRawPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& exceptionState)
780 if (!isValidName(localName)) {
781 exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + localName + "') is not a valid name.");
785 RefPtrWillBeRawPtr<Element> element;
787 if (CustomElement::isValidName(localName) && registrationContext()) {
788 element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, convertLocalName(localName), xhtmlNamespaceURI));
790 element = createElement(localName, exceptionState);
791 if (exceptionState.hadException())
795 if (!typeExtension.isEmpty())
796 CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
798 return element.release();
801 static inline QualifiedName createQualifiedName(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
803 AtomicString prefix, localName;
804 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
805 return QualifiedName::null();
807 QualifiedName qName(prefix, localName, namespaceURI);
808 if (!Document::hasValidNamespaceForElements(qName)) {
809 exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
810 return QualifiedName::null();
816 PassRefPtrWillBeRawPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
818 QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
819 if (qName == QualifiedName::null())
822 return createElement(qName, false);
825 PassRefPtrWillBeRawPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
827 QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
828 if (qName == QualifiedName::null())
831 RefPtrWillBeRawPtr<Element> element;
832 if (CustomElement::isValidName(qName.localName()) && registrationContext())
833 element = registrationContext()->createCustomTagElement(*this, qName);
835 element = createElement(qName, false);
837 if (!typeExtension.isEmpty())
838 CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
840 return element.release();
843 ScriptValue Document::registerElement(ScriptState* scriptState, const AtomicString& name, ExceptionState& exceptionState)
845 return registerElement(scriptState, name, Dictionary(), exceptionState);
848 ScriptValue Document::registerElement(ScriptState* scriptState, const AtomicString& name, const Dictionary& options, ExceptionState& exceptionState, CustomElement::NameSet validNames)
850 if (!registrationContext()) {
851 exceptionState.throwDOMException(NotSupportedError, "No element registration context is available.");
852 return ScriptValue();
855 CustomElementConstructorBuilder constructorBuilder(scriptState, &options);
856 registrationContext()->registerElement(this, &constructorBuilder, name, validNames, exceptionState);
857 return constructorBuilder.bindingsReturnValue();
860 CustomElementMicrotaskRunQueue* Document::customElementMicrotaskRunQueue()
862 if (!m_customElementMicrotaskRunQueue)
863 m_customElementMicrotaskRunQueue = CustomElementMicrotaskRunQueue::create();
864 return m_customElementMicrotaskRunQueue.get();
867 void Document::setImportsController(HTMLImportsController* controller)
869 ASSERT(!m_importsController || !controller);
870 m_importsController = controller;
873 HTMLImportLoader* Document::importLoader() const
875 if (!m_importsController)
877 return m_importsController->loaderFor(*this);
880 bool Document::haveImportsLoaded() const
882 if (!m_importsController)
884 return !m_importsController->shouldBlockScriptExecution(*this);
887 LocalDOMWindow* Document::executingWindow()
889 if (LocalDOMWindow* owningWindow = domWindow())
891 if (HTMLImportsController* import = this->importsController())
892 return import->master()->domWindow();
896 LocalFrame* Document::executingFrame()
898 LocalDOMWindow* window = executingWindow();
901 return window->frame();
904 PassRefPtrWillBeRawPtr<DocumentFragment> Document::createDocumentFragment()
906 return DocumentFragment::create(*this);
909 PassRefPtrWillBeRawPtr<Text> Document::createTextNode(const String& data)
911 return Text::create(*this, data);
914 PassRefPtrWillBeRawPtr<Comment> Document::createComment(const String& data)
916 return Comment::create(*this, data);
919 PassRefPtrWillBeRawPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& exceptionState)
921 if (isHTMLDocument()) {
922 exceptionState.throwDOMException(NotSupportedError, "This operation is not supported for HTML documents.");
925 if (data.contains("]]>")) {
926 exceptionState.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
929 return CDATASection::create(*this, data);
932 PassRefPtrWillBeRawPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& exceptionState)
934 if (!isValidName(target)) {
935 exceptionState.throwDOMException(InvalidCharacterError, "The target provided ('" + target + "') is not a valid name.");
938 if (data.contains("?>")) {
939 exceptionState.throwDOMException(InvalidCharacterError, "The data provided ('" + data + "') contains '?>'.");
942 return ProcessingInstruction::create(*this, target, data);
945 PassRefPtrWillBeRawPtr<Text> Document::createEditingTextNode(const String& text)
947 return Text::createEditingText(*this, text);
950 bool Document::importContainerNodeChildren(ContainerNode* oldContainerNode, PassRefPtrWillBeRawPtr<ContainerNode> newContainerNode, ExceptionState& exceptionState)
952 for (Node* oldChild = oldContainerNode->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
953 RefPtrWillBeRawPtr<Node> newChild = importNode(oldChild, true, exceptionState);
954 if (exceptionState.hadException())
956 newContainerNode->appendChild(newChild.release(), exceptionState);
957 if (exceptionState.hadException())
964 PassRefPtrWillBeRawPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& exceptionState)
966 switch (importedNode->nodeType()) {
968 return createTextNode(importedNode->nodeValue());
969 case CDATA_SECTION_NODE:
970 return CDATASection::create(*this, importedNode->nodeValue());
971 case PROCESSING_INSTRUCTION_NODE:
972 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), exceptionState);
974 return createComment(importedNode->nodeValue());
975 case DOCUMENT_TYPE_NODE: {
976 DocumentType* doctype = toDocumentType(importedNode);
977 return DocumentType::create(this, doctype->name(), doctype->publicId(), doctype->systemId());
980 Element* oldElement = toElement(importedNode);
981 // FIXME: The following check might be unnecessary. Is it possible that
982 // oldElement has mismatched prefix/namespace?
983 if (!hasValidNamespaceForElements(oldElement->tagQName())) {
984 exceptionState.throwDOMException(NamespaceError, "The imported node has an invalid namespace.");
987 RefPtrWillBeRawPtr<Element> newElement = createElement(oldElement->tagQName(), false);
989 newElement->cloneDataFromElement(*oldElement);
992 if (!importContainerNodeChildren(oldElement, newElement, exceptionState))
994 if (isHTMLTemplateElement(*oldElement)
995 && !importContainerNodeChildren(toHTMLTemplateElement(oldElement)->content(), toHTMLTemplateElement(newElement)->content(), exceptionState))
999 return newElement.release();
1001 case ATTRIBUTE_NODE:
1002 return Attr::create(*this, QualifiedName(nullAtom, AtomicString(toAttr(importedNode)->name()), nullAtom), toAttr(importedNode)->value());
1003 case DOCUMENT_FRAGMENT_NODE: {
1004 if (importedNode->isShadowRoot()) {
1005 // ShadowRoot nodes should not be explicitly importable.
1006 // Either they are imported along with their host node, or created implicitly.
1007 exceptionState.throwDOMException(NotSupportedError, "The node provided is a shadow root, which may not be imported.");
1010 DocumentFragment* oldFragment = toDocumentFragment(importedNode);
1011 RefPtrWillBeRawPtr<DocumentFragment> newFragment = createDocumentFragment();
1012 if (deep && !importContainerNodeChildren(oldFragment, newFragment, exceptionState))
1015 return newFragment.release();
1018 exceptionState.throwDOMException(NotSupportedError, "The node provided is a document, which may not be imported.");
1022 ASSERT_NOT_REACHED();
1026 PassRefPtrWillBeRawPtr<Node> Document::adoptNode(PassRefPtrWillBeRawPtr<Node> source, ExceptionState& exceptionState)
1028 EventQueueScope scope;
1030 switch (source->nodeType()) {
1032 exceptionState.throwDOMException(NotSupportedError, "The node provided is of type '" + source->nodeName() + "', which may not be adopted.");
1034 case ATTRIBUTE_NODE: {
1035 Attr* attr = toAttr(source.get());
1036 if (RefPtrWillBeRawPtr<Element> ownerElement = attr->ownerElement())
1037 ownerElement->removeAttributeNode(attr, exceptionState);
1041 if (source->isShadowRoot()) {
1042 // ShadowRoot cannot disconnect itself from the host node.
1043 exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a shadow root, which may not be adopted.");
1047 if (source->isFrameOwnerElement()) {
1048 HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
1049 // FIXME(kenrb): the downcast can be removed when the FrameTree supports RemoteFrames.
1050 if (frame() && frame()->tree().isDescendantOf(toLocalFrameTemporary(frameOwnerElement->contentFrame()))) {
1051 exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a frame which contains this document.");
1055 if (source->parentNode()) {
1056 source->parentNode()->removeChild(source.get(), exceptionState);
1057 if (exceptionState.hadException())
1062 this->adoptIfNeeded(*source);
1067 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1069 // These checks are from DOM Core Level 2, createElementNS
1070 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1071 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1073 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1076 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1077 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1078 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1079 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1080 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1081 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1084 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1086 return hasValidNamespaceForElements(qName);
1089 // FIXME: This should really be in a possible ElementFactory class
1090 PassRefPtrWillBeRawPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
1092 RefPtrWillBeRawPtr<Element> e = nullptr;
1094 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1095 if (qName.namespaceURI() == xhtmlNamespaceURI)
1096 e = HTMLElementFactory::createHTMLElement(qName.localName(), *this, 0, createdByParser);
1097 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
1098 e = SVGElementFactory::createSVGElement(qName.localName(), *this, createdByParser);
1101 m_sawElementsInKnownNamespaces = true;
1103 e = Element::create(qName, this);
1105 if (e->prefix() != qName.prefix())
1106 e->setTagNameForCreateElementNS(qName);
1108 ASSERT(qName == e->tagQName());
1113 bool Document::regionBasedColumnsEnabled() const
1115 return settings() && settings()->regionBasedColumnsEnabled();
1118 String Document::readyState() const
1120 DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
1121 DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
1122 DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
1124 switch (m_readyState) {
1133 ASSERT_NOT_REACHED();
1137 void Document::setReadyState(ReadyState readyState)
1139 if (readyState == m_readyState)
1142 switch (readyState) {
1144 if (!m_documentTiming.domLoading) {
1145 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1149 if (!m_documentTiming.domInteractive)
1150 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1153 if (!m_documentTiming.domComplete)
1154 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1158 m_readyState = readyState;
1159 dispatchEvent(Event::create(EventTypeNames::readystatechange));
1162 bool Document::isLoadCompleted()
1164 return m_readyState == Complete;
1167 AtomicString Document::encodingName() const
1169 // TextEncoding::name() returns a char*, no need to allocate a new
1170 // String for it each time.
1171 // FIXME: We should fix TextEncoding to speak AtomicString anyway.
1172 return AtomicString(encoding().name());
1175 String Document::defaultCharset() const
1177 if (Settings* settings = this->settings())
1178 return settings->defaultTextEncodingName();
1182 void Document::setCharset(const String& charset)
1184 UseCounter::count(*this, UseCounter::DocumentSetCharset);
1185 if (DocumentLoader* documentLoader = loader())
1186 documentLoader->setUserChosenEncoding(charset);
1187 WTF::TextEncoding encoding(charset);
1188 // In case the encoding didn't exist, we keep the old one (helps some sites specifying invalid encodings).
1189 if (!encoding.isValid())
1191 DocumentEncodingData newEncodingData = m_encodingData;
1192 newEncodingData.setEncoding(encoding);
1193 setEncodingData(newEncodingData);
1196 void Document::setContentLanguage(const AtomicString& language)
1198 if (m_contentLanguage == language)
1200 m_contentLanguage = language;
1202 // Document's style depends on the content language.
1203 setNeedsStyleRecalc(SubtreeStyleChange);
1206 void Document::setXMLVersion(const String& version, ExceptionState& exceptionState)
1208 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1209 exceptionState.throwDOMException(NotSupportedError, "This document does not support the XML version '" + version + "'.");
1213 m_xmlVersion = version;
1216 void Document::setXMLStandalone(bool standalone, ExceptionState& exceptionState)
1218 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1221 KURL Document::baseURI() const
1226 void Document::setContent(const String& content)
1229 // FIXME: This should probably use insert(), but that's (intentionally)
1230 // not implemented for the XML parser as it's normally synonymous with
1231 // document.write(). append() will end up yielding, but close() will
1232 // pump the tokenizer syncrhonously and finish the parse.
1233 m_parser->pinToMainThread();
1234 m_parser->append(content.impl());
1238 String Document::suggestedMIMEType() const
1240 if (isXMLDocument()) {
1241 if (isXHTMLDocument())
1242 return "application/xhtml+xml";
1243 if (isSVGDocument())
1244 return "image/svg+xml";
1245 return "application/xml";
1247 if (xmlStandalone())
1249 if (isHTMLDocument())
1252 if (DocumentLoader* documentLoader = loader())
1253 return documentLoader->responseMIMEType();
1257 void Document::setMimeType(const AtomicString& mimeType)
1259 m_mimeType = mimeType;
1262 AtomicString Document::contentType() const
1264 if (!m_mimeType.isEmpty())
1267 if (DocumentLoader* documentLoader = loader())
1268 return documentLoader->mimeType();
1270 String mimeType = suggestedMIMEType();
1271 if (!mimeType.isEmpty())
1272 return AtomicString(mimeType);
1274 return AtomicString("application/xml");
1277 Element* Document::elementFromPoint(int x, int y) const
1282 return TreeScope::elementFromPoint(x, y);
1285 PassRefPtrWillBeRawPtr<Range> Document::caretRangeFromPoint(int x, int y)
1289 HitTestResult result = hitTestInDocument(this, x, y);
1290 RenderObject* renderer = result.renderer();
1294 Node* node = renderer->node();
1295 Node* shadowAncestorNode = ancestorInThisScope(node);
1296 if (shadowAncestorNode != node) {
1297 unsigned offset = shadowAncestorNode->nodeIndex();
1298 ContainerNode* container = shadowAncestorNode->parentNode();
1299 return Range::create(*this, container, offset, container, offset);
1302 PositionWithAffinity positionWithAffinity = result.position();
1303 if (positionWithAffinity.position().isNull())
1306 Position rangeCompliantPosition = positionWithAffinity.position().parentAnchoredEquivalent();
1307 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1311 * Performs three operations:
1312 * 1. Convert control characters to spaces
1313 * 2. Trim leading and trailing spaces
1314 * 3. Collapse internal whitespace.
1316 template <typename CharacterType>
1317 static inline String canonicalizedTitle(Document* document, const String& title)
1319 unsigned length = title.length();
1320 unsigned builderIndex = 0;
1321 const CharacterType* characters = title.getCharacters<CharacterType>();
1323 StringBuffer<CharacterType> buffer(length);
1325 // Replace control characters with spaces and collapse whitespace.
1326 bool pendingWhitespace = false;
1327 for (unsigned i = 0; i < length; ++i) {
1328 UChar32 c = characters[i];
1329 if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1330 if (builderIndex != 0)
1331 pendingWhitespace = true;
1333 if (pendingWhitespace) {
1334 buffer[builderIndex++] = ' ';
1335 pendingWhitespace = false;
1337 buffer[builderIndex++] = c;
1340 buffer.shrink(builderIndex);
1342 return String::adopt(buffer);
1345 void Document::updateTitle(const String& title)
1347 if (m_rawTitle == title)
1352 String oldTitle = m_title;
1353 if (m_rawTitle.isEmpty())
1355 else if (m_rawTitle.is8Bit())
1356 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1358 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1360 if (!m_frame || oldTitle == m_title)
1362 m_frame->loader().client()->dispatchDidReceiveTitle(m_title);
1365 void Document::setTitle(const String& title)
1367 // Title set by JavaScript -- overrides any title elements.
1368 if (!isHTMLDocument() && !isXHTMLDocument())
1369 m_titleElement = nullptr;
1370 else if (!m_titleElement) {
1371 HTMLElement* headElement = head();
1374 m_titleElement = HTMLTitleElement::create(*this);
1375 headElement->appendChild(m_titleElement.get());
1378 if (isHTMLTitleElement(m_titleElement))
1379 toHTMLTitleElement(m_titleElement)->setText(title);
1384 void Document::setTitleElement(Element* titleElement)
1386 // Only allow the first title element to change the title -- others have no effect.
1387 if (m_titleElement && m_titleElement != titleElement) {
1388 if (isHTMLDocument() || isXHTMLDocument()) {
1389 m_titleElement = Traversal<HTMLTitleElement>::firstWithin(*this);
1390 } else if (isSVGDocument()) {
1391 m_titleElement = Traversal<SVGTitleElement>::firstWithin(*this);
1394 m_titleElement = titleElement;
1397 if (isHTMLTitleElement(m_titleElement))
1398 updateTitle(toHTMLTitleElement(m_titleElement)->text());
1399 else if (isSVGTitleElement(m_titleElement))
1400 updateTitle(toSVGTitleElement(m_titleElement)->textContent());
1403 void Document::removeTitle(Element* titleElement)
1405 if (m_titleElement != titleElement)
1408 m_titleElement = nullptr;
1410 // Update title based on first title element in the document, if one exists.
1411 if (isHTMLDocument() || isXHTMLDocument()) {
1412 if (HTMLTitleElement* title = Traversal<HTMLTitleElement>::firstWithin(*this))
1413 setTitleElement(title);
1414 } else if (isSVGDocument()) {
1415 if (SVGTitleElement* title = Traversal<SVGTitleElement>::firstWithin(*this))
1416 setTitleElement(title);
1419 if (!m_titleElement)
1420 updateTitle(String());
1423 const AtomicString& Document::dir()
1425 Element* rootElement = documentElement();
1426 if (isHTMLHtmlElement(rootElement))
1427 return toHTMLHtmlElement(rootElement)->dir();
1431 void Document::setDir(const AtomicString& value)
1433 Element* rootElement = documentElement();
1434 if (isHTMLHtmlElement(rootElement))
1435 toHTMLHtmlElement(rootElement)->setDir(value);
1438 PageVisibilityState Document::pageVisibilityState() const
1440 // The visibility of the document is inherited from the visibility of the
1441 // page. If there is no page associated with the document, we will assume
1442 // that the page is hidden, as specified by the spec:
1443 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1444 if (!m_frame || !m_frame->page())
1445 return PageVisibilityStateHidden;
1446 return m_frame->page()->visibilityState();
1449 String Document::visibilityState() const
1451 return pageVisibilityStateString(pageVisibilityState());
1454 bool Document::hidden() const
1456 return pageVisibilityState() != PageVisibilityStateVisible;
1459 void Document::didChangeVisibilityState()
1461 dispatchEvent(Event::create(EventTypeNames::visibilitychange));
1462 // Also send out the deprecated version until it can be removed.
1463 dispatchEvent(Event::create(EventTypeNames::webkitvisibilitychange));
1465 PageVisibilityState state = pageVisibilityState();
1466 DocumentVisibilityObserverSet::const_iterator observerEnd = m_visibilityObservers.end();
1467 for (DocumentVisibilityObserverSet::const_iterator it = m_visibilityObservers.begin(); it != observerEnd; ++it)
1468 (*it)->didChangeVisibilityState(state);
1471 void Document::registerVisibilityObserver(DocumentVisibilityObserver* observer)
1473 ASSERT(!m_visibilityObservers.contains(observer));
1474 m_visibilityObservers.add(observer);
1477 void Document::unregisterVisibilityObserver(DocumentVisibilityObserver* observer)
1479 ASSERT(m_visibilityObservers.contains(observer));
1480 m_visibilityObservers.remove(observer);
1483 String Document::nodeName() const
1488 Node::NodeType Document::nodeType() const
1490 return DOCUMENT_NODE;
1493 FormController& Document::formController()
1495 if (!m_formController) {
1496 m_formController = FormController::create();
1497 if (m_frame && m_frame->loader().currentItem() && m_frame->loader().currentItem()->isCurrentDocument(this))
1498 m_frame->loader().currentItem()->setDocumentState(m_formController->formElementsState());
1500 return *m_formController;
1503 DocumentState* Document::formElementsState() const
1505 if (!m_formController)
1507 return m_formController->formElementsState();
1510 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1512 if (!stateVector.size() && !m_formController)
1514 formController().setStateForNewFormElements(stateVector);
1517 FrameView* Document::view() const
1519 return m_frame ? m_frame->view() : 0;
1522 Page* Document::page() const
1524 return m_frame ? m_frame->page() : 0;
1527 FrameHost* Document::frameHost() const
1529 return m_frame ? m_frame->host() : 0;
1532 Settings* Document::settings() const
1534 return m_frame ? m_frame->settings() : 0;
1537 PassRefPtrWillBeRawPtr<Range> Document::createRange()
1539 return Range::create(*this);
1542 PassRefPtrWillBeRawPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtrWillBeRawPtr<NodeFilter> filter, ExceptionState& exceptionState)
1544 // FIXME: It might be a good idea to emit a warning if |whatToShow| contains a bit that is not defined in
1546 return NodeIterator::create(root, whatToShow, filter);
1549 PassRefPtrWillBeRawPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtrWillBeRawPtr<NodeFilter> filter, ExceptionState& exceptionState)
1551 return TreeWalker::create(root, whatToShow, filter);
1554 bool Document::needsRenderTreeUpdate() const
1556 if (!isActive() || !view())
1558 if (needsFullRenderTreeUpdate())
1560 if (childNeedsStyleRecalc())
1562 if (childNeedsStyleInvalidation())
1567 bool Document::needsFullRenderTreeUpdate() const
1569 if (!isActive() || !view())
1571 if (!m_useElementsNeedingUpdate.isEmpty())
1573 if (!m_layerUpdateSVGFilterElements.isEmpty())
1575 if (needsStyleRecalc())
1577 if (needsStyleInvalidation())
1579 // FIXME: The childNeedsDistributionRecalc bit means either self or children, we should fix that.
1580 if (childNeedsDistributionRecalc())
1582 if (DocumentAnimations::needsOutdatedAnimationPlayerUpdate(*this))
1587 bool Document::shouldScheduleRenderTreeUpdate() const
1591 if (inStyleRecalc())
1593 // InPreLayout will recalc style itself. There's no reason to schedule another recalc.
1594 if (m_lifecycle.state() == DocumentLifecycle::InPreLayout)
1596 if (!shouldScheduleLayout())
1601 void Document::scheduleRenderTreeUpdate()
1603 ASSERT(!hasPendingStyleRecalc());
1604 ASSERT(shouldScheduleRenderTreeUpdate());
1605 ASSERT(needsRenderTreeUpdate());
1607 page()->animator().scheduleVisualUpdate();
1608 m_lifecycle.ensureStateAtMost(DocumentLifecycle::VisualUpdatePending);
1610 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ScheduleStyleRecalculation", "frame", frame());
1611 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
1612 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1613 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1616 bool Document::hasPendingForcedStyleRecalc() const
1618 return hasPendingStyleRecalc() && !inStyleRecalc() && styleChangeType() >= SubtreeStyleChange;
1621 void Document::updateDistributionIfNeeded()
1623 ScriptForbiddenScope forbidScript;
1625 if (!childNeedsDistributionRecalc())
1627 TRACE_EVENT0("blink", "Document::updateDistributionIfNeeded");
1628 recalcDistribution();
1631 void Document::updateStyleInvalidationIfNeeded()
1633 ScriptForbiddenScope forbidScript;
1637 if (!childNeedsStyleInvalidation())
1639 TRACE_EVENT0("blink", "Document::updateStyleInvalidationIfNeeded");
1640 ASSERT(styleResolver());
1642 styleResolver()->ruleFeatureSet().styleInvalidator().invalidate(*this);
1645 void Document::updateDistributionForNodeIfNeeded(Node* node)
1647 ScriptForbiddenScope forbidScript;
1649 if (node->inDocument()) {
1650 updateDistributionIfNeeded();
1654 while (Node* host = root->shadowHost())
1656 while (Node* ancestor = root->parentOrShadowHostNode())
1658 if (root->childNeedsDistributionRecalc())
1659 root->recalcDistribution();
1662 void Document::setupFontBuilder(RenderStyle* documentStyle)
1664 FontBuilder fontBuilder;
1665 fontBuilder.initForStyleResolve(*this, documentStyle);
1666 RefPtrWillBeRawPtr<CSSFontSelector> selector = m_styleEngine->fontSelector();
1667 fontBuilder.createFontForDocument(selector, documentStyle);
1670 void Document::inheritHtmlAndBodyElementStyles(StyleRecalcChange change)
1672 ASSERT(inStyleRecalc());
1673 ASSERT(documentElement());
1675 RefPtr<RenderStyle> documentElementStyle = documentElement()->renderStyle();
1676 if (!documentElementStyle || documentElement()->needsStyleRecalc() || change == Force)
1677 documentElementStyle = ensureStyleResolver().styleForElement(documentElement());
1679 WritingMode rootWritingMode = documentElementStyle->writingMode();
1680 TextDirection rootDirection = documentElementStyle->direction();
1682 HTMLElement* body = this->body();
1683 RefPtr<RenderStyle> bodyStyle;
1685 bodyStyle = body->renderStyle();
1686 if (!bodyStyle || body->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
1687 bodyStyle = ensureStyleResolver().styleForElement(body, documentElementStyle.get());
1688 if (!writingModeSetOnDocumentElement())
1689 rootWritingMode = bodyStyle->writingMode();
1690 if (!directionSetOnDocumentElement())
1691 rootDirection = bodyStyle->direction();
1694 RefPtr<RenderStyle> overflowStyle;
1695 if (Element* element = viewportDefiningElement(documentElementStyle.get())) {
1696 if (element == body) {
1697 overflowStyle = bodyStyle;
1699 ASSERT(element == documentElement());
1700 overflowStyle = documentElementStyle;
1704 // Resolved rem units are stored in the matched properties cache so we need to make sure to
1705 // invalidate the cache if the documentElement needed to reattach or the font size changed
1706 // and then trigger a full document recalc. We also need to clear it here since the
1707 // call to styleForElement on the body above can cache bad values for rem units if the
1708 // documentElement's style was dirty. We could keep track of which elements depend on
1709 // rem units like we do for viewport styles, but we assume root font size changes are
1710 // rare and just invalidate the cache for now.
1711 if (styleEngine()->usesRemUnits() && (documentElement()->needsAttach() || documentElement()->computedStyle()->fontSize() != documentElementStyle->fontSize())) {
1712 ensureStyleResolver().invalidateMatchedPropertiesCache();
1713 documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
1716 EOverflow overflowX = OAUTO;
1717 EOverflow overflowY = OAUTO;
1718 float columnGap = 0;
1719 if (overflowStyle) {
1720 overflowX = overflowStyle->overflowX();
1721 overflowY = overflowStyle->overflowY();
1722 // Visible overflow on the viewport is meaningless, and the spec says to treat it as 'auto':
1723 if (overflowX == OVISIBLE)
1725 if (overflowY == OVISIBLE)
1727 // Column-gap is (ab)used by the current paged overflow implementation (in lack of other
1728 // ways to specify gaps between pages), so we have to propagate it too.
1729 columnGap = overflowStyle->columnGap();
1732 RefPtr<RenderStyle> documentStyle = renderView()->style();
1733 if (documentStyle->writingMode() != rootWritingMode
1734 || documentStyle->direction() != rootDirection
1735 || documentStyle->overflowX() != overflowX
1736 || documentStyle->overflowY() != overflowY
1737 || documentStyle->columnGap() != columnGap) {
1738 RefPtr<RenderStyle> newStyle = RenderStyle::clone(documentStyle.get());
1739 newStyle->setWritingMode(rootWritingMode);
1740 newStyle->setDirection(rootDirection);
1741 newStyle->setColumnGap(columnGap);
1742 newStyle->setOverflowX(overflowX);
1743 newStyle->setOverflowY(overflowY);
1744 renderView()->setStyle(newStyle);
1745 setupFontBuilder(newStyle.get());
1749 if (RenderStyle* style = body->renderStyle()) {
1750 if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
1751 body->setNeedsStyleRecalc(SubtreeStyleChange);
1755 if (RenderStyle* style = documentElement()->renderStyle()) {
1756 if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
1757 documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
1761 void Document::updateRenderTree(StyleRecalcChange change)
1763 ASSERT(isMainThread());
1765 ScriptForbiddenScope forbidScript;
1767 if (!view() || !isActive())
1770 if (change != Force && !needsRenderTreeUpdate())
1773 if (inStyleRecalc())
1776 // Entering here from inside layout or paint would be catastrophic since recalcStyle can
1777 // tear down the render tree or (unfortunately) run script. Kill the whole renderer if
1778 // someone managed to get into here from inside layout or paint.
1779 RELEASE_ASSERT(!view()->isInPerformLayout());
1780 RELEASE_ASSERT(!view()->isPainting());
1782 // Script can run below in WidgetUpdates, so protect the LocalFrame.
1783 // FIXME: Can this still happen? How does script run inside
1784 // UpdateSuspendScope::performDeferredWidgetTreeOperations() ?
1785 RefPtrWillBeRawPtr<LocalFrame> protect(m_frame.get());
1787 TRACE_EVENT_BEGIN0("blink", "Document::updateRenderTree");
1788 TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "UpdateRenderTree");
1790 // FIXME: Remove m_styleRecalcElementCounter, we should just use the accessCount() on the resolver.
1791 m_styleRecalcElementCounter = 0;
1792 TRACE_EVENT_BEGIN1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "RecalculateStyles", "frame", frame());
1793 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
1794 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1795 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1797 DocumentAnimations::updateOutdatedAnimationPlayersIfNeeded(*this);
1798 evaluateMediaQueryListIfNeeded();
1799 updateUseShadowTreesIfNeeded();
1800 updateDistributionIfNeeded();
1801 updateStyleInvalidationIfNeeded();
1803 // FIXME: We should update style on our ancestor chain before proceeding
1804 // however doing so currently causes several tests to crash, as LocalFrame::setDocument calls Document::attach
1805 // before setting the LocalDOMWindow on the LocalFrame, or the SecurityOrigin on the document. The attach, in turn
1806 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1807 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1808 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1810 if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
1811 m_styleEngine->setUsesRemUnit(true);
1813 updateStyle(change);
1815 // As a result of the style recalculation, the currently hovered element might have been
1816 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1817 // to check if any other elements ended up under the mouse pointer due to re-layout.
1818 if (hoverNode() && !hoverNode()->renderer() && frame())
1819 frame()->eventHandler().dispatchFakeMouseMoveEventSoon();
1821 if (m_focusedElement && !m_focusedElement->isFocusable())
1822 clearFocusedElementSoon();
1824 #if ENABLE(SVG_FONTS)
1825 if (svgExtensions())
1826 accessSVGExtensions().removePendingSVGFontFaceElementsForRemoval();
1829 ASSERT(!m_timeline->hasOutdatedAnimationPlayer());
1831 TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "RecalculateStyles", "elementCount", m_styleRecalcElementCounter);
1832 TRACE_EVENT_END1("blink", "Document::updateRenderTree", "elementCount", m_styleRecalcElementCounter);
1833 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1834 InspectorInstrumentation::didRecalculateStyle(cookie, m_styleRecalcElementCounter);
1837 void Document::updateStyle(StyleRecalcChange change)
1839 TRACE_EVENT0("blink", "Document::updateStyle");
1841 HTMLFrameOwnerElement::UpdateSuspendScope suspendWidgetHierarchyUpdates;
1842 m_lifecycle.advanceTo(DocumentLifecycle::InStyleRecalc);
1844 if (styleChangeType() >= SubtreeStyleChange)
1847 // FIXME: Cannot access the ensureStyleResolver() before calling styleForDocument below because
1848 // apparently the StyleResolver's constructor has side effects. We should fix it.
1849 // See printing/setPrinting.html, printing/width-overflow.html though they only fail on
1850 // mac when accessing the resolver by what appears to be a viewport size difference.
1852 if (change == Force) {
1853 m_hasNodesWithPlaceholderStyle = false;
1854 RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this);
1855 StyleRecalcChange localChange = RenderStyle::stylePropagationDiff(documentStyle.get(), renderView()->style());
1856 if (localChange != NoChange)
1857 renderView()->setStyle(documentStyle.release());
1860 clearNeedsStyleRecalc();
1862 // Uncomment to enable printing of statistics about style sharing and the matched property cache.
1863 // Optionally pass StyleResolver::ReportSlowStats to print numbers that require crawling the
1864 // entire DOM (where collecting them is very slow).
1865 // FIXME: Expose this as a runtime flag.
1866 // ensureStyleResolver().enableStats(/*StyleResolver::ReportSlowStats*/);
1868 if (StyleResolverStats* stats = ensureStyleResolver().stats())
1871 if (Element* documentElement = this->documentElement()) {
1872 inheritHtmlAndBodyElementStyles(change);
1873 dirtyElementsForLayerUpdate();
1874 if (documentElement->shouldCallRecalcStyle(change))
1875 documentElement->recalcStyle(change);
1876 while (dirtyElementsForLayerUpdate())
1877 documentElement->recalcStyle(NoChange);
1880 ensureStyleResolver().printStats();
1882 view()->recalcOverflowAfterStyleChange();
1884 clearChildNeedsStyleRecalc();
1886 if (m_styleEngine->hasResolver()) {
1887 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1888 StyleResolver& resolver = m_styleEngine->ensureResolver();
1889 m_styleEngine->resetCSSFeatureFlags(resolver.ensureUpdatedRuleFeatureSet());
1890 resolver.clearStyleSharingList();
1893 ASSERT(!needsStyleRecalc());
1894 ASSERT(!childNeedsStyleRecalc());
1895 ASSERT(inStyleRecalc());
1896 m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
1899 void Document::updateRenderTreeForNodeIfNeeded(Node* node)
1901 bool needsRecalc = needsFullRenderTreeUpdate();
1903 for (const Node* ancestor = node; ancestor && !needsRecalc; ancestor = NodeRenderingTraversal::parent(ancestor))
1904 needsRecalc = ancestor->needsStyleRecalc() || ancestor->needsStyleInvalidation();
1907 updateRenderTreeIfNeeded();
1910 void Document::updateLayout()
1912 ASSERT(isMainThread());
1914 ScriptForbiddenScope forbidScript;
1916 RefPtr<FrameView> frameView = view();
1917 if (frameView && frameView->isInPerformLayout()) {
1918 // View layout should not be re-entrant.
1919 ASSERT_NOT_REACHED();
1923 if (HTMLFrameOwnerElement* owner = ownerElement())
1924 owner->document().updateLayout();
1926 updateRenderTreeIfNeeded();
1931 if (frameView->needsLayout())
1932 frameView->layout();
1934 if (lifecycle().state() < DocumentLifecycle::LayoutClean)
1935 lifecycle().advanceTo(DocumentLifecycle::LayoutClean);
1938 void Document::setNeedsFocusedElementCheck()
1940 setNeedsStyleRecalc(LocalStyleChange);
1943 void Document::clearFocusedElementSoon()
1945 if (!m_clearFocusedElementTimer.isActive())
1946 m_clearFocusedElementTimer.startOneShot(0, FROM_HERE);
1949 void Document::clearFocusedElementTimerFired(Timer<Document>*)
1951 updateRenderTreeIfNeeded();
1952 m_clearFocusedElementTimer.stop();
1954 if (m_focusedElement && !m_focusedElement->isFocusable())
1955 m_focusedElement->blur();
1958 // FIXME: This is a bad idea and needs to be removed eventually.
1959 // Other browsers load stylesheets before they continue parsing the web page.
1960 // Since we don't, we can run JavaScript code that needs answers before the
1961 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1962 // lets us get reasonable answers. The long term solution to this problem is
1963 // to instead suspend JavaScript execution.
1964 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
1966 StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
1968 if (m_styleEngine->hasPendingSheets()) {
1969 // FIXME: We are willing to attempt to suppress painting with outdated style info only once.
1970 // Our assumption is that it would be dangerous to try to stop it a second time, after page
1971 // content has already been loaded and displayed with accurate style information. (Our
1972 // suppression involves blanking the whole page at the moment. If it were more refined, we
1973 // might be able to do something better.) It's worth noting though that this entire method
1974 // is a hack, since what we really want to do is suspend JS instead of doing a layout with
1975 // inaccurate information.
1976 HTMLElement* bodyElement = body();
1977 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1978 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1979 styleResolverChanged();
1980 } else if (m_hasNodesWithPlaceholderStyle) {
1981 // If new nodes have been added or style recalc has been done with style sheets still
1982 // pending, some nodes may not have had their real style calculated yet. Normally this
1983 // gets cleaned when style sheets arrive but here we need up-to-date style immediately.
1984 updateRenderTree(Force);
1990 if (runPostLayoutTasks == RunPostLayoutTasksSynchronously && view())
1991 view()->flushAnyPendingPostLayoutTasks();
1994 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1996 ASSERT_ARG(element, element->document() == this);
1997 StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
1998 return ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
2001 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
2003 updateDistributionIfNeeded();
2004 return ensureStyleResolver().styleForPage(pageIndex);
2007 bool Document::isPageBoxVisible(int pageIndex)
2009 return styleForPage(pageIndex)->visibility() != HIDDEN; // display property doesn't apply to @page.
2012 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2014 RefPtr<RenderStyle> style = styleForPage(pageIndex);
2016 int width = pageSize.width();
2017 int height = pageSize.height();
2018 switch (style->pageSizeType()) {
2019 case PAGE_SIZE_AUTO:
2021 case PAGE_SIZE_AUTO_LANDSCAPE:
2023 std::swap(width, height);
2025 case PAGE_SIZE_AUTO_PORTRAIT:
2027 std::swap(width, height);
2029 case PAGE_SIZE_RESOLVED: {
2030 LengthSize size = style->pageSize();
2031 ASSERT(size.width().isFixed());
2032 ASSERT(size.height().isFixed());
2033 width = valueForLength(size.width(), 0);
2034 height = valueForLength(size.height(), 0);
2038 ASSERT_NOT_REACHED();
2040 pageSize = IntSize(width, height);
2042 // The percentage is calculated with respect to the width even for margin top and bottom.
2043 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2044 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2045 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2046 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2047 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2050 void Document::setIsViewSource(bool isViewSource)
2052 m_isViewSource = isViewSource;
2053 if (!m_isViewSource)
2056 setSecurityOrigin(SecurityOrigin::createUnique());
2057 didUpdateSecurityOrigin();
2060 bool Document::dirtyElementsForLayerUpdate()
2062 if (m_layerUpdateSVGFilterElements.isEmpty())
2065 for (WillBeHeapHashSet<RawPtrWillBeMember<Element> >::iterator it = m_layerUpdateSVGFilterElements.begin(), end = m_layerUpdateSVGFilterElements.end(); it != end; ++it)
2066 (*it)->setNeedsStyleRecalc(LocalStyleChange);
2067 m_layerUpdateSVGFilterElements.clear();
2071 void Document::scheduleSVGFilterLayerUpdateHack(Element& element)
2073 if (element.styleChangeType() == NeedsReattachStyleChange)
2075 element.setSVGFilterNeedsLayerUpdate();
2076 m_layerUpdateSVGFilterElements.add(&element);
2077 scheduleRenderTreeUpdateIfNeeded();
2080 void Document::unscheduleSVGFilterLayerUpdateHack(Element& element)
2082 element.clearSVGFilterNeedsLayerUpdate();
2083 m_layerUpdateSVGFilterElements.remove(&element);
2086 void Document::scheduleUseShadowTreeUpdate(SVGUseElement& element)
2088 m_useElementsNeedingUpdate.add(&element);
2089 scheduleRenderTreeUpdateIfNeeded();
2092 void Document::unscheduleUseShadowTreeUpdate(SVGUseElement& element)
2094 m_useElementsNeedingUpdate.remove(&element);
2097 void Document::updateUseShadowTreesIfNeeded()
2099 ScriptForbiddenScope forbidScript;
2101 if (m_useElementsNeedingUpdate.isEmpty())
2104 WillBeHeapVector<RawPtrWillBeMember<SVGUseElement> > elements;
2105 copyToVector(m_useElementsNeedingUpdate, elements);
2106 m_useElementsNeedingUpdate.clear();
2108 for (WillBeHeapVector<RawPtrWillBeMember<SVGUseElement> >::iterator it = elements.begin(), end = elements.end(); it != end; ++it)
2109 (*it)->buildPendingResource();
2112 StyleResolver* Document::styleResolver() const
2114 return m_styleEngine->resolver();
2117 StyleResolver& Document::ensureStyleResolver() const
2119 return m_styleEngine->ensureResolver();
2122 void Document::clearStyleResolver()
2124 m_styleEngine->clearResolver();
2127 void Document::attach(const AttachContext& context)
2129 ASSERT(m_lifecycle.state() == DocumentLifecycle::Inactive);
2130 ASSERT(!m_axObjectCache || this != &axObjectCacheOwner());
2132 m_renderView = new RenderView(this);
2133 setRenderer(m_renderView);
2135 m_renderView->setIsInWindow(true);
2136 m_renderView->setStyle(StyleResolver::styleForDocument(*this));
2137 m_renderView->compositor()->setNeedsCompositingUpdate(CompositingUpdateAfterCompositingInputChange);
2139 ContainerNode::attach(context);
2141 // The TextAutosizer can't update render view info while the Document is detached, so update now in case anything changed.
2142 if (TextAutosizer* autosizer = textAutosizer())
2143 autosizer->updatePageInfo();
2145 m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
2148 void Document::detach(const AttachContext& context)
2151 m_lifecycle.advanceTo(DocumentLifecycle::Stopping);
2154 page()->documentDetached(this);
2155 InspectorInstrumentation::documentDetached(this);
2157 if (m_frame->loader().client()->sharedWorkerRepositoryClient())
2158 m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this);
2160 if (this == &axObjectCacheOwner())
2161 clearAXObjectCache();
2163 stopActiveDOMObjects();
2165 // FIXME: consider using ActiveDOMObject.
2166 if (m_scriptedAnimationController)
2167 m_scriptedAnimationController->clearDocumentPointer();
2168 m_scriptedAnimationController.clear();
2170 if (svgExtensions())
2171 accessSVGExtensions().pauseAnimations();
2173 // FIXME: This shouldn't be needed once LocalDOMWindow becomes ExecutionContext.
2175 m_domWindow->clearEventQueue();
2178 m_renderView->setIsInWindow(false);
2181 FrameView* view = m_frame->view();
2183 view->detachCustomScrollbars();
2186 m_hoverNode = nullptr;
2187 m_focusedElement = nullptr;
2188 m_activeHoverElement = nullptr;
2189 m_autofocusElement = nullptr;
2192 ContainerNode::detach(context);
2194 m_styleEngine->didDetach();
2196 frameHost()->eventHandlerRegistry().documentDetached(*this);
2198 // This is required, as our LocalFrame might delete itself as soon as it detaches
2199 // us. However, this violates Node::detach() semantics, as it's never
2200 // possible to re-attach. Eventually Document::detach() should be renamed,
2201 // or this setting of the frame to 0 could be made explicit in each of the
2202 // callers of Document::detach().
2205 if (m_mediaQueryMatcher)
2206 m_mediaQueryMatcher->documentDetached();
2208 lifecycleNotifier().notifyDocumentWasDetached();
2209 m_lifecycle.advanceTo(DocumentLifecycle::Stopped);
2211 // Done with the window, explicitly clear to hasten its
2217 void Document::prepareForDestruction()
2219 m_markers->prepareForDestruction();
2220 disconnectDescendantFrames();
2222 // The process of disconnecting descendant frames could have already detached us.
2226 if (LocalDOMWindow* window = this->domWindow())
2227 window->willDetachDocumentFromFrame();
2231 void Document::removeAllEventListeners()
2233 ContainerNode::removeAllEventListeners();
2235 if (LocalDOMWindow* domWindow = this->domWindow())
2236 domWindow->removeAllEventListeners();
2239 Document& Document::axObjectCacheOwner() const
2241 Document& top = topDocument();
2242 if (top.frame() && top.frame()->pagePopupOwner()) {
2243 ASSERT(!top.m_axObjectCache);
2244 return top.frame()->pagePopupOwner()->document().axObjectCacheOwner();
2249 void Document::clearAXObjectCache()
2251 ASSERT(&axObjectCacheOwner() == this);
2252 // Clear the cache member variable before calling delete because attempts
2253 // are made to access it during destruction.
2254 m_axObjectCache.clear();
2257 AXObjectCache* Document::existingAXObjectCache() const
2259 // If the renderer is gone then we are in the process of destruction.
2260 // This method will be called before m_frame = nullptr.
2261 if (!axObjectCacheOwner().renderView())
2264 return axObjectCacheOwner().m_axObjectCache.get();
2267 AXObjectCache* Document::axObjectCache() const
2269 Settings* settings = this->settings();
2270 if (!settings || !settings->accessibilityEnabled())
2273 // The only document that actually has a AXObjectCache is the top-level
2274 // document. This is because we need to be able to get from any WebCoreAXObject
2275 // to any other WebCoreAXObject on the same page. Using a single cache allows
2276 // lookups across nested webareas (i.e. multiple documents).
2277 Document& cacheOwner = this->axObjectCacheOwner();
2279 // If the document has already been detached, do not make a new axObjectCache.
2280 if (!cacheOwner.renderView())
2283 ASSERT(&cacheOwner == this || !m_axObjectCache);
2284 if (!cacheOwner.m_axObjectCache)
2285 cacheOwner.m_axObjectCache = adoptPtr(new AXObjectCache(cacheOwner));
2286 return cacheOwner.m_axObjectCache.get();
2289 PassRefPtrWillBeRawPtr<DocumentParser> Document::createParser()
2291 if (isHTMLDocument()) {
2292 bool reportErrors = InspectorInstrumentation::collectingHTMLParseErrors(page());
2293 return HTMLDocumentParser::create(toHTMLDocument(*this), reportErrors);
2295 // FIXME: this should probably pass the frame instead
2296 return XMLDocumentParser::create(*this, view());
2299 bool Document::isFrameSet() const
2301 if (!isHTMLDocument())
2303 return isHTMLFrameSetElement(body());
2306 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2308 return parser() ? parser()->asScriptableDocumentParser() : 0;
2311 void Document::open(Document* ownerDocument, ExceptionState& exceptionState)
2313 if (importLoader()) {
2314 exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support open().");
2318 if (ownerDocument) {
2319 setURL(ownerDocument->url());
2320 m_cookieURL = ownerDocument->cookieURL();
2321 setSecurityOrigin(ownerDocument->securityOrigin());
2325 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2326 if (parser->isParsing()) {
2327 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2328 if (parser->isExecutingScript())
2331 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2336 if (m_frame->loader().state() == FrameStateProvisional)
2337 m_frame->loader().stopAllLoaders();
2340 removeAllEventListenersRecursively();
2342 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2343 parser->setWasCreatedByScript(true);
2346 m_frame->loader().didExplicitOpen();
2347 if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
2348 m_loadEventProgress = LoadEventNotRun;
2351 void Document::detachParser()
2359 void Document::cancelParsing()
2364 // We have to clear the parser to avoid possibly triggering
2365 // the onload handler when closing as a side effect of a cancel-style
2366 // change, such as opening a new document or closing the window while
2372 PassRefPtrWillBeRawPtr<DocumentParser> Document::implicitOpen()
2377 ASSERT(!m_focusedElement);
2379 setCompatibilityMode(NoQuirksMode);
2381 m_parser = createParser();
2383 setReadyState(Loading);
2388 HTMLElement* Document::body() const
2390 if (!documentElement())
2393 for (HTMLElement* child = Traversal<HTMLElement>::firstChild(*documentElement()); child; child = Traversal<HTMLElement>::nextSibling(*child)) {
2394 if (isHTMLFrameSetElement(*child) || isHTMLBodyElement(*child))
2401 void Document::setBody(PassRefPtrWillBeRawPtr<HTMLElement> prpNewBody, ExceptionState& exceptionState)
2403 RefPtrWillBeRawPtr<HTMLElement> newBody = prpNewBody;
2406 exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::argumentNullOrIncorrectType(1, "HTMLElement"));
2409 if (!documentElement()) {
2410 exceptionState.throwDOMException(HierarchyRequestError, "No document element exists.");
2414 if (!isHTMLBodyElement(*newBody) && !isHTMLFrameSetElement(*newBody)) {
2415 exceptionState.throwDOMException(HierarchyRequestError, "The new body element is of type '" + newBody->tagName() + "'. It must be either a 'BODY' or 'FRAMESET' element.");
2419 HTMLElement* oldBody = body();
2420 if (oldBody == newBody)
2424 documentElement()->replaceChild(newBody.release(), oldBody, exceptionState);
2426 documentElement()->appendChild(newBody.release(), exceptionState);
2429 HTMLHeadElement* Document::head() const
2431 Node* de = documentElement();
2435 return Traversal<HTMLHeadElement>::firstChild(*de);
2438 Element* Document::viewportDefiningElement(RenderStyle* rootStyle) const
2440 // If a BODY element sets non-visible overflow, it is to be propagated to the viewport, as long
2441 // as the following conditions are all met:
2442 // (1) The root element is HTML.
2443 // (2) It is the primary BODY element (we only assert for this, expecting callers to behave).
2444 // (3) The root element has visible overflow.
2445 // Otherwise it's the root element's properties that are to be propagated.
2446 Element* rootElement = documentElement();
2447 Element* bodyElement = body();
2451 rootStyle = rootElement->renderStyle();
2455 if (bodyElement && rootStyle->isOverflowVisible() && isHTMLHtmlElement(*rootElement))
2460 void Document::close(ExceptionState& exceptionState)
2462 // FIXME: We should follow the specification more closely:
2463 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2465 if (importLoader()) {
2466 exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support close().");
2470 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2476 void Document::explicitClose()
2478 if (RefPtrWillBeRawPtr<DocumentParser> parser = m_parser)
2482 // Because we have no frame, we don't know if all loading has completed,
2483 // so we just call implicitClose() immediately. FIXME: This might fire
2484 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2489 m_frame->loader().checkCompleted();
2492 void Document::implicitClose()
2494 ASSERT(!inStyleRecalc());
2495 if (processingLoadEvent() || !m_parser)
2497 if (frame() && frame()->navigationScheduler().locationChangePending())
2500 // The call to dispatchWindowLoadEvent can detach the LocalDOMWindow and cause it (and its
2501 // attached Document) to be destroyed.
2502 RefPtrWillBeRawPtr<LocalDOMWindow> protectedWindow(this->domWindow());
2504 m_loadEventProgress = LoadEventInProgress;
2506 ScriptableDocumentParser* parser = scriptableDocumentParser();
2507 m_wellFormed = parser && parser->wellFormed();
2509 // We have to clear the parser, in case someone document.write()s from the
2510 // onLoad event handler, as in Radar 3206524.
2513 if (frame() && frame()->script().canExecuteScripts(NotAboutToExecuteScript)) {
2514 ImageLoader::dispatchPendingLoadEvents();
2515 ImageLoader::dispatchPendingErrorEvents();
2517 HTMLLinkElement::dispatchPendingLoadEvents();
2518 HTMLStyleElement::dispatchPendingLoadEvents();
2521 // JS running below could remove the frame or destroy the RenderView so we call
2522 // those two functions repeatedly and don't save them on the stack.
2524 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2525 // here, instead of doing it from SVGElement::finishedParsingChildren.
2526 if (svgExtensions())
2527 accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2529 if (protectedWindow)
2530 protectedWindow->documentWasClosed();
2533 frame()->loader().client()->dispatchDidHandleOnloadEvents();
2534 loader()->applicationCacheHost()->stopDeferringEvents();
2538 m_loadEventProgress = LoadEventCompleted;
2542 // Make sure both the initial layout and reflow happen after the onload
2543 // fires. This will improve onload scores, and other browsers do it.
2544 // If they wanna cheat, we can too. -dwh
2546 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2547 // Just bail out. Before or during the onload we were shifted to another page.
2548 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2549 m_loadEventProgress = LoadEventCompleted;
2553 // We used to force a synchronous display and flush here. This really isn't
2554 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2555 // (if your platform is syncing flushes and limiting them to 60fps).
2556 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2557 updateRenderTreeIfNeeded();
2559 // Always do a layout after loading if needed.
2560 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2564 m_loadEventProgress = LoadEventCompleted;
2566 if (frame() && renderView() && settings()->accessibilityEnabled()) {
2567 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2568 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2569 // exists in the cache (we ignore the return value because we don't need it here). This is
2570 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2571 if (AXObjectCache* cache = axObjectCache()) {
2572 cache->getOrCreate(renderView());
2573 if (this == &axObjectCacheOwner()) {
2574 cache->postNotification(renderView(), AXObjectCache::AXLoadComplete, true);
2576 // AXLoadComplete can only be posted on the top document, so if it's a document
2577 // in an iframe that just finished loading, post AXLayoutComplete instead.
2578 cache->postNotification(renderView(), AXObjectCache::AXLayoutComplete, true);
2583 if (svgExtensions())
2584 accessSVGExtensions().startAnimations();
2587 bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigation)
2595 RefPtrWillBeRawPtr<Document> protect(this);
2597 RefPtrWillBeRawPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2598 m_loadEventProgress = BeforeUnloadEventInProgress;
2599 m_domWindow->dispatchEvent(beforeUnloadEvent.get(), this);
2600 m_loadEventProgress = BeforeUnloadEventCompleted;
2601 if (!beforeUnloadEvent->defaultPrevented())
2602 defaultEventHandler(beforeUnloadEvent.get());
2603 if (beforeUnloadEvent->returnValue().isNull())
2606 if (didAllowNavigation) {
2607 addConsoleMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation."));
2611 String text = beforeUnloadEvent->returnValue();
2612 if (chrome.runBeforeUnloadConfirmPanel(text, m_frame)) {
2613 didAllowNavigation = true;
2619 void Document::dispatchUnloadEvents()
2621 RefPtrWillBeRawPtr<Document> protect(this);
2623 m_parser->stopParsing();
2625 if (m_loadEventProgress == LoadEventNotRun)
2628 if (m_loadEventProgress <= UnloadEventInProgress) {
2629 Element* currentFocusedElement = focusedElement();
2630 if (isHTMLInputElement(currentFocusedElement))
2631 toHTMLInputElement(*currentFocusedElement).endEditing();
2632 if (m_loadEventProgress < PageHideInProgress) {
2633 m_loadEventProgress = PageHideInProgress;
2634 if (LocalDOMWindow* window = domWindow())
2635 window->dispatchEvent(PageTransitionEvent::create(EventTypeNames::pagehide, false), this);
2639 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
2640 // while dispatching the event, so protect it to prevent writing the end
2641 // time into freed memory.
2642 RefPtr<DocumentLoader> documentLoader = m_frame->loader().provisionalDocumentLoader();
2643 m_loadEventProgress = UnloadEventInProgress;
2644 RefPtrWillBeRawPtr<Event> unloadEvent(Event::create(EventTypeNames::unload));
2645 if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
2646 DocumentLoadTiming* timing = documentLoader->timing();
2647 ASSERT(timing->navigationStart());
2648 timing->markUnloadEventStart();
2649 m_frame->domWindow()->dispatchEvent(unloadEvent, this);
2650 timing->markUnloadEventEnd();
2652 m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
2655 m_loadEventProgress = UnloadEventHandled;
2661 // Don't remove event listeners from a transitional empty document (see https://bugs.webkit.org/show_bug.cgi?id=28716 for more information).
2662 bool keepEventListeners = m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader().provisionalDocumentLoader()
2663 && isSecureTransitionTo(m_frame->loader().provisionalDocumentLoader()->url());
2664 if (!keepEventListeners)
2665 removeAllEventListenersRecursively();
2668 Document::PageDismissalType Document::pageDismissalEventBeingDispatched() const
2670 if (m_loadEventProgress == BeforeUnloadEventInProgress)
2671 return BeforeUnloadDismissal;
2672 if (m_loadEventProgress == PageHideInProgress)
2673 return PageHideDismissal;
2674 if (m_loadEventProgress == UnloadEventInProgress)
2675 return UnloadDismissal;
2679 void Document::setParsing(bool b)
2683 if (m_isParsing && !m_elementDataCache)
2684 m_elementDataCache = ElementDataCache::create();
2687 bool Document::shouldScheduleLayout() const
2689 // This function will only be called when FrameView thinks a layout is needed.
2690 // This enforces a couple extra rules.
2692 // (a) Only schedule a layout once the stylesheets are loaded.
2693 // (b) Only schedule layout once we have a body element.
2697 if (isRenderingReady() && body())
2700 if (documentElement() && !isHTMLHtmlElement(*documentElement()))
2706 int Document::elapsedTime() const
2708 return static_cast<int>((currentTime() - m_startTime) * 1000);
2711 void Document::write(const SegmentedString& text, Document* ownerDocument, ExceptionState& exceptionState)
2713 if (importLoader()) {
2714 exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support write().");
2718 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2720 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2721 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2723 if (m_writeRecursionIsTooDeep)
2726 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2728 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount) {
2729 addConsoleMessage(ConsoleMessage::create(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.")));
2733 if (!hasInsertionPoint)
2734 open(ownerDocument);
2737 m_parser->insert(text);
2740 void Document::write(const String& text, Document* ownerDocument, ExceptionState& exceptionState)
2742 write(SegmentedString(text), ownerDocument, exceptionState);
2745 void Document::writeln(const String& text, Document* ownerDocument, ExceptionState& exceptionState)
2747 write(text, ownerDocument, exceptionState);
2748 if (exceptionState.hadException())
2750 write("\n", ownerDocument);
2753 const KURL& Document::virtualURL() const
2758 KURL Document::virtualCompleteURL(const String& url) const
2760 return completeURL(url);
2763 double Document::timerAlignmentInterval() const
2767 return DOMTimer::visiblePageAlignmentInterval();
2768 return p->timerAlignmentInterval();
2771 EventTarget* Document::errorEventTarget()
2776 void Document::logExceptionToConsole(const String& errorMessage, int scriptId, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtrWillBeRawPtr<ScriptCallStack> callStack)
2778 RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber);
2779 consoleMessage->setScriptId(scriptId);
2780 consoleMessage->setCallStack(callStack);
2781 addConsoleMessage(consoleMessage.release());
2784 void Document::setURL(const KURL& url)
2786 const KURL& newURL = url.isEmpty() ? blankURL() : url;
2787 if (newURL == m_url)
2792 contextFeatures().urlDidChange(this);
2795 void Document::updateBaseURL()
2797 KURL oldBaseURL = m_baseURL;
2798 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2799 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2800 // from the Document interface otherwise (which we store, preparsed, in m_url).
2801 if (!m_baseElementURL.isEmpty())
2802 m_baseURL = m_baseElementURL;
2803 else if (!m_baseURLOverride.isEmpty())
2804 m_baseURL = m_baseURLOverride;
2808 selectorQueryCache().invalidate();
2810 if (!m_baseURL.isValid())
2814 // Element sheet is silly. It never contains anything.
2815 ASSERT(!m_elemSheet->contents()->ruleCount());
2816 bool usesRemUnits = m_elemSheet->contents()->usesRemUnits();
2817 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2818 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2819 m_elemSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
2822 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2823 // Base URL change changes any relative visited links.
2824 // 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.
2825 for (HTMLAnchorElement* anchor = Traversal<HTMLAnchorElement>::firstWithin(*this); anchor; anchor = Traversal<HTMLAnchorElement>::next(*anchor))
2826 anchor->invalidateCachedVisitedLinkHash();
2830 void Document::setBaseURLOverride(const KURL& url)
2832 m_baseURLOverride = url;
2836 void Document::processBaseElement()
2838 // Find the first href attribute in a base element and the first target attribute in a base element.
2839 const AtomicString* href = 0;
2840 const AtomicString* target = 0;
2841 for (HTMLBaseElement* base = Traversal<HTMLBaseElement>::firstWithin(*this); base && (!href || !target); base = Traversal<HTMLBaseElement>::next(*base)) {
2843 const AtomicString& value = base->fastGetAttribute(hrefAttr);
2844 if (!value.isNull())
2848 const AtomicString& value = base->fastGetAttribute(targetAttr);
2849 if (!value.isNull())
2852 if (contentSecurityPolicy()->isActive())
2853 UseCounter::count(*this, UseCounter::ContentSecurityPolicyWithBaseElement);
2856 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2857 KURL baseElementURL;
2859 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2860 if (!strippedHref.isEmpty())
2861 baseElementURL = KURL(url(), strippedHref);
2863 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
2864 m_baseElementURL = baseElementURL;
2868 m_baseTarget = target ? *target : nullAtom;
2871 String Document::userAgent(const KURL& url) const
2873 return frame() ? frame()->loader().userAgent(url) : String();
2876 void Document::disableEval(const String& errorMessage)
2881 frame()->script().disableEval(errorMessage);
2884 bool Document::canNavigate(const Frame& targetFrame)
2889 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
2890 if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
2893 if (isSandboxed(SandboxNavigation)) {
2894 if (targetFrame.tree().isDescendantOf(m_frame))
2897 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
2898 if (isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
2899 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
2901 printNavigationErrorMessage(toLocalFrameTemporary(targetFrame), url(), reason);
2905 ASSERT(securityOrigin());
2906 SecurityOrigin& origin = *securityOrigin();
2908 // This is the normal case. A document can navigate its decendant frames,
2909 // or, more generally, a document can navigate a frame if the document is
2910 // in the same origin as any of that frame's ancestors (in the frame
2913 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2914 // historical information about this security check.
2915 if (canAccessAncestor(origin, &targetFrame))
2918 // Top-level frames are easier to navigate than other frames because they
2919 // display their URLs in the address bar (in most browsers). However, there
2920 // are still some restrictions on navigation to avoid nuisance attacks.
2921 // Specifically, a document can navigate a top-level frame if that frame
2922 // opened the document or if the document is the same-origin with any of
2923 // the top-level frame's opener's ancestors (in the frame hierarchy).
2925 // In both of these cases, the document performing the navigation is in
2926 // some way related to the frame being navigate (e.g., by the "opener"
2927 // and/or "parent" relation). Requiring some sort of relation prevents a
2928 // document from navigating arbitrary, unrelated top-level frames.
2929 if (!targetFrame.tree().parent()) {
2930 if (targetFrame == m_frame->loader().opener())
2933 // FIXME: We don't have access to RemoteFrame's opener yet.
2934 if (targetFrame.isLocalFrame() && canAccessAncestor(origin, toLocalFrame(targetFrame).loader().opener()))
2938 printNavigationErrorMessage(toLocalFrameTemporary(targetFrame), url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
2942 LocalFrame* Document::findUnsafeParentScrollPropagationBoundary()
2944 LocalFrame* currentFrame = m_frame;
2945 Frame* ancestorFrame = currentFrame->tree().parent();
2947 while (ancestorFrame) {
2948 // FIXME: We don't yet have access to a RemoteFrame's security origin.
2949 if (!ancestorFrame->isLocalFrame())
2950 return currentFrame;
2951 if (!toLocalFrame(ancestorFrame)->document()->securityOrigin()->canAccess(securityOrigin()))
2952 return currentFrame;
2953 currentFrame = toLocalFrame(ancestorFrame);
2954 ancestorFrame = ancestorFrame->tree().parent();
2959 void Document::didLoadAllImports()
2961 if (!haveStylesheetsLoaded())
2963 if (!importLoader())
2964 styleResolverMayHaveChanged();
2965 didLoadAllScriptBlockingResources();
2968 void Document::didRemoveAllPendingStylesheet()
2970 styleResolverMayHaveChanged();
2972 // Only imports on master documents can trigger rendering.
2973 if (HTMLImportLoader* import = importLoader())
2974 import->didRemoveAllPendingStylesheet();
2975 if (!haveImportsLoaded())
2977 didLoadAllScriptBlockingResources();
2980 void Document::didLoadAllScriptBlockingResources()
2982 m_executeScriptsWaitingForResourcesTimer.startOneShot(0, FROM_HERE);
2985 frame()->loader().client()->didRemoveAllPendingStylesheet();
2987 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
2988 view()->scrollToFragment(m_url);
2991 void Document::executeScriptsWaitingForResourcesTimerFired(Timer<Document>*)
2993 if (!isRenderingReady())
2995 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2996 parser->executeScriptsWaitingForResources();
2999 CSSStyleSheet& Document::elementSheet()
3002 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
3003 return *m_elemSheet;
3006 void Document::processHttpEquiv(const AtomicString& equiv, const AtomicString& content, bool inDocumentHeadElement)
3008 ASSERT(!equiv.isNull() && !content.isNull());
3010 if (equalIgnoringCase(equiv, "default-style")) {
3011 processHttpEquivDefaultStyle(content);
3012 } else if (equalIgnoringCase(equiv, "refresh")) {
3013 processHttpEquivRefresh(content);
3014 } else if (equalIgnoringCase(equiv, "set-cookie")) {
3015 processHttpEquivSetCookie(content);
3016 } else if (equalIgnoringCase(equiv, "content-language")) {
3017 setContentLanguage(content);
3018 } else if (equalIgnoringCase(equiv, "x-dns-prefetch-control")) {
3019 parseDNSPrefetchControlHeader(content);
3020 } else if (equalIgnoringCase(equiv, "x-frame-options")) {
3021 processHttpEquivXFrameOptions(content);
3022 } else if (equalIgnoringCase(equiv, "content-security-policy") || equalIgnoringCase(equiv, "content-security-policy-report-only")) {
3023 if (inDocumentHeadElement)
3024 processHttpEquivContentSecurityPolicy(equiv, content);
3026 contentSecurityPolicy()->reportMetaOutsideHead(content);
3030 void Document::processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content)
3034 if (equalIgnoringCase(equiv, "content-security-policy"))
3035 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeEnforce, ContentSecurityPolicyHeaderSourceMeta);
3036 else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
3037 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeReport, ContentSecurityPolicyHeaderSourceMeta);
3039 ASSERT_NOT_REACHED();
3042 void Document::processHttpEquivDefaultStyle(const AtomicString& content)
3044 // The preferred style set has been overridden as per section
3045 // 14.3.2 of the HTML4.0 specification. We need to update the
3046 // sheet used variable and then update our style selector.
3047 // For more info, see the test at:
3048 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3050 m_styleEngine->setSelectedStylesheetSetName(content);
3051 m_styleEngine->setPreferredStylesheetSetName(content);
3052 styleResolverChanged();
3055 void Document::processHttpEquivRefresh(const AtomicString& content)
3057 maybeHandleHttpRefresh(content, HttpRefreshFromMetaTag);
3060 void Document::maybeHandleHttpRefresh(const String& content, HttpRefreshType httpRefreshType)
3062 if (m_isViewSource || !m_frame)
3067 if (!parseHTTPRefresh(content, httpRefreshType == HttpRefreshFromMetaTag, delay, refreshURL))
3069 if (refreshURL.isEmpty())
3070 refreshURL = url().string();
3072 refreshURL = completeURL(refreshURL).string();
3074 if (protocolIsJavaScript(refreshURL)) {
3075 String message = "Refused to refresh " + m_url.elidedString() + " to a javascript: URL";
3076 addConsoleMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, message));
3080 if (httpRefreshType == HttpRefreshFromMetaTag && isSandboxed(SandboxAutomaticFeatures)) {
3081 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.";
3082 addConsoleMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, message));
3085 m_frame->navigationScheduler().scheduleRedirect(delay, refreshURL);
3088 void Document::processHttpEquivSetCookie(const AtomicString& content)
3090 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3091 if (!isHTMLDocument())
3094 // Exception (for sandboxed documents) ignored.
3095 toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
3098 void Document::processHttpEquivXFrameOptions(const AtomicString& content)
3100 LocalFrame* frame = this->frame();
3104 FrameLoader& frameLoader = frame->loader();
3105 unsigned long requestIdentifier = loader()->mainResourceIdentifier();
3106 if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
3107 String message = "Refused to display '" + url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
3108 frameLoader.stopAllLoaders();
3109 // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
3110 // intent, we must navigate away from the possibly partially-rendered document to a location that
3111 // doesn't inherit the parent's SecurityOrigin.
3112 frame->navigationScheduler().scheduleLocationChange(this, SecurityOrigin::urlWithUniqueSecurityOrigin(), Referrer());
3113 RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, message);
3114 consoleMessage->setRequestIdentifier(requestIdentifier);
3115 addConsoleMessage(consoleMessage.release());
3119 bool Document::shouldMergeWithLegacyDescription(ViewportDescription::Type origin)
3121 return settings() && settings()->viewportMetaMergeContentQuirk() && m_legacyViewportDescription.isMetaViewportType() && m_legacyViewportDescription.type == origin;
3124 void Document::setViewportDescription(const ViewportDescription& viewportDescription)
3126 // The UA-defined min-width is used by the processing of legacy meta tags.
3127 if (!viewportDescription.isSpecifiedByAuthor())
3128 m_viewportDefaultMinWidth = viewportDescription.minWidth;
3130 if (viewportDescription.isLegacyViewportType()) {
3131 if (settings() && !settings()->viewportMetaEnabled())
3134 m_legacyViewportDescription = viewportDescription;
3136 // When no author style for @viewport is present, and a meta tag for defining
3137 // the viewport is, apply the meta tag viewport instead of the UA styles.
3138 if (m_viewportDescription.type == ViewportDescription::AuthorStyleSheet)
3140 m_viewportDescription = viewportDescription;
3142 // If the legacy viewport tag has higher priority than the cascaded @viewport
3143 // descriptors, use the values from the legacy tag.
3144 if (!shouldOverrideLegacyDescription(viewportDescription.type))
3145 m_viewportDescription = m_legacyViewportDescription;
3147 m_viewportDescription = viewportDescription;
3150 updateViewportDescription();
3153 void Document::updateViewportDescription()
3155 if (frame() && frame()->isMainFrame()) {
3156 frameHost()->chrome().dispatchViewportPropertiesDidChange(m_viewportDescription);
3160 void Document::processReferrerPolicy(const String& policy)
3162 ASSERT(!policy.isNull());
3164 if (equalIgnoringCase(policy, "never")) {
3165 setReferrerPolicy(ReferrerPolicyNever);
3166 } else if (equalIgnoringCase(policy, "always")) {
3167 setReferrerPolicy(ReferrerPolicyAlways);
3168 } else if (equalIgnoringCase(policy, "origin")) {
3169 setReferrerPolicy(ReferrerPolicyOrigin);
3170 } else if (equalIgnoringCase(policy, "default")) {
3171 setReferrerPolicy(ReferrerPolicyDefault);
3173 addConsoleMessage(ConsoleMessage::create(RenderingMessageSource, ErrorMessageLevel, "Failed to set referrer policy: The value '" + policy + "' is not one of 'always', 'default', 'never', or 'origin'. Defaulting to 'never'."));
3174 setReferrerPolicy(ReferrerPolicyNever);
3178 void Document::setReferrerPolicy(ReferrerPolicy referrerPolicy)
3180 // 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?
3181 if (m_didSetReferrerPolicy)
3182 UseCounter::count(this, UseCounter::ResetReferrerPolicy);
3183 m_didSetReferrerPolicy = true;
3185 m_referrerPolicy = referrerPolicy;
3188 String Document::outgoingReferrer()
3190 // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
3191 // for why we walk the parent chain for srcdoc documents.
3192 Document* referrerDocument = this;
3193 if (LocalFrame* frame = m_frame) {
3194 while (frame->document()->isSrcdocDocument()) {
3195 // Srcdoc documents must be local within the containing frame.
3196 frame = toLocalFrame(frame->tree().parent());
3197 // Srcdoc documents cannot be top-level documents, by definition,
3198 // because they need to be contained in iframes with the srcdoc.
3201 referrerDocument = frame->document();
3203 return referrerDocument->m_url.strippedForUseAsReferrer();
3206 String Document::outgoingOrigin() const
3208 return securityOrigin()->toString();
3211 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3213 ASSERT(!renderView() || renderView()->isRenderView());
3215 // RenderView::hitTest causes a layout, and we don't want to hit that until the first
3216 // layout because until then, there is nothing shown on the screen - the user can't
3217 // have intentionally clicked on something belonging to this page. Furthermore,
3218 // mousemove events before the first layout should not lead to a premature layout()
3219 // happening, which could show a flash of white.
3220 // See also the similar code in EventHandler::hitTestResultAtPoint.
3221 if (!renderView() || !view() || !view()->didFirstLayout())
3222 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3224 HitTestResult result(documentPoint);
3225 renderView()->hitTest(request, result);
3227 if (!request.readOnly())
3228 updateHoverActiveState(request, result.innerElement(), &event);
3230 return MouseEventWithHitTestResults(event, result);
3233 // DOM Section 1.1.1
3234 bool Document::childTypeAllowed(NodeType type) const
3237 case ATTRIBUTE_NODE:
3238 case CDATA_SECTION_NODE:
3239 case DOCUMENT_FRAGMENT_NODE:
3244 case PROCESSING_INSTRUCTION_NODE:
3246 case DOCUMENT_TYPE_NODE:
3248 // Documents may contain no more than one of each of these.
3249 // (One Element and one DocumentType.)
3250 for (Node* c = firstChild(); c; c = c->nextSibling())
3251 if (c->nodeType() == type)
3258 bool Document::canReplaceChild(const Node& newChild, const Node& oldChild) const
3260 if (oldChild.nodeType() == newChild.nodeType())
3263 int numDoctypes = 0;
3264 int numElements = 0;
3266 // First, check how many doctypes and elements we have, not counting
3267 // the child we're about to remove.
3268 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3272 switch (c->nodeType()) {
3273 case DOCUMENT_TYPE_NODE:
3284 // Then, see how many doctypes and elements might be added by the new child.
3285 if (newChild.isDocumentFragment()) {
3286 for (Node* c = toDocumentFragment(newChild).firstChild(); c; c = c->nextSibling()) {
3287 switch (c->nodeType()) {
3288 case ATTRIBUTE_NODE:
3289 case CDATA_SECTION_NODE:
3290 case DOCUMENT_FRAGMENT_NODE:
3295 case PROCESSING_INSTRUCTION_NODE:
3297 case DOCUMENT_TYPE_NODE:
3306 switch (newChild.nodeType()) {
3307 case ATTRIBUTE_NODE:
3308 case CDATA_SECTION_NODE:
3309 case DOCUMENT_FRAGMENT_NODE:
3314 case PROCESSING_INSTRUCTION_NODE:
3316 case DOCUMENT_TYPE_NODE:
3325 if (numElements > 1 || numDoctypes > 1)
3331 PassRefPtrWillBeRawPtr<Node> Document::cloneNode(bool deep)
3333 RefPtrWillBeRawPtr<Document> clone = cloneDocumentWithoutChildren();
3334 clone->cloneDataFromDocument(*this);
3336 cloneChildNodes(clone.get());
3337 return clone.release();
3340 PassRefPtrWillBeRawPtr<Document> Document::cloneDocumentWithoutChildren()
3342 DocumentInit init(url());
3343 if (isXMLDocument()) {
3344 if (isXHTMLDocument())
3345 return XMLDocument::createXHTML(init.withRegistrationContext(registrationContext()));
3346 return XMLDocument::create(init);
3348 return create(init);
3351 void Document::cloneDataFromDocument(const Document& other)
3353 setCompatibilityMode(other.compatibilityMode());
3354 setEncodingData(other.m_encodingData);
3355 setContextFeatures(other.contextFeatures());
3356 setSecurityOrigin(other.securityOrigin()->isolatedCopy());
3357 setMimeType(other.contentType());
3360 StyleSheetList* Document::styleSheets()
3362 if (!m_styleSheetList)
3363 m_styleSheetList = StyleSheetList::create(this);
3364 return m_styleSheetList.get();
3367 String Document::preferredStylesheetSet() const
3369 return m_styleEngine->preferredStylesheetSetName();
3372 String Document::selectedStylesheetSet() const
3374 return m_styleEngine->selectedStylesheetSetName();
3377 void Document::setSelectedStylesheetSet(const String& aString)
3379 m_styleEngine->setSelectedStylesheetSetName(aString);
3380 styleResolverChanged();
3383 void Document::evaluateMediaQueryListIfNeeded()
3385 if (!m_evaluateMediaQueriesOnStyleRecalc)
3387 evaluateMediaQueryList();
3388 m_evaluateMediaQueriesOnStyleRecalc = false;
3391 void Document::evaluateMediaQueryList()
3393 if (m_mediaQueryMatcher)
3394 m_mediaQueryMatcher->mediaFeaturesChanged();
3397 void Document::notifyResizeForViewportUnits()
3399 if (m_mediaQueryMatcher)
3400 m_mediaQueryMatcher->viewportChanged();
3401 if (!hasViewportUnits())
3403 ensureStyleResolver().notifyResizeForViewportUnits();
3404 setNeedsStyleRecalcForViewportUnits();
3407 void Document::styleResolverChanged(StyleResolverUpdateMode updateMode)
3409 // styleResolverChanged() can be invoked during Document destruction.
3410 // We just skip that case.
3414 m_styleEngine->resolverChanged(updateMode);
3416 if (didLayoutWithPendingStylesheets() && !m_styleEngine->hasPendingSheets()) {
3417 // We need to manually repaint because we avoid doing all repaints in layout or style
3418 // recalc while sheets are still loading to avoid FOUC.
3419 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3421 ASSERT(renderView() || importsController());
3423 renderView()->invalidatePaintForViewAndCompositedLayers();
3427 void Document::styleResolverMayHaveChanged()
3429 styleResolverChanged(hasNodesWithPlaceholderStyle() ? FullStyleUpdate : AnalyzedStyleUpdate);
3432 void Document::setHoverNode(PassRefPtrWillBeRawPtr<Node> newHoverNode)
3434 m_hoverNode = newHoverNode;
3437 void Document::setActiveHoverElement(PassRefPtrWillBeRawPtr<Element> newActiveElement)
3439 if (!newActiveElement) {
3440 m_activeHoverElement.clear();
3444 m_activeHoverElement = newActiveElement;
3447 void Document::removeFocusedElementOfSubtree(Node* node, bool amongChildrenOnly)
3449 if (!m_focusedElement)
3452 // We can't be focused if we're not in the document.
3453 if (!node->inDocument())
3455 bool contains = node->containsIncludingShadowDOM(m_focusedElement.get());
3456 if (contains && (m_focusedElement != node || !amongChildrenOnly))
3457 setFocusedElement(nullptr);
3460 void Document::hoveredNodeDetached(Node* node)
3465 if (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != NodeRenderingTraversal::parent(m_hoverNode.get())))
3468 m_hoverNode = NodeRenderingTraversal::parent(node);
3469 while (m_hoverNode && !m_hoverNode->renderer())
3470 m_hoverNode = NodeRenderingTraversal::parent(m_hoverNode.get());
3472 // If the mouse cursor is not visible, do not clear existing
3473 // hover effects on the ancestors of |node| and do not invoke
3474 // new hover effects on any other element.
3475 if (!page()->isCursorVisible())
3479 frame()->eventHandler().scheduleHoverStateUpdate();
3482 void Document::activeChainNodeDetached(Node* node)
3484 if (!m_activeHoverElement)
3487 if (node != m_activeHoverElement)
3490 Node* activeNode = NodeRenderingTraversal::parent(node);
3491 while (activeNode && activeNode->isElementNode() && !activeNode->renderer())
3492 activeNode = NodeRenderingTraversal::parent(activeNode);
3494 m_activeHoverElement = activeNode && activeNode->isElementNode() ? toElement(activeNode) : 0;
3497 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3499 return m_annotatedRegions;
3502 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3504 m_annotatedRegions = regions;
3505 setAnnotatedRegionsDirty(false);
3508 bool Document::setFocusedElement(PassRefPtrWillBeRawPtr<Element> prpNewFocusedElement, FocusType type)
3510 m_clearFocusedElementTimer.stop();
3512 RefPtrWillBeRawPtr<Element> newFocusedElement = prpNewFocusedElement;
3514 // Make sure newFocusedNode is actually in this document
3515 if (newFocusedElement && (newFocusedElement->document() != this))
3518 if (NodeChildRemovalTracker::isBeingRemoved(newFocusedElement.get()))
3521 if (m_focusedElement == newFocusedElement)
3524 bool focusChangeBlocked = false;
3525 RefPtrWillBeRawPtr<Element> oldFocusedElement = m_focusedElement;
3526 m_focusedElement = nullptr;
3528 // Remove focus from the existing focus node (if any)
3529 if (oldFocusedElement) {
3530 ASSERT(!oldFocusedElement->inDetach());
3532 if (oldFocusedElement->active())
3533 oldFocusedElement->setActive(false);
3535 oldFocusedElement->setFocus(false);
3537 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3538 // If page lost focus, blur event will have already been dispatched
3539 if (page() && (page()->focusController().isFocused())) {
3540 oldFocusedElement->dispatchBlurEvent(newFocusedElement.get());
3542 if (m_focusedElement) {
3543 // handler shifted focus
3544 focusChangeBlocked = true;
3545 newFocusedElement = nullptr;
3548 oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::focusout, newFocusedElement.get()); // DOM level 3 name for the bubbling blur event.
3549 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3550 // on it, probably when <rdar://problem/8503958> is resolved.
3551 oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, newFocusedElement.get()); // DOM level 2 name for compatibility.
3553 if (m_focusedElement) {
3554 // handler shifted focus
3555 focusChangeBlocked = true;
3556 newFocusedElement = nullptr;
3561 Widget* oldWidget = widgetForElement(*oldFocusedElement);
3563 oldWidget->setFocus(false);
3565 view()->setFocus(false);
3569 if (newFocusedElement && newFocusedElement->isFocusable()) {
3570 if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(*newFocusedElement)) {
3571 // delegate blocks focus change
3572 focusChangeBlocked = true;
3573 goto SetFocusedElementDone;
3575 // Set focus on the new node
3576 m_focusedElement = newFocusedElement;
3578 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3579 // If page lost focus, event will be dispatched on page focus, don't duplicate
3580 if (page() && (page()->focusController().isFocused())) {
3581 m_focusedElement->dispatchFocusEvent(oldFocusedElement.get(), type);
3584 if (m_focusedElement != newFocusedElement) {
3585 // handler shifted focus
3586 focusChangeBlocked = true;
3587 goto SetFocusedElementDone;
3590 m_focusedElement->dispatchFocusInEvent(EventTypeNames::focusin, oldFocusedElement.get(), type); // DOM level 3 bubbling focus event.
3592 if (m_focusedElement != newFocusedElement) {
3593 // handler shifted focus
3594 focusChangeBlocked = true;
3595 goto SetFocusedElementDone;
3598 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3599 // on it, probably when <rdar://problem/8503958> is m.
3600 m_focusedElement->dispatchFocusInEvent(EventTypeNames::DOMFocusIn, oldFocusedElement.get(), type); // DOM level 2 for compatibility.
3602 if (m_focusedElement != newFocusedElement) {
3603 // handler shifted focus
3604 focusChangeBlocked = true;
3605 goto SetFocusedElementDone;
3609 m_focusedElement->setFocus(true);
3611 if (m_focusedElement->isRootEditableElement())
3612 frame()->spellChecker().didBeginEditing(m_focusedElement.get());
3614 // eww, I suck. set the qt focus correctly
3615 // ### find a better place in the code for this
3617 Widget* focusWidget = widgetForElement(*m_focusedElement);
3619 // Make sure a widget has the right size before giving it focus.
3620 // Otherwise, we are testing edge cases of the Widget code.
3621 // Specifically, in WebCore this does not work well for text fields.
3623 // Re-get the widget in case updating the layout changed things.
3624 focusWidget = widgetForElement(*m_focusedElement);
3627 focusWidget->setFocus(true);
3629 view()->setFocus(true);
3633 if (!focusChangeBlocked && m_focusedElement) {
3634 // Create the AXObject cache in a focus change because Chromium relies on it.
3635 if (AXObjectCache* cache = axObjectCache())
3636 cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
3639 if (!focusChangeBlocked && frameHost())
3640 frameHost()->chrome().focusedNodeChanged(m_focusedElement.get());
3642 SetFocusedElementDone:
3643 updateRenderTreeIfNeeded();
3644 if (LocalFrame* frame = this->frame())
3645 frame->selection().didChangeFocus();
3646 return !focusChangeBlocked;
3649 void Document::setCSSTarget(Element* newTarget)
3652 m_cssTarget->pseudoStateChanged(CSSSelector::PseudoTarget);
3653 m_cssTarget = newTarget;
3655 m_cssTarget->pseudoStateChanged(CSSSelector::PseudoTarget);
3658 void Document::registerNodeList(const LiveNodeListBase* list)
3661 m_nodeLists[list->invalidationType()].add(list);
3663 m_nodeListCounts[list->invalidationType()]++;
3665 if (list->isRootedAtDocument())
3666 m_listsInvalidatedAtDocument.add(list);
3669 void Document::unregisterNodeList(const LiveNodeListBase* list)
3672 ASSERT(m_nodeLists[list->invalidationType()].contains(list));
3673 m_nodeLists[list->invalidationType()].remove(list);
3675 m_nodeListCounts[list->invalidationType()]--;
3677 if (list->isRootedAtDocument()) {
3678 ASSERT(m_listsInvalidatedAtDocument.contains(list));
3679 m_listsInvalidatedAtDocument.remove(list);
3683 void Document::registerNodeListWithIdNameCache(const LiveNodeListBase* list)
3686 m_nodeLists[InvalidateOnIdNameAttrChange].add(list);
3688 m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
3692 void Document::unregisterNodeListWithIdNameCache(const LiveNodeListBase* list)
3695 ASSERT(m_nodeLists[InvalidateOnIdNameAttrChange].contains(list));
3696 m_nodeLists[InvalidateOnIdNameAttrChange].remove(list);
3698 ASSERT(m_nodeListCounts[InvalidateOnIdNameAttrChange] > 0);
3699 m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
3703 void Document::attachNodeIterator(NodeIterator* ni)
3705 m_nodeIterators.add(ni);
3708 void Document::detachNodeIterator(NodeIterator* ni)
3710 // The node iterator can be detached without having been attached if its root node didn't have a document
3711 // when the iterator was created, but has it now.
3712 m_nodeIterators.remove(ni);
3715 void Document::moveNodeIteratorsToNewDocument(Node& node, Document& newDocument)
3717 WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> > nodeIteratorsList = m_nodeIterators;
3718 WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3719 for (WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3720 if ((*it)->root() == node) {
3721 detachNodeIterator(*it);
3722 newDocument.attachNodeIterator(*it);
3727 void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
3729 if (!m_ranges.isEmpty()) {
3730 AttachedRangeSet::const_iterator end = m_ranges.end();
3731 for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3732 (*it)->nodeChildrenChanged(container);
3736 void Document::updateRangesAfterNodeMovedToAnotherDocument(const Node& node)
3738 ASSERT(node.document() != this);
3739 if (m_ranges.isEmpty())
3741 AttachedRangeSet ranges = m_ranges;
3742 AttachedRangeSet::const_iterator end = ranges.end();
3743 for (AttachedRangeSet::const_iterator it = ranges.begin(); it != end; ++it)
3744 (*it)->updateOwnerDocumentIfNeeded();
3747 void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
3749 EventDispatchForbiddenScope assertNoEventDispatch;
3750 if (!m_ranges.isEmpty()) {
3751 AttachedRangeSet::const_iterator end = m_ranges.end();
3752 for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3753 (*it)->nodeChildrenWillBeRemoved(container);
3756 WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3757 for (WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
3758 for (Node* n = container.firstChild(); n; n = n->nextSibling())
3759 (*it)->nodeWillBeRemoved(*n);
3762 if (LocalFrame* frame = this->frame()) {
3763 for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
3764 frame->eventHandler().nodeWillBeRemoved(*n);
3765 frame->selection().nodeWillBeRemoved(*n);
3766 frame->page()->dragCaretController().nodeWillBeRemoved(*n);
3771 void Document::nodeWillBeRemoved(Node& n)
3773 WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3774 for (WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3775 (*it)->nodeWillBeRemoved(n);
3777 if (!m_ranges.isEmpty()) {
3778 AttachedRangeSet::const_iterator rangesEnd = m_ranges.end();
3779 for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3780 (*it)->nodeWillBeRemoved(n);
3783 if (LocalFrame* frame = this->frame()) {
3784 frame->eventHandler().nodeWillBeRemoved(n);
3785 frame->selection().nodeWillBeRemoved(n);
3786 frame->page()->dragCaretController().nodeWillBeRemoved(n);
3790 void Document::didInsertText(Node* text, unsigned offset, unsigned length)
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)->didInsertText(text, offset, length);
3798 // Update the markers for spelling and grammar checking.
3799 m_markers->shiftMarkers(text, offset, length);
3802 void Document::didRemoveText(Node* text, unsigned offset, unsigned length)
3804 if (!m_ranges.isEmpty()) {
3805 AttachedRangeSet::const_iterator end = m_ranges.end();
3806 for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3807 (*it)->didRemoveText(text, offset, length);
3810 // Update the markers for spelling and grammar checking.
3811 m_markers->removeMarkers(text, offset, length);
3812 m_markers->shiftMarkers(text, offset + length, 0 - length);
3815 void Document::didMergeTextNodes(Text& oldNode, unsigned offset)
3817 if (!m_ranges.isEmpty()) {
3818 NodeWithIndex oldNodeWithIndex(oldNode);
3819 AttachedRangeSet::const_iterator end = m_ranges.end();
3820 for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3821 (*it)->didMergeTextNodes(oldNodeWithIndex, offset);
3825 m_frame->selection().didMergeTextNodes(oldNode, offset);
3827 // FIXME: This should update markers for spelling and grammar checking.
3830 void Document::didSplitTextNode(Text& oldNode)
3832 if (!m_ranges.isEmpty()) {
3833 AttachedRangeSet::const_iterator end = m_ranges.end();
3834 for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3835 (*it)->didSplitTextNode(oldNode);
3839 m_frame->selection().didSplitTextNode(oldNode);
3841 // FIXME: This should update markers for spelling and grammar checking.
3844 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3846 LocalDOMWindow* domWindow = this->domWindow();
3849 domWindow->setAttributeEventListener(eventType, listener);
3852 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3854 LocalDOMWindow* domWindow = this->domWindow();
3857 return domWindow->getAttributeEventListener(eventType);
3860 EventQueue* Document::eventQueue() const
3864 return m_domWindow->eventQueue();
3867 void Document::enqueueAnimationFrameEvent(PassRefPtrWillBeRawPtr<Event> event)
3869 ensureScriptedAnimationController().enqueueEvent(event);
3872 void Document::enqueueUniqueAnimationFrameEvent(PassRefPtrWillBeRawPtr<Event> event)
3874 ensureScriptedAnimationController().enqueuePerFrameEvent(event);
3877 void Document::enqueueScrollEventForNode(Node* target)
3879 // Per the W3C CSSOM View Module only scroll events fired at the document should bubble.
3880 RefPtrWillBeRawPtr<Event> scrollEvent = target->isDocumentNode() ? Event::createBubble(EventTypeNames::scroll) : Event::create(EventTypeNames::scroll);
3881 scrollEvent->setTarget(target);
3882 ensureScriptedAnimationController().enqueuePerFrameEvent(scrollEvent.release());
3885 void Document::enqueueResizeEvent()
3887 RefPtrWillBeRawPtr<Event> event = Event::create(EventTypeNames::resize);
3888 event->setTarget(domWindow());
3889 ensureScriptedAnimationController().enqueuePerFrameEvent(event.release());
3892 void Document::enqueueMediaQueryChangeListeners(WillBeHeapVector<RefPtrWillBeMember<MediaQueryListListener> >& listeners)
3894 ensureScriptedAnimationController().enqueueMediaQueryChangeListeners(listeners);
3897 Document::EventFactorySet& Document::eventFactories()
3899 DEFINE_STATIC_LOCAL(EventFactorySet, s_eventFactory, ());
3900 return s_eventFactory;
3903 void Document::registerEventFactory(PassOwnPtr<EventFactoryBase> eventFactory)
3905 ASSERT(!eventFactories().contains(eventFactory.get()));
3906 eventFactories().add(eventFactory);
3909 PassRefPtrWillBeRawPtr<Event> Document::createEvent(const String& eventType, ExceptionState& exceptionState)
3911 RefPtrWillBeRawPtr<Event> event = nullptr;
3912 for (EventFactorySet::const_iterator it = eventFactories().begin(); it != eventFactories().end(); ++it) {
3913 event = (*it)->create(eventType);
3915 return event.release();
3917 exceptionState.throwDOMException(NotSupportedError, "The provided event type ('" + eventType + "') is invalid.");
3921 void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
3923 if (ContextFeatures::mutationEventsEnabled(this))
3924 addListenerType(listenerType);
3927 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
3929 if (eventType == EventTypeNames::DOMSubtreeModified) {
3930 UseCounter::count(*this, UseCounter::DOMSubtreeModifiedEvent);
3931 addMutationEventListenerTypeIfEnabled(DOMSUBTREEMODIFIED_LISTENER);
3932 } else if (eventType == EventTypeNames::DOMNodeInserted) {
3933 UseCounter::count(*this, UseCounter::DOMNodeInsertedEvent);
3934 addMutationEventListenerTypeIfEnabled(DOMNODEINSERTED_LISTENER);
3935 } else if (eventType == EventTypeNames::DOMNodeRemoved) {
3936 UseCounter::count(*this, UseCounter::DOMNodeRemovedEvent);
3937 addMutationEventListenerTypeIfEnabled(DOMNODEREMOVED_LISTENER);
3938 } else if (eventType == EventTypeNames::DOMNodeRemovedFromDocument) {
3939 UseCounter::count(*this, UseCounter::DOMNodeRemovedFromDocumentEvent);
3940 addMutationEventListenerTypeIfEnabled(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
3941 } else if (eventType == EventTypeNames::DOMNodeInsertedIntoDocument) {
3942 UseCounter::count(*this, UseCounter::DOMNodeInsertedIntoDocumentEvent);
3943 addMutationEventListenerTypeIfEnabled(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
3944 } else if (eventType == EventTypeNames::DOMCharacterDataModified) {
3945 UseCounter::count(*this, UseCounter::DOMCharacterDataModifiedEvent);
3946 addMutationEventListenerTypeIfEnabled(DOMCHARACTERDATAMODIFIED_LISTENER);
3947 } else if (eventType == EventTypeNames::overflowchanged) {
3948 UseCounter::countDeprecation(*this, UseCounter::OverflowChangedEvent);
3949 addListenerType(OVERFLOWCHANGED_LISTENER);
3950 } else if (eventType == EventTypeNames::webkitAnimationStart || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationstart)) {
3951 addListenerType(ANIMATIONSTART_LISTENER);
3952 } else if (eventType == EventTypeNames::webkitAnimationEnd || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationend)) {
3953 addListenerType(ANIMATIONEND_LISTENER);
3954 } else if (eventType == EventTypeNames::webkitAnimationIteration || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationiteration)) {
3955 addListenerType(ANIMATIONITERATION_LISTENER);
3956 } else if (eventType == EventTypeNames::webkitTransitionEnd || eventType == EventTypeNames::transitionend) {
3957 addListenerType(TRANSITIONEND_LISTENER);
3958 } else if (eventType == EventTypeNames::scroll) {
3959 addListenerType(SCROLL_LISTENER);
3963 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
3968 HTMLFrameOwnerElement* Document::ownerElement() const
3972 // FIXME: This probably breaks the attempts to layout after a load is finished in implicitClose(), and probably tons of other things...
3973 return frame()->deprecatedLocalOwner();
3976 bool Document::isInInvisibleSubframe() const
3978 if (!ownerElement())
3979 return false; // this is the root element
3982 return !frame()->ownerRenderer();
3985 String Document::cookie(ExceptionState& exceptionState) const
3987 if (settings() && !settings()->cookieEnabled())
3990 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3991 // InvalidStateError exception on getting if the Document has no
3992 // browsing context.
3994 if (!securityOrigin()->canAccessCookies()) {
3995 if (isSandboxed(SandboxOrigin))
3996 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
3997 else if (url().protocolIs("data"))
3998 exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
4000 exceptionState.throwSecurityError("Access is denied for this document.");
4004 KURL cookieURL = this->cookieURL();
4005 if (cookieURL.isEmpty())
4008 return cookies(this, cookieURL);
4011 void Document::setCookie(const String& value, ExceptionState& exceptionState)
4013 if (settings() && !settings()->cookieEnabled())
4016 // FIXME: The HTML5 DOM spec states that this attribute can raise an
4017 // InvalidStateError exception on setting if the Document has no
4018 // browsing context.
4020 if (!securityOrigin()->canAccessCookies()) {
4021 if (isSandboxed(SandboxOrigin))
4022 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
4023 else if (url().protocolIs("data"))
4024 exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
4026 exceptionState.throwSecurityError("Access is denied for this document.");
4030 KURL cookieURL = this->cookieURL();
4031 if (cookieURL.isEmpty())
4034 setCookies(this, cookieURL, value);
4037 const AtomicString& Document::referrer() const
4040 return loader()->request().httpReferrer();
4044 String Document::domain() const
4046 return securityOrigin()->domain();
4049 void Document::setDomain(const String& newDomain, ExceptionState& exceptionState)
4051 if (isSandboxed(SandboxDocumentDomain)) {
4052 exceptionState.throwSecurityError("Assignment is forbidden for sandboxed iframes.");
4056 if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
4057 exceptionState.throwSecurityError("Assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme.");
4061 if (newDomain.isEmpty()) {
4062 exceptionState.throwSecurityError("'" + newDomain + "' is an empty domain.");
4066 OriginAccessEntry::IPAddressSetting ipAddressSetting = settings() && settings()->treatIPAddressAsDomain() ? OriginAccessEntry::TreatIPAddressAsDomain : OriginAccessEntry::TreatIPAddressAsIPAddress;
4067 OriginAccessEntry accessEntry(securityOrigin()->protocol(), newDomain, OriginAccessEntry::AllowSubdomains, ipAddressSetting);
4068 OriginAccessEntry::MatchResult result = accessEntry.matchesOrigin(*securityOrigin());
4069 if (result == OriginAccessEntry::DoesNotMatchOrigin) {
4070 exceptionState.throwSecurityError("'" + newDomain + "' is not a suffix of '" + domain() + "'.");
4074 if (result == OriginAccessEntry::MatchesOriginButIsPublicSuffix) {
4075 exceptionState.throwSecurityError("'" + newDomain + "' is a top-level domain.");
4079 securityOrigin()->setDomainFromDOM(newDomain);
4081 m_frame->script().updateSecurityOrigin(securityOrigin());
4084 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
4085 String Document::lastModified() const
4087 DateComponents date;
4088 bool foundDate = false;
4090 if (DocumentLoader* documentLoader = loader()) {
4091 const AtomicString& httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
4092 if (!httpLastModified.isEmpty()) {
4093 date.setMillisecondsSinceEpochForDateTime(convertToLocalTime(parseDate(httpLastModified)));
4098 // FIXME: If this document came from the file system, the HTML5
4099 // specificiation tells us to read the last modification date from the file
4102 date.setMillisecondsSinceEpochForDateTime(convertToLocalTime(currentTimeMS()));
4103 return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
4106 const KURL& Document::firstPartyForCookies() const
4108 return topDocument().url();
4111 static bool isValidNameNonASCII(const LChar* characters, unsigned length)
4113 if (!isValidNameStart(characters[0]))
4116 for (unsigned i = 1; i < length; ++i) {
4117 if (!isValidNamePart(characters[i]))
4124 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
4126 for (unsigned i = 0; i < length;) {
4127 bool first = i == 0;
4129 U16_NEXT(characters, i, length, c); // Increments i.
4130 if (first ? !isValidNameStart(c) : !isValidNamePart(c))
4137 template<typename CharType>
4138 static inline bool isValidNameASCII(const CharType* characters, unsigned length)
4140 CharType c = characters[0];
4141 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
4144 for (unsigned i = 1; i < length; ++i) {
4146 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
4153 bool Document::isValidName(const String& name)
4155 unsigned length = name.length();
4159 if (name.is8Bit()) {
4160 const LChar* characters = name.characters8();
4162 if (isValidNameASCII(characters, length))
4165 return isValidNameNonASCII(characters, length);
4168 const UChar* characters = name.characters16();
4170 if (isValidNameASCII(characters, length))
4173 return isValidNameNonASCII(characters, length);
4176 enum QualifiedNameStatus {
4185 struct ParseQualifiedNameResult {
4186 QualifiedNameStatus status;
4188 ParseQualifiedNameResult() { }
4189 explicit ParseQualifiedNameResult(QualifiedNameStatus status) : status(status) { }
4190 ParseQualifiedNameResult(QualifiedNameStatus status, UChar32 character) : status(status), character(character) { }
4193 template<typename CharType>
4194 static ParseQualifiedNameResult parseQualifiedNameInternal(const AtomicString& qualifiedName, const CharType* characters, unsigned length, AtomicString& prefix, AtomicString& localName)
4196 bool nameStart = true;
4197 bool sawColon = false;
4200 for (unsigned i = 0; i < length;) {
4202 U16_NEXT(characters, i, length, c)
4205 return ParseQualifiedNameResult(QNMultipleColons);
4209 } else if (nameStart) {
4210 if (!isValidNameStart(c))
4211 return ParseQualifiedNameResult(QNInvalidStartChar, c);
4214 if (!isValidNamePart(c))
4215 return ParseQualifiedNameResult(QNInvalidChar, c);
4221 localName = qualifiedName;
4223 prefix = AtomicString(characters, colonPos);
4224 if (prefix.isEmpty())
4225 return ParseQualifiedNameResult(QNEmptyPrefix);
4226 int prefixStart = colonPos + 1;
4227 localName = AtomicString(characters + prefixStart, length - prefixStart);
4230 if (localName.isEmpty())
4231 return ParseQualifiedNameResult(QNEmptyLocalName);
4233 return ParseQualifiedNameResult(QNValid);
4236 bool Document::parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
4238 unsigned length = qualifiedName.length();
4241 exceptionState.throwDOMException(InvalidCharacterError, "The qualified name provided is empty.");
4245 ParseQualifiedNameResult returnValue;
4246 if (qualifiedName.is8Bit())
4247 returnValue = parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName);
4249 returnValue = parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName);
4250 if (returnValue.status == QNValid)
4253 StringBuilder message;
4254 message.appendLiteral("The qualified name provided ('");
4255 message.append(qualifiedName);
4256 message.appendLiteral("') ");
4258 if (returnValue.status == QNMultipleColons) {
4259 message.appendLiteral("contains multiple colons.");
4260 } else if (returnValue.status == QNInvalidStartChar) {
4261 message.appendLiteral("contains the invalid name-start character '");
4262 message.append(returnValue.character);
4263 message.appendLiteral("'.");
4264 } else if (returnValue.status == QNInvalidChar) {
4265 message.appendLiteral("contains the invalid character '");
4266 message.append(returnValue.character);
4267 message.appendLiteral("'.");
4268 } else if (returnValue.status == QNEmptyPrefix) {
4269 message.appendLiteral("has an empty namespace prefix.");
4271 ASSERT(returnValue.status == QNEmptyLocalName);
4272 message.appendLiteral("has an empty local name.");
4275 if (returnValue.status == QNInvalidStartChar || returnValue.status == QNInvalidChar)
4276 exceptionState.throwDOMException(InvalidCharacterError, message.toString());
4278 exceptionState.throwDOMException(NamespaceError, message.toString());
4282 void Document::setEncodingData(const DocumentEncodingData& newData)
4284 // It's possible for the encoding of the document to change while we're decoding
4285 // data. That can only occur while we're processing the <head> portion of the
4286 // document. There isn't much user-visible content in the <head>, but there is
4287 // the <title> element. This function detects that situation and re-decodes the
4288 // document's title so that the user doesn't see an incorrectly decoded title
4289 // in the title bar.
4291 && encoding() != newData.encoding()
4292 && !ElementTraversal::firstWithin(*m_titleElement)
4293 && encoding() == Latin1Encoding()
4294 && m_titleElement->textContent().containsOnlyLatin1()) {
4296 CString originalBytes = m_titleElement->textContent().latin1();
4297 OwnPtr<TextCodec> codec = newTextCodec(newData.encoding());
4298 String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), DataEOF);
4299 m_titleElement->setTextContent(correctlyDecodedTitle);
4302 m_encodingData = newData;
4304 // FIXME: Should be removed as part of https://code.google.com/p/chromium/issues/detail?id=319643
4305 bool shouldUseVisualOrdering = m_encodingData.encoding().usesVisualOrdering();
4306 if (shouldUseVisualOrdering != m_visuallyOrdered) {
4307 m_visuallyOrdered = shouldUseVisualOrdering;
4308 // FIXME: How is possible to not have a renderer here?
4310 renderView()->style()->setRTLOrdering(m_visuallyOrdered ? VisualOrder : LogicalOrder);
4311 setNeedsStyleRecalc(SubtreeStyleChange);
4315 KURL Document::completeURL(const String& url) const
4317 return completeURLWithOverride(url, m_baseURL);
4320 KURL Document::completeURLWithOverride(const String& url, const KURL& baseURLOverride) const
4322 // Always return a null URL when passed a null string.
4323 // FIXME: Should we change the KURL constructor to have this behavior?
4324 // See also [CSS]StyleSheet::completeURL(const String&)
4327 // This logic is deliberately spread over many statements in an attempt to track down http://crbug.com/312410.
4328 const KURL* baseURLFromParent = 0;
4329 bool shouldUseParentBaseURL = baseURLOverride.isEmpty();
4330 if (!shouldUseParentBaseURL) {
4331 const KURL& aboutBlankURL = blankURL();
4332 shouldUseParentBaseURL = (baseURLOverride == aboutBlankURL);
4334 if (shouldUseParentBaseURL) {
4335 if (Document* parent = parentDocument())
4336 baseURLFromParent = &parent->baseURL();
4338 const KURL& baseURL = baseURLFromParent ? *baseURLFromParent : baseURLOverride;
4339 if (!encoding().isValid())
4340 return KURL(baseURL, url);
4341 return KURL(baseURL, url, encoding());
4344 // Support for Javascript execCommand, and related methods
4346 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
4348 LocalFrame* frame = document->frame();
4349 if (!frame || frame->document() != document)
4350 return Editor::Command();
4352 document->updateRenderTreeIfNeeded();
4353 return frame->editor().command(commandName, userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
4356 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
4358 // We don't allow recusrive |execCommand()| to protect against attack code.
4359 // Recursive call of |execCommand()| could be happened by moving iframe
4360 // with script triggered by insertion, e.g. <iframe src="javascript:...">
4361 // <iframe onload="...">. This usage is valid as of the specification
4362 // although, it isn't common use case, rather it is used as attack code.
4363 static bool inExecCommand = false;
4364 if (inExecCommand) {
4365 String message = "We don't execute document.execCommand() this time, because it is called recursively.";
4366 addConsoleMessage(ConsoleMessage::create(JSMessageSource, WarningMessageLevel, message));
4369 TemporaryChange<bool> executeScope(inExecCommand, true);
4371 // Postpone DOM mutation events, which can execute scripts and change
4372 // DOM tree against implementation assumption.
4373 EventQueueScope eventQueueScope;
4374 Editor::Command editorCommand = command(this, commandName, userInterface);
4375 Platform::current()->histogramSparse("WebCore.Document.execCommand", editorCommand.idForHistogram());
4376 return editorCommand.execute(value);
4379 bool Document::queryCommandEnabled(const String& commandName)
4381 return command(this, commandName).isEnabled();
4384 bool Document::queryCommandIndeterm(const String& commandName)
4386 return command(this, commandName).state() == MixedTriState;
4389 bool Document::queryCommandState(const String& commandName)
4391 return command(this, commandName).state() == TrueTriState;
4394 bool Document::queryCommandSupported(const String& commandName)
4396 return command(this, commandName).isSupported();
4399 String Document::queryCommandValue(const String& commandName)
4401 return command(this, commandName).value();
4404 KURL Document::openSearchDescriptionURL()
4406 static const char openSearchMIMEType[] = "application/opensearchdescription+xml";
4407 static const char openSearchRelation[] = "search";
4409 // FIXME: Why do only top-level frames have openSearchDescriptionURLs?
4410 if (!frame() || frame()->tree().parent())
4413 // FIXME: Why do we need to wait for FrameStateComplete?
4414 if (frame()->loader().state() != FrameStateComplete)
4420 for (HTMLLinkElement* linkElement = Traversal<HTMLLinkElement>::firstChild(*head()); linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4421 if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
4423 if (linkElement->href().isEmpty())
4425 return linkElement->href();
4431 void Document::pushCurrentScript(PassRefPtrWillBeRawPtr<HTMLScriptElement> newCurrentScript)
4433 ASSERT(newCurrentScript);
4434 m_currentScriptStack.append(newCurrentScript);
4437 void Document::popCurrentScript()
4439 ASSERT(!m_currentScriptStack.isEmpty());
4440 m_currentScriptStack.removeLast();
4443 void Document::applyXSLTransform(ProcessingInstruction* pi)
4445 ASSERT(!pi->isLoading());
4446 UseCounter::count(*this, UseCounter::XSLProcessingInstruction);
4447 RefPtrWillBeRawPtr<XSLTProcessor> processor = XSLTProcessor::create(*this);
4448 processor->setXSLStyleSheet(toXSLStyleSheet(pi->sheet()));
4449 String resultMIMEType;
4451 String resultEncoding;
4452 if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
4454 // FIXME: If the transform failed we should probably report an error (like Mozilla does).
4455 LocalFrame* ownerFrame = frame();
4456 processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, ownerFrame);
4457 InspectorInstrumentation::frameDocumentUpdated(ownerFrame);
4460 void Document::setTransformSource(PassOwnPtr<TransformSource> source)
4462 m_transformSource = source;
4465 void Document::setDesignMode(InheritedBool value)
4467 m_designMode = value;
4468 for (Frame* frame = m_frame; frame; frame = frame->tree().traverseNext(m_frame)) {
4469 if (!frame->isLocalFrame())
4471 if (!toLocalFrame(frame)->document())
4473 toLocalFrame(frame)->document()->setNeedsStyleRecalc(SubtreeStyleChange);
4477 Document::InheritedBool Document::getDesignMode() const
4479 return m_designMode;
4482 bool Document::inDesignMode() const
4484 for (const Document* d = this; d; d = d->parentDocument()) {
4485 if (d->m_designMode != inherit)
4486 return d->m_designMode;
4491 String Document::designMode() const
4493 return inDesignMode() ? "on" : "off";
4496 void Document::setDesignMode(const String& value)
4499 if (equalIgnoringCase(value, "on"))
4501 else if (equalIgnoringCase(value, "off"))
4505 setDesignMode(mode);
4508 Document* Document::parentDocument() const
4512 Frame* parent = m_frame->tree().parent();
4513 if (!parent || !parent->isLocalFrame())
4515 return toLocalFrame(parent)->document();
4518 Document& Document::topDocument() const
4520 // FIXME: Not clear what topDocument() should do in the OOPI case--should it return the topmost
4521 // available Document, or something else?
4522 Document* doc = const_cast<Document*>(this);
4523 for (HTMLFrameOwnerElement* element = doc->ownerElement(); element; element = doc->ownerElement())
4524 doc = &element->document();
4530 WeakPtrWillBeRawPtr<Document> Document::contextDocument()
4532 if (m_contextDocument)
4533 return m_contextDocument;
4538 return m_weakFactory.createWeakPtr();
4541 return WeakPtrWillBeRawPtr<Document>(nullptr);
4544 PassRefPtrWillBeRawPtr<Attr> Document::createAttribute(const AtomicString& name, ExceptionState& exceptionState)
4546 return createAttributeNS(nullAtom, name, exceptionState, true);
4549 PassRefPtrWillBeRawPtr<Attr> Document::createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState, bool shouldIgnoreNamespaceChecks)
4551 AtomicString prefix, localName;
4552 if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
4555 QualifiedName qName(prefix, localName, namespaceURI);
4557 if (!shouldIgnoreNamespaceChecks && !hasValidNamespaceForAttributes(qName)) {
4558 exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
4562 return Attr::create(*this, qName, emptyAtom);
4565 const SVGDocumentExtensions* Document::svgExtensions()
4567 return m_svgExtensions.get();
4570 SVGDocumentExtensions& Document::accessSVGExtensions()
4572 if (!m_svgExtensions)
4573 m_svgExtensions = adoptPtrWillBeNoop(new SVGDocumentExtensions(this));
4574 return *m_svgExtensions;
4577 bool Document::hasSVGRootNode() const
4579 return isSVGSVGElement(documentElement());
4582 PassRefPtrWillBeRawPtr<HTMLCollection> Document::images()
4584 return ensureCachedCollection<HTMLCollection>(DocImages);
4587 PassRefPtrWillBeRawPtr<HTMLCollection> Document::applets()
4589 return ensureCachedCollection<HTMLCollection>(DocApplets);
4592 PassRefPtrWillBeRawPtr<HTMLCollection> Document::embeds()
4594 return ensureCachedCollection<HTMLCollection>(DocEmbeds);
4597 PassRefPtrWillBeRawPtr<HTMLCollection> Document::scripts()
4599 return ensureCachedCollection<HTMLCollection>(DocScripts);
4602 PassRefPtrWillBeRawPtr<HTMLCollection> Document::links()
4604 return ensureCachedCollection<HTMLCollection>(DocLinks);
4607 PassRefPtrWillBeRawPtr<HTMLCollection> Document::forms()
4609 return ensureCachedCollection<HTMLCollection>(DocForms);
4612 PassRefPtrWillBeRawPtr<HTMLCollection> Document::anchors()
4614 return ensureCachedCollection<HTMLCollection>(DocAnchors);
4617 PassRefPtrWillBeRawPtr<HTMLAllCollection> Document::allForBinding()
4619 UseCounter::count(*this, UseCounter::DocumentAll);
4623 PassRefPtrWillBeRawPtr<HTMLAllCollection> Document::all()
4625 return ensureCachedCollection<HTMLAllCollection>(DocAll);
4628 PassRefPtrWillBeRawPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
4630 return ensureCachedCollection<WindowNameCollection>(WindowNamedItems, name);
4633 PassRefPtrWillBeRawPtr<DocumentNameCollection> Document::documentNamedItems(const AtomicString& name)
4635 return ensureCachedCollection<DocumentNameCollection>(DocumentNamedItems, name);
4638 void Document::finishedParsing()
4640 ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
4641 ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
4643 if (!m_documentTiming.domContentLoadedEventStart)
4644 m_documentTiming.domContentLoadedEventStart = monotonicallyIncreasingTime();
4645 dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
4646 if (!m_documentTiming.domContentLoadedEventEnd)
4647 m_documentTiming.domContentLoadedEventEnd = monotonicallyIncreasingTime();
4649 // The loader's finishedParsing() method may invoke script that causes this object to
4650 // be dereferenced (when this document is in an iframe and the onload causes the iframe's src to change).
4651 // Keep it alive until we are done.
4652 RefPtrWillBeRawPtr<Document> protect(this);
4654 if (RefPtrWillBeRawPtr<LocalFrame> frame = this->frame()) {
4655 // Don't update the render tree if we haven't requested the main resource yet to avoid
4656 // adding extra latency. Note that the first render tree update can be expensive since it
4657 // triggers the parsing of the default stylesheets which are compiled-in.
4658 const bool mainResourceWasAlreadyRequested = frame->loader().stateMachine()->committedFirstRealDocumentLoad();
4660 // FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
4661 // resource loads are complete. HTMLObjectElements can start loading their resources from
4662 // post attach callbacks triggered by recalcStyle(). This means if we parse out an <object>
4663 // tag and then reach the end of the document without updating styles, we might not have yet
4664 // started the resource load and might fire the window load event too early. To avoid this
4665 // we force the styles to be up to date before calling FrameLoader::finishedParsing().
4666 // See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
4667 if (mainResourceWasAlreadyRequested)
4668 updateRenderTreeIfNeeded();
4670 frame->loader().finishedParsing();
4672 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", "data", InspectorMarkLoadEvent::data(frame.get()));
4673 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
4674 InspectorInstrumentation::domContentLoadedEventFired(frame.get());
4677 // Schedule dropping of the ElementDataCache. We keep it alive for a while after parsing finishes
4678 // so that dynamically inserted content can also benefit from sharing optimizations.
4679 // Note that we don't refresh the timer on cache access since that could lead to huge caches being kept
4680 // alive indefinitely by something innocuous like JS setting .innerHTML repeatedly on a timer.
4681 m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
4683 // Parser should have picked up all preloads by now
4684 m_fetcher->clearPreloads();
4687 void Document::elementDataCacheClearTimerFired(Timer<Document>*)
4689 m_elementDataCache.clear();
4692 Vector<IconURL> Document::iconURLs(int iconTypesMask)
4694 IconURL firstFavicon;
4695 IconURL firstTouchIcon;
4696 IconURL firstTouchPrecomposedIcon;
4697 Vector<IconURL> secondaryIcons;
4699 // Start from the last child node so that icons seen later take precedence as required by the spec.
4700 for (HTMLLinkElement* linkElement = head() ? Traversal<HTMLLinkElement>::firstChild(*head()) : 0; linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4701 if (!(linkElement->iconType() & iconTypesMask))
4703 if (linkElement->href().isEmpty())
4705 if (!RuntimeEnabledFeatures::touchIconLoadingEnabled() && linkElement->iconType() != Favicon)
4708 IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
4709 if (linkElement->iconType() == Favicon) {
4710 if (firstFavicon.m_iconType != InvalidIcon)
4711 secondaryIcons.append(firstFavicon);
4712 firstFavicon = newURL;
4713 } else if (linkElement->iconType() == TouchIcon) {
4714 if (firstTouchIcon.m_iconType != InvalidIcon)
4715 secondaryIcons.append(firstTouchIcon);
4716 firstTouchIcon = newURL;
4717 } else if (linkElement->iconType() == TouchPrecomposedIcon) {
4718 if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4719 secondaryIcons.append(firstTouchPrecomposedIcon);
4720 firstTouchPrecomposedIcon = newURL;
4722 ASSERT_NOT_REACHED();
4726 Vector<IconURL> iconURLs;
4727 if (firstFavicon.m_iconType != InvalidIcon)
4728 iconURLs.append(firstFavicon);
4729 else if (m_url.protocolIsInHTTPFamily() && iconTypesMask & Favicon)
4730 iconURLs.append(IconURL::defaultFavicon(m_url));
4732 if (firstTouchIcon.m_iconType != InvalidIcon)
4733 iconURLs.append(firstTouchIcon);
4734 if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4735 iconURLs.append(firstTouchPrecomposedIcon);
4736 for (int i = secondaryIcons.size() - 1; i >= 0; --i)
4737 iconURLs.append(secondaryIcons[i]);
4741 Color Document::themeColor() const
4743 if (!RuntimeEnabledFeatures::themeColorEnabled())
4746 for (HTMLMetaElement* metaElement = head() ? Traversal<HTMLMetaElement>::firstChild(*head()) : 0; metaElement; metaElement = Traversal<HTMLMetaElement>::nextSibling(*metaElement)) {
4747 RGBA32 rgb = Color::transparent;
4748 if (equalIgnoringCase(metaElement->name(), "theme-color") && CSSParser::parseColor(rgb, metaElement->content().string().stripWhiteSpace(), true))
4754 HTMLLinkElement* Document::linkManifest() const
4756 HTMLHeadElement* head = this->head();
4760 // The first link element with a manifest rel must be used. Others are ignored.
4761 for (HTMLLinkElement* linkElement = Traversal<HTMLLinkElement>::firstChild(*head); linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4762 if (!linkElement->relAttribute().isManifest())
4770 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
4772 if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
4775 m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
4776 m_frame->selection().updateSecureKeyboardEntryIfActive();
4779 bool Document::useSecureKeyboardEntryWhenActive() const
4781 return m_useSecureKeyboardEntryWhenActive;
4784 void Document::initSecurityContext()
4786 initSecurityContext(DocumentInit(m_url, m_frame, contextDocument(), m_importsController));
4789 void Document::initSecurityContext(const DocumentInit& initializer)
4791 if (haveInitializedSecurityOrigin()) {
4792 ASSERT(securityOrigin());
4796 if (!initializer.hasSecurityContext()) {
4797 // No source for a security context.
4798 // This can occur via document.implementation.createDocument().
4799 m_cookieURL = KURL(ParsedURLString, emptyString());
4800 setSecurityOrigin(SecurityOrigin::createUnique());
4801 initContentSecurityPolicy();
4805 // In the common case, create the security context from the currently
4806 // loading URL with a fresh content security policy.
4807 m_cookieURL = m_url;
4808 enforceSandboxFlags(initializer.sandboxFlags());
4809 setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
4811 if (importsController()) {
4812 // If this document is an HTML import, grab a reference to it's master document's Content
4813 // Security Policy. We don't call 'initContentSecurityPolicy' in this case, as we can't
4814 // rebind the master document's policy object: its ExecutionContext needs to remain tied
4815 // to the master document.
4816 setContentSecurityPolicy(importsController()->master()->contentSecurityPolicy());
4818 initContentSecurityPolicy();
4821 if (Settings* settings = initializer.settings()) {
4822 if (!settings->webSecurityEnabled()) {
4823 // Web security is turned off. We should let this document access every other document. This is used primary by testing
4824 // harnesses for web sites.
4825 securityOrigin()->grantUniversalAccess();
4826 } else if (securityOrigin()->isLocal()) {
4827 if (settings->allowUniversalAccessFromFileURLs()) {
4828 // Some clients want local URLs to have universal access, but that setting is dangerous for other clients.
4829 securityOrigin()->grantUniversalAccess();
4830 } else if (!settings->allowFileAccessFromFileURLs()) {
4831 // Some clients want local URLs to have even tighter restrictions by default, and not be able to access other local files.
4832 // FIXME 81578: The naming of this is confusing. Files with restricted access to other local files
4833 // still can have other privileges that can be remembered, thereby not making them unique origins.
4834 securityOrigin()->enforceFilePathSeparation();
4839 if (initializer.shouldTreatURLAsSrcdocDocument()) {
4840 m_isSrcdocDocument = true;
4841 setBaseURLOverride(initializer.parentBaseURL());
4844 if (!shouldInheritSecurityOriginFromOwner(m_url))
4847 // If we do not obtain a meaningful origin from the URL, then we try to
4848 // find one via the frame hierarchy.
4850 if (!initializer.owner()) {
4851 didFailToInitializeSecurityOrigin();
4855 if (isSandboxed(SandboxOrigin)) {
4856 // If we're supposed to inherit our security origin from our owner,
4857 // but we're also sandboxed, the only thing we inherit is the ability
4858 // to load local resources. This lets about:blank iframes in file://
4859 // URL documents load images and other resources from the file system.
4860 if (initializer.owner()->securityOrigin()->canLoadLocalResources())
4861 securityOrigin()->grantLoadLocalResources();
4865 m_cookieURL = initializer.owner()->cookieURL();
4866 // We alias the SecurityOrigins to match Firefox, see Bug 15313
4867 // https://bugs.webkit.org/show_bug.cgi?id=15313
4868 setSecurityOrigin(initializer.owner()->securityOrigin());
4871 void Document::initContentSecurityPolicy(PassRefPtr<ContentSecurityPolicy> csp)
4873 setContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::create());
4874 if (m_frame && m_frame->tree().parent() && m_frame->tree().parent()->isLocalFrame() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
4875 contentSecurityPolicy()->copyStateFrom(toLocalFrame(m_frame->tree().parent())->document()->contentSecurityPolicy());
4876 if (transformSourceDocument())
4877 contentSecurityPolicy()->copyStateFrom(transformSourceDocument()->contentSecurityPolicy());
4878 contentSecurityPolicy()->bindToExecutionContext(this);
4881 bool Document::allowInlineEventHandlers(Node* node, EventListener* listener, const String& contextURL, const WTF::OrdinalNumber& contextLine)
4883 if (!contentSecurityPolicy()->allowInlineEventHandlers(contextURL, contextLine))
4886 // HTML says that inline script needs browsing context to create its execution environment.
4887 // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#event-handler-attributes
4888 // Also, if the listening node came from other document, which happens on context-less event dispatching,
4889 // we also need to ask the owner document of the node.
4890 LocalFrame* frame = executingFrame();
4893 if (!frame->script().canExecuteScripts(NotAboutToExecuteScript))
4895 if (node && node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
4901 bool Document::allowExecutingScripts(Node* node)
4903 // FIXME: Eventually we'd like to evaluate scripts which are inserted into a
4904 // viewless document but this'll do for now.
4905 // See http://bugs.webkit.org/show_bug.cgi?id=5727
4906 LocalFrame* frame = executingFrame();
4909 if (!node->document().executingFrame())
4911 if (!frame->script().canExecuteScripts(AboutToExecuteScript))
4916 void Document::updateSecurityOrigin(PassRefPtr<SecurityOrigin> origin)
4918 setSecurityOrigin(origin);
4919 didUpdateSecurityOrigin();
4922 void Document::didUpdateSecurityOrigin()
4926 m_frame->script().updateSecurityOrigin(securityOrigin());
4929 bool Document::isContextThread() const
4931 return isMainThread();
4934 void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
4936 m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
4937 if (!m_updateFocusAppearanceTimer.isActive())
4938 m_updateFocusAppearanceTimer.startOneShot(0, FROM_HERE);
4941 void Document::cancelFocusAppearanceUpdate()
4943 m_updateFocusAppearanceTimer.stop();
4946 void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
4948 Element* element = focusedElement();
4952 if (element->isFocusable())
4953 element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
4956 void Document::attachRange(Range* range)
4958 ASSERT(!m_ranges.contains(range));
4959 m_ranges.add(range);
4962 void Document::detachRange(Range* range)
4964 // We don't ASSERT m_ranges.contains(range) to allow us to call this
4965 // unconditionally to fix: https://bugs.webkit.org/show_bug.cgi?id=26044
4966 m_ranges.remove(range);
4969 void Document::getCSSCanvasContext(const String& type, const String& name, int width, int height, RefPtrWillBeRawPtr<CanvasRenderingContext2D>& context2d, RefPtrWillBeRawPtr<WebGLRenderingContext>& context3d)
4971 HTMLCanvasElement& element = getCSSCanvasElement(name);
4972 element.setSize(IntSize(width, height));
4973 CanvasRenderingContext* context = element.getContext(type);
4977 if (context->is2d()) {
4978 context2d = toCanvasRenderingContext2D(context);
4979 } else if (context->is3d()) {
4980 context3d = toWebGLRenderingContext(context);
4984 HTMLCanvasElement& Document::getCSSCanvasElement(const String& name)
4986 RefPtrWillBeMember<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, nullptr).storedValue->value;
4988 element = HTMLCanvasElement::create(*this);
4989 element->setAccelerationDisabled(true);
4994 void Document::initDNSPrefetch()
4996 Settings* settings = this->settings();
4998 m_haveExplicitlyDisabledDNSPrefetch = false;
4999 m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
5001 // Inherit DNS prefetch opt-out from parent frame
5002 if (Document* parent = parentDocument()) {
5003 if (!parent->isDNSPrefetchEnabled())
5004 m_isDNSPrefetchEnabled = false;
5008 void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
5010 if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
5011 m_isDNSPrefetchEnabled = true;
5015 m_isDNSPrefetchEnabled = false;
5016 m_haveExplicitlyDisabledDNSPrefetch = true;
5019 void Document::reportBlockedScriptExecutionToInspector(const String& directiveText)
5021 InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText);
5024 void Document::addConsoleMessage(PassRefPtrWillBeRawPtr<ConsoleMessage> consoleMessage)
5026 if (!isContextThread()) {
5027 m_taskRunner->postTask(AddConsoleMessageTask::create(consoleMessage->source(), consoleMessage->level(), consoleMessage->message()));
5034 if (!consoleMessage->scriptState() && consoleMessage->url().isNull() && !consoleMessage->lineNumber()) {
5035 consoleMessage->setURL(url().string());
5036 if (parsing() && !isInDocumentWrite() && scriptableDocumentParser()) {
5037 ScriptableDocumentParser* parser = scriptableDocumentParser();
5038 if (!parser->isWaitingForScripts() && !parser->isExecutingScript())
5039 consoleMessage->setLineNumber(parser->lineNumber().oneBasedInt());
5042 m_frame->console().addMessage(consoleMessage);
5045 // FIXME(crbug.com/305497): This should be removed after ExecutionContext-LocalDOMWindow migration.
5046 void Document::postTask(PassOwnPtr<ExecutionContextTask> task)
5048 m_taskRunner->postTask(task);
5051 void Document::postInspectorTask(PassOwnPtr<ExecutionContextTask> task)
5053 m_taskRunner->postInspectorTask(task);
5056 void Document::tasksWereSuspended()
5058 scriptRunner()->suspend();
5061 m_parser->suspendScheduledTasks();
5062 if (m_scriptedAnimationController)
5063 m_scriptedAnimationController->suspend();
5066 void Document::tasksWereResumed()
5068 scriptRunner()->resume();
5071 m_parser->resumeScheduledTasks();
5072 if (m_scriptedAnimationController)
5073 m_scriptedAnimationController->resume();
5075 MutationObserver::resumeSuspendedObservers();
5078 // FIXME: suspendScheduledTasks(), resumeScheduledTasks(), tasksNeedSuspension()
5079 // should be moved to LocalDOMWindow once it inherits ExecutionContext
5080 void Document::suspendScheduledTasks()
5082 ExecutionContext::suspendScheduledTasks();
5083 m_taskRunner->suspend();
5086 void Document::resumeScheduledTasks()
5088 ExecutionContext::resumeScheduledTasks();
5089 m_taskRunner->resume();
5092 bool Document::tasksNeedSuspension()
5094 Page* page = this->page();
5095 return page && page->defersLoading();
5098 void Document::addToTopLayer(Element* element, const Element* before)
5100 if (element->isInTopLayer())
5103 ASSERT(!m_topLayerElements.contains(element));
5104 ASSERT(!before || m_topLayerElements.contains(before));
5106 size_t beforePosition = m_topLayerElements.find(before);
5107 m_topLayerElements.insert(beforePosition, element);
5109 m_topLayerElements.append(element);
5111 element->setIsInTopLayer(true);
5114 void Document::removeFromTopLayer(Element* element)
5116 if (!element->isInTopLayer())
5118 size_t position = m_topLayerElements.find(element);
5119 ASSERT(position != kNotFound);
5120 m_topLayerElements.remove(position);
5121 element->setIsInTopLayer(false);
5124 HTMLDialogElement* Document::activeModalDialog() const
5126 if (m_topLayerElements.isEmpty())
5128 return toHTMLDialogElement(m_topLayerElements.last().get());
5131 void Document::exitPointerLock()
5135 if (Element* target = page()->pointerLockController().element()) {
5136 if (target->document() != this)
5139 page()->pointerLockController().requestPointerUnlock();
5142 Element* Document::pointerLockElement() const
5144 if (!page() || page()->pointerLockController().lockPending())
5146 if (Element* element = page()->pointerLockController().element()) {
5147 if (element->document() == this)
5153 void Document::decrementLoadEventDelayCount()
5155 ASSERT(m_loadEventDelayCount);
5156 --m_loadEventDelayCount;
5158 if (!m_loadEventDelayCount)
5159 checkLoadEventSoon();
5162 void Document::checkLoadEventSoon()
5164 if (frame() && !m_loadEventDelayTimer.isActive())
5165 m_loadEventDelayTimer.startOneShot(0, FROM_HERE);
5168 bool Document::isDelayingLoadEvent()
5171 // Always delay load events until after garbage collection.
5172 // This way we don't have to explicitly delay load events via
5173 // incrementLoadEventDelayCount and decrementLoadEventDelayCount in
5174 // Node destructors.
5175 if (ThreadState::current()->isSweepInProgress()) {
5176 if (!m_loadEventDelayCount)
5177 checkLoadEventSoon();
5181 return m_loadEventDelayCount;
5185 void Document::loadEventDelayTimerFired(Timer<Document>*)
5188 frame()->loader().checkCompleted();
5191 void Document::loadPluginsSoon()
5193 // FIXME: Remove this timer once we don't need to compute layout to load plugins.
5194 if (!m_pluginLoadingTimer.isActive())
5195 m_pluginLoadingTimer.startOneShot(0, FROM_HERE);
5198 void Document::pluginLoadingTimerFired(Timer<Document>*)
5203 ScriptedAnimationController& Document::ensureScriptedAnimationController()
5205 if (!m_scriptedAnimationController) {
5206 m_scriptedAnimationController = ScriptedAnimationController::create(this);
5207 // We need to make sure that we don't start up the animation controller on a background tab, for example.
5209 m_scriptedAnimationController->suspend();
5211 return *m_scriptedAnimationController;
5214 int Document::requestAnimationFrame(RequestAnimationFrameCallback* callback)
5216 return ensureScriptedAnimationController().registerCallback(callback);
5219 void Document::cancelAnimationFrame(int id)
5221 if (!m_scriptedAnimationController)
5223 m_scriptedAnimationController->cancelCallback(id);
5226 void Document::serviceScriptedAnimations(double monotonicAnimationStartTime)
5228 if (!m_scriptedAnimationController)
5230 m_scriptedAnimationController->serviceScriptedAnimations(monotonicAnimationStartTime);
5233 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
5235 // Match behavior from when these types were integers, and avoid surprises from someone explicitly
5236 // passing Infinity/NaN.
5237 if (!std::isfinite(pageX))
5239 if (!std::isfinite(pageY))
5241 if (!std::isfinite(screenX))
5243 if (!std::isfinite(screenY))
5245 if (!std::isfinite(radiusX))
5247 if (!std::isfinite(radiusY))
5249 if (!std::isfinite(rotationAngle))
5251 if (!std::isfinite(force))
5254 // FIXME: It's not clear from the documentation at
5255 // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html
5256 // 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
5257 // and implement them here. See https://bugs.webkit.org/show_bug.cgi?id=47819
5258 LocalFrame* frame = window ? window->frame() : this->frame();
5259 return Touch::create(frame, target, identifier, FloatPoint(screenX, screenY), FloatPoint(pageX, pageY), FloatSize(radiusX, radiusY), rotationAngle, force);
5262 PassRefPtrWillBeRawPtr<TouchList> Document::createTouchList(WillBeHeapVector<RefPtrWillBeMember<Touch> >& touches) const
5264 return TouchList::adopt(touches);
5267 DocumentLoader* Document::loader() const
5272 DocumentLoader* loader = m_frame->loader().documentLoader();
5276 if (m_frame->document() != this)
5282 IntSize Document::initialViewportSize() const
5286 return view()->unscaledVisibleContentSize(IncludeScrollbars);
5289 Node* eventTargetNodeForDocument(Document* doc)
5293 Node* node = doc->focusedElement();
5294 if (!node && doc->isPluginDocument()) {
5295 PluginDocument* pluginDocument = toPluginDocument(doc);
5296 node = pluginDocument->pluginNode();
5298 if (!node && doc->isHTMLDocument())
5301 node = doc->documentElement();
5305 void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject& renderer)
5310 LayoutRect visibleContentRect = view()->visibleContentRect();
5311 for (size_t i = 0; i < quads.size(); ++i) {
5312 quads[i].move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
5313 adjustFloatQuadForAbsoluteZoom(quads[i], renderer);
5317 void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject& renderer)
5322 LayoutRect visibleContentRect = view()->visibleContentRect();
5323 rect.move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
5324 adjustFloatRectForAbsoluteZoom(rect, renderer);
5327 bool Document::hasActiveParser()
5329 return m_activeParserCount || (m_parser && m_parser->processingData());
5332 void Document::decrementActiveParserCount()
5334 --m_activeParserCount;
5337 frame()->loader().checkLoadComplete();
5340 void Document::setContextFeatures(ContextFeatures& features)
5342 m_contextFeatures = PassRefPtrWillBeRawPtr<ContextFeatures>(features);
5345 static RenderObject* nearestCommonHoverAncestor(RenderObject* obj1, RenderObject* obj2)
5350 for (RenderObject* currObj1 = obj1; currObj1; currObj1 = currObj1->hoverAncestor()) {
5351 for (RenderObject* currObj2 = obj2; currObj2; currObj2 = currObj2->hoverAncestor()) {
5352 if (currObj1 == currObj2)
5360 void Document::updateHoverActiveState(const HitTestRequest& request, Element* innerElement, const PlatformMouseEvent* event)
5362 ASSERT(!request.readOnly());
5364 if (request.active() && m_frame)
5365 m_frame->eventHandler().notifyElementActivated();
5367 Element* innerElementInDocument = innerElement;
5368 while (innerElementInDocument && innerElementInDocument->document() != this) {
5369 innerElementInDocument->document().updateHoverActiveState(request, innerElementInDocument, event);
5370 innerElementInDocument = innerElementInDocument->document().ownerElement();
5373 Element* oldActiveElement = activeHoverElement();
5374 if (oldActiveElement && !request.active()) {
5375 // The oldActiveElement renderer is null, dropped on :active by setting display: none,
5376 // for instance. We still need to clear the ActiveChain as the mouse is released.
5377 for (Node* node = oldActiveElement; node; node = NodeRenderingTraversal::parent(node)) {
5378 ASSERT(!node->isTextNode());
5379 node->setActive(false);
5380 m_userActionElements.setInActiveChain(node, false);
5382 setActiveHoverElement(nullptr);
5384 Element* newActiveElement = innerElementInDocument;
5385 if (!oldActiveElement && newActiveElement && !newActiveElement->isDisabledFormControl() && request.active() && !request.touchMove()) {
5386 // We are setting the :active chain and freezing it. If future moves happen, they
5387 // will need to reference this chain.
5388 for (Node* node = newActiveElement; node; node = NodeRenderingTraversal::parent(node)) {
5389 ASSERT(!node->isTextNode());
5390 m_userActionElements.setInActiveChain(node, true);
5392 setActiveHoverElement(newActiveElement);
5395 // If the mouse has just been pressed, set :active on the chain. Those (and only those)
5396 // nodes should remain :active until the mouse is released.
5397 bool allowActiveChanges = !oldActiveElement && activeHoverElement();
5399 // If the mouse is down and if this is a mouse move event, we want to restrict changes in
5400 // :hover/:active to only apply to elements that are in the :active chain that we froze
5401 // at the time the mouse went down.
5402 bool mustBeInActiveChain = request.active() && request.move();
5404 RefPtrWillBeRawPtr<Node> oldHoverNode = hoverNode();
5406 // Check to see if the hovered node has changed.
5407 // If it hasn't, we do not need to do anything.
5408 Node* newHoverNode = innerElementInDocument;
5409 while (newHoverNode && !newHoverNode->renderer())
5410 newHoverNode = newHoverNode->parentOrShadowHostNode();
5412 // Update our current hover node.
5413 setHoverNode(newHoverNode);
5415 // We have two different objects. Fetch their renderers.
5416 RenderObject* oldHoverObj = oldHoverNode ? oldHoverNode->renderer() : 0;
5417 RenderObject* newHoverObj = newHoverNode ? newHoverNode->renderer() : 0;
5419 // Locate the common ancestor render object for the two renderers.
5420 RenderObject* ancestor = nearestCommonHoverAncestor(oldHoverObj, newHoverObj);
5421 RefPtrWillBeRawPtr<Node> ancestorNode(ancestor ? ancestor->node() : 0);
5423 WillBeHeapVector<RefPtrWillBeMember<Node>, 32> nodesToRemoveFromChain;
5424 WillBeHeapVector<RefPtrWillBeMember<Node>, 32> nodesToAddToChain;
5426 if (oldHoverObj != newHoverObj) {
5427 // If the old hovered node is not nil but it's renderer is, it was probably detached as part of the :hover style
5428 // (for instance by setting display:none in the :hover pseudo-class). In this case, the old hovered element (and its ancestors)
5429 // must be updated, to ensure it's normal style is re-applied.
5430 if (oldHoverNode && !oldHoverObj) {
5431 for (Node* node = oldHoverNode.get(); node; node = node->parentNode()) {
5432 if (!mustBeInActiveChain || (node->isElementNode() && toElement(node)->inActiveChain()))
5433 nodesToRemoveFromChain.append(node);
5438 // The old hover path only needs to be cleared up to (and not including) the common ancestor;
5439 for (RenderObject* curr = oldHoverObj; curr && curr != ancestor; curr = curr->hoverAncestor()) {
5440 if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5441 nodesToRemoveFromChain.append(curr->node());
5445 // Now set the hover state for our new object up to the root.
5446 for (RenderObject* curr = newHoverObj; curr; curr = curr->hoverAncestor()) {
5447 if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5448 nodesToAddToChain.append(curr->node());
5451 // mouseenter and mouseleave events do not bubble, so they are dispatched iff there is a capturing
5452 // event handler on an ancestor or a normal event handler on the element itself. This special
5453 // handling is necessary to avoid O(n^2) capturing event handler checks. We'll check the previously
5454 // hovered node's ancestor tree for 'mouseleave' handlers here, then check the newly hovered node's
5455 // ancestor tree for 'mouseenter' handlers after dispatching the 'mouseleave' events (as the handler
5456 // for 'mouseleave' might set a capturing 'mouseenter' handler, odd as that might be).
5457 bool ancestorHasCapturingMouseleaveListener = false;
5458 if (event && newHoverNode != oldHoverNode.get()) {
5459 for (Node* node = oldHoverNode.get(); node; node = node->parentOrShadowHostNode()) {
5460 if (node->hasCapturingEventListeners(EventTypeNames::mouseleave)) {
5461 ancestorHasCapturingMouseleaveListener = true;
5467 size_t removeCount = nodesToRemoveFromChain.size();
5468 for (size_t i = 0; i < removeCount; ++i) {
5469 nodesToRemoveFromChain[i]->setHovered(false);
5470 if (event && (ancestorHasCapturingMouseleaveListener || nodesToRemoveFromChain[i]->hasEventListeners(EventTypeNames::mouseleave)))
5471 nodesToRemoveFromChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseleave, 0, newHoverNode);
5474 bool ancestorHasCapturingMouseenterListener = false;
5475 if (event && newHoverNode != oldHoverNode.get()) {
5476 for (Node* node = newHoverNode; node; node = node->parentOrShadowHostNode()) {
5477 if (node->hasCapturingEventListeners(EventTypeNames::mouseenter)) {
5478 ancestorHasCapturingMouseenterListener = true;
5484 bool sawCommonAncestor = false;
5485 size_t addCount = nodesToAddToChain.size();
5486 for (size_t i = 0; i < addCount; ++i) {
5487 // Elements past the common ancestor do not change hover state, but might change active state.
5488 if (ancestorNode && nodesToAddToChain[i] == ancestorNode)
5489 sawCommonAncestor = true;
5490 if (allowActiveChanges)
5491 nodesToAddToChain[i]->setActive(true);
5492 if (!sawCommonAncestor) {
5493 nodesToAddToChain[i]->setHovered(true);
5494 if (event && (ancestorHasCapturingMouseenterListener || nodesToAddToChain[i]->hasEventListeners(EventTypeNames::mouseenter)))
5495 nodesToAddToChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseenter, 0, oldHoverNode.get());
5500 bool Document::haveStylesheetsLoaded() const
5502 return m_styleEngine->haveStylesheetsLoaded();
5505 Locale& Document::getCachedLocale(const AtomicString& locale)
5507 AtomicString localeKey = locale;
5508 if (locale.isEmpty() || !RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
5509 return Locale::defaultLocale();
5510 LocaleIdentifierToLocaleMap::AddResult result = m_localeCache.add(localeKey, nullptr);
5511 if (result.isNewEntry)
5512 result.storedValue->value = Locale::create(localeKey);
5513 return *(result.storedValue->value);
5516 Document& Document::ensureTemplateDocument()
5518 if (isTemplateDocument())
5521 if (m_templateDocument)
5522 return *m_templateDocument;
5524 if (isHTMLDocument()) {
5525 DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL()).withNewRegistrationContext();
5526 m_templateDocument = HTMLDocument::create(init);
5528 m_templateDocument = Document::create(DocumentInit(blankURL()));
5531 m_templateDocument->m_templateDocumentHost = this; // balanced in dtor.
5533 return *m_templateDocument.get();
5536 void Document::didAssociateFormControl(Element* element)
5538 if (!frame() || !frame()->page())
5540 m_associatedFormControls.add(element);
5541 if (!m_didAssociateFormControlsTimer.isActive())
5542 m_didAssociateFormControlsTimer.startOneShot(0, FROM_HERE);
5545 void Document::didAssociateFormControlsTimerFired(Timer<Document>* timer)
5547 ASSERT_UNUSED(timer, timer == &m_didAssociateFormControlsTimer);
5548 if (!frame() || !frame()->page())
5551 WillBeHeapVector<RefPtrWillBeMember<Element> > associatedFormControls;
5552 copyToVector(m_associatedFormControls, associatedFormControls);
5554 frame()->page()->chrome().client().didAssociateFormControls(associatedFormControls);
5555 m_associatedFormControls.clear();
5558 float Document::devicePixelRatio() const
5560 return m_frame ? m_frame->devicePixelRatio() : 1.0;
5563 PassOwnPtr<LifecycleNotifier<Document> > Document::createLifecycleNotifier()
5565 return DocumentLifecycleNotifier::create(this);
5568 DocumentLifecycleNotifier& Document::lifecycleNotifier()
5570 return static_cast<DocumentLifecycleNotifier&>(LifecycleContext<Document>::lifecycleNotifier());
5573 void Document::removedStyleSheet(StyleSheet* sheet, StyleResolverUpdateMode updateMode)
5575 // If we're in document teardown, then we don't need this notification of our sheet's removal.
5576 // styleResolverChanged() is needed even when the document is inactive so that
5577 // imported docuements (which is inactive) notifies the change to the master document.
5579 styleEngine()->modifiedStyleSheet(sheet);
5580 styleResolverChanged(updateMode);
5583 void Document::modifiedStyleSheet(StyleSheet* sheet, StyleResolverUpdateMode updateMode)
5585 // If we're in document teardown, then we don't need this notification of our sheet's removal.
5586 // styleResolverChanged() is needed even when the document is inactive so that
5587 // imported docuements (which is inactive) notifies the change to the master document.
5589 styleEngine()->modifiedStyleSheet(sheet);
5590 styleResolverChanged(updateMode);
5593 TextAutosizer* Document::textAutosizer()
5595 if (!m_textAutosizer)
5596 m_textAutosizer = TextAutosizer::create(this);
5597 return m_textAutosizer.get();
5600 void Document::setAutofocusElement(Element* element)
5603 m_autofocusElement = nullptr;
5606 if (m_hasAutofocused)
5608 m_hasAutofocused = true;
5609 ASSERT(!m_autofocusElement);
5610 m_autofocusElement = element;
5611 m_taskRunner->postTask(AutofocusTask::create());
5614 Element* Document::activeElement() const
5616 if (Element* element = treeScope().adjustedFocusedElement())
5621 void Document::getTransitionElementData(Vector<TransitionElementData>& elementData)
5626 for (HTMLMetaElement* metaElement = Traversal<HTMLMetaElement>::firstChild(*head()); metaElement; metaElement = Traversal<HTMLMetaElement>::nextSibling(*metaElement)) {
5627 if (metaElement->name() != "transition-elements")
5630 const String& metaElementContents = metaElement->content().string();
5631 size_t firstSemicolon = metaElementContents.find(';');
5632 if (firstSemicolon == kNotFound)
5635 TrackExceptionState exceptionState;
5636 AtomicString selector(metaElementContents.substring(0, firstSemicolon));
5637 RefPtrWillBeRawPtr<StaticElementList> elementList = querySelectorAll(selector, exceptionState);
5638 if (!elementList || exceptionState.hadException())
5641 unsigned nodeListLength = elementList->length();
5642 if (!nodeListLength)
5645 StringBuilder markup;
5646 for (unsigned nodeIndex = 0; nodeIndex < nodeListLength; ++nodeIndex) {
5647 Element* element = elementList->item(nodeIndex);
5648 markup.append(createStyledMarkupForNavigationTransition(element));
5651 TransitionElementData newElements;
5652 newElements.scope = metaElementContents.substring(firstSemicolon + 1).stripWhiteSpace();
5653 newElements.selector = selector;
5654 newElements.markup = markup.toString();
5655 elementData.append(newElements);
5659 void Document::hideTransitionElements(const AtomicString& cssSelector)
5661 TrackExceptionState exceptionState;
5662 RefPtrWillBeRawPtr<StaticElementList> elementList = querySelectorAll(cssSelector, exceptionState);
5663 if (elementList && !exceptionState.hadException()) {
5664 unsigned nodeListLength = elementList->length();
5666 for (unsigned nodeIndex = 0; nodeIndex < nodeListLength; ++nodeIndex) {
5667 Element* element = elementList->item(nodeIndex);
5668 element->setInlineStyleProperty(CSSPropertyOpacity, 0.0, CSSPrimitiveValue::CSS_NUMBER);
5673 bool Document::hasFocus() const
5675 Page* page = this->page();
5678 if (!page->focusController().isActive() || !page->focusController().isFocused())
5680 Frame* focusedFrame = page->focusController().focusedFrame();
5681 if (focusedFrame && focusedFrame->isLocalFrame()) {
5682 if (toLocalFrame(focusedFrame)->tree().isDescendantOf(frame()))
5689 template<unsigned type>
5690 bool shouldInvalidateNodeListCachesForAttr(const HeapHashSet<WeakMember<const LiveNodeListBase> > nodeLists[], const QualifiedName& attrName)
5692 if (!nodeLists[type].isEmpty() && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
5694 return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeLists, attrName);
5698 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const HeapHashSet<WeakMember<const LiveNodeListBase> >[], const QualifiedName&)
5703 template<unsigned type>
5704 bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
5706 if (nodeListCounts[type] && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
5708 return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
5712 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
5718 bool Document::shouldInvalidateNodeListCaches(const QualifiedName* attrName) const
5722 return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeLists, *attrName);
5724 return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListCounts, *attrName);
5728 for (int type = 0; type < numNodeListInvalidationTypes; ++type) {
5730 if (!m_nodeLists[type].isEmpty())
5732 if (m_nodeListCounts[type])
5740 void Document::invalidateNodeListCaches(const QualifiedName* attrName)
5742 WillBeHeapHashSet<RawPtrWillBeWeakMember<const LiveNodeListBase> >::const_iterator end = m_listsInvalidatedAtDocument.end();
5743 for (WillBeHeapHashSet<RawPtrWillBeWeakMember<const LiveNodeListBase> >::const_iterator it = m_listsInvalidatedAtDocument.begin(); it != end; ++it)
5744 (*it)->invalidateCacheForAttribute(attrName);
5747 void Document::clearWeakMembers(Visitor* visitor)
5749 if (m_axObjectCache)
5750 m_axObjectCache->clearWeakMembers(visitor);
5753 v8::Handle<v8::Object> Document::wrap(v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
5755 // It's possible that no one except for the new wrapper owns this object at
5756 // this moment, so we have to prevent GC to collect this object until the
5757 // object gets associated with the wrapper.
5758 RefPtrWillBeRawPtr<Document> protect(this);
5760 ASSERT(!DOMDataStore::containsWrapperNonTemplate(this, isolate));
5762 const WrapperTypeInfo* wrapperType = wrapperTypeInfo();
5764 if (frame() && frame()->script().initializeMainWorld()) {
5765 // initializeMainWorld may have created a wrapper for the object, retry from the start.
5766 v8::Handle<v8::Object> wrapper = DOMDataStore::getWrapperNonTemplate(this, isolate);
5767 if (!wrapper.IsEmpty())
5771 v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, wrapperType, toScriptWrappableBase(), isolate);
5772 if (UNLIKELY(wrapper.IsEmpty()))
5775 wrapperType->installConditionallyEnabledProperties(wrapper, isolate);
5776 return associateWithWrapper(wrapperType, wrapper, isolate);
5779 v8::Handle<v8::Object> Document::associateWithWrapper(const WrapperTypeInfo* wrapperType, v8::Handle<v8::Object> wrapper, v8::Isolate* isolate)
5781 V8DOMWrapper::associateObjectWithWrapperNonTemplate(this, wrapperType, wrapper, isolate);
5782 DOMWrapperWorld& world = DOMWrapperWorld::current(isolate);
5783 if (world.isMainWorld() && frame())
5784 frame()->script().windowProxy(world)->updateDocumentWrapper(wrapper);
5788 void Document::trace(Visitor* visitor)
5791 visitor->trace(m_importsController);
5792 visitor->trace(m_docType);
5793 visitor->trace(m_implementation);
5794 visitor->trace(m_autofocusElement);
5795 visitor->trace(m_focusedElement);
5796 visitor->trace(m_hoverNode);
5797 visitor->trace(m_activeHoverElement);
5798 visitor->trace(m_documentElement);
5799 visitor->trace(m_titleElement);
5800 visitor->trace(m_markers);
5801 visitor->trace(m_cssTarget);
5802 visitor->trace(m_currentScriptStack);
5803 visitor->trace(m_scriptRunner);
5804 visitor->trace(m_transformSourceDocument);
5805 visitor->trace(m_listsInvalidatedAtDocument);
5806 for (int i = 0; i < numNodeListInvalidationTypes; ++i)
5807 visitor->trace(m_nodeLists[i]);
5808 visitor->trace(m_cssCanvasElements);
5809 visitor->trace(m_topLayerElements);
5810 visitor->trace(m_elemSheet);
5811 visitor->trace(m_nodeIterators);
5812 visitor->trace(m_ranges);
5813 visitor->trace(m_styleEngine);
5814 visitor->trace(m_formController);
5815 visitor->trace(m_visitedLinkState);
5816 visitor->trace(m_frame);
5817 visitor->trace(m_domWindow);
5818 visitor->trace(m_fetcher);
5819 visitor->trace(m_parser);
5820 visitor->trace(m_contextFeatures);
5821 visitor->trace(m_styleSheetList);
5822 visitor->trace(m_mediaQueryMatcher);
5823 visitor->trace(m_scriptedAnimationController);
5824 visitor->trace(m_textAutosizer);
5825 visitor->trace(m_registrationContext);
5826 visitor->trace(m_customElementMicrotaskRunQueue);
5827 visitor->trace(m_elementDataCache);
5828 visitor->trace(m_associatedFormControls);
5829 visitor->trace(m_useElementsNeedingUpdate);
5830 visitor->trace(m_layerUpdateSVGFilterElements);
5831 visitor->trace(m_templateDocument);
5832 visitor->trace(m_templateDocumentHost);
5833 visitor->trace(m_visibilityObservers);
5834 visitor->trace(m_userActionElements);
5835 visitor->trace(m_svgExtensions);
5836 visitor->trace(m_timeline);
5837 visitor->trace(m_compositorPendingAnimations);
5838 visitor->trace(m_contextDocument);
5839 visitor->registerWeakMembers<Document, &Document::clearWeakMembers>(this);
5840 DocumentSupplementable::trace(visitor);
5842 TreeScope::trace(visitor);
5843 ContainerNode::trace(visitor);
5844 ExecutionContext::trace(visitor);
5845 LifecycleContext<Document>::trace(visitor);
5848 } // namespace blink
5851 using namespace blink;
5852 void showLiveDocumentInstances()
5854 WeakDocumentSet& set = liveDocumentSet();
5855 fprintf(stderr, "There are %u documents currently alive:\n", set.size());
5856 for (WeakDocumentSet::const_iterator it = set.begin(); it != set.end(); ++it) {
5857 fprintf(stderr, "- Document %p URL: %s\n", *it, (*it)->url().string().utf8().data());