Upstream version 9.37.197.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / dom / Document.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2001 Dirk Mueller (mueller@kde.org)
5  *           (C) 2006 Alexey Proskuryakov (ap@webkit.org)
6  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2011, 2012 Apple Inc. All rights reserved.
7  * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8  * Copyright (C) 2008, 2009, 2011, 2012 Google Inc. All rights reserved.
9  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
10  * Copyright (C) Research In Motion Limited 2010-2011. All rights reserved.
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Library General Public
14  * License as published by the Free Software Foundation; either
15  * version 2 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public License
23  * along with this library; see the file COPYING.LIB.  If not, write to
24  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25  * Boston, MA 02110-1301, USA.
26  */
27
28 #include "config.h"
29 #include "core/dom/Document.h"
30
31 #include "bindings/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
3466         ASSERT(renderView() || importsController());
3467         if (renderView())
3468             renderView()->repaintViewAndCompositedLayers();
3469     }
3470 }
3471
3472 void Document::styleResolverMayHaveChanged()
3473 {
3474     styleResolverChanged(hasNodesWithPlaceholderStyle() ? FullStyleUpdate : AnalyzedStyleUpdate);
3475 }
3476
3477 void Document::setHoverNode(PassRefPtrWillBeRawPtr<Node> newHoverNode)
3478 {
3479     m_hoverNode = newHoverNode;
3480 }
3481
3482 void Document::setActiveHoverElement(PassRefPtrWillBeRawPtr<Element> newActiveElement)
3483 {
3484     if (!newActiveElement) {
3485         m_activeHoverElement.clear();
3486         return;
3487     }
3488
3489     m_activeHoverElement = newActiveElement;
3490 }
3491
3492 void Document::removeFocusedElementOfSubtree(Node* node, bool amongChildrenOnly)
3493 {
3494     if (!m_focusedElement)
3495         return;
3496
3497     // We can't be focused if we're not in the document.
3498     if (!node->inDocument())
3499         return;
3500     bool contains = node->containsIncludingShadowDOM(m_focusedElement.get());
3501     if (contains && (m_focusedElement != node || !amongChildrenOnly))
3502         setFocusedElement(nullptr);
3503 }
3504
3505 void Document::hoveredNodeDetached(Node* node)
3506 {
3507     if (!m_hoverNode)
3508         return;
3509
3510     if (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != NodeRenderingTraversal::parent(m_hoverNode.get())))
3511         return;
3512
3513     m_hoverNode = NodeRenderingTraversal::parent(node);
3514     while (m_hoverNode && !m_hoverNode->renderer())
3515         m_hoverNode = NodeRenderingTraversal::parent(m_hoverNode.get());
3516
3517     // If the mouse cursor is not visible, do not clear existing
3518     // hover effects on the ancestors of |node| and do not invoke
3519     // new hover effects on any other element.
3520     if (!page()->isCursorVisible())
3521         return;
3522
3523     if (frame())
3524         frame()->eventHandler().scheduleHoverStateUpdate();
3525 }
3526
3527 void Document::activeChainNodeDetached(Node* node)
3528 {
3529     if (!m_activeHoverElement)
3530         return;
3531
3532     if (node != m_activeHoverElement && (!m_activeHoverElement->isTextNode() || node != NodeRenderingTraversal::parent(m_activeHoverElement.get())))
3533         return;
3534
3535     Node* activeNode = NodeRenderingTraversal::parent(node);
3536     while (activeNode && activeNode->isElementNode() && !activeNode->renderer())
3537         activeNode = NodeRenderingTraversal::parent(activeNode);
3538
3539     m_activeHoverElement = activeNode && activeNode->isElementNode() ? toElement(activeNode) : 0;
3540 }
3541
3542 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3543 {
3544     return m_annotatedRegions;
3545 }
3546
3547 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3548 {
3549     m_annotatedRegions = regions;
3550     setAnnotatedRegionsDirty(false);
3551 }
3552
3553 bool Document::setFocusedElement(PassRefPtrWillBeRawPtr<Element> prpNewFocusedElement, FocusType type)
3554 {
3555     m_clearFocusedElementTimer.stop();
3556
3557     RefPtrWillBeRawPtr<Element> newFocusedElement = prpNewFocusedElement;
3558
3559     // Make sure newFocusedNode is actually in this document
3560     if (newFocusedElement && (newFocusedElement->document() != this))
3561         return true;
3562
3563     if (NodeChildRemovalTracker::isBeingRemoved(newFocusedElement.get()))
3564         return true;
3565
3566     if (m_focusedElement == newFocusedElement)
3567         return true;
3568
3569     bool focusChangeBlocked = false;
3570     RefPtrWillBeRawPtr<Element> oldFocusedElement = m_focusedElement;
3571     m_focusedElement = nullptr;
3572
3573     // Remove focus from the existing focus node (if any)
3574     if (oldFocusedElement) {
3575         ASSERT(!oldFocusedElement->inDetach());
3576
3577         if (oldFocusedElement->active())
3578             oldFocusedElement->setActive(false);
3579
3580         oldFocusedElement->setFocus(false);
3581
3582         // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3583         // If page lost focus, blur event will have already been dispatched
3584         if (page() && (page()->focusController().isFocused())) {
3585             oldFocusedElement->dispatchBlurEvent(newFocusedElement.get());
3586
3587             if (m_focusedElement) {
3588                 // handler shifted focus
3589                 focusChangeBlocked = true;
3590                 newFocusedElement = nullptr;
3591             }
3592
3593             oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::focusout, newFocusedElement.get()); // DOM level 3 name for the bubbling blur event.
3594             // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3595             // on it, probably when <rdar://problem/8503958> is resolved.
3596             oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, newFocusedElement.get()); // DOM level 2 name for compatibility.
3597
3598             if (m_focusedElement) {
3599                 // handler shifted focus
3600                 focusChangeBlocked = true;
3601                 newFocusedElement = nullptr;
3602             }
3603         }
3604
3605         if (view()) {
3606             Widget* oldWidget = widgetForElement(*oldFocusedElement);
3607             if (oldWidget)
3608                 oldWidget->setFocus(false);
3609             else
3610                 view()->setFocus(false);
3611         }
3612     }
3613
3614     if (newFocusedElement && newFocusedElement->isFocusable()) {
3615         if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(*newFocusedElement)) {
3616             // delegate blocks focus change
3617             focusChangeBlocked = true;
3618             goto SetFocusedElementDone;
3619         }
3620         // Set focus on the new node
3621         m_focusedElement = newFocusedElement;
3622
3623         // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3624         // If page lost focus, event will be dispatched on page focus, don't duplicate
3625         if (page() && (page()->focusController().isFocused())) {
3626             m_focusedElement->dispatchFocusEvent(oldFocusedElement.get(), type);
3627
3628
3629             if (m_focusedElement != newFocusedElement) {
3630                 // handler shifted focus
3631                 focusChangeBlocked = true;
3632                 goto SetFocusedElementDone;
3633             }
3634
3635             m_focusedElement->dispatchFocusInEvent(EventTypeNames::focusin, oldFocusedElement.get()); // DOM level 3 bubbling focus event.
3636
3637             if (m_focusedElement != newFocusedElement) {
3638                 // handler shifted focus
3639                 focusChangeBlocked = true;
3640                 goto SetFocusedElementDone;
3641             }
3642
3643             // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3644             // on it, probably when <rdar://problem/8503958> is m.
3645             m_focusedElement->dispatchFocusInEvent(EventTypeNames::DOMFocusIn, oldFocusedElement.get()); // DOM level 2 for compatibility.
3646
3647             if (m_focusedElement != newFocusedElement) {
3648                 // handler shifted focus
3649                 focusChangeBlocked = true;
3650                 goto SetFocusedElementDone;
3651             }
3652         }
3653
3654         m_focusedElement->setFocus(true);
3655
3656         if (m_focusedElement->isRootEditableElement())
3657             frame()->spellChecker().didBeginEditing(m_focusedElement.get());
3658
3659         // eww, I suck. set the qt focus correctly
3660         // ### find a better place in the code for this
3661         if (view()) {
3662             Widget* focusWidget = widgetForElement(*m_focusedElement);
3663             if (focusWidget) {
3664                 // Make sure a widget has the right size before giving it focus.
3665                 // Otherwise, we are testing edge cases of the Widget code.
3666                 // Specifically, in WebCore this does not work well for text fields.
3667                 updateLayout();
3668                 // Re-get the widget in case updating the layout changed things.
3669                 focusWidget = widgetForElement(*m_focusedElement);
3670             }
3671             if (focusWidget)
3672                 focusWidget->setFocus(true);
3673             else
3674                 view()->setFocus(true);
3675         }
3676     }
3677
3678     if (!focusChangeBlocked && m_focusedElement) {
3679         // Create the AXObject cache in a focus change because Chromium relies on it.
3680         if (AXObjectCache* cache = axObjectCache())
3681             cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
3682     }
3683
3684     if (!focusChangeBlocked && frameHost())
3685         frameHost()->chrome().focusedNodeChanged(m_focusedElement.get());
3686
3687 SetFocusedElementDone:
3688     updateRenderTreeIfNeeded();
3689     if (LocalFrame* frame = this->frame())
3690         frame->selection().didChangeFocus();
3691     return !focusChangeBlocked;
3692 }
3693
3694 void Document::setCSSTarget(Element* newTarget)
3695 {
3696     if (m_cssTarget)
3697         m_cssTarget->didAffectSelector(AffectedSelectorTarget);
3698     m_cssTarget = newTarget;
3699     if (m_cssTarget)
3700         m_cssTarget->didAffectSelector(AffectedSelectorTarget);
3701 }
3702
3703 void Document::registerNodeList(const LiveNodeListBase* list)
3704 {
3705 #if ENABLE(OILPAN)
3706     m_nodeLists[list->invalidationType()].add(list);
3707 #else
3708     m_nodeListCounts[list->invalidationType()]++;
3709 #endif
3710     if (list->isRootedAtDocument())
3711         m_listsInvalidatedAtDocument.add(list);
3712 }
3713
3714 void Document::unregisterNodeList(const LiveNodeListBase* list)
3715 {
3716 #if ENABLE(OILPAN)
3717     ASSERT(m_nodeLists[list->invalidationType()].contains(list));
3718     m_nodeLists[list->invalidationType()].remove(list);
3719 #else
3720     m_nodeListCounts[list->invalidationType()]--;
3721 #endif
3722     if (list->isRootedAtDocument()) {
3723         ASSERT(m_listsInvalidatedAtDocument.contains(list));
3724         m_listsInvalidatedAtDocument.remove(list);
3725     }
3726 }
3727
3728 void Document::registerNodeListWithIdNameCache(const LiveNodeListBase* list)
3729 {
3730 #if ENABLE(OILPAN)
3731     m_nodeLists[InvalidateOnIdNameAttrChange].add(list);
3732 #else
3733     m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
3734 #endif
3735 }
3736
3737 void Document::unregisterNodeListWithIdNameCache(const LiveNodeListBase* list)
3738 {
3739 #if ENABLE(OILPAN)
3740     ASSERT(m_nodeLists[InvalidateOnIdNameAttrChange].contains(list));
3741     m_nodeLists[InvalidateOnIdNameAttrChange].remove(list);
3742 #else
3743     ASSERT(m_nodeListCounts[InvalidateOnIdNameAttrChange] > 0);
3744     m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
3745 #endif
3746 }
3747
3748 void Document::attachNodeIterator(NodeIterator* ni)
3749 {
3750     m_nodeIterators.add(ni);
3751 }
3752
3753 void Document::detachNodeIterator(NodeIterator* ni)
3754 {
3755     // The node iterator can be detached without having been attached if its root node didn't have a document
3756     // when the iterator was created, but has it now.
3757     m_nodeIterators.remove(ni);
3758 }
3759
3760 void Document::moveNodeIteratorsToNewDocument(Node& node, Document& newDocument)
3761 {
3762     WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> > nodeIteratorsList = m_nodeIterators;
3763     WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3764     for (WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3765         if ((*it)->root() == node) {
3766             detachNodeIterator(*it);
3767             newDocument.attachNodeIterator(*it);
3768         }
3769     }
3770 }
3771
3772 void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
3773 {
3774     if (!m_ranges.isEmpty()) {
3775         AttachedRangeSet::const_iterator end = m_ranges.end();
3776         for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3777             (*it)->nodeChildrenChanged(container);
3778     }
3779 }
3780
3781 void Document::updateRangesAfterNodeMovedToAnotherDocument(const Node& node)
3782 {
3783     ASSERT(node.document() != this);
3784     if (m_ranges.isEmpty())
3785         return;
3786     AttachedRangeSet ranges = m_ranges;
3787     AttachedRangeSet::const_iterator end = ranges.end();
3788     for (AttachedRangeSet::const_iterator it = ranges.begin(); it != end; ++it)
3789         (*it)->updateOwnerDocumentIfNeeded();
3790 }
3791
3792 void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
3793 {
3794     NoEventDispatchAssertion assertNoEventDispatch;
3795     if (!m_ranges.isEmpty()) {
3796         AttachedRangeSet::const_iterator end = m_ranges.end();
3797         for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3798             (*it)->nodeChildrenWillBeRemoved(container);
3799     }
3800
3801     WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3802     for (WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
3803         for (Node* n = container.firstChild(); n; n = n->nextSibling())
3804             (*it)->nodeWillBeRemoved(*n);
3805     }
3806
3807     if (LocalFrame* frame = this->frame()) {
3808         for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
3809             frame->eventHandler().nodeWillBeRemoved(*n);
3810             frame->selection().nodeWillBeRemoved(*n);
3811             frame->page()->dragCaretController().nodeWillBeRemoved(*n);
3812         }
3813     }
3814 }
3815
3816 void Document::nodeWillBeRemoved(Node& n)
3817 {
3818     WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3819     for (WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> >::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3820         (*it)->nodeWillBeRemoved(n);
3821
3822     if (!m_ranges.isEmpty()) {
3823         AttachedRangeSet::const_iterator rangesEnd = m_ranges.end();
3824         for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3825             (*it)->nodeWillBeRemoved(n);
3826     }
3827
3828     if (LocalFrame* frame = this->frame()) {
3829         frame->eventHandler().nodeWillBeRemoved(n);
3830         frame->selection().nodeWillBeRemoved(n);
3831         frame->page()->dragCaretController().nodeWillBeRemoved(n);
3832     }
3833 }
3834
3835 void Document::didInsertText(Node* text, unsigned offset, unsigned length)
3836 {
3837     if (!m_ranges.isEmpty()) {
3838         AttachedRangeSet::const_iterator end = m_ranges.end();
3839         for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3840             (*it)->didInsertText(text, offset, length);
3841     }
3842
3843     // Update the markers for spelling and grammar checking.
3844     m_markers->shiftMarkers(text, offset, length);
3845 }
3846
3847 void Document::didRemoveText(Node* text, unsigned offset, unsigned length)
3848 {
3849     if (!m_ranges.isEmpty()) {
3850         AttachedRangeSet::const_iterator end = m_ranges.end();
3851         for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3852             (*it)->didRemoveText(text, offset, length);
3853     }
3854
3855     // Update the markers for spelling and grammar checking.
3856     m_markers->removeMarkers(text, offset, length);
3857     m_markers->shiftMarkers(text, offset + length, 0 - length);
3858 }
3859
3860 void Document::didMergeTextNodes(Text& oldNode, unsigned offset)
3861 {
3862     if (!m_ranges.isEmpty()) {
3863         NodeWithIndex oldNodeWithIndex(oldNode);
3864         AttachedRangeSet::const_iterator end = m_ranges.end();
3865         for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3866             (*it)->didMergeTextNodes(oldNodeWithIndex, offset);
3867     }
3868
3869     if (m_frame)
3870         m_frame->selection().didMergeTextNodes(oldNode, offset);
3871
3872     // FIXME: This should update markers for spelling and grammar checking.
3873 }
3874
3875 void Document::didSplitTextNode(Text& oldNode)
3876 {
3877     if (!m_ranges.isEmpty()) {
3878         AttachedRangeSet::const_iterator end = m_ranges.end();
3879         for (AttachedRangeSet::const_iterator it = m_ranges.begin(); it != end; ++it)
3880             (*it)->didSplitTextNode(oldNode);
3881     }
3882
3883     if (m_frame)
3884         m_frame->selection().didSplitTextNode(oldNode);
3885
3886     // FIXME: This should update markers for spelling and grammar checking.
3887 }
3888
3889 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3890 {
3891     LocalDOMWindow* domWindow = this->domWindow();
3892     if (!domWindow)
3893         return;
3894     domWindow->setAttributeEventListener(eventType, listener);
3895 }
3896
3897 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3898 {
3899     LocalDOMWindow* domWindow = this->domWindow();
3900     if (!domWindow)
3901         return 0;
3902     return domWindow->getAttributeEventListener(eventType);
3903 }
3904
3905 EventQueue* Document::eventQueue() const
3906 {
3907     if (!m_domWindow)
3908         return 0;
3909     return m_domWindow->eventQueue();
3910 }
3911
3912 void Document::enqueueAnimationFrameEvent(PassRefPtrWillBeRawPtr<Event> event)
3913 {
3914     ensureScriptedAnimationController().enqueueEvent(event);
3915 }
3916
3917 void Document::enqueueScrollEventForNode(Node* target)
3918 {
3919     // Per the W3C CSSOM View Module only scroll events fired at the document should bubble.
3920     RefPtrWillBeRawPtr<Event> scrollEvent = target->isDocumentNode() ? Event::createBubble(EventTypeNames::scroll) : Event::create(EventTypeNames::scroll);
3921     scrollEvent->setTarget(target);
3922     ensureScriptedAnimationController().enqueuePerFrameEvent(scrollEvent.release());
3923 }
3924
3925 void Document::enqueueResizeEvent()
3926 {
3927     RefPtrWillBeRawPtr<Event> event = Event::create(EventTypeNames::resize);
3928     event->setTarget(domWindow());
3929     ensureScriptedAnimationController().enqueuePerFrameEvent(event.release());
3930 }
3931
3932 Document::EventFactorySet& Document::eventFactories()
3933 {
3934     DEFINE_STATIC_LOCAL(EventFactorySet, s_eventFactory, ());
3935     return s_eventFactory;
3936 }
3937
3938 void Document::registerEventFactory(PassOwnPtr<EventFactoryBase> eventFactory)
3939 {
3940     ASSERT(!eventFactories().contains(eventFactory.get()));
3941     eventFactories().add(eventFactory);
3942 }
3943
3944 PassRefPtrWillBeRawPtr<Event> Document::createEvent(const String& eventType, ExceptionState& exceptionState)
3945 {
3946     RefPtrWillBeRawPtr<Event> event = nullptr;
3947     for (EventFactorySet::const_iterator it = eventFactories().begin(); it != eventFactories().end(); ++it) {
3948         event = (*it)->create(eventType);
3949         if (event)
3950             return event.release();
3951     }
3952     exceptionState.throwDOMException(NotSupportedError, "The provided event type ('" + eventType + "') is invalid.");
3953     return nullptr;
3954 }
3955
3956 void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
3957 {
3958     if (ContextFeatures::mutationEventsEnabled(this))
3959         addListenerType(listenerType);
3960 }
3961
3962 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
3963 {
3964     if (eventType == EventTypeNames::DOMSubtreeModified) {
3965         UseCounter::count(*this, UseCounter::DOMSubtreeModifiedEvent);
3966         addMutationEventListenerTypeIfEnabled(DOMSUBTREEMODIFIED_LISTENER);
3967     } else if (eventType == EventTypeNames::DOMNodeInserted) {
3968         UseCounter::count(*this, UseCounter::DOMNodeInsertedEvent);
3969         addMutationEventListenerTypeIfEnabled(DOMNODEINSERTED_LISTENER);
3970     } else if (eventType == EventTypeNames::DOMNodeRemoved) {
3971         UseCounter::count(*this, UseCounter::DOMNodeRemovedEvent);
3972         addMutationEventListenerTypeIfEnabled(DOMNODEREMOVED_LISTENER);
3973     } else if (eventType == EventTypeNames::DOMNodeRemovedFromDocument) {
3974         UseCounter::count(*this, UseCounter::DOMNodeRemovedFromDocumentEvent);
3975         addMutationEventListenerTypeIfEnabled(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
3976     } else if (eventType == EventTypeNames::DOMNodeInsertedIntoDocument) {
3977         UseCounter::count(*this, UseCounter::DOMNodeInsertedIntoDocumentEvent);
3978         addMutationEventListenerTypeIfEnabled(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
3979     } else if (eventType == EventTypeNames::DOMCharacterDataModified) {
3980         UseCounter::count(*this, UseCounter::DOMCharacterDataModifiedEvent);
3981         addMutationEventListenerTypeIfEnabled(DOMCHARACTERDATAMODIFIED_LISTENER);
3982     } else if (eventType == EventTypeNames::overflowchanged) {
3983         UseCounter::countDeprecation(*this, UseCounter::OverflowChangedEvent);
3984         addListenerType(OVERFLOWCHANGED_LISTENER);
3985     } else if (eventType == EventTypeNames::webkitAnimationStart || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationstart)) {
3986         addListenerType(ANIMATIONSTART_LISTENER);
3987     } else if (eventType == EventTypeNames::webkitAnimationEnd || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationend)) {
3988         addListenerType(ANIMATIONEND_LISTENER);
3989     } else if (eventType == EventTypeNames::webkitAnimationIteration || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationiteration)) {
3990         addListenerType(ANIMATIONITERATION_LISTENER);
3991     } else if (eventType == EventTypeNames::webkitTransitionEnd || eventType == EventTypeNames::transitionend) {
3992         addListenerType(TRANSITIONEND_LISTENER);
3993     } else if (eventType == EventTypeNames::scroll) {
3994         addListenerType(SCROLL_LISTENER);
3995     }
3996 }
3997
3998 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
3999 {
4000     return 0;
4001 }
4002
4003 HTMLFrameOwnerElement* Document::ownerElement() const
4004 {
4005     if (!frame())
4006         return 0;
4007     // FIXME: This probably breaks the attempts to layout after a load is finished in implicitClose(), and probably tons of other things...
4008     return frame()->deprecatedLocalOwner();
4009 }
4010
4011 String Document::cookie(ExceptionState& exceptionState) const
4012 {
4013     if (settings() && !settings()->cookieEnabled())
4014         return String();
4015
4016     // FIXME: The HTML5 DOM spec states that this attribute can raise an
4017     // InvalidStateError exception on getting if the Document has no
4018     // browsing context.
4019
4020     if (!securityOrigin()->canAccessCookies()) {
4021         if (isSandboxed(SandboxOrigin))
4022             exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
4023         else if (url().protocolIs("data"))
4024             exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
4025         else
4026             exceptionState.throwSecurityError("Access is denied for this document.");
4027         return String();
4028     }
4029
4030     KURL cookieURL = this->cookieURL();
4031     if (cookieURL.isEmpty())
4032         return String();
4033
4034     return cookies(this, cookieURL);
4035 }
4036
4037 void Document::setCookie(const String& value, ExceptionState& exceptionState)
4038 {
4039     if (settings() && !settings()->cookieEnabled())
4040         return;
4041
4042     // FIXME: The HTML5 DOM spec states that this attribute can raise an
4043     // InvalidStateError exception on setting if the Document has no
4044     // browsing context.
4045
4046     if (!securityOrigin()->canAccessCookies()) {
4047         if (isSandboxed(SandboxOrigin))
4048             exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
4049         else if (url().protocolIs("data"))
4050             exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
4051         else
4052             exceptionState.throwSecurityError("Access is denied for this document.");
4053         return;
4054     }
4055
4056     KURL cookieURL = this->cookieURL();
4057     if (cookieURL.isEmpty())
4058         return;
4059
4060     setCookies(this, cookieURL, value);
4061 }
4062
4063 const AtomicString& Document::referrer() const
4064 {
4065     if (loader())
4066         return loader()->request().httpReferrer();
4067     return nullAtom;
4068 }
4069
4070 String Document::domain() const
4071 {
4072     return securityOrigin()->domain();
4073 }
4074
4075 void Document::setDomain(const String& newDomain, ExceptionState& exceptionState)
4076 {
4077     if (isSandboxed(SandboxDocumentDomain)) {
4078         exceptionState.throwSecurityError("Assignment is forbidden for sandboxed iframes.");
4079         return;
4080     }
4081
4082     if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
4083         exceptionState.throwSecurityError("Assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme.");
4084         return;
4085     }
4086
4087     if (newDomain.isEmpty()) {
4088         exceptionState.throwSecurityError("'" + newDomain + "' is an empty domain.");
4089         return;
4090     }
4091
4092     OriginAccessEntry::IPAddressSetting ipAddressSetting = settings() && settings()->treatIPAddressAsDomain() ? OriginAccessEntry::TreatIPAddressAsDomain : OriginAccessEntry::TreatIPAddressAsIPAddress;
4093     OriginAccessEntry accessEntry(securityOrigin()->protocol(), newDomain, OriginAccessEntry::AllowSubdomains, ipAddressSetting);
4094     OriginAccessEntry::MatchResult result = accessEntry.matchesOrigin(*securityOrigin());
4095     if (result == OriginAccessEntry::DoesNotMatchOrigin) {
4096         exceptionState.throwSecurityError("'" + newDomain + "' is not a suffix of '" + domain() + "'.");
4097         return;
4098     }
4099
4100     if (result == OriginAccessEntry::MatchesOriginButIsPublicSuffix) {
4101         exceptionState.throwSecurityError("'" + newDomain + "' is a top-level domain.");
4102         return;
4103     }
4104
4105     securityOrigin()->setDomainFromDOM(newDomain);
4106     if (m_frame)
4107         m_frame->script().updateSecurityOrigin(securityOrigin());
4108 }
4109
4110 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
4111 String Document::lastModified() const
4112 {
4113     DateComponents date;
4114     bool foundDate = false;
4115     if (m_frame) {
4116         if (DocumentLoader* documentLoader = loader()) {
4117             const AtomicString& httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
4118             if (!httpLastModified.isEmpty()) {
4119                 date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
4120                 foundDate = true;
4121             }
4122         }
4123     }
4124     // FIXME: If this document came from the file system, the HTML5
4125     // specificiation tells us to read the last modification date from the file
4126     // system.
4127     if (!foundDate)
4128         date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
4129     return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
4130 }
4131
4132 const KURL& Document::firstPartyForCookies() const
4133 {
4134     return topDocument().url();
4135 }
4136
4137 static bool isValidNameNonASCII(const LChar* characters, unsigned length)
4138 {
4139     if (!isValidNameStart(characters[0]))
4140         return false;
4141
4142     for (unsigned i = 1; i < length; ++i) {
4143         if (!isValidNamePart(characters[i]))
4144             return false;
4145     }
4146
4147     return true;
4148 }
4149
4150 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
4151 {
4152     unsigned i = 0;
4153
4154     UChar32 c;
4155     U16_NEXT(characters, i, length, c)
4156     if (!isValidNameStart(c))
4157         return false;
4158
4159     while (i < length) {
4160         U16_NEXT(characters, i, length, c)
4161         if (!isValidNamePart(c))
4162             return false;
4163     }
4164
4165     return true;
4166 }
4167
4168 template<typename CharType>
4169 static inline bool isValidNameASCII(const CharType* characters, unsigned length)
4170 {
4171     CharType c = characters[0];
4172     if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
4173         return false;
4174
4175     for (unsigned i = 1; i < length; ++i) {
4176         c = characters[i];
4177         if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
4178             return false;
4179     }
4180
4181     return true;
4182 }
4183
4184 bool Document::isValidName(const String& name)
4185 {
4186     unsigned length = name.length();
4187     if (!length)
4188         return false;
4189
4190     if (name.is8Bit()) {
4191         const LChar* characters = name.characters8();
4192
4193         if (isValidNameASCII(characters, length))
4194             return true;
4195
4196         return isValidNameNonASCII(characters, length);
4197     }
4198
4199     const UChar* characters = name.characters16();
4200
4201     if (isValidNameASCII(characters, length))
4202         return true;
4203
4204     return isValidNameNonASCII(characters, length);
4205 }
4206
4207 template<typename CharType>
4208 static bool parseQualifiedNameInternal(const AtomicString& qualifiedName, const CharType* characters, unsigned length, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
4209 {
4210     bool nameStart = true;
4211     bool sawColon = false;
4212     int colonPos = 0;
4213
4214     for (unsigned i = 0; i < length;) {
4215         UChar32 c;
4216         U16_NEXT(characters, i, length, c)
4217         if (c == ':') {
4218             if (sawColon) {
4219                 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') contains multiple colons.");
4220                 return false; // multiple colons: not allowed
4221             }
4222             nameStart = true;
4223             sawColon = true;
4224             colonPos = i - 1;
4225         } else if (nameStart) {
4226             if (!isValidNameStart(c)) {
4227                 StringBuilder message;
4228                 message.appendLiteral("The qualified name provided ('");
4229                 message.append(qualifiedName);
4230                 message.appendLiteral("') contains the invalid name-start character '");
4231                 message.append(c);
4232                 message.appendLiteral("'.");
4233                 exceptionState.throwDOMException(InvalidCharacterError, message.toString());
4234                 return false;
4235             }
4236             nameStart = false;
4237         } else {
4238             if (!isValidNamePart(c)) {
4239                 StringBuilder message;
4240                 message.appendLiteral("The qualified name provided ('");
4241                 message.append(qualifiedName);
4242                 message.appendLiteral("') contains the invalid character '");
4243                 message.append(c);
4244                 message.appendLiteral("'.");
4245                 exceptionState.throwDOMException(InvalidCharacterError, message.toString());
4246                 return false;
4247             }
4248         }
4249     }
4250
4251     if (!sawColon) {
4252         prefix = nullAtom;
4253         localName = qualifiedName;
4254     } else {
4255         prefix = AtomicString(characters, colonPos);
4256         if (prefix.isEmpty()) {
4257             exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty namespace prefix.");
4258             return false;
4259         }
4260         int prefixStart = colonPos + 1;
4261         localName = AtomicString(characters + prefixStart, length - prefixStart);
4262     }
4263
4264     if (localName.isEmpty()) {
4265         exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty local name.");
4266         return false;
4267     }
4268
4269     return true;
4270 }
4271
4272 bool Document::parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
4273 {
4274     unsigned length = qualifiedName.length();
4275
4276     if (!length) {
4277         exceptionState.throwDOMException(InvalidCharacterError, "The qualified name provided is empty.");
4278         return false;
4279     }
4280
4281     if (qualifiedName.is8Bit())
4282         return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName, exceptionState);
4283     return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName, exceptionState);
4284 }
4285
4286 void Document::setEncodingData(const DocumentEncodingData& newData)
4287 {
4288     // It's possible for the encoding of the document to change while we're decoding
4289     // data. That can only occur while we're processing the <head> portion of the
4290     // document. There isn't much user-visible content in the <head>, but there is
4291     // the <title> element. This function detects that situation and re-decodes the
4292     // document's title so that the user doesn't see an incorrectly decoded title
4293     // in the title bar.
4294     if (m_titleElement
4295         && encoding() != newData.encoding()
4296         && !ElementTraversal::firstWithin(*m_titleElement)
4297         && encoding() == Latin1Encoding()
4298         && m_titleElement->textContent().containsOnlyLatin1()) {
4299
4300         CString originalBytes = m_titleElement->textContent().latin1();
4301         OwnPtr<TextCodec> codec = newTextCodec(newData.encoding());
4302         String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), DataEOF);
4303         m_titleElement->setTextContent(correctlyDecodedTitle);
4304     }
4305
4306     m_encodingData = newData;
4307
4308     // FIXME: Should be removed as part of https://code.google.com/p/chromium/issues/detail?id=319643
4309     bool shouldUseVisualOrdering = m_encodingData.encoding().usesVisualOrdering();
4310     if (shouldUseVisualOrdering != m_visuallyOrdered) {
4311         m_visuallyOrdered = shouldUseVisualOrdering;
4312         // FIXME: How is possible to not have a renderer here?
4313         if (renderView())
4314             renderView()->style()->setRTLOrdering(m_visuallyOrdered ? VisualOrder : LogicalOrder);
4315         setNeedsStyleRecalc(SubtreeStyleChange);
4316     }
4317 }
4318
4319 KURL Document::completeURL(const String& url) const
4320 {
4321     return completeURLWithOverride(url, m_baseURL);
4322 }
4323
4324 KURL Document::completeURLWithOverride(const String& url, const KURL& baseURLOverride) const
4325 {
4326     // Always return a null URL when passed a null string.
4327     // FIXME: Should we change the KURL constructor to have this behavior?
4328     // See also [CSS]StyleSheet::completeURL(const String&)
4329     if (url.isNull())
4330         return KURL();
4331     // This logic is deliberately spread over many statements in an attempt to track down http://crbug.com/312410.
4332     const KURL* baseURLFromParent = 0;
4333     bool shouldUseParentBaseURL = baseURLOverride.isEmpty();
4334     if (!shouldUseParentBaseURL) {
4335         const KURL& aboutBlankURL = blankURL();
4336         shouldUseParentBaseURL = (baseURLOverride == aboutBlankURL);
4337     }
4338     if (shouldUseParentBaseURL) {
4339         if (Document* parent = parentDocument())
4340             baseURLFromParent = &parent->baseURL();
4341     }
4342     const KURL& baseURL = baseURLFromParent ? *baseURLFromParent : baseURLOverride;
4343     if (!encoding().isValid())
4344         return KURL(baseURL, url);
4345     return KURL(baseURL, url, encoding());
4346 }
4347
4348 // Support for Javascript execCommand, and related methods
4349
4350 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
4351 {
4352     LocalFrame* frame = document->frame();
4353     if (!frame || frame->document() != document)
4354         return Editor::Command();
4355
4356     document->updateRenderTreeIfNeeded();
4357     return frame->editor().command(commandName, userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
4358 }
4359
4360 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
4361 {
4362     // We don't allow recusrive |execCommand()| to protect against attack code.
4363     // Recursive call of |execCommand()| could be happened by moving iframe
4364     // with script triggered by insertion, e.g. <iframe src="javascript:...">
4365     // <iframe onload="...">. This usage is valid as of the specification
4366     // although, it isn't common use case, rather it is used as attack code.
4367     static bool inExecCommand = false;
4368     if (inExecCommand) {
4369         String message = "We don't execute document.execCommand() this time, because it is called recursively.";
4370         addConsoleMessage(JSMessageSource, WarningMessageLevel, message);
4371         return false;
4372     }
4373     TemporaryChange<bool> executeScope(inExecCommand, true);
4374
4375     // Postpone DOM mutation events, which can execute scripts and change
4376     // DOM tree against implementation assumption.
4377     EventQueueScope eventQueueScope;
4378     Editor::Command editorCommand = command(this, commandName, userInterface);
4379     blink::Platform::current()->histogramSparse("WebCore.Document.execCommand", editorCommand.idForHistogram());
4380     return editorCommand.execute(value);
4381 }
4382
4383 bool Document::queryCommandEnabled(const String& commandName)
4384 {
4385     return command(this, commandName).isEnabled();
4386 }
4387
4388 bool Document::queryCommandIndeterm(const String& commandName)
4389 {
4390     return command(this, commandName).state() == MixedTriState;
4391 }
4392
4393 bool Document::queryCommandState(const String& commandName)
4394 {
4395     return command(this, commandName).state() == TrueTriState;
4396 }
4397
4398 bool Document::queryCommandSupported(const String& commandName)
4399 {
4400     return command(this, commandName).isSupported();
4401 }
4402
4403 String Document::queryCommandValue(const String& commandName)
4404 {
4405     return command(this, commandName).value();
4406 }
4407
4408 KURL Document::openSearchDescriptionURL()
4409 {
4410     static const char openSearchMIMEType[] = "application/opensearchdescription+xml";
4411     static const char openSearchRelation[] = "search";
4412
4413     // FIXME: Why do only top-level frames have openSearchDescriptionURLs?
4414     if (!frame() || frame()->tree().parent())
4415         return KURL();
4416
4417     // FIXME: Why do we need to wait for FrameStateComplete?
4418     if (frame()->loader().state() != FrameStateComplete)
4419         return KURL();
4420
4421     if (!head())
4422         return KURL();
4423
4424     for (HTMLLinkElement* linkElement = Traversal<HTMLLinkElement>::firstChild(*head()); linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4425         if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
4426             continue;
4427         if (linkElement->href().isEmpty())
4428             continue;
4429         return linkElement->href();
4430     }
4431
4432     return KURL();
4433 }
4434
4435 void Document::pushCurrentScript(PassRefPtrWillBeRawPtr<HTMLScriptElement> newCurrentScript)
4436 {
4437     ASSERT(newCurrentScript);
4438     m_currentScriptStack.append(newCurrentScript);
4439 }
4440
4441 void Document::popCurrentScript()
4442 {
4443     ASSERT(!m_currentScriptStack.isEmpty());
4444     m_currentScriptStack.removeLast();
4445 }
4446
4447 void Document::applyXSLTransform(ProcessingInstruction* pi)
4448 {
4449     ASSERT(!pi->isLoading());
4450     UseCounter::count(*this, UseCounter::XSLProcessingInstruction);
4451     RefPtrWillBeRawPtr<XSLTProcessor> processor = XSLTProcessor::create();
4452     processor->setXSLStyleSheet(toXSLStyleSheet(pi->sheet()));
4453     String resultMIMEType;
4454     String newSource;
4455     String resultEncoding;
4456     if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
4457         return;
4458     // FIXME: If the transform failed we should probably report an error (like Mozilla does).
4459     LocalFrame* ownerFrame = frame();
4460     processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, ownerFrame);
4461     InspectorInstrumentation::frameDocumentUpdated(ownerFrame);
4462 }
4463
4464 void Document::setTransformSource(PassOwnPtr<TransformSource> source)
4465 {
4466     m_transformSource = source;
4467 }
4468
4469 void Document::setDesignMode(InheritedBool value)
4470 {
4471     m_designMode = value;
4472     for (Frame* frame = m_frame; frame; frame = frame->tree().traverseNext(m_frame)) {
4473         if (!frame->isLocalFrame())
4474             continue;
4475         if (!toLocalFrame(frame)->document())
4476             break;
4477         toLocalFrame(frame)->document()->setNeedsStyleRecalc(SubtreeStyleChange);
4478     }
4479 }
4480
4481 Document::InheritedBool Document::getDesignMode() const
4482 {
4483     return m_designMode;
4484 }
4485
4486 bool Document::inDesignMode() const
4487 {
4488     for (const Document* d = this; d; d = d->parentDocument()) {
4489         if (d->m_designMode != inherit)
4490             return d->m_designMode;
4491     }
4492     return false;
4493 }
4494
4495 String Document::designMode() const
4496 {
4497     return inDesignMode() ? "on" : "off";
4498 }
4499
4500 void Document::setDesignMode(const String& value)
4501 {
4502     InheritedBool mode;
4503     if (equalIgnoringCase(value, "on"))
4504         mode = on;
4505     else if (equalIgnoringCase(value, "off"))
4506         mode = off;
4507     else
4508         mode = inherit;
4509     setDesignMode(mode);
4510 }
4511
4512 Document* Document::parentDocument() const
4513 {
4514     if (!m_frame)
4515         return 0;
4516     Frame* parent = m_frame->tree().parent();
4517     if (!parent || !parent->isLocalFrame())
4518         return 0;
4519     return toLocalFrame(parent)->document();
4520 }
4521
4522 Document& Document::topDocument() const
4523 {
4524     // FIXME: Not clear what topDocument() should do in the OOPI case--should it return the topmost
4525     // available Document, or something else?
4526     Document* doc = const_cast<Document*>(this);
4527     Element* element;
4528     while ((element = doc->ownerElement()))
4529         doc = &element->document();
4530
4531     ASSERT(doc);
4532     return *doc;
4533 }
4534
4535 WeakPtrWillBeRawPtr<Document> Document::contextDocument()
4536 {
4537     if (m_contextDocument)
4538         return m_contextDocument;
4539     if (m_frame) {
4540 #if ENABLE(OILPAN)
4541         return this;
4542 #else
4543         return m_weakFactory.createWeakPtr();
4544 #endif
4545     }
4546     return WeakPtrWillBeRawPtr<Document>(nullptr);
4547 }
4548
4549 PassRefPtrWillBeRawPtr<Attr> Document::createAttribute(const AtomicString& name, ExceptionState& exceptionState)
4550 {
4551     return createAttributeNS(nullAtom, name, exceptionState, true);
4552 }
4553
4554 PassRefPtrWillBeRawPtr<Attr> Document::createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState, bool shouldIgnoreNamespaceChecks)
4555 {
4556     AtomicString prefix, localName;
4557     if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
4558         return nullptr;
4559
4560     QualifiedName qName(prefix, localName, namespaceURI);
4561
4562     if (!shouldIgnoreNamespaceChecks && !hasValidNamespaceForAttributes(qName)) {
4563         exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
4564         return nullptr;
4565     }
4566
4567     return Attr::create(*this, qName, emptyAtom);
4568 }
4569
4570 const SVGDocumentExtensions* Document::svgExtensions()
4571 {
4572     return m_svgExtensions.get();
4573 }
4574
4575 SVGDocumentExtensions& Document::accessSVGExtensions()
4576 {
4577     if (!m_svgExtensions)
4578         m_svgExtensions = adoptPtrWillBeNoop(new SVGDocumentExtensions(this));
4579     return *m_svgExtensions;
4580 }
4581
4582 bool Document::hasSVGRootNode() const
4583 {
4584     return isSVGSVGElement(documentElement());
4585 }
4586
4587 PassRefPtrWillBeRawPtr<HTMLCollection> Document::ensureCachedCollection(CollectionType type)
4588 {
4589     return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(*this, type);
4590 }
4591
4592 PassRefPtrWillBeRawPtr<HTMLCollection> Document::images()
4593 {
4594     return ensureCachedCollection(DocImages);
4595 }
4596
4597 PassRefPtrWillBeRawPtr<HTMLCollection> Document::applets()
4598 {
4599     return ensureCachedCollection(DocApplets);
4600 }
4601
4602 PassRefPtrWillBeRawPtr<HTMLCollection> Document::embeds()
4603 {
4604     return ensureCachedCollection(DocEmbeds);
4605 }
4606
4607 PassRefPtrWillBeRawPtr<HTMLCollection> Document::scripts()
4608 {
4609     return ensureCachedCollection(DocScripts);
4610 }
4611
4612 PassRefPtrWillBeRawPtr<HTMLCollection> Document::links()
4613 {
4614     return ensureCachedCollection(DocLinks);
4615 }
4616
4617 PassRefPtrWillBeRawPtr<HTMLCollection> Document::forms()
4618 {
4619     return ensureCachedCollection(DocForms);
4620 }
4621
4622 PassRefPtrWillBeRawPtr<HTMLCollection> Document::anchors()
4623 {
4624     return ensureCachedCollection(DocAnchors);
4625 }
4626
4627 PassRefPtrWillBeRawPtr<HTMLAllCollection> Document::allForBinding()
4628 {
4629     UseCounter::count(*this, UseCounter::DocumentAll);
4630     return all();
4631 }
4632
4633 PassRefPtrWillBeRawPtr<HTMLAllCollection> Document::all()
4634 {
4635     return ensureRareData().ensureNodeLists().addCache<HTMLAllCollection>(*this, DocAll);
4636 }
4637
4638 PassRefPtrWillBeRawPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
4639 {
4640     return ensureRareData().ensureNodeLists().addCache<WindowNameCollection>(*this, WindowNamedItems, name);
4641 }
4642
4643 PassRefPtrWillBeRawPtr<HTMLCollection> Document::documentNamedItems(const AtomicString& name)
4644 {
4645     return ensureRareData().ensureNodeLists().addCache<DocumentNameCollection>(*this, DocumentNamedItems, name);
4646 }
4647
4648 void Document::finishedParsing()
4649 {
4650     ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
4651     ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
4652     setParsing(false);
4653     if (!m_documentTiming.domContentLoadedEventStart)
4654         m_documentTiming.domContentLoadedEventStart = monotonicallyIncreasingTime();
4655     dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
4656     if (!m_documentTiming.domContentLoadedEventEnd)
4657         m_documentTiming.domContentLoadedEventEnd = monotonicallyIncreasingTime();
4658
4659     if (frame() && frame()->isMainFrame()) {
4660         // Reset the text autosizing multipliers on main frame when DOM is loaded.
4661         // This is to allow for a fresh text autosizing pass when the page layout
4662         // changes significantly in the end.
4663         if (TextAutosizer* textAutosizer = this->textAutosizer())
4664             textAutosizer->recalculateMultipliers();
4665     }
4666
4667     // The loader's finishedParsing() method may invoke script that causes this object to
4668     // be dereferenced (when this document is in an iframe and the onload causes the iframe's src to change).
4669     // Keep it alive until we are done.
4670     RefPtrWillBeRawPtr<Document> protect(this);
4671
4672     if (RefPtr<LocalFrame> f = frame()) {
4673         // Don't update the render tree if we haven't requested the main resource yet to avoid
4674         // adding extra latency. Note that the first render tree update can be expensive since it
4675         // triggers the parsing of the default stylesheets which are compiled-in.
4676         const bool mainResourceWasAlreadyRequested =
4677             m_frame->loader().stateMachine()->committedFirstRealDocumentLoad();
4678
4679         // FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
4680         // resource loads are complete. HTMLObjectElements can start loading their resources from
4681         // post attach callbacks triggered by recalcStyle().  This means if we parse out an <object>
4682         // tag and then reach the end of the document without updating styles, we might not have yet
4683         // started the resource load and might fire the window load event too early.  To avoid this
4684         // we force the styles to be up to date before calling FrameLoader::finishedParsing().
4685         // See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
4686         if (mainResourceWasAlreadyRequested)
4687             updateRenderTreeIfNeeded();
4688
4689         f->loader().finishedParsing();
4690
4691         TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "MarkDOMContent", "data", InspectorMarkLoadEvent::data(f.get()));
4692         // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
4693         InspectorInstrumentation::domContentLoadedEventFired(f.get());
4694     }
4695
4696     // Schedule dropping of the ElementDataCache. We keep it alive for a while after parsing finishes
4697     // so that dynamically inserted content can also benefit from sharing optimizations.
4698     // Note that we don't refresh the timer on cache access since that could lead to huge caches being kept
4699     // alive indefinitely by something innocuous like JS setting .innerHTML repeatedly on a timer.
4700     m_elementDataCacheClearTimer.startOneShot(10, FROM_HERE);
4701
4702     // Parser should have picked up all preloads by now
4703     m_fetcher->clearPreloads();
4704
4705     if (HTMLImportLoader* import = importLoader())
4706         import->didFinishParsing();
4707 }
4708
4709 void Document::elementDataCacheClearTimerFired(Timer<Document>*)
4710 {
4711     m_elementDataCache.clear();
4712 }
4713
4714 Vector<IconURL> Document::iconURLs(int iconTypesMask)
4715 {
4716     IconURL firstFavicon;
4717     IconURL firstTouchIcon;
4718     IconURL firstTouchPrecomposedIcon;
4719     Vector<IconURL> secondaryIcons;
4720
4721     // Start from the last child node so that icons seen later take precedence as required by the spec.
4722     for (HTMLLinkElement* linkElement = head() ? Traversal<HTMLLinkElement>::firstChild(*head()) : 0; linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4723         if (!(linkElement->iconType() & iconTypesMask))
4724             continue;
4725         if (linkElement->href().isEmpty())
4726             continue;
4727         if (!RuntimeEnabledFeatures::touchIconLoadingEnabled() && linkElement->iconType() != Favicon)
4728             continue;
4729
4730         IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
4731         if (linkElement->iconType() == Favicon) {
4732             if (firstFavicon.m_iconType != InvalidIcon)
4733                 secondaryIcons.append(firstFavicon);
4734             firstFavicon = newURL;
4735         } else if (linkElement->iconType() == TouchIcon) {
4736             if (firstTouchIcon.m_iconType != InvalidIcon)
4737                 secondaryIcons.append(firstTouchIcon);
4738             firstTouchIcon = newURL;
4739         } else if (linkElement->iconType() == TouchPrecomposedIcon) {
4740             if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4741                 secondaryIcons.append(firstTouchPrecomposedIcon);
4742             firstTouchPrecomposedIcon = newURL;
4743         } else {
4744             ASSERT_NOT_REACHED();
4745         }
4746     }
4747
4748     Vector<IconURL> iconURLs;
4749     if (firstFavicon.m_iconType != InvalidIcon)
4750         iconURLs.append(firstFavicon);
4751     else if (m_url.protocolIsInHTTPFamily() && iconTypesMask & Favicon)
4752         iconURLs.append(IconURL::defaultFavicon(m_url));
4753
4754     if (firstTouchIcon.m_iconType != InvalidIcon)
4755         iconURLs.append(firstTouchIcon);
4756     if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4757         iconURLs.append(firstTouchPrecomposedIcon);
4758     for (int i = secondaryIcons.size() - 1; i >= 0; --i)
4759         iconURLs.append(secondaryIcons[i]);
4760     return iconURLs;
4761 }
4762
4763 Color Document::themeColor() const
4764 {
4765     if (!RuntimeEnabledFeatures::themeColorEnabled())
4766         return Color();
4767
4768     for (HTMLMetaElement* metaElement = head() ? Traversal<HTMLMetaElement>::firstChild(*head()) : 0; metaElement; metaElement = Traversal<HTMLMetaElement>::nextSibling(*metaElement)) {
4769         RGBA32 rgb;
4770         if (equalIgnoringCase(metaElement->name(), "theme-color") && BisonCSSParser::parseColor(rgb, metaElement->content().string().stripWhiteSpace(), true))
4771             return Color(rgb);
4772     }
4773     return Color();
4774 }
4775
4776 HTMLLinkElement* Document::linkManifest() const
4777 {
4778     HTMLHeadElement* head = this->head();
4779     if (!head)
4780         return 0;
4781
4782     // The first link element with a manifest rel must be used. Others are ignored.
4783     for (HTMLLinkElement* linkElement = Traversal<HTMLLinkElement>::firstChild(*head); linkElement; linkElement = Traversal<HTMLLinkElement>::nextSibling(*linkElement)) {
4784         if (!linkElement->relAttribute().isManifest())
4785             continue;
4786         return linkElement;
4787     }
4788
4789     return 0;
4790 }
4791
4792 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
4793 {
4794     if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
4795         return;
4796
4797     m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
4798     m_frame->selection().updateSecureKeyboardEntryIfActive();
4799 }
4800
4801 bool Document::useSecureKeyboardEntryWhenActive() const
4802 {
4803     return m_useSecureKeyboardEntryWhenActive;
4804 }
4805
4806 void Document::initSecurityContext()
4807 {
4808     initSecurityContext(DocumentInit(m_url, m_frame, contextDocument(), m_importsController));
4809 }
4810
4811 static PassRefPtr<ContentSecurityPolicy> contentSecurityPolicyFor(Document* document)
4812 {
4813     if (document->importsController())
4814         return document->importsController()->master()->contentSecurityPolicy();
4815     return ContentSecurityPolicy::create(document);
4816 }
4817
4818 void Document::initSecurityContext(const DocumentInit& initializer)
4819 {
4820     if (haveInitializedSecurityOrigin()) {
4821         ASSERT(securityOrigin());
4822         return;
4823     }
4824
4825     if (!initializer.hasSecurityContext()) {
4826         // No source for a security context.
4827         // This can occur via document.implementation.createDocument().
4828         m_cookieURL = KURL(ParsedURLString, emptyString());
4829         setSecurityOrigin(SecurityOrigin::createUnique());
4830         setContentSecurityPolicy(ContentSecurityPolicy::create(this));
4831         return;
4832     }
4833
4834     // In the common case, create the security context from the currently
4835     // loading URL with a fresh content security policy.
4836     m_cookieURL = m_url;
4837     enforceSandboxFlags(initializer.sandboxFlags());
4838     setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
4839     setContentSecurityPolicy(contentSecurityPolicyFor(this));
4840
4841     if (Settings* settings = initializer.settings()) {
4842         if (!settings->webSecurityEnabled()) {
4843             // Web security is turned off. We should let this document access every other document. This is used primary by testing
4844             // harnesses for web sites.
4845             securityOrigin()->grantUniversalAccess();
4846         } else if (securityOrigin()->isLocal()) {
4847             if (settings->allowUniversalAccessFromFileURLs()) {
4848                 // Some clients want local URLs to have universal access, but that setting is dangerous for other clients.
4849                 securityOrigin()->grantUniversalAccess();
4850             } else if (!settings->allowFileAccessFromFileURLs()) {
4851                 // Some clients want local URLs to have even tighter restrictions by default, and not be able to access other local files.
4852                 // FIXME 81578: The naming of this is confusing. Files with restricted access to other local files
4853                 // still can have other privileges that can be remembered, thereby not making them unique origins.
4854                 securityOrigin()->enforceFilePathSeparation();
4855             }
4856         }
4857     }
4858
4859     if (initializer.shouldTreatURLAsSrcdocDocument()) {
4860         m_isSrcdocDocument = true;
4861         setBaseURLOverride(initializer.parentBaseURL());
4862     }
4863
4864     if (!shouldInheritSecurityOriginFromOwner(m_url))
4865         return;
4866
4867     // If we do not obtain a meaningful origin from the URL, then we try to
4868     // find one via the frame hierarchy.
4869
4870     if (!initializer.owner()) {
4871         didFailToInitializeSecurityOrigin();
4872         return;
4873     }
4874
4875     if (isSandboxed(SandboxOrigin)) {
4876         // If we're supposed to inherit our security origin from our owner,
4877         // but we're also sandboxed, the only thing we inherit is the ability
4878         // to load local resources. This lets about:blank iframes in file://
4879         // URL documents load images and other resources from the file system.
4880         if (initializer.owner()->securityOrigin()->canLoadLocalResources())
4881             securityOrigin()->grantLoadLocalResources();
4882         return;
4883     }
4884
4885     m_cookieURL = initializer.owner()->cookieURL();
4886     // We alias the SecurityOrigins to match Firefox, see Bug 15313
4887     // https://bugs.webkit.org/show_bug.cgi?id=15313
4888     setSecurityOrigin(initializer.owner()->securityOrigin());
4889 }
4890
4891 void Document::initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders& headers)
4892 {
4893     if (m_frame && m_frame->tree().parent() && m_frame->tree().parent()->isLocalFrame() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
4894         contentSecurityPolicy()->copyStateFrom(toLocalFrame(m_frame->tree().parent())->document()->contentSecurityPolicy());
4895     contentSecurityPolicy()->didReceiveHeaders(headers);
4896 }
4897
4898 bool Document::allowInlineEventHandlers(Node* node, EventListener* listener, const String& contextURL, const WTF::OrdinalNumber& contextLine)
4899 {
4900     if (!contentSecurityPolicy()->allowInlineEventHandlers(contextURL, contextLine))
4901         return false;
4902
4903     // HTML says that inline script needs browsing context to create its execution environment.
4904     // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#event-handler-attributes
4905     // Also, if the listening node came from other document, which happens on context-less event dispatching,
4906     // we also need to ask the owner document of the node.
4907     LocalFrame* frame = executingFrame();
4908     if (!frame)
4909         return false;
4910     if (!frame->script().canExecuteScripts(NotAboutToExecuteScript))
4911         return false;
4912     if (node && node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
4913         return false;
4914
4915     return true;
4916 }
4917
4918 bool Document::allowExecutingScripts(Node* node)
4919 {
4920     // FIXME: Eventually we'd like to evaluate scripts which are inserted into a
4921     // viewless document but this'll do for now.
4922     // See http://bugs.webkit.org/show_bug.cgi?id=5727
4923     LocalFrame* frame = executingFrame();
4924     if (!frame)
4925         return false;
4926     if (!node->document().executingFrame())
4927         return false;
4928     if (!frame->script().canExecuteScripts(AboutToExecuteScript))
4929         return false;
4930     return true;
4931 }
4932
4933 void Document::updateSecurityOrigin(PassRefPtr<SecurityOrigin> origin)
4934 {
4935     setSecurityOrigin(origin);
4936     didUpdateSecurityOrigin();
4937 }
4938
4939 void Document::didUpdateSecurityOrigin()
4940 {
4941     if (!m_frame)
4942         return;
4943     m_frame->script().updateSecurityOrigin(securityOrigin());
4944 }
4945
4946 bool Document::isContextThread() const
4947 {
4948     return isMainThread();
4949 }
4950
4951 void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
4952 {
4953     m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
4954     if (!m_updateFocusAppearanceTimer.isActive())
4955         m_updateFocusAppearanceTimer.startOneShot(0, FROM_HERE);
4956 }
4957
4958 void Document::cancelFocusAppearanceUpdate()
4959 {
4960     m_updateFocusAppearanceTimer.stop();
4961 }
4962
4963 void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
4964 {
4965     Element* element = focusedElement();
4966     if (!element)
4967         return;
4968     updateLayout();
4969     if (element->isFocusable())
4970         element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
4971 }
4972
4973 void Document::attachRange(Range* range)
4974 {
4975     ASSERT(!m_ranges.contains(range));
4976     m_ranges.add(range);
4977 }
4978
4979 void Document::detachRange(Range* range)
4980 {
4981     // We don't ASSERT m_ranges.contains(range) to allow us to call this
4982     // unconditionally to fix: https://bugs.webkit.org/show_bug.cgi?id=26044
4983     m_ranges.remove(range);
4984 }
4985
4986 void Document::getCSSCanvasContext(const String& type, const String& name, int width, int height, bool& is2d, RefPtrWillBeRawPtr<CanvasRenderingContext2D>& context2d, bool& is3d, RefPtrWillBeRawPtr<WebGLRenderingContext>& context3d)
4987 {
4988     HTMLCanvasElement& element = getCSSCanvasElement(name);
4989     element.setSize(IntSize(width, height));
4990     CanvasRenderingContext* context = element.getContext(type);
4991     if (!context)
4992         return;
4993
4994     if (context->is2d()) {
4995         is2d = true;
4996         context2d = toCanvasRenderingContext2D(context);
4997     } else if (context->is3d()) {
4998         is3d = true;
4999         context3d = toWebGLRenderingContext(context);
5000     }
5001 }
5002
5003 HTMLCanvasElement& Document::getCSSCanvasElement(const String& name)
5004 {
5005     RefPtrWillBeMember<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, nullptr).storedValue->value;
5006     if (!element) {
5007         element = HTMLCanvasElement::create(*this);
5008         element->setAccelerationDisabled(true);
5009     }
5010     return *element;
5011 }
5012
5013 void Document::initDNSPrefetch()
5014 {
5015     Settings* settings = this->settings();
5016
5017     m_haveExplicitlyDisabledDNSPrefetch = false;
5018     m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
5019
5020     // Inherit DNS prefetch opt-out from parent frame
5021     if (Document* parent = parentDocument()) {
5022         if (!parent->isDNSPrefetchEnabled())
5023             m_isDNSPrefetchEnabled = false;
5024     }
5025 }
5026
5027 void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
5028 {
5029     if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
5030         m_isDNSPrefetchEnabled = true;
5031         return;
5032     }
5033
5034     m_isDNSPrefetchEnabled = false;
5035     m_haveExplicitlyDisabledDNSPrefetch = true;
5036 }
5037
5038 void Document::reportBlockedScriptExecutionToInspector(const String& directiveText)
5039 {
5040     InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText);
5041 }
5042
5043 void Document::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* scriptState)
5044 {
5045     internalAddMessage(source, level, message, sourceURL, lineNumber, nullptr, scriptState);
5046 }
5047
5048 void Document::internalAddMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtrWillBeRawPtr<ScriptCallStack> callStack, ScriptState* scriptState)
5049 {
5050     if (!isContextThread()) {
5051         m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
5052         return;
5053     }
5054
5055     if (!m_frame)
5056         return;
5057
5058     String messageURL = sourceURL;
5059     if (!scriptState && sourceURL.isNull() && !lineNumber) {
5060         messageURL = url().string();
5061         if (parsing() && !isInDocumentWrite() && scriptableDocumentParser()) {
5062             ScriptableDocumentParser* parser = scriptableDocumentParser();
5063             if (!parser->isWaitingForScripts() && !parser->isExecutingScript())
5064                 lineNumber = parser->lineNumber().oneBasedInt();
5065         }
5066     }
5067     m_frame->console().addMessage(source, level, message, messageURL, lineNumber, 0, callStack, scriptState, 0);
5068 }
5069
5070 void Document::addConsoleMessageWithRequestIdentifier(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
5071 {
5072     if (!isContextThread()) {
5073         m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
5074         return;
5075     }
5076
5077     if (m_frame)
5078         m_frame->console().addMessage(source, level, message, String(), 0, 0, nullptr, 0, requestIdentifier);
5079 }
5080
5081 // FIXME(crbug.com/305497): This should be removed after ExecutionContext-LocalDOMWindow migration.
5082 void Document::postTask(PassOwnPtr<ExecutionContextTask> task)
5083 {
5084     m_taskRunner->postTask(task);
5085 }
5086
5087 void Document::tasksWereSuspended()
5088 {
5089     scriptRunner()->suspend();
5090
5091     if (m_parser)
5092         m_parser->suspendScheduledTasks();
5093     if (m_scriptedAnimationController)
5094         m_scriptedAnimationController->suspend();
5095 }
5096
5097 void Document::tasksWereResumed()
5098 {
5099     scriptRunner()->resume();
5100
5101     if (m_parser)
5102         m_parser->resumeScheduledTasks();
5103     if (m_scriptedAnimationController)
5104         m_scriptedAnimationController->resume();
5105
5106     MutationObserver::resumeSuspendedObservers();
5107 }
5108
5109 // FIXME: suspendScheduledTasks(), resumeScheduledTasks(), tasksNeedSuspension()
5110 // should be moved to LocalDOMWindow once it inherits ExecutionContext
5111 void Document::suspendScheduledTasks()
5112 {
5113     ExecutionContext::suspendScheduledTasks();
5114     m_taskRunner->suspend();
5115 }
5116
5117 void Document::resumeScheduledTasks()
5118 {
5119     ExecutionContext::resumeScheduledTasks();
5120     m_taskRunner->resume();
5121 }
5122
5123 bool Document::tasksNeedSuspension()
5124 {
5125     Page* page = this->page();
5126     return page && page->defersLoading();
5127 }
5128
5129 void Document::addToTopLayer(Element* element, const Element* before)
5130 {
5131     if (element->isInTopLayer())
5132         return;
5133
5134     ASSERT(!m_topLayerElements.contains(element));
5135     ASSERT(!before || m_topLayerElements.contains(before));
5136     if (before) {
5137         size_t beforePosition = m_topLayerElements.find(before);
5138         m_topLayerElements.insert(beforePosition, element);
5139     } else {
5140         m_topLayerElements.append(element);
5141     }
5142     element->setIsInTopLayer(true);
5143 }
5144
5145 void Document::removeFromTopLayer(Element* element)
5146 {
5147     if (!element->isInTopLayer())
5148         return;
5149     size_t position = m_topLayerElements.find(element);
5150     ASSERT(position != kNotFound);
5151     m_topLayerElements.remove(position);
5152     element->setIsInTopLayer(false);
5153 }
5154
5155 HTMLDialogElement* Document::activeModalDialog() const
5156 {
5157     if (m_topLayerElements.isEmpty())
5158         return 0;
5159     return toHTMLDialogElement(m_topLayerElements.last().get());
5160 }
5161
5162 void Document::exitPointerLock()
5163 {
5164     if (!page())
5165         return;
5166     if (Element* target = page()->pointerLockController().element()) {
5167         if (target->document() != this)
5168             return;
5169     }
5170     page()->pointerLockController().requestPointerUnlock();
5171 }
5172
5173 Element* Document::pointerLockElement() const
5174 {
5175     if (!page() || page()->pointerLockController().lockPending())
5176         return 0;
5177     if (Element* element = page()->pointerLockController().element()) {
5178         if (element->document() == this)
5179             return element;
5180     }
5181     return 0;
5182 }
5183
5184 void Document::decrementLoadEventDelayCount()
5185 {
5186     ASSERT(m_loadEventDelayCount);
5187     --m_loadEventDelayCount;
5188
5189     if (!m_loadEventDelayCount)
5190         checkLoadEventSoon();
5191 }
5192
5193 void Document::checkLoadEventSoon()
5194 {
5195     if (frame() && !m_loadEventDelayTimer.isActive())
5196         m_loadEventDelayTimer.startOneShot(0, FROM_HERE);
5197 }
5198
5199 bool Document::isDelayingLoadEvent()
5200 {
5201 #if ENABLE(OILPAN)
5202     // Always delay load events until after garbage collection.
5203     // This way we don't have to explicitly delay load events via
5204     // incrementLoadEventDelayCount and decrementLoadEventDelayCount in
5205     // Node destructors.
5206     if (ThreadState::current()->isSweepInProgress()) {
5207         if (!m_loadEventDelayCount)
5208             checkLoadEventSoon();
5209         return true;
5210     }
5211 #endif
5212     return m_loadEventDelayCount;
5213 }
5214
5215
5216 void Document::loadEventDelayTimerFired(Timer<Document>*)
5217 {
5218     if (frame())
5219         frame()->loader().checkCompleted();
5220 }
5221
5222 void Document::loadPluginsSoon()
5223 {
5224     // FIXME: Remove this timer once we don't need to compute layout to load plugins.
5225     if (!m_pluginLoadingTimer.isActive())
5226         m_pluginLoadingTimer.startOneShot(0, FROM_HERE);
5227 }
5228
5229 void Document::pluginLoadingTimerFired(Timer<Document>*)
5230 {
5231     updateLayout();
5232 }
5233
5234 ScriptedAnimationController& Document::ensureScriptedAnimationController()
5235 {
5236     if (!m_scriptedAnimationController) {
5237         m_scriptedAnimationController = ScriptedAnimationController::create(this);
5238         // We need to make sure that we don't start up the animation controller on a background tab, for example.
5239         if (!page())
5240             m_scriptedAnimationController->suspend();
5241     }
5242     return *m_scriptedAnimationController;
5243 }
5244
5245 int Document::requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
5246 {
5247     return ensureScriptedAnimationController().registerCallback(callback);
5248 }
5249
5250 void Document::cancelAnimationFrame(int id)
5251 {
5252     if (!m_scriptedAnimationController)
5253         return;
5254     m_scriptedAnimationController->cancelCallback(id);
5255 }
5256
5257 void Document::serviceScriptedAnimations(double monotonicAnimationStartTime)
5258 {
5259     if (!m_scriptedAnimationController)
5260         return;
5261     m_scriptedAnimationController->serviceScriptedAnimations(monotonicAnimationStartTime);
5262 }
5263
5264 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
5265 {
5266     // Match behavior from when these types were integers, and avoid surprises from someone explicitly
5267     // passing Infinity/NaN.
5268     if (!std::isfinite(pageX))
5269         pageX = 0;
5270     if (!std::isfinite(pageY))
5271         pageY = 0;
5272     if (!std::isfinite(screenX))
5273         screenX = 0;
5274     if (!std::isfinite(screenY))
5275         screenY = 0;
5276     if (!std::isfinite(radiusX))
5277         radiusX = 0;
5278     if (!std::isfinite(radiusY))
5279         radiusY = 0;
5280     if (!std::isfinite(rotationAngle))
5281         rotationAngle = 0;
5282     if (!std::isfinite(force))
5283         force = 0;
5284
5285     // FIXME: It's not clear from the documentation at
5286     // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html
5287     // 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
5288     // and implement them here. See https://bugs.webkit.org/show_bug.cgi?id=47819
5289     LocalFrame* frame = window ? window->frame() : this->frame();
5290     return Touch::create(frame, target, identifier, FloatPoint(screenX, screenY), FloatPoint(pageX, pageY), FloatSize(radiusX, radiusY), rotationAngle, force);
5291 }
5292
5293 PassRefPtrWillBeRawPtr<TouchList> Document::createTouchList(WillBeHeapVector<RefPtrWillBeMember<Touch> >& touches) const
5294 {
5295     return TouchList::create(touches);
5296 }
5297
5298 void Document::didAddTouchEventHandler(Node* handler)
5299 {
5300     // The node should either be in this document, or be the Document node of a child
5301     // of this document.
5302     ASSERT(&handler->document() == this
5303         || (handler->isDocumentNode() && toDocument(handler)->parentDocument() == this));
5304     if (!m_touchEventTargets.get())
5305         m_touchEventTargets = adoptPtr(new TouchEventTargetSet);
5306     bool isFirstHandler = m_touchEventTargets->isEmpty();
5307
5308     if (!m_touchEventTargets->add(handler).isNewEntry) {
5309         // Just incremented refcount, no real change.
5310         // If this is a child document node, then the count should never go above 1.
5311         ASSERT(!handler->isDocumentNode() || &handler->document() == this);
5312         return;
5313     }
5314
5315     if (isFirstHandler) {
5316         if (Document* parent = parentDocument()) {
5317             parent->didAddTouchEventHandler(this);
5318         } else {
5319             // This is the first touch handler on the whole page.
5320             if (FrameHost* frameHost = this->frameHost())
5321                 frameHost->chrome().client().needTouchEvents(true);
5322         }
5323     }
5324
5325     // When we're all done with all frames, ensure touch hit rects are marked as dirty.
5326     if (!handler->isDocumentNode() || handler == this) {
5327         if (Page* page = this->page()) {
5328             if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
5329                 scrollingCoordinator->touchEventTargetRectsDidChange();
5330         }
5331     }
5332 }
5333
5334 void Document::didRemoveTouchEventHandler(Node* handler, bool clearAll)
5335 {
5336     // Note that we can't assert that |handler| is in this document because it might be in
5337     // the process of moving out of it.
5338     ASSERT(clearAll || m_touchEventTargets->contains(handler));
5339     if (!m_touchEventTargets.get())
5340         return;
5341
5342     if (clearAll) {
5343         if (!m_touchEventTargets->contains(handler))
5344             return;
5345         m_touchEventTargets->removeAll(handler);
5346     } else {
5347         if (!m_touchEventTargets->remove(handler))
5348             // Just decremented refcount, no real update.
5349             return;
5350     }
5351
5352     if (m_touchEventTargets->isEmpty()) {
5353         if (Document* parent = parentDocument()) {
5354             // This was the last handler in this document, update the parent document too.
5355             parent->didRemoveTouchEventHandler(this, clearAll);
5356         } else {
5357             // We just removed the last touch handler on the whole page.
5358             if (FrameHost* frameHost = this->frameHost())
5359                 frameHost->chrome().client().needTouchEvents(false);
5360         }
5361     }
5362
5363     // When we're all done with all frames, ensure touch hit rects are marked as dirty.
5364     if (!handler->isDocumentNode() || handler == this) {
5365         if (Page* page = this->page()) {
5366             if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
5367                 scrollingCoordinator->touchEventTargetRectsDidChange();
5368         }
5369     }
5370 }
5371
5372 DocumentLoader* Document::loader() const
5373 {
5374     if (!m_frame)
5375         return 0;
5376
5377     DocumentLoader* loader = m_frame->loader().documentLoader();
5378     if (!loader)
5379         return 0;
5380
5381     if (m_frame->document() != this)
5382         return 0;
5383
5384     return loader;
5385 }
5386
5387 IntSize Document::initialViewportSize() const
5388 {
5389     if (!view())
5390         return IntSize();
5391     return view()->unscaledVisibleContentSize(IncludeScrollbars);
5392 }
5393
5394 Node* eventTargetNodeForDocument(Document* doc)
5395 {
5396     if (!doc)
5397         return 0;
5398     Node* node = doc->focusedElement();
5399     if (!node && doc->isPluginDocument()) {
5400         PluginDocument* pluginDocument = toPluginDocument(doc);
5401         node =  pluginDocument->pluginNode();
5402     }
5403     if (!node && doc->isHTMLDocument())
5404         node = doc->body();
5405     if (!node)
5406         node = doc->documentElement();
5407     return node;
5408 }
5409
5410 void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject& renderer)
5411 {
5412     if (!view())
5413         return;
5414
5415     LayoutRect visibleContentRect = view()->visibleContentRect();
5416     for (size_t i = 0; i < quads.size(); ++i) {
5417         quads[i].move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
5418         adjustFloatQuadForAbsoluteZoom(quads[i], renderer);
5419     }
5420 }
5421
5422 void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject& renderer)
5423 {
5424     if (!view())
5425         return;
5426
5427     LayoutRect visibleContentRect = view()->visibleContentRect();
5428     rect.move(-FloatSize(visibleContentRect.x().toFloat(), visibleContentRect.y().toFloat()));
5429     adjustFloatRectForAbsoluteZoom(rect, renderer);
5430 }
5431
5432 bool Document::hasActiveParser()
5433 {
5434     return m_activeParserCount || (m_parser && m_parser->processingData());
5435 }
5436
5437 void Document::decrementActiveParserCount()
5438 {
5439     --m_activeParserCount;
5440     if (!frame())
5441         return;
5442     // FIXME: This should always be enabled, but it seems to cause
5443     // http/tests/security/feed-urls-from-remote.html to timeout on Mac WK1
5444     // see http://webkit.org/b/110554 and http://webkit.org/b/110401
5445     frame()->loader().checkLoadComplete();
5446 }
5447
5448 void Document::setContextFeatures(ContextFeatures& features)
5449 {
5450     m_contextFeatures = PassRefPtrWillBeRawPtr<ContextFeatures>(features);
5451 }
5452
5453 static RenderObject* nearestCommonHoverAncestor(RenderObject* obj1, RenderObject* obj2)
5454 {
5455     if (!obj1 || !obj2)
5456         return 0;
5457
5458     for (RenderObject* currObj1 = obj1; currObj1; currObj1 = currObj1->hoverAncestor()) {
5459         for (RenderObject* currObj2 = obj2; currObj2; currObj2 = currObj2->hoverAncestor()) {
5460             if (currObj1 == currObj2)
5461                 return currObj1;
5462         }
5463     }
5464
5465     return 0;
5466 }
5467
5468 void Document::updateHoverActiveState(const HitTestRequest& request, Element* innerElement, const PlatformMouseEvent* event)
5469 {
5470     ASSERT(!request.readOnly());
5471
5472     if (request.active() && m_frame)
5473         m_frame->eventHandler().notifyElementActivated();
5474
5475     Element* innerElementInDocument = innerElement;
5476     while (innerElementInDocument && innerElementInDocument->document() != this) {
5477         innerElementInDocument->document().updateHoverActiveState(request, innerElementInDocument, event);
5478         innerElementInDocument = innerElementInDocument->document().ownerElement();
5479     }
5480
5481     Element* oldActiveElement = activeHoverElement();
5482     if (oldActiveElement && !request.active()) {
5483         // We are clearing the :active chain because the mouse has been released.
5484         for (RenderObject* curr = oldActiveElement->renderer(); curr; curr = curr->parent()) {
5485             if (curr->node()) {
5486                 ASSERT(!curr->node()->isTextNode());
5487                 curr->node()->setActive(false);
5488                 m_userActionElements.setInActiveChain(curr->node(), false);
5489             }
5490         }
5491         setActiveHoverElement(nullptr);
5492     } else {
5493         Element* newActiveElement = innerElementInDocument;
5494         if (!oldActiveElement && newActiveElement && !newActiveElement->isDisabledFormControl() && request.active() && !request.touchMove()) {
5495             // We are setting the :active chain and freezing it. If future moves happen, they
5496             // will need to reference this chain.
5497             for (RenderObject* curr = newActiveElement->renderer(); curr; curr = curr->parent()) {
5498                 if (curr->node() && !curr->isText())
5499                     m_userActionElements.setInActiveChain(curr->node(), true);
5500             }
5501
5502             setActiveHoverElement(newActiveElement);
5503         }
5504     }
5505     // If the mouse has just been pressed, set :active on the chain. Those (and only those)
5506     // nodes should remain :active until the mouse is released.
5507     bool allowActiveChanges = !oldActiveElement && activeHoverElement();
5508
5509     // If the mouse is down and if this is a mouse move event, we want to restrict changes in
5510     // :hover/:active to only apply to elements that are in the :active chain that we froze
5511     // at the time the mouse went down.
5512     bool mustBeInActiveChain = request.active() && request.move();
5513
5514     RefPtrWillBeRawPtr<Node> oldHoverNode = hoverNode();
5515
5516     // Check to see if the hovered node has changed.
5517     // If it hasn't, we do not need to do anything.
5518     Node* newHoverNode = innerElementInDocument;
5519     while (newHoverNode && !newHoverNode->renderer())
5520         newHoverNode = newHoverNode->parentOrShadowHostNode();
5521
5522     // Update our current hover node.
5523     setHoverNode(newHoverNode);
5524
5525     // We have two different objects. Fetch their renderers.
5526     RenderObject* oldHoverObj = oldHoverNode ? oldHoverNode->renderer() : 0;
5527     RenderObject* newHoverObj = newHoverNode ? newHoverNode->renderer() : 0;
5528
5529     // Locate the common ancestor render object for the two renderers.
5530     RenderObject* ancestor = nearestCommonHoverAncestor(oldHoverObj, newHoverObj);
5531     RefPtrWillBeRawPtr<Node> ancestorNode(ancestor ? ancestor->node() : 0);
5532
5533     WillBeHeapVector<RefPtrWillBeMember<Node>, 32> nodesToRemoveFromChain;
5534     WillBeHeapVector<RefPtrWillBeMember<Node>, 32> nodesToAddToChain;
5535
5536     if (oldHoverObj != newHoverObj) {
5537         // If the old hovered node is not nil but it's renderer is, it was probably detached as part of the :hover style
5538         // (for instance by setting display:none in the :hover pseudo-class). In this case, the old hovered element (and its ancestors)
5539         // must be updated, to ensure it's normal style is re-applied.
5540         if (oldHoverNode && !oldHoverObj) {
5541             for (Node* node = oldHoverNode.get(); node; node = node->parentNode()) {
5542                 if (!mustBeInActiveChain || (node->isElementNode() && toElement(node)->inActiveChain()))
5543                     nodesToRemoveFromChain.append(node);
5544             }
5545
5546         }
5547
5548         // The old hover path only needs to be cleared up to (and not including) the common ancestor;
5549         for (RenderObject* curr = oldHoverObj; curr && curr != ancestor; curr = curr->hoverAncestor()) {
5550             if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5551                 nodesToRemoveFromChain.append(curr->node());
5552         }
5553     }
5554
5555     // Now set the hover state for our new object up to the root.
5556     for (RenderObject* curr = newHoverObj; curr; curr = curr->hoverAncestor()) {
5557         if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5558             nodesToAddToChain.append(curr->node());
5559     }
5560
5561     // mouseenter and mouseleave events do not bubble, so they are dispatched iff there is a capturing
5562     // event handler on an ancestor or a normal event handler on the element itself. This special
5563     // handling is necessary to avoid O(n^2) capturing event handler checks. We'll check the previously
5564     // hovered node's ancestor tree for 'mouseleave' handlers here, then check the newly hovered node's
5565     // ancestor tree for 'mouseenter' handlers after dispatching the 'mouseleave' events (as the handler
5566     // for 'mouseleave' might set a capturing 'mouseenter' handler, odd as that might be).
5567     bool ancestorHasCapturingMouseleaveListener = false;
5568     if (event && newHoverNode != oldHoverNode.get()) {
5569         for (Node* node = oldHoverNode.get(); node; node = node->parentOrShadowHostNode()) {
5570             if (node->hasCapturingEventListeners(EventTypeNames::mouseleave)) {
5571                 ancestorHasCapturingMouseleaveListener = true;
5572                 break;
5573             }
5574         }
5575     }
5576
5577     size_t removeCount = nodesToRemoveFromChain.size();
5578     for (size_t i = 0; i < removeCount; ++i) {
5579         nodesToRemoveFromChain[i]->setHovered(false);
5580         if (event && (ancestorHasCapturingMouseleaveListener || nodesToRemoveFromChain[i]->hasEventListeners(EventTypeNames::mouseleave)))
5581             nodesToRemoveFromChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseleave, 0, newHoverNode);
5582     }
5583
5584     bool ancestorHasCapturingMouseenterListener = false;
5585     if (event && newHoverNode != oldHoverNode.get()) {
5586         for (Node* node = newHoverNode; node; node = node->parentOrShadowHostNode()) {
5587             if (node->hasCapturingEventListeners(EventTypeNames::mouseenter)) {
5588                 ancestorHasCapturingMouseenterListener = true;
5589                 break;
5590             }
5591         }
5592     }
5593
5594     bool sawCommonAncestor = false;
5595     size_t addCount = nodesToAddToChain.size();
5596     for (size_t i = 0; i < addCount; ++i) {
5597         // Elements past the common ancestor do not change hover state, but might change active state.
5598         if (ancestorNode && nodesToAddToChain[i] == ancestorNode)
5599             sawCommonAncestor = true;
5600         if (allowActiveChanges)
5601             nodesToAddToChain[i]->setActive(true);
5602         if (!sawCommonAncestor) {
5603             nodesToAddToChain[i]->setHovered(true);
5604             if (event && (ancestorHasCapturingMouseenterListener || nodesToAddToChain[i]->hasEventListeners(EventTypeNames::mouseenter)))
5605                 nodesToAddToChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseenter, 0, oldHoverNode.get());
5606         }
5607     }
5608 }
5609
5610 bool Document::haveStylesheetsLoaded() const
5611 {
5612     return m_styleEngine->haveStylesheetsLoaded();
5613 }
5614
5615 Locale& Document::getCachedLocale(const AtomicString& locale)
5616 {
5617     AtomicString localeKey = locale;
5618     if (locale.isEmpty() || !RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
5619         return Locale::defaultLocale();
5620     LocaleIdentifierToLocaleMap::AddResult result = m_localeCache.add(localeKey, nullptr);
5621     if (result.isNewEntry)
5622         result.storedValue->value = Locale::create(localeKey);
5623     return *(result.storedValue->value);
5624 }
5625
5626 Document& Document::ensureTemplateDocument()
5627 {
5628     if (isTemplateDocument())
5629         return *this;
5630
5631     if (m_templateDocument)
5632         return *m_templateDocument;
5633
5634     if (isHTMLDocument()) {
5635         DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL()).withNewRegistrationContext();
5636         m_templateDocument = HTMLDocument::create(init);
5637     } else {
5638         m_templateDocument = Document::create(DocumentInit(blankURL()));
5639     }
5640
5641     m_templateDocument->m_templateDocumentHost = this; // balanced in dtor.
5642
5643     return *m_templateDocument.get();
5644 }
5645
5646 void Document::didAssociateFormControl(Element* element)
5647 {
5648     if (!frame() || !frame()->page())
5649         return;
5650     m_associatedFormControls.add(element);
5651     if (!m_didAssociateFormControlsTimer.isActive())
5652         m_didAssociateFormControlsTimer.startOneShot(0, FROM_HERE);
5653 }
5654
5655 void Document::didAssociateFormControlsTimerFired(Timer<Document>* timer)
5656 {
5657     ASSERT_UNUSED(timer, timer == &m_didAssociateFormControlsTimer);
5658     if (!frame() || !frame()->page())
5659         return;
5660
5661     WillBeHeapVector<RefPtrWillBeMember<Element> > associatedFormControls;
5662     copyToVector(m_associatedFormControls, associatedFormControls);
5663
5664     frame()->page()->chrome().client().didAssociateFormControls(associatedFormControls);
5665     m_associatedFormControls.clear();
5666 }
5667
5668 float Document::devicePixelRatio() const
5669 {
5670     return m_frame ? m_frame->devicePixelRatio() : 1.0;
5671 }
5672
5673 PassOwnPtr<LifecycleNotifier<Document> > Document::createLifecycleNotifier()
5674 {
5675     return DocumentLifecycleNotifier::create(this);
5676 }
5677
5678 DocumentLifecycleNotifier& Document::lifecycleNotifier()
5679 {
5680     return static_cast<DocumentLifecycleNotifier&>(LifecycleContext<Document>::lifecycleNotifier());
5681 }
5682
5683 void Document::removedStyleSheet(StyleSheet* sheet, StyleResolverUpdateMode updateMode)
5684 {
5685     // If we're in document teardown, then we don't need this notification of our sheet's removal.
5686     // styleResolverChanged() is needed even when the document is inactive so that
5687     // imported docuements (which is inactive) notifies the change to the master document.
5688     if (isActive())
5689         styleEngine()->modifiedStyleSheet(sheet);
5690     styleResolverChanged(updateMode);
5691 }
5692
5693 void Document::modifiedStyleSheet(StyleSheet* sheet, StyleResolverUpdateMode updateMode)
5694 {
5695     // If we're in document teardown, then we don't need this notification of our sheet's removal.
5696     // styleResolverChanged() is needed even when the document is inactive so that
5697     // imported docuements (which is inactive) notifies the change to the master document.
5698     if (isActive())
5699         styleEngine()->modifiedStyleSheet(sheet);
5700     styleResolverChanged(updateMode);
5701 }
5702
5703 TextAutosizer* Document::textAutosizer()
5704 {
5705     if (!m_textAutosizer && !RuntimeEnabledFeatures::fastTextAutosizingEnabled())
5706         m_textAutosizer = TextAutosizer::create(this);
5707     return m_textAutosizer.get();
5708 }
5709
5710 FastTextAutosizer* Document::fastTextAutosizer()
5711 {
5712     if (!m_fastTextAutosizer && RuntimeEnabledFeatures::fastTextAutosizingEnabled())
5713         m_fastTextAutosizer = FastTextAutosizer::create(this);
5714     return m_fastTextAutosizer.get();
5715 }
5716
5717 void Document::setAutofocusElement(Element* element)
5718 {
5719     if (!element) {
5720         m_autofocusElement = nullptr;
5721         return;
5722     }
5723     if (m_hasAutofocused)
5724         return;
5725     m_hasAutofocused = true;
5726     ASSERT(!m_autofocusElement);
5727     m_autofocusElement = element;
5728     m_taskRunner->postTask(AutofocusTask::create());
5729 }
5730
5731 Element* Document::activeElement() const
5732 {
5733     if (Element* element = treeScope().adjustedFocusedElement())
5734         return element;
5735     return body();
5736 }
5737
5738 bool Document::hasFocus() const
5739 {
5740     Page* page = this->page();
5741     if (!page)
5742         return false;
5743     if (!page->focusController().isActive() || !page->focusController().isFocused())
5744         return false;
5745     Frame* focusedFrame = page->focusController().focusedFrame();
5746     if (focusedFrame && focusedFrame->isLocalFrame()) {
5747         if (toLocalFrame(focusedFrame)->tree().isDescendantOf(frame()))
5748             return true;
5749     }
5750     return false;
5751 }
5752
5753 #if ENABLE(OILPAN)
5754 template<unsigned type>
5755 bool shouldInvalidateNodeListCachesForAttr(const HeapHashSet<WeakMember<const LiveNodeListBase> > nodeLists[], const QualifiedName& attrName)
5756 {
5757     if (!nodeLists[type].isEmpty() && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
5758         return true;
5759     return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeLists, attrName);
5760 }
5761
5762 template<>
5763 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const HeapHashSet<WeakMember<const LiveNodeListBase> >[], const QualifiedName&)
5764 {
5765     return false;
5766 }
5767 #else
5768 template<unsigned type>
5769 bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
5770 {
5771     if (nodeListCounts[type] && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
5772         return true;
5773     return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
5774 }
5775
5776 template<>
5777 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
5778 {
5779     return false;
5780 }
5781 #endif
5782
5783 bool Document::shouldInvalidateNodeListCaches(const QualifiedName* attrName) const
5784 {
5785     if (attrName) {
5786 #if ENABLE(OILPAN)
5787         return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeLists, *attrName);
5788 #else
5789         return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListCounts, *attrName);
5790 #endif
5791     }
5792
5793     for (int type = 0; type < numNodeListInvalidationTypes; ++type) {
5794 #if ENABLE(OILPAN)
5795         if (!m_nodeLists[type].isEmpty())
5796 #else
5797         if (m_nodeListCounts[type])
5798 #endif
5799             return true;
5800     }
5801
5802     return false;
5803 }
5804
5805 void Document::invalidateNodeListCaches(const QualifiedName* attrName)
5806 {
5807     WillBeHeapHashSet<RawPtrWillBeWeakMember<const LiveNodeListBase> >::const_iterator end = m_listsInvalidatedAtDocument.end();
5808     for (WillBeHeapHashSet<RawPtrWillBeWeakMember<const LiveNodeListBase> >::const_iterator it = m_listsInvalidatedAtDocument.begin(); it != end; ++it)
5809         (*it)->invalidateCacheForAttribute(attrName);
5810 }
5811
5812 void Document::clearWeakMembers(Visitor* visitor)
5813 {
5814     if (m_axObjectCache)
5815         m_axObjectCache->clearWeakMembers(visitor);
5816
5817     // FIXME: Oilpan: Use a weak counted set instead.
5818     if (m_touchEventTargets) {
5819         Vector<Node*> deadNodes;
5820         for (TouchEventTargetSet::iterator it = m_touchEventTargets->begin(); it != m_touchEventTargets->end(); ++it) {
5821             if (!visitor->isAlive(it->key))
5822                 deadNodes.append(it->key);
5823         }
5824         for (unsigned i = 0; i < deadNodes.size(); ++i)
5825             didClearTouchEventHandlers(deadNodes[i]);
5826     }
5827 }
5828
5829 void Document::trace(Visitor* visitor)
5830 {
5831     visitor->trace(m_importsController);
5832     visitor->trace(m_docType);
5833     visitor->trace(m_implementation);
5834     visitor->trace(m_autofocusElement);
5835     visitor->trace(m_focusedElement);
5836     visitor->trace(m_hoverNode);
5837     visitor->trace(m_activeHoverElement);
5838     visitor->trace(m_documentElement);
5839     visitor->trace(m_titleElement);
5840     visitor->trace(m_markers);
5841     visitor->trace(m_cssTarget);
5842     visitor->trace(m_currentScriptStack);
5843     visitor->trace(m_scriptRunner);
5844     visitor->trace(m_transformSourceDocument);
5845     visitor->trace(m_listsInvalidatedAtDocument);
5846 #if ENABLE(OILPAN)
5847     for (int i = 0; i < numNodeListInvalidationTypes; ++i)
5848         visitor->trace(m_nodeLists[i]);
5849 #endif
5850     visitor->trace(m_cssCanvasElements);
5851     visitor->trace(m_topLayerElements);
5852     visitor->trace(m_elemSheet);
5853     visitor->trace(m_nodeIterators);
5854     visitor->trace(m_ranges);
5855     visitor->trace(m_styleEngine);
5856     visitor->trace(m_formController);
5857     visitor->trace(m_domWindow);
5858     visitor->trace(m_fetcher);
5859     visitor->trace(m_parser);
5860     visitor->trace(m_contextFeatures);
5861     visitor->trace(m_styleSheetList);
5862     visitor->trace(m_mediaQueryMatcher);
5863     visitor->trace(m_scriptedAnimationController);
5864     visitor->trace(m_registrationContext);
5865     visitor->trace(m_associatedFormControls);
5866     visitor->trace(m_useElementsNeedingUpdate);
5867     visitor->trace(m_layerUpdateSVGFilterElements);
5868     visitor->trace(m_templateDocument);
5869     visitor->trace(m_templateDocumentHost);
5870     visitor->trace(m_visibilityObservers);
5871     visitor->trace(m_userActionElements);
5872     visitor->trace(m_svgExtensions);
5873     visitor->trace(m_timeline);
5874     visitor->trace(m_compositorPendingAnimations);
5875     visitor->trace(m_contextDocument);
5876     visitor->registerWeakMembers<Document, &Document::clearWeakMembers>(this);
5877     DocumentSupplementable::trace(visitor);
5878     TreeScope::trace(visitor);
5879     ContainerNode::trace(visitor);
5880     ExecutionContext::trace(visitor);
5881 }
5882
5883 } // namespace WebCore