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