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