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