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.
31 #include "AXObjectCache.h"
32 #include "AnimationController.h"
34 #include "Attribute.h"
35 #include "CDATASection.h"
36 #include "CSSParser.h"
37 #include "CSSStyleDeclaration.h"
38 #include "CSSStyleSheet.h"
39 #include "CSSValueKeywords.h"
40 #include "CachedCSSStyleSheet.h"
41 #include "CachedResourceLoader.h"
43 #include "ChromeClient.h"
46 #include "ContentSecurityPolicy.h"
47 #include "ContextFeatures.h"
48 #include "CookieJar.h"
49 #include "DOMImplementation.h"
50 #include "DOMSelection.h"
51 #include "DOMWindow.h"
52 #include "DateComponents.h"
53 #include "DeviceMotionController.h"
54 #include "DeviceMotionEvent.h"
55 #include "DeviceOrientationController.h"
56 #include "DeviceOrientationEvent.h"
57 #include "DocumentEventQueue.h"
58 #include "DocumentFragment.h"
59 #include "DocumentLoader.h"
60 #include "DocumentMarkerController.h"
61 #include "DocumentType.h"
62 #include "EditingText.h"
65 #include "ElementShadow.h"
66 #include "EntityReference.h"
68 #include "EventFactory.h"
69 #include "EventHandler.h"
70 #include "EventListener.h"
71 #include "EventNames.h"
72 #include "ExceptionCode.h"
73 #include "FlowThreadController.h"
74 #include "FocusController.h"
75 #include "FormController.h"
77 #include "FrameLoader.h"
78 #include "FrameLoaderClient.h"
79 #include "FrameSelection.h"
80 #include "FrameTree.h"
81 #include "FrameView.h"
82 #include "GeolocationController.h"
83 #include "HashChangeEvent.h"
84 #include "HistogramSupport.h"
86 #include "HTMLAllCollection.h"
87 #include "HTMLAnchorElement.h"
88 #include "HTMLBodyElement.h"
89 #include "HTMLCanvasElement.h"
90 #include "HTMLCollection.h"
91 #include "HTMLDocument.h"
92 #include "HTMLElementFactory.h"
93 #include "HTMLFrameOwnerElement.h"
94 #include "HTMLHeadElement.h"
95 #include "HTMLIFrameElement.h"
96 #include "HTMLLinkElement.h"
97 #include "HTMLMapElement.h"
98 #include "HTMLNameCollection.h"
99 #include "HTMLNames.h"
100 #include "HTMLParserIdioms.h"
101 #include "HTMLStyleElement.h"
102 #include "HTMLTitleElement.h"
103 #include "HTTPParsers.h"
104 #include "HitTestRequest.h"
105 #include "HitTestResult.h"
106 #include "ImageLoader.h"
107 #include "InspectorCounters.h"
108 #include "InspectorInstrumentation.h"
110 #include "MediaQueryList.h"
111 #include "MediaQueryMatcher.h"
112 #include "MemoryInstrumentation.h"
113 #include "MouseEventWithHitTestResults.h"
114 #include "NameNodeList.h"
115 #include "NestingLevelIncrementer.h"
116 #include "NewXMLDocumentParser.h"
117 #include "NodeFilter.h"
118 #include "NodeIterator.h"
119 #include "NodeRareData.h"
120 #include "NodeWithIndex.h"
122 #include "PageGroup.h"
123 #include "PageTransitionEvent.h"
124 #include "PlatformKeyboardEvent.h"
125 #include "PluginDocument.h"
126 #include "PointerLockController.h"
127 #include "PopStateEvent.h"
128 #include "ProcessingInstruction.h"
129 #include "RegisteredEventListener.h"
130 #include "RenderArena.h"
131 #include "RenderLayerCompositor.h"
132 #include "RenderNamedFlowThread.h"
133 #include "RenderTextControl.h"
134 #include "RenderView.h"
135 #include "RenderWidget.h"
136 #include "SchemeRegistry.h"
137 #include "ScopedEventQueue.h"
138 #include "ScriptCallStack.h"
139 #include "ScriptController.h"
140 #include "ScriptElement.h"
141 #include "ScriptEventListener.h"
142 #include "ScriptRunner.h"
143 #include "ScrollingCoordinator.h"
144 #include "SecurityOrigin.h"
145 #include "SecurityPolicy.h"
146 #include "SegmentedString.h"
147 #include "SelectorQuery.h"
148 #include "Settings.h"
149 #include "ShadowRoot.h"
150 #include "StaticHashSetNodeList.h"
151 #include "StyleResolver.h"
152 #include "StyleSheetContents.h"
153 #include "StyleSheetList.h"
154 #include "TextResourceDecoder.h"
156 #include "TransformSource.h"
157 #include "TreeWalker.h"
158 #include "UndoManager.h"
159 #include "UserContentURLPattern.h"
160 #include "WebKitNamedFlow.h"
161 #include "WebKitNamedFlowCollection.h"
162 #include "XMLDocumentParser.h"
163 #include "XMLHttpRequest.h"
164 #include "XMLNSNames.h"
165 #include "XMLNames.h"
166 #include "XPathEvaluator.h"
167 #include "XPathExpression.h"
168 #include "XPathNSResolver.h"
169 #include "XPathResult.h"
170 #include "htmlediting.h"
171 #include <wtf/CurrentTime.h>
172 #include <wtf/HashFunctions.h>
173 #include <wtf/MainThread.h>
174 #include <wtf/PassRefPtr.h>
175 #include <wtf/StdLibExtras.h>
176 #include <wtf/text/StringBuffer.h>
178 #if ENABLE(SHARED_WORKERS)
179 #include "SharedWorkerRepository.h"
183 #include "XSLTProcessor.h"
187 #include "SVGDocumentExtensions.h"
188 #include "SVGElementFactory.h"
189 #include "SVGNames.h"
190 #include "SVGSVGElement.h"
191 #include "SVGStyleElement.h"
194 #if ENABLE(TOUCH_EVENTS)
195 #include "TouchList.h"
199 #include "MathMLElement.h"
200 #include "MathMLElementFactory.h"
201 #include "MathMLNames.h"
204 #if ENABLE(FULLSCREEN_API)
205 #include "RenderFullScreen.h"
208 #if ENABLE(REQUEST_ANIMATION_FRAME)
209 #include "RequestAnimationFrameCallback.h"
210 #include "ScriptedAnimationController.h"
213 #if ENABLE(MICRODATA)
214 #include "MicroDataItemList.h"
215 #include "NodeRareData.h"
218 #if ENABLE(LINK_PRERENDER)
219 #include "Prerenderer.h"
222 #if ENABLE(TEXT_AUTOSIZING)
223 #include "TextAutosizer.h"
227 #include "DOMSecurityPolicy.h"
230 #if ENABLE(TIZEN_EXTENSIBLE_API)
231 #include "TizenExtensibleAPI.h"
234 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
235 #include "AudioSessionManagerGStreamerTizen.h"
240 using namespace Unicode;
244 using namespace HTMLNames;
246 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
248 static const unsigned cMaxWriteRecursionDepth = 21;
250 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
251 // FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
253 static const int cLayoutScheduleThreshold = 250;
255 // DOM Level 2 says (letters added):
257 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
258 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
259 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
260 // 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.
261 // 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.
262 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
263 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
264 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
265 // i) Characters ':' and '_' are allowed as name-start characters.
266 // j) Characters '-' and '.' are allowed as name characters.
268 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
270 static inline bool isValidNameStart(UChar32 c)
273 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
277 if (c == ':' || c == '_')
280 // rules (a) and (f) above
281 const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
282 if (!(Unicode::category(c) & nameStartMask))
286 if (c >= 0xF900 && c < 0xFFFE)
290 DecompositionType decompType = decompositionType(c);
291 if (decompType == DecompositionFont || decompType == DecompositionCompat)
297 static inline bool isValidNamePart(UChar32 c)
299 // rules (a), (e), and (i) above
300 if (isValidNameStart(c))
303 // rules (g) and (h) above
304 if (c == 0x00B7 || c == 0x0387)
308 if (c == '-' || c == '.')
311 // rules (b) and (f) above
312 const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
313 if (!(Unicode::category(c) & otherNamePartMask))
317 if (c >= 0xF900 && c < 0xFFFE)
321 DecompositionType decompType = decompositionType(c);
322 if (decompType == DecompositionFont || decompType == DecompositionCompat)
328 static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
330 // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
332 // If a Document has the address "about:blank"
333 // The origin of the Document is the origin it was assigned when its browsing context was created.
335 // Note: We generalize this to all "blank" URLs and invalid URLs because we
336 // treat all of these URLs as about:blank.
338 return !url.isValid() || url.isBlankURL();
341 static Widget* widgetForNode(Node* focusedNode)
345 RenderObject* renderer = focusedNode->renderer();
346 if (!renderer || !renderer->isWidget())
348 return toRenderWidget(renderer)->widget();
351 static bool acceptsEditingFocus(Node* node)
354 ASSERT(node->rendererIsEditable());
356 Node* root = node->rootEditableElement();
357 Frame* frame = node->document()->frame();
361 return frame->editor()->shouldBeginEditing(rangeOfContents(root).get());
364 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
366 // targetFrame can be 0 when we're trying to navigate a top-level frame
367 // that has a 0 opener.
371 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
372 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree()->parent()) {
373 Document* ancestorDocument = ancestorFrame->document();
374 // FIXME: Should be an ASSERT? Frames should alway have documents.
375 if (!ancestorDocument)
378 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
379 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
382 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
383 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
384 // something more general instead?
385 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
392 static void printNavigationErrorMessage(Frame* frame, const KURL& activeURL)
394 // FIXME: this error message should contain more specifics of why the navigation change is not allowed.
395 String message = "Unsafe JavaScript attempt to initiate a navigation change for frame with URL " +
396 frame->document()->url().string() + " from frame with URL " + activeURL.string() + ".\n";
398 // FIXME: should we print to the console of the document performing the navigation instead?
399 frame->domWindow()->printErrorMessage(message);
402 static HashSet<Document*>* documentsThatNeedStyleRecalc = 0;
404 class DocumentWeakReference : public ThreadSafeRefCounted<DocumentWeakReference> {
406 static PassRefPtr<DocumentWeakReference> create(Document* document)
408 return adoptRef(new DocumentWeakReference(document));
413 ASSERT(isMainThread());
419 ASSERT(isMainThread());
424 DocumentWeakReference(Document* document)
425 : m_document(document)
427 ASSERT(isMainThread());
430 Document* m_document;
433 uint64_t Document::s_globalTreeVersion = 0;
435 Document::Document(Frame* frame, const KURL& url, bool isXHTML, bool isHTML)
436 : ContainerNode(0, CreateDocument)
439 , m_contextFeatures(ContextFeatures::defaultSwitch())
440 , m_compatibilityMode(NoQuirksMode)
441 , m_compatibilityModeLocked(false)
442 , m_domTreeVersion(++s_globalTreeVersion)
443 #if ENABLE(MUTATION_OBSERVERS)
444 , m_mutationObserverTypes(0)
446 , m_styleSheets(StyleSheetList::create(this))
447 , m_hadActiveLoadingStylesheet(false)
448 , m_readyState(Complete)
449 , m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
450 , m_pendingStyleRecalcShouldForce(false)
451 , m_frameElementsShouldIgnoreScrolling(false)
452 , m_containsValidityStyleRules(false)
453 , m_updateFocusAppearanceRestoresSelection(false)
454 , m_ignoreDestructiveWriteCount(0)
455 , m_titleSetExplicitly(false)
456 , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
457 , m_loadEventFinished(false)
458 , m_startTime(currentTime())
459 , m_overMinimumLayoutThreshold(false)
460 , m_scriptRunner(ScriptRunner::create(this))
461 , m_xmlVersion("1.0")
462 , m_xmlStandalone(StandaloneUnspecified)
463 , m_hasXMLDeclaration(0)
465 , m_designMode(inherit)
466 #if ENABLE(DASHBOARD_SUPPORT)
467 , m_hasDashboardRegions(false)
468 , m_dashboardRegionsDirty(false)
470 , m_createRenderers(true)
471 , m_inPageCache(false)
472 , m_accessKeyMapValid(false)
473 , m_useSecureKeyboardEntryWhenActive(false)
476 , m_isViewSource(false)
477 , m_sawElementsInKnownNamespaces(false)
478 , m_isSrcdocDocument(false)
479 , m_documentRareData(0)
480 , m_eventQueue(DocumentEventQueue::create(this))
481 , m_weakReference(DocumentWeakReference::create(this))
482 , m_idAttributeName(idAttr)
483 #if ENABLE(FULLSCREEN_API)
484 , m_areKeysEnabledInFullScreen(0)
485 , m_fullScreenRenderer(0)
486 , m_fullScreenChangeDelayTimer(this, &Document::fullScreenChangeDelayTimerFired)
487 , m_isAnimatingFullScreen(false)
488 #if ENABLE(TIZEN_FULLSCREEN_API)
489 , m_exitFullScreenByHwBackKey(false)
492 , m_loadEventDelayCount(0)
493 , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
494 , m_referrerPolicy(ReferrerPolicyDefault)
495 , m_directionSetOnDocumentElement(false)
496 , m_writingModeSetOnDocumentElement(false)
497 , m_writeRecursionIsTooDeep(false)
498 , m_writeRecursionDepth(0)
499 , m_wheelEventHandlerCount(0)
500 #if ENABLE(TOUCH_EVENTS)
501 , m_touchEventHandlerCount(0)
503 #if ENABLE(UNDO_MANAGER)
506 , m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
507 , m_scheduledTasksAreSuspended(false)
508 , m_visualUpdatesAllowed(true)
509 , m_visualUpdatesSuppressionTimer(this, &Document::visualUpdatesSuppressionTimerFired)
511 , m_didDispatchViewportPropertiesChanged(false)
513 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
514 , m_activeMediaObjectCount(0)
516 #if ENABLE(TIZEN_INPUT_TAG_EXTENSION)
517 , m_currentTargetNode(0)
522 m_pageGroupUserSheetCacheValid = false;
525 m_paginatedForScreen = false;
527 m_ignoreAutofocus = false;
531 provideContextFeaturesToDocumentFrom(this, m_frame->page());
533 // We depend on the url getting immediately set in subframes, but we
534 // also depend on the url NOT getting immediately set in opened windows.
535 // See fast/dom/early-frame-url.html
536 // and fast/dom/location-new-window-no-crash.html, respectively.
537 // FIXME: Can/should we unify this behavior?
538 if ((frame && frame->ownerElement()) || !url.isEmpty())
543 m_markers = adoptPtr(new DocumentMarkerController);
545 m_cachedResourceLoader = adoptPtr(new CachedResourceLoader(this));
546 #if ENABLE(LINK_PRERENDER)
547 m_prerenderer = Prerenderer::create(this);
549 #if ENABLE(TEXT_AUTOSIZING)
550 m_textAutosizer = TextAutosizer::create(this);
552 m_visuallyOrdered = false;
554 m_wellFormed = false;
556 m_textColor = Color::black;
558 m_inStyleRecalc = false;
559 m_closeAfterStyleRecalc = false;
561 m_usesSiblingRules = false;
562 m_usesSiblingRulesOverride = false;
563 m_usesFirstLineRules = false;
564 m_usesFirstLetterRules = false;
565 m_usesBeforeAfterRules = false;
566 m_usesBeforeAfterRulesOverride = false;
567 m_usesRemUnits = false;
568 m_usesLinkRules = false;
570 m_gotoAnchorNeededAfterStylesheetsLoad = false;
572 m_didCalculateStyleResolver = false;
573 m_hasDirtyStyleResolver = false;
574 m_pendingStylesheets = 0;
575 m_ignorePendingStylesheets = false;
576 m_hasNodesWithPlaceholderStyle = false;
577 m_pendingSheetLayout = NoLayoutWithPendingSheets;
582 resetVisitedLinkColor();
583 resetActiveLinkColor();
585 m_processingLoadEvent = false;
587 initSecurityContext();
590 static int docID = 0;
593 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
594 m_nodeListCounts[i] = 0;
596 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_collections); i++)
597 m_collections[i] = 0;
599 InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
602 static void histogramMutationEventUsage(const unsigned short& listenerTypes)
604 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMSubtreeModified", static_cast<bool>(listenerTypes & Document::DOMSUBTREEMODIFIED_LISTENER), 2);
605 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInserted", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTED_LISTENER), 2);
606 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemoved", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVED_LISTENER), 2);
607 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemovedFromDocument", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER), 2);
608 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInsertedIntoDocument", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER), 2);
609 HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMCharacterDataModified", static_cast<bool>(listenerTypes & Document::DOMCHARACTERDATAMODIFIED_LISTENER), 2);
612 #if ENABLE(FULLSCREEN_API)
613 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const HTMLFrameOwnerElement* owner)
618 if (!owner->hasAttribute(attribute))
620 } while ((owner = owner->document()->ownerElement()));
625 Document::~Document()
628 ASSERT(!m_inPageCache);
629 ASSERT(!m_savedRenderer);
630 ASSERT(m_ranges.isEmpty());
631 ASSERT(!m_styleRecalcTimer.isActive());
632 ASSERT(!m_parentTreeScope);
633 ASSERT(!m_guardRefCount);
635 m_scriptRunner.clear();
637 histogramMutationEventUsage(m_listenerTypes);
639 removeAllEventListeners();
641 // Currently we believe that Document can never outlive the parser.
642 // Although the Document may be replaced synchronously, DocumentParsers
643 // generally keep at least one reference to an Element which would in turn
644 // has a reference to the Document. If you hit this ASSERT, then that
645 // assumption is wrong. DocumentParser::detach() should ensure that even
646 // if the DocumentParser outlives the Document it won't cause badness.
647 ASSERT(!m_parser || m_parser->refCount() == 1);
650 m_renderArena.clear();
652 clearAXObjectCache();
657 m_styleSheets->documentDestroyed();
660 m_namedFlows->documentDestroyed();
663 m_elemSheet->clearOwnerNode();
665 m_pageUserSheet->clearOwnerNode();
666 if (m_pageGroupUserSheets) {
667 for (size_t i = 0; i < m_pageGroupUserSheets->size(); ++i)
668 (*m_pageGroupUserSheets)[i]->clearOwnerNode();
671 for (size_t i = 0; i < m_userSheets->size(); ++i)
672 (*m_userSheets)[i]->clearOwnerNode();
677 m_weakReference->clear();
679 if (m_mediaQueryMatcher)
680 m_mediaQueryMatcher->documentDestroyed();
682 clearStyleResolver(); // We need to destory CSSFontSelector before destroying m_cachedResourceLoader.
683 m_cachedResourceLoader.clear();
685 #if ENABLE(UNDO_MANAGER)
687 m_undoManager->disconnect();
690 // We must call clearRareData() here since a Document class inherits TreeScope
691 // as well as Node. See a comment on TreeScope.h for the reason.
695 ASSERT(!m_listsInvalidatedAtDocument.size());
697 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); i++)
698 ASSERT(!m_nodeListCounts[i]);
700 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_collections); i++)
701 ASSERT(!m_collections[i]);
705 InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
708 void Document::removedLastRef()
710 ASSERT(!m_deletionHasBegun);
711 if (m_guardRefCount) {
712 // If removing a child removes the last self-only ref, we don't
713 // want the scope to be destructed until after
714 // removeAllChildren returns, so we guard ourselves with an
715 // extra self-only ref.
718 // We must make sure not to be retaining any of our children through
719 // these extra pointers or we will create a reference cycle.
725 m_documentElement = 0;
726 #if ENABLE(TIZEN_INPUT_TAG_EXTENSION)
727 m_currentTargetNode = 0;
729 m_contextFeatures = ContextFeatures::defaultSwitch();
730 #if ENABLE(FULLSCREEN_API)
731 m_fullScreenElement = 0;
732 m_fullScreenElementStack.clear();
737 // removeAllChildren() doesn't always unregister IDs,
738 // so tear down scope information upfront to avoid having stale references in the map.
739 destroyTreeScopeData();
744 m_cssCanvasElements.clear();
746 #if ENABLE(REQUEST_ANIMATION_FRAME)
747 // FIXME: consider using ActiveDOMObject.
748 if (m_scriptedAnimationController)
749 m_scriptedAnimationController->clearDocumentPointer();
750 m_scriptedAnimationController.clear();
754 m_inRemovedLastRefFunction = false;
760 m_deletionHasBegun = true;
766 Element* Document::getElementById(const AtomicString& id) const
768 return TreeScope::getElementById(id);
771 Element* Document::getElementByAccessKey(const String& key)
775 if (!m_accessKeyMapValid) {
776 buildAccessKeyMap(this);
777 m_accessKeyMapValid = true;
779 return m_elementsByAccessKey.get(key.impl());
782 void Document::buildAccessKeyMap(TreeScope* scope)
785 Node* rootNode = scope->rootNode();
786 for (Node* node = rootNode; node; node = node->traverseNextNode(rootNode)) {
787 if (!node->isElementNode())
789 Element* element = static_cast<Element*>(node);
790 const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
791 if (!accessKey.isEmpty())
792 m_elementsByAccessKey.set(accessKey.impl(), element);
794 for (ShadowRoot* root = node->youngestShadowRoot(); root; root = root->olderShadowRoot())
795 buildAccessKeyMap(root);
799 void Document::invalidateAccessKeyMap()
801 m_accessKeyMapValid = false;
802 m_elementsByAccessKey.clear();
805 SelectorQueryCache* Document::selectorQueryCache()
807 if (!m_selectorQueryCache)
808 m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
809 return m_selectorQueryCache.get();
812 MediaQueryMatcher* Document::mediaQueryMatcher()
814 if (!m_mediaQueryMatcher)
815 m_mediaQueryMatcher = MediaQueryMatcher::create(this);
816 return m_mediaQueryMatcher.get();
819 void Document::setCompatibilityMode(CompatibilityMode mode)
821 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
823 ASSERT(!m_styleSheets->length());
824 bool wasInQuirksMode = inQuirksMode();
825 m_compatibilityMode = mode;
826 selectorQueryCache()->invalidate();
827 if (inQuirksMode() != wasInQuirksMode) {
828 // All user stylesheets have to reparse using the different mode.
829 clearPageUserSheet();
830 clearPageGroupUserSheets();
834 String Document::compatMode() const
836 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
839 void Document::resetLinkColor()
841 m_linkColor = Color(0, 0, 238);
844 void Document::resetVisitedLinkColor()
846 m_visitedLinkColor = Color(85, 26, 139);
849 void Document::resetActiveLinkColor()
851 m_activeLinkColor.setNamedColor("red");
854 void Document::setDocType(PassRefPtr<DocumentType> docType)
856 // This should never be called more than once.
857 ASSERT(!m_docType || !docType);
860 this->adoptIfNeeded(m_docType.get());
861 #if ENABLE(LEGACY_VIEWPORT_ADAPTION)
862 if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
863 processViewport("width=device-width, height=device-height", ViewportArguments::XHTMLMobileProfile);
866 // Doctype affects the interpretation of the stylesheets.
867 clearStyleResolver();
870 DOMImplementation* Document::implementation()
872 if (!m_implementation)
873 m_implementation = DOMImplementation::create(this);
874 return m_implementation.get();
877 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
879 ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
881 Element* newDocumentElement = firstElementChild(this);
882 if (newDocumentElement == m_documentElement)
884 m_documentElement = newDocumentElement;
885 // The root style used for media query matching depends on the document element.
886 clearStyleResolver();
889 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
891 if (!isValidName(name)) {
892 ec = INVALID_CHARACTER_ERR;
897 return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
899 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
902 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
904 return DocumentFragment::create(document());
907 PassRefPtr<Text> Document::createTextNode(const String& data)
909 return Text::create(this, data);
912 PassRefPtr<Comment> Document::createComment(const String& data)
914 return Comment::create(this, data);
917 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
919 if (isHTMLDocument()) {
920 ec = NOT_SUPPORTED_ERR;
923 return CDATASection::create(this, data);
926 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
928 if (!isValidName(target)) {
929 ec = INVALID_CHARACTER_ERR;
932 if (isHTMLDocument()) {
933 ec = NOT_SUPPORTED_ERR;
936 return ProcessingInstruction::create(this, target, data);
939 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
941 if (!isValidName(name)) {
942 ec = INVALID_CHARACTER_ERR;
945 if (isHTMLDocument()) {
946 ec = NOT_SUPPORTED_ERR;
949 return EntityReference::create(this, name);
952 PassRefPtr<EditingText> Document::createEditingTextNode(const String& text)
954 return EditingText::create(this, text);
957 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
959 return StylePropertySet::create()->ensureCSSStyleDeclaration();
962 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
967 ec = NOT_SUPPORTED_ERR;
971 switch (importedNode->nodeType()) {
973 return createTextNode(importedNode->nodeValue());
974 case CDATA_SECTION_NODE:
975 return createCDATASection(importedNode->nodeValue(), ec);
976 case ENTITY_REFERENCE_NODE:
977 return createEntityReference(importedNode->nodeName(), ec);
978 case PROCESSING_INSTRUCTION_NODE:
979 return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
981 return createComment(importedNode->nodeValue());
983 Element* oldElement = static_cast<Element*>(importedNode);
984 // FIXME: The following check might be unnecessary. Is it possible that
985 // oldElement has mismatched prefix/namespace?
986 if (!hasValidNamespaceForElements(oldElement->tagQName())) {
990 RefPtr<Element> newElement = createElement(oldElement->tagQName(), ec);
994 newElement->cloneDataFromElement(*oldElement);
997 for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
998 RefPtr<Node> newChild = importNode(oldChild, true, ec);
1001 newElement->appendChild(newChild.release(), ec);
1007 return newElement.release();
1009 case ATTRIBUTE_NODE:
1010 return Attr::create(this, QualifiedName(nullAtom, static_cast<Attr*>(importedNode)->name(), nullAtom), static_cast<Attr*>(importedNode)->value());
1011 case DOCUMENT_FRAGMENT_NODE: {
1012 if (importedNode->isShadowRoot()) {
1013 // ShadowRoot nodes should not be explicitly importable.
1014 // Either they are imported along with their host node, or created implicitly.
1017 DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
1018 RefPtr<DocumentFragment> newFragment = createDocumentFragment();
1020 for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
1021 RefPtr<Node> newChild = importNode(oldChild, true, ec);
1024 newFragment->appendChild(newChild.release(), ec);
1030 return newFragment.release();
1034 // FIXME: It should be possible to import these node types, however in DOM3 the DocumentType is readonly, so there isn't much sense in doing that.
1035 // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
1037 case DOCUMENT_TYPE_NODE:
1038 case XPATH_NAMESPACE_NODE:
1041 ec = NOT_SUPPORTED_ERR;
1046 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
1049 ec = NOT_SUPPORTED_ERR;
1053 if (source->isReadOnlyNode()) {
1054 ec = NO_MODIFICATION_ALLOWED_ERR;
1058 EventQueueScope scope;
1060 switch (source->nodeType()) {
1064 case DOCUMENT_TYPE_NODE:
1065 case XPATH_NAMESPACE_NODE:
1066 ec = NOT_SUPPORTED_ERR;
1068 case ATTRIBUTE_NODE: {
1069 Attr* attr = static_cast<Attr*>(source.get());
1070 if (attr->ownerElement())
1071 attr->ownerElement()->removeAttributeNode(attr, ec);
1072 attr->setSpecified(true);
1076 if (source->isShadowRoot()) {
1077 // ShadowRoot cannot disconnect itself from the host node.
1078 ec = HIERARCHY_REQUEST_ERR;
1082 // FIXME: What about <frame> and <object>?
1083 if (source->hasTagName(iframeTag)) {
1084 HTMLIFrameElement* iframe = static_cast<HTMLIFrameElement*>(source.get());
1085 if (frame() && frame()->tree()->isDescendantOf(iframe->contentFrame())) {
1086 ec = HIERARCHY_REQUEST_ERR;
1090 if (source->parentNode())
1091 source->parentNode()->removeChild(source.get(), ec);
1094 this->adoptIfNeeded(source.get());
1099 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1101 // These checks are from DOM Core Level 2, createElementNS
1102 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1103 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1105 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1108 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1109 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1110 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
1111 if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
1117 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1119 // Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS
1120 if (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom) {
1121 // Note: The case of an "xmlns" qualified name with a namespace of
1122 // xmlnsNamespaceURI is specifically allowed (See <http://www.w3.org/2000/xmlns/>).
1123 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1125 return hasValidNamespaceForElements(qName);
1128 // FIXME: This should really be in a possible ElementFactory class
1129 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
1133 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1134 if (qName.namespaceURI() == xhtmlNamespaceURI)
1135 e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
1137 else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
1138 e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
1141 else if (qName.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1142 e = MathMLElementFactory::createMathMLElement(qName, this, createdByParser);
1146 m_sawElementsInKnownNamespaces = true;
1148 e = Element::create(qName, document());
1150 // <image> uses imgTag so we need a special rule.
1151 ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
1156 bool Document::regionBasedColumnsEnabled() const
1158 return settings() && settings()->regionBasedColumnsEnabled();
1161 bool Document::cssRegionsEnabled() const
1163 return settings() && settings()->cssRegionsEnabled();
1166 bool Document::cssGridLayoutEnabled() const
1168 return settings() && settings()->cssGridLayoutEnabled();
1171 #if ENABLE(CSS_REGIONS)
1173 PassRefPtr<WebKitNamedFlow> Document::webkitGetFlowByName(const String& flowName)
1175 if (!cssRegionsEnabled() || !renderer())
1178 // It's possible to have pending styles not applied that affect the existing flows.
1179 updateStyleIfNeeded();
1181 return namedFlows()->flowByName(flowName);
1185 WebKitNamedFlowCollection* Document::namedFlows()
1188 m_namedFlows = WebKitNamedFlowCollection::create(this);
1190 return m_namedFlows.get();
1193 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
1195 String prefix, localName;
1196 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
1199 QualifiedName qName(prefix, localName, namespaceURI);
1200 if (!hasValidNamespaceForElements(qName)) {
1205 return createElement(qName, false);
1208 String Document::readyState() const
1210 DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
1211 DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
1212 DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
1214 switch (m_readyState) {
1223 ASSERT_NOT_REACHED();
1227 void Document::setReadyState(ReadyState readyState)
1229 if (readyState == m_readyState)
1232 switch (readyState) {
1234 if (!m_documentTiming.domLoading)
1235 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1238 if (!m_documentTiming.domInteractive)
1239 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1242 if (!m_documentTiming.domComplete)
1243 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1247 m_readyState = readyState;
1248 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1250 if (settings() && settings()->suppressesIncrementalRendering())
1251 setVisualUpdatesAllowed(readyState);
1254 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1256 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1257 switch (readyState) {
1259 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1260 ASSERT(m_visualUpdatesAllowed);
1261 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1262 setVisualUpdatesAllowed(false);
1265 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1268 if (m_visualUpdatesSuppressionTimer.isActive()) {
1269 ASSERT(!m_visualUpdatesAllowed);
1270 m_visualUpdatesSuppressionTimer.stop();
1271 setVisualUpdatesAllowed(true);
1273 ASSERT(m_visualUpdatesAllowed);
1278 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1280 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1283 m_visualUpdatesAllowed = visualUpdatesAllowed;
1285 if (!visualUpdatesAllowed)
1288 #if USE(ACCELERATED_COMPOSITING)
1290 view()->updateCompositingLayersAfterLayout();
1294 renderer()->repaint();
1297 void Document::visualUpdatesSuppressionTimerFired(Timer<Document>*)
1299 ASSERT(!m_visualUpdatesAllowed);
1300 setVisualUpdatesAllowed(true);
1303 String Document::encoding() const
1305 if (TextResourceDecoder* d = decoder())
1306 return d->encoding().domName();
1310 String Document::defaultCharset() const
1312 if (Settings* settings = this->settings())
1313 return settings->defaultTextEncodingName();
1317 void Document::setCharset(const String& charset)
1321 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1324 void Document::setContentLanguage(const String& language)
1326 if (m_contentLanguage == language)
1328 m_contentLanguage = language;
1330 // Recalculate style so language is used when selecting the initial font.
1331 styleResolverChanged(DeferRecalcStyle);
1334 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1336 if (!implementation()->hasFeature("XML", String())) {
1337 ec = NOT_SUPPORTED_ERR;
1341 if (!XMLDocumentParser::supportsXMLVersion(version)) {
1342 ec = NOT_SUPPORTED_ERR;
1346 m_xmlVersion = version;
1349 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1351 if (!implementation()->hasFeature("XML", String())) {
1352 ec = NOT_SUPPORTED_ERR;
1356 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1359 void Document::setDocumentURI(const String& uri)
1361 // This property is read-only from JavaScript, but writable from Objective-C.
1362 m_documentURI = uri;
1366 KURL Document::baseURI() const
1371 void Document::setContent(const String& content)
1374 m_parser->append(content);
1378 String Document::suggestedMIMEType() const
1380 if (m_document->isXHTMLDocument())
1381 return "application/xhtml+xml";
1382 if (m_document->isSVGDocument())
1383 return "image/svg+xml";
1384 if (m_document->xmlStandalone())
1386 if (m_document->isHTMLDocument())
1389 if (DocumentLoader* documentLoader = loader())
1390 return documentLoader->responseMIMEType();
1394 // FIXME: We need to discuss the DOM API here at some point. Ideas:
1395 // * making it receive a rect as parameter, i.e. nodesFromRect(x, y, w, h);
1396 // * making it receive the expading size of each direction separately,
1397 // i.e. nodesFromRect(x, y, topSize, rightSize, bottomSize, leftSize);
1398 PassRefPtr<NodeList> Document::nodesFromRect(int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent) const
1400 // FIXME: Share code between this, elementFromPoint and caretRangeFromPoint.
1403 Frame* frame = this->frame();
1406 FrameView* frameView = frame->view();
1410 float zoomFactor = frame->pageZoomFactor();
1411 LayoutPoint point = roundedLayoutPoint(FloatPoint(centerX * zoomFactor + view()->scrollX(), centerY * zoomFactor + view()->scrollY()));
1413 int type = HitTestRequest::ReadOnly | HitTestRequest::Active;
1415 // When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
1417 type |= HitTestRequest::IgnoreClipping;
1418 else if (!frameView->visibleContentRect().intersects(HitTestResult::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
1421 HitTestRequest request(type);
1423 // Passing a zero padding will trigger a rect hit test, however for the purposes of nodesFromRect,
1424 // we special handle this case in order to return a valid NodeList.
1425 if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) {
1426 HitTestResult result(point);
1427 return handleZeroPadding(request, result);
1430 enum ShadowContentFilterPolicy shadowContentFilterPolicy = allowShadowContent ? AllowShadowContent : DoNotAllowShadowContent;
1431 HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding, shadowContentFilterPolicy);
1432 renderView()->hitTest(request, result);
1434 return StaticHashSetNodeList::adopt(result.rectBasedTestResult());
1437 PassRefPtr<NodeList> Document::handleZeroPadding(const HitTestRequest& request, HitTestResult& result) const
1439 renderView()->hitTest(request, result);
1441 Node* node = result.innerNode();
1445 node = node->shadowAncestorNode();
1446 ListHashSet<RefPtr<Node> > list;
1448 return StaticHashSetNodeList::adopt(list);
1451 static Node* nodeFromPoint(Frame* frame, RenderView* renderView, int x, int y, LayoutPoint* localPoint = 0)
1455 FrameView* frameView = frame->view();
1459 float zoomFactor = frame->pageZoomFactor();
1460 IntPoint point = roundedIntPoint(FloatPoint(x * zoomFactor + frameView->scrollX(), y * zoomFactor + frameView->scrollY()));
1462 if (!frameView->visibleContentRect().contains(point))
1465 HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
1466 HitTestResult result(point);
1468 renderView->hitTest(request, result);
1471 *localPoint = result.localPoint();
1473 return result.innerNode();
1476 Element* Document::elementFromPoint(int x, int y) const
1480 Node* node = nodeFromPoint(frame(), renderView(), x, y);
1481 while (node && !node->isElementNode())
1482 node = node->parentNode();
1484 node = ancestorInThisScope(node);
1485 return static_cast<Element*>(node);
1488 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1492 LayoutPoint localPoint;
1493 Node* node = nodeFromPoint(frame(), renderView(), x, y, &localPoint);
1497 Node* shadowAncestorNode = ancestorInThisScope(node);
1498 if (shadowAncestorNode != node) {
1499 unsigned offset = shadowAncestorNode->nodeIndex();
1500 ContainerNode* container = shadowAncestorNode->parentNode();
1501 return Range::create(this, container, offset, container, offset);
1504 RenderObject* renderer = node->renderer();
1507 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint);
1508 if (visiblePosition.isNull())
1511 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1512 return Range::create(this, rangeCompliantPosition, rangeCompliantPosition);
1516 * Performs three operations:
1517 * 1. Convert control characters to spaces
1518 * 2. Trim leading and trailing spaces
1519 * 3. Collapse internal whitespace.
1521 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1523 const String& title = titleWithDirection.string();
1524 const UChar* characters = title.characters();
1525 unsigned length = title.length();
1528 StringBuffer<UChar> buffer(length);
1529 unsigned builderIndex = 0;
1531 // Skip leading spaces and leading characters that would convert to spaces
1532 for (i = 0; i < length; ++i) {
1533 UChar c = characters[i];
1534 if (!(c <= 0x20 || c == 0x7F))
1539 return StringWithDirection();
1541 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1542 bool previousCharWasWS = false;
1543 for (; i < length; ++i) {
1544 UChar c = characters[i];
1545 if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1546 if (previousCharWasWS)
1548 buffer[builderIndex++] = ' ';
1549 previousCharWasWS = true;
1551 buffer[builderIndex++] = c;
1552 previousCharWasWS = false;
1556 // Strip trailing spaces
1557 while (builderIndex > 0) {
1559 if (buffer[builderIndex] != ' ')
1563 if (!builderIndex && buffer[builderIndex] == ' ')
1564 return StringWithDirection();
1566 buffer.shrink(builderIndex + 1);
1568 // Replace the backslashes with currency symbols if the encoding requires it.
1569 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1571 return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1574 void Document::updateTitle(const StringWithDirection& title)
1576 if (m_rawTitle == title)
1580 m_title = canonicalizedTitle(this, m_rawTitle);
1581 if (Frame* f = frame())
1582 f->loader()->setTitle(m_title);
1585 void Document::setTitle(const String& title)
1587 // Title set by JavaScript -- overrides any title elements.
1588 m_titleSetExplicitly = true;
1589 if (!isHTMLDocument() && !isXHTMLDocument())
1591 else if (!m_titleElement) {
1592 if (HTMLElement* headElement = head()) {
1593 m_titleElement = createElement(titleTag, false);
1594 ExceptionCode ec = 0;
1595 headElement->appendChild(m_titleElement, ec);
1600 // The DOM API has no method of specifying direction, so assume LTR.
1601 updateTitle(StringWithDirection(title, LTR));
1603 if (m_titleElement) {
1604 ASSERT(m_titleElement->hasTagName(titleTag));
1605 if (m_titleElement->hasTagName(titleTag))
1606 static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(title);
1610 void Document::setTitleElement(const StringWithDirection& title, Element* titleElement)
1612 if (titleElement != m_titleElement) {
1613 if (m_titleElement || m_titleSetExplicitly)
1614 // Only allow the first title element to change the title -- others have no effect.
1616 m_titleElement = titleElement;
1622 void Document::removeTitle(Element* titleElement)
1624 if (m_titleElement != titleElement)
1628 m_titleSetExplicitly = false;
1630 // Update title based on first title element in the head, if one exists.
1631 if (HTMLElement* headElement = head()) {
1632 for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
1633 if (e->hasTagName(titleTag)) {
1634 HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
1635 setTitleElement(titleElement->textWithDirection(), titleElement);
1640 if (!m_titleElement)
1641 updateTitle(StringWithDirection());
1644 #if ENABLE(PAGE_VISIBILITY_API)
1645 PageVisibilityState Document::visibilityState() const
1647 // The visibility of the document is inherited from the visibility of the
1648 // page. If there is no page associated with the document, we will assume
1649 // that the page is hidden, as specified by the spec:
1650 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1651 if (!m_frame || !m_frame->page())
1652 return PageVisibilityStateHidden;
1653 return m_frame->page()->visibilityState();
1656 String Document::webkitVisibilityState() const
1658 return pageVisibilityStateString(visibilityState());
1661 bool Document::webkitHidden() const
1663 return visibilityState() != PageVisibilityStateVisible;
1666 void Document::dispatchVisibilityStateChangeEvent()
1668 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1669 if (m_activeMediaObjectCount) {
1670 if (!webkitHidden())
1671 AudioSessionManagerGStreamerTizen::setVolumeSessionToMediaType();
1673 AudioSessionManagerGStreamerTizen::clearVolumeSessionFromMediaType();
1676 dispatchEvent(Event::create(eventNames().webkitvisibilitychangeEvent, false, false));
1680 #if ENABLE(CSP_NEXT)
1681 DOMSecurityPolicy* Document::securityPolicy()
1683 if (!m_domSecurityPolicy)
1684 m_domSecurityPolicy = DOMSecurityPolicy::create(this);
1685 return m_domSecurityPolicy.get();
1689 String Document::nodeName() const
1694 Node::NodeType Document::nodeType() const
1696 return DOCUMENT_NODE;
1699 FormController* Document::formController()
1701 if (!m_formController)
1702 m_formController = FormController::create();
1703 return m_formController.get();
1706 Vector<String> Document::formElementsState() const
1708 if (!m_formController)
1709 return Vector<String>();
1710 return m_formController->formElementsState();
1713 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1715 if (!stateVector.size() && !m_formController)
1717 formController()->setStateForNewFormElements(stateVector);
1720 FrameView* Document::view() const
1722 return m_frame ? m_frame->view() : 0;
1725 Page* Document::page() const
1727 return m_frame ? m_frame->page() : 0;
1730 Settings* Document::settings() const
1732 return m_frame ? m_frame->settings() : 0;
1735 PassRefPtr<Range> Document::createRange()
1737 return Range::create(this);
1740 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
1741 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1744 ec = NOT_SUPPORTED_ERR;
1747 return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1750 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
1751 PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1754 ec = NOT_SUPPORTED_ERR;
1757 return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1760 void Document::scheduleForcedStyleRecalc()
1762 m_pendingStyleRecalcShouldForce = true;
1763 scheduleStyleRecalc();
1766 void Document::scheduleStyleRecalc()
1768 if (shouldDisplaySeamlesslyWithParent()) {
1769 // When we're seamless, our parent document manages our style recalcs.
1770 ownerElement()->setNeedsStyleRecalc();
1771 ownerElement()->document()->scheduleStyleRecalc();
1775 if (m_styleRecalcTimer.isActive() || inPageCache())
1778 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1780 if (!documentsThatNeedStyleRecalc)
1781 documentsThatNeedStyleRecalc = new HashSet<Document*>;
1782 documentsThatNeedStyleRecalc->add(this);
1784 // FIXME: Why on earth is this here? This is clearly misplaced.
1785 invalidateAccessKeyMap();
1787 m_styleRecalcTimer.startOneShot(0);
1789 InspectorInstrumentation::didScheduleStyleRecalculation(this);
1792 void Document::unscheduleStyleRecalc()
1794 ASSERT(!childNeedsStyleRecalc());
1796 if (documentsThatNeedStyleRecalc)
1797 documentsThatNeedStyleRecalc->remove(this);
1799 m_styleRecalcTimer.stop();
1800 m_pendingStyleRecalcShouldForce = false;
1803 bool Document::isPendingStyleRecalc() const
1805 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1808 void Document::styleRecalcTimerFired(Timer<Document>*)
1810 updateStyleIfNeeded();
1813 bool Document::childNeedsAndNotInStyleRecalc()
1815 return childNeedsStyleRecalc() && !m_inStyleRecalc;
1818 void Document::recalcStyle(StyleChange change)
1820 // we should not enter style recalc while painting
1821 if (view() && view()->isPainting()) {
1822 ASSERT(!view()->isPainting());
1826 if (m_inStyleRecalc)
1827 return; // Guard against re-entrancy. -dwh
1829 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1830 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1831 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1832 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1833 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1834 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1836 if (m_hasDirtyStyleResolver)
1837 updateActiveStylesheets(RecalcStyleImmediately);
1839 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1841 if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
1842 m_usesRemUnits = true;
1844 m_inStyleRecalc = true;
1845 suspendPostAttachCallbacks();
1846 RenderWidget::suspendWidgetHierarchyUpdates();
1848 RefPtr<FrameView> frameView = view();
1850 frameView->pauseScheduledEvents();
1851 frameView->beginDeferredRepaints();
1854 ASSERT(!renderer() || renderArena());
1855 if (!renderer() || !renderArena())
1858 if (m_pendingStyleRecalcShouldForce)
1861 // Recalculating the root style (on the document) is not needed in the common case.
1862 if ((change == Force) || (shouldDisplaySeamlesslyWithParent() && (change >= Inherit))) {
1863 // style selector may set this again during recalc
1864 m_hasNodesWithPlaceholderStyle = false;
1866 RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(this, m_styleResolver ? m_styleResolver->fontSelector() : 0);
1867 StyleChange ch = Node::diff(documentStyle.get(), renderer()->style(), this);
1869 renderer()->setStyle(documentStyle.release());
1872 for (Node* n = firstChild(); n; n = n->nextSibling()) {
1873 if (!n->isElementNode())
1875 Element* element = static_cast<Element*>(n);
1876 if (change >= Inherit || element->childNeedsStyleRecalc() || element->needsStyleRecalc())
1877 element->recalcStyle(change);
1880 #if USE(ACCELERATED_COMPOSITING)
1882 bool layoutPending = view()->layoutPending() || renderer()->needsLayout();
1883 // If we didn't update compositing layers because of layout(), we need to do so here.
1885 view()->updateCompositingLayersAfterStyleChange();
1890 clearNeedsStyleRecalc();
1891 clearChildNeedsStyleRecalc();
1892 unscheduleStyleRecalc();
1894 m_inStyleRecalc = false;
1896 // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1897 if (m_styleResolver)
1898 resetCSSFeatureFlags();
1901 frameView->resumeScheduledEvents();
1902 frameView->endDeferredRepaints();
1904 RenderWidget::resumeWidgetHierarchyUpdates();
1905 resumePostAttachCallbacks();
1907 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1908 if (m_closeAfterStyleRecalc) {
1909 m_closeAfterStyleRecalc = false;
1913 InspectorInstrumentation::didRecalculateStyle(cookie);
1916 void Document::updateStyleIfNeeded()
1918 ASSERT(isMainThread());
1919 ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
1921 if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
1924 AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
1925 recalcStyle(NoChange);
1928 void Document::updateStyleForAllDocuments()
1930 ASSERT(isMainThread());
1931 if (!documentsThatNeedStyleRecalc)
1934 while (documentsThatNeedStyleRecalc->size()) {
1935 HashSet<Document*>::iterator it = documentsThatNeedStyleRecalc->begin();
1936 Document* doc = *it;
1937 documentsThatNeedStyleRecalc->remove(doc);
1938 doc->updateStyleIfNeeded();
1942 void Document::updateLayout()
1944 ASSERT(isMainThread());
1945 if (Element* oe = ownerElement())
1946 oe->document()->updateLayout();
1948 updateStyleIfNeeded();
1950 // Only do a layout if changes have occurred that make it necessary.
1951 FrameView* v = view();
1952 if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
1956 // FIXME: This is a bad idea and needs to be removed eventually.
1957 // Other browsers load stylesheets before they continue parsing the web page.
1958 // Since we don't, we can run JavaScript code that needs answers before the
1959 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1960 // lets us get reasonable answers. The long term solution to this problem is
1961 // to instead suspend JavaScript execution.
1962 void Document::updateLayoutIgnorePendingStylesheets()
1964 bool oldIgnore = m_ignorePendingStylesheets;
1966 if (!haveStylesheetsLoaded()) {
1967 m_ignorePendingStylesheets = true;
1968 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1969 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1970 // with accurate style information. (Our suppression involves blanking the whole page at the
1971 // moment. If it were more refined, we might be able to do something better.)
1972 // It's worth noting though that this entire method is a hack, since what we really want to do is
1973 // suspend JS instead of doing a layout with inaccurate information.
1974 HTMLElement* bodyElement = body();
1975 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1976 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1977 styleResolverChanged(RecalcStyleImmediately);
1978 } else if (m_hasNodesWithPlaceholderStyle)
1979 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1980 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1981 // but here we need up-to-date style immediately.
1987 m_ignorePendingStylesheets = oldIgnore;
1990 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1992 ASSERT_ARG(element, element->document() == this);
1994 bool oldIgnore = m_ignorePendingStylesheets;
1995 m_ignorePendingStylesheets = true;
1996 RefPtr<RenderStyle> style = styleResolver()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
1997 m_ignorePendingStylesheets = oldIgnore;
1998 return style.release();
2001 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
2003 RefPtr<RenderStyle> style = styleResolver()->styleForPage(pageIndex);
2004 return style.release();
2007 void Document::registerCustomFont(PassOwnPtr<FontData> fontData)
2009 m_customFonts.append(fontData);
2012 void Document::deleteCustomFonts()
2014 size_t size = m_customFonts.size();
2015 for (size_t i = 0; i < size; ++i)
2016 GlyphPageTreeNode::pruneTreeCustomFontData(m_customFonts[i].get());
2018 m_customFonts.clear();
2021 bool Document::isPageBoxVisible(int pageIndex)
2023 RefPtr<RenderStyle> style = styleForPage(pageIndex);
2024 return style->visibility() != HIDDEN; // display property doesn't apply to @page.
2027 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2029 RefPtr<RenderStyle> style = styleForPage(pageIndex);
2030 RenderView* view = renderView();
2032 int width = pageSize.width();
2033 int height = pageSize.height();
2034 switch (style->pageSizeType()) {
2035 case PAGE_SIZE_AUTO:
2037 case PAGE_SIZE_AUTO_LANDSCAPE:
2039 std::swap(width, height);
2041 case PAGE_SIZE_AUTO_PORTRAIT:
2043 std::swap(width, height);
2045 case PAGE_SIZE_RESOLVED: {
2046 LengthSize size = style->pageSize();
2047 ASSERT(size.width().isFixed());
2048 ASSERT(size.height().isFixed());
2049 width = valueForLength(size.width(), 0, view);
2050 height = valueForLength(size.height(), 0, view);
2054 ASSERT_NOT_REACHED();
2056 pageSize = IntSize(width, height);
2058 // The percentage is calculated with respect to the width even for margin top and bottom.
2059 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2060 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width, view);
2061 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width, view);
2062 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width, view);
2063 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width, view);
2066 void Document::setDocumentRareData(NodeRareData* rareData)
2068 m_documentRareData = rareData;
2071 void Document::setIsViewSource(bool isViewSource)
2073 m_isViewSource = isViewSource;
2074 if (!m_isViewSource)
2077 setSecurityOrigin(SecurityOrigin::createUnique());
2080 void Document::combineCSSFeatureFlags()
2082 // Delay resetting the flags until after next style recalc since unapplying the style may not work without these set (this is true at least with before/after).
2083 m_usesSiblingRules = m_usesSiblingRules || m_styleResolver->usesSiblingRules();
2084 m_usesFirstLineRules = m_usesFirstLineRules || m_styleResolver->usesFirstLineRules();
2085 m_usesBeforeAfterRules = m_usesBeforeAfterRules || m_styleResolver->usesBeforeAfterRules();
2086 m_usesLinkRules = m_usesLinkRules || m_styleResolver->usesLinkRules();
2089 void Document::resetCSSFeatureFlags()
2091 m_usesSiblingRules = m_styleResolver->usesSiblingRules();
2092 m_usesFirstLineRules = m_styleResolver->usesFirstLineRules();
2093 m_usesBeforeAfterRules = m_styleResolver->usesBeforeAfterRules();
2094 m_usesLinkRules = m_styleResolver->usesLinkRules();
2097 void Document::createStyleResolver()
2099 bool matchAuthorAndUserStyles = true;
2100 if (Settings* docSettings = settings())
2101 matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
2102 m_styleResolver = adoptPtr(new StyleResolver(this, matchAuthorAndUserStyles));
2103 combineCSSFeatureFlags();
2106 inline void Document::clearStyleResolver()
2108 m_styleResolver.clear();
2111 #if ENABLE(TIZEN_INPUT_TAG_EXTENSION)
2112 void Document::setCurrentTargetNode(PassRefPtr<Node> prpNode)
2114 m_currentTargetNode = prpNode;
2118 void Document::attach()
2120 ASSERT(!attached());
2121 ASSERT(!m_inPageCache);
2122 ASSERT(!m_axObjectCache || this != topDocument());
2125 m_renderArena = adoptPtr(new RenderArena);
2127 // Create the rendering tree
2128 setRenderer(new (m_renderArena.get()) RenderView(this, view()));
2129 #if USE(ACCELERATED_COMPOSITING)
2130 renderView()->didMoveOnscreen();
2135 RenderObject* render = renderer();
2138 ContainerNode::attach();
2140 setRenderer(render);
2143 void Document::detach()
2146 ASSERT(!m_inPageCache);
2148 #if ENABLE(POINTER_LOCK)
2150 page()->pointerLockController()->documentDetached(this);
2153 if (this == topDocument())
2154 clearAXObjectCache();
2156 stopActiveDOMObjects();
2157 m_eventQueue->close();
2158 #if ENABLE(FULLSCREEN_API)
2159 m_fullScreenChangeEventTargetQueue.clear();
2160 m_fullScreenErrorEventTargetQueue.clear();
2163 #if ENABLE(REQUEST_ANIMATION_FRAME)
2164 // FIXME: consider using ActiveDOMObject.
2165 if (m_scriptedAnimationController)
2166 m_scriptedAnimationController->clearDocumentPointer();
2167 m_scriptedAnimationController.clear();
2170 RenderObject* render = renderer();
2172 documentWillBecomeInactive();
2174 #if ENABLE(SHARED_WORKERS)
2175 SharedWorkerRepository::documentDetached(this);
2179 FrameView* view = m_frame->view();
2181 view->detachCustomScrollbars();
2185 // indicate destruction mode, i.e. attached() but renderer == 0
2188 #if ENABLE(FULLSCREEN_API)
2189 if (m_fullScreenRenderer)
2190 setFullScreenRenderer(0);
2196 #if ENABLE(TIZEN_INPUT_TAG_EXTENSION)
2197 m_currentTargetNode = 0;
2200 ContainerNode::detach();
2202 unscheduleStyleRecalc();
2207 // This is required, as our Frame might delete itself as soon as it detaches
2208 // us. However, this violates Node::detach() semantics, as it's never
2209 // possible to re-attach. Eventually Document::detach() should be renamed,
2210 // or this setting of the frame to 0 could be made explicit in each of the
2211 // callers of Document::detach().
2213 m_renderArena.clear();
2216 void Document::prepareForDestruction()
2218 disconnectDescendantFrames();
2219 if (DOMWindow* window = this->domWindow())
2220 window->willDetachDocumentFromFrame();
2224 void Document::removeAllEventListeners()
2226 EventTarget::removeAllEventListeners();
2228 if (DOMWindow* domWindow = this->domWindow())
2229 domWindow->removeAllEventListeners();
2230 for (Node* node = firstChild(); node; node = node->traverseNextNode())
2231 node->removeAllEventListeners();
2234 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2236 ScriptExecutionContext::suspendActiveDOMObjects(why);
2238 #if ENABLE(DEVICE_ORIENTATION)
2242 if (DeviceMotionController* controller = DeviceMotionController::from(page()))
2243 controller->suspendEventsForAllListeners(domWindow());
2244 if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
2245 controller->suspendEventsForAllListeners(domWindow());
2249 #if ENABLE(TIZEN_WEBKIT2_NOTIFY_SUSPEND_BY_REMOTE_WEB_INSPECTOR)
2250 if (why == ActiveDOMObject::JavaScriptDebuggerPaused)
2251 page()->chrome()->setContentSuspendedByInspector(true);
2255 void Document::resumeActiveDOMObjects()
2257 ScriptExecutionContext::resumeActiveDOMObjects();
2259 #if ENABLE(DEVICE_ORIENTATION)
2263 if (DeviceMotionController* controller = DeviceMotionController::from(page()))
2264 controller->resumeEventsForAllListeners(domWindow());
2265 if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
2266 controller->resumeEventsForAllListeners(domWindow());
2269 #if ENABLE(TIZEN_WEBKIT2_NOTIFY_SUSPEND_BY_REMOTE_WEB_INSPECTOR)
2270 page()->chrome()->setContentSuspendedByInspector(false);
2274 RenderView* Document::renderView() const
2276 return toRenderView(renderer());
2279 void Document::clearAXObjectCache()
2281 // clear cache in top document
2282 if (m_axObjectCache) {
2283 // Clear the cache member variable before calling delete because attempts
2284 // are made to access it during destruction.
2285 AXObjectCache* axObjectCache = m_axObjectCache;
2286 m_axObjectCache = 0;
2287 delete axObjectCache;
2291 // ask the top-level document to clear its cache
2292 Document* doc = topDocument();
2294 doc->clearAXObjectCache();
2297 bool Document::axObjectCacheExists() const
2299 if (m_axObjectCache)
2302 Document* doc = topDocument();
2304 return doc->axObjectCacheExists();
2309 AXObjectCache* Document::axObjectCache() const
2311 // The only document that actually has a AXObjectCache is the top-level
2312 // document. This is because we need to be able to get from any WebCoreAXObject
2313 // to any other WebCoreAXObject on the same page. Using a single cache allows
2314 // lookups across nested webareas (i.e. multiple documents).
2316 if (m_axObjectCache) {
2317 // return already known top-level cache
2318 if (!ownerElement())
2319 return m_axObjectCache;
2321 // In some pages with frames, the cache is created before the sub-webarea is
2322 // inserted into the tree. Here, we catch that case and just toss the old
2323 // cache and start over.
2324 // NOTE: This recovery may no longer be needed. I have been unable to trigger
2325 // it again. See rdar://5794454
2326 // FIXME: Can this be fixed when inserting the subframe instead of now?
2327 // FIXME: If this function was called to get the cache in order to remove
2328 // an AXObject, we are now deleting the cache as a whole and returning a
2329 // new empty cache that does not contain the AXObject! That should actually
2330 // be OK. I am concerned about other cases like this where accessing the
2331 // cache blows away the AXObject being operated on.
2332 delete m_axObjectCache;
2333 m_axObjectCache = 0;
2336 // ask the top-level document for its cache
2337 Document* doc = topDocument();
2339 return doc->axObjectCache();
2341 // this is the top-level document, so install a new cache
2342 m_axObjectCache = new AXObjectCache(this);
2343 return m_axObjectCache;
2346 void Document::setVisuallyOrdered()
2348 m_visuallyOrdered = true;
2350 renderer()->style()->setRTLOrdering(VisualOrder);
2353 PassRefPtr<DocumentParser> Document::createParser()
2355 // FIXME: this should probably pass the frame instead
2357 return NewXMLDocumentParser::create(this);
2359 return XMLDocumentParser::create(this, view());
2363 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2365 return parser() ? parser()->asScriptableDocumentParser() : 0;
2368 void Document::open(Document* ownerDocument)
2370 if (ownerDocument) {
2371 setURL(ownerDocument->url());
2372 m_cookieURL = ownerDocument->cookieURL();
2373 setSecurityOrigin(ownerDocument->securityOrigin());
2377 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2378 if (parser->isParsing()) {
2379 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2380 if (parser->isExecutingScript())
2383 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2388 if (m_frame->loader()->state() == FrameStateProvisional)
2389 m_frame->loader()->stopAllLoaders();
2392 removeAllEventListeners();
2394 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2395 parser->setWasCreatedByScript(true);
2397 if (DOMWindow* domWindow = this->domWindow())
2398 domWindow->removeAllEventListeners();
2401 m_frame->loader()->didExplicitOpen();
2404 void Document::detachParser()
2412 void Document::cancelParsing()
2417 // We have to clear the parser to avoid possibly triggering
2418 // the onload handler when closing as a side effect of a cancel-style
2419 // change, such as opening a new document or closing the window while
2425 void Document::implicitOpen()
2431 setCompatibilityMode(NoQuirksMode);
2433 m_parser = createParser();
2435 setReadyState(Loading);
2438 HTMLElement* Document::body() const
2440 Node* de = documentElement();
2444 // try to prefer a FRAMESET element over BODY
2446 for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
2447 if (i->hasTagName(framesetTag))
2448 return toHTMLElement(i);
2450 if (i->hasTagName(bodyTag) && !body)
2453 return toHTMLElement(body);
2456 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2458 RefPtr<HTMLElement> newBody = prpNewBody;
2460 if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
2461 ec = HIERARCHY_REQUEST_ERR;
2465 if (newBody->document() && newBody->document() != this) {
2467 RefPtr<Node> node = importNode(newBody.get(), true, ec);
2471 newBody = toHTMLElement(node.get());
2474 HTMLElement* b = body();
2476 documentElement()->appendChild(newBody.release(), ec);
2478 documentElement()->replaceChild(newBody.release(), b, ec);
2481 HTMLHeadElement* Document::head()
2483 Node* de = documentElement();
2487 for (Node* e = de->firstChild(); e; e = e->nextSibling())
2488 if (e->hasTagName(headTag))
2489 return static_cast<HTMLHeadElement*>(e);
2494 void Document::close()
2496 // FIXME: We should follow the specification more closely:
2497 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2499 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2505 void Document::explicitClose()
2511 // Because we have no frame, we don't know if all loading has completed,
2512 // so we just call implicitClose() immediately. FIXME: This might fire
2513 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2518 m_frame->loader()->checkCompleted();
2521 void Document::implicitClose()
2523 // If we're in the middle of recalcStyle, we need to defer the close until the style information is accurate and all elements are re-attached.
2524 if (m_inStyleRecalc) {
2525 m_closeAfterStyleRecalc = true;
2529 bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
2530 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2535 m_processingLoadEvent = true;
2537 ScriptableDocumentParser* parser = scriptableDocumentParser();
2538 m_wellFormed = parser && parser->wellFormed();
2540 // We have to clear the parser, in case someone document.write()s from the
2541 // onLoad event handler, as in Radar 3206524.
2544 // Parser should have picked up all preloads by now
2545 m_cachedResourceLoader->clearPreloads();
2547 // FIXME: We kick off the icon loader when the Document is done parsing.
2548 // There are earlier opportunities we could start it:
2549 // -When the <head> finishes parsing
2550 // -When any new HTMLLinkElement is inserted into the document
2551 // But those add a dynamic component to the favicon that has UI
2552 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2555 f->loader()->icon()->startLoader();
2556 f->animation()->resumeAnimationsForDocument(this);
2559 ImageLoader::dispatchPendingBeforeLoadEvents();
2560 ImageLoader::dispatchPendingLoadEvents();
2561 ImageLoader::dispatchPendingErrorEvents();
2563 HTMLLinkElement::dispatchPendingLoadEvents();
2564 HTMLStyleElement::dispatchPendingLoadEvents();
2567 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2568 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2569 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2570 if (svgExtensions())
2571 accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
2574 dispatchWindowLoadEvent();
2575 enqueuePageshowEvent(PageshowEventNotPersisted);
2576 enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
2579 f->loader()->handledOnloadEvents();
2580 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2581 if (!ownerElement())
2582 printf("onload fired at %d\n", elapsedTime());
2585 // An event handler may have removed the frame
2587 m_processingLoadEvent = false;
2591 // Make sure both the initial layout and reflow happen after the onload
2592 // fires. This will improve onload scores, and other browsers do it.
2593 // If they wanna cheat, we can too. -dwh
2595 if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2596 // Just bail out. Before or during the onload we were shifted to another page.
2597 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2598 m_processingLoadEvent = false;
2599 view()->unscheduleRelayout();
2603 frame()->loader()->checkCallImplicitClose();
2604 RenderObject* renderObject = renderer();
2606 // We used to force a synchronous display and flush here. This really isn't
2607 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2608 // (if your platform is syncing flushes and limiting them to 60fps).
2609 m_overMinimumLayoutThreshold = true;
2610 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2611 updateStyleIfNeeded();
2613 // Always do a layout after loading if needed.
2614 if (view() && renderObject && (!renderObject->firstChild() || renderObject->needsLayout()))
2618 m_processingLoadEvent = false;
2620 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
2621 if (f && renderObject && AXObjectCache::accessibilityEnabled()) {
2622 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2623 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2624 // exists in the cache (we ignore the return value because we don't need it here). This is
2625 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2626 axObjectCache()->getOrCreate(renderObject);
2627 if (this == topDocument())
2628 axObjectCache()->postNotification(renderObject, AXObjectCache::AXLoadComplete, true);
2630 // AXLoadComplete can only be posted on the top document, so if it's a document
2631 // in an iframe that just finished loading, post AXLayoutComplete instead.
2632 axObjectCache()->postNotification(renderObject, AXObjectCache::AXLayoutComplete, true);
2638 if (svgExtensions())
2639 accessSVGExtensions()->startAnimations();
2643 void Document::setParsing(bool b)
2646 if (!m_bParsing && view())
2647 view()->scheduleRelayout();
2649 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2650 if (!ownerElement() && !m_bParsing)
2651 printf("Parsing finished at %d\n", elapsedTime());
2655 bool Document::shouldScheduleLayout()
2657 // This function will only be called when FrameView thinks a layout is needed.
2658 // This enforces a couple extra rules.
2660 // (a) Only schedule a layout once the stylesheets are loaded.
2661 // (b) Only schedule layout once we have a body element.
2663 return (haveStylesheetsLoaded() && body())
2664 || (documentElement() && !documentElement()->hasTagName(htmlTag));
2667 bool Document::isLayoutTimerActive()
2669 return view() && view()->layoutPending() && !minimumLayoutDelay();
2672 int Document::minimumLayoutDelay()
2674 if (m_overMinimumLayoutThreshold)
2677 int elapsed = elapsedTime();
2678 m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
2680 // We'll want to schedule the timer to fire at the minimum layout threshold.
2681 return max(0, cLayoutScheduleThreshold - elapsed);
2684 int Document::elapsedTime() const
2686 return static_cast<int>((currentTime() - m_startTime) * 1000);
2689 void Document::write(const SegmentedString& text, Document* ownerDocument)
2691 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2693 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2694 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2696 if (m_writeRecursionIsTooDeep)
2699 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2700 if (!ownerElement())
2701 printf("Beginning a document.write at %d\n", elapsedTime());
2704 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2705 if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2708 if (!hasInsertionPoint)
2709 open(ownerDocument);
2712 m_parser->insert(text);
2714 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2715 if (!ownerElement())
2716 printf("Ending a document.write at %d\n", elapsedTime());
2720 void Document::write(const String& text, Document* ownerDocument)
2722 write(SegmentedString(text), ownerDocument);
2725 void Document::writeln(const String& text, Document* ownerDocument)
2727 write(text, ownerDocument);
2728 write("\n", ownerDocument);
2731 const KURL& Document::virtualURL() const
2736 KURL Document::virtualCompleteURL(const String& url) const
2738 return completeURL(url);
2741 double Document::minimumTimerInterval() const
2745 return ScriptExecutionContext::minimumTimerInterval();
2746 return p->settings()->minDOMTimerInterval();
2749 EventTarget* Document::errorEventTarget()
2754 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack> callStack)
2756 addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack);
2759 void Document::setURL(const KURL& url)
2761 const KURL& newURL = url.isEmpty() ? blankURL() : url;
2762 if (newURL == m_url)
2766 m_documentURI = m_url.string();
2768 contextFeatures()->urlDidChange(this);
2771 void Document::updateBaseURL()
2773 KURL oldBaseURL = m_baseURL;
2774 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2775 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2776 // from the Document interface otherwise.
2777 if (!m_baseElementURL.isEmpty())
2778 m_baseURL = m_baseElementURL;
2779 else if (!m_baseURLOverride.isEmpty())
2780 m_baseURL = m_baseURLOverride;
2782 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2783 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2784 // and DOM 3 Core does not specify how it should be resolved.
2785 m_baseURL = KURL(KURL(), documentURI());
2787 selectorQueryCache()->invalidate();
2789 if (!m_baseURL.isValid())
2793 // Element sheet is silly. It never contains anything.
2794 ASSERT(!m_elemSheet->contents()->ruleCount());
2795 bool usesRemUnits = m_elemSheet->contents()->usesRemUnits();
2796 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2797 // FIXME: So we are not really the parser. The right fix is to eliminate the element sheet completely.
2798 m_elemSheet->contents()->parserSetUsesRemUnits(usesRemUnits);
2801 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2802 // Base URL change changes any relative visited links.
2803 // 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.
2804 for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
2805 if (node->hasTagName(aTag))
2806 static_cast<HTMLAnchorElement*>(node)->invalidateCachedVisitedLinkHash();
2811 void Document::setBaseURLOverride(const KURL& url)
2813 m_baseURLOverride = url;
2817 void Document::processBaseElement()
2819 // Find the first href attribute in a base element and the first target attribute in a base element.
2820 const AtomicString* href = 0;
2821 const AtomicString* target = 0;
2822 for (Node* node = document()->firstChild(); node && (!href || !target); node = node->traverseNextNode()) {
2823 if (node->hasTagName(baseTag)) {
2825 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(hrefAttr);
2826 if (!value.isNull())
2830 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(targetAttr);
2831 if (!value.isNull())
2837 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2838 KURL baseElementURL;
2840 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2841 if (!strippedHref.isEmpty())
2842 baseElementURL = KURL(url(), strippedHref);
2844 if (m_baseElementURL != baseElementURL) {
2845 m_baseElementURL = baseElementURL;
2849 m_baseTarget = target ? *target : nullAtom;
2852 String Document::userAgent(const KURL& url) const
2854 return frame() ? frame()->loader()->userAgent(url) : String();
2857 void Document::disableEval()
2862 frame()->script()->disableEval();
2865 bool Document::canNavigate(Frame* targetFrame)
2870 // FIXME: We shouldn't call this function without a target frame, but
2871 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2872 // returning true when supplied with a 0 targetFrame.
2876 // Frame-busting is generally allowed (unless we're sandboxed and prevent from frame-busting).
2877 if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
2880 if (isSandboxed(SandboxNavigation)) {
2881 if (targetFrame->tree()->isDescendantOf(m_frame))
2884 printNavigationErrorMessage(targetFrame, url());
2888 // This is the normal case. A document can navigate its decendant frames,
2889 // or, more generally, a document can navigate a frame if the document is
2890 // in the same origin as any of that frame's ancestors (in the frame
2893 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
2894 // historical information about this security check.
2895 if (canAccessAncestor(securityOrigin(), targetFrame))
2898 // Top-level frames are easier to navigate than other frames because they
2899 // display their URLs in the address bar (in most browsers). However, there
2900 // are still some restrictions on navigation to avoid nuisance attacks.
2901 // Specifically, a document can navigate a top-level frame if that frame
2902 // opened the document or if the document is the same-origin with any of
2903 // the top-level frame's opener's ancestors (in the frame hierarchy).
2905 // In both of these cases, the document performing the navigation is in
2906 // some way related to the frame being navigate (e.g., by the "opener"
2907 // and/or "parent" relation). Requiring some sort of relation prevents a
2908 // document from navigating arbitrary, unrelated top-level frames.
2909 if (!targetFrame->tree()->parent()) {
2910 if (targetFrame == m_frame->loader()->opener())
2913 if (canAccessAncestor(securityOrigin(), targetFrame->loader()->opener()))
2917 printNavigationErrorMessage(targetFrame, url());
2921 Frame* Document::findUnsafeParentScrollPropagationBoundary()
2923 Frame* currentFrame = m_frame;
2924 Frame* ancestorFrame = currentFrame->tree()->parent();
2926 while (ancestorFrame) {
2927 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
2928 return currentFrame;
2929 currentFrame = ancestorFrame;
2930 ancestorFrame = ancestorFrame->tree()->parent();
2935 CSSStyleSheet* Document::pageUserSheet()
2937 if (m_pageUserSheet)
2938 return m_pageUserSheet.get();
2940 Page* owningPage = page();
2944 String userSheetText = owningPage->userStyleSheet();
2945 if (userSheetText.isEmpty())
2948 // Parse the sheet and cache it.
2949 m_pageUserSheet = CSSStyleSheet::createInline(this, settings()->userStyleSheetLocation());
2950 m_pageUserSheet->contents()->setIsUserStyleSheet(true);
2951 m_pageUserSheet->contents()->parseString(userSheetText);
2952 return m_pageUserSheet.get();
2955 void Document::clearPageUserSheet()
2957 if (m_pageUserSheet) {
2958 m_pageUserSheet = 0;
2959 styleResolverChanged(DeferRecalcStyle);
2963 void Document::updatePageUserSheet()
2965 clearPageUserSheet();
2966 if (pageUserSheet())
2967 styleResolverChanged(RecalcStyleImmediately);
2970 const Vector<RefPtr<CSSStyleSheet> >* Document::pageGroupUserSheets() const
2972 if (m_pageGroupUserSheetCacheValid)
2973 return m_pageGroupUserSheets.get();
2975 m_pageGroupUserSheetCacheValid = true;
2977 Page* owningPage = page();
2981 const PageGroup& pageGroup = owningPage->group();
2982 const UserStyleSheetMap* sheetsMap = pageGroup.userStyleSheets();
2986 UserStyleSheetMap::const_iterator end = sheetsMap->end();
2987 for (UserStyleSheetMap::const_iterator it = sheetsMap->begin(); it != end; ++it) {
2988 const UserStyleSheetVector* sheets = it->second.get();
2989 for (unsigned i = 0; i < sheets->size(); ++i) {
2990 const UserStyleSheet* sheet = sheets->at(i).get();
2991 if (sheet->injectedFrames() == InjectInTopFrameOnly && ownerElement())
2993 if (!UserContentURLPattern::matchesPatterns(url(), sheet->whitelist(), sheet->blacklist()))
2995 RefPtr<CSSStyleSheet> groupSheet = CSSStyleSheet::createInline(const_cast<Document*>(this), sheet->url());
2996 if (!m_pageGroupUserSheets)
2997 m_pageGroupUserSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
2998 m_pageGroupUserSheets->append(groupSheet);
2999 groupSheet->contents()->setIsUserStyleSheet(sheet->level() == UserStyleUserLevel);
3000 groupSheet->contents()->parseString(sheet->source());
3004 return m_pageGroupUserSheets.get();
3007 void Document::clearPageGroupUserSheets()
3009 m_pageGroupUserSheetCacheValid = false;
3010 if (m_pageGroupUserSheets && m_pageGroupUserSheets->size()) {
3011 m_pageGroupUserSheets->clear();
3012 styleResolverChanged(DeferRecalcStyle);
3016 void Document::updatePageGroupUserSheets()
3018 clearPageGroupUserSheets();
3019 if (pageGroupUserSheets() && pageGroupUserSheets()->size())
3020 styleResolverChanged(RecalcStyleImmediately);
3023 void Document::addUserSheet(PassRefPtr<StyleSheetContents> userSheet)
3026 m_userSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
3027 m_userSheets->append(CSSStyleSheet::create(userSheet, this));
3028 styleResolverChanged(RecalcStyleImmediately);
3031 void Document::seamlessParentUpdatedStylesheets()
3033 styleResolverChanged(RecalcStyleImmediately);
3036 CSSStyleSheet* Document::elementSheet()
3039 m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
3040 return m_elemSheet.get();
3043 int Document::nodeAbsIndex(Node *node)
3045 ASSERT(node->document() == this);
3048 for (Node* n = node; n && n != this; n = n->traversePreviousNode())
3053 Node* Document::nodeWithAbsIndex(int absIndex)
3056 for (int i = 0; n && (i < absIndex); i++)
3057 n = n->traverseNextNode();
3061 void Document::processHttpEquiv(const String& equiv, const String& content)
3063 ASSERT(!equiv.isNull() && !content.isNull());
3065 Frame* frame = this->frame();
3067 if (equalIgnoringCase(equiv, "default-style")) {
3068 // The preferred style set has been overridden as per section
3069 // 14.3.2 of the HTML4.0 specification. We need to update the
3070 // sheet used variable and then update our style selector.
3071 // For more info, see the test at:
3072 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3074 m_selectedStylesheetSet = content;
3075 m_preferredStylesheetSet = content;
3076 styleResolverChanged(DeferRecalcStyle);
3077 } else if (equalIgnoringCase(equiv, "refresh")) {
3080 if (frame && parseHTTPRefresh(content, true, delay, url)) {
3082 url = m_url.string();
3084 url = completeURL(url).string();
3085 frame->navigationScheduler()->scheduleRedirect(delay, url);
3087 } else if (equalIgnoringCase(equiv, "set-cookie")) {
3088 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3089 if (isHTMLDocument()) {
3090 ExceptionCode ec; // Exception (for sandboxed documents) ignored.
3091 static_cast<HTMLDocument*>(this)->setCookie(content, ec);
3093 } else if (equalIgnoringCase(equiv, "content-language"))
3094 setContentLanguage(content);
3095 else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
3096 parseDNSPrefetchControlHeader(content);
3097 else if (equalIgnoringCase(equiv, "x-frame-options")) {
3099 FrameLoader* frameLoader = frame->loader();
3100 if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url())) {
3101 frameLoader->stopAllLoaders();
3102 frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), blankURL(), String());
3104 DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to display document because display forbidden by X-Frame-Options.\n"));
3105 addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, consoleMessage);
3108 } else if (equalIgnoringCase(equiv, "x-webkit-csp"))
3109 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::EnforcePolicy);
3110 else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
3111 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::ReportOnly);
3114 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
3115 static bool isSeparator(UChar c)
3117 return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
3120 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
3122 // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
3123 int keyBegin, keyEnd;
3124 int valueBegin, valueEnd;
3127 int length = features.length();
3128 String buffer = features.lower();
3129 while (i < length) {
3130 // skip to first non-separator, but don't skip past the end of the string
3131 while (isSeparator(buffer[i])) {
3138 // skip to first separator
3139 while (!isSeparator(buffer[i]))
3143 // skip to first '=', but don't skip past a ',' or the end of the string
3144 while (buffer[i] != '=') {
3145 if (buffer[i] == ',' || i >= length)
3150 // skip to first non-separator, but don't skip past a ',' or the end of the string
3151 while (isSeparator(buffer[i])) {
3152 if (buffer[i] == ',' || i >= length)
3158 // skip to first separator
3159 while (!isSeparator(buffer[i]))
3163 ASSERT(i <= length);
3165 String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
3166 String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
3167 callback(keyString, valueString, this, data);
3171 void Document::processViewport(const String& features, ViewportArguments::Type origin)
3173 ASSERT(!features.isNull());
3175 if (origin < m_viewportArguments.type)
3178 m_viewportArguments = ViewportArguments(origin);
3179 processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
3181 updateViewportArguments();
3184 void Document::updateViewportArguments()
3186 if (page() && page()->mainFrame() == frame()) {
3188 m_didDispatchViewportPropertiesChanged = true;
3190 page()->chrome()->dispatchViewportPropertiesDidChange(m_viewportArguments);
3194 void Document::processReferrerPolicy(const String& policy)
3196 ASSERT(!policy.isNull());
3198 m_referrerPolicy = ReferrerPolicyDefault;
3200 if (equalIgnoringCase(policy, "never"))
3201 m_referrerPolicy = ReferrerPolicyNever;
3202 else if (equalIgnoringCase(policy, "always"))
3203 m_referrerPolicy = ReferrerPolicyAlways;
3204 else if (equalIgnoringCase(policy, "origin"))
3205 m_referrerPolicy = ReferrerPolicyOrigin;
3208 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3210 ASSERT(!renderer() || renderer()->isRenderView());
3213 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3215 HitTestResult result(documentPoint);
3216 renderView()->hitTest(request, result);
3218 if (!request.readOnly())
3219 updateStyleIfNeeded();
3221 return MouseEventWithHitTestResults(event, result);
3224 // DOM Section 1.1.1
3225 bool Document::childTypeAllowed(NodeType type) const
3228 case ATTRIBUTE_NODE:
3229 case CDATA_SECTION_NODE:
3230 case DOCUMENT_FRAGMENT_NODE:
3233 case ENTITY_REFERENCE_NODE:
3236 case XPATH_NAMESPACE_NODE:
3239 case PROCESSING_INSTRUCTION_NODE:
3241 case DOCUMENT_TYPE_NODE:
3243 // Documents may contain no more than one of each of these.
3244 // (One Element and one DocumentType.)
3245 for (Node* c = firstChild(); c; c = c->nextSibling())
3246 if (c->nodeType() == type)
3253 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
3256 // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
3259 if (oldChild->nodeType() == newChild->nodeType())
3262 int numDoctypes = 0;
3263 int numElements = 0;
3265 // First, check how many doctypes and elements we have, not counting
3266 // the child we're about to remove.
3267 for (Node* c = firstChild(); c; c = c->nextSibling()) {
3271 switch (c->nodeType()) {
3272 case DOCUMENT_TYPE_NODE:
3283 // Then, see how many doctypes and elements might be added by the new child.
3284 if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
3285 for (Node* c = newChild->firstChild(); c; c = c->nextSibling()) {
3286 switch (c->nodeType()) {
3287 case ATTRIBUTE_NODE:
3288 case CDATA_SECTION_NODE:
3289 case DOCUMENT_FRAGMENT_NODE:
3292 case ENTITY_REFERENCE_NODE:
3295 case XPATH_NAMESPACE_NODE:
3298 case PROCESSING_INSTRUCTION_NODE:
3300 case DOCUMENT_TYPE_NODE:
3309 switch (newChild->nodeType()) {
3310 case ATTRIBUTE_NODE:
3311 case CDATA_SECTION_NODE:
3312 case DOCUMENT_FRAGMENT_NODE:
3315 case ENTITY_REFERENCE_NODE:
3318 case XPATH_NAMESPACE_NODE:
3321 case PROCESSING_INSTRUCTION_NODE:
3323 case DOCUMENT_TYPE_NODE:
3332 if (numElements > 1 || numDoctypes > 1)
3338 PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
3340 // Spec says cloning Document nodes is "implementation dependent"
3341 // so we do not support it...
3345 StyleSheetList* Document::styleSheets()
3347 return m_styleSheets.get();
3350 String Document::preferredStylesheetSet() const
3352 return m_preferredStylesheetSet;
3355 String Document::selectedStylesheetSet() const
3357 return m_selectedStylesheetSet;
3360 void Document::setSelectedStylesheetSet(const String& aString)
3362 m_selectedStylesheetSet = aString;
3363 styleResolverChanged(DeferRecalcStyle);
3366 // This method is called whenever a top-level stylesheet has finished loading.
3367 void Document::removePendingSheet()
3369 // Make sure we knew this sheet was pending, and that our count isn't out of sync.
3370 ASSERT(m_pendingStylesheets > 0);
3372 m_pendingStylesheets--;
3374 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3375 if (!ownerElement())
3376 printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
3379 if (m_pendingStylesheets)
3382 styleResolverChanged(RecalcStyleIfNeeded);
3384 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
3385 parser->executeScriptsWaitingForStylesheets();
3387 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
3388 view()->scrollToFragment(m_url);
3391 void Document::evaluateMediaQueryList()
3393 if (m_mediaQueryMatcher)
3394 m_mediaQueryMatcher->styleResolverChanged();
3397 void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
3399 // Don't bother updating, since we haven't loaded all our style info yet
3400 // and haven't calculated the style selector for the first time.
3401 if (!attached() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
3402 m_styleResolver.clear();
3406 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3407 if (!ownerElement())
3408 printf("Beginning update of style selector at time %d.\n", elapsedTime());
3411 bool stylesheetChangeRequiresStyleRecalc = updateActiveStylesheets(updateFlag);
3413 if (updateFlag == DeferRecalcStyle) {
3414 scheduleForcedStyleRecalc();
3418 if (didLayoutWithPendingStylesheets() && m_pendingStylesheets <= 0) {
3419 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3421 renderer()->repaint();
3424 if (!stylesheetChangeRequiresStyleRecalc)
3427 // This recalcStyle initiates a new recalc cycle. We need to bracket it to
3428 // make sure animations get the correct update time
3430 AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
3434 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3435 if (!ownerElement())
3436 printf("Finished update of style selector at time %d\n", elapsedTime());
3440 renderer()->setNeedsLayoutAndPrefWidthsRecalc();
3442 view()->scheduleRelayout();
3445 evaluateMediaQueryList();
3448 void Document::addStyleSheetCandidateNode(Node* node, bool createdByParser)
3450 if (!node->inDocument())
3453 // Until the <body> exists, we have no choice but to compare document positions,
3454 // since styles outside of the body and head continue to be shunted into the head
3455 // (and thus can shift to end up before dynamically added DOM content that is also
3456 // outside the body).
3457 if ((createdByParser && body()) || m_styleSheetCandidateNodes.isEmpty()) {
3458 m_styleSheetCandidateNodes.add(node);
3462 // Determine an appropriate insertion point.
3463 StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
3464 StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
3465 StyleSheetCandidateListHashSet::iterator it = end;
3466 Node* followingNode = 0;
3470 unsigned short position = n->compareDocumentPosition(node);
3471 if (position == DOCUMENT_POSITION_FOLLOWING) {
3472 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
3476 } while (it != begin);
3478 m_styleSheetCandidateNodes.insertBefore(followingNode, node);
3481 void Document::removeStyleSheetCandidateNode(Node* node)
3483 m_styleSheetCandidateNodes.remove(node);
3486 void Document::collectActiveStylesheets(Vector<RefPtr<StyleSheet> >& sheets)
3488 if (settings() && !settings()->authorAndUserStylesEnabled())
3491 StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
3492 StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
3493 for (StyleSheetCandidateListHashSet::iterator it = begin; it != end; ++it) {
3495 StyleSheet* sheet = 0;
3496 if (n->nodeType() == PROCESSING_INSTRUCTION_NODE) {
3497 // Processing instruction (XML documents only).
3498 // We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion.
3499 ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
3500 sheet = pi->sheet();
3502 // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
3503 if (pi->isXSL() && !transformSourceDocument()) {
3504 // Don't apply XSL transforms until loading is finished.
3506 applyXSLTransform(pi);
3510 } else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag)))
3512 || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
3515 Element* e = static_cast<Element*>(n);
3516 AtomicString title = e->getAttribute(titleAttr);
3517 bool enabledViaScript = false;
3518 if (e->hasLocalName(linkTag)) {
3520 HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(n);
3521 if (linkElement->isDisabled())
3523 enabledViaScript = linkElement->isEnabledViaScript();
3524 if (linkElement->styleSheetIsLoading()) {
3525 // it is loading but we should still decide which style sheet set to use
3526 if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSet.isEmpty()) {
3527 const AtomicString& rel = e->getAttribute(relAttr);
3528 if (!rel.contains("alternate")) {
3529 m_preferredStylesheetSet = title;
3530 m_selectedStylesheetSet = title;
3535 if (!linkElement->sheet())
3538 // Get the current preferred styleset. This is the
3539 // set of sheets that will be enabled.
3541 if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
3542 sheet = static_cast<SVGStyleElement*>(n)->sheet();
3545 if (e->hasLocalName(linkTag))
3546 sheet = static_cast<HTMLLinkElement*>(n)->sheet();
3549 sheet = static_cast<HTMLStyleElement*>(n)->sheet();
3550 // Check to see if this sheet belongs to a styleset
3551 // (thus making it PREFERRED or ALTERNATE rather than
3553 AtomicString rel = e->getAttribute(relAttr);
3554 if (!enabledViaScript && !title.isEmpty()) {
3555 // Yes, we have a title.
3556 if (m_preferredStylesheetSet.isEmpty()) {
3557 // No preferred set has been established. If
3558 // we are NOT an alternate sheet, then establish
3559 // us as the preferred set. Otherwise, just ignore
3561 if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
3562 m_preferredStylesheetSet = m_selectedStylesheetSet = title;
3564 if (title != m_preferredStylesheetSet)
3568 if (rel.contains("alternate") && title.isEmpty())
3572 sheets.append(sheet);
3576 bool Document::testAddedStylesheetRequiresStyleRecalc(StyleSheetContents* stylesheet)
3578 // See if all rules on the sheet are scoped to some specific ids or classes.
3579 // Then test if we actually have any of those in the tree at the moment.
3580 HashSet<AtomicStringImpl*> idScopes;
3581 HashSet<AtomicStringImpl*> classScopes;
3582 if (!StyleResolver::determineStylesheetSelectorScopes(stylesheet, idScopes, classScopes))
3584 // Invalidate the subtrees that match the scopes.
3585 Node* node = firstChild();
3587 if (!node->isStyledElement()) {
3588 node = node->traverseNextNode();
3591 StyledElement* element = static_cast<StyledElement*>(node);
3592 if (SelectorChecker::elementMatchesSelectorScopes(element, idScopes, classScopes)) {
3593 element->setNeedsStyleRecalc();
3594 // The whole subtree is now invalidated, we can skip to the next sibling.
3595 node = node->traverseNextSibling();
3598 node = node->traverseNextNode();
3603 void Document::analyzeStylesheetChange(StyleResolverUpdateFlag updateFlag, const Vector<RefPtr<StyleSheet> >& newStylesheets, bool& requiresStyleResolverReset, bool& requiresFullStyleRecalc)
3605 requiresStyleResolverReset = true;
3606 requiresFullStyleRecalc = true;
3608 // Stylesheets of <style> elements that @import stylesheets are active but loading. We need to trigger a full recalc when such loads are done.
3609 bool hasActiveLoadingStylesheet = false;
3610 unsigned newStylesheetCount = newStylesheets.size();
3611 for (unsigned i = 0; i < newStylesheetCount; ++i) {
3612 if (newStylesheets[i]->isLoading())
3613 hasActiveLoadingStylesheet = true;
3615 if (m_hadActiveLoadingStylesheet && !hasActiveLoadingStylesheet) {
3616 m_hadActiveLoadingStylesheet = false;
3619 m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet;
3621 if (updateFlag != RecalcStyleIfNeeded)
3623 if (!m_styleResolver)
3626 // See if we are just adding stylesheets.
3627 unsigned oldStylesheetCount = m_styleSheets->length();
3628 if (newStylesheetCount < oldStylesheetCount)
3630 for (unsigned i = 0; i < oldStylesheetCount; ++i) {
3631 if (m_styleSheets->item(i) != newStylesheets[i])
3634 requiresStyleResolverReset = false;
3636 // If we are already parsing the body and so may have significant amount of elements, put some effort into trying to avoid style recalcs.
3637 if (!body() || m_hasNodesWithPlaceholderStyle)
3639 for (unsigned i = oldStylesheetCount; i < newStylesheetCount; ++i) {
3640 if (!newStylesheets[i]->isCSSStyleSheet())
3642 if (newStylesheets[i]->disabled())
3644 if (testAddedStylesheetRequiresStyleRecalc(static_cast<CSSStyleSheet*>(newStylesheets[i].get())->contents()))
3647 requiresFullStyleRecalc = false;
3650 static bool styleSheetsUseRemUnits(const Vector<RefPtr<StyleSheet> >& sheets)
3652 for (unsigned i = 0; i < sheets.size(); ++i) {
3653 if (!sheets[i]->isCSSStyleSheet())
3655 if (static_cast<CSSStyleSheet*>(sheets[i].get())->contents()->usesRemUnits())
3661 void Document::notifySeamlessChildDocumentsOfStylesheetUpdate() const
3663 // If we're not in a frame yet any potential child documents won't have a StyleResolver to update.
3667 // Seamless child frames are expected to notify their seamless children recursively, so we only do direct children.
3668 for (Frame* child = frame()->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
3669 Document* childDocument = child->document();
3670 if (childDocument->shouldDisplaySeamlesslyWithParent()) {
3671 ASSERT(childDocument->seamlessParentIFrame()->document() == this);
3672 childDocument->seamlessParentUpdatedStylesheets();
3677 bool Document::updateActiveStylesheets(StyleResolverUpdateFlag updateFlag)
3679 if (m_inStyleRecalc) {
3680 // SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
3681 // https://bugs.webkit.org/show_bug.cgi?id=54344
3682 // FIXME: This should be fixed in SVG and this code replaced with ASSERT(!m_inStyleRecalc).
3683 m_hasDirtyStyleResolver = true;
3684 scheduleForcedStyleRecalc();
3687 if (!renderer() || !attached())
3690 StyleSheetVector newStylesheets;
3691 collectActiveStylesheets(newStylesheets);
3693 bool requiresStyleResolverReset;
3694 bool requiresFullStyleRecalc;
3695 analyzeStylesheetChange(updateFlag, newStylesheets, requiresStyleResolverReset, requiresFullStyleRecalc);
3697 if (requiresStyleResolverReset)
3698 clearStyleResolver();
3700 m_styleResolver->appendAuthorStylesheets(m_styleSheets->length(), newStylesheets);
3701 resetCSSFeatureFlags();
3703 m_styleSheets->swap(newStylesheets);
3705 m_usesRemUnits = styleSheetsUseRemUnits(m_styleSheets->vector());
3706 m_didCalculateStyleResolver = true;
3707 m_hasDirtyStyleResolver = false;
3709 notifySeamlessChildDocumentsOfStylesheetUpdate();
3711 return requiresFullStyleRecalc;
3714 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
3716 m_hoverNode = newHoverNode;
3719 void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
3721 m_activeNode = newActiveNode;
3724 void Document::focusedNodeRemoved()
3729 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3731 if (!m_focusedNode || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
3734 bool nodeInSubtree = false;
3735 if (amongChildrenOnly)
3736 nodeInSubtree = m_focusedNode->isDescendantOf(node);
3738 nodeInSubtree = (m_focusedNode == node) || m_focusedNode->isDescendantOf(node);
3741 document()->focusedNodeRemoved();
3744 void Document::hoveredNodeDetached(Node* node)
3746 if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parentNode())))
3749 m_hoverNode = node->parentNode();
3750 while (m_hoverNode && !m_hoverNode->renderer())
3751 m_hoverNode = m_hoverNode->parentNode();
3753 frame()->eventHandler()->scheduleHoverStateUpdate();
3756 void Document::activeChainNodeDetached(Node* node)
3758 if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parentNode())))
3761 m_activeNode = node->parentNode();
3762 while (m_activeNode && !m_activeNode->renderer())
3763 m_activeNode = m_activeNode->parentNode();
3766 #if ENABLE(DASHBOARD_SUPPORT)
3767 const Vector<DashboardRegionValue>& Document::dashboardRegions() const
3769 return m_dashboardRegions;
3772 void Document::setDashboardRegions(const Vector<DashboardRegionValue>& regions)
3774 m_dashboardRegions = regions;
3775 setDashboardRegionsDirty(false);
3779 bool Document::setFocusedNode(PassRefPtr<Node> prpNewFocusedNode)
3781 RefPtr<Node> newFocusedNode = prpNewFocusedNode;
3783 // Make sure newFocusedNode is actually in this document
3784 if (newFocusedNode && (newFocusedNode->document() != this))
3787 if (m_focusedNode == newFocusedNode) {
3788 #if ENABLE(TIZEN_WEBKIT2_FOCUS_RING)
3789 page()->chrome()->focusedNodeChanged(m_focusedNode.get());
3797 bool focusChangeBlocked = false;
3798 RefPtr<Node> oldFocusedNode = m_focusedNode;
3801 // Remove focus from the existing focus node (if any)
3802 if (oldFocusedNode) {
3803 ASSERT(!oldFocusedNode->inDetach());
3805 if (oldFocusedNode->active())
3806 oldFocusedNode->setActive(false);
3808 oldFocusedNode->setFocus(false);
3810 // Dispatch a change event for text fields or textareas that have been edited
3811 if (oldFocusedNode->isElementNode()) {
3812 Element* element = static_cast<Element*>(oldFocusedNode.get());
3813 if (element->wasChangedSinceLastFormControlChangeEvent())
3814 element->dispatchFormControlChangeEvent();
3817 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3818 oldFocusedNode->dispatchBlurEvent(newFocusedNode);
3820 if (m_focusedNode) {
3821 // handler shifted focus
3822 focusChangeBlocked = true;
3826 oldFocusedNode->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedNode); // DOM level 3 name for the bubbling blur event.
3827 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3828 // on it, probably when <rdar://problem/8503958> is resolved.
3829 oldFocusedNode->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedNode); // DOM level 2 name for compatibility.
3831 if (m_focusedNode) {
3832 // handler shifted focus
3833 focusChangeBlocked = true;
3836 if (oldFocusedNode == this && oldFocusedNode->hasOneRef())
3839 if (oldFocusedNode->isRootEditableElement())
3840 frame()->editor()->didEndEditing();
3843 Widget* oldWidget = widgetForNode(oldFocusedNode.get());
3845 oldWidget->setFocus(false);
3847 view()->setFocus(false);
3851 if (newFocusedNode) {
3852 if (newFocusedNode->isRootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
3853 // delegate blocks focus change
3854 focusChangeBlocked = true;
3855 goto SetFocusedNodeDone;
3857 // Set focus on the new node
3858 m_focusedNode = newFocusedNode;
3860 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3861 m_focusedNode->dispatchFocusEvent(oldFocusedNode);
3863 if (m_focusedNode != newFocusedNode) {
3864 // handler shifted focus
3865 focusChangeBlocked = true;
3866 goto SetFocusedNodeDone;
3869 m_focusedNode->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedNode); // DOM level 3 bubbling focus event.
3871 if (m_focusedNode != newFocusedNode) {
3872 // handler shifted focus
3873 focusChangeBlocked = true;
3874 goto SetFocusedNodeDone;
3877 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3878 // on it, probably when <rdar://problem/8503958> is m.
3879 m_focusedNode->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedNode); // DOM level 2 for compatibility.
3881 if (m_focusedNode != newFocusedNode) {
3882 // handler shifted focus
3883 focusChangeBlocked = true;
3884 goto SetFocusedNodeDone;
3886 m_focusedNode->setFocus(true);
3888 if (m_focusedNode->isRootEditableElement())
3889 frame()->editor()->didBeginEditing();
3891 // eww, I suck. set the qt focus correctly
3892 // ### find a better place in the code for this
3894 Widget* focusWidget = widgetForNode(m_focusedNode.get());
3896 // Make sure a widget has the right size before giving it focus.
3897 // Otherwise, we are testing edge cases of the Widget code.
3898 // Specifically, in WebCore this does not work well for text fields.
3900 // Re-get the widget in case updating the layout changed things.
3901 focusWidget = widgetForNode(m_focusedNode.get());
3904 focusWidget->setFocus(true);
3906 view()->setFocus(true);
3910 #if PLATFORM(MAC) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(CHROMIUM)
3911 if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled()) {
3912 RenderObject* oldFocusedRenderer = 0;
3913 RenderObject* newFocusedRenderer = 0;
3916 oldFocusedRenderer = oldFocusedNode->renderer();
3918 newFocusedRenderer = newFocusedNode->renderer();
3920 axObjectCache()->handleFocusedUIElementChanged(oldFocusedRenderer, newFocusedRenderer);
3923 if (!focusChangeBlocked)
3924 page()->chrome()->focusedNodeChanged(m_focusedNode.get());
3927 updateStyleIfNeeded();
3928 return !focusChangeBlocked;
3931 void Document::getFocusableNodes(Vector<RefPtr<Node> >& nodes)
3935 for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
3936 if (node->isFocusable())
3941 void Document::setCSSTarget(Element* n)
3944 m_cssTarget->setNeedsStyleRecalc();
3947 n->setNeedsStyleRecalc();
3950 void Document::registerNodeListCache(DynamicNodeListCacheBase* list)
3952 if (list->type() != NodeListCollectionType)
3953 m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
3954 m_nodeListCounts[list->invalidationType()]++;
3955 if (list->isRootedAtDocument())
3956 m_listsInvalidatedAtDocument.add(list);
3959 void Document::unregisterNodeListCache(DynamicNodeListCacheBase* list)
3961 if (list->type() != NodeListCollectionType)
3962 m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
3963 m_nodeListCounts[list->invalidationType()]--;
3964 if (list->isRootedAtDocument()) {
3965 ASSERT(m_listsInvalidatedAtDocument.contains(list));
3966 m_listsInvalidatedAtDocument.remove(list);
3970 void Document::attachNodeIterator(NodeIterator* ni)
3972 m_nodeIterators.add(ni);
3975 void Document::detachNodeIterator(NodeIterator* ni)
3977 // The node iterator can be detached without having been attached if its root node didn't have a document
3978 // when the iterator was created, but has it now.
3979 m_nodeIterators.remove(ni);
3982 void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
3984 HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3985 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3986 for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3987 if ((*it)->root() == node) {
3988 detachNodeIterator(*it);
3989 newDocument->attachNodeIterator(*it);
3994 void Document::updateRangesAfterChildrenChanged(ContainerNode* container)
3996 if (!m_ranges.isEmpty()) {
3997 HashSet<Range*>::const_iterator end = m_ranges.end();
3998 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3999 (*it)->nodeChildrenChanged(container);
4003 void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
4005 if (!m_ranges.isEmpty()) {
4006 HashSet<Range*>::const_iterator end = m_ranges.end();
4007 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
4008 (*it)->nodeChildrenWillBeRemoved(container);
4011 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
4012 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
4013 for (Node* n = container->firstChild(); n; n = n->nextSibling())
4014 (*it)->nodeWillBeRemoved(n);
4017 if (Frame* frame = this->frame()) {
4018 for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
4019 frame->eventHandler()->nodeWillBeRemoved(n);
4020 frame->selection()->nodeWillBeRemoved(n);
4021 frame->page()->dragCaretController()->nodeWillBeRemoved(n);
4026 void Document::nodeWillBeRemoved(Node* n)
4028 HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
4029 for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
4030 (*it)->nodeWillBeRemoved(n);
4032 if (!m_ranges.isEmpty()) {
4033 HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
4034 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
4035 (*it)->nodeWillBeRemoved(n);
4038 if (Frame* frame = this->frame()) {
4039 frame->eventHandler()->nodeWillBeRemoved(n);
4040 frame->selection()->nodeWillBeRemoved(n);
4041 frame->page()->dragCaretController()->nodeWillBeRemoved(n);
4045 void Document::textInserted(Node* text, unsigned offset, unsigned length)
4047 if (!m_ranges.isEmpty()) {
4048 HashSet<Range*>::const_iterator end = m_ranges.end();
4049 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
4050 (*it)->textInserted(text, offset, length);
4053 // Update the markers for spelling and grammar checking.
4054 m_markers->shiftMarkers(text, offset, length);
4057 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
4059 if (!m_ranges.isEmpty()) {
4060 HashSet<Range*>::const_iterator end = m_ranges.end();
4061 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
4062 (*it)->textRemoved(text, offset, length);
4065 // Update the markers for spelling and grammar checking.
4066 m_markers->removeMarkers(text, offset, length);
4067 m_markers->shiftMarkers(text, offset + length, 0 - length);
4070 void Document::textNodesMerged(Text* oldNode, unsigned offset)
4072 if (!m_ranges.isEmpty()) {
4073 NodeWithIndex oldNodeWithIndex(oldNode);
4074 HashSet<Range*>::const_iterator end = m_ranges.end();
4075 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
4076 (*it)->textNodesMerged(oldNodeWithIndex, offset);
4079 // FIXME: This should update markers for spelling and grammar checking.
4082 void Document::textNodeSplit(Text* oldNode)
4084 if (!m_ranges.isEmpty()) {
4085 HashSet<Range*>::const_iterator end = m_ranges.end();
4086 for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
4087 (*it)->textNodeSplit(oldNode);
4090 // FIXME: This should update markers for spelling and grammar checking.
4093 // FIXME: eventually, this should return a DOMWindow stored in the document.
4094 DOMWindow* Document::domWindow() const
4099 // The m_frame pointer is not (not always?) zeroed out when the document is put into b/f cache, so the frame can hold an unrelated document/window pair.
4100 // FIXME: We should always zero out the frame pointer on navigation to avoid accidentally accessing the new frame content.
4101 if (m_frame->document() != this)
4104 return frame()->domWindow();
4107 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
4109 DOMWindow* domWindow = this->domWindow();
4112 domWindow->setAttributeEventListener(eventType, listener);
4115 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
4117 DOMWindow* domWindow = this->domWindow();
4120 return domWindow->getAttributeEventListener(eventType);
4123 void Document::dispatchWindowEvent(PassRefPtr<Event> event, PassRefPtr<EventTarget> target)
4125 ASSERT(!eventDispatchForbidden());
4126 DOMWindow* domWindow = this->domWindow();
4129 domWindow->dispatchEvent(event, target);
4132 void Document::dispatchWindowLoadEvent()
4134 ASSERT(!eventDispatchForbidden());
4135 DOMWindow* domWindow = this->domWindow();
4138 domWindow->dispatchLoadEvent();
4139 m_loadEventFinished = true;
4142 void Document::enqueueWindowEvent(PassRefPtr<Event> event)
4144 event->setTarget(domWindow());
4145 m_eventQueue->enqueueEvent(event);
4148 void Document::enqueueDocumentEvent(PassRefPtr<Event> event)
4150 event->setTarget(this);
4151 m_eventQueue->enqueueEvent(event);
4154 PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionCode& ec)
4156 RefPtr<Event> event = EventFactory::create(eventType);
4158 return event.release();
4160 ec = NOT_SUPPORTED_ERR;
4164 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
4166 if (eventType == eventNames().DOMSubtreeModifiedEvent)
4167 addListenerType(DOMSUBTREEMODIFIED_LISTENER);
4168 else if (eventType == eventNames().DOMNodeInsertedEvent)
4169 addListenerType(DOMNODEINSERTED_LISTENER);
4170 else if (eventType == eventNames().DOMNodeRemovedEvent)
4171 addListenerType(DOMNODEREMOVED_LISTENER);
4172 else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
4173 addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
4174 else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
4175 addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
4176 else if (eventType == eventNames().DOMAttrModifiedEvent)
4177 addListenerType(DOMATTRMODIFIED_LISTENER);
4178 else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
4179 addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
4180 else if (eventType == eventNames().overflowchangedEvent)
4181 addListenerType(OVERFLOWCHANGED_LISTENER);
4182 else if (eventType == eventNames().webkitAnimationStartEvent)
4183 addListenerType(ANIMATIONSTART_LISTENER);
4184 else if (eventType == eventNames().webkitAnimationEndEvent)
4185 addListenerType(ANIMATIONEND_LISTENER);
4186 else if (eventType == eventNames().webkitAnimationIterationEvent)
4187 addListenerType(ANIMATIONITERATION_LISTENER);
4188 else if (eventType == eventNames().webkitTransitionEndEvent)
4189 addListenerType(TRANSITIONEND_LISTENER);
4190 else if (eventType == eventNames().beforeloadEvent)
4191 addListenerType(BEFORELOAD_LISTENER);
4192 #if ENABLE(TOUCH_EVENTS)
4193 else if (eventType == eventNames().touchstartEvent
4194 || eventType == eventNames().touchmoveEvent
4195 || eventType == eventNames().touchendEvent
4196 || eventType == eventNames().touchcancelEvent) {
4197 addListenerType(TOUCH_LISTENER);
4198 if (Page* page = this->page())
4199 page->chrome()->client()->needTouchEvents(true);
4202 else if (eventType == eventNames().scrollEvent)
4203 addListenerType(SCROLL_LISTENER);
4204 else if (eventType == eventNames().webkitRegionLayoutUpdateEvent)
4205 addListenerType(REGIONLAYOUTUPDATE_LISTENER);
4208 #if ENABLE(TIZEN_PLUGIN_TOUCH_EVENT)
4209 void Document::removeListenerType(const AtomicString& eventType)
4211 if (eventType == eventNames().touchstartEvent
4212 || eventType == eventNames().touchmoveEvent
4213 || eventType == eventNames().touchendEvent
4214 || eventType == eventNames().touchcancelEvent) {
4215 if (!m_touchEventHandlerCount) {
4216 m_listenerTypes = m_listenerTypes & ~TOUCH_LISTENER;
4217 if (Page* page = this->page())
4218 page->chrome()->client()->needTouchEvents(false);
4224 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
4229 HTMLFrameOwnerElement* Document::ownerElement() const
4233 return frame()->ownerElement();
4236 String Document::cookie(ExceptionCode& ec) const
4238 if (page() && !page()->settings()->cookieEnabled())
4241 // FIXME: The HTML5 DOM spec states that this attribute can raise an
4242 // INVALID_STATE_ERR exception on getting if the Document has no
4243 // browsing context.
4245 if (!securityOrigin()->canAccessCookies()) {
4250 KURL cookieURL = this->cookieURL();
4251 if (cookieURL.isEmpty())
4254 return cookies(this, cookieURL);
4257 void Document::setCookie(const String& value, ExceptionCode& ec)
4259 if (page() && !page()->settings()->cookieEnabled())
4262 // FIXME: The HTML5 DOM spec states that this attribute can raise an
4263 // INVALID_STATE_ERR exception on setting if the Document has no
4264 // browsing context.
4266 if (!securityOrigin()->canAccessCookies()) {
4271 KURL cookieURL = this->cookieURL();
4272 if (cookieURL.isEmpty())
4275 setCookies(this, cookieURL, value);
4278 String Document::referrer() const
4281 return frame()->loader()->referrer();
4285 String Document::domain() const
4287 return securityOrigin()->domain();
4290 void Document::setDomain(const String& newDomain, ExceptionCode& ec)
4292 if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
4297 // Both NS and IE specify that changing the domain is only allowed when
4298 // the new domain is a suffix of the old domain.
4300 // FIXME: We should add logging indicating why a domain was not allowed.
4302 // If the new domain is the same as the old domain, still call
4303 // securityOrigin()->setDomainForDOM. This will change the
4304 // security check behavior. For example, if a page loaded on port 8000
4305 // assigns its current domain using document.domain, the page will
4306 // allow other pages loaded on different ports in the same domain that
4307 // have also assigned to access this page.
4308 if (equalIgnoringCase(domain(), newDomain)) {
4309 securityOrigin()->setDomainFromDOM(newDomain);
4311 m_frame->script()->updateSecurityOrigin();
4315 int oldLength = domain().length();
4316 int newLength = newDomain.length();
4317 // e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
4318 if (newLength >= oldLength) {
4323 String test = domain();
4324 // Check that it's a subdomain, not e.g. "ebkit.org"
4325 if (test[oldLength - newLength - 1] != '.') {
4330 // Now test is "webkit.org" from domain()
4331 // and we check that it's the same thing as newDomain
4332 test.remove(0, oldLength - newLength);
4333 if (test != newDomain) {
4338 securityOrigin()->setDomainFromDOM(newDomain);
4340 m_frame->script()->updateSecurityOrigin();
4343 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
4344 String Document::lastModified() const
4346 DateComponents date;
4347 bool foundDate = false;
4349 String httpLastModified;
4350 if (DocumentLoader* documentLoader = loader())
4351 httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
4352 if (!httpLastModified.isEmpty()) {
4353 date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
4357 // FIXME: If this document came from the file system, the HTML5
4358 // specificiation tells us to read the last modification date from the file
4361 date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
4362 return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
4365 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
4370 U16_NEXT(characters, i, length, c)
4371 if (!isValidNameStart(c))
4374 while (i < length) {
4375 U16_NEXT(characters, i, length, c)
4376 if (!isValidNamePart(c))
4383 template<typename CharType>
4384 static inline bool isValidNameASCII(const CharType* characters, unsigned length)
4386 CharType c = characters[0];
4387 if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
4390 for (unsigned i = 1; i < length; ++i) {
4392 if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
4399 bool Document::isValidName(const String& name)
4401 unsigned length = name.length();
4405 const UChar* characters;
4406 if (name.is8Bit()) {
4407 if (isValidNameASCII(name.characters8(), length))
4409 characters = name.characters();
4411 characters = name.characters16();
4412 if (isValidNameASCII(characters, length))
4415 return isValidNameNonASCII(characters, length);
4418 bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode& ec)
4420 unsigned length = qualifiedName.length();
4423 ec = INVALID_CHARACTER_ERR;
4427 bool nameStart = true;
4428 bool sawColon = false;
4431 const UChar* s = qualifiedName.characters();
4432 for (unsigned i = 0; i < length;) {
4434 U16_NEXT(s, i, length, c)
4438 return false; // multiple colons: not allowed
4443 } else if (nameStart) {
4444 if (!isValidNameStart(c)) {
4445 ec = INVALID_CHARACTER_ERR;
4450 if (!isValidNamePart(c)) {
4451 ec = INVALID_CHARACTER_ERR;
4459 localName = qualifiedName;
4461 prefix = qualifiedName.substring(0, colonPos);
4462 if (prefix.isEmpty()) {
4466 localName = qualifiedName.substring(colonPos + 1);
4469 if (localName.isEmpty()) {
4477 void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
4479 m_decoder = decoder;
4482 KURL Document::completeURL(const String& url, const KURL& baseURLOverride) const
4484 // Always return a null URL when passed a null string.
4485 // FIXME: Should we change the KURL constructor to have this behavior?
4486 // See also [CSS]StyleSheet::completeURL(const String&)
4489 const KURL& baseURL = ((baseURLOverride.isEmpty() || baseURLOverride == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : baseURLOverride;
4491 return KURL(baseURL, url);
4492 return KURL(baseURL, url, m_decoder->encoding());
4495 KURL Document::completeURL(const String& url) const
4497 return completeURL(url, m_baseURL);
4500 void Document::setInPageCache(bool flag)
4502 if (m_inPageCache == flag)
4505 m_inPageCache = flag;
4507 FrameView* v = view();
4509 ASSERT(!m_savedRenderer);
4510 m_savedRenderer = renderer();
4512 v->cacheCurrentScrollPosition();
4513 if (page() && page()->mainFrame() == m_frame)
4514 v->resetScrollbarsAndClearContentsSize();
4516 v->resetScrollbars();
4518 m_styleRecalcTimer.stop();
4520 ASSERT(!renderer() || renderer() == m_savedRenderer);
4521 ASSERT(m_renderArena);
4522 setRenderer(m_savedRenderer);
4523 m_savedRenderer = 0;
4525 if (childNeedsStyleRecalc())
4526 scheduleStyleRecalc();
4530 void Document::documentWillBecomeInactive()
4532 #if USE(ACCELERATED_COMPOSITING)
4534 renderView()->willMoveOffscreen();
4538 void Document::documentWillSuspendForPageCache()
4540 documentWillBecomeInactive();
4542 HashSet<Element*>::iterator end = m_documentSuspensionCallbackElements.end();
4543 for (HashSet<Element*>::iterator i = m_documentSuspensionCallbackElements.begin(); i != end; ++i)
4544 (*i)->documentWillSuspendForPageCache();
4547 // Clear the update flag to be able to check if the viewport arguments update
4548 // is dispatched, after the document is restored from the page cache.
4549 m_didDispatchViewportPropertiesChanged = false;
4553 void Document::documentDidResumeFromPageCache()
4555 Vector<Element*> elements;
4556 copyToVector(m_documentSuspensionCallbackElements, elements);
4557 Vector<Element*>::iterator end = elements.end();
4558 for (Vector<Element*>::iterator i = elements.begin(); i != end; ++i)
4559 (*i)->documentDidResumeFromPageCache();
4561 #if USE(ACCELERATED_COMPOSITING)
4563 renderView()->didMoveOnscreen();
4566 if (FrameView* frameView = view())
4567 frameView->setAnimatorsAreActive();
4570 m_frame->loader()->client()->dispatchDidBecomeFrameset(isFrameSet());
4573 void Document::registerForPageCacheSuspensionCallbacks(Element* e)
4575 m_documentSuspensionCallbackElements.add(e);
4578 void Document::unregisterForPageCacheSuspensionCallbacks(Element* e)
4580 m_documentSuspensionCallbackElements.remove(e);
4583 void Document::mediaVolumeDidChange()
4585 HashSet<Element*>::iterator end = m_mediaVolumeCallbackElements.end();
4586 for (HashSet<Element*>::iterator i = m_mediaVolumeCallbackElements.begin(); i != end; ++i)
4587 (*i)->mediaVolumeDidChange();
4590 void Document::registerForMediaVolumeCallbacks(Element* e)
4592 m_mediaVolumeCallbackElements.add(e);
4595 void Document::unregisterForMediaVolumeCallbacks(Element* e)
4597 m_mediaVolumeCallbackElements.remove(e);
4600 void Document::privateBrowsingStateDidChange()
4602 HashSet<Element*>::iterator end = m_privateBrowsingStateChangedElements.end();
4603 for (HashSet<Element*>::iterator it = m_privateBrowsingStateChangedElements.begin(); it != end; ++it)
4604 (*it)->privateBrowsingStateDidChange();
4607 void Document::registerForPrivateBrowsingStateChangedCallbacks(Element* e)
4609 m_privateBrowsingStateChangedElements.add(e);
4612 void Document::unregisterForPrivateBrowsingStateChangedCallbacks(Element* e)
4614 m_privateBrowsingStateChangedElements.remove(e);
4617 void Document::setShouldCreateRenderers(bool f)
4619 m_createRenderers = f;
4622 bool Document::shouldCreateRenderers()
4624 return m_createRenderers;
4627 // Support for Javascript execCommand, and related methods
4629 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
4631 Frame* frame = document->frame();
4632 if (!frame || frame->document() != document)
4633 return Editor::Command();
4635 document->updateStyleIfNeeded();
4637 return frame->editor()->command(commandName,
4638 userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
4641 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
4643 return command(this, commandName, userInterface).execute(value);
4646 bool Document::queryCommandEnabled(const String& commandName)
4648 return command(this, commandName).isEnabled();
4651 bool Document::queryCommandIndeterm(const String& commandName)
4653 return command(this, commandName).state() == MixedTriState;
4656 bool Document::queryCommandState(const String& commandName)
4658 return command(this, commandName).state() == TrueTriState;
4661 bool Document::queryCommandSupported(const String& commandName)
4663 return command(this, commandName).isSupported();
4666 String Document::queryCommandValue(const String& commandName)
4668 return command(this, commandName).value();
4671 KURL Document::openSearchDescriptionURL()
4673 static const char* const openSearchMIMEType = "application/opensearchdescription+xml";
4674 static const char* const openSearchRelation = "search";
4676 // FIXME: Why do only top-level frames have openSearchDescriptionURLs?
4677 if (!frame() || frame()->tree()->parent())
4680 // FIXME: Why do we need to wait for FrameStateComplete?
4681 if (frame()->loader()->state() != FrameStateComplete)
4687 RefPtr<HTMLCollection> children = head()->children();
4688 for (unsigned i = 0; Node* child = children->item(i); i++) {
4689 if (!child->hasTagName(linkTag))
4691 HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(child);
4692 if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
4694 if (linkElement->href().isEmpty())
4696 return linkElement->href();
4704 void Document::applyXSLTransform(ProcessingInstruction* pi)
4706 RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
4707 processor->setXSLStyleSheet(static_cast<XSLStyleSheet*>(pi->sheet()));
4708 String resultMIMEType;
4710 String resultEncoding;
4711 if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
4713 // FIXME: If the transform failed we should probably report an error (like Mozilla does).
4714 processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, frame());
4717 void Document::setTransformSource(PassOwnPtr<TransformSource> source)
4719 m_transformSource = source;
4724 void Document::setDesignMode(InheritedBool value)
4726 m_designMode = value;
4727 for (Frame* frame = m_frame; frame && frame->document(); frame = frame->tree()->traverseNext(m_frame))
4728 frame->document()->scheduleForcedStyleRecalc();
4731 Document::InheritedBool Document::getDesignMode() const
4733 return m_designMode;
4736 bool Document::inDesignMode() const
4738 for (const Document* d = this; d; d = d->parentDocument()) {
4739 if (d->m_designMode != inherit)
4740 return d->m_designMode;
4745 Document* Document::parentDocument() const
4749 Frame* parent = m_frame->tree()->parent();
4752 return parent->document();
4755 Document* Document::topDocument() const
4757 Document* doc = const_cast<Document *>(this);
4759 while ((element = doc->ownerElement()))
4760 doc = element->document();
4765 PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionCode& ec)
4767 return createAttributeNS(String(), name, ec, true);
4770 PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec, bool shouldIgnoreNamespaceChecks)
4772 String prefix, localName;
4773 if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
4776 QualifiedName qName(prefix, localName, namespaceURI);
4778 if (!shouldIgnoreNamespaceChecks && !hasValidNamespaceForAttributes(qName)) {
4783 return Attr::create(this, qName, emptyString());
4787 const SVGDocumentExtensions* Document::svgExtensions()
4789 return m_svgExtensions.get();
4792 SVGDocumentExtensions* Document::accessSVGExtensions()
4794 if (!m_svgExtensions)
4795 m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this));
4796 return m_svgExtensions.get();
4799 bool Document::hasSVGRootNode() const
4801 return documentElement() && documentElement()->hasTagName(SVGNames::svgTag);
4805 // FIXME: This caching mechanism should be merged that of DynamicNodeList in NodeRareData.
4806 PassRefPtr<HTMLCollection> Document::cachedCollection(CollectionType type)
4808 ASSERT(static_cast<unsigned>(type) < NumUnnamedDocumentCachedTypes);
4809 if (m_collections[type])
4810 return m_collections[type];
4812 RefPtr<HTMLCollection> collection;
4814 collection = HTMLAllCollection::create(this);
4816 collection = HTMLCollection::create(this, type);
4817 m_collections[type] = collection.get();
4819 return collection.release();
4822 void Document::removeCachedHTMLCollection(HTMLCollection* collection, CollectionType type)
4824 ASSERT_UNUSED(collection, m_collections[type] == collection);
4825 m_collections[type] = 0;
4828 PassRefPtr<HTMLCollection> Document::images()
4830 return cachedCollection(DocImages);
4833 PassRefPtr<HTMLCollection> Document::applets()
4835 return cachedCollection(DocApplets);
4838 PassRefPtr<HTMLCollection> Document::embeds()
4840 return cachedCollection(DocEmbeds);
4843 PassRefPtr<HTMLCollection> Document::plugins()
4845 // This is an alias for embeds() required for the JS DOM bindings.
4846 return cachedCollection(DocEmbeds);
4849 PassRefPtr<HTMLCollection> Document::objects()
4851 return cachedCollection(DocObjects);
4854 PassRefPtr<HTMLCollection> Document::scripts()
4856 return cachedCollection(DocScripts);
4859 PassRefPtr<HTMLCollection> Document::links()
4861 return cachedCollection(DocLinks);
4864 PassRefPtr<HTMLCollection> Document::forms()
4866 return cachedCollection(DocForms);
4869 PassRefPtr<HTMLCollection> Document::anchors()
4871 return cachedCollection(DocAnchors);
4874 PassRefPtr<HTMLCollection> Document::all()
4876 return cachedCollection(DocAll);
4879 PassRefPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
4881 NamedCollectionMap::AddResult result = m_windowNamedItemCollections.add(name, 0);
4882 if (!result.isNewEntry)
4883 return result.iterator->second;
4885 RefPtr<HTMLNameCollection> collection = HTMLNameCollection::create(this, WindowNamedItems, name);
4886 result.iterator->second = collection.get();
4887 return collection.release();
4890 PassRefPtr<HTMLCollection> Document::documentNamedItems(const AtomicString& name)
4892 NamedCollectionMap::AddResult result = m_documentNamedItemCollections.add(name, 0);
4893 if (!result.isNewEntry)
4894 return result.iterator->second;
4896 RefPtr<HTMLNameCollection> collection = HTMLNameCollection::create(this, DocumentNamedItems, name);
4897 result.iterator->second = collection.get();
4898 return collection.release();
4901 // FIXME: This caching mechanism should be merged that of DynamicNodeList in NodeRareData.
4902 void Document::removeWindowNamedItemCache(HTMLCollection* collection, const AtomicString& name)
4904 ASSERT_UNUSED(collection, m_windowNamedItemCollections.get(name) == collection);
4905 m_windowNamedItemCollections.remove(name);
4908 void Document::removeDocumentNamedItemCache(HTMLCollection* collection, const AtomicString& name)
4910 ASSERT_UNUSED(collection, m_documentNamedItemCollections.get(name) == collection);
4911 m_documentNamedItemCollections.remove(name);
4914 void Document::finishedParsing()
4916 ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
4917 ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
4919 if (!m_documentTiming.domContentLoadedEventStart)
4920 m_documentTiming.domContentLoadedEventStart = monotonicallyIncreasingTime();
4921 dispatchEvent(Event::create(eventNames().DOMContentLoadedEvent, true, false));
4922 if (!m_documentTiming.domContentLoadedEventEnd)
4923 m_documentTiming.domContentLoadedEventEnd = monotonicallyIncreasingTime();
4925 if (RefPtr<Frame> f = frame()) {
4926 // FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
4927 // resource loads are complete. HTMLObjectElements can start loading their resources from
4928 // post attach callbacks triggered by recalcStyle(). This means if we parse out an <object>
4929 // tag and then reach the end of the document without updating styles, we might not have yet
4930 // started the resource load and might fire the window load event too early. To avoid this
4931 // we force the styles to be up to date before calling FrameLoader::finishedParsing().
4932 // See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
4933 updateStyleIfNeeded();
4935 f->loader()->finishedParsing();
4937 InspectorInstrumentation::domContentLoadedEventFired(f.get());
4941 PassRefPtr<XPathExpression> Document::createExpression(const String& expression,
4942 XPathNSResolver* resolver,
4945 if (!m_xpathEvaluator)
4946 m_xpathEvaluator = XPathEvaluator::create();
4947 return m_xpathEvaluator->createExpression(expression, resolver, ec);
4950 PassRefPtr<XPathNSResolver> Document::createNSResolver(Node* nodeResolver)
4952 if (!m_xpathEvaluator)
4953 m_xpathEvaluator = XPathEvaluator::create();
4954 return m_xpathEvaluator->createNSResolver(nodeResolver);
4957 PassRefPtr<XPathResult> Document::evaluate(const String& expression,
4959 XPathNSResolver* resolver,
4960 unsigned short type,
4961 XPathResult* result,
4964 if (!m_xpathEvaluator)
4965 m_xpathEvaluator = XPathEvaluator::create();
4966 return m_xpathEvaluator->evaluate(expression, contextNode, resolver, type, result, ec);
4969 const Vector<IconURL>& Document::iconURLs()
4973 if (!head() || !(head()->children()))
4976 // Include any icons where type = link, rel = "shortcut icon".
4977 RefPtr<HTMLCollection> children = head()->children();
4978 unsigned int length = children->length();
4979 for (unsigned int i = 0; i < length; ++i) {
4980 Node* child = children->item(i);
4981 if (!child->hasTagName(linkTag))
4983 HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(child);
4984 if (linkElement->iconType() != Favicon)
4986 if (linkElement->href().isEmpty())
4989 // Put it at the front to ensure that icons seen later take precedence as required by the spec.
4990 IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
4991 m_iconURLs.prepend(newURL);
4997 void Document::addIconURL(const String& url, const String& mimeType, const String& sizes, IconType iconType)
5002 // FIXME - <rdar://problem/4727645> - At some point in the future, we might actually honor the "mimeType"
5003 IconURL newURL(KURL(ParsedURLString, url), sizes, mimeType, iconType);
5005 if (Frame* f = frame()) {
5006 IconURL iconURL = f->loader()->icon()->iconURL(iconType);
5007 if (iconURL == newURL)
5008 f->loader()->didChangeIcons(iconType);
5012 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
5014 if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
5017 m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
5018 m_frame->selection()->updateSecureKeyboardEntryIfActive();
5021 bool Document::useSecureKeyboardEntryWhenActive() const
5023 return m_useSecureKeyboardEntryWhenActive;
5026 static bool isEligibleForSeamless(Document* parent, Document* child)
5028 // It should not matter what we return for the top-most document.
5031 if (parent->isSandboxed(SandboxSeamlessIframes))
5033 if (child->isSrcdocDocument())
5035 if (parent->securityOrigin()->canAccess(child->securityOrigin()))
5037 return parent->securityOrigin()->canRequest(child->url());
5040 void Document::initSecurityContext()
5042 if (haveInitializedSecurityOrigin()) {
5043 ASSERT(securityOrigin());
5048 // No source for a security context.
5049 // This can occur via document.implementation.createDocument().
5050 m_cookieURL = KURL(ParsedURLString, emptyString());
5051 setSecurityOrigin(SecurityOrigin::createUnique());
5052 setContentSecurityPolicy(ContentSecurityPolicy::create(this));
5056 // In the common case, create the security context from the currently
5057 // loading URL with a fresh content security policy.
5058 m_cookieURL = m_url;
5059 enforceSandboxFlags(m_frame->loader()->effectiveSandboxFlags());
5060 setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
5061 setContentSecurityPolicy(ContentSecurityPolicy::create(this));
5063 if (SecurityPolicy::allowSubstituteDataAccessToLocal()) {
5064 // If this document was loaded with substituteData, then the document can
5065 // load local resources. See https://bugs.webkit.org/show_bug.cgi?id=16756
5066 // and https://bugs.webkit.org/show_bug.cgi?id=19760 for further
5069 DocumentLoader* documentLoader = loader();
5070 if (documentLoader && documentLoader->substituteData().isValid())
5071 securityOrigin()->grantLoadLocalResources();
5074 if (Settings* settings = this->settings()) {
5075 if (!settings->isWebSecurityEnabled()) {
5076 // Web security is turned off. We should let this document access every other document. This is used primary by testing
5077 // harnesses for web sites.
5078 securityOrigin()->grantUniversalAccess();
5079 } else if (securityOrigin()->isLocal()) {
5080 if (settings->allowUniversalAccessFromFileURLs() || m_frame->loader()->client()->shouldForceUniversalAccessFromLocalURL(m_url)) {
5081 // Some clients want local URLs to have universal access, but that setting is dangerous for other clients.
5082 securityOrigin()->grantUniversalAccess();
5083 } else if (!settings->allowFileAccessFromFileURLs()) {
5084 // Some clients want local URLs to have even tighter restrictions by default, and not be able to access other local files.
5085 // FIXME 81578: The naming of this is confusing. Files with restricted access to other local files
5086 // still can have other privileges that can be remembered, thereby not making them unique origins.
5087 securityOrigin()->enforceFilePathSeparation();
5092 Document* parentDocument = ownerElement() ? ownerElement()->document() : 0;
5093 if (parentDocument && m_frame->loader()->shouldTreatURLAsSrcdocDocument(url())) {
5094 m_isSrcdocDocument = true;
5095 setBaseURLOverride(parentDocument->baseURL());
5098 // FIXME: What happens if we inherit the security origin? This check may need to be later.
5099 // <iframe seamless src="about:blank"> likely won't work as-is.
5100 m_mayDisplaySeamlessWithParent = isEligibleForSeamless(parentDocument, this);
5102 if (!shouldInheritSecurityOriginFromOwner(m_url))
5105 // If we do not obtain a meaningful origin from the URL, then we try to
5106 // find one via the frame hierarchy.
5108 Frame* ownerFrame = m_frame->tree()->parent();
5110 ownerFrame = m_frame->loader()->opener();
5113 didFailToInitializeSecurityOrigin();
5117 if (isSandboxed(SandboxOrigin)) {
5118 // If we're supposed to inherit our security origin from our owner,
5119 // but we're also sandboxed, the only thing we inherit is the ability
5120 // to load local resources. This lets about:blank iframes in file://
5121 // URL documents load images and other resources from the file system.
5122 if (ownerFrame->document()->securityOrigin()->canLoadLocalResources())
5123 securityOrigin()->grantLoadLocalResources();
5127 m_cookieURL = ownerFrame->document()->cookieURL();
5128 // We alias the SecurityOrigins to match Firefox, see Bug 15313
5129 // https://bugs.webkit.org/show_bug.cgi?id=15313
5130 setSecurityOrigin(ownerFrame->document()->securityOrigin());
5133 void Document::initContentSecurityPolicy()
5135 if (!m_frame->tree()->parent() || !shouldInheritSecurityOriginFromOwner(m_url))
5137 contentSecurityPolicy()->copyStateFrom(m_frame->tree()->parent()->document()->contentSecurityPolicy());
5140 #if ENABLE(TIZEN_CSP)
5141 void Document::copyContentSecurityPolicy(Document* other)
5143 contentSecurityPolicy()->copyStateFrom(other->contentSecurityPolicy());
5147 void Document::didUpdateSecurityOrigin()
5151 // FIXME: We should remove DOMWindow::m_securityOrigin so that we don't need to keep them in sync.
5152 // See <https://bugs.webkit.org/show_bug.cgi?id=75793>.
5153 m_frame->domWindow()->setSecurityOrigin(securityOrigin());
5154 m_frame->script()->updateSecurityOrigin();
5157 bool Document::isContextThread() const
5159 return isMainThread();
5162 void Document::updateURLForPushOrReplaceState(const KURL& url)
5169 f->loader()->setOutgoingReferrer(url);
5171 if (DocumentLoader* documentLoader = loader())
5172 documentLoader->replaceRequestURLForSameDocumentNavigation(url);
5175 void Document::statePopped(PassRefPtr<SerializedScriptValue> stateObject)
5180 // Per step 11 of section 6.5.9 (history traversal) of the HTML5 spec, we
5181 // defer firing of popstate until we're in the complete state.
5182 if (m_readyState == Complete)
5183 enqueuePopstateEvent(stateObject);
5185 m_pendingStateObject = stateObject;
5188 void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
5190 m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
5191 if (!m_updateFocusAppearanceTimer.isActive())
5192 m_updateFocusAppearanceTimer.startOneShot(0);
5195 void Document::cancelFocusAppearanceUpdate()
5197 m_updateFocusAppearanceTimer.stop();
5200 void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
5202 Node* node = focusedNode();
5205 if (!node->isElementNode())
5210 Element* element = static_cast<Element*>(node);
5211 if (element->isFocusable())
5212 element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
5215 void Document::attachRange(Range* range)
5217 ASSERT(!m_ranges.contains(range));
5218 m_ranges.add(range);
5221 void Document::detachRange(Range* range)
5223 // We don't ASSERT m_ranges.contains(range) to allow us to call this
5224 // unconditionally to fix: https://bugs.webkit.org/show_bug.cgi?id=26044
5225 m_ranges.remove(range);
5228 CanvasRenderingContext* Document::getCSSCanvasContext(const String& type, const String& name, int width, int height)
5230 HTMLCanvasElement* element = getCSSCanvasElement(name);
5233 element->setSize(IntSize(width, height));
5234 return element->getContext(type);
5237 HTMLCanvasElement* Document::getCSSCanvasElement(const String& name)
5239 RefPtr<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, 0).iterator->second;
5241 element = HTMLCanvasElement::create(this);
5242 return element.get();
5245 void Document::initDNSPrefetch()
5247 Settings* settings = this->settings();
5249 m_haveExplicitlyDisabledDNSPrefetch = false;
5250 m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
5252 // Inherit DNS prefetch opt-out from parent frame
5253 if (Document* parent = parentDocument()) {
5254 if (!parent->isDNSPrefetchEnabled())
5255 m_isDNSPrefetchEnabled = false;
5259 void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
5261 if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
5262 m_isDNSPrefetchEnabled = true;
5266 m_isDNSPrefetchEnabled = false;
5267 m_haveExplicitlyDisabledDNSPrefetch = true;
5270 void Document::addMessage(MessageSource source, MessageType type, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack)
5272 if (!isContextThread()) {
5273 postTask(AddConsoleMessageTask::create(source, type, level, message));
5277 if (DOMWindow* window = domWindow())
5278 window->console()->addMessage(source, type, level, message, sourceURL, lineNumber, callStack);
5281 struct PerformTaskContext {
5282 WTF_MAKE_NONCOPYABLE(PerformTaskContext); WTF_MAKE_FAST_ALLOCATED;
5284 PerformTaskContext(PassRefPtr<DocumentWeakReference> documentReference, PassOwnPtr<ScriptExecutionContext::Task> task)
5285 : documentReference(documentReference)
5290 RefPtr<DocumentWeakReference> documentReference;
5291 OwnPtr<ScriptExecutionContext::Task> task;
5294 void Document::didReceiveTask(void* untypedContext)
5296 ASSERT(isMainThread());
5298 OwnPtr<PerformTaskContext> context = adoptPtr(static_cast<PerformTaskContext*>(untypedContext));
5301 Document* document = context->documentReference->document();
5305 Page* page = document->page();
5306 if ((page && page->defersLoading()) || !document->m_pendingTasks.isEmpty()) {
5307 document->m_pendingTasks.append(context->task.release());
5311 context->task->performTask(document);
5314 void Document::postTask(PassOwnPtr<Task> task)
5316 callOnMainThread(didReceiveTask, new PerformTaskContext(m_weakReference, task));
5319 void Document::pendingTasksTimerFired(Timer<Document>*)
5321 while (!m_pendingTasks.isEmpty()) {
5322 OwnPtr<Task> task = m_pendingTasks[0].release();
5323 m_pendingTasks.remove(0);
5324 task->performTask(this);
5328 void Document::suspendScheduledTasks(ActiveDOMObject::ReasonForSuspension reason)
5330 ASSERT(!m_scheduledTasksAreSuspended);
5332 suspendScriptedAnimationControllerCallbacks();
5333 suspendActiveDOMObjects(reason);
5334 scriptRunner()->suspend();
5335 m_pendingTasksTimer.stop();
5337 m_parser->suspendScheduledTasks();
5339 m_scheduledTasksAreSuspended = true;
5342 void Document::resumeScheduledTasks()
5344 ASSERT(m_scheduledTasksAreSuspended);
5347 m_parser->resumeScheduledTasks();
5348 if (!m_pendingTasks.isEmpty())
5349 m_pendingTasksTimer.startOneShot(0);
5350 scriptRunner()->resume();
5351 resumeActiveDOMObjects();
5352 resumeScriptedAnimationControllerCallbacks();
5354 m_scheduledTasksAreSuspended = false;
5357 void Document::suspendScriptedAnimationControllerCallbacks()
5359 #if ENABLE(REQUEST_ANIMATION_FRAME)
5360 if (m_scriptedAnimationController)
5361 m_scriptedAnimationController->suspend();
5365 void Document::resumeScriptedAnimationControllerCallbacks()
5367 #if ENABLE(REQUEST_ANIMATION_FRAME)
5368 if (m_scriptedAnimationController)
5369 m_scriptedAnimationController->resume();
5373 void Document::windowScreenDidChange(PlatformDisplayID displayID)
5375 UNUSED_PARAM(displayID);
5377 #if ENABLE(REQUEST_ANIMATION_FRAME)
5378 if (m_scriptedAnimationController)
5379 m_scriptedAnimationController->windowScreenDidChange(displayID);
5382 #if USE(ACCELERATED_COMPOSITING)
5383 if (renderView()->usesCompositing())
5384 renderView()->compositor()->windowScreenDidChange(displayID);
5388 String Document::displayStringModifiedByEncoding(const String& str) const
5391 return m_decoder->encoding().displayString(str.impl());
5395 PassRefPtr<StringImpl> Document::displayStringModifiedByEncoding(PassRefPtr<StringImpl> str) const
5398 return m_decoder->encoding().displayString(str);
5402 void Document::displayBufferModifiedByEncoding(UChar* buffer, unsigned len) const
5405 m_decoder->encoding().displayBuffer(buffer, len);
5408 void Document::enqueuePageshowEvent(PageshowEventPersistence persisted)
5410 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36334 Pageshow event needs to fire asynchronously.
5411 dispatchWindowEvent(PageTransitionEvent::create(eventNames().pageshowEvent, persisted), this);
5414 void Document::enqueueHashchangeEvent(const String& oldURL, const String& newURL)
5416 enqueueWindowEvent(HashChangeEvent::create(oldURL, newURL));
5419 void Document::enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject)
5421 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36202 Popstate event needs to fire asynchronously
5422 dispatchWindowEvent(PopStateEvent::create(stateObject, domWindow() ? domWindow()->history() : 0));
5425 void Document::addMediaCanStartListener(MediaCanStartListener* listener)
5427 ASSERT(!m_mediaCanStartListeners.contains(listener));
5428 m_mediaCanStartListeners.add(listener);
5431 void Document::removeMediaCanStartListener(MediaCanStartListener* listener)
5433 ASSERT(m_mediaCanStartListeners.contains(listener));
5434 m_mediaCanStartListeners.remove(listener);
5437 MediaCanStartListener* Document::takeAnyMediaCanStartListener()
5439 HashSet<MediaCanStartListener*>::iterator slot = m_mediaCanStartListeners.begin();
5440 if (slot == m_mediaCanStartListeners.end())
5442 MediaCanStartListener* listener = *slot;
5443 m_mediaCanStartListeners.remove(slot);
5447 #if ENABLE(FULLSCREEN_API)
5448 bool Document::fullScreenIsAllowedForElement(Element* element) const
5451 return isAttributeOnAllOwners(webkitallowfullscreenAttr, element->document()->ownerElement());
5454 void Document::requestFullScreenForElement(Element* element, unsigned short flags, FullScreenCheckType checkType)
5456 // The Mozilla Full Screen API <https://wiki.mozilla.org/Gecko:FullScreenAPI> has different requirements
5457 // for full screen mode, and do not have the concept of a full screen element stack.
5458 bool inLegacyMozillaMode = (flags & Element::LEGACY_MOZILLA_REQUEST);
5462 element = documentElement();
5464 // 1. If any of the following conditions are true, terminate these steps and queue a task to fire
5465 // an event named fullscreenerror with its bubbles attribute set to true on the context object's
5468 // The context object is not in a document.
5469 if (!element->inDocument())
5472 // The context object's node document, or an ancestor browsing context's document does not have
5473 // the fullscreen enabled flag set.
5474 if (checkType == EnforceIFrameAllowFullScreenRequirement && !fullScreenIsAllowedForElement(element))
5477 // The context object's node document fullscreen element stack is not empty and its top element
5478 // is not an ancestor of the context object. (NOTE: Ignore this requirement if the request was
5479 // made via the legacy Mozilla-style API.)
5480 if (!m_fullScreenElementStack.isEmpty() && !m_fullScreenElementStack.first()->contains(element) && !inLegacyMozillaMode)
5483 // A descendant browsing context's document has a non-empty fullscreen element stack.
5484 bool descendentHasNonEmptyStack = false;
5485 for (Frame* descendant = frame() ? frame()->tree()->traverseNext() : 0; descendant; descendant = descendant->tree()->traverseNext()) {
5486 if (descendant->document()->webkitFullscreenElement()) {
5487 descendentHasNonEmptyStack = true;
5491 if (descendentHasNonEmptyStack && !inLegacyMozillaMode)
5494 // This algorithm is not allowed to show a pop-up:
5495 // An algorithm is allowed to show a pop-up if, in the task in which the algorithm is running, either:
5496 // - an activation behavior is currently being processed whose click event was trusted, or
5497 // - the event listener for a trusted click event is being handled.
5498 #if ENABLE(TIZEN_EXTENSIBLE_API)
5499 if (!TizenExtensibleAPI::extensibleAPI().fullScreen())
5500 if (!ScriptController::processingUserGesture())
5503 if (!ScriptController::processingUserGesture())
5507 // There is a previously-established user preference, security risk, or platform limitation.
5508 if (!page() || !page()->settings()->fullScreenEnabled())
5511 if (!page()->chrome()->client()->supportsFullScreenForElement(element, flags & Element::ALLOW_KEYBOARD_INPUT))
5514 // 2. Let doc be element's node document. (i.e. "this")
5515 Document* currentDoc = this;
5517 // 3. Let docs be all doc's ancestor browsing context's documents (if any) and doc.
5518 Deque<Document*> docs;
5521 docs.prepend(currentDoc);
5522 currentDoc = currentDoc->ownerElement() ? currentDoc->ownerElement()->document() : 0;
5523 } while (currentDoc);
5525 // 4. For each document in docs, run these substeps:
5526 Deque<Document*>::iterator current = docs.begin(), following = docs.begin();
5531 // 1. Let following document be the document after document in docs, or null if there is no
5533 Document* currentDoc = *current;
5534 Document* followingDoc = following != docs.end() ? *following : 0;
5536 // 2. If following document is null, push context object on document's fullscreen element
5537 // stack, and queue a task to fire an event named fullscreenchange with its bubbles attribute
5538 // set to true on the document.
5539 if (!followingDoc) {
5540 currentDoc->pushFullscreenElementStack(element);
5541 addDocumentToFullScreenChangeEventQueue(currentDoc);
5545 // 3. Otherwise, if document's fullscreen element stack is either empty or its top element
5546 // is not following document's browsing context container,
5547 Element* topElement = currentDoc->webkitFullscreenElement();
5548 if (!topElement || topElement != followingDoc->ownerElement()) {
5549 // ...push following document's browsing context container on document's fullscreen element
5550 // stack, and queue a task to fire an event named fullscreenchange with its bubbles attribute
5551 // set to true on document.
5552 currentDoc->pushFullscreenElementStack(followingDoc->ownerElement());
5553 addDocumentToFullScreenChangeEventQueue(currentDoc);
5557 // 4. Otherwise, do nothing for this document. It stays the same.
5558 } while (++current != docs.end());
5560 // 5. Return, and run the remaining steps asynchronously.
5561 // 6. Optionally, perform some animation.
5562 m_areKeysEnabledInFullScreen = flags & Element::ALLOW_KEYBOARD_INPUT;
5563 #if ENABLE(TIZEN_FULLSCREEN_API)
5564 m_exitFullScreenByHwBackKey = flags & Element::HARDWARE_BACKKEY_EXIT;
5566 page()->chrome()->client()->enterFullScreenForElement(element);
5568 // 7. Optionally, display a message indicating how the user can exit displaying the context object fullscreen.
5572 m_fullScreenErrorEventTargetQueue.append(element ? element : documentElement());
5573 m_fullScreenChangeDelayTimer.startOneShot(0);
5576 void Document::webkitCancelFullScreen()
5578 // The Mozilla "cancelFullScreen()" API behaves like the W3C "fully exit fullscreen" behavior, which
5580 // "To fully exit fullscreen act as if the exitFullscreen() method was invoked on the top-level browsing
5581 // context's document and subsequently empty that document's fullscreen element stack."
5582 if (!topDocument()->webkitFullscreenElement())
5585 // To achieve that aim, remove all the elements from the top document's stack except for the first before
5586 // calling webkitExitFullscreen():
5587 Deque<RefPtr<Element> > replacementFullscreenElementStack;
5588 replacementFullscreenElementStack.prepend(topDocument()->webkitFullscreenElement());
5589 topDocument()->m_fullScreenElementStack.swap(replacementFullscreenElementStack);
5591 topDocument()->webkitExitFullscreen();
5594 void Document::webkitExitFullscreen()
5596 // The exitFullscreen() method must run these steps:
5598 // 1. Let doc be the context object. (i.e. "this")
5599 Document* currentDoc = this;
5601 // 2. If doc's fullscreen element stack is empty, terminate these steps.
5602 if (m_fullScreenElementStack.isEmpty())
5605 // 3. Let descendants be all the doc's descendant browsing context's documents with a non-empty fullscreen
5606 // element stack (if any), ordered so that the child of the doc is last and the document furthest
5607 // away from the doc is first.
5608 Deque<RefPtr<Document> > descendants;
5609 for (Frame* descendant = frame() ? frame()->tree()->traverseNext() : 0; descendant; descendant = descendant->tree()->traverseNext()) {
5610 if (descendant->document()->webkitFullscreenElement())
5611 descendants.prepend(descendant->document());
5614 // 4. For each descendant in descendants, empty descendant's fullscreen element stack, and queue a
5615 // task to fire an event named fullscreenchange with its bubbles attribute set to true on descendant.
5616 for (Deque<RefPtr<Document> >::iterator i = descendants.begin(); i != descendants.end(); ++i) {
5617 (*i)->clearFullscreenElementStack();
5618 addDocumentToFullScreenChangeEventQueue(i->get());
5621 // 5. While doc is not null, run these substeps:
5622 Element* newTop = 0;
5623 while (currentDoc) {
5624 // 1. Pop the top element of doc's fullscreen element stack.
5625 currentDoc->popFullscreenElementStack();
5627 // If doc's fullscreen element stack is non-empty and the element now at the top is either
5628 // not in a document or its node document is not doc, repeat this substep.
5629 newTop = currentDoc->webkitFullscreenElement();
5630 if (newTop && (!newTop->inDocument() || newTop->document() != currentDoc))
5633 // 2. Queue a task to fire an event named fullscreenchange with its bubbles attribute set to true
5635 addDocumentToFullScreenChangeEventQueue(currentDoc);
5637 // 3. If doc's fullscreen element stack is empty and doc's browsing context has a browsing context
5638 // container, set doc to that browsing context container's node document.
5639 if (!newTop && currentDoc->ownerElement()) {
5640 currentDoc = currentDoc->ownerElement()->document();
5644 // 4. Otherwise, set doc to null.
5648 // 6. Return, and run the remaining steps asynchronously.
5649 // 7. Optionally, perform some animation.
5651 // Only exit out of full screen window mode if there are no remaining elements in the
5652 // full screen stack.
5654 page()->chrome()->client()->exitFullScreenForElement(m_fullScreenElement.get());
5658 // Otherwise, notify the chrome of the new full screen element.
5659 page()->chrome()->client()->enterFullScreenForElement(newTop);
5662 bool Document::webkitFullscreenEnabled() const
5664 // 4. The fullscreenEnabled attribute must return true if the context object and all ancestor
5665 // browsing context's documents have their fullscreen enabled flag set, or false otherwise.
5667 // Top-level browsing contexts are implied to have their allowFullScreen attribute set.
5668 return isAttributeOnAllOwners(webkitallowfullscreenAttr, ownerElement());
5671 void Document::webkitWillEnterFullScreenForElement(Element* element)
5673 if (!attached() || inPageCache())
5678 // Protect against being called after the document has been removed from the page.
5682 ASSERT(page()->settings()->fullScreenEnabled());
5684 if (m_fullScreenRenderer)
5685 m_fullScreenRenderer->unwrapRenderer();
5687 m_fullScreenElement = element;
5689 #if USE(NATIVE_FULLSCREEN_VIDEO)
5690 if (element && element->isMediaElement())
5694 // Create a placeholder block for a the full-screen element, to keep the page from reflowing
5695 // when the element is removed from the normal flow. Only do this for a RenderBox, as only
5696 // a box will have a frameRect. The placeholder will be created in setFullScreenRenderer()
5698 RenderObject* renderer = m_fullScreenElement->renderer();
5699 bool shouldCreatePlaceholder = renderer && renderer->isBox();
5700 if (shouldCreatePlaceholder) {
5701 m_savedPlaceholderFrameRect = toRenderBox(renderer)->frameRect();
5702 m_savedPlaceholderRenderStyle = RenderStyle::clone(renderer->style());
5705 if (m_fullScreenElement != documentElement())
5706 RenderFullScreen::wrapRenderer(renderer, this);
5708 m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
5713 void Document::webkitDidEnterFullScreenForElement(Element*)
5715 if (!m_fullScreenElement)
5718 if (!attached() || inPageCache())
5721 m_fullScreenElement->didBecomeFullscreenElement();
5723 m_fullScreenChangeDelayTimer.startOneShot(0);
5726 void Document::webkitWillExitFullScreenForElement(Element*)
5728 if (!m_fullScreenElement)
5731 if (!attached() || inPageCache())
5734 m_fullScreenElement->willStopBeingFullscreenElement();
5737 void Document::webkitDidExitFullScreenForElement(Element*)
5739 if (!m_fullScreenElement)
5742 if (!attached() || inPageCache())
5745 m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
5747 m_areKeysEnabledInFullScreen = false;
5748 #if ENABLE(TIZEN_FULLSCREEN_API)
5749 m_exitFullScreenByHwBackKey = false;
5752 if (m_fullScreenRenderer)
5753 m_fullScreenRenderer->unwrapRenderer();
5755 m_fullScreenElement = 0;
5756 scheduleForcedStyleRecalc();
5758 // When webkitCancelFullScreen is called, we call webkitExitFullScreen on the topDocument(). That
5759 // means that the events will be queued there. So if we have no events here, start the timer on
5760 // the exiting document.
5761 Document* exitingDocument = this;
5762 if (m_fullScreenChangeEventTargetQueue.isEmpty() && m_fullScreenErrorEventTargetQueue.isEmpty())
5763 exitingDocument = topDocument();
5764 exitingDocument->m_fullScreenChangeDelayTimer.startOneShot(0);
5767 void Document::setFullScreenRenderer(RenderFullScreen* renderer)
5769 if (renderer == m_fullScreenRenderer)
5772 if (renderer && m_savedPlaceholderRenderStyle)
5773 renderer->createPlaceholder(m_savedPlaceholderRenderStyle.release(), m_savedPlaceholderFrameRect);
5774 else if (renderer && m_fullScreenRenderer && m_fullScreenRenderer->placeholder()) {
5775 RenderBlock* placeholder = m_fullScreenRenderer->placeholder();
5776 renderer->createPlaceholder(RenderStyle::clone(placeholder->style()), placeholder->frameRect());
5779 if (m_fullScreenRenderer)
5780 m_fullScreenRenderer->destroy();
5781 ASSERT(!m_fullScreenRenderer);
5783 m_fullScreenRenderer = renderer;
5785 // This notification can come in after the page has been destroyed.
5787 page()->chrome()->client()->fullScreenRendererChanged(m_fullScreenRenderer);
5790 void Document::fullScreenRendererDestroyed()
5792 m_fullScreenRenderer = 0;
5795 page()->chrome()->client()->fullScreenRendererChanged(0);
5798 void Document::setFullScreenRendererSize(const IntSize& size)
5800 ASSERT(m_fullScreenRenderer);
5801 if (!m_fullScreenRenderer)
5804 if (m_fullScreenRenderer) {
5805 RefPtr<RenderStyle> newStyle = RenderStyle::clone(m_fullScreenRenderer->style());
5806 newStyle->setWidth(Length(size.width(), WebCore::Fixed));
5807 newStyle->setHeight(Length(size.height(), WebCore::Fixed));
5808 newStyle->setTop(Length(0, WebCore::Fixed));
5809 newStyle->setLeft(Length(0, WebCore::Fixed));
5810 m_fullScreenRenderer->setStyle(newStyle);
5815 void Document::setFullScreenRendererBackgroundColor(Color backgroundColor)
5817 if (!m_fullScreenRenderer)
5820 RefPtr<RenderStyle> newStyle = RenderStyle::clone(m_fullScreenRenderer->style());
5821 newStyle->setBackgroundColor(backgroundColor);
5822 m_fullScreenRenderer->setStyle(newStyle);
5825 void Document::fullScreenChangeDelayTimerFired(Timer<Document>*)
5827 Deque<RefPtr<Node> > changeQueue;
5828 m_fullScreenChangeEventTargetQueue.swap(changeQueue);
5830 while (!changeQueue.isEmpty()) {
5831 RefPtr<Node> node = changeQueue.takeFirst();
5833 node = documentElement();
5835 // If the element was removed from our tree, also message the documentElement. Since we may
5836 // have a document hierarchy, check that node isn't in another document.
5837 if (!contains(node.get()) && !node->inDocument())
5838 changeQueue.append(documentElement());
5840 node->dispatchEvent(Event::create(eventNames().webkitfullscreenchangeEvent, true, false));
5843 Deque<RefPtr<Node> > errorQueue;
5844 m_fullScreenErrorEventTargetQueue.swap(errorQueue);
5846 while (!errorQueue.isEmpty()) {
5847 RefPtr<Node> node = errorQueue.takeFirst();
5849 node = documentElement();
5851 // If the element was removed from our tree, also message the documentElement. Since we may
5852 // have a document hierarchy, check that node isn't in another document.
5853 if (!contains(node.get()) && !node->inDocument())
5854 errorQueue.append(documentElement());
5856 node->dispatchEvent(Event::create(eventNames().webkitfullscreenerrorEvent, true, false));
5860 void Document::fullScreenElementRemoved()
5862 m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
5863 webkitCancelFullScreen();
5866 void Document::removeFullScreenElementOfSubtree(Node* node, bool amongChildrenOnly)
5868 if (!m_fullScreenElement)
5871 bool elementInSubtree = false;
5872 if (amongChildrenOnly)
5873 elementInSubtree = m_fullScreenElement->isDescendantOf(node);
5875 elementInSubtree = (m_fullScreenElement == node) || m_fullScreenElement->isDescendantOf(node);
5877 if (elementInSubtree)
5878 fullScreenElementRemoved();
5881 bool Document::isAnimatingFullScreen() const
5883 return m_isAnimatingFullScreen;
5886 void Document::setAnimatingFullScreen(bool flag)
5888 if (m_isAnimatingFullScreen == flag)
5890 m_isAnimatingFullScreen = flag;
5892 if (m_fullScreenElement && m_fullScreenElement->isDescendantOf(this)) {
5893 m_fullScreenElement->setNeedsStyleRecalc();
5894 scheduleForcedStyleRecalc();
5898 void Document::clearFullscreenElementStack()
5900 m_fullScreenElementStack.clear();
5903 void Document::popFullscreenElementStack()
5905 if (m_fullScreenElementStack.isEmpty())
5908 m_fullScreenElementStack.removeFirst();
5911 void Document::pushFullscreenElementStack(Element* element)
5913 m_fullScreenElementStack.prepend(element);
5916 void Document::addDocumentToFullScreenChangeEventQueue(Document* doc)
5919 Node* target = doc->webkitFullscreenElement();
5921 target = doc->webkitCurrentFullScreenElement();
5924 m_fullScreenChangeEventTargetQueue.append(target);
5928 #if ENABLE(POINTER_LOCK)
5929 void Document::webkitExitPointerLock()
5932 page()->pointerLockController()->requestPointerUnlock();
5935 Element* Document::webkitPointerLockElement() const
5939 if (Element* element = page()->pointerLockController()->element()) {
5940 if (element->document() == this)
5947 void Document::decrementLoadEventDelayCount()
5949 ASSERT(m_loadEventDelayCount);
5950 --m_loadEventDelayCount;
5952 if (frame() && !m_loadEventDelayCount && !m_loadEventDelayTimer.isActive())
5953 m_loadEventDelayTimer.startOneShot(0);
5956 void Document::loadEventDelayTimerFired(Timer<Document>*)
5959 frame()->loader()->checkCompleted();
5962 #if ENABLE(REQUEST_ANIMATION_FRAME)
5963 int Document::webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback)
5965 if (!m_scriptedAnimationController) {
5966 #if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
5967 m_scriptedAnimationController = ScriptedAnimationController::create(this, page() ? page()->displayID() : 0);
5969 m_scriptedAnimationController = ScriptedAnimationController::create(this, 0);
5971 // It's possible that the Page may have suspended scripted animations before
5972 // we were created. We need to make sure that we don't start up the animation
5973 // controller on a background tab, for example.
5974 if (!page() || page()->scriptedAnimationsSuspended())
5975 m_scriptedAnimationController->suspend();
5978 return m_scriptedAnimationController->registerCallback(callback);
5981 void Document::webkitCancelAnimationFrame(int id)
5983 if (!m_scriptedAnimationController)
5985 m_scriptedAnimationController->cancelCallback(id);
5988 void Document::serviceScriptedAnimations(DOMTimeStamp time)
5990 if (!m_scriptedAnimationController)
5992 m_scriptedAnimationController->serviceScriptedAnimations(time);
5996 #if ENABLE(TOUCH_EVENTS)
5997 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, ExceptionCode&) const
5999 // FIXME: It's not clear from the documentation at
6000 // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html
6001 // 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
6002 // and implement them here. See https://bugs.webkit.org/show_bug.cgi?id=47819
6003 Frame* frame = window ? window->frame() : this->frame();
6004 return Touch::create(frame, target, identifier, screenX, screenY, pageX, pageY, radiusX, radiusY, rotationAngle, force);
6008 static void wheelEventHandlerCountChanged(Document* document)
6010 Page* page = document->page();
6014 ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator();
6015 if (!scrollingCoordinator)
6018 FrameView* frameView = document->view();
6022 scrollingCoordinator->frameViewWheelEventHandlerCountChanged(frameView);
6025 void Document::didAddWheelEventHandler()
6027 ++m_wheelEventHandlerCount;
6028 Frame* mainFrame = page() ? page()->mainFrame() : 0;
6030 mainFrame->notifyChromeClientWheelEventHandlerCountChanged();
6032 wheelEventHandlerCountChanged(this);
6035 void Document::didRemoveWheelEventHandler()
6037 ASSERT(m_wheelEventHandlerCount > 0);
6038 --m_wheelEventHandlerCount;
6039 Frame* mainFrame = page() ? page()->mainFrame() : 0;
6041 mainFrame->notifyChromeClientWheelEventHandlerCountChanged();
6043 wheelEventHandlerCountChanged(this);
6046 void Document::didAddTouchEventHandler()
6048 #if ENABLE(TOUCH_EVENTS)
6049 ++m_touchEventHandlerCount;
6050 if (m_touchEventHandlerCount > 1)
6052 if (Page* page = this->page())
6053 page->chrome()->client()->needTouchEvents(true);
6057 void Document::didRemoveTouchEventHandler()
6059 #if ENABLE(TOUCH_EVENTS)
6060 ASSERT(m_touchEventHandlerCount);
6061 --m_touchEventHandlerCount;
6062 if (m_touchEventHandlerCount)
6065 m_listenerTypes &= ~TOUCH_LISTENER;
6066 Page* page = this->page();
6069 for (const Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
6070 if (frame->document() && frame->document()->touchEventHandlerCount())
6073 page->chrome()->client()->needTouchEvents(false);
6077 HTMLIFrameElement* Document::seamlessParentIFrame() const
6079 if (!shouldDisplaySeamlesslyWithParent())
6082 HTMLFrameOwnerElement* ownerElement = this->ownerElement();
6083 ASSERT(ownerElement->hasTagName(iframeTag));
6084 return static_cast<HTMLIFrameElement*>(ownerElement);
6087 bool Document::shouldDisplaySeamlesslyWithParent() const
6089 #if ENABLE(IFRAME_SEAMLESS)
6090 HTMLFrameOwnerElement* ownerElement = this->ownerElement();
6093 return m_mayDisplaySeamlessWithParent && ownerElement->hasTagName(iframeTag) && ownerElement->fastHasAttribute(seamlessAttr);
6099 DocumentLoader* Document::loader() const
6104 DocumentLoader* loader = m_frame->loader()->documentLoader();
6108 if (m_frame->document() != this)
6114 #if ENABLE(MICRODATA)
6115 PassRefPtr<NodeList> Document::getItems(const String& typeNames)
6117 // Since documet.getItem() is allowed for microdata, typeNames will be null string.
6118 // In this case we need to create an unique string identifier to map such request in the cache.
6119 String localTypeNames = typeNames.isNull() ? MicroDataItemList::undefinedItemType() : typeNames;
6121 return ensureRareData()->ensureNodeLists()->addCacheWithName<MicroDataItemList>(this, DynamicNodeList::MicroDataItemListType, localTypeNames);
6125 IntSize Document::viewportSize() const
6129 return view()->visibleContentRect(/* includeScrollbars */ true).size();
6132 Node* eventTargetNodeForDocument(Document* doc)
6136 Node* node = doc->focusedNode();
6137 if (!node && doc->isPluginDocument()) {
6138 PluginDocument* pluginDocument = static_cast<PluginDocument*>(doc);
6139 node = pluginDocument->pluginNode();
6141 if (!node && doc->isHTMLDocument())
6144 node = doc->documentElement();
6148 void Document::adjustFloatQuadsForScrollAndAbsoluteZoomAndFrameScale(Vector<FloatQuad>& quads, RenderObject* renderer)
6153 float inverseFrameScale = 1;
6155 inverseFrameScale = 1 / frame()->frameScaleFactor();
6157 LayoutRect visibleContentRect = view()->visibleContentRect();
6158 for (size_t i = 0; i < quads.size(); ++i) {
6159 quads[i].move(-visibleContentRect.x(), -visibleContentRect.y());
6160 adjustFloatQuadForAbsoluteZoom(quads[i], renderer);
6161 if (inverseFrameScale != 1)
6162 quads[i].scale(inverseFrameScale, inverseFrameScale);
6166 void Document::adjustFloatRectForScrollAndAbsoluteZoomAndFrameScale(FloatRect& rect, RenderObject* renderer)
6171 float inverseFrameScale = 1;
6173 inverseFrameScale = 1 / frame()->frameScaleFactor();
6175 LayoutRect visibleContentRect = view()->visibleContentRect();
6176 rect.move(-visibleContentRect.x(), -visibleContentRect.y());
6177 adjustFloatRectForAbsoluteZoom(rect, renderer);
6178 if (inverseFrameScale != 1)
6179 rect.scale(inverseFrameScale);
6182 void Document::setContextFeatures(PassRefPtr<ContextFeatures> features)
6184 m_contextFeatures = features;
6187 void Document::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
6189 MemoryClassInfo<Document> info(memoryObjectInfo, this, MemoryInstrumentation::DOM);
6190 info.addInstrumentedMember(m_styleResolver);
6191 info.visitBaseClass<ContainerNode>(this);
6192 info.addVector(m_customFonts);
6193 info.addString(m_documentURI);
6194 info.addString(m_baseTarget);
6195 if (m_pageGroupUserSheets)
6196 info.addVector(*m_pageGroupUserSheets.get());
6198 info.addVector(*m_userSheets.get());
6199 info.addHashSet(m_nodeIterators);
6200 info.addHashSet(m_ranges);
6201 info.addListHashSet(m_styleSheetCandidateNodes);
6202 info.addString(m_preferredStylesheetSet);
6203 info.addString(m_selectedStylesheetSet);
6204 info.addString(m_title.string());
6205 info.addString(m_rawTitle.string());
6206 info.addString(m_xmlEncoding);
6207 info.addString(m_xmlVersion);
6208 info.addString(m_contentLanguage);
6209 info.addHashMap(m_documentNamedItemCollections);
6210 info.addHashMap(m_windowNamedItemCollections);
6211 #if ENABLE(DASHBOARD_SUPPORT)
6212 info.addVector(m_dashboardRegions);
6214 info.addHashMap(m_cssCanvasElements);
6215 info.addVector(m_iconURLs);
6216 info.addHashSet(m_documentSuspensionCallbackElements);
6217 info.addHashSet(m_mediaVolumeCallbackElements);
6218 info.addHashSet(m_privateBrowsingStateChangedElements);
6219 info.addHashMap(m_elementsByAccessKey);
6220 info.addHashSet(m_mediaCanStartListeners);
6221 info.addVector(m_pendingTasks);
6224 #if ENABLE(UNDO_MANAGER)
6225 PassRefPtr<UndoManager> Document::undoManager()
6228 m_undoManager = UndoManager::create(this);
6229 return m_undoManager;
6233 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
6234 void Document::incrementActiveMediaObjectCount()
6236 if (!m_activeMediaObjectCount)
6237 AudioSessionManagerGStreamerTizen::setVolumeSessionToMediaType();
6238 atomicIncrement(&m_activeMediaObjectCount);
6241 void Document::decrementActiveMediaObjectCount()
6243 atomicDecrement(&m_activeMediaObjectCount);
6244 if (!m_activeMediaObjectCount)
6245 AudioSessionManagerGStreamerTizen::clearVolumeSessionFromMediaType();
6248 } // namespace WebCore