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.
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.
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.
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.
29 #include "core/dom/Document.h"
31 #include "HTMLElementFactory.h"
32 #include "HTMLNames.h"
33 #include "RuntimeEnabledFeatures.h"
34 #include "SVGElementFactory.h"
36 #include "XMLNSNames.h"
38 #include "bindings/v8/CustomElementConstructorBuilder.h"
39 #include "bindings/v8/Dictionary.h"
40 #include "bindings/v8/ExceptionMessages.h"
41 #include "bindings/v8/ExceptionState.h"
42 #include "bindings/v8/ExceptionStatePlaceholder.h"
43 #include "bindings/v8/ScriptController.h"
44 #include "core/accessibility/AXObjectCache.h"
45 #include "core/animation/AnimationClock.h"
46 #include "core/animation/DocumentAnimations.h"
47 #include "core/animation/DocumentTimeline.h"
48 #include "core/animation/css/TransitionTimeline.h"
49 #include "core/css/CSSFontSelector.h"
50 #include "core/css/CSSStyleDeclaration.h"
51 #include "core/css/CSSStyleSheet.h"
52 #include "core/css/MediaQueryMatcher.h"
53 #include "core/css/StylePropertySet.h"
54 #include "core/css/StyleSheetContents.h"
55 #include "core/css/StyleSheetList.h"
56 #include "core/css/resolver/FontBuilder.h"
57 #include "core/css/resolver/StyleResolver.h"
58 #include "core/css/resolver/StyleResolverStats.h"
59 #include "core/dom/AddConsoleMessageTask.h"
60 #include "core/dom/Attr.h"
61 #include "core/dom/CDATASection.h"
62 #include "core/dom/Comment.h"
63 #include "core/dom/ContextFeatures.h"
64 #include "core/dom/DOMImplementation.h"
65 #include "core/dom/DocumentFragment.h"
66 #include "core/dom/DocumentLifecycleNotifier.h"
67 #include "core/dom/DocumentLifecycleObserver.h"
68 #include "core/dom/DocumentMarkerController.h"
69 #include "core/dom/DocumentType.h"
70 #include "core/dom/Element.h"
71 #include "core/dom/ElementDataCache.h"
72 #include "core/dom/ElementTraversal.h"
73 #include "core/dom/ExceptionCode.h"
74 #include "core/dom/ExecutionContextTask.h"
75 #include "core/dom/MainThreadTaskRunner.h"
76 #include "core/dom/MutationObserver.h"
77 #include "core/dom/NodeChildRemovalTracker.h"
78 #include "core/dom/NodeFilter.h"
79 #include "core/dom/NodeIterator.h"
80 #include "core/dom/NodeRareData.h"
81 #include "core/dom/NodeRenderStyle.h"
82 #include "core/dom/NodeRenderingTraversal.h"
83 #include "core/dom/NodeTraversal.h"
84 #include "core/dom/NodeWithIndex.h"
85 #include "core/dom/PostAttachCallbacks.h"
86 #include "core/dom/ProcessingInstruction.h"
87 #include "core/dom/RequestAnimationFrameCallback.h"
88 #include "core/dom/ScriptRunner.h"
89 #include "core/dom/ScriptedAnimationController.h"
90 #include "core/dom/SelectorQuery.h"
91 #include "core/dom/StyleEngine.h"
92 #include "core/dom/TouchList.h"
93 #include "core/dom/TransformSource.h"
94 #include "core/dom/TreeWalker.h"
95 #include "core/dom/VisitedLinkState.h"
96 #include "core/dom/XMLDocument.h"
97 #include "core/dom/custom/CustomElementRegistrationContext.h"
98 #include "core/dom/shadow/ElementShadow.h"
99 #include "core/dom/shadow/ShadowRoot.h"
100 #include "core/editing/Editor.h"
101 #include "core/editing/FrameSelection.h"
102 #include "core/editing/SpellChecker.h"
103 #include "core/events/BeforeUnloadEvent.h"
104 #include "core/events/Event.h"
105 #include "core/events/EventFactory.h"
106 #include "core/events/EventListener.h"
107 #include "core/events/HashChangeEvent.h"
108 #include "core/events/PageTransitionEvent.h"
109 #include "core/events/ScopedEventQueue.h"
110 #include "core/events/ThreadLocalEventNames.h"
111 #include "core/fetch/ResourceFetcher.h"
112 #include "core/frame/ContentSecurityPolicy.h"
113 #include "core/frame/DOMWindow.h"
114 #include "core/frame/Frame.h"
115 #include "core/frame/FrameHost.h"
116 #include "core/frame/FrameView.h"
117 #include "core/frame/History.h"
118 #include "core/frame/PageConsole.h"
119 #include "core/frame/Settings.h"
120 #include "core/html/HTMLAllCollection.h"
121 #include "core/html/HTMLAnchorElement.h"
122 #include "core/html/HTMLCanvasElement.h"
123 #include "core/html/HTMLCollection.h"
124 #include "core/html/HTMLDialogElement.h"
125 #include "core/html/HTMLDocument.h"
126 #include "core/html/HTMLFrameOwnerElement.h"
127 #include "core/html/HTMLHeadElement.h"
128 #include "core/html/HTMLIFrameElement.h"
129 #include "core/html/HTMLImport.h"
130 #include "core/html/HTMLInputElement.h"
131 #include "core/html/HTMLLinkElement.h"
132 #include "core/html/HTMLMetaElement.h"
133 #include "core/html/HTMLNameCollection.h"
134 #include "core/html/HTMLScriptElement.h"
135 #include "core/html/HTMLStyleElement.h"
136 #include "core/html/HTMLTitleElement.h"
137 #include "core/html/PluginDocument.h"
138 #include "core/html/forms/FormController.h"
139 #include "core/html/parser/HTMLDocumentParser.h"
140 #include "core/html/parser/HTMLParserIdioms.h"
141 #include "core/html/parser/NestingLevelIncrementer.h"
142 #include "core/html/parser/TextResourceDecoder.h"
143 #include "core/inspector/InspectorCounters.h"
144 #include "core/inspector/InspectorInstrumentation.h"
145 #include "core/inspector/ScriptCallStack.h"
146 #include "core/loader/CookieJar.h"
147 #include "core/loader/DocumentLoader.h"
148 #include "core/loader/FrameLoader.h"
149 #include "core/loader/FrameLoaderClient.h"
150 #include "core/loader/ImageLoader.h"
151 #include "core/loader/appcache/ApplicationCacheHost.h"
152 #include "core/page/Chrome.h"
153 #include "core/page/ChromeClient.h"
154 #include "core/page/EventHandler.h"
155 #include "core/page/FocusController.h"
156 #include "core/page/FrameTree.h"
157 #include "core/page/MouseEventWithHitTestResults.h"
158 #include "core/page/Page.h"
159 #include "core/page/PointerLockController.h"
160 #include "core/page/scrolling/ScrollingCoordinator.h"
161 #include "core/rendering/FastTextAutosizer.h"
162 #include "core/rendering/HitTestResult.h"
163 #include "core/rendering/RenderView.h"
164 #include "core/rendering/RenderWidget.h"
165 #include "core/rendering/TextAutosizer.h"
166 #include "core/svg/SVGDocumentExtensions.h"
167 #include "core/svg/SVGFontFaceElement.h"
168 #include "core/svg/SVGStyleElement.h"
169 #include "core/svg/SVGUseElement.h"
170 #include "core/workers/SharedWorkerRepositoryClient.h"
171 #include "core/xml/XSLTProcessor.h"
172 #include "core/xml/parser/XMLDocumentParser.h"
173 #include "platform/DateComponents.h"
174 #include "platform/Language.h"
175 #include "platform/TraceEvent.h"
176 #include "platform/network/HTTPParsers.h"
177 #include "platform/scroll/ScrollbarTheme.h"
178 #include "platform/text/PlatformLocale.h"
179 #include "platform/text/SegmentedString.h"
180 #include "platform/weborigin/OriginAccessEntry.h"
181 #include "platform/weborigin/SchemeRegistry.h"
182 #include "platform/weborigin/SecurityOrigin.h"
183 #include "wtf/CurrentTime.h"
184 #include "wtf/HashFunctions.h"
185 #include "wtf/MainThread.h"
186 #include "wtf/StdLibExtras.h"
187 #include "wtf/TemporaryChange.h"
188 #include "wtf/text/StringBuffer.h"
189 #include "wtf/text/TextEncodingRegistry.h"
193 using namespace Unicode;
197 using namespace HTMLNames;
199 static const unsigned cMaxWriteRecursionDepth = 21;
201 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
202 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
204 static const int cLayoutScheduleThreshold = 250;
206 // DOM Level 2 says (letters added):
208 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
209 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
210 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
211 // d) Characters which have a font or compatibility decomposition (i.e. those with a "compatibility formatting tag" in field 5 of the database -- marked by field 5 beginning with a "<") are not allowed.
212 // e) The following characters are treated as name-start characters rather than name characters, because the property file classifies them as Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.
213 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
214 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
215 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
216 // i) Characters ':' and '_' are allowed as name-start characters.
217 // j) Characters '-' and '.' are allowed as name characters.
219 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
221 static inline bool isValidNameStart(UChar32 c)
224 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
228 if (c == ':' || c == '_')
231 // rules (a) and (f) above
232 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
233 if (!(Unicode::category(c) & nameStartMask))
237 if (c >= 0xF900 && c < 0xFFFE)
241 DecompositionType decompType = decompositionType(c);
242 if (decompType == DecompositionFont || decompType == DecompositionCompat)
248 static inline bool isValidNamePart(UChar32 c)
250 // rules (a), (e), and (i) above
251 if (isValidNameStart(c))
254 // rules (g) and (h) above
255 if (c == 0x00B7 || c == 0x0387)
259 if (c == '-' || c == '.')
262 // rules (b) and (f) above
263 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
264 if (!(Unicode::category(c) & otherNamePartMask))
268 if (c >= 0xF900 && c < 0xFFFE)
272 DecompositionType decompType = decompositionType(c);
273 if (decompType == DecompositionFont || decompType == DecompositionCompat)
279 static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
281 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
283 // If a Document has the address "about:blank"
284 // The origin of the Document is the origin it was assigned when its browsing context was created.
286 // Note: We generalize this to all "blank" URLs and invalid URLs because we
287 // treat all of these URLs as about:blank.
289 return url.isEmpty() || url.isBlankURL();
292 static Widget* widgetForElement(const Element& focusedElement)
294 RenderObject* renderer = focusedElement.renderer();
295 if (!renderer || !renderer->isWidget())
297 return toRenderWidget(renderer)->widget();
300 static bool acceptsEditingFocus(const Element& element)
302 ASSERT(element.rendererIsEditable());
304 return element.document().frame() && element.rootEditableElement();
307 static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, Frame* targetFrame)
309 // targetFrame can be 0 when we're trying to navigate a top-level frame
310 // that has a 0 opener.
314 const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
315 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
316 Document* ancestorDocument = ancestorFrame->document();
317 // FIXME: Should be an ASSERT? Frames should alway have documents.
318 if (!ancestorDocument)
321 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
322 if (activeSecurityOrigin.canAccess(ancestorSecurityOrigin))
325 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
326 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
327 // something more general instead?
328 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
335 static void printNavigationErrorMessage(const Frame& frame, const KURL& activeURL, const char* reason)
337 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame.document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
339 // FIXME: should we print to the console of the document performing the navigation instead?
340 frame.domWindow()->printErrorMessage(message);
343 uint64_t Document::s_globalTreeVersion = 0;
345 // This class doesn't work with non-Document ExecutionContext.
346 class AutofocusTask FINAL : public ExecutionContextTask {
348 static PassOwnPtr<AutofocusTask> create()
350 return adoptPtr(new AutofocusTask());
352 virtual ~AutofocusTask() { }
356 virtual void performTask(ExecutionContext* context) OVERRIDE
358 Document* document = toDocument(context);
359 if (RefPtr<Element> element = document->autofocusElement()) {
360 document->setAutofocusElement(0);
366 DocumentVisibilityObserver::DocumentVisibilityObserver(Document& document)
369 registerObserver(document);
372 DocumentVisibilityObserver::~DocumentVisibilityObserver()
374 unregisterObserver();
377 void DocumentVisibilityObserver::unregisterObserver()
380 m_document->unregisterVisibilityObserver(this);
385 void DocumentVisibilityObserver::registerObserver(Document& document)
388 m_document = &document;
390 m_document->registerVisibilityObserver(this);
393 void DocumentVisibilityObserver::setObservedDocument(Document& document)
395 unregisterObserver();
396 registerObserver(document);
399 Document::Document(const DocumentInit& initializer, DocumentClassFlags documentClasses)
400 : ContainerNode(0, CreateDocument)
402 , m_hasNodesWithPlaceholderStyle(false)
403 , m_needsNotifyRemoveAllPendingStylesheet(false)
404 , m_evaluateMediaQueriesOnStyleRecalc(false)
405 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
406 , m_frame(initializer.frame())
407 , m_domWindow(m_frame ? m_frame->domWindow() : 0)
408 , m_import(initializer.import())
409 , m_activeParserCount(0)
410 , m_contextFeatures(ContextFeatures::defaultSwitch())
411 , m_wellFormed(false)
413 , m_paginatedForScreen(false)
414 , m_compatibilityMode(NoQuirksMode)
415 , m_compatibilityModeLocked(false)
416 , m_hasAutofocused(false)
417 , m_clearFocusedElementTimer(this, &Document::clearFocusedElementTimerFired)
418 , m_domTreeVersion(++s_globalTreeVersion)
420 , m_mutationObserverTypes(0)
421 , m_visitedLinkState(VisitedLinkState::create(*this))
422 , m_visuallyOrdered(false)
423 , m_readyState(Complete)
425 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
426 , m_containsValidityStyleRules(false)
427 , m_updateFocusAppearanceRestoresSelection(false)
428 , m_containsPlugins(false)
429 , m_ignoreDestructiveWriteCount(0)
430 , m_titleSetExplicitly(false)
431 , m_markers(adoptPtr(new DocumentMarkerController))
432 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
434 , m_loadEventProgress(LoadEventNotRun)
435 , m_startTime(currentTime())
436 , m_scriptRunner(ScriptRunner::create(this))
437 , m_xmlVersion("1.0")
438 , m_xmlStandalone(StandaloneUnspecified)
439 , m_hasXMLDeclaration(0)
440 , m_designMode(inherit)
441 , m_hasAnnotatedRegions(false)
442 , m_annotatedRegionsDirty(false)
443 , m_useSecureKeyboardEntryWhenActive(false)
444 , m_documentClasses(documentClasses)
445 , m_isViewSource(false)
446 , m_sawElementsInKnownNamespaces(false)
447 , m_isSrcdocDocument(false)
448 , m_isMobileDocument(false)
450 , m_weakFactory(this)
451 , m_contextDocument(initializer.contextDocument())
452 , m_hasFullscreenElementStack(false)
453 , m_loadEventDelayCount(0)
454 , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
455 , m_pluginLoadingTimer(this, &Document::pluginLoadingTimerFired)
456 , m_didSetReferrerPolicy(false)
457 , m_referrerPolicy(ReferrerPolicyDefault)
458 , m_directionSetOnDocumentElement(false)
459 , m_writingModeSetOnDocumentElement(false)
460 , m_writeRecursionIsTooDeep(false)
461 , m_writeRecursionDepth(0)
462 , m_lastHandledUserGestureTimestamp(0)
463 , m_taskRunner(MainThreadTaskRunner::create(this))
464 , m_registrationContext(initializer.registrationContext(this))
465 , m_elementDataCacheClearTimer(this, &Document::elementDataCacheClearTimerFired)
467 , m_didDispatchViewportPropertiesChanged(false)
469 , m_animationClock(AnimationClock::create())
470 , m_timeline(DocumentTimeline::create(this))
471 , m_transitionTimeline(TransitionTimeline::create(this))
472 , m_templateDocumentHost(0)
473 , m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
474 , m_hasViewportUnits(false)
477 ScriptWrappable::init(this);
480 provideContextFeaturesToDocumentFrom(this, m_frame->page());
482 m_fetcher = m_frame->loader().documentLoader()->fetcher();
486 m_fetcher = ResourceFetcher::create(0);
487 m_fetcher->setDocument(this);
489 // We depend on the url getting immediately set in subframes, but we
490 // also depend on the url NOT getting immediately set in opened windows.
491 // See fast/dom/early-frame-url.html
492 // and fast/dom/location-new-window-no-crash.html, respectively.
493 // FIXME: Can/should we unify this behavior?
494 if (initializer.shouldSetURL())
495 setURL(initializer.url());
497 initSecurityContext(initializer);
500 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
501 m_nodeListCounts[i] = 0;
503 InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
505 m_lifecycle.advanceTo(DocumentLifecycle::Inactive);
507 // Since CSSFontSelector requires Document::m_fetcher and StyleEngine owns
508 // CSSFontSelector, need to initialize m_styleEngine after initializing
510 m_styleEngine = StyleEngine::create(*this);
513 Document::~Document()
515 ASSERT(!renderView());
516 ASSERT(m_ranges.isEmpty());
517 ASSERT(!parentTreeScope());
518 ASSERT(!hasGuardRefCount());
519 ASSERT(m_visibilityObservers.isEmpty());
521 if (m_templateDocument)
522 m_templateDocument->m_templateDocumentHost = 0; // balanced in ensureTemplateDocument().
524 m_scriptRunner.clear();
526 removeAllEventListeners();
528 // Currently we believe that Document can never outlive the parser.
529 // Although the Document may be replaced synchronously, DocumentParsers
530 // generally keep at least one reference to an Element which would in turn
531 // has a reference to the Document. If you hit this ASSERT, then that
532 // assumption is wrong. DocumentParser::detach() should ensure that even
533 // if the DocumentParser outlives the Document it won't cause badness.
534 ASSERT(!m_parser || m_parser->refCount() == 1);
537 if (this == topDocument())
538 clearAXObjectCache();
540 if (m_styleSheetList)
541 m_styleSheetList->detachFromDocument();
544 m_import->wasDetachedFromDocument();
549 m_timeline->detachFromDocument();
552 if (m_transitionTimeline) {
553 m_transitionTimeline->detachFromDocument();
556 m_styleEngine.clear(); // We need to destory CSSFontSelector before destroying m_fetcher.
559 m_elemSheet->clearOwnerNode();
561 // It's possible for multiple Documents to end up referencing the same ResourceFetcher (e.g., SVGImages
562 // load the initial empty document and the SVGDocument with the same DocumentLoader).
563 if (m_fetcher->document() == this)
564 m_fetcher->setDocument(0);
567 // We must call clearRareData() here since a Document class inherits TreeScope
568 // as well as Node. See a comment on TreeScope.h for the reason.
572 ASSERT(!m_listsInvalidatedAtDocument.size());
574 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
575 ASSERT(!m_nodeListCounts[i]);
579 InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
582 void Document::dispose()
584 ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
585 // We must make sure not to be retaining any of our children through
586 // these extra pointers or we will create a reference cycle.
588 m_focusedElement = 0;
590 m_activeHoverElement = 0;
592 m_documentElement = 0;
593 m_contextFeatures = ContextFeatures::defaultSwitch();
594 m_userActionElements.documentDidRemoveLastRef();
595 m_associatedFormControls.clear();
599 m_registrationContext.clear();
602 m_import->wasDetachedFromDocument();
606 // removeDetachedChildren() doesn't always unregister IDs,
607 // so tear down scope information upfront to avoid having stale references in the map.
608 destroyTreeScopeData();
609 removeDetachedChildren();
610 // removeDetachedChildren() can access FormController.
611 m_formController.clear();
615 m_cssCanvasElements.clear();
617 // FIXME: consider using ActiveDOMObject.
618 if (m_scriptedAnimationController)
619 m_scriptedAnimationController->clearDocumentPointer();
620 m_scriptedAnimationController.clear();
623 accessSVGExtensions()->pauseAnimations();
625 m_lifecycle.advanceTo(DocumentLifecycle::Disposed);
626 lifecycleNotifier().notifyDocumentWasDisposed();
629 SelectorQueryCache& Document::selectorQueryCache()
631 if (!m_selectorQueryCache)
632 m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
633 return *m_selectorQueryCache;
636 MediaQueryMatcher& Document::mediaQueryMatcher()
638 if (!m_mediaQueryMatcher)
639 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
640 return *m_mediaQueryMatcher;
643 void Document::mediaQueryAffectingValueChanged()
645 styleEngine()->clearMediaQueryRuleSetStyleSheets();
648 void Document::setCompatibilityMode(CompatibilityMode mode)
650 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
652 bool wasInQuirksMode = inQuirksMode();
653 m_compatibilityMode = mode;
654 selectorQueryCache().invalidate();
655 if (inQuirksMode() != wasInQuirksMode) {
656 // All injected stylesheets have to reparse using the different mode.
657 m_styleEngine->invalidateInjectedStyleSheetCache();
661 String Document::compatMode() const
663 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
666 void Document::setDoctype(PassRefPtr<DocumentType> docType)
668 // This should never be called more than once.
669 ASSERT(!m_docType || !docType);
672 this->adoptIfNeeded(*m_docType);
673 if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
674 m_isMobileDocument = true;
676 // Doctype affects the interpretation of the stylesheets.
677 clearStyleResolver();
680 DOMImplementation* Document::implementation()
682 if (!m_implementation)
683 m_implementation = DOMImplementation::create(*this);
684 return m_implementation.get();
687 bool Document::hasManifest() const
689 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->hasAttribute(manifestAttr);
692 Location* Document::location() const
697 return domWindow()->location();
700 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
702 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
704 Element* newDocumentElement = ElementTraversal::firstWithin(*this);
705 if (newDocumentElement == m_documentElement)
707 m_documentElement = newDocumentElement;
708 // The root style used for media query matching depends on the document element.
709 clearStyleResolver();
712 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& exceptionState)
714 if (!isValidName(name)) {
715 exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + name + "') is not a valid name.");
719 if (isXHTMLDocument() || isHTMLDocument())
720 return HTMLElementFactory::createHTMLElement(isHTMLDocument() ? name.lower() : name, *this, 0, false);
722 return Element::create(QualifiedName(nullAtom, name, nullAtom), this);
725 PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& exceptionState)
727 if (!isValidName(localName)) {
728 exceptionState.throwDOMException(InvalidCharacterError, "The tag name provided ('" + localName + "') is not a valid name.");
732 RefPtr<Element> element;
734 if (CustomElement::isValidName(localName) && registrationContext()) {
735 element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI));
737 element = createElement(localName, exceptionState);
738 if (exceptionState.hadException())
742 if (!typeExtension.isEmpty())
743 CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
748 static inline QualifiedName createQualifiedName(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
750 AtomicString prefix, localName;
751 if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
754 QualifiedName qName(prefix, localName, namespaceURI);
755 if (!Document::hasValidNamespaceForElements(qName)) {
756 exceptionState.throwDOMException(NamespaceError, "The namespace URI provided ('" + namespaceURI + "') is not valid for the qualified name provided ('" + qualifiedName + "').");
763 PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
765 QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
766 if (qName == nullQName())
769 return createElement(qName, false);
772 PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
774 QualifiedName qName(createQualifiedName(namespaceURI, qualifiedName, exceptionState));
775 if (qName == nullQName())
778 RefPtr<Element> element;
779 if (CustomElement::isValidName(qName.localName()) && registrationContext())
780 element = registrationContext()->createCustomTagElement(*this, qName);
782 element = createElement(qName, false);
784 if (!typeExtension.isEmpty())
785 CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
790 ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, ExceptionState& exceptionState)
792 return registerElement(state, name, Dictionary(), exceptionState);
795 ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, const Dictionary& options, ExceptionState& exceptionState, CustomElement::NameSet validNames)
797 if (!registrationContext()) {
798 exceptionState.throwDOMException(NotSupportedError, "No element registration context is available.");
799 return ScriptValue();
802 CustomElementConstructorBuilder constructorBuilder(state, &options);
803 registrationContext()->registerElement(this, &constructorBuilder, name, validNames, exceptionState);
804 return constructorBuilder.bindingsReturnValue();
807 void Document::setImport(HTMLImport* import)
809 ASSERT(!m_import || !import);
813 void Document::didLoadAllImports()
815 executeScriptsWaitingForResourcesIfNeeded();
818 bool Document::haveImportsLoaded() const
820 return !m_import || !m_import->state().shouldBlockScriptExecution();
823 DOMWindow* Document::executingWindow()
825 if (DOMWindow* owningWindow = domWindow())
827 if (HTMLImport* import = this->import())
828 return import->master()->domWindow();
832 Frame* Document::executingFrame()
834 DOMWindow* window = executingWindow();
837 return window->frame();
840 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
842 return DocumentFragment::create(*this);
845 PassRefPtr<Text> Document::createTextNode(const String& data)
847 return Text::create(*this, data);
850 PassRefPtr<Comment> Document::createComment(const String& data)
852 return Comment::create(*this, data);
855 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& exceptionState)
857 if (isHTMLDocument()) {
858 exceptionState.throwDOMException(NotSupportedError, "This operation is not supported for HTML documents.");
861 if (data.contains("]]>")) {
862 exceptionState.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
865 return CDATASection::create(*this, data);
868 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& exceptionState)
870 if (!isValidName(target)) {
871 exceptionState.throwDOMException(InvalidCharacterError, "The target provided ('" + target + "') is not a valid name.");
874 if (data.contains("?>")) {
875 exceptionState.throwDOMException(InvalidCharacterError, "The data provided ('" + data + "') contains '?>'.");
878 return ProcessingInstruction::create(*this, target, data);
881 PassRefPtr<Text> Document::createEditingTextNode(const String& text)
883 return Text::createEditingText(*this, text);
886 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& exceptionState)
889 exceptionState.throwDOMException(NotSupportedError, "The node provided is invalid.");
893 switch (importedNode->nodeType()) {
895 return createTextNode(importedNode->nodeValue());
896 case CDATA_SECTION_NODE:
897 return createCDATASection(importedNode->nodeValue(), exceptionState);
898 case PROCESSING_INSTRUCTION_NODE:
899 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), exceptionState);
901 return createComment(importedNode->nodeValue());
902 case DOCUMENT_TYPE_NODE: {
903 DocumentType* doctype = toDocumentType(importedNode);
904 return DocumentType::create(this, doctype->name(), doctype->publicId(), doctype->systemId());
907 Element* oldElement = toElement(importedNode);
908 // FIXME: The following check might be unnecessary. Is it possible that
909 // oldElement has mismatched prefix/namespace?
910 if (!hasValidNamespaceForElements(oldElement->tagQName())) {
911 exceptionState.throwDOMException(NamespaceError, "The imported node has an invalid namespace.");
914 RefPtr<Element> newElement = createElement(oldElement->tagQName(), false);
916 newElement->cloneDataFromElement(*oldElement);
919 for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
920 RefPtr<Node> newChild = importNode(oldChild, true, exceptionState);
921 if (exceptionState.hadException())
923 newElement->appendChild(newChild.release(), exceptionState);
924 if (exceptionState.hadException())
929 return newElement.release();
932 return Attr::create(*this, QualifiedName(nullAtom, AtomicString(toAttr(importedNode)->name()), nullAtom), toAttr(importedNode)->value());
933 case DOCUMENT_FRAGMENT_NODE: {
934 if (importedNode->isShadowRoot()) {
935 // ShadowRoot nodes should not be explicitly importable.
936 // Either they are imported along with their host node, or created implicitly.
937 exceptionState.throwDOMException(NotSupportedError, "The node provided is a shadow root, which may not be imported.");
940 DocumentFragment* oldFragment = toDocumentFragment(importedNode);
941 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
943 for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
944 RefPtr<Node> newChild = importNode(oldChild, true, exceptionState);
945 if (exceptionState.hadException())
947 newFragment->appendChild(newChild.release(), exceptionState);
948 if (exceptionState.hadException())
953 return newFragment.release();
956 exceptionState.throwDOMException(NotSupportedError, "The node provided is a document, which may not be imported.");
960 ASSERT_NOT_REACHED();
964 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionState& exceptionState)
967 exceptionState.throwDOMException(NotSupportedError, "The node provided is invalid.");
971 EventQueueScope scope;
973 switch (source->nodeType()) {
975 case DOCUMENT_TYPE_NODE:
976 exceptionState.throwDOMException(NotSupportedError, "The node provided is of type '" + source->nodeName() + "', which may not be adopted.");
978 case ATTRIBUTE_NODE: {
979 Attr* attr = toAttr(source.get());
980 if (attr->ownerElement())
981 attr->ownerElement()->removeAttributeNode(attr, exceptionState);
985 if (source->isShadowRoot()) {
986 // ShadowRoot cannot disconnect itself from the host node.
987 exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a shadow root, which may not be adopted.");
991 if (source->isFrameOwnerElement()) {
992 HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
993 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement->contentFrame())) {
994 exceptionState.throwDOMException(HierarchyRequestError, "The node provided is a frame which contains this document.");
998 if (source->parentNode()) {
999 source->parentNode()->removeChild(source.get(), exceptionState);
1000 if (exceptionState.hadException())
1005 this->adoptIfNeeded(*source);
1010 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1012 // These checks are from DOM Core Level 2, createElementNS
1013 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1014 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1016 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1019 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1020 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1021 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1022 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1023 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1024 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1027 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1029 return hasValidNamespaceForElements(qName);
1032 // FIXME: This should really be in a possible ElementFactory class
1033 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
1037 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1038 if (qName.namespaceURI() == xhtmlNamespaceURI)
1039 e = HTMLElementFactory::createHTMLElement(qName.localName(), *this, 0, createdByParser);
1040 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
1041 e = SVGElementFactory::createSVGElement(qName.localName(), *this, createdByParser);
1044 m_sawElementsInKnownNamespaces = true;
1046 e = Element::create(qName, this);
1048 if (e->prefix() != qName.prefix())
1049 e->setTagNameForCreateElementNS(qName);
1051 ASSERT(qName == e->tagQName());
1056 bool Document::regionBasedColumnsEnabled() const
1058 return settings() && settings()->regionBasedColumnsEnabled();
1061 String Document::readyState() const
1063 DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
1064 DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
1065 DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
1067 switch (m_readyState) {
1076 ASSERT_NOT_REACHED();
1080 void Document::setReadyState(ReadyState readyState)
1082 if (readyState == m_readyState)
1085 switch (readyState) {
1087 if (!m_documentTiming.domLoading) {
1088 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1089 m_timeline->setZeroTime(m_documentTiming.domLoading);
1093 if (!m_documentTiming.domInteractive)
1094 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1097 if (!m_documentTiming.domComplete)
1098 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1102 m_readyState = readyState;
1103 dispatchEvent(Event::create(EventTypeNames::readystatechange));
1106 bool Document::isLoadCompleted()
1108 return m_readyState == Complete;
1111 AtomicString Document::encodingName() const
1113 // TextEncoding::name() returns a char*, no need to allocate a new
1114 // String for it each time.
1115 // FIXME: We should fix TextEncoding to speak AtomicString anyway.
1116 return AtomicString(encoding().name());
1119 String Document::defaultCharset() const
1121 if (Settings* settings = this->settings())
1122 return settings->defaultTextEncodingName();
1126 void Document::setCharset(const String& charset)
1128 if (DocumentLoader* documentLoader = loader())
1129 documentLoader->setUserChosenEncoding(charset);
1130 WTF::TextEncoding encoding(charset);
1131 // In case the encoding didn't exist, we keep the old one (helps some sites specifying invalid encodings).
1132 if (!encoding.isValid())
1134 DocumentEncodingData newEncodingData = m_encodingData;
1135 newEncodingData.setEncoding(encoding);
1136 setEncodingData(newEncodingData);
1139 void Document::setContentLanguage(const AtomicString& language)
1141 if (m_contentLanguage == language)
1143 m_contentLanguage = language;
1145 // Document's style depends on the content language.
1146 setNeedsStyleRecalc(SubtreeStyleChange);
1149 void Document::setXMLVersion(const String& version, ExceptionState& exceptionState)
1151 if (!implementation()->hasFeature("XML", String())) {
1152 exceptionState.throwDOMException(NotSupportedError, "This document does not support XML.");
1156 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1157 exceptionState.throwDOMException(NotSupportedError, "This document does not support the XML version '" + version + "'.");
1161 m_xmlVersion = version;
1164 void Document::setXMLStandalone(bool standalone, ExceptionState& exceptionState)
1166 if (!implementation()->hasFeature("XML", String())) {
1167 exceptionState.throwDOMException(NotSupportedError, "This document does not support XML.");
1171 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1174 KURL Document::baseURI() const
1179 void Document::setContent(const String& content)
1182 // FIXME: This should probably use insert(), but that's (intentionally)
1183 // not implemented for the XML parser as it's normally synonymous with
1184 // document.write(). append() will end up yielding, but close() will
1185 // pump the tokenizer syncrhonously and finish the parse.
1186 m_parser->pinToMainThread();
1187 m_parser->append(content.impl());
1191 String Document::suggestedMIMEType() const
1193 if (isXMLDocument()) {
1194 if (isXHTMLDocument())
1195 return "application/xhtml+xml";
1196 if (isSVGDocument())
1197 return "image/svg+xml";
1198 return "application/xml";
1200 if (xmlStandalone())
1202 if (isHTMLDocument())
1205 if (DocumentLoader* documentLoader = loader())
1206 return documentLoader->responseMIMEType();
1210 Element* Document::elementFromPoint(int x, int y) const
1215 return TreeScope::elementFromPoint(x, y);
1218 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1222 HitTestResult result = hitTestInDocument(this, x, y);
1223 RenderObject* renderer = result.renderer();
1227 Node* node = renderer->node();
1228 Node* shadowAncestorNode = ancestorInThisScope(node);
1229 if (shadowAncestorNode != node) {
1230 unsigned offset = shadowAncestorNode->nodeIndex();
1231 ContainerNode* container = shadowAncestorNode->parentNode();
1232 return Range::create(*this, container, offset, container, offset);
1235 PositionWithAffinity positionWithAffinity = renderer->positionForPoint(result.localPoint());
1236 if (positionWithAffinity.position().isNull())
1239 Position rangeCompliantPosition = positionWithAffinity.position().parentAnchoredEquivalent();
1240 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1244 * Performs three operations:
1245 * 1. Convert control characters to spaces
1246 * 2. Trim leading and trailing spaces
1247 * 3. Collapse internal whitespace.
1249 template <typename CharacterType>
1250 static inline String canonicalizedTitle(Document* document, const String& title)
1252 const CharacterType* characters = title.getCharacters<CharacterType>();
1253 unsigned length = title.length();
1256 StringBuffer<CharacterType> buffer(length);
1257 unsigned builderIndex = 0;
1259 // Skip leading spaces and leading characters that would convert to spaces
1260 for (i = 0; i < length; ++i) {
1261 CharacterType c = characters[i];
1262 if (!(c <= 0x20 || c == 0x7F))
1269 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1270 bool previousCharWasWS = false;
1271 for (; i < length; ++i) {
1272 CharacterType c = characters[i];
1273 if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1274 if (previousCharWasWS)
1276 buffer[builderIndex++] = ' ';
1277 previousCharWasWS = true;
1279 buffer[builderIndex++] = c;
1280 previousCharWasWS = false;
1284 // Strip trailing spaces
1285 while (builderIndex > 0) {
1287 if (buffer[builderIndex] != ' ')
1291 if (!builderIndex && buffer[builderIndex] == ' ')
1294 buffer.shrink(builderIndex + 1);
1296 return String::adopt(buffer);
1299 void Document::updateTitle(const String& title)
1301 if (m_rawTitle == title)
1306 String oldTitle = m_title;
1307 if (m_rawTitle.isEmpty())
1309 else if (m_rawTitle.is8Bit())
1310 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1312 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1314 if (!m_frame || oldTitle == m_title)
1316 m_frame->loader().client()->dispatchDidReceiveTitle(m_title);
1319 void Document::setTitle(const String& title)
1321 // Title set by JavaScript -- overrides any title elements.
1322 m_titleSetExplicitly = true;
1323 if (!isHTMLDocument() && !isXHTMLDocument())
1325 else if (!m_titleElement) {
1326 if (HTMLElement* headElement = head()) {
1327 m_titleElement = HTMLTitleElement::create(*this);
1328 headElement->appendChild(m_titleElement);
1332 if (m_titleElement && m_titleElement->hasTagName(titleTag))
1333 toHTMLTitleElement(m_titleElement)->setText(title);
1338 void Document::setTitleElement(const String& title, Element* titleElement)
1340 if (titleElement != m_titleElement) {
1341 if (m_titleElement || m_titleSetExplicitly)
1342 // Only allow the first title element to change the title -- others have no effect.
1344 m_titleElement = titleElement;
1350 void Document::removeTitle(Element* titleElement)
1352 if (m_titleElement != titleElement)
1356 m_titleSetExplicitly = false;
1358 // FIXME: This is broken for SVG.
1359 // Update title based on first title element in the head, if one exists.
1360 if (HTMLElement* headElement = head()) {
1361 for (Element* element = ElementTraversal::firstWithin(*headElement); element; element = ElementTraversal::nextSibling(*element)) {
1362 if (!element->hasTagName(titleTag))
1364 HTMLTitleElement* title = toHTMLTitleElement(element);
1365 setTitleElement(title->text(), title);
1370 if (!m_titleElement)
1371 updateTitle(String());
1374 PageVisibilityState Document::pageVisibilityState() const
1376 // The visibility of the document is inherited from the visibility of the
1377 // page. If there is no page associated with the document, we will assume
1378 // that the page is hidden, as specified by the spec:
1379 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1380 if (!m_frame || !m_frame->page())
1381 return PageVisibilityStateHidden;
1382 return m_frame->page()->visibilityState();
1385 String Document::visibilityState() const
1387 return pageVisibilityStateString(pageVisibilityState());
1390 bool Document::hidden() const
1392 return pageVisibilityState() != PageVisibilityStateVisible;
1395 void Document::didChangeVisibilityState()
1397 dispatchEvent(Event::create(EventTypeNames::visibilitychange));
1398 // Also send out the deprecated version until it can be removed.
1399 dispatchEvent(Event::create(EventTypeNames::webkitvisibilitychange));
1401 PageVisibilityState state = pageVisibilityState();
1402 HashSet<DocumentVisibilityObserver*>::const_iterator observerEnd = m_visibilityObservers.end();
1403 for (HashSet<DocumentVisibilityObserver*>::const_iterator it = m_visibilityObservers.begin(); it != observerEnd; ++it)
1404 (*it)->didChangeVisibilityState(state);
1407 void Document::registerVisibilityObserver(DocumentVisibilityObserver* observer)
1409 ASSERT(!m_visibilityObservers.contains(observer));
1410 m_visibilityObservers.add(observer);
1413 void Document::unregisterVisibilityObserver(DocumentVisibilityObserver* observer)
1415 ASSERT(m_visibilityObservers.contains(observer));
1416 m_visibilityObservers.remove(observer);
1419 String Document::nodeName() const
1424 Node::NodeType Document::nodeType() const
1426 return DOCUMENT_NODE;
1429 FormController* Document::formController()
1431 if (!m_formController)
1432 m_formController = FormController::create();
1433 return m_formController.get();
1436 Vector<String> Document::formElementsState() const
1438 if (!m_formController)
1439 return Vector<String>();
1440 return m_formController->formElementsState();
1443 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1445 if (!stateVector.size() && !m_formController)
1447 formController()->setStateForNewFormElements(stateVector);
1450 FrameView* Document::view() const
1452 return m_frame ? m_frame->view() : 0;
1455 Page* Document::page() const
1457 return m_frame ? m_frame->page() : 0;
1460 FrameHost* Document::frameHost() const
1462 return m_frame ? m_frame->host() : 0;
1465 Settings* Document::settings() const
1467 return m_frame ? m_frame->settings() : 0;
1470 PassRefPtr<Range> Document::createRange()
1472 return Range::create(*this);
1475 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionState& exceptionState)
1477 // FIXME: Probably this should be handled within the bindings layer and TypeError should be thrown.
1479 exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
1482 return NodeIterator::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
1485 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
1488 exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
1491 // FIXME: It might be a good idea to emit a warning if |whatToShow| contains a bit that is not defined in
1493 return NodeIterator::create(root, whatToShow, PassRefPtr<NodeFilter>());
1496 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
1499 exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
1503 return NodeIterator::create(root, whatToShow, filter);
1506 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionState& exceptionState)
1509 exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
1512 return TreeWalker::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
1515 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
1518 exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
1521 return TreeWalker::create(root, whatToShow, PassRefPtr<NodeFilter>());
1524 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
1527 exceptionState.throwDOMException(NotSupportedError, "The provided node is invalid.");
1530 return TreeWalker::create(root, whatToShow, filter);
1533 bool Document::shouldCallRecalcStyleForDocument()
1535 if (!isActive() || !view())
1537 return needsStyleRecalc() || childNeedsStyleRecalc() || childNeedsDistributionRecalc() || !m_useElementsNeedingUpdate.isEmpty() || childNeedsStyleInvalidation();
1540 bool Document::shouldScheduleStyleRecalc()
1544 if (hasPendingStyleRecalc())
1546 if (inStyleRecalc())
1548 // InPreLayout will recalc style itself. There's no reason to schedule another recalc.
1549 if (m_lifecycle.state() == DocumentLifecycle::InPreLayout)
1551 if (!shouldScheduleLayout())
1556 void Document::scheduleStyleRecalc()
1558 if (!shouldScheduleStyleRecalc())
1561 ASSERT(shouldCallRecalcStyleForDocument());
1563 if (!view()->isServicingAnimations())
1564 view()->scheduleAnimation();
1565 m_lifecycle.advanceTo(DocumentLifecycle::StyleRecalcPending);
1567 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1570 bool Document::hasPendingForcedStyleRecalc() const
1572 return hasPendingStyleRecalc() && !inStyleRecalc() && styleChangeType() >= SubtreeStyleChange;
1575 void Document::updateDistributionIfNeeded()
1577 if (!childNeedsDistributionRecalc())
1579 TRACE_EVENT0("webkit", "Document::recalcDistribution");
1580 recalcDistribution();
1583 void Document::updateStyleInvalidationIfNeeded()
1585 if (!childNeedsStyleInvalidation())
1587 TRACE_EVENT0("webkit", "Document::computeNeedsStyleRecalcState");
1588 if (!styleResolver()) {
1589 clearChildNeedsStyleInvalidation();
1593 // FIXME: the style resolver can be deleted at present. Either resolve
1594 // crbug.com/335964 or move the invalidation data elsewhere.
1595 styleResolver()->ensureRuleFeatureSet().computeStyleInvalidation(*this);
1598 void Document::updateDistributionForNodeIfNeeded(Node* node)
1600 if (node->inDocument()) {
1601 updateDistributionIfNeeded();
1605 while (Node* host = root->shadowHost())
1607 while (Node* ancestor = root->parentOrShadowHostNode())
1609 if (root->childNeedsDistributionRecalc())
1610 root->recalcDistribution();
1613 void Document::setupFontBuilder(RenderStyle* documentStyle)
1615 FontBuilder fontBuilder;
1616 fontBuilder.initForStyleResolve(*this, documentStyle, isSVGDocument());
1617 RefPtr<CSSFontSelector> selector = m_styleEngine->fontSelector();
1618 fontBuilder.createFontForDocument(selector, documentStyle);
1621 void Document::inheritHtmlAndBodyElementStyles(StyleRecalcChange change)
1623 ASSERT(inStyleRecalc());
1624 ASSERT(documentElement());
1626 RefPtr<RenderStyle> documentElementStyle = documentElement()->renderStyle();
1627 if (!documentElementStyle || documentElement()->needsStyleRecalc() || change == Force)
1628 documentElementStyle = ensureStyleResolver().styleForElement(documentElement());
1630 WritingMode rootWritingMode = documentElementStyle->writingMode();
1631 TextDirection rootDirection = documentElementStyle->direction();
1633 HTMLElement* body = this->body();
1634 RefPtr<RenderStyle> bodyStyle;
1636 bodyStyle = body->renderStyle();
1637 if (!bodyStyle || body->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
1638 bodyStyle = ensureStyleResolver().styleForElement(body, documentElementStyle.get());
1639 if (!writingModeSetOnDocumentElement())
1640 rootWritingMode = bodyStyle->writingMode();
1641 if (!directionSetOnDocumentElement())
1642 rootDirection = bodyStyle->direction();
1645 RefPtr<RenderStyle> overflowStyle;
1646 if (Element* element = viewportDefiningElement(documentElementStyle.get())) {
1647 if (element == body) {
1648 overflowStyle = bodyStyle;
1650 ASSERT(element == documentElement());
1651 overflowStyle = documentElementStyle;
1655 // Resolved rem units are stored in the matched properties cache so we need to make sure to
1656 // invalidate the cache if the documentElement needed to reattach or the font size changed
1657 // and then trigger a full document recalc. We also need to clear it here since the
1658 // call to styleForElement on the body above can cache bad values for rem units if the
1659 // documentElement's style was dirty. We could keep track of which elements depend on
1660 // rem units like we do for viewport styles, but we assume root font size changes are
1661 // rare and just invalidate the cache for now.
1662 if (styleEngine()->usesRemUnits() && (documentElement()->needsAttach() || documentElement()->computedStyle()->fontSize() != documentElementStyle->fontSize())) {
1663 ensureStyleResolver().invalidateMatchedPropertiesCache();
1664 documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
1667 RefPtr<RenderStyle> documentStyle = renderView()->style();
1668 if (documentStyle->writingMode() != rootWritingMode
1669 || documentStyle->direction() != rootDirection
1670 || (overflowStyle && (documentStyle->overflowX() != overflowStyle->overflowX() || documentStyle->overflowY() != overflowStyle->overflowY()))) {
1671 RefPtr<RenderStyle> newStyle = RenderStyle::clone(documentStyle.get());
1672 newStyle->setWritingMode(rootWritingMode);
1673 newStyle->setDirection(rootDirection);
1674 EOverflow overflowX = OAUTO;
1675 EOverflow overflowY = OAUTO;
1676 if (overflowStyle) {
1677 overflowX = overflowStyle->overflowX();
1678 overflowY = overflowStyle->overflowY();
1679 // Visible overflow on the viewport is meaningless, and the spec says to treat it as 'auto':
1680 if (overflowX == OVISIBLE)
1682 if (overflowY == OVISIBLE)
1685 // Column-gap is (ab)used by the current paged overflow implementation (in lack of other
1686 // ways to specify gaps between pages), so we have to propagate it too.
1687 newStyle->setColumnGap(overflowStyle->columnGap());
1689 newStyle->setOverflowX(overflowX);
1690 newStyle->setOverflowY(overflowY);
1691 renderView()->setStyle(newStyle);
1692 setupFontBuilder(newStyle.get());
1696 if (RenderStyle* style = body->renderStyle()) {
1697 if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
1698 body->setNeedsStyleRecalc(SubtreeStyleChange);
1702 if (RenderStyle* style = documentElement()->renderStyle()) {
1703 if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
1704 documentElement()->setNeedsStyleRecalc(SubtreeStyleChange);
1708 void Document::updateStyleIfNeeded()
1710 updateStyle(NoChange);
1713 // FIXME: We need a better name than updateStyleIfNeeded. It's performing style invalidation,
1714 // style recalc, distribution and <use> shadow tree creation.
1715 void Document::updateStyle(StyleRecalcChange change)
1717 ASSERT(isMainThread());
1719 if (!shouldCallRecalcStyleForDocument())
1722 if (inStyleRecalc())
1725 // Entering here from inside layout or paint would be catastrophic since recalcStyle can
1726 // tear down the render tree or (unfortunately) run script. Kill the whole renderer if
1727 // someone managed to get into here from inside layout or paint.
1728 RELEASE_ASSERT(!view()->isInPerformLayout());
1729 RELEASE_ASSERT(!view()->isPainting());
1731 // Script can run below in PostAttachCallbacks or WidgetUpdates, so protect the Frame.
1732 RefPtr<Frame> protect(m_frame);
1734 TRACE_EVENT0("webkit", "Document::recalcStyle");
1735 TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "RecalcStyle");
1737 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1739 updateDistributionIfNeeded();
1740 updateUseShadowTreesIfNeeded();
1741 updateStyleInvalidationIfNeeded();
1743 if (m_evaluateMediaQueriesOnStyleRecalc) {
1744 m_evaluateMediaQueriesOnStyleRecalc = false;
1745 evaluateMediaQueryList();
1748 // FIXME: We should update style on our ancestor chain before proceeding
1749 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1750 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1751 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1752 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1753 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1755 if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
1756 m_styleEngine->setUsesRemUnit(true);
1759 PostAttachCallbacks::SuspendScope suspendPostAttachCallbacks;
1760 RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
1761 m_lifecycle.advanceTo(DocumentLifecycle::InStyleRecalc);
1763 if (styleChangeType() >= SubtreeStyleChange)
1766 // FIXME: Cannot access the ensureStyleResolver() before calling styleForDocument below because
1767 // apparently the StyleResolver's constructor has side effects. We should fix it.
1768 // See printing/setPrinting.html, printing/width-overflow.html though they only fail on
1769 // mac when accessing the resolver by what appears to be a viewport size difference.
1771 if (change == Force) {
1772 m_hasNodesWithPlaceholderStyle = false;
1773 RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this, m_styleEngine->fontSelector());
1774 StyleRecalcChange localChange = RenderStyle::compare(documentStyle.get(), renderView()->style());
1775 if (localChange != NoChange)
1776 renderView()->setStyle(documentStyle.release());
1779 clearNeedsStyleRecalc();
1781 // Uncomment to enable printing of statistics about style sharing and the matched property cache.
1782 // Optionally pass StyleResolver::ReportSlowStats to print numbers that require crawling the
1783 // entire DOM (where collecting them is very slow).
1784 // FIXME: Expose this as a runtime flag.
1785 // ensureStyleResolver().enableStats(/*StyleResolver::ReportSlowStats*/);
1787 if (StyleResolverStats* stats = ensureStyleResolver().stats())
1790 if (Element* documentElement = this->documentElement()) {
1791 inheritHtmlAndBodyElementStyles(change);
1792 if (documentElement->shouldCallRecalcStyle(change))
1793 documentElement->recalcStyle(change);
1796 ensureStyleResolver().printStats();
1798 view()->updateCompositingLayersAfterStyleChange();
1800 clearChildNeedsStyleRecalc();
1802 if (m_styleEngine->hasResolver()) {
1803 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1804 StyleResolver& resolver = m_styleEngine->ensureResolver();
1805 m_styleEngine->resetCSSFeatureFlags(resolver.ensureRuleFeatureSet());
1806 resolver.clearStyleSharingList();
1809 ASSERT(!needsStyleRecalc());
1810 ASSERT(!childNeedsStyleRecalc());
1811 ASSERT(inStyleRecalc());
1812 m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
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();
1821 if (m_focusedElement && !m_focusedElement->isFocusable())
1822 clearFocusedElementSoon();
1824 DocumentAnimations::serviceAfterStyleRecalc(*this);
1826 InspectorInstrumentation::didRecalculateStyle(cookie);
1829 void Document::updateStyleForNodeIfNeeded(Node* node)
1831 if (!shouldCallRecalcStyleForDocument())
1834 // At this point, we know that we need to recalc some style on the document in order to fully update styles.
1835 // However, style on 'node' only needs to be recalculated if a global recomputation is needed, or a node on
1836 // the path from 'node' to the root needs style recalc.
1839 bool needsRecalc = needsStyleRecalc() || childNeedsDistributionRecalc() || !m_useElementsNeedingUpdate.isEmpty() || childNeedsStyleInvalidation();
1842 for (Node* ancestor = node; ancestor && !needsRecalc; ancestor = ancestor->parentOrShadowHostNode())
1843 needsRecalc = ancestor->needsStyleRecalc();
1845 updateStyleIfNeeded();
1848 void Document::updateLayout()
1850 ASSERT(isMainThread());
1852 RefPtr<FrameView> frameView = view();
1853 if (frameView && frameView->isInPerformLayout()) {
1854 // View layout should not be re-entrant.
1855 ASSERT_NOT_REACHED();
1859 if (Element* oe = ownerElement())
1860 oe->document().updateLayout();
1862 updateStyleIfNeeded();
1864 // Only do a layout if changes have occurred that make it necessary.
1865 if (isActive() && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1866 frameView->layout();
1868 if (isActive() && frameView)
1869 frameView->partialLayout().reset();
1872 void Document::setNeedsFocusedElementCheck()
1874 setNeedsStyleRecalc(LocalStyleChange);
1877 void Document::clearFocusedElementSoon()
1879 if (!m_clearFocusedElementTimer.isActive())
1880 m_clearFocusedElementTimer.startOneShot(0);
1883 void Document::clearFocusedElementTimerFired(Timer<Document>*)
1885 updateStyleIfNeeded();
1886 m_clearFocusedElementTimer.stop();
1888 if (m_focusedElement && !m_focusedElement->isFocusable())
1889 setFocusedElement(0);
1892 void Document::recalcStyleForLayoutIgnoringPendingStylesheets()
1894 ASSERT(m_styleEngine->ignoringPendingStylesheets());
1896 if (!m_styleEngine->hasPendingSheets())
1899 // FIXME: We are willing to attempt to suppress painting with outdated style info only once.
1900 // Our assumption is that it would be dangerous to try to stop it a second time, after page
1901 // content has already been loaded and displayed with accurate style information. (Our
1902 // suppression involves blanking the whole page at the moment. If it were more refined, we
1903 // might be able to do something better.) It's worth noting though that this entire method
1904 // is a hack, since what we really want to do is suspend JS instead of doing a layout with
1905 // inaccurate information.
1906 HTMLElement* bodyElement = body();
1907 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1908 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1909 styleResolverChanged(RecalcStyleImmediately);
1910 } else if (m_hasNodesWithPlaceholderStyle) {
1911 // If new nodes have been added or style recalc has been done with style sheets still
1912 // pending, some nodes may not have had their real style calculated yet. Normally this
1913 // gets cleaned when style sheets arrive but here we need up-to-date style immediately.
1918 // FIXME: This is a bad idea and needs to be removed eventually.
1919 // Other browsers load stylesheets before they continue parsing the web page.
1920 // Since we don't, we can run JavaScript code that needs answers before the
1921 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1922 // lets us get reasonable answers. The long term solution to this problem is
1923 // to instead suspend JavaScript execution.
1924 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
1926 StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
1927 recalcStyleForLayoutIgnoringPendingStylesheets();
1929 if (runPostLayoutTasks == RunPostLayoutTasksSynchronously && view())
1930 view()->flushAnyPendingPostLayoutTasks();
1933 void Document::partialUpdateLayoutIgnorePendingStylesheets(Node* stopLayoutAtNode)
1935 // Non-overlay scrollbars can cause a second layout that is dependent
1936 // on a first layout. This is disabled for partial layout for now.
1937 if (!RuntimeEnabledFeatures::partialLayoutEnabled() || !ScrollbarTheme::theme()->usesOverlayScrollbars()) {
1938 updateLayoutIgnorePendingStylesheets();
1942 StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
1943 recalcStyleForLayoutIgnoringPendingStylesheets();
1945 if (stopLayoutAtNode) {
1946 RenderObject* renderer = stopLayoutAtNode->renderer();
1947 bool canPartialLayout = renderer;
1949 if (!renderer->supportsPartialLayout()) {
1950 canPartialLayout = false;
1953 renderer = renderer->parent();
1955 if (canPartialLayout && view())
1956 view()->partialLayout().setStopAtRenderer(stopLayoutAtNode->renderer());
1962 view()->partialLayout().reset();
1965 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1967 ASSERT_ARG(element, element->document() == this);
1968 StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
1969 return ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
1972 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
1974 return ensureStyleResolver().styleForPage(pageIndex);
1977 bool Document::isPageBoxVisible(int pageIndex)
1979 return styleForPage(pageIndex)->visibility() != HIDDEN; // display property doesn't apply to @page.
1982 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1984 RefPtr<RenderStyle> style = styleForPage(pageIndex);
1986 int width = pageSize.width();
1987 int height = pageSize.height();
1988 switch (style->pageSizeType()) {
1989 case PAGE_SIZE_AUTO:
1991 case PAGE_SIZE_AUTO_LANDSCAPE:
1993 std::swap(width, height);
1995 case PAGE_SIZE_AUTO_PORTRAIT:
1997 std::swap(width, height);
1999 case PAGE_SIZE_RESOLVED: {
2000 LengthSize size = style->pageSize();
2001 ASSERT(size.width().isFixed());
2002 ASSERT(size.height().isFixed());
2003 width = valueForLength(size.width(), 0);
2004 height = valueForLength(size.height(), 0);
2008 ASSERT_NOT_REACHED();
2010 pageSize = IntSize(width, height);
2012 // The percentage is calculated with respect to the width even for margin top and bottom.
2013 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2014 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2015 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2016 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2017 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2020 void Document::setIsViewSource(bool isViewSource)
2022 m_isViewSource = isViewSource;
2023 if (!m_isViewSource)
2026 setSecurityOrigin(SecurityOrigin::createUnique());
2027 didUpdateSecurityOrigin();
2030 void Document::scheduleUseShadowTreeUpdate(SVGUseElement& element)
2032 m_useElementsNeedingUpdate.add(&element);
2033 scheduleStyleRecalc();
2036 void Document::unscheduleUseShadowTreeUpdate(SVGUseElement& element)
2038 m_useElementsNeedingUpdate.remove(&element);
2041 void Document::updateUseShadowTreesIfNeeded()
2043 if (m_useElementsNeedingUpdate.isEmpty())
2046 Vector<SVGUseElement*> elements;
2047 copyToVector(m_useElementsNeedingUpdate, elements);
2048 m_useElementsNeedingUpdate.clear();
2050 Vector<SVGUseElement*>::iterator end = elements.end();
2051 for (Vector<SVGUseElement*>::iterator it = elements.begin(); it != end; ++it)
2052 (*it)->buildPendingResource();
2055 StyleResolver* Document::styleResolver() const
2057 return m_styleEngine->resolver();
2060 StyleResolver& Document::ensureStyleResolver() const
2062 return m_styleEngine->ensureResolver();
2065 void Document::clearStyleResolver()
2067 m_styleEngine->clearResolver();
2070 void Document::attach(const AttachContext& context)
2072 ASSERT(m_lifecycle.state() == DocumentLifecycle::Inactive);
2073 ASSERT(!m_axObjectCache || this != topDocument());
2075 m_renderView = new RenderView(this);
2076 setRenderer(m_renderView);
2078 m_renderView->setIsInWindow(true);
2079 m_renderView->setStyle(StyleResolver::styleForDocument(*this));
2080 view()->updateCompositingLayersAfterStyleChange();
2082 ContainerNode::attach(context);
2084 m_lifecycle.advanceTo(DocumentLifecycle::StyleClean);
2087 void Document::detach(const AttachContext& context)
2090 m_lifecycle.advanceTo(DocumentLifecycle::Stopping);
2093 page()->documentDetached(this);
2095 if (m_frame->loader().client()->sharedWorkerRepositoryClient())
2096 m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this);
2098 if (this == topDocument())
2099 clearAXObjectCache();
2101 stopActiveDOMObjects();
2103 // FIXME: consider using ActiveDOMObject.
2104 if (m_scriptedAnimationController)
2105 m_scriptedAnimationController->clearDocumentPointer();
2106 m_scriptedAnimationController.clear();
2108 if (svgExtensions())
2109 accessSVGExtensions()->pauseAnimations();
2111 // FIXME: This shouldn't be needed once DOMWindow becomes ExecutionContext.
2113 m_domWindow->clearEventQueue();
2115 RenderView* renderView = m_renderView;
2118 renderView->setIsInWindow(false);
2121 FrameView* view = m_frame->view();
2123 view->detachCustomScrollbars();
2126 // Indicate destruction mode by setting the renderer to null.
2127 // FIXME: Don't do this and use m_lifecycle.state() == Stopping instead.
2132 m_focusedElement = 0;
2133 m_activeHoverElement = 0;
2134 m_autofocusElement = 0;
2136 ContainerNode::detach(context);
2138 m_styleEngine->didDetach();
2141 renderView->destroy();
2143 if (Document* parentDoc = parentDocument())
2144 parentDoc->didClearTouchEventHandlers(this);
2146 // This is required, as our Frame might delete itself as soon as it detaches
2147 // us. However, this violates Node::detach() semantics, as it's never
2148 // possible to re-attach. Eventually Document::detach() should be renamed,
2149 // or this setting of the frame to 0 could be made explicit in each of the
2150 // callers of Document::detach().
2153 if (m_mediaQueryMatcher)
2154 m_mediaQueryMatcher->documentDestroyed();
2156 lifecycleNotifier().notifyDocumentWasDetached();
2157 m_lifecycle.advanceTo(DocumentLifecycle::Stopped);
2160 void Document::prepareForDestruction()
2162 m_markers->prepareForDestruction();
2163 disconnectDescendantFrames();
2165 // The process of disconnecting descendant frames could have already detached us.
2169 if (DOMWindow* window = this->domWindow())
2170 window->willDetachDocumentFromFrame();
2174 void Document::removeAllEventListeners()
2176 ContainerNode::removeAllEventListeners();
2178 if (DOMWindow* domWindow = this->domWindow())
2179 domWindow->removeAllEventListeners();
2180 for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
2181 node->removeAllEventListeners();
2184 void Document::clearAXObjectCache()
2186 ASSERT(topDocument() == this);
2187 // Clear the cache member variable before calling delete because attempts
2188 // are made to access it during destruction.
2189 m_axObjectCache.clear();
2192 AXObjectCache* Document::existingAXObjectCache() const
2194 if (!AXObjectCache::accessibilityEnabled())
2197 // If the renderer is gone then we are in the process of destruction.
2198 // This method will be called before m_frame = 0.
2199 if (!topDocument()->renderView())
2202 return topDocument()->m_axObjectCache.get();
2205 AXObjectCache* Document::axObjectCache() const
2207 if (!AXObjectCache::accessibilityEnabled())
2210 // The only document that actually has a AXObjectCache is the top-level
2211 // document. This is because we need to be able to get from any WebCoreAXObject
2212 // to any other WebCoreAXObject on the same page. Using a single cache allows
2213 // lookups across nested webareas (i.e. multiple documents).
2214 Document* topDocument = this->topDocument();
2216 // If the document has already been detached, do not make a new axObjectCache.
2217 if (!topDocument->renderView())
2220 ASSERT(topDocument == this || !m_axObjectCache);
2221 if (!topDocument->m_axObjectCache)
2222 topDocument->m_axObjectCache = adoptPtr(new AXObjectCache(topDocument));
2223 return topDocument->m_axObjectCache.get();
2226 PassRefPtr<DocumentParser> Document::createParser()
2228 if (isHTMLDocument()) {
2229 bool reportErrors = InspectorInstrumentation::collectingHTMLParseErrors(page());
2230 return HTMLDocumentParser::create(toHTMLDocument(this), reportErrors);
2232 // FIXME: this should probably pass the frame instead
2233 return XMLDocumentParser::create(this, view());
2236 bool Document::isFrameSet() const
2238 if (!isHTMLDocument())
2240 HTMLElement* bodyElement = body();
2241 return bodyElement && bodyElement->hasTagName(framesetTag);
2244 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2246 return parser() ? parser()->asScriptableDocumentParser() : 0;
2249 void Document::open(Document* ownerDocument)
2251 if (ownerDocument) {
2252 setURL(ownerDocument->url());
2253 m_cookieURL = ownerDocument->cookieURL();
2254 setSecurityOrigin(ownerDocument->securityOrigin());
2258 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2259 if (parser->isParsing()) {
2260 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2261 if (parser->isExecutingScript())
2264 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2269 if (m_frame->loader().state() == FrameStateProvisional)
2270 m_frame->loader().stopAllLoaders();
2273 removeAllEventListeners();
2275 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2276 parser->setWasCreatedByScript(true);
2279 m_frame->loader().didExplicitOpen();
2280 if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
2281 m_loadEventProgress = LoadEventNotRun;
2284 void Document::detachParser()
2292 void Document::cancelParsing()
2297 // We have to clear the parser to avoid possibly triggering
2298 // the onload handler when closing as a side effect of a cancel-style
2299 // change, such as opening a new document or closing the window while
2305 PassRefPtr<DocumentParser> Document::implicitOpen()
2310 ASSERT(!m_focusedElement);
2312 setCompatibilityMode(NoQuirksMode);
2314 m_parser = createParser();
2316 setReadyState(Loading);
2321 HTMLElement* Document::body() const
2323 if (!documentElement())
2326 for (Node* child = documentElement()->firstChild(); child; child = child->nextSibling()) {
2327 if (child->hasTagName(framesetTag) || child->hasTagName(bodyTag))
2328 return toHTMLElement(child);
2334 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionState& exceptionState)
2336 RefPtr<HTMLElement> newBody = prpNewBody;
2339 exceptionState.throwDOMException(HierarchyRequestError, "The node provided is invalid.");
2342 if (!documentElement()) {
2343 exceptionState.throwDOMException(HierarchyRequestError, "No document element exists.");
2347 if (!newBody->hasTagName(bodyTag) && !newBody->hasTagName(framesetTag)) {
2348 exceptionState.throwDOMException(HierarchyRequestError, "The new body element is of type '" + newBody->tagName() + "'. It must be either a 'BODY' or 'FRAMESET' element.");
2352 HTMLElement* oldBody = body();
2353 if (oldBody == newBody)
2357 documentElement()->replaceChild(newBody.release(), oldBody, exceptionState);
2359 documentElement()->appendChild(newBody.release(), exceptionState);
2362 HTMLHeadElement* Document::head()
2364 Node* de = documentElement();
2368 for (Node* node = de->firstChild(); node; node = node->nextSibling()) {
2369 if (node->hasTagName(headTag))
2370 return toHTMLHeadElement(node);
2375 Element* Document::viewportDefiningElement(RenderStyle* rootStyle) const
2377 // If a BODY element sets non-visible overflow, it is to be propagated to the viewport, as long
2378 // as the following conditions are all met:
2379 // (1) The root element is HTML.
2380 // (2) It is the primary BODY element (we only assert for this, expecting callers to behave).
2381 // (3) The root element has visible overflow.
2382 // Otherwise it's the root element's properties that are to be propagated.
2383 Element* rootElement = documentElement();
2384 Element* bodyElement = body();
2388 rootStyle = rootElement->renderStyle();
2392 if (bodyElement && rootStyle->isOverflowVisible() && rootElement->hasTagName(htmlTag))
2397 void Document::close()
2399 // FIXME: We should follow the specification more closely:
2400 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2402 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2408 void Document::explicitClose()
2410 if (RefPtr<DocumentParser> parser = m_parser)
2414 // Because we have no frame, we don't know if all loading has completed,
2415 // so we just call implicitClose() immediately. FIXME: This might fire
2416 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2421 m_frame->loader().checkCompleted();
2424 void Document::implicitClose()
2426 ASSERT(!inStyleRecalc());
2428 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2429 bool doload = !parsing() && m_parser && !processingLoadEvent() && !wasLocationChangePending;
2431 // If the load was blocked because of a pending location change and the location change triggers a same document
2432 // navigation, don't fire load events after the same document navigation completes (unless there's an explicit open).
2433 m_loadEventProgress = LoadEventTried;
2438 // The call to dispatchWindowLoadEvent can detach the DOMWindow and cause it (and its
2439 // attached Document) to be destroyed.
2440 RefPtr<DOMWindow> protectedWindow(this->domWindow());
2442 m_loadEventProgress = LoadEventInProgress;
2444 ScriptableDocumentParser* parser = scriptableDocumentParser();
2445 m_wellFormed = parser && parser->wellFormed();
2447 // We have to clear the parser, in case someone document.write()s from the
2448 // onLoad event handler, as in Radar 3206524.
2451 if (frame() && frame()->script().canExecuteScripts(NotAboutToExecuteScript)) {
2452 ImageLoader::dispatchPendingBeforeLoadEvents();
2453 ImageLoader::dispatchPendingLoadEvents();
2454 ImageLoader::dispatchPendingErrorEvents();
2456 HTMLLinkElement::dispatchPendingLoadEvents();
2457 HTMLStyleElement::dispatchPendingLoadEvents();
2460 // JS running below could remove the frame or destroy the RenderView so we call
2461 // those two functions repeatedly and don't save them on the stack.
2463 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2464 // here, instead of doing it from SVGElement::finishedParsingChildren.
2465 if (svgExtensions())
2466 accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
2468 if (protectedWindow)
2469 protectedWindow->documentWasClosed();
2472 frame()->loader().client()->dispatchDidHandleOnloadEvents();
2473 loader()->applicationCacheHost()->stopDeferringEvents();
2477 m_loadEventProgress = LoadEventCompleted;
2481 // Make sure both the initial layout and reflow happen after the onload
2482 // fires. This will improve onload scores, and other browsers do it.
2483 // If they wanna cheat, we can too. -dwh
2485 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2486 // Just bail out. Before or during the onload we were shifted to another page.
2487 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2488 m_loadEventProgress = LoadEventCompleted;
2492 // We used to force a synchronous display and flush here. This really isn't
2493 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2494 // (if your platform is syncing flushes and limiting them to 60fps).
2495 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2496 updateStyleIfNeeded();
2498 // Always do a layout after loading if needed.
2499 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2503 m_loadEventProgress = LoadEventCompleted;
2505 if (frame() && renderView() && AXObjectCache::accessibilityEnabled()) {
2506 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2507 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2508 // exists in the cache (we ignore the return value because we don't need it here). This is
2509 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2510 if (AXObjectCache* cache = axObjectCache()) {
2511 cache->getOrCreate(renderView());
2512 if (this == topDocument()) {
2513 cache->postNotification(renderView(), AXObjectCache::AXLoadComplete, true);
2515 // AXLoadComplete can only be posted on the top document, so if it's a document
2516 // in an iframe that just finished loading, post AXLayoutComplete instead.
2517 cache->postNotification(renderView(), AXObjectCache::AXLayoutComplete, true);
2522 if (svgExtensions())
2523 accessSVGExtensions()->startAnimations();
2526 bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigation)
2534 RefPtr<Document> protect(this);
2536 RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
2537 m_loadEventProgress = BeforeUnloadEventInProgress;
2538 m_domWindow->dispatchEvent(beforeUnloadEvent.get(), this);
2539 m_loadEventProgress = BeforeUnloadEventCompleted;
2540 if (!beforeUnloadEvent->defaultPrevented())
2541 defaultEventHandler(beforeUnloadEvent.get());
2542 if (beforeUnloadEvent->returnValue().isNull())
2545 if (didAllowNavigation) {
2546 addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels for a single navigation.");
2550 String text = beforeUnloadEvent->returnValue();
2551 if (chrome.runBeforeUnloadConfirmPanel(text, m_frame)) {
2552 didAllowNavigation = true;
2558 void Document::dispatchUnloadEvents()
2560 RefPtr<Document> protect(this);
2562 m_parser->stopParsing();
2564 if (m_loadEventProgress >= LoadEventTried && m_loadEventProgress <= UnloadEventInProgress) {
2565 Element* currentFocusedElement = focusedElement();
2566 if (currentFocusedElement && currentFocusedElement->hasTagName(inputTag))
2567 toHTMLInputElement(currentFocusedElement)->endEditing();
2568 if (m_loadEventProgress < PageHideInProgress) {
2569 m_loadEventProgress = PageHideInProgress;
2570 if (DOMWindow* window = domWindow())
2571 window->dispatchEvent(PageTransitionEvent::create(EventTypeNames::pagehide, false), this);
2575 // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
2576 // while dispatching the event, so protect it to prevent writing the end
2577 // time into freed memory.
2578 RefPtr<DocumentLoader> documentLoader = m_frame->loader().provisionalDocumentLoader();
2579 m_loadEventProgress = UnloadEventInProgress;
2580 RefPtr<Event> unloadEvent(Event::create(EventTypeNames::unload));
2581 if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
2582 DocumentLoadTiming* timing = documentLoader->timing();
2583 ASSERT(timing->navigationStart());
2584 timing->markUnloadEventStart();
2585 m_frame->domWindow()->dispatchEvent(unloadEvent, this);
2586 timing->markUnloadEventEnd();
2588 m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
2591 m_loadEventProgress = UnloadEventHandled;
2597 // Don't remove event listeners from a transitional empty document (see https://bugs.webkit.org/show_bug.cgi?id=28716 for more information).
2598 bool keepEventListeners = m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader().provisionalDocumentLoader()
2599 && isSecureTransitionTo(m_frame->loader().provisionalDocumentLoader()->url());
2600 if (!keepEventListeners)
2601 removeAllEventListeners();
2604 Document::PageDismissalType Document::pageDismissalEventBeingDispatched() const
2606 if (m_loadEventProgress == BeforeUnloadEventInProgress)
2607 return BeforeUnloadDismissal;
2608 if (m_loadEventProgress == PageHideInProgress)
2609 return PageHideDismissal;
2610 if (m_loadEventProgress == UnloadEventInProgress)
2611 return UnloadDismissal;
2615 void Document::setParsing(bool b)
2619 if (m_isParsing && !m_elementDataCache)
2620 m_elementDataCache = ElementDataCache::create();
2623 bool Document::shouldScheduleLayout()
2625 // This function will only be called when FrameView thinks a layout is needed.
2626 // This enforces a couple extra rules.
2628 // (a) Only schedule a layout once the stylesheets are loaded.
2629 // (b) Only schedule layout once we have a body element.
2631 return (haveStylesheetsLoaded() && body())
2632 || (documentElement() && !documentElement()->hasTagName(htmlTag));
2635 bool Document::shouldParserYieldAgressivelyBeforeScriptExecution()
2637 return view() && view()->layoutPending();
2640 int Document::elapsedTime() const
2642 return static_cast<int>((currentTime() - m_startTime) * 1000);
2645 void Document::write(const SegmentedString& text, Document* ownerDocument)
2647 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2649 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2650 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2652 if (m_writeRecursionIsTooDeep)
2655 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2657 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount) {
2658 addConsoleMessage(JSMessageSource, WarningMessageLevel, ExceptionMessages::failedToExecute("write", "Document", "It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened."));
2662 if (!hasInsertionPoint)
2663 open(ownerDocument);
2666 m_parser->insert(text);
2669 void Document::write(const String& text, Document* ownerDocument)
2671 write(SegmentedString(text), ownerDocument);
2674 void Document::writeln(const String& text, Document* ownerDocument)
2676 write(text, ownerDocument);
2677 write("\n", ownerDocument);
2680 const KURL& Document::virtualURL() const
2685 KURL Document::virtualCompleteURL(const String& url) const
2687 return completeURL(url);
2690 double Document::timerAlignmentInterval() const
2694 return DOMTimer::visiblePageAlignmentInterval();
2695 return p->timerAlignmentInterval();
2698 EventTarget* Document::errorEventTarget()
2703 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
2705 internalAddMessage(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack, 0);
2708 void Document::setURL(const KURL& url)
2710 const KURL& newURL = url.isEmpty() ? blankURL() : url;
2711 if (newURL == m_url)
2716 contextFeatures()->urlDidChange(this);
2719 void Document::updateBaseURL()
2721 KURL oldBaseURL = m_baseURL;
2722 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2723 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2724 // from the Document interface otherwise (which we store, preparsed, in m_url).
2725 if (!m_baseElementURL.isEmpty())
2726 m_baseURL = m_baseElementURL;
2727 else if (!m_baseURLOverride.isEmpty())
2728 m_baseURL = m_baseURLOverride;
2732 selectorQueryCache().invalidate();
2734 if (!m_baseURL.isValid())
2738 // Element sheet is silly. It never contains anything.
2739 ASSERT(!m_elemSheet->contents()->ruleCount());
2740 bool usesRemUnits = m_elemSheet->contents()->usesRemUnits();
2741 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2742 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2743 m_elemSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
2746 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2747 // Base URL change changes any relative visited links.
2748 // FIXME: There are other URLs in the tree that would need to be re-evaluated on dynamic base URL change. Style should be invalidated too.
2749 for (Element* element = ElementTraversal::firstWithin(*this); element; element = ElementTraversal::next(*element)) {
2750 if (element->hasTagName(aTag))
2751 toHTMLAnchorElement(element)->invalidateCachedVisitedLinkHash();
2756 void Document::setBaseURLOverride(const KURL& url)
2758 m_baseURLOverride = url;
2762 void Document::processBaseElement()
2764 // Find the first href attribute in a base element and the first target attribute in a base element.
2765 const AtomicString* href = 0;
2766 const AtomicString* target = 0;
2767 for (Element* element = ElementTraversal::firstWithin(*this); element && (!href || !target); element = ElementTraversal::next(*element)) {
2768 if (element->hasTagName(baseTag)) {
2770 const AtomicString& value = element->fastGetAttribute(hrefAttr);
2771 if (!value.isNull())
2775 const AtomicString& value = element->fastGetAttribute(targetAttr);
2776 if (!value.isNull())
2779 if (contentSecurityPolicy()->isActive())
2780 UseCounter::count(*this, UseCounter::ContentSecurityPolicyWithBaseElement);
2784 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2785 KURL baseElementURL;
2787 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2788 if (!strippedHref.isEmpty())
2789 baseElementURL = KURL(url(), strippedHref);
2791 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
2792 m_baseElementURL = baseElementURL;
2796 m_baseTarget = target ? *target : nullAtom;
2799 String Document::userAgent(const KURL& url) const
2801 return frame() ? frame()->loader().userAgent(url) : String();
2804 void Document::disableEval(const String& errorMessage)
2809 frame()->script().disableEval(errorMessage);
2812 bool Document::canNavigate(Frame* targetFrame)
2817 // FIXME: We shouldn't call this function without a target frame, but
2818 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2819 // returning true when supplied with a 0 targetFrame.
2823 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
2824 if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
2827 if (isSandboxed(SandboxNavigation)) {
2828 if (targetFrame->tree().isDescendantOf(m_frame))
2831 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
2832 if (isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
2833 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
2835 printNavigationErrorMessage(*targetFrame, url(), reason);
2839 ASSERT(securityOrigin());
2840 SecurityOrigin& origin = *securityOrigin();
2842 // This is the normal case. A document can navigate its decendant frames,
2843 // or, more generally, a document can navigate a frame if the document is
2844 // in the same origin as any of that frame's ancestors (in the frame
2847 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2848 // historical information about this security check.
2849 if (canAccessAncestor(origin, targetFrame))
2852 // Top-level frames are easier to navigate than other frames because they
2853 // display their URLs in the address bar (in most browsers). However, there
2854 // are still some restrictions on navigation to avoid nuisance attacks.
2855 // Specifically, a document can navigate a top-level frame if that frame
2856 // opened the document or if the document is the same-origin with any of
2857 // the top-level frame's opener's ancestors (in the frame hierarchy).
2859 // In both of these cases, the document performing the navigation is in
2860 // some way related to the frame being navigate (e.g., by the "opener"
2861 // and/or "parent" relation). Requiring some sort of relation prevents a
2862 // document from navigating arbitrary, unrelated top-level frames.
2863 if (!targetFrame->tree().parent()) {
2864 if (targetFrame == m_frame->loader().opener())
2867 if (canAccessAncestor(origin, targetFrame->loader().opener()))
2871 printNavigationErrorMessage(*targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
2875 Frame* Document::findUnsafeParentScrollPropagationBoundary()
2877 Frame* currentFrame = m_frame;
2878 Frame* ancestorFrame = currentFrame->tree().parent();
2880 while (ancestorFrame) {
2881 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
2882 return currentFrame;
2883 currentFrame = ancestorFrame;
2884 ancestorFrame = ancestorFrame->tree().parent();
2889 void Document::didRemoveAllPendingStylesheet()
2891 m_needsNotifyRemoveAllPendingStylesheet = false;
2893 styleResolverChanged(RecalcStyleDeferred, AnalyzedStyleUpdate);
2894 executeScriptsWaitingForResourcesIfNeeded();
2896 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
2897 view()->scrollToFragment(m_url);
2900 void Document::executeScriptsWaitingForResourcesIfNeeded()
2902 if (!haveStylesheetsAndImportsLoaded())
2904 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2905 parser->executeScriptsWaitingForResources();
2909 CSSStyleSheet* Document::elementSheet()
2912 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2913 return m_elemSheet.get();
2916 void Document::processHttpEquiv(const AtomicString& equiv, const AtomicString& content, bool inDocumentHeadElement)
2918 ASSERT(!equiv.isNull() && !content.isNull());
2920 if (equalIgnoringCase(equiv, "default-style")) {
2921 processHttpEquivDefaultStyle(content);
2922 } else if (equalIgnoringCase(equiv, "refresh")) {
2923 processHttpEquivRefresh(content);
2924 } else if (equalIgnoringCase(equiv, "set-cookie")) {
2925 processHttpEquivSetCookie(content);
2926 } else if (equalIgnoringCase(equiv, "content-language")) {
2927 setContentLanguage(content);
2928 } else if (equalIgnoringCase(equiv, "x-dns-prefetch-control")) {
2929 parseDNSPrefetchControlHeader(content);
2930 } else if (equalIgnoringCase(equiv, "x-frame-options")) {
2931 processHttpEquivXFrameOptions(content);
2932 } else if (equalIgnoringCase(equiv, "content-security-policy") || equalIgnoringCase(equiv, "content-security-policy-report-only")) {
2933 if (inDocumentHeadElement)
2934 processHttpEquivContentSecurityPolicy(equiv, content);
2936 contentSecurityPolicy()->reportMetaOutsideHead(content);
2940 void Document::processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content)
2942 if (equalIgnoringCase(equiv, "content-security-policy"))
2943 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce, ContentSecurityPolicy::HeaderSourceMeta);
2944 else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
2945 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report, ContentSecurityPolicy::HeaderSourceMeta);
2947 ASSERT_NOT_REACHED();
2950 void Document::processHttpEquivDefaultStyle(const AtomicString& content)
2952 // The preferred style set has been overridden as per section
2953 // 14.3.2 of the HTML4.0 specification. We need to update the
2954 // sheet used variable and then update our style selector.
2955 // For more info, see the test at:
2956 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
2958 m_styleEngine->setSelectedStylesheetSetName(content);
2959 m_styleEngine->setPreferredStylesheetSetName(content);
2960 styleResolverChanged(RecalcStyleDeferred);
2963 void Document::processHttpEquivRefresh(const AtomicString& content)
2965 maybeHandleHttpRefresh(content, HttpRefreshFromMetaTag);
2968 void Document::maybeHandleHttpRefresh(const String& content, HttpRefreshType httpRefreshType)
2970 if (m_isViewSource || !m_frame)
2975 if (!parseHTTPRefresh(content, httpRefreshType == HttpRefreshFromMetaTag, delay, refreshURL))
2977 if (refreshURL.isEmpty())
2978 refreshURL = url().string();
2980 refreshURL = completeURL(refreshURL).string();
2982 if (protocolIsJavaScript(refreshURL)) {
2983 String message = "Refused to refresh " + m_url.elidedString() + " to a javascript: URL";
2984 addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
2988 if (httpRefreshType == HttpRefreshFromMetaTag && isSandboxed(SandboxAutomaticFeatures)) {
2989 String message = "Refused to execute the redirect specified via '<meta http-equiv='refresh' content='...'>'. The document is sandboxed, and the 'allow-scripts' keyword is not set.";
2990 addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
2993 m_frame->navigationScheduler().scheduleRedirect(delay, refreshURL);
2996 void Document::processHttpEquivSetCookie(const AtomicString& content)
2998 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
2999 if (!isHTMLDocument())
3002 // Exception (for sandboxed documents) ignored.
3003 toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
3006 void Document::processHttpEquivXFrameOptions(const AtomicString& content)
3008 Frame* frame = this->frame();
3012 FrameLoader& frameLoader = frame->loader();
3013 unsigned long requestIdentifier = loader()->mainResourceIdentifier();
3014 if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
3015 String message = "Refused to display '" + url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
3016 frameLoader.stopAllLoaders();
3017 // Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
3018 // intent, we must navigate away from the possibly partially-rendered document to a location that
3019 // doesn't inherit the parent's SecurityOrigin.
3020 frame->navigationScheduler().scheduleLocationChange(this, SecurityOrigin::urlWithUniqueSecurityOrigin(), Referrer());
3021 addConsoleMessageWithRequestIdentifier(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
3025 bool Document::shouldMergeWithLegacyDescription(ViewportDescription::Type origin)
3027 return settings() && settings()->viewportMetaMergeContentQuirk() && m_legacyViewportDescription.isMetaViewportType() && m_legacyViewportDescription.type == origin;
3030 void Document::setViewportDescription(const ViewportDescription& viewportDescription)
3032 if (viewportDescription.isLegacyViewportType()) {
3033 if (settings() && !settings()->viewportMetaEnabled())
3036 m_legacyViewportDescription = viewportDescription;
3038 // When no author style for @viewport is present, and a meta tag for defining
3039 // the viewport is, apply the meta tag viewport instead of the UA styles.
3040 if (m_viewportDescription.type == ViewportDescription::AuthorStyleSheet)
3042 m_viewportDescription = viewportDescription;
3044 // If the legacy viewport tag has higher priority than the cascaded @viewport
3045 // descriptors, use the values from the legacy tag.
3046 if (!shouldOverrideLegacyDescription(viewportDescription.type))
3047 m_viewportDescription = m_legacyViewportDescription;
3049 m_viewportDescription = viewportDescription;
3052 updateViewportDescription();
3055 void Document::updateViewportDescription()
3057 if (frame() && frame()->isMainFrame()) {
3059 m_didDispatchViewportPropertiesChanged = true;
3061 frameHost()->chrome().dispatchViewportPropertiesDidChange(m_viewportDescription);
3065 void Document::processReferrerPolicy(const String& policy)
3067 ASSERT(!policy.isNull());
3069 if (equalIgnoringCase(policy, "never")) {
3070 setReferrerPolicy(ReferrerPolicyNever);
3071 } else if (equalIgnoringCase(policy, "always")) {
3072 setReferrerPolicy(ReferrerPolicyAlways);
3073 } else if (equalIgnoringCase(policy, "origin")) {
3074 setReferrerPolicy(ReferrerPolicyOrigin);
3075 } else if (equalIgnoringCase(policy, "default")) {
3076 setReferrerPolicy(ReferrerPolicyDefault);
3078 addConsoleMessage(RenderingMessageSource, ErrorMessageLevel, "Failed to set referrer policy: The value '" + policy + "' is not one of 'always', 'default', 'never', or 'origin'. Defaulting to 'never'.");
3079 setReferrerPolicy(ReferrerPolicyNever);
3083 void Document::setReferrerPolicy(ReferrerPolicy referrerPolicy)
3085 // FIXME: Can we adopt the CSP referrer policy merge algorithm? Or does the web rely on being able to modify the referrer policy in-flight?
3086 if (m_didSetReferrerPolicy)
3087 UseCounter::count(this, UseCounter::ResetReferrerPolicy);
3088 m_didSetReferrerPolicy = true;
3090 m_referrerPolicy = referrerPolicy;
3093 String Document::outgoingReferrer()
3095 // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
3096 // for why we walk the parent chain for srcdoc documents.
3097 Document* referrerDocument = this;
3098 if (Frame* frame = m_frame) {
3099 while (frame->document()->isSrcdocDocument()) {
3100 frame = frame->tree().parent();
3101 // Srcdoc documents cannot be top-level documents, by definition,
3102 // because they need to be contained in iframes with the srcdoc.
3105 referrerDocument = frame->document();
3107 return referrerDocument->m_url.strippedForUseAsReferrer();
3110 String Document::outgoingOrigin() const
3112 return securityOrigin()->toString();
3115 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3117 ASSERT(!renderView() || renderView()->isRenderView());
3119 // RenderView::hitTest causes a layout, and we don't want to hit that until the first
3120 // layout because until then, there is nothing shown on the screen - the user can't
3121 // have intentionally clicked on something belonging to this page. Furthermore,
3122 // mousemove events before the first layout should not lead to a premature layout()
3123 // happening, which could show a flash of white.
3124 // See also the similar code in EventHandler::hitTestResultAtPoint.
3125 if (!renderView() || !view() || !view()->didFirstLayout())
3126 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3128 HitTestResult result(documentPoint);
3129 renderView()->hitTest(request, result);
3131 if (!request.readOnly())
3132 updateHoverActiveState(request, result.innerElement(), &event);
3134 return MouseEventWithHitTestResults(event, result);
3137 // DOM Section 1.1.1
3138 bool Document::childTypeAllowed(NodeType type) const
3141 case ATTRIBUTE_NODE:
3142 case CDATA_SECTION_NODE:
3143 case DOCUMENT_FRAGMENT_NODE:
3148 case PROCESSING_INSTRUCTION_NODE:
3150 case DOCUMENT_TYPE_NODE:
3152 // Documents may contain no more than one of each of these.
3153 // (One Element and one DocumentType.)
3154 for (Node* c = firstChild(); c; c = c->nextSibling())
3155 if (c->nodeType() == type)
3162 bool Document::canReplaceChild(const Node& newChild, const Node& oldChild) const
3164 if (oldChild.nodeType() == newChild.nodeType())
3167 int numDoctypes = 0;
3168 int numElements = 0;
3170 // First, check how many doctypes and elements we have, not counting
3171 // the child we're about to remove.
3172 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3176 switch (c->nodeType()) {
3177 case DOCUMENT_TYPE_NODE:
3188 // Then, see how many doctypes and elements might be added by the new child.
3189 if (newChild.nodeType() == DOCUMENT_FRAGMENT_NODE) {
3190 for (Node* c = newChild.firstChild(); c; c = c->nextSibling()) {
3191 switch (c->nodeType()) {
3192 case ATTRIBUTE_NODE:
3193 case CDATA_SECTION_NODE:
3194 case DOCUMENT_FRAGMENT_NODE:
3199 case PROCESSING_INSTRUCTION_NODE:
3201 case DOCUMENT_TYPE_NODE:
3210 switch (newChild.nodeType()) {
3211 case ATTRIBUTE_NODE:
3212 case CDATA_SECTION_NODE:
3213 case DOCUMENT_FRAGMENT_NODE:
3218 case PROCESSING_INSTRUCTION_NODE:
3220 case DOCUMENT_TYPE_NODE:
3229 if (numElements > 1 || numDoctypes > 1)
3235 PassRefPtr<Node> Document::cloneNode(bool deep)
3237 RefPtr<Document> clone = cloneDocumentWithoutChildren();
3238 clone->cloneDataFromDocument(*this);
3240 cloneChildNodes(clone.get());
3241 return clone.release();
3244 PassRefPtr<Document> Document::cloneDocumentWithoutChildren()
3246 DocumentInit init(url());
3247 if (isXMLDocument()) {
3248 if (isXHTMLDocument())
3249 return XMLDocument::createXHTML(init.withRegistrationContext(registrationContext()));
3250 return XMLDocument::create(init);
3252 return create(init);
3255 void Document::cloneDataFromDocument(const Document& other)
3257 setCompatibilityMode(other.compatibilityMode());
3258 setEncodingData(other.m_encodingData);
3259 setContextFeatures(other.contextFeatures());
3260 setSecurityOrigin(other.securityOrigin()->isolatedCopy());
3263 StyleSheetList* Document::styleSheets()
3265 if (!m_styleSheetList)
3266 m_styleSheetList = StyleSheetList::create(this);
3267 return m_styleSheetList.get();
3270 String Document::preferredStylesheetSet() const
3272 return m_styleEngine->preferredStylesheetSetName();
3275 String Document::selectedStylesheetSet() const
3277 return m_styleEngine->selectedStylesheetSetName();
3280 void Document::setSelectedStylesheetSet(const String& aString)
3282 m_styleEngine->setSelectedStylesheetSetName(aString);
3283 styleResolverChanged(RecalcStyleDeferred);
3286 void Document::evaluateMediaQueryList()
3288 if (m_mediaQueryMatcher)
3289 m_mediaQueryMatcher->styleResolverChanged();
3292 void Document::notifyResizeForViewportUnits()
3294 if (!hasViewportUnits())
3296 ensureStyleResolver().notifyResizeForViewportUnits();
3297 setNeedsStyleRecalcForViewportUnits();
3300 void Document::styleResolverChanged(RecalcStyleTime updateTime, StyleResolverUpdateMode updateMode)
3302 // styleResolverChanged() can be invoked during Document destruction.
3303 // We just skip that case.
3307 StyleResolverChange change = m_styleEngine->resolverChanged(updateTime, updateMode);
3308 if (change.needsRepaint()) {
3309 // We need to manually repaint because we avoid doing all repaints in layout or style
3310 // recalc while sheets are still loading to avoid FOUC.
3311 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3312 renderView()->repaintViewAndCompositedLayers();
3315 if (!change.needsStyleRecalc())
3318 m_evaluateMediaQueriesOnStyleRecalc = true;
3319 setNeedsStyleRecalc(SubtreeStyleChange);
3321 if (updateTime == RecalcStyleImmediately)
3322 updateStyleIfNeeded();
3325 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
3327 m_hoverNode = newHoverNode;
3330 void Document::setActiveHoverElement(PassRefPtr<Element> newActiveElement)
3332 if (!newActiveElement) {
3333 m_activeHoverElement.clear();
3337 m_activeHoverElement = newActiveElement;
3340 void Document::removeFocusedElementOfSubtree(Node* node, bool amongChildrenOnly)
3342 if (!m_focusedElement)
3345 // We can't be focused if we're not in the document.
3346 if (!node->inDocument())
3348 bool contains = node->containsIncludingShadowDOM(m_focusedElement.get());
3349 if (contains && (m_focusedElement != node || !amongChildrenOnly))
3350 setFocusedElement(0);
3353 void Document::hoveredNodeDetached(Node* node)
3358 if (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != NodeRenderingTraversal::parent(m_hoverNode.get())))
3361 m_hoverNode = NodeRenderingTraversal::parent(node);
3362 while (m_hoverNode && !m_hoverNode->renderer())
3363 m_hoverNode = NodeRenderingTraversal::parent(m_hoverNode.get());
3365 // If the mouse cursor is not visible, do not clear existing
3366 // hover effects on the ancestors of |node| and do not invoke
3367 // new hover effects on any other element.
3368 if (!page()->isCursorVisible())
3372 frame()->eventHandler().scheduleHoverStateUpdate();
3375 void Document::activeChainNodeDetached(Node* node)
3377 if (!m_activeHoverElement)
3380 if (node != m_activeHoverElement && (!m_activeHoverElement->isTextNode() || node != NodeRenderingTraversal::parent(m_activeHoverElement.get())))
3383 Node* activeNode = NodeRenderingTraversal::parent(node);
3384 while (activeNode && activeNode->isElementNode() && !activeNode->renderer())
3385 activeNode = NodeRenderingTraversal::parent(activeNode);
3387 m_activeHoverElement = activeNode && activeNode->isElementNode() ? toElement(activeNode) : 0;
3390 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3392 return m_annotatedRegions;
3395 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3397 m_annotatedRegions = regions;
3398 setAnnotatedRegionsDirty(false);
3401 bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, FocusType type)
3403 m_clearFocusedElementTimer.stop();
3405 RefPtr<Element> newFocusedElement = prpNewFocusedElement;
3407 // Make sure newFocusedNode is actually in this document
3408 if (newFocusedElement && (newFocusedElement->document() != this))
3411 if (NodeChildRemovalTracker::isBeingRemoved(newFocusedElement.get()))
3414 if (m_focusedElement == newFocusedElement)
3417 bool focusChangeBlocked = false;
3418 RefPtr<Element> oldFocusedElement = m_focusedElement;
3419 m_focusedElement = 0;
3421 // Remove focus from the existing focus node (if any)
3422 if (oldFocusedElement) {
3423 ASSERT(!oldFocusedElement->inDetach());
3425 if (oldFocusedElement->active())
3426 oldFocusedElement->setActive(false);
3428 oldFocusedElement->setFocus(false);
3430 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3431 // If page lost focus, blur event will have already been dispatched
3432 if (page() && (page()->focusController().isFocused())) {
3433 oldFocusedElement->dispatchBlurEvent(newFocusedElement.get());
3435 if (m_focusedElement) {
3436 // handler shifted focus
3437 focusChangeBlocked = true;
3438 newFocusedElement = 0;
3441 oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::focusout, newFocusedElement.get()); // DOM level 3 name for the bubbling blur event.
3442 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3443 // on it, probably when <rdar://problem/8503958> is resolved.
3444 oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, newFocusedElement.get()); // DOM level 2 name for compatibility.
3446 if (m_focusedElement) {
3447 // handler shifted focus
3448 focusChangeBlocked = true;
3449 newFocusedElement = 0;
3454 Widget* oldWidget = widgetForElement(*oldFocusedElement);
3456 oldWidget->setFocus(false);
3458 view()->setFocus(false);
3462 if (newFocusedElement && newFocusedElement->isFocusable()) {
3463 if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(*newFocusedElement)) {
3464 // delegate blocks focus change
3465 focusChangeBlocked = true;
3466 goto SetFocusedElementDone;
3468 // Set focus on the new node
3469 m_focusedElement = newFocusedElement;
3471 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3472 // If page lost focus, event will be dispatched on page focus, don't duplicate
3473 if (page() && (page()->focusController().isFocused())) {
3474 m_focusedElement->dispatchFocusEvent(oldFocusedElement.get(), type);
3477 if (m_focusedElement != newFocusedElement) {
3478 // handler shifted focus
3479 focusChangeBlocked = true;
3480 goto SetFocusedElementDone;
3483 m_focusedElement->dispatchFocusInEvent(EventTypeNames::focusin, oldFocusedElement.get()); // DOM level 3 bubbling focus event.
3485 if (m_focusedElement != newFocusedElement) {
3486 // handler shifted focus
3487 focusChangeBlocked = true;
3488 goto SetFocusedElementDone;
3491 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3492 // on it, probably when <rdar://problem/8503958> is m.
3493 m_focusedElement->dispatchFocusInEvent(EventTypeNames::DOMFocusIn, oldFocusedElement.get()); // DOM level 2 for compatibility.
3495 if (m_focusedElement != newFocusedElement) {
3496 // handler shifted focus
3497 focusChangeBlocked = true;
3498 goto SetFocusedElementDone;
3502 m_focusedElement->setFocus(true);
3504 if (m_focusedElement->isRootEditableElement())
3505 frame()->spellChecker().didBeginEditing(m_focusedElement.get());
3507 // eww, I suck. set the qt focus correctly
3508 // ### find a better place in the code for this
3510 Widget* focusWidget = widgetForElement(*m_focusedElement);
3512 // Make sure a widget has the right size before giving it focus.
3513 // Otherwise, we are testing edge cases of the Widget code.
3514 // Specifically, in WebCore this does not work well for text fields.
3516 // Re-get the widget in case updating the layout changed things.
3517 focusWidget = widgetForElement(*m_focusedElement);
3520 focusWidget->setFocus(true);
3522 view()->setFocus(true);
3526 if (!focusChangeBlocked && m_focusedElement) {
3527 // Create the AXObject cache in a focus change because Chromium relies on it.
3528 if (AXObjectCache* cache = axObjectCache())
3529 cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
3532 if (!focusChangeBlocked && frameHost())
3533 frameHost()->chrome().focusedNodeChanged(m_focusedElement.get());
3535 SetFocusedElementDone:
3536 updateStyleIfNeeded();
3537 if (Frame* frame = this->frame())
3538 frame->selection().didChangeFocus();
3539 return !focusChangeBlocked;
3542 void Document::setCSSTarget(Element* n)
3545 m_cssTarget->didAffectSelector(AffectedSelectorTarget);
3548 n->didAffectSelector(AffectedSelectorTarget);
3551 void Document::registerNodeList(LiveNodeListBase* list)
3553 m_nodeListCounts[list->invalidationType()]++;
3554 if (list->isRootedAtDocument())
3555 m_listsInvalidatedAtDocument.add(list);
3558 void Document::unregisterNodeList(LiveNodeListBase* list)
3560 m_nodeListCounts[list->invalidationType()]--;
3561 if (list->isRootedAtDocument()) {
3562 ASSERT(m_listsInvalidatedAtDocument.contains(list));
3563 m_listsInvalidatedAtDocument.remove(list);
3567 void Document::attachNodeIterator(NodeIterator* ni)
3569 m_nodeIterators.add(ni);
3572 void Document::detachNodeIterator(NodeIterator* ni)
3574 // The node iterator can be detached without having been attached if its root node didn't have a document
3575 // when the iterator was created, but has it now.
3576 m_nodeIterators.remove(ni);
3579 void Document::moveNodeIteratorsToNewDocument(Node& node, Document& newDocument)
3581 HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3582 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3583 for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3584 if ((*it)->root() == node) {
3585 detachNodeIterator(*it);
3586 newDocument.attachNodeIterator(*it);
3591 void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
3593 if (!m_ranges.isEmpty()) {
3594 HashSet<Range*>::const_iterator end = m_ranges.end();
3595 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3596 (*it)->nodeChildrenChanged(container);
3600 void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
3602 NoEventDispatchAssertion assertNoEventDispatch;
3603 if (!m_ranges.isEmpty()) {
3604 HashSet<Range*>::const_iterator end = m_ranges.end();
3605 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3606 (*it)->nodeChildrenWillBeRemoved(container);
3609 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3610 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
3611 for (Node* n = container->firstChild(); n; n = n->nextSibling())
3612 (*it)->nodeWillBeRemoved(*n);
3615 if (Frame* frame = this->frame()) {
3616 for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
3617 frame->eventHandler().nodeWillBeRemoved(*n);
3618 frame->selection().nodeWillBeRemoved(*n);
3619 frame->page()->dragCaretController().nodeWillBeRemoved(*n);
3624 void Document::nodeWillBeRemoved(Node& n)
3626 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3627 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3628 (*it)->nodeWillBeRemoved(n);
3630 if (!m_ranges.isEmpty()) {
3631 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
3632 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3633 (*it)->nodeWillBeRemoved(n);
3636 if (Frame* frame = this->frame()) {
3637 frame->eventHandler().nodeWillBeRemoved(n);
3638 frame->selection().nodeWillBeRemoved(n);
3639 frame->page()->dragCaretController().nodeWillBeRemoved(n);
3643 void Document::didInsertText(Node* text, unsigned offset, unsigned length)
3645 if (!m_ranges.isEmpty()) {
3646 HashSet<Range*>::const_iterator end = m_ranges.end();
3647 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3648 (*it)->didInsertText(text, offset, length);
3651 // Update the markers for spelling and grammar checking.
3652 m_markers->shiftMarkers(text, offset, length);
3655 void Document::didRemoveText(Node* text, unsigned offset, unsigned length)
3657 if (!m_ranges.isEmpty()) {
3658 HashSet<Range*>::const_iterator end = m_ranges.end();
3659 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3660 (*it)->didRemoveText(text, offset, length);
3663 // Update the markers for spelling and grammar checking.
3664 m_markers->removeMarkers(text, offset, length);
3665 m_markers->shiftMarkers(text, offset + length, 0 - length);
3668 void Document::didMergeTextNodes(Text* oldNode, unsigned offset)
3670 if (!m_ranges.isEmpty()) {
3671 NodeWithIndex oldNodeWithIndex(oldNode);
3672 HashSet<Range*>::const_iterator end = m_ranges.end();
3673 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3674 (*it)->didMergeTextNodes(oldNodeWithIndex, offset);
3678 m_frame->selection().didMergeTextNodes(*oldNode, offset);
3680 // FIXME: This should update markers for spelling and grammar checking.
3683 void Document::didSplitTextNode(Text* oldNode)
3685 if (!m_ranges.isEmpty()) {
3686 HashSet<Range*>::const_iterator end = m_ranges.end();
3687 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3688 (*it)->didSplitTextNode(oldNode);
3692 m_frame->selection().didSplitTextNode(*oldNode);
3694 // FIXME: This should update markers for spelling and grammar checking.
3697 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3699 DOMWindow* domWindow = this->domWindow();
3702 domWindow->setAttributeEventListener(eventType, listener);
3705 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3707 DOMWindow* domWindow = this->domWindow();
3710 return domWindow->getAttributeEventListener(eventType);
3713 EventQueue* Document::eventQueue() const
3717 return m_domWindow->eventQueue();
3720 void Document::enqueueAnimationFrameEvent(PassRefPtr<Event> event)
3722 ensureScriptedAnimationController().enqueueEvent(event);
3725 void Document::enqueueScrollEventForNode(Node* target)
3727 // Per the W3C CSSOM View Module only scroll events fired at the document should bubble.
3728 RefPtr<Event> scrollEvent = target->isDocumentNode() ? Event::createBubble(EventTypeNames::scroll) : Event::create(EventTypeNames::scroll);
3729 scrollEvent->setTarget(target);
3730 ensureScriptedAnimationController().enqueuePerFrameEvent(scrollEvent.release());
3733 void Document::enqueueResizeEvent()
3735 RefPtr<Event> event = Event::create(EventTypeNames::resize);
3736 event->setTarget(domWindow());
3737 ensureScriptedAnimationController().enqueuePerFrameEvent(event.release());
3740 PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionState& exceptionState)
3742 RefPtr<Event> event = EventFactory::create(eventType);
3744 return event.release();
3746 exceptionState.throwDOMException(NotSupportedError, "The provided event type ('" + eventType + "') is invalid.");
3750 PassRefPtr<Event> Document::createEvent(ExceptionState& exceptionState)
3752 if (!isSVGDocument()) {
3753 exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(1, 0));
3757 UseCounter::count(this, UseCounter::DocumentCreateEventOptionalArgument);
3758 // Legacy SVGDocument behavior.
3759 return createEvent("undefined", exceptionState);
3762 void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
3764 if (ContextFeatures::mutationEventsEnabled(this))
3765 addListenerType(listenerType);
3768 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
3770 if (eventType == EventTypeNames::DOMSubtreeModified) {
3771 UseCounter::count(*this, UseCounter::DOMSubtreeModifiedEvent);
3772 addMutationEventListenerTypeIfEnabled(DOMSUBTREEMODIFIED_LISTENER);
3773 } else if (eventType == EventTypeNames::DOMNodeInserted) {
3774 UseCounter::count(*this, UseCounter::DOMNodeInsertedEvent);
3775 addMutationEventListenerTypeIfEnabled(DOMNODEINSERTED_LISTENER);
3776 } else if (eventType == EventTypeNames::DOMNodeRemoved) {
3777 UseCounter::count(*this, UseCounter::DOMNodeRemovedEvent);
3778 addMutationEventListenerTypeIfEnabled(DOMNODEREMOVED_LISTENER);
3779 } else if (eventType == EventTypeNames::DOMNodeRemovedFromDocument) {
3780 UseCounter::count(*this, UseCounter::DOMNodeRemovedFromDocumentEvent);
3781 addMutationEventListenerTypeIfEnabled(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
3782 } else if (eventType == EventTypeNames::DOMNodeInsertedIntoDocument) {
3783 UseCounter::count(*this, UseCounter::DOMNodeInsertedIntoDocumentEvent);
3784 addMutationEventListenerTypeIfEnabled(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
3785 } else if (eventType == EventTypeNames::DOMCharacterDataModified) {
3786 UseCounter::count(*this, UseCounter::DOMCharacterDataModifiedEvent);
3787 addMutationEventListenerTypeIfEnabled(DOMCHARACTERDATAMODIFIED_LISTENER);
3788 } else if (eventType == EventTypeNames::overflowchanged) {
3789 UseCounter::count(*this, UseCounter::OverflowChangedEvent);
3790 addListenerType(OVERFLOWCHANGED_LISTENER);
3791 } else if (eventType == EventTypeNames::webkitAnimationStart || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationstart)) {
3792 addListenerType(ANIMATIONSTART_LISTENER);
3793 } else if (eventType == EventTypeNames::webkitAnimationEnd || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationend)) {
3794 addListenerType(ANIMATIONEND_LISTENER);
3795 } else if (eventType == EventTypeNames::webkitAnimationIteration || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationiteration)) {
3796 addListenerType(ANIMATIONITERATION_LISTENER);
3797 } else if (eventType == EventTypeNames::webkitTransitionEnd || eventType == EventTypeNames::transitionend) {
3798 addListenerType(TRANSITIONEND_LISTENER);
3799 } else if (eventType == EventTypeNames::beforeload) {
3800 if (m_frame && m_frame->script().shouldBypassMainWorldContentSecurityPolicy()) {
3801 UseCounter::count(*this, UseCounter::BeforeLoadEventInIsolatedWorld);
3803 UseCounter::count(*this, UseCounter::BeforeLoadEvent);
3805 addListenerType(BEFORELOAD_LISTENER);
3806 } else if (eventType == EventTypeNames::scroll) {
3807 addListenerType(SCROLL_LISTENER);
3808 } else if (eventType == EventTypeNames::DOMFocusIn || eventType == EventTypeNames::DOMFocusOut) {
3809 UseCounter::count(*this, UseCounter::DOMFocusInOutEvent);
3813 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
3818 HTMLFrameOwnerElement* Document::ownerElement() const
3822 return frame()->ownerElement();
3825 String Document::cookie(ExceptionState& exceptionState) const
3827 if (settings() && !settings()->cookieEnabled())
3830 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3831 // InvalidStateError exception on getting if the Document has no
3832 // browsing context.
3834 if (!securityOrigin()->canAccessCookies()) {
3835 if (isSandboxed(SandboxOrigin))
3836 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
3837 else if (url().protocolIs("data"))
3838 exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
3840 exceptionState.throwSecurityError("Access is denied for this document.");
3844 KURL cookieURL = this->cookieURL();
3845 if (cookieURL.isEmpty())
3848 return cookies(this, cookieURL);
3851 void Document::setCookie(const String& value, ExceptionState& exceptionState)
3853 if (settings() && !settings()->cookieEnabled())
3856 // FIXME: The HTML5 DOM spec states that this attribute can raise an
3857 // InvalidStateError exception on setting if the Document has no
3858 // browsing context.
3860 if (!securityOrigin()->canAccessCookies()) {
3861 if (isSandboxed(SandboxOrigin))
3862 exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
3863 else if (url().protocolIs("data"))
3864 exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
3866 exceptionState.throwSecurityError("Access is denied for this document.");
3870 KURL cookieURL = this->cookieURL();
3871 if (cookieURL.isEmpty())
3874 setCookies(this, cookieURL, value);
3877 const AtomicString& Document::referrer() const
3880 return loader()->request().httpReferrer();
3884 String Document::domain() const
3886 return securityOrigin()->domain();
3889 void Document::setDomain(const String& newDomain, ExceptionState& exceptionState)
3891 if (isSandboxed(SandboxDocumentDomain)) {
3892 exceptionState.throwSecurityError("Assignment is forbidden for sandboxed iframes.");
3896 if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
3897 exceptionState.throwSecurityError("Assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme.");
3901 if (newDomain.isEmpty()) {
3902 exceptionState.throwSecurityError("'" + newDomain + "' is an empty domain.");
3906 OriginAccessEntry::IPAddressSetting ipAddressSetting = settings() && settings()->treatIPAddressAsDomain() ? OriginAccessEntry::TreatIPAddressAsDomain : OriginAccessEntry::TreatIPAddressAsIPAddress;
3907 OriginAccessEntry accessEntry(securityOrigin()->protocol(), newDomain, OriginAccessEntry::AllowSubdomains, ipAddressSetting);
3908 OriginAccessEntry::MatchResult result = accessEntry.matchesOrigin(*securityOrigin());
3909 if (result == OriginAccessEntry::DoesNotMatchOrigin) {
3910 exceptionState.throwSecurityError("'" + newDomain + "' is not a suffix of '" + domain() + "'.");
3914 if (result == OriginAccessEntry::MatchesOriginButIsPublicSuffix) {
3915 exceptionState.throwSecurityError("'" + newDomain + "' is a top-level domain.");
3919 securityOrigin()->setDomainFromDOM(newDomain);
3921 m_frame->script().updateSecurityOrigin(securityOrigin());
3924 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
3925 String Document::lastModified() const
3927 DateComponents date;
3928 bool foundDate = false;
3930 if (DocumentLoader* documentLoader = loader()) {
3931 const AtomicString& httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
3932 if (!httpLastModified.isEmpty()) {
3933 date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
3938 // FIXME: If this document came from the file system, the HTML5
3939 // specificiation tells us to read the last modification date from the file
3942 date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
3943 return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
3946 const KURL& Document::firstPartyForCookies() const
3948 return topDocument()->url();
3951 static bool isValidNameNonASCII(const LChar* characters, unsigned length)
3953 if (!isValidNameStart(characters[0]))
3956 for (unsigned i = 1; i < length; ++i) {
3957 if (!isValidNamePart(characters[i]))
3964 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
3969 U16_NEXT(characters, i, length, c)
3970 if (!isValidNameStart(c))
3973 while (i < length) {
3974 U16_NEXT(characters, i, length, c)
3975 if (!isValidNamePart(c))
3982 template<typename CharType>
3983 static inline bool isValidNameASCII(const CharType* characters, unsigned length)
3985 CharType c = characters[0];
3986 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
3989 for (unsigned i = 1; i < length; ++i) {
3991 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
3998 bool Document::isValidName(const String& name)
4000 unsigned length = name.length();
4004 if (name.is8Bit()) {
4005 const LChar* characters = name.characters8();
4007 if (isValidNameASCII(characters, length))
4010 return isValidNameNonASCII(characters, length);
4013 const UChar* characters = name.characters16();
4015 if (isValidNameASCII(characters, length))
4018 return isValidNameNonASCII(characters, length);
4021 template<typename CharType>
4022 static bool parseQualifiedNameInternal(const AtomicString& qualifiedName, const CharType* characters, unsigned length, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
4024 bool nameStart = true;
4025 bool sawColon = false;
4028 for (unsigned i = 0; i < length;) {
4030 U16_NEXT(characters, i, length, c)
4033 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') contains multiple colons.");
4034 return false; // multiple colons: not allowed
4039 } else if (nameStart) {
4040 if (!isValidNameStart(c)) {
4041 StringBuilder message;
4042 message.appendLiteral("The qualified name provided ('");
4043 message.append(qualifiedName);
4044 message.appendLiteral("') contains the invalid name-start character '");
4046 message.appendLiteral("'.");
4047 exceptionState.throwDOMException(InvalidCharacterError, message.toString());
4052 if (!isValidNamePart(c)) {
4053 StringBuilder message;
4054 message.appendLiteral("The qualified name provided ('");
4055 message.append(qualifiedName);
4056 message.appendLiteral("') contains the invalid character '");
4058 message.appendLiteral("'.");
4059 exceptionState.throwDOMException(InvalidCharacterError, message.toString());
4067 localName = qualifiedName;
4069 prefix = AtomicString(characters, colonPos);
4070 if (prefix.isEmpty()) {
4071 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty namespace prefix.");
4074 int prefixStart = colonPos + 1;
4075 localName = AtomicString(characters + prefixStart, length - prefixStart);
4078 if (localName.isEmpty()) {
4079 exceptionState.throwDOMException(NamespaceError, "The qualified name provided ('" + qualifiedName + "') has an empty local name.");
4086 bool Document::parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
4088 unsigned length = qualifiedName.length();
4091 exceptionState.throwDOMException(InvalidCharacterError, "The qualified name provided is empty.");
4095 if (qualifiedName.is8Bit())
4096 return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName, exceptionState);
4097 return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName, exceptionState);
4100 void Document::setEncodingData(const DocumentEncodingData& newData)
4102 // It's possible for the encoding of the document to change while we're decoding
4103 // data. That can only occur while we're processing the <head> portion of the
4104 // document. There isn't much user-visible content in the <head>, but there is
4105 // the <title> element. This function detects that situation and re-decodes the
4106 // document's title so that the user doesn't see an incorrectly decoded title
4107 // in the title bar.
4109 && encoding() != newData.encoding()
4110 && !ElementTraversal::firstWithin(*m_titleElement)
4111 && encoding() == Latin1Encoding()
4112 && m_titleElement->textContent().containsOnlyLatin1()) {
4114 CString originalBytes = m_titleElement->textContent().latin1();
4115 OwnPtr<TextCodec> codec = newTextCodec(newData.encoding());
4116 String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), true);
4117 m_titleElement->setTextContent(correctlyDecodedTitle);
4120 m_encodingData = newData;
4122 // FIXME: Should be removed as part of https://code.google.com/p/chromium/issues/detail?id=319643
4123 bool shouldUseVisualOrdering = m_encodingData.encoding().usesVisualOrdering();
4124 if (shouldUseVisualOrdering != m_visuallyOrdered) {
4125 m_visuallyOrdered = shouldUseVisualOrdering;
4126 // FIXME: How is possible to not have a renderer here?
4128 renderView()->style()->setRTLOrdering(m_visuallyOrdered ? VisualOrder : LogicalOrder);
4129 setNeedsStyleRecalc(SubtreeStyleChange);
4133 KURL Document::completeURL(const String& url) const
4135 return completeURLWithOverride(url, m_baseURL);
4138 KURL Document::completeURLWithOverride(const String& url, const KURL& baseURLOverride) const
4140 // Always return a null URL when passed a null string.
4141 // FIXME: Should we change the KURL constructor to have this behavior?
4142 // See also [CSS]StyleSheet::completeURL(const String&)
4145 // This logic is deliberately spread over many statements in an attempt to track down http://crbug.com/312410.
4146 const KURL* baseURLFromParent = 0;
4147 bool shouldUseParentBaseURL = baseURLOverride.isEmpty();
4148 if (!shouldUseParentBaseURL) {
4149 const KURL& aboutBlankURL = blankURL();
4150 shouldUseParentBaseURL = (baseURLOverride == aboutBlankURL);
4152 if (shouldUseParentBaseURL) {
4153 if (Document* parent = parentDocument())
4154 baseURLFromParent = &parent->baseURL();
4156 const KURL& baseURL = baseURLFromParent ? *baseURLFromParent : baseURLOverride;
4157 if (!encoding().isValid())
4158 return KURL(baseURL, url);
4159 return KURL(baseURL, url, encoding());
4162 // Support for Javascript execCommand, and related methods
4164 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
4166 Frame* frame = document->frame();
4167 if (!frame || frame->document() != document)
4168 return Editor::Command();
4170 document->updateStyleIfNeeded();
4171 return frame->editor().command(commandName, userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
4174 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
4176 // We don't allow recusrive |execCommand()| to protect against attack code.
4177 // Recursive call of |execCommand()| could be happened by moving iframe
4178 // with script triggered by insertion, e.g. <iframe src="javascript:...">
4179 // <iframe onload="...">. This usage is valid as of the specification
4180 // although, it isn't common use case, rather it is used as attack code.
4181 static bool inExecCommand = false;
4182 if (inExecCommand) {
4183 String message = "We don't execute document.execCommand() this time, because it is called recursively.";
4184 addConsoleMessage(JSMessageSource, WarningMessageLevel, message);
4187 TemporaryChange<bool> executeScope(inExecCommand, true);
4189 // Postpone DOM mutation events, which can execute scripts and change
4190 // DOM tree against implementation assumption.
4191 EventQueueScope eventQueueScope;
4192 return command(this, commandName, userInterface).execute(value);
4195 bool Document::queryCommandEnabled(const String& commandName)
4197 return command(this, commandName).isEnabled();
4200 bool Document::queryCommandIndeterm(const String& commandName)
4202 return command(this, commandName).state() == MixedTriState;
4205 bool Document::queryCommandState(const String& commandName)
4207 return command(this, commandName).state() == TrueTriState;
4210 bool Document::queryCommandSupported(const String& commandName)
4212 return command(this, commandName).isSupported();
4215 String Document::queryCommandValue(const String& commandName)
4217 return command(this, commandName).value();
4220 KURL Document::openSearchDescriptionURL()
4222 static const char openSearchMIMEType[] = "application/opensearchdescription+xml";
4223 static const char openSearchRelation[] = "search";
4225 // FIXME: Why do only top-level frames have openSearchDescriptionURLs?
4226 if (!frame() || frame()->tree().parent())
4229 // FIXME: Why do we need to wait for FrameStateComplete?
4230 if (frame()->loader().state() != FrameStateComplete)
4236 RefPtr<HTMLCollection> children = head()->children();
4237 for (unsigned i = 0; Element* child = children->item(i); i++) {
4238 if (!child->hasTagName(linkTag))
4240 HTMLLinkElement* linkElement = toHTMLLinkElement(child);
4241 if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
4243 if (linkElement->href().isEmpty())
4245 return linkElement->href();
4251 void Document::pushCurrentScript(PassRefPtr<HTMLScriptElement> newCurrentScript)
4253 ASSERT(newCurrentScript);
4254 m_currentScriptStack.append(newCurrentScript);
4257 void Document::popCurrentScript()
4259 ASSERT(!m_currentScriptStack.isEmpty());
4260 m_currentScriptStack.removeLast();
4263 void Document::applyXSLTransform(ProcessingInstruction* pi)
4265 ASSERT(!pi->isLoading());
4266 UseCounter::count(*this, UseCounter::XSLProcessingInstruction);
4267 RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
4268 processor->setXSLStyleSheet(toXSLStyleSheet(pi->sheet()));
4269 String resultMIMEType;
4271 String resultEncoding;
4272 if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
4274 // FIXME: If the transform failed we should probably report an error (like Mozilla does).
4275 Frame* ownerFrame = frame();
4276 processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, ownerFrame);
4277 InspectorInstrumentation::frameDocumentUpdated(ownerFrame);
4280 void Document::setTransformSource(PassOwnPtr<TransformSource> source)
4282 m_transformSource = source;
4285 void Document::setDesignMode(InheritedBool value)
4287 m_designMode = value;
4288 for (Frame* frame = m_frame; frame && frame->document(); frame = frame->tree().traverseNext(m_frame))
4289 frame->document()->setNeedsStyleRecalc(SubtreeStyleChange);
4292 Document::InheritedBool Document::getDesignMode() const
4294 return m_designMode;
4297 bool Document::inDesignMode() const
4299 for (const Document* d = this; d; d = d->parentDocument()) {
4300 if (d->m_designMode != inherit)
4301 return d->m_designMode;
4306 Document* Document::parentDocument() const
4310 Frame* parent = m_frame->tree().parent();
4313 return parent->document();
4316 Document* Document::topDocument() const
4318 Document* doc = const_cast<Document*>(this);
4320 while ((element = doc->ownerElement()))
4321 doc = &element->document();
4326 WeakPtr<Document> Document::contextDocument()
4328 if (m_contextDocument)
4329 return m_contextDocument;
4331 return m_weakFactory.createWeakPtr();
4332 return WeakPtr<Document>(0);
4335 PassRefPtr<Attr> Document::createAttribute(const AtomicString& name, ExceptionState& exceptionState)
4337 AtomicString prefix, localName;
4338 if (!parseQualifiedName(name, prefix, localName, exceptionState))
4341 QualifiedName qName(prefix, localName, nullAtom);
4343 return Attr::create(*this, qName, emptyAtom);
4346 const SVGDocumentExtensions* Document::svgExtensions()
4348 return m_svgExtensions.get();
4351 SVGDocumentExtensions* Document::accessSVGExtensions()
4353 if (!m_svgExtensions)
4354 m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this));
4355 return m_svgExtensions.get();
4358 bool Document::hasSVGRootNode() const
4360 return documentElement() && documentElement()->hasTagName(SVGNames::svgTag);
4363 PassRefPtr<HTMLCollection> Document::ensureCachedCollection(CollectionType type)
4365 return ensureRareData().ensureNodeLists().addCache<HTMLCollection>(this, type);
4368 PassRefPtr<HTMLCollection> Document::images()
4370 return ensureCachedCollection(DocImages);
4373 PassRefPtr<HTMLCollection> Document::applets()
4375 return ensureCachedCollection(DocApplets);
4378 PassRefPtr<HTMLCollection> Document::embeds()
4380 return ensureCachedCollection(DocEmbeds);
4383 PassRefPtr<HTMLCollection> Document::scripts()
4385 return ensureCachedCollection(DocScripts);
4388 PassRefPtr<HTMLCollection> Document::links()
4390 return ensureCachedCollection(DocLinks);
4393 PassRefPtr<HTMLCollection> Document::forms()
4395 return ensureCachedCollection(DocForms);
4398 PassRefPtr<HTMLCollection> Document::anchors()
4400 return ensureCachedCollection(DocAnchors);
4403 PassRefPtr<HTMLCollection> Document::allForBinding()
4405 UseCounter::count(*this, UseCounter::DocumentAll);
4409 PassRefPtr<HTMLCollection> Document::all()
4411 return ensureRareData().ensureNodeLists().addCache<HTMLAllCollection>(this, DocAll);
4414 PassRefPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
4416 return ensureRareData().ensureNodeLists().addCache<HTMLNameCollection>(this, WindowNamedItems, name);
4419 PassRefPtr<HTMLCollection> Document::documentNamedItems(const AtomicString& name)
4421 return ensureRareData().ensureNodeLists().addCache<HTMLNameCollection>(this, DocumentNamedItems, name);
4424 void Document::finishedParsing()
4426 ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
4427 ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
4429 if (!m_documentTiming.domContentLoadedEventStart)
4430 m_documentTiming.domContentLoadedEventStart = monotonicallyIncreasingTime();
4431 dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
4432 if (!m_documentTiming.domContentLoadedEventEnd)
4433 m_documentTiming.domContentLoadedEventEnd = monotonicallyIncreasingTime();
4435 // The loader's finishedParsing() method may invoke script that causes this object to
4436 // be dereferenced (when this document is in an iframe and the onload causes the iframe's src to change).
4437 // Keep it alive until we are done.
4438 RefPtr<Document> protect(this);
4440 if (RefPtr<Frame> f = frame()) {
4441 // FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
4442 // resource loads are complete. HTMLObjectElements can start loading their resources from
4443 // post attach callbacks triggered by recalcStyle(). This means if we parse out an <object>
4444 // tag and then reach the end of the document without updating styles, we might not have yet
4445 // started the resource load and might fire the window load event too early. To avoid this
4446 // we force the styles to be up to date before calling FrameLoader::finishedParsing().
4447 // See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
4448 updateStyleIfNeeded();
4450 f->loader().finishedParsing();
4452 InspectorInstrumentation::domContentLoadedEventFired(f.get());
4455 // Schedule dropping of the ElementDataCache. We keep it alive for a while after parsing finishes
4456 // so that dynamically inserted content can also benefit from sharing optimizations.
4457 // Note that we don't refresh the timer on cache access since that could lead to huge caches being kept
4458 // alive indefinitely by something innocuous like JS setting .innerHTML repeatedly on a timer.
4459 m_elementDataCacheClearTimer.startOneShot(10);
4461 // Parser should have picked up all preloads by now
4462 m_fetcher->clearPreloads();
4465 m_import->didFinishParsing();
4468 void Document::elementDataCacheClearTimerFired(Timer<Document>*)
4470 m_elementDataCache.clear();
4473 Vector<IconURL> Document::iconURLs(int iconTypesMask)
4475 IconURL firstFavicon;
4476 IconURL firstTouchIcon;
4477 IconURL firstTouchPrecomposedIcon;
4478 Vector<IconURL> secondaryIcons;
4480 // Start from the last child node so that icons seen later take precedence as required by the spec.
4481 RefPtr<HTMLCollection> children = head() ? head()->children() : 0;
4482 unsigned length = children ? children->length() : 0;
4483 for (unsigned i = 0; i < length; i++) {
4484 Element* child = children->item(i);
4485 if (!child->hasTagName(linkTag))
4487 HTMLLinkElement* linkElement = toHTMLLinkElement(child);
4488 if (!(linkElement->iconType() & iconTypesMask))
4490 if (linkElement->href().isEmpty())
4492 if (!RuntimeEnabledFeatures::touchIconLoadingEnabled() && linkElement->iconType() != Favicon)
4495 IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
4496 if (linkElement->iconType() == Favicon) {
4497 if (firstFavicon.m_iconType != InvalidIcon)
4498 secondaryIcons.append(firstFavicon);
4499 firstFavicon = newURL;
4500 } else if (linkElement->iconType() == TouchIcon) {
4501 if (firstTouchIcon.m_iconType != InvalidIcon)
4502 secondaryIcons.append(firstTouchIcon);
4503 firstTouchIcon = newURL;
4504 } else if (linkElement->iconType() == TouchPrecomposedIcon) {
4505 if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4506 secondaryIcons.append(firstTouchPrecomposedIcon);
4507 firstTouchPrecomposedIcon = newURL;
4509 ASSERT_NOT_REACHED();
4513 Vector<IconURL> iconURLs;
4514 if (firstFavicon.m_iconType != InvalidIcon)
4515 iconURLs.append(firstFavicon);
4516 else if (m_url.protocolIsInHTTPFamily() && iconTypesMask & Favicon)
4517 iconURLs.append(IconURL::defaultFavicon(m_url));
4519 if (firstTouchIcon.m_iconType != InvalidIcon)
4520 iconURLs.append(firstTouchIcon);
4521 if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
4522 iconURLs.append(firstTouchPrecomposedIcon);
4523 for (int i = secondaryIcons.size() - 1; i >= 0; --i)
4524 iconURLs.append(secondaryIcons[i]);
4528 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
4530 if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
4533 m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
4534 m_frame->selection().updateSecureKeyboardEntryIfActive();
4537 bool Document::useSecureKeyboardEntryWhenActive() const
4539 return m_useSecureKeyboardEntryWhenActive;
4542 void Document::initSecurityContext()
4544 initSecurityContext(DocumentInit(m_url, m_frame, contextDocument(), m_import));
4547 void Document::initSecurityContext(const DocumentInit& initializer)
4549 if (haveInitializedSecurityOrigin()) {
4550 ASSERT(securityOrigin());
4554 if (!initializer.hasSecurityContext()) {
4555 // No source for a security context.
4556 // This can occur via document.implementation.createDocument().
4557 m_cookieURL = KURL(ParsedURLString, emptyString());
4558 setSecurityOrigin(SecurityOrigin::createUnique());
4559 setContentSecurityPolicy(ContentSecurityPolicy::create(this));
4563 // In the common case, create the security context from the currently
4564 // loading URL with a fresh content security policy.
4565 m_cookieURL = m_url;
4566 enforceSandboxFlags(initializer.sandboxFlags());
4567 setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
4568 setContentSecurityPolicy(ContentSecurityPolicy::create(this));
4570 if (Settings* settings = initializer.settings()) {
4571 if (!settings->webSecurityEnabled()) {
4572 // Web security is turned off. We should let this document access every other document. This is used primary by testing
4573 // harnesses for web sites.
4574 securityOrigin()->grantUniversalAccess();
4575 } else if (securityOrigin()->isLocal()) {
4576 if (settings->allowUniversalAccessFromFileURLs()) {
4577 // Some clients want local URLs to have universal access, but that setting is dangerous for other clients.
4578 securityOrigin()->grantUniversalAccess();
4579 } else if (!settings->allowFileAccessFromFileURLs()) {
4580 // Some clients want local URLs to have even tighter restrictions by default, and not be able to access other local files.
4581 // FIXME 81578: The naming of this is confusing. Files with restricted access to other local files
4582 // still can have other privileges that can be remembered, thereby not making them unique origins.
4583 securityOrigin()->enforceFilePathSeparation();
4588 if (initializer.shouldTreatURLAsSrcdocDocument()) {
4589 m_isSrcdocDocument = true;
4590 setBaseURLOverride(initializer.parentBaseURL());
4593 if (!shouldInheritSecurityOriginFromOwner(m_url))
4596 // If we do not obtain a meaningful origin from the URL, then we try to
4597 // find one via the frame hierarchy.
4599 if (!initializer.owner()) {
4600 didFailToInitializeSecurityOrigin();
4604 if (isSandboxed(SandboxOrigin)) {
4605 // If we're supposed to inherit our security origin from our owner,
4606 // but we're also sandboxed, the only thing we inherit is the ability
4607 // to load local resources. This lets about:blank iframes in file://
4608 // URL documents load images and other resources from the file system.
4609 if (initializer.owner()->securityOrigin()->canLoadLocalResources())
4610 securityOrigin()->grantLoadLocalResources();
4614 m_cookieURL = initializer.owner()->cookieURL();
4615 // We alias the SecurityOrigins to match Firefox, see Bug 15313
4616 // https://bugs.webkit.org/show_bug.cgi?id=15313
4617 setSecurityOrigin(initializer.owner()->securityOrigin());
4620 void Document::initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders& headers)
4622 if (m_frame && m_frame->tree().parent() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
4623 contentSecurityPolicy()->copyStateFrom(m_frame->tree().parent()->document()->contentSecurityPolicy());
4624 contentSecurityPolicy()->didReceiveHeaders(headers);
4627 bool Document::allowInlineEventHandlers(Node* node, EventListener* listener, const String& contextURL, const WTF::OrdinalNumber& contextLine)
4629 if (!contentSecurityPolicy()->allowInlineEventHandlers(contextURL, contextLine))
4632 // HTML says that inline script needs browsing context to create its execution environment.
4633 // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#event-handler-attributes
4634 // Also, if the listening node came from other document, which happens on context-less event dispatching,
4635 // we also need to ask the owner document of the node.
4636 Frame* frame = executingFrame();
4639 if (!frame->script().canExecuteScripts(NotAboutToExecuteScript))
4641 if (node && node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
4647 bool Document::allowExecutingScripts(Node* node)
4649 // FIXME: Eventually we'd like to evaluate scripts which are inserted into a
4650 // viewless document but this'll do for now.
4651 // See http://bugs.webkit.org/show_bug.cgi?id=5727
4652 Frame* frame = executingFrame();
4655 if (!node->document().executingFrame())
4657 if (!frame->script().canExecuteScripts(AboutToExecuteScript))
4662 void Document::updateSecurityOrigin(PassRefPtr<SecurityOrigin> origin)
4664 setSecurityOrigin(origin);
4665 didUpdateSecurityOrigin();
4668 void Document::didUpdateSecurityOrigin()
4672 m_frame->script().updateSecurityOrigin(securityOrigin());
4675 bool Document::isContextThread() const
4677 return isMainThread();
4680 void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
4682 m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
4683 if (!m_updateFocusAppearanceTimer.isActive())
4684 m_updateFocusAppearanceTimer.startOneShot(0);
4687 void Document::cancelFocusAppearanceUpdate()
4689 m_updateFocusAppearanceTimer.stop();
4692 void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
4694 Element* element = focusedElement();
4698 if (element->isFocusable())
4699 element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
4702 void Document::attachRange(Range* range)
4704 ASSERT(!m_ranges.contains(range));
4705 m_ranges.add(range);
4708 void Document::detachRange(Range* range)
4710 // We don't ASSERT m_ranges.contains(range) to allow us to call this
4711 // unconditionally to fix: https://bugs.webkit.org/show_bug.cgi?id=26044
4712 m_ranges.remove(range);
4715 CanvasRenderingContext* Document::getCSSCanvasContext(const String& type, const String& name, int width, int height)
4717 HTMLCanvasElement* element = getCSSCanvasElement(name);
4720 element->setSize(IntSize(width, height));
4721 return element->getContext(type);
4724 HTMLCanvasElement* Document::getCSSCanvasElement(const String& name)
4726 RefPtr<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, 0).storedValue->value;
4728 element = HTMLCanvasElement::create(*this);
4729 element->setAccelerationDisabled(true);
4731 return element.get();
4734 void Document::initDNSPrefetch()
4736 Settings* settings = this->settings();
4738 m_haveExplicitlyDisabledDNSPrefetch = false;
4739 m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
4741 // Inherit DNS prefetch opt-out from parent frame
4742 if (Document* parent = parentDocument()) {
4743 if (!parent->isDNSPrefetchEnabled())
4744 m_isDNSPrefetchEnabled = false;
4748 void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
4750 if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
4751 m_isDNSPrefetchEnabled = true;
4755 m_isDNSPrefetchEnabled = false;
4756 m_haveExplicitlyDisabledDNSPrefetch = true;
4759 void Document::reportBlockedScriptExecutionToInspector(const String& directiveText)
4761 InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText);
4764 void Document::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* state)
4766 internalAddMessage(source, level, message, sourceURL, lineNumber, 0, state);
4769 void Document::internalAddMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state)
4771 if (!isContextThread()) {
4772 m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
4775 FrameHost* host = frameHost();
4779 String messageURL = sourceURL;
4780 if (!state && sourceURL.isNull() && !lineNumber) {
4781 messageURL = url().string();
4782 if (parsing() && !isInDocumentWrite() && scriptableDocumentParser()) {
4783 ScriptableDocumentParser* parser = scriptableDocumentParser();
4784 if (!parser->isWaitingForScripts() && !parser->isExecutingScript())
4785 lineNumber = parser->lineNumber().oneBasedInt();
4788 host->console().addMessage(source, level, message, messageURL, lineNumber, 0, callStack, state, 0);
4791 void Document::addConsoleMessageWithRequestIdentifier(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
4793 if (!isContextThread()) {
4794 m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
4798 if (FrameHost* host = frameHost())
4799 host->console().addMessage(source, level, message, String(), 0, 0, 0, 0, requestIdentifier);
4802 // FIXME(crbug.com/305497): This should be removed after ExecutionContext-DOMWindow migration.
4803 void Document::postTask(PassOwnPtr<ExecutionContextTask> task)
4805 m_taskRunner->postTask(task);
4808 void Document::tasksWereSuspended()
4810 scriptRunner()->suspend();
4813 m_parser->suspendScheduledTasks();
4814 if (m_scriptedAnimationController)
4815 m_scriptedAnimationController->suspend();
4818 void Document::tasksWereResumed()
4820 scriptRunner()->resume();
4823 m_parser->resumeScheduledTasks();
4824 if (m_scriptedAnimationController)
4825 m_scriptedAnimationController->resume();
4827 MutationObserver::resumeSuspendedObservers();
4830 // FIXME: suspendScheduledTasks(), resumeScheduledTasks(), tasksNeedSuspension()
4831 // should be moved to DOMWindow once it inherits ExecutionContext
4832 void Document::suspendScheduledTasks()
4834 ExecutionContext::suspendScheduledTasks();
4835 m_taskRunner->suspend();
4838 void Document::resumeScheduledTasks()
4840 ExecutionContext::resumeScheduledTasks();
4841 m_taskRunner->resume();
4844 bool Document::tasksNeedSuspension()
4846 Page* page = this->page();
4847 return page && page->defersLoading();
4850 void Document::addToTopLayer(Element* element, const Element* before)
4852 if (element->isInTopLayer())
4855 ASSERT(!m_topLayerElements.contains(element));
4856 ASSERT(!before || m_topLayerElements.contains(before));
4858 size_t beforePosition = m_topLayerElements.find(before);
4859 m_topLayerElements.insert(beforePosition, element);
4861 m_topLayerElements.append(element);
4863 element->setIsInTopLayer(true);
4866 void Document::removeFromTopLayer(Element* element)
4868 if (!element->isInTopLayer())
4870 size_t position = m_topLayerElements.find(element);
4871 ASSERT(position != kNotFound);
4872 m_topLayerElements.remove(position);
4873 element->setIsInTopLayer(false);
4876 HTMLDialogElement* Document::activeModalDialog() const
4878 if (m_topLayerElements.isEmpty())
4880 return toHTMLDialogElement(m_topLayerElements.last().get());
4883 void Document::webkitExitPointerLock()
4887 if (Element* target = page()->pointerLockController().element()) {
4888 if (target->document() != this)
4891 page()->pointerLockController().requestPointerUnlock();
4894 Element* Document::webkitPointerLockElement() const
4896 if (!page() || page()->pointerLockController().lockPending())
4898 if (Element* element = page()->pointerLockController().element()) {
4899 if (element->document() == this)
4905 void Document::decrementLoadEventDelayCount()
4907 ASSERT(m_loadEventDelayCount);
4908 --m_loadEventDelayCount;
4910 if (frame() && !m_loadEventDelayCount && !m_loadEventDelayTimer.isActive())
4911 m_loadEventDelayTimer.startOneShot(0);
4914 void Document::loadEventDelayTimerFired(Timer<Document>*)
4917 frame()->loader().checkCompleted();
4920 void Document::loadPluginsSoon()
4922 // FIXME: Remove this timer once we don't need to compute layout to load plugins.
4923 if (!m_pluginLoadingTimer.isActive())
4924 m_pluginLoadingTimer.startOneShot(0);
4927 void Document::pluginLoadingTimerFired(Timer<Document>*)
4932 ScriptedAnimationController& Document::ensureScriptedAnimationController()
4934 if (!m_scriptedAnimationController) {
4935 m_scriptedAnimationController = ScriptedAnimationController::create(this);
4936 // We need to make sure that we don't start up the animation controller on a background tab, for example.
4938 m_scriptedAnimationController->suspend();
4940 return *m_scriptedAnimationController;
4943 int Document::requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
4945 return ensureScriptedAnimationController().registerCallback(callback);
4948 void Document::cancelAnimationFrame(int id)
4950 if (!m_scriptedAnimationController)
4952 m_scriptedAnimationController->cancelCallback(id);
4955 void Document::serviceScriptedAnimations(double monotonicAnimationStartTime)
4957 if (!m_scriptedAnimationController)
4959 m_scriptedAnimationController->serviceScriptedAnimations(monotonicAnimationStartTime);
4962 PassRefPtr<Touch> Document::createTouch(DOMWindow* window, EventTarget* target, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force) const
4964 // FIXME: It's not clear from the documentation at
4965 // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html
4966 // when this method should throw and nor is it by inspection of iOS behavior. It would be nice to verify any cases where it throws under iOS
4967 // and implement them here. See https://bugs.webkit.org/show_bug.cgi?id=47819
4968 Frame* frame = window ? window->frame() : this->frame();
4969 return Touch::create(frame, target, identifier, screenX, screenY, pageX, pageY, radiusX, radiusY, rotationAngle, force);
4972 PassRefPtr<TouchList> Document::createTouchList(Vector<RefPtr<Touch> >& touches) const
4974 return TouchList::create(touches);
4977 void Document::didAddTouchEventHandler(Node* handler)
4979 // The node should either be in this document, or be the Document node of a child
4980 // of this document.
4981 ASSERT(&handler->document() == this
4982 || (handler->isDocumentNode() && toDocument(handler)->parentDocument() == this));
4983 if (!m_touchEventTargets.get())
4984 m_touchEventTargets = adoptPtr(new TouchEventTargetSet);
4985 bool isFirstHandler = m_touchEventTargets->isEmpty();
4987 if (!m_touchEventTargets->add(handler).isNewEntry) {
4988 // Just incremented refcount, no real change.
4989 // If this is a child document node, then the count should never go above 1.
4990 ASSERT(!handler->isDocumentNode() || &handler->document() == this);
4994 if (isFirstHandler) {
4995 if (Document* parent = parentDocument()) {
4996 parent->didAddTouchEventHandler(this);
4998 // This is the first touch handler on the whole page.
4999 if (FrameHost* frameHost = this->frameHost())
5000 frameHost->chrome().client().needTouchEvents(true);
5004 // When we're all done with all frames, ensure touch hit rects are marked as dirty.
5005 if (!handler->isDocumentNode() || handler == this) {
5006 if (Page* page = this->page()) {
5007 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
5008 scrollingCoordinator->touchEventTargetRectsDidChange();
5013 void Document::didRemoveTouchEventHandler(Node* handler, bool clearAll)
5015 // Note that we can't assert that |handler| is in this document because it might be in
5016 // the process of moving out of it.
5017 ASSERT(clearAll || m_touchEventTargets->contains(handler));
5018 if (!m_touchEventTargets.get())
5022 if (!m_touchEventTargets->contains(handler))
5024 m_touchEventTargets->removeAll(handler);
5026 if (!m_touchEventTargets->remove(handler))
5027 // Just decremented refcount, no real update.
5031 if (m_touchEventTargets->isEmpty()) {
5032 if (Document* parent = parentDocument()) {
5033 // This was the last handler in this document, update the parent document too.
5034 parent->didRemoveTouchEventHandler(this, clearAll);
5036 // We just removed the last touch handler on the whole page.
5037 if (FrameHost* frameHost = this->frameHost())
5038 frameHost->chrome().client().needTouchEvents(false);
5042 // When we're all done with all frames, ensure touch hit rects are marked as dirty.
5043 if (!handler->isDocumentNode() || handler == this) {
5044 if (Page* page = this->page()) {
5045 if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
5046 scrollingCoordinator->touchEventTargetRectsDidChange();
5051 void Document::resetLastHandledUserGestureTimestamp()
5053 m_lastHandledUserGestureTimestamp = currentTime();
5056 DocumentLoader* Document::loader() const
5061 DocumentLoader* loader = m_frame->loader().documentLoader();
5065 if (m_frame->document() != this)
5071 IntSize Document::initialViewportSize() const
5075 return view()->unscaledVisibleContentSize(ScrollableArea::IncludeScrollbars);
5078 Node* eventTargetNodeForDocument(Document* doc)
5082 Node* node = doc->focusedElement();
5083 if (!node && doc->isPluginDocument()) {
5084 PluginDocument* pluginDocument = toPluginDocument(doc);
5085 node = pluginDocument->pluginNode();
5087 if (!node && doc->isHTMLDocument())
5090 node = doc->documentElement();
5094 void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject& renderer)
5099 LayoutRect visibleContentRect = view()->visibleContentRect();
5100 for (size_t i = 0; i < quads.size(); ++i) {
5101 quads[i].move(-visibleContentRect.x(), -visibleContentRect.y());
5102 adjustFloatQuadForAbsoluteZoom(quads[i], renderer);
5106 void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject& renderer)
5111 LayoutRect visibleContentRect = view()->visibleContentRect();
5112 rect.move(-visibleContentRect.x(), -visibleContentRect.y());
5113 adjustFloatRectForAbsoluteZoom(rect, renderer);
5116 bool Document::hasActiveParser()
5118 return m_activeParserCount || (m_parser && m_parser->processingData());
5121 void Document::decrementActiveParserCount()
5123 --m_activeParserCount;
5126 // FIXME: This should always be enabled, but it seems to cause
5127 // http/tests/security/feed-urls-from-remote.html to timeout on Mac WK1
5128 // see http://webkit.org/b/110554 and http://webkit.org/b/110401
5129 loader()->checkLoadComplete();
5130 frame()->loader().checkLoadComplete();
5133 void Document::setContextFeatures(PassRefPtr<ContextFeatures> features)
5135 m_contextFeatures = features;
5138 static RenderObject* nearestCommonHoverAncestor(RenderObject* obj1, RenderObject* obj2)
5143 for (RenderObject* currObj1 = obj1; currObj1; currObj1 = currObj1->hoverAncestor()) {
5144 for (RenderObject* currObj2 = obj2; currObj2; currObj2 = currObj2->hoverAncestor()) {
5145 if (currObj1 == currObj2)
5153 void Document::updateHoverActiveState(const HitTestRequest& request, Element* innerElement, const PlatformMouseEvent* event)
5155 ASSERT(!request.readOnly());
5157 if (request.active() && m_frame)
5158 m_frame->eventHandler().notifyElementActivated();
5160 Element* innerElementInDocument = innerElement;
5161 while (innerElementInDocument && innerElementInDocument->document() != this) {
5162 innerElementInDocument->document().updateHoverActiveState(request, innerElementInDocument, event);
5163 innerElementInDocument = innerElementInDocument->document().ownerElement();
5166 Element* oldActiveElement = activeHoverElement();
5167 if (oldActiveElement && !request.active()) {
5168 // We are clearing the :active chain because the mouse has been released.
5169 for (RenderObject* curr = oldActiveElement->renderer(); curr; curr = curr->parent()) {
5171 ASSERT(!curr->node()->isTextNode());
5172 curr->node()->setActive(false);
5173 m_userActionElements.setInActiveChain(curr->node(), false);
5176 setActiveHoverElement(0);
5178 Element* newActiveElement = innerElementInDocument;
5179 if (!oldActiveElement && newActiveElement && request.active() && !request.touchMove()) {
5180 // We are setting the :active chain and freezing it. If future moves happen, they
5181 // will need to reference this chain.
5182 for (RenderObject* curr = newActiveElement->renderer(); curr; curr = curr->parent()) {
5183 if (curr->node() && !curr->isText())
5184 m_userActionElements.setInActiveChain(curr->node(), true);
5187 setActiveHoverElement(newActiveElement);
5190 // If the mouse has just been pressed, set :active on the chain. Those (and only those)
5191 // nodes should remain :active until the mouse is released.
5192 bool allowActiveChanges = !oldActiveElement && activeHoverElement();
5194 // If the mouse is down and if this is a mouse move event, we want to restrict changes in
5195 // :hover/:active to only apply to elements that are in the :active chain that we froze
5196 // at the time the mouse went down.
5197 bool mustBeInActiveChain = request.active() && request.move();
5199 RefPtr<Node> oldHoverNode = hoverNode();
5201 // Check to see if the hovered node has changed.
5202 // If it hasn't, we do not need to do anything.
5203 Node* newHoverNode = innerElementInDocument;
5204 while (newHoverNode && !newHoverNode->renderer())
5205 newHoverNode = newHoverNode->parentOrShadowHostNode();
5207 // Update our current hover node.
5208 setHoverNode(newHoverNode);
5210 // We have two different objects. Fetch their renderers.
5211 RenderObject* oldHoverObj = oldHoverNode ? oldHoverNode->renderer() : 0;
5212 RenderObject* newHoverObj = newHoverNode ? newHoverNode->renderer() : 0;
5214 // Locate the common ancestor render object for the two renderers.
5215 RenderObject* ancestor = nearestCommonHoverAncestor(oldHoverObj, newHoverObj);
5216 RefPtr<Node> ancestorNode(ancestor ? ancestor->node() : 0);
5218 Vector<RefPtr<Node>, 32> nodesToRemoveFromChain;
5219 Vector<RefPtr<Node>, 32> nodesToAddToChain;
5221 if (oldHoverObj != newHoverObj) {
5222 // If the old hovered node is not nil but it's renderer is, it was probably detached as part of the :hover style
5223 // (for instance by setting display:none in the :hover pseudo-class). In this case, the old hovered element (and its ancestors)
5224 // must be updated, to ensure it's normal style is re-applied.
5225 if (oldHoverNode && !oldHoverObj) {
5226 for (Node* node = oldHoverNode.get(); node; node = node->parentNode()) {
5227 if (!mustBeInActiveChain || (node->isElementNode() && toElement(node)->inActiveChain()))
5228 nodesToRemoveFromChain.append(node);
5233 // The old hover path only needs to be cleared up to (and not including) the common ancestor;
5234 for (RenderObject* curr = oldHoverObj; curr && curr != ancestor; curr = curr->hoverAncestor()) {
5235 if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5236 nodesToRemoveFromChain.append(curr->node());
5240 // Now set the hover state for our new object up to the root.
5241 for (RenderObject* curr = newHoverObj; curr; curr = curr->hoverAncestor()) {
5242 if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
5243 nodesToAddToChain.append(curr->node());
5246 // mouseenter and mouseleave events do not bubble, so they are dispatched iff there is a capturing
5247 // event handler on an ancestor or a normal event handler on the element itself. This special
5248 // handling is necessary to avoid O(n^2) capturing event handler checks. We'll check the previously
5249 // hovered node's ancestor tree for 'mouseleave' handlers here, then check the newly hovered node's
5250 // ancestor tree for 'mouseenter' handlers after dispatching the 'mouseleave' events (as the handler
5251 // for 'mouseleave' might set a capturing 'mouseenter' handler, odd as that might be).
5252 bool ancestorHasCapturingMouseleaveListener = false;
5253 if (event && newHoverNode != oldHoverNode.get()) {
5254 for (Node* node = oldHoverNode.get(); node; node = node->parentOrShadowHostNode()) {
5255 if (node->hasCapturingEventListeners(EventTypeNames::mouseleave)) {
5256 ancestorHasCapturingMouseleaveListener = true;
5262 size_t removeCount = nodesToRemoveFromChain.size();
5263 for (size_t i = 0; i < removeCount; ++i) {
5264 nodesToRemoveFromChain[i]->setHovered(false);
5265 if (event && (ancestorHasCapturingMouseleaveListener || nodesToRemoveFromChain[i]->hasEventListeners(EventTypeNames::mouseleave)))
5266 nodesToRemoveFromChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseleave, 0, newHoverNode);
5269 bool ancestorHasCapturingMouseenterListener = false;
5270 if (event && newHoverNode != oldHoverNode.get()) {
5271 for (Node* node = newHoverNode; node; node = node->parentOrShadowHostNode()) {
5272 if (node->hasCapturingEventListeners(EventTypeNames::mouseenter)) {
5273 ancestorHasCapturingMouseenterListener = true;
5279 bool sawCommonAncestor = false;
5280 size_t addCount = nodesToAddToChain.size();
5281 for (size_t i = 0; i < addCount; ++i) {
5282 // Elements past the common ancestor do not change hover state, but might change active state.
5283 if (ancestorNode && nodesToAddToChain[i] == ancestorNode)
5284 sawCommonAncestor = true;
5285 if (allowActiveChanges)
5286 nodesToAddToChain[i]->setActive(true);
5287 if (!sawCommonAncestor) {
5288 nodesToAddToChain[i]->setHovered(true);
5289 if (event && (ancestorHasCapturingMouseenterListener || nodesToAddToChain[i]->hasEventListeners(EventTypeNames::mouseenter)))
5290 nodesToAddToChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseenter, 0, oldHoverNode.get());
5294 updateStyleIfNeeded();
5297 bool Document::haveStylesheetsLoaded() const
5299 return m_styleEngine->haveStylesheetsLoaded();
5302 Locale& Document::getCachedLocale(const AtomicString& locale)
5304 AtomicString localeKey = locale;
5305 if (locale.isEmpty() || !RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
5306 return Locale::defaultLocale();
5307 LocaleIdentifierToLocaleMap::AddResult result = m_localeCache.add(localeKey, nullptr);
5308 if (result.isNewEntry)
5309 result.storedValue->value = Locale::create(localeKey);
5310 return *(result.storedValue->value);
5313 Document& Document::ensureTemplateDocument()
5315 if (isTemplateDocument())
5318 if (m_templateDocument)
5319 return *m_templateDocument;
5321 if (isHTMLDocument()) {
5322 DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL()).withNewRegistrationContext();
5323 m_templateDocument = HTMLDocument::create(init);
5325 m_templateDocument = Document::create(DocumentInit(blankURL()));
5328 m_templateDocument->m_templateDocumentHost = this; // balanced in dtor.
5330 return *m_templateDocument.get();
5333 void Document::didAssociateFormControl(Element* element)
5335 if (!frame() || !frame()->page())
5337 m_associatedFormControls.add(element);
5338 if (!m_didAssociateFormControlsTimer.isActive())
5339 m_didAssociateFormControlsTimer.startOneShot(0);
5342 void Document::didAssociateFormControlsTimerFired(Timer<Document>* timer)
5344 ASSERT_UNUSED(timer, timer == &m_didAssociateFormControlsTimer);
5345 if (!frame() || !frame()->page())
5348 Vector<RefPtr<Element> > associatedFormControls;
5349 copyToVector(m_associatedFormControls, associatedFormControls);
5351 frame()->page()->chrome().client().didAssociateFormControls(associatedFormControls);
5352 m_associatedFormControls.clear();
5355 float Document::devicePixelRatio() const
5357 return m_frame ? m_frame->devicePixelRatio() : 1.0;
5360 PassOwnPtr<LifecycleNotifier<Document> > Document::createLifecycleNotifier()
5362 return DocumentLifecycleNotifier::create(this);
5365 DocumentLifecycleNotifier& Document::lifecycleNotifier()
5367 return static_cast<DocumentLifecycleNotifier&>(LifecycleContext<Document>::lifecycleNotifier());
5370 void Document::removedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
5372 // If we're in document teardown, then we don't need this notification of our sheet's removal.
5373 // styleResolverChanged() is needed even when the document is inactive so that
5374 // imported docuements (which is inactive) notifies the change to the master document.
5376 styleEngine()->modifiedStyleSheet(sheet);
5377 styleResolverChanged(when, updateMode);
5380 void Document::modifiedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
5382 // If we're in document teardown, then we don't need this notification of our sheet's removal.
5383 // styleResolverChanged() is needed even when the document is inactive so that
5384 // imported docuements (which is inactive) notifies the change to the master document.
5386 styleEngine()->modifiedStyleSheet(sheet);
5387 styleResolverChanged(when, updateMode);
5390 TextAutosizer* Document::textAutosizer()
5392 if (!m_textAutosizer && !RuntimeEnabledFeatures::fastTextAutosizingEnabled())
5393 m_textAutosizer = TextAutosizer::create(this);
5394 return m_textAutosizer.get();
5397 FastTextAutosizer* Document::fastTextAutosizer()
5399 if (!m_fastTextAutosizer && RuntimeEnabledFeatures::fastTextAutosizingEnabled())
5400 m_fastTextAutosizer = FastTextAutosizer::create(this);
5401 return m_fastTextAutosizer.get();
5404 void Document::setAutofocusElement(Element* element)
5407 m_autofocusElement = 0;
5410 if (m_hasAutofocused)
5412 m_hasAutofocused = true;
5413 ASSERT(!m_autofocusElement);
5414 m_autofocusElement = element;
5415 m_taskRunner->postTask(AutofocusTask::create());
5418 Element* Document::activeElement() const
5420 if (Element* element = treeScope().adjustedFocusedElement())
5425 bool Document::hasFocus() const
5427 Page* page = this->page();
5430 if (!page->focusController().isActive() || !page->focusController().isFocused())
5432 if (Frame* focusedFrame = page->focusController().focusedFrame()) {
5433 if (focusedFrame->tree().isDescendantOf(frame()))
5439 // FIXME: Remove this code once we have input routing in the browser
5440 // process. See http://crbug.com/339659.
5441 void Document::defaultEventHandler(Event* event)
5443 if (frame() && frame()->remotePlatformLayer()) {
5444 frame()->chromeClient().forwardInputEvent(this, event);
5447 Node::defaultEventHandler(event);
5450 } // namespace WebCore