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