Roll r168668 back in.
[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 "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 "FormController.h"
51 #include "FrameLoader.h"
52 #include "FrameView.h"
53 #include "HTMLIFrameElement.h"
54 #include "HTMLInputElement.h"
55 #include "HTMLNames.h"
56 #include "HTMLPlugInElement.h"
57 #include "HTMLSelectElement.h"
58 #include "HTMLTextAreaElement.h"
59 #include "HistoryController.h"
60 #include "HistoryItem.h"
61 #include "InspectorClient.h"
62 #include "InspectorController.h"
63 #include "InspectorForwarding.h"
64 #include "InspectorFrontendClientLocal.h"
65 #include "InspectorInstrumentation.h"
66 #include "InspectorOverlay.h"
67 #include "InstrumentingAgents.h"
68 #include "IntRect.h"
69 #include "InternalSettings.h"
70 #include "Language.h"
71 #include "MainFrame.h"
72 #include "MallocStatistics.h"
73 #include "MediaPlayer.h"
74 #include "MediaSessionManager.h"
75 #include "MemoryCache.h"
76 #include "MemoryInfo.h"
77 #include "Page.h"
78 #include "PrintContext.h"
79 #include "PseudoElement.h"
80 #include "Range.h"
81 #include "RenderEmbeddedObject.h"
82 #include "RenderMenuList.h"
83 #include "RenderTreeAsText.h"
84 #include "RenderView.h"
85 #include "RuntimeEnabledFeatures.h"
86 #include "SchemeRegistry.h"
87 #include "ScrollingCoordinator.h"
88 #include "SerializedScriptValue.h"
89 #include "Settings.h"
90 #include "ShadowRoot.h"
91 #include "SpellChecker.h"
92 #include "StaticNodeList.h"
93 #include "StyleSheetContents.h"
94 #include "TextIterator.h"
95 #include "TreeScope.h"
96 #include "TypeConversions.h"
97 #include "ViewportArguments.h"
98 #include "WebConsoleAgent.h"
99 #include "WorkerThread.h"
100 #include <bytecode/CodeBlock.h>
101 #include <inspector/InspectorAgentBase.h>
102 #include <inspector/InspectorValues.h>
103 #include <runtime/JSCInlines.h>
104 #include <runtime/JSCJSValue.h>
105 #include <wtf/text/CString.h>
106 #include <wtf/text/StringBuffer.h>
107
108 #if ENABLE(INPUT_TYPE_COLOR)
109 #include "ColorChooser.h"
110 #endif
111
112 #if ENABLE(BATTERY_STATUS)
113 #include "BatteryController.h"
114 #endif
115
116 #if ENABLE(PROXIMITY_EVENTS)
117 #include "DeviceProximityController.h"
118 #endif
119
120 #if ENABLE(MOUSE_CURSOR_SCALE)
121 #include <wtf/dtoa.h>
122 #endif
123
124 #if ENABLE(ENCRYPTED_MEDIA_V2)
125 #include "CDM.h"
126 #include "MockCDM.h"
127 #endif
128
129 #if ENABLE(VIDEO_TRACK)
130 #include "CaptionUserPreferences.h"
131 #include "PageGroup.h"
132 #endif
133
134 #if ENABLE(VIDEO)
135 #include "HTMLMediaElement.h"
136 #include "TimeRanges.h"
137 #endif
138
139 #if ENABLE(SPEECH_SYNTHESIS)
140 #include "DOMWindowSpeechSynthesis.h"
141 #include "PlatformSpeechSynthesizerMock.h"
142 #include "SpeechSynthesis.h"
143 #endif
144
145 #if ENABLE(VIBRATION)
146 #include "Vibration.h"
147 #endif
148
149 #if ENABLE(MEDIA_STREAM)
150 #include "MockMediaStreamCenter.h"
151 #include "RTCPeerConnection.h"
152 #include "RTCPeerConnectionHandlerMock.h"
153 #include "UserMediaClientMock.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, std::make_unique<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 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
245     else if (equalIgnoringCase(markerType, "TelephoneNumber"))
246         result =  DocumentMarker::TelephoneNumber;
247 #endif
248     else
249         return false;
250
251     return true;
252 }
253
254 const char* Internals::internalsId = "internals";
255
256 PassRefPtr<Internals> Internals::create(Document* document)
257 {
258     return adoptRef(new Internals(document));
259 }
260
261 Internals::~Internals()
262 {
263 }
264
265 void Internals::resetToConsistentState(Page* page)
266 {
267     ASSERT(page);
268
269     page->setPageScaleFactor(1, IntPoint(0, 0));
270     page->setPagination(Pagination());
271
272     FrameView* mainFrameView = page->mainFrame().view();
273     if (mainFrameView) {
274         mainFrameView->setHeaderHeight(0);
275         mainFrameView->setFooterHeight(0);
276         page->setTopContentInset(0);
277     }
278
279     TextRun::setAllowsRoundingHacks(false);
280     WebCore::overrideUserPreferredLanguages(Vector<String>());
281     WebCore::Settings::setUsesOverlayScrollbars(false);
282 #if ENABLE(INSPECTOR)
283     page->inspectorController().setProfilerEnabled(false);
284 #endif
285 #if ENABLE(VIDEO_TRACK)
286     page->group().captionPreferences()->setCaptionsStyleSheetOverride(emptyString());
287     page->group().captionPreferences()->setTestingMode(false);
288 #endif
289     if (!page->mainFrame().editor().isContinuousSpellCheckingEnabled())
290         page->mainFrame().editor().toggleContinuousSpellChecking();
291     if (page->mainFrame().editor().isOverwriteModeEnabled())
292         page->mainFrame().editor().toggleOverwriteModeEnabled();
293     cacheStorage().setDefaultOriginQuota(ApplicationCacheStorage::noQuota());
294 #if ENABLE(VIDEO)
295     MediaSessionManager::sharedManager().resetRestrictions();
296 #endif
297 #if HAVE(ACCESSIBILITY)
298     AXObjectCache::setEnhancedUserInterfaceAccessibility(false);
299     AXObjectCache::disableAccessibility();
300 #endif
301 }
302
303 Internals::Internals(Document* document)
304     : ContextDestructionObserver(document)
305 {
306 #if ENABLE(VIDEO_TRACK)
307     if (document && document->page())
308         document->page()->group().captionPreferences()->setTestingMode(true);
309 #endif
310
311 #if ENABLE(MEDIA_STREAM)
312     MockMediaStreamCenter::registerMockMediaStreamCenter();
313     enableMockRTCPeerConnectionHandler();
314     WebCore::provideUserMediaTo(document->page(), new UserMediaClientMock());
315 #endif
316 }
317
318 Document* Internals::contextDocument() const
319 {
320     return toDocument(scriptExecutionContext());
321 }
322
323 Frame* Internals::frame() const
324 {
325     if (!contextDocument())
326         return 0;
327     return contextDocument()->frame();
328 }
329
330 InternalSettings* Internals::settings() const
331 {
332     Document* document = contextDocument();
333     if (!document)
334         return 0;
335     Page* page = document->page();
336     if (!page)
337         return 0;
338     return InternalSettings::from(page);
339 }
340
341 unsigned Internals::workerThreadCount() const
342 {
343     return WorkerThread::workerThreadCount();
344 }
345
346 String Internals::address(Node* node)
347 {
348     char buf[32];
349     sprintf(buf, "%p", node);
350
351     return String(buf);
352 }
353
354 bool Internals::isPreloaded(const String& url)
355 {
356     Document* document = contextDocument();
357     return document->cachedResourceLoader()->isPreloaded(url);
358 }
359
360 bool Internals::isLoadingFromMemoryCache(const String& url)
361 {
362     if (!contextDocument() || !contextDocument()->page())
363         return false;
364     CachedResource* resource = memoryCache()->resourceForURL(contextDocument()->completeURL(url), contextDocument()->page()->sessionID());
365     return resource && resource->status() == CachedResource::Cached;
366 }
367
368
369 Node* Internals::treeScopeRootNode(Node* node, ExceptionCode& ec)
370 {
371     if (!node) {
372         ec = INVALID_ACCESS_ERR;
373         return nullptr;
374     }
375
376     return &node->treeScope().rootNode();
377 }
378
379 Node* Internals::parentTreeScope(Node* node, ExceptionCode& ec)
380 {
381     if (!node) {
382         ec = INVALID_ACCESS_ERR;
383         return nullptr;
384     }
385     const TreeScope* parentTreeScope = node->treeScope().parentTreeScope();
386     return parentTreeScope ? &parentTreeScope->rootNode() : nullptr;
387 }
388
389 unsigned Internals::lastSpatialNavigationCandidateCount(ExceptionCode& ec) const
390 {
391     if (!contextDocument() || !contextDocument()->page()) {
392         ec = INVALID_ACCESS_ERR;
393         return 0;
394     }
395
396     return contextDocument()->page()->lastSpatialNavigationCandidateCount();
397 }
398
399 unsigned Internals::numberOfActiveAnimations() const
400 {
401     return frame()->animation().numberOfActiveAnimations(frame()->document());
402 }
403
404 bool Internals::animationsAreSuspended(ExceptionCode& ec) const
405 {
406     Document* document = contextDocument();
407     if (!document || !document->frame()) {
408         ec = INVALID_ACCESS_ERR;
409         return false;
410     }
411
412     return document->frame()->animation().isSuspended();
413 }
414
415 void Internals::suspendAnimations(ExceptionCode& ec) const
416 {
417     Document* document = contextDocument();
418     if (!document || !document->frame()) {
419         ec = INVALID_ACCESS_ERR;
420         return;
421     }
422
423     document->frame()->animation().suspendAnimations();
424 }
425
426 void Internals::resumeAnimations(ExceptionCode& ec) const
427 {
428     Document* document = contextDocument();
429     if (!document || !document->frame()) {
430         ec = INVALID_ACCESS_ERR;
431         return;
432     }
433
434     document->frame()->animation().resumeAnimations();
435 }
436
437 bool Internals::pauseAnimationAtTimeOnElement(const String& animationName, double pauseTime, Element* element, ExceptionCode& ec)
438 {
439     if (!element || pauseTime < 0) {
440         ec = INVALID_ACCESS_ERR;
441         return false;
442     }
443     return frame()->animation().pauseAnimationAtTime(element->renderer(), AtomicString(animationName), pauseTime);
444 }
445
446 bool Internals::pauseAnimationAtTimeOnPseudoElement(const String& animationName, double pauseTime, Element* element, const String& pseudoId, ExceptionCode& ec)
447 {
448     if (!element || pauseTime < 0) {
449         ec = INVALID_ACCESS_ERR;
450         return false;
451     }
452
453     if (pseudoId != "before" && pseudoId != "after") {
454         ec = INVALID_ACCESS_ERR;
455         return false;
456     }
457
458     PseudoElement* pseudoElement = pseudoId == "before" ? element->beforePseudoElement() : element->afterPseudoElement();
459     if (!pseudoElement) {
460         ec = INVALID_ACCESS_ERR;
461         return false;
462     }
463
464     return frame()->animation().pauseAnimationAtTime(pseudoElement->renderer(), AtomicString(animationName), pauseTime);
465 }
466
467 bool Internals::pauseTransitionAtTimeOnElement(const String& propertyName, double pauseTime, Element* element, ExceptionCode& ec)
468 {
469     if (!element || pauseTime < 0) {
470         ec = INVALID_ACCESS_ERR;
471         return false;
472     }
473     return frame()->animation().pauseTransitionAtTime(element->renderer(), propertyName, pauseTime);
474 }
475
476 bool Internals::pauseTransitionAtTimeOnPseudoElement(const String& property, double pauseTime, Element* element, const String& pseudoId, ExceptionCode& ec)
477 {
478     if (!element || pauseTime < 0) {
479         ec = INVALID_ACCESS_ERR;
480         return false;
481     }
482
483     if (pseudoId != "before" && pseudoId != "after") {
484         ec = INVALID_ACCESS_ERR;
485         return false;
486     }
487
488     PseudoElement* pseudoElement = pseudoId == "before" ? element->beforePseudoElement() : element->afterPseudoElement();
489     if (!pseudoElement) {
490         ec = INVALID_ACCESS_ERR;
491         return false;
492     }
493
494     return frame()->animation().pauseTransitionAtTime(pseudoElement->renderer(), property, pauseTime);
495 }
496
497 // FIXME: Remove.
498 bool Internals::attached(Node* node, ExceptionCode& ec)
499 {
500     if (!node) {
501         ec = INVALID_ACCESS_ERR;
502         return false;
503     }
504
505     return true;
506 }
507
508 String Internals::elementRenderTreeAsText(Element* element, ExceptionCode& ec)
509 {
510     if (!element) {
511         ec = INVALID_ACCESS_ERR;
512         return String();
513     }
514
515     element->document().updateStyleIfNeeded();
516
517     String representation = externalRepresentation(element);
518     if (representation.isEmpty()) {
519         ec = INVALID_ACCESS_ERR;
520         return String();
521     }
522
523     return representation;
524 }
525
526 PassRefPtr<CSSComputedStyleDeclaration> Internals::computedStyleIncludingVisitedInfo(Node* node, ExceptionCode& ec) const
527 {
528     if (!node) {
529         ec = INVALID_ACCESS_ERR;
530         return 0;
531     }
532
533     bool allowVisitedStyle = true;
534     return CSSComputedStyleDeclaration::create(node, allowVisitedStyle);
535 }
536
537 Node* Internals::ensureShadowRoot(Element* host, ExceptionCode& ec)
538 {
539     if (!host) {
540         ec = INVALID_ACCESS_ERR;
541         return 0;
542     }
543
544     if (ShadowRoot* shadowRoot = host->shadowRoot())
545         return shadowRoot;
546
547     return host->createShadowRoot(ec).get();
548 }
549
550 Node* Internals::createShadowRoot(Element* host, ExceptionCode& ec)
551 {
552     if (!host) {
553         ec = INVALID_ACCESS_ERR;
554         return 0;
555     }
556     return host->createShadowRoot(ec).get();
557 }
558
559 Node* Internals::shadowRoot(Element* host, ExceptionCode& ec)
560 {
561     if (!host) {
562         ec = INVALID_ACCESS_ERR;
563         return 0;
564     }
565     return host->shadowRoot();
566 }
567
568 String Internals::shadowRootType(const Node* root, ExceptionCode& ec) const
569 {
570     if (!root || !root->isShadowRoot()) {
571         ec = INVALID_ACCESS_ERR;
572         return String();
573     }
574
575     switch (toShadowRoot(root)->type()) {
576     case ShadowRoot::UserAgentShadowRoot:
577         return String("UserAgentShadowRoot");
578     default:
579         ASSERT_NOT_REACHED();
580         return String("Unknown");
581     }
582 }
583
584 Element* Internals::includerFor(Node*, ExceptionCode& ec)
585 {
586     ec = INVALID_ACCESS_ERR;
587     return 0;
588 }
589
590 String Internals::shadowPseudoId(Element* element, ExceptionCode& ec)
591 {
592     if (!element) {
593         ec = INVALID_ACCESS_ERR;
594         return String();
595     }
596
597     return element->shadowPseudoId().string();
598 }
599
600 void Internals::setShadowPseudoId(Element* element, const String& id, ExceptionCode& ec)
601 {
602     if (!element) {
603         ec = INVALID_ACCESS_ERR;
604         return;
605     }
606
607     return element->setPseudo(id);
608 }
609
610 String Internals::visiblePlaceholder(Element* element)
611 {
612     if (element && isHTMLTextFormControlElement(*element)) {
613         if (toHTMLTextFormControlElement(*element).placeholderShouldBeVisible())
614             return toHTMLTextFormControlElement(*element).placeholderElement()->textContent();
615     }
616
617     return String();
618 }
619
620 #if ENABLE(INPUT_TYPE_COLOR)
621 void Internals::selectColorInColorChooser(Element* element, const String& colorValue)
622 {
623     if (!isHTMLInputElement(element))
624         return;
625     HTMLInputElement* inputElement = element->toInputElement();
626     if (!inputElement)
627         return;
628     inputElement->selectColorInColorChooser(Color(colorValue));
629 }
630 #endif
631
632 Vector<String> Internals::formControlStateOfPreviousHistoryItem(ExceptionCode& ec)
633 {
634     HistoryItem* mainItem = frame()->loader().history().previousItem();
635     if (!mainItem) {
636         ec = INVALID_ACCESS_ERR;
637         return Vector<String>();
638     }
639     String uniqueName = frame()->tree().uniqueName();
640     if (mainItem->target() != uniqueName && !mainItem->childItemWithTarget(uniqueName)) {
641         ec = INVALID_ACCESS_ERR;
642         return Vector<String>();
643     }
644     return mainItem->target() == uniqueName ? mainItem->documentState() : mainItem->childItemWithTarget(uniqueName)->documentState();
645 }
646
647 void Internals::setFormControlStateOfPreviousHistoryItem(const Vector<String>& state, ExceptionCode& ec)
648 {
649     HistoryItem* mainItem = frame()->loader().history().previousItem();
650     if (!mainItem) {
651         ec = INVALID_ACCESS_ERR;
652         return;
653     }
654     String uniqueName = frame()->tree().uniqueName();
655     if (mainItem->target() == uniqueName)
656         mainItem->setDocumentState(state);
657     else if (HistoryItem* subItem = mainItem->childItemWithTarget(uniqueName))
658         subItem->setDocumentState(state);
659     else
660         ec = INVALID_ACCESS_ERR;
661 }
662
663 #if ENABLE(SPEECH_SYNTHESIS)
664 void Internals::enableMockSpeechSynthesizer()
665 {
666     Document* document = contextDocument();
667     if (!document || !document->domWindow())
668         return;
669     SpeechSynthesis* synthesis = DOMWindowSpeechSynthesis::speechSynthesis(document->domWindow());
670     if (!synthesis)
671         return;
672     
673     synthesis->setPlatformSynthesizer(std::make_unique<PlatformSpeechSynthesizerMock>(synthesis));
674 }
675 #endif
676
677 #if ENABLE(MEDIA_STREAM)
678 void Internals::enableMockRTCPeerConnectionHandler()
679 {
680     RTCPeerConnectionHandler::create = RTCPeerConnectionHandlerMock::create;
681 }
682 #endif
683
684 PassRefPtr<ClientRect> Internals::absoluteCaretBounds(ExceptionCode& ec)
685 {
686     Document* document = contextDocument();
687     if (!document || !document->frame()) {
688         ec = INVALID_ACCESS_ERR;
689         return ClientRect::create();
690     }
691
692     return ClientRect::create(document->frame()->selection().absoluteCaretBounds());
693 }
694
695 PassRefPtr<ClientRect> Internals::boundingBox(Element* element, ExceptionCode& ec)
696 {
697     if (!element) {
698         ec = INVALID_ACCESS_ERR;
699         return ClientRect::create();
700     }
701
702     element->document().updateLayoutIgnorePendingStylesheets();
703     auto renderer = element->renderer();
704     if (!renderer)
705         return ClientRect::create();
706     return ClientRect::create(renderer->absoluteBoundingBoxRectIgnoringTransforms());
707 }
708
709 PassRefPtr<ClientRectList> Internals::inspectorHighlightRects(ExceptionCode& ec)
710 {
711 #if ENABLE(INSPECTOR)
712     Document* document = contextDocument();
713     if (!document || !document->page()) {
714         ec = INVALID_ACCESS_ERR;
715         return ClientRectList::create();
716     }
717
718     Highlight highlight;
719     document->page()->inspectorController().getHighlight(&highlight);
720     return ClientRectList::create(highlight.quads);
721 #else
722     UNUSED_PARAM(ec);
723     return ClientRectList::create();
724 #endif
725 }
726
727 String Internals::inspectorHighlightObject(ExceptionCode& ec)
728 {
729 #if ENABLE(INSPECTOR)
730     Document* document = contextDocument();
731     if (!document || !document->page()) {
732         ec = INVALID_ACCESS_ERR;
733         return String();
734     }
735     RefPtr<InspectorObject> object = document->page()->inspectorController().buildObjectForHighlightedNode();
736     return object ? object->toJSONString() : String();
737 #else
738     UNUSED_PARAM(ec);
739     return String();
740 #endif
741 }
742
743 unsigned Internals::markerCountForNode(Node* node, const String& markerType, ExceptionCode& ec)
744 {
745     if (!node) {
746         ec = INVALID_ACCESS_ERR;
747         return 0;
748     }
749
750     DocumentMarker::MarkerTypes markerTypes = 0;
751     if (!markerTypesFrom(markerType, markerTypes)) {
752         ec = SYNTAX_ERR;
753         return 0;
754     }
755
756     node->document().frame()->editor().updateEditorUINowIfScheduled();
757
758     return node->document().markers().markersFor(node, markerTypes).size();
759 }
760
761 DocumentMarker* Internals::markerAt(Node* node, const String& markerType, unsigned index, ExceptionCode& ec)
762 {
763     node->document().updateLayoutIgnorePendingStylesheets();
764     if (!node) {
765         ec = INVALID_ACCESS_ERR;
766         return 0;
767     }
768
769     DocumentMarker::MarkerTypes markerTypes = 0;
770     if (!markerTypesFrom(markerType, markerTypes)) {
771         ec = SYNTAX_ERR;
772         return 0;
773     }
774
775     node->document().frame()->editor().updateEditorUINowIfScheduled();
776
777     Vector<DocumentMarker*> markers = node->document().markers().markersFor(node, markerTypes);
778     if (markers.size() <= index)
779         return 0;
780     return markers[index];
781 }
782
783 PassRefPtr<Range> Internals::markerRangeForNode(Node* node, const String& markerType, unsigned index, ExceptionCode& ec)
784 {
785     DocumentMarker* marker = markerAt(node, markerType, index, ec);
786     if (!marker)
787         return 0;
788     return Range::create(node->document(), node, marker->startOffset(), node, marker->endOffset());
789 }
790
791 String Internals::markerDescriptionForNode(Node* node, const String& markerType, unsigned index, ExceptionCode& ec)
792 {
793     DocumentMarker* marker = markerAt(node, markerType, index, ec);
794     if (!marker)
795         return String();
796     return marker->description();
797 }
798
799 void Internals::addTextMatchMarker(const Range* range, bool isActive)
800 {
801     range->ownerDocument().updateLayoutIgnorePendingStylesheets();
802     range->ownerDocument().markers().addTextMatchMarker(range, isActive);
803 }
804
805 void Internals::setMarkedTextMatchesAreHighlighted(bool flag, ExceptionCode& ec)
806 {
807     Document* document = contextDocument();
808     if (!document || !document->frame()) {
809         ec = INVALID_ACCESS_ERR;
810         return;
811     }
812     document->frame()->editor().setMarkedTextMatchesAreHighlighted(flag);
813 }
814
815 void Internals::setScrollViewPosition(long x, long y, ExceptionCode& ec)
816 {
817     Document* document = contextDocument();
818     if (!document || !document->view()) {
819         ec = INVALID_ACCESS_ERR;
820         return;
821     }
822
823     FrameView* frameView = document->view();
824     bool constrainsScrollingToContentEdgeOldValue = frameView->constrainsScrollingToContentEdge();
825     bool scrollbarsSuppressedOldValue = frameView->scrollbarsSuppressed();
826
827     frameView->setConstrainsScrollingToContentEdge(false);
828     frameView->setScrollbarsSuppressed(false);
829     frameView->setScrollOffsetFromInternals(IntPoint(x, y));
830     frameView->setScrollbarsSuppressed(scrollbarsSuppressedOldValue);
831     frameView->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdgeOldValue);
832 }
833
834 void Internals::setPagination(const String& mode, int gap, int pageLength, ExceptionCode& ec)
835 {
836     Document* document = contextDocument();
837     if (!document || !document->page()) {
838         ec = INVALID_ACCESS_ERR;
839         return;
840     }
841     Page* page = document->page();
842
843     Pagination pagination;
844     if (mode == "Unpaginated")
845         pagination.mode = Pagination::Unpaginated;
846     else if (mode == "LeftToRightPaginated")
847         pagination.mode = Pagination::LeftToRightPaginated;
848     else if (mode == "RightToLeftPaginated")
849         pagination.mode = Pagination::RightToLeftPaginated;
850     else if (mode == "TopToBottomPaginated")
851         pagination.mode = Pagination::TopToBottomPaginated;
852     else if (mode == "BottomToTopPaginated")
853         pagination.mode = Pagination::BottomToTopPaginated;
854     else {
855         ec = SYNTAX_ERR;
856         return;
857     }
858
859     pagination.gap = gap;
860     pagination.pageLength = pageLength;
861     page->setPagination(pagination);
862 }
863
864 String Internals::configurationForViewport(float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight, ExceptionCode& ec)
865 {
866     Document* document = contextDocument();
867     if (!document || !document->page()) {
868         ec = INVALID_ACCESS_ERR;
869         return String();
870     }
871     Page* page = document->page();
872
873     const int defaultLayoutWidthForNonMobilePages = 980;
874
875     ViewportArguments arguments = page->viewportArguments();
876     ViewportAttributes attributes = computeViewportAttributes(arguments, defaultLayoutWidthForNonMobilePages, deviceWidth, deviceHeight, devicePixelRatio, IntSize(availableWidth, availableHeight));
877     restrictMinimumScaleFactorToViewportSize(attributes, IntSize(availableWidth, availableHeight), devicePixelRatio);
878     restrictScaleFactorToInitialScaleIfNotUserScalable(attributes);
879
880     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");
881 }
882
883 bool Internals::wasLastChangeUserEdit(Element* textField, ExceptionCode& ec)
884 {
885     if (!textField) {
886         ec = INVALID_ACCESS_ERR;
887         return false;
888     }
889
890     if (HTMLInputElement* inputElement = textField->toInputElement())
891         return inputElement->lastChangeWasUserEdit();
892
893     // FIXME: We should be using hasTagName instead but Windows port doesn't link QualifiedNames properly.
894     if (textField->tagName() == "TEXTAREA")
895         return toHTMLTextAreaElement(textField)->lastChangeWasUserEdit();
896
897     ec = INVALID_NODE_TYPE_ERR;
898     return false;
899 }
900
901 bool Internals::elementShouldAutoComplete(Element* element, ExceptionCode& ec)
902 {
903     if (!element) {
904         ec = INVALID_ACCESS_ERR;
905         return false;
906     }
907
908     if (HTMLInputElement* inputElement = element->toInputElement())
909         return inputElement->shouldAutocomplete();
910
911     ec = INVALID_NODE_TYPE_ERR;
912     return false;
913 }
914
915 String Internals::suggestedValue(Element* element, ExceptionCode& ec)
916 {
917     if (!element) {
918         ec = INVALID_ACCESS_ERR;
919         return String();
920     }
921
922     HTMLInputElement* inputElement = element->toInputElement();
923     if (!inputElement) {
924         ec = INVALID_NODE_TYPE_ERR;
925         return String();
926     }
927
928     return inputElement->suggestedValue();
929 }
930
931 void Internals::setSuggestedValue(Element* element, const String& value, ExceptionCode& ec)
932 {
933     if (!element) {
934         ec = INVALID_ACCESS_ERR;
935         return;
936     }
937
938     HTMLInputElement* inputElement = element->toInputElement();
939     if (!inputElement) {
940         ec = INVALID_NODE_TYPE_ERR;
941         return;
942     }
943
944     inputElement->setSuggestedValue(value);
945 }
946
947 void Internals::setEditingValue(Element* element, const String& value, ExceptionCode& ec)
948 {
949     if (!element) {
950         ec = INVALID_ACCESS_ERR;
951         return;
952     }
953
954     HTMLInputElement* inputElement = element->toInputElement();
955     if (!inputElement) {
956         ec = INVALID_NODE_TYPE_ERR;
957         return;
958     }
959
960     inputElement->setEditingValue(value);
961 }
962
963 void Internals::setAutofilled(Element* element, bool enabled, ExceptionCode& ec)
964 {
965     HTMLInputElement* inputElement = element->toInputElement();
966     if (!inputElement) {
967         ec = INVALID_ACCESS_ERR;
968         return;
969     }
970     inputElement->setAutofilled(enabled);
971 }
972
973 void Internals::scrollElementToRect(Element* element, long x, long y, long w, long h, ExceptionCode& ec)
974 {
975     if (!element || !element->document().view()) {
976         ec = INVALID_ACCESS_ERR;
977         return;
978     }
979     FrameView* frameView = element->document().view();
980     frameView->scrollElementToRect(element, IntRect(x, y, w, h));
981 }
982
983 void Internals::paintControlTints(ExceptionCode& ec)
984 {
985     Document* document = contextDocument();
986     if (!document || !document->view()) {
987         ec = INVALID_ACCESS_ERR;
988         return;
989     }
990
991     FrameView* frameView = document->view();
992     frameView->paintControlTints();
993 }
994
995 PassRefPtr<Range> Internals::rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength, ExceptionCode& ec)
996 {
997     if (!scope) {
998         ec = INVALID_ACCESS_ERR;
999         return 0;
1000     }
1001
1002     return TextIterator::rangeFromLocationAndLength(scope, rangeLocation, rangeLength);
1003 }
1004
1005 unsigned Internals::locationFromRange(Element* scope, const Range* range, ExceptionCode& ec)
1006 {
1007     if (!scope || !range) {
1008         ec = INVALID_ACCESS_ERR;
1009         return 0;
1010     }
1011
1012     size_t location = 0;
1013     size_t unusedLength = 0;
1014     TextIterator::getLocationAndLengthFromRange(scope, range, location, unusedLength);
1015     return location;
1016 }
1017
1018 unsigned Internals::lengthFromRange(Element* scope, const Range* range, ExceptionCode& ec)
1019 {
1020     if (!scope || !range) {
1021         ec = INVALID_ACCESS_ERR;
1022         return 0;
1023     }
1024
1025     size_t unusedLocation = 0;
1026     size_t length = 0;
1027     TextIterator::getLocationAndLengthFromRange(scope, range, unusedLocation, length);
1028     return length;
1029 }
1030
1031 String Internals::rangeAsText(const Range* range, ExceptionCode& ec)
1032 {
1033     if (!range) {
1034         ec = INVALID_ACCESS_ERR;
1035         return String();
1036     }
1037
1038     return range->text();
1039 }
1040
1041 void Internals::setDelegatesScrolling(bool enabled, ExceptionCode& ec)
1042 {
1043     Document* document = contextDocument();
1044     // Delegate scrolling is valid only on mainframe's view.
1045     if (!document || !document->view() || !document->page() || &document->page()->mainFrame() != document->frame()) {
1046         ec = INVALID_ACCESS_ERR;
1047         return;
1048     }
1049
1050     document->view()->setDelegatesScrolling(enabled);
1051 }
1052
1053 int Internals::lastSpellCheckRequestSequence(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().lastRequestSequence();
1062 }
1063
1064 int Internals::lastSpellCheckProcessedSequence(ExceptionCode& ec)
1065 {
1066     Document* document = contextDocument();
1067     if (!document || !document->frame()) {
1068         ec = INVALID_ACCESS_ERR;
1069         return -1;
1070     }
1071
1072     return document->frame()->editor().spellChecker().lastProcessedSequence();
1073 }
1074
1075 Vector<String> Internals::userPreferredLanguages() const
1076 {
1077     return WebCore::userPreferredLanguages();
1078 }
1079
1080 void Internals::setUserPreferredLanguages(const Vector<String>& languages)
1081 {
1082     WebCore::overrideUserPreferredLanguages(languages);
1083 }
1084
1085 unsigned Internals::wheelEventHandlerCount(ExceptionCode& ec)
1086 {
1087     Document* document = contextDocument();
1088     if (!document) {
1089         ec = INVALID_ACCESS_ERR;
1090         return 0;
1091     }
1092
1093     return document->wheelEventHandlerCount();
1094 }
1095
1096 unsigned Internals::touchEventHandlerCount(ExceptionCode& ec)
1097 {
1098     Document* document = contextDocument();
1099     if (!document) {
1100         ec = INVALID_ACCESS_ERR;
1101         return 0;
1102     }
1103
1104     const TouchEventTargetSet* touchHandlers = document->touchEventTargets();
1105     if (!touchHandlers)
1106         return 0;
1107
1108     unsigned count = 0;
1109     for (TouchEventTargetSet::const_iterator iter = touchHandlers->begin(); iter != touchHandlers->end(); ++iter)
1110         count += iter->value;
1111     return count;
1112 }
1113
1114 // FIXME: Remove the document argument. It is almost always the same as
1115 // contextDocument(), with the exception of a few tests that pass a
1116 // different document, and could just make the call through another Internals
1117 // instance instead.
1118 PassRefPtr<NodeList> Internals::nodesFromRect(Document* document, int centerX, int centerY, unsigned topPadding, unsigned rightPadding,
1119     unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent, bool allowChildFrameContent, ExceptionCode& ec) const
1120 {
1121     if (!document || !document->frame() || !document->frame()->view()) {
1122         ec = INVALID_ACCESS_ERR;
1123         return 0;
1124     }
1125
1126     Frame* frame = document->frame();
1127     FrameView* frameView = document->view();
1128     RenderView* renderView = document->renderView();
1129     if (!renderView)
1130         return 0;
1131
1132     document->updateLayoutIgnorePendingStylesheets();
1133
1134     float zoomFactor = frame->pageZoomFactor();
1135     LayoutPoint point = roundedLayoutPoint(FloatPoint(centerX * zoomFactor + frameView->scrollX(), centerY * zoomFactor + frameView->scrollY()));
1136
1137     HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active;
1138     if (ignoreClipping)
1139         hitType |= HitTestRequest::IgnoreClipping;
1140     if (!allowShadowContent)
1141         hitType |= HitTestRequest::DisallowShadowContent;
1142     if (allowChildFrameContent)
1143         hitType |= HitTestRequest::AllowChildFrameContent;
1144
1145     HitTestRequest request(hitType);
1146
1147     // When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
1148     if (!request.ignoreClipping() && !frameView->visibleContentRect().intersects(HitTestLocation::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
1149         return 0;
1150
1151     Vector<Ref<Node>> matches;
1152
1153     // Need padding to trigger a rect based hit test, but we want to return a NodeList
1154     // so we special case this.
1155     if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) {
1156         HitTestResult result(point);
1157         renderView->hitTest(request, result);
1158         if (result.innerNode())
1159             matches.append(*result.innerNode()->deprecatedShadowAncestorNode());
1160     } else {
1161         HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding);
1162         renderView->hitTest(request, result);
1163         
1164         const HitTestResult::NodeSet& nodeSet = result.rectBasedTestResult();
1165         matches.reserveInitialCapacity(nodeSet.size());
1166         for (auto it = nodeSet.begin(), end = nodeSet.end(); it != end; ++it)
1167             matches.uncheckedAppend(*it->get());
1168     }
1169
1170     return StaticNodeList::adopt(matches);
1171 }
1172
1173 class GetCallerCodeBlockFunctor {
1174 public:
1175     GetCallerCodeBlockFunctor()
1176         : m_iterations(0)
1177         , m_codeBlock(0)
1178     {
1179     }
1180
1181     StackVisitor::Status operator()(StackVisitor& visitor)
1182     {
1183         ++m_iterations;
1184         if (m_iterations < 2)
1185             return StackVisitor::Continue;
1186
1187         m_codeBlock = visitor->codeBlock();
1188         return StackVisitor::Done;
1189     }
1190
1191     CodeBlock* codeBlock() const { return m_codeBlock; }
1192
1193 private:
1194     int m_iterations;
1195     CodeBlock* m_codeBlock;
1196 };
1197
1198 String Internals::parserMetaData(Deprecated::ScriptValue value)
1199 {
1200     JSC::VM& vm = contextDocument()->vm();
1201     JSC::ExecState* exec = vm.topCallFrame;
1202     JSC::JSValue code = value.jsValue();
1203     ScriptExecutable* executable;
1204
1205     if (!code || code.isNull() || code.isUndefined()) {
1206         GetCallerCodeBlockFunctor iter;
1207         exec->iterate(iter);
1208         CodeBlock* codeBlock = iter.codeBlock();
1209         executable = codeBlock->ownerExecutable(); 
1210     } else if (code.isFunction()) {
1211         JSFunction* funcObj = JSC::jsCast<JSFunction*>(code.toObject(exec));
1212         executable = funcObj->jsExecutable();
1213     } else
1214         return String();
1215
1216     unsigned startLine = executable->lineNo();
1217     unsigned startColumn = executable->startColumn();
1218     unsigned endLine = executable->lastLine();
1219     unsigned endColumn = executable->endColumn();
1220
1221     StringBuilder result;
1222
1223     if (executable->isFunctionExecutable()) {
1224         FunctionExecutable* funcExecutable = reinterpret_cast<FunctionExecutable*>(executable);
1225         String inferredName = funcExecutable->inferredName().string();
1226         result.append("function \"");
1227         result.append(inferredName);
1228         result.append("\"");
1229     } else if (executable->isEvalExecutable())
1230         result.append("eval");
1231     else {
1232         ASSERT(executable->isProgramExecutable());
1233         result.append("program");
1234     }
1235
1236     result.append(" { ");
1237     result.appendNumber(startLine);
1238     result.append(":");
1239     result.appendNumber(startColumn);
1240     result.append(" - ");
1241     result.appendNumber(endLine);
1242     result.append(":");
1243     result.appendNumber(endColumn);
1244     result.append(" }");
1245
1246     return result.toString();
1247 }
1248
1249 void Internals::setBatteryStatus(const String& eventType, bool charging, double chargingTime, double dischargingTime, double level, ExceptionCode& ec)
1250 {
1251     Document* document = contextDocument();
1252     if (!document || !document->page()) {
1253         ec = INVALID_ACCESS_ERR;
1254         return;
1255     }
1256
1257 #if ENABLE(BATTERY_STATUS)
1258     BatteryController::from(document->page())->didChangeBatteryStatus(eventType, BatteryStatus::create(charging, chargingTime, dischargingTime, level));
1259 #else
1260     UNUSED_PARAM(eventType);
1261     UNUSED_PARAM(charging);
1262     UNUSED_PARAM(chargingTime);
1263     UNUSED_PARAM(dischargingTime);
1264     UNUSED_PARAM(level);
1265 #endif
1266 }
1267
1268 void Internals::setDeviceProximity(const String& eventType, double value, double min, double max, ExceptionCode& ec)
1269 {
1270     Document* document = contextDocument();
1271     if (!document || !document->page()) {
1272         ec = INVALID_ACCESS_ERR;
1273         return;
1274     }
1275
1276 #if ENABLE(PROXIMITY_EVENTS)
1277     DeviceProximityController::from(document->page())->didChangeDeviceProximity(value, min, max);
1278 #else
1279     UNUSED_PARAM(eventType);
1280     UNUSED_PARAM(value);
1281     UNUSED_PARAM(min);
1282     UNUSED_PARAM(max);
1283 #endif
1284 }
1285
1286 void Internals::updateEditorUINowIfScheduled()
1287 {
1288     if (Document* document = contextDocument()) {
1289         if (Frame* frame = document->frame())
1290             frame->editor().updateEditorUINowIfScheduled();
1291     }
1292 }
1293
1294 Node* Internals::findEditingDeleteButton()
1295 {
1296     Document* document = contextDocument();
1297     if (!document || !document->frame())
1298         return 0;
1299
1300     updateEditorUINowIfScheduled();
1301
1302     // FIXME: We shouldn't pollute the id namespace with this name.
1303     return document->getElementById(String(ASCIILiteral("WebKit-Editing-Delete-Button")));
1304 }
1305
1306 bool Internals::hasSpellingMarker(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::Spelling, from, length);
1315 }
1316     
1317 bool Internals::hasAutocorrectedMarker(int from, int length, ExceptionCode&)
1318 {
1319     Document* document = contextDocument();
1320     if (!document || !document->frame())
1321         return 0;
1322
1323     updateEditorUINowIfScheduled();
1324
1325     return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Autocorrected, from, length);
1326 }
1327
1328 void Internals::setContinuousSpellCheckingEnabled(bool enabled, ExceptionCode&)
1329 {
1330     if (!contextDocument() || !contextDocument()->frame())
1331         return;
1332
1333     if (enabled != contextDocument()->frame()->editor().isContinuousSpellCheckingEnabled())
1334         contextDocument()->frame()->editor().toggleContinuousSpellChecking();
1335 }
1336
1337 void Internals::setAutomaticQuoteSubstitutionEnabled(bool enabled, ExceptionCode&)
1338 {
1339     if (!contextDocument() || !contextDocument()->frame())
1340         return;
1341
1342 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1343     if (enabled != contextDocument()->frame()->editor().isAutomaticQuoteSubstitutionEnabled())
1344         contextDocument()->frame()->editor().toggleAutomaticQuoteSubstitution();
1345 #else
1346     UNUSED_PARAM(enabled);
1347 #endif
1348 }
1349
1350 void Internals::setAutomaticLinkDetectionEnabled(bool enabled, ExceptionCode&)
1351 {
1352     if (!contextDocument() || !contextDocument()->frame())
1353         return;
1354
1355 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1356     if (enabled != contextDocument()->frame()->editor().isAutomaticLinkDetectionEnabled())
1357         contextDocument()->frame()->editor().toggleAutomaticLinkDetection();
1358 #else
1359     UNUSED_PARAM(enabled);
1360 #endif
1361 }
1362
1363 void Internals::setAutomaticDashSubstitutionEnabled(bool enabled, ExceptionCode&)
1364 {
1365     if (!contextDocument() || !contextDocument()->frame())
1366         return;
1367
1368 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1369     if (enabled != contextDocument()->frame()->editor().isAutomaticDashSubstitutionEnabled())
1370         contextDocument()->frame()->editor().toggleAutomaticDashSubstitution();
1371 #else
1372     UNUSED_PARAM(enabled);
1373 #endif
1374 }
1375
1376 void Internals::setAutomaticTextReplacementEnabled(bool enabled, ExceptionCode&)
1377 {
1378     if (!contextDocument() || !contextDocument()->frame())
1379         return;
1380
1381 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1382     if (enabled != contextDocument()->frame()->editor().isAutomaticTextReplacementEnabled())
1383         contextDocument()->frame()->editor().toggleAutomaticTextReplacement();
1384 #else
1385     UNUSED_PARAM(enabled);
1386 #endif
1387 }
1388
1389 void Internals::setAutomaticSpellingCorrectionEnabled(bool enabled, ExceptionCode&)
1390 {
1391     if (!contextDocument() || !contextDocument()->frame())
1392         return;
1393
1394 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1395     if (enabled != contextDocument()->frame()->editor().isAutomaticSpellingCorrectionEnabled())
1396         contextDocument()->frame()->editor().toggleAutomaticSpellingCorrection();
1397 #else
1398     UNUSED_PARAM(enabled);
1399 #endif
1400 }
1401
1402 bool Internals::isOverwriteModeEnabled(ExceptionCode&)
1403 {
1404     Document* document = contextDocument();
1405     if (!document || !document->frame())
1406         return 0;
1407
1408     return document->frame()->editor().isOverwriteModeEnabled();
1409 }
1410
1411 void Internals::toggleOverwriteModeEnabled(ExceptionCode&)
1412 {
1413     Document* document = contextDocument();
1414     if (!document || !document->frame())
1415         return;
1416
1417     document->frame()->editor().toggleOverwriteModeEnabled();
1418 }
1419
1420 unsigned Internals::countMatchesForText(const String& text, unsigned findOptions, const String& markMatches, ExceptionCode&)
1421 {
1422     Document* document = contextDocument();
1423     if (!document || !document->frame())
1424         return 0;
1425
1426     bool mark = markMatches == "mark";
1427     return document->frame()->editor().countMatchesForText(text, nullptr, findOptions, 1000, mark, nullptr);
1428 }
1429
1430 const ProfilesArray& Internals::consoleProfiles() const
1431 {
1432     return contextDocument()->page()->console().profiles();
1433 }
1434
1435 unsigned Internals::numberOfLiveNodes() const
1436 {
1437     unsigned nodeCount = 0;
1438     for (auto* document : Document::allDocuments())
1439         nodeCount += document->referencingNodeCount();
1440     return nodeCount;
1441 }
1442
1443 unsigned Internals::numberOfLiveDocuments() const
1444 {
1445     return Document::allDocuments().size();
1446 }
1447
1448 #if ENABLE(INSPECTOR)
1449 Vector<String> Internals::consoleMessageArgumentCounts() const
1450 {
1451     Document* document = contextDocument();
1452     if (!document || !document->page())
1453         return Vector<String>();
1454
1455     InstrumentingAgents* instrumentingAgents = instrumentationForPage(document->page());
1456     if (!instrumentingAgents)
1457         return Vector<String>();
1458
1459     InspectorConsoleAgent* consoleAgent = instrumentingAgents->webConsoleAgent();
1460     if (!consoleAgent)
1461         return Vector<String>();
1462
1463     Vector<unsigned> counts = consoleAgent->consoleMessageArgumentCounts();
1464     Vector<String> result(counts.size());
1465     for (size_t i = 0; i < counts.size(); i++)
1466         result[i] = String::number(counts[i]);
1467     return result;
1468 }
1469
1470 PassRefPtr<DOMWindow> Internals::openDummyInspectorFrontend(const String& url)
1471 {
1472     Page* page = contextDocument()->frame()->page();
1473     ASSERT(page);
1474
1475     DOMWindow* window = page->mainFrame().document()->domWindow();
1476     ASSERT(window);
1477
1478     m_frontendWindow = window->open(url, "", "", *window, *window);
1479     ASSERT(m_frontendWindow);
1480
1481     Page* frontendPage = m_frontendWindow->document()->page();
1482     ASSERT(frontendPage);
1483
1484     auto frontendClient = std::make_unique<InspectorFrontendClientDummy>(&page->inspectorController(), frontendPage);
1485
1486     frontendPage->inspectorController().setInspectorFrontendClient(std::move(frontendClient));
1487
1488     m_frontendChannel = adoptPtr(new InspectorFrontendChannelDummy(frontendPage));
1489
1490     page->inspectorController().connectFrontend(m_frontendChannel.get());
1491
1492     return m_frontendWindow;
1493 }
1494
1495 void Internals::closeDummyInspectorFrontend()
1496 {
1497     Page* page = contextDocument()->frame()->page();
1498     ASSERT(page);
1499     ASSERT(m_frontendWindow);
1500
1501     page->inspectorController().disconnectFrontend(InspectorDisconnectReason::InspectorDestroyed);
1502
1503     m_frontendChannel.release();
1504
1505     m_frontendWindow->close(m_frontendWindow->scriptExecutionContext());
1506     m_frontendWindow.release();
1507 }
1508
1509 void Internals::setJavaScriptProfilingEnabled(bool enabled, ExceptionCode& ec)
1510 {
1511     Page* page = contextDocument()->frame()->page();
1512     if (!page) {
1513         ec = INVALID_ACCESS_ERR;
1514         return;
1515     }
1516
1517     page->inspectorController().setProfilerEnabled(enabled);
1518 }
1519
1520 void Internals::setInspectorIsUnderTest(bool isUnderTest, ExceptionCode& ec)
1521 {
1522     Page* page = contextDocument()->frame()->page();
1523     if (!page) {
1524         ec = INVALID_ACCESS_ERR;
1525         return;
1526     }
1527
1528     page->inspectorController().setIsUnderTest(isUnderTest);
1529 }
1530 #endif // ENABLE(INSPECTOR)
1531
1532 bool Internals::hasGrammarMarker(int from, int length, ExceptionCode&)
1533 {
1534     Document* document = contextDocument();
1535     if (!document || !document->frame())
1536         return 0;
1537
1538     return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Grammar, from, length);
1539 }
1540
1541 unsigned Internals::numberOfScrollableAreas(ExceptionCode&)
1542 {
1543     Document* document = contextDocument();
1544     if (!document || !document->frame())
1545         return 0;
1546
1547     unsigned count = 0;
1548     Frame* frame = document->frame();
1549     if (frame->view()->scrollableAreas())
1550         count += frame->view()->scrollableAreas()->size();
1551
1552     for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
1553         if (child->view() && child->view()->scrollableAreas())
1554             count += child->view()->scrollableAreas()->size();
1555     }
1556
1557     return count;
1558 }
1559     
1560 bool Internals::isPageBoxVisible(int pageNumber, ExceptionCode& ec)
1561 {
1562     Document* document = contextDocument();
1563     if (!document) {
1564         ec = INVALID_ACCESS_ERR;
1565         return false;
1566     }
1567
1568     return document->isPageBoxVisible(pageNumber);
1569 }
1570
1571 // FIXME: Remove the document argument. It is almost always the same as
1572 // contextDocument(), with the exception of a few tests that pass a
1573 // different document, and could just make the call through another Internals
1574 // instance instead.
1575 String Internals::layerTreeAsText(Document* document, ExceptionCode& ec) const
1576 {
1577     return layerTreeAsText(document, 0, ec);
1578 }
1579
1580 String Internals::layerTreeAsText(Document* document, unsigned flags, ExceptionCode& ec) const
1581 {
1582     if (!document || !document->frame()) {
1583         ec = INVALID_ACCESS_ERR;
1584         return String();
1585     }
1586
1587     LayerTreeFlags layerTreeFlags = 0;
1588     if (flags & LAYER_TREE_INCLUDES_VISIBLE_RECTS)
1589         layerTreeFlags |= LayerTreeFlagsIncludeVisibleRects;
1590     if (flags & LAYER_TREE_INCLUDES_TILE_CACHES)
1591         layerTreeFlags |= LayerTreeFlagsIncludeTileCaches;
1592     if (flags & LAYER_TREE_INCLUDES_REPAINT_RECTS)
1593         layerTreeFlags |= LayerTreeFlagsIncludeRepaintRects;
1594     if (flags & LAYER_TREE_INCLUDES_PAINTING_PHASES)
1595         layerTreeFlags |= LayerTreeFlagsIncludePaintingPhases;
1596     if (flags & LAYER_TREE_INCLUDES_CONTENT_LAYERS)
1597         layerTreeFlags |= LayerTreeFlagsIncludeContentLayers;
1598
1599     return document->frame()->layerTreeAsText(layerTreeFlags);
1600 }
1601
1602 String Internals::repaintRectsAsText(ExceptionCode& ec) const
1603 {
1604     Document* document = contextDocument();
1605     if (!document || !document->frame()) {
1606         ec = INVALID_ACCESS_ERR;
1607         return String();
1608     }
1609
1610     return document->frame()->trackedRepaintRectsAsText();
1611 }
1612
1613 String Internals::scrollingStateTreeAsText(ExceptionCode& ec) const
1614 {
1615     Document* document = contextDocument();
1616     if (!document || !document->frame()) {
1617         ec = INVALID_ACCESS_ERR;
1618         return String();
1619     }
1620
1621     Page* page = document->page();
1622     if (!page)
1623         return String();
1624
1625     return page->scrollingStateTreeAsText();
1626 }
1627
1628 String Internals::mainThreadScrollingReasons(ExceptionCode& ec) const
1629 {
1630     Document* document = contextDocument();
1631     if (!document || !document->frame()) {
1632         ec = INVALID_ACCESS_ERR;
1633         return String();
1634     }
1635
1636     Page* page = document->page();
1637     if (!page)
1638         return String();
1639
1640     return page->synchronousScrollingReasonsAsText();
1641 }
1642
1643 PassRefPtr<ClientRectList> Internals::nonFastScrollableRects(ExceptionCode& ec) const
1644 {
1645     Document* document = contextDocument();
1646     if (!document || !document->frame()) {
1647         ec = INVALID_ACCESS_ERR;
1648         return 0;
1649     }
1650
1651     Page* page = document->page();
1652     if (!page)
1653         return 0;
1654
1655     return page->nonFastScrollableRects(document->frame());
1656 }
1657
1658 void Internals::garbageCollectDocumentResources(ExceptionCode& ec) const
1659 {
1660     Document* document = contextDocument();
1661     if (!document) {
1662         ec = INVALID_ACCESS_ERR;
1663         return;
1664     }
1665
1666     CachedResourceLoader* cachedResourceLoader = document->cachedResourceLoader();
1667     if (!cachedResourceLoader)
1668         return;
1669     cachedResourceLoader->garbageCollectDocumentResources();
1670 }
1671
1672 void Internals::allowRoundingHacks() const
1673 {
1674     TextRun::setAllowsRoundingHacks(true);
1675 }
1676
1677 void Internals::insertAuthorCSS(const String& css, ExceptionCode& ec) const
1678 {
1679     Document* document = contextDocument();
1680     if (!document) {
1681         ec = INVALID_ACCESS_ERR;
1682         return;
1683     }
1684
1685     auto parsedSheet = StyleSheetContents::create(*document);
1686     parsedSheet.get().setIsUserStyleSheet(false);
1687     parsedSheet.get().parseString(css);
1688     document->styleSheetCollection().addAuthorSheet(std::move(parsedSheet));
1689 }
1690
1691 void Internals::insertUserCSS(const String& css, ExceptionCode& ec) const
1692 {
1693     Document* document = contextDocument();
1694     if (!document) {
1695         ec = INVALID_ACCESS_ERR;
1696         return;
1697     }
1698
1699     auto parsedSheet = StyleSheetContents::create(*document);
1700     parsedSheet.get().setIsUserStyleSheet(true);
1701     parsedSheet.get().parseString(css);
1702     document->styleSheetCollection().addUserSheet(std::move(parsedSheet));
1703 }
1704
1705 String Internals::counterValue(Element* element)
1706 {
1707     if (!element)
1708         return String();
1709
1710     return counterValueForElement(element);
1711 }
1712
1713 int Internals::pageNumber(Element* element, float pageWidth, float pageHeight)
1714 {
1715     if (!element)
1716         return 0;
1717
1718     return PrintContext::pageNumberForElement(element, FloatSize(pageWidth, pageHeight));
1719 }
1720
1721 Vector<String> Internals::iconURLs(Document* document, int iconTypesMask) const
1722 {
1723     Vector<IconURL> iconURLs = document->iconURLs(iconTypesMask);
1724     Vector<String> array;
1725
1726     Vector<IconURL>::const_iterator iter(iconURLs.begin());
1727     for (; iter != iconURLs.end(); ++iter)
1728         array.append(iter->m_iconURL.string());
1729
1730     return array;
1731 }
1732
1733 Vector<String> Internals::shortcutIconURLs() const
1734 {
1735     return iconURLs(contextDocument(), Favicon);
1736 }
1737
1738 Vector<String> Internals::allIconURLs() const
1739 {
1740     return iconURLs(contextDocument(), Favicon | TouchIcon | TouchPrecomposedIcon);
1741 }
1742
1743 int Internals::numberOfPages(float pageWidth, float pageHeight)
1744 {
1745     if (!frame())
1746         return -1;
1747
1748     return PrintContext::numberOfPages(frame(), FloatSize(pageWidth, pageHeight));
1749 }
1750
1751 String Internals::pageProperty(String propertyName, int pageNumber, ExceptionCode& ec) const
1752 {
1753     if (!frame()) {
1754         ec = INVALID_ACCESS_ERR;
1755         return String();
1756     }
1757
1758     return PrintContext::pageProperty(frame(), propertyName.utf8().data(), pageNumber);
1759 }
1760
1761 String Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft, ExceptionCode& ec) const
1762 {
1763     if (!frame()) {
1764         ec = INVALID_ACCESS_ERR;
1765         return String();
1766     }
1767
1768     return PrintContext::pageSizeAndMarginsInPixels(frame(), pageNumber, width, height, marginTop, marginRight, marginBottom, marginLeft);
1769 }
1770
1771 void Internals::setPageScaleFactor(float scaleFactor, int x, int y, ExceptionCode& ec)
1772 {
1773     Document* document = contextDocument();
1774     if (!document || !document->page()) {
1775         ec = INVALID_ACCESS_ERR;
1776         return;
1777     }
1778     Page* page = document->page();
1779     page->setPageScaleFactor(scaleFactor, IntPoint(x, y));
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 (node->isDocumentNode())
1920         document = toDocument(node);
1921     else if (node->hasTagName(HTMLNames::iframeTag))
1922         document = toHTMLIFrameElement(node)->contentDocument();
1923     else {
1924         ec = TypeError;
1925         return;
1926     }
1927
1928     document->updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasksSynchronously);
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.append("type=");
1999     result.append(cursorTypeToString(cursor.type()));
2000     result.append(" 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.append(" 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.append(" 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 = toHTMLMediaElement(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 (!isHTMLSelectElement(node))
2087         return false;
2088
2089     HTMLSelectElement* select = toHTMLSelectElement(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 = toHTMLPlugInElement(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 #endif
2248
2249 #if ENABLE(VIDEO)
2250 void Internals::beginMediaSessionInterruption()
2251 {
2252     MediaSessionManager::sharedManager().beginInterruption(MediaSession::SystemInterruption);
2253 }
2254
2255 void Internals::endMediaSessionInterruption(const String& flagsString)
2256 {
2257     MediaSession::EndInterruptionFlags flags = MediaSession::NoFlags;
2258
2259     if (equalIgnoringCase(flagsString, "MayResumePlaying"))
2260         flags = MediaSession::MayResumePlaying;
2261     
2262     MediaSessionManager::sharedManager().endInterruption(flags);
2263 }
2264
2265 void Internals::applicationWillEnterForeground() const
2266 {
2267     MediaSessionManager::sharedManager().applicationWillEnterForeground();
2268 }
2269
2270 void Internals::applicationWillEnterBackground() const
2271 {
2272     MediaSessionManager::sharedManager().applicationWillEnterBackground();
2273 }
2274
2275 void Internals::setMediaSessionRestrictions(const String& mediaTypeString, const String& restrictionsString, ExceptionCode& ec)
2276 {
2277     MediaSession::MediaType mediaType = MediaSession::None;
2278     if (equalIgnoringCase(mediaTypeString, "Video"))
2279         mediaType = MediaSession::Video;
2280     else if (equalIgnoringCase(mediaTypeString, "Audio"))
2281         mediaType = MediaSession::Audio;
2282     else if (equalIgnoringCase(mediaTypeString, "WebAudio"))
2283         mediaType = MediaSession::WebAudio;
2284     else {
2285         ec = INVALID_ACCESS_ERR;
2286         return;
2287     }
2288
2289     MediaSessionManager::SessionRestrictions restrictions = MediaSessionManager::sharedManager().restrictions(mediaType);
2290     MediaSessionManager::sharedManager().removeRestriction(mediaType, restrictions);
2291
2292     restrictions = MediaSessionManager::NoRestrictions;
2293     
2294     if (equalIgnoringCase(restrictionsString, "ConcurrentPlaybackNotPermitted"))
2295         restrictions = MediaSessionManager::ConcurrentPlaybackNotPermitted;
2296     if (equalIgnoringCase(restrictionsString, "InlineVideoPlaybackRestricted"))
2297         restrictions += MediaSessionManager::InlineVideoPlaybackRestricted;
2298     if (equalIgnoringCase(restrictionsString, "MetadataPreloadingNotPermitted"))
2299         restrictions += MediaSessionManager::MetadataPreloadingNotPermitted;
2300     if (equalIgnoringCase(restrictionsString, "AutoPreloadingNotPermitted"))
2301         restrictions += MediaSessionManager::AutoPreloadingNotPermitted;
2302     if (equalIgnoringCase(restrictionsString, "BackgroundPlaybackNotPermitted"))
2303         restrictions += MediaSessionManager::BackgroundPlaybackNotPermitted;
2304
2305     MediaSessionManager::sharedManager().addRestriction(mediaType, restrictions);
2306 }
2307     
2308 void Internals::postRemoteControlCommand(const String& commandString, ExceptionCode& ec)
2309 {
2310     MediaSession::RemoteControlCommandType command;
2311     
2312     if (equalIgnoringCase(commandString, "Play"))
2313         command = MediaSession::PlayCommand;
2314     else if (equalIgnoringCase(commandString, "Pause"))
2315         command = MediaSession::PauseCommand;
2316     else if (equalIgnoringCase(commandString, "Stop"))
2317         command = MediaSession::StopCommand;
2318     else if (equalIgnoringCase(commandString, "TogglePlayPause"))
2319         command = MediaSession::TogglePlayPauseCommand;
2320     else if (equalIgnoringCase(commandString, "BeginSeekingBackward"))
2321         command = MediaSession::BeginSeekingBackwardCommand;
2322     else if (equalIgnoringCase(commandString, "EndSeekingBackward"))
2323         command = MediaSession::EndSeekingBackwardCommand;
2324     else if (equalIgnoringCase(commandString, "BeginSeekingForward"))
2325         command = MediaSession::BeginSeekingForwardCommand;
2326     else if (equalIgnoringCase(commandString, "EndSeekingForward"))
2327         command = MediaSession::EndSeekingForwardCommand;
2328     else {
2329         ec = INVALID_ACCESS_ERR;
2330         return;
2331     }
2332     
2333     MediaSessionManager::sharedManager().didReceiveRemoteControlCommand(command);
2334 }
2335 #endif // ENABLE(VIDEO)
2336
2337 void Internals::simulateSystemSleep() const
2338 {
2339 #if ENABLE(VIDEO)
2340     MediaSessionManager::sharedManager().systemWillSleep();
2341 #endif
2342 }
2343
2344 void Internals::simulateSystemWake() const
2345 {
2346 #if ENABLE(VIDEO)
2347     MediaSessionManager::sharedManager().systemDidWake();
2348 #endif
2349 }
2350
2351 }