Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / dom / Document.cpp
1 /*
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.
11  *
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.
16  *
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.
21  *
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.
26  */
27
28 #include "config.h"
29 #include "core/dom/Document.h"
30
31 #include "HTMLElementFactory.h"
32 #include "HTMLNames.h"
33 #include "RuntimeEnabledFeatures.h"
34 #include "SVGElementFactory.h"
35 #include "SVGNames.h"
36 #include "XMLNSNames.h"
37 #include "XMLNames.h"
38 #include "bindings/v8/CustomElementConstructorBuilder.h"
39 #include "bindings/v8/Dictionary.h"
40 #include "bindings/v8/ExceptionMessages.h"
41 #include "bindings/v8/ExceptionState.h"
42 #include "bindings/v8/ExceptionStatePlaceholder.h"
43 #include "bindings/v8/ScriptController.h"
44 #include "core/accessibility/AXObjectCache.h"
45 #include "core/animation/AnimationClock.h"
46 #include "core/animation/DocumentAnimations.h"
47 #include "core/animation/DocumentTimeline.h"
48 #include "core/animation/css/TransitionTimeline.h"
49 #include "core/css/CSSFontSelector.h"
50 #include "core/css/CSSStyleDeclaration.h"
51 #include "core/css/CSSStyleSheet.h"
52 #include "core/css/MediaQueryMatcher.h"
53 #include "core/css/StylePropertySet.h"
54 #include "core/css/StyleSheetContents.h"
55 #include "core/css/StyleSheetList.h"
56 #include "core/css/invalidation/StyleInvalidator.h"
57 #include "core/css/resolver/FontBuilder.h"
58 #include "core/css/resolver/StyleResolver.h"
59 #include "core/css/resolver/StyleResolverStats.h"
60 #include "core/dom/AddConsoleMessageTask.h"
61 #include "core/dom/Attr.h"
62 #include "core/dom/CDATASection.h"
63 #include "core/dom/Comment.h"
64 #include "core/dom/ContextFeatures.h"
65 #include "core/dom/DOMImplementation.h"
66 #include "core/dom/DocumentFragment.h"
67 #include "core/dom/DocumentLifecycleNotifier.h"
68 #include "core/dom/DocumentLifecycleObserver.h"
69 #include "core/dom/DocumentMarkerController.h"
70 #include "core/dom/DocumentType.h"
71 #include "core/dom/Element.h"
72 #include "core/dom/ElementDataCache.h"
73 #include "core/dom/ElementTraversal.h"
74 #include "core/dom/ExceptionCode.h"
75 #include "core/dom/ExecutionContextTask.h"
76 #include "core/dom/MainThreadTaskRunner.h"
77 #include "core/dom/MutationObserver.h"
78 #include "core/dom/NodeChildRemovalTracker.h"
79 #include "core/dom/NodeFilter.h"
80 #include "core/dom/NodeIterator.h"
81 #include "core/dom/NodeRareData.h"
82 #include "core/dom/NodeRenderStyle.h"
83 #include "core/dom/NodeRenderingTraversal.h"
84 #include "core/dom/NodeTraversal.h"
85 #include "core/dom/NodeWithIndex.h"
86 #include "core/dom/ProcessingInstruction.h"
87 #include "core/dom/RequestAnimationFrameCallback.h"
88 #include "core/dom/ScriptForbiddenScope.h"
89 #include "core/dom/ScriptRunner.h"
90 #include "core/dom/ScriptedAnimationController.h"
91 #include "core/dom/SelectorQuery.h"
92 #include "core/dom/StyleEngine.h"
93 #include "core/dom/TouchList.h"
94 #include "core/dom/TransformSource.h"
95 #include "core/dom/TreeWalker.h"
96 #include "core/dom/VisitedLinkState.h"
97 #include "core/dom/XMLDocument.h"
98 #include "core/dom/custom/CustomElementRegistrationContext.h"
99 #include "core/dom/shadow/ElementShadow.h"
100 #include "core/dom/shadow/ShadowRoot.h"
101 #include "core/editing/Editor.h"
102 #include "core/editing/FrameSelection.h"
103 #include "core/editing/SpellChecker.h"
104 #include "core/events/BeforeUnloadEvent.h"
105 #include "core/events/Event.h"
106 #include "core/events/EventFactory.h"
107 #include "core/events/EventListener.h"
108 #include "core/events/HashChangeEvent.h"
109 #include "core/events/PageTransitionEvent.h"
110 #include "core/events/ScopedEventQueue.h"
111 #include "core/fetch/ResourceFetcher.h"
112 #include "core/frame/DOMWindow.h"
113 #include "core/frame/FrameConsole.h"
114 #include "core/frame/FrameHost.h"
115 #include "core/frame/FrameView.h"
116 #include "core/frame/History.h"
117 #include "core/frame/LocalFrame.h"
118 #include "core/frame/Settings.h"
119 #include "core/frame/csp/ContentSecurityPolicy.h"
120 #include "core/html/HTMLAllCollection.h"
121 #include "core/html/HTMLAnchorElement.h"
122 #include "core/html/HTMLBaseElement.h"
123 #include "core/html/HTMLCanvasElement.h"
124 #include "core/html/HTMLCollection.h"
125 #include "core/html/HTMLDialogElement.h"
126 #include "core/html/HTMLDocument.h"
127 #include "core/html/HTMLFrameOwnerElement.h"
128 #include "core/html/HTMLHeadElement.h"
129 #include "core/html/HTMLHtmlElement.h"
130 #include "core/html/HTMLIFrameElement.h"
131 #include "core/html/HTMLInputElement.h"
132 #include "core/html/HTMLLinkElement.h"
133 #include "core/html/HTMLMetaElement.h"
134 #include "core/html/HTMLNameCollection.h"
135 #include "core/html/HTMLScriptElement.h"
136 #include "core/html/HTMLStyleElement.h"
137 #include "core/html/HTMLTemplateElement.h"
138 #include "core/html/HTMLTitleElement.h"
139 #include "core/html/PluginDocument.h"
140 #include "core/html/canvas/CanvasRenderingContext.h"
141 #include "core/html/canvas/CanvasRenderingContext2D.h"
142 #include "core/html/canvas/WebGLRenderingContext.h"
143 #include "core/html/forms/FormController.h"
144 #include "core/html/imports/HTMLImportLoader.h"
145 #include "core/html/imports/HTMLImportsController.h"
146 #include "core/html/parser/HTMLDocumentParser.h"
147 #include "core/html/parser/HTMLParserIdioms.h"
148 #include "core/html/parser/NestingLevelIncrementer.h"
149 #include "core/html/parser/TextResourceDecoder.h"
150 #include "core/inspector/InspectorCounters.h"
151 #include "core/inspector/InspectorInstrumentation.h"
152 #include "core/inspector/InspectorTraceEvents.h"
153 #include "core/inspector/ScriptCallStack.h"
154 #include "core/loader/CookieJar.h"
155 #include "core/loader/DocumentLoader.h"
156 #include "core/loader/FrameLoader.h"
157 #include "core/loader/FrameLoaderClient.h"
158 #include "core/loader/ImageLoader.h"
159 #include "core/loader/appcache/ApplicationCacheHost.h"
160 #include "core/page/Chrome.h"
161 #include "core/page/ChromeClient.h"
162 #include "core/page/EventHandler.h"
163 #include "core/page/FocusController.h"
164 #include "core/page/FrameTree.h"
165 #include "core/page/MouseEventWithHitTestResults.h"
166 #include "core/page/Page.h"
167 #include "core/page/PointerLockController.h"
168 #include "core/page/scrolling/ScrollingCoordinator.h"
169 #include "core/rendering/FastTextAutosizer.h"
170 #include "core/rendering/HitTestResult.h"
171 #include "core/rendering/RenderView.h"
172 #include "core/rendering/TextAutosizer.h"
173 #include "core/svg/SVGDocumentExtensions.h"
174 #include "core/svg/SVGFontFaceElement.h"
175 #include "core/svg/SVGStyleElement.h"
176 #include "core/svg/SVGUseElement.h"
177 #include "core/workers/SharedWorkerRepositoryClient.h"
178 #include "core/xml/XSLTProcessor.h"
179 #include "core/xml/parser/XMLDocumentParser.h"
180 #include "platform/DateComponents.h"
181 #include "platform/Language.h"
182 #include "platform/TraceEvent.h"
183 #include "platform/network/ContentSecurityPolicyParsers.h"
184 #include "platform/network/HTTPParsers.h"
185 #include "platform/scroll/ScrollbarTheme.h"
186 #include "platform/text/PlatformLocale.h"
187 #include "platform/text/SegmentedString.h"
188 #include "platform/weborigin/OriginAccessEntry.h"
189 #include "platform/weborigin/SchemeRegistry.h"
190 #include "platform/weborigin/SecurityOrigin.h"
191 #include "public/platform/Platform.h"
192 #include "wtf/CurrentTime.h"
193 #include "wtf/HashFunctions.h"
194 #include "wtf/MainThread.h"
195 #include "wtf/StdLibExtras.h"
196 #include "wtf/TemporaryChange.h"
197 #include "wtf/text/StringBuffer.h"
198 #include "wtf/text/TextEncodingRegistry.h"
199
200 using namespace std;
201 using namespace WTF;
202 using namespace Unicode;
203
204 namespace WebCore {
205
206 using namespace HTMLNames;
207
208 static const unsigned cMaxWriteRecursionDepth = 21;
209
210 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
211 // FIXME: For faster machines this value can really be lowered to 200.  250 is adequate, but a little high
212 // for dual G5s. :)
213 static const int cLayoutScheduleThreshold = 250;
214
215 // DOM Level 2 says (letters added):
216 //
217 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
218 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
219 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
220 // d) Characters which have a font or compatibility decomposition (i.e. those with a "compatibility formatting tag" in field 5 of the database -- marked by field 5 beginning with a "<") are not allowed.
221 // e) The following characters are treated as name-start characters rather than name characters, because the property file classifies them as Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.
222 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
223 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
224 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
225 // i) Characters ':' and '_' are allowed as name-start characters.
226 // j) Characters '-' and '.' are allowed as name characters.
227 //
228 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
229
230 static inline bool isValidNameStart(UChar32 c)
231 {
232     // rule (e) above
233     if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
234         return true;
235
236     // rule (i) above
237     if (c == ':' || c == '_')
238         return true;
239
240     // rules (a) and (f) above
241     const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
242     if (!(Unicode::category(c) & nameStartMask))
243         return false;
244
245     // rule (c) above
246     if (c >= 0xF900 && c < 0xFFFE)
247         return false;
248
249     // rule (d) above
250     DecompositionType decompType = decompositionType(c);
251     if (decompType == DecompositionFont || decompType == DecompositionCompat)
252         return false;
253
254     return true;
255 }
256
257 static inline bool isValidNamePart(UChar32 c)
258 {
259     // rules (a), (e), and (i) above
260     if (isValidNameStart(c))
261         return true;
262
263     // rules (g) and (h) above
264     if (c == 0x00B7 || c == 0x0387)
265         return true;
266
267     // rule (j) above
268     if (c == '-' || c == '.')
269         return true;
270
271     // rules (b) and (f) above
272     const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
273     if (!(Unicode::category(c) & otherNamePartMask))
274         return false;
275
276     // rule (c) above
277     if (c >= 0xF900 && c < 0xFFFE)
278         return false;
279
280     // rule (d) above
281     DecompositionType decompType = decompositionType(c);
282     if (decompType == DecompositionFont || decompType == DecompositionCompat)
283         return false;
284
285     return true;
286 }
287
288 static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
289 {
290     // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
291     //
292     // If a Document has the address "about:blank"
293     //     The origin of the Document is the origin it was assigned when its browsing context was created.
294     //
295     // Note: We generalize this to all "blank" URLs and invalid URLs because we
296     // treat all of these URLs as about:blank.
297     //
298     return url.isEmpty() || url.protocolIsAbout();
299 }
300
301 static Widget* widgetForElement(const Element& focusedElement)
302 {
303     RenderObject* renderer = focusedElement.renderer();
304     if (!renderer || !renderer->isWidget())
305         return 0;
306     return toRenderWidget(renderer)->widget();
307 }
308
309 static bool acceptsEditingFocus(const Element& element)
310 {
311     ASSERT(element.rendererIsEditable());
312
313     return element.document().frame() && element.rootEditableElement();
314 }
315
316 static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, LocalFrame* targetFrame)
317 {
318     // targetFrame can be 0 when we're trying to navigate a top-level frame
319     // that has a 0 opener.
320     if (!targetFrame)
321         return false;
322
323     const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
324     for (LocalFrame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
325         Document* ancestorDocument = ancestorFrame->document();
326         // FIXME: Should be an ASSERT? Frames should alway have documents.
327         if (!ancestorDocument)
328             return true;
329
330         const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
331         if (activeSecurityOrigin.canAccess(ancestorSecurityOrigin))
332             return true;
333
334         // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
335         // FIXME: It's a bit strange to special-case local origins here. Should we be doing
336         // something more general instead?
337         if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
338             return true;
339     }
340
341     return false;
342 }
343
344 static void printNavigationErrorMessage(const LocalFrame& frame, const KURL& activeURL, const char* reason)
345 {
346     String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame.document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
347
348     // FIXME: should we print to the console of the document performing the navigation instead?
349     frame.domWindow()->printErrorMessage(message);
350 }
351
352 uint64_t Document::s_globalTreeVersion = 0;
353
354 // This class doesn't work with non-Document ExecutionContext.
355 class AutofocusTask FINAL : public ExecutionContextTask {
356 public:
357     static PassOwnPtr<AutofocusTask> create()
358     {
359         return adoptPtr(new AutofocusTask());
360     }
361     virtual ~AutofocusTask() { }
362
363 private:
364     AutofocusTask() { }
365     virtual void performTask(ExecutionContext* context) OVERRIDE
366     {
367         Document* document = toDocument(context);
368         if (RefPtr<Element> element = document->autofocusElement()) {
369             document->setAutofocusElement(0);
370             element->focus();
371         }
372     }
373 };
374
375 DocumentVisibilityObserver::DocumentVisibilityObserver(Document& document)
376     : m_document(0)
377 {
378     registerObserver(document);
379 }
380
381 DocumentVisibilityObserver::~DocumentVisibilityObserver()
382 {
383 #if !ENABLE(OILPAN)
384     unregisterObserver();
385 #endif
386 }
387
388 void DocumentVisibilityObserver::unregisterObserver()
389 {
390     if (m_document) {
391         m_document->unregisterVisibilityObserver(this);
392         m_document = 0;
393     }
394 }
395
396 void DocumentVisibilityObserver::registerObserver(Document& document)
397 {
398     ASSERT(!m_document);
399     m_document = &document;
400     if (m_document)
401         m_document->registerVisibilityObserver(this);
402 }
403
404 void DocumentVisibilityObserver::setObservedDocument(Document& document)
405 {
406     unregisterObserver();
407     registerObserver(document);
408 }
409
410 Document::Document(const DocumentInit& initializer, DocumentClassFlags documentClasses)
411     : ContainerNode(0, CreateDocument)
412     , TreeScope(*this)
413     , m_hasNodesWithPlaceholderStyle(false)
414     , m_needsNotifyRemoveAllPendingStylesheet(false)
415     , m_evaluateMediaQueriesOnStyleRecalc(false)
416     , m_pendingSheetLayout(NoLayoutWithPendingSheets)
417     , m_frame(initializer.frame())
418     , m_domWindow(m_frame ? m_frame->domWindow() : 0)
419     , m_importsController(initializer.importsController())
420     , m_activeParserCount(0)
421     , m_contextFeatures(ContextFeatures::defaultSwitch())
422     , m_wellFormed(false)
423     , m_printing(false)
424     , m_paginatedForScreen(false)
425     , m_compatibilityMode(NoQuirksMode)
426     , m_compatibilityModeLocked(false)
427     , m_hasAutofocused(false)
428     , m_clearFocusedElementTimer(this, &Document::clearFocusedElementTimerFired)
429     , m_domTreeVersion(++s_globalTreeVersion)
430     , m_listenerTypes(0)
431     , m_mutationObserverTypes(0)
432     , m_visitedLinkState(VisitedLinkState::create(*this))
433     , m_visuallyOrdered(false)
434     , m_readyState(Complete)
435     , m_isParsing(false)
436     , m_gotoAnchorNeededAfterStylesheetsLoad(false)
437     , m_containsValidityStyleRules(false)
438     , m_updateFocusAppearanceRestoresSelection(false)
439     , m_containsPlugins(false)
440     , m_ignoreDestructiveWriteCount(0)
441     , m_titleSetExplicitly(false)
442     , m_markers(adoptPtr(new DocumentMarkerController))
443     , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
444     , m_cssTarget(0)
445     , m_loadEventProgress(LoadEventNotRun)
446     , m_startTime(currentTime())
447     , m_scriptRunner(ScriptRunner::create(this))
448     , m_xmlVersion("1.0")
449     , m_xmlStandalone(StandaloneUnspecified)
450     , m_hasXMLDeclaration(0)
451     , m_designMode(inherit)
452     , m_hasAnnotatedRegions(false)
453     , m_annotatedRegionsDirty(false)
454     , m_useSecureKeyboardEntryWhenActive(false)
455     , m_documentClasses(documentClasses)
456     , m_isViewSource(false)
457     , m_sawElementsInKnownNamespaces(false)
458     , m_isSrcdocDocument(false)
459     , m_isMobileDocument(false)
460     , m_renderView(0)
461     , m_weakFactory(this)
462     , m_contextDocument(initializer.contextDocument())
463     , m_hasFullscreenElementStack(false)
464     , m_loadEventDelayCount(0)
465     , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
466     , m_pluginLoadingTimer(this, &Document::pluginLoadingTimerFired)
467     , m_didSetReferrerPolicy(false)
468     , m_referrerPolicy(ReferrerPolicyDefault)
469     , m_directionSetOnDocumentElement(false)
470     , m_writingModeSetOnDocumentElement(false)
471     , m_writeRecursionIsTooDeep(false)
472     , m_writeRecursionDepth(0)
473     , m_taskRunner(MainThreadTaskRunner::create(this))
474     , m_registrationContext(initializer.registrationContext(this))
475     , m_elementDataCacheClearTimer(this, &Document::elementDataCacheClearTimerFired)
476 #ifndef NDEBUG
477     , m_didDispatchViewportPropertiesChanged(false)
478 #endif
479     , m_animationClock(AnimationClock::create())
480     , m_timeline(DocumentTimeline::create(this))
481     , m_transitionTimeline(TransitionTimeline::create(this))
482     , m_templateDocumentHost(nullptr)
483     , m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
484     , m_hasViewportUnits(false)
485     , m_styleRecalcElementCounter(0)
486 {
487     setClient(this);
488     ScriptWrappable::init(this);
489
490     if (m_frame) {
491         ASSERT(m_frame->page());
492         provideContextFeaturesToDocumentFrom(*this, *m_frame->page());
493
494         m_fetcher = m_frame->loader().documentLoader()->fetcher();
495     }
496
497     if (!m_fetcher)
498         m_fetcher = ResourceFetcher::create(0);
499     m_fetcher->setDocument(this);
500
501     // We depend on the url getting immediately set in subframes, but we
502     // also depend on the url NOT getting immediately set in opened windows.
503     // See fast/dom/early-frame-url.html
504     // and fast/dom/location-new-window-no-crash.html, respectively.
505     // FIXME: Can/should we unify this behavior?
506     if (initializer.shouldSetURL())
507         setURL(initializer.url());
508
509     initSecurityContext(initializer);
510     initDNSPrefetch();
511
512     for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
513         m_nodeListCounts[i] = 0;
514
515     InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
516
517     m_lifecycle.advanceTo(DocumentLifecycle::Inactive);
518
519     // Since CSSFontSelector requires Document::m_fetcher and StyleEngine owns
520     // CSSFontSelector, need to initialize m_styleEngine after initializing
521     // m_fetcher.
522     m_styleEngine = StyleEngine::create(*this);
523 }
524
525 Document::~Document()
526 {
527     ASSERT(!renderView());
528     ASSERT(m_ranges.isEmpty());
529     ASSERT(!parentTreeScope());
530 #if !ENABLE(OILPAN)
531     ASSERT(!hasGuardRefCount());
532     // With Oilpan, either the document outlives the visibility observers
533     // or the visibility observers and the document die in the same GC round.
534     // When they die in the same GC round, the list of visibility observers
535     // will not be empty on Document destruction.
536     ASSERT(m_visibilityObservers.isEmpty());
537
538     if (m_templateDocument)
539         m_templateDocument->m_templateDocumentHost = nullptr; // balanced in ensureTemplateDocument().
540 #endif
541
542     m_scriptRunner.clear();
543
544     // FIXME: Oilpan: Not removing event listeners here also means that we do
545     // not notify the inspector instrumentation that the event listeners are
546     // gone. The Document and all the nodes in the document are gone, so maybe
547     // that is OK?
548 #if !ENABLE(OILPAN)
549     removeAllEventListenersRecursively();
550 #endif
551
552     // Currently we believe that Document can never outlive the parser.
553     // Although the Document may be replaced synchronously, DocumentParsers
554     // generally keep at least one reference to an Element which would in turn
555     // has a reference to the Document.  If you hit this ASSERT, then that
556     // assumption is wrong.  DocumentParser::detach() should ensure that even
557     // if the DocumentParser outlives the Document it won't cause badness.
558     ASSERT(!m_parser || m_parser->refCount() == 1);
559     detachParser();
560
561     if (this == topDocument())
562         clearAXObjectCache();
563
564 #if !ENABLE(OILPAN)
565     if (m_styleSheetList)
566         m_styleSheetList->detachFromDocument();
567 #endif
568
569     if (m_importsController) {
570         m_importsController->wasDetachedFrom(*this);
571         m_importsController = 0;
572     }
573
574     m_timeline->detachFromDocument();
575     m_transitionTimeline->detachFromDocument();
576
577 #if !ENABLE(OILPAN)
578     // We need to destroy CSSFontSelector before destroying m_fetcher.
579     if (m_styleEngine)
580         m_styleEngine->detachFromDocument();
581
582     if (m_elemSheet)
583         m_elemSheet->clearOwnerNode();
584
585     // It's possible for multiple Documents to end up referencing the same ResourceFetcher (e.g., SVGImages
586     // load the initial empty document and the SVGDocument with the same DocumentLoader).
587     if (m_fetcher->document() == this)
588         m_fetcher->setDocument(nullptr);
589     m_fetcher.clear();
590 #endif
591
592     // We must call clearRareData() here since a Document class inherits TreeScope
593     // as well as Node. See a comment on TreeScope.h for the reason.
594 #if !ENABLE(OILPAN)
595     if (hasRareData())
596         clearRareData();
597 #endif
598
599     ASSERT(!m_listsInvalidatedAtDocument.size());
600
601     for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
602         ASSERT(!m_nodeListCounts[i]);
603
604     setClient(0);
605
606     InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
607 }
608
609 void Document::dispose()
610 {
611 #if !ENABLE(OILPAN)
612     ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
613
614     // We must make sure not to be retaining any of our children through
615     // these extra pointers or we will create a reference cycle.
616     m_docType = nullptr;
617     m_focusedElement = nullptr;
618     m_hoverNode = nullptr;
619     m_activeHoverElement = nullptr;
620     m_titleElement = nullptr;
621     m_documentElement = nullptr;
622     m_contextFeatures = ContextFeatures::defaultSwitch();
623     m_userActionElements.documentDidRemoveLastRef();
624     m_associatedFormControls.clear();
625
626     detachParser();
627 #endif
628
629     m_registrationContext.clear();
630
631     if (m_importsController) {
632         m_importsController->wasDetachedFrom(*this);
633         m_importsController = 0;
634     }
635
636 #if !ENABLE(OILPAN)
637     // removeDetachedChildren() doesn't always unregister IDs,
638     // so tear down scope information upfront to avoid having stale references in the map.
639     destroyTreeScopeData();
640
641     removeDetachedChildren();
642
643     // removeDetachedChildren() can access FormController.
644     m_formController.clear();
645
646     m_markers->clear();
647
648     m_cssCanvasElements.clear();
649 #endif
650
651     // FIXME: consider using ActiveDOMObject.
652     if (m_scriptedAnimationController)
653         m_scriptedAnimationController->clearDocumentPointer();
654     m_scriptedAnimationController.clear();
655
656     if (svgExtensions())
657         accessSVGExtensions().pauseAnimations();
658
659     m_lifecycle.advanceTo(DocumentLifecycle::Disposed);
660     lifecycleNotifier().notifyDocumentWasDisposed();
661 }
662
663 SelectorQueryCache& Document::selectorQueryCache()
664 {
665     if (!m_selectorQueryCache)
666         m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
667     return *m_selectorQueryCache;
668 }
669
670 MediaQueryMatcher& Document::mediaQueryMatcher()
671 {
672     if (!m_mediaQueryMatcher)
673         m_mediaQueryMatcher = MediaQueryMatcher::create(this);
674     return *m_mediaQueryMatcher;
675 }
676
677 void Document::mediaQueryAffectingValueChanged()
678 {
679     styleEngine()->clearMediaQueryRuleSetStyleSheets();
680 }
681
682 void Document::setCompatibilityMode(CompatibilityMode mode)
683 {
684     if (m_compatibilityModeLocked || mode == m_compatibilityMode)
685         return;
686     bool wasInQuirksMode = inQuirksMode();
687     m_compatibilityMode = mode;
688     selectorQueryCache().invalidate();
689     if (inQuirksMode() != wasInQuirksMode) {
690         // All injected stylesheets have to reparse using the different mode.
691         m_styleEngine->invalidateInjectedStyleSheetCache();
692     }
693 }
694
695 String Document::compatMode() const
696 {
697     return inQuirksMode() ? "BackCompat" : "CSS1Compat";
698 }
699
700 void Document::setDoctype(PassRefPtr<DocumentType> docType)
701 {
702     // This should never be called more than once.
703     ASSERT(!m_docType || !docType);
704     m_docType = docType;
705     if (m_docType) {
706         this->adoptIfNeeded(*m_docType);
707         if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
708             m_isMobileDocument = true;
709     }
710     // Doctype affects the interpretation of the stylesheets.
711     clearStyleResolver();
712 }
713
714 DOMImplementation& Document::implementation()
715 {
716     if (!m_implementation)
717         m_implementation = DOMImplementation::create(*this);
718     return *m_implementation;
719 }
720
721 bool Document::hasManifest() const
722 {
723     return isHTMLHtmlElement(documentElement()) && documentElement()->hasAttribute(manifestAttr);
724 }
725
726 Location* Document::location() const
727 {
728     if (!frame())
729         return 0;
730
731     return &domWindow()->location();
732 }
733
734 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
735 {
736     ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
737     m_documentElement = ElementTraversal::firstWithin(*this);
738 }
739
740 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& exceptionState)
741 {
742     if (!isValidName(name)) {
743         exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + name + "') is not a valid name.");
744         return nullptr;
745     }
746
747     if (isXHTMLDocument() || isHTMLDocument())
748         return HTMLElementFactory::createHTMLElement(isHTMLDocument() ? name.lower() : name, *this, 0, false);
749
750     return Element::create(QualifiedName(nullAtom, name, nullAtom), this);
751 }
752
753 PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& exceptionState)
754 {
755     if (!isValidName(localName)) {
756         exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + localName + "') is not a valid name.");
757         return nullptr;
758     }
759
760     RefPtr<Element> element;
761
762     if (CustomElement::isValidName(localName) && registrationContext()) {
763         element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI));
764     } else {
765         element = createElement(localName, exceptionState);
766         if (exceptionState.hadException())
767             return nullptr;
768     }
769
770     if (!typeExtension.isEmpty())
771         CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
772
773     return element;
774 }
775
776 static inline QualifiedName createQualifiedName(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
777 {
778     AtomicString prefix, localName;
779     if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
780         return nullQName();
781
782     QualifiedName qName(prefix, localName, namespaceURI);
783     if (!Document::hasValidNamespaceForElements(qName)) {
784         exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
785         return nullQName();
786     }
787
788     return qName;
789 }
790
791 PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
792 {
793     QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
794     if (qName == nullQName())
795         return nullptr;
796
797     return createElement(qName, false);
798 }
799
800 PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
801 {
802     QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
803     if (qName == nullQName())
804         return nullptr;
805
806     RefPtr<Element> element;
807     if (CustomElement::isValidName(qName.localName()) && registrationContext())
808         element = registrationContext()->createCustomTagElement(*this, qName);
809     else
810         element = createElement(qName, false);
811
812     if (!typeExtension.isEmpty())
813         CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
814
815     return element;
816 }
817
818 ScriptValue Document::registerElement(WebCore::ScriptState* scriptState, const AtomicString& name, ExceptionState& exceptionState)
819 {
820     return registerElement(scriptState, name, Dictionary(), exceptionState);
821 }
822
823 ScriptValue Document::registerElement(WebCore::ScriptState* scriptState, const AtomicString& name, const Dictionary& options, ExceptionState& exceptionState, CustomElement::NameSet validNames)
824 {
825     if (!registrationContext()) {
826         exceptionState.throwDOMException(NotSupportedError, "No element registration context is available.");
827         return ScriptValue();
828     }
829
830     CustomElementConstructorBuilder constructorBuilder(scriptState, &options);
831     registrationContext()->registerElement(this, &constructorBuilder, name, validNames, exceptionState);
832     return constructorBuilder.bindingsReturnValue();
833 }
834
835 void Document::setImportsController(HTMLImportsController* controller)
836 {
837     ASSERT(!m_importsController || !controller);
838     m_importsController = controller;
839 }
840
841 HTMLImportLoader* Document::importLoader() const
842 {
843     if (!m_importsController)
844         return 0;
845     return m_importsController->loaderFor(*this);
846 }
847
848 bool Document::haveImportsLoaded() const
849 {
850     if (!m_importsController)
851         return true;
852     return !m_importsController->shouldBlockScriptExecution(*this);
853 }
854
855 DOMWindow* Document::executingWindow()
856 {
857     if (DOMWindow* owningWindow = domWindow())
858         return owningWindow;
859     if (HTMLImportsController* import = this->importsController())
860         return import->master()->domWindow();
861     return 0;
862 }
863
864 LocalFrame* Document::executingFrame()
865 {
866     DOMWindow* window = executingWindow();
867     if (!window)
868         return 0;
869     return window->frame();
870 }
871
872 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
873 {
874     return DocumentFragment::create(*this);
875 }
876
877 PassRefPtr<Text> Document::createTextNode(const String& data)
878 {
879     return Text::create(*this, data);
880 }
881
882 PassRefPtr<Comment> Document::createComment(const String& data)
883 {
884     return Comment::create(*this, data);
885 }
886
887 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& exceptionState)
888 {
889     if (isHTMLDocument()) {
890         exceptionState.throwDOMException(NotSupportedError, "This operation is not supported for HTML documents.");
891         return nullptr;
892     }
893     if (data.contains("]]>")) {
894         exceptionState.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
895         return nullptr;
896     }
897     return CDATASection::create(*this, data);
898 }
899
900 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& exceptionState)
901 {
902     if (!isValidName(target)) {
903         exceptionState.throwDOMException(InvalidCharacterError, "The target provided ('" + target + "') is not a valid name.");
904         return nullptr;
905     }
906     if (data.contains("?>")) {
907         exceptionState.throwDOMException(InvalidCharacterError, "The data provided ('" + data + "') contains '?>'.");
908         return nullptr;
909     }
910     return ProcessingInstruction::create(*this, target, data);
911 }
912
913 PassRefPtr<Text> Document::createEditingTextNode(const String& text)
914 {
915     return Text::createEditingText(*this, text);
916 }
917
918 bool Document::importContainerNodeChildren(ContainerNode* oldContainerNode, PassRefPtr<ContainerNode> newContainerNode, ExceptionState& exceptionState)
919 {
920     for (Node* oldChild = oldContainerNode->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
921         RefPtr<Node> newChild = importNode(oldChild, true, exceptionState);
922         if (exceptionState.hadException())
923             return false;
924         newContainerNode->appendChild(newChild.release(), exceptionState);
925         if (exceptionState.hadException())
926             return false;
927     }
928
929     return true;
930 }
931
932 PassRefPtr<Node> Document::importNode(Node* importedNode, ExceptionState& ec)
933 {
934     UseCounter::countDeprecation(this, UseCounter::DocumentImportNodeOptionalArgument);
935     return importNode(importedNode, true, ec);
936 }
937
938 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& exceptionState)
939 {
940     if (!importedNode) {
941         exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
942         return nullptr;
943     }
944
945     switch (importedNode->nodeType()) {
946     case TEXT_NODE:
947         return createTextNode(importedNode->nodeValue());
948     case CDATA_SECTION_NODE:
949         return createCDATASection(importedNode->nodeValue(), exceptionState);
950     case PROCESSING_INSTRUCTION_NODE:
951         return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), exceptionState);
952     case COMMENT_NODE:
953         return createComment(importedNode->nodeValue());
954     case DOCUMENT_TYPE_NODE: {
955         DocumentType* doctype = toDocumentType(importedNode);
956         return DocumentType::create(this, doctype->name(), doctype->publicId(), doctype->systemId());
957     }
958     case ELEMENT_NODE: {
959         Element* oldElement = toElement(importedNode);
960         // FIXME: The following check might be unnecessary. Is it possible that
961         // oldElement has mismatched prefix/namespace?
962         if (!hasValidNamespaceForElements(oldElement->tagQName())) {
963             exceptionState.throwDOMException(NamespaceError, "The imported node has an invalid namespace.");
964             return nullptr;
965         }
966         RefPtr<Element> newElement = createElement(oldElement->tagQName(), false);
967
968         newElement->cloneDataFromElement(*oldElement);
969
970         if (deep) {
971             if (!importContainerNodeChildren(oldElement, newElement, exceptionState))
972                 return nullptr;
973             if (isHTMLTemplateElement(*oldElement)
974                 && !importContainerNodeChildren(toHTMLTemplateElement(oldElement)->content(), toHTMLTemplateElement(newElement)->content(), exceptionState))
975                 return nullptr;
976         }
977
978         return newElement.release();
979     }
980     case ATTRIBUTE_NODE:
981         return Attr::create(*this, QualifiedName(nullAtom, AtomicString(toAttr(importedNode)->name()), nullAtom), toAttr(importedNode)->value());
982     case DOCUMENT_FRAGMENT_NODE: {
983         if (importedNode->isShadowRoot()) {
984             // ShadowRoot nodes should not be explicitly importable.
985             // Either they are imported along with their host node, or created implicitly.
986             exceptionState.throwDOMException(NotSupportedError, "The node provided is a shadow root, which may not be imported.");
987             return nullptr;
988         }
989         DocumentFragment* oldFragment = toDocumentFragment(importedNode);
990         RefPtr<DocumentFragment> newFragment = createDocumentFragment();
991         if (deep && !importContainerNodeChildren(oldFragment, newFragment, exceptionState))
992             return nullptr;
993
994         return newFragment.release();
995     }
996     case DOCUMENT_NODE:
997         exceptionState.throwDOMException(NotSupportedError, "The node provided is a document, which may not be imported.");
998         return nullptr;
999     }
1000
1001     ASSERT_NOT_REACHED();
1002     return nullptr;
1003 }
1004
1005 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionState& exceptionState)
1006 {
1007     if (!source) {
1008         exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1009         return nullptr;
1010     }
1011
1012     EventQueueScope scope;
1013
1014     switch (source->nodeType()) {
1015     case DOCUMENT_NODE:
1016     case DOCUMENT_TYPE_NODE:
1017         exceptionState.throwDOMException(NotSupportedError, "The node provided is of type '" + source->nodeName() + "', which may not be adopted.");
1018         return nullptr;
1019     case ATTRIBUTE_NODE: {
1020         Attr* attr = toAttr(source.get());
1021         if (attr->ownerElement())
1022             attr->ownerElement()->removeAttributeNode(attr, exceptionState);
1023         break;
1024     }
1025     default:
1026         if (source->isShadowRoot()) {
1027             // ShadowRoot cannot disconnect itself from the host node.
1028             exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a shadow root, which may not be adopted.");
1029             return nullptr;
1030         }
1031
1032         if (source->isFrameOwnerElement()) {
1033             HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
1034             // FIXME(kenrb): the downcast can be removed when the FrameTree supports RemoteFrames.
1035             if (frame() && frame()->tree().isDescendantOf(toLocalFrameTemporary(frameOwnerElement->contentFrame()))) {
1036                 exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a frame which contains this document.");
1037                 return nullptr;
1038             }
1039         }
1040         if (source->parentNode()) {
1041             source->parentNode()->removeChild(source.get(), exceptionState);
1042             if (exceptionState.hadException())
1043                 return nullptr;
1044         }
1045     }
1046
1047     this->adoptIfNeeded(*source);
1048
1049     return source;
1050 }
1051
1052 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1053 {
1054     // These checks are from DOM Core Level 2, createElementNS
1055     // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1056     if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1057         return false;
1058     if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1059         return false;
1060
1061     // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1062     // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1063     // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1064     if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1065         return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1066     return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1067 }
1068
1069 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1070 {
1071     return hasValidNamespaceForElements(qName);
1072 }
1073
1074 // FIXME: This should really be in a possible ElementFactory class
1075 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
1076 {
1077     RefPtr<Element> e;
1078
1079     // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1080     if (qName.namespaceURI() == xhtmlNamespaceURI)
1081         e = HTMLElementFactory::createHTMLElement(qName.localName(), *this, 0, createdByParser);
1082     else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
1083         e = SVGElementFactory::createSVGElement(qName.localName(), *this, createdByParser);
1084
1085     if (e)
1086         m_sawElementsInKnownNamespaces = true;
1087     else
1088         e = Element::create(qName, this);
1089
1090     if (e->prefix() != qName.prefix())
1091         e->setTagNameForCreateElementNS(qName);
1092
1093     ASSERT(qName == e->tagQName());
1094
1095     return e.release();
1096 }
1097
1098 bool Document::regionBasedColumnsEnabled() const
1099 {
1100     return settings() && settings()->regionBasedColumnsEnabled();
1101 }
1102
1103 String Document::readyState() const
1104 {
1105     DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
1106     DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
1107     DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
1108
1109     switch (m_readyState) {
1110     case Loading:
1111         return loading;
1112     case Interactive:
1113         return interactive;
1114     case Complete:
1115         return complete;
1116     }
1117
1118     ASSERT_NOT_REACHED();
1119     return String();
1120 }
1121
1122 void Document::setReadyState(ReadyState readyState)
1123 {
1124     if (readyState == m_readyState)
1125         return;
1126
1127     switch (readyState) {
1128     case Loading:
1129         if (!m_documentTiming.domLoading) {
1130             m_documentTiming.domLoading = monotonicallyIncreasingTime();
1131             m_timeline->setZeroTime(m_documentTiming.domLoading);
1132         }
1133         break;
1134     case Interactive:
1135         if (!m_documentTiming.domInteractive)
1136             m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1137         break;
1138     case Complete:
1139         if (!m_documentTiming.domComplete)
1140             m_documentTiming.domComplete = monotonicallyIncreasingTime();
1141         break;
1142     }
1143
1144     m_readyState = readyState;
1145     dispatchEvent(Event::create(EventTypeNames::readystatechange));
1146 }
1147
1148 bool Document::isLoadCompleted()
1149 {
1150     return m_readyState == Complete;
1151 }
1152
1153 AtomicString Document::encodingName() const
1154 {
1155     // TextEncoding::name() returns a char*, no need to allocate a new
1156     // String for it each time.
1157     // FIXME: We should fix TextEncoding to speak AtomicString anyway.
1158     return AtomicString(encoding().name());
1159 }
1160
1161 String Document::defaultCharset() const
1162 {
1163     if (Settings* settings = this->settings())
1164         return settings->defaultTextEncodingName();
1165     return String();
1166 }
1167
1168 void Document::setCharset(const String& charset)
1169 {
1170     if (DocumentLoader* documentLoader = loader())
1171         documentLoader->setUserChosenEncoding(charset);
1172     WTF::TextEncoding encoding(charset);
1173     // In case the encoding didn't exist, we keep the old one (helps some sites specifying invalid encodings).
1174     if (!encoding.isValid())
1175         return;
1176     DocumentEncodingData newEncodingData = m_encodingData;
1177     newEncodingData.setEncoding(encoding);
1178     setEncodingData(newEncodingData);
1179 }
1180
1181 void Document::setContentLanguage(const AtomicString& language)
1182 {
1183     if (m_contentLanguage == language)
1184         return;
1185     m_contentLanguage = language;
1186
1187     // Document's style depends on the content language.
1188     setNeedsStyleRecalc(SubtreeStyleChange);
1189 }
1190
1191 void Document::setXMLVersion(const String& version, ExceptionState& exceptionState)
1192 {
1193     if (!XMLDocumentParser::supportsXMLVersion(version)) {
1194         exceptionState.throwDOMException(NotSupportedError, "This document does not support the XML version '" + version + "'.");
1195         return;
1196     }
1197
1198     m_xmlVersion = version;
1199 }
1200
1201 void Document::setXMLStandalone(bool standalone, ExceptionState& exceptionState)
1202 {
1203     m_xmlStandalone = standalone ? Standalone : NotStandalone;
1204 }
1205
1206 KURL Document::baseURI() const
1207 {
1208     return m_baseURL;
1209 }
1210
1211 void Document::setContent(const String& content)
1212 {
1213     open();
1214     // FIXME: This should probably use insert(), but that's (intentionally)
1215     // not implemented for the XML parser as it's normally synonymous with
1216     // document.write(). append() will end up yielding, but close() will
1217     // pump the tokenizer syncrhonously and finish the parse.
1218     m_parser->pinToMainThread();
1219     m_parser->append(content.impl());
1220     close();
1221 }
1222
1223 String Document::suggestedMIMEType() const
1224 {
1225     if (isXMLDocument()) {
1226         if (isXHTMLDocument())
1227             return "application/xhtml+xml";
1228         if (isSVGDocument())
1229             return "image/svg+xml";
1230         return "application/xml";
1231     }
1232     if (xmlStandalone())
1233         return "text/xml";
1234     if (isHTMLDocument())
1235         return "text/html";
1236
1237     if (DocumentLoader* documentLoader = loader())
1238         return documentLoader->responseMIMEType();
1239     return String();
1240 }
1241
1242 void Document::setMimeType(const AtomicString& mimeType)
1243 {
1244     m_mimeType = mimeType;
1245 }
1246
1247 AtomicString Document::contentType() const
1248 {
1249     if (!m_mimeType.isEmpty())
1250         return m_mimeType;
1251
1252     if (DocumentLoader* documentLoader = loader())
1253         return documentLoader->mimeType();
1254
1255     String mimeType = suggestedMIMEType();
1256     if (!mimeType.isEmpty())
1257         return AtomicString(mimeType);
1258
1259     return AtomicString("application/xml");
1260 }
1261
1262 Element* Document::elementFromPoint(int x, int y) const
1263 {
1264     if (!renderView())
1265         return 0;
1266
1267     return TreeScope::elementFromPoint(x, y);
1268 }
1269
1270 PassRefPtrWillBeRawPtr<Range> Document::caretRangeFromPoint(int x, int y)
1271 {
1272     if (!renderView())
1273         return nullptr;
1274     HitTestResult result = hitTestInDocument(this, x, y);
1275     RenderObject* renderer = result.renderer();
1276     if (!renderer)
1277         return nullptr;
1278
1279     Node* node = renderer->node();
1280     Node* shadowAncestorNode = ancestorInThisScope(node);
1281     if (shadowAncestorNode != node) {
1282         unsigned offset = shadowAncestorNode->nodeIndex();
1283         ContainerNode* container = shadowAncestorNode->parentNode();
1284         return Range::create(*this, container, offset, container, offset);
1285     }
1286
1287     PositionWithAffinity positionWithAffinity = renderer->positionForPoint(result.localPoint());
1288     if (positionWithAffinity.position().isNull())
1289         return nullptr;
1290
1291     Position rangeCompliantPosition = positionWithAffinity.position().parentAnchoredEquivalent();
1292     return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1293 }
1294
1295 /*
1296  * Performs three operations:
1297  *  1. Convert control characters to spaces
1298  *  2. Trim leading and trailing spaces
1299  *  3. Collapse internal whitespace.
1300  */
1301 template <typename CharacterType>
1302 static inline String canonicalizedTitle(Document* document, const String& title)
1303 {
1304     const CharacterType* characters = title.getCharacters<CharacterType>();
1305     unsigned length = title.length();
1306     unsigned i;
1307
1308     StringBuffer<CharacterType> buffer(length);
1309     unsigned builderIndex = 0;
1310
1311     // Skip leading spaces and leading characters that would convert to spaces
1312     for (i = 0; i < length; ++i) {
1313         CharacterType c = characters[i];
1314         if (!(c <= 0x20 || c == 0x7F))
1315             break;
1316     }
1317
1318     if (i == length)
1319         return String();
1320
1321     // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1322     bool previousCharWasWS = false;
1323     for (; i < length; ++i) {
1324         CharacterType c = characters[i];
1325         if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1326             if (previousCharWasWS)
1327                 continue;
1328             buffer[builderIndex++] = ' ';
1329             previousCharWasWS = true;
1330         } else {
1331             buffer[builderIndex++] = c;
1332             previousCharWasWS = false;
1333         }
1334     }
1335
1336     // Strip trailing spaces
1337     while (builderIndex > 0) {
1338         --builderIndex;
1339         if (buffer[builderIndex] != ' ')
1340             break;
1341     }
1342
1343     if (!builderIndex && buffer[builderIndex] == ' ')
1344         return String();
1345
1346     buffer.shrink(builderIndex + 1);
1347
1348     return String::adopt(buffer);
1349 }
1350
1351 void Document::updateTitle(const String& title)
1352 {
1353     if (m_rawTitle == title)
1354         return;
1355
1356     m_rawTitle = title;
1357
1358     String oldTitle = m_title;
1359     if (m_rawTitle.isEmpty())
1360         m_title = String();
1361     else if (m_rawTitle.is8Bit())
1362         m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1363     else
1364         m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1365
1366     if (!m_frame || oldTitle == m_title)
1367         return;
1368     m_frame->loader().client()->dispatchDidReceiveTitle(m_title);
1369 }
1370
1371 void Document::setTitle(const String& title)
1372 {
1373     // Title set by JavaScript -- overrides any title elements.
1374     m_titleSetExplicitly = true;
1375     if (!isHTMLDocument() && !isXHTMLDocument())
1376         m_titleElement = nullptr;
1377     else if (!m_titleElement) {
1378         if (HTMLElement* headElement = head()) {
1379             m_titleElement = HTMLTitleElement::create(*this);
1380             headElement->appendChild(m_titleElement.get());
1381         }
1382     }
1383
1384     if (isHTMLTitleElement(m_titleElement))
1385         toHTMLTitleElement(m_titleElement)->setText(title);
1386     else
1387         updateTitle(title);
1388 }
1389
1390 void Document::setTitleElement(const String& title, Element* titleElement)
1391 {
1392     if (titleElement != m_titleElement) {
1393         if (m_titleElement || m_titleSetExplicitly)
1394             // Only allow the first title element to change the title -- others have no effect.
1395             return;
1396         m_titleElement = titleElement;
1397     }
1398
1399     updateTitle(title);
1400 }
1401
1402 void Document::removeTitle(Element* titleElement)
1403 {
1404     if (m_titleElement != titleElement)
1405         return;
1406
1407     m_titleElement = nullptr;
1408     m_titleSetExplicitly = false;
1409
1410     // FIXME: This is broken for SVG.
1411     // Update title based on first title element in the head, if one exists.
1412     if (HTMLElement* headElement = head()) {
1413         if (HTMLTitleElement* title = Traversal<HTMLTitleElement>::firstChild(*headElement))
1414             setTitleElement(title->text(), title);
1415     }
1416
1417     if (!m_titleElement)
1418         updateTitle(String());
1419 }
1420
1421 const AtomicString& Document::dir()
1422 {
1423     Element* rootElement = documentElement();
1424     if (isHTMLHtmlElement(rootElement))
1425         return toHTMLHtmlElement(rootElement)->dir();
1426     return nullAtom;
1427 }
1428
1429 void Document::setDir(const AtomicString& value)
1430 {
1431     Element* rootElement = documentElement();
1432     if (isHTMLHtmlElement(rootElement))
1433         toHTMLHtmlElement(rootElement)->setDir(value);
1434 }
1435
1436 PageVisibilityState Document::pageVisibilityState() const
1437 {
1438     // The visibility of the document is inherited from the visibility of the
1439     // page. If there is no page associated with the document, we will assume
1440     // that the page is hidden, as specified by the spec:
1441     // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1442     if (!m_frame || !m_frame->page())
1443         return PageVisibilityStateHidden;
1444     return m_frame->page()->visibilityState();
1445 }
1446
1447 String Document::visibilityState() const
1448 {
1449     return pageVisibilityStateString(pageVisibilityState());
1450 }
1451
1452 bool Document::hidden() const
1453 {
1454     return pageVisibilityState() != PageVisibilityStateVisible;
1455 }
1456
1457 void Document::didChangeVisibilityState()
1458 {
1459     dispatchEvent(Event::create(EventTypeNames::visibilitychange));
1460     // Also send out the deprecated version until it can be removed.
1461     dispatchEvent(Event::create(EventTypeNames::webkitvisibilitychange));
1462
1463     PageVisibilityState state = pageVisibilityState();
1464     DocumentVisibilityObserverSet::const_iterator observerEnd = m_visibilityObservers.end();
1465     for (DocumentVisibilityObserverSet::const_iterator it = m_visibilityObservers.begin(); it != observerEnd; ++it)
1466         (*it)->didChangeVisibilityState(state);
1467 }
1468
1469 void Document::registerVisibilityObserver(DocumentVisibilityObserver* observer)
1470 {
1471     ASSERT(!m_visibilityObservers.contains(observer));
1472     m_visibilityObservers.add(observer);
1473 }
1474
1475 void Document::unregisterVisibilityObserver(DocumentVisibilityObserver* observer)
1476 {
1477     ASSERT(m_visibilityObservers.contains(observer));
1478     m_visibilityObservers.remove(observer);
1479 }
1480
1481 String Document::nodeName() const
1482 {
1483     return "#document";
1484 }
1485
1486 Node::NodeType Document::nodeType() const
1487 {
1488     return DOCUMENT_NODE;
1489 }
1490
1491 FormController& Document::formController()
1492 {
1493     if (!m_formController) {
1494         m_formController = FormController::create();
1495         if (m_frame && m_frame->loader().currentItem() && m_frame->loader().currentItem()->isCurrentDocument(this))
1496             m_frame->loader().currentItem()->setDocumentState(m_formController->formElementsState());
1497     }
1498     return *m_formController;
1499 }
1500
1501 DocumentState* Document::formElementsState() const
1502 {
1503     if (!m_formController)
1504         return 0;
1505     return m_formController->formElementsState();
1506 }
1507
1508 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1509 {
1510     if (!stateVector.size() && !m_formController)
1511         return;
1512     formController().setStateForNewFormElements(stateVector);
1513 }
1514
1515 FrameView* Document::view() const
1516 {
1517     return m_frame ? m_frame->view() : 0;
1518 }
1519
1520 Page* Document::page() const
1521 {
1522     return m_frame ? m_frame->page() : 0;
1523 }
1524
1525 FrameHost* Document::frameHost() const
1526 {
1527     return m_frame ? m_frame->host() : 0;
1528 }
1529
1530 Settings* Document::settings() const
1531 {
1532     return m_frame ? m_frame->settings() : 0;
1533 }
1534
1535 PassRefPtrWillBeRawPtr<Range> Document::createRange()
1536 {
1537     return Range::create(*this);
1538 }
1539
1540 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionState& exceptionState)
1541 {
1542     // FIXME: Probably this should be handled within the bindings layer and TypeError should be thrown.
1543     if (!root) {
1544         exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1545         return nullptr;
1546     }
1547     return NodeIterator::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
1548 }
1549
1550 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
1551 {
1552     if (!root) {
1553         exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1554         return nullptr;
1555     }
1556     // FIXME: It might be a good idea to emit a warning if |whatToShow| contains a bit that is not defined in
1557     // NodeFilter.
1558     return NodeIterator::create(root, whatToShow, PassRefPtr<NodeFilter>());
1559 }
1560
1561 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
1562 {
1563     if (!root) {
1564         exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1565         return nullptr;
1566     }
1567     // FIXME: Ditto.
1568     return NodeIterator::create(root, whatToShow, filter);
1569 }
1570
1571 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionState& exceptionState)
1572 {
1573     if (!root) {
1574         exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1575         return nullptr;
1576     }
1577     return TreeWalker::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
1578 }
1579
1580 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
1581 {
1582     if (!root) {
1583         exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1584         return nullptr;
1585     }
1586     return TreeWalker::create(root, whatToShow, PassRefPtr<NodeFilter>());
1587 }
1588
1589 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
1590 {
1591     if (!root) {
1592         exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::argumentNullOrIncorrectType(1, "Node"));
1593         return nullptr;
1594     }
1595     return TreeWalker::create(root, whatToShow, filter);
1596 }
1597
1598 bool Document::needsRenderTreeUpdate() const
1599 {
1600     if (!isActive() || !view())
1601         return false;
1602     if (needsFullRenderTreeUpdate())
1603         return true;
1604     if (childNeedsStyleRecalc())
1605         return true;
1606     if (childNeedsStyleInvalidation())
1607         return true;
1608     return false;
1609 }
1610
1611 bool Document::needsFullRenderTreeUpdate() const
1612 {
1613     if (!isActive() || !view())
1614         return false;
1615     if (!m_useElementsNeedingUpdate.isEmpty())
1616         return true;
1617     if (!m_layerUpdateElements.isEmpty())
1618         return true;
1619     if (needsStyleRecalc())
1620         return true;
1621     if (needsStyleInvalidation())
1622         return true;
1623     // FIXME: The childNeedsDistributionRecalc bit means either self or children, we should fix that.
1624     if (childNeedsDistributionRecalc())
1625         return true;
1626     if (DocumentAnimations::needsOutdatedAnimationPlayerUpdate(*this))
1627         return true;
1628     return false;
1629 }
1630
1631 bool Document::shouldScheduleRenderTreeUpdate() const
1632 {
1633     if (!isActive())
1634         return false;
1635     if (inStyleRecalc())
1636         return false;
1637     // InPreLayout will recalc style itself. There's no reason to schedule another recalc.
1638     if (m_lifecycle.state() == DocumentLifecycle::InPreLayout)
1639         return false;
1640     if (!shouldScheduleLayout())
1641         return false;
1642     return true;
1643 }
1644
1645 void Document::scheduleRenderTreeUpdate()
1646 {
1647     ASSERT(!hasPendingStyleRecalc());
1648     ASSERT(shouldScheduleRenderTreeUpdate());
1649     ASSERT(needsRenderTreeUpdate());
1650
1651     page()->animator().scheduleVisualUpdate();
1652     m_lifecycle.ensureStateAtMost(DocumentLifecycle::VisualUpdatePending);
1653
1654     TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ScheduleStyleRecalculation", "frame", frame());
1655     TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
1656     // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1657     InspectorInstrumentation::didScheduleStyleRecalculation(this);
1658 }
1659
1660 bool Document::hasPendingForcedStyleRecalc() const
1661 {
1662     return hasPendingStyleRecalc() && !inStyleRecalc() && styleChangeType() >= SubtreeStyleChange;
1663 }
1664
1665 void Document::updateDistributionIfNeeded()
1666 {
1667     ScriptForbiddenScope forbidScript;
1668
1669     if (!childNeedsDistributionRecalc())
1670         return;
1671     TRACE_EVENT0("webkit", "Document::updateDistributionIfNeeded");
1672     recalcDistribution();
1673 }
1674
1675 void Document::updateStyleInvalidationIfNeeded()
1676 {
1677     ScriptForbiddenScope forbidScript;
1678
1679     if (!isActive())
1680         return;
1681     if (!childNeedsStyleInvalidation())
1682         return;
1683     TRACE_EVENT0("webkit", "Document::updateStyleInvalidationIfNeeded");
1684     ASSERT(styleResolver());
1685
1686     styleResolver()->ruleFeatureSet().styleInvalidator().invalidate(*this);
1687 }
1688
1689 void Document::updateDistributionForNodeIfNeeded(Node* node)
1690 {
1691     ScriptForbiddenScope forbidScript;
1692
1693     if (node->inDocument()) {
1694         updateDistributionIfNeeded();
1695         return;
1696     }
1697     Node* root = node;
1698     while (Node* host = root->shadowHost())
1699         root = host;
1700     while (Node* ancestor = root->parentOrShadowHostNode())
1701         root = ancestor;
1702     if (root->childNeedsDistributionRecalc())
1703         root->recalcDistribution();
1704 }
1705
1706 void Document::setupFontBuilder(RenderStyle* documentStyle)
1707 {
1708     FontBuilder fontBuilder;
1709     fontBuilder.initForStyleResolve(*this, documentStyle, isSVGDocument());
1710     RefPtrWillBeRawPtr<CSSFontSelector> selector = m_styleEngine->fontSelector();
1711     fontBuilder.createFontForDocument(selector, documentStyle);
1712 }
1713
1714 void Document::inheritHtmlAndBodyElementStyles(StyleRecalcChange change)
1715 {
1716     ASSERT(inStyleRecalc());
1717     ASSERT(documentElement());
1718
1719     RefPtr<RenderStyle> documentElementStyle = documentElement()->renderStyle();
1720     if (!documentElementStyle || documentElement()->needsStyleRecalc() || change == Force)
1721         documentElementStyle = ensureStyleResolver().styleForElement(documentElement());
1722
1723     WritingMode rootWritingMode = documentElementStyle->writingMode();
1724     TextDirection rootDirection = documentElementStyle->direction();
1725
1726     HTMLElement* body = this->body();
1727     RefPtr<RenderStyle> bodyStyle;
1728     if (body) {
1729         bodyStyle = body->renderStyle();
1730         if (!bodyStyle || body->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
1731             bodyStyle = ensureStyleResolver().styleForElement(body, documentElementStyle.get());
1732         if (!writingModeSetOnDocumentElement())
1733             rootWritingMode = bodyStyle->writingMode();
1734         if (!directionSetOnDocumentElement())
1735             rootDirection = bodyStyle->direction();
1736     }
1737
1738     RefPtr<RenderStyle> overflowStyle;
1739     if (Element* element = viewportDefiningElement(documentElementStyle.get())) {
1740         if (element == body) {
1741             overflowStyle = bodyStyle;
1742         } else {
1743             ASSERT(element == documentElement());
1744             overflowStyle = documentElementStyle;
1745         }
1746     }
1747
1748     // Resolved rem units are stored in the matched properties cache so we need to make sure to
1749     // invalidate the cache if the documentElement needed to reattach or the font size changed
1750     // and then trigger a full document recalc. We also need to clear it here since the
1751     // call to styleForElement on the body above can cache bad values for rem units if the
1752     // documentElement's style was dirty. We could keep track of which elements depend on
1753     // rem units like we do for viewport styles, but we assume root font size changes are
1754     // rare and just invalidate the cache for now.
1755     if (styleEngine()->usesRemUnits() && (documentElement()->needsAttach() || documentElement()->computedStyle()->fontSize() != documentElementStyle->fontSize())) {
1756         ensureStyleResolver().invalidateMatchedPropertiesCache();
1757         documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
1758     }
1759
1760     EOverflow overflowX = OAUTO;
1761     EOverflow overflowY = OAUTO;
1762     float columnGap = 0;
1763     if (overflowStyle) {
1764         overflowX = overflowStyle->overflowX();
1765         overflowY = overflowStyle->overflowY();
1766         // Visible overflow on the viewport is meaningless, and the spec says to treat it as 'auto':
1767         if (overflowX == OVISIBLE)
1768             overflowX = OAUTO;
1769         if (overflowY == OVISIBLE)
1770             overflowY = OAUTO;
1771         // Column-gap is (ab)used by the current paged overflow implementation (in lack of other
1772         // ways to specify gaps between pages), so we have to propagate it too.
1773         columnGap = overflowStyle->columnGap();
1774     }
1775
1776     RefPtr<RenderStyle> documentStyle = renderView()->style();
1777     if (documentStyle->writingMode() != rootWritingMode
1778         || documentStyle->direction() != rootDirection
1779         || documentStyle->overflowX() != overflowX
1780         || documentStyle->overflowY() != overflowY
1781         || documentStyle->columnGap() != columnGap) {
1782         RefPtr<RenderStyle> newStyle = RenderStyle::clone(documentStyle.get());
1783         newStyle->setWritingMode(rootWritingMode);
1784         newStyle->setDirection(rootDirection);
1785         newStyle->setColumnGap(columnGap);
1786         newStyle->setOverflowX(overflowX);
1787         newStyle->setOverflowY(overflowY);
1788         renderView()->setStyle(newStyle);
1789         setupFontBuilder(newStyle.get());
1790     }
1791
1792     if (body) {
1793         if (RenderStyle* style = body->renderStyle()) {
1794             if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
1795                 body->setNeedsStyleRecalc(SubtreeStyleChange);
1796         }
1797     }
1798
1799     if (RenderStyle* style = documentElement()->renderStyle()) {
1800         if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
1801             documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
1802     }
1803 }
1804
1805 void Document::updateRenderTree(StyleRecalcChange change)
1806 {
1807     ASSERT(isMainThread());
1808
1809     if (change != Force && !needsRenderTreeUpdate())
1810         return;
1811
1812     if (inStyleRecalc())
1813         return;
1814
1815     // Entering here from inside layout or paint would be catastrophic since recalcStyle can
1816     // tear down the render tree or (unfortunately) run script. Kill the whole renderer if
1817     // someone managed to get into here from inside layout or paint.
1818     RELEASE_ASSERT(!view()->isInPerformLayout());
1819     RELEASE_ASSERT(!view()->isPainting());
1820
1821     // Script can run below in WidgetUpdates, so protect the LocalFrame.
1822     RefPtr<LocalFrame> protect(m_frame);
1823
1824     TRACE_EVENT0("webkit", "Document::updateRenderTree");
1825     TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "UpdateRenderTree");
1826
1827     m_styleRecalcElementCounter = 0;
1828     TRACE_EVENT_BEGIN1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "RecalculateStyles", "frame", frame());
1829     TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
1830     // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1831     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1832
1833     DocumentAnimations::updateOutdatedAnimationPlayersIfNeeded(*this);
1834     updateDistributionIfNeeded();
1835     updateUseShadowTreesIfNeeded();
1836     updateStyleInvalidationIfNeeded();
1837
1838     // FIXME: This executes media query listeners which runs script, instead the script
1839     // should run at raf timing in ScriptedAnimationController just like resize events.
1840     evaluateMediaQueryListIfNeeded();
1841
1842     // FIXME: We should update style on our ancestor chain before proceeding
1843     // however doing so currently causes several tests to crash, as LocalFrame::setDocument calls Document::attach
1844     // before setting the DOMWindow on the LocalFrame, or the SecurityOrigin on the document. The attach, in turn
1845     // resolves style (here) and then when we resolve style on the parent chain, we may end up
1846     // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1847     // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1848
1849     if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
1850         m_styleEngine->setUsesRemUnit(true);
1851
1852     updateStyle(change);
1853
1854     // As a result of the style recalculation, the currently hovered element might have been
1855     // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1856     // to check if any other elements ended up under the mouse pointer due to re-layout.
1857     if (hoverNode() && !hoverNode()->renderer() && frame())
1858         frame()->eventHandler().dispatchFakeMouseMoveEventSoon();
1859
1860     if (m_focusedElement && !m_focusedElement->isFocusable())
1861         clearFocusedElementSoon();
1862
1863 #if ENABLE(SVG_FONTS)
1864     if (svgExtensions())
1865         accessSVGExtensions().removePendingSVGFontFaceElementsForRemoval();
1866 #endif
1867
1868     ASSERT(!m_timeline->hasOutdatedAnimationPlayer());
1869     ASSERT(!m_transitionTimeline->hasOutdatedAnimationPlayer());
1870
1871     TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "RecalculateStyles", "elementCount", m_styleRecalcElementCounter);
1872     // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
1873     InspectorInstrumentation::didRecalculateStyle(cookie, m_styleRecalcElementCounter);
1874 }
1875
1876 void Document::updateStyle(StyleRecalcChange change)
1877 {
1878     TRACE_EVENT0("webkit", "Document::updateStyle");
1879
1880     ScriptForbiddenScope forbidScript;
1881     HTMLFrameOwnerElement::UpdateSuspendScope suspendWidgetHierarchyUpdates;
1882     m_lifecycle.advanceTo(DocumentLifecycle::InStyleRecalc);
1883
1884     if (styleChangeType() >= SubtreeStyleChange)
1885         change = Force;
1886
1887     // FIXME: Cannot access the ensureStyleResolver() before calling styleForDocument below because
1888     // apparently the StyleResolver's constructor has side effects. We should fix it.
1889     // See printing/setPrinting.html, printing/width-overflow.html though they only fail on
1890     // mac when accessing the resolver by what appears to be a viewport size difference.
1891
1892     if (change == Force) {
1893         m_hasNodesWithPlaceholderStyle = false;
1894         RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this);
1895         StyleRecalcChange localChange = RenderStyle::stylePropagationDiff(documentStyle.get(), renderView()->style());
1896         if (localChange != NoChange)
1897             renderView()->setStyle(documentStyle.release());
1898     }
1899
1900     clearNeedsStyleRecalc();
1901
1902     // Uncomment to enable printing of statistics about style sharing and the matched property cache.
1903     // Optionally pass StyleResolver::ReportSlowStats to print numbers that require crawling the
1904     // entire DOM (where collecting them is very slow).
1905     // FIXME: Expose this as a runtime flag.
1906     // ensureStyleResolver().enableStats(/*StyleResolver::ReportSlowStats*/);
1907
1908     if (StyleResolverStats* stats = ensureStyleResolver().stats())
1909         stats->reset();
1910
1911     if (Element* documentElement = this->documentElement()) {
1912         inheritHtmlAndBodyElementStyles(change);
1913         dirtyElementsForLayerUpdate();
1914         if (documentElement->shouldCallRecalcStyle(change))
1915             documentElement->recalcStyle(change);
1916         while (dirtyElementsForLayerUpdate())
1917             documentElement->recalcStyle(NoChange);
1918     }
1919
1920     ensureStyleResolver().printStats();
1921
1922     view()->recalcOverflowAfterStyleChange();
1923     view()->updateCompositingLayersAfterStyleChange();
1924
1925     clearChildNeedsStyleRecalc();
1926
1927     if (m_styleEngine->hasResolver()) {
1928         // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1929         StyleResolver& resolver = m_styleEngine->ensureResolver();
1930         m_styleEngine->resetCSSFeatureFlags(resolver.ensureUpdatedRuleFeatureSet());
1931         resolver.clearStyleSharingList();
1932     }
1933
1934     ASSERT(!needsStyleRecalc());
1935     ASSERT(!childNeedsStyleRecalc());
1936     ASSERT(inStyleRecalc());
1937     m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
1938 }
1939
1940 void Document::updateRenderTreeForNodeIfNeeded(Node* node)
1941 {
1942     bool needsRecalc = needsFullRenderTreeUpdate();
1943
1944     for (const Node* ancestor = node; ancestor && !needsRecalc; ancestor = NodeRenderingTraversal::parent(ancestor))
1945         needsRecalc = ancestor->needsStyleRecalc() || ancestor->needsStyleInvalidation();
1946
1947     if (needsRecalc)
1948         updateRenderTreeIfNeeded();
1949 }
1950
1951 void Document::updateLayout()
1952 {
1953     ASSERT(isMainThread());
1954
1955     RefPtr<FrameView> frameView = view();
1956     if (frameView && frameView->isInPerformLayout()) {
1957         // View layout should not be re-entrant.
1958         ASSERT_NOT_REACHED();
1959         return;
1960     }
1961
1962     if (Element* oe = ownerElement())
1963         oe->document().updateLayout();
1964
1965     updateRenderTreeIfNeeded();
1966
1967     if (!isActive())
1968         return;
1969
1970     if (frameView->needsLayout())
1971         frameView->layout();
1972
1973     if (lifecycle().state() < DocumentLifecycle::LayoutClean)
1974         lifecycle().advanceTo(DocumentLifecycle::LayoutClean);
1975 }
1976
1977 void Document::setNeedsFocusedElementCheck()
1978 {
1979     setNeedsStyleRecalc(LocalStyleChange);
1980 }
1981
1982 void Document::clearFocusedElementSoon()
1983 {
1984     if (!m_clearFocusedElementTimer.isActive())
1985         m_clearFocusedElementTimer.startOneShot(0, FROM_HERE);
1986 }
1987
1988 void Document::clearFocusedElementTimerFired(Timer<Document>*)
1989 {
1990     updateRenderTreeIfNeeded();
1991     m_clearFocusedElementTimer.stop();
1992
1993     if (m_focusedElement && !m_focusedElement->isFocusable())
1994         m_focusedElement->blur();
1995 }
1996
1997 // FIXME: This is a bad idea and needs to be removed eventually.
1998 // Other browsers load stylesheets before they continue parsing the web page.
1999 // Since we don't, we can run JavaScript code that needs answers before the
2000 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
2001 // lets us get reasonable answers. The long term solution to this problem is
2002 // to instead suspend JavaScript execution.
2003 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
2004 {
2005     StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
2006
2007     if (m_styleEngine->hasPendingSheets()) {
2008         // FIXME: We are willing to attempt to suppress painting with outdated style info only once.
2009         // Our assumption is that it would be dangerous to try to stop it a second time, after page
2010         // content has already been loaded and displayed with accurate style information. (Our
2011         // suppression involves blanking the whole page at the moment. If it were more refined, we
2012         // might be able to do something better.) It's worth noting though that this entire method
2013         // is a hack, since what we really want to do is suspend JS instead of doing a layout with
2014         // inaccurate information.
2015         HTMLElement* bodyElement = body();
2016         if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
2017             m_pendingSheetLayout = DidLayoutWithPendingSheets;
2018             styleResolverChanged(RecalcStyleImmediately);
2019         } else if (m_hasNodesWithPlaceholderStyle) {
2020             // If new nodes have been added or style recalc has been done with style sheets still
2021             // pending, some nodes may not have had their real style calculated yet. Normally this
2022             // gets cleaned when style sheets arrive but here we need up-to-date style immediately.
2023             updateRenderTree(Force);
2024         }
2025     }
2026
2027     updateLayout();
2028
2029     if (runPostLayoutTasks == RunPostLayoutTasksSynchronously && view())
2030         view()->flushAnyPendingPostLayoutTasks();
2031 }
2032
2033 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
2034 {
2035     ASSERT_ARG(element, element->document() == this);
2036     StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
2037     return ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
2038 }
2039
2040 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
2041 {
2042     return ensureStyleResolver().styleForPage(pageIndex);
2043 }
2044
2045 bool Document::isPageBoxVisible(int pageIndex)
2046 {
2047     return styleForPage(pageIndex)->visibility() != HIDDEN; // display property doesn't apply to @page.
2048 }
2049
2050 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2051 {
2052     RefPtr<RenderStyle> style = styleForPage(pageIndex);
2053
2054     int width = pageSize.width();
2055     int height = pageSize.height();
2056     switch (style->pageSizeType()) {
2057     case PAGE_SIZE_AUTO:
2058         break;
2059     case PAGE_SIZE_AUTO_LANDSCAPE:
2060         if (width < height)
2061             std::swap(width, height);
2062         break;
2063     case PAGE_SIZE_AUTO_PORTRAIT:
2064         if (width > height)
2065             std::swap(width, height);
2066         break;
2067     case PAGE_SIZE_RESOLVED: {
2068         LengthSize size = style->pageSize();
2069         ASSERT(size.width().isFixed());
2070         ASSERT(size.height().isFixed());
2071         width = valueForLength(size.width(), 0);
2072         height = valueForLength(size.height(), 0);
2073         break;
2074     }
2075     default:
2076         ASSERT_NOT_REACHED();
2077     }
2078     pageSize = IntSize(width, height);
2079
2080     // The percentage is calculated with respect to the width even for margin top and bottom.
2081     // http://www.w3.org/TR/CSS2/box.html#margin-properties
2082     marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2083     marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2084     marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2085     marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2086 }
2087
2088 void Document::setIsViewSource(bool isViewSource)
2089 {
2090     m_isViewSource = isViewSource;
2091     if (!m_isViewSource)
2092         return;
2093
2094     setSecurityOrigin(SecurityOrigin::createUnique());
2095     didUpdateSecurityOrigin();
2096 }
2097
2098 bool Document::dirtyElementsForLayerUpdate()
2099 {
2100     if (m_layerUpdateElements.isEmpty())
2101         return false;
2102     HashSet<Element*>::iterator end = m_layerUpdateElements.end();
2103     for (HashSet<Element*>::iterator it = m_layerUpdateElements.begin(); it != end; ++it)
2104         (*it)->setNeedsStyleRecalc(LocalStyleChange);
2105     m_layerUpdateElements.clear();
2106     return true;
2107 }
2108
2109 void Document::scheduleLayerUpdate(Element& element)
2110 {
2111     if (element.styleChangeType() == NeedsReattachStyleChange)
2112         return;
2113     element.setNeedsLayerUpdate();
2114     m_layerUpdateElements.add(&element);
2115     scheduleRenderTreeUpdateIfNeeded();
2116 }
2117
2118 void Document::unscheduleLayerUpdate(Element& element)
2119 {
2120     element.clearNeedsLayerUpdate();
2121     m_layerUpdateElements.remove(&element);
2122 }
2123
2124 void Document::scheduleUseShadowTreeUpdate(SVGUseElement& element)
2125 {
2126     m_useElementsNeedingUpdate.add(&element);
2127     scheduleRenderTreeUpdateIfNeeded();
2128 }
2129
2130 void Document::unscheduleUseShadowTreeUpdate(SVGUseElement& element)
2131 {
2132     m_useElementsNeedingUpdate.remove(&element);
2133 }
2134
2135 void Document::updateUseShadowTreesIfNeeded()
2136 {
2137     ScriptForbiddenScope forbidScript;
2138
2139     if (m_useElementsNeedingUpdate.isEmpty())
2140         return;
2141
2142     Vector<SVGUseElement*> elements;
2143     copyToVector(m_useElementsNeedingUpdate, elements);
2144     m_useElementsNeedingUpdate.clear();
2145
2146     Vector<SVGUseElement*>::iterator end = elements.end();
2147     for (Vector<SVGUseElement*>::iterator it = elements.begin(); it != end; ++it)
2148         (*it)->buildPendingResource();
2149 }
2150
2151 StyleResolver* Document::styleResolver() const
2152 {
2153     return m_styleEngine->resolver();
2154 }
2155
2156 StyleResolver& Document::ensureStyleResolver() const
2157 {
2158     return m_styleEngine->ensureResolver();
2159 }
2160
2161 void Document::clearStyleResolver()
2162 {
2163     m_styleEngine->clearResolver();
2164 }
2165
2166 void Document::attach(const AttachContext& context)
2167 {
2168     ASSERT(m_lifecycle.state() == DocumentLifecycle::Inactive);
2169     ASSERT(!m_axObjectCache || this != topDocument());
2170
2171     m_renderView = new RenderView(this);
2172     setRenderer(m_renderView);
2173
2174     m_renderView->setIsInWindow(true);
2175     m_renderView->setStyle(StyleResolver::styleForDocument(*this));
2176     view()->updateCompositingLayersAfterStyleChange();
2177
2178     ContainerNode::attach(context);
2179
2180     // FastTextAutosizer can't update render view info while the Document is detached, so update now in case anything changed.
2181     if (FastTextAutosizer* textAutosizer = fastTextAutosizer())
2182         textAutosizer->updatePageInfo();
2183
2184     m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
2185 }
2186
2187 void Document::detach(const AttachContext& context)
2188 {
2189     ASSERT(isActive());
2190     m_lifecycle.advanceTo(DocumentLifecycle::Stopping);
2191
2192     if (page())
2193         page()->documentDetached(this);
2194     InspectorInstrumentation::documentDetached(this);
2195
2196     if (m_frame->loader().client()->sharedWorkerRepositoryClient())
2197         m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this);
2198
2199     if (this == topDocument())
2200         clearAXObjectCache();
2201
2202     stopActiveDOMObjects();
2203
2204     // FIXME: consider using ActiveDOMObject.
2205     if (m_scriptedAnimationController)
2206         m_scriptedAnimationController->clearDocumentPointer();
2207     m_scriptedAnimationController.clear();
2208
2209     if (svgExtensions())
2210         accessSVGExtensions().pauseAnimations();
2211
2212     // FIXME: This shouldn't be needed once DOMWindow becomes ExecutionContext.
2213     if (m_domWindow)
2214         m_domWindow->clearEventQueue();
2215
2216     if (m_renderView)
2217         m_renderView->setIsInWindow(false);
2218
2219     if (m_frame) {
2220         FrameView* view = m_frame->view();
2221         if (view)
2222             view->detachCustomScrollbars();
2223     }
2224
2225     m_hoverNode = nullptr;
2226     m_focusedElement = nullptr;
2227     m_activeHoverElement = nullptr;
2228     m_autofocusElement = nullptr;
2229
2230     m_renderView = 0;
2231     ContainerNode::detach(context);
2232
2233     m_styleEngine->didDetach();
2234
2235     if (Document* parentDoc = parentDocument())
2236         parentDoc->didClearTouchEventHandlers(this);
2237
2238     // This is required, as our LocalFrame might delete itself as soon as it detaches
2239     // us. However, this violates Node::detach() semantics, as it's never
2240     // possible to re-attach. Eventually Document::detach() should be renamed,
2241     // or this setting of the frame to 0 could be made explicit in each of the
2242     // callers of Document::detach().
2243     m_frame = 0;
2244
2245     if (m_mediaQueryMatcher)
2246         m_mediaQueryMatcher->documentDestroyed();
2247
2248     lifecycleNotifier().notifyDocumentWasDetached();
2249     m_lifecycle.advanceTo(DocumentLifecycle::Stopped);
2250 #if ENABLE(OILPAN)
2251     // FIXME: Oilpan: With Oilpan dispose should not be needed. At
2252     // this point we still have dispose in order to clear out some
2253     // RefPtrs that would otherwise cause leaks. However, when the
2254     // Document is detached the document can still be alive, so we
2255     // really shouldn't clear anything at this point. It should just
2256     // die with the document when the document is no longer reachable.
2257     dispose();
2258 #endif
2259 }
2260
2261 void Document::prepareForDestruction()
2262 {
2263     m_markers->prepareForDestruction();
2264     disconnectDescendantFrames();
2265
2266     // The process of disconnecting descendant frames could have already detached us.
2267     if (!isActive())
2268         return;
2269
2270     if (DOMWindow* window = this->domWindow())
2271         window->willDetachDocumentFromFrame();
2272     detach();
2273 }
2274
2275 void Document::removeAllEventListeners()
2276 {
2277     ContainerNode::removeAllEventListeners();
2278
2279     if (DOMWindow* domWindow = this->domWindow())
2280         domWindow->removeAllEventListeners();
2281 }
2282
2283 void Document::clearAXObjectCache()
2284 {
2285     ASSERT(topDocument() == this);
2286     // Clear the cache member variable before calling delete because attempts
2287     // are made to access it during destruction.
2288     m_axObjectCache.clear();
2289 }
2290
2291 AXObjectCache* Document::existingAXObjectCache() const
2292 {
2293     if (!AXObjectCache::accessibilityEnabled())
2294         return 0;
2295
2296     // If the renderer is gone then we are in the process of destruction.
2297     // This method will be called before m_frame = 0.
2298     if (!topDocument().renderView())
2299         return 0;
2300
2301     return topDocument().m_axObjectCache.get();
2302 }
2303
2304 AXObjectCache* Document::axObjectCache() const
2305 {
2306     if (!AXObjectCache::accessibilityEnabled())
2307         return 0;
2308
2309     // The only document that actually has a AXObjectCache is the top-level
2310     // document.  This is because we need to be able to get from any WebCoreAXObject
2311     // to any other WebCoreAXObject on the same page.  Using a single cache allows
2312     // lookups across nested webareas (i.e. multiple documents).
2313     Document& topDocument = this->topDocument();
2314
2315     // If the document has already been detached, do not make a new axObjectCache.
2316     if (!topDocument.renderView())
2317         return 0;
2318
2319     ASSERT(topDocument == this || !m_axObjectCache);
2320     if (!topDocument.m_axObjectCache)
2321         topDocument.m_axObjectCache = adoptPtr(new AXObjectCache(topDocument));
2322     return topDocument.m_axObjectCache.get();
2323 }
2324
2325 PassRefPtr<DocumentParser> Document::createParser()
2326 {
2327     if (isHTMLDocument()) {
2328         bool reportErrors = InspectorInstrumentation::collectingHTMLParseErrors(page());
2329         return HTMLDocumentParser::create(toHTMLDocument(this), reportErrors);
2330     }
2331     // FIXME: this should probably pass the frame instead
2332     return XMLDocumentParser::create(this, view());
2333 }
2334
2335 bool Document::isFrameSet() const
2336 {
2337     if (!isHTMLDocument())
2338         return false;
2339     return isHTMLFrameSetElement(body());
2340 }
2341
2342 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2343 {
2344     return parser() ? parser()->asScriptableDocumentParser() : 0;
2345 }
2346
2347 void Document::open(Document* ownerDocument, ExceptionState& exceptionState)
2348 {
2349     if (importLoader()) {
2350         exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support open().");
2351         return;
2352     }
2353
2354     if (ownerDocument) {
2355         setURL(ownerDocument->url());
2356         m_cookieURL = ownerDocument->cookieURL();
2357         setSecurityOrigin(ownerDocument->securityOrigin());
2358     }
2359
2360     if (m_frame) {
2361         if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2362             if (parser->isParsing()) {
2363                 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2364                 if (parser->isExecutingScript())
2365                     return;
2366
2367                 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2368                     return;
2369             }
2370         }
2371
2372         if (m_frame->loader().state() == FrameStateProvisional)
2373             m_frame->loader().stopAllLoaders();
2374     }
2375
2376     removeAllEventListenersRecursively();
2377     implicitOpen();
2378     if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2379         parser->setWasCreatedByScript(true);
2380
2381     if (m_frame)
2382         m_frame->loader().didExplicitOpen();
2383     if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
2384         m_loadEventProgress = LoadEventNotRun;
2385 }
2386
2387 void Document::detachParser()
2388 {
2389     if (!m_parser)
2390         return;
2391     m_parser->detach();
2392     m_parser.clear();
2393 }
2394
2395 void Document::cancelParsing()
2396 {
2397     if (!m_parser)
2398         return;
2399
2400     // We have to clear the parser to avoid possibly triggering
2401     // the onload handler when closing as a side effect of a cancel-style
2402     // change, such as opening a new document or closing the window while
2403     // still parsing.
2404     detachParser();
2405     explicitClose();
2406 }
2407
2408 PassRefPtr<DocumentParser> Document::implicitOpen()
2409 {
2410     cancelParsing();
2411
2412     removeChildren();
2413     ASSERT(!m_focusedElement);
2414
2415     setCompatibilityMode(NoQuirksMode);
2416
2417     m_parser = createParser();
2418     setParsing(true);
2419     setReadyState(Loading);
2420
2421     return m_parser;
2422 }
2423
2424 HTMLElement* Document::body() const
2425 {
2426     if (!documentElement())
2427         return 0;
2428
2429     for (HTMLElement* child = Traversal<HTMLElement>::firstWithin(*documentElement()); child; child = Traversal<HTMLElement>::nextSibling(*child)) {
2430         if (isHTMLFrameSetElement(*child) || isHTMLBodyElement(*child))
2431             return child;
2432     }
2433
2434     return 0;
2435 }
2436
2437 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionState& exceptionState)
2438 {
2439     RefPtr<HTMLElement> newBody = prpNewBody;
2440
2441     if (!newBody) {
2442         exceptionState.throwDOMException(HierarchyRequestError, ExceptionMessages::argumentNullOrIncorrectType(1, "HTMLElement"));
2443         return;
2444     }
2445     if (!documentElement()) {
2446         exceptionState.throwDOMException(HierarchyRequestError, "No document element exists.");
2447         return;
2448     }
2449
2450     if (!isHTMLBodyElement(*newBody) && !isHTMLFrameSetElement(*newBody)) {
2451         exceptionState.throwDOMException(HierarchyRequestError, "The new body element is of type '" + newBody->tagName() + "'. It must be either a 'BODY' or 'FRAMESET' element.");
2452         return;
2453     }
2454
2455     HTMLElement* oldBody = body();
2456     if (oldBody == newBody)
2457         return;
2458
2459     if (oldBody)
2460         documentElement()->replaceChild(newBody.release(), oldBody, exceptionState);
2461     else
2462         documentElement()->appendChild(newBody.release(), exceptionState);
2463 }
2464
2465 HTMLHeadElement* Document::head()
2466 {
2467     Node* de = documentElement();
2468     if (!de)
2469         return 0;
2470
2471     return Traversal<HTMLHeadElement>::firstChild(*de);
2472 }
2473
2474 Element* Document::viewportDefiningElement(RenderStyle* rootStyle) const
2475 {
2476     // If a BODY element sets non-visible overflow, it is to be propagated to the viewport, as long
2477     // as the following conditions are all met:
2478     // (1) The root element is HTML.
2479     // (2) It is the primary BODY element (we only assert for this, expecting callers to behave).
2480     // (3) The root element has visible overflow.
2481     // Otherwise it's the root element's properties that are to be propagated.
2482     Element* rootElement = documentElement();
2483     Element* bodyElement = body();
2484     if (!rootElement)
2485         return 0;
2486     if (!rootStyle) {
2487         rootStyle = rootElement->renderStyle();
2488         if (!rootStyle)
2489             return 0;
2490     }
2491     if (bodyElement && rootStyle->isOverflowVisible() && isHTMLHtmlElement(*rootElement))
2492         return bodyElement;
2493     return rootElement;
2494 }
2495
2496 void Document::close(ExceptionState& exceptionState)
2497 {
2498     // FIXME: We should follow the specification more closely:
2499     //        http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2500
2501     if (importLoader()) {
2502         exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support close().");
2503         return;
2504     }
2505
2506     if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2507         return;
2508
2509     explicitClose();
2510 }
2511
2512 void Document::explicitClose()
2513 {
2514     if (RefPtr<DocumentParser> parser = m_parser)
2515         parser->finish();
2516
2517     if (!m_frame) {
2518         // Because we have no frame, we don't know if all loading has completed,
2519         // so we just call implicitClose() immediately. FIXME: This might fire
2520         // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2521         implicitClose();
2522         return;
2523     }
2524
2525     m_frame->loader().checkCompleted();
2526 }
2527
2528 void Document::implicitClose()
2529 {
2530     ASSERT(!inStyleRecalc());
2531
2532     bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2533     bool doload = !parsing() && m_parser && !processingLoadEvent() && !wasLocationChangePending;
2534
2535     // If the load was blocked because of a pending location change and the location change triggers a same document
2536     // navigation, don't fire load events after the same document navigation completes (unless there's an explicit open).
2537     m_loadEventProgress = LoadEventTried;
2538
2539     if (!doload)
2540         return;
2541
2542     // The call to dispatchWindowLoadEvent can detach the DOMWindow and cause it (and its
2543     // attached Document) to be destroyed.
2544     RefPtrWillBeRawPtr<DOMWindow> protectedWindow(this->domWindow());
2545
2546     m_loadEventProgress = LoadEventInProgress;
2547
2548     ScriptableDocumentParser* parser = scriptableDocumentParser();
2549     m_wellFormed = parser && parser->wellFormed();
2550
2551     // We have to clear the parser, in case someone document.write()s from the
2552     // onLoad event handler, as in Radar 3206524.
2553     detachParser();
2554
2555     if (frame() && frame()->script().canExecuteScripts(NotAboutToExecuteScript)) {
2556         ImageLoader::dispatchPendingLoadEvents();
2557         ImageLoader::dispatchPendingErrorEvents();
2558
2559         HTMLLinkElement::dispatchPendingLoadEvents();
2560         HTMLStyleElement::dispatchPendingLoadEvents();
2561     }
2562
2563     // JS running below could remove the frame or destroy the RenderView so we call
2564     // those two functions repeatedly and don't save them on the stack.
2565
2566     // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2567     // here, instead of doing it from SVGElement::finishedParsingChildren.
2568     if (svgExtensions())
2569         accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2570
2571     if (protectedWindow)
2572         protectedWindow->documentWasClosed();
2573
2574     if (frame()) {
2575         frame()->loader().client()->dispatchDidHandleOnloadEvents();
2576         loader()->applicationCacheHost()->stopDeferringEvents();
2577     }
2578
2579     if (!frame()) {
2580         m_loadEventProgress = LoadEventCompleted;
2581         return;
2582     }
2583
2584     // Make sure both the initial layout and reflow happen after the onload
2585     // fires. This will improve onload scores, and other browsers do it.
2586     // If they wanna cheat, we can too. -dwh
2587
2588     if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2589         // Just bail out. Before or during the onload we were shifted to another page.
2590         // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2591         m_loadEventProgress = LoadEventCompleted;
2592         return;
2593     }
2594
2595     // We used to force a synchronous display and flush here.  This really isn't
2596     // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2597     // (if your platform is syncing flushes and limiting them to 60fps).
2598     if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2599         updateRenderTreeIfNeeded();
2600
2601         // Always do a layout after loading if needed.
2602         if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2603             view()->layout();
2604     }
2605
2606     m_loadEventProgress = LoadEventCompleted;
2607
2608     if (frame() && renderView() && AXObjectCache::accessibilityEnabled()) {
2609         // The AX cache may have been cleared at this point, but we need to make sure it contains an
2610         // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2611         // exists in the cache (we ignore the return value because we don't need it here). This is
2612         // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2613         if (AXObjectCache* cache = axObjectCache()) {
2614             cache->getOrCreate(renderView());
2615             if (this == topDocument()) {
2616                 cache->postNotification(renderView(), AXObjectCache::AXLoadComplete, true);
2617             } else {
2618                 // AXLoadComplete can only be posted on the top document, so if it's a document
2619                 // in an iframe that just finished loading, post AXLayoutComplete instead.
2620                 cache->postNotification(renderView(), AXObjectCache::AXLayoutComplete, true);
2621             }
2622         }
2623     }
2624
2625     if (svgExtensions())
2626         accessSVGExtensions().startAnimations();
2627 }
2628
2629 bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigation)
2630 {
2631     if (!m_domWindow)
2632         return true;
2633
2634     if (!body())
2635         return true;
2636
2637     RefPtr<Document> protect(this);
2638
2639     RefPtrWillBeRawPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2640     m_loadEventProgress = BeforeUnloadEventInProgress;
2641     m_domWindow->dispatchEvent(beforeUnloadEvent.get(), this);
2642     m_loadEventProgress = BeforeUnloadEventCompleted;
2643     if (!beforeUnloadEvent->defaultPrevented())
2644         defaultEventHandler(beforeUnloadEvent.get());
2645     if (beforeUnloadEvent->returnValue().isNull())
2646         return true;
2647
2648     if (didAllowNavigation) {
2649         addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation.");
2650         return true;
2651     }
2652
2653     String text = beforeUnloadEvent->returnValue();
2654     if (chrome.runBeforeUnloadConfirmPanel(text, m_frame)) {
2655         didAllowNavigation = true;
2656         return true;
2657     }
2658     return false;
2659 }
2660
2661 void Document::dispatchUnloadEvents()
2662 {
2663     RefPtr<Document> protect(this);
2664     if (m_parser)
2665         m_parser->stopParsing();
2666
2667     if (m_loadEventProgress >= LoadEventTried && m_loadEventProgress <= UnloadEventInProgress) {
2668         Element* currentFocusedElement = focusedElement();
2669         if (isHTMLInputElement(currentFocusedElement))
2670             toHTMLInputElement(*currentFocusedElement).endEditing();
2671         if (m_loadEventProgress < PageHideInProgress) {
2672             m_loadEventProgress = PageHideInProgress;
2673             if (DOMWindow* window = domWindow())
2674                 window->dispatchEvent(PageTransitionEvent::create(EventTypeNames::pagehide, false), this);
2675             if (!m_frame)
2676                 return;
2677
2678             // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
2679             // while dispatching the event, so protect it to prevent writing the end
2680             // time into freed memory.
2681             RefPtr<DocumentLoader> documentLoader =  m_frame->loader().provisionalDocumentLoader();
2682             m_loadEventProgress = UnloadEventInProgress;
2683             RefPtrWillBeRawPtr<Event> unloadEvent(Event::create(EventTypeNames::unload));
2684             if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
2685                 DocumentLoadTiming* timing = documentLoader->timing();
2686                 ASSERT(timing->navigationStart());
2687                 timing->markUnloadEventStart();
2688                 m_frame->domWindow()->dispatchEvent(unloadEvent, this);
2689                 timing->markUnloadEventEnd();
2690             } else {
2691                 m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
2692             }
2693         }
2694         m_loadEventProgress = UnloadEventHandled;
2695     }
2696
2697     if (!m_frame)
2698         return;
2699
2700     // Don't remove event listeners from a transitional empty document (see https://bugs.webkit.org/show_bug.cgi?id=28716 for more information).
2701     bool keepEventListeners = m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader().provisionalDocumentLoader()
2702         && isSecureTransitionTo(m_frame->loader().provisionalDocumentLoader()->url());
2703     if (!keepEventListeners)
2704         removeAllEventListenersRecursively();
2705 }
2706
2707 Document::PageDismissalType Document::pageDismissalEventBeingDispatched() const
2708 {
2709     if (m_loadEventProgress == BeforeUnloadEventInProgress)
2710         return BeforeUnloadDismissal;
2711     if (m_loadEventProgress == PageHideInProgress)
2712         return PageHideDismissal;
2713     if (m_loadEventProgress == UnloadEventInProgress)
2714         return UnloadDismissal;
2715     return NoDismissal;
2716 }
2717
2718 void Document::setParsing(bool b)
2719 {
2720     m_isParsing = b;
2721
2722     if (m_isParsing && !m_elementDataCache)
2723         m_elementDataCache = ElementDataCache::create();
2724 }
2725
2726 bool Document::shouldScheduleLayout() const
2727 {
2728     // This function will only be called when FrameView thinks a layout is needed.
2729     // This enforces a couple extra rules.
2730     //
2731     //    (a) Only schedule a layout once the stylesheets are loaded.
2732     //    (b) Only schedule layout once we have a body element.
2733     if (!isActive())
2734         return false;
2735
2736     if (isRenderingReady() && body())
2737         return true;
2738
2739     if (documentElement() && !isHTMLHtmlElement(*documentElement()))
2740         return true;
2741
2742     return false;
2743 }
2744
2745 int Document::elapsedTime() const
2746 {
2747     return static_cast<int>((currentTime() - m_startTime) * 1000);
2748 }
2749
2750 void Document::write(const SegmentedString& text, Document* ownerDocument, ExceptionState& exceptionState)
2751 {
2752     if (importLoader()) {
2753         exceptionState.throwDOMException(InvalidStateError, "Imported document doesn't support write().");
2754         return;
2755     }
2756
2757     NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2758
2759     m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2760     m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2761
2762     if (m_writeRecursionIsTooDeep)
2763        return;
2764
2765     bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2766
2767     if (!hasInsertionPoint && m_ignoreDestructiveWriteCount) {
2768         addConsoleMessage(JSMessageSource, WarningMessageLevel, ExceptionMessages::failedToExecute("write", "Document", "It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened."));
2769         return;
2770     }
2771
2772     if (!hasInsertionPoint)
2773         open(ownerDocument);
2774
2775     ASSERT(m_parser);
2776     m_parser->insert(text);
2777 }
2778
2779 void Document::write(const String& text, Document* ownerDocument, ExceptionState& exceptionState)
2780 {
2781     write(SegmentedString(text), ownerDocument, exceptionState);
2782 }
2783
2784 void Document::writeln(const String& text, Document* ownerDocument, ExceptionState& exceptionState)
2785 {
2786     write(text, ownerDocument, exceptionState);
2787     if (exceptionState.hadException())
2788         return;
2789     write("\n", ownerDocument);
2790 }
2791
2792 const KURL& Document::virtualURL() const
2793 {
2794     return m_url;
2795 }
2796
2797 KURL Document::virtualCompleteURL(const String& url) const
2798 {
2799     return completeURL(url);
2800 }
2801
2802 double Document::timerAlignmentInterval() const
2803 {
2804     Page* p = page();
2805     if (!p)
2806         return DOMTimer::visiblePageAlignmentInterval();
2807     return p->timerAlignmentInterval();
2808 }
2809
2810 EventTarget* Document::errorEventTarget()
2811 {
2812     return domWindow();
2813 }
2814
2815 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
2816 {
2817     internalAddMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack, 0);
2818 }
2819
2820 void Document::setURL(const KURL& url)
2821 {
2822     const KURL& newURL = url.isEmpty() ? blankURL() : url;
2823     if (newURL == m_url)
2824         return;
2825
2826     m_url = newURL;
2827     updateBaseURL();
2828     contextFeatures().urlDidChange(this);
2829 }
2830
2831 void Document::updateBaseURL()
2832 {
2833     KURL oldBaseURL = m_baseURL;
2834     // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2835     // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2836     // from the Document interface otherwise (which we store, preparsed, in m_url).
2837     if (!m_baseElementURL.isEmpty())
2838         m_baseURL = m_baseElementURL;
2839     else if (!m_baseURLOverride.isEmpty())
2840         m_baseURL = m_baseURLOverride;
2841     else
2842         m_baseURL = m_url;
2843
2844     selectorQueryCache().invalidate();
2845
2846     if (!m_baseURL.isValid())
2847         m_baseURL = KURL();
2848
2849     if (m_elemSheet) {
2850         // Element sheet is silly. It never contains anything.
2851         ASSERT(!m_elemSheet->contents()->ruleCount());
2852         bool usesRemUnits = m_elemSheet->contents()->usesRemUnits();
2853         m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2854         // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2855         m_elemSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
2856     }
2857
2858     if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2859         // Base URL change changes any relative visited links.
2860         // FIXME: There are other URLs in the tree that would need to be re-evaluated on dynamic base URL change. Style should be invalidated too.
2861         for (HTMLAnchorElement* anchor = Traversal<HTMLAnchorElement>::firstWithin(*this); anchor; anchor = Traversal<HTMLAnchorElement>::next(*anchor))
2862             anchor->invalidateCachedVisitedLinkHash();
2863     }
2864 }
2865
2866 void Document::setBaseURLOverride(const KURL& url)
2867 {
2868     m_baseURLOverride = url;
2869     updateBaseURL();
2870 }
2871
2872 void Document::processBaseElement()
2873 {
2874     // Find the first href attribute in a base element and the first target attribute in a base element.
2875     const AtomicString* href = 0;
2876     const AtomicString* target = 0;
2877     for (HTMLBaseElement* base = Traversal<HTMLBaseElement>::firstWithin(*this); base && (!href || !target); base = Traversal<HTMLBaseElement>::next(*base)) {
2878         if (!href) {
2879             const AtomicString& value = base->fastGetAttribute(hrefAttr);
2880             if (!value.isNull())
2881                 href = &value;
2882         }
2883         if (!target) {
2884             const AtomicString& value = base->fastGetAttribute(targetAttr);
2885             if (!value.isNull())
2886                 target = &value;
2887         }
2888         if (contentSecurityPolicy()->isActive())
2889             UseCounter::count(*this, UseCounter::ContentSecurityPolicyWithBaseElement);
2890     }
2891
2892     // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2893     KURL baseElementURL;
2894     if (href) {
2895         String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2896         if (!strippedHref.isEmpty())
2897             baseElementURL = KURL(url(), strippedHref);
2898     }
2899     if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
2900         m_baseElementURL = baseElementURL;
2901         updateBaseURL();
2902     }
2903
2904     m_baseTarget = target ? *target : nullAtom;
2905 }
2906
2907 String Document::userAgent(const KURL& url) const
2908 {
2909     return frame() ? frame()->loader().userAgent(url) : String();
2910 }
2911
2912 void Document::disableEval(const String& errorMessage)
2913 {
2914     if (!frame())
2915         return;
2916
2917     frame()->script().disableEval(errorMessage);
2918 }
2919
2920 bool Document::canNavigate(LocalFrame* targetFrame)
2921 {
2922     if (!m_frame)
2923         return false;
2924
2925     // FIXME: We shouldn't call this function without a target frame, but
2926     // fast/forms/submit-to-blank-multiple-times.html depends on this function
2927     // returning true when supplied with a 0 targetFrame.
2928     if (!targetFrame)
2929         return true;
2930
2931     // LocalFrame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
2932     if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
2933         return true;
2934
2935     if (isSandboxed(SandboxNavigation)) {
2936         if (targetFrame->tree().isDescendantOf(m_frame))
2937             return true;
2938
2939         const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
2940         if (isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
2941             reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
2942
2943         printNavigationErrorMessage(*targetFrame, url(), reason);
2944         return false;
2945     }
2946
2947     ASSERT(securityOrigin());
2948     SecurityOrigin& origin = *securityOrigin();
2949
2950     // This is the normal case. A document can navigate its decendant frames,
2951     // or, more generally, a document can navigate a frame if the document is
2952     // in the same origin as any of that frame's ancestors (in the frame
2953     // hierarchy).
2954     //
2955     // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2956     // historical information about this security check.
2957     if (canAccessAncestor(origin, targetFrame))
2958         return true;
2959
2960     // Top-level frames are easier to navigate than other frames because they
2961     // display their URLs in the address bar (in most browsers). However, there
2962     // are still some restrictions on navigation to avoid nuisance attacks.
2963     // Specifically, a document can navigate a top-level frame if that frame
2964     // opened the document or if the document is the same-origin with any of
2965     // the top-level frame's opener's ancestors (in the frame hierarchy).
2966     //
2967     // In both of these cases, the document performing the navigation is in
2968     // some way related to the frame being navigate (e.g., by the "opener"
2969     // and/or "parent" relation). Requiring some sort of relation prevents a
2970     // document from navigating arbitrary, unrelated top-level frames.
2971     if (!targetFrame->tree().parent()) {
2972         if (targetFrame == m_frame->loader().opener())
2973             return true;
2974
2975         if (canAccessAncestor(origin, targetFrame->loader().opener()))
2976             return true;
2977     }
2978
2979     printNavigationErrorMessage(*targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
2980     return false;
2981 }
2982
2983 LocalFrame* Document::findUnsafeParentScrollPropagationBoundary()
2984 {
2985     LocalFrame* currentFrame = m_frame;
2986     LocalFrame* ancestorFrame = currentFrame->tree().parent();
2987
2988     while (ancestorFrame) {
2989         if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
2990             return currentFrame;
2991         currentFrame = ancestorFrame;
2992         ancestorFrame = ancestorFrame->tree().parent();
2993     }
2994     return 0;
2995 }
2996
2997 void Document::didLoadAllImports()
2998 {
2999     if (!haveStylesheetsLoaded())
3000         return;
3001     if (!importLoader())
3002         styleResolverMayHaveChanged();
3003     didLoadAllScriptBlockingResources();
3004 }
3005
3006 void Document::didRemoveAllPendingStylesheet()
3007 {
3008     m_needsNotifyRemoveAllPendingStylesheet = false;
3009
3010     styleResolverMayHaveChanged();
3011
3012     // Only imports on master documents can trigger rendering.
3013     if (HTMLImportLoader* import = importLoader())
3014         import->didRemoveAllPendingStylesheet();
3015     if (!haveImportsLoaded())
3016         return;
3017     didLoadAllScriptBlockingResources();
3018 }
3019
3020 void Document::didLoadAllScriptBlockingResources()
3021 {
3022     executeScriptsWaitingForResourcesIfNeeded();
3023
3024     if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
3025         view()->scrollToFragment(m_url);
3026 }
3027
3028
3029 void Document::executeScriptsWaitingForResourcesIfNeeded()
3030 {
3031     if (!isRenderingReady())
3032         return;
3033     if (ScriptableDocumentParser* parser = scriptableDocumentParser())
3034         parser->executeScriptsWaitingForResources();
3035 }
3036
3037
3038 CSSStyleSheet& Document::elementSheet()
3039 {
3040     if (!m_elemSheet)
3041         m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
3042     return *m_elemSheet;
3043 }
3044
3045 void Document::processHttpEquiv(const AtomicString& equiv, const AtomicString& content, bool inDocumentHeadElement)
3046 {
3047     ASSERT(!equiv.isNull() && !content.isNull());
3048
3049     if (equalIgnoringCase(equiv, "default-style")) {
3050         processHttpEquivDefaultStyle(content);
3051     } else if (equalIgnoringCase(equiv, "refresh")) {
3052         processHttpEquivRefresh(content);
3053     } else if (equalIgnoringCase(equiv, "set-cookie")) {
3054         processHttpEquivSetCookie(content);
3055     } else if (equalIgnoringCase(equiv, "content-language")) {
3056         setContentLanguage(content);
3057     } else if (equalIgnoringCase(equiv, "x-dns-prefetch-control")) {
3058         parseDNSPrefetchControlHeader(content);
3059     } else if (equalIgnoringCase(equiv, "x-frame-options")) {
3060         processHttpEquivXFrameOptions(content);
3061     } else if (equalIgnoringCase(equiv, "content-security-policy") || equalIgnoringCase(equiv, "content-security-policy-report-only")) {
3062         if (inDocumentHeadElement)
3063             processHttpEquivContentSecurityPolicy(equiv, content);
3064         else
3065             contentSecurityPolicy()->reportMetaOutsideHead(content);
3066     }
3067 }
3068
3069 void Document::processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content)
3070 {
3071     if (importLoader())
3072         return;
3073     if (equalIgnoringCase(equiv, "content-security-policy"))
3074         contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeEnforce, ContentSecurityPolicyHeaderSourceMeta);
3075     else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
3076         contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderTypeReport, ContentSecurityPolicyHeaderSourceMeta);
3077     else
3078         ASSERT_NOT_REACHED();
3079 }
3080
3081 void Document::processHttpEquivDefaultStyle(const AtomicString& content)
3082 {
3083     // The preferred style set has been overridden as per section
3084     // 14.3.2 of the HTML4.0 specification. We need to update the
3085     // sheet used variable and then update our style selector.
3086     // For more info, see the test at:
3087     // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3088     // -dwh
3089     m_styleEngine->setSelectedStylesheetSetName(content);
3090     m_styleEngine->setPreferredStylesheetSetName(content);
3091     styleResolverChanged(RecalcStyleDeferred);
3092 }
3093
3094 void Document::processHttpEquivRefresh(const AtomicString& content)
3095 {
3096     maybeHandleHttpRefresh(content, HttpRefreshFromMetaTag);
3097 }
3098
3099 void Document::maybeHandleHttpRefresh(const String& content, HttpRefreshType httpRefreshType)
3100 {
3101     if (m_isViewSource || !m_frame)
3102         return;
3103
3104     double delay;
3105     String refreshURL;
3106     if (!parseHTTPRefresh(content, httpRefreshType == HttpRefreshFromMetaTag, delay, refreshURL))
3107         return;
3108     if (refreshURL.isEmpty())
3109         refreshURL = url().string();
3110     else
3111         refreshURL = completeURL(refreshURL).string();
3112
3113     if (protocolIsJavaScript(refreshURL)) {
3114         String message = "Refused to refresh " + m_url.elidedString() + " to a javascript: URL";
3115         addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
3116         return;
3117     }
3118
3119     if (httpRefreshType == HttpRefreshFromMetaTag && isSandboxed(SandboxAutomaticFeatures)) {
3120         String message = "Refused to execute the redirect specified via '<meta http-equiv='refresh' content='...'>'. The document is sandboxed, and the 'allow-scripts' keyword is not set.";
3121         addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
3122         return;
3123     }
3124     m_frame->navigationScheduler().scheduleRedirect(delay, refreshURL);
3125 }
3126
3127 void Document::processHttpEquivSetCookie(const AtomicString& content)
3128 {
3129     // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3130     if (!isHTMLDocument())
3131         return;
3132
3133     // Exception (for sandboxed documents) ignored.
3134     toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
3135 }
3136
3137 void Document::processHttpEquivXFrameOptions(const AtomicString& content)
3138 {
3139     LocalFrame* frame = this->frame();
3140     if (!frame)
3141         return;
3142
3143     FrameLoader& frameLoader = frame->loader();
3144     unsigned long requestIdentifier = loader()->mainResourceIdentifier();
3145     if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
3146         String message = "Refused to display '" + url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
3147         frameLoader.stopAllLoaders();
3148         // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
3149         // intent, we must navigate away from the possibly partially-rendered document to a location that
3150         // doesn't inherit the parent's SecurityOrigin.
3151         frame->navigationScheduler().scheduleLocationChange(this, SecurityOrigin::urlWithUniqueSecurityOrigin(), Referrer());
3152         addConsoleMessageWithRequestIdentifier(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
3153     }
3154 }
3155
3156 bool Document::shouldMergeWithLegacyDescription(ViewportDescription::Type origin)
3157 {
3158     return settings() && settings()->viewportMetaMergeContentQuirk() && m_legacyViewportDescription.isMetaViewportType() && m_legacyViewportDescription.type == origin;
3159 }
3160
3161 void Document::setViewportDescription(const ViewportDescription& viewportDescription)
3162 {
3163     // The UA-defined min-width is used by the processing of legacy meta tags.
3164     if (!viewportDescription.isSpecifiedByAuthor())
3165         m_viewportDefaultMinWidth = viewportDescription.minWidth;
3166
3167     if (viewportDescription.isLegacyViewportType()) {
3168         if (settings() && !settings()->viewportMetaEnabled())
3169             return;
3170
3171         m_legacyViewportDescription = viewportDescription;
3172
3173         // When no author style for @viewport is present, and a meta tag for defining
3174         // the viewport is, apply the meta tag viewport instead of the UA styles.
3175         if (m_viewportDescription.type == ViewportDescription::AuthorStyleSheet)
3176             return;
3177         m_viewportDescription = viewportDescription;
3178     } else {
3179         // If the legacy viewport tag has higher priority than the cascaded @viewport
3180         // descriptors, use the values from the legacy tag.
3181         if (!shouldOverrideLegacyDescription(viewportDescription.type))
3182             m_viewportDescription = m_legacyViewportDescription;
3183         else
3184             m_viewportDescription = viewportDescription;
3185     }
3186
3187     updateViewportDescription();
3188 }
3189
3190 void Document::updateViewportDescription()
3191 {
3192     if (frame() && frame()->isMainFrame()) {
3193 #ifndef NDEBUG
3194         m_didDispatchViewportPropertiesChanged = true;
3195 #endif
3196         frameHost()->chrome().dispatchViewportPropertiesDidChange(m_viewportDescription);
3197     }
3198 }
3199
3200 void Document::processReferrerPolicy(const String& policy)
3201 {
3202     ASSERT(!policy.isNull());
3203
3204     if (equalIgnoringCase(policy, "never")) {
3205         setReferrerPolicy(ReferrerPolicyNever);
3206     } else if (equalIgnoringCase(policy, "always")) {
3207         setReferrerPolicy(ReferrerPolicyAlways);
3208     } else if (equalIgnoringCase(policy, "origin")) {
3209         setReferrerPolicy(ReferrerPolicyOrigin);
3210     } else if (equalIgnoringCase(policy, "default")) {
3211         setReferrerPolicy(ReferrerPolicyDefault);
3212     } else {
3213         addConsoleMessage(RenderingMessageSource, ErrorMessageLevel, "Failed to set referrer policy: The value '" + policy + "' is not one of 'always', 'default', 'never', or 'origin'. Defaulting to 'never'.");
3214         setReferrerPolicy(ReferrerPolicyNever);
3215     }
3216 }
3217
3218 void Document::setReferrerPolicy(ReferrerPolicy referrerPolicy)
3219 {
3220     // FIXME: Can we adopt the CSP referrer policy merge algorithm? Or does the web rely on being able to modify the referrer policy in-flight?
3221     if (m_didSetReferrerPolicy)
3222         UseCounter::count(this, UseCounter::ResetReferrerPolicy);
3223     m_didSetReferrerPolicy = true;
3224
3225     m_referrerPolicy = referrerPolicy;
3226 }
3227
3228 String Document::outgoingReferrer()
3229 {
3230     // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
3231     // for why we walk the parent chain for srcdoc documents.
3232     Document* referrerDocument = this;
3233     if (LocalFrame* frame = m_frame) {
3234         while (frame->document()->isSrcdocDocument()) {
3235             frame = frame->tree().parent();
3236             // Srcdoc documents cannot be top-level documents, by definition,
3237             // because they need to be contained in iframes with the srcdoc.
3238             ASSERT(frame);
3239         }
3240         referrerDocument = frame->document();
3241     }
3242     return referrerDocument->m_url.strippedForUseAsReferrer();
3243 }
3244
3245 String Document::outgoingOrigin() const
3246 {
3247     return securityOrigin()->toString();
3248 }
3249
3250 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3251 {
3252     ASSERT(!renderView() || renderView()->isRenderView());
3253
3254     // RenderView::hitTest causes a layout, and we don't want to hit that until the first
3255     // layout because until then, there is nothing shown on the screen - the user can't
3256     // have intentionally clicked on something belonging to this page. Furthermore,
3257     // mousemove events before the first layout should not lead to a premature layout()
3258     // happening, which could show a flash of white.
3259     // See also the similar code in EventHandler::hitTestResultAtPoint.
3260     if (!renderView() || !view() || !view()->didFirstLayout())
3261         return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3262
3263     HitTestResult result(documentPoint);
3264     renderView()->hitTest(request, result);
3265
3266     if (!request.readOnly())
3267         updateHoverActiveState(request, result.innerElement(), &event);
3268
3269     return MouseEventWithHitTestResults(event, result);
3270 }
3271
3272 // DOM Section 1.1.1
3273 bool Document::childTypeAllowed(NodeType type) const
3274 {
3275     switch (type) {
3276     case ATTRIBUTE_NODE:
3277     case CDATA_SECTION_NODE:
3278     case DOCUMENT_FRAGMENT_NODE:
3279     case DOCUMENT_NODE:
3280     case TEXT_NODE:
3281         return false;
3282     case COMMENT_NODE:
3283     case PROCESSING_INSTRUCTION_NODE:
3284         return true;
3285     case DOCUMENT_TYPE_NODE:
3286     case ELEMENT_NODE:
3287         // Documents may contain no more than one of each of these.
3288         // (One Element and one DocumentType.)
3289         for (Node* c = firstChild(); c; c = c->nextSibling())
3290             if (c->nodeType() == type)
3291                 return false;
3292         return true;
3293     }
3294     return false;
3295 }
3296
3297 bool Document::canReplaceChild(const Node& newChild, const Node& oldChild) const
3298 {
3299     if (oldChild.nodeType() == newChild.nodeType())
3300         return true;
3301
3302     int numDoctypes = 0;
3303     int numElements = 0;
3304
3305     // First, check how many doctypes and elements we have, not counting
3306     // the child we're about to remove.
3307     for (Node* c = firstChild(); c; c = c->nextSibling()) {
3308         if (c == oldChild)
3309             continue;
3310
3311         switch (c->nodeType()) {
3312         case DOCUMENT_TYPE_NODE:
3313             numDoctypes++;
3314             break;
3315         case ELEMENT_NODE:
3316             numElements++;
3317             break;
3318         default:
3319             break;
3320         }
3321     }
3322
3323     // Then, see how many doctypes and elements might be added by the new child.
3324     if (newChild.nodeType() == DOCUMENT_FRAGMENT_NODE) {
3325         for (Node* c = newChild.firstChild(); c; c = c->nextSibling()) {
3326             switch (c->nodeType()) {
3327             case ATTRIBUTE_NODE:
3328             case CDATA_SECTION_NODE:
3329             case DOCUMENT_FRAGMENT_NODE:
3330             case DOCUMENT_NODE:
3331             case TEXT_NODE:
3332                 return false;
3333             case COMMENT_NODE:
3334             case PROCESSING_INSTRUCTION_NODE:
3335                 break;
3336             case DOCUMENT_TYPE_NODE:
3337                 numDoctypes++;
3338                 break;
3339             case ELEMENT_NODE:
3340                 numElements++;
3341                 break;
3342             }
3343         }
3344     } else {
3345         switch (newChild.nodeType()) {
3346         case ATTRIBUTE_NODE:
3347         case CDATA_SECTION_NODE:
3348         case DOCUMENT_FRAGMENT_NODE:
3349         case DOCUMENT_NODE:
3350         case TEXT_NODE:
3351             return false;
3352         case COMMENT_NODE:
3353         case PROCESSING_INSTRUCTION_NODE:
3354             return true;
3355         case DOCUMENT_TYPE_NODE:
3356             numDoctypes++;
3357             break;
3358         case ELEMENT_NODE:
3359             numElements++;
3360             break;
3361         }
3362     }
3363
3364     if (numElements > 1 || numDoctypes > 1)
3365         return false;
3366
3367     return true;
3368 }
3369
3370 PassRefPtr<Node> Document::cloneNode(bool deep)
3371 {
3372     RefPtr<Document> clone = cloneDocumentWithoutChildren();
3373     clone->cloneDataFromDocument(*this);
3374     if (deep)
3375         cloneChildNodes(clone.get());
3376     return clone.release();
3377 }
3378
3379 PassRefPtr<Document> Document::cloneDocumentWithoutChildren()
3380 {
3381     DocumentInit init(url());
3382     if (isXMLDocument()) {
3383         if (isXHTMLDocument())
3384             return XMLDocument::createXHTML(init.withRegistrationContext(registrationContext()));
3385         return XMLDocument::create(init);
3386     }
3387     return create(init);
3388 }
3389
3390 void Document::cloneDataFromDocument(const Document& other)
3391 {
3392     setCompatibilityMode(other.compatibilityMode());
3393     setEncodingData(other.m_encodingData);
3394     setContextFeatures(other.contextFeatures());
3395     setSecurityOrigin(other.securityOrigin()->isolatedCopy());
3396     setMimeType(other.contentType());
3397 }
3398
3399 StyleSheetList* Document::styleSheets()
3400 {
3401     if (!m_styleSheetList)
3402         m_styleSheetList = StyleSheetList::create(this);
3403     return m_styleSheetList.get();
3404 }
3405
3406 String Document::preferredStylesheetSet() const
3407 {
3408     return m_styleEngine->preferredStylesheetSetName();
3409 }
3410
3411 String Document::selectedStylesheetSet() const
3412 {
3413     return m_styleEngine->selectedStylesheetSetName();
3414 }
3415
3416 void Document::setSelectedStylesheetSet(const String& aString)
3417 {
3418     m_styleEngine->setSelectedStylesheetSetName(aString);
3419     styleResolverChanged(RecalcStyleDeferred);
3420 }
3421
3422 void Document::evaluateMediaQueryListIfNeeded()
3423 {
3424     if (!m_evaluateMediaQueriesOnStyleRecalc)
3425         return;
3426     evaluateMediaQueryList();
3427     m_evaluateMediaQueriesOnStyleRecalc = false;
3428 }
3429
3430 void Document::evaluateMediaQueryList()
3431 {
3432     if (m_mediaQueryMatcher)
3433         m_mediaQueryMatcher->styleResolverChanged();
3434 }
3435
3436 void Document::notifyResizeForViewportUnits()
3437 {
3438     if (!hasViewportUnits())
3439         return;
3440     ensureStyleResolver().notifyResizeForViewportUnits();
3441     setNeedsStyleRecalcForViewportUnits();
3442 }
3443
3444 void Document::styleResolverChanged(RecalcStyleTime updateTime, StyleResolverUpdateMode updateMode)
3445 {
3446     // styleResolverChanged() can be invoked during Document destruction.
3447     // We just skip that case.
3448     if (!m_styleEngine)
3449         return;
3450
3451     StyleResolverChange change = m_styleEngine->resolverChanged(updateTime, updateMode);
3452     if (change.needsRepaint()) {
3453         // We need to manually repaint because we avoid doing all repaints in layout or style
3454         // recalc while sheets are still loading to avoid FOUC.
3455         m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3456         renderView()->repaintViewAndCompositedLayers();
3457     }
3458
3459     if (!change.needsStyleRecalc())
3460         return;
3461
3462     m_evaluateMediaQueriesOnStyleRecalc = true;
3463     setNeedsStyleRecalc(SubtreeStyleChange);
3464
3465     if (updateTime == RecalcStyleImmediately)
3466         updateRenderTreeIfNeeded();
3467 }
3468
3469 void Document::styleResolverMayHaveChanged()
3470 {
3471     styleResolverChanged(RecalcStyleDeferred, hasNodesWithPlaceholderStyle() ? FullStyleUpdate : AnalyzedStyleUpdate);
3472 }
3473
3474 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
3475 {
3476     m_hoverNode = newHoverNode;
3477 }
3478
3479 void Document::setActiveHoverElement(PassRefPtr<Element> newActiveElement)
3480 {
3481     if (!newActiveElement) {
3482         m_activeHoverElement.clear();
3483         return;
3484     }
3485
3486     m_activeHoverElement = newActiveElement;
3487 }
3488
3489 void Document::removeFocusedElementOfSubtree(Node* node, bool amongChildrenOnly)
3490 {
3491     if (!m_focusedElement)
3492         return;
3493
3494     // We can't be focused if we're not in the document.
3495     if (!node->inDocument())
3496         return;
3497     bool contains = node->containsIncludingShadowDOM(m_focusedElement.get());
3498     if (contains && (m_focusedElement != node || !amongChildrenOnly))
3499         setFocusedElement(nullptr);
3500 }
3501
3502 void Document::hoveredNodeDetached(Node* node)
3503 {
3504     if (!m_hoverNode)
3505         return;
3506
3507     if (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != NodeRenderingTraversal::parent(m_hoverNode.get())))
3508         return;
3509
3510     m_hoverNode = NodeRenderingTraversal::parent(node);
3511     while (m_hoverNode && !m_hoverNode->renderer())
3512         m_hoverNode = NodeRenderingTraversal::parent(m_hoverNode.get());
3513
3514     // If the mouse cursor is not visible, do not clear existing
3515     // hover effects on the ancestors of |node| and do not invoke
3516     // new hover effects on any other element.
3517     if (!page()->isCursorVisible())
3518         return;
3519
3520     if (frame())
3521         frame()->eventHandler().scheduleHoverStateUpdate();
3522 }
3523
3524 void Document::activeChainNodeDetached(Node* node)
3525 {
3526     if (!m_activeHoverElement)
3527         return;
3528
3529     if (node != m_activeHoverElement && (!m_activeHoverElement->isTextNode() || node != NodeRenderingTraversal::parent(m_activeHoverElement.get())))
3530         return;
3531
3532     Node* activeNode = NodeRenderingTraversal::parent(node);
3533     while (activeNode && activeNode->isElementNode() && !activeNode->renderer())
3534         activeNode = NodeRenderingTraversal::parent(activeNode);
3535
3536     m_activeHoverElement = activeNode && activeNode->isElementNode() ? toElement(activeNode) : 0;
3537 }
3538
3539 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3540 {
3541     return m_annotatedRegions;
3542 }
3543
3544 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3545 {
3546     m_annotatedRegions = regions;
3547     setAnnotatedRegionsDirty(false);
3548 }
3549
3550 bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusType type)
3551 {
3552     m_clearFocusedElementTimer.stop();
3553
3554     RefPtr<Element> newFocusedElement = prpNewFocusedElement;
3555
3556     // Make sure newFocusedNode is actually in this document
3557     if (newFocusedElement && (newFocusedElement->document() != this))
3558         return true;
3559
3560     if (NodeChildRemovalTracker::isBeingRemoved(newFocusedElement.get()))
3561         return true;
3562
3563     if (m_focusedElement == newFocusedElement)
3564         return true;
3565
3566     bool focusChangeBlocked = false;
3567     RefPtrWillBeRawPtr<Element> oldFocusedElement = m_focusedElement;
3568     m_focusedElement = nullptr;
3569
3570     // Remove focus from the existing focus node (if any)
3571     if (oldFocusedElement) {
3572         ASSERT(!oldFocusedElement->inDetach());
3573
3574         if (oldFocusedElement->active())
3575             oldFocusedElement->setActive(false);
3576
3577         oldFocusedElement->setFocus(false);
3578
3579         // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3580         // If page lost focus, blur event will have already been dispatched
3581         if (page() && (page()->focusController().isFocused())) {
3582             oldFocusedElement->dispatchBlurEvent(newFocusedElement.get());
3583
3584             if (m_focusedElement) {
3585                 // handler shifted focus
3586                 focusChangeBlocked = true;
3587                 newFocusedElement = nullptr;
3588             }
3589
3590             oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::focusout, newFocusedElement.get()); // DOM level 3 name for the bubbling blur event.
3591             // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3592             // on it, probably when <rdar://problem/8503958> is resolved.
3593             oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, newFocusedElement.get()); // DOM level 2 name for compatibility.
3594
3595             if (m_focusedElement) {
3596                 // handler shifted focus
3597                 focusChangeBlocked = true;
3598                 newFocusedElement = nullptr;
3599             }
3600         }
3601
3602         if (view()) {
3603             Widget* oldWidget = widgetForElement(*oldFocusedElement);
3604             if (oldWidget)
3605                 oldWidget->setFocus(false);
3606             else
3607                 view()->setFocus(false);
3608         }
3609     }
3610
3611     if (newFocusedElement && newFocusedElement->isFocusable()) {
3612         if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(*newFocusedElement)) {
3613             // delegate blocks focus change
3614             focusChangeBlocked = true;
3615             goto SetFocusedElementDone;
3616         }
3617         // Set focus on the new node
3618         m_focusedElement = newFocusedElement;
3619
3620         // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3621         // If page lost focus, event will be dispatched on page focus, don't duplicate
3622         if (page() && (page()->focusController().isFocused())) {
3623             m_focusedElement->dispatchFocusEvent(oldFocusedElement.get(), type);
3624
3625
3626             if (m_focusedElement != newFocusedElement) {
3627                 // handler shifted focus
3628                 focusChangeBlocked = true;
3629                 goto SetFocusedElementDone;
3630             }
3631
3632             m_focusedElement->dispatchFocusInEvent(EventTypeNames::focusin, oldFocusedElement.get()); // DOM level 3 bubbling focus event.
3633
3634             if (m_focusedElement != newFocusedElement) {
3635                 // handler shifted focus
3636                 focusChangeBlocked = true;
3637                 goto SetFocusedElementDone;
3638             }
3639
3640             // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3641             // on it, probably when <rdar://problem/8503958> is m.
3642             m_focusedElement->dispatchFocusInEvent(EventTypeNames::DOMFocusIn, oldFocusedElement.get()); // DOM level 2 for compatibility.
3643
3644             if (m_focusedElement != newFocusedElement) {
3645                 // handler shifted focus
3646                 focusChangeBlocked = true;
3647                 goto SetFocusedElementDone;
3648             }
3649         }
3650
3651         m_focusedElement->setFocus(true);
3652
3653         if (m_focusedElement->isRootEditableElement())
3654             frame()->spellChecker().didBeginEditing(m_focusedElement.get());
3655
3656         // eww, I suck. set the qt focus correctly
3657         // ### find a better place in the code for this
3658         if (view()) {
3659             Widget* focusWidget = widgetForElement(*m_focusedElement);
3660             if (focusWidget) {
3661                 // Make sure a widget has the right size before giving it focus.
3662                 // Otherwise, we are testing edge cases of the Widget code.
3663                 // Specifically, in WebCore this does not work well for text fields.
3664                 updateLayout();
3665                 // Re-get the widget in case updating the layout changed things.
3666                 focusWidget = widgetForElement(*m_focusedElement);
3667             }
3668             if (focusWidget)
3669                 focusWidget->setFocus(true);
3670             else
3671                 view()->setFocus(true);
3672         }
3673     }
3674
3675     if (!focusChangeBlocked && m_focusedElement) {
3676         // Create the AXObject cache in a focus change because Chromium relies on it.
3677         if (AXObjectCache* cache = axObjectCache())
3678             cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
3679     }
3680
3681     if (!focusChangeBlocked && frameHost())
3682         frameHost()->chrome().focusedNodeChanged(m_focusedElement.get());
3683
3684 SetFocusedElementDone:
3685     updateRenderTreeIfNeeded();
3686     if (LocalFrame* frame = this->frame())
3687         frame->selection().didChangeFocus();
3688     return !focusChangeBlocked;
3689 }
3690
3691 void Document::setCSSTarget(Element* n)
3692 {
3693     if (m_cssTarget)
3694         m_cssTarget->didAffectSelector(AffectedSelectorTarget);
3695     m_cssTarget = n;
3696     if (n)
3697         n->didAffectSelector(AffectedSelectorTarget);
3698 }
3699
3700 void Document::registerNodeList(LiveNodeListBase* list)
3701 {
3702     m_nodeListCounts[list->invalidationType()]++;
3703     if (list->isRootedAtDocument())
3704         m_listsInvalidatedAtDocument.add(list);
3705 }
3706
3707 void Document::unregisterNodeList(LiveNodeListBase* list)
3708 {
3709     m_nodeListCounts[list->invalidationType()]--;
3710     if (list->isRootedAtDocument()) {
3711         ASSERT(m_listsInvalidatedAtDocument.contains(list));
3712         m_listsInvalidatedAtDocument.remove(list);
3713     }
3714 }
3715
3716 void Document::attachNodeIterator(NodeIterator* ni)
3717 {
3718     m_nodeIterators.add(ni);
3719 }
3720
3721 void Document::detachNodeIterator(NodeIterator* ni)
3722 {
3723     // The node iterator can be detached without having been attached if its root node didn't have a document
3724     // when the iterator was created, but has it now.
3725     m_nodeIterators.remove(ni);
3726 }
3727
3728 void Document::moveNodeIteratorsToNewDocument(Node& node, Document& newDocument)
3729 {
3730     HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3731     HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3732     for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3733         if ((*it)->root() == node) {
3734             detachNodeIterator(*it);
3735             newDocument.attachNodeIterator(*it);
3736         }
3737     }
3738 }
3739
3740 void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
3741 {
3742     if (!m_ranges.isEmpty()) {
3743         HashSet<Range*>::const_iterator end = m_ranges.end();
3744         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3745             (*it)->nodeChildrenChanged(container);
3746     }
3747 }
3748
3749 void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
3750 {
3751     NoEventDispatchAssertion assertNoEventDispatch;
3752     if (!m_ranges.isEmpty()) {
3753         HashSet<Range*>::const_iterator end = m_ranges.end();
3754         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3755             (*it)->nodeChildrenWillBeRemoved(container);
3756     }
3757
3758     HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3759     for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
3760         for (Node* n = container.firstChild(); n; n = n->nextSibling())
3761             (*it)->nodeWillBeRemoved(*n);
3762     }
3763
3764     if (LocalFrame* frame = this->frame()) {
3765         for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
3766             frame->eventHandler().nodeWillBeRemoved(*n);
3767             frame->selection().nodeWillBeRemoved(*n);
3768             frame->page()->dragCaretController().nodeWillBeRemoved(*n);
3769         }
3770     }
3771 }
3772
3773 void Document::nodeWillBeRemoved(Node& n)
3774 {
3775     HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3776     for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3777         (*it)->nodeWillBeRemoved(n);
3778
3779     if (!m_ranges.isEmpty()) {
3780         HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
3781         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3782             (*it)->nodeWillBeRemoved(n);
3783     }
3784
3785     if (LocalFrame* frame = this->frame()) {
3786         frame->eventHandler().nodeWillBeRemoved(n);
3787         frame->selection().nodeWillBeRemoved(n);
3788         frame->page()->dragCaretController().nodeWillBeRemoved(n);
3789     }
3790 }
3791
3792 void Document::didInsertText(Node* text, unsigned offset, unsigned length)
3793 {
3794     if (!m_ranges.isEmpty()) {
3795         HashSet<Range*>::const_iterator end = m_ranges.end();
3796         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3797             (*it)->didInsertText(text, offset, length);
3798     }
3799
3800     // Update the markers for spelling and grammar checking.
3801     m_markers->shiftMarkers(text, offset, length);
3802 }
3803
3804 void Document::didRemoveText(Node* text, unsigned offset, unsigned length)
3805 {
3806     if (!m_ranges.isEmpty()) {
3807         HashSet<Range*>::const_iterator end = m_ranges.end();
3808         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3809             (*it)->didRemoveText(text, offset, length);
3810     }
3811
3812     // Update the markers for spelling and grammar checking.
3813     m_markers->removeMarkers(text, offset, length);
3814     m_markers->shiftMarkers(text, offset + length, 0 - length);
3815 }
3816
3817 void Document::didMergeTextNodes(Text& oldNode, unsigned offset)
3818 {
3819     if (!m_ranges.isEmpty()) {
3820         NodeWithIndex oldNodeWithIndex(oldNode);
3821         HashSet<Range*>::const_iterator end = m_ranges.end();
3822         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3823             (*it)->didMergeTextNodes(oldNodeWithIndex, offset);
3824     }
3825
3826     if (m_frame)
3827         m_frame->selection().didMergeTextNodes(oldNode, offset);
3828
3829     // FIXME: This should update markers for spelling and grammar checking.
3830 }
3831
3832 void Document::didSplitTextNode(Text& oldNode)
3833 {
3834     if (!m_ranges.isEmpty()) {
3835         HashSet<Range*>::const_iterator end = m_ranges.end();
3836         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3837             (*it)->didSplitTextNode(oldNode);
3838     }
3839
3840     if (m_frame)
3841         m_frame->selection().didSplitTextNode(oldNode);
3842
3843     // FIXME: This should update markers for spelling and grammar checking.
3844 }
3845
3846 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3847 {
3848     DOMWindow* domWindow = this->domWindow();
3849     if (!domWindow)
3850         return;
3851     domWindow->setAttributeEventListener(eventType, listener);
3852 }
3853
3854 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3855 {
3856     DOMWindow* domWindow = this->domWindow();
3857     if (!domWindow)
3858         return 0;
3859     return domWindow->getAttributeEventListener(eventType);
3860 }
3861
3862 EventQueue* Document::eventQueue() const
3863 {
3864     if (!m_domWindow)
3865         return 0;
3866     return m_domWindow->eventQueue();
3867 }
3868
3869 void Document::enqueueAnimationFrameEvent(PassRefPtrWillBeRawPtr<Event> event)
3870 {
3871     ensureScriptedAnimationController().enqueueEvent(event);
3872 }
3873
3874 void Document::enqueueScrollEventForNode(Node* target)
3875 {
3876     // Per the W3C CSSOM View Module only scroll events fired at the document should bubble.
3877     RefPtrWillBeRawPtr<Event> scrollEvent = target->isDocumentNode() ? Event::createBubble(EventTypeNames::scroll) : Event::create(EventTypeNames::scroll);
3878     scrollEvent->setTarget(target);
3879     ensureScriptedAnimationController().enqueuePerFrameEvent(scrollEvent.release());
3880 }
3881
3882 void Document::enqueueResizeEvent()
3883 {
3884     RefPtrWillBeRawPtr<Event> event = Event::create(EventTypeNames::resize);
3885     event->setTarget(domWindow());
3886     ensureScriptedAnimationController().enqueuePerFrameEvent(event.release());
3887 }
3888
3889 PassRefPtrWillBeRawPtr<Event> Document::createEvent(const String& eventType, ExceptionState& exceptionState)
3890 {
3891     RefPtrWillBeRawPtr<Event> event = EventFactory::create(eventType);
3892     if (event)
3893         return event.release();
3894
3895     exceptionState.throwDOMException(NotSupportedError, "The provided event type ('" + eventType + "') is invalid.");
3896     return nullptr;
3897 }
3898
3899 void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
3900 {
3901     if (ContextFeatures::mutationEventsEnabled(this))
3902         addListenerType(listenerType);
3903 }
3904
3905 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
3906 {
3907     if (eventType == EventTypeNames::DOMSubtreeModified) {
3908         UseCounter::count(*this, UseCounter::DOMSubtreeModifiedEvent);
3909         addMutationEventListenerTypeIfEnabled(DOMSUBTREEMODIFIED_LISTENER);
3910     } else if (eventType == EventTypeNames::DOMNodeInserted) {
3911         UseCounter::count(*this, UseCounter::DOMNodeInsertedEvent);
3912         addMutationEventListenerTypeIfEnabled(DOMNODEINSERTED_LISTENER);
3913     } else if (eventType == EventTypeNames::DOMNodeRemoved) {
3914         UseCounter::count(*this, UseCounter::DOMNodeRemovedEvent);
3915         addMutationEventListenerTypeIfEnabled(DOMNODEREMOVED_LISTENER);
3916     } else if (eventType == EventTypeNames::DOMNodeRemovedFromDocument) {
3917         UseCounter::count(*this, UseCounter::DOMNodeRemovedFromDocumentEvent);
3918         addMutationEventListenerTypeIfEnabled(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
3919     } else if (eventType == EventTypeNames::DOMNodeInsertedIntoDocument) {
3920         UseCounter::count(*this, UseCounter::DOMNodeInsertedIntoDocumentEvent);
3921         addMutationEventListenerTypeIfEnabled(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
3922     } else if (eventType == EventTypeNames::DOMCharacterDataModified) {
3923         UseCounter::count(*this, UseCounter::DOMCharacterDataModifiedEvent);
3924         addMutationEventListenerTypeIfEnabled(DOMCHARACTERDATAMODIFIED_LISTENER);
3925     } else if (eventType == EventTypeNames::overflowchanged) {
3926         UseCounter::count(*this, UseCounter::OverflowChangedEvent);
3927         addListenerType(OVERFLOWCHANGED_LISTENER);
3928     } else if (eventType == EventTypeNames::webkitAnimationStart || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationstart)) {
3929         addListenerType(ANIMATIONSTART_LISTENER);
3930     } else if (eventType == EventTypeNames::webkitAnimationEnd || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationend)) {
3931         addListenerType(ANIMATIONEND_LISTENER);
3932     } else if (eventType == EventTypeNames::webkitAnimationIteration || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationiteration)) {
3933         addListenerType(ANIMATIONITERATION_LISTENER);
3934     } else if (eventType == EventTypeNames::webkitTransitionEnd || eventType == EventTypeNames::transitionend) {
3935         addListenerType(TRANSITIONEND_LISTENER);
3936     } else if (eventType == EventTypeNames::scroll) {
3937         addListenerType(SCROLL_LISTENER);
3938     } else if (eventType == EventTypeNames::DOMFocusIn || eventType == EventTypeNames::DOMFocusOut) {
3939         UseCounter::count(*this, UseCounter::DOMFocusInOutEvent);
3940     }
3941 }
3942
3943 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
3944 {
3945     return 0;
3946 }
3947
3948 HTMLFrameOwnerElement* Document::ownerElement() const
3949 {
3950     if (!frame())
3951         return 0;
3952     return frame()->ownerElement();
3953 }
3954
3955 String Document::cookie(ExceptionState& exceptionState) const
3956 {
3957     if (settings() && !settings()->cookieEnabled())
3958         return String();
3959
3960     // FIXME: The HTML5 DOM spec states that this attribute can raise an
3961     // InvalidStateError exception on getting if the Document has no
3962     // browsing context.
3963
3964     if (!securityOrigin()->canAccessCookies()) {
3965         if (isSandboxed(SandboxOrigin))
3966             exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
3967         else if (url().protocolIs("data"))
3968             exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
3969         else
3970             exceptionState.throwSecurityError("Access is denied for this document.");
3971         return String();
3972     }
3973
3974     KURL cookieURL = this->cookieURL();
3975     if (cookieURL.isEmpty())
3976         return String();
3977
3978     return cookies(this, cookieURL);
3979 }
3980
3981 void Document::setCookie(const String& value, ExceptionState& exceptionState)
3982 {
3983     if (settings() && !settings()->cookieEnabled())
3984         return;
3985
3986     // FIXME: The HTML5 DOM spec states that this attribute can raise an
3987     // InvalidStateError exception on setting if the Document has no
3988     // browsing context.
3989
3990     if (!securityOrigin()->canAccessCookies()) {
3991         if (isSandboxed(SandboxOrigin))
3992             exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
3993         else if (url().protocolIs("data"))
3994             exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
3995         else
3996             exceptionState.throwSecurityError("Access is denied for this document.");
3997         return;
3998     }
3999
4000     KURL cookieURL = this->cookieURL();
4001     if (cookieURL.isEmpty())
4002         return;
4003
4004     setCookies(this, cookieURL, value);
4005 }
4006
4007 const AtomicString& Document::referrer() const
4008 {
4009     if (loader())
4010         return loader()->request().httpReferrer();
4011     return nullAtom;
4012 }
4013
4014 String Document::domain() const
4015 {
4016     return securityOrigin()->domain();
4017 }
4018
4019 void Document::setDomain(const String& newDomain, ExceptionState& exceptionState)
4020 {
4021     if (isSandboxed(SandboxDocumentDomain)) {
4022         exceptionState.throwSecurityError("Assignment is forbidden for sandboxed iframes.");
4023         return;
4024     }
4025
4026     if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
4027         exceptionState.throwSecurityError("Assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme.");
4028         return;
4029     }
4030
4031     if (newDomain.isEmpty()) {
4032         exceptionState.throwSecurityError("'" + newDomain + "' is an empty domain.");
4033         return;
4034     }
4035
4036     OriginAccessEntry::IPAddressSetting ipAddressSetting = settings() && settings()->treatIPAddressAsDomain() ? OriginAccessEntry::TreatIPAddressAsDomain : OriginAccessEntry::TreatIPAddressAsIPAddress;
4037     OriginAccessEntry accessEntry(securityOrigin()->protocol(), newDomain, OriginAccessEntry::AllowSubdomains, ipAddressSetting);
4038     OriginAccessEntry::MatchResult result = accessEntry.matchesOrigin(*securityOrigin());
4039     if (result == OriginAccessEntry::DoesNotMatchOrigin) {
4040         exceptionState.throwSecurityError("'" + newDomain + "' is not a suffix of '" + domain() + "'.");
4041         return;
4042     }
4043
4044     if (result == OriginAccessEntry::MatchesOriginButIsPublicSuffix) {
4045         exceptionState.throwSecurityError("'" + newDomain + "' is a top-level domain.");
4046         return;
4047     }
4048
4049     securityOrigin()->setDomainFromDOM(newDomain);
4050     if (m_frame)
4051         m_frame->script().updateSecurityOrigin(securityOrigin());
4052 }
4053
4054 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
4055 String Document::lastModified() const
4056 {
4057     DateComponents date;
4058     bool foundDate = false;
4059     if (m_frame) {
4060         if (DocumentLoader* documentLoader = loader()) {
4061             const AtomicString& httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
4062             if (!httpLastModified.isEmpty()) {
4063                 date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
4064                 foundDate = true;
4065             }
4066         }
4067     }
4068     // FIXME: If this document came from the file system, the HTML5
4069     // specificiation tells us to read the last modification date from the file
4070     // system.
4071     if (!foundDate)
4072         date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
4073     return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
4074 }
4075
4076 const KURL& Document::firstPartyForCookies() const
4077 {
4078     return topDocument().url();
4079 }
4080
4081 static bool isValidNameNonASCII(const LChar* characters, unsigned length)
4082 {
4083     if (!isValidNameStart(characters[0]))
4084         return false;
4085
4086     for (unsigned i = 1; i < length; ++i) {
4087         if (!isValidNamePart(characters[i]))
4088             return false;
4089     }
4090
4091     return true;
4092 }
4093
4094 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
4095 {
4096     unsigned i = 0;
4097
4098     UChar32 c;
4099     U16_NEXT(characters, i, length, c)
4100     if (!isValidNameStart(c))
4101         return false;
4102
4103     while (i < length) {
4104         U16_NEXT(characters, i, length, c)
4105         if (!isValidNamePart(c))
4106             return false;
4107     }
4108
4109     return true;
4110 }
4111
4112 template<typename CharType>
4113 static inline bool isValidNameASCII(const CharType* characters, unsigned length)
4114 {
4115     CharType c = characters[0];
4116     if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
4117         return false;
4118
4119     for (unsigned i = 1; i < length; ++i) {
4120         c = characters[i];
4121         if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
4122             return false;
4123     }
4124
4125     return true;
4126 }
4127
4128 bool Document::isValidName(const String& name)
4129 {
4130     unsigned length = name.length();
4131     if (!length)
4132         return false;
4133
4134     if (name.is8Bit()) {
4135         const LChar* characters = name.characters8();
4136
4137         if (isValidNameASCII(characters, length))
4138             return true;
4139
4140         return isValidNameNonASCII(characters, length);
4141     }
4142
4143     const UChar* characters = name.characters16();
4144
4145     if (isValidNameASCII(characters, length))
4146         return true;
4147
4148     return isValidNameNonASCII(characters, length);
4149 }
4150
4151 template<typename CharType>
4152 static bool parseQualifiedNameInternal(const AtomicString& qualifiedName, const CharType* characters, unsigned length, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
4153 {
4154     bool nameStart = true;
4155     bool sawColon = false;
4156     int colonPos = 0;
4157
4158     for (unsigned i = 0; i < length;) {
4159         UChar32 c;
4160         U16_NEXT(characters, i, length, c)
4161         if (c == ':') {
4162             if (sawColon) {
4163                 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') contains multiple colons.");
4164                 return false; // multiple colons: not allowed
4165             }
4166             nameStart = true;
4167             sawColon = true;
4168             colonPos = i - 1;
4169         } else if (nameStart) {
4170             if (!isValidNameStart(c)) {
4171                 StringBuilder message;
4172                 message.appendLiteral("The qualified name provided ('");
4173                 message.append(qualifiedName);
4174                 message.appendLiteral("') contains the invalid name-start character '");
4175                 message.append(c);
4176                 message.appendLiteral("'.");
4177                 exceptionState.throwDOMException(InvalidCharacterError, message.toString());
4178                 return false;
4179             }
4180             nameStart = false;
4181         } else {
4182             if (!isValidNamePart(c)) {
4183                 StringBuilder message;
4184                 message.appendLiteral("The qualified name provided ('");
4185                 message.append(qualifiedName);
4186                 message.appendLiteral("') contains the invalid character '");
4187                 message.append(c);
4188                 message.appendLiteral("'.");
4189                 exceptionState.throwDOMException(InvalidCharacterError, message.toString());
4190                 return false;
4191             }
4192         }
4193     }
4194
4195     if (!sawColon) {
4196         prefix = nullAtom;
4197         localName = qualifiedName;
4198     } else {
4199         prefix = AtomicString(characters, colonPos);
4200         if (prefix.isEmpty()) {
4201             exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty namespace prefix.");
4202             return false;
4203         }
4204         int prefixStart = colonPos + 1;
4205         localName = AtomicString(characters + prefixStart, length - prefixStart);
4206     }
4207
4208     if (localName.isEmpty()) {
4209         exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty local name.");
4210         return false;
4211     }
4212
4213     return true;
4214 }
4215
4216 bool Document::parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
4217 {
4218     unsigned length = qualifiedName.length();
4219
4220     if (!length) {
4221         exceptionState.throwDOMException(InvalidCharacterError, "The qualified name provided is empty.");
4222         return false;
4223     }
4224
4225     if (qualifiedName.is8Bit())
4226         return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName, exceptionState);
4227     return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName, exceptionState);
4228 }
4229
4230 void Document::setEncodingData(const DocumentEncodingData& newData)
4231 {
4232     // It's possible for the encoding of the document to change while we're decoding
4233     // data. That can only occur while we're processing the <head> portion of the
4234     // document. There isn't much user-visible content in the <head>, but there is
4235     // the <title> element. This function detects that situation and re-decodes the
4236     // document's title so that the user doesn't see an incorrectly decoded title
4237     // in the title bar.
4238     if (m_titleElement
4239         && encoding() != newData.encoding()
4240         && !ElementTraversal::firstWithin(*m_titleElement)
4241         && encoding() == Latin1Encoding()
4242         && m_titleElement->textContent().containsOnlyLatin1()) {
4243
4244         CString originalBytes = m_titleElement->textContent().latin1();
4245         OwnPtr<TextCodec> codec = newTextCodec(newData.encoding());
4246         String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), DataEOF);
4247         m_titleElement->setTextContent(correctlyDecodedTitle);
4248     }
4249
4250     m_encodingData = newData;
4251
4252     // FIXME: Should be removed as part of https://code.google.com/p/chromium/issues/detail?id=319643
4253     bool shouldUseVisualOrdering = m_encodingData.encoding().usesVisualOrdering();
4254     if (shouldUseVisualOrdering != m_visuallyOrdered) {
4255         m_visuallyOrdered = shouldUseVisualOrdering;
4256         // FIXME: How is possible to not have a renderer here?
4257         if (renderView())
4258             renderView()->style()->setRTLOrdering(m_visuallyOrdered ? VisualOrder : LogicalOrder);
4259         setNeedsStyleRecalc(SubtreeStyleChange);
4260     }
4261 }
4262
4263 KURL Document::completeURL(const String& url) const
4264 {
4265     return completeURLWithOverride(url, m_baseURL);
4266 }
4267
4268 KURL Document::completeURLWithOverride(const String& url, const KURL& baseURLOverride) const
4269 {
4270     // Always return a null URL when passed a null string.
4271     // FIXME: Should we change the KURL constructor to have this behavior?
4272     // See also [CSS]StyleSheet::completeURL(const String&)
4273     if (url.isNull())
4274         return KURL();
4275     // This logic is deliberately spread over many statements in an attempt to track down http://crbug.com/312410.
4276     const KURL* baseURLFromParent = 0;
4277     bool shouldUseParentBaseURL = baseURLOverride.isEmpty();
4278     if (!shouldUseParentBaseURL) {
4279         const KURL& aboutBlankURL = blankURL();
4280         shouldUseParentBaseURL = (baseURLOverride == aboutBlankURL);
4281     }
4282     if (shouldUseParentBaseURL) {
4283         if (Document* parent = parentDocument())
4284             baseURLFromParent = &parent->baseURL();
4285     }
4286     const KURL& baseURL = baseURLFromParent ? *baseURLFromParent : baseURLOverride;
4287     if (!encoding().isValid())
4288         return KURL(baseURL, url);
4289     return KURL(baseURL, url, encoding());
4290 }
4291
4292 // Support for Javascript execCommand, and related methods
4293
4294 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
4295 {
4296     LocalFrame* frame = document->frame();
4297     if (!frame || frame->document() != document)
4298         return Editor::Command();
4299
4300     document->updateRenderTreeIfNeeded();
4301     return frame->editor().command(commandName, userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
4302 }
4303
4304 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
4305 {
4306     // We don't allow recusrive |execCommand()| to protect against attack code.
4307     // Recursive call of |execCommand()| could be happened by moving iframe
4308     // with script triggered by insertion, e.g. <iframe src="javascript:...">
4309     // <iframe onload="...">. This usage is valid as of the specification
4310     // although, it isn't common use case, rather it is used as attack code.
4311     static bool inExecCommand = false;
4312     if (inExecCommand) {
4313         String message = "We don't execute document.execCommand() this time, because it is called recursively.";
4314         addConsoleMessage(JSMessageSource, WarningMessageLevel, message);
4315         return false;
4316     }
4317     TemporaryChange<bool> executeScope(inExecCommand, true);
4318
4319     // Postpone DOM mutation events, which can execute scripts and change
4320     // DOM tree against implementation assumption.
4321     EventQueueScope eventQueueScope;
4322     Editor::Command editorCommand = command(this, commandName, userInterface);
4323     blink::Platform::current()->histogramSparse("WebCore.Document.execCommand", editorCommand.idForHistogram());
4324     return editorCommand.execute(value);
4325 }
4326
4327 bool Document::queryCommandEnabled(const String& commandName)
4328 {
4329     return command(this, commandName).isEnabled();
4330 }
4331
4332 bool Document::queryCommandIndeterm(const String& commandName)
4333 {
4334     return command(this, commandName).state() == MixedTriState;
4335 }
4336
4337 bool Document::queryCommandState(const String& commandName)
4338 {
4339     return command(this, commandName).state() == TrueTriState;
4340 }
4341
4342 bool Document::queryCommandSupported(const String& commandName)
4343 {
4344     return command(this, commandName).isSupported();
4345 }
4346
4347 String Document::queryCommandValue(const String& commandName)
4348 {
4349     return command(this, commandName).value();
4350 }
4351
4352 KURL Document::openSearchDescriptionURL()
4353 {
4354     static const char openSearchMIMEType[] = "application/opensearchdescription+xml";
4355     static const char openSearchRelation[] = "search";
4356
4357     // FIXME: Why do only top-level frames have openSearchDescriptionURLs?
4358     if (!frame() || frame()->tree().parent())
4359         return KURL();
4360
4361     // FIXME: Why do we need to wait for FrameStateComplete?
4362     if (frame()->loader().state() != FrameStateComplete)
4363         return KURL();
4364
4365     if (!head())
4366         return KURL();
4367
4368     for (HTMLLinkElement* linkElement = Traversal<HTMLLinkElement>::firstChild(*head()); linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4369         if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
4370             continue;
4371         if (linkElement->href().isEmpty())
4372             continue;
4373         return linkElement->href();
4374     }
4375
4376     return KURL();
4377 }
4378
4379 void Document::pushCurrentScript(PassRefPtr<HTMLScriptElement> newCurrentScript)
4380 {
4381     ASSERT(newCurrentScript);
4382     m_currentScriptStack.append(newCurrentScript);
4383 }
4384
4385 void Document::popCurrentScript()
4386 {
4387     ASSERT(!m_currentScriptStack.isEmpty());
4388     m_currentScriptStack.removeLast();
4389 }
4390
4391 void Document::applyXSLTransform(ProcessingInstruction* pi)
4392 {
4393     ASSERT(!pi->isLoading());
4394     UseCounter::count(*this, UseCounter::XSLProcessingInstruction);
4395     RefPtrWillBeRawPtr<XSLTProcessor> processor = XSLTProcessor::create();
4396     processor->setXSLStyleSheet(toXSLStyleSheet(pi->sheet()));
4397     String resultMIMEType;
4398     String newSource;
4399     String resultEncoding;
4400     if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
4401         return;
4402     // FIXME: If the transform failed we should probably report an error (like Mozilla does).
4403     LocalFrame* ownerFrame = frame();
4404     processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, ownerFrame);
4405     InspectorInstrumentation::frameDocumentUpdated(ownerFrame);
4406 }
4407
4408 void Document::setTransformSource(PassOwnPtr<TransformSource> source)
4409 {
4410     m_transformSource = source;
4411 }
4412
4413 void Document::setDesignMode(InheritedBool value)
4414 {
4415     m_designMode = value;
4416     for (LocalFrame* frame = m_frame; frame && frame->document(); frame = frame->tree().traverseNext(m_frame))
4417         frame->document()->setNeedsStyleRecalc(SubtreeStyleChange);
4418 }
4419
4420 Document::InheritedBool Document::getDesignMode() const
4421 {
4422     return m_designMode;
4423 }
4424
4425 bool Document::inDesignMode() const
4426 {
4427     for (const Document* d = this; d; d = d->parentDocument()) {
4428         if (d->m_designMode != inherit)
4429             return d->m_designMode;
4430     }
4431     return false;
4432 }
4433
4434 String Document::designMode() const
4435 {
4436     return inDesignMode() ? "on" : "off";
4437 }
4438
4439 void Document::setDesignMode(const String& value)
4440 {
4441     InheritedBool mode;
4442     if (equalIgnoringCase(value, "on"))
4443         mode = on;
4444     else if (equalIgnoringCase(value, "off"))
4445         mode = off;
4446     else
4447         mode = inherit;
4448     setDesignMode(mode);
4449 }
4450
4451 Document* Document::parentDocument() const
4452 {
4453     if (!m_frame)
4454         return 0;
4455     LocalFrame* parent = m_frame->tree().parent();
4456     if (!parent)
4457         return 0;
4458     return parent->document();
4459 }
4460
4461 Document& Document::topDocument() const
4462 {
4463     Document* doc = const_cast<Document*>(this);
4464     Element* element;
4465     while ((element = doc->ownerElement()))
4466         doc = &element->document();
4467
4468     ASSERT(doc);
4469     return *doc;
4470 }
4471
4472 WeakPtr<Document> Document::contextDocument()
4473 {
4474     if (m_contextDocument)
4475         return m_contextDocument;
4476     if (m_frame)
4477         return m_weakFactory.createWeakPtr();
4478     return WeakPtr<Document>(nullptr);
4479 }
4480
4481 PassRefPtr<Attr> Document::createAttribute(const AtomicString& name, ExceptionState& exceptionState)
4482 {
4483     return createAttributeNS(nullAtom, name, exceptionState, true);
4484 }
4485
4486 PassRefPtr<Attr> Document::createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState, bool shouldIgnoreNamespaceChecks)
4487 {
4488     AtomicString prefix, localName;
4489     if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
4490         return nullptr;
4491
4492     QualifiedName qName(prefix, localName, namespaceURI);
4493
4494     if (!shouldIgnoreNamespaceChecks && !hasValidNamespaceForAttributes(qName)) {
4495         exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
4496         return nullptr;
4497     }
4498
4499     return Attr::create(*this, qName, emptyAtom);
4500 }
4501
4502 const SVGDocumentExtensions* Document::svgExtensions()
4503 {
4504     return m_svgExtensions.get();
4505 }
4506
4507 SVGDocumentExtensions& Document::accessSVGExtensions()
4508 {
4509     if (!m_svgExtensions)
4510         m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this));
4511     return *m_svgExtensions;
4512 }
4513
4514 bool Document::hasSVGRootNode() const
4515 {
4516     return isSVGSVGElement(documentElement());
4517 }
4518
4519 PassRefPtr<HTMLCollection> Document::ensureCachedCollection(CollectionType type)
4520 {
4521     return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(*this, type);
4522 }
4523
4524 PassRefPtr<HTMLCollection> Document::images()
4525 {
4526     return ensureCachedCollection(DocImages);
4527 }
4528
4529 PassRefPtr<HTMLCollection> Document::applets()
4530 {
4531     return ensureCachedCollection(DocApplets);
4532 }
4533
4534 PassRefPtr<HTMLCollection> Document::embeds()
4535 {
4536     return ensureCachedCollection(DocEmbeds);
4537 }
4538
4539 PassRefPtr<HTMLCollection> Document::scripts()
4540 {
4541     return ensureCachedCollection(DocScripts);
4542 }
4543
4544 PassRefPtr<HTMLCollection> Document::links()
4545 {
4546     return ensureCachedCollection(DocLinks);
4547 }
4548
4549 PassRefPtr<HTMLCollection> Document::forms()
4550 {
4551     return ensureCachedCollection(DocForms);
4552 }
4553
4554 PassRefPtr<HTMLCollection> Document::anchors()
4555 {
4556     return ensureCachedCollection(DocAnchors);
4557 }
4558
4559 PassRefPtr<HTMLAllCollection> Document::allForBinding()
4560 {
4561     UseCounter::count(*this, UseCounter::DocumentAll);
4562     return all();
4563 }
4564
4565 PassRefPtr<HTMLAllCollection> Document::all()
4566 {
4567     return ensureRareData().ensureNodeLists().addCache<HTMLAllCollection>(*this, DocAll);
4568 }
4569
4570 PassRefPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
4571 {
4572     return ensureRareData().ensureNodeLists().addCache<HTMLNameCollection>(*this, WindowNamedItems, name);
4573 }
4574
4575 PassRefPtr<HTMLCollection> Document::documentNamedItems(const AtomicString& name)
4576 {
4577     return ensureRareData().ensureNodeLists().addCache<HTMLNameCollection>(*this, DocumentNamedItems, name);
4578 }
4579
4580 void Document::finishedParsing()
4581 {
4582     ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
4583     ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
4584     setParsing(false);
4585     if (!m_documentTiming.domContentLoadedEventStart)
4586         m_documentTiming.domContentLoadedEventStart = monotonicallyIncreasingTime();
4587     dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
4588     if (!m_documentTiming.domContentLoadedEventEnd)
4589         m_documentTiming.domContentLoadedEventEnd = monotonicallyIncreasingTime();
4590
4591     if (frame() && frame()->isMainFrame()) {
4592         // Reset the text autosizing multipliers on main frame when DOM is loaded.
4593         // This is to allow for a fresh text autosizing pass when the page layout
4594         // changes significantly in the end.
4595         if (TextAutosizer* textAutosizer = this->textAutosizer())
4596             textAutosizer->recalculateMultipliers();
4597     }
4598
4599     // The loader's finishedParsing() method may invoke script that causes this object to
4600     // be dereferenced (when this document is in an iframe and the onload causes the iframe's src to change).
4601     // Keep it alive until we are done.
4602     RefPtr<Document> protect(this);
4603
4604     if (RefPtr<LocalFrame> f = frame()) {
4605         // Don't update the render tree if we haven't requested the main resource yet to avoid
4606         // adding extra latency. Note that the first render tree update can be expensive since it
4607         // triggers the parsing of the default stylesheets which are compiled-in.
4608         const bool mainResourceWasAlreadyRequested =
4609             m_frame->loader().stateMachine()->committedFirstRealDocumentLoad();
4610
4611         // FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
4612         // resource loads are complete. HTMLObjectElements can start loading their resources from
4613         // post attach callbacks triggered by recalcStyle().  This means if we parse out an <object>
4614         // tag and then reach the end of the document without updating styles, we might not have yet
4615         // started the resource load and might fire the window load event too early.  To avoid this
4616         // we force the styles to be up to date before calling FrameLoader::finishedParsing().
4617         // See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
4618         if (mainResourceWasAlreadyRequested)
4619             updateRenderTreeIfNeeded();
4620
4621         f->loader().finishedParsing();
4622
4623         TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", "data", InspectorMarkLoadEvent::data(f.get()));
4624         // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
4625         InspectorInstrumentation::domContentLoadedEventFired(f.get());
4626     }
4627
4628     // Schedule dropping of the ElementDataCache. We keep it alive for a while after parsing finishes
4629     // so that dynamically inserted content can also benefit from sharing optimizations.
4630     // Note that we don't refresh the timer on cache access since that could lead to huge caches being kept
4631     // alive indefinitely by something innocuous like JS setting .innerHTML repeatedly on a timer.
4632     m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
4633
4634     // Parser should have picked up all preloads by now
4635     m_fetcher->clearPreloads();
4636
4637     if (HTMLImportLoader* import = importLoader())
4638         import->didFinishParsing();
4639 }
4640
4641 void Document::elementDataCacheClearTimerFired(Timer<Document>*)
4642 {
4643     m_elementDataCache.clear();
4644 }
4645
4646 Vector<IconURL> Document::iconURLs(int iconTypesMask)
4647 {
4648     IconURL firstFavicon;
4649     IconURL firstTouchIcon;
4650     IconURL firstTouchPrecomposedIcon;
4651     Vector<IconURL> secondaryIcons;
4652
4653     // Start from the last child node so that icons seen later take precedence as required by the spec.
4654     for (HTMLLinkElement* linkElement = head() ? Traversal<HTMLLinkElement>::firstChild(*head()) : 0; linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4655         if (!(linkElement->iconType() & iconTypesMask))
4656             continue;
4657         if (linkElement->href().isEmpty())
4658             continue;
4659         if (!RuntimeEnabledFeatures::touchIconLoadingEnabled() && linkElement->iconType() != Favicon)
4660             continue;
4661
4662         IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
4663         if (linkElement->iconType() == Favicon) {
4664             if (firstFavicon.m_iconType != InvalidIcon)
4665                 secondaryIcons.append(firstFavicon);
4666             firstFavicon = newURL;
4667         } else if (linkElement->iconType() == TouchIcon) {
4668             if (firstTouchIcon.m_iconType != InvalidIcon)
4669                 secondaryIcons.append(firstTouchIcon);
4670             firstTouchIcon = newURL;
4671         } else if (linkElement->iconType() == TouchPrecomposedIcon) {
4672             if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4673                 secondaryIcons.append(firstTouchPrecomposedIcon);
4674             firstTouchPrecomposedIcon = newURL;
4675         } else {
4676             ASSERT_NOT_REACHED();
4677         }
4678     }
4679
4680     Vector<IconURL> iconURLs;
4681     if (firstFavicon.m_iconType != InvalidIcon)
4682         iconURLs.append(firstFavicon);
4683     else if (m_url.protocolIsInHTTPFamily() && iconTypesMask & Favicon)
4684         iconURLs.append(IconURL::defaultFavicon(m_url));
4685
4686     if (firstTouchIcon.m_iconType != InvalidIcon)
4687         iconURLs.append(firstTouchIcon);
4688     if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4689         iconURLs.append(firstTouchPrecomposedIcon);
4690     for (int i = secondaryIcons.size() - 1; i >= 0; --i)
4691         iconURLs.append(secondaryIcons[i]);
4692     return iconURLs;
4693 }
4694
4695 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
4696 {
4697     if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
4698         return;
4699
4700     m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
4701     m_frame->selection().updateSecureKeyboardEntryIfActive();
4702 }
4703
4704 bool Document::useSecureKeyboardEntryWhenActive() const
4705 {
4706     return m_useSecureKeyboardEntryWhenActive;
4707 }
4708
4709 void Document::initSecurityContext()
4710 {
4711     initSecurityContext(DocumentInit(m_url, m_frame, contextDocument(), m_importsController));
4712 }
4713
4714 static PassRefPtr<ContentSecurityPolicy> contentSecurityPolicyFor(Document* document)
4715 {
4716     if (document->importsController())
4717         return document->importsController()->master()->contentSecurityPolicy();
4718     return ContentSecurityPolicy::create(document);
4719 }
4720
4721 void Document::initSecurityContext(const DocumentInit& initializer)
4722 {
4723     if (haveInitializedSecurityOrigin()) {
4724         ASSERT(securityOrigin());
4725         return;
4726     }
4727
4728     if (!initializer.hasSecurityContext()) {
4729         // No source for a security context.
4730         // This can occur via document.implementation.createDocument().
4731         m_cookieURL = KURL(ParsedURLString, emptyString());
4732         setSecurityOrigin(SecurityOrigin::createUnique());
4733         setContentSecurityPolicy(ContentSecurityPolicy::create(this));
4734         return;
4735     }
4736
4737     // In the common case, create the security context from the currently
4738     // loading URL with a fresh content security policy.
4739     m_cookieURL = m_url;
4740     enforceSandboxFlags(initializer.sandboxFlags());
4741     setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
4742     setContentSecurityPolicy(contentSecurityPolicyFor(this));
4743
4744     if (Settings* settings = initializer.settings()) {
4745         if (!settings->webSecurityEnabled()) {
4746             // Web security is turned off. We should let this document access every other document. This is used primary by testing
4747             // harnesses for web sites.
4748             securityOrigin()->grantUniversalAccess();
4749         } else if (securityOrigin()->isLocal()) {
4750             if (settings->allowUniversalAccessFromFileURLs()) {
4751                 // Some clients want local URLs to have universal access, but that setting is dangerous for other clients.
4752                 securityOrigin()->grantUniversalAccess();
4753             } else if (!settings->allowFileAccessFromFileURLs()) {
4754                 // Some clients want local URLs to have even tighter restrictions by default, and not be able to access other local files.
4755                 // FIXME 81578: The naming of this is confusing. Files with restricted access to other local files
4756                 // still can have other privileges that can be remembered, thereby not making them unique origins.
4757                 securityOrigin()->enforceFilePathSeparation();
4758             }
4759         }
4760     }
4761
4762     if (initializer.shouldTreatURLAsSrcdocDocument()) {
4763         m_isSrcdocDocument = true;
4764         setBaseURLOverride(initializer.parentBaseURL());
4765     }
4766
4767     if (!shouldInheritSecurityOriginFromOwner(m_url))
4768         return;
4769
4770     // If we do not obtain a meaningful origin from the URL, then we try to
4771     // find one via the frame hierarchy.
4772
4773     if (!initializer.owner()) {
4774         didFailToInitializeSecurityOrigin();
4775         return;
4776     }
4777
4778     if (isSandboxed(SandboxOrigin)) {
4779         // If we're supposed to inherit our security origin from our owner,
4780         // but we're also sandboxed, the only thing we inherit is the ability
4781         // to load local resources. This lets about:blank iframes in file://
4782         // URL documents load images and other resources from the file system.
4783         if (initializer.owner()->securityOrigin()->canLoadLocalResources())
4784             securityOrigin()->grantLoadLocalResources();
4785         return;
4786     }
4787
4788     m_cookieURL = initializer.owner()->cookieURL();
4789     // We alias the SecurityOrigins to match Firefox, see Bug 15313
4790     // https://bugs.webkit.org/show_bug.cgi?id=15313
4791     setSecurityOrigin(initializer.owner()->securityOrigin());
4792 }
4793
4794 void Document::initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders& headers)
4795 {
4796     if (m_frame && m_frame->tree().parent() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
4797         contentSecurityPolicy()->copyStateFrom(m_frame->tree().parent()->document()->contentSecurityPolicy());
4798     contentSecurityPolicy()->didReceiveHeaders(headers);
4799 }
4800
4801 bool Document::allowInlineEventHandlers(Node* node, EventListener* listener, const String& contextURL, const WTF::OrdinalNumber& contextLine)
4802 {
4803     if (!contentSecurityPolicy()->allowInlineEventHandlers(contextURL, contextLine))
4804         return false;
4805
4806     // HTML says that inline script needs browsing context to create its execution environment.
4807     // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#event-handler-attributes
4808     // Also, if the listening node came from other document, which happens on context-less event dispatching,
4809     // we also need to ask the owner document of the node.
4810     LocalFrame* frame = executingFrame();
4811     if (!frame)
4812         return false;
4813     if (!frame->script().canExecuteScripts(NotAboutToExecuteScript))
4814         return false;
4815     if (node && node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
4816         return false;
4817
4818     return true;
4819 }
4820
4821 bool Document::allowExecutingScripts(Node* node)
4822 {
4823     // FIXME: Eventually we'd like to evaluate scripts which are inserted into a
4824     // viewless document but this'll do for now.
4825     // See http://bugs.webkit.org/show_bug.cgi?id=5727
4826     LocalFrame* frame = executingFrame();
4827     if (!frame)
4828         return false;
4829     if (!node->document().executingFrame())
4830         return false;
4831     if (!frame->script().canExecuteScripts(AboutToExecuteScript))
4832         return false;
4833     return true;
4834 }
4835
4836 void Document::updateSecurityOrigin(PassRefPtr<SecurityOrigin> origin)
4837 {
4838     setSecurityOrigin(origin);
4839     didUpdateSecurityOrigin();
4840 }
4841
4842 void Document::didUpdateSecurityOrigin()
4843 {
4844     if (!m_frame)
4845         return;
4846     m_frame->script().updateSecurityOrigin(securityOrigin());
4847 }
4848
4849 bool Document::isContextThread() const
4850 {
4851     return isMainThread();
4852 }
4853
4854 void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
4855 {
4856     m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
4857     if (!m_updateFocusAppearanceTimer.isActive())
4858         m_updateFocusAppearanceTimer.startOneShot(0, FROM_HERE);
4859 }
4860
4861 void Document::cancelFocusAppearanceUpdate()
4862 {
4863     m_updateFocusAppearanceTimer.stop();
4864 }
4865
4866 void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
4867 {
4868     Element* element = focusedElement();
4869     if (!element)
4870         return;
4871     updateLayout();
4872     if (element->isFocusable())
4873         element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
4874 }
4875
4876 void Document::attachRange(Range* range)
4877 {
4878     ASSERT(!m_ranges.contains(range));
4879     m_ranges.add(range);
4880 }
4881
4882 void Document::detachRange(Range* range)
4883 {
4884     // We don't ASSERT m_ranges.contains(range) to allow us to call this
4885     // unconditionally to fix: https://bugs.webkit.org/show_bug.cgi?id=26044
4886     m_ranges.remove(range);
4887 }
4888
4889 void Document::getCSSCanvasContext(const String& type, const String& name, int width, int height, bool& is2d, RefPtrWillBeRawPtr<CanvasRenderingContext2D>& context2d, bool& is3d, RefPtrWillBeRawPtr<WebGLRenderingContext>& context3d)
4890 {
4891     HTMLCanvasElement& element = getCSSCanvasElement(name);
4892     element.setSize(IntSize(width, height));
4893     CanvasRenderingContext* context = element.getContext(type);
4894     if (!context)
4895         return;
4896
4897     if (context->is2d()) {
4898         is2d = true;
4899         context2d = toCanvasRenderingContext2D(context);
4900     } else if (context->is3d()) {
4901         is3d = true;
4902         context3d = toWebGLRenderingContext(context);
4903     }
4904 }
4905
4906 HTMLCanvasElement& Document::getCSSCanvasElement(const String& name)
4907 {
4908     RefPtrWillBeMember<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, nullptr).storedValue->value;
4909     if (!element) {
4910         element = HTMLCanvasElement::create(*this);
4911         element->setAccelerationDisabled(true);
4912     }
4913     return *element;
4914 }
4915
4916 void Document::initDNSPrefetch()
4917 {
4918     Settings* settings = this->settings();
4919
4920     m_haveExplicitlyDisabledDNSPrefetch = false;
4921     m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
4922
4923     // Inherit DNS prefetch opt-out from parent frame
4924     if (Document* parent = parentDocument()) {
4925         if (!parent->isDNSPrefetchEnabled())
4926             m_isDNSPrefetchEnabled = false;
4927     }
4928 }
4929
4930 void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
4931 {
4932     if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
4933         m_isDNSPrefetchEnabled = true;
4934         return;
4935     }
4936
4937     m_isDNSPrefetchEnabled = false;
4938     m_haveExplicitlyDisabledDNSPrefetch = true;
4939 }
4940
4941 void Document::reportBlockedScriptExecutionToInspector(const String& directiveText)
4942 {
4943     InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText);
4944 }
4945
4946 void Document::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* scriptState)
4947 {
4948     internalAddMessage(source, level, message, sourceURL, lineNumber, nullptr, scriptState);
4949 }
4950
4951 void Document::internalAddMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* scriptState)
4952 {
4953     if (!isContextThread()) {
4954         m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
4955         return;
4956     }
4957
4958     if (!m_frame)
4959         return;
4960
4961     String messageURL = sourceURL;
4962     if (!scriptState && sourceURL.isNull() && !lineNumber) {
4963         messageURL = url().string();
4964         if (parsing() && !isInDocumentWrite() && scriptableDocumentParser()) {
4965             ScriptableDocumentParser* parser = scriptableDocumentParser();
4966             if (!parser->isWaitingForScripts() && !parser->isExecutingScript())
4967                 lineNumber = parser->lineNumber().oneBasedInt();
4968         }
4969     }
4970     m_frame->console().addMessage(source, level, message, messageURL, lineNumber, 0, callStack, scriptState, 0);
4971 }
4972
4973 void Document::addConsoleMessageWithRequestIdentifier(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
4974 {
4975     if (!isContextThread()) {
4976         m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
4977         return;
4978     }
4979
4980     if (m_frame)
4981         m_frame->console().addMessage(source, level, message, String(), 0, 0, nullptr, 0, requestIdentifier);
4982 }
4983
4984 // FIXME(crbug.com/305497): This should be removed after ExecutionContext-DOMWindow migration.
4985 void Document::postTask(PassOwnPtr<ExecutionContextTask> task)
4986 {
4987     m_taskRunner->postTask(task);
4988 }
4989
4990 void Document::tasksWereSuspended()
4991 {
4992     scriptRunner()->suspend();
4993
4994     if (m_parser)
4995         m_parser->suspendScheduledTasks();
4996     if (m_scriptedAnimationController)
4997         m_scriptedAnimationController->suspend();
4998 }
4999
5000 void Document::tasksWereResumed()
5001 {
5002     scriptRunner()->resume();
5003
5004     if (m_parser)
5005         m_parser->resumeScheduledTasks();
5006     if (m_scriptedAnimationController)
5007         m_scriptedAnimationController->resume();
5008
5009     MutationObserver::resumeSuspendedObservers();
5010 }
5011
5012 // FIXME: suspendScheduledTasks(), resumeScheduledTasks(), tasksNeedSuspension()
5013 // should be moved to DOMWindow once it inherits ExecutionContext
5014 void Document::suspendScheduledTasks()
5015 {
5016     ExecutionContext::suspendScheduledTasks();
5017     m_taskRunner->suspend();
5018 }
5019
5020 void Document::resumeScheduledTasks()
5021 {
5022     ExecutionContext::resumeScheduledTasks();
5023     m_taskRunner->resume();
5024 }
5025
5026 bool Document::tasksNeedSuspension()
5027 {
5028     Page* page = this->page();
5029     return page && page->defersLoading();
5030 }
5031
5032 void Document::addToTopLayer(Element* element, const Element* before)
5033 {
5034     if (element->isInTopLayer())
5035         return;
5036
5037     ASSERT(!m_topLayerElements.contains(element));
5038     ASSERT(!before || m_topLayerElements.contains(before));
5039     if (before) {
5040         size_t beforePosition = m_topLayerElements.find(before);
5041         m_topLayerElements.insert(beforePosition, element);
5042     } else {
5043         m_topLayerElements.append(element);
5044     }
5045     element->setIsInTopLayer(true);
5046 }
5047
5048 void Document::removeFromTopLayer(Element* element)
5049 {
5050     if (!element->isInTopLayer())
5051         return;
5052     size_t position = m_topLayerElements.find(element);
5053     ASSERT(position != kNotFound);
5054     m_topLayerElements.remove(position);
5055     element->setIsInTopLayer(false);
5056 }
5057
5058 HTMLDialogElement* Document::activeModalDialog() const
5059 {
5060     if (m_topLayerElements.isEmpty())
5061         return 0;
5062     return toHTMLDialogElement(m_topLayerElements.last().get());
5063 }
5064
5065 void Document::webkitExitPointerLock()
5066 {
5067     if (!page())
5068         return;
5069     if (Element* target = page()->pointerLockController().element()) {
5070         if (target->document() != this)
5071             return;
5072     }
5073     page()->pointerLockController().requestPointerUnlock();
5074 }
5075
5076 Element* Document::webkitPointerLockElement() const
5077 {
5078     if (!page() || page()->pointerLockController().lockPending())
5079         return 0;
5080     if (Element* element = page()->pointerLockController().element()) {
5081         if (element->document() == this)
5082             return element;
5083     }
5084     return 0;
5085 }
5086
5087 void Document::decrementLoadEventDelayCount()
5088 {
5089     ASSERT(m_loadEventDelayCount);
5090     --m_loadEventDelayCount;
5091
5092     if (!m_loadEventDelayCount)
5093         checkLoadEventSoon();
5094 }
5095
5096 void Document::checkLoadEventSoon()
5097 {
5098     if (frame() && !m_loadEventDelayTimer.isActive())
5099         m_loadEventDelayTimer.startOneShot(0, FROM_HERE);
5100 }
5101
5102 bool Document::isDelayingLoadEvent()
5103 {
5104 #if ENABLE(OILPAN)
5105     // Always delay load events until after garbage collection.
5106     // This way we don't have to explicitly delay load events via
5107     // incrementLoadEventDelayCount and decrementLoadEventDelayCount in
5108     // Node destructors.
5109     if (ThreadState::current()->isSweepInProgress()) {
5110         if (!m_loadEventDelayCount)
5111             checkLoadEventSoon();
5112         return true;
5113     }
5114 #endif
5115     return m_loadEventDelayCount;
5116 }
5117
5118
5119 void Document::loadEventDelayTimerFired(Timer<Document>*)
5120 {
5121     if (frame())
5122         frame()->loader().checkCompleted();
5123 }
5124
5125 void Document::loadPluginsSoon()
5126 {
5127     // FIXME: Remove this timer once we don't need to compute layout to load plugins.
5128     if (!m_pluginLoadingTimer.isActive())
5129         m_pluginLoadingTimer.startOneShot(0, FROM_HERE);
5130 }
5131
5132 void Document::pluginLoadingTimerFired(Timer<Document>*)
5133 {
5134     updateLayout();
5135 }
5136
5137 ScriptedAnimationController& Document::ensureScriptedAnimationController()
5138 {
5139     if (!m_scriptedAnimationController) {
5140         m_scriptedAnimationController = ScriptedAnimationController::create(this);
5141         // We need to make sure that we don't start up the animation controller on a background tab, for example.
5142         if (!page())
5143             m_scriptedAnimationController->suspend();
5144     }
5145     return *m_scriptedAnimationController;
5146 }
5147
5148 int Document::requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
5149 {
5150     return ensureScriptedAnimationController().registerCallback(callback);
5151 }
5152
5153 void Document::cancelAnimationFrame(int id)
5154 {
5155     if (!m_scriptedAnimationController)
5156         return;
5157     m_scriptedAnimationController->cancelCallback(id);
5158 }
5159
5160 void Document::serviceScriptedAnimations(double monotonicAnimationStartTime)
5161 {
5162     if (!m_scriptedAnimationController)
5163         return;
5164     m_scriptedAnimationController->serviceScriptedAnimations(monotonicAnimationStartTime);
5165 }
5166
5167 PassRefPtrWillBeRawPtr<Touch> Document::createTouch(DOMWindow* window, EventTarget* target, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force) const
5168 {
5169     // FIXME: It's not clear from the documentation at
5170     // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html
5171     // when this method should throw and nor is it by inspection of iOS behavior. It would be nice to verify any cases where it throws under iOS
5172     // and implement them here. See https://bugs.webkit.org/show_bug.cgi?id=47819
5173     LocalFrame* frame = window ? window->frame() : this->frame();
5174     return Touch::create(frame, target, identifier, screenX, screenY, pageX, pageY, radiusX, radiusY, rotationAngle, force);
5175 }
5176
5177 PassRefPtrWillBeRawPtr<TouchList> Document::createTouchList(WillBeHeapVector<RefPtrWillBeMember<Touch> >& touches) const
5178 {
5179     return TouchList::create(touches);
5180 }
5181
5182 void Document::didAddTouchEventHandler(Node* handler)
5183 {
5184     // The node should either be in this document, or be the Document node of a child
5185     // of this document.
5186     ASSERT(&handler->document() == this
5187         || (handler->isDocumentNode() && toDocument(handler)->parentDocument() == this));
5188     if (!m_touchEventTargets.get())
5189         m_touchEventTargets = adoptPtr(new TouchEventTargetSet);
5190     bool isFirstHandler = m_touchEventTargets->isEmpty();
5191
5192     if (!m_touchEventTargets->add(handler).isNewEntry) {
5193         // Just incremented refcount, no real change.
5194         // If this is a child document node, then the count should never go above 1.
5195         ASSERT(!handler->isDocumentNode() || &handler->document() == this);
5196         return;
5197     }
5198
5199     if (isFirstHandler) {
5200         if (Document* parent = parentDocument()) {
5201             parent->didAddTouchEventHandler(this);
5202         } else {
5203             // This is the first touch handler on the whole page.
5204             if (FrameHost* frameHost = this->frameHost())
5205                 frameHost->chrome().client().needTouchEvents(true);
5206         }
5207     }
5208
5209     // When we're all done with all frames, ensure touch hit rects are marked as dirty.
5210     if (!handler->isDocumentNode() || handler == this) {
5211         if (Page* page = this->page()) {
5212             if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
5213                 scrollingCoordinator->touchEventTargetRectsDidChange();
5214         }
5215     }
5216 }
5217
5218 void Document::didRemoveTouchEventHandler(Node* handler, bool clearAll)
5219 {
5220     // Note that we can't assert that |handler| is in this document because it might be in
5221     // the process of moving out of it.
5222     ASSERT(clearAll || m_touchEventTargets->contains(handler));
5223     if (!m_touchEventTargets.get())
5224         return;
5225
5226     if (clearAll) {
5227         if (!m_touchEventTargets->contains(handler))
5228             return;
5229         m_touchEventTargets->removeAll(handler);
5230     } else {
5231         if (!m_touchEventTargets->remove(handler))
5232             // Just decremented refcount, no real update.
5233             return;
5234     }
5235
5236     if (m_touchEventTargets->isEmpty()) {
5237         if (Document* parent = parentDocument()) {
5238             // This was the last handler in this document, update the parent document too.
5239             parent->didRemoveTouchEventHandler(this, clearAll);
5240         } else {
5241             // We just removed the last touch handler on the whole page.
5242             if (FrameHost* frameHost = this->frameHost())
5243                 frameHost->chrome().client().needTouchEvents(false);
5244         }
5245     }
5246
5247     // When we're all done with all frames, ensure touch hit rects are marked as dirty.
5248     if (!handler->isDocumentNode() || handler == this) {
5249         if (Page* page = this->page()) {
5250             if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
5251                 scrollingCoordinator->touchEventTargetRectsDidChange();
5252         }
5253     }
5254 }
5255
5256 DocumentLoader* Document::loader() const
5257 {
5258     if (!m_frame)
5259         return 0;
5260
5261     DocumentLoader* loader = m_frame->loader().documentLoader();
5262     if (!loader)
5263         return 0;
5264
5265     if (m_frame->document() != this)
5266         return 0;
5267
5268     return loader;
5269 }
5270
5271 IntSize Document::initialViewportSize() const
5272 {
5273     if (!view())
5274         return IntSize();
5275     return view()->unscaledVisibleContentSize(IncludeScrollbars);
5276 }
5277
5278 Node* eventTargetNodeForDocument(Document* doc)
5279 {
5280     if (!doc)
5281         return 0;
5282     Node* node = doc->focusedElement();
5283     if (!node && doc->isPluginDocument()) {
5284         PluginDocument* pluginDocument = toPluginDocument(doc);
5285         node =  pluginDocument->pluginNode();
5286     }
5287     if (!node && doc->isHTMLDocument())
5288         node = doc->body();
5289     if (!node)
5290         node = doc->documentElement();
5291     return node;
5292 }
5293
5294 void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject& renderer)
5295 {
5296     if (!view())
5297         return;
5298
5299     LayoutRect visibleContentRect = view()->visibleContentRect();
5300     for (size_t i = 0; i < quads.size(); ++i) {
5301         quads[i].move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
5302         adjustFloatQuadForAbsoluteZoom(quads[i], renderer);
5303     }
5304 }
5305
5306 void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject& renderer)
5307 {
5308     if (!view())
5309         return;
5310
5311     LayoutRect visibleContentRect = view()->visibleContentRect();
5312     rect.move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
5313     adjustFloatRectForAbsoluteZoom(rect, renderer);
5314 }
5315
5316 bool Document::hasActiveParser()
5317 {
5318     return m_activeParserCount || (m_parser && m_parser->processingData());
5319 }
5320
5321 void Document::decrementActiveParserCount()
5322 {
5323     --m_activeParserCount;
5324     if (!frame())
5325         return;
5326     // FIXME: This should always be enabled, but it seems to cause
5327     // http/tests/security/feed-urls-from-remote.html to timeout on Mac WK1
5328     // see http://webkit.org/b/110554 and http://webkit.org/b/110401
5329     frame()->loader().checkLoadComplete();
5330 }
5331
5332 void Document::setContextFeatures(ContextFeatures& features)
5333 {
5334     m_contextFeatures = PassRefPtrWillBeRawPtr<ContextFeatures>(features);
5335 }
5336
5337 static RenderObject* nearestCommonHoverAncestor(RenderObject* obj1, RenderObject* obj2)
5338 {
5339     if (!obj1 || !obj2)
5340         return 0;
5341
5342     for (RenderObject* currObj1 = obj1; currObj1; currObj1 = currObj1->hoverAncestor()) {
5343         for (RenderObject* currObj2 = obj2; currObj2; currObj2 = currObj2->hoverAncestor()) {
5344             if (currObj1 == currObj2)
5345                 return currObj1;
5346         }
5347     }
5348
5349     return 0;
5350 }
5351
5352 void Document::updateHoverActiveState(const HitTestRequest& request, Element* innerElement, const PlatformMouseEvent* event)
5353 {
5354     ASSERT(!request.readOnly());
5355
5356     if (request.active() && m_frame)
5357         m_frame->eventHandler().notifyElementActivated();
5358
5359     Element* innerElementInDocument = innerElement;
5360     while (innerElementInDocument && innerElementInDocument->document() != this) {
5361         innerElementInDocument->document().updateHoverActiveState(request, innerElementInDocument, event);
5362         innerElementInDocument = innerElementInDocument->document().ownerElement();
5363     }
5364
5365     Element* oldActiveElement = activeHoverElement();
5366     if (oldActiveElement && !request.active()) {
5367         // We are clearing the :active chain because the mouse has been released.
5368         for (RenderObject* curr = oldActiveElement->renderer(); curr; curr = curr->parent()) {
5369             if (curr->node()) {
5370                 ASSERT(!curr->node()->isTextNode());
5371                 curr->node()->setActive(false);
5372                 m_userActionElements.setInActiveChain(curr->node(), false);
5373             }
5374         }
5375         setActiveHoverElement(nullptr);
5376     } else {
5377         Element* newActiveElement = innerElementInDocument;
5378         if (!oldActiveElement && newActiveElement && request.active() && !request.touchMove()) {
5379             // We are setting the :active chain and freezing it. If future moves happen, they
5380             // will need to reference this chain.
5381             for (RenderObject* curr = newActiveElement->renderer(); curr; curr = curr->parent()) {
5382                 if (curr->node() && !curr->isText())
5383                     m_userActionElements.setInActiveChain(curr->node(), true);
5384             }
5385
5386             setActiveHoverElement(newActiveElement);
5387         }
5388     }
5389     // If the mouse has just been pressed, set :active on the chain. Those (and only those)
5390     // nodes should remain :active until the mouse is released.
5391     bool allowActiveChanges = !oldActiveElement && activeHoverElement();
5392
5393     // If the mouse is down and if this is a mouse move event, we want to restrict changes in
5394     // :hover/:active to only apply to elements that are in the :active chain that we froze
5395     // at the time the mouse went down.
5396     bool mustBeInActiveChain = request.active() && request.move();
5397
5398     RefPtr<Node> oldHoverNode = hoverNode();
5399
5400     // Check to see if the hovered node has changed.
5401     // If it hasn't, we do not need to do anything.
5402     Node* newHoverNode = innerElementInDocument;
5403     while (newHoverNode && !newHoverNode->renderer())
5404         newHoverNode = newHoverNode->parentOrShadowHostNode();
5405
5406     // Update our current hover node.
5407     setHoverNode(newHoverNode);
5408
5409     // We have two different objects. Fetch their renderers.
5410     RenderObject* oldHoverObj = oldHoverNode ? oldHoverNode->renderer() : 0;
5411     RenderObject* newHoverObj = newHoverNode ? newHoverNode->renderer() : 0;
5412
5413     // Locate the common ancestor render object for the two renderers.
5414     RenderObject* ancestor = nearestCommonHoverAncestor(oldHoverObj, newHoverObj);
5415     RefPtr<Node> ancestorNode(ancestor ? ancestor->node() : 0);
5416
5417     Vector<RefPtr<Node>, 32> nodesToRemoveFromChain;
5418     Vector<RefPtr<Node>, 32> nodesToAddToChain;
5419
5420     if (oldHoverObj != newHoverObj) {
5421         // If the old hovered node is not nil but it's renderer is, it was probably detached as part of the :hover style
5422         // (for instance by setting display:none in the :hover pseudo-class). In this case, the old hovered element (and its ancestors)
5423         // must be updated, to ensure it's normal style is re-applied.
5424         if (oldHoverNode && !oldHoverObj) {
5425             for (Node* node = oldHoverNode.get(); node; node = node->parentNode()) {
5426                 if (!mustBeInActiveChain || (node->isElementNode() && toElement(node)->inActiveChain()))
5427                     nodesToRemoveFromChain.append(node);
5428             }
5429
5430         }
5431
5432         // The old hover path only needs to be cleared up to (and not including) the common ancestor;
5433         for (RenderObject* curr = oldHoverObj; curr && curr != ancestor; curr = curr->hoverAncestor()) {
5434             if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5435                 nodesToRemoveFromChain.append(curr->node());
5436         }
5437     }
5438
5439     // Now set the hover state for our new object up to the root.
5440     for (RenderObject* curr = newHoverObj; curr; curr = curr->hoverAncestor()) {
5441         if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5442             nodesToAddToChain.append(curr->node());
5443     }
5444
5445     // mouseenter and mouseleave events do not bubble, so they are dispatched iff there is a capturing
5446     // event handler on an ancestor or a normal event handler on the element itself. This special
5447     // handling is necessary to avoid O(n^2) capturing event handler checks. We'll check the previously
5448     // hovered node's ancestor tree for 'mouseleave' handlers here, then check the newly hovered node's
5449     // ancestor tree for 'mouseenter' handlers after dispatching the 'mouseleave' events (as the handler
5450     // for 'mouseleave' might set a capturing 'mouseenter' handler, odd as that might be).
5451     bool ancestorHasCapturingMouseleaveListener = false;
5452     if (event && newHoverNode != oldHoverNode.get()) {
5453         for (Node* node = oldHoverNode.get(); node; node = node->parentOrShadowHostNode()) {
5454             if (node->hasCapturingEventListeners(EventTypeNames::mouseleave)) {
5455                 ancestorHasCapturingMouseleaveListener = true;
5456                 break;
5457             }
5458         }
5459     }
5460
5461     size_t removeCount = nodesToRemoveFromChain.size();
5462     for (size_t i = 0; i < removeCount; ++i) {
5463         nodesToRemoveFromChain[i]->setHovered(false);
5464         if (event && (ancestorHasCapturingMouseleaveListener || nodesToRemoveFromChain[i]->hasEventListeners(EventTypeNames::mouseleave)))
5465             nodesToRemoveFromChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseleave, 0, newHoverNode);
5466     }
5467
5468     bool ancestorHasCapturingMouseenterListener = false;
5469     if (event && newHoverNode != oldHoverNode.get()) {
5470         for (Node* node = newHoverNode; node; node = node->parentOrShadowHostNode()) {
5471             if (node->hasCapturingEventListeners(EventTypeNames::mouseenter)) {
5472                 ancestorHasCapturingMouseenterListener = true;
5473                 break;
5474             }
5475         }
5476     }
5477
5478     bool sawCommonAncestor = false;
5479     size_t addCount = nodesToAddToChain.size();
5480     for (size_t i = 0; i < addCount; ++i) {
5481         // Elements past the common ancestor do not change hover state, but might change active state.
5482         if (ancestorNode && nodesToAddToChain[i] == ancestorNode)
5483             sawCommonAncestor = true;
5484         if (allowActiveChanges)
5485             nodesToAddToChain[i]->setActive(true);
5486         if (!sawCommonAncestor) {
5487             nodesToAddToChain[i]->setHovered(true);
5488             if (event && (ancestorHasCapturingMouseenterListener || nodesToAddToChain[i]->hasEventListeners(EventTypeNames::mouseenter)))
5489                 nodesToAddToChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseenter, 0, oldHoverNode.get());
5490         }
5491     }
5492 }
5493
5494 bool Document::haveStylesheetsLoaded() const
5495 {
5496     return m_styleEngine->haveStylesheetsLoaded();
5497 }
5498
5499 Locale& Document::getCachedLocale(const AtomicString& locale)
5500 {
5501     AtomicString localeKey = locale;
5502     if (locale.isEmpty() || !RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
5503         return Locale::defaultLocale();
5504     LocaleIdentifierToLocaleMap::AddResult result = m_localeCache.add(localeKey, nullptr);
5505     if (result.isNewEntry)
5506         result.storedValue->value = Locale::create(localeKey);
5507     return *(result.storedValue->value);
5508 }
5509
5510 Document& Document::ensureTemplateDocument()
5511 {
5512     if (isTemplateDocument())
5513         return *this;
5514
5515     if (m_templateDocument)
5516         return *m_templateDocument;
5517
5518     if (isHTMLDocument()) {
5519         DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL()).withNewRegistrationContext();
5520         m_templateDocument = HTMLDocument::create(init);
5521     } else {
5522         m_templateDocument = Document::create(DocumentInit(blankURL()));
5523     }
5524
5525     m_templateDocument->m_templateDocumentHost = this; // balanced in dtor.
5526
5527     return *m_templateDocument.get();
5528 }
5529
5530 void Document::didAssociateFormControl(Element* element)
5531 {
5532     if (!frame() || !frame()->page())
5533         return;
5534     m_associatedFormControls.add(element);
5535     if (!m_didAssociateFormControlsTimer.isActive())
5536         m_didAssociateFormControlsTimer.startOneShot(0, FROM_HERE);
5537 }
5538
5539 void Document::didAssociateFormControlsTimerFired(Timer<Document>* timer)
5540 {
5541     ASSERT_UNUSED(timer, timer == &m_didAssociateFormControlsTimer);
5542     if (!frame() || !frame()->page())
5543         return;
5544
5545     Vector<RefPtr<Element> > associatedFormControls;
5546     copyToVector(m_associatedFormControls, associatedFormControls);
5547
5548     frame()->page()->chrome().client().didAssociateFormControls(associatedFormControls);
5549     m_associatedFormControls.clear();
5550 }
5551
5552 float Document::devicePixelRatio() const
5553 {
5554     return m_frame ? m_frame->devicePixelRatio() : 1.0;
5555 }
5556
5557 PassOwnPtr<LifecycleNotifier<Document> > Document::createLifecycleNotifier()
5558 {
5559     return DocumentLifecycleNotifier::create(this);
5560 }
5561
5562 DocumentLifecycleNotifier& Document::lifecycleNotifier()
5563 {
5564     return static_cast<DocumentLifecycleNotifier&>(LifecycleContext<Document>::lifecycleNotifier());
5565 }
5566
5567 void Document::removedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
5568 {
5569     // If we're in document teardown, then we don't need this notification of our sheet's removal.
5570     // styleResolverChanged() is needed even when the document is inactive so that
5571     // imported docuements (which is inactive) notifies the change to the master document.
5572     if (isActive())
5573         styleEngine()->modifiedStyleSheet(sheet);
5574     styleResolverChanged(when, updateMode);
5575 }
5576
5577 void Document::modifiedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
5578 {
5579     // If we're in document teardown, then we don't need this notification of our sheet's removal.
5580     // styleResolverChanged() is needed even when the document is inactive so that
5581     // imported docuements (which is inactive) notifies the change to the master document.
5582     if (isActive())
5583         styleEngine()->modifiedStyleSheet(sheet);
5584     styleResolverChanged(when, updateMode);
5585 }
5586
5587 TextAutosizer* Document::textAutosizer()
5588 {
5589     if (!m_textAutosizer && !RuntimeEnabledFeatures::fastTextAutosizingEnabled())
5590         m_textAutosizer = TextAutosizer::create(this);
5591     return m_textAutosizer.get();
5592 }
5593
5594 FastTextAutosizer* Document::fastTextAutosizer()
5595 {
5596     if (!m_fastTextAutosizer && RuntimeEnabledFeatures::fastTextAutosizingEnabled())
5597         m_fastTextAutosizer = FastTextAutosizer::create(this);
5598     return m_fastTextAutosizer.get();
5599 }
5600
5601 void Document::setAutofocusElement(Element* element)
5602 {
5603     if (!element) {
5604         m_autofocusElement = nullptr;
5605         return;
5606     }
5607     if (m_hasAutofocused)
5608         return;
5609     m_hasAutofocused = true;
5610     ASSERT(!m_autofocusElement);
5611     m_autofocusElement = element;
5612     m_taskRunner->postTask(AutofocusTask::create());
5613 }
5614
5615 Element* Document::activeElement() const
5616 {
5617     if (Element* element = treeScope().adjustedFocusedElement())
5618         return element;
5619     return body();
5620 }
5621
5622 bool Document::hasFocus() const
5623 {
5624     Page* page = this->page();
5625     if (!page)
5626         return false;
5627     if (!page->focusController().isActive() || !page->focusController().isFocused())
5628         return false;
5629     Frame* focusedFrame = page->focusController().focusedFrame();
5630     if (focusedFrame && focusedFrame->isLocalFrame()) {
5631         if (toLocalFrame(focusedFrame)->tree().isDescendantOf(frame()))
5632             return true;
5633     }
5634     return false;
5635 }
5636
5637 template<unsigned type>
5638 bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
5639 {
5640     if (nodeListCounts[type] && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
5641         return true;
5642     return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
5643 }
5644
5645 template<>
5646 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
5647 {
5648     return false;
5649 }
5650
5651 bool Document::shouldInvalidateNodeListCaches(const QualifiedName* attrName) const
5652 {
5653     if (attrName)
5654         return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListCounts, *attrName);
5655
5656     for (int type = 0; type < numNodeListInvalidationTypes; type++) {
5657         if (m_nodeListCounts[type])
5658             return true;
5659     }
5660
5661     return false;
5662 }
5663
5664 void Document::invalidateNodeListCaches(const QualifiedName* attrName)
5665 {
5666     HashSet<LiveNodeListBase*>::iterator end = m_listsInvalidatedAtDocument.end();
5667     for (HashSet<LiveNodeListBase*>::iterator it = m_listsInvalidatedAtDocument.begin(); it != end; ++it)
5668         (*it)->invalidateCacheForAttribute(attrName);
5669 }
5670
5671 void Document::clearWeakMembers(Visitor* visitor)
5672 {
5673     if (m_axObjectCache)
5674         m_axObjectCache->clearWeakMembers(visitor);
5675
5676     if (m_markers)
5677         m_markers->clearWeakMembers(visitor);
5678
5679     // FIXME: Oilpan: Use a weak counted set instead.
5680     if (m_touchEventTargets) {
5681         Vector<Node*> deadNodes;
5682         for (TouchEventTargetSet::iterator it = m_touchEventTargets->begin(); it != m_touchEventTargets->end(); ++it) {
5683             if (!visitor->isAlive(it->key))
5684                 deadNodes.append(it->key);
5685         }
5686         for (unsigned i = 0; i < deadNodes.size(); ++i)
5687             didClearTouchEventHandlers(deadNodes[i]);
5688     }
5689 }
5690
5691 void Document::trace(Visitor* visitor)
5692 {
5693     visitor->trace(m_docType);
5694     visitor->trace(m_implementation);
5695     visitor->trace(m_autofocusElement);
5696     visitor->trace(m_focusedElement);
5697     visitor->trace(m_hoverNode);
5698     visitor->trace(m_activeHoverElement);
5699     visitor->trace(m_documentElement);
5700     visitor->trace(m_titleElement);
5701     visitor->trace(m_currentScriptStack);
5702     visitor->trace(m_transformSourceDocument);
5703     visitor->trace(m_cssCanvasElements);
5704     visitor->trace(m_topLayerElements);
5705     visitor->trace(m_elemSheet);
5706     visitor->trace(m_styleEngine);
5707     visitor->trace(m_formController);
5708     visitor->trace(m_fetcher);
5709     visitor->trace(m_contextFeatures);
5710     visitor->trace(m_styleSheetList);
5711     visitor->trace(m_mediaQueryMatcher);
5712     visitor->trace(m_associatedFormControls);
5713     visitor->trace(m_templateDocument);
5714     visitor->trace(m_templateDocumentHost);
5715     visitor->trace(m_visibilityObservers);
5716     visitor->trace(m_userActionElements);
5717     visitor->registerWeakMembers<Document, &Document::clearWeakMembers>(this);
5718     DocumentSupplementable::trace(visitor);
5719     TreeScope::trace(visitor);
5720     ContainerNode::trace(visitor);
5721     ExecutionContext::trace(visitor);
5722 }
5723
5724 } // namespace WebCore