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