e0be09cda153b4a1823b3cad262dff622554d30d
[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 "HTMLInputElement.h"
54 #include "HTMLNames.h"
55 #include "HTMLPlugInElement.h"
56 #include "HTMLSelectElement.h"
57 #include "HTMLTextAreaElement.h"
58 #include "HistoryController.h"
59 #include "HistoryItem.h"
60 #include "InspectorClient.h"
61 #include "InspectorController.h"
62 #include "InspectorForwarding.h"
63 #include "InspectorFrontendClientLocal.h"
64 #include "InspectorInstrumentation.h"
65 #include "InspectorOverlay.h"
66 #include "InstrumentingAgents.h"
67 #include "IntRect.h"
68 #include "InternalSettings.h"
69 #include "Language.h"
70 #include "MainFrame.h"
71 #include "MallocStatistics.h"
72 #include "MediaPlayer.h"
73 #include "MediaSessionManager.h"
74 #include "MemoryCache.h"
75 #include "MemoryInfo.h"
76 #include "Page.h"
77 #include "PrintContext.h"
78 #include "PseudoElement.h"
79 #include "Range.h"
80 #include "RenderEmbeddedObject.h"
81 #include "RenderMenuList.h"
82 #include "RenderTreeAsText.h"
83 #include "RenderView.h"
84 #include "RuntimeEnabledFeatures.h"
85 #include "SchemeRegistry.h"
86 #include "ScrollingCoordinator.h"
87 #include "SerializedScriptValue.h"
88 #include "Settings.h"
89 #include "ShadowRoot.h"
90 #include "SpellChecker.h"
91 #include "StaticNodeList.h"
92 #include "StyleSheetContents.h"
93 #include "TextIterator.h"
94 #include "TreeScope.h"
95 #include "TypeConversions.h"
96 #include "ViewportArguments.h"
97 #include "WebConsoleAgent.h"
98 #include "WorkerThread.h"
99 #include <bytecode/CodeBlock.h>
100 #include <inspector/InspectorAgentBase.h>
101 #include <inspector/InspectorValues.h>
102 #include <runtime/JSCInlines.h>
103 #include <runtime/JSCJSValue.h>
104 #include <wtf/text/CString.h>
105 #include <wtf/text/StringBuffer.h>
106
107 #if ENABLE(INPUT_TYPE_COLOR)
108 #include "ColorChooser.h"
109 #endif
110
111 #if ENABLE(BATTERY_STATUS)
112 #include "BatteryController.h"
113 #endif
114
115 #if ENABLE(PROXIMITY_EVENTS)
116 #include "DeviceProximityController.h"
117 #endif
118
119 #if ENABLE(MOUSE_CURSOR_SCALE)
120 #include <wtf/dtoa.h>
121 #endif
122
123 #if ENABLE(ENCRYPTED_MEDIA_V2)
124 #include "CDM.h"
125 #include "MockCDM.h"
126 #endif
127
128 #if ENABLE(VIDEO_TRACK)
129 #include "CaptionUserPreferences.h"
130 #include "PageGroup.h"
131 #endif
132
133 #if ENABLE(VIDEO)
134 #include "HTMLMediaElement.h"
135 #include "TimeRanges.h"
136 #endif
137
138 #if ENABLE(SPEECH_SYNTHESIS)
139 #include "DOMWindowSpeechSynthesis.h"
140 #include "PlatformSpeechSynthesizerMock.h"
141 #include "SpeechSynthesis.h"
142 #endif
143
144 #if ENABLE(VIBRATION)
145 #include "Vibration.h"
146 #endif
147
148 #if ENABLE(MEDIA_STREAM)
149 #include "MockMediaStreamCenter.h"
150 #include "RTCPeerConnection.h"
151 #include "RTCPeerConnectionHandlerMock.h"
152 #include "UserMediaClientMock.h"
153 #endif
154
155 #if ENABLE(MEDIA_SOURCE)
156 #include "MockMediaPlayerMediaSource.h"
157 #endif
158
159 using JSC::CodeBlock;
160 using JSC::FunctionExecutable;
161 using JSC::JSFunction;
162 using JSC::JSValue;
163 using JSC::ScriptExecutable;
164 using JSC::StackVisitor;
165
166 using namespace Inspector;
167
168 namespace WebCore {
169
170 using namespace HTMLNames;
171
172 #if ENABLE(INSPECTOR)
173 class InspectorFrontendClientDummy : public InspectorFrontendClientLocal {
174 public:
175     InspectorFrontendClientDummy(InspectorController*, Page*);
176     virtual ~InspectorFrontendClientDummy() { }
177     virtual void attachWindow(DockSide) override { }
178     virtual void detachWindow() override { }
179
180     virtual String localizedStringsURL() override { return String(); }
181
182     virtual void bringToFront() override { }
183     virtual void closeWindow() override { }
184
185     virtual void inspectedURLChanged(const String&) override { }
186
187 protected:
188     virtual void setAttachedWindowHeight(unsigned) override { }
189     virtual void setAttachedWindowWidth(unsigned) override { }
190     virtual void setToolbarHeight(unsigned) override { }
191 };
192
193 InspectorFrontendClientDummy::InspectorFrontendClientDummy(InspectorController* controller, Page* page)
194     : InspectorFrontendClientLocal(controller, page, std::make_unique<InspectorFrontendClientLocal::Settings>())
195 {
196 }
197
198 class InspectorFrontendChannelDummy : public InspectorFrontendChannel {
199 public:
200     explicit InspectorFrontendChannelDummy(Page*);
201     virtual ~InspectorFrontendChannelDummy() { }
202     virtual bool sendMessageToFrontend(const String& message) override;
203
204 private:
205     Page* m_frontendPage;
206 };
207
208 InspectorFrontendChannelDummy::InspectorFrontendChannelDummy(Page* page)
209     : m_frontendPage(page)
210 {
211 }
212
213 bool InspectorFrontendChannelDummy::sendMessageToFrontend(const String& message)
214 {
215     return InspectorClient::doDispatchMessageOnFrontendPage(m_frontendPage, message);
216 }
217 #endif // ENABLE(INSPECTOR)
218
219 static bool markerTypesFrom(const String& markerType, DocumentMarker::MarkerTypes& result)
220 {
221     if (markerType.isEmpty() || equalIgnoringCase(markerType, "all"))
222         result = DocumentMarker::AllMarkers();
223     else if (equalIgnoringCase(markerType, "Spelling"))
224         result =  DocumentMarker::Spelling;
225     else if (equalIgnoringCase(markerType, "Grammar"))
226         result =  DocumentMarker::Grammar;
227     else if (equalIgnoringCase(markerType, "TextMatch"))
228         result =  DocumentMarker::TextMatch;
229     else if (equalIgnoringCase(markerType, "Replacement"))
230         result =  DocumentMarker::Replacement;
231     else if (equalIgnoringCase(markerType, "CorrectionIndicator"))
232         result =  DocumentMarker::CorrectionIndicator;
233     else if (equalIgnoringCase(markerType, "RejectedCorrection"))
234         result =  DocumentMarker::RejectedCorrection;
235     else if (equalIgnoringCase(markerType, "Autocorrected"))
236         result =  DocumentMarker::Autocorrected;
237     else if (equalIgnoringCase(markerType, "SpellCheckingExemption"))
238         result =  DocumentMarker::SpellCheckingExemption;
239     else if (equalIgnoringCase(markerType, "DeletedAutocorrection"))
240         result =  DocumentMarker::DeletedAutocorrection;
241     else if (equalIgnoringCase(markerType, "DictationAlternatives"))
242         result =  DocumentMarker::DictationAlternatives;
243 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
244     else if (equalIgnoringCase(markerType, "TelephoneNumber"))
245         result =  DocumentMarker::TelephoneNumber;
246 #endif
247     else
248         return false;
249
250     return true;
251 }
252
253 const char* Internals::internalsId = "internals";
254
255 PassRefPtr<Internals> Internals::create(Document* document)
256 {
257     return adoptRef(new Internals(document));
258 }
259
260 Internals::~Internals()
261 {
262 }
263
264 void Internals::resetToConsistentState(Page* page)
265 {
266     ASSERT(page);
267
268     page->setPageScaleFactor(1, IntPoint(0, 0));
269     page->setPagination(Pagination());
270
271     FrameView* mainFrameView = page->mainFrame().view();
272     if (mainFrameView) {
273         mainFrameView->setHeaderHeight(0);
274         mainFrameView->setFooterHeight(0);
275         page->setTopContentInset(0);
276     }
277
278     TextRun::setAllowsRoundingHacks(false);
279     WebCore::overrideUserPreferredLanguages(Vector<String>());
280     WebCore::Settings::setUsesOverlayScrollbars(false);
281 #if ENABLE(INSPECTOR)
282     page->inspectorController().setProfilerEnabled(false);
283 #endif
284 #if ENABLE(VIDEO_TRACK)
285     page->group().captionPreferences()->setCaptionsStyleSheetOverride(emptyString());
286     page->group().captionPreferences()->setTestingMode(false);
287 #endif
288     if (!page->mainFrame().editor().isContinuousSpellCheckingEnabled())
289         page->mainFrame().editor().toggleContinuousSpellChecking();
290     if (page->mainFrame().editor().isOverwriteModeEnabled())
291         page->mainFrame().editor().toggleOverwriteModeEnabled();
292     cacheStorage().setDefaultOriginQuota(ApplicationCacheStorage::noQuota());
293 #if ENABLE(VIDEO)
294     MediaSessionManager::sharedManager().resetRestrictions();
295 #endif
296 #if HAVE(ACCESSIBILITY)
297     AXObjectCache::setEnhancedUserInterfaceAccessibility(false);
298     AXObjectCache::disableAccessibility();
299 #endif
300 }
301
302 Internals::Internals(Document* document)
303     : ContextDestructionObserver(document)
304 {
305 #if ENABLE(VIDEO_TRACK)
306     if (document && document->page())
307         document->page()->group().captionPreferences()->setTestingMode(true);
308 #endif
309
310 #if ENABLE(MEDIA_STREAM)
311     MockMediaStreamCenter::registerMockMediaStreamCenter();
312     enableMockRTCPeerConnectionHandler();
313     WebCore::provideUserMediaTo(document->page(), new UserMediaClientMock());
314 #endif
315 }
316
317 Document* Internals::contextDocument() const
318 {
319     return toDocument(scriptExecutionContext());
320 }
321
322 Frame* Internals::frame() const
323 {
324     if (!contextDocument())
325         return 0;
326     return contextDocument()->frame();
327 }
328
329 InternalSettings* Internals::settings() const
330 {
331     Document* document = contextDocument();
332     if (!document)
333         return 0;
334     Page* page = document->page();
335     if (!page)
336         return 0;
337     return InternalSettings::from(page);
338 }
339
340 unsigned Internals::workerThreadCount() const
341 {
342     return WorkerThread::workerThreadCount();
343 }
344
345 String Internals::address(Node* node)
346 {
347     char buf[32];
348     sprintf(buf, "%p", node);
349
350     return String(buf);
351 }
352
353 bool Internals::isPreloaded(const String& url)
354 {
355     Document* document = contextDocument();
356     return document->cachedResourceLoader()->isPreloaded(url);
357 }
358
359 bool Internals::isLoadingFromMemoryCache(const String& url)
360 {
361     if (!contextDocument() || !contextDocument()->page())
362         return false;
363     CachedResource* resource = memoryCache()->resourceForURL(contextDocument()->completeURL(url), contextDocument()->page()->sessionID());
364     return resource && resource->status() == CachedResource::Cached;
365 }
366
367
368 Node* Internals::treeScopeRootNode(Node* node, ExceptionCode& ec)
369 {
370     if (!node) {
371         ec = INVALID_ACCESS_ERR;
372         return nullptr;
373     }
374
375     return &node->treeScope().rootNode();
376 }
377
378 Node* Internals::parentTreeScope(Node* node, ExceptionCode& ec)
379 {
380     if (!node) {
381         ec = INVALID_ACCESS_ERR;
382         return nullptr;
383     }
384     const TreeScope* parentTreeScope = node->treeScope().parentTreeScope();
385     return parentTreeScope ? &parentTreeScope->rootNode() : nullptr;
386 }
387
388 unsigned Internals::lastSpatialNavigationCandidateCount(ExceptionCode& ec) const
389 {
390     if (!contextDocument() || !contextDocument()->page()) {
391         ec = INVALID_ACCESS_ERR;
392         return 0;
393     }
394
395     return contextDocument()->page()->lastSpatialNavigationCandidateCount();
396 }
397
398 unsigned Internals::numberOfActiveAnimations() const
399 {
400     return frame()->animation().numberOfActiveAnimations(frame()->document());
401 }
402
403 bool Internals::animationsAreSuspended(ExceptionCode& ec) const
404 {
405     Document* document = contextDocument();
406     if (!document || !document->frame()) {
407         ec = INVALID_ACCESS_ERR;
408         return false;
409     }
410
411     return document->frame()->animation().isSuspended();
412 }
413
414 void Internals::suspendAnimations(ExceptionCode& ec) const
415 {
416     Document* document = contextDocument();
417     if (!document || !document->frame()) {
418         ec = INVALID_ACCESS_ERR;
419         return;
420     }
421
422     document->frame()->animation().suspendAnimations();
423 }
424
425 void Internals::resumeAnimations(ExceptionCode& ec) const
426 {
427     Document* document = contextDocument();
428     if (!document || !document->frame()) {
429         ec = INVALID_ACCESS_ERR;
430         return;
431     }
432
433     document->frame()->animation().resumeAnimations();
434 }
435
436 bool Internals::pauseAnimationAtTimeOnElement(const String& animationName, double pauseTime, Element* element, ExceptionCode& ec)
437 {
438     if (!element || pauseTime < 0) {
439         ec = INVALID_ACCESS_ERR;
440         return false;
441     }
442     return frame()->animation().pauseAnimationAtTime(element->renderer(), AtomicString(animationName), pauseTime);
443 }
444
445 bool Internals::pauseAnimationAtTimeOnPseudoElement(const String& animationName, double pauseTime, Element* element, const String& pseudoId, ExceptionCode& ec)
446 {
447     if (!element || pauseTime < 0) {
448         ec = INVALID_ACCESS_ERR;
449         return false;
450     }
451
452     if (pseudoId != "before" && pseudoId != "after") {
453         ec = INVALID_ACCESS_ERR;
454         return false;
455     }
456
457     PseudoElement* pseudoElement = pseudoId == "before" ? element->beforePseudoElement() : element->afterPseudoElement();
458     if (!pseudoElement) {
459         ec = INVALID_ACCESS_ERR;
460         return false;
461     }
462
463     return frame()->animation().pauseAnimationAtTime(pseudoElement->renderer(), AtomicString(animationName), pauseTime);
464 }
465
466 bool Internals::pauseTransitionAtTimeOnElement(const String& propertyName, double pauseTime, Element* element, ExceptionCode& ec)
467 {
468     if (!element || pauseTime < 0) {
469         ec = INVALID_ACCESS_ERR;
470         return false;
471     }
472     return frame()->animation().pauseTransitionAtTime(element->renderer(), propertyName, pauseTime);
473 }
474
475 bool Internals::pauseTransitionAtTimeOnPseudoElement(const String& property, double pauseTime, Element* element, const String& pseudoId, ExceptionCode& ec)
476 {
477     if (!element || pauseTime < 0) {
478         ec = INVALID_ACCESS_ERR;
479         return false;
480     }
481
482     if (pseudoId != "before" && pseudoId != "after") {
483         ec = INVALID_ACCESS_ERR;
484         return false;
485     }
486
487     PseudoElement* pseudoElement = pseudoId == "before" ? element->beforePseudoElement() : element->afterPseudoElement();
488     if (!pseudoElement) {
489         ec = INVALID_ACCESS_ERR;
490         return false;
491     }
492
493     return frame()->animation().pauseTransitionAtTime(pseudoElement->renderer(), property, pauseTime);
494 }
495
496 // FIXME: Remove.
497 bool Internals::attached(Node* node, ExceptionCode& ec)
498 {
499     if (!node) {
500         ec = INVALID_ACCESS_ERR;
501         return false;
502     }
503
504     return true;
505 }
506
507 String Internals::elementRenderTreeAsText(Element* element, ExceptionCode& ec)
508 {
509     if (!element) {
510         ec = INVALID_ACCESS_ERR;
511         return String();
512     }
513
514     element->document().updateStyleIfNeeded();
515
516     String representation = externalRepresentation(element);
517     if (representation.isEmpty()) {
518         ec = INVALID_ACCESS_ERR;
519         return String();
520     }
521
522     return representation;
523 }
524
525 PassRefPtr<CSSComputedStyleDeclaration> Internals::computedStyleIncludingVisitedInfo(Node* node, ExceptionCode& ec) const
526 {
527     if (!node) {
528         ec = INVALID_ACCESS_ERR;
529         return 0;
530     }
531
532     bool allowVisitedStyle = true;
533     return CSSComputedStyleDeclaration::create(node, allowVisitedStyle);
534 }
535
536 Node* Internals::ensureShadowRoot(Element* host, ExceptionCode& ec)
537 {
538     if (!host) {
539         ec = INVALID_ACCESS_ERR;
540         return 0;
541     }
542
543     if (ShadowRoot* shadowRoot = host->shadowRoot())
544         return shadowRoot;
545
546     return host->createShadowRoot(ec).get();
547 }
548
549 Node* Internals::createShadowRoot(Element* host, ExceptionCode& ec)
550 {
551     if (!host) {
552         ec = INVALID_ACCESS_ERR;
553         return 0;
554     }
555     return host->createShadowRoot(ec).get();
556 }
557
558 Node* Internals::shadowRoot(Element* host, ExceptionCode& ec)
559 {
560     if (!host) {
561         ec = INVALID_ACCESS_ERR;
562         return 0;
563     }
564     return host->shadowRoot();
565 }
566
567 String Internals::shadowRootType(const Node* root, ExceptionCode& ec) const
568 {
569     if (!root || !root->isShadowRoot()) {
570         ec = INVALID_ACCESS_ERR;
571         return String();
572     }
573
574     switch (toShadowRoot(root)->type()) {
575     case ShadowRoot::UserAgentShadowRoot:
576         return String("UserAgentShadowRoot");
577     default:
578         ASSERT_NOT_REACHED();
579         return String("Unknown");
580     }
581 }
582
583 Element* Internals::includerFor(Node*, ExceptionCode& ec)
584 {
585     ec = INVALID_ACCESS_ERR;
586     return 0;
587 }
588
589 String Internals::shadowPseudoId(Element* element, ExceptionCode& ec)
590 {
591     if (!element) {
592         ec = INVALID_ACCESS_ERR;
593         return String();
594     }
595
596     return element->shadowPseudoId().string();
597 }
598
599 void Internals::setShadowPseudoId(Element* element, const String& id, ExceptionCode& ec)
600 {
601     if (!element) {
602         ec = INVALID_ACCESS_ERR;
603         return;
604     }
605
606     return element->setPseudo(id);
607 }
608
609 String Internals::visiblePlaceholder(Element* element)
610 {
611     if (element && isHTMLTextFormControlElement(*element)) {
612         if (toHTMLTextFormControlElement(*element).placeholderShouldBeVisible())
613             return toHTMLTextFormControlElement(*element).placeholderElement()->textContent();
614     }
615
616     return String();
617 }
618
619 #if ENABLE(INPUT_TYPE_COLOR)
620 void Internals::selectColorInColorChooser(Element* element, const String& colorValue)
621 {
622     if (!isHTMLInputElement(element))
623         return;
624     HTMLInputElement* inputElement = element->toInputElement();
625     if (!inputElement)
626         return;
627     inputElement->selectColorInColorChooser(Color(colorValue));
628 }
629 #endif
630
631 Vector<String> Internals::formControlStateOfPreviousHistoryItem(ExceptionCode& ec)
632 {
633     HistoryItem* mainItem = frame()->loader().history().previousItem();
634     if (!mainItem) {
635         ec = INVALID_ACCESS_ERR;
636         return Vector<String>();
637     }
638     String uniqueName = frame()->tree().uniqueName();
639     if (mainItem->target() != uniqueName && !mainItem->childItemWithTarget(uniqueName)) {
640         ec = INVALID_ACCESS_ERR;
641         return Vector<String>();
642     }
643     return mainItem->target() == uniqueName ? mainItem->documentState() : mainItem->childItemWithTarget(uniqueName)->documentState();
644 }
645
646 void Internals::setFormControlStateOfPreviousHistoryItem(const Vector<String>& state, ExceptionCode& ec)
647 {
648     HistoryItem* mainItem = frame()->loader().history().previousItem();
649     if (!mainItem) {
650         ec = INVALID_ACCESS_ERR;
651         return;
652     }
653     String uniqueName = frame()->tree().uniqueName();
654     if (mainItem->target() == uniqueName)
655         mainItem->setDocumentState(state);
656     else if (HistoryItem* subItem = mainItem->childItemWithTarget(uniqueName))
657         subItem->setDocumentState(state);
658     else
659         ec = INVALID_ACCESS_ERR;
660 }
661
662 #if ENABLE(SPEECH_SYNTHESIS)
663 void Internals::enableMockSpeechSynthesizer()
664 {
665     Document* document = contextDocument();
666     if (!document || !document->domWindow())
667         return;
668     SpeechSynthesis* synthesis = DOMWindowSpeechSynthesis::speechSynthesis(document->domWindow());
669     if (!synthesis)
670         return;
671     
672     synthesis->setPlatformSynthesizer(std::make_unique<PlatformSpeechSynthesizerMock>(synthesis));
673 }
674 #endif
675
676 #if ENABLE(MEDIA_STREAM)
677 void Internals::enableMockRTCPeerConnectionHandler()
678 {
679     RTCPeerConnectionHandler::create = RTCPeerConnectionHandlerMock::create;
680 }
681 #endif
682
683 PassRefPtr<ClientRect> Internals::absoluteCaretBounds(ExceptionCode& ec)
684 {
685     Document* document = contextDocument();
686     if (!document || !document->frame()) {
687         ec = INVALID_ACCESS_ERR;
688         return ClientRect::create();
689     }
690
691     return ClientRect::create(document->frame()->selection().absoluteCaretBounds());
692 }
693
694 PassRefPtr<ClientRect> Internals::boundingBox(Element* element, ExceptionCode& ec)
695 {
696     if (!element) {
697         ec = INVALID_ACCESS_ERR;
698         return ClientRect::create();
699     }
700
701     element->document().updateLayoutIgnorePendingStylesheets();
702     auto renderer = element->renderer();
703     if (!renderer)
704         return ClientRect::create();
705     return ClientRect::create(renderer->absoluteBoundingBoxRectIgnoringTransforms());
706 }
707
708 PassRefPtr<ClientRectList> Internals::inspectorHighlightRects(ExceptionCode& ec)
709 {
710 #if ENABLE(INSPECTOR)
711     Document* document = contextDocument();
712     if (!document || !document->page()) {
713         ec = INVALID_ACCESS_ERR;
714         return ClientRectList::create();
715     }
716
717     Highlight highlight;
718     document->page()->inspectorController().getHighlight(&highlight);
719     return ClientRectList::create(highlight.quads);
720 #else
721     UNUSED_PARAM(ec);
722     return ClientRectList::create();
723 #endif
724 }
725
726 String Internals::inspectorHighlightObject(ExceptionCode& ec)
727 {
728 #if ENABLE(INSPECTOR)
729     Document* document = contextDocument();
730     if (!document || !document->page()) {
731         ec = INVALID_ACCESS_ERR;
732         return String();
733     }
734     RefPtr<InspectorObject> object = document->page()->inspectorController().buildObjectForHighlightedNode();
735     return object ? object->toJSONString() : String();
736 #else
737     UNUSED_PARAM(ec);
738     return String();
739 #endif
740 }
741
742 unsigned Internals::markerCountForNode(Node* node, const String& markerType, ExceptionCode& ec)
743 {
744     if (!node) {
745         ec = INVALID_ACCESS_ERR;
746         return 0;
747     }
748
749     DocumentMarker::MarkerTypes markerTypes = 0;
750     if (!markerTypesFrom(markerType, markerTypes)) {
751         ec = SYNTAX_ERR;
752         return 0;
753     }
754
755     node->document().frame()->editor().updateEditorUINowIfScheduled();
756
757     return node->document().markers().markersFor(node, markerTypes).size();
758 }
759
760 DocumentMarker* Internals::markerAt(Node* node, const String& markerType, unsigned index, ExceptionCode& ec)
761 {
762     node->document().updateLayoutIgnorePendingStylesheets();
763     if (!node) {
764         ec = INVALID_ACCESS_ERR;
765         return 0;
766     }
767
768     DocumentMarker::MarkerTypes markerTypes = 0;
769     if (!markerTypesFrom(markerType, markerTypes)) {
770         ec = SYNTAX_ERR;
771         return 0;
772     }
773
774     node->document().frame()->editor().updateEditorUINowIfScheduled();
775
776     Vector<DocumentMarker*> markers = node->document().markers().markersFor(node, markerTypes);
777     if (markers.size() <= index)
778         return 0;
779     return markers[index];
780 }
781
782 PassRefPtr<Range> Internals::markerRangeForNode(Node* node, const String& markerType, unsigned index, ExceptionCode& ec)
783 {
784     DocumentMarker* marker = markerAt(node, markerType, index, ec);
785     if (!marker)
786         return 0;
787     return Range::create(node->document(), node, marker->startOffset(), node, marker->endOffset());
788 }
789
790 String Internals::markerDescriptionForNode(Node* node, const String& markerType, unsigned index, ExceptionCode& ec)
791 {
792     DocumentMarker* marker = markerAt(node, markerType, index, ec);
793     if (!marker)
794         return String();
795     return marker->description();
796 }
797
798 void Internals::addTextMatchMarker(const Range* range, bool isActive)
799 {
800     range->ownerDocument().updateLayoutIgnorePendingStylesheets();
801     range->ownerDocument().markers().addTextMatchMarker(range, isActive);
802 }
803
804 void Internals::setScrollViewPosition(long x, long y, ExceptionCode& ec)
805 {
806     Document* document = contextDocument();
807     if (!document || !document->view()) {
808         ec = INVALID_ACCESS_ERR;
809         return;
810     }
811
812     FrameView* frameView = document->view();
813     bool constrainsScrollingToContentEdgeOldValue = frameView->constrainsScrollingToContentEdge();
814     bool scrollbarsSuppressedOldValue = frameView->scrollbarsSuppressed();
815
816     frameView->setConstrainsScrollingToContentEdge(false);
817     frameView->setScrollbarsSuppressed(false);
818     frameView->setScrollOffsetFromInternals(IntPoint(x, y));
819     frameView->setScrollbarsSuppressed(scrollbarsSuppressedOldValue);
820     frameView->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdgeOldValue);
821 }
822
823 void Internals::setPagination(const String& mode, int gap, int pageLength, ExceptionCode& ec)
824 {
825     Document* document = contextDocument();
826     if (!document || !document->page()) {
827         ec = INVALID_ACCESS_ERR;
828         return;
829     }
830     Page* page = document->page();
831
832     Pagination pagination;
833     if (mode == "Unpaginated")
834         pagination.mode = Pagination::Unpaginated;
835     else if (mode == "LeftToRightPaginated")
836         pagination.mode = Pagination::LeftToRightPaginated;
837     else if (mode == "RightToLeftPaginated")
838         pagination.mode = Pagination::RightToLeftPaginated;
839     else if (mode == "TopToBottomPaginated")
840         pagination.mode = Pagination::TopToBottomPaginated;
841     else if (mode == "BottomToTopPaginated")
842         pagination.mode = Pagination::BottomToTopPaginated;
843     else {
844         ec = SYNTAX_ERR;
845         return;
846     }
847
848     pagination.gap = gap;
849     pagination.pageLength = pageLength;
850     page->setPagination(pagination);
851 }
852
853 String Internals::configurationForViewport(float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight, ExceptionCode& ec)
854 {
855     Document* document = contextDocument();
856     if (!document || !document->page()) {
857         ec = INVALID_ACCESS_ERR;
858         return String();
859     }
860     Page* page = document->page();
861
862     const int defaultLayoutWidthForNonMobilePages = 980;
863
864     ViewportArguments arguments = page->viewportArguments();
865     ViewportAttributes attributes = computeViewportAttributes(arguments, defaultLayoutWidthForNonMobilePages, deviceWidth, deviceHeight, devicePixelRatio, IntSize(availableWidth, availableHeight));
866     restrictMinimumScaleFactorToViewportSize(attributes, IntSize(availableWidth, availableHeight), devicePixelRatio);
867     restrictScaleFactorToInitialScaleIfNotUserScalable(attributes);
868
869     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");
870 }
871
872 bool Internals::wasLastChangeUserEdit(Element* textField, ExceptionCode& ec)
873 {
874     if (!textField) {
875         ec = INVALID_ACCESS_ERR;
876         return false;
877     }
878
879     if (HTMLInputElement* inputElement = textField->toInputElement())
880         return inputElement->lastChangeWasUserEdit();
881
882     // FIXME: We should be using hasTagName instead but Windows port doesn't link QualifiedNames properly.
883     if (textField->tagName() == "TEXTAREA")
884         return toHTMLTextAreaElement(textField)->lastChangeWasUserEdit();
885
886     ec = INVALID_NODE_TYPE_ERR;
887     return false;
888 }
889
890 bool Internals::elementShouldAutoComplete(Element* element, ExceptionCode& ec)
891 {
892     if (!element) {
893         ec = INVALID_ACCESS_ERR;
894         return false;
895     }
896
897     if (HTMLInputElement* inputElement = element->toInputElement())
898         return inputElement->shouldAutocomplete();
899
900     ec = INVALID_NODE_TYPE_ERR;
901     return false;
902 }
903
904 String Internals::suggestedValue(Element* element, ExceptionCode& ec)
905 {
906     if (!element) {
907         ec = INVALID_ACCESS_ERR;
908         return String();
909     }
910
911     HTMLInputElement* inputElement = element->toInputElement();
912     if (!inputElement) {
913         ec = INVALID_NODE_TYPE_ERR;
914         return String();
915     }
916
917     return inputElement->suggestedValue();
918 }
919
920 void Internals::setSuggestedValue(Element* element, const String& value, ExceptionCode& ec)
921 {
922     if (!element) {
923         ec = INVALID_ACCESS_ERR;
924         return;
925     }
926
927     HTMLInputElement* inputElement = element->toInputElement();
928     if (!inputElement) {
929         ec = INVALID_NODE_TYPE_ERR;
930         return;
931     }
932
933     inputElement->setSuggestedValue(value);
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 = roundedLayoutPoint(FloatPoint(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.append("function \"");
1216         result.append(inferredName);
1217         result.append("\"");
1218     } else if (executable->isEvalExecutable())
1219         result.append("eval");
1220     else {
1221         ASSERT(executable->isProgramExecutable());
1222         result.append("program");
1223     }
1224
1225     result.append(" { ");
1226     result.appendNumber(startLine);
1227     result.append(":");
1228     result.appendNumber(startColumn);
1229     result.append(" - ");
1230     result.appendNumber(endLine);
1231     result.append(":");
1232     result.appendNumber(endColumn);
1233     result.append(" }");
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     auto frontendClient = std::make_unique<InspectorFrontendClientDummy>(&page->inspectorController(), frontendPage);
1474
1475     frontendPage->inspectorController().setInspectorFrontendClient(std::move(frontendClient));
1476
1477     m_frontendChannel = adoptPtr(new InspectorFrontendChannelDummy(frontendPage));
1478
1479     page->inspectorController().connectFrontend(m_frontendChannel.get());
1480
1481     return m_frontendWindow;
1482 }
1483
1484 void Internals::closeDummyInspectorFrontend()
1485 {
1486     Page* page = contextDocument()->frame()->page();
1487     ASSERT(page);
1488     ASSERT(m_frontendWindow);
1489
1490     page->inspectorController().disconnectFrontend(InspectorDisconnectReason::InspectorDestroyed);
1491
1492     m_frontendChannel.release();
1493
1494     m_frontendWindow->close(m_frontendWindow->scriptExecutionContext());
1495     m_frontendWindow.release();
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(std::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(std::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::setHeaderHeight(float height)
1772 {
1773     Document* document = contextDocument();
1774     if (!document || !document->view())
1775         return;
1776
1777     FrameView* frameView = document->view();
1778     frameView->setHeaderHeight(height);
1779 }
1780
1781 void Internals::setFooterHeight(float height)
1782 {
1783     Document* document = contextDocument();
1784     if (!document || !document->view())
1785         return;
1786
1787     FrameView* frameView = document->view();
1788     frameView->setFooterHeight(height);
1789 }
1790     
1791 void Internals::setTopContentInset(float contentInset)
1792 {
1793     Document* document = contextDocument();
1794     if (!document)
1795         return;
1796     
1797     Page* page = document->page();
1798     page->setTopContentInset(contentInset);
1799 }
1800
1801 #if ENABLE(FULLSCREEN_API)
1802 void Internals::webkitWillEnterFullScreenForElement(Element* element)
1803 {
1804     Document* document = contextDocument();
1805     if (!document)
1806         return;
1807     document->webkitWillEnterFullScreenForElement(element);
1808 }
1809
1810 void Internals::webkitDidEnterFullScreenForElement(Element* element)
1811 {
1812     Document* document = contextDocument();
1813     if (!document)
1814         return;
1815     document->webkitDidEnterFullScreenForElement(element);
1816 }
1817
1818 void Internals::webkitWillExitFullScreenForElement(Element* element)
1819 {
1820     Document* document = contextDocument();
1821     if (!document)
1822         return;
1823     document->webkitWillExitFullScreenForElement(element);
1824 }
1825
1826 void Internals::webkitDidExitFullScreenForElement(Element* element)
1827 {
1828     Document* document = contextDocument();
1829     if (!document)
1830         return;
1831     document->webkitDidExitFullScreenForElement(element);
1832 }
1833 #endif
1834
1835 void Internals::setApplicationCacheOriginQuota(unsigned long long quota)
1836 {
1837     Document* document = contextDocument();
1838     if (!document)
1839         return;
1840     cacheStorage().storeUpdatedQuotaForOrigin(document->securityOrigin(), quota);
1841 }
1842
1843 void Internals::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme)
1844 {
1845     SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(scheme);
1846 }
1847
1848 void Internals::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(const String& scheme)
1849 {
1850     SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(scheme);
1851 }
1852
1853 PassRefPtr<MallocStatistics> Internals::mallocStatistics() const
1854 {
1855     return MallocStatistics::create();
1856 }
1857
1858 PassRefPtr<TypeConversions> Internals::typeConversions() const
1859 {
1860     return TypeConversions::create();
1861 }
1862
1863 PassRefPtr<MemoryInfo> Internals::memoryInfo() const
1864 {
1865     return MemoryInfo::create();
1866 }
1867
1868 Vector<String> Internals::getReferencedFilePaths() const
1869 {
1870     frame()->loader().history().saveDocumentAndScrollState();
1871     return FormController::getReferencedFilePaths(frame()->loader().history().currentItem()->documentState());
1872 }
1873
1874 void Internals::startTrackingRepaints(ExceptionCode& ec)
1875 {
1876     Document* document = contextDocument();
1877     if (!document || !document->view()) {
1878         ec = INVALID_ACCESS_ERR;
1879         return;
1880     }
1881
1882     FrameView* frameView = document->view();
1883     frameView->setTracksRepaints(true);
1884 }
1885
1886 void Internals::stopTrackingRepaints(ExceptionCode& ec)
1887 {
1888     Document* document = contextDocument();
1889     if (!document || !document->view()) {
1890         ec = INVALID_ACCESS_ERR;
1891         return;
1892     }
1893
1894     FrameView* frameView = document->view();
1895     frameView->setTracksRepaints(false);
1896 }
1897
1898 #if !PLATFORM(IOS)
1899 static const char* cursorTypeToString(Cursor::Type cursorType)
1900 {
1901     switch (cursorType) {
1902     case Cursor::Pointer: return "Pointer";
1903     case Cursor::Cross: return "Cross";
1904     case Cursor::Hand: return "Hand";
1905     case Cursor::IBeam: return "IBeam";
1906     case Cursor::Wait: return "Wait";
1907     case Cursor::Help: return "Help";
1908     case Cursor::EastResize: return "EastResize";
1909     case Cursor::NorthResize: return "NorthResize";
1910     case Cursor::NorthEastResize: return "NorthEastResize";
1911     case Cursor::NorthWestResize: return "NorthWestResize";
1912     case Cursor::SouthResize: return "SouthResize";
1913     case Cursor::SouthEastResize: return "SouthEastResize";
1914     case Cursor::SouthWestResize: return "SouthWestResize";
1915     case Cursor::WestResize: return "WestResize";
1916     case Cursor::NorthSouthResize: return "NorthSouthResize";
1917     case Cursor::EastWestResize: return "EastWestResize";
1918     case Cursor::NorthEastSouthWestResize: return "NorthEastSouthWestResize";
1919     case Cursor::NorthWestSouthEastResize: return "NorthWestSouthEastResize";
1920     case Cursor::ColumnResize: return "ColumnResize";
1921     case Cursor::RowResize: return "RowResize";
1922     case Cursor::MiddlePanning: return "MiddlePanning";
1923     case Cursor::EastPanning: return "EastPanning";
1924     case Cursor::NorthPanning: return "NorthPanning";
1925     case Cursor::NorthEastPanning: return "NorthEastPanning";
1926     case Cursor::NorthWestPanning: return "NorthWestPanning";
1927     case Cursor::SouthPanning: return "SouthPanning";
1928     case Cursor::SouthEastPanning: return "SouthEastPanning";
1929     case Cursor::SouthWestPanning: return "SouthWestPanning";
1930     case Cursor::WestPanning: return "WestPanning";
1931     case Cursor::Move: return "Move";
1932     case Cursor::VerticalText: return "VerticalText";
1933     case Cursor::Cell: return "Cell";
1934     case Cursor::ContextMenu: return "ContextMenu";
1935     case Cursor::Alias: return "Alias";
1936     case Cursor::Progress: return "Progress";
1937     case Cursor::NoDrop: return "NoDrop";
1938     case Cursor::Copy: return "Copy";
1939     case Cursor::None: return "None";
1940     case Cursor::NotAllowed: return "NotAllowed";
1941     case Cursor::ZoomIn: return "ZoomIn";
1942     case Cursor::ZoomOut: return "ZoomOut";
1943     case Cursor::Grab: return "Grab";
1944     case Cursor::Grabbing: return "Grabbing";
1945     case Cursor::Custom: return "Custom";
1946     }
1947
1948     ASSERT_NOT_REACHED();
1949     return "UNKNOWN";
1950 }
1951 #endif
1952
1953 String Internals::getCurrentCursorInfo(ExceptionCode& ec)
1954 {
1955     Document* document = contextDocument();
1956     if (!document || !document->frame()) {
1957         ec = INVALID_ACCESS_ERR;
1958         return String();
1959     }
1960
1961 #if !PLATFORM(IOS)
1962     Cursor cursor = document->frame()->eventHandler().currentMouseCursor();
1963
1964     StringBuilder result;
1965     result.append("type=");
1966     result.append(cursorTypeToString(cursor.type()));
1967     result.append(" hotSpot=");
1968     result.appendNumber(cursor.hotSpot().x());
1969     result.append(",");
1970     result.appendNumber(cursor.hotSpot().y());
1971     if (cursor.image()) {
1972         FloatSize size = cursor.image()->size();
1973         result.append(" image=");
1974         result.appendNumber(size.width());
1975         result.append("x");
1976         result.appendNumber(size.height());
1977     }
1978 #if ENABLE(MOUSE_CURSOR_SCALE)
1979     if (cursor.imageScaleFactor() != 1) {
1980         result.append(" scale=");
1981         NumberToStringBuffer buffer;
1982         result.append(numberToFixedPrecisionString(cursor.imageScaleFactor(), 8, buffer, true));
1983     }
1984 #endif
1985     return result.toString();
1986 #else
1987     return "FAIL: Cursor details not available on this platform.";
1988 #endif
1989 }
1990
1991 PassRefPtr<ArrayBuffer> Internals::serializeObject(PassRefPtr<SerializedScriptValue> value) const
1992 {
1993     Vector<uint8_t> bytes = value->data();
1994     return ArrayBuffer::create(bytes.data(), bytes.size());
1995 }
1996
1997 PassRefPtr<SerializedScriptValue> Internals::deserializeBuffer(PassRefPtr<ArrayBuffer> buffer) const
1998 {
1999     Vector<uint8_t> bytes;
2000     bytes.append(static_cast<const uint8_t*>(buffer->data()), buffer->byteLength());
2001     return SerializedScriptValue::adopt(bytes);
2002 }
2003
2004 void Internals::setUsesOverlayScrollbars(bool enabled)
2005 {
2006     WebCore::Settings::setUsesOverlayScrollbars(enabled);
2007 }
2008
2009 void Internals::forceReload(bool endToEnd)
2010 {
2011     frame()->loader().reload(endToEnd);
2012 }
2013
2014 #if ENABLE(ENCRYPTED_MEDIA_V2)
2015 void Internals::initializeMockCDM()
2016 {
2017     CDM::registerCDMFactory(MockCDM::create, MockCDM::supportsKeySystem, MockCDM::supportsKeySystemAndMimeType);
2018 }
2019 #endif
2020
2021 String Internals::markerTextForListItem(Element* element, ExceptionCode& ec)
2022 {
2023     if (!element) {
2024         ec = INVALID_ACCESS_ERR;
2025         return String();
2026     }
2027     return WebCore::markerTextForListItem(element);
2028 }
2029
2030 String Internals::getImageSourceURL(Element* element, ExceptionCode& ec)
2031 {
2032     if (!element) {
2033         ec = INVALID_ACCESS_ERR;
2034         return String();
2035     }
2036     return element->imageSourceURL();
2037 }
2038
2039 #if ENABLE(VIDEO)
2040 void Internals::simulateAudioInterruption(Node* node)
2041 {
2042 #if USE(GSTREAMER)
2043     HTMLMediaElement* element = toHTMLMediaElement(node);
2044     element->player()->simulateAudioInterruption();
2045 #else
2046     UNUSED_PARAM(node);
2047 #endif
2048 }
2049 #endif
2050
2051 bool Internals::isSelectPopupVisible(Node* node)
2052 {
2053     if (!isHTMLSelectElement(node))
2054         return false;
2055
2056     HTMLSelectElement* select = toHTMLSelectElement(node);
2057
2058     auto renderer = select->renderer();
2059     if (!renderer->isMenuList())
2060         return false;
2061
2062 #if !PLATFORM(IOS)
2063     RenderMenuList* menuList = toRenderMenuList(renderer);
2064     return menuList->popupIsVisible();
2065 #else
2066     return false;
2067 #endif // !PLATFORM(IOS)
2068 }
2069
2070 String Internals::captionsStyleSheetOverride(ExceptionCode& ec)
2071 {
2072     Document* document = contextDocument();
2073     if (!document || !document->page()) {
2074         ec = INVALID_ACCESS_ERR;
2075         return emptyString();
2076     }
2077
2078 #if ENABLE(VIDEO_TRACK)
2079     return document->page()->group().captionPreferences()->captionsStyleSheetOverride();
2080 #else
2081     return emptyString();
2082 #endif
2083 }
2084
2085 void Internals::setCaptionsStyleSheetOverride(const String& override, ExceptionCode& ec)
2086 {
2087     Document* document = contextDocument();
2088     if (!document || !document->page()) {
2089         ec = INVALID_ACCESS_ERR;
2090         return;
2091     }
2092
2093 #if ENABLE(VIDEO_TRACK)
2094     document->page()->group().captionPreferences()->setCaptionsStyleSheetOverride(override);
2095 #else
2096     UNUSED_PARAM(override);
2097 #endif
2098 }
2099
2100 void Internals::setPrimaryAudioTrackLanguageOverride(const String& language, ExceptionCode& ec)
2101 {
2102     Document* document = contextDocument();
2103     if (!document || !document->page()) {
2104         ec = INVALID_ACCESS_ERR;
2105         return;
2106     }
2107
2108 #if ENABLE(VIDEO_TRACK)
2109     document->page()->group().captionPreferences()->setPrimaryAudioTrackLanguageOverride(language);
2110 #else
2111     UNUSED_PARAM(language);
2112 #endif
2113 }
2114
2115 void Internals::setCaptionDisplayMode(const String& mode, ExceptionCode& ec)
2116 {
2117     Document* document = contextDocument();
2118     if (!document || !document->page()) {
2119         ec = INVALID_ACCESS_ERR;
2120         return;
2121     }
2122     
2123 #if ENABLE(VIDEO_TRACK)
2124     CaptionUserPreferences* captionPreferences = document->page()->group().captionPreferences();
2125     
2126     if (equalIgnoringCase(mode, "Automatic"))
2127         captionPreferences->setCaptionDisplayMode(CaptionUserPreferences::Automatic);
2128     else if (equalIgnoringCase(mode, "ForcedOnly"))
2129         captionPreferences->setCaptionDisplayMode(CaptionUserPreferences::ForcedOnly);
2130     else if (equalIgnoringCase(mode, "AlwaysOn"))
2131         captionPreferences->setCaptionDisplayMode(CaptionUserPreferences::AlwaysOn);
2132     else
2133         ec = SYNTAX_ERR;
2134 #else
2135     UNUSED_PARAM(mode);
2136 #endif
2137 }
2138
2139 #if ENABLE(VIDEO)
2140 PassRefPtr<TimeRanges> Internals::createTimeRanges(Float32Array* startTimes, Float32Array* endTimes)
2141 {
2142     ASSERT(startTimes && endTimes);
2143     ASSERT(startTimes->length() == endTimes->length());
2144     RefPtr<TimeRanges> ranges = TimeRanges::create();
2145
2146     unsigned count = std::min(startTimes->length(), endTimes->length());
2147     for (unsigned i = 0; i < count; ++i)
2148         ranges->add(startTimes->item(i), endTimes->item(i));
2149     return ranges;
2150 }
2151
2152 double Internals::closestTimeToTimeRanges(double time, TimeRanges* ranges)
2153 {
2154     return ranges->nearest(time);
2155 }
2156 #endif
2157
2158 PassRefPtr<ClientRect> Internals::selectionBounds(ExceptionCode& ec)
2159 {
2160     Document* document = contextDocument();
2161     if (!document || !document->frame()) {
2162         ec = INVALID_ACCESS_ERR;
2163         return ClientRect::create();
2164     }
2165
2166     return ClientRect::create(document->frame()->selection().selectionBounds());
2167 }
2168
2169 #if ENABLE(VIBRATION)
2170 bool Internals::isVibrating()
2171 {
2172     Page* page = contextDocument()->page();
2173     ASSERT(page);
2174
2175     return Vibration::from(page)->isVibrating();
2176 }
2177 #endif
2178
2179 bool Internals::isPluginUnavailabilityIndicatorObscured(Element* element, ExceptionCode& ec)
2180 {
2181     if (!element) {
2182         ec = INVALID_ACCESS_ERR;
2183         return false;
2184     }
2185
2186     auto renderer = element->renderer();
2187     if (!renderer || !renderer->isEmbeddedObject()) {
2188         ec = INVALID_ACCESS_ERR;
2189         return false;
2190     }
2191
2192     RenderEmbeddedObject* embed = toRenderEmbeddedObject(renderer);
2193     return embed->isReplacementObscured();
2194 }
2195     
2196 bool Internals::isPluginSnapshotted(Element* element, ExceptionCode& ec)
2197 {
2198     if (!element) {
2199         ec = INVALID_ACCESS_ERR;
2200         return false;
2201     }
2202     HTMLPlugInElement* pluginElement = toHTMLPlugInElement(element);
2203     return pluginElement->displayState() <= HTMLPlugInElement::DisplayingSnapshot;
2204 }
2205     
2206 #if ENABLE(MEDIA_SOURCE)
2207 void Internals::initializeMockMediaSource()
2208 {
2209 #if USE(AVFOUNDATION)
2210     WebCore::Settings::setAVFoundationEnabled(false);
2211 #endif
2212     MediaPlayerFactorySupport::callRegisterMediaEngine(MockMediaPlayerMediaSource::registerMediaEngine);
2213 }
2214 #endif
2215
2216 #if ENABLE(VIDEO)
2217 void Internals::beginMediaSessionInterruption()
2218 {
2219     MediaSessionManager::sharedManager().beginInterruption(MediaSession::SystemInterruption);
2220 }
2221
2222 void Internals::endMediaSessionInterruption(const String& flagsString)
2223 {
2224     MediaSession::EndInterruptionFlags flags = MediaSession::NoFlags;
2225
2226     if (equalIgnoringCase(flagsString, "MayResumePlaying"))
2227         flags = MediaSession::MayResumePlaying;
2228     
2229     MediaSessionManager::sharedManager().endInterruption(flags);
2230 }
2231
2232 void Internals::applicationWillEnterForeground() const
2233 {
2234     MediaSessionManager::sharedManager().applicationWillEnterForeground();
2235 }
2236
2237 void Internals::applicationWillEnterBackground() const
2238 {
2239     MediaSessionManager::sharedManager().applicationWillEnterBackground();
2240 }
2241
2242 void Internals::setMediaSessionRestrictions(const String& mediaTypeString, const String& restrictionsString, ExceptionCode& ec)
2243 {
2244     MediaSession::MediaType mediaType = MediaSession::None;
2245     if (equalIgnoringCase(mediaTypeString, "Video"))
2246         mediaType = MediaSession::Video;
2247     else if (equalIgnoringCase(mediaTypeString, "Audio"))
2248         mediaType = MediaSession::Audio;
2249     else if (equalIgnoringCase(mediaTypeString, "WebAudio"))
2250         mediaType = MediaSession::WebAudio;
2251     else {
2252         ec = INVALID_ACCESS_ERR;
2253         return;
2254     }
2255
2256     MediaSessionManager::SessionRestrictions restrictions = MediaSessionManager::sharedManager().restrictions(mediaType);
2257     MediaSessionManager::sharedManager().removeRestriction(mediaType, restrictions);
2258
2259     restrictions = MediaSessionManager::NoRestrictions;
2260     
2261     if (equalIgnoringCase(restrictionsString, "ConcurrentPlaybackNotPermitted"))
2262         restrictions = MediaSessionManager::ConcurrentPlaybackNotPermitted;
2263     if (equalIgnoringCase(restrictionsString, "InlineVideoPlaybackRestricted"))
2264         restrictions += MediaSessionManager::InlineVideoPlaybackRestricted;
2265     if (equalIgnoringCase(restrictionsString, "MetadataPreloadingNotPermitted"))
2266         restrictions += MediaSessionManager::MetadataPreloadingNotPermitted;
2267     if (equalIgnoringCase(restrictionsString, "AutoPreloadingNotPermitted"))
2268         restrictions += MediaSessionManager::AutoPreloadingNotPermitted;
2269     if (equalIgnoringCase(restrictionsString, "BackgroundPlaybackNotPermitted"))
2270         restrictions += MediaSessionManager::BackgroundPlaybackNotPermitted;
2271
2272     MediaSessionManager::sharedManager().addRestriction(mediaType, restrictions);
2273 }
2274     
2275 void Internals::postRemoteControlCommand(const String& commandString, ExceptionCode& ec)
2276 {
2277     MediaSession::RemoteControlCommandType command;
2278     
2279     if (equalIgnoringCase(commandString, "Play"))
2280         command = MediaSession::PlayCommand;
2281     else if (equalIgnoringCase(commandString, "Pause"))
2282         command = MediaSession::PauseCommand;
2283     else if (equalIgnoringCase(commandString, "Stop"))
2284         command = MediaSession::StopCommand;
2285     else if (equalIgnoringCase(commandString, "TogglePlayPause"))
2286         command = MediaSession::TogglePlayPauseCommand;
2287     else if (equalIgnoringCase(commandString, "BeginSeekingBackward"))
2288         command = MediaSession::BeginSeekingBackwardCommand;
2289     else if (equalIgnoringCase(commandString, "EndSeekingBackward"))
2290         command = MediaSession::EndSeekingBackwardCommand;
2291     else if (equalIgnoringCase(commandString, "BeginSeekingForward"))
2292         command = MediaSession::BeginSeekingForwardCommand;
2293     else if (equalIgnoringCase(commandString, "EndSeekingForward"))
2294         command = MediaSession::EndSeekingForwardCommand;
2295     else {
2296         ec = INVALID_ACCESS_ERR;
2297         return;
2298     }
2299     
2300     MediaSessionManager::sharedManager().didReceiveRemoteControlCommand(command);
2301 }
2302 #endif // ENABLE(VIDEO)
2303
2304 void Internals::simulateSystemSleep() const
2305 {
2306 #if ENABLE(VIDEO)
2307     MediaSessionManager::sharedManager().systemWillSleep();
2308 #endif
2309 }
2310
2311 void Internals::simulateSystemWake() const
2312 {
2313 #if ENABLE(VIDEO)
2314     MediaSessionManager::sharedManager().systemDidWake();
2315 #endif
2316 }
2317
2318 }