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