tizen beta release
[profile/ivi/webkit-efl.git] / Source / WebCore / dom / Document.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2001 Dirk Mueller (mueller@kde.org)
5  *           (C) 2006 Alexey Proskuryakov (ap@webkit.org)
6  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2011 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 Google Inc. All rights reserved.
9  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Library General Public
13  * License as published by the Free Software Foundation; either
14  * version 2 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Library General Public License for more details.
20  *
21  * You should have received a copy of the GNU Library General Public License
22  * along with this library; see the file COPYING.LIB.  If not, write to
23  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24  * Boston, MA 02110-1301, USA.
25  */
26
27 #include "config.h"
28 #include "Document.h"
29
30 #include "AXObjectCache.h"
31 #include "AnimationController.h"
32 #include "Attr.h"
33 #include "Attribute.h"
34 #include "CDATASection.h"
35 #include "CSSPrimitiveValueCache.h"
36 #include "CSSStyleSelector.h"
37 #include "CSSStyleSheet.h"
38 #include "CSSValueKeywords.h"
39 #include "CachedCSSStyleSheet.h"
40 #include "CachedResourceLoader.h"
41 #include "Chrome.h"
42 #include "ChromeClient.h"
43 #include "Comment.h"
44 #include "Console.h"
45 #include "ContentSecurityPolicy.h"
46 #include "CookieJar.h"
47 #include "DOMImplementation.h"
48 #include "DOMWindow.h"
49 #include "DateComponents.h"
50 #include "DeviceMotionController.h"
51 #include "DeviceMotionEvent.h"
52 #include "DeviceOrientationController.h"
53 #include "DeviceOrientationEvent.h"
54 #include "DocumentEventQueue.h"
55 #include "DocumentFragment.h"
56 #include "DocumentLoader.h"
57 #include "DocumentMarkerController.h"
58 #include "DocumentType.h"
59 #include "EditingText.h"
60 #include "Editor.h"
61 #include "Element.h"
62 #include "EntityReference.h"
63 #include "Event.h"
64 #include "EventFactory.h"
65 #include "EventHandler.h"
66 #include "EventListener.h"
67 #include "EventNames.h"
68 #include "ExceptionCode.h"
69 #include "FocusController.h"
70 #include "FormAssociatedElement.h"
71 #include "Frame.h"
72 #include "FrameLoader.h"
73 #include "FrameLoaderClient.h"
74 #include "FrameSelection.h"
75 #include "FrameTree.h"
76 #include "FrameView.h"
77 #include "GeolocationController.h"
78 #include "HashChangeEvent.h"
79 #include "HTMLAllCollection.h"
80 #include "HTMLAnchorElement.h"
81 #include "HTMLBodyElement.h"
82 #include "HTMLCanvasElement.h"
83 #include "HTMLCollection.h"
84 #include "HTMLDocument.h"
85 #include "HTMLElementFactory.h"
86 #include "HTMLFrameOwnerElement.h"
87 #include "HTMLHeadElement.h"
88 #include "HTMLIFrameElement.h"
89 #include "HTMLInputElement.h"
90 #include "HTMLLinkElement.h"
91 #include "HTMLMapElement.h"
92 #include "HTMLNameCollection.h"
93 #include "HTMLNames.h"
94 #include "HTMLParserIdioms.h"
95 #include "HTMLStyleElement.h"
96 #include "HTMLTitleElement.h"
97 #include "HTTPParsers.h"
98 #include "HitTestRequest.h"
99 #include "HitTestResult.h"
100 #include "ImageLoader.h"
101 #include "InspectorInstrumentation.h"
102 #include "Logging.h"
103 #include "MediaQueryList.h"
104 #include "MediaQueryMatcher.h"
105 #include "MouseEventWithHitTestResults.h"
106 #include "NameNodeList.h"
107 #include "NestingLevelIncrementer.h"
108 #include "NewXMLDocumentParser.h"
109 #include "NodeFilter.h"
110 #include "NodeIterator.h"
111 #include "NodeWithIndex.h"
112 #include "Page.h"
113 #include "PageGroup.h"
114 #include "PageTransitionEvent.h"
115 #include "PlatformKeyboardEvent.h"
116 #include "PopStateEvent.h"
117 #include "ProcessingInstruction.h"
118 #include "RegisteredEventListener.h"
119 #include "RenderArena.h"
120 #include "RenderLayer.h"
121 #include "RenderLayerBacking.h"
122 #include "RenderTextControl.h"
123 #include "RenderView.h"
124 #include "RenderWidget.h"
125 #include "SchemeRegistry.h"
126 #include "ScopedEventQueue.h"
127 #include "ScriptCallStack.h"
128 #include "ScriptController.h"
129 #include "ScriptElement.h"
130 #include "ScriptEventListener.h"
131 #include "ScriptRunner.h"
132 #include "SecurityOrigin.h"
133 #include "SecurityPolicy.h"
134 #include "SegmentedString.h"
135 #include "Settings.h"
136 #include "ShadowRoot.h"
137 #include "StaticHashSetNodeList.h"
138 #include "StyleSheetList.h"
139 #include "TextResourceDecoder.h"
140 #include "Timer.h"
141 #include "TransformSource.h"
142 #include "TreeWalker.h"
143 #include "UserContentURLPattern.h"
144 #include "XMLDocumentParser.h"
145 #include "XMLHttpRequest.h"
146 #include "XMLNSNames.h"
147 #include "XMLNames.h"
148 #include "XPathEvaluator.h"
149 #include "XPathExpression.h"
150 #include "XPathNSResolver.h"
151 #include "XPathResult.h"
152 #include "htmlediting.h"
153 #include <wtf/CurrentTime.h>
154 #include <wtf/HashFunctions.h>
155 #include <wtf/MainThread.h>
156 #include <wtf/PassRefPtr.h>
157 #include <wtf/StdLibExtras.h>
158 #include <wtf/text/StringBuffer.h>
159
160 #if PLATFORM(CHROMIUM)
161 #include "PlatformSupport.h"
162 #endif
163
164 #if ENABLE(SHARED_WORKERS)
165 #include "SharedWorkerRepository.h"
166 #endif
167
168 #if ENABLE(XSLT)
169 #include "XSLTProcessor.h"
170 #endif
171
172 #if ENABLE(SVG)
173 #include "SVGDocumentExtensions.h"
174 #include "SVGElementFactory.h"
175 #include "SVGNames.h"
176 #include "SVGStyleElement.h"
177 #endif
178
179 #if ENABLE(TOUCH_EVENTS)
180 #include "TouchList.h"
181 #endif
182
183 #if ENABLE(MATHML)
184 #include "MathMLElement.h"
185 #include "MathMLElementFactory.h"
186 #include "MathMLNames.h"
187 #endif
188
189 #if ENABLE(FULLSCREEN_API)
190 #include "RenderFullScreen.h"
191 #endif
192
193 #if ENABLE(REQUEST_ANIMATION_FRAME)
194 #include "RequestAnimationFrameCallback.h"
195 #include "ScriptedAnimationController.h"
196 #endif
197
198 #if ENABLE(MICRODATA)
199 #include "MicroDataItemList.h"
200 #include "NodeRareData.h"
201 #endif
202
203 using namespace std;
204 using namespace WTF;
205 using namespace Unicode;
206
207 namespace WebCore {
208
209 using namespace HTMLNames;
210
211 // #define INSTRUMENT_LAYOUT_SCHEDULING 1
212
213 static const unsigned cMaxWriteRecursionDepth = 21;
214
215 // This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
216 // FIXME: For faster machines this value can really be lowered to 200.  250 is adequate, but a little high
217 // for dual G5s. :)
218 static const int cLayoutScheduleThreshold = 250;
219
220 // DOM Level 2 says (letters added):
221 //
222 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
223 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
224 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
225 // 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.
226 // 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.
227 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
228 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
229 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
230 // i) Characters ':' and '_' are allowed as name-start characters.
231 // j) Characters '-' and '.' are allowed as name characters.
232 //
233 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
234
235 static inline bool isValidNameStart(UChar32 c)
236 {
237     // rule (e) above
238     if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
239         return true;
240
241     // rule (i) above
242     if (c == ':' || c == '_')
243         return true;
244
245     // rules (a) and (f) above
246     const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
247     if (!(Unicode::category(c) & nameStartMask))
248         return false;
249
250     // rule (c) above
251     if (c >= 0xF900 && c < 0xFFFE)
252         return false;
253
254     // rule (d) above
255     DecompositionType decompType = decompositionType(c);
256     if (decompType == DecompositionFont || decompType == DecompositionCompat)
257         return false;
258
259     return true;
260 }
261
262 static inline bool isValidNamePart(UChar32 c)
263 {
264     // rules (a), (e), and (i) above
265     if (isValidNameStart(c))
266         return true;
267
268     // rules (g) and (h) above
269     if (c == 0x00B7 || c == 0x0387)
270         return true;
271
272     // rule (j) above
273     if (c == '-' || c == '.')
274         return true;
275
276     // rules (b) and (f) above
277     const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
278     if (!(Unicode::category(c) & otherNamePartMask))
279         return false;
280
281     // rule (c) above
282     if (c >= 0xF900 && c < 0xFFFE)
283         return false;
284
285     // rule (d) above
286     DecompositionType decompType = decompositionType(c);
287     if (decompType == DecompositionFont || decompType == DecompositionCompat)
288         return false;
289
290     return true;
291 }
292
293 static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
294 {
295     // http://www.whatwg.org/specs/web-apps/current-work/#origin-0
296     //
297     // If a Document has the address "about:blank"
298     //     The origin of the Document is the origin it was assigned when its browsing context was created.
299     //
300     // Note: We generalize this to all "about" URLs and invalid URLs because we
301     // treat all of these URLs as about:blank.
302     //
303     return !url.isValid() || url.protocolIs("about");
304 }
305
306 static Widget* widgetForNode(Node* focusedNode)
307 {
308     if (!focusedNode)
309         return 0;
310     RenderObject* renderer = focusedNode->renderer();
311     if (!renderer || !renderer->isWidget())
312         return 0;
313     return toRenderWidget(renderer)->widget();
314 }
315
316 static bool acceptsEditingFocus(Node* node)
317 {
318     ASSERT(node);
319     ASSERT(node->rendererIsEditable());
320
321     Node* root = node->rootEditableElement();
322     Frame* frame = node->document()->frame();
323     if (!frame || !root)
324         return false;
325
326     return frame->editor()->shouldBeginEditing(rangeOfContents(root).get());
327 }
328
329 static bool disableRangeMutation(Page* page)
330 {
331     // This check is made on super-hot code paths, so we only want this on Leopard.
332 #ifdef TARGETING_LEOPARD
333     // Disable Range mutation on document modifications in Leopard Mail.
334     // See <rdar://problem/5865171>
335     return page && page->settings()->needsLeopardMailQuirks();
336 #else
337     UNUSED_PARAM(page);
338     return false;
339 #endif
340 }
341
342 static HashSet<Document*>* documentsThatNeedStyleRecalc = 0;
343
344 class DocumentWeakReference : public ThreadSafeRefCounted<DocumentWeakReference> {
345 public:
346     static PassRefPtr<DocumentWeakReference> create(Document* document)
347     {
348         return adoptRef(new DocumentWeakReference(document));
349     }
350
351     Document* document()
352     {
353         ASSERT(isMainThread());
354         return m_document;
355     }
356
357     void clear()
358     {
359         ASSERT(isMainThread());
360         m_document = 0;
361     }
362
363 private:
364     DocumentWeakReference(Document* document)
365         : m_document(document)
366     {
367         ASSERT(isMainThread());
368     }
369
370     Document* m_document;
371 };
372
373 uint64_t Document::s_globalTreeVersion = 0;
374
375 Document::Document(Frame* frame, const KURL& url, bool isXHTML, bool isHTML)
376     : TreeScope(0)
377     , m_guardRefCount(0)
378     , m_compatibilityMode(NoQuirksMode)
379     , m_compatibilityModeLocked(false)
380     , m_domTreeVersion(++s_globalTreeVersion)
381 #if ENABLE(MUTATION_OBSERVERS)
382     , m_subtreeMutationObserverTypes(0)
383 #endif
384     , m_styleSheets(StyleSheetList::create(this))
385     , m_readyState(Complete)
386     , m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
387     , m_pendingStyleRecalcShouldForce(false)
388     , m_frameElementsShouldIgnoreScrolling(false)
389     , m_containsValidityStyleRules(false)
390     , m_updateFocusAppearanceRestoresSelection(false)
391     , m_ignoreDestructiveWriteCount(0)
392     , m_titleSetExplicitly(false)
393     , m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
394     , m_loadEventFinished(false)
395     , m_startTime(currentTime())
396     , m_overMinimumLayoutThreshold(false)
397     , m_scriptRunner(ScriptRunner::create(this))
398     , m_xmlVersion("1.0")
399     , m_xmlStandalone(false)
400     , m_savedRenderer(0)
401     , m_designMode(inherit)
402 #if ENABLE(DASHBOARD_SUPPORT)
403     , m_hasDashboardRegions(false)
404     , m_dashboardRegionsDirty(false)
405 #endif
406     , m_createRenderers(true)
407     , m_inPageCache(false)
408     , m_accessKeyMapValid(false)
409     , m_useSecureKeyboardEntryWhenActive(false)
410     , m_isXHTML(isXHTML)
411     , m_isHTML(isHTML)
412     , m_isViewSource(false)
413     , m_sawElementsInKnownNamespaces(false)
414     , m_usingGeolocation(false)
415     , m_eventQueue(DocumentEventQueue::create(this))
416     , m_weakReference(DocumentWeakReference::create(this))
417     , m_idAttributeName(idAttr)
418 #if ENABLE(FULLSCREEN_API)
419     , m_areKeysEnabledInFullScreen(0)
420     , m_fullScreenRenderer(0)
421     , m_fullScreenChangeDelayTimer(this, &Document::fullScreenChangeDelayTimerFired)
422     , m_isAnimatingFullScreen(false)
423 #endif
424     , m_loadEventDelayCount(0)
425     , m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
426     , m_referrerPolicy(SecurityPolicy::ReferrerPolicyDefault)
427     , m_directionSetOnDocumentElement(false)
428     , m_writingModeSetOnDocumentElement(false)
429     , m_writeRecursionIsTooDeep(false)
430     , m_writeRecursionDepth(0)
431     , m_wheelEventHandlerCount(0)
432 {
433     m_document = this;
434
435     m_pageGroupUserSheetCacheValid = false;
436
437     m_printing = false;
438     m_paginatedForScreen = false;
439
440     m_ignoreAutofocus = false;
441
442     m_frame = frame;
443
444     // We depend on the url getting immediately set in subframes, but we
445     // also depend on the url NOT getting immediately set in opened windows.
446     // See fast/dom/early-frame-url.html
447     // and fast/dom/location-new-window-no-crash.html, respectively.
448     // FIXME: Can/should we unify this behavior?
449     if ((frame && frame->ownerElement()) || !url.isEmpty())
450         setURL(url);
451
452     m_axObjectCache = 0;
453
454     m_markers = adoptPtr(new DocumentMarkerController);
455
456     m_cachedResourceLoader = adoptPtr(new CachedResourceLoader(this));
457
458     m_visuallyOrdered = false;
459     m_bParsing = false;
460     m_wellFormed = false;
461
462     m_textColor = Color::black;
463     m_listenerTypes = 0;
464     setInDocument();
465     m_inStyleRecalc = false;
466     m_closeAfterStyleRecalc = false;
467
468     m_usesSiblingRules = false;
469     m_usesSiblingRulesOverride = false;
470     m_usesFirstLineRules = false;
471     m_usesFirstLetterRules = false;
472     m_usesBeforeAfterRules = false;
473     m_usesBeforeAfterRulesOverride = false;
474     m_usesRemUnits = false;
475     m_usesLinkRules = false;
476
477     m_gotoAnchorNeededAfterStylesheetsLoad = false;
478
479     m_didCalculateStyleSelector = false;
480     m_hasDirtyStyleSelector = false;
481     m_pendingStylesheets = 0;
482     m_ignorePendingStylesheets = false;
483     m_hasNodesWithPlaceholderStyle = false;
484     m_pendingSheetLayout = NoLayoutWithPendingSheets;
485
486     m_cssTarget = 0;
487
488     resetLinkColor();
489     resetVisitedLinkColor();
490     resetActiveLinkColor();
491
492     m_processingLoadEvent = false;
493     
494     initSecurityContext();
495     initDNSPrefetch();
496
497     static int docID = 0;
498     m_docID = docID++;
499 }
500
501 #if PLATFORM(CHROMIUM)
502 static void histogramMutationEventUsage(const unsigned short& listenerTypes)
503 {
504     PlatformSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMSubtreeModified", static_cast<bool>(listenerTypes & Document::DOMSUBTREEMODIFIED_LISTENER), 2);
505     PlatformSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInserted", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTED_LISTENER), 2);
506     PlatformSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemoved", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVED_LISTENER), 2);
507     PlatformSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemovedFromDocument", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER), 2);
508     PlatformSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInsertedIntoDocument", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER), 2);
509     PlatformSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMCharacterDataModified", static_cast<bool>(listenerTypes & Document::DOMCHARACTERDATAMODIFIED_LISTENER), 2);
510 }
511 #endif
512
513 Document::~Document()
514 {
515     ASSERT(!renderer());
516     ASSERT(!m_inPageCache);
517     ASSERT(!m_savedRenderer);
518     ASSERT(m_ranges.isEmpty());
519     ASSERT(!m_styleRecalcTimer.isActive());
520     ASSERT(!m_parentTreeScope);
521     ASSERT(!m_guardRefCount);
522
523     m_scriptRunner.clear();
524
525 #if PLATFORM(CHROMIUM)
526     histogramMutationEventUsage(m_listenerTypes);
527 #endif
528
529     removeAllEventListeners();
530
531     // Currently we believe that Document can never outlive the parser.
532     // Although the Document may be replaced synchronously, DocumentParsers
533     // generally keep at least one reference to an Element which would in turn
534     // has a reference to the Document.  If you hit this ASSERT, then that
535     // assumption is wrong.  DocumentParser::detach() should ensure that even
536     // if the DocumentParser outlives the Document it won't cause badness.
537     ASSERT(!m_parser || m_parser->refCount() == 1);
538     detachParser();
539     m_document = 0;
540     m_cachedResourceLoader.clear();
541
542     m_renderArena.clear();
543
544     clearAXObjectCache();
545
546     m_decoder = 0;
547
548     for (size_t i = 0; i < m_nameCollectionInfo.size(); ++i)
549         deleteAllValues(m_nameCollectionInfo[i]);
550
551     if (m_styleSheets)
552         m_styleSheets->documentDestroyed();
553
554     if (m_elemSheet)
555         m_elemSheet->clearOwnerNode();
556     if (m_mappedElementSheet)
557         m_mappedElementSheet->clearOwnerNode();
558     if (m_pageUserSheet)
559         m_pageUserSheet->clearOwnerNode();
560     if (m_pageGroupUserSheets) {
561         for (size_t i = 0; i < m_pageGroupUserSheets->size(); ++i)
562             (*m_pageGroupUserSheets)[i]->clearOwnerNode();
563     }
564     if (m_userSheets) {
565         for (size_t i = 0; i < m_userSheets->size(); ++i)
566             (*m_userSheets)[i]->clearOwnerNode();
567     }
568
569     deleteCustomFonts();
570
571     m_weakReference->clear();
572
573     if (m_mediaQueryMatcher)
574         m_mediaQueryMatcher->documentDestroyed();
575 }
576
577 void Document::removedLastRef()
578 {
579     ASSERT(!m_deletionHasBegun);
580     if (m_guardRefCount) {
581         // If removing a child removes the last self-only ref, we don't
582         // want the scope to be destructed until after
583         // removeAllChildren returns, so we guard ourselves with an
584         // extra self-only ref.
585         guardRef();
586
587         // We must make sure not to be retaining any of our children through
588         // these extra pointers or we will create a reference cycle.
589         m_docType = 0;
590         m_focusedNode = 0;
591         m_hoverNode = 0;
592         m_activeNode = 0;
593         m_titleElement = 0;
594         m_documentElement = 0;
595 #if ENABLE(FULLSCREEN_API)
596         m_fullScreenElement = 0;
597 #endif
598
599         // removeAllChildren() doesn't always unregister IDs,
600         // so tear down scope information upfront to avoid having stale references in the map.
601         destroyTreeScopeData();
602         removeAllChildren();
603
604         m_markers->detach();
605
606         detachParser();
607
608         m_cssCanvasElements.clear();
609
610 #if ENABLE(REQUEST_ANIMATION_FRAME)
611         // FIXME: consider using ActiveDOMObject.
612         m_scriptedAnimationController = nullptr;
613 #endif
614
615 #ifndef NDEBUG
616         m_inRemovedLastRefFunction = false;
617 #endif
618
619         guardDeref();
620     } else {
621 #ifndef NDEBUG
622         m_deletionHasBegun = true;
623 #endif
624         delete this;
625     }
626 }
627
628 Element* Document::getElementById(const AtomicString& id) const
629 {
630     return TreeScope::getElementById(id);
631 }
632
633 Element* Document::getElementByAccessKey(const String& key)
634 {
635     if (key.isEmpty())
636         return 0;
637     if (!m_accessKeyMapValid) {
638         buildAccessKeyMap(this);
639         m_accessKeyMapValid = true;
640     }
641     return m_elementsByAccessKey.get(key.impl());
642 }
643
644 void Document::buildAccessKeyMap(TreeScope* root)
645 {
646      for (Node* n = root; n; n = n->traverseNextNode(root)) {
647         if (!n->isElementNode())
648             continue;
649         Element* element = static_cast<Element*>(n);
650         const AtomicString& accessKey = element->getAttribute(accesskeyAttr);
651         if (!accessKey.isEmpty())
652             m_elementsByAccessKey.set(accessKey.impl(), element);
653         buildAccessKeyMap(element->shadowRoot());
654     }
655 }
656
657 void Document::invalidateAccessKeyMap()
658 {
659     m_accessKeyMapValid = false;
660     m_elementsByAccessKey.clear();
661 }
662
663 MediaQueryMatcher* Document::mediaQueryMatcher()
664 {
665     if (!m_mediaQueryMatcher)
666         m_mediaQueryMatcher = MediaQueryMatcher::create(this);
667     return m_mediaQueryMatcher.get();
668 }
669
670 void Document::setCompatibilityMode(CompatibilityMode mode)
671 {
672     if (m_compatibilityModeLocked || mode == m_compatibilityMode)
673         return;
674     ASSERT(!m_styleSheets->length());
675     bool wasInQuirksMode = inQuirksMode();
676     m_compatibilityMode = mode;
677     if (inQuirksMode() != wasInQuirksMode) {
678         // All user stylesheets have to reparse using the different mode.
679         clearPageUserSheet();
680         clearPageGroupUserSheets();
681     }
682 }
683
684 String Document::compatMode() const
685 {
686     return inQuirksMode() ? "BackCompat" : "CSS1Compat";
687 }
688
689 void Document::resetLinkColor()
690 {
691     m_linkColor = Color(0, 0, 238);
692 }
693
694 void Document::resetVisitedLinkColor()
695 {
696     m_visitedLinkColor = Color(85, 26, 139);    
697 }
698
699 void Document::resetActiveLinkColor()
700 {
701     m_activeLinkColor.setNamedColor("red");
702 }
703
704 void Document::setDocType(PassRefPtr<DocumentType> docType)
705 {
706     // This should never be called more than once.
707     ASSERT(!m_docType || !docType);
708     m_docType = docType;
709     if (m_docType)
710         m_docType->setTreeScopeRecursively(this);
711 }
712
713 DOMImplementation* Document::implementation()
714 {
715     if (!m_implementation)
716         m_implementation = DOMImplementation::create(this);
717     return m_implementation.get();
718 }
719
720 void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
721 {
722     TreeScope::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
723     
724     // Invalidate the document element we have cached in case it was replaced.
725     m_documentElement = 0;
726 }
727
728 void Document::cacheDocumentElement() const
729 {
730     ASSERT(!m_documentElement);
731     m_documentElement = firstElementChild(this);
732 }
733
734 PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
735 {
736     if (!isValidName(name)) {
737         ec = INVALID_CHARACTER_ERR;
738         return 0;
739     }
740
741     if (m_isXHTML)
742         return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
743
744     return createElement(QualifiedName(nullAtom, name, nullAtom), false);
745 }
746
747 PassRefPtr<DocumentFragment> Document::createDocumentFragment()
748 {
749     return DocumentFragment::create(document());
750 }
751
752 PassRefPtr<Text> Document::createTextNode(const String& data)
753 {
754     return Text::create(this, data);
755 }
756
757 PassRefPtr<Comment> Document::createComment(const String& data)
758 {
759     return Comment::create(this, data);
760 }
761
762 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
763 {
764     if (isHTMLDocument()) {
765         ec = NOT_SUPPORTED_ERR;
766         return 0;
767     }
768     return CDATASection::create(this, data);
769 }
770
771 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
772 {
773     if (!isValidName(target)) {
774         ec = INVALID_CHARACTER_ERR;
775         return 0;
776     }
777     if (isHTMLDocument()) {
778         ec = NOT_SUPPORTED_ERR;
779         return 0;
780     }
781     return ProcessingInstruction::create(this, target, data);
782 }
783
784 PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
785 {
786     if (!isValidName(name)) {
787         ec = INVALID_CHARACTER_ERR;
788         return 0;
789     }
790     if (isHTMLDocument()) {
791         ec = NOT_SUPPORTED_ERR;
792         return 0;
793     }
794     return EntityReference::create(this, name);
795 }
796
797 PassRefPtr<EditingText> Document::createEditingTextNode(const String& text)
798 {
799     return EditingText::create(this, text);
800 }
801
802 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
803 {
804     return CSSMutableStyleDeclaration::create();
805 }
806
807 PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
808 {
809     ec = 0;
810     
811     if (!importedNode
812 #if ENABLE(SVG) && ENABLE(DASHBOARD_SUPPORT)
813         || (importedNode->isSVGElement() && page() && page()->settings()->usesDashboardBackwardCompatibilityMode())
814 #endif
815         ) {
816         ec = NOT_SUPPORTED_ERR;
817         return 0;
818     }
819
820     switch (importedNode->nodeType()) {
821     case TEXT_NODE:
822         return createTextNode(importedNode->nodeValue());
823     case CDATA_SECTION_NODE:
824         return createCDATASection(importedNode->nodeValue(), ec);
825     case ENTITY_REFERENCE_NODE:
826         return createEntityReference(importedNode->nodeName(), ec);
827     case PROCESSING_INSTRUCTION_NODE:
828         return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
829     case COMMENT_NODE:
830         return createComment(importedNode->nodeValue());
831     case ELEMENT_NODE: {
832         Element* oldElement = static_cast<Element*>(importedNode);
833         RefPtr<Element> newElement = createElementNS(oldElement->namespaceURI(), oldElement->tagQName().toString(), ec);
834                     
835         if (ec)
836             return 0;
837
838         NamedNodeMap* attrs = oldElement->attributes(true);
839         if (attrs) {
840             unsigned length = attrs->length();
841             for (unsigned i = 0; i < length; i++) {
842                 Attribute* attr = attrs->attributeItem(i);
843                 newElement->setAttribute(attr->name(), attr->value().impl(), ec);
844                 if (ec)
845                     return 0;
846             }
847         }
848
849         newElement->copyNonAttributeProperties(oldElement);
850
851         if (deep) {
852             for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
853                 RefPtr<Node> newChild = importNode(oldChild, true, ec);
854                 if (ec)
855                     return 0;
856                 newElement->appendChild(newChild.release(), ec);
857                 if (ec)
858                     return 0;
859             }
860         }
861
862         return newElement.release();
863     }
864     case ATTRIBUTE_NODE:
865         return Attr::create(0, this, static_cast<Attr*>(importedNode)->attr()->clone());
866     case DOCUMENT_FRAGMENT_NODE: {
867         DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
868         RefPtr<DocumentFragment> newFragment = createDocumentFragment();
869         if (deep) {
870             for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
871                 RefPtr<Node> newChild = importNode(oldChild, true, ec);
872                 if (ec)
873                     return 0;
874                 newFragment->appendChild(newChild.release(), ec);
875                 if (ec)
876                     return 0;
877             }
878         }
879         
880         return newFragment.release();
881     }
882     case ENTITY_NODE:
883     case NOTATION_NODE:
884         // 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.
885         // Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
886     case DOCUMENT_NODE:
887     case DOCUMENT_TYPE_NODE:
888     case XPATH_NAMESPACE_NODE:
889     case SHADOW_ROOT_NODE:
890         // ShadowRoot nodes should not be explicitly importable.
891         // Either they are imported along with their host node, or created implicitly.
892         break;
893     }
894     ec = NOT_SUPPORTED_ERR;
895     return 0;
896 }
897
898
899 PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
900 {
901     if (!source) {
902         ec = NOT_SUPPORTED_ERR;
903         return 0;
904     }
905
906     if (source->isReadOnlyNode()) {
907         ec = NO_MODIFICATION_ALLOWED_ERR;
908         return 0;
909     }
910
911     EventQueueScope scope;
912
913     switch (source->nodeType()) {
914     case ENTITY_NODE:
915     case NOTATION_NODE:
916     case DOCUMENT_NODE:
917     case DOCUMENT_TYPE_NODE:
918     case XPATH_NAMESPACE_NODE:
919         ec = NOT_SUPPORTED_ERR;
920         return 0;            
921     case ATTRIBUTE_NODE: {                   
922         Attr* attr = static_cast<Attr*>(source.get());
923         if (attr->ownerElement())
924             attr->ownerElement()->removeAttributeNode(attr, ec);
925         attr->setSpecified(true);
926         break;
927     }       
928     default:
929         if (source->hasTagName(iframeTag)) {
930             HTMLIFrameElement* iframe = static_cast<HTMLIFrameElement*>(source.get());
931             if (frame() && frame()->tree()->isDescendantOf(iframe->contentFrame())) {
932                 ec = HIERARCHY_REQUEST_ERR;
933                 return 0;
934             }
935             iframe->setRemainsAliveOnRemovalFromTree(attached() && source->attached() && iframe->canRemainAliveOnRemovalFromTree());
936         }
937
938         if (source->parentNode())
939             source->parentNode()->removeChild(source.get(), ec);
940     }
941
942     source->setTreeScopeRecursively(this);
943
944     return source;
945 }
946
947 bool Document::hasPrefixNamespaceMismatch(const QualifiedName& qName)
948 {
949     // These checks are from DOM Core Level 2, createElementNS
950     // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
951     if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
952         return true;
953     if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
954         return true;
955
956     // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
957     // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
958     // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
959     if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
960         return true;
961
962     return false;
963 }
964
965 // FIXME: This should really be in a possible ElementFactory class
966 PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
967 {
968     RefPtr<Element> e;
969
970     // FIXME: Use registered namespaces and look up in a hash to find the right factory.
971     if (qName.namespaceURI() == xhtmlNamespaceURI)
972         e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
973 #if ENABLE(SVG)
974     else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
975         e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
976 #endif
977 #if ENABLE(MATHML)
978     else if (qName.namespaceURI() == MathMLNames::mathmlNamespaceURI)
979         e = MathMLElementFactory::createMathMLElement(qName, this, createdByParser);
980 #endif
981
982     if (e)
983         m_sawElementsInKnownNamespaces = true;
984     else
985         e = Element::create(qName, document());
986
987     // <image> uses imgTag so we need a special rule.
988     ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
989
990     return e.release();
991 }
992
993 PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
994 {
995     String prefix, localName;
996     if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
997         return 0;
998
999     QualifiedName qName(prefix, localName, namespaceURI);
1000     if (hasPrefixNamespaceMismatch(qName)) {
1001         ec = NAMESPACE_ERR;
1002         return 0;
1003     }
1004
1005     return createElement(qName, false);
1006 }
1007
1008 String Document::readyState() const
1009 {
1010     DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
1011     DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
1012     DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
1013
1014     switch (m_readyState) {
1015     case Loading:
1016         return loading;
1017     case Interactive:
1018         return interactive;
1019     case Complete:
1020         return complete;
1021     }
1022
1023     ASSERT_NOT_REACHED();
1024     return String();
1025 }
1026
1027 void Document::setReadyState(ReadyState readyState)
1028 {
1029     if (readyState == m_readyState)
1030         return;
1031
1032     switch (readyState) {
1033     case Loading:
1034         if (!m_documentTiming.domLoading)
1035             m_documentTiming.domLoading = currentTime();
1036         break;
1037     case Interactive:
1038         if (!m_documentTiming.domInteractive)
1039             m_documentTiming.domInteractive = currentTime();
1040         break;
1041     case Complete:
1042         if (!m_documentTiming.domComplete)
1043             m_documentTiming.domComplete = currentTime();
1044         break;
1045     }
1046
1047     m_readyState = readyState;
1048     dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1049 }
1050
1051 String Document::encoding() const
1052 {
1053     if (TextResourceDecoder* d = decoder())
1054         return d->encoding().domName();
1055     return String();
1056 }
1057
1058 String Document::defaultCharset() const
1059 {
1060     if (Settings* settings = this->settings())
1061         return settings->defaultTextEncodingName();
1062     return String();
1063 }
1064
1065 void Document::setCharset(const String& charset)
1066 {
1067     if (!decoder())
1068         return;
1069     decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1070 }
1071
1072 void Document::setXMLVersion(const String& version, ExceptionCode& ec)
1073 {
1074     if (!implementation()->hasFeature("XML", String())) {
1075         ec = NOT_SUPPORTED_ERR;
1076         return;
1077     }
1078
1079     if (!XMLDocumentParser::supportsXMLVersion(version)) {
1080         ec = NOT_SUPPORTED_ERR;
1081         return;
1082     }
1083
1084     m_xmlVersion = version;
1085 }
1086
1087 void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
1088 {
1089     if (!implementation()->hasFeature("XML", String())) {
1090         ec = NOT_SUPPORTED_ERR;
1091         return;
1092     }
1093
1094     m_xmlStandalone = standalone;
1095 }
1096
1097 void Document::setDocumentURI(const String& uri)
1098 {
1099     m_documentURI = uri;
1100     updateBaseURL();
1101 }
1102
1103 KURL Document::baseURI() const
1104 {
1105     return m_baseURL;
1106 }
1107
1108 void Document::setContent(const String& content)
1109 {
1110     open();
1111     m_parser->append(content);
1112     close();
1113 }
1114
1115 String Document::suggestedMIMEType() const
1116 {
1117     if (m_document->isXHTMLDocument())
1118         return "application/xhtml+xml";
1119     if (m_document->isSVGDocument())
1120         return "image/svg+xml";
1121     if (m_document->xmlStandalone())
1122         return "text/xml";
1123     if (m_document->isHTMLDocument())
1124         return "text/html";
1125
1126     if (DocumentLoader* documentLoader = loader())
1127         return documentLoader->responseMIMEType();
1128     return String();
1129 }
1130
1131 // FIXME: We need to discuss the DOM API here at some point. Ideas:
1132 // * making it receive a rect as parameter, i.e. nodesFromRect(x, y, w, h);
1133 // * making it receive the expading size of each direction separately,
1134 //   i.e. nodesFromRect(x, y, topSize, rightSize, bottomSize, leftSize);
1135 PassRefPtr<NodeList> Document::nodesFromRect(int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping) const
1136 {
1137     // FIXME: Share code between this, elementFromPoint and caretRangeFromPoint.
1138     if (!renderer())
1139         return 0;
1140     Frame* frame = this->frame();
1141     if (!frame)
1142         return 0;
1143     FrameView* frameView = frame->view();
1144     if (!frameView)
1145         return 0;
1146
1147     float zoomFactor = frame->pageZoomFactor();
1148     LayoutPoint point = roundedLayoutPoint(FloatPoint(centerX * zoomFactor + view()->scrollX(), centerY * zoomFactor + view()->scrollY()));
1149
1150     int type = HitTestRequest::ReadOnly | HitTestRequest::Active;
1151
1152     // When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
1153     if (ignoreClipping)
1154         type |= HitTestRequest::IgnoreClipping;
1155     else if (!frameView->visibleContentRect().intersects(HitTestResult::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
1156         return 0;
1157
1158     HitTestRequest request(type);
1159
1160     // Passing a zero padding will trigger a rect hit test, however for the purposes of nodesFromRect,
1161     // we special handle this case in order to return a valid NodeList.
1162     if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) {
1163         HitTestResult result(point);
1164         return handleZeroPadding(request, result);
1165     }
1166
1167     HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding);
1168     renderView()->layer()->hitTest(request, result);
1169
1170     return StaticHashSetNodeList::adopt(result.rectBasedTestResult());
1171 }
1172
1173 PassRefPtr<NodeList> Document::handleZeroPadding(const HitTestRequest& request, HitTestResult& result) const
1174 {
1175     renderView()->layer()->hitTest(request, result);
1176
1177     Node* node = result.innerNode();
1178     if (!node)
1179         return 0;
1180
1181     node = node->shadowAncestorNode();
1182     ListHashSet<RefPtr<Node> > list;
1183     list.add(node);
1184     return StaticHashSetNodeList::adopt(list);
1185 }
1186
1187 static Node* nodeFromPoint(Frame* frame, RenderView* renderView, int x, int y, LayoutPoint* localPoint = 0)
1188 {
1189     if (!frame)
1190         return 0;
1191     FrameView* frameView = frame->view();
1192     if (!frameView)
1193         return 0;
1194
1195     float zoomFactor = frame->pageZoomFactor();
1196 #if ENABLE(TIZEN_SMART_FOCUSING)
1197     // 1. Apply every outter frames' scroll value (x, y) to the point
1198     IntPoint convertedPointWithOutterFrames = frameView->convertFromContainingWindow(IntPoint(x, y));
1199     // 2. Apply zoom scale value and current frame's scroll value (x,y) to convertedPointWithOutterFrames
1200     //   convertedPointWithOutterFrames.x() * zoomFactor + frameView->scrollX()
1201     //   convertedPointWithOutterFrames.y() * zoomFactor + frameView->scrollY()
1202     // 3. Finally, round the point value
1203     IntPoint pointForHittedFrame = roundedIntPoint(FloatPoint(convertedPointWithOutterFrames.x() * zoomFactor + frameView->scrollX(),
1204                                                             convertedPointWithOutterFrames.y() * zoomFactor + frameView->scrollY()));
1205
1206     if (!frameView->visibleContentRect().contains(pointForHittedFrame))
1207         return 0;
1208
1209     HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
1210     HitTestResult result(pointForHittedFrame);
1211 #else
1212     IntPoint point = roundedIntPoint(FloatPoint(x * zoomFactor  + frameView->scrollX(), y * zoomFactor + frameView->scrollY()));
1213
1214     if (!frameView->visibleContentRect().contains(point))
1215         return 0;
1216
1217     HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
1218     HitTestResult result(point);
1219 #endif
1220
1221     renderView->layer()->hitTest(request, result);
1222
1223     if (localPoint)
1224         *localPoint = result.localPoint();
1225
1226     return result.innerNode();
1227 }
1228
1229 Element* Document::elementFromPoint(int x, int y) const
1230 {
1231     if (!renderer())
1232         return 0;
1233     Node* node = nodeFromPoint(frame(), renderView(), x, y);
1234     while (node && !node->isElementNode())
1235         node = node->parentNode();
1236     if (node)
1237         node = node->shadowAncestorNode();
1238     return static_cast<Element*>(node);
1239 }
1240
1241 PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1242 {
1243     if (!renderer())
1244         return 0;
1245     LayoutPoint localPoint;
1246     Node* node = nodeFromPoint(frame(), renderView(), x, y, &localPoint);
1247     if (!node)
1248         return 0;
1249
1250     Node* shadowAncestorNode = node->shadowAncestorNode();
1251     if (shadowAncestorNode != node) {
1252         unsigned offset = shadowAncestorNode->nodeIndex();
1253         ContainerNode* container = shadowAncestorNode->parentNode();
1254         return Range::create(this, container, offset, container, offset);
1255     }
1256
1257     RenderObject* renderer = node->renderer();
1258     if (!renderer)
1259         return 0;
1260     VisiblePosition visiblePosition = renderer->positionForPoint(localPoint);
1261     if (visiblePosition.isNull())
1262         return 0;
1263
1264     Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1265     return Range::create(this, rangeCompliantPosition, rangeCompliantPosition);
1266 }
1267
1268 /*
1269  * Performs three operations:
1270  *  1. Convert control characters to spaces
1271  *  2. Trim leading and trailing spaces
1272  *  3. Collapse internal whitespace.
1273  */
1274 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1275 {
1276     const String& title = titleWithDirection.string();
1277     const UChar* characters = title.characters();
1278     unsigned length = title.length();
1279     unsigned i;
1280
1281     StringBuffer<UChar> buffer(length);
1282     unsigned builderIndex = 0;
1283
1284     // Skip leading spaces and leading characters that would convert to spaces
1285     for (i = 0; i < length; ++i) {
1286         UChar c = characters[i];
1287         if (!(c <= 0x20 || c == 0x7F))
1288             break;
1289     }
1290
1291     if (i == length)
1292         return StringWithDirection();
1293
1294     // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1295     bool previousCharWasWS = false;
1296     for (; i < length; ++i) {
1297         UChar c = characters[i];
1298         if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
1299             if (previousCharWasWS)
1300                 continue;
1301             buffer[builderIndex++] = ' ';
1302             previousCharWasWS = true;
1303         } else {
1304             buffer[builderIndex++] = c;
1305             previousCharWasWS = false;
1306         }
1307     }
1308
1309     // Strip trailing spaces
1310     while (builderIndex > 0) {
1311         --builderIndex;
1312         if (buffer[builderIndex] != ' ')
1313             break;
1314     }
1315
1316     if (!builderIndex && buffer[builderIndex] == ' ')
1317         return StringWithDirection();
1318
1319     buffer.shrink(builderIndex + 1);
1320
1321     // Replace the backslashes with currency symbols if the encoding requires it.
1322     document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1323     
1324     return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
1325 }
1326
1327 void Document::updateTitle(const StringWithDirection& title)
1328 {
1329     if (m_rawTitle == title)
1330         return;
1331
1332     m_rawTitle = title;
1333     m_title = canonicalizedTitle(this, m_rawTitle);
1334     if (Frame* f = frame())
1335         f->loader()->setTitle(m_title);
1336 }
1337
1338 void Document::setTitle(const String& title)
1339 {
1340     // Title set by JavaScript -- overrides any title elements.
1341     m_titleSetExplicitly = true;
1342     if (!isHTMLDocument() && !isXHTMLDocument())
1343         m_titleElement = 0;
1344     else if (!m_titleElement) {
1345         if (HTMLElement* headElement = head()) {
1346             m_titleElement = createElement(titleTag, false);
1347             ExceptionCode ec = 0;
1348             headElement->appendChild(m_titleElement, ec);
1349             ASSERT(!ec);
1350         }
1351     }
1352
1353     // The DOM API has no method of specifying direction, so assume LTR.
1354     updateTitle(StringWithDirection(title, LTR));
1355
1356     if (m_titleElement) {
1357         ASSERT(m_titleElement->hasTagName(titleTag));
1358         if (m_titleElement->hasTagName(titleTag))
1359             static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(title);
1360     }
1361 }
1362
1363 void Document::setTitleElement(const StringWithDirection& title, Element* titleElement)
1364 {
1365     if (titleElement != m_titleElement) {
1366         if (m_titleElement || m_titleSetExplicitly)
1367             // Only allow the first title element to change the title -- others have no effect.
1368             return;
1369         m_titleElement = titleElement;
1370     }
1371
1372     updateTitle(title);
1373 }
1374
1375 void Document::removeTitle(Element* titleElement)
1376 {
1377     if (m_titleElement != titleElement)
1378         return;
1379
1380     m_titleElement = 0;
1381     m_titleSetExplicitly = false;
1382
1383     // Update title based on first title element in the head, if one exists.
1384     if (HTMLElement* headElement = head()) {
1385         for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
1386             if (e->hasTagName(titleTag)) {
1387                 HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
1388                 setTitleElement(titleElement->textWithDirection(), titleElement);
1389                 break;
1390             }
1391     }
1392
1393     if (!m_titleElement)
1394         updateTitle(StringWithDirection());
1395 }
1396
1397 #if ENABLE(PAGE_VISIBILITY_API)
1398 PageVisibilityState Document::visibilityState() const
1399 {
1400     // The visibility of the document is inherited from the visibility of the
1401     // page. If there is no page associated with the document, we will assume
1402     // that the page is visible i.e. invisibility has to be explicitly
1403     // specified by the embedder.
1404     if (!m_frame || !m_frame->page())
1405         return PageVisibilityStateVisible;
1406     return m_frame->page()->visibilityState();
1407 }
1408
1409 String Document::webkitVisibilityState() const
1410 {
1411     return pageVisibilityStateString(visibilityState());
1412 }
1413
1414 bool Document::webkitHidden() const
1415 {
1416     return visibilityState() != PageVisibilityStateVisible;
1417 }
1418
1419 void Document::dispatchVisibilityStateChangeEvent()
1420 {
1421     dispatchEvent(Event::create(eventNames().webkitvisibilitychangeEvent, false, false));
1422 }
1423 #endif
1424
1425 String Document::nodeName() const
1426 {
1427     return "#document";
1428 }
1429
1430 Node::NodeType Document::nodeType() const
1431 {
1432     return DOCUMENT_NODE;
1433 }
1434
1435 FrameView* Document::view() const
1436 {
1437     return m_frame ? m_frame->view() : 0;
1438 }
1439
1440 Page* Document::page() const
1441 {
1442     return m_frame ? m_frame->page() : 0;    
1443 }
1444
1445 Settings* Document::settings() const
1446 {
1447     return m_frame ? m_frame->settings() : 0;
1448 }
1449
1450 PassRefPtr<Range> Document::createRange()
1451 {
1452     return Range::create(this);
1453 }
1454
1455 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, 
1456     PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1457 {
1458     if (!root) {
1459         ec = NOT_SUPPORTED_ERR;
1460         return 0;
1461     }
1462     return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
1463 }
1464
1465 PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, 
1466     PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
1467 {
1468     if (!root) {
1469         ec = NOT_SUPPORTED_ERR;
1470         return 0;
1471     }
1472     return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
1473 }
1474
1475 void Document::scheduleForcedStyleRecalc()
1476 {
1477     m_pendingStyleRecalcShouldForce = true;
1478     scheduleStyleRecalc();
1479 }
1480
1481 void Document::scheduleStyleRecalc()
1482 {
1483     if (m_styleRecalcTimer.isActive() || inPageCache())
1484         return;
1485
1486     ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1487
1488     if (!documentsThatNeedStyleRecalc)
1489         documentsThatNeedStyleRecalc = new HashSet<Document*>;
1490     documentsThatNeedStyleRecalc->add(this);
1491     
1492     // FIXME: Why on earth is this here? This is clearly misplaced.
1493     invalidateAccessKeyMap();
1494     
1495     m_styleRecalcTimer.startOneShot(0);
1496
1497     InspectorInstrumentation::didScheduleStyleRecalculation(this);
1498 }
1499
1500 void Document::unscheduleStyleRecalc()
1501 {
1502     ASSERT(!childNeedsStyleRecalc());
1503
1504     if (documentsThatNeedStyleRecalc)
1505         documentsThatNeedStyleRecalc->remove(this);
1506
1507     m_styleRecalcTimer.stop();
1508     m_pendingStyleRecalcShouldForce = false;
1509 }
1510
1511 bool Document::isPendingStyleRecalc() const
1512 {
1513     return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1514 }
1515
1516 void Document::styleRecalcTimerFired(Timer<Document>*)
1517 {
1518     updateStyleIfNeeded();
1519 }
1520
1521 bool Document::childNeedsAndNotInStyleRecalc()
1522 {
1523     return childNeedsStyleRecalc() && !m_inStyleRecalc;
1524 }
1525
1526 void Document::recalcStyle(StyleChange change)
1527 {
1528     // we should not enter style recalc while painting
1529     if (view() && view()->isPainting()) {
1530         ASSERT(!view()->isPainting());
1531         return;
1532     }
1533     
1534     if (m_inStyleRecalc)
1535         return; // Guard against re-entrancy. -dwh
1536     
1537     if (m_hasDirtyStyleSelector)
1538         recalcStyleSelector();
1539
1540     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
1541
1542     m_inStyleRecalc = true;
1543     suspendPostAttachCallbacks();
1544     RenderWidget::suspendWidgetHierarchyUpdates();
1545     
1546     RefPtr<FrameView> frameView = view();
1547     if (frameView) {
1548         frameView->pauseScheduledEvents();
1549         frameView->beginDeferredRepaints();
1550     }
1551
1552     ASSERT(!renderer() || renderArena());
1553     if (!renderer() || !renderArena())
1554         goto bail_out;
1555
1556     if (m_pendingStyleRecalcShouldForce)
1557         change = Force;
1558
1559     if (change == Force) {
1560         // style selector may set this again during recalc
1561         m_hasNodesWithPlaceholderStyle = false;
1562         
1563         RefPtr<RenderStyle> documentStyle = CSSStyleSelector::styleForDocument(this);
1564         StyleChange ch = diff(documentStyle.get(), renderer()->style());
1565         if (ch != NoChange)
1566             renderer()->setStyle(documentStyle.release());
1567     }
1568
1569     for (Node* n = firstChild(); n; n = n->nextSibling()) {
1570         if (!n->isElementNode())
1571             continue;
1572         Element* element = static_cast<Element*>(n);
1573         if (change >= Inherit || element->childNeedsStyleRecalc() || element->needsStyleRecalc())
1574             element->recalcStyle(change);
1575     }
1576
1577 #if USE(ACCELERATED_COMPOSITING)
1578     if (view()) {
1579         bool layoutPending = view()->layoutPending() || renderer()->needsLayout();
1580         // If we didn't update compositing layers because of layout(), we need to do so here.
1581         if (!layoutPending)
1582             view()->updateCompositingLayers();
1583     }
1584 #endif
1585
1586 bail_out:
1587     clearNeedsStyleRecalc();
1588     clearChildNeedsStyleRecalc();
1589     unscheduleStyleRecalc();
1590
1591     m_inStyleRecalc = false;
1592     
1593     // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
1594     if (m_styleSelector) {
1595         m_usesSiblingRules = m_styleSelector->usesSiblingRules();
1596         m_usesFirstLineRules = m_styleSelector->usesFirstLineRules();
1597         m_usesBeforeAfterRules = m_styleSelector->usesBeforeAfterRules();
1598         m_usesLinkRules = m_styleSelector->usesLinkRules();
1599     }
1600
1601     if (frameView) {
1602         frameView->resumeScheduledEvents();
1603         frameView->endDeferredRepaints();
1604     }
1605     RenderWidget::resumeWidgetHierarchyUpdates();
1606     resumePostAttachCallbacks();
1607
1608     // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1609     if (m_closeAfterStyleRecalc) {
1610         m_closeAfterStyleRecalc = false;
1611         implicitClose();
1612     }
1613
1614     InspectorInstrumentation::didRecalculateStyle(cookie);
1615 }
1616
1617 void Document::updateStyleIfNeeded()
1618 {
1619     ASSERT(isMainThread());
1620     ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
1621     
1622     if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
1623         return;
1624
1625     if (m_frame)
1626         m_frame->animation()->beginAnimationUpdate();
1627         
1628     recalcStyle(NoChange);
1629
1630     // Tell the animation controller that updateStyleIfNeeded is finished and it can do any post-processing
1631     if (m_frame)
1632         m_frame->animation()->endAnimationUpdate();
1633 }
1634
1635 void Document::updateStyleForAllDocuments()
1636 {
1637     ASSERT(isMainThread());
1638     if (!documentsThatNeedStyleRecalc)
1639         return;
1640
1641     while (documentsThatNeedStyleRecalc->size()) {
1642         HashSet<Document*>::iterator it = documentsThatNeedStyleRecalc->begin();
1643         Document* doc = *it;
1644         documentsThatNeedStyleRecalc->remove(doc);
1645         doc->updateStyleIfNeeded();
1646     }
1647 }
1648
1649 void Document::updateLayout()
1650 {
1651     ASSERT(isMainThread());
1652     if (Element* oe = ownerElement())
1653         oe->document()->updateLayout();
1654
1655     updateStyleIfNeeded();
1656
1657     // Only do a layout if changes have occurred that make it necessary.      
1658     FrameView* v = view();
1659     if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
1660         v->layout();
1661 }
1662
1663 // FIXME: This is a bad idea and needs to be removed eventually.
1664 // Other browsers load stylesheets before they continue parsing the web page.
1665 // Since we don't, we can run JavaScript code that needs answers before the
1666 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1667 // lets us get reasonable answers. The long term solution to this problem is
1668 // to instead suspend JavaScript execution.
1669 void Document::updateLayoutIgnorePendingStylesheets()
1670 {
1671     bool oldIgnore = m_ignorePendingStylesheets;
1672     
1673     if (!haveStylesheetsLoaded()) {
1674         m_ignorePendingStylesheets = true;
1675         // FIXME: We are willing to attempt to suppress painting with outdated style info only once.  Our assumption is that it would be
1676         // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1677         // with accurate style information.  (Our suppression involves blanking the whole page at the
1678         // moment.  If it were more refined, we might be able to do something better.)
1679         // It's worth noting though that this entire method is a hack, since what we really want to do is
1680         // suspend JS instead of doing a layout with inaccurate information.
1681         if (body() && !body()->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1682             m_pendingSheetLayout = DidLayoutWithPendingSheets;
1683             styleSelectorChanged(RecalcStyleImmediately);
1684         } else if (m_hasNodesWithPlaceholderStyle)
1685             // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes 
1686             // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive 
1687             // but here we need up-to-date style immediately.
1688             recalcStyle(Force);
1689     }
1690
1691     updateLayout();
1692
1693     m_ignorePendingStylesheets = oldIgnore;
1694 }
1695
1696 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
1697 {
1698     ASSERT_ARG(element, element->document() == this);
1699
1700     bool oldIgnore = m_ignorePendingStylesheets;
1701     m_ignorePendingStylesheets = true;
1702     RefPtr<RenderStyle> style = styleSelector()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
1703     m_ignorePendingStylesheets = oldIgnore;
1704     return style.release();
1705 }
1706
1707 PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
1708 {
1709     RefPtr<RenderStyle> style = styleSelector()->styleForPage(pageIndex);
1710     return style.release();
1711 }
1712
1713 void Document::registerCustomFont(FontData* fontData)
1714 {
1715     m_customFonts.append(adoptPtr(fontData));
1716 }
1717
1718 void Document::deleteCustomFonts()
1719 {
1720     size_t size = m_customFonts.size();
1721     for (size_t i = 0; i < size; ++i)
1722         GlyphPageTreeNode::pruneTreeCustomFontData(m_customFonts[i].get());
1723
1724     m_customFonts.clear();
1725 }
1726
1727 bool Document::isPageBoxVisible(int pageIndex)
1728 {
1729     RefPtr<RenderStyle> style = styleForPage(pageIndex);
1730     return style->visibility() != HIDDEN; // display property doesn't apply to @page.
1731 }
1732
1733 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
1734 {
1735     RefPtr<RenderStyle> style = styleForPage(pageIndex);
1736
1737     int width = pageSize.width();
1738     int height = pageSize.height();
1739     switch (style->pageSizeType()) {
1740     case PAGE_SIZE_AUTO:
1741         break;
1742     case PAGE_SIZE_AUTO_LANDSCAPE:
1743         if (width < height)
1744             std::swap(width, height);
1745         break;
1746     case PAGE_SIZE_AUTO_PORTRAIT:
1747         if (width > height)
1748             std::swap(width, height);
1749         break;
1750     case PAGE_SIZE_RESOLVED: {
1751         LengthSize size = style->pageSize();
1752         ASSERT(size.width().isFixed());
1753         ASSERT(size.height().isFixed());
1754         width = size.width().calcValue(0);
1755         height = size.height().calcValue(0);
1756         break;
1757     }
1758     default:
1759         ASSERT_NOT_REACHED();
1760     }
1761     pageSize = IntSize(width, height);
1762
1763     // The percentage is calculated with respect to the width even for margin top and bottom.
1764     // http://www.w3.org/TR/CSS2/box.html#margin-properties
1765     marginTop = style->marginTop().isAuto() ? marginTop : style->marginTop().calcValue(width);
1766     marginRight = style->marginRight().isAuto() ? marginRight : style->marginRight().calcValue(width);
1767     marginBottom = style->marginBottom().isAuto() ? marginBottom : style->marginBottom().calcValue(width);
1768     marginLeft = style->marginLeft().isAuto() ? marginLeft : style->marginLeft().calcValue(width);
1769 }
1770
1771 PassRefPtr<CSSPrimitiveValueCache> Document::cssPrimitiveValueCache() const
1772 {
1773     if (!m_cssPrimitiveValueCache)
1774         m_cssPrimitiveValueCache = CSSPrimitiveValueCache::create();
1775     return m_cssPrimitiveValueCache;
1776 }
1777
1778 void Document::setIsViewSource(bool isViewSource)
1779 {
1780     m_isViewSource = isViewSource;
1781     if (!m_isViewSource)
1782         return;
1783
1784     setSecurityOrigin(SecurityOrigin::createUnique());
1785 }
1786
1787 void Document::createStyleSelector()
1788 {
1789     bool matchAuthorAndUserStyles = true;
1790     if (Settings* docSettings = settings())
1791         matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
1792     m_styleSelector = adoptPtr(new CSSStyleSelector(this, m_styleSheets.get(), m_mappedElementSheet.get(), pageUserSheet(), pageGroupUserSheets(), m_userSheets.get(),
1793                                                     !inQuirksMode(), matchAuthorAndUserStyles));
1794     // 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).
1795     m_usesSiblingRules = m_usesSiblingRules || m_styleSelector->usesSiblingRules();
1796     m_usesFirstLineRules = m_usesFirstLineRules || m_styleSelector->usesFirstLineRules();
1797     m_usesBeforeAfterRules = m_usesBeforeAfterRules || m_styleSelector->usesBeforeAfterRules();
1798     m_usesLinkRules = m_usesLinkRules || m_styleSelector->usesLinkRules();
1799 }
1800
1801 void Document::attach()
1802 {
1803     ASSERT(!attached());
1804     ASSERT(!m_inPageCache);
1805     ASSERT(!m_axObjectCache || this != topDocument());
1806
1807     if (!m_renderArena)
1808         m_renderArena = adoptPtr(new RenderArena);
1809     
1810     // Create the rendering tree
1811     setRenderer(new (m_renderArena.get()) RenderView(this, view()));
1812 #if USE(ACCELERATED_COMPOSITING)
1813     renderView()->didMoveOnscreen();
1814 #endif
1815
1816     recalcStyle(Force);
1817
1818     RenderObject* render = renderer();
1819     setRenderer(0);
1820
1821     TreeScope::attach();
1822
1823     setRenderer(render);
1824 }
1825
1826 void Document::detach()
1827 {
1828     ASSERT(attached());
1829     ASSERT(!m_inPageCache);
1830
1831     if (this == topDocument())
1832         clearAXObjectCache();
1833
1834     stopActiveDOMObjects();
1835     m_eventQueue->close();
1836 #if ENABLE(FULLSCREEN_API)
1837     m_fullScreenChangeEventTargetQueue.clear();
1838 #endif
1839
1840 #if ENABLE(REQUEST_ANIMATION_FRAME)
1841     // FIXME: consider using ActiveDOMObject.
1842     m_scriptedAnimationController = nullptr;
1843 #endif
1844
1845     RenderObject* render = renderer();
1846
1847     // Send out documentWillBecomeInactive() notifications to registered elements,
1848     // in order to stop media elements
1849     documentWillBecomeInactive();
1850
1851 #if ENABLE(SHARED_WORKERS)
1852     SharedWorkerRepository::documentDetached(this);
1853 #endif
1854
1855     if (m_frame) {
1856         FrameView* view = m_frame->view();
1857         if (view)
1858             view->detachCustomScrollbars();
1859
1860     }
1861
1862     // indicate destruction mode,  i.e. attached() but renderer == 0
1863     setRenderer(0);
1864     
1865 #if ENABLE(FULLSCREEN_API)
1866     if (m_fullScreenRenderer)
1867         setFullScreenRenderer(0);
1868 #endif
1869
1870     m_hoverNode = 0;
1871     m_focusedNode = 0;
1872     m_activeNode = 0;
1873
1874     TreeScope::detach();
1875
1876     unscheduleStyleRecalc();
1877
1878     if (render)
1879         render->destroy();
1880     
1881     // This is required, as our Frame might delete itself as soon as it detaches
1882     // us. However, this violates Node::detach() semantics, as it's never
1883     // possible to re-attach. Eventually Document::detach() should be renamed,
1884     // or this setting of the frame to 0 could be made explicit in each of the
1885     // callers of Document::detach().
1886     m_frame = 0;
1887     m_renderArena.clear();
1888 }
1889
1890 void Document::removeAllEventListeners()
1891 {
1892     EventTarget::removeAllEventListeners();
1893
1894     if (DOMWindow* domWindow = this->domWindow())
1895         domWindow->removeAllEventListeners();
1896     for (Node* node = firstChild(); node; node = node->traverseNextNode())
1897         node->removeAllEventListeners();
1898 }
1899
1900 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
1901 {
1902     ScriptExecutionContext::suspendActiveDOMObjects(why);
1903
1904 #if ENABLE(DEVICE_ORIENTATION)
1905     if (!page())
1906         return;
1907
1908     if (page()->deviceMotionController())
1909         page()->deviceMotionController()->suspendEventsForAllListeners(domWindow());
1910     if (page()->deviceOrientationController())
1911         page()->deviceOrientationController()->suspendEventsForAllListeners(domWindow());
1912 #endif
1913 }
1914
1915 void Document::resumeActiveDOMObjects()
1916 {
1917     ScriptExecutionContext::resumeActiveDOMObjects();
1918
1919 #if ENABLE(DEVICE_ORIENTATION)
1920     if (!page())
1921         return;
1922
1923     if (page()->deviceMotionController())
1924         page()->deviceMotionController()->resumeEventsForAllListeners(domWindow());
1925     if (page()->deviceOrientationController())
1926         page()->deviceOrientationController()->resumeEventsForAllListeners(domWindow());
1927 #endif
1928 }
1929
1930 RenderView* Document::renderView() const
1931 {
1932     return toRenderView(renderer());
1933 }
1934
1935 void Document::clearAXObjectCache()
1936 {
1937     // clear cache in top document
1938     if (m_axObjectCache) {
1939         // Clear the cache member variable before calling delete because attempts
1940         // are made to access it during destruction.
1941         AXObjectCache* axObjectCache = m_axObjectCache;
1942         m_axObjectCache = 0;
1943         delete axObjectCache;
1944         return;
1945     }
1946     
1947     // ask the top-level document to clear its cache
1948     Document* doc = topDocument();
1949     if (doc != this)
1950         doc->clearAXObjectCache();
1951 }
1952
1953 bool Document::axObjectCacheExists() const
1954 {
1955     if (m_axObjectCache)
1956         return true;
1957     
1958     Document* doc = topDocument();
1959     if (doc != this)
1960         return doc->axObjectCacheExists();
1961     
1962     return false;
1963 }
1964     
1965 AXObjectCache* Document::axObjectCache() const
1966 {
1967     // The only document that actually has a AXObjectCache is the top-level
1968     // document.  This is because we need to be able to get from any WebCoreAXObject
1969     // to any other WebCoreAXObject on the same page.  Using a single cache allows
1970     // lookups across nested webareas (i.e. multiple documents).
1971     
1972     if (m_axObjectCache) {
1973         // return already known top-level cache
1974         if (!ownerElement())
1975             return m_axObjectCache;
1976         
1977         // In some pages with frames, the cache is created before the sub-webarea is
1978         // inserted into the tree.  Here, we catch that case and just toss the old
1979         // cache and start over.
1980         // NOTE: This recovery may no longer be needed. I have been unable to trigger
1981         // it again. See rdar://5794454
1982         // FIXME: Can this be fixed when inserting the subframe instead of now?
1983         // FIXME: If this function was called to get the cache in order to remove
1984         // an AXObject, we are now deleting the cache as a whole and returning a
1985         // new empty cache that does not contain the AXObject! That should actually
1986         // be OK. I am concerned about other cases like this where accessing the
1987         // cache blows away the AXObject being operated on.
1988         delete m_axObjectCache;
1989         m_axObjectCache = 0;
1990     }
1991
1992     // ask the top-level document for its cache
1993     Document* doc = topDocument();
1994     if (doc != this)
1995         return doc->axObjectCache();
1996     
1997     // this is the top-level document, so install a new cache
1998     m_axObjectCache = new AXObjectCache(this);
1999     return m_axObjectCache;
2000 }
2001
2002 void Document::setVisuallyOrdered()
2003 {
2004     m_visuallyOrdered = true;
2005     if (renderer())
2006         renderer()->style()->setRTLOrdering(VisualOrder);
2007 }
2008
2009 PassRefPtr<DocumentParser> Document::createParser()
2010 {
2011     // FIXME: this should probably pass the frame instead
2012 #if ENABLE(NEW_XML)
2013     return NewXMLDocumentParser::create(this);
2014 #else
2015     return XMLDocumentParser::create(this, view());
2016 #endif
2017 }
2018
2019 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2020 {
2021     return parser() ? parser()->asScriptableDocumentParser() : 0;
2022 }
2023
2024 void Document::open(Document* ownerDocument)
2025 {
2026     if (ownerDocument) {
2027         setURL(ownerDocument->url());
2028         m_cookieURL = ownerDocument->cookieURL();
2029         setSecurityOrigin(ownerDocument->securityOrigin());
2030     }
2031
2032     if (m_frame) {
2033         if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2034             if (parser->isParsing()) {
2035                 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2036                 if (parser->isExecutingScript())
2037                     return;
2038
2039                 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2040                     return;
2041             }
2042         }
2043
2044         if (m_frame->loader()->state() == FrameStateProvisional)
2045             m_frame->loader()->stopAllLoaders();
2046     }
2047
2048     removeAllEventListeners();
2049     implicitOpen();
2050     if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2051         parser->setWasCreatedByScript(true);
2052
2053     if (DOMWindow* domWindow = this->domWindow())
2054         domWindow->removeAllEventListeners();
2055
2056     if (m_frame)
2057         m_frame->loader()->didExplicitOpen();
2058 }
2059
2060 void Document::detachParser()
2061 {
2062     if (!m_parser)
2063         return;
2064     m_parser->detach();
2065     m_parser.clear();
2066 }
2067
2068 void Document::cancelParsing()
2069 {
2070     if (!m_parser)
2071         return;
2072
2073     // We have to clear the parser to avoid possibly triggering
2074     // the onload handler when closing as a side effect of a cancel-style
2075     // change, such as opening a new document or closing the window while
2076     // still parsing
2077     detachParser();
2078     explicitClose();
2079 }
2080
2081 void Document::implicitOpen()
2082 {
2083     cancelParsing();
2084
2085     removeChildren();
2086
2087     setCompatibilityMode(NoQuirksMode);
2088
2089     m_parser = createParser();
2090     setParsing(true);
2091     setReadyState(Loading);
2092
2093     // If we reload, the animation controller sticks around and has
2094     // a stale animation time. We need to update it here.
2095     if (m_frame && m_frame->animation())
2096         m_frame->animation()->beginAnimationUpdate();
2097 }
2098
2099 HTMLElement* Document::body() const
2100 {
2101     Node* de = documentElement();
2102     if (!de)
2103         return 0;
2104     
2105     // try to prefer a FRAMESET element over BODY
2106     Node* body = 0;
2107     for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
2108         if (i->hasTagName(framesetTag))
2109             return toHTMLElement(i);
2110         
2111         if (i->hasTagName(bodyTag) && !body)
2112             body = i;
2113     }
2114     return toHTMLElement(body);
2115 }
2116
2117 void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionCode& ec)
2118 {
2119     RefPtr<HTMLElement> newBody = prpNewBody;
2120
2121     if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) { 
2122         ec = HIERARCHY_REQUEST_ERR;
2123         return;
2124     }
2125
2126     if (newBody->document() && newBody->document() != this) {
2127         ec = 0;
2128         RefPtr<Node> node = importNode(newBody.get(), true, ec);
2129         if (ec)
2130             return;
2131         
2132         newBody = toHTMLElement(node.get());
2133     }
2134
2135     HTMLElement* b = body();
2136     if (!b)
2137         documentElement()->appendChild(newBody.release(), ec);
2138     else
2139         documentElement()->replaceChild(newBody.release(), b, ec);
2140 }
2141
2142 HTMLHeadElement* Document::head()
2143 {
2144     Node* de = documentElement();
2145     if (!de)
2146         return 0;
2147
2148     for (Node* e = de->firstChild(); e; e = e->nextSibling())
2149         if (e->hasTagName(headTag))
2150             return static_cast<HTMLHeadElement*>(e);
2151
2152     return 0;
2153 }
2154
2155 void Document::close()
2156 {
2157     // FIXME: We should follow the specification more closely:
2158     //        http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2159
2160     if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2161         return;
2162
2163     explicitClose();
2164 }
2165
2166 void Document::explicitClose()
2167 {
2168     if (m_parser)
2169         m_parser->finish();
2170
2171     if (!m_frame) {
2172         // Because we have no frame, we don't know if all loading has completed,
2173         // so we just call implicitClose() immediately. FIXME: This might fire
2174         // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2175         implicitClose();
2176         return;
2177     }
2178
2179     m_frame->loader()->checkCompleted();
2180 }
2181
2182 void Document::implicitClose()
2183 {
2184     // 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.
2185     if (m_inStyleRecalc) {
2186         m_closeAfterStyleRecalc = true;
2187         return;
2188     }
2189
2190     bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
2191     bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2192     
2193     if (!doload)
2194         return;
2195
2196     m_processingLoadEvent = true;
2197
2198     ScriptableDocumentParser* parser = scriptableDocumentParser();
2199     m_wellFormed = parser && parser->wellFormed();
2200
2201     // We have to clear the parser, in case someone document.write()s from the
2202     // onLoad event handler, as in Radar 3206524.
2203     detachParser();
2204
2205     // Parser should have picked up all preloads by now
2206     m_cachedResourceLoader->clearPreloads();
2207
2208     // FIXME: We kick off the icon loader when the Document is done parsing.
2209     // There are earlier opportunities we could start it:
2210     //  -When the <head> finishes parsing
2211     //  -When any new HTMLLinkElement is inserted into the document
2212     // But those add a dynamic component to the favicon that has UI 
2213     // ramifications, and we need to decide what is the Right Thing To Do(tm)
2214     Frame* f = frame();
2215     if (f) {
2216         f->loader()->icon()->startLoader();
2217         f->animation()->resumeAnimationsForDocument(this);
2218     }
2219
2220     ImageLoader::dispatchPendingBeforeLoadEvents();
2221     ImageLoader::dispatchPendingLoadEvents();
2222     dispatchWindowLoadEvent();
2223     enqueuePageshowEvent(PageshowEventNotPersisted);
2224     enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
2225     
2226     if (f)
2227         f->loader()->handledOnloadEvents();
2228 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2229     if (!ownerElement())
2230         printf("onload fired at %d\n", elapsedTime());
2231 #endif
2232
2233     m_processingLoadEvent = false;
2234
2235     // An event handler may have removed the frame
2236     if (!frame())
2237         return;
2238
2239     // Make sure both the initial layout and reflow happen after the onload
2240     // fires. This will improve onload scores, and other browsers do it.
2241     // If they wanna cheat, we can too. -dwh
2242
2243     if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
2244         // Just bail out. Before or during the onload we were shifted to another page.
2245         // The old i-Bench suite does this. When this happens don't bother painting or laying out.        
2246         view()->unscheduleRelayout();
2247         return;
2248     }
2249
2250     frame()->loader()->checkCallImplicitClose();
2251     RenderObject* renderObject = renderer();
2252     
2253     // We used to force a synchronous display and flush here.  This really isn't
2254     // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2255     // (if your platform is syncing flushes and limiting them to 60fps).
2256     m_overMinimumLayoutThreshold = true;
2257     if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2258         updateStyleIfNeeded();
2259         
2260         // Always do a layout after loading if needed.
2261         if (view() && renderObject && (!renderObject->firstChild() || renderObject->needsLayout()))
2262             view()->layout();
2263     }
2264
2265     // If painting and compositing layer updates were suppressed pending the load event, do these actions now.
2266     if (renderer() && settings() && settings()->suppressIncrementalRendering()) {
2267 #if USE(ACCELERATED_COMPOSITING)
2268         view()->updateCompositingLayers();
2269 #endif
2270         renderer()->repaint();
2271     }
2272
2273 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
2274     if (f && renderObject && AXObjectCache::accessibilityEnabled()) {
2275         // The AX cache may have been cleared at this point, but we need to make sure it contains an
2276         // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2277         // exists in the cache (we ignore the return value because we don't need it here). This is 
2278         // only safe to call when a layout is not in progress, so it can not be used in postNotification.    
2279         axObjectCache()->getOrCreate(renderObject);
2280         if (this == topDocument())
2281             axObjectCache()->postNotification(renderObject, AXObjectCache::AXLoadComplete, true);
2282         else {
2283             // AXLoadComplete can only be posted on the top document, so if it's a document
2284             // in an iframe that just finished loading, post a notification on the iframe
2285             // element instead.
2286             ScrollView* scrollView = frame()->view();
2287             if (scrollView && scrollView->isFrameView()) {
2288                 HTMLFrameOwnerElement* owner = static_cast<FrameView*>(scrollView)->frame()->ownerElement();
2289                 if (owner && owner->renderer()) {
2290                     AccessibilityObject* axIFrame = axObjectCache()->getOrCreate(owner->renderer());
2291                     axObjectCache()->postNotification(axIFrame, axIFrame->document(), AXObjectCache::AXLayoutComplete, true);
2292                 }
2293             }
2294         }
2295     }
2296 #endif
2297
2298 #if ENABLE(SVG)
2299     // FIXME: Officially, time 0 is when the outermost <svg> receives its
2300     // SVGLoad event, but we don't implement those yet.  This is close enough
2301     // for now.  In some cases we should have fired earlier.
2302     if (svgExtensions())
2303         accessSVGExtensions()->startAnimations();
2304 #endif
2305 }
2306
2307 void Document::setParsing(bool b)
2308 {
2309     m_bParsing = b;
2310     if (!m_bParsing && view())
2311         view()->scheduleRelayout();
2312
2313 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2314     if (!ownerElement() && !m_bParsing)
2315         printf("Parsing finished at %d\n", elapsedTime());
2316 #endif
2317 }
2318
2319 bool Document::shouldScheduleLayout()
2320 {
2321     // This function will only be called when FrameView thinks a layout is needed.
2322     // This enforces a couple extra rules.
2323     //
2324     //    (a) Only schedule a layout once the stylesheets are loaded.
2325     //    (b) Only schedule layout once we have a body element.
2326
2327     return (haveStylesheetsLoaded() && body())
2328         || (documentElement() && !documentElement()->hasTagName(htmlTag));
2329 }
2330     
2331 bool Document::isLayoutTimerActive()
2332 {
2333     return view() && view()->layoutPending() && !minimumLayoutDelay();
2334 }
2335
2336 int Document::minimumLayoutDelay()
2337 {
2338     if (m_overMinimumLayoutThreshold)
2339         return 0;
2340     
2341     int elapsed = elapsedTime();
2342     m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
2343     
2344     // We'll want to schedule the timer to fire at the minimum layout threshold.
2345     return max(0, cLayoutScheduleThreshold - elapsed);
2346 }
2347
2348 int Document::elapsedTime() const
2349 {
2350     return static_cast<int>((currentTime() - m_startTime) * 1000);
2351 }
2352
2353 void Document::write(const SegmentedString& text, Document* ownerDocument)
2354 {
2355     NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2356
2357     m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2358     m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2359
2360     if (m_writeRecursionIsTooDeep)
2361        return;
2362
2363 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2364     if (!ownerElement())
2365         printf("Beginning a document.write at %d\n", elapsedTime());
2366 #endif
2367
2368     bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2369     if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
2370         return;
2371
2372     if (!hasInsertionPoint)
2373         open(ownerDocument);
2374
2375     ASSERT(m_parser);
2376     m_parser->insert(text);
2377
2378 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2379     if (!ownerElement())
2380         printf("Ending a document.write at %d\n", elapsedTime());
2381 #endif    
2382 }
2383
2384 void Document::write(const String& text, Document* ownerDocument)
2385 {
2386     write(SegmentedString(text), ownerDocument);
2387 }
2388
2389 void Document::writeln(const String& text, Document* ownerDocument)
2390 {
2391     write(text, ownerDocument);
2392     write("\n", ownerDocument);
2393 }
2394
2395 const KURL& Document::virtualURL() const
2396 {
2397     return m_url;
2398 }
2399
2400 KURL Document::virtualCompleteURL(const String& url) const
2401 {
2402     return completeURL(url);
2403 }
2404
2405 double Document::minimumTimerInterval() const
2406 {
2407     Page* p = page();
2408     if (!p)
2409         return ScriptExecutionContext::minimumTimerInterval();
2410     return p->settings()->minDOMTimerInterval();
2411 }
2412
2413 EventTarget* Document::errorEventTarget()
2414 {
2415     return domWindow();
2416 }
2417
2418 void Document::logExceptionToConsole(const String& errorMessage, int lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack)
2419 {
2420     addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, errorMessage, lineNumber, sourceURL, callStack);
2421 }
2422
2423 void Document::setURL(const KURL& url)
2424 {
2425     const KURL& newURL = url.isEmpty() ? blankURL() : url;
2426     if (newURL == m_url)
2427         return;
2428
2429     m_url = newURL;
2430     m_documentURI = m_url.string();
2431     updateBaseURL();
2432 }
2433
2434 void Document::updateBaseURL()
2435 {
2436     // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2437     // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2438     // from the Document interface otherwise.
2439     if (!m_baseElementURL.isEmpty())
2440         m_baseURL = m_baseElementURL;
2441     else if (!m_baseURLOverride.isEmpty())
2442         m_baseURL = m_baseURLOverride;
2443     else {
2444         // The documentURI attribute is an arbitrary string. DOM 3 Core does not specify how it should be resolved,
2445         // so we use a null base URL.
2446         m_baseURL = KURL(KURL(), documentURI());
2447     }
2448
2449     if (!m_baseURL.isValid())
2450         m_baseURL = KURL();
2451
2452     if (m_elemSheet)
2453         m_elemSheet->setFinalURL(m_baseURL);
2454     if (m_mappedElementSheet)
2455         m_mappedElementSheet->setFinalURL(m_baseURL);
2456 }
2457
2458 void Document::setBaseURLOverride(const KURL& url)
2459 {
2460     m_baseURLOverride = url;
2461     updateBaseURL();
2462 }
2463
2464 void Document::processBaseElement()
2465 {
2466     // Find the first href attribute in a base element and the first target attribute in a base element.
2467     const AtomicString* href = 0;
2468     const AtomicString* target = 0;
2469     for (Node* node = document()->firstChild(); node && (!href || !target); node = node->traverseNextNode()) {
2470         if (node->hasTagName(baseTag)) {
2471             if (!href) {
2472                 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(hrefAttr);
2473                 if (!value.isNull())
2474                     href = &value;
2475             }
2476             if (!target) {
2477                 const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(targetAttr);
2478                 if (!value.isNull())
2479                     target = &value;
2480             }
2481         }
2482     }
2483
2484     // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2485     KURL baseElementURL;
2486     if (href) {
2487         String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2488         if (!strippedHref.isEmpty())
2489             baseElementURL = KURL(url(), strippedHref);
2490     }
2491     if (m_baseElementURL != baseElementURL) {
2492         m_baseElementURL = baseElementURL;
2493         updateBaseURL();
2494     }
2495
2496     m_baseTarget = target ? *target : nullAtom;
2497 }
2498
2499 String Document::userAgent(const KURL& url) const
2500 {
2501     return frame() ? frame()->loader()->userAgent(url) : String();
2502 }
2503
2504 void Document::disableEval()
2505 {
2506     if (!frame())
2507         return;
2508
2509     frame()->script()->disableEval();
2510 }
2511
2512 CSSStyleSheet* Document::pageUserSheet()
2513 {
2514     if (m_pageUserSheet)
2515         return m_pageUserSheet.get();
2516     
2517     Page* owningPage = page();
2518     if (!owningPage)
2519         return 0;
2520     
2521     String userSheetText = owningPage->userStyleSheet();
2522     if (userSheetText.isEmpty())
2523         return 0;
2524     
2525     // Parse the sheet and cache it.
2526     m_pageUserSheet = CSSStyleSheet::createInline(this, settings()->userStyleSheetLocation());
2527     m_pageUserSheet->setIsUserStyleSheet(true);
2528     m_pageUserSheet->parseString(userSheetText, !inQuirksMode());
2529     return m_pageUserSheet.get();
2530 }
2531
2532 void Document::clearPageUserSheet()
2533 {
2534     if (m_pageUserSheet) {
2535         m_pageUserSheet = 0;
2536         styleSelectorChanged(DeferRecalcStyle);
2537     }
2538 }
2539
2540 void Document::updatePageUserSheet()
2541 {
2542     clearPageUserSheet();
2543     if (pageUserSheet())
2544         styleSelectorChanged(RecalcStyleImmediately);
2545 }
2546
2547 const Vector<RefPtr<CSSStyleSheet> >* Document::pageGroupUserSheets() const
2548 {
2549     if (m_pageGroupUserSheetCacheValid)
2550         return m_pageGroupUserSheets.get();
2551     
2552     m_pageGroupUserSheetCacheValid = true;
2553     
2554     Page* owningPage = page();
2555     if (!owningPage)
2556         return 0;
2557         
2558     const PageGroup& pageGroup = owningPage->group();
2559     const UserStyleSheetMap* sheetsMap = pageGroup.userStyleSheets();
2560     if (!sheetsMap)
2561         return 0;
2562
2563     UserStyleSheetMap::const_iterator end = sheetsMap->end();
2564     for (UserStyleSheetMap::const_iterator it = sheetsMap->begin(); it != end; ++it) {
2565         const UserStyleSheetVector* sheets = it->second;
2566         for (unsigned i = 0; i < sheets->size(); ++i) {
2567             const UserStyleSheet* sheet = sheets->at(i).get();
2568             if (sheet->injectedFrames() == InjectInTopFrameOnly && ownerElement())
2569                 continue;
2570             if (!UserContentURLPattern::matchesPatterns(url(), sheet->whitelist(), sheet->blacklist()))
2571                 continue;
2572             RefPtr<CSSStyleSheet> parsedSheet = CSSStyleSheet::createInline(const_cast<Document*>(this), sheet->url());
2573             parsedSheet->setIsUserStyleSheet(sheet->level() == UserStyleUserLevel);
2574             parsedSheet->parseString(sheet->source(), !inQuirksMode());
2575             if (!m_pageGroupUserSheets)
2576                 m_pageGroupUserSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
2577             m_pageGroupUserSheets->append(parsedSheet.release());
2578         }
2579     }
2580
2581     return m_pageGroupUserSheets.get();
2582 }
2583
2584 void Document::clearPageGroupUserSheets()
2585 {
2586     m_pageGroupUserSheetCacheValid = false;
2587     if (m_pageGroupUserSheets && m_pageGroupUserSheets->size()) {
2588         m_pageGroupUserSheets->clear();
2589         styleSelectorChanged(DeferRecalcStyle);
2590     }
2591 }
2592
2593 void Document::updatePageGroupUserSheets()
2594 {
2595     clearPageGroupUserSheets();
2596     if (pageGroupUserSheets() && pageGroupUserSheets()->size())
2597         styleSelectorChanged(RecalcStyleImmediately);
2598 }
2599
2600 void Document::addUserSheet(PassRefPtr<CSSStyleSheet> userSheet)
2601 {
2602     if (!m_userSheets)
2603         m_userSheets = adoptPtr(new Vector<RefPtr<CSSStyleSheet> >);
2604     m_userSheets->append(userSheet);
2605     styleSelectorChanged(RecalcStyleImmediately);
2606 }
2607
2608 CSSStyleSheet* Document::elementSheet()
2609 {
2610     if (!m_elemSheet)
2611         m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
2612     return m_elemSheet.get();
2613 }
2614
2615 CSSStyleSheet* Document::mappedElementSheet()
2616 {
2617     if (!m_mappedElementSheet)
2618         m_mappedElementSheet = CSSStyleSheet::createInline(this, m_baseURL);
2619     return m_mappedElementSheet.get();
2620 }
2621
2622 int Document::nodeAbsIndex(Node *node)
2623 {
2624     ASSERT(node->document() == this);
2625
2626     int absIndex = 0;
2627     for (Node* n = node; n && n != this; n = n->traversePreviousNode())
2628         absIndex++;
2629     return absIndex;
2630 }
2631
2632 Node* Document::nodeWithAbsIndex(int absIndex)
2633 {
2634     Node* n = this;
2635     for (int i = 0; n && (i < absIndex); i++)
2636         n = n->traverseNextNode();
2637     return n;
2638 }
2639
2640 void Document::processHttpEquiv(const String& equiv, const String& content)
2641 {
2642     ASSERT(!equiv.isNull() && !content.isNull());
2643
2644     Frame* frame = this->frame();
2645
2646     if (equalIgnoringCase(equiv, "default-style")) {
2647         // The preferred style set has been overridden as per section 
2648         // 14.3.2 of the HTML4.0 specification.  We need to update the
2649         // sheet used variable and then update our style selector. 
2650         // For more info, see the test at:
2651         // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
2652         // -dwh
2653         m_selectedStylesheetSet = content;
2654         m_preferredStylesheetSet = content;
2655         styleSelectorChanged(DeferRecalcStyle);
2656     } else if (equalIgnoringCase(equiv, "refresh")) {
2657         double delay;
2658         String url;
2659         if (frame && parseHTTPRefresh(content, true, delay, url)) {
2660             if (url.isEmpty())
2661                 url = m_url.string();
2662             else
2663                 url = completeURL(url).string();
2664             frame->navigationScheduler()->scheduleRedirect(delay, url);
2665         }
2666     } else if (equalIgnoringCase(equiv, "set-cookie")) {
2667         // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
2668         if (isHTMLDocument()) {
2669             ExceptionCode ec; // Exception (for sandboxed documents) ignored.
2670             static_cast<HTMLDocument*>(this)->setCookie(content, ec);
2671         }
2672     } else if (equalIgnoringCase(equiv, "content-language"))
2673         setContentLanguage(content);
2674     else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
2675         parseDNSPrefetchControlHeader(content);
2676     else if (equalIgnoringCase(equiv, "x-frame-options")) {
2677         if (frame) {
2678             FrameLoader* frameLoader = frame->loader();
2679             if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url())) {
2680                 frameLoader->stopAllLoaders();
2681                 frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), blankURL(), String());
2682
2683                 DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to display document because display forbidden by X-Frame-Options.\n"));
2684                 addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, consoleMessage);
2685             }
2686         }
2687     } else if (equalIgnoringCase(equiv, "x-webkit-csp"))
2688         contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::EnforcePolicy);
2689     else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
2690         contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::ReportOnly);
2691 }
2692
2693 // Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
2694 static bool isSeparator(UChar c)
2695 {
2696 #if ENABLE(TIZEN_SUPPORT_VIEWPORT)
2697     // Some websites are using seprator of viewport meta tag with ';'. 
2698     // For example, facebook.
2699     // However, the ';' is not correct sperator in viewport specification.
2700     // I report this problem to webkit. WebKit guy said that facebook should
2701     // fix this wrong usage. For now, our browser needs to support ';' until facebook fixes this problem. - Gyuyoung Kim
2702     return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0' || c == ';';
2703 #else
2704     return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
2705 #endif
2706 }
2707
2708 void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
2709 {
2710     // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
2711     int keyBegin, keyEnd;
2712     int valueBegin, valueEnd;
2713
2714     int i = 0;
2715     int length = features.length();
2716     String buffer = features.lower();
2717     while (i < length) {
2718         // skip to first non-separator, but don't skip past the end of the string
2719         while (isSeparator(buffer[i])) {
2720             if (i >= length)
2721                 break;
2722             i++;
2723         }
2724         keyBegin = i;
2725
2726         // skip to first separator
2727         while (!isSeparator(buffer[i]))
2728             i++;
2729         keyEnd = i;
2730
2731         // skip to first '=', but don't skip past a ',' or the end of the string
2732         while (buffer[i] != '=') {
2733             if (buffer[i] == ',' || i >= length)
2734                 break;
2735             i++;
2736         }
2737
2738         // skip to first non-separator, but don't skip past a ',' or the end of the string
2739         while (isSeparator(buffer[i])) {
2740             if (buffer[i] == ',' || i >= length)
2741                 break;
2742             i++;
2743         }
2744         valueBegin = i;
2745
2746         // skip to first separator
2747         while (!isSeparator(buffer[i]))
2748             i++;
2749         valueEnd = i;
2750
2751         ASSERT(i <= length);
2752
2753         String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
2754         String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
2755         callback(keyString, valueString, this, data);
2756     }
2757 }
2758
2759 void Document::processViewport(const String& features)
2760 {
2761     ASSERT(!features.isNull());
2762
2763     m_viewportArguments = ViewportArguments(ViewportArguments::ViewportMeta);
2764     processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
2765
2766     Frame* frame = this->frame();
2767     if (!frame || !frame->page())
2768         return;
2769
2770     frame->page()->updateViewportArguments();
2771 }
2772
2773 #if ENABLE(TIZEN_DAILY_UPVERSIONING)
2774 void Document::processReferrerPolicy(const String& policy)
2775 {
2776     ASSERT(!policy.isNull());
2777
2778     m_referrerPolicy = SecurityPolicy::ReferrerPolicyDefault;
2779
2780     if (equalIgnoringCase(policy, "never"))
2781         m_referrerPolicy = SecurityPolicy::ReferrerPolicyNever;
2782     else if (equalIgnoringCase(policy, "always"))
2783         m_referrerPolicy = SecurityPolicy::ReferrerPolicyAlways;
2784     else if (equalIgnoringCase(policy, "origin"))
2785         m_referrerPolicy = SecurityPolicy::ReferrerPolicyOrigin;
2786 }
2787 #endif
2788 #if ENABLE(TIZEN_SUPPORT_WEBAPP_META_TAG)
2789 void Document::processMobileWebAppCapable(const String& content)
2790 {
2791     ASSERT(!content.isNull());
2792
2793     Frame* frame = this->frame();
2794     if (!frame || !frame->page() || !frame->page()->chrome() || !frame->page()->chrome()->client())
2795         return;
2796
2797     frame->page()->chrome()->client()->setMobileWebAppCapableState(content);
2798 }
2799
2800 void Document::processMobileWebAppStatusBarStyle(const String& content)
2801 {
2802     ASSERT(!content.isNull());
2803
2804     Frame* frame = this->frame();
2805     if (!frame || !frame->page() || !frame->page()->chrome() || !frame->page()->chrome()->client())
2806         return;
2807
2808     frame->page()->chrome()->client()->setMobileWebAppStatusBarStyle(content);
2809 }
2810 #endif
2811
2812 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
2813 {
2814     ASSERT(!renderer() || renderer()->isRenderView());
2815
2816     if (!renderer())
2817         return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
2818
2819     HitTestResult result(documentPoint);
2820     renderView()->layer()->hitTest(request, result);
2821
2822     if (!request.readOnly())
2823         updateStyleIfNeeded();
2824
2825     return MouseEventWithHitTestResults(event, result);
2826 }
2827
2828 // DOM Section 1.1.1
2829 bool Document::childTypeAllowed(NodeType type) const
2830 {
2831     switch (type) {
2832     case ATTRIBUTE_NODE:
2833     case CDATA_SECTION_NODE:
2834     case DOCUMENT_FRAGMENT_NODE:
2835     case DOCUMENT_NODE:
2836     case ENTITY_NODE:
2837     case ENTITY_REFERENCE_NODE:
2838     case NOTATION_NODE:
2839     case TEXT_NODE:
2840     case XPATH_NAMESPACE_NODE:
2841     case SHADOW_ROOT_NODE:
2842         return false;
2843     case COMMENT_NODE:
2844     case PROCESSING_INSTRUCTION_NODE:
2845         return true;
2846     case DOCUMENT_TYPE_NODE:
2847     case ELEMENT_NODE:
2848         // Documents may contain no more than one of each of these.
2849         // (One Element and one DocumentType.)
2850         for (Node* c = firstChild(); c; c = c->nextSibling())
2851             if (c->nodeType() == type)
2852                 return false;
2853         return true;
2854     }
2855     return false;
2856 }
2857
2858 bool Document::canReplaceChild(Node* newChild, Node* oldChild)
2859 {
2860     if (!oldChild)
2861         // ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
2862         return true;
2863
2864     if (oldChild->nodeType() == newChild->nodeType())
2865         return true;
2866
2867     int numDoctypes = 0;
2868     int numElements = 0;
2869
2870     // First, check how many doctypes and elements we have, not counting
2871     // the child we're about to remove.
2872     for (Node* c = firstChild(); c; c = c->nextSibling()) {
2873         if (c == oldChild)
2874             continue;
2875         
2876         switch (c->nodeType()) {
2877         case DOCUMENT_TYPE_NODE:
2878             numDoctypes++;
2879             break;
2880         case ELEMENT_NODE:
2881             numElements++;
2882             break;
2883         default:
2884             break;
2885         }
2886     }
2887     
2888     // Then, see how many doctypes and elements might be added by the new child.
2889     if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
2890         for (Node* c = firstChild(); c; c = c->nextSibling()) {
2891             switch (c->nodeType()) {
2892             case ATTRIBUTE_NODE:
2893             case CDATA_SECTION_NODE:
2894             case DOCUMENT_FRAGMENT_NODE:
2895             case DOCUMENT_NODE:
2896             case ENTITY_NODE:
2897             case ENTITY_REFERENCE_NODE:
2898             case NOTATION_NODE:
2899             case TEXT_NODE:
2900             case XPATH_NAMESPACE_NODE:
2901                 return false;
2902             case COMMENT_NODE:
2903             case PROCESSING_INSTRUCTION_NODE:
2904                 break;
2905             case DOCUMENT_TYPE_NODE:
2906                 numDoctypes++;
2907                 break;
2908             case ELEMENT_NODE:
2909                 numElements++;
2910                 break;
2911             case SHADOW_ROOT_NODE:
2912                 ASSERT_NOT_REACHED();
2913                 return false;
2914             }
2915         }
2916     } else {
2917         switch (newChild->nodeType()) {
2918         case ATTRIBUTE_NODE:
2919         case CDATA_SECTION_NODE:
2920         case DOCUMENT_FRAGMENT_NODE:
2921         case DOCUMENT_NODE:
2922         case ENTITY_NODE:
2923         case ENTITY_REFERENCE_NODE:
2924         case NOTATION_NODE:
2925         case TEXT_NODE:
2926         case XPATH_NAMESPACE_NODE:
2927         case SHADOW_ROOT_NODE:
2928             return false;
2929         case COMMENT_NODE:
2930         case PROCESSING_INSTRUCTION_NODE:
2931             return true;
2932         case DOCUMENT_TYPE_NODE:
2933             numDoctypes++;
2934             break;
2935         case ELEMENT_NODE:
2936             numElements++;
2937             break;
2938         }                
2939     }
2940         
2941     if (numElements > 1 || numDoctypes > 1)
2942         return false;
2943     
2944     return true;
2945 }
2946
2947 PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
2948 {
2949     // Spec says cloning Document nodes is "implementation dependent"
2950     // so we do not support it...
2951     return 0;
2952 }
2953
2954 StyleSheetList* Document::styleSheets()
2955 {
2956     return m_styleSheets.get();
2957 }
2958
2959 String Document::preferredStylesheetSet() const
2960 {
2961     return m_preferredStylesheetSet;
2962 }
2963
2964 String Document::selectedStylesheetSet() const
2965 {
2966     return m_selectedStylesheetSet;
2967 }
2968
2969 void Document::setSelectedStylesheetSet(const String& aString)
2970 {
2971     m_selectedStylesheetSet = aString;
2972     styleSelectorChanged(DeferRecalcStyle);
2973 }
2974
2975 // This method is called whenever a top-level stylesheet has finished loading.
2976 void Document::removePendingSheet()
2977 {
2978     // Make sure we knew this sheet was pending, and that our count isn't out of sync.
2979     ASSERT(m_pendingStylesheets > 0);
2980
2981     m_pendingStylesheets--;
2982     
2983 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
2984     if (!ownerElement())
2985         printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
2986 #endif
2987
2988     if (m_pendingStylesheets)
2989         return;
2990
2991     styleSelectorChanged(RecalcStyleImmediately);
2992
2993     if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2994         parser->executeScriptsWaitingForStylesheets();
2995
2996     if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
2997         view()->scrollToFragment(m_url);
2998 }
2999
3000 void Document::styleSelectorChanged(StyleSelectorUpdateFlag updateFlag)
3001 {
3002     // Don't bother updating, since we haven't loaded all our style info yet
3003     // and haven't calculated the style selector for the first time.
3004     if (!attached() || (!m_didCalculateStyleSelector && !haveStylesheetsLoaded()))
3005         return;
3006
3007 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3008     if (!ownerElement())
3009         printf("Beginning update of style selector at time %d.\n", elapsedTime());
3010 #endif
3011
3012     recalcStyleSelector();
3013     
3014     if (updateFlag == DeferRecalcStyle) {
3015         scheduleForcedStyleRecalc();
3016         return;
3017     }
3018     
3019     if (didLayoutWithPendingStylesheets() && m_pendingStylesheets <= 0) {
3020         m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3021         if (renderer())
3022             renderer()->repaint();
3023     }
3024
3025     // This recalcStyle initiates a new recalc cycle. We need to bracket it to
3026     // make sure animations get the correct update time
3027     if (m_frame)
3028         m_frame->animation()->beginAnimationUpdate();
3029     recalcStyle(Force);
3030     if (m_frame)
3031         m_frame->animation()->endAnimationUpdate();
3032
3033 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
3034     if (!ownerElement())
3035         printf("Finished update of style selector at time %d\n", elapsedTime());
3036 #endif
3037
3038     if (renderer()) {
3039         renderer()->setNeedsLayoutAndPrefWidthsRecalc();
3040         if (view())
3041             view()->scheduleRelayout();
3042     }
3043
3044     if (m_mediaQueryMatcher)
3045         m_mediaQueryMatcher->styleSelectorChanged();
3046 }
3047
3048 void Document::addStyleSheetCandidateNode(Node* node, bool createdByParser)
3049 {
3050     if (!node->inDocument())
3051         return;
3052     
3053     // Until the <body> exists, we have no choice but to compare document positions,
3054     // since styles outside of the body and head continue to be shunted into the head
3055     // (and thus can shift to end up before dynamically added DOM content that is also
3056     // outside the body).
3057     if ((createdByParser && body()) || m_styleSheetCandidateNodes.isEmpty()) {
3058         m_styleSheetCandidateNodes.add(node);
3059         return;
3060     }
3061
3062     // Determine an appropriate insertion point.
3063     StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
3064     StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
3065     StyleSheetCandidateListHashSet::iterator it = end;
3066     Node* followingNode = 0;
3067     do {
3068         --it;
3069         Node* n = *it;
3070         unsigned short position = n->compareDocumentPosition(node);
3071         if (position == DOCUMENT_POSITION_FOLLOWING) {
3072             m_styleSheetCandidateNodes.insertBefore(followingNode, node);
3073             return;
3074         }
3075         followingNode = n;
3076     } while (it != begin);
3077     
3078     m_styleSheetCandidateNodes.insertBefore(followingNode, node);
3079 }
3080
3081 void Document::removeStyleSheetCandidateNode(Node* node)
3082 {
3083     m_styleSheetCandidateNodes.remove(node);
3084 }
3085
3086 void Document::recalcStyleSelector()
3087 {
3088     if (m_inStyleRecalc) {
3089         // SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
3090         // https://bugs.webkit.org/show_bug.cgi?id=54344
3091         // FIXME: This should be fixed in SVG and this code replaced with ASSERT(!m_inStyleRecalc).
3092         m_hasDirtyStyleSelector = true;
3093         scheduleForcedStyleRecalc();
3094         return;
3095     }
3096     if (!renderer() || !attached())
3097         return;
3098
3099     StyleSheetVector sheets;
3100
3101     bool matchAuthorAndUserStyles = true;
3102     if (Settings* settings = this->settings())
3103         matchAuthorAndUserStyles = settings->authorAndUserStylesEnabled();
3104
3105     StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
3106     StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
3107     if (!matchAuthorAndUserStyles)
3108         end = begin;
3109     for (StyleSheetCandidateListHashSet::iterator it = begin; it != end; ++it) {
3110         Node* n = *it;
3111
3112         StyleSheet* sheet = 0;
3113
3114         if (n->nodeType() == PROCESSING_INSTRUCTION_NODE) {
3115             // Processing instruction (XML documents only).
3116             // We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion.
3117             ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
3118             sheet = pi->sheet();
3119 #if ENABLE(XSLT)
3120             // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
3121             if (pi->isXSL() && !transformSourceDocument()) {
3122                 // Don't apply XSL transforms until loading is finished.
3123                 if (!parsing())
3124                     applyXSLTransform(pi);
3125                 return;
3126             }
3127 #endif
3128         } else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag)))
3129 #if ENABLE(SVG)
3130             ||  (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
3131 #endif
3132         ) {
3133             Element* e = static_cast<Element*>(n);
3134             AtomicString title = e->getAttribute(titleAttr);
3135             bool enabledViaScript = false;
3136             if (e->hasLocalName(linkTag)) {
3137                 // <LINK> element
3138                 HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(n);
3139                 if (linkElement->isDisabled())
3140                     continue;
3141                 enabledViaScript = linkElement->isEnabledViaScript();
3142                 if (linkElement->isLoading()) {
3143                     // it is loading but we should still decide which style sheet set to use
3144                     if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSet.isEmpty()) {
3145                         const AtomicString& rel = e->getAttribute(relAttr);
3146                         if (!rel.contains("alternate")) {
3147                             m_preferredStylesheetSet = title;
3148                             m_selectedStylesheetSet = title;
3149                         }
3150                     }
3151                     continue;
3152                 }
3153                 if (!linkElement->sheet())
3154                     title = nullAtom;
3155             }
3156
3157             // Get the current preferred styleset.  This is the
3158             // set of sheets that will be enabled.
3159 #if ENABLE(SVG)
3160             if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
3161                 sheet = static_cast<SVGStyleElement*>(n)->sheet();
3162             else
3163 #endif
3164             if (e->hasLocalName(linkTag))
3165                 sheet = static_cast<HTMLLinkElement*>(n)->sheet();
3166             else
3167                 // <STYLE> element
3168                 sheet = static_cast<HTMLStyleElement*>(n)->sheet();
3169
3170             // Check to see if this sheet belongs to a styleset
3171             // (thus making it PREFERRED or ALTERNATE rather than
3172             // PERSISTENT).
3173             if (!enabledViaScript && !title.isEmpty()) {
3174                 // Yes, we have a title.
3175                 if (m_preferredStylesheetSet.isEmpty()) {
3176                     // No preferred set has been established.  If
3177                     // we are NOT an alternate sheet, then establish
3178                     // us as the preferred set.  Otherwise, just ignore
3179                     // this sheet.
3180                     AtomicString rel = e->getAttribute(relAttr);
3181                     if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
3182                         m_preferredStylesheetSet = m_selectedStylesheetSet = title;
3183                 }
3184
3185                 if (title != m_preferredStylesheetSet)
3186                     sheet = 0;
3187             }
3188         }
3189
3190         if (sheet)
3191             sheets.append(sheet);
3192     }
3193
3194     m_styleSheets->swap(sheets);
3195
3196     m_styleSelector.clear();
3197     m_didCalculateStyleSelector = true;
3198     m_hasDirtyStyleSelector = false;
3199 }
3200
3201 void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
3202 {
3203     m_hoverNode = newHoverNode;
3204 }
3205
3206 void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
3207 {
3208     m_activeNode = newActiveNode;
3209 }
3210
3211 void Document::focusedNodeRemoved()
3212 {
3213     setFocusedNode(0);
3214 }
3215
3216 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3217 {
3218     if (!m_focusedNode || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
3219         return;
3220         
3221     bool nodeInSubtree = false;
3222     if (amongChildrenOnly)
3223         nodeInSubtree = m_focusedNode->isDescendantOf(node);
3224     else
3225         nodeInSubtree = (m_focusedNode == node) || m_focusedNode->isDescendantOf(node);
3226     
3227     if (nodeInSubtree)
3228         document()->focusedNodeRemoved();
3229 }
3230
3231 void Document::hoveredNodeDetached(Node* node)
3232 {
3233     if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parentNode())))
3234         return;
3235
3236     m_hoverNode = node->parentNode();
3237     while (m_hoverNode && !m_hoverNode->renderer())
3238         m_hoverNode = m_hoverNode->parentNode();
3239     if (frame())
3240         frame()->eventHandler()->scheduleHoverStateUpdate();
3241 }
3242
3243 void Document::activeChainNodeDetached(Node* node)
3244 {
3245     if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parentNode())))
3246         return;
3247
3248     m_activeNode = node->parentNode();
3249     while (m_activeNode && !m_activeNode->renderer())
3250         m_activeNode = m_activeNode->parentNode();
3251 }
3252
3253 #if ENABLE(DASHBOARD_SUPPORT)
3254 const Vector<DashboardRegionValue>& Document::dashboardRegions() const
3255 {
3256     return m_dashboardRegions;
3257 }
3258
3259 void Document::setDashboardRegions(const Vector<DashboardRegionValue>& regions)
3260 {
3261     m_dashboardRegions = regions;
3262     setDashboardRegionsDirty(false);
3263 }
3264 #endif
3265
3266 bool Document::setFocusedNode(PassRefPtr<Node> prpNewFocusedNode)
3267 {
3268     RefPtr<Node> newFocusedNode = prpNewFocusedNode;
3269
3270     // Make sure newFocusedNode is actually in this document
3271     if (newFocusedNode && (newFocusedNode->document() != this))
3272         return true;
3273
3274     if (m_focusedNode == newFocusedNode)
3275         return true;
3276
3277     if (m_inPageCache)
3278         return false;
3279
3280     bool focusChangeBlocked = false;
3281     RefPtr<Node> oldFocusedNode = m_focusedNode;
3282     m_focusedNode = 0;
3283
3284     // Remove focus from the existing focus node (if any)
3285     if (oldFocusedNode && !oldFocusedNode->inDetach()) {
3286         if (oldFocusedNode->active())
3287             oldFocusedNode->setActive(false);
3288
3289         oldFocusedNode->setFocus(false);
3290
3291         // Dispatch a change event for text fields or textareas that have been edited
3292         if (oldFocusedNode->isElementNode()) {
3293             Element* element = static_cast<Element*>(oldFocusedNode.get());
3294             if (element->wasChangedSinceLastFormControlChangeEvent())
3295                 element->dispatchFormControlChangeEvent();
3296         }
3297
3298         // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3299         oldFocusedNode->dispatchBlurEvent(newFocusedNode);
3300
3301         if (m_focusedNode) {
3302             // handler shifted focus
3303             focusChangeBlocked = true;
3304             newFocusedNode = 0;
3305         }
3306         
3307         oldFocusedNode->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedNode); // DOM level 3 name for the bubbling blur event.
3308         // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3309         // on it, probably when <rdar://problem/8503958> is resolved.
3310         oldFocusedNode->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedNode); // DOM level 2 name for compatibility.
3311
3312         if (m_focusedNode) {
3313             // handler shifted focus
3314             focusChangeBlocked = true;
3315             newFocusedNode = 0;
3316         }
3317         if (oldFocusedNode == this && oldFocusedNode->hasOneRef())
3318             return true;
3319             
3320         if (oldFocusedNode == oldFocusedNode->rootEditableElement())
3321             frame()->editor()->didEndEditing();
3322
3323         if (view()) {
3324             Widget* oldWidget = widgetForNode(oldFocusedNode.get());
3325             if (oldWidget)
3326                 oldWidget->setFocus(false);
3327             else
3328                 view()->setFocus(false);
3329         }
3330     }
3331
3332     if (newFocusedNode) {
3333         if (newFocusedNode == newFocusedNode->rootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
3334             // delegate blocks focus change
3335             focusChangeBlocked = true;
3336             goto SetFocusedNodeDone;
3337         }
3338         // Set focus on the new node
3339         m_focusedNode = newFocusedNode;
3340
3341         // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3342         m_focusedNode->dispatchFocusEvent(oldFocusedNode);
3343
3344         if (m_focusedNode != newFocusedNode) {
3345             // handler shifted focus
3346             focusChangeBlocked = true;
3347             goto SetFocusedNodeDone;
3348         }
3349
3350         m_focusedNode->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedNode); // DOM level 3 bubbling focus event.
3351         // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3352         // on it, probably when <rdar://problem/8503958> is m.
3353         m_focusedNode->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedNode); // DOM level 2 for compatibility.
3354
3355         if (m_focusedNode != newFocusedNode) { 
3356             // handler shifted focus
3357             focusChangeBlocked = true;
3358             goto SetFocusedNodeDone;
3359         }
3360         m_focusedNode->setFocus(true);
3361
3362         if (m_focusedNode == m_focusedNode->rootEditableElement())
3363             frame()->editor()->didBeginEditing();
3364
3365         // eww, I suck. set the qt focus correctly
3366         // ### find a better place in the code for this
3367         if (view()) {
3368             Widget* focusWidget = widgetForNode(m_focusedNode.get());
3369             if (focusWidget) {
3370                 // Make sure a widget has the right size before giving it focus.
3371                 // Otherwise, we are testing edge cases of the Widget code.
3372                 // Specifically, in WebCore this does not work well for text fields.
3373                 updateLayout();
3374                 // Re-get the widget in case updating the layout changed things.
3375                 focusWidget = widgetForNode(m_focusedNode.get());
3376             }
3377             if (focusWidget)
3378                 focusWidget->setFocus(true);
3379             else
3380                 view()->setFocus(true);
3381         }
3382     }
3383
3384 #if PLATFORM(MAC) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(CHROMIUM)
3385     if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled()) {
3386         RenderObject* oldFocusedRenderer = 0;
3387         RenderObject* newFocusedRenderer = 0;
3388
3389         if (oldFocusedNode)
3390             oldFocusedRenderer = oldFocusedNode->renderer();
3391         if (newFocusedNode)
3392             newFocusedRenderer = newFocusedNode->renderer();
3393
3394         axObjectCache()->handleFocusedUIElementChanged(oldFocusedRenderer, newFocusedRenderer);
3395     }
3396 #endif
3397     if (!focusChangeBlocked)
3398         page()->chrome()->focusedNodeChanged(m_focusedNode.get());
3399
3400 SetFocusedNodeDone:
3401     updateStyleIfNeeded();
3402     return !focusChangeBlocked;
3403 }
3404     
3405 void Document::getFocusableNodes(Vector<RefPtr<Node> >& nodes)
3406 {
3407     updateLayout();
3408
3409     for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
3410         if (node->isFocusable())
3411             nodes.append(node);
3412     }
3413 }
3414   
3415 void Document::setCSSTarget(Element* n)
3416 {
3417     if (m_cssTarget)
3418         m_cssTarget->setNeedsStyleRecalc();
3419     m_cssTarget = n;
3420     if (n)
3421         n->setNeedsStyleRecalc();
3422 }
3423
3424 void Document::attachNodeIterator(NodeIterator* ni)
3425 {
3426     m_nodeIterators.add(ni);
3427 }
3428
3429 void Document::detachNodeIterator(NodeIterator* ni)
3430 {
3431     // The node iterator can be detached without having been attached if its root node didn't have a document
3432     // when the iterator was created, but has it now.
3433     m_nodeIterators.remove(ni);
3434 }
3435
3436 void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
3437 {
3438     HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
3439     HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
3440     for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
3441         if ((*it)->root() == node) {
3442             detachNodeIterator(*it);
3443             newDocument->attachNodeIterator(*it);
3444         }
3445     }
3446 }
3447
3448 void Document::nodeChildrenChanged(ContainerNode* container)
3449 {
3450     if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3451         HashSet<Range*>::const_iterator end = m_ranges.end();
3452         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3453             (*it)->nodeChildrenChanged(container);
3454     }
3455 }
3456
3457 void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
3458 {
3459     if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3460         HashSet<Range*>::const_iterator end = m_ranges.end();
3461         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3462             (*it)->nodeChildrenWillBeRemoved(container);
3463     }
3464
3465     HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3466     for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
3467         for (Node* n = container->firstChild(); n; n = n->nextSibling())
3468             (*it)->nodeWillBeRemoved(n);
3469     }
3470
3471     if (Frame* frame = this->frame()) {
3472         for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
3473             frame->eventHandler()->nodeWillBeRemoved(n);
3474             frame->selection()->nodeWillBeRemoved(n);
3475             frame->page()->dragCaretController()->nodeWillBeRemoved(n);
3476         }
3477     }
3478 }
3479
3480 void Document::nodeWillBeRemoved(Node* n)
3481 {
3482     HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
3483     for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
3484         (*it)->nodeWillBeRemoved(n);
3485
3486     if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3487         HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
3488         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
3489             (*it)->nodeWillBeRemoved(n);
3490     }
3491
3492     if (Frame* frame = this->frame()) {
3493         frame->eventHandler()->nodeWillBeRemoved(n);
3494         frame->selection()->nodeWillBeRemoved(n);
3495         frame->page()->dragCaretController()->nodeWillBeRemoved(n);
3496     }
3497 }
3498
3499 void Document::textInserted(Node* text, unsigned offset, unsigned length)
3500 {
3501     if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3502         HashSet<Range*>::const_iterator end = m_ranges.end();
3503         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3504             (*it)->textInserted(text, offset, length);
3505     }
3506
3507     // Update the markers for spelling and grammar checking.
3508     m_markers->shiftMarkers(text, offset, length);
3509 }
3510
3511 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
3512 {
3513     if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3514         HashSet<Range*>::const_iterator end = m_ranges.end();
3515         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3516             (*it)->textRemoved(text, offset, length);
3517     }
3518
3519     // Update the markers for spelling and grammar checking.
3520     m_markers->removeMarkers(text, offset, length);
3521     m_markers->shiftMarkers(text, offset + length, 0 - length);
3522 }
3523
3524 void Document::textNodesMerged(Text* oldNode, unsigned offset)
3525 {
3526     if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3527         NodeWithIndex oldNodeWithIndex(oldNode);
3528         HashSet<Range*>::const_iterator end = m_ranges.end();
3529         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3530             (*it)->textNodesMerged(oldNodeWithIndex, offset);
3531     }
3532
3533     // FIXME: This should update markers for spelling and grammar checking.
3534 }
3535
3536 void Document::textNodeSplit(Text* oldNode)
3537 {
3538     if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
3539         HashSet<Range*>::const_iterator end = m_ranges.end();
3540         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
3541             (*it)->textNodeSplit(oldNode);
3542     }
3543
3544     // FIXME: This should update markers for spelling and grammar checking.
3545 }
3546
3547 // FIXME: eventually, this should return a DOMWindow stored in the document.
3548 DOMWindow* Document::domWindow() const
3549 {
3550     if (!frame())
3551         return 0;
3552
3553     // 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.
3554     // FIXME: We should always zero out the frame pointer on navigation to avoid accidentally accessing the new frame content.
3555     if (m_frame->document() != this)
3556         return 0;
3557
3558     return frame()->domWindow();
3559 }
3560
3561 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
3562 {
3563     DOMWindow* domWindow = this->domWindow();
3564     if (!domWindow)
3565         return;
3566     domWindow->setAttributeEventListener(eventType, listener);
3567 }
3568
3569 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
3570 {
3571     DOMWindow* domWindow = this->domWindow();
3572     if (!domWindow)
3573         return 0;
3574     return domWindow->getAttributeEventListener(eventType);
3575 }
3576
3577 void Document::dispatchWindowEvent(PassRefPtr<Event> event,  PassRefPtr<EventTarget> target)
3578 {
3579     ASSERT(!eventDispatchForbidden());
3580     DOMWindow* domWindow = this->domWindow();
3581     if (!domWindow)
3582         return;
3583     domWindow->dispatchEvent(event, target);
3584 }
3585
3586 void Document::dispatchWindowLoadEvent()
3587 {
3588     ASSERT(!eventDispatchForbidden());
3589     DOMWindow* domWindow = this->domWindow();
3590     if (!domWindow)
3591         return;
3592     domWindow->dispatchLoadEvent();
3593     m_loadEventFinished = true;
3594 }
3595
3596 void Document::enqueueWindowEvent(PassRefPtr<Event> event)
3597 {
3598     event->setTarget(domWindow());
3599     m_eventQueue->enqueueEvent(event);
3600 }
3601
3602 void Document::enqueueDocumentEvent(PassRefPtr<Event> event)
3603 {
3604     event->setTarget(this);
3605     m_eventQueue->enqueueEvent(event);
3606 }
3607
3608 PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionCode& ec)
3609 {
3610     RefPtr<Event> event = EventFactory::create(eventType);
3611     if (event)
3612         return event.release();
3613
3614     ec = NOT_SUPPORTED_ERR;
3615     return 0;
3616 }
3617
3618 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
3619 {
3620     if (eventType == eventNames().DOMSubtreeModifiedEvent)
3621         addListenerType(DOMSUBTREEMODIFIED_LISTENER);
3622     else if (eventType == eventNames().DOMNodeInsertedEvent)
3623         addListenerType(DOMNODEINSERTED_LISTENER);
3624     else if (eventType == eventNames().DOMNodeRemovedEvent)
3625         addListenerType(DOMNODEREMOVED_LISTENER);
3626     else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
3627         addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
3628     else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
3629         addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
3630     else if (eventType == eventNames().DOMAttrModifiedEvent)
3631         addListenerType(DOMATTRMODIFIED_LISTENER);
3632     else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
3633         addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
3634     else if (eventType == eventNames().overflowchangedEvent)
3635         addListenerType(OVERFLOWCHANGED_LISTENER);
3636     else if (eventType == eventNames().webkitAnimationStartEvent)
3637         addListenerType(ANIMATIONSTART_LISTENER);
3638     else if (eventType == eventNames().webkitAnimationEndEvent)
3639         addListenerType(ANIMATIONEND_LISTENER);
3640     else if (eventType == eventNames().webkitAnimationIterationEvent)
3641         addListenerType(ANIMATIONITERATION_LISTENER);
3642     else if (eventType == eventNames().webkitTransitionEndEvent)
3643         addListenerType(TRANSITIONEND_LISTENER);
3644     else if (eventType == eventNames().beforeloadEvent)
3645         addListenerType(BEFORELOAD_LISTENER);
3646 #if ENABLE(TOUCH_EVENTS)
3647     else if (eventType == eventNames().touchstartEvent
3648              || eventType == eventNames().touchmoveEvent
3649              || eventType == eventNames().touchendEvent
3650              || eventType == eventNames().touchcancelEvent) {
3651         addListenerType(TOUCH_LISTENER);
3652         if (Page* page = this->page())
3653             page->chrome()->client()->needTouchEvents(true);
3654     }
3655 #endif
3656     else if (eventType == eventNames().scrollEvent)
3657         addListenerType(SCROLL_LISTENER);
3658 }
3659
3660 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
3661 {
3662     return 0;
3663 }
3664
3665 HTMLFrameOwnerElement* Document::ownerElement() const
3666 {
3667     if (!frame())
3668         return 0;
3669     return frame()->ownerElement();
3670 }
3671
3672 String Document::cookie(ExceptionCode& ec) const
3673 {
3674     if (page() && !page()->cookieEnabled())
3675         return String();
3676
3677     // FIXME: The HTML5 DOM spec states that this attribute can raise an
3678     // INVALID_STATE_ERR exception on getting if the Document has no
3679     // browsing context.
3680
3681     if (!securityOrigin()->canAccessCookies()) {
3682         ec = SECURITY_ERR;
3683         return String();
3684     }
3685
3686     KURL cookieURL = this->cookieURL();
3687     if (cookieURL.isEmpty())
3688         return String();
3689
3690     return cookies(this, cookieURL);
3691 }
3692
3693 void Document::setCookie(const String& value, ExceptionCode& ec)
3694 {
3695     if (page() && !page()->cookieEnabled())
3696         return;
3697
3698     // FIXME: The HTML5 DOM spec states that this attribute can raise an
3699     // INVALID_STATE_ERR exception on setting if the Document has no
3700     // browsing context.
3701
3702     if (!securityOrigin()->canAccessCookies()) {
3703         ec = SECURITY_ERR;
3704         return;
3705     }
3706
3707     KURL cookieURL = this->cookieURL();
3708     if (cookieURL.isEmpty())
3709         return;
3710
3711     setCookies(this, cookieURL, value);
3712 }
3713
3714 String Document::referrer() const
3715 {
3716     if (frame())
3717         return frame()->loader()->referrer();
3718     return String();
3719 }
3720
3721 String Document::domain() const
3722 {
3723     return securityOrigin()->domain();
3724 }
3725
3726 void Document::setDomain(const String& newDomain, ExceptionCode& ec)
3727 {
3728     if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
3729         ec = SECURITY_ERR;
3730         return;
3731     }
3732
3733     // Both NS and IE specify that changing the domain is only allowed when
3734     // the new domain is a suffix of the old domain.
3735
3736     // FIXME: We should add logging indicating why a domain was not allowed.
3737
3738     // If the new domain is the same as the old domain, still call
3739     // securityOrigin()->setDomainForDOM. This will change the
3740     // security check behavior. For example, if a page loaded on port 8000
3741     // assigns its current domain using document.domain, the page will
3742     // allow other pages loaded on different ports in the same domain that
3743     // have also assigned to access this page.
3744     if (equalIgnoringCase(domain(), newDomain)) {
3745         securityOrigin()->setDomainFromDOM(newDomain);
3746         if (m_frame)
3747             m_frame->script()->updateSecurityOrigin();
3748         return;
3749     }
3750
3751     int oldLength = domain().length();
3752     int newLength = newDomain.length();
3753     // e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
3754     if (newLength >= oldLength) {
3755         ec = SECURITY_ERR;
3756         return;
3757     }
3758
3759     String test = domain();
3760     // Check that it's a subdomain, not e.g. "ebkit.org"
3761     if (test[oldLength - newLength - 1] != '.') {
3762         ec = SECURITY_ERR;
3763         return;
3764     }
3765
3766     // Now test is "webkit.org" from domain()
3767     // and we check that it's the same thing as newDomain
3768     test.remove(0, oldLength - newLength);
3769     if (test != newDomain) {
3770         ec = SECURITY_ERR;
3771         return;
3772     }
3773
3774     securityOrigin()->setDomainFromDOM(newDomain);
3775     if (m_frame)
3776         m_frame->script()->updateSecurityOrigin();
3777 }
3778
3779 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
3780 String Document::lastModified() const
3781 {
3782     DateComponents date;
3783     bool foundDate = false;
3784     if (m_frame) {
3785         String httpLastModified;
3786         if (DocumentLoader* documentLoader = loader()) 
3787             httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
3788         if (!httpLastModified.isEmpty()) {
3789             date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
3790             foundDate = true;
3791         }
3792     }
3793     // FIXME: If this document came from the file system, the HTML5
3794     // specificiation tells us to read the last modification date from the file
3795     // system.
3796     if (!foundDate)
3797         date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
3798     return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
3799 }
3800
3801 static bool isValidNameNonASCII(const UChar* characters, unsigned length)
3802 {
3803     unsigned i = 0;
3804
3805     UChar32 c;
3806     U16_NEXT(characters, i, length, c)
3807     if (!isValidNameStart(c))
3808         return false;
3809
3810     while (i < length) {
3811         U16_NEXT(characters, i, length, c)
3812         if (!isValidNamePart(c))
3813             return false;
3814     }
3815
3816     return true;
3817 }
3818
3819 static inline bool isValidNameASCII(const UChar* characters, unsigned length)
3820 {
3821     UChar c = characters[0];
3822     if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
3823         return false;
3824
3825     for (unsigned i = 1; i < length; ++i) {
3826         c = characters[i];
3827         if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
3828             return false;
3829     }
3830
3831     return true;
3832 }
3833
3834 bool Document::isValidName(const String& name)
3835 {
3836     unsigned length = name.length();
3837     if (!length)
3838         return false;
3839
3840     const UChar* characters = name.characters();
3841     return isValidNameASCII(characters, length) || isValidNameNonASCII(characters, length);
3842 }
3843
3844 bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode& ec)
3845 {
3846     unsigned length = qualifiedName.length();
3847
3848     if (!length) {
3849         ec = INVALID_CHARACTER_ERR;
3850         return false;
3851     }
3852
3853     bool nameStart = true;
3854     bool sawColon = false;
3855     int colonPos = 0;
3856
3857     const UChar* s = qualifiedName.characters();
3858     for (unsigned i = 0; i < length;) {
3859         UChar32 c;
3860         U16_NEXT(s, i, length, c)
3861         if (c == ':') {
3862             if (sawColon) {
3863                 ec = NAMESPACE_ERR;
3864                 return false; // multiple colons: not allowed
3865             }
3866             nameStart = true;
3867             sawColon = true;
3868             colonPos = i - 1;
3869         } else if (nameStart) {
3870             if (!isValidNameStart(c)) {
3871                 ec = INVALID_CHARACTER_ERR;
3872                 return false;
3873             }
3874             nameStart = false;
3875         } else {
3876             if (!isValidNamePart(c)) {
3877                 ec = INVALID_CHARACTER_ERR;
3878                 return false;
3879             }
3880         }
3881     }
3882
3883     if (!sawColon) {
3884         prefix = String();
3885         localName = qualifiedName;
3886     } else {
3887         prefix = qualifiedName.substring(0, colonPos);
3888         if (prefix.isEmpty()) {
3889             ec = NAMESPACE_ERR;
3890             return false;
3891         }
3892         localName = qualifiedName.substring(colonPos + 1);
3893     }
3894
3895     if (localName.isEmpty()) {
3896         ec = NAMESPACE_ERR;
3897         return false;
3898     }
3899
3900     return true;
3901 }
3902
3903 void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
3904 {
3905     m_decoder = decoder;
3906 }
3907
3908 KURL Document::completeURL(const String& url) const
3909 {
3910     // Always return a null URL when passed a null string.
3911     // FIXME: Should we change the KURL constructor to have this behavior?
3912     // See also [CSS]StyleSheet::completeURL(const String&)
3913     if (url.isNull())
3914         return KURL();
3915     const KURL& baseURL = ((m_baseURL.isEmpty() || m_baseURL == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : m_baseURL;
3916     if (!m_decoder)
3917         return KURL(baseURL, url);
3918     return KURL(baseURL, url, m_decoder->encoding());
3919 }
3920
3921 void Document::setInPageCache(bool flag)
3922 {
3923     if (m_inPageCache == flag)
3924         return;
3925
3926     m_inPageCache = flag;
3927
3928     FrameView* v = view();
3929     if (flag) {
3930         ASSERT(!m_savedRenderer);
3931         m_savedRenderer = renderer();
3932         if (v) {
3933             v->cacheCurrentScrollPosition();
3934             if (page() && page()->mainFrame() == m_frame)
3935                 v->resetScrollbarsAndClearContentsSize();
3936             else
3937                 v->resetScrollbars();
3938         }
3939         m_styleRecalcTimer.stop();
3940     } else {
3941         ASSERT(!renderer() || renderer() == m_savedRenderer);
3942         ASSERT(m_renderArena);
3943         setRenderer(m_savedRenderer);
3944         m_savedRenderer = 0;
3945
3946         if (frame() && frame()->page())
3947             frame()->page()->updateViewportArguments();
3948
3949         if (childNeedsStyleRecalc())
3950             scheduleStyleRecalc();
3951     }
3952 }
3953
3954 void Document::documentWillBecomeInactive() 
3955 {
3956 #if USE(ACCELERATED_COMPOSITING)
3957     if (renderer())
3958         renderView()->willMoveOffscreen();
3959 #endif
3960
3961     HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3962     for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3963         (*i)->documentWillBecomeInactive();
3964 }
3965
3966 void Document::documentDidBecomeActive() 
3967 {
3968     HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
3969     for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
3970         (*i)->documentDidBecomeActive();
3971
3972 #if USE(ACCELERATED_COMPOSITING)
3973     if (renderer())
3974         renderView()->didMoveOnscreen();
3975 #endif
3976
3977     if (FrameView* frameView = view())
3978         frameView->setAnimatorsAreActive();
3979
3980     ASSERT(m_frame);
3981     m_frame->loader()->client()->dispatchDidBecomeFrameset(isFrameSet());
3982 }
3983
3984 void Document::registerForDocumentActivationCallbacks(Element* e)
3985 {
3986     m_documentActivationCallbackElements.add(e);
3987 }
3988
3989 void Document::unregisterForDocumentActivationCallbacks(Element* e)
3990 {
3991     m_documentActivationCallbackElements.remove(e);
3992 }
3993
3994 void Document::mediaVolumeDidChange() 
3995 {
3996     HashSet<Element*>::iterator end = m_mediaVolumeCallbackElements.end();
3997     for (HashSet<Element*>::iterator i = m_mediaVolumeCallbackElements.begin(); i != end; ++i)
3998         (*i)->mediaVolumeDidChange();
3999 }
4000
4001 void Document::registerForMediaVolumeCallbacks(Element* e)
4002 {
4003     m_mediaVolumeCallbackElements.add(e);
4004 }
4005
4006 void Document::unregisterForMediaVolumeCallbacks(Element* e)
4007 {
4008     m_mediaVolumeCallbackElements.remove(e);
4009 }
4010
4011 void Document::privateBrowsingStateDidChange() 
4012 {
4013     HashSet<Element*>::iterator end = m_privateBrowsingStateChangedElements.end();
4014     for (HashSet<Element*>::iterator it = m_privateBrowsingStateChangedElements.begin(); it != end; ++it)
4015         (*it)->privateBrowsingStateDidChange();
4016 }
4017
4018 void Document::registerForPrivateBrowsingStateChangedCallbacks(Element* e)
4019 {
4020     m_privateBrowsingStateChangedElements.add(e);
4021 }
4022
4023 void Document::unregisterForPrivateBrowsingStateChangedCallbacks(Element* e)
4024 {
4025     m_privateBrowsingStateChangedElements.remove(e);
4026 }
4027
4028 void Document::setShouldCreateRenderers(bool f)
4029 {
4030     m_createRenderers = f;
4031 }
4032
4033 bool Document::shouldCreateRenderers()
4034 {
4035     return m_createRenderers;
4036 }
4037
4038 // Support for Javascript execCommand, and related methods
4039
4040 static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
4041 {
4042     Frame* frame = document->frame();
4043     if (!frame || frame->document() != document)
4044         return Editor::Command();
4045
4046     document->updateStyleIfNeeded();
4047
4048     return frame->editor()->command(commandName,
4049         userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
4050 }
4051
4052 bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
4053 {
4054     return command(this, commandName, userInterface).execute(value);
4055 }
4056
4057 bool Document::queryCommandEnabled(const String& commandName)
4058 {
4059     return command(this, commandName).isEnabled();
4060 }
4061
4062 bool Document::queryCommandIndeterm(const String& commandName)
4063 {
4064     return command(this, commandName).state() == MixedTriState;
4065 }
4066
4067 bool Document::queryCommandState(const String& commandName)
4068 {
4069     return command(this, commandName).state() == TrueTriState;
4070 }
4071
4072 bool Document::queryCommandSupported(const String& commandName)
4073 {
4074     return command(this, commandName).isSupported();
4075 }
4076
4077 String Document::queryCommandValue(const String& commandName)
4078 {
4079     return command(this, commandName).value();
4080 }
4081
4082 KURL Document::openSearchDescriptionURL()
4083 {
4084     static const char* const openSearchMIMEType = "application/opensearchdescription+xml";
4085     static const char* const openSearchRelation = "search";
4086
4087     // FIXME: Why do only top-level frames have openSearchDescriptionURLs?
4088     if (!frame() || frame()->tree()->parent())
4089         return KURL();
4090
4091     // FIXME: Why do we need to wait for FrameStateComplete?
4092     if (frame()->loader()->state() != FrameStateComplete)
4093         return KURL();
4094
4095     if (!head())
4096         return KURL();
4097
4098     RefPtr<HTMLCollection> children = head()->children();
4099     for (Node* child = children->firstItem(); child; child = children->nextItem()) {
4100         if (!child->hasTagName(linkTag))
4101             continue;
4102         HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(child);
4103         if (!equalIgnoringCase(linkElement->type(), openSearchMIMEType) || !equalIgnoringCase(linkElement->rel(), openSearchRelation))
4104             continue;
4105         if (linkElement->href().isEmpty())
4106             continue;
4107         return linkElement->href();
4108     }
4109
4110     return KURL();
4111 }
4112
4113 #if ENABLE(XSLT)
4114
4115 void Document::applyXSLTransform(ProcessingInstruction* pi)
4116 {
4117     RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
4118     processor->setXSLStyleSheet(static_cast<XSLStyleSheet*>(pi->sheet()));
4119     String resultMIMEType;
4120     String newSource;
4121     String resultEncoding;
4122     if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
4123         return;
4124     // FIXME: If the transform failed we should probably report an error (like Mozilla does).
4125     processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, frame());
4126 }
4127
4128 void Document::setTransformSource(PassOwnPtr<TransformSource> source)
4129 {
4130     m_transformSource = source;
4131 }
4132
4133 #endif
4134
4135 void Document::setDesignMode(InheritedBool value)
4136 {
4137     m_designMode = value;
4138     for (Frame* frame = m_frame; frame && frame->document(); frame = frame->tree()->traverseNext(m_frame))
4139         frame->document()->scheduleForcedStyleRecalc();
4140 }
4141
4142 Document::InheritedBool Document::getDesignMode() const
4143 {
4144     return m_designMode;
4145 }
4146
4147 bool Document::inDesignMode() const
4148 {
4149     for (const Document* d = this; d; d = d->parentDocument()) {
4150         if (d->m_designMode != inherit)
4151             return d->m_designMode;
4152     }
4153     return false;
4154 }
4155
4156 Document* Document::parentDocument() const
4157 {
4158     if (!m_frame)
4159         return 0;
4160     Frame* parent = m_frame->tree()->parent();
4161     if (!parent)
4162         return 0;
4163     return parent->document();
4164 }
4165
4166 Document* Document::topDocument() const
4167 {
4168     Document* doc = const_cast<Document *>(this);
4169     Element* element;
4170     while ((element = doc->ownerElement()))
4171         doc = element->document();
4172     
4173     return doc;
4174 }
4175
4176 PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionCode& ec)
4177 {
4178     return createAttributeNS(String(), name, ec, true);
4179 }
4180
4181 PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec, bool shouldIgnoreNamespaceChecks)
4182 {
4183     String prefix, localName;
4184     if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
4185         return 0;
4186
4187     QualifiedName qName(prefix, localName, namespaceURI);
4188     if (!shouldIgnoreNamespaceChecks && hasPrefixNamespaceMismatch(qName)) {
4189         ec = NAMESPACE_ERR;
4190         return 0;
4191     }
4192
4193     // Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrAttrNS
4194     if (!shouldIgnoreNamespaceChecks && qName.localName() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) {
4195         ec = NAMESPACE_ERR;
4196         return 0;
4197     }
4198
4199     // FIXME: Assume this is a mapped attribute, since createAttribute isn't namespace-aware.  There's no harm to XML
4200     // documents if we're wrong.
4201     return Attr::create(0, this, Attribute::createMapped(qName, StringImpl::empty()));
4202 }
4203
4204 #if ENABLE(SVG)
4205 const SVGDocumentExtensions* Document::svgExtensions()
4206 {
4207     return m_svgExtensions.get();
4208 }
4209
4210 SVGDocumentExtensions* Document::accessSVGExtensions()
4211 {
4212     if (!m_svgExtensions)
4213         m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this));
4214     return m_svgExtensions.get();
4215 }
4216
4217 bool Document::hasSVGRootNode() const
4218 {
4219     return documentElement() && documentElement()->hasTagName(SVGNames::svgTag);
4220 }
4221 #endif
4222
4223 PassRefPtr<HTMLCollection> Document::images()
4224 {
4225     return HTMLCollection::create(this, DocImages);
4226 }
4227
4228 PassRefPtr<HTMLCollection> Document::applets()
4229 {
4230     return HTMLCollection::create(this, DocApplets);
4231 }
4232
4233 PassRefPtr<HTMLCollection> Document::embeds()
4234 {
4235     return HTMLCollection::create(this, DocEmbeds);
4236 }
4237
4238 PassRefPtr<HTMLCollection> Document::plugins()
4239 {
4240     // This is an alias for embeds() required for the JS DOM bindings.
4241     return HTMLCollection::create(this, DocEmbeds);
4242 }
4243
4244 PassRefPtr<HTMLCollection> Document::objects()
4245 {
4246     return HTMLCollection::create(this, DocObjects);
4247 }
4248
4249 PassRefPtr<HTMLCollection> Document::scripts()
4250 {
4251     return HTMLCollection::create(this, DocScripts);
4252 }
4253
4254 PassRefPtr<HTMLCollection> Document::links()
4255 {
4256     return HTMLCollection::create(this, DocLinks);
4257 }
4258
4259 PassRefPtr<HTMLCollection> Document::forms()
4260 {
4261     return HTMLCollection::create(this, DocForms);
4262 }
4263
4264 PassRefPtr<HTMLCollection> Document::anchors()
4265 {
4266     return HTMLCollection::create(this, DocAnchors);
4267 }
4268
4269 PassRefPtr<HTMLAllCollection> Document::all()
4270 {
4271     return HTMLAllCollection::create(this);
4272 }
4273
4274 PassRefPtr<HTMLCollection> Document::windowNamedItems(const String &name)
4275 {
4276     return HTMLNameCollection::create(this, WindowNamedItems, name);
4277 }
4278
4279 PassRefPtr<HTMLCollection> Document::documentNamedItems(const String &name)
4280 {
4281     return HTMLNameCollection::create(this, DocumentNamedItems, name);
4282 }
4283
4284 CollectionCache* Document::nameCollectionInfo(CollectionType type, const AtomicString& name)
4285 {
4286     ASSERT(type >= FirstNamedDocumentCachedType);
4287     unsigned index = type - FirstNamedDocumentCachedType;
4288     ASSERT(index < NumNamedDocumentCachedTypes);
4289
4290     NamedCollectionMap& map = m_nameCollectionInfo[index];
4291     NamedCollectionMap::iterator iter = map.find(name.impl());
4292     if (iter == map.end())
4293         iter = map.add(name.impl(), new CollectionCache).first;
4294     iter->second->checkConsistency();
4295     return iter->second;
4296 }
4297
4298 void Document::finishedParsing()
4299 {
4300     ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
4301     ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
4302     setParsing(false);
4303     if (!m_documentTiming.domContentLoadedEventStart)
4304         m_documentTiming.domContentLoadedEventStart = currentTime();
4305     dispatchEvent(Event::create(eventNames().DOMContentLoadedEvent, true, false));
4306     if (!m_documentTiming.domContentLoadedEventEnd)
4307         m_documentTiming.domContentLoadedEventEnd = currentTime();
4308
4309     if (RefPtr<Frame> f = frame()) {
4310         // FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
4311         // resource loads are complete. HTMLObjectElements can start loading their resources from
4312         // post attach callbacks triggered by recalcStyle().  This means if we parse out an <object>
4313         // tag and then reach the end of the document without updating styles, we might not have yet
4314         // started the resource load and might fire the window load event too early.  To avoid this
4315         // we force the styles to be up to date before calling FrameLoader::finishedParsing().
4316         // See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
4317         updateStyleIfNeeded();
4318
4319         f->loader()->finishedParsing();
4320
4321         InspectorInstrumentation::domContentLoadedEventFired(f.get());
4322     }
4323 }
4324
4325 Vector<String> Document::formElementsState() const
4326 {
4327     Vector<String> stateVector;
4328     stateVector.reserveInitialCapacity(m_formElementsWithState.size() * 3);
4329     typedef FormElementListHashSet::const_iterator Iterator;
4330     Iterator end = m_formElementsWithState.end();
4331     for (Iterator it = m_formElementsWithState.begin(); it != end; ++it) {
4332         Element* elementWithState = *it;
4333         String value;
4334         if (!elementWithState->shouldSaveAndRestoreFormControlState())
4335             continue;
4336         if (!elementWithState->saveFormControlState(value))
4337             continue;
4338         stateVector.append(elementWithState->formControlName().string());
4339         stateVector.append(elementWithState->formControlType().string());
4340         stateVector.append(value);
4341     }
4342     return stateVector;
4343 }
4344
4345 PassRefPtr<XPathExpression> Document::createExpression(const String& expression,
4346                                                        XPathNSResolver* resolver,
4347                                                        ExceptionCode& ec)
4348 {
4349     if (!m_xpathEvaluator)
4350         m_xpathEvaluator = XPathEvaluator::create();
4351     return m_xpathEvaluator->createExpression(expression, resolver, ec);
4352 }
4353
4354 PassRefPtr<XPathNSResolver> Document::createNSResolver(Node* nodeResolver)
4355 {
4356     if (!m_xpathEvaluator)
4357         m_xpathEvaluator = XPathEvaluator::create();
4358     return m_xpathEvaluator->createNSResolver(nodeResolver);
4359 }
4360
4361 PassRefPtr<XPathResult> Document::evaluate(const String& expression,
4362                                            Node* contextNode,
4363                                            XPathNSResolver* resolver,
4364                                            unsigned short type,
4365                                            XPathResult* result,
4366                                            ExceptionCode& ec)
4367 {
4368     if (!m_xpathEvaluator)
4369         m_xpathEvaluator = XPathEvaluator::create();
4370     return m_xpathEvaluator->evaluate(expression, contextNode, resolver, type, result, ec);
4371 }
4372
4373 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
4374 {
4375     // Walk the state vector backwards so that the value to use for each
4376     // name/type pair first is the one at the end of each individual vector
4377     // in the FormElementStateMap. We're using them like stacks.
4378     typedef FormElementStateMap::iterator Iterator;
4379     m_formElementsWithState.clear();
4380     for (size_t i = stateVector.size() / 3 * 3; i; i -= 3) {
4381         AtomicString a = stateVector[i - 3];
4382         AtomicString b = stateVector[i - 2];
4383         const String& c = stateVector[i - 1];
4384         FormElementKey key(a.impl(), b.impl());
4385         Iterator it = m_stateForNewFormElements.find(key);
4386         if (it != m_stateForNewFormElements.end())
4387             it->second.append(c);
4388         else {
4389             Vector<String> v(1);
4390             v[0] = c;
4391             m_stateForNewFormElements.set(key, v);
4392         }
4393     }
4394 }
4395
4396 bool Document::hasStateForNewFormElements() const
4397 {
4398     return !m_stateForNewFormElements.isEmpty();
4399 }
4400
4401 bool Document::takeStateForFormElement(AtomicStringImpl* name, AtomicStringImpl* type, String& state)
4402 {
4403     typedef FormElementStateMap::iterator Iterator;
4404     Iterator it = m_stateForNewFormElements.find(FormElementKey(name, type));
4405     if (it == m_stateForNewFormElements.end())
4406         return false;
4407     ASSERT(it->second.size());
4408     state = it->second.last();
4409     if (it->second.size() > 1)
4410         it->second.removeLast();
4411     else
4412         m_stateForNewFormElements.remove(it);
4413     return true;
4414 }
4415
4416 FormElementKey::FormElementKey(AtomicStringImpl* name, AtomicStringImpl* type)
4417     : m_name(name), m_type(type)
4418 {
4419     ref();
4420 }
4421
4422 FormElementKey::~FormElementKey()
4423 {
4424     deref();
4425 }
4426
4427 FormElementKey::FormElementKey(const FormElementKey& other)
4428     : m_name(other.name()), m_type(other.type())
4429 {
4430     ref();
4431 }
4432
4433 FormElementKey& FormElementKey::operator=(const FormElementKey& other)
4434 {
4435     other.ref();
4436     deref();
4437     m_name = other.name();
4438     m_type = other.type();
4439     return *this;
4440 }
4441
4442 void FormElementKey::ref() const
4443 {
4444     if (name())
4445         name()->ref();
4446     if (type())
4447         type()->ref();
4448 }
4449
4450 void FormElementKey::deref() const
4451 {
4452     if (name())
4453         name()->deref();
4454     if (type())
4455         type()->deref();
4456 }
4457
4458 unsigned FormElementKeyHash::hash(const FormElementKey& key)
4459 {
4460     return StringHasher::hashMemory<sizeof(FormElementKey)>(&key);
4461 }
4462
4463 const Vector<IconURL>& Document::iconURLs() const
4464 {
4465     return m_iconURLs;
4466 }
4467
4468 void Document::addIconURL(const String& url, const String& mimeType, const String& sizes, IconType iconType)
4469 {
4470     if (url.isEmpty())
4471         return;
4472
4473     // FIXME - <rdar://problem/4727645> - At some point in the future, we might actually honor the "mimeType"
4474     IconURL newURL(KURL(ParsedURLString, url), sizes, mimeType, iconType);
4475     m_iconURLs.append(newURL);
4476
4477     if (Frame* f = frame()) {
4478         IconURL iconURL = f->loader()->icon()->iconURL(iconType);
4479         if (iconURL == newURL)
4480             f->loader()->didChangeIcons(iconType);
4481     }
4482 }
4483
4484 void Document::registerFormElementWithFormAttribute(FormAssociatedElement* element)
4485 {
4486     ASSERT(toHTMLElement(element)->fastHasAttribute(formAttr));
4487     m_formElementsWithFormAttribute.add(element);
4488 }
4489
4490 void Document::unregisterFormElementWithFormAttribute(FormAssociatedElement* element)
4491 {
4492     m_formElementsWithFormAttribute.remove(element);
4493 }
4494
4495 void Document::resetFormElementsOwner()
4496 {
4497     typedef FormAssociatedElementListHashSet::iterator Iterator;
4498     Iterator end = m_formElementsWithFormAttribute.end();
4499     for (Iterator it = m_formElementsWithFormAttribute.begin(); it != end; ++it)
4500         (*it)->resetFormOwner();
4501 }
4502
4503 void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
4504 {
4505     if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
4506         return;
4507         
4508     m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
4509     m_frame->selection()->updateSecureKeyboardEntryIfActive();
4510 }
4511
4512 bool Document::useSecureKeyboardEntryWhenActive() const
4513 {
4514     return m_useSecureKeyboardEntryWhenActive;
4515 }
4516
4517 void Document::initSecurityContext()
4518 {
4519     if (haveInitializedSecurityOrigin()) {
4520         ASSERT(securityOrigin());
4521         return;
4522     }
4523
4524     if (!m_frame) {
4525         // No source for a security context.
4526         // This can occur via document.implementation.createDocument().
4527         m_cookieURL = KURL(ParsedURLString, "");
4528         setSecurityOrigin(SecurityOrigin::createUnique());
4529         setContentSecurityPolicy(ContentSecurityPolicy::create(this));
4530         return;
4531     }
4532
4533     // In the common case, create the security context from the currently
4534     // loading URL with a fresh content security policy.
4535     m_cookieURL = m_url;
4536     enforceSandboxFlags(m_frame->loader()->effectiveSandboxFlags());
4537     setSecurityOrigin(isSandboxed(SandboxOrigin) ? SecurityOrigin::createUnique() : SecurityOrigin::create(m_url));
4538     setContentSecurityPolicy(ContentSecurityPolicy::create(this));
4539
4540     if (SecurityPolicy::allowSubstituteDataAccessToLocal()) {
4541         // If this document was loaded with substituteData, then the document can
4542         // load local resources.  See https://bugs.webkit.org/show_bug.cgi?id=16756
4543         // and https://bugs.webkit.org/show_bug.cgi?id=19760 for further
4544         // discussion.
4545         
4546         DocumentLoader* documentLoader = loader();
4547         if (documentLoader && documentLoader->substituteData().isValid())
4548             securityOrigin()->grantLoadLocalResources();
4549     }
4550
4551     if (Settings* settings = this->settings()) {
4552         if (!settings->isWebSecurityEnabled()) {
4553           // Web security is turned off.  We should let this document access every
4554           // other document.  This is used primary by testing harnesses for web
4555           // sites.
4556           securityOrigin()->grantUniversalAccess();
4557
4558         } else if (settings->allowUniversalAccessFromFileURLs() && securityOrigin()->isLocal()) {
4559           // Some clients want file:// URLs to have universal access, but that
4560           // setting is dangerous for other clients.
4561           securityOrigin()->grantUniversalAccess();
4562         } else if (!settings->allowFileAccessFromFileURLs() && securityOrigin()->isLocal()) {
4563           // Some clients want file:// URLs to have even tighter restrictions by
4564           // default, and not be able to access other local files.
4565           securityOrigin()->enforceFilePathSeparation();
4566         }
4567     }
4568
4569     if (!shouldInheritSecurityOriginFromOwner(m_url))
4570         return;
4571
4572     // If we do not obtain a meaningful origin from the URL, then we try to
4573     // find one via the frame hierarchy.
4574
4575     Frame* ownerFrame = m_frame->tree()->parent();
4576     if (!ownerFrame)
4577         ownerFrame = m_frame->loader()->opener();
4578
4579     if (!ownerFrame) {
4580         didFailToInitializeSecurityOrigin();
4581         return;
4582     }
4583
4584     m_cookieURL = ownerFrame->document()->cookieURL();
4585     // We alias the SecurityOrigins to match Firefox, see Bug 15313
4586     // https://bugs.webkit.org/show_bug.cgi?id=15313
4587     setSecurityOrigin(ownerFrame->document()->securityOrigin());
4588     setContentSecurityPolicy(ownerFrame->document()->contentSecurityPolicy());
4589 }
4590
4591 void Document::setSecurityOrigin(PassRefPtr<SecurityOrigin> origin)
4592 {
4593     SecurityContext::setSecurityOrigin(origin);
4594 }
4595
4596 #if ENABLE(SQL_DATABASE)
4597
4598 bool Document::allowDatabaseAccess() const
4599 {
4600     if (!page() || (page()->settings()->privateBrowsingEnabled() && !SchemeRegistry::allowsDatabaseAccessInPrivateBrowsing(securityOrigin()->protocol())))
4601         return false;
4602     return true;
4603 }
4604
4605 void Document::databaseExceededQuota(const String& name)
4606 {
4607     Page* currentPage = page();
4608     if (currentPage)
4609         currentPage->chrome()->client()->exceededDatabaseQuota(document()->frame(), name);
4610 }
4611
4612 #endif
4613
4614 bool Document::isContextThread() const
4615 {
4616     return isMainThread();
4617 }
4618
4619 void Document::updateURLForPushOrReplaceState(const KURL& url)
4620 {
4621     Frame* f = frame();
4622     if (!f)
4623         return;
4624
4625     setURL(url);
4626     f->loader()->setOutgoingReferrer(url);
4627
4628     if (DocumentLoader* documentLoader = loader())
4629         documentLoader->replaceRequestURLForSameDocumentNavigation(url);
4630 }
4631
4632 void Document::statePopped(SerializedScriptValue* stateObject)
4633 {
4634     if (!frame())
4635         return;
4636     
4637     // Per step 11 of section 6.5.9 (history traversal) of the HTML5 spec, we 
4638     // defer firing of popstate until we're in the complete state.
4639     if (m_readyState == Complete)
4640         enqueuePopstateEvent(stateObject);
4641     else
4642         m_pendingStateObject = stateObject;
4643 }
4644
4645 void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
4646 {
4647     m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
4648     if (!m_updateFocusAppearanceTimer.isActive())
4649         m_updateFocusAppearanceTimer.startOneShot(0);
4650 }
4651
4652 void Document::cancelFocusAppearanceUpdate()
4653 {
4654     m_updateFocusAppearanceTimer.stop();
4655 }
4656
4657 void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
4658 {
4659     Node* node = focusedNode();
4660     if (!node)
4661         return;
4662     if (!node->isElementNode())
4663         return;
4664
4665     updateLayout();
4666
4667     Element* element = static_cast<Element*>(node);
4668     if (element->isFocusable())
4669         element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
4670 }
4671
4672 // FF method for accessing the selection added for compatibility.
4673 DOMSelection* Document::getSelection() const
4674 {
4675     return frame() ? frame()->domWindow()->getSelection() : 0;
4676 }
4677
4678 void Document::attachRange(Range* range)
4679 {
4680     ASSERT(!m_ranges.contains(range));
4681     m_ranges.add(range);
4682 }
4683
4684 void Document::detachRange(Range* range)
4685 {
4686     // We don't ASSERT m_ranges.contains(range) to allow us to call this
4687     // unconditionally to fix: https://bugs.webkit.org/show_bug.cgi?id=26044
4688     m_ranges.remove(range);
4689 }
4690
4691 CanvasRenderingContext* Document::getCSSCanvasContext(const String& type, const String& name, int width, int height)
4692 {
4693     HTMLCanvasElement* result = getCSSCanvasElement(name);
4694     if (!result)
4695         return 0;
4696     result->setSize(IntSize(width, height));
4697     return result->getContext(type);
4698 }
4699
4700 HTMLCanvasElement* Document::getCSSCanvasElement(const String& name)
4701 {
4702     RefPtr<HTMLCanvasElement> result = m_cssCanvasElements.get(name).get();
4703     if (!result) {
4704         result = HTMLCanvasElement::create(this);
4705         m_cssCanvasElements.set(name, result);
4706     }
4707     return result.get();
4708 }
4709
4710 void Document::initDNSPrefetch()
4711 {
4712     Settings* settings = this->settings();
4713
4714     m_haveExplicitlyDisabledDNSPrefetch = false;
4715     m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
4716
4717     // Inherit DNS prefetch opt-out from parent frame    
4718     if (Document* parent = parentDocument()) {
4719         if (!parent->isDNSPrefetchEnabled())
4720             m_isDNSPrefetchEnabled = false;
4721     }
4722 }
4723
4724 void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
4725 {
4726     if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
4727         m_isDNSPrefetchEnabled = true;
4728         return;
4729     }
4730
4731     m_isDNSPrefetchEnabled = false;
4732     m_haveExplicitlyDisabledDNSPrefetch = true;
4733 }
4734
4735 void Document::addMessage(MessageSource source, MessageType type, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack)
4736 {
4737     if (!isContextThread()) {
4738         postTask(AddConsoleMessageTask::create(source, type, level, message));
4739         return;
4740     }
4741
4742     if (DOMWindow* window = domWindow())
4743         window->console()->addMessage(source, type, level, message, lineNumber, sourceURL, callStack);
4744 }
4745
4746 struct PerformTaskContext {
4747     WTF_MAKE_NONCOPYABLE(PerformTaskContext); WTF_MAKE_FAST_ALLOCATED;
4748 public:
4749     PerformTaskContext(PassRefPtr<DocumentWeakReference> documentReference, PassOwnPtr<ScriptExecutionContext::Task> task)
4750         : documentReference(documentReference)
4751         , task(task)
4752     {
4753     }
4754
4755     RefPtr<DocumentWeakReference> documentReference;
4756     OwnPtr<ScriptExecutionContext::Task> task;
4757 };
4758
4759 static void performTask(void* ctx)
4760 {
4761     ASSERT(isMainThread());
4762
4763     PerformTaskContext* context = reinterpret_cast<PerformTaskContext*>(ctx);
4764     ASSERT(context);
4765
4766     if (Document* document = context->documentReference->document())
4767         context->task->performTask(document);
4768
4769     delete context;
4770 }
4771
4772 void Document::postTask(PassOwnPtr<Task> task)
4773 {
4774     callOnMainThread(performTask, new PerformTaskContext(m_weakReference, task));
4775 }
4776
4777 void Document::suspendScriptedAnimationControllerCallbacks()
4778 {
4779 #if ENABLE(REQUEST_ANIMATION_FRAME)
4780     if (m_scriptedAnimationController)
4781         m_scriptedAnimationController->suspend();
4782 #endif
4783 }
4784
4785 void Document::resumeScriptedAnimationControllerCallbacks()
4786 {
4787 #if ENABLE(REQUEST_ANIMATION_FRAME)
4788     if (m_scriptedAnimationController)
4789         m_scriptedAnimationController->resume();
4790 #endif
4791 }
4792
4793 void Document::windowScreenDidChange(PlatformDisplayID displayID)
4794 {
4795 #if ENABLE(REQUEST_ANIMATION_FRAME)
4796     if (m_scriptedAnimationController)
4797         m_scriptedAnimationController->windowScreenDidChange(displayID);
4798 #endif
4799 }
4800
4801
4802 String Document::displayStringModifiedByEncoding(const String& str) const
4803 {
4804     if (m_decoder)
4805         return m_decoder->encoding().displayString(str.impl());
4806     return str;
4807 }
4808
4809 PassRefPtr<StringImpl> Document::displayStringModifiedByEncoding(PassRefPtr<StringImpl> str) const
4810 {
4811     if (m_decoder)
4812         return m_decoder->encoding().displayString(str);
4813     return str;
4814 }
4815
4816 void Document::displayBufferModifiedByEncoding(UChar* buffer, unsigned len) const
4817 {
4818     if (m_decoder)
4819         m_decoder->encoding().displayBuffer(buffer, len);
4820 }
4821
4822 void Document::enqueuePageshowEvent(PageshowEventPersistence persisted)
4823 {
4824     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36334 Pageshow event needs to fire asynchronously.
4825     dispatchWindowEvent(PageTransitionEvent::create(eventNames().pageshowEvent, persisted), this);
4826 }
4827
4828 void Document::enqueueHashchangeEvent(const String& oldURL, const String& newURL)
4829 {
4830     enqueueWindowEvent(HashChangeEvent::create(oldURL, newURL));
4831 }
4832
4833 void Document::enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject)
4834 {
4835     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36202 Popstate event needs to fire asynchronously
4836     dispatchWindowEvent(PopStateEvent::create(stateObject));
4837 }
4838
4839 void Document::addMediaCanStartListener(MediaCanStartListener* listener)
4840 {
4841     ASSERT(!m_mediaCanStartListeners.contains(listener));
4842     m_mediaCanStartListeners.add(listener);
4843 }
4844
4845 void Document::removeMediaCanStartListener(MediaCanStartListener* listener)
4846 {
4847     ASSERT(m_mediaCanStartListeners.contains(listener));
4848     m_mediaCanStartListeners.remove(listener);
4849 }
4850
4851 MediaCanStartListener* Document::takeAnyMediaCanStartListener()
4852 {
4853     HashSet<MediaCanStartListener*>::iterator slot = m_mediaCanStartListeners.begin();
4854     if (slot == m_mediaCanStartListeners.end())
4855         return 0;
4856     MediaCanStartListener* listener = *slot;
4857     m_mediaCanStartListeners.remove(slot);
4858     return listener;
4859 }
4860
4861 #if ENABLE(FULLSCREEN_API)
4862 bool Document::fullScreenIsAllowedForElement(Element* element) const
4863 {
4864     ASSERT(element);
4865     while (HTMLFrameOwnerElement* ownerElement = element->document()->ownerElement()) {
4866         if (!ownerElement->isFrameElementBase())
4867             continue;
4868
4869         if (!static_cast<HTMLFrameElementBase*>(ownerElement)->allowFullScreen())
4870             return false;
4871         element = ownerElement;
4872     }
4873     return true;
4874 }
4875
4876 void Document::requestFullScreenForElement(Element* element, unsigned short flags, FullScreenCheckType checkType)
4877 {
4878     if (!page() || !page()->settings()->fullScreenEnabled())
4879         return;
4880
4881     if (!element)
4882         element = documentElement();
4883     
4884     if (checkType == EnforceIFrameAllowFulScreenRequirement && !fullScreenIsAllowedForElement(element))
4885         return;
4886     
4887     if (!ScriptController::processingUserGesture())
4888         return;
4889     
4890     if (!page()->chrome()->client()->supportsFullScreenForElement(element, flags & Element::ALLOW_KEYBOARD_INPUT))
4891         return;
4892     
4893     m_areKeysEnabledInFullScreen = flags & Element::ALLOW_KEYBOARD_INPUT;
4894     page()->chrome()->client()->enterFullScreenForElement(element);
4895 }
4896
4897 void Document::webkitCancelFullScreen()
4898 {
4899     if (!page() || !m_fullScreenElement)
4900         return;
4901     
4902     page()->chrome()->client()->exitFullScreenForElement(m_fullScreenElement.get());
4903 }
4904
4905 void Document::webkitWillEnterFullScreenForElement(Element* element)
4906 {
4907     ASSERT(element);
4908     ASSERT(page() && page()->settings()->fullScreenEnabled());
4909
4910     if (m_fullScreenRenderer)
4911         m_fullScreenRenderer->unwrapRenderer();
4912
4913     m_fullScreenElement = element;
4914
4915     // Create a placeholder block for a the full-screen element, to keep the page from reflowing
4916     // when the element is removed from the normal flow.  Only do this for a RenderBox, as only 
4917     // a box will have a frameRect.  The placeholder will be created in setFullScreenRenderer()
4918     // during layout.
4919     RenderObject* renderer = m_fullScreenElement->renderer();
4920     bool shouldCreatePlaceholder = renderer && renderer->isBox();
4921     if (shouldCreatePlaceholder) {
4922         m_savedPlaceholderFrameRect = toRenderBox(renderer)->frameRect();
4923         m_savedPlaceholderRenderStyle = RenderStyle::clone(renderer->style());
4924     }
4925
4926     if (m_fullScreenElement != documentElement())
4927         RenderFullScreen::wrapRenderer(renderer, this);
4928
4929     m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
4930     
4931     recalcStyle(Force);
4932     
4933     if (m_fullScreenRenderer) {
4934         setAnimatingFullScreen(true);
4935 #if USE(ACCELERATED_COMPOSITING)
4936         view()->updateCompositingLayers();
4937         if (m_fullScreenRenderer->layer() && m_fullScreenRenderer->layer()->isComposited())
4938             page()->chrome()->client()->setRootFullScreenLayer(m_fullScreenRenderer->layer()->backing()->graphicsLayer());
4939 #endif
4940     }
4941 }
4942     
4943 void Document::webkitDidEnterFullScreenForElement(Element*)
4944 {
4945     m_fullScreenElement->didBecomeFullscreenElement();
4946
4947     if (m_fullScreenRenderer) {
4948         setAnimatingFullScreen(false);
4949 #if USE(ACCELERATED_COMPOSITING)
4950         view()->updateCompositingLayers();
4951         page()->chrome()->client()->setRootFullScreenLayer(0);
4952 #endif
4953     }
4954     m_fullScreenChangeEventTargetQueue.append(m_fullScreenElement);
4955     m_fullScreenChangeDelayTimer.startOneShot(0);
4956 }
4957
4958 void Document::webkitWillExitFullScreenForElement(Element*)
4959 {
4960     m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
4961     
4962     m_fullScreenElement->willStopBeingFullscreenElement();
4963
4964     if (m_fullScreenRenderer) {
4965         setAnimatingFullScreen(true);
4966 #if USE(ACCELERATED_COMPOSITING)
4967         view()->updateCompositingLayers();
4968         if (m_fullScreenRenderer->layer() && m_fullScreenRenderer->layer()->isComposited())
4969             page()->chrome()->client()->setRootFullScreenLayer(m_fullScreenRenderer->layer()->backing()->graphicsLayer());
4970 #endif
4971     }
4972 }
4973
4974 void Document::webkitDidExitFullScreenForElement(Element*)
4975 {
4976     m_areKeysEnabledInFullScreen = false;
4977     setAnimatingFullScreen(false);
4978     
4979     if (m_fullScreenRenderer)
4980         m_fullScreenRenderer->unwrapRenderer();
4981
4982     m_fullScreenChangeEventTargetQueue.append(m_fullScreenElement.release());
4983 #if USE(ACCELERATED_COMPOSITING)
4984     page()->chrome()->client()->setRootFullScreenLayer(0);
4985 #endif
4986     scheduleForcedStyleRecalc();
4987     
4988     m_fullScreenChangeDelayTimer.startOneShot(0);
4989 }
4990     
4991 void Document::setFullScreenRenderer(RenderFullScreen* renderer)
4992 {
4993     if (renderer == m_fullScreenRenderer)
4994         return;
4995
4996     if (renderer && m_savedPlaceholderRenderStyle) 
4997         renderer->createPlaceholder(m_savedPlaceholderRenderStyle.release(), m_savedPlaceholderFrameRect);
4998     else if (renderer && m_fullScreenRenderer && m_fullScreenRenderer->placeholder()) {
4999         RenderBlock* placeholder = m_fullScreenRenderer->placeholder();
5000         renderer->createPlaceholder(RenderStyle::clone(placeholder->style()), placeholder->frameRect());
5001     }
5002
5003     if (m_fullScreenRenderer)
5004         m_fullScreenRenderer->destroy();
5005     ASSERT(!m_fullScreenRenderer);
5006
5007     m_fullScreenRenderer = renderer;
5008     
5009     // This notification can come in after the page has been destroyed.
5010     if (page())
5011         page()->chrome()->client()->fullScreenRendererChanged(m_fullScreenRenderer);
5012 }
5013
5014 void Document::fullScreenRendererDestroyed()
5015 {
5016     m_fullScreenRenderer = 0;
5017
5018     if (page())
5019         page()->chrome()->client()->fullScreenRendererChanged(0);
5020 }
5021
5022 void Document::setFullScreenRendererSize(const IntSize& size)
5023 {
5024     ASSERT(m_fullScreenRenderer);
5025     if (!m_fullScreenRenderer)
5026         return;
5027     
5028     if (m_fullScreenRenderer) {
5029         RefPtr<RenderStyle> newStyle = RenderStyle::clone(m_fullScreenRenderer->style());
5030         newStyle->setWidth(Length(size.width(), WebCore::Fixed));
5031         newStyle->setHeight(Length(size.height(), WebCore::Fixed));
5032         newStyle->setTop(Length(0, WebCore::Fixed));
5033         newStyle->setLeft(Length(0, WebCore::Fixed));
5034         m_fullScreenRenderer->setStyle(newStyle);
5035         updateLayout();
5036     }
5037 }
5038     
5039 void Document::setFullScreenRendererBackgroundColor(Color backgroundColor)
5040 {
5041     if (!m_fullScreenRenderer)
5042         return;
5043     
5044     RefPtr<RenderStyle> newStyle = RenderStyle::clone(m_fullScreenRenderer->style());
5045     newStyle->setBackgroundColor(backgroundColor);
5046     m_fullScreenRenderer->setStyle(newStyle);
5047 }
5048     
5049 void Document::fullScreenChangeDelayTimerFired(Timer<Document>*)
5050 {
5051     while (!m_fullScreenChangeEventTargetQueue.isEmpty()) {
5052         RefPtr<Element> element = m_fullScreenChangeEventTargetQueue.takeFirst();
5053         if (!element)
5054             element = documentElement();
5055
5056         // If the element was removed from our tree, also message the documentElement.
5057         if (!contains(element.get()))
5058             m_fullScreenChangeEventTargetQueue.append(documentElement());
5059         
5060         element->dispatchEvent(Event::create(eventNames().webkitfullscreenchangeEvent, true, false));
5061     }
5062 }
5063
5064 void Document::fullScreenElementRemoved()
5065 {
5066     m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
5067     webkitCancelFullScreen();
5068 }
5069
5070 void Document::removeFullScreenElementOfSubtree(Node* node, bool amongChildrenOnly)
5071 {
5072     if (!m_fullScreenElement)
5073         return;
5074     
5075     bool elementInSubtree = false;
5076     if (amongChildrenOnly)
5077         elementInSubtree = m_fullScreenElement->isDescendantOf(node);
5078     else
5079         elementInSubtree = (m_fullScreenElement == node) || m_fullScreenElement->isDescendantOf(node);
5080     
5081     if (elementInSubtree)
5082         fullScreenElementRemoved();
5083 }
5084
5085 bool Document::isAnimatingFullScreen() const
5086 {
5087     return m_isAnimatingFullScreen;
5088 }
5089
5090 void Document::setAnimatingFullScreen(bool flag)
5091 {
5092     if (m_isAnimatingFullScreen == flag)
5093         return;
5094     m_isAnimatingFullScreen = flag;
5095
5096     if (m_fullScreenElement && m_fullScreenElement->isDescendantOf(this)) {
5097         m_fullScreenElement->setNeedsStyleRecalc();
5098         scheduleForcedStyleRecalc();
5099     }
5100
5101 #if USE(ACCELERATED_COMPOSITING)
5102     if (m_fullScreenRenderer && m_fullScreenRenderer->layer()) {
5103         m_fullScreenRenderer->layer()->contentChanged(RenderLayer::FullScreenChanged);
5104         // Clearing the layer's backing will force the compositor to reparent
5105         // the layer the next time layers are synchronized.
5106         m_fullScreenRenderer->layer()->clearBacking();
5107     }
5108 #endif
5109 }
5110 #endif
5111
5112 void Document::decrementLoadEventDelayCount()
5113 {
5114     ASSERT(m_loadEventDelayCount);
5115     --m_loadEventDelayCount;
5116
5117     if (frame() && !m_loadEventDelayCount && !m_loadEventDelayTimer.isActive())
5118         m_loadEventDelayTimer.startOneShot(0);
5119 }
5120
5121 void Document::loadEventDelayTimerFired(Timer<Document>*)
5122 {
5123     if (frame())
5124         frame()->loader()->checkCompleted();
5125 }
5126
5127 #if ENABLE(REQUEST_ANIMATION_FRAME)
5128 int Document::webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback, Element* animationElement)
5129 {
5130     if (!m_scriptedAnimationController)
5131         m_scriptedAnimationController = ScriptedAnimationController::create(this, page()->displayID());
5132
5133     return m_scriptedAnimationController->registerCallback(callback, animationElement);
5134 }
5135
5136 void Document::webkitCancelRequestAnimationFrame(int id)
5137 {
5138     if (!m_scriptedAnimationController)
5139         return;
5140     m_scriptedAnimationController->cancelCallback(id);
5141 }
5142
5143 void Document::serviceScriptedAnimations(DOMTimeStamp time)
5144 {
5145     if (!m_scriptedAnimationController)
5146         return;
5147     m_scriptedAnimationController->serviceScriptedAnimations(time);
5148 }
5149 #endif
5150
5151 #if ENABLE(TOUCH_EVENTS)
5152 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
5153 {
5154     // FIXME: It's not clear from the documentation at
5155     // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html
5156     // 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
5157     // and implement them here. See https://bugs.webkit.org/show_bug.cgi?id=47819
5158     // Ditto for the createTouchList method below.
5159     Frame* frame = window ? window->frame() : this->frame();
5160     return Touch::create(frame, target, identifier, screenX, screenY, pageX, pageY, radiusX, radiusY, rotationAngle, force);
5161 }
5162
5163 PassRefPtr<TouchList> Document::createTouchList(ExceptionCode&) const
5164 {
5165     return TouchList::create();
5166 }
5167 #endif
5168
5169 void Document::didAddWheelEventHandler()
5170 {
5171     ++m_wheelEventHandlerCount;
5172     Frame* mainFrame = page() ? page()->mainFrame() : 0;
5173     if (mainFrame)
5174         mainFrame->notifyChromeClientWheelEventHandlerCountChanged();
5175 }
5176
5177 void Document::didRemoveWheelEventHandler()
5178 {
5179     ASSERT(m_wheelEventHandlerCount > 0);
5180     --m_wheelEventHandlerCount;
5181     Frame* mainFrame = page() ? page()->mainFrame() : 0;
5182     if (mainFrame)
5183         mainFrame->notifyChromeClientWheelEventHandlerCountChanged();
5184 }
5185
5186 bool Document::visualUpdatesAllowed() const
5187 {
5188     return !settings()
5189         || !settings()->suppressIncrementalRendering()
5190         || loadEventFinished();
5191 }
5192
5193 DocumentLoader* Document::loader() const
5194 {
5195     if (!m_frame)
5196         return 0;
5197     
5198     DocumentLoader* loader = m_frame->loader()->documentLoader();
5199     if (!loader)
5200         return 0;
5201     
5202     if (m_frame->document() != this)
5203         return 0;
5204     
5205     return loader;
5206 }
5207
5208 #if ENABLE(MICRODATA)
5209 PassRefPtr<NodeList> Document::getItems(const String& typeNames)
5210 {
5211     NodeRareData* data = ensureRareData();
5212     if (!data->nodeLists()) {
5213         data->setNodeLists(NodeListsNodeData::create());
5214         treeScope()->addNodeListCache();
5215     }
5216
5217     // Since documet.getItem() is allowed for microdata, typeNames will be null string.
5218     // In this case we need to create an unique string identifier to map such request in the cache.
5219     String localTypeNames = typeNames.isNull() ? String("http://webkit.org/microdata/undefinedItemType") : typeNames;
5220
5221     pair<NodeListsNodeData::MicroDataItemListCache::iterator, bool> result = data->nodeLists()->m_microDataItemListCache.add(localTypeNames, 0);
5222     if (!result.second)
5223         return PassRefPtr<NodeList>(result.first->second);
5224
5225     RefPtr<MicroDataItemList> list = MicroDataItemList::create(this, typeNames);
5226     result.first->second = list.get();
5227     return list.release();
5228 }
5229
5230 void Document::removeCachedMicroDataItemList(MicroDataItemList* list, const String& typeNames)
5231 {
5232     ASSERT(rareData());
5233     ASSERT(rareData()->nodeLists());
5234     ASSERT_UNUSED(list, list->hasOwnCaches());
5235
5236     NodeListsNodeData* data = rareData()->nodeLists();
5237
5238     String localTypeNames = typeNames.isNull() ? String("http://webkit.org/microdata/undefinedItemType") : typeNames;
5239     ASSERT_UNUSED(list, list == data->m_microDataItemListCache.get(localTypeNames));
5240     data->m_microDataItemListCache.remove(localTypeNames);
5241 }
5242 #endif
5243
5244 } // namespace WebCore