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