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