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