initial import
[vuplus_webkit] / Source / WebKit / chromium / src / WebFrameImpl.cpp
1 /*
2  * Copyright (C) 2009 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 are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 // How ownership works
32 // -------------------
33 //
34 // Big oh represents a refcounted relationship: owner O--- ownee
35 //
36 // WebView (for the toplevel frame only)
37 //    O
38 //    |
39 //   Page O------- Frame (m_mainFrame) O-------O FrameView
40 //                   ||
41 //                   ||
42 //               FrameLoader O-------- WebFrame (via FrameLoaderClient)
43 //
44 // FrameLoader and Frame are formerly one object that was split apart because
45 // it got too big. They basically have the same lifetime, hence the double line.
46 //
47 // WebFrame is refcounted and has one ref on behalf of the FrameLoader/Frame.
48 // This is not a normal reference counted pointer because that would require
49 // changing WebKit code that we don't control. Instead, it is created with this
50 // ref initially and it is removed when the FrameLoader is getting destroyed.
51 //
52 // WebFrames are created in two places, first in WebViewImpl when the root
53 // frame is created, and second in WebFrame::CreateChildFrame when sub-frames
54 // are created. WebKit will hook up this object to the FrameLoader/Frame
55 // and the refcount will be correct.
56 //
57 // How frames are destroyed
58 // ------------------------
59 //
60 // The main frame is never destroyed and is re-used. The FrameLoader is re-used
61 // and a reference to the main frame is kept by the Page.
62 //
63 // When frame content is replaced, all subframes are destroyed. This happens
64 // in FrameLoader::detachFromParent for each subframe.
65 //
66 // Frame going away causes the FrameLoader to get deleted. In FrameLoader's
67 // destructor, it notifies its client with frameLoaderDestroyed. This calls
68 // WebFrame::Closing and then derefs the WebFrame and will cause it to be
69 // deleted (unless an external someone is also holding a reference).
70
71 #include "config.h"
72 #include "WebFrameImpl.h"
73
74 #include "AssociatedURLLoader.h"
75 #include "BackForwardController.h"
76 #include "Chrome.h"
77 #include "ClipboardUtilitiesChromium.h"
78 #include "Console.h"
79 #include "DOMUtilitiesPrivate.h"
80 #include "DOMWindow.h"
81 #include "Document.h"
82 #include "DocumentFragment.h" // Only needed for ReplaceSelectionCommand.h :(
83 #include "DocumentLoader.h"
84 #include "DocumentMarker.h"
85 #include "DocumentMarkerController.h"
86 #include "Editor.h"
87 #include "EventHandler.h"
88 #include "FocusController.h"
89 #include "FormState.h"
90 #include "FrameLoadRequest.h"
91 #include "FrameLoader.h"
92 #include "FrameSelection.h"
93 #include "FrameTree.h"
94 #include "FrameView.h"
95 #include "HTMLCollection.h"
96 #include "HTMLFormElement.h"
97 #include "HTMLFrameOwnerElement.h"
98 #include "HTMLHeadElement.h"
99 #include "HTMLInputElement.h"
100 #include "HTMLLinkElement.h"
101 #include "HTMLNames.h"
102 #include "HistoryItem.h"
103 #include "HitTestResult.h"
104 #include "IconURL.h"
105 #include "InspectorController.h"
106 #include "KURL.h"
107 #include "Page.h"
108 #include "PageOverlay.h"
109 #include "painting/GraphicsContextBuilder.h"
110 #include "Performance.h"
111 #include "PlatformSupport.h"
112 #include "PluginDocument.h"
113 #include "PrintContext.h"
114 #include "RenderFrame.h"
115 #include "RenderLayer.h"
116 #include "RenderObject.h"
117 #include "RenderTreeAsText.h"
118 #include "RenderView.h"
119 #include "RenderWidget.h"
120 #include "ReplaceSelectionCommand.h"
121 #include "ResourceHandle.h"
122 #include "ResourceRequest.h"
123 #include "SVGDocumentExtensions.h"
124 #include "SVGSMILElement.h"
125 #include "SchemeRegistry.h"
126 #include "ScriptController.h"
127 #include "ScriptSourceCode.h"
128 #include "ScriptValue.h"
129 #include "ScrollTypes.h"
130 #include "ScrollbarTheme.h"
131 #include "Settings.h"
132 #include "SkiaUtils.h"
133 #include "SubstituteData.h"
134 #include "TextAffinity.h"
135 #include "TextIterator.h"
136 #include "UserGestureIndicator.h"
137 #include "WebAnimationControllerImpl.h"
138 #include "WebConsoleMessage.h"
139 #include "WebDataSourceImpl.h"
140 #include "WebDocument.h"
141 #include "WebFindOptions.h"
142 #include "WebFormElement.h"
143 #include "WebFrameClient.h"
144 #include "WebHistoryItem.h"
145 #include "WebIconURL.h"
146 #include "WebInputElement.h"
147 #include "WebNode.h"
148 #include "WebPerformance.h"
149 #include "WebPlugin.h"
150 #include "WebPluginContainerImpl.h"
151 #include "WebPoint.h"
152 #include "WebRange.h"
153 #include "WebRect.h"
154 #include "WebScriptSource.h"
155 #include "WebSecurityOrigin.h"
156 #include "WebSize.h"
157 #include "WebURLError.h"
158 #include "WebVector.h"
159 #include "WebViewImpl.h"
160 #include "XPathResult.h"
161 #include "markup.h"
162
163 #include <algorithm>
164 #include <wtf/CurrentTime.h>
165
166 #if OS(UNIX) && !OS(DARWIN) && !OS(ANDROID)
167 #include <gdk/gdk.h>
168 #endif
169
170 #if USE(V8)
171 #include "AsyncFileSystem.h"
172 #include "AsyncFileSystemChromium.h"
173 #include "DirectoryEntry.h"
174 #include "DOMFileSystem.h"
175 #include "FileEntry.h"
176 #include "V8DirectoryEntry.h"
177 #include "V8DOMFileSystem.h"
178 #include "V8FileEntry.h"
179 #include "WebFileSystem.h"
180 #endif
181
182 using namespace WebCore;
183
184 namespace WebKit {
185
186 static int frameCount = 0;
187
188 // Key for a StatsCounter tracking how many WebFrames are active.
189 static const char* const webFrameActiveCount = "WebFrameActiveCount";
190
191 // Backend for contentAsPlainText, this is a recursive function that gets
192 // the text for the current frame and all of its subframes. It will append
193 // the text of each frame in turn to the |output| up to |maxChars| length.
194 //
195 // The |frame| must be non-null.
196 static void frameContentAsPlainText(size_t maxChars, Frame* frame,
197                                     Vector<UChar>* output)
198 {
199     Document* doc = frame->document();
200     if (!doc)
201         return;
202
203     if (!frame->view())
204         return;
205
206     // TextIterator iterates over the visual representation of the DOM. As such,
207     // it requires you to do a layout before using it (otherwise it'll crash).
208     if (frame->view()->needsLayout())
209         frame->view()->layout();
210
211     // Select the document body.
212     RefPtr<Range> range(doc->createRange());
213     ExceptionCode exception = 0;
214     range->selectNodeContents(doc->body(), exception);
215
216     if (!exception) {
217         // The text iterator will walk nodes giving us text. This is similar to
218         // the plainText() function in TextIterator.h, but we implement the maximum
219         // size and also copy the results directly into a wstring, avoiding the
220         // string conversion.
221         for (TextIterator it(range.get()); !it.atEnd(); it.advance()) {
222             const UChar* chars = it.characters();
223             if (!chars) {
224                 if (it.length()) {
225                     // It appears from crash reports that an iterator can get into a state
226                     // where the character count is nonempty but the character pointer is
227                     // null. advance()ing it will then just add that many to the null
228                     // pointer which won't be caught in a null check but will crash.
229                     //
230                     // A null pointer and 0 length is common for some nodes.
231                     //
232                     // IF YOU CATCH THIS IN A DEBUGGER please let brettw know. We don't
233                     // currently understand the conditions for this to occur. Ideally, the
234                     // iterators would never get into the condition so we should fix them
235                     // if we can.
236                     ASSERT_NOT_REACHED();
237                     break;
238                 }
239
240                 // Just got a null node, we can forge ahead!
241                 continue;
242             }
243             size_t toAppend =
244                 std::min(static_cast<size_t>(it.length()), maxChars - output->size());
245             output->append(chars, toAppend);
246             if (output->size() >= maxChars)
247                 return; // Filled up the buffer.
248         }
249     }
250
251     // The separator between frames when the frames are converted to plain text.
252     const UChar frameSeparator[] = { '\n', '\n' };
253     const size_t frameSeparatorLen = 2;
254
255     // Recursively walk the children.
256     FrameTree* frameTree = frame->tree();
257     for (Frame* curChild = frameTree->firstChild(); curChild; curChild = curChild->tree()->nextSibling()) {
258         // Ignore the text of non-visible frames.
259         RenderView* contentRenderer = curChild->contentRenderer();
260         RenderPart* ownerRenderer = curChild->ownerRenderer();
261         if (!contentRenderer || !contentRenderer->width() || !contentRenderer->height()
262             || (contentRenderer->x() + contentRenderer->width() <= 0) || (contentRenderer->y() + contentRenderer->height() <= 0)
263             || (ownerRenderer && ownerRenderer->style() && ownerRenderer->style()->visibility() != VISIBLE)) {
264             continue;
265         }
266
267         // Make sure the frame separator won't fill up the buffer, and give up if
268         // it will. The danger is if the separator will make the buffer longer than
269         // maxChars. This will cause the computation above:
270         //   maxChars - output->size()
271         // to be a negative number which will crash when the subframe is added.
272         if (output->size() >= maxChars - frameSeparatorLen)
273             return;
274
275         output->append(frameSeparator, frameSeparatorLen);
276         frameContentAsPlainText(maxChars, curChild, output);
277         if (output->size() >= maxChars)
278             return; // Filled up the buffer.
279     }
280 }
281
282 static long long generateFrameIdentifier()
283 {
284     static long long next = 0;
285     return ++next;
286 }
287
288 static WebPluginContainerImpl* pluginContainerFromNode(const WebNode& node)
289 {
290     if (node.isNull())
291         return 0;
292
293     const Node* coreNode = node.constUnwrap<Node>();
294     if (coreNode->hasTagName(HTMLNames::objectTag) || coreNode->hasTagName(HTMLNames::embedTag)) {
295         RenderObject* object = coreNode->renderer();
296         if (object && object->isWidget()) {
297             Widget* widget = toRenderWidget(object)->widget();
298             if (widget && widget->isPluginContainer())
299                 return static_cast<WebPluginContainerImpl*>(widget);
300         }
301     }
302     return 0;
303 }
304
305 WebPluginContainerImpl* WebFrameImpl::pluginContainerFromFrame(Frame* frame)
306 {
307     if (!frame)
308         return 0;
309     if (!frame->document() || !frame->document()->isPluginDocument())
310         return 0;
311     PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
312     return static_cast<WebPluginContainerImpl *>(pluginDocument->pluginWidget());
313 }
314
315 // Simple class to override some of PrintContext behavior. Some of the methods
316 // made virtual so that they can be overridden by ChromePluginPrintContext.
317 class ChromePrintContext : public PrintContext {
318     WTF_MAKE_NONCOPYABLE(ChromePrintContext);
319 public:
320     ChromePrintContext(Frame* frame)
321         : PrintContext(frame)
322         , m_printedPageWidth(0)
323     {
324     }
325
326     virtual ~ChromePrintContext() { }
327
328     virtual void begin(float width, float height)
329     {
330         ASSERT(!m_printedPageWidth);
331         m_printedPageWidth = width;
332         PrintContext::begin(m_printedPageWidth, height);
333     }
334
335     virtual void end()
336     {
337         PrintContext::end();
338     }
339
340     virtual float getPageShrink(int pageNumber) const
341     {
342         IntRect pageRect = m_pageRects[pageNumber];
343         return m_printedPageWidth / pageRect.width();
344     }
345
346     // Spools the printed page, a subrect of m_frame. Skip the scale step.
347     // NativeTheme doesn't play well with scaling. Scaling is done browser side
348     // instead. Returns the scale to be applied.
349     // On Linux, we don't have the problem with NativeTheme, hence we let WebKit
350     // do the scaling and ignore the return value.
351     virtual float spoolPage(GraphicsContext& ctx, int pageNumber)
352     {
353         IntRect pageRect = m_pageRects[pageNumber];
354         float scale = m_printedPageWidth / pageRect.width();
355
356         ctx.save();
357 #if OS(UNIX) && !OS(DARWIN)
358         ctx.scale(WebCore::FloatSize(scale, scale));
359 #endif
360         ctx.translate(static_cast<float>(-pageRect.x()),
361                       static_cast<float>(-pageRect.y()));
362         ctx.clip(pageRect);
363         m_frame->view()->paintContents(&ctx, pageRect);
364         ctx.restore();
365         return scale;
366     }
367
368     virtual void computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight)
369     {
370         return PrintContext::computePageRects(printRect, headerHeight, footerHeight, userScaleFactor, outPageHeight);
371     }
372
373     virtual int pageCount() const
374     {
375         return PrintContext::pageCount();
376     }
377
378     virtual bool shouldUseBrowserOverlays() const
379     {
380         return true;
381     }
382
383 private:
384     // Set when printing.
385     float m_printedPageWidth;
386 };
387
388 // Simple class to override some of PrintContext behavior. This is used when
389 // the frame hosts a plugin that supports custom printing. In this case, we
390 // want to delegate all printing related calls to the plugin.
391 class ChromePluginPrintContext : public ChromePrintContext {
392 public:
393     ChromePluginPrintContext(Frame* frame, WebPluginContainerImpl* plugin, int printerDPI)
394         : ChromePrintContext(frame), m_plugin(plugin), m_pageCount(0), m_printerDPI(printerDPI)
395     {
396     }
397
398     virtual ~ChromePluginPrintContext() { }
399
400     virtual void begin(float width, float height)
401     {
402     }
403
404     virtual void end()
405     {
406         m_plugin->printEnd();
407     }
408
409     virtual float getPageShrink(int pageNumber) const
410     {
411         // We don't shrink the page (maybe we should ask the widget ??)
412         return 1.0;
413     }
414
415     virtual void computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight)
416     {
417         m_pageCount = m_plugin->printBegin(IntRect(printRect), m_printerDPI);
418     }
419
420     virtual int pageCount() const
421     {
422         return m_pageCount;
423     }
424
425     // Spools the printed page, a subrect of m_frame.  Skip the scale step.
426     // NativeTheme doesn't play well with scaling. Scaling is done browser side
427     // instead.  Returns the scale to be applied.
428     virtual float spoolPage(GraphicsContext& ctx, int pageNumber)
429     {
430         m_plugin->printPage(pageNumber, &ctx);
431         return 1.0;
432     }
433
434     virtual bool shouldUseBrowserOverlays() const
435     {
436         return false;
437     }
438
439 private:
440     // Set when printing.
441     WebPluginContainerImpl* m_plugin;
442     int m_pageCount;
443     int m_printerDPI;
444 };
445
446 static WebDataSource* DataSourceForDocLoader(DocumentLoader* loader)
447 {
448     return loader ? WebDataSourceImpl::fromDocumentLoader(loader) : 0;
449 }
450
451
452 // WebFrame -------------------------------------------------------------------
453
454 class WebFrameImpl::DeferredScopeStringMatches {
455 public:
456     DeferredScopeStringMatches(WebFrameImpl* webFrame,
457                                int identifier,
458                                const WebString& searchText,
459                                const WebFindOptions& options,
460                                bool reset)
461         : m_timer(this, &DeferredScopeStringMatches::doTimeout)
462         , m_webFrame(webFrame)
463         , m_identifier(identifier)
464         , m_searchText(searchText)
465         , m_options(options)
466         , m_reset(reset)
467     {
468         m_timer.startOneShot(0.0);
469     }
470
471 private:
472     void doTimeout(Timer<DeferredScopeStringMatches>*)
473     {
474         m_webFrame->callScopeStringMatches(
475             this, m_identifier, m_searchText, m_options, m_reset);
476     }
477
478     Timer<DeferredScopeStringMatches> m_timer;
479     RefPtr<WebFrameImpl> m_webFrame;
480     int m_identifier;
481     WebString m_searchText;
482     WebFindOptions m_options;
483     bool m_reset;
484 };
485
486
487 // WebFrame -------------------------------------------------------------------
488
489 int WebFrame::instanceCount()
490 {
491     return frameCount;
492 }
493
494 WebFrame* WebFrame::frameForEnteredContext()
495 {
496     Frame* frame =
497         ScriptController::retrieveFrameForEnteredContext();
498     return WebFrameImpl::fromFrame(frame);
499 }
500
501 WebFrame* WebFrame::frameForCurrentContext()
502 {
503     Frame* frame =
504         ScriptController::retrieveFrameForCurrentContext();
505     return WebFrameImpl::fromFrame(frame);
506 }
507
508 #if WEBKIT_USING_V8
509 WebFrame* WebFrame::frameForContext(v8::Handle<v8::Context> context)
510 {
511     return WebFrameImpl::fromFrame(V8Proxy::retrieveFrame(context));
512 }
513 #endif
514
515 WebFrame* WebFrame::fromFrameOwnerElement(const WebElement& element)
516 {
517     return WebFrameImpl::fromFrameOwnerElement(
518         PassRefPtr<Element>(element).get());
519 }
520
521 WebString WebFrameImpl::name() const
522 {
523     return m_frame->tree()->uniqueName();
524 }
525
526 void WebFrameImpl::setName(const WebString& name)
527 {
528     m_frame->tree()->setName(name);
529 }
530
531 long long WebFrameImpl::identifier() const
532 {
533     return m_identifier;
534 }
535
536 WebVector<WebIconURL> WebFrameImpl::iconURLs(int iconTypes) const
537 {
538     FrameLoader* frameLoader = m_frame->loader();
539     // The URL to the icon may be in the header. As such, only
540     // ask the loader for the icon if it's finished loading.
541     if (frameLoader->state() == FrameStateComplete)
542         return frameLoader->icon()->urlsForTypes(iconTypes);
543     return WebVector<WebIconURL>();
544 }
545
546 WebSize WebFrameImpl::scrollOffset() const
547 {
548     FrameView* view = frameView();
549     if (view)
550         return view->scrollOffset();
551
552     return WebSize();
553 }
554
555 WebSize WebFrameImpl::minimumScrollOffset() const
556 {
557     FrameView* view = frameView();
558     if (view)
559         return view->minimumScrollPosition() - IntPoint();
560
561     return WebSize();
562 }
563
564 WebSize WebFrameImpl::maximumScrollOffset() const
565 {
566     FrameView* view = frameView();
567     if (view)
568         return view->maximumScrollPosition() - IntPoint();
569
570     return WebSize();
571 }
572
573 void WebFrameImpl::setScrollOffset(const WebSize& offset)
574 {
575     if (FrameView* view = frameView())
576         view->setScrollOffset(IntPoint(offset.width, offset.height));
577 }
578
579 WebSize WebFrameImpl::contentsSize() const
580 {
581     return frame()->view()->contentsSize();
582 }
583
584 int WebFrameImpl::contentsPreferredWidth() const
585 {
586     if (m_frame->document() && m_frame->document()->renderView())
587         return m_frame->document()->renderView()->minPreferredLogicalWidth();
588     return 0;
589 }
590
591 int WebFrameImpl::documentElementScrollHeight() const
592 {
593     if (m_frame->document() && m_frame->document()->documentElement())
594         return m_frame->document()->documentElement()->scrollHeight();
595     return 0;
596 }
597
598 bool WebFrameImpl::hasVisibleContent() const
599 {
600     return frame()->view()->visibleWidth() > 0 && frame()->view()->visibleHeight() > 0;
601 }
602
603 bool WebFrameImpl::hasHorizontalScrollbar() const
604 {
605     return m_frame && m_frame->view() && m_frame->view()->horizontalScrollbar();
606 }
607
608 bool WebFrameImpl::hasVerticalScrollbar() const
609 {
610     return m_frame && m_frame->view() && m_frame->view()->verticalScrollbar();
611 }
612
613 WebView* WebFrameImpl::view() const
614 {
615     return viewImpl();
616 }
617
618 void WebFrameImpl::clearOpener()
619 {
620     m_frame->loader()->setOpener(0);
621 }
622
623 WebFrame* WebFrameImpl::opener() const
624 {
625     Frame* opener = 0;
626     if (m_frame)
627         opener = m_frame->loader()->opener();
628     return fromFrame(opener);
629 }
630
631 WebFrame* WebFrameImpl::parent() const
632 {
633     Frame* parent = 0;
634     if (m_frame)
635         parent = m_frame->tree()->parent();
636     return fromFrame(parent);
637 }
638
639 WebFrame* WebFrameImpl::top() const
640 {
641     if (m_frame)
642         return fromFrame(m_frame->tree()->top());
643
644     return 0;
645 }
646
647 WebFrame* WebFrameImpl::firstChild() const
648 {
649     return fromFrame(frame()->tree()->firstChild());
650 }
651
652 WebFrame* WebFrameImpl::lastChild() const
653 {
654     return fromFrame(frame()->tree()->lastChild());
655 }
656
657 WebFrame* WebFrameImpl::nextSibling() const
658 {
659     return fromFrame(frame()->tree()->nextSibling());
660 }
661
662 WebFrame* WebFrameImpl::previousSibling() const
663 {
664     return fromFrame(frame()->tree()->previousSibling());
665 }
666
667 WebFrame* WebFrameImpl::traverseNext(bool wrap) const
668 {
669     return fromFrame(frame()->tree()->traverseNextWithWrap(wrap));
670 }
671
672 WebFrame* WebFrameImpl::traversePrevious(bool wrap) const
673 {
674     return fromFrame(frame()->tree()->traversePreviousWithWrap(wrap));
675 }
676
677 WebFrame* WebFrameImpl::findChildByName(const WebString& name) const
678 {
679     return fromFrame(frame()->tree()->child(name));
680 }
681
682 WebFrame* WebFrameImpl::findChildByExpression(const WebString& xpath) const
683 {
684     if (xpath.isEmpty())
685         return 0;
686
687     Document* document = m_frame->document();
688
689     ExceptionCode ec = 0;
690     PassRefPtr<XPathResult> xpathResult =
691         document->evaluate(xpath,
692         document,
693         0, // namespace
694         XPathResult::ORDERED_NODE_ITERATOR_TYPE,
695         0, // XPathResult object
696         ec);
697     if (!xpathResult.get())
698         return 0;
699
700     Node* node = xpathResult->iterateNext(ec);
701
702     if (!node || !node->isFrameOwnerElement())
703         return 0;
704     HTMLFrameOwnerElement* frameElement =
705         static_cast<HTMLFrameOwnerElement*>(node);
706     return fromFrame(frameElement->contentFrame());
707 }
708
709 WebDocument WebFrameImpl::document() const
710 {
711     if (!m_frame || !m_frame->document())
712         return WebDocument();
713     return WebDocument(m_frame->document());
714 }
715
716 WebAnimationController* WebFrameImpl::animationController()
717 {
718     return &m_animationController;
719 }
720
721 WebPerformance WebFrameImpl::performance() const
722 {
723     if (!m_frame || !m_frame->domWindow())
724         return WebPerformance();
725
726     return WebPerformance(m_frame->domWindow()->performance());
727 }
728
729 NPObject* WebFrameImpl::windowObject() const
730 {
731     if (!m_frame)
732         return 0;
733
734     return m_frame->script()->windowScriptNPObject();
735 }
736
737 void WebFrameImpl::bindToWindowObject(const WebString& name, NPObject* object)
738 {
739     ASSERT(m_frame);
740     if (!m_frame || !m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
741         return;
742
743     String key = name;
744 #if USE(V8)
745     m_frame->script()->bindToWindowObject(m_frame, key, object);
746 #else
747     notImplemented();
748 #endif
749 }
750
751 void WebFrameImpl::executeScript(const WebScriptSource& source)
752 {
753     TextPosition1 position(WTF::OneBasedNumber::fromOneBasedInt(source.startLine), WTF::OneBasedNumber::base());
754     m_frame->script()->executeScript(
755         ScriptSourceCode(source.code, source.url, position));
756 }
757
758 void WebFrameImpl::executeScriptInIsolatedWorld(
759     int worldID, const WebScriptSource* sourcesIn, unsigned numSources,
760     int extensionGroup)
761 {
762     Vector<ScriptSourceCode> sources;
763
764     for (unsigned i = 0; i < numSources; ++i) {
765         TextPosition1 position(WTF::OneBasedNumber::fromOneBasedInt(sourcesIn[i].startLine), WTF::OneBasedNumber::base());
766         sources.append(ScriptSourceCode(
767             sourcesIn[i].code, sourcesIn[i].url, position));
768     }
769
770     m_frame->script()->evaluateInIsolatedWorld(worldID, sources, extensionGroup);
771 }
772
773 void WebFrameImpl::setIsolatedWorldSecurityOrigin(int worldID, const WebSecurityOrigin& securityOrigin)
774 {
775     m_frame->script()->setIsolatedWorldSecurityOrigin(worldID, securityOrigin.get());
776 }
777
778 void WebFrameImpl::addMessageToConsole(const WebConsoleMessage& message)
779 {
780     ASSERT(frame());
781
782     MessageLevel webCoreMessageLevel;
783     switch (message.level) {
784     case WebConsoleMessage::LevelTip:
785         webCoreMessageLevel = TipMessageLevel;
786         break;
787     case WebConsoleMessage::LevelLog:
788         webCoreMessageLevel = LogMessageLevel;
789         break;
790     case WebConsoleMessage::LevelWarning:
791         webCoreMessageLevel = WarningMessageLevel;
792         break;
793     case WebConsoleMessage::LevelError:
794         webCoreMessageLevel = ErrorMessageLevel;
795         break;
796     default:
797         ASSERT_NOT_REACHED();
798         return;
799     }
800
801     frame()->domWindow()->console()->addMessage(
802         OtherMessageSource, LogMessageType, webCoreMessageLevel, message.text,
803         1, String());
804 }
805
806 void WebFrameImpl::collectGarbage()
807 {
808     if (!m_frame)
809         return;
810     if (!m_frame->settings()->isJavaScriptEnabled())
811         return;
812     // FIXME: Move this to the ScriptController and make it JS neutral.
813 #if USE(V8)
814     m_frame->script()->collectGarbage();
815 #else
816     notImplemented();
817 #endif
818 }
819
820 bool WebFrameImpl::checkIfRunInsecureContent(const WebURL& url) const
821 {
822     FrameLoader* frameLoader = m_frame->loader();
823     return frameLoader->checkIfRunInsecureContent(m_frame->document()->securityOrigin(), url);
824 }
825
826 #if USE(V8)
827 v8::Handle<v8::Value> WebFrameImpl::executeScriptAndReturnValue(const WebScriptSource& source)
828 {
829     // FIXME: This fake user gesture is required to make a bunch of pyauto
830     // tests pass. If this isn't needed in non-test situations, we should
831     // consider removing this code and changing the tests.
832     // http://code.google.com/p/chromium/issues/detail?id=86397
833     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
834
835     TextPosition1 position(WTF::OneBasedNumber::fromOneBasedInt(source.startLine), WTF::OneBasedNumber::base());
836     return m_frame->script()->executeScript(ScriptSourceCode(source.code, source.url, position)).v8Value();
837 }
838
839 // Returns the V8 context for this frame, or an empty handle if there is none.
840 v8::Local<v8::Context> WebFrameImpl::mainWorldScriptContext() const
841 {
842     if (!m_frame)
843         return v8::Local<v8::Context>();
844
845     return V8Proxy::mainWorldContext(m_frame);
846 }
847
848 v8::Handle<v8::Value> WebFrameImpl::createFileSystem(WebFileSystem::Type type,
849                                                      const WebString& name,
850                                                      const WebString& path)
851 {
852     return toV8(DOMFileSystem::create(frame()->document(), name, AsyncFileSystemChromium::create(static_cast<AsyncFileSystem::Type>(type), KURL(ParsedURLString, path.utf8().data()))));
853 }
854
855 v8::Handle<v8::Value> WebFrameImpl::createFileEntry(WebFileSystem::Type type,
856                                                     const WebString& fileSystemName,
857                                                     const WebString& fileSystemPath,
858                                                     const WebString& filePath,
859                                                     bool isDirectory)
860 {
861     RefPtr<DOMFileSystemBase> fileSystem = DOMFileSystem::create(frame()->document(), fileSystemName, AsyncFileSystemChromium::create(static_cast<AsyncFileSystem::Type>(type), KURL(ParsedURLString, fileSystemPath.utf8().data())));
862     if (isDirectory)
863         return toV8(DirectoryEntry::create(fileSystem, filePath));
864     return toV8(FileEntry::create(fileSystem, filePath));
865 }
866 #endif
867
868 void WebFrameImpl::reload(bool ignoreCache)
869 {
870     m_frame->loader()->history()->saveDocumentAndScrollState();
871     m_frame->loader()->reload(ignoreCache);
872 }
873
874 void WebFrameImpl::loadRequest(const WebURLRequest& request)
875 {
876     ASSERT(!request.isNull());
877     const ResourceRequest& resourceRequest = request.toResourceRequest();
878
879     if (resourceRequest.url().protocolIs("javascript")) {
880         loadJavaScriptURL(resourceRequest.url());
881         return;
882     }
883
884     m_frame->loader()->load(resourceRequest, false);
885 }
886
887 void WebFrameImpl::loadHistoryItem(const WebHistoryItem& item)
888 {
889     RefPtr<HistoryItem> historyItem = PassRefPtr<HistoryItem>(item);
890     ASSERT(historyItem.get());
891
892     m_frame->loader()->prepareForHistoryNavigation();
893     RefPtr<HistoryItem> currentItem = m_frame->loader()->history()->currentItem();
894     m_inSameDocumentHistoryLoad = currentItem->shouldDoSameDocumentNavigationTo(historyItem.get());
895     m_frame->page()->goToItem(historyItem.get(),
896                               FrameLoadTypeIndexedBackForward);
897     m_inSameDocumentHistoryLoad = false;
898 }
899
900 void WebFrameImpl::loadData(const WebData& data,
901                             const WebString& mimeType,
902                             const WebString& textEncoding,
903                             const WebURL& baseURL,
904                             const WebURL& unreachableURL,
905                             bool replace)
906 {
907     SubstituteData substData(data, mimeType, textEncoding, unreachableURL);
908     ASSERT(substData.isValid());
909
910     // If we are loading substitute data to replace an existing load, then
911     // inherit all of the properties of that original request.  This way,
912     // reload will re-attempt the original request.  It is essential that
913     // we only do this when there is an unreachableURL since a non-empty
914     // unreachableURL informs FrameLoader::reload to load unreachableURL
915     // instead of the currently loaded URL.
916     ResourceRequest request;
917     if (replace && !unreachableURL.isEmpty())
918         request = m_frame->loader()->originalRequest();
919     request.setURL(baseURL);
920
921     m_frame->loader()->load(request, substData, false);
922     if (replace) {
923         // Do this to force WebKit to treat the load as replacing the currently
924         // loaded page.
925         m_frame->loader()->setReplacing();
926     }
927 }
928
929 void WebFrameImpl::loadHTMLString(const WebData& data,
930                                   const WebURL& baseURL,
931                                   const WebURL& unreachableURL,
932                                   bool replace)
933 {
934     loadData(data,
935              WebString::fromUTF8("text/html"),
936              WebString::fromUTF8("UTF-8"),
937              baseURL,
938              unreachableURL,
939              replace);
940 }
941
942 bool WebFrameImpl::isLoading() const
943 {
944     if (!m_frame)
945         return false;
946     return m_frame->loader()->isLoading();
947 }
948
949 void WebFrameImpl::stopLoading()
950 {
951     if (!m_frame)
952       return;
953
954     // FIXME: Figure out what we should really do here.  It seems like a bug
955     // that FrameLoader::stopLoading doesn't call stopAllLoaders.
956     m_frame->loader()->stopAllLoaders();
957     m_frame->loader()->stopLoading(UnloadEventPolicyNone);
958 }
959
960 WebDataSource* WebFrameImpl::provisionalDataSource() const
961 {
962     FrameLoader* frameLoader = m_frame->loader();
963
964     // We regard the policy document loader as still provisional.
965     DocumentLoader* docLoader = frameLoader->provisionalDocumentLoader();
966     if (!docLoader)
967         docLoader = frameLoader->policyDocumentLoader();
968
969     return DataSourceForDocLoader(docLoader);
970 }
971
972 WebDataSource* WebFrameImpl::dataSource() const
973 {
974     return DataSourceForDocLoader(m_frame->loader()->documentLoader());
975 }
976
977 WebHistoryItem WebFrameImpl::previousHistoryItem() const
978 {
979     // We use the previous item here because documentState (filled-out forms)
980     // only get saved to history when it becomes the previous item.  The caller
981     // is expected to query the history item after a navigation occurs, after
982     // the desired history item has become the previous entry.
983     return WebHistoryItem(m_frame->loader()->history()->previousItem());
984 }
985
986 WebHistoryItem WebFrameImpl::currentHistoryItem() const
987 {
988     // We're shutting down.
989     if (!m_frame->loader()->activeDocumentLoader())
990         return WebHistoryItem();
991
992     // If we are still loading, then we don't want to clobber the current
993     // history item as this could cause us to lose the scroll position and
994     // document state.  However, it is OK for new navigations.
995     // FIXME: Can we make this a plain old getter, instead of worrying about
996     // clobbering here?
997     if (!m_inSameDocumentHistoryLoad && (m_frame->loader()->loadType() == FrameLoadTypeStandard
998         || !m_frame->loader()->activeDocumentLoader()->isLoadingInAPISense()))
999         m_frame->loader()->history()->saveDocumentAndScrollState();
1000
1001     return WebHistoryItem(m_frame->page()->backForward()->currentItem());
1002 }
1003
1004 void WebFrameImpl::enableViewSourceMode(bool enable)
1005 {
1006     if (m_frame)
1007         m_frame->setInViewSourceMode(enable);
1008 }
1009
1010 bool WebFrameImpl::isViewSourceModeEnabled() const
1011 {
1012     if (m_frame)
1013         return m_frame->inViewSourceMode();
1014
1015     return false;
1016 }
1017
1018 void WebFrameImpl::setReferrerForRequest(
1019     WebURLRequest& request, const WebURL& referrerURL) {
1020     String referrer;
1021     if (referrerURL.isEmpty())
1022         referrer = m_frame->loader()->outgoingReferrer();
1023     else
1024         referrer = referrerURL.spec().utf16();
1025     if (SecurityOrigin::shouldHideReferrer(request.url(), referrer))
1026         return;
1027     request.setHTTPHeaderField(WebString::fromUTF8("Referer"), referrer);
1028 }
1029
1030 void WebFrameImpl::dispatchWillSendRequest(WebURLRequest& request)
1031 {
1032     ResourceResponse response;
1033     m_frame->loader()->client()->dispatchWillSendRequest(
1034         0, 0, request.toMutableResourceRequest(), response);
1035 }
1036
1037 WebURLLoader* WebFrameImpl::createAssociatedURLLoader(const WebURLLoaderOptions& options)
1038 {
1039     return new AssociatedURLLoader(this, options);
1040 }
1041
1042 void WebFrameImpl::commitDocumentData(const char* data, size_t length)
1043 {
1044     m_frame->loader()->documentLoader()->commitData(data, length);
1045 }
1046
1047 unsigned WebFrameImpl::unloadListenerCount() const
1048 {
1049     return frame()->domWindow()->pendingUnloadEventListeners();
1050 }
1051
1052 bool WebFrameImpl::isProcessingUserGesture() const
1053 {
1054     return ScriptController::processingUserGesture();
1055 }
1056
1057 bool WebFrameImpl::willSuppressOpenerInNewFrame() const
1058 {
1059     return frame()->loader()->suppressOpenerInNewFrame();
1060 }
1061
1062 void WebFrameImpl::replaceSelection(const WebString& text)
1063 {
1064     RefPtr<DocumentFragment> fragment = createFragmentFromText(
1065         frame()->selection()->toNormalizedRange().get(), text);
1066     applyCommand(ReplaceSelectionCommand::create(
1067         frame()->document(), fragment.get(), ReplaceSelectionCommand::SmartReplace | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
1068 }
1069
1070 void WebFrameImpl::insertText(const WebString& text)
1071 {
1072     Editor* editor = frame()->editor();
1073
1074     if (editor->hasComposition())
1075         editor->confirmComposition(text);
1076     else
1077         editor->insertText(text, 0);
1078 }
1079
1080 void WebFrameImpl::setMarkedText(
1081     const WebString& text, unsigned location, unsigned length)
1082 {
1083     Editor* editor = frame()->editor();
1084
1085     Vector<CompositionUnderline> decorations;
1086     editor->setComposition(text, decorations, location, length);
1087 }
1088
1089 void WebFrameImpl::unmarkText()
1090 {
1091     frame()->editor()->cancelComposition();
1092 }
1093
1094 bool WebFrameImpl::hasMarkedText() const
1095 {
1096     return frame()->editor()->hasComposition();
1097 }
1098
1099 WebRange WebFrameImpl::markedRange() const
1100 {
1101     return frame()->editor()->compositionRange();
1102 }
1103
1104 bool WebFrameImpl::firstRectForCharacterRange(unsigned location, unsigned length, WebRect& rect) const
1105 {
1106     if ((location + length < location) && (location + length))
1107         length = 0;
1108
1109     Element* selectionRoot = frame()->selection()->rootEditableElement();
1110     Element* scope = selectionRoot ? selectionRoot : frame()->document()->documentElement();
1111     RefPtr<Range> range = TextIterator::rangeFromLocationAndLength(scope, location, length);
1112     if (!range)
1113         return false;
1114     IntRect intRect = frame()->editor()->firstRectForRange(range.get());
1115     rect = WebRect(intRect);
1116     rect = frame()->view()->contentsToWindow(rect);
1117
1118     return true;
1119 }
1120
1121 size_t WebFrameImpl::characterIndexForPoint(const WebPoint& webPoint) const
1122 {
1123     if (!frame())
1124         return notFound;
1125
1126     IntPoint point = frame()->view()->windowToContents(webPoint);
1127     HitTestResult result = frame()->eventHandler()->hitTestResultAtPoint(point, false);
1128     RefPtr<Range> range = frame()->rangeForPoint(result.point());
1129     if (!range.get())
1130         return notFound;
1131
1132     size_t location, length;
1133     TextIterator::locationAndLengthFromRange(range.get(), location, length);
1134     return location;
1135 }
1136
1137 bool WebFrameImpl::executeCommand(const WebString& name, const WebNode& node)
1138 {
1139     ASSERT(frame());
1140
1141     if (name.length() <= 2)
1142         return false;
1143
1144     // Since we don't have NSControl, we will convert the format of command
1145     // string and call the function on Editor directly.
1146     String command = name;
1147
1148     // Make sure the first letter is upper case.
1149     command.replace(0, 1, command.substring(0, 1).upper());
1150
1151     // Remove the trailing ':' if existing.
1152     if (command[command.length() - 1] == UChar(':'))
1153         command = command.substring(0, command.length() - 1);
1154
1155     if (command == "Copy") {
1156         WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1157         if (!pluginContainer)
1158             pluginContainer = pluginContainerFromNode(node);
1159         if (pluginContainer) {
1160             pluginContainer->copy();
1161             return true;
1162         }
1163     }
1164
1165     bool rv = true;
1166
1167     // Specially handling commands that Editor::execCommand does not directly
1168     // support.
1169     if (command == "DeleteToEndOfParagraph") {
1170         Editor* editor = frame()->editor();
1171         if (!editor->deleteWithDirection(DirectionForward,
1172                                          ParagraphBoundary,
1173                                          true,
1174                                          false)) {
1175             editor->deleteWithDirection(DirectionForward,
1176                                         CharacterGranularity,
1177                                         true,
1178                                         false);
1179         }
1180     } else if (command == "Indent")
1181         frame()->editor()->indent();
1182     else if (command == "Outdent")
1183         frame()->editor()->outdent();
1184     else if (command == "DeleteBackward")
1185         rv = frame()->editor()->command(AtomicString("BackwardDelete")).execute();
1186     else if (command == "DeleteForward")
1187         rv = frame()->editor()->command(AtomicString("ForwardDelete")).execute();
1188     else if (command == "AdvanceToNextMisspelling") {
1189         // False must be passed here, or the currently selected word will never be
1190         // skipped.
1191         frame()->editor()->advanceToNextMisspelling(false);
1192     } else if (command == "ToggleSpellPanel")
1193         frame()->editor()->showSpellingGuessPanel();
1194     else
1195         rv = frame()->editor()->command(command).execute();
1196     return rv;
1197 }
1198
1199 bool WebFrameImpl::executeCommand(const WebString& name, const WebString& value)
1200 {
1201     ASSERT(frame());
1202     String webName = name;
1203
1204     // moveToBeginningOfDocument and moveToEndfDocument are only handled by WebKit
1205     // for editable nodes.
1206     if (!frame()->editor()->canEdit() && webName == "moveToBeginningOfDocument")
1207         return viewImpl()->propagateScroll(ScrollUp, ScrollByDocument);
1208
1209     if (!frame()->editor()->canEdit() && webName == "moveToEndOfDocument")
1210         return viewImpl()->propagateScroll(ScrollDown, ScrollByDocument);
1211
1212     return frame()->editor()->command(webName).execute(value);
1213 }
1214
1215 bool WebFrameImpl::isCommandEnabled(const WebString& name) const
1216 {
1217     ASSERT(frame());
1218     return frame()->editor()->command(name).isEnabled();
1219 }
1220
1221 void WebFrameImpl::enableContinuousSpellChecking(bool enable)
1222 {
1223     if (enable == isContinuousSpellCheckingEnabled())
1224         return;
1225     frame()->editor()->toggleContinuousSpellChecking();
1226 }
1227
1228 bool WebFrameImpl::isContinuousSpellCheckingEnabled() const
1229 {
1230     return frame()->editor()->isContinuousSpellCheckingEnabled();
1231 }
1232
1233 bool WebFrameImpl::hasSelection() const
1234 {
1235     WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1236     if (pluginContainer)
1237         return pluginContainer->plugin()->hasSelection();
1238
1239     // frame()->selection()->isNone() never returns true.
1240     return (frame()->selection()->start() != frame()->selection()->end());
1241 }
1242
1243 WebRange WebFrameImpl::selectionRange() const
1244 {
1245     return frame()->selection()->toNormalizedRange();
1246 }
1247
1248 WebString WebFrameImpl::selectionAsText() const
1249 {
1250     WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1251     if (pluginContainer)
1252         return pluginContainer->plugin()->selectionAsText();
1253
1254     RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1255     if (!range.get())
1256         return WebString();
1257
1258     String text = range->text();
1259 #if OS(WINDOWS)
1260     replaceNewlinesWithWindowsStyleNewlines(text);
1261 #endif
1262     replaceNBSPWithSpace(text);
1263     return text;
1264 }
1265
1266 WebString WebFrameImpl::selectionAsMarkup() const
1267 {
1268     WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1269     if (pluginContainer)
1270         return pluginContainer->plugin()->selectionAsMarkup();
1271
1272     RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1273     if (!range.get())
1274         return WebString();
1275
1276     return createMarkup(range.get(), 0);
1277 }
1278
1279 void WebFrameImpl::selectWordAroundPosition(Frame* frame, VisiblePosition pos)
1280 {
1281     VisibleSelection selection(pos);
1282     selection.expandUsingGranularity(WordGranularity);
1283
1284     if (frame->selection()->shouldChangeSelection(selection)) {
1285         TextGranularity granularity = selection.isRange() ? WordGranularity : CharacterGranularity;
1286         frame->selection()->setSelection(selection, granularity);
1287     }
1288 }
1289
1290 bool WebFrameImpl::selectWordAroundCaret()
1291 {
1292     FrameSelection* selection = frame()->selection();
1293     ASSERT(!selection->isNone());
1294     if (selection->isNone() || selection->isRange())
1295         return false;
1296     selectWordAroundPosition(frame(), selection->selection().visibleStart());
1297     return true;
1298 }
1299
1300 void WebFrameImpl::selectRange(const WebPoint& start, const WebPoint& end)
1301 {
1302     VisibleSelection selection(visiblePositionForWindowPoint(start),
1303                                visiblePositionForWindowPoint(end));
1304
1305     if (frame()->selection()->shouldChangeSelection(selection))
1306         frame()->selection()->setSelection(selection, CharacterGranularity);
1307 }
1308
1309 VisiblePosition WebFrameImpl::visiblePositionForWindowPoint(const WebPoint& point)
1310 {
1311     HitTestRequest::HitTestRequestType hitType = HitTestRequest::MouseMove;
1312     hitType |= HitTestRequest::ReadOnly;
1313     hitType |= HitTestRequest::Active;
1314     HitTestRequest request(hitType);
1315     FrameView* view = frame()->view();
1316     HitTestResult result(view->windowToContents(
1317         view->convertFromContainingWindow(IntPoint(point.x, point.y))));
1318
1319     frame()->document()->renderView()->layer()->hitTest(request, result);
1320
1321     // Matching the logic in MouseEventWithHitTestResults::targetNode()
1322     Node* node = result.innerNode();
1323     if (!node)
1324         return VisiblePosition();
1325     Element* element = node->parentElement();
1326     if (!node->inDocument() && element && element->inDocument())
1327         node = element;
1328
1329     return node->renderer()->positionForPoint(result.localPoint());
1330 }
1331
1332 int WebFrameImpl::printBegin(const WebSize& pageSize,
1333                              const WebNode& constrainToNode,
1334                              int printerDPI,
1335                              bool* useBrowserOverlays)
1336 {
1337     ASSERT(!frame()->document()->isFrameSet());
1338     WebPluginContainerImpl* pluginContainer = 0;
1339     if (constrainToNode.isNull()) {
1340         // If this is a plugin document, check if the plugin supports its own
1341         // printing. If it does, we will delegate all printing to that.
1342         pluginContainer = pluginContainerFromFrame(frame());
1343     } else {
1344         // We only support printing plugin nodes for now.
1345         pluginContainer = pluginContainerFromNode(constrainToNode);
1346     }
1347
1348     if (pluginContainer && pluginContainer->supportsPaginatedPrint())
1349         m_printContext = adoptPtr(new ChromePluginPrintContext(frame(), pluginContainer, printerDPI));
1350     else
1351         m_printContext = adoptPtr(new ChromePrintContext(frame()));
1352
1353     FloatRect rect(0, 0, static_cast<float>(pageSize.width),
1354                          static_cast<float>(pageSize.height));
1355     m_printContext->begin(rect.width(), rect.height());
1356     float pageHeight;
1357     // We ignore the overlays calculation for now since they are generated in the
1358     // browser. pageHeight is actually an output parameter.
1359     m_printContext->computePageRects(rect, 0, 0, 1.0, pageHeight);
1360     if (useBrowserOverlays)
1361         *useBrowserOverlays = m_printContext->shouldUseBrowserOverlays();
1362
1363     return m_printContext->pageCount();
1364 }
1365
1366 float WebFrameImpl::getPrintPageShrink(int page)
1367 {
1368     // Ensure correct state.
1369     if (!m_printContext.get() || page < 0) {
1370         ASSERT_NOT_REACHED();
1371         return 0;
1372     }
1373
1374     return m_printContext->getPageShrink(page);
1375 }
1376
1377 float WebFrameImpl::printPage(int page, WebCanvas* canvas)
1378 {
1379     // Ensure correct state.
1380     if (!m_printContext.get() || page < 0 || !frame() || !frame()->document()) {
1381         ASSERT_NOT_REACHED();
1382         return 0;
1383     }
1384
1385     GraphicsContextBuilder builder(canvas);
1386     GraphicsContext& gc = builder.context();
1387 #if WEBKIT_USING_SKIA
1388     gc.platformContext()->setPrinting(true);
1389 #endif
1390
1391     return m_printContext->spoolPage(gc, page);
1392 }
1393
1394 void WebFrameImpl::printEnd()
1395 {
1396     ASSERT(m_printContext.get());
1397     if (m_printContext.get())
1398         m_printContext->end();
1399     m_printContext.clear();
1400 }
1401
1402 bool WebFrameImpl::isPageBoxVisible(int pageIndex)
1403 {
1404     return frame()->document()->isPageBoxVisible(pageIndex);
1405 }
1406
1407 void WebFrameImpl::pageSizeAndMarginsInPixels(int pageIndex,
1408                                               WebSize& pageSize,
1409                                               int& marginTop,
1410                                               int& marginRight,
1411                                               int& marginBottom,
1412                                               int& marginLeft)
1413 {
1414     IntSize size(pageSize.width, pageSize.height);
1415     frame()->document()->pageSizeAndMarginsInPixels(pageIndex,
1416                                                     size,
1417                                                     marginTop,
1418                                                     marginRight,
1419                                                     marginBottom,
1420                                                     marginLeft);
1421     pageSize = size;
1422 }
1423
1424 bool WebFrameImpl::find(int identifier,
1425                         const WebString& searchText,
1426                         const WebFindOptions& options,
1427                         bool wrapWithinFrame,
1428                         WebRect* selectionRect)
1429 {
1430     WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
1431
1432     if (!options.findNext)
1433         frame()->page()->unmarkAllTextMatches();
1434     else
1435         setMarkerActive(m_activeMatch.get(), false); // Active match is changing.
1436
1437     // Starts the search from the current selection.
1438     bool startInSelection = true;
1439
1440     // If the user has selected something since the last Find operation we want
1441     // to start from there. Otherwise, we start searching from where the last Find
1442     // operation left off (either a Find or a FindNext operation).
1443     VisibleSelection selection(frame()->selection()->selection());
1444     bool activeSelection = !selection.isNone();
1445     if (!activeSelection && m_activeMatch) {
1446         selection = VisibleSelection(m_activeMatch.get());
1447         frame()->selection()->setSelection(selection);
1448     }
1449
1450     ASSERT(frame() && frame()->view());
1451     bool found = frame()->editor()->findString(
1452         searchText, options.forward, options.matchCase, wrapWithinFrame,
1453         startInSelection);
1454     if (found) {
1455         // Store which frame was active. This will come in handy later when we
1456         // change the active match ordinal below.
1457         WebFrameImpl* oldActiveFrame = mainFrameImpl->m_activeMatchFrame;
1458         // Set this frame as the active frame (the one with the active highlight).
1459         mainFrameImpl->m_activeMatchFrame = this;
1460
1461         // We found something, so we can now query the selection for its position.
1462         VisibleSelection newSelection(frame()->selection()->selection());
1463         IntRect currSelectionRect;
1464
1465         // If we thought we found something, but it couldn't be selected (perhaps
1466         // because it was marked -webkit-user-select: none), we can't set it to
1467         // be active but we still continue searching. This matches Safari's
1468         // behavior, including some oddities when selectable and un-selectable text
1469         // are mixed on a page: see https://bugs.webkit.org/show_bug.cgi?id=19127.
1470         if (newSelection.isNone() || (newSelection.start() == newSelection.end()))
1471             m_activeMatch = 0;
1472         else {
1473             m_activeMatch = newSelection.toNormalizedRange();
1474             currSelectionRect = m_activeMatch->boundingBox();
1475             setMarkerActive(m_activeMatch.get(), true); // Active.
1476             // WebKit draws the highlighting for all matches.
1477             executeCommand(WebString::fromUTF8("Unselect"));
1478         }
1479
1480         // Make sure no node is focused. See http://crbug.com/38700.
1481         frame()->document()->setFocusedNode(0);
1482
1483         if (!options.findNext || activeSelection) {
1484             // This is either a Find operation or a Find-next from a new start point
1485             // due to a selection, so we set the flag to ask the scoping effort
1486             // to find the active rect for us so we can update the ordinal (n of m).
1487             m_locatingActiveRect = true;
1488         } else {
1489             if (oldActiveFrame != this) {
1490                 // If the active frame has changed it means that we have a multi-frame
1491                 // page and we just switch to searching in a new frame. Then we just
1492                 // want to reset the index.
1493                 if (options.forward)
1494                     m_activeMatchIndex = 0;
1495                 else
1496                     m_activeMatchIndex = m_lastMatchCount - 1;
1497             } else {
1498                 // We are still the active frame, so increment (or decrement) the
1499                 // |m_activeMatchIndex|, wrapping if needed (on single frame pages).
1500                 options.forward ? ++m_activeMatchIndex : --m_activeMatchIndex;
1501                 if (m_activeMatchIndex + 1 > m_lastMatchCount)
1502                     m_activeMatchIndex = 0;
1503                 if (m_activeMatchIndex == -1)
1504                     m_activeMatchIndex = m_lastMatchCount - 1;
1505             }
1506             if (selectionRect) {
1507                 *selectionRect = frameView()->contentsToWindow(currSelectionRect);
1508                 reportFindInPageSelection(*selectionRect, m_activeMatchIndex + 1, identifier);
1509             }
1510         }
1511     } else {
1512         // Nothing was found in this frame.
1513         m_activeMatch = 0;
1514
1515         // Erase all previous tickmarks and highlighting.
1516         invalidateArea(InvalidateAll);
1517     }
1518
1519     return found;
1520 }
1521
1522 void WebFrameImpl::stopFinding(bool clearSelection)
1523 {
1524     if (!clearSelection)
1525         setFindEndstateFocusAndSelection();
1526     cancelPendingScopingEffort();
1527
1528     // Remove all markers for matches found and turn off the highlighting.
1529     frame()->document()->markers()->removeMarkers(DocumentMarker::TextMatch);
1530     frame()->editor()->setMarkedTextMatchesAreHighlighted(false);
1531
1532     // Let the frame know that we don't want tickmarks or highlighting anymore.
1533     invalidateArea(InvalidateAll);
1534 }
1535
1536 void WebFrameImpl::scopeStringMatches(int identifier,
1537                                       const WebString& searchText,
1538                                       const WebFindOptions& options,
1539                                       bool reset)
1540 {
1541     if (!shouldScopeMatches(searchText))
1542         return;
1543
1544     WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
1545
1546     if (reset) {
1547         // This is a brand new search, so we need to reset everything.
1548         // Scoping is just about to begin.
1549         m_scopingComplete = false;
1550         // Clear highlighting for this frame.
1551         if (frame()->editor()->markedTextMatchesAreHighlighted())
1552             frame()->page()->unmarkAllTextMatches();
1553         // Clear the counters from last operation.
1554         m_lastMatchCount = 0;
1555         m_nextInvalidateAfter = 0;
1556
1557         m_resumeScopingFromRange = 0;
1558
1559         mainFrameImpl->m_framesScopingCount++;
1560
1561         // Now, defer scoping until later to allow find operation to finish quickly.
1562         scopeStringMatchesSoon(
1563             identifier,
1564             searchText,
1565             options,
1566             false); // false=we just reset, so don't do it again.
1567         return;
1568     }
1569
1570     RefPtr<Range> searchRange(rangeOfContents(frame()->document()));
1571
1572     Node* originalEndContainer = searchRange->endContainer();
1573     int originalEndOffset = searchRange->endOffset();
1574
1575     ExceptionCode ec = 0, ec2 = 0;
1576     if (m_resumeScopingFromRange.get()) {
1577         // This is a continuation of a scoping operation that timed out and didn't
1578         // complete last time around, so we should start from where we left off.
1579         searchRange->setStart(m_resumeScopingFromRange->startContainer(),
1580                               m_resumeScopingFromRange->startOffset(ec2) + 1,
1581                               ec);
1582         if (ec || ec2) {
1583             if (ec2) // A non-zero |ec| happens when navigating during search.
1584                 ASSERT_NOT_REACHED();
1585             return;
1586         }
1587     }
1588
1589     // This timeout controls how long we scope before releasing control.  This
1590     // value does not prevent us from running for longer than this, but it is
1591     // periodically checked to see if we have exceeded our allocated time.
1592     const double maxScopingDuration = 0.1; // seconds
1593
1594     int matchCount = 0;
1595     bool timedOut = false;
1596     double startTime = currentTime();
1597     do {
1598         // Find next occurrence of the search string.
1599         // FIXME: (http://b/1088245) This WebKit operation may run for longer
1600         // than the timeout value, and is not interruptible as it is currently
1601         // written. We may need to rewrite it with interruptibility in mind, or
1602         // find an alternative.
1603         RefPtr<Range> resultRange(findPlainText(searchRange.get(),
1604                                                 searchText,
1605                                                 options.matchCase ? 0 : CaseInsensitive));
1606         if (resultRange->collapsed(ec)) {
1607             if (!resultRange->startContainer()->isInShadowTree())
1608                 break;
1609
1610             searchRange->setStartAfter(
1611                 resultRange->startContainer()->shadowAncestorNode(), ec);
1612             searchRange->setEnd(originalEndContainer, originalEndOffset, ec);
1613             continue;
1614         }
1615
1616         // Only treat the result as a match if it is visible
1617         if (frame()->editor()->insideVisibleArea(resultRange.get())) {
1618             ++matchCount;
1619
1620             // Catch a special case where Find found something but doesn't know what
1621             // the bounding box for it is. In this case we set the first match we find
1622             // as the active rect.
1623             IntRect resultBounds = resultRange->boundingBox();
1624             IntRect activeSelectionRect;
1625             if (m_locatingActiveRect) {
1626                 activeSelectionRect = m_activeMatch.get() ?
1627                     m_activeMatch->boundingBox() : resultBounds;
1628             }
1629
1630             // If the Find function found a match it will have stored where the
1631             // match was found in m_activeSelectionRect on the current frame. If we
1632             // find this rect during scoping it means we have found the active
1633             // tickmark.
1634             bool foundActiveMatch = false;
1635             if (m_locatingActiveRect && (activeSelectionRect == resultBounds)) {
1636                 // We have found the active tickmark frame.
1637                 mainFrameImpl->m_activeMatchFrame = this;
1638                 foundActiveMatch = true;
1639                 // We also know which tickmark is active now.
1640                 m_activeMatchIndex = matchCount - 1;
1641                 // To stop looking for the active tickmark, we set this flag.
1642                 m_locatingActiveRect = false;
1643
1644                 // Notify browser of new location for the selected rectangle.
1645                 reportFindInPageSelection(
1646                     frameView()->contentsToWindow(resultBounds),
1647                     m_activeMatchIndex + 1,
1648                     identifier);
1649             }
1650
1651             addMarker(resultRange.get(), foundActiveMatch);
1652         }
1653
1654         // Set the new start for the search range to be the end of the previous
1655         // result range. There is no need to use a VisiblePosition here,
1656         // since findPlainText will use a TextIterator to go over the visible
1657         // text nodes.
1658         searchRange->setStart(resultRange->endContainer(ec), resultRange->endOffset(ec), ec);
1659
1660         Node* shadowTreeRoot = searchRange->shadowTreeRootNode();
1661         if (searchRange->collapsed(ec) && shadowTreeRoot)
1662             searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), ec);
1663
1664         m_resumeScopingFromRange = resultRange;
1665         timedOut = (currentTime() - startTime) >= maxScopingDuration;
1666     } while (!timedOut);
1667
1668     // Remember what we search for last time, so we can skip searching if more
1669     // letters are added to the search string (and last outcome was 0).
1670     m_lastSearchString = searchText;
1671
1672     if (matchCount > 0) {
1673         frame()->editor()->setMarkedTextMatchesAreHighlighted(true);
1674
1675         m_lastMatchCount += matchCount;
1676
1677         // Let the mainframe know how much we found during this pass.
1678         mainFrameImpl->increaseMatchCount(matchCount, identifier);
1679     }
1680
1681     if (timedOut) {
1682         // If we found anything during this pass, we should redraw. However, we
1683         // don't want to spam too much if the page is extremely long, so if we
1684         // reach a certain point we start throttling the redraw requests.
1685         if (matchCount > 0)
1686             invalidateIfNecessary();
1687
1688         // Scoping effort ran out of time, lets ask for another time-slice.
1689         scopeStringMatchesSoon(
1690             identifier,
1691             searchText,
1692             options,
1693             false); // don't reset.
1694         return; // Done for now, resume work later.
1695     }
1696
1697     // This frame has no further scoping left, so it is done. Other frames might,
1698     // of course, continue to scope matches.
1699     m_scopingComplete = true;
1700     mainFrameImpl->m_framesScopingCount--;
1701
1702     // If this is the last frame to finish scoping we need to trigger the final
1703     // update to be sent.
1704     if (!mainFrameImpl->m_framesScopingCount)
1705         mainFrameImpl->increaseMatchCount(0, identifier);
1706
1707     // This frame is done, so show any scrollbar tickmarks we haven't drawn yet.
1708     invalidateArea(InvalidateScrollbar);
1709 }
1710
1711 void WebFrameImpl::cancelPendingScopingEffort()
1712 {
1713     deleteAllValues(m_deferredScopingWork);
1714     m_deferredScopingWork.clear();
1715
1716     m_activeMatchIndex = -1;
1717 }
1718
1719 void WebFrameImpl::increaseMatchCount(int count, int identifier)
1720 {
1721     // This function should only be called on the mainframe.
1722     ASSERT(!parent());
1723
1724     m_totalMatchCount += count;
1725
1726     // Update the UI with the latest findings.
1727     if (client())
1728         client()->reportFindInPageMatchCount(identifier, m_totalMatchCount, !m_framesScopingCount);
1729 }
1730
1731 void WebFrameImpl::reportFindInPageSelection(const WebRect& selectionRect,
1732                                              int activeMatchOrdinal,
1733                                              int identifier)
1734 {
1735     // Update the UI with the latest selection rect.
1736     if (client())
1737         client()->reportFindInPageSelection(identifier, ordinalOfFirstMatchForFrame(this) + activeMatchOrdinal, selectionRect);
1738 }
1739
1740 void WebFrameImpl::resetMatchCount()
1741 {
1742     m_totalMatchCount = 0;
1743     m_framesScopingCount = 0;
1744 }
1745
1746 WebString WebFrameImpl::contentAsText(size_t maxChars) const
1747 {
1748     if (!m_frame)
1749         return WebString();
1750
1751     Vector<UChar> text;
1752     frameContentAsPlainText(maxChars, m_frame, &text);
1753     return String::adopt(text);
1754 }
1755
1756 WebString WebFrameImpl::contentAsMarkup() const
1757 {
1758     return createFullMarkup(m_frame->document());
1759 }
1760
1761 WebString WebFrameImpl::renderTreeAsText(bool showDebugInfo) const
1762 {
1763     RenderAsTextBehavior behavior = RenderAsTextBehaviorNormal;
1764
1765     if (showDebugInfo) {
1766         behavior |= RenderAsTextShowCompositedLayers
1767             | RenderAsTextShowAddresses
1768             | RenderAsTextShowIDAndClass
1769             | RenderAsTextShowLayerNesting;
1770     }
1771
1772     return externalRepresentation(m_frame, behavior);
1773 }
1774
1775 WebString WebFrameImpl::counterValueForElementById(const WebString& id) const
1776 {
1777     if (!m_frame)
1778         return WebString();
1779
1780     Element* element = m_frame->document()->getElementById(id);
1781     if (!element)
1782         return WebString();
1783
1784     return counterValueForElement(element);
1785 }
1786
1787 WebString WebFrameImpl::markerTextForListItem(const WebElement& webElement) const
1788 {
1789     return WebCore::markerTextForListItem(const_cast<Element*>(webElement.constUnwrap<Element>()));
1790 }
1791
1792 int WebFrameImpl::pageNumberForElementById(const WebString& id,
1793                                            float pageWidthInPixels,
1794                                            float pageHeightInPixels) const
1795 {
1796     if (!m_frame)
1797         return -1;
1798
1799     Element* element = m_frame->document()->getElementById(id);
1800     if (!element)
1801         return -1;
1802
1803     FloatSize pageSize(pageWidthInPixels, pageHeightInPixels);
1804     return PrintContext::pageNumberForElement(element, pageSize);
1805 }
1806
1807 WebRect WebFrameImpl::selectionBoundsRect() const
1808 {
1809     if (hasSelection())
1810         return IntRect(frame()->selection()->bounds(false));
1811
1812     return WebRect();
1813 }
1814
1815 bool WebFrameImpl::selectionStartHasSpellingMarkerFor(int from, int length) const
1816 {
1817     if (!m_frame)
1818         return false;
1819     return m_frame->editor()->selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length);
1820 }
1821
1822 bool WebFrameImpl::pauseSVGAnimation(const WebString& animationId, double time, const WebString& elementId)
1823 {
1824 #if !ENABLE(SVG)
1825     return false;
1826 #else
1827     if (!m_frame)
1828         return false;
1829
1830     Document* document = m_frame->document();
1831     if (!document || !document->svgExtensions())
1832         return false;
1833
1834     Node* coreNode = document->getElementById(animationId);
1835     if (!coreNode || !SVGSMILElement::isSMILElement(coreNode))
1836         return false;
1837
1838     return document->accessSVGExtensions()->sampleAnimationAtTime(elementId, static_cast<SVGSMILElement*>(coreNode), time);
1839 #endif
1840 }
1841
1842 WebString WebFrameImpl::layerTreeAsText(bool showDebugInfo) const
1843 {
1844     if (!m_frame)
1845         return WebString();
1846     return WebString(m_frame->layerTreeAsText(showDebugInfo));
1847 }
1848
1849 // WebFrameImpl public ---------------------------------------------------------
1850
1851 PassRefPtr<WebFrameImpl> WebFrameImpl::create(WebFrameClient* client)
1852 {
1853     return adoptRef(new WebFrameImpl(client));
1854 }
1855
1856 WebFrameImpl::WebFrameImpl(WebFrameClient* client)
1857     : m_frameLoaderClient(this)
1858     , m_client(client)
1859     , m_activeMatchFrame(0)
1860     , m_activeMatchIndex(-1)
1861     , m_locatingActiveRect(false)
1862     , m_resumeScopingFromRange(0)
1863     , m_lastMatchCount(-1)
1864     , m_totalMatchCount(-1)
1865     , m_framesScopingCount(-1)
1866     , m_scopingComplete(false)
1867     , m_nextInvalidateAfter(0)
1868     , m_animationController(this)
1869     , m_identifier(generateFrameIdentifier())
1870     , m_inSameDocumentHistoryLoad(false)
1871 {
1872     PlatformSupport::incrementStatsCounter(webFrameActiveCount);
1873     frameCount++;
1874 }
1875
1876 WebFrameImpl::~WebFrameImpl()
1877 {
1878     PlatformSupport::decrementStatsCounter(webFrameActiveCount);
1879     frameCount--;
1880
1881     cancelPendingScopingEffort();
1882 }
1883
1884 void WebFrameImpl::initializeAsMainFrame(WebViewImpl* webViewImpl)
1885 {
1886     RefPtr<Frame> frame = Frame::create(webViewImpl->page(), 0, &m_frameLoaderClient);
1887     m_frame = frame.get();
1888
1889     // Add reference on behalf of FrameLoader.  See comments in
1890     // WebFrameLoaderClient::frameLoaderDestroyed for more info.
1891     ref();
1892
1893     // We must call init() after m_frame is assigned because it is referenced
1894     // during init().
1895     m_frame->init();
1896 }
1897
1898 PassRefPtr<Frame> WebFrameImpl::createChildFrame(
1899     const FrameLoadRequest& request, HTMLFrameOwnerElement* ownerElement)
1900 {
1901     RefPtr<WebFrameImpl> webframe(adoptRef(new WebFrameImpl(m_client)));
1902
1903     // Add an extra ref on behalf of the Frame/FrameLoader, which references the
1904     // WebFrame via the FrameLoaderClient interface. See the comment at the top
1905     // of this file for more info.
1906     webframe->ref();
1907
1908     RefPtr<Frame> childFrame = Frame::create(
1909         m_frame->page(), ownerElement, &webframe->m_frameLoaderClient);
1910     webframe->m_frame = childFrame.get();
1911
1912     childFrame->tree()->setName(request.frameName());
1913
1914     m_frame->tree()->appendChild(childFrame);
1915
1916     // Frame::init() can trigger onload event in the parent frame,
1917     // which may detach this frame and trigger a null-pointer access
1918     // in FrameTree::removeChild. Move init() after appendChild call
1919     // so that webframe->mFrame is in the tree before triggering
1920     // onload event handler.
1921     // Because the event handler may set webframe->mFrame to null,
1922     // it is necessary to check the value after calling init() and
1923     // return without loading URL.
1924     // (b:791612)
1925     childFrame->init(); // create an empty document
1926     if (!childFrame->tree()->parent())
1927         return 0;
1928
1929     m_frame->loader()->loadURLIntoChildFrame(
1930         request.resourceRequest().url(),
1931         request.resourceRequest().httpReferrer(),
1932         childFrame.get());
1933
1934     // A synchronous navigation (about:blank) would have already processed
1935     // onload, so it is possible for the frame to have already been destroyed by
1936     // script in the page.
1937     if (!childFrame->tree()->parent())
1938         return 0;
1939
1940     return childFrame.release();
1941 }
1942
1943 void WebFrameImpl::layout()
1944 {
1945     // layout this frame
1946     FrameView* view = m_frame->view();
1947     if (view)
1948         view->updateLayoutAndStyleIfNeededRecursive();
1949 }
1950
1951 void WebFrameImpl::paintWithContext(GraphicsContext& gc, const WebRect& rect)
1952 {
1953     IntRect dirtyRect(rect);
1954     gc.save();
1955     if (m_frame->document() && frameView()) {
1956         gc.clip(dirtyRect);
1957         frameView()->paint(&gc, dirtyRect);
1958         if (viewImpl()->pageOverlay())
1959             viewImpl()->pageOverlay()->paintWebFrame(gc);
1960     } else
1961         gc.fillRect(dirtyRect, Color::white, ColorSpaceDeviceRGB);
1962     gc.restore();
1963 }
1964
1965 void WebFrameImpl::paint(WebCanvas* canvas, const WebRect& rect)
1966 {
1967     if (rect.isEmpty())
1968         return;
1969     paintWithContext(GraphicsContextBuilder(canvas).context(), rect);
1970 }
1971
1972 void WebFrameImpl::createFrameView()
1973 {
1974     ASSERT(m_frame); // If m_frame doesn't exist, we probably didn't init properly.
1975
1976     Page* page = m_frame->page();
1977     ASSERT(page);
1978     ASSERT(page->mainFrame());
1979
1980     bool isMainFrame = m_frame == page->mainFrame();
1981     bool useFixedLayout = false;
1982     IntSize fixedLayoutSize;
1983     if (isMainFrame && m_frame->view()) {
1984         m_frame->view()->setParentVisible(false);
1985         // Save the fixed layout information before destroying the
1986         // existing FrameView of this frame.
1987         useFixedLayout = m_frame->view()->useFixedLayout();
1988         fixedLayoutSize = m_frame->view()->fixedLayoutSize();
1989     }
1990
1991     m_frame->setView(0);
1992
1993     WebViewImpl* webView = viewImpl();
1994
1995     RefPtr<FrameView> view;
1996     if (isMainFrame)
1997         view = FrameView::create(m_frame, webView->size());
1998     else
1999         view = FrameView::create(m_frame);
2000
2001     m_frame->setView(view);
2002
2003     if (webView->isTransparent())
2004         view->setTransparent(true);
2005
2006     // FIXME: The Mac code has a comment about this possibly being unnecessary.
2007     // See installInFrame in WebCoreFrameBridge.mm
2008     if (m_frame->ownerRenderer())
2009         m_frame->ownerRenderer()->setWidget(view.get());
2010
2011     if (HTMLFrameOwnerElement* owner = m_frame->ownerElement())
2012         view->setCanHaveScrollbars(owner->scrollingMode() != ScrollbarAlwaysOff);
2013
2014     if (isMainFrame)
2015         view->setParentVisible(true);
2016
2017 #if ENABLE(GESTURE_RECOGNIZER)
2018     webView->resetGestureRecognizer();
2019 #endif
2020
2021     // Restore the saved fixed layout information.
2022     view->setUseFixedLayout(useFixedLayout);
2023     view->setFixedLayoutSize(fixedLayoutSize);
2024 }
2025
2026 WebFrameImpl* WebFrameImpl::fromFrame(Frame* frame)
2027 {
2028     if (!frame)
2029         return 0;
2030
2031     return static_cast<FrameLoaderClientImpl*>(frame->loader()->client())->webFrame();
2032 }
2033
2034 WebFrameImpl* WebFrameImpl::fromFrameOwnerElement(Element* element)
2035 {
2036     if (!element
2037         || !element->isFrameOwnerElement()
2038         || (!element->hasTagName(HTMLNames::iframeTag)
2039             && !element->hasTagName(HTMLNames::frameTag)))
2040         return 0;
2041
2042     HTMLFrameOwnerElement* frameElement =
2043         static_cast<HTMLFrameOwnerElement*>(element);
2044     return fromFrame(frameElement->contentFrame());
2045 }
2046
2047 WebViewImpl* WebFrameImpl::viewImpl() const
2048 {
2049     if (!m_frame)
2050         return 0;
2051
2052     return WebViewImpl::fromPage(m_frame->page());
2053 }
2054
2055 WebDataSourceImpl* WebFrameImpl::dataSourceImpl() const
2056 {
2057     return static_cast<WebDataSourceImpl*>(dataSource());
2058 }
2059
2060 WebDataSourceImpl* WebFrameImpl::provisionalDataSourceImpl() const
2061 {
2062     return static_cast<WebDataSourceImpl*>(provisionalDataSource());
2063 }
2064
2065 void WebFrameImpl::setFindEndstateFocusAndSelection()
2066 {
2067     WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
2068
2069     if (this == mainFrameImpl->activeMatchFrame() && m_activeMatch.get()) {
2070         // If the user has set the selection since the match was found, we
2071         // don't focus anything.
2072         VisibleSelection selection(frame()->selection()->selection());
2073         if (!selection.isNone())
2074             return;
2075
2076         // Try to find the first focusable node up the chain, which will, for
2077         // example, focus links if we have found text within the link.
2078         Node* node = m_activeMatch->firstNode();
2079         while (node && !node->isFocusable() && node != frame()->document())
2080             node = node->parentNode();
2081
2082         if (node && node != frame()->document()) {
2083             // Found a focusable parent node. Set focus to it.
2084             frame()->document()->setFocusedNode(node);
2085             return;
2086         }
2087
2088         // Iterate over all the nodes in the range until we find a focusable node.
2089         // This, for example, sets focus to the first link if you search for
2090         // text and text that is within one or more links.
2091         node = m_activeMatch->firstNode();
2092         while (node && node != m_activeMatch->pastLastNode()) {
2093             if (node->isFocusable()) {
2094                 frame()->document()->setFocusedNode(node);
2095                 return;
2096             }
2097             node = node->traverseNextNode();
2098         }
2099
2100         // No node related to the active match was focusable, so set the
2101         // active match as the selection (so that when you end the Find session,
2102         // you'll have the last thing you found highlighted) and make sure that
2103         // we have nothing focused (otherwise you might have text selected but
2104         // a link focused, which is weird).
2105         frame()->selection()->setSelection(m_activeMatch.get());
2106         frame()->document()->setFocusedNode(0);
2107     }
2108 }
2109
2110 void WebFrameImpl::didFail(const ResourceError& error, bool wasProvisional)
2111 {
2112     if (!client())
2113         return;
2114     WebURLError webError = error;
2115     if (wasProvisional)
2116         client()->didFailProvisionalLoad(this, webError);
2117     else
2118         client()->didFailLoad(this, webError);
2119 }
2120
2121 void WebFrameImpl::setCanHaveScrollbars(bool canHaveScrollbars)
2122 {
2123     m_frame->view()->setCanHaveScrollbars(canHaveScrollbars);
2124 }
2125
2126 // WebFrameImpl private --------------------------------------------------------
2127
2128 void WebFrameImpl::closing()
2129 {
2130     m_frame = 0;
2131 }
2132
2133 void WebFrameImpl::invalidateArea(AreaToInvalidate area)
2134 {
2135     ASSERT(frame() && frame()->view());
2136     FrameView* view = frame()->view();
2137
2138     if ((area & InvalidateAll) == InvalidateAll)
2139         view->invalidateRect(view->frameRect());
2140     else {
2141         if ((area & InvalidateContentArea) == InvalidateContentArea) {
2142             IntRect contentArea(
2143                 view->x(), view->y(), view->visibleWidth(), view->visibleHeight());
2144             IntRect frameRect = view->frameRect();
2145             contentArea.move(-frameRect.x(), -frameRect.y());
2146             view->invalidateRect(contentArea);
2147         }
2148
2149         if ((area & InvalidateScrollbar) == InvalidateScrollbar) {
2150             // Invalidate the vertical scroll bar region for the view.
2151             Scrollbar* scrollbar = view->verticalScrollbar();
2152             if (scrollbar)
2153                 scrollbar->invalidate();
2154         }
2155     }
2156 }
2157
2158 void WebFrameImpl::addMarker(Range* range, bool activeMatch)
2159 {
2160     frame()->document()->markers()->addTextMatchMarker(range, activeMatch);
2161 }
2162
2163 void WebFrameImpl::setMarkerActive(Range* range, bool active)
2164 {
2165     WebCore::ExceptionCode ec;
2166     if (!range || range->collapsed(ec))
2167         return;
2168
2169     frame()->document()->markers()->setMarkersActive(range, active);
2170 }
2171
2172 int WebFrameImpl::ordinalOfFirstMatchForFrame(WebFrameImpl* frame) const
2173 {
2174     int ordinal = 0;
2175     WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
2176     // Iterate from the main frame up to (but not including) |frame| and
2177     // add up the number of matches found so far.
2178     for (WebFrameImpl* it = mainFrameImpl;
2179          it != frame;
2180          it = static_cast<WebFrameImpl*>(it->traverseNext(true))) {
2181         if (it->m_lastMatchCount > 0)
2182             ordinal += it->m_lastMatchCount;
2183     }
2184     return ordinal;
2185 }
2186
2187 bool WebFrameImpl::shouldScopeMatches(const String& searchText)
2188 {
2189     // Don't scope if we can't find a frame or a view or if the frame is not visible.
2190     // The user may have closed the tab/application, so abort.
2191     if (!frame() || !frame()->view() || !hasVisibleContent())
2192         return false;
2193
2194     ASSERT(frame()->document() && frame()->view());
2195
2196     // If the frame completed the scoping operation and found 0 matches the last
2197     // time it was searched, then we don't have to search it again if the user is
2198     // just adding to the search string or sending the same search string again.
2199     if (m_scopingComplete && !m_lastSearchString.isEmpty() && !m_lastMatchCount) {
2200         // Check to see if the search string prefixes match.
2201         String previousSearchPrefix =
2202             searchText.substring(0, m_lastSearchString.length());
2203
2204         if (previousSearchPrefix == m_lastSearchString)
2205             return false; // Don't search this frame, it will be fruitless.
2206     }
2207
2208     return true;
2209 }
2210
2211 void WebFrameImpl::scopeStringMatchesSoon(int identifier, const WebString& searchText,
2212                                           const WebFindOptions& options, bool reset)
2213 {
2214     m_deferredScopingWork.append(new DeferredScopeStringMatches(
2215         this, identifier, searchText, options, reset));
2216 }
2217
2218 void WebFrameImpl::callScopeStringMatches(DeferredScopeStringMatches* caller,
2219                                           int identifier, const WebString& searchText,
2220                                           const WebFindOptions& options, bool reset)
2221 {
2222     m_deferredScopingWork.remove(m_deferredScopingWork.find(caller));
2223
2224     scopeStringMatches(identifier, searchText, options, reset);
2225
2226     // This needs to happen last since searchText is passed by reference.
2227     delete caller;
2228 }
2229
2230 void WebFrameImpl::invalidateIfNecessary()
2231 {
2232     if (m_lastMatchCount > m_nextInvalidateAfter) {
2233         // FIXME: (http://b/1088165) Optimize the drawing of the tickmarks and
2234         // remove this. This calculation sets a milestone for when next to
2235         // invalidate the scrollbar and the content area. We do this so that we
2236         // don't spend too much time drawing the scrollbar over and over again.
2237         // Basically, up until the first 500 matches there is no throttle.
2238         // After the first 500 matches, we set set the milestone further and
2239         // further out (750, 1125, 1688, 2K, 3K).
2240         static const int startSlowingDownAfter = 500;
2241         static const int slowdown = 750;
2242         int i = (m_lastMatchCount / startSlowingDownAfter);
2243         m_nextInvalidateAfter += i * slowdown;
2244
2245         invalidateArea(InvalidateScrollbar);
2246     }
2247 }
2248
2249 void WebFrameImpl::loadJavaScriptURL(const KURL& url)
2250 {
2251     // This is copied from ScriptController::executeIfJavaScriptURL.
2252     // Unfortunately, we cannot just use that method since it is private, and
2253     // it also doesn't quite behave as we require it to for bookmarklets.  The
2254     // key difference is that we need to suppress loading the string result
2255     // from evaluating the JS URL if executing the JS URL resulted in a
2256     // location change.  We also allow a JS URL to be loaded even if scripts on
2257     // the page are otherwise disabled.
2258
2259     if (!m_frame->document() || !m_frame->page())
2260         return;
2261
2262     // Protect privileged pages against bookmarklets and other javascript manipulations.
2263     if (SchemeRegistry::shouldTreatURLSchemeAsNotAllowingJavascriptURLs(m_frame->document()->url().protocol()))
2264         return;
2265
2266     String script = decodeURLEscapeSequences(url.string().substring(strlen("javascript:")));
2267     ScriptValue result = m_frame->script()->executeScript(script, true);
2268
2269     String scriptResult;
2270     if (!result.getString(scriptResult))
2271         return;
2272
2273     if (!m_frame->navigationScheduler()->locationChangePending())
2274         m_frame->document()->loader()->writer()->replaceDocument(scriptResult);
2275 }
2276
2277 } // namespace WebKit