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