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