Unreviewed Windows build fix.
[WebKit-https.git] / Source / WebCore / testing / Internals.cpp
1 /*
2  * Copyright (C) 2012 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer.
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
18  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
21  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "Internals.h"
28
29 #include "BackForwardController.h"
30 #include "CachedResourceLoader.h"
31 #include "Chrome.h"
32 #include "ChromeClient.h"
33 #include "ClientRect.h"
34 #include "ClientRectList.h"
35 #include "ComposedShadowTreeWalker.h"
36 #include "ContentDistributor.h"
37 #include "Cursor.h"
38 #include "DOMStringList.h"
39 #include "DOMWindow.h"
40 #include "Document.h"
41 #include "DocumentMarker.h"
42 #include "DocumentMarkerController.h"
43 #include "Element.h"
44 #include "ElementShadow.h"
45 #include "EventHandler.h"
46 #include "ExceptionCode.h"
47 #include "FormController.h"
48 #include "Frame.h"
49 #include "FrameView.h"
50 #include "HTMLContentElement.h"
51 #include "HTMLInputElement.h"
52 #include "HTMLNames.h"
53 #include "HTMLTextAreaElement.h"
54 #include "HistoryItem.h"
55 #include "InspectorClient.h"
56 #include "InspectorConsoleAgent.h"
57 #include "InspectorController.h"
58 #include "InspectorCounters.h"
59 #include "InspectorFrontendChannel.h"
60 #include "InspectorFrontendClientLocal.h"
61 #include "InspectorInstrumentation.h"
62 #include "InspectorOverlay.h"
63 #include "InstrumentingAgents.h"
64 #include "InternalSettings.h"
65 #include "IntRect.h"
66 #include "Language.h"
67 #include "MallocStatistics.h"
68 #include "MemoryCache.h"
69 #include "MockPagePopupDriver.h"
70 #include "NodeRenderingContext.h"
71 #include "Page.h"
72 #include "PrintContext.h"
73 #include "PseudoElement.h"
74 #include "Range.h"
75 #include "RenderObject.h"
76 #include "RenderTreeAsText.h"
77 #include "RuntimeEnabledFeatures.h"
78 #include "SchemeRegistry.h"
79 #include "ScrollingCoordinator.h"
80 #include "SelectRuleFeatureSet.h"
81 #include "SerializedScriptValue.h"
82 #include "Settings.h"
83 #include "ShadowRoot.h"
84 #include "SpellChecker.h"
85 #include "StyleSheetContents.h"
86 #include "TextIterator.h"
87 #include "TreeScope.h"
88 #include "TypeConversions.h"
89 #include "ViewportArguments.h"
90 #include "WorkerThread.h"
91 #include <wtf/text/StringBuffer.h>
92
93 #if ENABLE(INPUT_TYPE_COLOR)
94 #include "ColorChooser.h"
95 #endif
96
97 #if ENABLE(BATTERY_STATUS)
98 #include "BatteryController.h"
99 #endif
100
101 #if ENABLE(NETWORK_INFO)
102 #include "NetworkInfo.h"
103 #include "NetworkInfoController.h"
104 #endif
105
106 #if ENABLE(PROXIMITY_EVENTS)
107 #include "DeviceProximityController.h"
108 #endif
109
110 #if ENABLE(PAGE_POPUP)
111 #include "PagePopupController.h"
112 #endif
113
114 #if ENABLE(TOUCH_ADJUSTMENT)
115 #include "WebKitPoint.h"
116 #endif
117
118 #if ENABLE(MOUSE_CURSOR_SCALE)
119 #include <wtf/dtoa.h>
120 #endif
121
122 #if PLATFORM(CHROMIUM)
123 #include "FilterOperation.h"
124 #include "FilterOperations.h"
125 #include "GraphicsLayer.h"
126 #include "GraphicsLayerChromium.h"
127 #include "RenderLayerBacking.h"
128 #endif
129
130 #if ENABLE(ENCRYPTED_MEDIA_V2)
131 #include "CDM.h"
132 #include "MockCDM.h"
133 #endif
134
135 #if ENABLE(VIDEO_TRACK)
136 #include "CaptionUserPreferences.h"
137 #include "PageGroup.h"
138 #endif
139
140 namespace WebCore {
141
142 #if ENABLE(PAGE_POPUP)
143 static MockPagePopupDriver* s_pagePopupDriver = 0;
144 #endif
145
146 using namespace HTMLNames;
147
148 #if ENABLE(INSPECTOR)
149 class InspectorFrontendClientDummy : public InspectorFrontendClientLocal {
150 public:
151     InspectorFrontendClientDummy(InspectorController*, Page*);
152     virtual ~InspectorFrontendClientDummy() { }
153     virtual void attachWindow() OVERRIDE { }
154     virtual void detachWindow() OVERRIDE { }
155
156     virtual String localizedStringsURL() OVERRIDE { return String(); }
157     virtual String hiddenPanels() OVERRIDE { return String(); }
158
159     virtual void bringToFront() OVERRIDE { }
160     virtual void closeWindow() OVERRIDE { }
161
162     virtual void inspectedURLChanged(const String&) OVERRIDE { }
163
164 protected:
165     virtual void setAttachedWindowHeight(unsigned) OVERRIDE { }
166 };
167
168 InspectorFrontendClientDummy::InspectorFrontendClientDummy(InspectorController* controller, Page* page)
169     : InspectorFrontendClientLocal(controller, page, adoptPtr(new InspectorFrontendClientLocal::Settings()))
170 {
171 }
172
173 class InspectorFrontendChannelDummy : public InspectorFrontendChannel {
174 public:
175     explicit InspectorFrontendChannelDummy(Page*);
176     virtual ~InspectorFrontendChannelDummy() { }
177     virtual bool sendMessageToFrontend(const String& message) OVERRIDE;
178
179 private:
180     Page* m_frontendPage;
181 };
182
183 InspectorFrontendChannelDummy::InspectorFrontendChannelDummy(Page* page)
184     : m_frontendPage(page)
185 {
186 }
187
188 bool InspectorFrontendChannelDummy::sendMessageToFrontend(const String& message)
189 {
190     return InspectorClient::doDispatchMessageOnFrontendPage(m_frontendPage, message);
191 }
192 #endif // ENABLE(INSPECTOR)
193
194 static bool markerTypesFrom(const String& markerType, DocumentMarker::MarkerTypes& result)
195 {
196     if (markerType.isEmpty() || equalIgnoringCase(markerType, "all"))
197         result = DocumentMarker::AllMarkers();
198     else if (equalIgnoringCase(markerType, "Spelling"))
199         result =  DocumentMarker::Spelling;
200     else if (equalIgnoringCase(markerType, "Grammar"))
201         result =  DocumentMarker::Grammar;
202     else if (equalIgnoringCase(markerType, "TextMatch"))
203         result =  DocumentMarker::TextMatch;
204     else if (equalIgnoringCase(markerType, "Replacement"))
205         result =  DocumentMarker::Replacement;
206     else if (equalIgnoringCase(markerType, "CorrectionIndicator"))
207         result =  DocumentMarker::CorrectionIndicator;
208     else if (equalIgnoringCase(markerType, "RejectedCorrection"))
209         result =  DocumentMarker::RejectedCorrection;
210     else if (equalIgnoringCase(markerType, "Autocorrected"))
211         result =  DocumentMarker::Autocorrected;
212     else if (equalIgnoringCase(markerType, "SpellCheckingExemption"))
213         result =  DocumentMarker::SpellCheckingExemption;
214     else if (equalIgnoringCase(markerType, "DeletedAutocorrection"))
215         result =  DocumentMarker::DeletedAutocorrection;
216     else if (equalIgnoringCase(markerType, "DictationAlternatives"))
217         result =  DocumentMarker::DictationAlternatives;
218     else
219         return false;
220
221     return true;
222 }
223
224 static SpellChecker* spellchecker(Document* document)
225 {
226     if (!document || !document->frame() || !document->frame()->editor())
227         return 0;
228
229     return document->frame()->editor()->spellChecker();
230 }
231
232 const char* Internals::internalsId = "internals";
233
234 PassRefPtr<Internals> Internals::create(Document* document)
235 {
236     return adoptRef(new Internals(document));
237 }
238
239 Internals::~Internals()
240 {
241 }
242
243 void Internals::resetToConsistentState(Page* page)
244 {
245     ASSERT(page);
246
247     page->setPageScaleFactor(1, IntPoint(0, 0));
248     page->setPagination(Pagination());
249     TextRun::setAllowsRoundingHacks(false);
250     WebCore::overrideUserPreferredLanguages(Vector<String>());
251     WebCore::Settings::setUsesOverlayScrollbars(false);
252 #if ENABLE(PAGE_POPUP)
253     delete s_pagePopupDriver;
254     s_pagePopupDriver = 0;
255     if (page->chrome())
256         page->chrome()->client()->resetPagePopupDriver();
257 #endif
258 #if ENABLE(INSPECTOR) && ENABLE(JAVASCRIPT_DEBUGGER)
259     if (page->inspectorController())
260         page->inspectorController()->setProfilerEnabled(false);
261 #endif
262 #if ENABLE(VIDEO_TRACK) && !PLATFORM(WIN)
263     page->group().captionPreferences()->setTestingMode(false);
264 #endif
265 }
266
267 Internals::Internals(Document* document)
268     : ContextDestructionObserver(document)
269 {
270 #if ENABLE(VIDEO_TRACK) && !PLATFORM(WIN)
271     if (document && document->page())
272         document->page()->group().captionPreferences()->setTestingMode(true);
273 #endif
274 }
275
276 Document* Internals::contextDocument() const
277 {
278     return static_cast<Document*>(scriptExecutionContext());
279 }
280
281 Frame* Internals::frame() const
282 {
283     if (!contextDocument())
284         return 0;
285     return contextDocument()->frame();
286 }
287
288 InternalSettings* Internals::settings() const
289 {
290     Document* document = contextDocument();
291     if (!document)
292         return 0;
293     Page* page = document->page();
294     if (!page)
295         return 0;
296     return InternalSettings::from(page);
297 }
298
299 unsigned Internals::workerThreadCount() const
300 {
301 #if ENABLE(WORKERS)
302     return WorkerThread::workerThreadCount();
303 #else
304     return 0;
305 #endif
306 }
307
308 String Internals::address(Node* node)
309 {
310     char buf[32];
311     sprintf(buf, "%p", node);
312
313     return String(buf);
314 }
315
316 bool Internals::isPreloaded(const String& url)
317 {
318     Document* document = contextDocument();
319     return document->cachedResourceLoader()->isPreloaded(url);
320 }
321
322 bool Internals::isLoadingFromMemoryCache(const String& url)
323 {
324     if (!contextDocument())
325         return false;
326     CachedResource* resource = memoryCache()->resourceForURL(contextDocument()->completeURL(url));
327     return resource && resource->status() == CachedResource::Cached;
328 }
329
330 PassRefPtr<Element> Internals::createContentElement(ExceptionCode& ec)
331 {
332     Document* document = contextDocument();
333     if (!document) {
334         ec = INVALID_ACCESS_ERR;
335         return 0;
336     }
337
338 #if ENABLE(SHADOW_DOM)
339     return HTMLContentElement::create(document);
340 #else
341     return 0;
342 #endif
343 }
344
345 bool Internals::isValidContentSelect(Element* insertionPoint, ExceptionCode& ec)
346 {
347     if (!insertionPoint || !insertionPoint->isInsertionPoint()) {
348         ec = INVALID_ACCESS_ERR;
349         return false;
350     }
351
352 #if ENABLE(SHADOW_DOM)
353     return isHTMLContentElement(insertionPoint) && toHTMLContentElement(insertionPoint)->isSelectValid();
354 #else
355     return false;
356 #endif
357 }
358
359 Node* Internals::treeScopeRootNode(Node* node, ExceptionCode& ec)
360 {
361     if (!node) {
362         ec = INVALID_ACCESS_ERR;
363         return 0;
364     }
365
366     return node->treeScope()->rootNode();
367 }
368
369 Node* Internals::parentTreeScope(Node* node, ExceptionCode& ec)
370 {
371     if (!node) {
372         ec = INVALID_ACCESS_ERR;
373         return 0;
374     }
375     const TreeScope* parentTreeScope = node->treeScope()->parentTreeScope();
376     return parentTreeScope ? parentTreeScope->rootNode() : 0;
377 }
378
379 bool Internals::hasSelectorForIdInShadow(Element* host, const String& idValue, ExceptionCode& ec)
380 {
381     if (!host || !host->shadow()) {
382         ec = INVALID_ACCESS_ERR;
383         return 0;
384     }
385
386     return host->shadow()->distributor().ensureSelectFeatureSet(host->shadow()).hasSelectorForId(idValue);
387 }
388
389 bool Internals::hasSelectorForClassInShadow(Element* host, const String& className, ExceptionCode& ec)
390 {
391     if (!host || !host->shadow()) {
392         ec = INVALID_ACCESS_ERR;
393         return 0;
394     }
395
396     return host->shadow()->distributor().ensureSelectFeatureSet(host->shadow()).hasSelectorForClass(className);
397 }
398
399 bool Internals::hasSelectorForAttributeInShadow(Element* host, const String& attributeName, ExceptionCode& ec)
400 {
401     if (!host || !host->shadow()) {
402         ec = INVALID_ACCESS_ERR;
403         return 0;
404     }
405
406     return host->shadow()->distributor().ensureSelectFeatureSet(host->shadow()).hasSelectorForAttribute(attributeName);
407 }
408
409 bool Internals::hasSelectorForPseudoClassInShadow(Element* host, const String& pseudoClass, ExceptionCode& ec)
410 {
411     if (!host || !host->shadow()) {
412         ec = INVALID_ACCESS_ERR;
413         return 0;
414     }
415
416     const SelectRuleFeatureSet& featureSet = host->shadow()->distributor().ensureSelectFeatureSet(host->shadow());
417     if (pseudoClass == "checked")
418         return featureSet.hasSelectorForChecked();
419     if (pseudoClass == "enabled")
420         return featureSet.hasSelectorForEnabled();
421     if (pseudoClass == "disabled")
422         return featureSet.hasSelectorForDisabled();
423     if (pseudoClass == "indeterminate")
424         return featureSet.hasSelectorForIndeterminate();
425     if (pseudoClass == "link")
426         return featureSet.hasSelectorForLink();
427     if (pseudoClass == "target")
428         return featureSet.hasSelectorForTarget();
429     if (pseudoClass == "visited")
430         return featureSet.hasSelectorForVisited();
431
432     ASSERT_NOT_REACHED();
433     return false;
434 }
435
436 unsigned Internals::numberOfActiveAnimations() const
437 {
438     Frame* contextFrame = frame();
439     if (AnimationController* controller = contextFrame->animation())
440         return controller->numberOfActiveAnimations(contextFrame->document());
441     return 0;
442 }
443
444 void Internals::suspendAnimations(Document* document, ExceptionCode& ec) const
445 {
446     if (!document || !document->frame()) {
447         ec = INVALID_ACCESS_ERR;
448         return;
449     }
450
451     AnimationController* controller = document->frame()->animation();
452     if (!controller)
453         return;
454
455     controller->suspendAnimations();
456 }
457
458 void Internals::resumeAnimations(Document* document, ExceptionCode& ec) const
459 {
460     if (!document || !document->frame()) {
461         ec = INVALID_ACCESS_ERR;
462         return;
463     }
464
465     AnimationController* controller = document->frame()->animation();
466     if (!controller)
467         return;
468
469     controller->resumeAnimations();
470 }
471
472 bool Internals::pauseAnimationAtTimeOnElement(const String& animationName, double pauseTime, Element* element, ExceptionCode& ec)
473 {
474     if (!element || pauseTime < 0) {
475         ec = INVALID_ACCESS_ERR;
476         return false;
477     }
478     AnimationController* controller = frame()->animation();
479     return controller->pauseAnimationAtTime(element->renderer(), AtomicString(animationName), pauseTime);
480 }
481
482 bool Internals::pauseAnimationAtTimeOnPseudoElement(const String& animationName, double pauseTime, Element* element, const String& pseudoId, ExceptionCode& ec)
483 {
484     if (!element || pauseTime < 0) {
485         ec = INVALID_ACCESS_ERR;
486         return false;
487     }
488
489     if (pseudoId != "before" && pseudoId != "after") {
490         ec = INVALID_ACCESS_ERR;
491         return false;
492     }
493
494     PseudoElement* pseudoElement = element->pseudoElement(pseudoId == "before" ? BEFORE : AFTER);
495     if (!pseudoElement) {
496         ec = INVALID_ACCESS_ERR;
497         return false;
498     }
499
500     return frame()->animation()->pauseAnimationAtTime(pseudoElement->renderer(), AtomicString(animationName), pauseTime);
501 }
502
503 bool Internals::pauseTransitionAtTimeOnElement(const String& propertyName, double pauseTime, Element* element, ExceptionCode& ec)
504 {
505     if (!element || pauseTime < 0) {
506         ec = INVALID_ACCESS_ERR;
507         return false;
508     }
509     AnimationController* controller = frame()->animation();
510     return controller->pauseTransitionAtTime(element->renderer(), propertyName, pauseTime);
511 }
512
513 bool Internals::pauseTransitionAtTimeOnPseudoElement(const String& property, double pauseTime, Element* element, const String& pseudoId, ExceptionCode& ec)
514 {
515     if (!element || pauseTime < 0) {
516         ec = INVALID_ACCESS_ERR;
517         return false;
518     }
519
520     if (pseudoId != "before" && pseudoId != "after") {
521         ec = INVALID_ACCESS_ERR;
522         return false;
523     }
524
525     PseudoElement* pseudoElement = element->pseudoElement(pseudoId == "before" ? BEFORE : AFTER);
526     if (!pseudoElement) {
527         ec = INVALID_ACCESS_ERR;
528         return false;
529     }
530
531     return frame()->animation()->pauseTransitionAtTime(pseudoElement->renderer(), property, pauseTime);
532 }
533
534 bool Internals::hasShadowInsertionPoint(const Node* root, ExceptionCode& ec) const
535 {
536     if (root && root->isShadowRoot())
537         return ScopeContentDistribution::hasShadowElement(toShadowRoot(root));
538
539     ec = INVALID_ACCESS_ERR;
540     return 0;
541 }
542
543 bool Internals::hasContentElement(const Node* root, ExceptionCode& ec) const
544 {
545     if (root && root->isShadowRoot())
546         return ScopeContentDistribution::hasContentElement(toShadowRoot(root));
547
548     ec = INVALID_ACCESS_ERR;
549     return 0;
550 }
551
552 size_t Internals::countElementShadow(const Node* root, ExceptionCode& ec) const
553 {
554     if (!root || !root->isShadowRoot()) {
555         ec = INVALID_ACCESS_ERR;
556         return 0;
557     }
558
559     return ScopeContentDistribution::countElementShadow(toShadowRoot(root));
560 }
561
562 bool Internals::attached(Node* node, ExceptionCode& ec)
563 {
564     if (!node) {
565         ec = INVALID_ACCESS_ERR;
566         return false;
567     }
568
569     return node->attached();
570 }
571
572 Node* Internals::nextSiblingByWalker(Node* node, ExceptionCode& ec)
573 {
574     if (!node) {
575         ec = INVALID_ACCESS_ERR;
576         return 0;
577     }
578     ComposedShadowTreeWalker walker(node);
579     walker.nextSibling();
580     return walker.get();
581 }
582
583 Node* Internals::firstChildByWalker(Node* node, ExceptionCode& ec)
584 {
585     if (!node) {
586         ec = INVALID_ACCESS_ERR;
587         return 0;
588     }
589     ComposedShadowTreeWalker walker(node);
590     walker.firstChild();
591     return walker.get();
592 }
593
594 Node* Internals::lastChildByWalker(Node* node, ExceptionCode& ec)
595 {
596     if (!node) {
597         ec = INVALID_ACCESS_ERR;
598         return 0;
599     }
600     ComposedShadowTreeWalker walker(node);
601     walker.lastChild();
602     return walker.get();
603 }
604
605 Node* Internals::nextNodeByWalker(Node* node, ExceptionCode& ec)
606 {
607     if (!node) {
608         ec = INVALID_ACCESS_ERR;
609         return 0;
610     }
611     ComposedShadowTreeWalker walker(node);
612     walker.next();
613     return walker.get();
614 }
615
616 Node* Internals::previousNodeByWalker(Node* node, ExceptionCode& ec)
617 {
618     if (!node) {
619         ec = INVALID_ACCESS_ERR;
620         return 0;
621     }
622     ComposedShadowTreeWalker walker(node);
623     walker.previous();
624     return walker.get();
625 }
626
627 String Internals::elementRenderTreeAsText(Element* element, ExceptionCode& ec)
628 {
629     if (!element) {
630         ec = INVALID_ACCESS_ERR;
631         return String();
632     }
633
634     String representation = externalRepresentation(element);
635     if (representation.isEmpty()) {
636         ec = INVALID_ACCESS_ERR;
637         return String();
638     }
639
640     return representation;
641 }
642
643 size_t Internals::numberOfScopedHTMLStyleChildren(const Node* scope, ExceptionCode& ec) const
644 {
645     if (scope && (scope->isElementNode() || scope->isShadowRoot()))
646 #if ENABLE(STYLE_SCOPED)
647         return scope->numberOfScopedHTMLStyleChildren();
648 #else
649         return 0;
650 #endif
651
652     ec = INVALID_ACCESS_ERR;
653     return 0;
654 }
655
656 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::ensureShadowRoot(Element* host, ExceptionCode& ec)
657 {
658     if (!host) {
659         ec = INVALID_ACCESS_ERR;
660         return 0;
661     }
662
663     if (ElementShadow* shadow = host->shadow())
664         return shadow->youngestShadowRoot();
665
666     return host->createShadowRoot(ec).get();
667 }
668
669 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::createShadowRoot(Element* host, ExceptionCode& ec)
670 {
671     if (!host) {
672         ec = INVALID_ACCESS_ERR;
673         return 0;
674     }
675     return host->createShadowRoot(ec).get();
676 }
677
678 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::shadowRoot(Element* host, ExceptionCode& ec)
679 {
680     // FIXME: Internals::shadowRoot() in tests should be converted to youngestShadowRoot() or oldestShadowRoot().
681     // https://bugs.webkit.org/show_bug.cgi?id=78465
682     return youngestShadowRoot(host, ec);
683 }
684
685 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::youngestShadowRoot(Element* host, ExceptionCode& ec)
686 {
687     if (!host) {
688         ec = INVALID_ACCESS_ERR;
689         return 0;
690     }
691
692     if (ElementShadow* shadow = host->shadow())
693         return shadow->youngestShadowRoot();
694     return 0;
695 }
696
697 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::oldestShadowRoot(Element* host, ExceptionCode& ec)
698 {
699     if (!host) {
700         ec = INVALID_ACCESS_ERR;
701         return 0;
702     }
703
704     if (ElementShadow* shadow = host->shadow())
705         return shadow->oldestShadowRoot();
706     return 0;
707 }
708
709 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::youngerShadowRoot(Node* shadow, ExceptionCode& ec)
710 {
711     if (!shadow || !shadow->isShadowRoot()) {
712         ec = INVALID_ACCESS_ERR;
713         return 0;
714     }
715
716     return toShadowRoot(shadow)->youngerShadowRoot();
717 }
718
719 Internals::ShadowRootIfShadowDOMEnabledOrNode* Internals::olderShadowRoot(Node* shadow, ExceptionCode& ec)
720 {
721     if (!shadow || !shadow->isShadowRoot()) {
722         ec = INVALID_ACCESS_ERR;
723         return 0;
724     }
725
726     return toShadowRoot(shadow)->olderShadowRoot();
727 }
728
729 String Internals::shadowRootType(const Node* root, ExceptionCode& ec) const
730 {
731     if (!root || !root->isShadowRoot()) {
732         ec = INVALID_ACCESS_ERR;
733         return String();
734     }
735
736     switch (toShadowRoot(root)->type()) {
737     case ShadowRoot::UserAgentShadowRoot:
738         return String("UserAgentShadowRoot");
739     case ShadowRoot::AuthorShadowRoot:
740         return String("AuthorShadowRoot");
741     default:
742         ASSERT_NOT_REACHED();
743         return String("Unknown");
744     }
745 }
746
747 Element* Internals::includerFor(Node* node, ExceptionCode& ec)
748 {
749     if (!node) {
750         ec = INVALID_ACCESS_ERR;
751         return 0;
752     }
753
754     return NodeRenderingContext(node).insertionPoint();
755 }
756
757 String Internals::shadowPseudoId(Element* element, ExceptionCode& ec)
758 {
759     if (!element) {
760         ec = INVALID_ACCESS_ERR;
761         return String();
762     }
763
764     return element->shadowPseudoId().string();
765 }
766
767 void Internals::setShadowPseudoId(Element* element, const String& id, ExceptionCode& ec)
768 {
769     if (!element) {
770         ec = INVALID_ACCESS_ERR;
771         return;
772     }
773
774     return element->setPseudo(id);
775 }
776
777 String Internals::visiblePlaceholder(Element* element)
778 {
779     if (element && isHTMLTextFormControlElement(element)) {
780         if (toHTMLTextFormControlElement(element)->placeholderShouldBeVisible())
781             return toHTMLTextFormControlElement(element)->placeholderElement()->textContent();
782     }
783
784     return String();
785 }
786
787 #if ENABLE(INPUT_TYPE_COLOR)
788 void Internals::selectColorInColorChooser(Element* element, const String& colorValue)
789 {
790     if (!element->hasTagName(inputTag))
791         return;
792     HTMLInputElement* inputElement = element->toInputElement();
793     if (!inputElement)
794         return;
795     inputElement->selectColorInColorChooser(Color(colorValue));
796 }
797 #endif
798
799 Vector<String> Internals::formControlStateOfPreviousHistoryItem(ExceptionCode& ec)
800 {
801     HistoryItem* mainItem = frame()->loader()->history()->previousItem();
802     if (!mainItem) {
803         ec = INVALID_ACCESS_ERR;
804         return Vector<String>();
805     }
806     String uniqueName = frame()->tree()->uniqueName();
807     if (mainItem->target() != uniqueName && !mainItem->childItemWithTarget(uniqueName)) {
808         ec = INVALID_ACCESS_ERR;
809         return Vector<String>();
810     }
811     return mainItem->target() == uniqueName ? mainItem->documentState() : mainItem->childItemWithTarget(uniqueName)->documentState();
812 }
813
814 void Internals::setFormControlStateOfPreviousHistoryItem(const Vector<String>& state, ExceptionCode& ec)
815 {
816     HistoryItem* mainItem = frame()->loader()->history()->previousItem();
817     if (!mainItem) {
818         ec = INVALID_ACCESS_ERR;
819         return;
820     }
821     String uniqueName = frame()->tree()->uniqueName();
822     if (mainItem->target() == uniqueName)
823         mainItem->setDocumentState(state);
824     else if (HistoryItem* subItem = mainItem->childItemWithTarget(uniqueName))
825         subItem->setDocumentState(state);
826     else
827         ec = INVALID_ACCESS_ERR;
828 }
829
830 void Internals::setEnableMockPagePopup(bool enabled, ExceptionCode& ec)
831 {
832 #if ENABLE(PAGE_POPUP)
833     Document* document = contextDocument();
834     if (!document || !document->page() || !document->page()->chrome())
835         return;
836     Page* page = document->page();
837     if (!enabled) {
838         page->chrome()->client()->resetPagePopupDriver();
839         return;
840     }
841     if (!s_pagePopupDriver)
842         s_pagePopupDriver = MockPagePopupDriver::create(page->mainFrame()).leakPtr();
843     page->chrome()->client()->setPagePopupDriver(s_pagePopupDriver);
844 #else
845     UNUSED_PARAM(enabled);
846     UNUSED_PARAM(ec);
847 #endif
848 }
849
850 #if ENABLE(PAGE_POPUP)
851 PassRefPtr<PagePopupController> Internals::pagePopupController()
852 {
853     return s_pagePopupDriver ? s_pagePopupDriver->pagePopupController() : 0;
854 }
855 #endif
856
857 PassRefPtr<ClientRect> Internals::absoluteCaretBounds(ExceptionCode& ec)
858 {
859     Document* document = contextDocument();
860     if (!document || !document->frame() || !document->frame()->selection()) {
861         ec = INVALID_ACCESS_ERR;
862         return ClientRect::create();
863     }
864
865     return ClientRect::create(document->frame()->selection()->absoluteCaretBounds());
866 }
867
868 PassRefPtr<ClientRect> Internals::boundingBox(Element* element, ExceptionCode& ec)
869 {
870     if (!element) {
871         ec = INVALID_ACCESS_ERR;
872         return ClientRect::create();
873     }
874
875     element->document()->updateLayoutIgnorePendingStylesheets();
876     RenderObject* renderer = element->renderer();
877     if (!renderer)
878         return ClientRect::create();
879     return ClientRect::create(renderer->absoluteBoundingBoxRectIgnoringTransforms());
880 }
881
882 PassRefPtr<ClientRectList> Internals::inspectorHighlightRects(Document* document, ExceptionCode& ec)
883 {
884 #if ENABLE(INSPECTOR)
885     if (!document || !document->page() || !document->page()->inspectorController()) {
886         ec = INVALID_ACCESS_ERR;
887         return ClientRectList::create();
888     }
889
890     Highlight highlight;
891     document->page()->inspectorController()->getHighlight(&highlight);
892     return ClientRectList::create(highlight.quads);
893 #else
894     UNUSED_PARAM(document);
895     UNUSED_PARAM(ec);
896     return ClientRectList::create();
897 #endif
898 }
899
900 #if PLATFORM(CHROMIUM)
901 void Internals::setBackgroundBlurOnNode(Node* node, int blurLength, ExceptionCode& ec)
902 {
903     if (!node) {
904         ec = INVALID_ACCESS_ERR;
905         return;
906     }
907
908     RenderObject* renderObject = node->renderer();
909     if (!renderObject) {
910         ec = INVALID_NODE_TYPE_ERR;
911         return;
912     }
913
914     RenderLayer* renderLayer = renderObject->enclosingLayer();
915     if (!renderLayer || !renderLayer->isComposited()) {
916         ec = INVALID_STATE_ERR;
917         return;
918     }
919
920     GraphicsLayer* graphicsLayer = renderLayer->backing()->graphicsLayer();
921     if (!graphicsLayer) {
922         ec = INVALID_NODE_TYPE_ERR;
923         return;
924     }
925
926     FilterOperations filters;
927     filters.operations().append(BlurFilterOperation::create(Length(blurLength, Fixed), FilterOperation::BLUR));
928     static_cast<GraphicsLayerChromium*>(graphicsLayer)->setBackgroundFilters(filters);
929 }
930 #else
931 void Internals::setBackgroundBlurOnNode(Node*, int, ExceptionCode&)
932 {
933 }
934 #endif
935
936 unsigned Internals::markerCountForNode(Node* node, const String& markerType, ExceptionCode& ec)
937 {
938     if (!node) {
939         ec = INVALID_ACCESS_ERR;
940         return 0;
941     }
942
943     DocumentMarker::MarkerTypes markerTypes = 0;
944     if (!markerTypesFrom(markerType, markerTypes)) {
945         ec = SYNTAX_ERR;
946         return 0;
947     }
948
949     return node->document()->markers()->markersFor(node, markerTypes).size();
950 }
951
952 DocumentMarker* Internals::markerAt(Node* node, const String& markerType, unsigned index, ExceptionCode& ec)
953 {
954     if (!node) {
955         ec = INVALID_ACCESS_ERR;
956         return 0;
957     }
958
959     DocumentMarker::MarkerTypes markerTypes = 0;
960     if (!markerTypesFrom(markerType, markerTypes)) {
961         ec = SYNTAX_ERR;
962         return 0;
963     }
964
965     Vector<DocumentMarker*> markers = node->document()->markers()->markersFor(node, markerTypes);
966     if (markers.size() <= index)
967         return 0;
968     return markers[index];
969 }
970
971 PassRefPtr<Range> Internals::markerRangeForNode(Node* node, const String& markerType, unsigned index, ExceptionCode& ec)
972 {
973     DocumentMarker* marker = markerAt(node, markerType, index, ec);
974     if (!marker)
975         return 0;
976     return Range::create(node->document(), node, marker->startOffset(), node, marker->endOffset());
977 }
978
979 String Internals::markerDescriptionForNode(Node* node, const String& markerType, unsigned index, ExceptionCode& ec)
980 {
981     DocumentMarker* marker = markerAt(node, markerType, index, ec);
982     if (!marker)
983         return String();
984     return marker->description();
985 }
986
987 void Internals::addTextMatchMarker(const Range* range, bool isActive)
988 {
989     range->ownerDocument()->updateLayoutIgnorePendingStylesheets();
990     range->ownerDocument()->markers()->addTextMatchMarker(range, isActive);
991 }
992
993 void Internals::setScrollViewPosition(Document* document, long x, long y, ExceptionCode& ec)
994 {
995     if (!document || !document->view()) {
996         ec = INVALID_ACCESS_ERR;
997         return;
998     }
999
1000     FrameView* frameView = document->view();
1001     bool constrainsScrollingToContentEdgeOldValue = frameView->constrainsScrollingToContentEdge();
1002     bool scrollbarsSuppressedOldValue = frameView->scrollbarsSuppressed();
1003
1004     frameView->setConstrainsScrollingToContentEdge(false);
1005     frameView->setScrollbarsSuppressed(false);
1006     frameView->setScrollOffsetFromInternals(IntPoint(x, y));
1007     frameView->setScrollbarsSuppressed(scrollbarsSuppressedOldValue);
1008     frameView->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdgeOldValue);
1009 }
1010
1011 void Internals::setPagination(Document* document, const String& mode, int gap, int pageLength, ExceptionCode& ec)
1012 {
1013     if (!document || !document->page()) {
1014         ec = INVALID_ACCESS_ERR;
1015         return;
1016     }
1017     Page* page = document->page();
1018
1019     Pagination pagination;
1020     if (mode == "Unpaginated")
1021         pagination.mode = Pagination::Unpaginated;
1022     else if (mode == "LeftToRightPaginated")
1023         pagination.mode = Pagination::LeftToRightPaginated;
1024     else if (mode == "RightToLeftPaginated")
1025         pagination.mode = Pagination::RightToLeftPaginated;
1026     else if (mode == "TopToBottomPaginated")
1027         pagination.mode = Pagination::TopToBottomPaginated;
1028     else if (mode == "BottomToTopPaginated")
1029         pagination.mode = Pagination::BottomToTopPaginated;
1030     else {
1031         ec = SYNTAX_ERR;
1032         return;
1033     }
1034
1035     pagination.gap = gap;
1036     pagination.pageLength = pageLength;
1037     page->setPagination(pagination);
1038 }
1039
1040 String Internals::configurationForViewport(Document* document, float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight, ExceptionCode& ec)
1041 {
1042     if (!document || !document->page()) {
1043         ec = INVALID_ACCESS_ERR;
1044         return String();
1045     }
1046     Page* page = document->page();
1047
1048     const int defaultLayoutWidthForNonMobilePages = 980;
1049
1050     ViewportArguments arguments = page->viewportArguments();
1051     ViewportAttributes attributes = computeViewportAttributes(arguments, defaultLayoutWidthForNonMobilePages, deviceWidth, deviceHeight, devicePixelRatio, IntSize(availableWidth, availableHeight));
1052     restrictMinimumScaleFactorToViewportSize(attributes, IntSize(availableWidth, availableHeight), devicePixelRatio);
1053     restrictScaleFactorToInitialScaleIfNotUserScalable(attributes);
1054
1055     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");
1056 }
1057
1058 bool Internals::wasLastChangeUserEdit(Element* textField, ExceptionCode& ec)
1059 {
1060     if (!textField) {
1061         ec = INVALID_ACCESS_ERR;
1062         return false;
1063     }
1064
1065     if (HTMLInputElement* inputElement = textField->toInputElement())
1066         return inputElement->lastChangeWasUserEdit();
1067
1068     // FIXME: We should be using hasTagName instead but Windows port doesn't link QualifiedNames properly.
1069     if (textField->tagName() == "TEXTAREA")
1070         return static_cast<HTMLTextAreaElement*>(textField)->lastChangeWasUserEdit();
1071
1072     ec = INVALID_NODE_TYPE_ERR;
1073     return false;
1074 }
1075
1076 String Internals::suggestedValue(Element* element, ExceptionCode& ec)
1077 {
1078     if (!element) {
1079         ec = INVALID_ACCESS_ERR;
1080         return String();
1081     }
1082
1083     HTMLInputElement* inputElement = element->toInputElement();
1084     if (!inputElement) {
1085         ec = INVALID_NODE_TYPE_ERR;
1086         return String();
1087     }
1088
1089     return inputElement->suggestedValue();
1090 }
1091
1092 void Internals::setSuggestedValue(Element* element, const String& value, ExceptionCode& ec)
1093 {
1094     if (!element) {
1095         ec = INVALID_ACCESS_ERR;
1096         return;
1097     }
1098
1099     HTMLInputElement* inputElement = element->toInputElement();
1100     if (!inputElement) {
1101         ec = INVALID_NODE_TYPE_ERR;
1102         return;
1103     }
1104
1105     inputElement->setSuggestedValue(value);
1106 }
1107
1108 void Internals::setEditingValue(Element* element, const String& value, ExceptionCode& ec)
1109 {
1110     if (!element) {
1111         ec = INVALID_ACCESS_ERR;
1112         return;
1113     }
1114
1115     HTMLInputElement* inputElement = element->toInputElement();
1116     if (!inputElement) {
1117         ec = INVALID_NODE_TYPE_ERR;
1118         return;
1119     }
1120
1121     inputElement->setEditingValue(value);
1122 }
1123
1124 void Internals::scrollElementToRect(Element* element, long x, long y, long w, long h, ExceptionCode& ec)
1125 {
1126     if (!element || !element->document() || !element->document()->view()) {
1127         ec = INVALID_ACCESS_ERR;
1128         return;
1129     }
1130     FrameView* frameView = element->document()->view();
1131     frameView->scrollElementToRect(element, IntRect(x, y, w, h));
1132 }
1133
1134 void Internals::paintControlTints(Document* document, ExceptionCode& ec)
1135 {
1136     if (!document || !document->view()) {
1137         ec = INVALID_ACCESS_ERR;
1138         return;
1139     }
1140
1141     FrameView* frameView = document->view();
1142     frameView->paintControlTints();
1143 }
1144
1145 PassRefPtr<Range> Internals::rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength, ExceptionCode& ec)
1146 {
1147     if (!scope) {
1148         ec = INVALID_ACCESS_ERR;
1149         return 0;
1150     }
1151
1152     return TextIterator::rangeFromLocationAndLength(scope, rangeLocation, rangeLength);
1153 }
1154
1155 unsigned Internals::locationFromRange(Element* scope, const Range* range, ExceptionCode& ec)
1156 {
1157     if (!scope || !range) {
1158         ec = INVALID_ACCESS_ERR;
1159         return 0;
1160     }
1161
1162     size_t location = 0;
1163     size_t unusedLength = 0;
1164     TextIterator::getLocationAndLengthFromRange(scope, range, location, unusedLength);
1165     return location;
1166 }
1167
1168 unsigned Internals::lengthFromRange(Element* scope, const Range* range, ExceptionCode& ec)
1169 {
1170     if (!scope || !range) {
1171         ec = INVALID_ACCESS_ERR;
1172         return 0;
1173     }
1174
1175     size_t unusedLocation = 0;
1176     size_t length = 0;
1177     TextIterator::getLocationAndLengthFromRange(scope, range, unusedLocation, length);
1178     return length;
1179 }
1180
1181 String Internals::rangeAsText(const Range* range, ExceptionCode& ec)
1182 {
1183     if (!range) {
1184         ec = INVALID_ACCESS_ERR;
1185         return String();
1186     }
1187
1188     return range->text();
1189 }
1190
1191 void Internals::setDelegatesScrolling(bool enabled, Document* document, ExceptionCode& ec)
1192 {
1193     // Delegate scrolling is valid only on mainframe's view.
1194     if (!document || !document->view() || !document->page() || document->page()->mainFrame() != document->frame()) {
1195         ec = INVALID_ACCESS_ERR;
1196         return;
1197     }
1198
1199     document->view()->setDelegatesScrolling(enabled);
1200 }
1201
1202 #if ENABLE(TOUCH_ADJUSTMENT)
1203 PassRefPtr<WebKitPoint> Internals::touchPositionAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionCode& ec)
1204 {
1205     if (!document || !document->frame()) {
1206         ec = INVALID_ACCESS_ERR;
1207         return 0;
1208     }
1209
1210     IntSize radius(width / 2, height / 2);
1211     IntPoint point(x + radius.width(), y + radius.height());
1212
1213     Node* targetNode;
1214     IntPoint adjustedPoint;
1215
1216     bool foundNode = document->frame()->eventHandler()->bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
1217     if (foundNode)
1218         return WebKitPoint::create(adjustedPoint.x(), adjustedPoint.y());
1219
1220     return 0;
1221 }
1222
1223 Node* Internals::touchNodeAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionCode& ec)
1224 {
1225     if (!document || !document->frame()) {
1226         ec = INVALID_ACCESS_ERR;
1227         return 0;
1228     }
1229
1230     IntSize radius(width / 2, height / 2);
1231     IntPoint point(x + radius.width(), y + radius.height());
1232
1233     Node* targetNode;
1234     IntPoint adjustedPoint;
1235     document->frame()->eventHandler()->bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
1236     return targetNode;
1237 }
1238
1239 PassRefPtr<WebKitPoint> Internals::touchPositionAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionCode& ec)
1240 {
1241     if (!document || !document->frame()) {
1242         ec = INVALID_ACCESS_ERR;
1243         return 0;
1244     }
1245
1246     IntSize radius(width / 2, height / 2);
1247     IntPoint point(x + radius.width(), y + radius.height());
1248
1249     Node* targetNode = 0;
1250     IntPoint adjustedPoint;
1251
1252     bool foundNode = document->frame()->eventHandler()->bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
1253     if (foundNode)
1254         return WebKitPoint::create(adjustedPoint.x(), adjustedPoint.y());
1255
1256     return WebKitPoint::create(x, y);
1257 }
1258
1259 Node* Internals::touchNodeAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionCode& ec)
1260 {
1261     if (!document || !document->frame()) {
1262         ec = INVALID_ACCESS_ERR;
1263         return 0;
1264     }
1265
1266     IntSize radius(width / 2, height / 2);
1267     IntPoint point(x + radius.width(), y + radius.height());
1268
1269     Node* targetNode = 0;
1270     IntPoint adjustedPoint;
1271     document->frame()->eventHandler()->bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
1272     return targetNode;
1273 }
1274
1275 PassRefPtr<ClientRect> Internals::bestZoomableAreaForTouchPoint(long x, long y, long width, long height, Document* document, ExceptionCode& ec)
1276 {
1277     if (!document || !document->frame()) {
1278         ec = INVALID_ACCESS_ERR;
1279         return 0;
1280     }
1281
1282     IntSize radius(width / 2, height / 2);
1283     IntPoint point(x + radius.width(), y + radius.height());
1284
1285     Node* targetNode;
1286     IntRect zoomableArea;
1287     bool foundNode = document->frame()->eventHandler()->bestZoomableAreaForTouchPoint(point, radius, zoomableArea, targetNode);
1288     if (foundNode)
1289         return ClientRect::create(zoomableArea);
1290
1291     return 0;
1292 }
1293 #endif
1294
1295
1296 int Internals::lastSpellCheckRequestSequence(Document* document, ExceptionCode& ec)
1297 {
1298     SpellChecker* checker = spellchecker(document);
1299
1300     if (!checker) {
1301         ec = INVALID_ACCESS_ERR;
1302         return -1;
1303     }
1304
1305     return checker->lastRequestSequence();
1306 }
1307
1308 int Internals::lastSpellCheckProcessedSequence(Document* document, ExceptionCode& ec)
1309 {
1310     SpellChecker* checker = spellchecker(document);
1311
1312     if (!checker) {
1313         ec = INVALID_ACCESS_ERR;
1314         return -1;
1315     }
1316
1317     return checker->lastProcessedSequence();
1318 }
1319
1320 Vector<String> Internals::userPreferredLanguages() const
1321 {
1322     return WebCore::userPreferredLanguages();
1323 }
1324
1325 void Internals::setUserPreferredLanguages(const Vector<String>& languages)
1326 {
1327     WebCore::overrideUserPreferredLanguages(languages);
1328 }
1329
1330 unsigned Internals::wheelEventHandlerCount(Document* document, ExceptionCode& ec)
1331 {
1332     if (!document) {
1333         ec = INVALID_ACCESS_ERR;
1334         return 0;
1335     }
1336
1337     return document->wheelEventHandlerCount();
1338 }
1339
1340 unsigned Internals::touchEventHandlerCount(Document* document, ExceptionCode& ec)
1341 {
1342     if (!document) {
1343         ec = INVALID_ACCESS_ERR;
1344         return 0;
1345     }
1346
1347     const TouchEventTargetSet* touchHandlers = document->touchEventTargets();
1348     if (!touchHandlers)
1349         return 0;
1350
1351     unsigned count = 0;
1352     for (TouchEventTargetSet::const_iterator iter = touchHandlers->begin(); iter != touchHandlers->end(); ++iter)
1353         count += iter->value;
1354     return count;
1355 }
1356
1357 #if ENABLE(TOUCH_EVENT_TRACKING)
1358 PassRefPtr<ClientRectList> Internals::touchEventTargetClientRects(Document* document, ExceptionCode& ec)
1359 {
1360     if (!document || !document->view() || !document->page()) {
1361         ec = INVALID_ACCESS_ERR;
1362         return 0;
1363     }
1364     if (!document->page()->scrollingCoordinator())
1365         return ClientRectList::create();
1366
1367     document->updateLayoutIgnorePendingStylesheets();
1368
1369     Vector<IntRect> absoluteRects;
1370     document->page()->scrollingCoordinator()->computeAbsoluteTouchEventTargetRects(document, absoluteRects);
1371     Vector<FloatQuad> absoluteQuads(absoluteRects.size());
1372
1373     for (size_t i = 0; i < absoluteRects.size(); ++i)
1374         absoluteQuads[i] = FloatQuad(absoluteRects[i]);
1375
1376     return ClientRectList::create(absoluteQuads);
1377 }
1378 #endif
1379
1380 PassRefPtr<NodeList> Internals::nodesFromRect(Document* document, int x, int y, unsigned topPadding, unsigned rightPadding,
1381     unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent, ExceptionCode& ec) const
1382 {
1383     if (!document || !document->frame() || !document->frame()->view()) {
1384         ec = INVALID_ACCESS_ERR;
1385         return 0;
1386     }
1387
1388     return document->nodesFromRect(x, y, topPadding, rightPadding, bottomPadding, leftPadding, ignoreClipping, allowShadowContent);
1389 }
1390
1391 void Internals::emitInspectorDidBeginFrame()
1392 {
1393     InspectorInstrumentation::didBeginFrame(contextDocument()->frame()->page());
1394 }
1395
1396 void Internals::emitInspectorDidCancelFrame()
1397 {
1398     InspectorInstrumentation::didCancelFrame(contextDocument()->frame()->page());
1399 }
1400
1401 void Internals::setBatteryStatus(Document* document, const String& eventType, bool charging, double chargingTime, double dischargingTime, double level, ExceptionCode& ec)
1402 {
1403     if (!document || !document->page()) {
1404         ec = INVALID_ACCESS_ERR;
1405         return;
1406     }
1407
1408 #if ENABLE(BATTERY_STATUS)
1409     BatteryController::from(document->page())->didChangeBatteryStatus(eventType, BatteryStatus::create(charging, chargingTime, dischargingTime, level));
1410 #else
1411     UNUSED_PARAM(eventType);
1412     UNUSED_PARAM(charging);
1413     UNUSED_PARAM(chargingTime);
1414     UNUSED_PARAM(dischargingTime);
1415     UNUSED_PARAM(level);
1416 #endif
1417 }
1418
1419 void Internals::setNetworkInformation(Document* document, const String& eventType, double bandwidth, bool metered, ExceptionCode& ec)
1420 {
1421     if (!document || !document->page()) {
1422         ec = INVALID_ACCESS_ERR;
1423         return;
1424     }
1425
1426 #if ENABLE(NETWORK_INFO)
1427     NetworkInfoController::from(document->page())->didChangeNetworkInformation(eventType, NetworkInfo::create(bandwidth, metered));
1428 #else
1429     UNUSED_PARAM(eventType);
1430     UNUSED_PARAM(bandwidth);
1431     UNUSED_PARAM(metered);
1432 #endif
1433 }
1434
1435 void Internals::setDeviceProximity(Document* document, const String& eventType, double value, double min, double max, ExceptionCode& ec)
1436 {
1437     if (!document || !document->page()) {
1438         ec = INVALID_ACCESS_ERR;
1439         return;
1440     }
1441
1442 #if ENABLE(PROXIMITY_EVENTS)
1443     DeviceProximityController::from(document->page())->didChangeDeviceProximity(value, min, max);
1444 #else
1445     UNUSED_PARAM(eventType);
1446     UNUSED_PARAM(value);
1447     UNUSED_PARAM(min);
1448     UNUSED_PARAM(max);
1449 #endif
1450 }
1451
1452 bool Internals::hasSpellingMarker(Document* document, int from, int length, ExceptionCode&)
1453 {
1454     if (!document || !document->frame())
1455         return 0;
1456
1457     return document->frame()->editor()->selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length);
1458 }
1459     
1460 bool Internals::hasAutocorrectedMarker(Document* document, int from, int length, ExceptionCode&)
1461 {
1462     if (!document || !document->frame())
1463         return 0;
1464     
1465     return document->frame()->editor()->selectionStartHasMarkerFor(DocumentMarker::Autocorrected, from, length);
1466 }
1467
1468 #if ENABLE(INSPECTOR)
1469 unsigned Internals::numberOfLiveNodes() const
1470 {
1471     return InspectorCounters::counterValue(InspectorCounters::NodeCounter);
1472 }
1473
1474 unsigned Internals::numberOfLiveDocuments() const
1475 {
1476     return InspectorCounters::counterValue(InspectorCounters::DocumentCounter);
1477 }
1478
1479 Vector<String> Internals::consoleMessageArgumentCounts(Document* document) const
1480 {
1481     InstrumentingAgents* instrumentingAgents = instrumentationForPage(document->page());
1482     if (!instrumentingAgents)
1483         return Vector<String>();
1484     InspectorConsoleAgent* consoleAgent = instrumentingAgents->inspectorConsoleAgent();
1485     if (!consoleAgent)
1486         return Vector<String>();
1487     Vector<unsigned> counts = consoleAgent->consoleMessageArgumentCounts();
1488     Vector<String> result(counts.size());
1489     for (size_t i = 0; i < counts.size(); i++)
1490         result[i] = String::number(counts[i]);
1491     return result;
1492 }
1493
1494 PassRefPtr<DOMWindow> Internals::openDummyInspectorFrontend(const String& url)
1495 {
1496     Page* page = contextDocument()->frame()->page();
1497     ASSERT(page);
1498
1499     DOMWindow* window = page->mainFrame()->document()->domWindow();
1500     ASSERT(window);
1501
1502     m_frontendWindow = window->open(url, "", "", window, window);
1503     ASSERT(m_frontendWindow);
1504
1505     Page* frontendPage = m_frontendWindow->document()->page();
1506     ASSERT(frontendPage);
1507
1508     OwnPtr<InspectorFrontendClientDummy> frontendClient = adoptPtr(new InspectorFrontendClientDummy(page->inspectorController(), frontendPage));
1509
1510     frontendPage->inspectorController()->setInspectorFrontendClient(frontendClient.release());
1511
1512     m_frontendChannel = adoptPtr(new InspectorFrontendChannelDummy(frontendPage));
1513
1514     page->inspectorController()->connectFrontend(m_frontendChannel.get());
1515
1516     return m_frontendWindow;
1517 }
1518
1519 void Internals::closeDummyInspectorFrontend()
1520 {
1521     Page* page = contextDocument()->frame()->page();
1522     ASSERT(page);
1523     ASSERT(m_frontendWindow);
1524
1525     page->inspectorController()->disconnectFrontend();
1526
1527     m_frontendChannel.release();
1528
1529     m_frontendWindow->close(m_frontendWindow->scriptExecutionContext());
1530     m_frontendWindow.release();
1531 }
1532
1533 void Internals::setInspectorResourcesDataSizeLimits(int maximumResourcesContentSize, int maximumSingleResourceContentSize, ExceptionCode& ec)
1534 {
1535     Page* page = contextDocument()->frame()->page();
1536     if (!page || !page->inspectorController()) {
1537         ec = INVALID_ACCESS_ERR;
1538         return;
1539     }
1540     page->inspectorController()->setResourcesDataSizeLimitsFromInternals(maximumResourcesContentSize, maximumSingleResourceContentSize);
1541 }
1542
1543 void Internals::setJavaScriptProfilingEnabled(bool enabled, ExceptionCode& ec)
1544 {
1545     Page* page = contextDocument()->frame()->page();
1546     if (!page || !page->inspectorController()) {
1547         ec = INVALID_ACCESS_ERR;
1548         return;
1549     }
1550
1551     page->inspectorController()->setProfilerEnabled(enabled);
1552 }
1553 #endif // ENABLE(INSPECTOR)
1554
1555 bool Internals::hasGrammarMarker(Document* document, int from, int length, ExceptionCode&)
1556 {
1557     if (!document || !document->frame())
1558         return 0;
1559
1560     return document->frame()->editor()->selectionStartHasMarkerFor(DocumentMarker::Grammar, from, length);
1561 }
1562
1563 unsigned Internals::numberOfScrollableAreas(Document* document, ExceptionCode&)
1564 {
1565     unsigned count = 0;
1566     Frame* frame = document->frame();
1567     if (frame->view()->scrollableAreas())
1568         count += frame->view()->scrollableAreas()->size();
1569
1570     for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
1571         if (child->view() && child->view()->scrollableAreas())
1572             count += child->view()->scrollableAreas()->size();
1573     }
1574
1575     return count;
1576 }
1577     
1578 bool Internals::isPageBoxVisible(Document* document, int pageNumber, ExceptionCode& ec)
1579 {
1580     if (!document) {
1581         ec = INVALID_ACCESS_ERR;
1582         return false;
1583     }
1584
1585     return document->isPageBoxVisible(pageNumber);
1586 }
1587
1588 String Internals::layerTreeAsText(Document* document, ExceptionCode& ec) const
1589 {
1590     return layerTreeAsText(document, 0, ec);
1591 }
1592
1593 String Internals::layerTreeAsText(Document* document, unsigned flags, ExceptionCode& ec) const
1594 {
1595     if (!document || !document->frame()) {
1596         ec = INVALID_ACCESS_ERR;
1597         return String();
1598     }
1599
1600     LayerTreeFlags layerTreeFlags = 0;
1601     if (flags & LAYER_TREE_INCLUDES_VISIBLE_RECTS)
1602         layerTreeFlags |= LayerTreeFlagsIncludeVisibleRects;
1603     if (flags & LAYER_TREE_INCLUDES_TILE_CACHES)
1604         layerTreeFlags |= LayerTreeFlagsIncludeTileCaches;
1605     if (flags & LAYER_TREE_INCLUDES_REPAINT_RECTS)
1606         layerTreeFlags |= LayerTreeFlagsIncludeRepaintRects;
1607
1608     return document->frame()->layerTreeAsText(layerTreeFlags);
1609 }
1610
1611 String Internals::repaintRectsAsText(Document* document, ExceptionCode& ec) const
1612 {
1613     if (!document || !document->frame()) {
1614         ec = INVALID_ACCESS_ERR;
1615         return String();
1616     }
1617
1618     return document->frame()->trackedRepaintRectsAsText();
1619 }
1620
1621 String Internals::scrollingStateTreeAsText(Document* document, ExceptionCode& ec) const
1622 {
1623     if (!document || !document->frame()) {
1624         ec = INVALID_ACCESS_ERR;
1625         return String();
1626     }
1627
1628     Page* page = document->page();
1629     if (!page)
1630         return String();
1631
1632     return page->scrollingStateTreeAsText();
1633 }
1634
1635 String Internals::mainThreadScrollingReasons(Document* document, ExceptionCode& ec) const
1636 {
1637     if (!document || !document->frame()) {
1638         ec = INVALID_ACCESS_ERR;
1639         return String();
1640     }
1641
1642     Page* page = document->page();
1643     if (!page)
1644         return String();
1645
1646     return page->mainThreadScrollingReasonsAsText();
1647 }
1648
1649 PassRefPtr<ClientRectList> Internals::nonFastScrollableRects(Document* document, ExceptionCode& ec) const
1650 {
1651     if (!document || !document->frame()) {
1652         ec = INVALID_ACCESS_ERR;
1653         return 0;
1654     }
1655
1656     Page* page = document->page();
1657     if (!page)
1658         return 0;
1659
1660     return page->nonFastScrollableRects(document->frame());
1661 }
1662
1663 void Internals::garbageCollectDocumentResources(Document* document, ExceptionCode& ec) const
1664 {
1665     if (!document) {
1666         ec = INVALID_ACCESS_ERR;
1667         return;
1668     }
1669
1670     CachedResourceLoader* cachedResourceLoader = document->cachedResourceLoader();
1671     if (!cachedResourceLoader)
1672         return;
1673     cachedResourceLoader->garbageCollectDocumentResources();
1674 }
1675
1676 void Internals::allowRoundingHacks() const
1677 {
1678     TextRun::setAllowsRoundingHacks(true);
1679 }
1680
1681 void Internals::insertAuthorCSS(Document* document, const String& css) const
1682 {
1683     RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(document);
1684     parsedSheet->setIsUserStyleSheet(false);
1685     parsedSheet->parseString(css);
1686     document->styleSheetCollection()->addAuthorSheet(parsedSheet);
1687 }
1688
1689 void Internals::insertUserCSS(Document* document, const String& css) const
1690 {
1691     RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(document);
1692     parsedSheet->setIsUserStyleSheet(true);
1693     parsedSheet->parseString(css);
1694     document->styleSheetCollection()->addUserSheet(parsedSheet);
1695 }
1696
1697 String Internals::counterValue(Element* element)
1698 {
1699     if (!element)
1700         return String();
1701
1702     return counterValueForElement(element);
1703 }
1704
1705 int Internals::pageNumber(Element* element, float pageWidth, float pageHeight)
1706 {
1707     if (!element)
1708         return 0;
1709
1710     return PrintContext::pageNumberForElement(element, FloatSize(pageWidth, pageHeight));
1711 }
1712
1713 Vector<String> Internals::iconURLs(Document* document) const
1714 {
1715     Vector<IconURL> iconURLs = document->iconURLs();
1716     Vector<String> array;
1717
1718     Vector<IconURL>::const_iterator iter(iconURLs.begin());
1719     for (; iter != iconURLs.end(); ++iter)
1720         array.append(iter->m_iconURL.string());
1721
1722     return array;
1723 }
1724
1725 int Internals::numberOfPages(float pageWidth, float pageHeight)
1726 {
1727     if (!frame())
1728         return -1;
1729
1730     return PrintContext::numberOfPages(frame(), FloatSize(pageWidth, pageHeight));
1731 }
1732
1733 String Internals::pageProperty(String propertyName, int pageNumber, ExceptionCode& ec) const
1734 {
1735     if (!frame()) {
1736         ec = INVALID_ACCESS_ERR;
1737         return String();
1738     }
1739
1740     return PrintContext::pageProperty(frame(), propertyName.utf8().data(), pageNumber);
1741 }
1742
1743 String Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft, ExceptionCode& ec) const
1744 {
1745     if (!frame()) {
1746         ec = INVALID_ACCESS_ERR;
1747         return String();
1748     }
1749
1750     return PrintContext::pageSizeAndMarginsInPixels(frame(), pageNumber, width, height, marginTop, marginRight, marginBottom, marginLeft);
1751 }
1752
1753 void Internals::setPageScaleFactor(float scaleFactor, int x, int y, ExceptionCode& ec)
1754 {
1755     Document* document = contextDocument();
1756     if (!document || !document->page()) {
1757         ec = INVALID_ACCESS_ERR;
1758         return;
1759     }
1760     Page* page = document->page();
1761     page->setPageScaleFactor(scaleFactor, IntPoint(x, y));
1762 }
1763
1764 #if ENABLE(FULLSCREEN_API)
1765 void Internals::webkitWillEnterFullScreenForElement(Document* document, Element* element)
1766 {
1767     if (!document)
1768         return;
1769     document->webkitWillEnterFullScreenForElement(element);
1770 }
1771
1772 void Internals::webkitDidEnterFullScreenForElement(Document* document, Element* element)
1773 {
1774     if (!document)
1775         return;
1776     document->webkitDidEnterFullScreenForElement(element);
1777 }
1778
1779 void Internals::webkitWillExitFullScreenForElement(Document* document, Element* element)
1780 {
1781     if (!document)
1782         return;
1783     document->webkitWillExitFullScreenForElement(element);
1784 }
1785
1786 void Internals::webkitDidExitFullScreenForElement(Document* document, Element* element)
1787 {
1788     if (!document)
1789         return;
1790     document->webkitDidExitFullScreenForElement(element);
1791 }
1792 #endif
1793
1794 void Internals::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme)
1795 {
1796     SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(scheme);
1797 }
1798
1799 void Internals::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(const String& scheme)
1800 {
1801     SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(scheme);
1802 }
1803
1804 PassRefPtr<MallocStatistics> Internals::mallocStatistics() const
1805 {
1806     return MallocStatistics::create();
1807 }
1808
1809 PassRefPtr<TypeConversions> Internals::typeConversions() const
1810 {
1811     return TypeConversions::create();
1812 }
1813
1814 Vector<String> Internals::getReferencedFilePaths() const
1815 {
1816     frame()->loader()->history()->saveDocumentAndScrollState();
1817     return FormController::getReferencedFilePaths(frame()->loader()->history()->currentItem()->documentState());
1818 }
1819
1820 void Internals::startTrackingRepaints(Document* document, ExceptionCode& ec)
1821 {
1822     if (!document || !document->view()) {
1823         ec = INVALID_ACCESS_ERR;
1824         return;
1825     }
1826
1827     FrameView* frameView = document->view();
1828     frameView->setTracksRepaints(true);
1829 }
1830
1831 void Internals::stopTrackingRepaints(Document* document, ExceptionCode& ec)
1832 {
1833     if (!document || !document->view()) {
1834         ec = INVALID_ACCESS_ERR;
1835         return;
1836     }
1837
1838     FrameView* frameView = document->view();
1839     frameView->setTracksRepaints(false);
1840 }
1841
1842 #if USE(LAZY_NATIVE_CURSOR)
1843 static const char* cursorTypeToString(Cursor::Type cursorType)
1844 {
1845     switch (cursorType) {
1846     case Cursor::Pointer: return "Pointer";
1847     case Cursor::Cross: return "Cross";
1848     case Cursor::Hand: return "Hand";
1849     case Cursor::IBeam: return "IBeam";
1850     case Cursor::Wait: return "Wait";
1851     case Cursor::Help: return "Help";
1852     case Cursor::EastResize: return "EastResize";
1853     case Cursor::NorthResize: return "NorthResize";
1854     case Cursor::NorthEastResize: return "NorthEastResize";
1855     case Cursor::NorthWestResize: return "NorthWestResize";
1856     case Cursor::SouthResize: return "SouthResize";
1857     case Cursor::SouthEastResize: return "SouthEastResize";
1858     case Cursor::SouthWestResize: return "SouthWestResize";
1859     case Cursor::WestResize: return "WestResize";
1860     case Cursor::NorthSouthResize: return "NorthSouthResize";
1861     case Cursor::EastWestResize: return "EastWestResize";
1862     case Cursor::NorthEastSouthWestResize: return "NorthEastSouthWestResize";
1863     case Cursor::NorthWestSouthEastResize: return "NorthWestSouthEastResize";
1864     case Cursor::ColumnResize: return "ColumnResize";
1865     case Cursor::RowResize: return "RowResize";
1866     case Cursor::MiddlePanning: return "MiddlePanning";
1867     case Cursor::EastPanning: return "EastPanning";
1868     case Cursor::NorthPanning: return "NorthPanning";
1869     case Cursor::NorthEastPanning: return "NorthEastPanning";
1870     case Cursor::NorthWestPanning: return "NorthWestPanning";
1871     case Cursor::SouthPanning: return "SouthPanning";
1872     case Cursor::SouthEastPanning: return "SouthEastPanning";
1873     case Cursor::SouthWestPanning: return "SouthWestPanning";
1874     case Cursor::WestPanning: return "WestPanning";
1875     case Cursor::Move: return "Move";
1876     case Cursor::VerticalText: return "VerticalText";
1877     case Cursor::Cell: return "Cell";
1878     case Cursor::ContextMenu: return "ContextMenu";
1879     case Cursor::Alias: return "Alias";
1880     case Cursor::Progress: return "Progress";
1881     case Cursor::NoDrop: return "NoDrop";
1882     case Cursor::Copy: return "Copy";
1883     case Cursor::None: return "None";
1884     case Cursor::NotAllowed: return "NotAllowed";
1885     case Cursor::ZoomIn: return "ZoomIn";
1886     case Cursor::ZoomOut: return "ZoomOut";
1887     case Cursor::Grab: return "Grab";
1888     case Cursor::Grabbing: return "Grabbing";
1889     case Cursor::Custom: return "Custom";
1890     }
1891
1892     ASSERT_NOT_REACHED();
1893     return "UNKNOWN";
1894 }
1895 #endif
1896
1897 String Internals::getCurrentCursorInfo(Document* document, ExceptionCode& ec)
1898 {
1899     if (!document || !document->frame()) {
1900         ec = INVALID_ACCESS_ERR;
1901         return String();
1902     }
1903
1904     Cursor cursor = document->frame()->eventHandler()->currentMouseCursor();
1905
1906 #if USE(LAZY_NATIVE_CURSOR)
1907     StringBuilder result;
1908     result.append("type=");
1909     result.append(cursorTypeToString(cursor.type()));
1910     result.append(" hotSpot=");
1911     result.appendNumber(cursor.hotSpot().x());
1912     result.append(",");
1913     result.appendNumber(cursor.hotSpot().y());
1914     if (cursor.image()) {
1915         IntSize size = cursor.image()->size();
1916         result.append(" image=");
1917         result.appendNumber(size.width());
1918         result.append("x");
1919         result.appendNumber(size.height());
1920     }
1921 #if ENABLE(MOUSE_CURSOR_SCALE)
1922     if (cursor.imageScaleFactor() != 1) {
1923         result.append(" scale=");
1924         NumberToStringBuffer buffer;
1925         result.append(numberToFixedPrecisionString(cursor.imageScaleFactor(), 8, buffer, true));
1926     }
1927 #endif
1928     return result.toString();
1929 #else
1930     return "FAIL: Cursor details not available on this platform.";
1931 #endif
1932 }
1933
1934 PassRefPtr<ArrayBuffer> Internals::serializeObject(PassRefPtr<SerializedScriptValue> value) const
1935 {
1936 #if USE(V8)
1937     String stringValue = value->toWireString();
1938     return ArrayBuffer::create(static_cast<const void*>(stringValue.impl()->characters()), stringValue.sizeInBytes());
1939 #else
1940     Vector<uint8_t> bytes = value->data();
1941     return ArrayBuffer::create(bytes.data(), bytes.size());
1942 #endif
1943 }
1944
1945 PassRefPtr<SerializedScriptValue> Internals::deserializeBuffer(PassRefPtr<ArrayBuffer> buffer) const
1946 {
1947 #if USE(V8)
1948     String value(static_cast<const UChar*>(buffer->data()), buffer->byteLength() / sizeof(UChar));
1949     return SerializedScriptValue::createFromWire(value);
1950 #else
1951     Vector<uint8_t> bytes;
1952     bytes.append(static_cast<const uint8_t*>(buffer->data()), buffer->byteLength());
1953     return SerializedScriptValue::adopt(bytes);
1954 #endif
1955 }
1956
1957 void Internals::setUsesOverlayScrollbars(bool enabled)
1958 {
1959     WebCore::Settings::setUsesOverlayScrollbars(enabled);
1960 }
1961
1962 #if ENABLE(ENCRYPTED_MEDIA_V2)
1963 void Internals::initializeMockCDM()
1964 {
1965     CDM::registerCDMFactory(MockCDM::create, MockCDM::supportsKeySytem);
1966 }
1967 #endif
1968
1969 }