TimeRanges::nearest() returns incorrect results.
[WebKit-https.git] / Source / WebCore / testing / Internals.cpp
1 /*
2  * Copyright (C) 2012 Google Inc. All rights reserved.
3  * Copyright (C) 2013 Apple Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
16  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
19  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "Internals.h"
29
30 #include "BackForwardController.h"
31 #include "CachedResourceLoader.h"
32 #include "Chrome.h"
33 #include "ChromeClient.h"
34 #include "ClientRect.h"
35 #include "ClientRectList.h"
36 #include "ComposedShadowTreeWalker.h"
37 #include "ContentDistributor.h"
38 #include "Cursor.h"
39 #include "DOMStringList.h"
40 #include "DOMWindow.h"
41 #include "Document.h"
42 #include "DocumentMarker.h"
43 #include "DocumentMarkerController.h"
44 #include "Element.h"
45 #include "ElementShadow.h"
46 #include "EventHandler.h"
47 #include "ExceptionCode.h"
48 #include "FormController.h"
49 #include "Frame.h"
50 #include "FrameLoader.h"
51 #include "FrameView.h"
52 #include "HTMLContentElement.h"
53 #include "HTMLInputElement.h"
54 #include "HTMLNames.h"
55 #include "HTMLSelectElement.h"
56 #include "HTMLTextAreaElement.h"
57 #include "HistoryController.h"
58 #include "HistoryItem.h"
59 #include "InspectorClient.h"
60 #include "InspectorConsoleAgent.h"
61 #include "InspectorController.h"
62 #include "InspectorCounters.h"
63 #include "InspectorFrontendChannel.h"
64 #include "InspectorFrontendClientLocal.h"
65 #include "InspectorInstrumentation.h"
66 #include "InspectorOverlay.h"
67 #include "InstrumentingAgents.h"
68 #include "InternalSettings.h"
69 #include "IntRect.h"
70 #include "Language.h"
71 #include "MallocStatistics.h"
72 #include "MemoryCache.h"
73 #include "MockPagePopupDriver.h"
74 #include "NodeRenderingContext.h"
75 #include "Page.h"
76 #include "PrintContext.h"
77 #include "PseudoElement.h"
78 #include "Range.h"
79 #include "RenderMenuList.h"
80 #include "RenderObject.h"
81 #include "RenderTreeAsText.h"
82 #include "RuntimeEnabledFeatures.h"
83 #include "SchemeRegistry.h"
84 #include "ScrollingCoordinator.h"
85 #include "SelectRuleFeatureSet.h"
86 #include "SerializedScriptValue.h"
87 #include "Settings.h"
88 #include "ShadowRoot.h"
89 #include "SpellChecker.h"
90 #include "StyleSheetContents.h"
91 #include "TextIterator.h"
92 #include "TreeScope.h"
93 #include "TypeConversions.h"
94 #include "ViewportArguments.h"
95 #include "WorkerThread.h"
96 #include <wtf/text/StringBuffer.h>
97
98 #if ENABLE(INPUT_TYPE_COLOR)
99 #include "ColorChooser.h"
100 #endif
101
102 #if ENABLE(BATTERY_STATUS)
103 #include "BatteryController.h"
104 #endif
105
106 #if ENABLE(NETWORK_INFO)
107 #include "NetworkInfo.h"
108 #include "NetworkInfoController.h"
109 #endif
110
111 #if ENABLE(PROXIMITY_EVENTS)
112 #include "DeviceProximityController.h"
113 #endif
114
115 #if ENABLE(PAGE_POPUP)
116 #include "PagePopupController.h"
117 #endif
118
119 #if ENABLE(TOUCH_ADJUSTMENT)
120 #include "WebKitPoint.h"
121 #endif
122
123 #if ENABLE(MOUSE_CURSOR_SCALE)
124 #include <wtf/dtoa.h>
125 #endif
126
127 #if ENABLE(ENCRYPTED_MEDIA_V2)
128 #include "CDM.h"
129 #include "MockCDM.h"
130 #endif
131
132 #if ENABLE(VIDEO_TRACK)
133 #include "CaptionUserPreferences.h"
134 #include "PageGroup.h"
135 #endif
136
137 #if ENABLE(VIDEO)
138 #include "HTMLMediaElement.h"
139 #include "TimeRanges.h"
140 #endif
141
142 #if ENABLE(SPEECH_SYNTHESIS)
143 #include "DOMWindowSpeechSynthesis.h"
144 #include "PlatformSpeechSynthesizerMock.h"
145 #include "SpeechSynthesis.h"
146 #endif
147
148 namespace WebCore {
149
150 #if ENABLE(PAGE_POPUP)
151 static MockPagePopupDriver* s_pagePopupDriver = 0;
152 #endif
153
154 using namespace HTMLNames;
155
156 #if ENABLE(INSPECTOR)
157 class InspectorFrontendClientDummy : public InspectorFrontendClientLocal {
158 public:
159     InspectorFrontendClientDummy(InspectorController*, Page*);
160     virtual ~InspectorFrontendClientDummy() { }
161     virtual void attachWindow(DockSide) OVERRIDE { }
162     virtual void detachWindow() OVERRIDE { }
163
164     virtual String localizedStringsURL() OVERRIDE { return String(); }
165
166     virtual void bringToFront() OVERRIDE { }
167     virtual void closeWindow() OVERRIDE { }
168
169     virtual void inspectedURLChanged(const String&) OVERRIDE { }
170
171 protected:
172     virtual void setAttachedWindowHeight(unsigned) OVERRIDE { }
173     virtual void setAttachedWindowWidth(unsigned) OVERRIDE { }
174 };
175
176 InspectorFrontendClientDummy::InspectorFrontendClientDummy(InspectorController* controller, Page* page)
177     : InspectorFrontendClientLocal(controller, page, adoptPtr(new InspectorFrontendClientLocal::Settings()))
178 {
179 }
180
181 class InspectorFrontendChannelDummy : public InspectorFrontendChannel {
182 public:
183     explicit InspectorFrontendChannelDummy(Page*);
184     virtual ~InspectorFrontendChannelDummy() { }
185     virtual bool sendMessageToFrontend(const String& message) OVERRIDE;
186
187 private:
188     Page* m_frontendPage;
189 };
190
191 InspectorFrontendChannelDummy::InspectorFrontendChannelDummy(Page* page)
192     : m_frontendPage(page)
193 {
194 }
195
196 bool InspectorFrontendChannelDummy::sendMessageToFrontend(const String& message)
197 {
198     return InspectorClient::doDispatchMessageOnFrontendPage(m_frontendPage, message);
199 }
200 #endif // ENABLE(INSPECTOR)
201
202 static bool markerTypesFrom(const String& markerType, DocumentMarker::MarkerTypes& result)
203 {
204     if (markerType.isEmpty() || equalIgnoringCase(markerType, "all"))
205         result = DocumentMarker::AllMarkers();
206     else if (equalIgnoringCase(markerType, "Spelling"))
207         result =  DocumentMarker::Spelling;
208     else if (equalIgnoringCase(markerType, "Grammar"))
209         result =  DocumentMarker::Grammar;
210     else if (equalIgnoringCase(markerType, "TextMatch"))
211         result =  DocumentMarker::TextMatch;
212     else if (equalIgnoringCase(markerType, "Replacement"))
213         result =  DocumentMarker::Replacement;
214     else if (equalIgnoringCase(markerType, "CorrectionIndicator"))
215         result =  DocumentMarker::CorrectionIndicator;
216     else if (equalIgnoringCase(markerType, "RejectedCorrection"))
217         result =  DocumentMarker::RejectedCorrection;
218     else if (equalIgnoringCase(markerType, "Autocorrected"))
219         result =  DocumentMarker::Autocorrected;
220     else if (equalIgnoringCase(markerType, "SpellCheckingExemption"))
221         result =  DocumentMarker::SpellCheckingExemption;
222     else if (equalIgnoringCase(markerType, "DeletedAutocorrection"))
223         result =  DocumentMarker::DeletedAutocorrection;
224     else if (equalIgnoringCase(markerType, "DictationAlternatives"))
225         result =  DocumentMarker::DictationAlternatives;
226     else
227         return false;
228
229     return true;
230 }
231
232 static SpellChecker* spellchecker(Document* document)
233 {
234     if (!document || !document->frame() || !document->frame()->editor())
235         return 0;
236
237     return document->frame()->editor()->spellChecker();
238 }
239
240 const char* Internals::internalsId = "internals";
241
242 PassRefPtr<Internals> Internals::create(Document* document)
243 {
244     return adoptRef(new Internals(document));
245 }
246
247 Internals::~Internals()
248 {
249 }
250
251 void Internals::resetToConsistentState(Page* page)
252 {
253     ASSERT(page);
254
255     page->setPageScaleFactor(1, IntPoint(0, 0));
256     page->setPagination(Pagination());
257
258 #if USE(ACCELERATED_COMPOSITING)
259     FrameView* mainFrameView = page->mainFrame()->view();
260     if (mainFrameView) {
261         mainFrameView->setHeaderHeight(0);
262         mainFrameView->setFooterHeight(0);
263     }
264 #endif
265     TextRun::setAllowsRoundingHacks(false);
266     WebCore::overrideUserPreferredLanguages(Vector<String>());
267     WebCore::Settings::setUsesOverlayScrollbars(false);
268 #if ENABLE(PAGE_POPUP)
269     delete s_pagePopupDriver;
270     s_pagePopupDriver = 0;
271     if (page->chrome())
272         page->chrome()->client()->resetPagePopupDriver();
273 #endif
274 #if ENABLE(INSPECTOR) && ENABLE(JAVASCRIPT_DEBUGGER)
275     if (page->inspectorController())
276         page->inspectorController()->setProfilerEnabled(false);
277 #endif
278 #if ENABLE(VIDEO_TRACK) && !PLATFORM(WIN)
279     page->group().captionPreferences()->setCaptionsStyleSheetOverride(emptyString());
280     page->group().captionPreferences()->setTestingMode(false);
281 #endif
282     if (!page->mainFrame()->editor()->isContinuousSpellCheckingEnabled())
283         page->mainFrame()->editor()->toggleContinuousSpellChecking();
284     if (page->mainFrame()->editor()->isOverwriteModeEnabled())
285         page->mainFrame()->editor()->toggleOverwriteModeEnabled();
286 }
287
288 Internals::Internals(Document* document)
289     : ContextDestructionObserver(document)
290 {
291 #if ENABLE(VIDEO_TRACK) && !PLATFORM(WIN)
292     if (document && document->page())
293         document->page()->group().captionPreferences()->setTestingMode(true);
294 #endif
295 }
296
297 Document* Internals::contextDocument() const
298 {
299     return toDocument(scriptExecutionContext());
300 }
301
302 Frame* Internals::frame() const
303 {
304     if (!contextDocument())
305         return 0;
306     return contextDocument()->frame();
307 }
308
309 InternalSettings* Internals::settings() const
310 {
311     Document* document = contextDocument();
312     if (!document)
313         return 0;
314     Page* page = document->page();
315     if (!page)
316         return 0;
317     return InternalSettings::from(page);
318 }
319
320 unsigned Internals::workerThreadCount() const
321 {
322 #if ENABLE(WORKERS)
323     return WorkerThread::workerThreadCount();
324 #else
325     return 0;
326 #endif
327 }
328
329 String Internals::address(Node* node)
330 {
331     char buf[32];
332     sprintf(buf, "%p", node);
333
334     return String(buf);
335 }
336
337 bool Internals::isPreloaded(const String& url)
338 {
339     Document* document = contextDocument();
340     return document->cachedResourceLoader()->isPreloaded(url);
341 }
342
343 bool Internals::isLoadingFromMemoryCache(const String& url)
344 {
345     if (!contextDocument())
346         return false;
347     CachedResource* resource = memoryCache()->resourceForURL(contextDocument()->completeURL(url));
348     return resource && resource->status() == CachedResource::Cached;
349 }
350
351 PassRefPtr<Element> Internals::createContentElement(ExceptionCode& ec)
352 {
353     Document* document = contextDocument();
354     if (!document) {
355         ec = INVALID_ACCESS_ERR;
356         return 0;
357     }
358
359 #if ENABLE(SHADOW_DOM)
360     return HTMLContentElement::create(document);
361 #else
362     return 0;
363 #endif
364 }
365
366 bool Internals::isValidContentSelect(Element* insertionPoint, ExceptionCode& ec)
367 {
368     if (!insertionPoint || !insertionPoint->isInsertionPoint()) {
369         ec = INVALID_ACCESS_ERR;
370         return false;
371     }
372
373 #if ENABLE(SHADOW_DOM)
374     return isHTMLContentElement(insertionPoint) && toHTMLContentElement(insertionPoint)->isSelectValid();
375 #else
376     return false;
377 #endif
378 }
379
380 Node* Internals::treeScopeRootNode(Node* node, ExceptionCode& ec)
381 {
382     if (!node) {
383         ec = INVALID_ACCESS_ERR;
384         return 0;
385     }
386
387     return node->treeScope()->rootNode();
388 }
389
390 Node* Internals::parentTreeScope(Node* node, ExceptionCode& ec)
391 {
392     if (!node) {
393         ec = INVALID_ACCESS_ERR;
394         return 0;
395     }
396     const TreeScope* parentTreeScope = node->treeScope()->parentTreeScope();
397     return parentTreeScope ? parentTreeScope->rootNode() : 0;
398 }
399
400 bool Internals::hasSelectorForIdInShadow(Element* host, const String& idValue, ExceptionCode& ec)
401 {
402     if (!host || !host->shadow()) {
403         ec = INVALID_ACCESS_ERR;
404         return 0;
405     }
406
407     return host->shadow()->distributor().ensureSelectFeatureSet(host->shadow()).hasSelectorForId(idValue);
408 }
409
410 bool Internals::hasSelectorForClassInShadow(Element* host, const String& className, ExceptionCode& ec)
411 {
412     if (!host || !host->shadow()) {
413         ec = INVALID_ACCESS_ERR;
414         return 0;
415     }
416
417     return host->shadow()->distributor().ensureSelectFeatureSet(host->shadow()).hasSelectorForClass(className);
418 }
419
420 bool Internals::hasSelectorForAttributeInShadow(Element* host, const String& attributeName, ExceptionCode& ec)
421 {
422     if (!host || !host->shadow()) {
423         ec = INVALID_ACCESS_ERR;
424         return 0;
425     }
426
427     return host->shadow()->distributor().ensureSelectFeatureSet(host->shadow()).hasSelectorForAttribute(attributeName);
428 }
429
430 bool Internals::hasSelectorForPseudoClassInShadow(Element* host, const String& pseudoClass, ExceptionCode& ec)
431 {
432     if (!host || !host->shadow()) {
433         ec = INVALID_ACCESS_ERR;
434         return 0;
435     }
436
437     const SelectRuleFeatureSet& featureSet = host->shadow()->distributor().ensureSelectFeatureSet(host->shadow());
438     if (pseudoClass == "checked")
439         return featureSet.hasSelectorForChecked();
440     if (pseudoClass == "enabled")
441         return featureSet.hasSelectorForEnabled();
442     if (pseudoClass == "disabled")
443         return featureSet.hasSelectorForDisabled();
444     if (pseudoClass == "indeterminate")
445         return featureSet.hasSelectorForIndeterminate();
446     if (pseudoClass == "link")
447         return featureSet.hasSelectorForLink();
448     if (pseudoClass == "target")
449         return featureSet.hasSelectorForTarget();
450     if (pseudoClass == "visited")
451         return featureSet.hasSelectorForVisited();
452
453     ASSERT_NOT_REACHED();
454     return false;
455 }
456
457 unsigned Internals::numberOfActiveAnimations() const
458 {
459     Frame* contextFrame = frame();
460     if (AnimationController* controller = contextFrame->animation())
461         return controller->numberOfActiveAnimations(contextFrame->document());
462     return 0;
463 }
464
465 void Internals::suspendAnimations(Document* document, ExceptionCode& ec) const
466 {
467     if (!document || !document->frame()) {
468         ec = INVALID_ACCESS_ERR;
469         return;
470     }
471
472     AnimationController* controller = document->frame()->animation();
473     if (!controller)
474         return;
475
476     controller->suspendAnimations();
477 }
478
479 void Internals::resumeAnimations(Document* document, ExceptionCode& ec) const
480 {
481     if (!document || !document->frame()) {
482         ec = INVALID_ACCESS_ERR;
483         return;
484     }
485
486     AnimationController* controller = document->frame()->animation();
487     if (!controller)
488         return;
489
490     controller->resumeAnimations();
491 }
492
493 bool Internals::pauseAnimationAtTimeOnElement(const String& animationName, double pauseTime, Element* element, ExceptionCode& ec)
494 {
495     if (!element || pauseTime < 0) {
496         ec = INVALID_ACCESS_ERR;
497         return false;
498     }
499     AnimationController* controller = frame()->animation();
500     return controller->pauseAnimationAtTime(element->renderer(), AtomicString(animationName), pauseTime);
501 }
502
503 bool Internals::pauseAnimationAtTimeOnPseudoElement(const String& animationName, double pauseTime, Element* element, const String& pseudoId, ExceptionCode& ec)
504 {
505     if (!element || pauseTime < 0) {
506         ec = INVALID_ACCESS_ERR;
507         return false;
508     }
509
510     if (pseudoId != "before" && pseudoId != "after") {
511         ec = INVALID_ACCESS_ERR;
512         return false;
513     }
514
515     PseudoElement* pseudoElement = element->pseudoElement(pseudoId == "before" ? BEFORE : AFTER);
516     if (!pseudoElement) {
517         ec = INVALID_ACCESS_ERR;
518         return false;
519     }
520
521     return frame()->animation()->pauseAnimationAtTime(pseudoElement->renderer(), AtomicString(animationName), pauseTime);
522 }
523
524 bool Internals::pauseTransitionAtTimeOnElement(const String& propertyName, double pauseTime, Element* element, ExceptionCode& ec)
525 {
526     if (!element || pauseTime < 0) {
527         ec = INVALID_ACCESS_ERR;
528         return false;
529     }
530     AnimationController* controller = frame()->animation();
531     return controller->pauseTransitionAtTime(element->renderer(), propertyName, pauseTime);
532 }
533
534 bool Internals::pauseTransitionAtTimeOnPseudoElement(const String& property, double pauseTime, Element* element, const String& pseudoId, ExceptionCode& ec)
535 {
536     if (!element || pauseTime < 0) {
537         ec = INVALID_ACCESS_ERR;
538         return false;
539     }
540
541     if (pseudoId != "before" && pseudoId != "after") {
542         ec = INVALID_ACCESS_ERR;
543         return false;
544     }
545
546     PseudoElement* pseudoElement = element->pseudoElement(pseudoId == "before" ? BEFORE : AFTER);
547     if (!pseudoElement) {
548         ec = INVALID_ACCESS_ERR;
549         return false;
550     }
551
552     return frame()->animation()->pauseTransitionAtTime(pseudoElement->renderer(), property, pauseTime);
553 }
554
555 bool Internals::hasShadowInsertionPoint(const Node* root, ExceptionCode& ec) const
556 {
557     if (root && root->isShadowRoot())
558         return ScopeContentDistribution::hasShadowElement(toShadowRoot(root));
559
560     ec = INVALID_ACCESS_ERR;
561     return 0;
562 }
563
564 bool Internals::hasContentElement(const Node* root, ExceptionCode& ec) const
565 {
566     if (root && root->isShadowRoot())
567         return ScopeContentDistribution::hasContentElement(toShadowRoot(root));
568
569     ec = INVALID_ACCESS_ERR;
570     return 0;
571 }
572
573 size_t Internals::countElementShadow(const Node* root, ExceptionCode& ec) const
574 {
575     if (!root || !root->isShadowRoot()) {
576         ec = INVALID_ACCESS_ERR;
577         return 0;
578     }
579
580     return ScopeContentDistribution::countElementShadow(toShadowRoot(root));
581 }
582
583 bool Internals::attached(Node* node, ExceptionCode& ec)
584 {
585     if (!node) {
586         ec = INVALID_ACCESS_ERR;
587         return false;
588     }
589
590     return node->attached();
591 }
592
593 Node* Internals::nextSiblingByWalker(Node* node, ExceptionCode& ec)
594 {
595     if (!node) {
596         ec = INVALID_ACCESS_ERR;
597         return 0;
598     }
599     ComposedShadowTreeWalker walker(node);
600     walker.nextSibling();
601     return walker.get();
602 }
603
604 Node* Internals::firstChildByWalker(Node* node, ExceptionCode& ec)
605 {
606     if (!node) {
607         ec = INVALID_ACCESS_ERR;
608         return 0;
609     }
610     ComposedShadowTreeWalker walker(node);
611     walker.firstChild();
612     return walker.get();
613 }
614
615 Node* Internals::lastChildByWalker(Node* node, ExceptionCode& ec)
616 {
617     if (!node) {
618         ec = INVALID_ACCESS_ERR;
619         return 0;
620     }
621     ComposedShadowTreeWalker walker(node);
622     walker.lastChild();
623     return walker.get();
624 }
625
626 Node* Internals::nextNodeByWalker(Node* node, ExceptionCode& ec)
627 {
628     if (!node) {
629         ec = INVALID_ACCESS_ERR;
630         return 0;
631     }
632     ComposedShadowTreeWalker walker(node);
633     walker.next();
634     return walker.get();
635 }
636
637 Node* Internals::previousNodeByWalker(Node* node, ExceptionCode& ec)
638 {
639     if (!node) {
640         ec = INVALID_ACCESS_ERR;
641         return 0;
642     }
643     ComposedShadowTreeWalker walker(node);
644     walker.previous();
645     return walker.get();
646 }
647
648 String Internals::elementRenderTreeAsText(Element* element, ExceptionCode& ec)
649 {
650     if (!element) {
651         ec = INVALID_ACCESS_ERR;
652         return String();
653     }
654
655     String representation = externalRepresentation(element);
656     if (representation.isEmpty()) {
657         ec = INVALID_ACCESS_ERR;
658         return String();
659     }
660
661     return representation;
662 }
663
664 size_t Internals::numberOfScopedHTMLStyleChildren(const Node* scope, ExceptionCode& ec) const
665 {
666     if (scope && (scope->isElementNode() || scope->isShadowRoot()))
667 #if ENABLE(STYLE_SCOPED)
668         return scope->numberOfScopedHTMLStyleChildren();
669 #else
670         return 0;
671 #endif
672
673     ec = INVALID_ACCESS_ERR;
674     return 0;
675 }
676
677 PassRefPtr<CSSComputedStyleDeclaration> Internals::computedStyleIncludingVisitedInfo(Node* node, ExceptionCode& ec) const
678 {
679     if (!node) {
680         ec = INVALID_ACCESS_ERR;
681         return 0;
682     }
683
684     bool allowVisitedStyle = true;
685     return CSSComputedStyleDeclaration::create(node, allowVisitedStyle);
686 }
687
688 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::ensureShadowRoot(Element* host, ExceptionCode& ec)
689 {
690     if (!host) {
691         ec = INVALID_ACCESS_ERR;
692         return 0;
693     }
694
695     if (ElementShadow* shadow = host->shadow())
696         return shadow->youngestShadowRoot();
697
698     return host->createShadowRoot(ec).get();
699 }
700
701 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::createShadowRoot(Element* host, ExceptionCode& ec)
702 {
703     if (!host) {
704         ec = INVALID_ACCESS_ERR;
705         return 0;
706     }
707     return host->createShadowRoot(ec).get();
708 }
709
710 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::shadowRoot(Element* host, ExceptionCode& ec)
711 {
712     // FIXME: Internals::shadowRoot() in tests should be converted to youngestShadowRoot() or oldestShadowRoot().
713     // https://bugs.webkit.org/show_bug.cgi?id=78465
714     return youngestShadowRoot(host, ec);
715 }
716
717 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::youngestShadowRoot(Element* host, ExceptionCode& ec)
718 {
719     if (!host) {
720         ec = INVALID_ACCESS_ERR;
721         return 0;
722     }
723
724     if (ElementShadow* shadow = host->shadow())
725         return shadow->youngestShadowRoot();
726     return 0;
727 }
728
729 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::oldestShadowRoot(Element* host, ExceptionCode& ec)
730 {
731     if (!host) {
732         ec = INVALID_ACCESS_ERR;
733         return 0;
734     }
735
736     if (ElementShadow* shadow = host->shadow())
737         return shadow->oldestShadowRoot();
738     return 0;
739 }
740
741 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::youngerShadowRoot(Node* shadow, ExceptionCode& ec)
742 {
743     if (!shadow || !shadow->isShadowRoot()) {
744         ec = INVALID_ACCESS_ERR;
745         return 0;
746     }
747
748     return toShadowRoot(shadow)->youngerShadowRoot();
749 }
750
751 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::olderShadowRoot(Node* shadow, ExceptionCode& ec)
752 {
753     if (!shadow || !shadow->isShadowRoot()) {
754         ec = INVALID_ACCESS_ERR;
755         return 0;
756     }
757
758     return toShadowRoot(shadow)->olderShadowRoot();
759 }
760
761 String Internals::shadowRootType(const Node* root, ExceptionCode& ec) const
762 {
763     if (!root || !root->isShadowRoot()) {
764         ec = INVALID_ACCESS_ERR;
765         return String();
766     }
767
768     switch (toShadowRoot(root)->type()) {
769     case ShadowRoot::UserAgentShadowRoot:
770         return String("UserAgentShadowRoot");
771     case ShadowRoot::AuthorShadowRoot:
772         return String("AuthorShadowRoot");
773     default:
774         ASSERT_NOT_REACHED();
775         return String("Unknown");
776     }
777 }
778
779 Element* Internals::includerFor(Node* node, ExceptionCode& ec)
780 {
781     if (!node) {
782         ec = INVALID_ACCESS_ERR;
783         return 0;
784     }
785
786     return NodeRenderingContext(node).insertionPoint();
787 }
788
789 String Internals::shadowPseudoId(Element* element, ExceptionCode& ec)
790 {
791     if (!element) {
792         ec = INVALID_ACCESS_ERR;
793         return String();
794     }
795
796     return element->shadowPseudoId().string();
797 }
798
799 void Internals::setShadowPseudoId(Element* element, const String& id, ExceptionCode& ec)
800 {
801     if (!element) {
802         ec = INVALID_ACCESS_ERR;
803         return;
804     }
805
806     return element->setPseudo(id);
807 }
808
809 String Internals::visiblePlaceholder(Element* element)
810 {
811     if (element && isHTMLTextFormControlElement(element)) {
812         if (toHTMLTextFormControlElement(element)->placeholderShouldBeVisible())
813             return toHTMLTextFormControlElement(element)->placeholderElement()->textContent();
814     }
815
816     return String();
817 }
818
819 #if ENABLE(INPUT_TYPE_COLOR)
820 void Internals::selectColorInColorChooser(Element* element, const String& colorValue)
821 {
822     if (!element->hasTagName(inputTag))
823         return;
824     HTMLInputElement* inputElement = element->toInputElement();
825     if (!inputElement)
826         return;
827     inputElement->selectColorInColorChooser(Color(colorValue));
828 }
829 #endif
830
831 Vector<String> Internals::formControlStateOfPreviousHistoryItem(ExceptionCode& ec)
832 {
833     HistoryItem* mainItem = frame()->loader()->history()->previousItem();
834     if (!mainItem) {
835         ec = INVALID_ACCESS_ERR;
836         return Vector<String>();
837     }
838     String uniqueName = frame()->tree()->uniqueName();
839     if (mainItem->target() != uniqueName && !mainItem->childItemWithTarget(uniqueName)) {
840         ec = INVALID_ACCESS_ERR;
841         return Vector<String>();
842     }
843     return mainItem->target() == uniqueName ? mainItem->documentState() : mainItem->childItemWithTarget(uniqueName)->documentState();
844 }
845
846 void Internals::setFormControlStateOfPreviousHistoryItem(const Vector<String>& state, ExceptionCode& ec)
847 {
848     HistoryItem* mainItem = frame()->loader()->history()->previousItem();
849     if (!mainItem) {
850         ec = INVALID_ACCESS_ERR;
851         return;
852     }
853     String uniqueName = frame()->tree()->uniqueName();
854     if (mainItem->target() == uniqueName)
855         mainItem->setDocumentState(state);
856     else if (HistoryItem* subItem = mainItem->childItemWithTarget(uniqueName))
857         subItem->setDocumentState(state);
858     else
859         ec = INVALID_ACCESS_ERR;
860 }
861
862 #if ENABLE(SPEECH_SYNTHESIS)
863 void Internals::enableMockSpeechSynthesizer()
864 {
865     Document* document = contextDocument();
866     if (!document || !document->domWindow())
867         return;
868     SpeechSynthesis* synthesis = DOMWindowSpeechSynthesis::speechSynthesis(document->domWindow());
869     if (!synthesis)
870         return;
871     
872     synthesis->setPlatformSynthesizer(PlatformSpeechSynthesizerMock::create(synthesis));
873 }
874 #endif
875     
876 void Internals::setEnableMockPagePopup(bool enabled, ExceptionCode& ec)
877 {
878 #if ENABLE(PAGE_POPUP)
879     Document* document = contextDocument();
880     if (!document || !document->page() || !document->page()->chrome())
881         return;
882     Page* page = document->page();
883     if (!enabled) {
884         page->chrome()->client()->resetPagePopupDriver();
885         return;
886     }
887     if (!s_pagePopupDriver)
888         s_pagePopupDriver = MockPagePopupDriver::create(page->mainFrame()).leakPtr();
889     page->chrome()->client()->setPagePopupDriver(s_pagePopupDriver);
890 #else
891     UNUSED_PARAM(enabled);
892     UNUSED_PARAM(ec);
893 #endif
894 }
895
896 #if ENABLE(PAGE_POPUP)
897 PassRefPtr<PagePopupController> Internals::pagePopupController()
898 {
899     return s_pagePopupDriver ? s_pagePopupDriver->pagePopupController() : 0;
900 }
901 #endif
902
903 PassRefPtr<ClientRect> Internals::absoluteCaretBounds(ExceptionCode& ec)
904 {
905     Document* document = contextDocument();
906     if (!document || !document->frame() || !document->frame()->selection()) {
907         ec = INVALID_ACCESS_ERR;
908         return ClientRect::create();
909     }
910
911     return ClientRect::create(document->frame()->selection()->absoluteCaretBounds());
912 }
913
914 PassRefPtr<ClientRect> Internals::boundingBox(Element* element, ExceptionCode& ec)
915 {
916     if (!element) {
917         ec = INVALID_ACCESS_ERR;
918         return ClientRect::create();
919     }
920
921     element->document()->updateLayoutIgnorePendingStylesheets();
922     RenderObject* renderer = element->renderer();
923     if (!renderer)
924         return ClientRect::create();
925     return ClientRect::create(renderer->absoluteBoundingBoxRectIgnoringTransforms());
926 }
927
928 PassRefPtr<ClientRectList> Internals::inspectorHighlightRects(Document* document, ExceptionCode& ec)
929 {
930 #if ENABLE(INSPECTOR)
931     if (!document || !document->page() || !document->page()->inspectorController()) {
932         ec = INVALID_ACCESS_ERR;
933         return ClientRectList::create();
934     }
935
936     Highlight highlight;
937     document->page()->inspectorController()->getHighlight(&highlight);
938     return ClientRectList::create(highlight.quads);
939 #else
940     UNUSED_PARAM(document);
941     UNUSED_PARAM(ec);
942     return ClientRectList::create();
943 #endif
944 }
945
946 unsigned Internals::markerCountForNode(Node* node, const String& markerType, ExceptionCode& ec)
947 {
948     if (!node) {
949         ec = INVALID_ACCESS_ERR;
950         return 0;
951     }
952
953     DocumentMarker::MarkerTypes markerTypes = 0;
954     if (!markerTypesFrom(markerType, markerTypes)) {
955         ec = SYNTAX_ERR;
956         return 0;
957     }
958
959     return node->document()->markers()->markersFor(node, markerTypes).size();
960 }
961
962 DocumentMarker* Internals::markerAt(Node* node, const String& markerType, unsigned index, ExceptionCode& ec)
963 {
964     if (!node) {
965         ec = INVALID_ACCESS_ERR;
966         return 0;
967     }
968
969     DocumentMarker::MarkerTypes markerTypes = 0;
970     if (!markerTypesFrom(markerType, markerTypes)) {
971         ec = SYNTAX_ERR;
972         return 0;
973     }
974
975     Vector<DocumentMarker*> markers = node->document()->markers()->markersFor(node, markerTypes);
976     if (markers.size() <= index)
977         return 0;
978     return markers[index];
979 }
980
981 PassRefPtr<Range> Internals::markerRangeForNode(Node* node, const String& markerType, unsigned index, ExceptionCode& ec)
982 {
983     DocumentMarker* marker = markerAt(node, markerType, index, ec);
984     if (!marker)
985         return 0;
986     return Range::create(node->document(), node, marker->startOffset(), node, marker->endOffset());
987 }
988
989 String Internals::markerDescriptionForNode(Node* node, const String& markerType, unsigned index, ExceptionCode& ec)
990 {
991     DocumentMarker* marker = markerAt(node, markerType, index, ec);
992     if (!marker)
993         return String();
994     return marker->description();
995 }
996
997 void Internals::addTextMatchMarker(const Range* range, bool isActive)
998 {
999     range->ownerDocument()->updateLayoutIgnorePendingStylesheets();
1000     range->ownerDocument()->markers()->addTextMatchMarker(range, isActive);
1001 }
1002
1003 void Internals::setScrollViewPosition(Document* document, long x, long y, ExceptionCode& ec)
1004 {
1005     if (!document || !document->view()) {
1006         ec = INVALID_ACCESS_ERR;
1007         return;
1008     }
1009
1010     FrameView* frameView = document->view();
1011     bool constrainsScrollingToContentEdgeOldValue = frameView->constrainsScrollingToContentEdge();
1012     bool scrollbarsSuppressedOldValue = frameView->scrollbarsSuppressed();
1013
1014     frameView->setConstrainsScrollingToContentEdge(false);
1015     frameView->setScrollbarsSuppressed(false);
1016     frameView->setScrollOffsetFromInternals(IntPoint(x, y));
1017     frameView->setScrollbarsSuppressed(scrollbarsSuppressedOldValue);
1018     frameView->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdgeOldValue);
1019 }
1020
1021 void Internals::setPagination(Document* document, const String& mode, int gap, int pageLength, ExceptionCode& ec)
1022 {
1023     if (!document || !document->page()) {
1024         ec = INVALID_ACCESS_ERR;
1025         return;
1026     }
1027     Page* page = document->page();
1028
1029     Pagination pagination;
1030     if (mode == "Unpaginated")
1031         pagination.mode = Pagination::Unpaginated;
1032     else if (mode == "LeftToRightPaginated")
1033         pagination.mode = Pagination::LeftToRightPaginated;
1034     else if (mode == "RightToLeftPaginated")
1035         pagination.mode = Pagination::RightToLeftPaginated;
1036     else if (mode == "TopToBottomPaginated")
1037         pagination.mode = Pagination::TopToBottomPaginated;
1038     else if (mode == "BottomToTopPaginated")
1039         pagination.mode = Pagination::BottomToTopPaginated;
1040     else {
1041         ec = SYNTAX_ERR;
1042         return;
1043     }
1044
1045     pagination.gap = gap;
1046     pagination.pageLength = pageLength;
1047     page->setPagination(pagination);
1048 }
1049
1050 String Internals::configurationForViewport(Document* document, float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight, ExceptionCode& ec)
1051 {
1052     if (!document || !document->page()) {
1053         ec = INVALID_ACCESS_ERR;
1054         return String();
1055     }
1056     Page* page = document->page();
1057
1058     const int defaultLayoutWidthForNonMobilePages = 980;
1059
1060     ViewportArguments arguments = page->viewportArguments();
1061     ViewportAttributes attributes = computeViewportAttributes(arguments, defaultLayoutWidthForNonMobilePages, deviceWidth, deviceHeight, devicePixelRatio, IntSize(availableWidth, availableHeight));
1062     restrictMinimumScaleFactorToViewportSize(attributes, IntSize(availableWidth, availableHeight), devicePixelRatio);
1063     restrictScaleFactorToInitialScaleIfNotUserScalable(attributes);
1064
1065     return "viewport size " + String::number(attributes.layoutSize.width()) + "x" + String::number(attributes.layoutSize.height()) + " scale " + String::number(attributes.initialScale) + " with limits [" + String::number(attributes.minimumScale) + ", " + String::number(attributes.maximumScale) + "] and userScalable " + (attributes.userScalable ? "true" : "false");
1066 }
1067
1068 bool Internals::wasLastChangeUserEdit(Element* textField, ExceptionCode& ec)
1069 {
1070     if (!textField) {
1071         ec = INVALID_ACCESS_ERR;
1072         return false;
1073     }
1074
1075     if (HTMLInputElement* inputElement = textField->toInputElement())
1076         return inputElement->lastChangeWasUserEdit();
1077
1078     // FIXME: We should be using hasTagName instead but Windows port doesn't link QualifiedNames properly.
1079     if (textField->tagName() == "TEXTAREA")
1080         return static_cast<HTMLTextAreaElement*>(textField)->lastChangeWasUserEdit();
1081
1082     ec = INVALID_NODE_TYPE_ERR;
1083     return false;
1084 }
1085
1086 bool Internals::elementShouldAutoComplete(Element* element, ExceptionCode& ec)
1087 {
1088     if (!element) {
1089         ec = INVALID_ACCESS_ERR;
1090         return false;
1091     }
1092
1093     if (HTMLInputElement* inputElement = element->toInputElement())
1094         return inputElement->shouldAutocomplete();
1095
1096     ec = INVALID_NODE_TYPE_ERR;
1097     return false;
1098 }
1099
1100 String Internals::suggestedValue(Element* element, ExceptionCode& ec)
1101 {
1102     if (!element) {
1103         ec = INVALID_ACCESS_ERR;
1104         return String();
1105     }
1106
1107     HTMLInputElement* inputElement = element->toInputElement();
1108     if (!inputElement) {
1109         ec = INVALID_NODE_TYPE_ERR;
1110         return String();
1111     }
1112
1113     return inputElement->suggestedValue();
1114 }
1115
1116 void Internals::setSuggestedValue(Element* element, const String& value, ExceptionCode& ec)
1117 {
1118     if (!element) {
1119         ec = INVALID_ACCESS_ERR;
1120         return;
1121     }
1122
1123     HTMLInputElement* inputElement = element->toInputElement();
1124     if (!inputElement) {
1125         ec = INVALID_NODE_TYPE_ERR;
1126         return;
1127     }
1128
1129     inputElement->setSuggestedValue(value);
1130 }
1131
1132 void Internals::setEditingValue(Element* element, const String& value, ExceptionCode& ec)
1133 {
1134     if (!element) {
1135         ec = INVALID_ACCESS_ERR;
1136         return;
1137     }
1138
1139     HTMLInputElement* inputElement = element->toInputElement();
1140     if (!inputElement) {
1141         ec = INVALID_NODE_TYPE_ERR;
1142         return;
1143     }
1144
1145     inputElement->setEditingValue(value);
1146 }
1147
1148 void Internals::setAutofilled(Element* element, bool enabled, ExceptionCode& ec)
1149 {
1150     HTMLInputElement* inputElement = element->toInputElement();
1151     if (!inputElement) {
1152         ec = INVALID_ACCESS_ERR;
1153         return;
1154     }
1155     inputElement->setAutofilled(enabled);
1156 }
1157
1158 void Internals::scrollElementToRect(Element* element, long x, long y, long w, long h, ExceptionCode& ec)
1159 {
1160     if (!element || !element->document() || !element->document()->view()) {
1161         ec = INVALID_ACCESS_ERR;
1162         return;
1163     }
1164     FrameView* frameView = element->document()->view();
1165     frameView->scrollElementToRect(element, IntRect(x, y, w, h));
1166 }
1167
1168 void Internals::paintControlTints(Document* document, ExceptionCode& ec)
1169 {
1170     if (!document || !document->view()) {
1171         ec = INVALID_ACCESS_ERR;
1172         return;
1173     }
1174
1175     FrameView* frameView = document->view();
1176     frameView->paintControlTints();
1177 }
1178
1179 PassRefPtr<Range> Internals::rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength, ExceptionCode& ec)
1180 {
1181     if (!scope) {
1182         ec = INVALID_ACCESS_ERR;
1183         return 0;
1184     }
1185
1186     return TextIterator::rangeFromLocationAndLength(scope, rangeLocation, rangeLength);
1187 }
1188
1189 unsigned Internals::locationFromRange(Element* scope, const Range* range, ExceptionCode& ec)
1190 {
1191     if (!scope || !range) {
1192         ec = INVALID_ACCESS_ERR;
1193         return 0;
1194     }
1195
1196     size_t location = 0;
1197     size_t unusedLength = 0;
1198     TextIterator::getLocationAndLengthFromRange(scope, range, location, unusedLength);
1199     return location;
1200 }
1201
1202 unsigned Internals::lengthFromRange(Element* scope, const Range* range, ExceptionCode& ec)
1203 {
1204     if (!scope || !range) {
1205         ec = INVALID_ACCESS_ERR;
1206         return 0;
1207     }
1208
1209     size_t unusedLocation = 0;
1210     size_t length = 0;
1211     TextIterator::getLocationAndLengthFromRange(scope, range, unusedLocation, length);
1212     return length;
1213 }
1214
1215 String Internals::rangeAsText(const Range* range, ExceptionCode& ec)
1216 {
1217     if (!range) {
1218         ec = INVALID_ACCESS_ERR;
1219         return String();
1220     }
1221
1222     return range->text();
1223 }
1224
1225 void Internals::setDelegatesScrolling(bool enabled, Document* document, ExceptionCode& ec)
1226 {
1227     // Delegate scrolling is valid only on mainframe's view.
1228     if (!document || !document->view() || !document->page() || document->page()->mainFrame() != document->frame()) {
1229         ec = INVALID_ACCESS_ERR;
1230         return;
1231     }
1232
1233     document->view()->setDelegatesScrolling(enabled);
1234 }
1235
1236 #if ENABLE(TOUCH_ADJUSTMENT)
1237 PassRefPtr<WebKitPoint> Internals::touchPositionAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionCode& ec)
1238 {
1239     if (!document || !document->frame()) {
1240         ec = INVALID_ACCESS_ERR;
1241         return 0;
1242     }
1243
1244     IntSize radius(width / 2, height / 2);
1245     IntPoint point(x + radius.width(), y + radius.height());
1246
1247     Node* targetNode;
1248     IntPoint adjustedPoint;
1249
1250     bool foundNode = document->frame()->eventHandler()->bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
1251     if (foundNode)
1252         return WebKitPoint::create(adjustedPoint.x(), adjustedPoint.y());
1253
1254     return 0;
1255 }
1256
1257 Node* Internals::touchNodeAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionCode& ec)
1258 {
1259     if (!document || !document->frame()) {
1260         ec = INVALID_ACCESS_ERR;
1261         return 0;
1262     }
1263
1264     IntSize radius(width / 2, height / 2);
1265     IntPoint point(x + radius.width(), y + radius.height());
1266
1267     Node* targetNode;
1268     IntPoint adjustedPoint;
1269     document->frame()->eventHandler()->bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
1270     return targetNode;
1271 }
1272
1273 PassRefPtr<WebKitPoint> Internals::touchPositionAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionCode& ec)
1274 {
1275     if (!document || !document->frame()) {
1276         ec = INVALID_ACCESS_ERR;
1277         return 0;
1278     }
1279
1280     IntSize radius(width / 2, height / 2);
1281     IntPoint point(x + radius.width(), y + radius.height());
1282
1283     Node* targetNode = 0;
1284     IntPoint adjustedPoint;
1285
1286     bool foundNode = document->frame()->eventHandler()->bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
1287     if (foundNode)
1288         return WebKitPoint::create(adjustedPoint.x(), adjustedPoint.y());
1289
1290     return WebKitPoint::create(x, y);
1291 }
1292
1293 Node* Internals::touchNodeAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionCode& ec)
1294 {
1295     if (!document || !document->frame()) {
1296         ec = INVALID_ACCESS_ERR;
1297         return 0;
1298     }
1299
1300     IntSize radius(width / 2, height / 2);
1301     IntPoint point(x + radius.width(), y + radius.height());
1302
1303     Node* targetNode = 0;
1304     IntPoint adjustedPoint;
1305     document->frame()->eventHandler()->bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
1306     return targetNode;
1307 }
1308
1309 PassRefPtr<ClientRect> Internals::bestZoomableAreaForTouchPoint(long x, long y, long width, long height, Document* document, ExceptionCode& ec)
1310 {
1311     if (!document || !document->frame()) {
1312         ec = INVALID_ACCESS_ERR;
1313         return 0;
1314     }
1315
1316     IntSize radius(width / 2, height / 2);
1317     IntPoint point(x + radius.width(), y + radius.height());
1318
1319     Node* targetNode;
1320     IntRect zoomableArea;
1321     bool foundNode = document->frame()->eventHandler()->bestZoomableAreaForTouchPoint(point, radius, zoomableArea, targetNode);
1322     if (foundNode)
1323         return ClientRect::create(zoomableArea);
1324
1325     return 0;
1326 }
1327 #endif
1328
1329
1330 int Internals::lastSpellCheckRequestSequence(Document* document, ExceptionCode& ec)
1331 {
1332     SpellChecker* checker = spellchecker(document);
1333
1334     if (!checker) {
1335         ec = INVALID_ACCESS_ERR;
1336         return -1;
1337     }
1338
1339     return checker->lastRequestSequence();
1340 }
1341
1342 int Internals::lastSpellCheckProcessedSequence(Document* document, ExceptionCode& ec)
1343 {
1344     SpellChecker* checker = spellchecker(document);
1345
1346     if (!checker) {
1347         ec = INVALID_ACCESS_ERR;
1348         return -1;
1349     }
1350
1351     return checker->lastProcessedSequence();
1352 }
1353
1354 Vector<String> Internals::userPreferredLanguages() const
1355 {
1356     return WebCore::userPreferredLanguages();
1357 }
1358
1359 void Internals::setUserPreferredLanguages(const Vector<String>& languages)
1360 {
1361     WebCore::overrideUserPreferredLanguages(languages);
1362 }
1363
1364 unsigned Internals::wheelEventHandlerCount(Document* document, ExceptionCode& ec)
1365 {
1366     if (!document) {
1367         ec = INVALID_ACCESS_ERR;
1368         return 0;
1369     }
1370
1371     return document->wheelEventHandlerCount();
1372 }
1373
1374 unsigned Internals::touchEventHandlerCount(Document* document, ExceptionCode& ec)
1375 {
1376     if (!document) {
1377         ec = INVALID_ACCESS_ERR;
1378         return 0;
1379     }
1380
1381     const TouchEventTargetSet* touchHandlers = document->touchEventTargets();
1382     if (!touchHandlers)
1383         return 0;
1384
1385     unsigned count = 0;
1386     for (TouchEventTargetSet::const_iterator iter = touchHandlers->begin(); iter != touchHandlers->end(); ++iter)
1387         count += iter->value;
1388     return count;
1389 }
1390
1391 #if ENABLE(TOUCH_EVENT_TRACKING)
1392 PassRefPtr<ClientRectList> Internals::touchEventTargetClientRects(Document* document, ExceptionCode& ec)
1393 {
1394     if (!document || !document->view() || !document->page()) {
1395         ec = INVALID_ACCESS_ERR;
1396         return 0;
1397     }
1398     if (!document->page()->scrollingCoordinator())
1399         return ClientRectList::create();
1400
1401     document->updateLayoutIgnorePendingStylesheets();
1402
1403     Vector<IntRect> absoluteRects;
1404     document->page()->scrollingCoordinator()->computeAbsoluteTouchEventTargetRects(document, absoluteRects);
1405     Vector<FloatQuad> absoluteQuads(absoluteRects.size());
1406
1407     for (size_t i = 0; i < absoluteRects.size(); ++i)
1408         absoluteQuads[i] = FloatQuad(absoluteRects[i]);
1409
1410     return ClientRectList::create(absoluteQuads);
1411 }
1412 #endif
1413
1414 PassRefPtr<NodeList> Internals::nodesFromRect(Document* document, int x, int y, unsigned topPadding, unsigned rightPadding,
1415     unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent, bool allowChildFrameContent, ExceptionCode& ec) const
1416 {
1417     if (!document || !document->frame() || !document->frame()->view()) {
1418         ec = INVALID_ACCESS_ERR;
1419         return 0;
1420     }
1421
1422     HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active;
1423     if (ignoreClipping)
1424         hitType |= HitTestRequest::IgnoreClipping;
1425     if (!allowShadowContent)
1426         hitType |= HitTestRequest::DisallowShadowContent;
1427     if (allowChildFrameContent)
1428         hitType |= HitTestRequest::AllowChildFrameContent;
1429
1430     return document->nodesFromRect(x, y, topPadding, rightPadding, bottomPadding, leftPadding, hitType);
1431 }
1432
1433 void Internals::emitInspectorDidBeginFrame()
1434 {
1435 #if ENABLE(INSPECTOR)
1436     InspectorController* inspectorController = contextDocument()->frame()->page()->inspectorController();
1437     inspectorController->didBeginFrame();
1438 #endif
1439 }
1440
1441 void Internals::emitInspectorDidCancelFrame()
1442 {
1443 #if ENABLE(INSPECTOR)
1444     InspectorController* inspectorController = contextDocument()->frame()->page()->inspectorController();
1445     inspectorController->didCancelFrame();
1446 #endif
1447 }
1448
1449 void Internals::setBatteryStatus(Document* document, const String& eventType, bool charging, double chargingTime, double dischargingTime, double level, ExceptionCode& ec)
1450 {
1451     if (!document || !document->page()) {
1452         ec = INVALID_ACCESS_ERR;
1453         return;
1454     }
1455
1456 #if ENABLE(BATTERY_STATUS)
1457     BatteryController::from(document->page())->didChangeBatteryStatus(eventType, BatteryStatus::create(charging, chargingTime, dischargingTime, level));
1458 #else
1459     UNUSED_PARAM(eventType);
1460     UNUSED_PARAM(charging);
1461     UNUSED_PARAM(chargingTime);
1462     UNUSED_PARAM(dischargingTime);
1463     UNUSED_PARAM(level);
1464 #endif
1465 }
1466
1467 void Internals::setNetworkInformation(Document* document, const String& eventType, double bandwidth, bool metered, ExceptionCode& ec)
1468 {
1469     if (!document || !document->page()) {
1470         ec = INVALID_ACCESS_ERR;
1471         return;
1472     }
1473
1474 #if ENABLE(NETWORK_INFO)
1475     NetworkInfoController::from(document->page())->didChangeNetworkInformation(eventType, NetworkInfo::create(bandwidth, metered));
1476 #else
1477     UNUSED_PARAM(eventType);
1478     UNUSED_PARAM(bandwidth);
1479     UNUSED_PARAM(metered);
1480 #endif
1481 }
1482
1483 void Internals::setDeviceProximity(Document* document, const String& eventType, double value, double min, double max, ExceptionCode& ec)
1484 {
1485     if (!document || !document->page()) {
1486         ec = INVALID_ACCESS_ERR;
1487         return;
1488     }
1489
1490 #if ENABLE(PROXIMITY_EVENTS)
1491     DeviceProximityController::from(document->page())->didChangeDeviceProximity(value, min, max);
1492 #else
1493     UNUSED_PARAM(eventType);
1494     UNUSED_PARAM(value);
1495     UNUSED_PARAM(min);
1496     UNUSED_PARAM(max);
1497 #endif
1498 }
1499
1500 bool Internals::hasSpellingMarker(Document* document, int from, int length, ExceptionCode&)
1501 {
1502     if (!document || !document->frame())
1503         return 0;
1504
1505     return document->frame()->editor()->selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length);
1506 }
1507     
1508 bool Internals::hasAutocorrectedMarker(Document* document, int from, int length, ExceptionCode&)
1509 {
1510     if (!document || !document->frame())
1511         return 0;
1512     
1513     return document->frame()->editor()->selectionStartHasMarkerFor(DocumentMarker::Autocorrected, from, length);
1514 }
1515
1516 void Internals::setContinuousSpellCheckingEnabled(bool enabled, ExceptionCode&)
1517 {
1518     if (!contextDocument() || !contextDocument()->frame())
1519         return;
1520
1521     if (enabled != contextDocument()->frame()->editor()->isContinuousSpellCheckingEnabled())
1522         contextDocument()->frame()->editor()->toggleContinuousSpellChecking();
1523 }
1524
1525 void Internals::setAutomaticQuoteSubstitutionEnabled(bool enabled, ExceptionCode&)
1526 {
1527     if (!contextDocument() || !contextDocument()->frame())
1528         return;
1529
1530 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1531     if (enabled != contextDocument()->frame()->editor()->isAutomaticQuoteSubstitutionEnabled())
1532         contextDocument()->frame()->editor()->toggleAutomaticQuoteSubstitution();
1533 #else
1534     UNUSED_PARAM(enabled);
1535 #endif
1536 }
1537
1538 void Internals::setAutomaticLinkDetectionEnabled(bool enabled, ExceptionCode&)
1539 {
1540     if (!contextDocument() || !contextDocument()->frame())
1541         return;
1542
1543 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1544     if (enabled != contextDocument()->frame()->editor()->isAutomaticLinkDetectionEnabled())
1545         contextDocument()->frame()->editor()->toggleAutomaticLinkDetection();
1546 #else
1547     UNUSED_PARAM(enabled);
1548 #endif
1549 }
1550
1551 void Internals::setAutomaticDashSubstitutionEnabled(bool enabled, ExceptionCode&)
1552 {
1553     if (!contextDocument() || !contextDocument()->frame())
1554         return;
1555
1556 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1557     if (enabled != contextDocument()->frame()->editor()->isAutomaticDashSubstitutionEnabled())
1558         contextDocument()->frame()->editor()->toggleAutomaticDashSubstitution();
1559 #else
1560     UNUSED_PARAM(enabled);
1561 #endif
1562 }
1563
1564 void Internals::setAutomaticTextReplacementEnabled(bool enabled, ExceptionCode&)
1565 {
1566     if (!contextDocument() || !contextDocument()->frame())
1567         return;
1568
1569 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1570     if (enabled != contextDocument()->frame()->editor()->isAutomaticTextReplacementEnabled())
1571         contextDocument()->frame()->editor()->toggleAutomaticTextReplacement();
1572 #else
1573     UNUSED_PARAM(enabled);
1574 #endif
1575 }
1576
1577 void Internals::setAutomaticSpellingCorrectionEnabled(bool enabled, ExceptionCode&)
1578 {
1579     if (!contextDocument() || !contextDocument()->frame())
1580         return;
1581
1582 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1583     if (enabled != contextDocument()->frame()->editor()->isAutomaticSpellingCorrectionEnabled())
1584         contextDocument()->frame()->editor()->toggleAutomaticSpellingCorrection();
1585 #else
1586     UNUSED_PARAM(enabled);
1587 #endif
1588 }
1589
1590 bool Internals::isOverwriteModeEnabled(Document* document, ExceptionCode&)
1591 {
1592     if (!document || !document->frame())
1593         return 0;
1594
1595     return document->frame()->editor()->isOverwriteModeEnabled();
1596 }
1597
1598 void Internals::toggleOverwriteModeEnabled(Document* document, ExceptionCode&)
1599 {
1600     if (!document || !document->frame())
1601         return;
1602
1603     document->frame()->editor()->toggleOverwriteModeEnabled();
1604 }
1605
1606 #if ENABLE(INSPECTOR)
1607 unsigned Internals::numberOfLiveNodes() const
1608 {
1609     return InspectorCounters::counterValue(InspectorCounters::NodeCounter);
1610 }
1611
1612 unsigned Internals::numberOfLiveDocuments() const
1613 {
1614     return InspectorCounters::counterValue(InspectorCounters::DocumentCounter);
1615 }
1616
1617 Vector<String> Internals::consoleMessageArgumentCounts(Document* document) const
1618 {
1619     InstrumentingAgents* instrumentingAgents = instrumentationForPage(document->page());
1620     if (!instrumentingAgents)
1621         return Vector<String>();
1622     InspectorConsoleAgent* consoleAgent = instrumentingAgents->inspectorConsoleAgent();
1623     if (!consoleAgent)
1624         return Vector<String>();
1625     Vector<unsigned> counts = consoleAgent->consoleMessageArgumentCounts();
1626     Vector<String> result(counts.size());
1627     for (size_t i = 0; i < counts.size(); i++)
1628         result[i] = String::number(counts[i]);
1629     return result;
1630 }
1631
1632 PassRefPtr<DOMWindow> Internals::openDummyInspectorFrontend(const String& url)
1633 {
1634     Page* page = contextDocument()->frame()->page();
1635     ASSERT(page);
1636
1637     DOMWindow* window = page->mainFrame()->document()->domWindow();
1638     ASSERT(window);
1639
1640     m_frontendWindow = window->open(url, "", "", window, window);
1641     ASSERT(m_frontendWindow);
1642
1643     Page* frontendPage = m_frontendWindow->document()->page();
1644     ASSERT(frontendPage);
1645
1646     OwnPtr<InspectorFrontendClientDummy> frontendClient = adoptPtr(new InspectorFrontendClientDummy(page->inspectorController(), frontendPage));
1647
1648     frontendPage->inspectorController()->setInspectorFrontendClient(frontendClient.release());
1649
1650     m_frontendChannel = adoptPtr(new InspectorFrontendChannelDummy(frontendPage));
1651
1652     page->inspectorController()->connectFrontend(m_frontendChannel.get());
1653
1654     return m_frontendWindow;
1655 }
1656
1657 void Internals::closeDummyInspectorFrontend()
1658 {
1659     Page* page = contextDocument()->frame()->page();
1660     ASSERT(page);
1661     ASSERT(m_frontendWindow);
1662
1663     page->inspectorController()->disconnectFrontend();
1664
1665     m_frontendChannel.release();
1666
1667     m_frontendWindow->close(m_frontendWindow->scriptExecutionContext());
1668     m_frontendWindow.release();
1669 }
1670
1671 void Internals::setInspectorResourcesDataSizeLimits(int maximumResourcesContentSize, int maximumSingleResourceContentSize, ExceptionCode& ec)
1672 {
1673     Page* page = contextDocument()->frame()->page();
1674     if (!page || !page->inspectorController()) {
1675         ec = INVALID_ACCESS_ERR;
1676         return;
1677     }
1678     page->inspectorController()->setResourcesDataSizeLimitsFromInternals(maximumResourcesContentSize, maximumSingleResourceContentSize);
1679 }
1680
1681 void Internals::setJavaScriptProfilingEnabled(bool enabled, ExceptionCode& ec)
1682 {
1683     Page* page = contextDocument()->frame()->page();
1684     if (!page || !page->inspectorController()) {
1685         ec = INVALID_ACCESS_ERR;
1686         return;
1687     }
1688
1689     page->inspectorController()->setProfilerEnabled(enabled);
1690 }
1691 #endif // ENABLE(INSPECTOR)
1692
1693 bool Internals::hasGrammarMarker(Document* document, int from, int length, ExceptionCode&)
1694 {
1695     if (!document || !document->frame())
1696         return 0;
1697
1698     return document->frame()->editor()->selectionStartHasMarkerFor(DocumentMarker::Grammar, from, length);
1699 }
1700
1701 unsigned Internals::numberOfScrollableAreas(Document* document, ExceptionCode&)
1702 {
1703     unsigned count = 0;
1704     Frame* frame = document->frame();
1705     if (frame->view()->scrollableAreas())
1706         count += frame->view()->scrollableAreas()->size();
1707
1708     for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
1709         if (child->view() && child->view()->scrollableAreas())
1710             count += child->view()->scrollableAreas()->size();
1711     }
1712
1713     return count;
1714 }
1715     
1716 bool Internals::isPageBoxVisible(Document* document, int pageNumber, ExceptionCode& ec)
1717 {
1718     if (!document) {
1719         ec = INVALID_ACCESS_ERR;
1720         return false;
1721     }
1722
1723     return document->isPageBoxVisible(pageNumber);
1724 }
1725
1726 String Internals::layerTreeAsText(Document* document, ExceptionCode& ec) const
1727 {
1728     return layerTreeAsText(document, 0, ec);
1729 }
1730
1731 String Internals::layerTreeAsText(Document* document, unsigned flags, ExceptionCode& ec) const
1732 {
1733     if (!document || !document->frame()) {
1734         ec = INVALID_ACCESS_ERR;
1735         return String();
1736     }
1737
1738     LayerTreeFlags layerTreeFlags = 0;
1739     if (flags & LAYER_TREE_INCLUDES_VISIBLE_RECTS)
1740         layerTreeFlags |= LayerTreeFlagsIncludeVisibleRects;
1741     if (flags & LAYER_TREE_INCLUDES_TILE_CACHES)
1742         layerTreeFlags |= LayerTreeFlagsIncludeTileCaches;
1743     if (flags & LAYER_TREE_INCLUDES_REPAINT_RECTS)
1744         layerTreeFlags |= LayerTreeFlagsIncludeRepaintRects;
1745     if (flags & LAYER_TREE_INCLUDES_PAINTING_PHASES)
1746         layerTreeFlags |= LayerTreeFlagsIncludePaintingPhases;
1747
1748     return document->frame()->layerTreeAsText(layerTreeFlags);
1749 }
1750
1751 String Internals::repaintRectsAsText(Document* document, ExceptionCode& ec) const
1752 {
1753     if (!document || !document->frame()) {
1754         ec = INVALID_ACCESS_ERR;
1755         return String();
1756     }
1757
1758     return document->frame()->trackedRepaintRectsAsText();
1759 }
1760
1761 String Internals::scrollingStateTreeAsText(Document* document, ExceptionCode& ec) const
1762 {
1763     if (!document || !document->frame()) {
1764         ec = INVALID_ACCESS_ERR;
1765         return String();
1766     }
1767
1768     Page* page = document->page();
1769     if (!page)
1770         return String();
1771
1772     return page->scrollingStateTreeAsText();
1773 }
1774
1775 String Internals::mainThreadScrollingReasons(Document* document, ExceptionCode& ec) const
1776 {
1777     if (!document || !document->frame()) {
1778         ec = INVALID_ACCESS_ERR;
1779         return String();
1780     }
1781
1782     Page* page = document->page();
1783     if (!page)
1784         return String();
1785
1786     return page->mainThreadScrollingReasonsAsText();
1787 }
1788
1789 PassRefPtr<ClientRectList> Internals::nonFastScrollableRects(Document* document, ExceptionCode& ec) const
1790 {
1791     if (!document || !document->frame()) {
1792         ec = INVALID_ACCESS_ERR;
1793         return 0;
1794     }
1795
1796     Page* page = document->page();
1797     if (!page)
1798         return 0;
1799
1800     return page->nonFastScrollableRects(document->frame());
1801 }
1802
1803 void Internals::garbageCollectDocumentResources(Document* document, ExceptionCode& ec) const
1804 {
1805     if (!document) {
1806         ec = INVALID_ACCESS_ERR;
1807         return;
1808     }
1809
1810     CachedResourceLoader* cachedResourceLoader = document->cachedResourceLoader();
1811     if (!cachedResourceLoader)
1812         return;
1813     cachedResourceLoader->garbageCollectDocumentResources();
1814 }
1815
1816 void Internals::allowRoundingHacks() const
1817 {
1818     TextRun::setAllowsRoundingHacks(true);
1819 }
1820
1821 void Internals::insertAuthorCSS(Document* document, const String& css) const
1822 {
1823     RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(document);
1824     parsedSheet->setIsUserStyleSheet(false);
1825     parsedSheet->parseString(css);
1826     document->styleSheetCollection()->addAuthorSheet(parsedSheet);
1827 }
1828
1829 void Internals::insertUserCSS(Document* document, const String& css) const
1830 {
1831     RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(document);
1832     parsedSheet->setIsUserStyleSheet(true);
1833     parsedSheet->parseString(css);
1834     document->styleSheetCollection()->addUserSheet(parsedSheet);
1835 }
1836
1837 String Internals::counterValue(Element* element)
1838 {
1839     if (!element)
1840         return String();
1841
1842     return counterValueForElement(element);
1843 }
1844
1845 int Internals::pageNumber(Element* element, float pageWidth, float pageHeight)
1846 {
1847     if (!element)
1848         return 0;
1849
1850     return PrintContext::pageNumberForElement(element, FloatSize(pageWidth, pageHeight));
1851 }
1852
1853 Vector<String> Internals::iconURLs(Document* document, int iconTypesMask) const
1854 {
1855     Vector<IconURL> iconURLs = document->iconURLs(iconTypesMask);
1856     Vector<String> array;
1857
1858     Vector<IconURL>::const_iterator iter(iconURLs.begin());
1859     for (; iter != iconURLs.end(); ++iter)
1860         array.append(iter->m_iconURL.string());
1861
1862     return array;
1863 }
1864
1865 Vector<String> Internals::shortcutIconURLs(Document* document) const
1866 {
1867     return iconURLs(document, Favicon);
1868 }
1869
1870 Vector<String> Internals::allIconURLs(Document* document) const
1871 {
1872     return iconURLs(document, Favicon | TouchIcon | TouchPrecomposedIcon);
1873 }
1874
1875 int Internals::numberOfPages(float pageWidth, float pageHeight)
1876 {
1877     if (!frame())
1878         return -1;
1879
1880     return PrintContext::numberOfPages(frame(), FloatSize(pageWidth, pageHeight));
1881 }
1882
1883 String Internals::pageProperty(String propertyName, int pageNumber, ExceptionCode& ec) const
1884 {
1885     if (!frame()) {
1886         ec = INVALID_ACCESS_ERR;
1887         return String();
1888     }
1889
1890     return PrintContext::pageProperty(frame(), propertyName.utf8().data(), pageNumber);
1891 }
1892
1893 String Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft, ExceptionCode& ec) const
1894 {
1895     if (!frame()) {
1896         ec = INVALID_ACCESS_ERR;
1897         return String();
1898     }
1899
1900     return PrintContext::pageSizeAndMarginsInPixels(frame(), pageNumber, width, height, marginTop, marginRight, marginBottom, marginLeft);
1901 }
1902
1903 void Internals::setPageScaleFactor(float scaleFactor, int x, int y, ExceptionCode& ec)
1904 {
1905     Document* document = contextDocument();
1906     if (!document || !document->page()) {
1907         ec = INVALID_ACCESS_ERR;
1908         return;
1909     }
1910     Page* page = document->page();
1911     page->setPageScaleFactor(scaleFactor, IntPoint(x, y));
1912 }
1913
1914 void Internals::setHeaderHeight(Document* document, float height)
1915 {
1916     if (!document || !document->view())
1917         return;
1918 #if USE(ACCELERATED_COMPOSITING)
1919     FrameView* frameView = document->view();
1920     frameView->setHeaderHeight(height);
1921 #endif
1922 }
1923
1924 void Internals::setFooterHeight(Document* document, float height)
1925 {
1926     if (!document || !document->view())
1927         return;
1928 #if USE(ACCELERATED_COMPOSITING)
1929     FrameView* frameView = document->view();
1930     frameView->setFooterHeight(height);
1931 #endif
1932 }
1933
1934 #if ENABLE(FULLSCREEN_API)
1935 void Internals::webkitWillEnterFullScreenForElement(Document* document, Element* element)
1936 {
1937     if (!document)
1938         return;
1939     document->webkitWillEnterFullScreenForElement(element);
1940 }
1941
1942 void Internals::webkitDidEnterFullScreenForElement(Document* document, Element* element)
1943 {
1944     if (!document)
1945         return;
1946     document->webkitDidEnterFullScreenForElement(element);
1947 }
1948
1949 void Internals::webkitWillExitFullScreenForElement(Document* document, Element* element)
1950 {
1951     if (!document)
1952         return;
1953     document->webkitWillExitFullScreenForElement(element);
1954 }
1955
1956 void Internals::webkitDidExitFullScreenForElement(Document* document, Element* element)
1957 {
1958     if (!document)
1959         return;
1960     document->webkitDidExitFullScreenForElement(element);
1961 }
1962 #endif
1963
1964 void Internals::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme)
1965 {
1966     SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(scheme);
1967 }
1968
1969 void Internals::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(const String& scheme)
1970 {
1971     SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(scheme);
1972 }
1973
1974 PassRefPtr<MallocStatistics> Internals::mallocStatistics() const
1975 {
1976     return MallocStatistics::create();
1977 }
1978
1979 PassRefPtr<TypeConversions> Internals::typeConversions() const
1980 {
1981     return TypeConversions::create();
1982 }
1983
1984 Vector<String> Internals::getReferencedFilePaths() const
1985 {
1986     frame()->loader()->history()->saveDocumentAndScrollState();
1987     return FormController::getReferencedFilePaths(frame()->loader()->history()->currentItem()->documentState());
1988 }
1989
1990 void Internals::startTrackingRepaints(Document* document, ExceptionCode& ec)
1991 {
1992     if (!document || !document->view()) {
1993         ec = INVALID_ACCESS_ERR;
1994         return;
1995     }
1996
1997     FrameView* frameView = document->view();
1998     frameView->setTracksRepaints(true);
1999 }
2000
2001 void Internals::stopTrackingRepaints(Document* document, ExceptionCode& ec)
2002 {
2003     if (!document || !document->view()) {
2004         ec = INVALID_ACCESS_ERR;
2005         return;
2006     }
2007
2008     FrameView* frameView = document->view();
2009     frameView->setTracksRepaints(false);
2010 }
2011
2012 #if USE(LAZY_NATIVE_CURSOR)
2013 static const char* cursorTypeToString(Cursor::Type cursorType)
2014 {
2015     switch (cursorType) {
2016     case Cursor::Pointer: return "Pointer";
2017     case Cursor::Cross: return "Cross";
2018     case Cursor::Hand: return "Hand";
2019     case Cursor::IBeam: return "IBeam";
2020     case Cursor::Wait: return "Wait";
2021     case Cursor::Help: return "Help";
2022     case Cursor::EastResize: return "EastResize";
2023     case Cursor::NorthResize: return "NorthResize";
2024     case Cursor::NorthEastResize: return "NorthEastResize";
2025     case Cursor::NorthWestResize: return "NorthWestResize";
2026     case Cursor::SouthResize: return "SouthResize";
2027     case Cursor::SouthEastResize: return "SouthEastResize";
2028     case Cursor::SouthWestResize: return "SouthWestResize";
2029     case Cursor::WestResize: return "WestResize";
2030     case Cursor::NorthSouthResize: return "NorthSouthResize";
2031     case Cursor::EastWestResize: return "EastWestResize";
2032     case Cursor::NorthEastSouthWestResize: return "NorthEastSouthWestResize";
2033     case Cursor::NorthWestSouthEastResize: return "NorthWestSouthEastResize";
2034     case Cursor::ColumnResize: return "ColumnResize";
2035     case Cursor::RowResize: return "RowResize";
2036     case Cursor::MiddlePanning: return "MiddlePanning";
2037     case Cursor::EastPanning: return "EastPanning";
2038     case Cursor::NorthPanning: return "NorthPanning";
2039     case Cursor::NorthEastPanning: return "NorthEastPanning";
2040     case Cursor::NorthWestPanning: return "NorthWestPanning";
2041     case Cursor::SouthPanning: return "SouthPanning";
2042     case Cursor::SouthEastPanning: return "SouthEastPanning";
2043     case Cursor::SouthWestPanning: return "SouthWestPanning";
2044     case Cursor::WestPanning: return "WestPanning";
2045     case Cursor::Move: return "Move";
2046     case Cursor::VerticalText: return "VerticalText";
2047     case Cursor::Cell: return "Cell";
2048     case Cursor::ContextMenu: return "ContextMenu";
2049     case Cursor::Alias: return "Alias";
2050     case Cursor::Progress: return "Progress";
2051     case Cursor::NoDrop: return "NoDrop";
2052     case Cursor::Copy: return "Copy";
2053     case Cursor::None: return "None";
2054     case Cursor::NotAllowed: return "NotAllowed";
2055     case Cursor::ZoomIn: return "ZoomIn";
2056     case Cursor::ZoomOut: return "ZoomOut";
2057     case Cursor::Grab: return "Grab";
2058     case Cursor::Grabbing: return "Grabbing";
2059     case Cursor::Custom: return "Custom";
2060     }
2061
2062     ASSERT_NOT_REACHED();
2063     return "UNKNOWN";
2064 }
2065 #endif
2066
2067 String Internals::getCurrentCursorInfo(Document* document, ExceptionCode& ec)
2068 {
2069     if (!document || !document->frame()) {
2070         ec = INVALID_ACCESS_ERR;
2071         return String();
2072     }
2073
2074     Cursor cursor = document->frame()->eventHandler()->currentMouseCursor();
2075
2076 #if USE(LAZY_NATIVE_CURSOR)
2077     StringBuilder result;
2078     result.append("type=");
2079     result.append(cursorTypeToString(cursor.type()));
2080     result.append(" hotSpot=");
2081     result.appendNumber(cursor.hotSpot().x());
2082     result.append(",");
2083     result.appendNumber(cursor.hotSpot().y());
2084     if (cursor.image()) {
2085         IntSize size = cursor.image()->size();
2086         result.append(" image=");
2087         result.appendNumber(size.width());
2088         result.append("x");
2089         result.appendNumber(size.height());
2090     }
2091 #if ENABLE(MOUSE_CURSOR_SCALE)
2092     if (cursor.imageScaleFactor() != 1) {
2093         result.append(" scale=");
2094         NumberToStringBuffer buffer;
2095         result.append(numberToFixedPrecisionString(cursor.imageScaleFactor(), 8, buffer, true));
2096     }
2097 #endif
2098     return result.toString();
2099 #else
2100     return "FAIL: Cursor details not available on this platform.";
2101 #endif
2102 }
2103
2104 PassRefPtr<ArrayBuffer> Internals::serializeObject(PassRefPtr<SerializedScriptValue> value) const
2105 {
2106     Vector<uint8_t> bytes = value->data();
2107     return ArrayBuffer::create(bytes.data(), bytes.size());
2108 }
2109
2110 PassRefPtr<SerializedScriptValue> Internals::deserializeBuffer(PassRefPtr<ArrayBuffer> buffer) const
2111 {
2112     Vector<uint8_t> bytes;
2113     bytes.append(static_cast<const uint8_t*>(buffer->data()), buffer->byteLength());
2114     return SerializedScriptValue::adopt(bytes);
2115 }
2116
2117 void Internals::setUsesOverlayScrollbars(bool enabled)
2118 {
2119     WebCore::Settings::setUsesOverlayScrollbars(enabled);
2120 }
2121
2122 void Internals::forceReload(bool endToEnd)
2123 {
2124     frame()->loader()->reload(endToEnd);
2125 }
2126
2127 #if ENABLE(ENCRYPTED_MEDIA_V2)
2128 void Internals::initializeMockCDM()
2129 {
2130     CDM::registerCDMFactory(MockCDM::create, MockCDM::supportsKeySytem);
2131 }
2132 #endif
2133
2134 String Internals::markerTextForListItem(Element* element, ExceptionCode& ec)
2135 {
2136     if (!element) {
2137         ec = INVALID_ACCESS_ERR;
2138         return String();
2139     }
2140     return WebCore::markerTextForListItem(element);
2141 }
2142
2143 String Internals::getImageSourceURL(Element* element, ExceptionCode& ec)
2144 {
2145     if (!element) {
2146         ec = INVALID_ACCESS_ERR;
2147         return String();
2148     }
2149     return element->imageSourceURL();
2150 }
2151
2152 #if ENABLE(VIDEO)
2153 void Internals::simulateAudioInterruption(Node* node)
2154 {
2155 #if USE(GSTREAMER)
2156     HTMLMediaElement* element = toMediaElement(node);
2157     element->player()->simulateAudioInterruption();
2158 #else
2159     UNUSED_PARAM(node);
2160 #endif
2161 }
2162 #endif
2163
2164 bool Internals::isSelectPopupVisible(Node* node)
2165 {
2166     if (!isHTMLSelectElement(node))
2167         return false;
2168
2169     HTMLSelectElement* select = toHTMLSelectElement(node);
2170
2171     RenderObject* renderer = select->renderer();
2172     if (!renderer->isMenuList())
2173         return false;
2174
2175     RenderMenuList* menuList = toRenderMenuList(renderer);
2176     return menuList->popupIsVisible();
2177 }
2178
2179 String Internals::captionsStyleSheetOverride(ExceptionCode& ec)
2180 {
2181     Document* document = contextDocument();
2182     if (!document || !document->page()) {
2183         ec = INVALID_ACCESS_ERR;
2184         return emptyString();
2185     }
2186
2187 #if ENABLE(VIDEO_TRACK) && !PLATFORM(WIN)
2188     return document->page()->group().captionPreferences()->captionsStyleSheetOverride();
2189 #else
2190     return emptyString();
2191 #endif
2192 }
2193
2194 void Internals::setCaptionsStyleSheetOverride(const String& override, ExceptionCode& ec)
2195 {
2196     Document* document = contextDocument();
2197     if (!document || !document->page()) {
2198         ec = INVALID_ACCESS_ERR;
2199         return;
2200     }
2201
2202 #if ENABLE(VIDEO_TRACK) && !PLATFORM(WIN)
2203     document->page()->group().captionPreferences()->setCaptionsStyleSheetOverride(override);
2204 #endif
2205 }
2206
2207 void Internals::setPrimaryAudioTrackLanguageOverride(const String& language, ExceptionCode& ec)
2208 {
2209     Document* document = contextDocument();
2210     if (!document || !document->page()) {
2211         ec = INVALID_ACCESS_ERR;
2212         return;
2213     }
2214
2215 #if ENABLE(VIDEO_TRACK) && !PLATFORM(WIN)
2216     document->page()->group().captionPreferences()->setPrimaryAudioTrackLanguageOverride(language);
2217 #else
2218     UNUSED_PARAM(language);
2219 #endif
2220 }
2221
2222 void Internals::setCaptionDisplayMode(const String& mode, ExceptionCode& ec)
2223 {
2224     Document* document = contextDocument();
2225     if (!document || !document->page()) {
2226         ec = INVALID_ACCESS_ERR;
2227         return;
2228     }
2229     
2230 #if ENABLE(VIDEO_TRACK) && !PLATFORM(WIN)
2231     CaptionUserPreferences* captionPreferences = document->page()->group().captionPreferences();
2232     
2233     if (equalIgnoringCase(mode, "Automatic"))
2234         captionPreferences->setCaptionDisplayMode(CaptionUserPreferences::Automatic);
2235     else if (equalIgnoringCase(mode, "ForcedOnly"))
2236         captionPreferences->setCaptionDisplayMode(CaptionUserPreferences::ForcedOnly);
2237     else if (equalIgnoringCase(mode, "AlwaysOn"))
2238         captionPreferences->setCaptionDisplayMode(CaptionUserPreferences::AlwaysOn);
2239     else
2240         ec = SYNTAX_ERR;
2241 #else
2242     UNUSED_PARAM(mode);
2243 #endif
2244 }
2245
2246 #if ENABLE(VIDEO)
2247 PassRefPtr<TimeRanges> Internals::createTimeRanges(Float32Array* startTimes, Float32Array* endTimes)
2248 {
2249     ASSERT(startTimes && endTimes);
2250     ASSERT(startTimes->length() == endTimes->length());
2251     RefPtr<TimeRanges> ranges = TimeRanges::create();
2252
2253     unsigned count = std::min(startTimes->length(), endTimes->length());
2254     for (unsigned i = 0; i < count; ++i)
2255         ranges->add(startTimes->item(i), endTimes->item(i));
2256     return ranges;
2257 }
2258
2259 double Internals::closestTimeToTimeRanges(double time, TimeRanges* ranges)
2260 {
2261     return ranges->nearest(time);
2262 }
2263 #endif
2264
2265 }