Text markers don't paint on simple lines
[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::setMarkedTextMatchesAreHighlighted(bool flag, ExceptionCode& ec)
805 {
806     Document* document = contextDocument();
807     if (!document || !document->frame()) {
808         ec = INVALID_ACCESS_ERR;
809         return;
810     }
811     document->frame()->editor().setMarkedTextMatchesAreHighlighted(flag);
812 }
813
814 void Internals::setScrollViewPosition(long x, long y, ExceptionCode& ec)
815 {
816     Document* document = contextDocument();
817     if (!document || !document->view()) {
818         ec = INVALID_ACCESS_ERR;
819         return;
820     }
821
822     FrameView* frameView = document->view();
823     bool constrainsScrollingToContentEdgeOldValue = frameView->constrainsScrollingToContentEdge();
824     bool scrollbarsSuppressedOldValue = frameView->scrollbarsSuppressed();
825
826     frameView->setConstrainsScrollingToContentEdge(false);
827     frameView->setScrollbarsSuppressed(false);
828     frameView->setScrollOffsetFromInternals(IntPoint(x, y));
829     frameView->setScrollbarsSuppressed(scrollbarsSuppressedOldValue);
830     frameView->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdgeOldValue);
831 }
832
833 void Internals::setPagination(const String& mode, int gap, int pageLength, ExceptionCode& ec)
834 {
835     Document* document = contextDocument();
836     if (!document || !document->page()) {
837         ec = INVALID_ACCESS_ERR;
838         return;
839     }
840     Page* page = document->page();
841
842     Pagination pagination;
843     if (mode == "Unpaginated")
844         pagination.mode = Pagination::Unpaginated;
845     else if (mode == "LeftToRightPaginated")
846         pagination.mode = Pagination::LeftToRightPaginated;
847     else if (mode == "RightToLeftPaginated")
848         pagination.mode = Pagination::RightToLeftPaginated;
849     else if (mode == "TopToBottomPaginated")
850         pagination.mode = Pagination::TopToBottomPaginated;
851     else if (mode == "BottomToTopPaginated")
852         pagination.mode = Pagination::BottomToTopPaginated;
853     else {
854         ec = SYNTAX_ERR;
855         return;
856     }
857
858     pagination.gap = gap;
859     pagination.pageLength = pageLength;
860     page->setPagination(pagination);
861 }
862
863 String Internals::configurationForViewport(float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight, ExceptionCode& ec)
864 {
865     Document* document = contextDocument();
866     if (!document || !document->page()) {
867         ec = INVALID_ACCESS_ERR;
868         return String();
869     }
870     Page* page = document->page();
871
872     const int defaultLayoutWidthForNonMobilePages = 980;
873
874     ViewportArguments arguments = page->viewportArguments();
875     ViewportAttributes attributes = computeViewportAttributes(arguments, defaultLayoutWidthForNonMobilePages, deviceWidth, deviceHeight, devicePixelRatio, IntSize(availableWidth, availableHeight));
876     restrictMinimumScaleFactorToViewportSize(attributes, IntSize(availableWidth, availableHeight), devicePixelRatio);
877     restrictScaleFactorToInitialScaleIfNotUserScalable(attributes);
878
879     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");
880 }
881
882 bool Internals::wasLastChangeUserEdit(Element* textField, ExceptionCode& ec)
883 {
884     if (!textField) {
885         ec = INVALID_ACCESS_ERR;
886         return false;
887     }
888
889     if (HTMLInputElement* inputElement = textField->toInputElement())
890         return inputElement->lastChangeWasUserEdit();
891
892     // FIXME: We should be using hasTagName instead but Windows port doesn't link QualifiedNames properly.
893     if (textField->tagName() == "TEXTAREA")
894         return toHTMLTextAreaElement(textField)->lastChangeWasUserEdit();
895
896     ec = INVALID_NODE_TYPE_ERR;
897     return false;
898 }
899
900 bool Internals::elementShouldAutoComplete(Element* element, ExceptionCode& ec)
901 {
902     if (!element) {
903         ec = INVALID_ACCESS_ERR;
904         return false;
905     }
906
907     if (HTMLInputElement* inputElement = element->toInputElement())
908         return inputElement->shouldAutocomplete();
909
910     ec = INVALID_NODE_TYPE_ERR;
911     return false;
912 }
913
914 String Internals::suggestedValue(Element* element, ExceptionCode& ec)
915 {
916     if (!element) {
917         ec = INVALID_ACCESS_ERR;
918         return String();
919     }
920
921     HTMLInputElement* inputElement = element->toInputElement();
922     if (!inputElement) {
923         ec = INVALID_NODE_TYPE_ERR;
924         return String();
925     }
926
927     return inputElement->suggestedValue();
928 }
929
930 void Internals::setSuggestedValue(Element* element, const String& value, ExceptionCode& ec)
931 {
932     if (!element) {
933         ec = INVALID_ACCESS_ERR;
934         return;
935     }
936
937     HTMLInputElement* inputElement = element->toInputElement();
938     if (!inputElement) {
939         ec = INVALID_NODE_TYPE_ERR;
940         return;
941     }
942
943     inputElement->setSuggestedValue(value);
944 }
945
946 void Internals::setEditingValue(Element* element, const String& value, ExceptionCode& ec)
947 {
948     if (!element) {
949         ec = INVALID_ACCESS_ERR;
950         return;
951     }
952
953     HTMLInputElement* inputElement = element->toInputElement();
954     if (!inputElement) {
955         ec = INVALID_NODE_TYPE_ERR;
956         return;
957     }
958
959     inputElement->setEditingValue(value);
960 }
961
962 void Internals::setAutofilled(Element* element, bool enabled, ExceptionCode& ec)
963 {
964     HTMLInputElement* inputElement = element->toInputElement();
965     if (!inputElement) {
966         ec = INVALID_ACCESS_ERR;
967         return;
968     }
969     inputElement->setAutofilled(enabled);
970 }
971
972 void Internals::scrollElementToRect(Element* element, long x, long y, long w, long h, ExceptionCode& ec)
973 {
974     if (!element || !element->document().view()) {
975         ec = INVALID_ACCESS_ERR;
976         return;
977     }
978     FrameView* frameView = element->document().view();
979     frameView->scrollElementToRect(element, IntRect(x, y, w, h));
980 }
981
982 void Internals::paintControlTints(ExceptionCode& ec)
983 {
984     Document* document = contextDocument();
985     if (!document || !document->view()) {
986         ec = INVALID_ACCESS_ERR;
987         return;
988     }
989
990     FrameView* frameView = document->view();
991     frameView->paintControlTints();
992 }
993
994 PassRefPtr<Range> Internals::rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength, ExceptionCode& ec)
995 {
996     if (!scope) {
997         ec = INVALID_ACCESS_ERR;
998         return 0;
999     }
1000
1001     return TextIterator::rangeFromLocationAndLength(scope, rangeLocation, rangeLength);
1002 }
1003
1004 unsigned Internals::locationFromRange(Element* scope, const Range* range, ExceptionCode& ec)
1005 {
1006     if (!scope || !range) {
1007         ec = INVALID_ACCESS_ERR;
1008         return 0;
1009     }
1010
1011     size_t location = 0;
1012     size_t unusedLength = 0;
1013     TextIterator::getLocationAndLengthFromRange(scope, range, location, unusedLength);
1014     return location;
1015 }
1016
1017 unsigned Internals::lengthFromRange(Element* scope, const Range* range, ExceptionCode& ec)
1018 {
1019     if (!scope || !range) {
1020         ec = INVALID_ACCESS_ERR;
1021         return 0;
1022     }
1023
1024     size_t unusedLocation = 0;
1025     size_t length = 0;
1026     TextIterator::getLocationAndLengthFromRange(scope, range, unusedLocation, length);
1027     return length;
1028 }
1029
1030 String Internals::rangeAsText(const Range* range, ExceptionCode& ec)
1031 {
1032     if (!range) {
1033         ec = INVALID_ACCESS_ERR;
1034         return String();
1035     }
1036
1037     return range->text();
1038 }
1039
1040 void Internals::setDelegatesScrolling(bool enabled, ExceptionCode& ec)
1041 {
1042     Document* document = contextDocument();
1043     // Delegate scrolling is valid only on mainframe's view.
1044     if (!document || !document->view() || !document->page() || &document->page()->mainFrame() != document->frame()) {
1045         ec = INVALID_ACCESS_ERR;
1046         return;
1047     }
1048
1049     document->view()->setDelegatesScrolling(enabled);
1050 }
1051
1052 int Internals::lastSpellCheckRequestSequence(ExceptionCode& ec)
1053 {
1054     Document* document = contextDocument();
1055     if (!document || !document->frame()) {
1056         ec = INVALID_ACCESS_ERR;
1057         return -1;
1058     }
1059
1060     return document->frame()->editor().spellChecker().lastRequestSequence();
1061 }
1062
1063 int Internals::lastSpellCheckProcessedSequence(ExceptionCode& ec)
1064 {
1065     Document* document = contextDocument();
1066     if (!document || !document->frame()) {
1067         ec = INVALID_ACCESS_ERR;
1068         return -1;
1069     }
1070
1071     return document->frame()->editor().spellChecker().lastProcessedSequence();
1072 }
1073
1074 Vector<String> Internals::userPreferredLanguages() const
1075 {
1076     return WebCore::userPreferredLanguages();
1077 }
1078
1079 void Internals::setUserPreferredLanguages(const Vector<String>& languages)
1080 {
1081     WebCore::overrideUserPreferredLanguages(languages);
1082 }
1083
1084 unsigned Internals::wheelEventHandlerCount(ExceptionCode& ec)
1085 {
1086     Document* document = contextDocument();
1087     if (!document) {
1088         ec = INVALID_ACCESS_ERR;
1089         return 0;
1090     }
1091
1092     return document->wheelEventHandlerCount();
1093 }
1094
1095 unsigned Internals::touchEventHandlerCount(ExceptionCode& ec)
1096 {
1097     Document* document = contextDocument();
1098     if (!document) {
1099         ec = INVALID_ACCESS_ERR;
1100         return 0;
1101     }
1102
1103     const TouchEventTargetSet* touchHandlers = document->touchEventTargets();
1104     if (!touchHandlers)
1105         return 0;
1106
1107     unsigned count = 0;
1108     for (TouchEventTargetSet::const_iterator iter = touchHandlers->begin(); iter != touchHandlers->end(); ++iter)
1109         count += iter->value;
1110     return count;
1111 }
1112
1113 // FIXME: Remove the document argument. It is almost always the same as
1114 // contextDocument(), with the exception of a few tests that pass a
1115 // different document, and could just make the call through another Internals
1116 // instance instead.
1117 PassRefPtr<NodeList> Internals::nodesFromRect(Document* document, int centerX, int centerY, unsigned topPadding, unsigned rightPadding,
1118     unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent, bool allowChildFrameContent, ExceptionCode& ec) const
1119 {
1120     if (!document || !document->frame() || !document->frame()->view()) {
1121         ec = INVALID_ACCESS_ERR;
1122         return 0;
1123     }
1124
1125     Frame* frame = document->frame();
1126     FrameView* frameView = document->view();
1127     RenderView* renderView = document->renderView();
1128     if (!renderView)
1129         return 0;
1130
1131     document->updateLayoutIgnorePendingStylesheets();
1132
1133     float zoomFactor = frame->pageZoomFactor();
1134     LayoutPoint point = roundedLayoutPoint(FloatPoint(centerX * zoomFactor + frameView->scrollX(), centerY * zoomFactor + frameView->scrollY()));
1135
1136     HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active;
1137     if (ignoreClipping)
1138         hitType |= HitTestRequest::IgnoreClipping;
1139     if (!allowShadowContent)
1140         hitType |= HitTestRequest::DisallowShadowContent;
1141     if (allowChildFrameContent)
1142         hitType |= HitTestRequest::AllowChildFrameContent;
1143
1144     HitTestRequest request(hitType);
1145
1146     // When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
1147     if (!request.ignoreClipping() && !frameView->visibleContentRect().intersects(HitTestLocation::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
1148         return 0;
1149
1150     Vector<Ref<Node>> matches;
1151
1152     // Need padding to trigger a rect based hit test, but we want to return a NodeList
1153     // so we special case this.
1154     if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) {
1155         HitTestResult result(point);
1156         renderView->hitTest(request, result);
1157         if (result.innerNode())
1158             matches.append(*result.innerNode()->deprecatedShadowAncestorNode());
1159     } else {
1160         HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding);
1161         renderView->hitTest(request, result);
1162         
1163         const HitTestResult::NodeSet& nodeSet = result.rectBasedTestResult();
1164         matches.reserveInitialCapacity(nodeSet.size());
1165         for (auto it = nodeSet.begin(), end = nodeSet.end(); it != end; ++it)
1166             matches.uncheckedAppend(*it->get());
1167     }
1168
1169     return StaticNodeList::adopt(matches);
1170 }
1171
1172 class GetCallerCodeBlockFunctor {
1173 public:
1174     GetCallerCodeBlockFunctor()
1175         : m_iterations(0)
1176         , m_codeBlock(0)
1177     {
1178     }
1179
1180     StackVisitor::Status operator()(StackVisitor& visitor)
1181     {
1182         ++m_iterations;
1183         if (m_iterations < 2)
1184             return StackVisitor::Continue;
1185
1186         m_codeBlock = visitor->codeBlock();
1187         return StackVisitor::Done;
1188     }
1189
1190     CodeBlock* codeBlock() const { return m_codeBlock; }
1191
1192 private:
1193     int m_iterations;
1194     CodeBlock* m_codeBlock;
1195 };
1196
1197 String Internals::parserMetaData(Deprecated::ScriptValue value)
1198 {
1199     JSC::VM& vm = contextDocument()->vm();
1200     JSC::ExecState* exec = vm.topCallFrame;
1201     JSC::JSValue code = value.jsValue();
1202     ScriptExecutable* executable;
1203
1204     if (!code || code.isNull() || code.isUndefined()) {
1205         GetCallerCodeBlockFunctor iter;
1206         exec->iterate(iter);
1207         CodeBlock* codeBlock = iter.codeBlock();
1208         executable = codeBlock->ownerExecutable(); 
1209     } else if (code.isFunction()) {
1210         JSFunction* funcObj = JSC::jsCast<JSFunction*>(code.toObject(exec));
1211         executable = funcObj->jsExecutable();
1212     } else
1213         return String();
1214
1215     unsigned startLine = executable->lineNo();
1216     unsigned startColumn = executable->startColumn();
1217     unsigned endLine = executable->lastLine();
1218     unsigned endColumn = executable->endColumn();
1219
1220     StringBuilder result;
1221
1222     if (executable->isFunctionExecutable()) {
1223         FunctionExecutable* funcExecutable = reinterpret_cast<FunctionExecutable*>(executable);
1224         String inferredName = funcExecutable->inferredName().string();
1225         result.append("function \"");
1226         result.append(inferredName);
1227         result.append("\"");
1228     } else if (executable->isEvalExecutable())
1229         result.append("eval");
1230     else {
1231         ASSERT(executable->isProgramExecutable());
1232         result.append("program");
1233     }
1234
1235     result.append(" { ");
1236     result.appendNumber(startLine);
1237     result.append(":");
1238     result.appendNumber(startColumn);
1239     result.append(" - ");
1240     result.appendNumber(endLine);
1241     result.append(":");
1242     result.appendNumber(endColumn);
1243     result.append(" }");
1244
1245     return result.toString();
1246 }
1247
1248 void Internals::setBatteryStatus(const String& eventType, bool charging, double chargingTime, double dischargingTime, double level, ExceptionCode& ec)
1249 {
1250     Document* document = contextDocument();
1251     if (!document || !document->page()) {
1252         ec = INVALID_ACCESS_ERR;
1253         return;
1254     }
1255
1256 #if ENABLE(BATTERY_STATUS)
1257     BatteryController::from(document->page())->didChangeBatteryStatus(eventType, BatteryStatus::create(charging, chargingTime, dischargingTime, level));
1258 #else
1259     UNUSED_PARAM(eventType);
1260     UNUSED_PARAM(charging);
1261     UNUSED_PARAM(chargingTime);
1262     UNUSED_PARAM(dischargingTime);
1263     UNUSED_PARAM(level);
1264 #endif
1265 }
1266
1267 void Internals::setDeviceProximity(const String& eventType, double value, double min, double max, ExceptionCode& ec)
1268 {
1269     Document* document = contextDocument();
1270     if (!document || !document->page()) {
1271         ec = INVALID_ACCESS_ERR;
1272         return;
1273     }
1274
1275 #if ENABLE(PROXIMITY_EVENTS)
1276     DeviceProximityController::from(document->page())->didChangeDeviceProximity(value, min, max);
1277 #else
1278     UNUSED_PARAM(eventType);
1279     UNUSED_PARAM(value);
1280     UNUSED_PARAM(min);
1281     UNUSED_PARAM(max);
1282 #endif
1283 }
1284
1285 void Internals::updateEditorUINowIfScheduled()
1286 {
1287     if (Document* document = contextDocument()) {
1288         if (Frame* frame = document->frame())
1289             frame->editor().updateEditorUINowIfScheduled();
1290     }
1291 }
1292
1293 Node* Internals::findEditingDeleteButton()
1294 {
1295     Document* document = contextDocument();
1296     if (!document || !document->frame())
1297         return 0;
1298
1299     updateEditorUINowIfScheduled();
1300
1301     // FIXME: We shouldn't pollute the id namespace with this name.
1302     return document->getElementById(String(ASCIILiteral("WebKit-Editing-Delete-Button")));
1303 }
1304
1305 bool Internals::hasSpellingMarker(int from, int length, ExceptionCode&)
1306 {
1307     Document* document = contextDocument();
1308     if (!document || !document->frame())
1309         return 0;
1310
1311     updateEditorUINowIfScheduled();
1312
1313     return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length);
1314 }
1315     
1316 bool Internals::hasAutocorrectedMarker(int from, int length, ExceptionCode&)
1317 {
1318     Document* document = contextDocument();
1319     if (!document || !document->frame())
1320         return 0;
1321
1322     updateEditorUINowIfScheduled();
1323
1324     return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Autocorrected, from, length);
1325 }
1326
1327 void Internals::setContinuousSpellCheckingEnabled(bool enabled, ExceptionCode&)
1328 {
1329     if (!contextDocument() || !contextDocument()->frame())
1330         return;
1331
1332     if (enabled != contextDocument()->frame()->editor().isContinuousSpellCheckingEnabled())
1333         contextDocument()->frame()->editor().toggleContinuousSpellChecking();
1334 }
1335
1336 void Internals::setAutomaticQuoteSubstitutionEnabled(bool enabled, ExceptionCode&)
1337 {
1338     if (!contextDocument() || !contextDocument()->frame())
1339         return;
1340
1341 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1342     if (enabled != contextDocument()->frame()->editor().isAutomaticQuoteSubstitutionEnabled())
1343         contextDocument()->frame()->editor().toggleAutomaticQuoteSubstitution();
1344 #else
1345     UNUSED_PARAM(enabled);
1346 #endif
1347 }
1348
1349 void Internals::setAutomaticLinkDetectionEnabled(bool enabled, ExceptionCode&)
1350 {
1351     if (!contextDocument() || !contextDocument()->frame())
1352         return;
1353
1354 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1355     if (enabled != contextDocument()->frame()->editor().isAutomaticLinkDetectionEnabled())
1356         contextDocument()->frame()->editor().toggleAutomaticLinkDetection();
1357 #else
1358     UNUSED_PARAM(enabled);
1359 #endif
1360 }
1361
1362 void Internals::setAutomaticDashSubstitutionEnabled(bool enabled, ExceptionCode&)
1363 {
1364     if (!contextDocument() || !contextDocument()->frame())
1365         return;
1366
1367 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1368     if (enabled != contextDocument()->frame()->editor().isAutomaticDashSubstitutionEnabled())
1369         contextDocument()->frame()->editor().toggleAutomaticDashSubstitution();
1370 #else
1371     UNUSED_PARAM(enabled);
1372 #endif
1373 }
1374
1375 void Internals::setAutomaticTextReplacementEnabled(bool enabled, ExceptionCode&)
1376 {
1377     if (!contextDocument() || !contextDocument()->frame())
1378         return;
1379
1380 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1381     if (enabled != contextDocument()->frame()->editor().isAutomaticTextReplacementEnabled())
1382         contextDocument()->frame()->editor().toggleAutomaticTextReplacement();
1383 #else
1384     UNUSED_PARAM(enabled);
1385 #endif
1386 }
1387
1388 void Internals::setAutomaticSpellingCorrectionEnabled(bool enabled, ExceptionCode&)
1389 {
1390     if (!contextDocument() || !contextDocument()->frame())
1391         return;
1392
1393 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1394     if (enabled != contextDocument()->frame()->editor().isAutomaticSpellingCorrectionEnabled())
1395         contextDocument()->frame()->editor().toggleAutomaticSpellingCorrection();
1396 #else
1397     UNUSED_PARAM(enabled);
1398 #endif
1399 }
1400
1401 bool Internals::isOverwriteModeEnabled(ExceptionCode&)
1402 {
1403     Document* document = contextDocument();
1404     if (!document || !document->frame())
1405         return 0;
1406
1407     return document->frame()->editor().isOverwriteModeEnabled();
1408 }
1409
1410 void Internals::toggleOverwriteModeEnabled(ExceptionCode&)
1411 {
1412     Document* document = contextDocument();
1413     if (!document || !document->frame())
1414         return;
1415
1416     document->frame()->editor().toggleOverwriteModeEnabled();
1417 }
1418
1419 unsigned Internals::countMatchesForText(const String& text, unsigned findOptions, const String& markMatches, ExceptionCode&)
1420 {
1421     Document* document = contextDocument();
1422     if (!document || !document->frame())
1423         return 0;
1424
1425     bool mark = markMatches == "mark";
1426     return document->frame()->editor().countMatchesForText(text, nullptr, findOptions, 1000, mark, nullptr);
1427 }
1428
1429 const ProfilesArray& Internals::consoleProfiles() const
1430 {
1431     return contextDocument()->page()->console().profiles();
1432 }
1433
1434 unsigned Internals::numberOfLiveNodes() const
1435 {
1436     unsigned nodeCount = 0;
1437     for (auto* document : Document::allDocuments())
1438         nodeCount += document->referencingNodeCount();
1439     return nodeCount;
1440 }
1441
1442 unsigned Internals::numberOfLiveDocuments() const
1443 {
1444     return Document::allDocuments().size();
1445 }
1446
1447 #if ENABLE(INSPECTOR)
1448 Vector<String> Internals::consoleMessageArgumentCounts() const
1449 {
1450     Document* document = contextDocument();
1451     if (!document || !document->page())
1452         return Vector<String>();
1453
1454     InstrumentingAgents* instrumentingAgents = instrumentationForPage(document->page());
1455     if (!instrumentingAgents)
1456         return Vector<String>();
1457
1458     InspectorConsoleAgent* consoleAgent = instrumentingAgents->webConsoleAgent();
1459     if (!consoleAgent)
1460         return Vector<String>();
1461
1462     Vector<unsigned> counts = consoleAgent->consoleMessageArgumentCounts();
1463     Vector<String> result(counts.size());
1464     for (size_t i = 0; i < counts.size(); i++)
1465         result[i] = String::number(counts[i]);
1466     return result;
1467 }
1468
1469 PassRefPtr<DOMWindow> Internals::openDummyInspectorFrontend(const String& url)
1470 {
1471     Page* page = contextDocument()->frame()->page();
1472     ASSERT(page);
1473
1474     DOMWindow* window = page->mainFrame().document()->domWindow();
1475     ASSERT(window);
1476
1477     m_frontendWindow = window->open(url, "", "", *window, *window);
1478     ASSERT(m_frontendWindow);
1479
1480     Page* frontendPage = m_frontendWindow->document()->page();
1481     ASSERT(frontendPage);
1482
1483     auto frontendClient = std::make_unique<InspectorFrontendClientDummy>(&page->inspectorController(), frontendPage);
1484
1485     frontendPage->inspectorController().setInspectorFrontendClient(std::move(frontendClient));
1486
1487     m_frontendChannel = adoptPtr(new InspectorFrontendChannelDummy(frontendPage));
1488
1489     page->inspectorController().connectFrontend(m_frontendChannel.get());
1490
1491     return m_frontendWindow;
1492 }
1493
1494 void Internals::closeDummyInspectorFrontend()
1495 {
1496     Page* page = contextDocument()->frame()->page();
1497     ASSERT(page);
1498     ASSERT(m_frontendWindow);
1499
1500     page->inspectorController().disconnectFrontend(InspectorDisconnectReason::InspectorDestroyed);
1501
1502     m_frontendChannel.release();
1503
1504     m_frontendWindow->close(m_frontendWindow->scriptExecutionContext());
1505     m_frontendWindow.release();
1506 }
1507
1508 void Internals::setJavaScriptProfilingEnabled(bool enabled, ExceptionCode& ec)
1509 {
1510     Page* page = contextDocument()->frame()->page();
1511     if (!page) {
1512         ec = INVALID_ACCESS_ERR;
1513         return;
1514     }
1515
1516     page->inspectorController().setProfilerEnabled(enabled);
1517 }
1518
1519 void Internals::setInspectorIsUnderTest(bool isUnderTest, ExceptionCode& ec)
1520 {
1521     Page* page = contextDocument()->frame()->page();
1522     if (!page) {
1523         ec = INVALID_ACCESS_ERR;
1524         return;
1525     }
1526
1527     page->inspectorController().setIsUnderTest(isUnderTest);
1528 }
1529 #endif // ENABLE(INSPECTOR)
1530
1531 bool Internals::hasGrammarMarker(int from, int length, ExceptionCode&)
1532 {
1533     Document* document = contextDocument();
1534     if (!document || !document->frame())
1535         return 0;
1536
1537     return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Grammar, from, length);
1538 }
1539
1540 unsigned Internals::numberOfScrollableAreas(ExceptionCode&)
1541 {
1542     Document* document = contextDocument();
1543     if (!document || !document->frame())
1544         return 0;
1545
1546     unsigned count = 0;
1547     Frame* frame = document->frame();
1548     if (frame->view()->scrollableAreas())
1549         count += frame->view()->scrollableAreas()->size();
1550
1551     for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
1552         if (child->view() && child->view()->scrollableAreas())
1553             count += child->view()->scrollableAreas()->size();
1554     }
1555
1556     return count;
1557 }
1558     
1559 bool Internals::isPageBoxVisible(int pageNumber, ExceptionCode& ec)
1560 {
1561     Document* document = contextDocument();
1562     if (!document) {
1563         ec = INVALID_ACCESS_ERR;
1564         return false;
1565     }
1566
1567     return document->isPageBoxVisible(pageNumber);
1568 }
1569
1570 // FIXME: Remove the document argument. It is almost always the same as
1571 // contextDocument(), with the exception of a few tests that pass a
1572 // different document, and could just make the call through another Internals
1573 // instance instead.
1574 String Internals::layerTreeAsText(Document* document, ExceptionCode& ec) const
1575 {
1576     return layerTreeAsText(document, 0, ec);
1577 }
1578
1579 String Internals::layerTreeAsText(Document* document, unsigned flags, ExceptionCode& ec) const
1580 {
1581     if (!document || !document->frame()) {
1582         ec = INVALID_ACCESS_ERR;
1583         return String();
1584     }
1585
1586     LayerTreeFlags layerTreeFlags = 0;
1587     if (flags & LAYER_TREE_INCLUDES_VISIBLE_RECTS)
1588         layerTreeFlags |= LayerTreeFlagsIncludeVisibleRects;
1589     if (flags & LAYER_TREE_INCLUDES_TILE_CACHES)
1590         layerTreeFlags |= LayerTreeFlagsIncludeTileCaches;
1591     if (flags & LAYER_TREE_INCLUDES_REPAINT_RECTS)
1592         layerTreeFlags |= LayerTreeFlagsIncludeRepaintRects;
1593     if (flags & LAYER_TREE_INCLUDES_PAINTING_PHASES)
1594         layerTreeFlags |= LayerTreeFlagsIncludePaintingPhases;
1595     if (flags & LAYER_TREE_INCLUDES_CONTENT_LAYERS)
1596         layerTreeFlags |= LayerTreeFlagsIncludeContentLayers;
1597
1598     return document->frame()->layerTreeAsText(layerTreeFlags);
1599 }
1600
1601 String Internals::repaintRectsAsText(ExceptionCode& ec) const
1602 {
1603     Document* document = contextDocument();
1604     if (!document || !document->frame()) {
1605         ec = INVALID_ACCESS_ERR;
1606         return String();
1607     }
1608
1609     return document->frame()->trackedRepaintRectsAsText();
1610 }
1611
1612 String Internals::scrollingStateTreeAsText(ExceptionCode& ec) const
1613 {
1614     Document* document = contextDocument();
1615     if (!document || !document->frame()) {
1616         ec = INVALID_ACCESS_ERR;
1617         return String();
1618     }
1619
1620     Page* page = document->page();
1621     if (!page)
1622         return String();
1623
1624     return page->scrollingStateTreeAsText();
1625 }
1626
1627 String Internals::mainThreadScrollingReasons(ExceptionCode& ec) const
1628 {
1629     Document* document = contextDocument();
1630     if (!document || !document->frame()) {
1631         ec = INVALID_ACCESS_ERR;
1632         return String();
1633     }
1634
1635     Page* page = document->page();
1636     if (!page)
1637         return String();
1638
1639     return page->synchronousScrollingReasonsAsText();
1640 }
1641
1642 PassRefPtr<ClientRectList> Internals::nonFastScrollableRects(ExceptionCode& ec) const
1643 {
1644     Document* document = contextDocument();
1645     if (!document || !document->frame()) {
1646         ec = INVALID_ACCESS_ERR;
1647         return 0;
1648     }
1649
1650     Page* page = document->page();
1651     if (!page)
1652         return 0;
1653
1654     return page->nonFastScrollableRects(document->frame());
1655 }
1656
1657 void Internals::garbageCollectDocumentResources(ExceptionCode& ec) const
1658 {
1659     Document* document = contextDocument();
1660     if (!document) {
1661         ec = INVALID_ACCESS_ERR;
1662         return;
1663     }
1664
1665     CachedResourceLoader* cachedResourceLoader = document->cachedResourceLoader();
1666     if (!cachedResourceLoader)
1667         return;
1668     cachedResourceLoader->garbageCollectDocumentResources();
1669 }
1670
1671 void Internals::allowRoundingHacks() const
1672 {
1673     TextRun::setAllowsRoundingHacks(true);
1674 }
1675
1676 void Internals::insertAuthorCSS(const String& css, ExceptionCode& ec) const
1677 {
1678     Document* document = contextDocument();
1679     if (!document) {
1680         ec = INVALID_ACCESS_ERR;
1681         return;
1682     }
1683
1684     auto parsedSheet = StyleSheetContents::create(*document);
1685     parsedSheet.get().setIsUserStyleSheet(false);
1686     parsedSheet.get().parseString(css);
1687     document->styleSheetCollection().addAuthorSheet(std::move(parsedSheet));
1688 }
1689
1690 void Internals::insertUserCSS(const String& css, ExceptionCode& ec) const
1691 {
1692     Document* document = contextDocument();
1693     if (!document) {
1694         ec = INVALID_ACCESS_ERR;
1695         return;
1696     }
1697
1698     auto parsedSheet = StyleSheetContents::create(*document);
1699     parsedSheet.get().setIsUserStyleSheet(true);
1700     parsedSheet.get().parseString(css);
1701     document->styleSheetCollection().addUserSheet(std::move(parsedSheet));
1702 }
1703
1704 String Internals::counterValue(Element* element)
1705 {
1706     if (!element)
1707         return String();
1708
1709     return counterValueForElement(element);
1710 }
1711
1712 int Internals::pageNumber(Element* element, float pageWidth, float pageHeight)
1713 {
1714     if (!element)
1715         return 0;
1716
1717     return PrintContext::pageNumberForElement(element, FloatSize(pageWidth, pageHeight));
1718 }
1719
1720 Vector<String> Internals::iconURLs(Document* document, int iconTypesMask) const
1721 {
1722     Vector<IconURL> iconURLs = document->iconURLs(iconTypesMask);
1723     Vector<String> array;
1724
1725     Vector<IconURL>::const_iterator iter(iconURLs.begin());
1726     for (; iter != iconURLs.end(); ++iter)
1727         array.append(iter->m_iconURL.string());
1728
1729     return array;
1730 }
1731
1732 Vector<String> Internals::shortcutIconURLs() const
1733 {
1734     return iconURLs(contextDocument(), Favicon);
1735 }
1736
1737 Vector<String> Internals::allIconURLs() const
1738 {
1739     return iconURLs(contextDocument(), Favicon | TouchIcon | TouchPrecomposedIcon);
1740 }
1741
1742 int Internals::numberOfPages(float pageWidth, float pageHeight)
1743 {
1744     if (!frame())
1745         return -1;
1746
1747     return PrintContext::numberOfPages(frame(), FloatSize(pageWidth, pageHeight));
1748 }
1749
1750 String Internals::pageProperty(String propertyName, int pageNumber, ExceptionCode& ec) const
1751 {
1752     if (!frame()) {
1753         ec = INVALID_ACCESS_ERR;
1754         return String();
1755     }
1756
1757     return PrintContext::pageProperty(frame(), propertyName.utf8().data(), pageNumber);
1758 }
1759
1760 String Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft, ExceptionCode& ec) const
1761 {
1762     if (!frame()) {
1763         ec = INVALID_ACCESS_ERR;
1764         return String();
1765     }
1766
1767     return PrintContext::pageSizeAndMarginsInPixels(frame(), pageNumber, width, height, marginTop, marginRight, marginBottom, marginLeft);
1768 }
1769
1770 void Internals::setPageScaleFactor(float scaleFactor, int x, int y, ExceptionCode& ec)
1771 {
1772     Document* document = contextDocument();
1773     if (!document || !document->page()) {
1774         ec = INVALID_ACCESS_ERR;
1775         return;
1776     }
1777     Page* page = document->page();
1778     page->setPageScaleFactor(scaleFactor, IntPoint(x, y));
1779 }
1780
1781 void Internals::setHeaderHeight(float height)
1782 {
1783     Document* document = contextDocument();
1784     if (!document || !document->view())
1785         return;
1786
1787     FrameView* frameView = document->view();
1788     frameView->setHeaderHeight(height);
1789 }
1790
1791 void Internals::setFooterHeight(float height)
1792 {
1793     Document* document = contextDocument();
1794     if (!document || !document->view())
1795         return;
1796
1797     FrameView* frameView = document->view();
1798     frameView->setFooterHeight(height);
1799 }
1800     
1801 void Internals::setTopContentInset(float contentInset)
1802 {
1803     Document* document = contextDocument();
1804     if (!document)
1805         return;
1806     
1807     Page* page = document->page();
1808     page->setTopContentInset(contentInset);
1809 }
1810
1811 #if ENABLE(FULLSCREEN_API)
1812 void Internals::webkitWillEnterFullScreenForElement(Element* element)
1813 {
1814     Document* document = contextDocument();
1815     if (!document)
1816         return;
1817     document->webkitWillEnterFullScreenForElement(element);
1818 }
1819
1820 void Internals::webkitDidEnterFullScreenForElement(Element* element)
1821 {
1822     Document* document = contextDocument();
1823     if (!document)
1824         return;
1825     document->webkitDidEnterFullScreenForElement(element);
1826 }
1827
1828 void Internals::webkitWillExitFullScreenForElement(Element* element)
1829 {
1830     Document* document = contextDocument();
1831     if (!document)
1832         return;
1833     document->webkitWillExitFullScreenForElement(element);
1834 }
1835
1836 void Internals::webkitDidExitFullScreenForElement(Element* element)
1837 {
1838     Document* document = contextDocument();
1839     if (!document)
1840         return;
1841     document->webkitDidExitFullScreenForElement(element);
1842 }
1843 #endif
1844
1845 void Internals::setApplicationCacheOriginQuota(unsigned long long quota)
1846 {
1847     Document* document = contextDocument();
1848     if (!document)
1849         return;
1850     cacheStorage().storeUpdatedQuotaForOrigin(document->securityOrigin(), quota);
1851 }
1852
1853 void Internals::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme)
1854 {
1855     SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(scheme);
1856 }
1857
1858 void Internals::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(const String& scheme)
1859 {
1860     SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(scheme);
1861 }
1862
1863 PassRefPtr<MallocStatistics> Internals::mallocStatistics() const
1864 {
1865     return MallocStatistics::create();
1866 }
1867
1868 PassRefPtr<TypeConversions> Internals::typeConversions() const
1869 {
1870     return TypeConversions::create();
1871 }
1872
1873 PassRefPtr<MemoryInfo> Internals::memoryInfo() const
1874 {
1875     return MemoryInfo::create();
1876 }
1877
1878 Vector<String> Internals::getReferencedFilePaths() const
1879 {
1880     frame()->loader().history().saveDocumentAndScrollState();
1881     return FormController::getReferencedFilePaths(frame()->loader().history().currentItem()->documentState());
1882 }
1883
1884 void Internals::startTrackingRepaints(ExceptionCode& ec)
1885 {
1886     Document* document = contextDocument();
1887     if (!document || !document->view()) {
1888         ec = INVALID_ACCESS_ERR;
1889         return;
1890     }
1891
1892     FrameView* frameView = document->view();
1893     frameView->setTracksRepaints(true);
1894 }
1895
1896 void Internals::stopTrackingRepaints(ExceptionCode& ec)
1897 {
1898     Document* document = contextDocument();
1899     if (!document || !document->view()) {
1900         ec = INVALID_ACCESS_ERR;
1901         return;
1902     }
1903
1904     FrameView* frameView = document->view();
1905     frameView->setTracksRepaints(false);
1906 }
1907
1908 #if !PLATFORM(IOS)
1909 static const char* cursorTypeToString(Cursor::Type cursorType)
1910 {
1911     switch (cursorType) {
1912     case Cursor::Pointer: return "Pointer";
1913     case Cursor::Cross: return "Cross";
1914     case Cursor::Hand: return "Hand";
1915     case Cursor::IBeam: return "IBeam";
1916     case Cursor::Wait: return "Wait";
1917     case Cursor::Help: return "Help";
1918     case Cursor::EastResize: return "EastResize";
1919     case Cursor::NorthResize: return "NorthResize";
1920     case Cursor::NorthEastResize: return "NorthEastResize";
1921     case Cursor::NorthWestResize: return "NorthWestResize";
1922     case Cursor::SouthResize: return "SouthResize";
1923     case Cursor::SouthEastResize: return "SouthEastResize";
1924     case Cursor::SouthWestResize: return "SouthWestResize";
1925     case Cursor::WestResize: return "WestResize";
1926     case Cursor::NorthSouthResize: return "NorthSouthResize";
1927     case Cursor::EastWestResize: return "EastWestResize";
1928     case Cursor::NorthEastSouthWestResize: return "NorthEastSouthWestResize";
1929     case Cursor::NorthWestSouthEastResize: return "NorthWestSouthEastResize";
1930     case Cursor::ColumnResize: return "ColumnResize";
1931     case Cursor::RowResize: return "RowResize";
1932     case Cursor::MiddlePanning: return "MiddlePanning";
1933     case Cursor::EastPanning: return "EastPanning";
1934     case Cursor::NorthPanning: return "NorthPanning";
1935     case Cursor::NorthEastPanning: return "NorthEastPanning";
1936     case Cursor::NorthWestPanning: return "NorthWestPanning";
1937     case Cursor::SouthPanning: return "SouthPanning";
1938     case Cursor::SouthEastPanning: return "SouthEastPanning";
1939     case Cursor::SouthWestPanning: return "SouthWestPanning";
1940     case Cursor::WestPanning: return "WestPanning";
1941     case Cursor::Move: return "Move";
1942     case Cursor::VerticalText: return "VerticalText";
1943     case Cursor::Cell: return "Cell";
1944     case Cursor::ContextMenu: return "ContextMenu";
1945     case Cursor::Alias: return "Alias";
1946     case Cursor::Progress: return "Progress";
1947     case Cursor::NoDrop: return "NoDrop";
1948     case Cursor::Copy: return "Copy";
1949     case Cursor::None: return "None";
1950     case Cursor::NotAllowed: return "NotAllowed";
1951     case Cursor::ZoomIn: return "ZoomIn";
1952     case Cursor::ZoomOut: return "ZoomOut";
1953     case Cursor::Grab: return "Grab";
1954     case Cursor::Grabbing: return "Grabbing";
1955     case Cursor::Custom: return "Custom";
1956     }
1957
1958     ASSERT_NOT_REACHED();
1959     return "UNKNOWN";
1960 }
1961 #endif
1962
1963 String Internals::getCurrentCursorInfo(ExceptionCode& ec)
1964 {
1965     Document* document = contextDocument();
1966     if (!document || !document->frame()) {
1967         ec = INVALID_ACCESS_ERR;
1968         return String();
1969     }
1970
1971 #if !PLATFORM(IOS)
1972     Cursor cursor = document->frame()->eventHandler().currentMouseCursor();
1973
1974     StringBuilder result;
1975     result.append("type=");
1976     result.append(cursorTypeToString(cursor.type()));
1977     result.append(" hotSpot=");
1978     result.appendNumber(cursor.hotSpot().x());
1979     result.append(",");
1980     result.appendNumber(cursor.hotSpot().y());
1981     if (cursor.image()) {
1982         FloatSize size = cursor.image()->size();
1983         result.append(" image=");
1984         result.appendNumber(size.width());
1985         result.append("x");
1986         result.appendNumber(size.height());
1987     }
1988 #if ENABLE(MOUSE_CURSOR_SCALE)
1989     if (cursor.imageScaleFactor() != 1) {
1990         result.append(" scale=");
1991         NumberToStringBuffer buffer;
1992         result.append(numberToFixedPrecisionString(cursor.imageScaleFactor(), 8, buffer, true));
1993     }
1994 #endif
1995     return result.toString();
1996 #else
1997     return "FAIL: Cursor details not available on this platform.";
1998 #endif
1999 }
2000
2001 PassRefPtr<ArrayBuffer> Internals::serializeObject(PassRefPtr<SerializedScriptValue> value) const
2002 {
2003     Vector<uint8_t> bytes = value->data();
2004     return ArrayBuffer::create(bytes.data(), bytes.size());
2005 }
2006
2007 PassRefPtr<SerializedScriptValue> Internals::deserializeBuffer(PassRefPtr<ArrayBuffer> buffer) const
2008 {
2009     Vector<uint8_t> bytes;
2010     bytes.append(static_cast<const uint8_t*>(buffer->data()), buffer->byteLength());
2011     return SerializedScriptValue::adopt(bytes);
2012 }
2013
2014 void Internals::setUsesOverlayScrollbars(bool enabled)
2015 {
2016     WebCore::Settings::setUsesOverlayScrollbars(enabled);
2017 }
2018
2019 void Internals::forceReload(bool endToEnd)
2020 {
2021     frame()->loader().reload(endToEnd);
2022 }
2023
2024 #if ENABLE(ENCRYPTED_MEDIA_V2)
2025 void Internals::initializeMockCDM()
2026 {
2027     CDM::registerCDMFactory(MockCDM::create, MockCDM::supportsKeySystem, MockCDM::supportsKeySystemAndMimeType);
2028 }
2029 #endif
2030
2031 String Internals::markerTextForListItem(Element* element, ExceptionCode& ec)
2032 {
2033     if (!element) {
2034         ec = INVALID_ACCESS_ERR;
2035         return String();
2036     }
2037     return WebCore::markerTextForListItem(element);
2038 }
2039
2040 String Internals::getImageSourceURL(Element* element, ExceptionCode& ec)
2041 {
2042     if (!element) {
2043         ec = INVALID_ACCESS_ERR;
2044         return String();
2045     }
2046     return element->imageSourceURL();
2047 }
2048
2049 #if ENABLE(VIDEO)
2050 void Internals::simulateAudioInterruption(Node* node)
2051 {
2052 #if USE(GSTREAMER)
2053     HTMLMediaElement* element = toHTMLMediaElement(node);
2054     element->player()->simulateAudioInterruption();
2055 #else
2056     UNUSED_PARAM(node);
2057 #endif
2058 }
2059 #endif
2060
2061 bool Internals::isSelectPopupVisible(Node* node)
2062 {
2063     if (!isHTMLSelectElement(node))
2064         return false;
2065
2066     HTMLSelectElement* select = toHTMLSelectElement(node);
2067
2068     auto renderer = select->renderer();
2069     if (!renderer->isMenuList())
2070         return false;
2071
2072 #if !PLATFORM(IOS)
2073     RenderMenuList* menuList = toRenderMenuList(renderer);
2074     return menuList->popupIsVisible();
2075 #else
2076     return false;
2077 #endif // !PLATFORM(IOS)
2078 }
2079
2080 String Internals::captionsStyleSheetOverride(ExceptionCode& ec)
2081 {
2082     Document* document = contextDocument();
2083     if (!document || !document->page()) {
2084         ec = INVALID_ACCESS_ERR;
2085         return emptyString();
2086     }
2087
2088 #if ENABLE(VIDEO_TRACK)
2089     return document->page()->group().captionPreferences()->captionsStyleSheetOverride();
2090 #else
2091     return emptyString();
2092 #endif
2093 }
2094
2095 void Internals::setCaptionsStyleSheetOverride(const String& override, ExceptionCode& ec)
2096 {
2097     Document* document = contextDocument();
2098     if (!document || !document->page()) {
2099         ec = INVALID_ACCESS_ERR;
2100         return;
2101     }
2102
2103 #if ENABLE(VIDEO_TRACK)
2104     document->page()->group().captionPreferences()->setCaptionsStyleSheetOverride(override);
2105 #else
2106     UNUSED_PARAM(override);
2107 #endif
2108 }
2109
2110 void Internals::setPrimaryAudioTrackLanguageOverride(const String& language, ExceptionCode& ec)
2111 {
2112     Document* document = contextDocument();
2113     if (!document || !document->page()) {
2114         ec = INVALID_ACCESS_ERR;
2115         return;
2116     }
2117
2118 #if ENABLE(VIDEO_TRACK)
2119     document->page()->group().captionPreferences()->setPrimaryAudioTrackLanguageOverride(language);
2120 #else
2121     UNUSED_PARAM(language);
2122 #endif
2123 }
2124
2125 void Internals::setCaptionDisplayMode(const String& mode, ExceptionCode& ec)
2126 {
2127     Document* document = contextDocument();
2128     if (!document || !document->page()) {
2129         ec = INVALID_ACCESS_ERR;
2130         return;
2131     }
2132     
2133 #if ENABLE(VIDEO_TRACK)
2134     CaptionUserPreferences* captionPreferences = document->page()->group().captionPreferences();
2135     
2136     if (equalIgnoringCase(mode, "Automatic"))
2137         captionPreferences->setCaptionDisplayMode(CaptionUserPreferences::Automatic);
2138     else if (equalIgnoringCase(mode, "ForcedOnly"))
2139         captionPreferences->setCaptionDisplayMode(CaptionUserPreferences::ForcedOnly);
2140     else if (equalIgnoringCase(mode, "AlwaysOn"))
2141         captionPreferences->setCaptionDisplayMode(CaptionUserPreferences::AlwaysOn);
2142     else
2143         ec = SYNTAX_ERR;
2144 #else
2145     UNUSED_PARAM(mode);
2146 #endif
2147 }
2148
2149 #if ENABLE(VIDEO)
2150 PassRefPtr<TimeRanges> Internals::createTimeRanges(Float32Array* startTimes, Float32Array* endTimes)
2151 {
2152     ASSERT(startTimes && endTimes);
2153     ASSERT(startTimes->length() == endTimes->length());
2154     RefPtr<TimeRanges> ranges = TimeRanges::create();
2155
2156     unsigned count = std::min(startTimes->length(), endTimes->length());
2157     for (unsigned i = 0; i < count; ++i)
2158         ranges->add(startTimes->item(i), endTimes->item(i));
2159     return ranges;
2160 }
2161
2162 double Internals::closestTimeToTimeRanges(double time, TimeRanges* ranges)
2163 {
2164     return ranges->nearest(time);
2165 }
2166 #endif
2167
2168 PassRefPtr<ClientRect> Internals::selectionBounds(ExceptionCode& ec)
2169 {
2170     Document* document = contextDocument();
2171     if (!document || !document->frame()) {
2172         ec = INVALID_ACCESS_ERR;
2173         return ClientRect::create();
2174     }
2175
2176     return ClientRect::create(document->frame()->selection().selectionBounds());
2177 }
2178
2179 #if ENABLE(VIBRATION)
2180 bool Internals::isVibrating()
2181 {
2182     Page* page = contextDocument()->page();
2183     ASSERT(page);
2184
2185     return Vibration::from(page)->isVibrating();
2186 }
2187 #endif
2188
2189 bool Internals::isPluginUnavailabilityIndicatorObscured(Element* element, ExceptionCode& ec)
2190 {
2191     if (!element) {
2192         ec = INVALID_ACCESS_ERR;
2193         return false;
2194     }
2195
2196     auto renderer = element->renderer();
2197     if (!renderer || !renderer->isEmbeddedObject()) {
2198         ec = INVALID_ACCESS_ERR;
2199         return false;
2200     }
2201
2202     RenderEmbeddedObject* embed = toRenderEmbeddedObject(renderer);
2203     return embed->isReplacementObscured();
2204 }
2205     
2206 bool Internals::isPluginSnapshotted(Element* element, ExceptionCode& ec)
2207 {
2208     if (!element) {
2209         ec = INVALID_ACCESS_ERR;
2210         return false;
2211     }
2212     HTMLPlugInElement* pluginElement = toHTMLPlugInElement(element);
2213     return pluginElement->displayState() <= HTMLPlugInElement::DisplayingSnapshot;
2214 }
2215     
2216 #if ENABLE(MEDIA_SOURCE)
2217 void Internals::initializeMockMediaSource()
2218 {
2219 #if USE(AVFOUNDATION)
2220     WebCore::Settings::setAVFoundationEnabled(false);
2221 #endif
2222     MediaPlayerFactorySupport::callRegisterMediaEngine(MockMediaPlayerMediaSource::registerMediaEngine);
2223 }
2224 #endif
2225
2226 #if ENABLE(VIDEO)
2227 void Internals::beginMediaSessionInterruption()
2228 {
2229     MediaSessionManager::sharedManager().beginInterruption(MediaSession::SystemInterruption);
2230 }
2231
2232 void Internals::endMediaSessionInterruption(const String& flagsString)
2233 {
2234     MediaSession::EndInterruptionFlags flags = MediaSession::NoFlags;
2235
2236     if (equalIgnoringCase(flagsString, "MayResumePlaying"))
2237         flags = MediaSession::MayResumePlaying;
2238     
2239     MediaSessionManager::sharedManager().endInterruption(flags);
2240 }
2241
2242 void Internals::applicationWillEnterForeground() const
2243 {
2244     MediaSessionManager::sharedManager().applicationWillEnterForeground();
2245 }
2246
2247 void Internals::applicationWillEnterBackground() const
2248 {
2249     MediaSessionManager::sharedManager().applicationWillEnterBackground();
2250 }
2251
2252 void Internals::setMediaSessionRestrictions(const String& mediaTypeString, const String& restrictionsString, ExceptionCode& ec)
2253 {
2254     MediaSession::MediaType mediaType = MediaSession::None;
2255     if (equalIgnoringCase(mediaTypeString, "Video"))
2256         mediaType = MediaSession::Video;
2257     else if (equalIgnoringCase(mediaTypeString, "Audio"))
2258         mediaType = MediaSession::Audio;
2259     else if (equalIgnoringCase(mediaTypeString, "WebAudio"))
2260         mediaType = MediaSession::WebAudio;
2261     else {
2262         ec = INVALID_ACCESS_ERR;
2263         return;
2264     }
2265
2266     MediaSessionManager::SessionRestrictions restrictions = MediaSessionManager::sharedManager().restrictions(mediaType);
2267     MediaSessionManager::sharedManager().removeRestriction(mediaType, restrictions);
2268
2269     restrictions = MediaSessionManager::NoRestrictions;
2270     
2271     if (equalIgnoringCase(restrictionsString, "ConcurrentPlaybackNotPermitted"))
2272         restrictions = MediaSessionManager::ConcurrentPlaybackNotPermitted;
2273     if (equalIgnoringCase(restrictionsString, "InlineVideoPlaybackRestricted"))
2274         restrictions += MediaSessionManager::InlineVideoPlaybackRestricted;
2275     if (equalIgnoringCase(restrictionsString, "MetadataPreloadingNotPermitted"))
2276         restrictions += MediaSessionManager::MetadataPreloadingNotPermitted;
2277     if (equalIgnoringCase(restrictionsString, "AutoPreloadingNotPermitted"))
2278         restrictions += MediaSessionManager::AutoPreloadingNotPermitted;
2279     if (equalIgnoringCase(restrictionsString, "BackgroundPlaybackNotPermitted"))
2280         restrictions += MediaSessionManager::BackgroundPlaybackNotPermitted;
2281
2282     MediaSessionManager::sharedManager().addRestriction(mediaType, restrictions);
2283 }
2284     
2285 void Internals::postRemoteControlCommand(const String& commandString, ExceptionCode& ec)
2286 {
2287     MediaSession::RemoteControlCommandType command;
2288     
2289     if (equalIgnoringCase(commandString, "Play"))
2290         command = MediaSession::PlayCommand;
2291     else if (equalIgnoringCase(commandString, "Pause"))
2292         command = MediaSession::PauseCommand;
2293     else if (equalIgnoringCase(commandString, "Stop"))
2294         command = MediaSession::StopCommand;
2295     else if (equalIgnoringCase(commandString, "TogglePlayPause"))
2296         command = MediaSession::TogglePlayPauseCommand;
2297     else if (equalIgnoringCase(commandString, "BeginSeekingBackward"))
2298         command = MediaSession::BeginSeekingBackwardCommand;
2299     else if (equalIgnoringCase(commandString, "EndSeekingBackward"))
2300         command = MediaSession::EndSeekingBackwardCommand;
2301     else if (equalIgnoringCase(commandString, "BeginSeekingForward"))
2302         command = MediaSession::BeginSeekingForwardCommand;
2303     else if (equalIgnoringCase(commandString, "EndSeekingForward"))
2304         command = MediaSession::EndSeekingForwardCommand;
2305     else {
2306         ec = INVALID_ACCESS_ERR;
2307         return;
2308     }
2309     
2310     MediaSessionManager::sharedManager().didReceiveRemoteControlCommand(command);
2311 }
2312 #endif // ENABLE(VIDEO)
2313
2314 void Internals::simulateSystemSleep() const
2315 {
2316 #if ENABLE(VIDEO)
2317     MediaSessionManager::sharedManager().systemWillSleep();
2318 #endif
2319 }
2320
2321 void Internals::simulateSystemWake() const
2322 {
2323 #if ENABLE(VIDEO)
2324     MediaSessionManager::sharedManager().systemDidWake();
2325 #endif
2326 }
2327
2328 }