2 * Copyright (C) 2009 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
31 // How ownership works
32 // -------------------
34 // Big oh represents a refcounted relationship: owner O--- ownee
36 // WebView (for the toplevel frame only)
39 // Page O------- Frame (m_mainFrame) O-------O FrameView
42 // FrameLoader O-------- WebFrame (via FrameLoaderClient)
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.
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.
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.
57 // How frames are destroyed
58 // ------------------------
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.
63 // When frame content is replaced, all subframes are destroyed. This happens
64 // in FrameLoader::detachFromParent for each subframe.
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).
72 #include "WebFrameImpl.h"
74 #include "AssociatedURLLoader.h"
75 #include "BackForwardController.h"
77 #include "ClipboardUtilitiesChromium.h"
79 #include "DOMUtilitiesPrivate.h"
80 #include "DOMWindow.h"
82 #include "DocumentFragment.h" // Only needed for ReplaceSelectionCommand.h :(
83 #include "DocumentLoader.h"
84 #include "DocumentMarker.h"
85 #include "DocumentMarkerController.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"
105 #include "InspectorController.h"
108 #include "PageOverlay.h"
109 #include "painting/GraphicsContextBuilder.h"
110 #include "Performance.h"
111 #include "PlatformBridge.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"
148 #include "WebPasswordAutocompleteListener.h"
149 #include "WebPerformance.h"
150 #include "WebPlugin.h"
151 #include "WebPluginContainerImpl.h"
152 #include "WebPoint.h"
153 #include "WebRange.h"
155 #include "WebScriptSource.h"
156 #include "WebSecurityOrigin.h"
158 #include "WebURLError.h"
159 #include "WebVector.h"
160 #include "WebViewImpl.h"
161 #include "XPathResult.h"
165 #include <wtf/CurrentTime.h>
167 #if OS(UNIX) && !OS(DARWIN)
172 #include "AsyncFileSystem.h"
173 #include "AsyncFileSystemChromium.h"
174 #include "DirectoryEntry.h"
175 #include "DOMFileSystem.h"
176 #include "FileEntry.h"
177 #include "V8DirectoryEntry.h"
178 #include "V8DOMFileSystem.h"
179 #include "V8FileEntry.h"
180 #include "WebFileSystem.h"
183 using namespace WebCore;
187 static int frameCount = 0;
189 // Key for a StatsCounter tracking how many WebFrames are active.
190 static const char* const webFrameActiveCount = "WebFrameActiveCount";
192 // Backend for contentAsPlainText, this is a recursive function that gets
193 // the text for the current frame and all of its subframes. It will append
194 // the text of each frame in turn to the |output| up to |maxChars| length.
196 // The |frame| must be non-null.
197 static void frameContentAsPlainText(size_t maxChars, Frame* frame,
198 Vector<UChar>* output)
200 Document* doc = frame->document();
207 // TextIterator iterates over the visual representation of the DOM. As such,
208 // it requires you to do a layout before using it (otherwise it'll crash).
209 if (frame->view()->needsLayout())
210 frame->view()->layout();
212 // Select the document body.
213 RefPtr<Range> range(doc->createRange());
214 ExceptionCode exception = 0;
215 range->selectNodeContents(doc->body(), exception);
218 // The text iterator will walk nodes giving us text. This is similar to
219 // the plainText() function in TextIterator.h, but we implement the maximum
220 // size and also copy the results directly into a wstring, avoiding the
221 // string conversion.
222 for (TextIterator it(range.get()); !it.atEnd(); it.advance()) {
223 const UChar* chars = it.characters();
226 // It appears from crash reports that an iterator can get into a state
227 // where the character count is nonempty but the character pointer is
228 // null. advance()ing it will then just add that many to the null
229 // pointer which won't be caught in a null check but will crash.
231 // A null pointer and 0 length is common for some nodes.
233 // IF YOU CATCH THIS IN A DEBUGGER please let brettw know. We don't
234 // currently understand the conditions for this to occur. Ideally, the
235 // iterators would never get into the condition so we should fix them
237 ASSERT_NOT_REACHED();
241 // Just got a null node, we can forge ahead!
245 std::min(static_cast<size_t>(it.length()), maxChars - output->size());
246 output->append(chars, toAppend);
247 if (output->size() >= maxChars)
248 return; // Filled up the buffer.
252 // The separator between frames when the frames are converted to plain text.
253 const UChar frameSeparator[] = { '\n', '\n' };
254 const size_t frameSeparatorLen = 2;
256 // Recursively walk the children.
257 FrameTree* frameTree = frame->tree();
258 for (Frame* curChild = frameTree->firstChild(); curChild; curChild = curChild->tree()->nextSibling()) {
259 // Ignore the text of non-visible frames.
260 RenderView* contentRenderer = curChild->contentRenderer();
261 RenderPart* ownerRenderer = curChild->ownerRenderer();
262 if (!contentRenderer || !contentRenderer->width() || !contentRenderer->height()
263 || (contentRenderer->x() + contentRenderer->width() <= 0) || (contentRenderer->y() + contentRenderer->height() <= 0)
264 || (ownerRenderer && ownerRenderer->style() && ownerRenderer->style()->visibility() != VISIBLE)) {
268 // Make sure the frame separator won't fill up the buffer, and give up if
269 // it will. The danger is if the separator will make the buffer longer than
270 // maxChars. This will cause the computation above:
271 // maxChars - output->size()
272 // to be a negative number which will crash when the subframe is added.
273 if (output->size() >= maxChars - frameSeparatorLen)
276 output->append(frameSeparator, frameSeparatorLen);
277 frameContentAsPlainText(maxChars, curChild, output);
278 if (output->size() >= maxChars)
279 return; // Filled up the buffer.
283 static long long generateFrameIdentifier()
285 static long long next = 0;
289 static WebPluginContainerImpl* pluginContainerFromNode(const WebNode& node)
294 const Node* coreNode = node.constUnwrap<Node>();
295 if (coreNode->hasTagName(HTMLNames::objectTag) || coreNode->hasTagName(HTMLNames::embedTag)) {
296 RenderObject* object = coreNode->renderer();
297 if (object && object->isWidget()) {
298 Widget* widget = toRenderWidget(object)->widget();
299 if (widget && widget->isPluginContainer())
300 return static_cast<WebPluginContainerImpl*>(widget);
306 WebPluginContainerImpl* WebFrameImpl::pluginContainerFromFrame(Frame* frame)
310 if (!frame->document() || !frame->document()->isPluginDocument())
312 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
313 return static_cast<WebPluginContainerImpl *>(pluginDocument->pluginWidget());
316 // Simple class to override some of PrintContext behavior. Some of the methods
317 // made virtual so that they can be overridden by ChromePluginPrintContext.
318 class ChromePrintContext : public PrintContext {
319 WTF_MAKE_NONCOPYABLE(ChromePrintContext);
321 ChromePrintContext(Frame* frame)
322 : PrintContext(frame)
323 , m_printedPageWidth(0)
327 virtual ~ChromePrintContext() { }
329 virtual void begin(float width, float height)
331 ASSERT(!m_printedPageWidth);
332 m_printedPageWidth = width;
333 PrintContext::begin(m_printedPageWidth, height);
341 virtual float getPageShrink(int pageNumber) const
343 IntRect pageRect = m_pageRects[pageNumber];
344 return m_printedPageWidth / pageRect.width();
347 // Spools the printed page, a subrect of m_frame. Skip the scale step.
348 // NativeTheme doesn't play well with scaling. Scaling is done browser side
349 // instead. Returns the scale to be applied.
350 // On Linux, we don't have the problem with NativeTheme, hence we let WebKit
351 // do the scaling and ignore the return value.
352 virtual float spoolPage(GraphicsContext& ctx, int pageNumber)
354 IntRect pageRect = m_pageRects[pageNumber];
355 float scale = m_printedPageWidth / pageRect.width();
358 #if OS(UNIX) && !OS(DARWIN)
359 ctx.scale(WebCore::FloatSize(scale, scale));
361 ctx.translate(static_cast<float>(-pageRect.x()),
362 static_cast<float>(-pageRect.y()));
364 m_frame->view()->paintContents(&ctx, pageRect);
369 virtual void computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight)
371 return PrintContext::computePageRects(printRect, headerHeight, footerHeight, userScaleFactor, outPageHeight);
374 virtual int pageCount() const
376 return PrintContext::pageCount();
379 virtual bool shouldUseBrowserOverlays() const
385 // Set when printing.
386 float m_printedPageWidth;
389 // Simple class to override some of PrintContext behavior. This is used when
390 // the frame hosts a plugin that supports custom printing. In this case, we
391 // want to delegate all printing related calls to the plugin.
392 class ChromePluginPrintContext : public ChromePrintContext {
394 ChromePluginPrintContext(Frame* frame, WebPluginContainerImpl* plugin, int printerDPI)
395 : ChromePrintContext(frame), m_plugin(plugin), m_pageCount(0), m_printerDPI(printerDPI)
399 virtual ~ChromePluginPrintContext() { }
401 virtual void begin(float width, float height)
407 m_plugin->printEnd();
410 virtual float getPageShrink(int pageNumber) const
412 // We don't shrink the page (maybe we should ask the widget ??)
416 virtual void computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight)
418 m_pageCount = m_plugin->printBegin(IntRect(printRect), m_printerDPI);
421 virtual int pageCount() const
426 // Spools the printed page, a subrect of m_frame. Skip the scale step.
427 // NativeTheme doesn't play well with scaling. Scaling is done browser side
428 // instead. Returns the scale to be applied.
429 virtual float spoolPage(GraphicsContext& ctx, int pageNumber)
431 m_plugin->printPage(pageNumber, &ctx);
435 virtual bool shouldUseBrowserOverlays() const
441 // Set when printing.
442 WebPluginContainerImpl* m_plugin;
447 static WebDataSource* DataSourceForDocLoader(DocumentLoader* loader)
449 return loader ? WebDataSourceImpl::fromDocumentLoader(loader) : 0;
453 // WebFrame -------------------------------------------------------------------
455 class WebFrameImpl::DeferredScopeStringMatches {
457 DeferredScopeStringMatches(WebFrameImpl* webFrame,
459 const WebString& searchText,
460 const WebFindOptions& options,
462 : m_timer(this, &DeferredScopeStringMatches::doTimeout)
463 , m_webFrame(webFrame)
464 , m_identifier(identifier)
465 , m_searchText(searchText)
469 m_timer.startOneShot(0.0);
473 void doTimeout(Timer<DeferredScopeStringMatches>*)
475 m_webFrame->callScopeStringMatches(
476 this, m_identifier, m_searchText, m_options, m_reset);
479 Timer<DeferredScopeStringMatches> m_timer;
480 RefPtr<WebFrameImpl> m_webFrame;
482 WebString m_searchText;
483 WebFindOptions m_options;
488 // WebFrame -------------------------------------------------------------------
490 int WebFrame::instanceCount()
495 WebFrame* WebFrame::frameForEnteredContext()
498 ScriptController::retrieveFrameForEnteredContext();
499 return WebFrameImpl::fromFrame(frame);
502 WebFrame* WebFrame::frameForCurrentContext()
505 ScriptController::retrieveFrameForCurrentContext();
506 return WebFrameImpl::fromFrame(frame);
510 WebFrame* WebFrame::frameForContext(v8::Handle<v8::Context> context)
512 return WebFrameImpl::fromFrame(V8Proxy::retrieveFrame(context));
516 WebFrame* WebFrame::fromFrameOwnerElement(const WebElement& element)
518 return WebFrameImpl::fromFrameOwnerElement(
519 PassRefPtr<Element>(element).get());
522 WebString WebFrameImpl::name() const
524 return m_frame->tree()->uniqueName();
527 void WebFrameImpl::setName(const WebString& name)
529 m_frame->tree()->setName(name);
532 long long WebFrameImpl::identifier() const
537 WebVector<WebIconURL> WebFrameImpl::iconURLs(int iconTypes) const
539 FrameLoader* frameLoader = m_frame->loader();
540 // The URL to the icon may be in the header. As such, only
541 // ask the loader for the icon if it's finished loading.
542 if (frameLoader->state() == FrameStateComplete)
543 return frameLoader->icon()->urlsForTypes(iconTypes);
544 return WebVector<WebIconURL>();
547 WebSize WebFrameImpl::scrollOffset() const
549 FrameView* view = frameView();
551 return view->scrollOffset();
556 WebSize WebFrameImpl::minimumScrollOffset() const
558 FrameView* view = frameView();
560 return view->minimumScrollPosition() - IntPoint();
565 WebSize WebFrameImpl::maximumScrollOffset() const
567 FrameView* view = frameView();
569 return view->maximumScrollPosition() - IntPoint();
574 void WebFrameImpl::setScrollOffset(const WebSize& offset)
576 if (FrameView* view = frameView())
577 view->setScrollOffset(IntPoint(offset.width, offset.height));
580 WebSize WebFrameImpl::contentsSize() const
582 return frame()->view()->contentsSize();
585 int WebFrameImpl::contentsPreferredWidth() const
587 if (m_frame->document() && m_frame->document()->renderView())
588 return m_frame->document()->renderView()->minPreferredLogicalWidth();
592 int WebFrameImpl::documentElementScrollHeight() const
594 if (m_frame->document() && m_frame->document()->documentElement())
595 return m_frame->document()->documentElement()->scrollHeight();
599 bool WebFrameImpl::hasVisibleContent() const
601 return frame()->view()->visibleWidth() > 0 && frame()->view()->visibleHeight() > 0;
604 bool WebFrameImpl::hasHorizontalScrollbar() const
606 return m_frame && m_frame->view() && m_frame->view()->horizontalScrollbar();
609 bool WebFrameImpl::hasVerticalScrollbar() const
611 return m_frame && m_frame->view() && m_frame->view()->verticalScrollbar();
614 WebView* WebFrameImpl::view() const
619 void WebFrameImpl::clearOpener()
621 m_frame->loader()->setOpener(0);
624 WebFrame* WebFrameImpl::opener() const
628 opener = m_frame->loader()->opener();
629 return fromFrame(opener);
632 WebFrame* WebFrameImpl::parent() const
636 parent = m_frame->tree()->parent();
637 return fromFrame(parent);
640 WebFrame* WebFrameImpl::top() const
643 return fromFrame(m_frame->tree()->top());
648 WebFrame* WebFrameImpl::firstChild() const
650 return fromFrame(frame()->tree()->firstChild());
653 WebFrame* WebFrameImpl::lastChild() const
655 return fromFrame(frame()->tree()->lastChild());
658 WebFrame* WebFrameImpl::nextSibling() const
660 return fromFrame(frame()->tree()->nextSibling());
663 WebFrame* WebFrameImpl::previousSibling() const
665 return fromFrame(frame()->tree()->previousSibling());
668 WebFrame* WebFrameImpl::traverseNext(bool wrap) const
670 return fromFrame(frame()->tree()->traverseNextWithWrap(wrap));
673 WebFrame* WebFrameImpl::traversePrevious(bool wrap) const
675 return fromFrame(frame()->tree()->traversePreviousWithWrap(wrap));
678 WebFrame* WebFrameImpl::findChildByName(const WebString& name) const
680 return fromFrame(frame()->tree()->child(name));
683 WebFrame* WebFrameImpl::findChildByExpression(const WebString& xpath) const
688 Document* document = m_frame->document();
690 ExceptionCode ec = 0;
691 PassRefPtr<XPathResult> xpathResult =
692 document->evaluate(xpath,
695 XPathResult::ORDERED_NODE_ITERATOR_TYPE,
696 0, // XPathResult object
698 if (!xpathResult.get())
701 Node* node = xpathResult->iterateNext(ec);
703 if (!node || !node->isFrameOwnerElement())
705 HTMLFrameOwnerElement* frameElement =
706 static_cast<HTMLFrameOwnerElement*>(node);
707 return fromFrame(frameElement->contentFrame());
710 WebDocument WebFrameImpl::document() const
712 if (!m_frame || !m_frame->document())
713 return WebDocument();
714 return WebDocument(m_frame->document());
717 WebAnimationController* WebFrameImpl::animationController()
719 return &m_animationController;
722 WebPerformance WebFrameImpl::performance() const
724 if (!m_frame || !m_frame->domWindow())
725 return WebPerformance();
727 return WebPerformance(m_frame->domWindow()->performance());
730 NPObject* WebFrameImpl::windowObject() const
735 return m_frame->script()->windowScriptNPObject();
738 void WebFrameImpl::bindToWindowObject(const WebString& name, NPObject* object)
741 if (!m_frame || !m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
746 m_frame->script()->bindToWindowObject(m_frame, key, object);
752 void WebFrameImpl::executeScript(const WebScriptSource& source)
754 TextPosition1 position(WTF::OneBasedNumber::fromOneBasedInt(source.startLine), WTF::OneBasedNumber::base());
755 m_frame->script()->executeScript(
756 ScriptSourceCode(source.code, source.url, position));
759 void WebFrameImpl::executeScriptInIsolatedWorld(
760 int worldID, const WebScriptSource* sourcesIn, unsigned numSources,
763 Vector<ScriptSourceCode> sources;
765 for (unsigned i = 0; i < numSources; ++i) {
766 TextPosition1 position(WTF::OneBasedNumber::fromOneBasedInt(sourcesIn[i].startLine), WTF::OneBasedNumber::base());
767 sources.append(ScriptSourceCode(
768 sourcesIn[i].code, sourcesIn[i].url, position));
771 m_frame->script()->evaluateInIsolatedWorld(worldID, sources, extensionGroup);
774 void WebFrameImpl::setIsolatedWorldSecurityOrigin(int worldID, const WebSecurityOrigin& securityOrigin)
776 m_frame->script()->setIsolatedWorldSecurityOrigin(worldID, securityOrigin.get());
779 void WebFrameImpl::addMessageToConsole(const WebConsoleMessage& message)
783 MessageLevel webCoreMessageLevel;
784 switch (message.level) {
785 case WebConsoleMessage::LevelTip:
786 webCoreMessageLevel = TipMessageLevel;
788 case WebConsoleMessage::LevelLog:
789 webCoreMessageLevel = LogMessageLevel;
791 case WebConsoleMessage::LevelWarning:
792 webCoreMessageLevel = WarningMessageLevel;
794 case WebConsoleMessage::LevelError:
795 webCoreMessageLevel = ErrorMessageLevel;
798 ASSERT_NOT_REACHED();
802 frame()->domWindow()->console()->addMessage(
803 OtherMessageSource, LogMessageType, webCoreMessageLevel, message.text,
807 void WebFrameImpl::collectGarbage()
811 if (!m_frame->settings()->isJavaScriptEnabled())
813 // FIXME: Move this to the ScriptController and make it JS neutral.
815 m_frame->script()->collectGarbage();
821 bool WebFrameImpl::checkIfRunInsecureContent(const WebURL& url) const
823 FrameLoader* frameLoader = m_frame->loader();
824 return frameLoader->checkIfRunInsecureContent(m_frame->document()->securityOrigin(), url);
828 v8::Handle<v8::Value> WebFrameImpl::executeScriptAndReturnValue(const WebScriptSource& source)
830 // FIXME: This fake user gesture is required to make a bunch of pyauto
831 // tests pass. If this isn't needed in non-test situations, we should
832 // consider removing this code and changing the tests.
833 // http://code.google.com/p/chromium/issues/detail?id=86397
834 UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
836 TextPosition1 position(WTF::OneBasedNumber::fromOneBasedInt(source.startLine), WTF::OneBasedNumber::base());
837 return m_frame->script()->executeScript(ScriptSourceCode(source.code, source.url, position)).v8Value();
840 // Returns the V8 context for this frame, or an empty handle if there is none.
841 v8::Local<v8::Context> WebFrameImpl::mainWorldScriptContext() const
844 return v8::Local<v8::Context>();
846 return V8Proxy::mainWorldContext(m_frame);
849 v8::Handle<v8::Value> WebFrameImpl::createFileSystem(WebFileSystem::Type type,
850 const WebString& name,
851 const WebString& path)
853 return toV8(DOMFileSystem::create(frame()->document(), name, AsyncFileSystemChromium::create(static_cast<AsyncFileSystem::Type>(type), KURL(ParsedURLString, path.utf8().data()))));
856 v8::Handle<v8::Value> WebFrameImpl::createFileEntry(WebFileSystem::Type type,
857 const WebString& fileSystemName,
858 const WebString& fileSystemPath,
859 const WebString& filePath,
862 RefPtr<DOMFileSystemBase> fileSystem = DOMFileSystem::create(frame()->document(), fileSystemName, AsyncFileSystemChromium::create(static_cast<AsyncFileSystem::Type>(type), KURL(ParsedURLString, fileSystemPath.utf8().data())));
864 return toV8(DirectoryEntry::create(fileSystem, filePath));
865 return toV8(FileEntry::create(fileSystem, filePath));
869 void WebFrameImpl::reload(bool ignoreCache)
871 m_frame->loader()->history()->saveDocumentAndScrollState();
872 m_frame->loader()->reload(ignoreCache);
875 void WebFrameImpl::loadRequest(const WebURLRequest& request)
877 ASSERT(!request.isNull());
878 const ResourceRequest& resourceRequest = request.toResourceRequest();
880 if (resourceRequest.url().protocolIs("javascript")) {
881 loadJavaScriptURL(resourceRequest.url());
885 m_frame->loader()->load(resourceRequest, false);
888 void WebFrameImpl::loadHistoryItem(const WebHistoryItem& item)
890 RefPtr<HistoryItem> historyItem = PassRefPtr<HistoryItem>(item);
891 ASSERT(historyItem.get());
893 m_frame->loader()->prepareForHistoryNavigation();
894 RefPtr<HistoryItem> currentItem = m_frame->loader()->history()->currentItem();
895 m_inSameDocumentHistoryLoad = currentItem->shouldDoSameDocumentNavigationTo(historyItem.get());
896 m_frame->page()->goToItem(historyItem.get(),
897 FrameLoadTypeIndexedBackForward);
898 m_inSameDocumentHistoryLoad = false;
901 void WebFrameImpl::loadData(const WebData& data,
902 const WebString& mimeType,
903 const WebString& textEncoding,
904 const WebURL& baseURL,
905 const WebURL& unreachableURL,
908 SubstituteData substData(data, mimeType, textEncoding, unreachableURL);
909 ASSERT(substData.isValid());
911 // If we are loading substitute data to replace an existing load, then
912 // inherit all of the properties of that original request. This way,
913 // reload will re-attempt the original request. It is essential that
914 // we only do this when there is an unreachableURL since a non-empty
915 // unreachableURL informs FrameLoader::reload to load unreachableURL
916 // instead of the currently loaded URL.
917 ResourceRequest request;
918 if (replace && !unreachableURL.isEmpty())
919 request = m_frame->loader()->originalRequest();
920 request.setURL(baseURL);
922 m_frame->loader()->load(request, substData, false);
924 // Do this to force WebKit to treat the load as replacing the currently
926 m_frame->loader()->setReplacing();
930 void WebFrameImpl::loadHTMLString(const WebData& data,
931 const WebURL& baseURL,
932 const WebURL& unreachableURL,
936 WebString::fromUTF8("text/html"),
937 WebString::fromUTF8("UTF-8"),
943 bool WebFrameImpl::isLoading() const
947 return m_frame->loader()->isLoading();
950 void WebFrameImpl::stopLoading()
955 // FIXME: Figure out what we should really do here. It seems like a bug
956 // that FrameLoader::stopLoading doesn't call stopAllLoaders.
957 m_frame->loader()->stopAllLoaders();
958 m_frame->loader()->stopLoading(UnloadEventPolicyNone);
961 WebDataSource* WebFrameImpl::provisionalDataSource() const
963 FrameLoader* frameLoader = m_frame->loader();
965 // We regard the policy document loader as still provisional.
966 DocumentLoader* docLoader = frameLoader->provisionalDocumentLoader();
968 docLoader = frameLoader->policyDocumentLoader();
970 return DataSourceForDocLoader(docLoader);
973 WebDataSource* WebFrameImpl::dataSource() const
975 return DataSourceForDocLoader(m_frame->loader()->documentLoader());
978 WebHistoryItem WebFrameImpl::previousHistoryItem() const
980 // We use the previous item here because documentState (filled-out forms)
981 // only get saved to history when it becomes the previous item. The caller
982 // is expected to query the history item after a navigation occurs, after
983 // the desired history item has become the previous entry.
984 return WebHistoryItem(m_frame->loader()->history()->previousItem());
987 WebHistoryItem WebFrameImpl::currentHistoryItem() const
989 // We're shutting down.
990 if (!m_frame->loader()->activeDocumentLoader())
991 return WebHistoryItem();
993 // If we are still loading, then we don't want to clobber the current
994 // history item as this could cause us to lose the scroll position and
995 // document state. However, it is OK for new navigations.
996 // FIXME: Can we make this a plain old getter, instead of worrying about
998 if (!m_inSameDocumentHistoryLoad && (m_frame->loader()->loadType() == FrameLoadTypeStandard
999 || !m_frame->loader()->activeDocumentLoader()->isLoadingInAPISense()))
1000 m_frame->loader()->history()->saveDocumentAndScrollState();
1002 return WebHistoryItem(m_frame->page()->backForward()->currentItem());
1005 void WebFrameImpl::enableViewSourceMode(bool enable)
1008 m_frame->setInViewSourceMode(enable);
1011 bool WebFrameImpl::isViewSourceModeEnabled() const
1014 return m_frame->inViewSourceMode();
1019 void WebFrameImpl::setReferrerForRequest(
1020 WebURLRequest& request, const WebURL& referrerURL) {
1022 if (referrerURL.isEmpty())
1023 referrer = m_frame->loader()->outgoingReferrer();
1025 referrer = referrerURL.spec().utf16();
1026 if (SecurityOrigin::shouldHideReferrer(request.url(), referrer))
1028 request.setHTTPHeaderField(WebString::fromUTF8("Referer"), referrer);
1031 void WebFrameImpl::dispatchWillSendRequest(WebURLRequest& request)
1033 ResourceResponse response;
1034 m_frame->loader()->client()->dispatchWillSendRequest(
1035 0, 0, request.toMutableResourceRequest(), response);
1038 WebURLLoader* WebFrameImpl::createAssociatedURLLoader(const WebURLLoaderOptions& options)
1040 return new AssociatedURLLoader(this, options);
1043 void WebFrameImpl::commitDocumentData(const char* data, size_t length)
1045 m_frame->loader()->documentLoader()->commitData(data, length);
1048 unsigned WebFrameImpl::unloadListenerCount() const
1050 return frame()->domWindow()->pendingUnloadEventListeners();
1053 bool WebFrameImpl::isProcessingUserGesture() const
1055 return ScriptController::processingUserGesture();
1058 bool WebFrameImpl::willSuppressOpenerInNewFrame() const
1060 return frame()->loader()->suppressOpenerInNewFrame();
1063 void WebFrameImpl::replaceSelection(const WebString& text)
1065 RefPtr<DocumentFragment> fragment = createFragmentFromText(
1066 frame()->selection()->toNormalizedRange().get(), text);
1067 applyCommand(ReplaceSelectionCommand::create(
1068 frame()->document(), fragment.get(), ReplaceSelectionCommand::SmartReplace | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
1071 void WebFrameImpl::insertText(const WebString& text)
1073 Editor* editor = frame()->editor();
1075 if (editor->hasComposition())
1076 editor->confirmComposition(text);
1078 editor->insertText(text, 0);
1081 void WebFrameImpl::setMarkedText(
1082 const WebString& text, unsigned location, unsigned length)
1084 Editor* editor = frame()->editor();
1086 Vector<CompositionUnderline> decorations;
1087 editor->setComposition(text, decorations, location, length);
1090 void WebFrameImpl::unmarkText()
1092 frame()->editor()->confirmCompositionWithoutDisturbingSelection();
1095 bool WebFrameImpl::hasMarkedText() const
1097 return frame()->editor()->hasComposition();
1100 WebRange WebFrameImpl::markedRange() const
1102 return frame()->editor()->compositionRange();
1105 bool WebFrameImpl::firstRectForCharacterRange(unsigned location, unsigned length, WebRect& rect) const
1107 if ((location + length < location) && (location + length))
1110 Element* selectionRoot = frame()->selection()->rootEditableElement();
1111 Element* scope = selectionRoot ? selectionRoot : frame()->document()->documentElement();
1112 RefPtr<Range> range = TextIterator::rangeFromLocationAndLength(scope, location, length);
1115 IntRect intRect = frame()->editor()->firstRectForRange(range.get());
1116 rect = WebRect(intRect);
1117 rect = frame()->view()->contentsToWindow(rect);
1122 size_t WebFrameImpl::characterIndexForPoint(const WebPoint& webPoint) const
1127 IntPoint point = frame()->view()->windowToContents(webPoint);
1128 HitTestResult result = frame()->eventHandler()->hitTestResultAtPoint(point, false);
1129 RefPtr<Range> range = frame()->rangeForPoint(result.point());
1133 size_t location, length;
1134 TextIterator::locationAndLengthFromRange(range.get(), location, length);
1138 bool WebFrameImpl::executeCommand(const WebString& name, const WebNode& node)
1142 if (name.length() <= 2)
1145 // Since we don't have NSControl, we will convert the format of command
1146 // string and call the function on Editor directly.
1147 String command = name;
1149 // Make sure the first letter is upper case.
1150 command.replace(0, 1, command.substring(0, 1).upper());
1152 // Remove the trailing ':' if existing.
1153 if (command[command.length() - 1] == UChar(':'))
1154 command = command.substring(0, command.length() - 1);
1156 if (command == "Copy") {
1157 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1158 if (!pluginContainer)
1159 pluginContainer = pluginContainerFromNode(node);
1160 if (pluginContainer) {
1161 pluginContainer->copy();
1168 // Specially handling commands that Editor::execCommand does not directly
1170 if (command == "DeleteToEndOfParagraph") {
1171 Editor* editor = frame()->editor();
1172 if (!editor->deleteWithDirection(DirectionForward,
1176 editor->deleteWithDirection(DirectionForward,
1177 CharacterGranularity,
1181 } else if (command == "Indent")
1182 frame()->editor()->indent();
1183 else if (command == "Outdent")
1184 frame()->editor()->outdent();
1185 else if (command == "DeleteBackward")
1186 rv = frame()->editor()->command(AtomicString("BackwardDelete")).execute();
1187 else if (command == "DeleteForward")
1188 rv = frame()->editor()->command(AtomicString("ForwardDelete")).execute();
1189 else if (command == "AdvanceToNextMisspelling") {
1190 // False must be passed here, or the currently selected word will never be
1192 frame()->editor()->advanceToNextMisspelling(false);
1193 } else if (command == "ToggleSpellPanel")
1194 frame()->editor()->showSpellingGuessPanel();
1196 rv = frame()->editor()->command(command).execute();
1200 bool WebFrameImpl::executeCommand(const WebString& name, const WebString& value)
1203 String webName = name;
1205 // moveToBeginningOfDocument and moveToEndfDocument are only handled by WebKit
1206 // for editable nodes.
1207 if (!frame()->editor()->canEdit() && webName == "moveToBeginningOfDocument")
1208 return viewImpl()->propagateScroll(ScrollUp, ScrollByDocument);
1210 if (!frame()->editor()->canEdit() && webName == "moveToEndOfDocument")
1211 return viewImpl()->propagateScroll(ScrollDown, ScrollByDocument);
1213 return frame()->editor()->command(webName).execute(value);
1216 bool WebFrameImpl::isCommandEnabled(const WebString& name) const
1219 return frame()->editor()->command(name).isEnabled();
1222 void WebFrameImpl::enableContinuousSpellChecking(bool enable)
1224 if (enable == isContinuousSpellCheckingEnabled())
1226 frame()->editor()->toggleContinuousSpellChecking();
1229 bool WebFrameImpl::isContinuousSpellCheckingEnabled() const
1231 return frame()->editor()->isContinuousSpellCheckingEnabled();
1234 bool WebFrameImpl::hasSelection() const
1236 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1237 if (pluginContainer)
1238 return pluginContainer->plugin()->hasSelection();
1240 // frame()->selection()->isNone() never returns true.
1241 return (frame()->selection()->start() != frame()->selection()->end());
1244 WebRange WebFrameImpl::selectionRange() const
1246 return frame()->selection()->toNormalizedRange();
1249 WebString WebFrameImpl::selectionAsText() const
1251 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1252 if (pluginContainer)
1253 return pluginContainer->plugin()->selectionAsText();
1255 RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1259 String text = range->text();
1261 replaceNewlinesWithWindowsStyleNewlines(text);
1263 replaceNBSPWithSpace(text);
1267 WebString WebFrameImpl::selectionAsMarkup() const
1269 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1270 if (pluginContainer)
1271 return pluginContainer->plugin()->selectionAsMarkup();
1273 RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1277 return createMarkup(range.get(), 0);
1280 void WebFrameImpl::selectWordAroundPosition(Frame* frame, VisiblePosition pos)
1282 VisibleSelection selection(pos);
1283 selection.expandUsingGranularity(WordGranularity);
1285 if (frame->selection()->shouldChangeSelection(selection)) {
1286 TextGranularity granularity = selection.isRange() ? WordGranularity : CharacterGranularity;
1287 frame->selection()->setSelection(selection, granularity);
1291 bool WebFrameImpl::selectWordAroundCaret()
1293 FrameSelection* selection = frame()->selection();
1294 ASSERT(!selection->isNone());
1295 if (selection->isNone() || selection->isRange())
1297 selectWordAroundPosition(frame(), selection->selection().visibleStart());
1301 void WebFrameImpl::selectRange(const WebPoint& start, const WebPoint& end)
1303 VisibleSelection selection(visiblePositionForWindowPoint(start),
1304 visiblePositionForWindowPoint(end));
1306 if (frame()->selection()->shouldChangeSelection(selection))
1307 frame()->selection()->setSelection(selection, CharacterGranularity);
1310 VisiblePosition WebFrameImpl::visiblePositionForWindowPoint(const WebPoint& point)
1312 HitTestRequest::HitTestRequestType hitType = HitTestRequest::MouseMove;
1313 hitType |= HitTestRequest::ReadOnly;
1314 hitType |= HitTestRequest::Active;
1315 HitTestRequest request(hitType);
1316 FrameView* view = frame()->view();
1317 HitTestResult result(view->windowToContents(
1318 view->convertFromContainingWindow(IntPoint(point.x, point.y))));
1320 frame()->document()->renderView()->layer()->hitTest(request, result);
1322 // Matching the logic in MouseEventWithHitTestResults::targetNode()
1323 Node* node = result.innerNode();
1325 return VisiblePosition();
1326 Element* element = node->parentElement();
1327 if (!node->inDocument() && element && element->inDocument())
1330 return node->renderer()->positionForPoint(result.localPoint());
1333 int WebFrameImpl::printBegin(const WebSize& pageSize,
1334 const WebNode& constrainToNode,
1336 bool* useBrowserOverlays)
1338 ASSERT(!frame()->document()->isFrameSet());
1339 WebPluginContainerImpl* pluginContainer = 0;
1340 if (constrainToNode.isNull()) {
1341 // If this is a plugin document, check if the plugin supports its own
1342 // printing. If it does, we will delegate all printing to that.
1343 pluginContainer = pluginContainerFromFrame(frame());
1345 // We only support printing plugin nodes for now.
1346 pluginContainer = pluginContainerFromNode(constrainToNode);
1349 if (pluginContainer && pluginContainer->supportsPaginatedPrint())
1350 m_printContext = adoptPtr(new ChromePluginPrintContext(frame(), pluginContainer, printerDPI));
1352 m_printContext = adoptPtr(new ChromePrintContext(frame()));
1354 FloatRect rect(0, 0, static_cast<float>(pageSize.width),
1355 static_cast<float>(pageSize.height));
1356 m_printContext->begin(rect.width(), rect.height());
1358 // We ignore the overlays calculation for now since they are generated in the
1359 // browser. pageHeight is actually an output parameter.
1360 m_printContext->computePageRects(rect, 0, 0, 1.0, pageHeight);
1361 if (useBrowserOverlays)
1362 *useBrowserOverlays = m_printContext->shouldUseBrowserOverlays();
1364 return m_printContext->pageCount();
1367 float WebFrameImpl::getPrintPageShrink(int page)
1369 // Ensure correct state.
1370 if (!m_printContext.get() || page < 0) {
1371 ASSERT_NOT_REACHED();
1375 return m_printContext->getPageShrink(page);
1378 float WebFrameImpl::printPage(int page, WebCanvas* canvas)
1380 // Ensure correct state.
1381 if (!m_printContext.get() || page < 0 || !frame() || !frame()->document()) {
1382 ASSERT_NOT_REACHED();
1386 GraphicsContextBuilder builder(canvas);
1387 GraphicsContext& gc = builder.context();
1388 #if WEBKIT_USING_SKIA
1389 gc.platformContext()->setPrinting(true);
1392 return m_printContext->spoolPage(gc, page);
1395 void WebFrameImpl::printEnd()
1397 ASSERT(m_printContext.get());
1398 if (m_printContext.get())
1399 m_printContext->end();
1400 m_printContext.clear();
1403 bool WebFrameImpl::isPageBoxVisible(int pageIndex)
1405 return frame()->document()->isPageBoxVisible(pageIndex);
1408 void WebFrameImpl::pageSizeAndMarginsInPixels(int pageIndex,
1415 IntSize size(pageSize.width, pageSize.height);
1416 frame()->document()->pageSizeAndMarginsInPixels(pageIndex,
1425 bool WebFrameImpl::find(int identifier,
1426 const WebString& searchText,
1427 const WebFindOptions& options,
1428 bool wrapWithinFrame,
1429 WebRect* selectionRect)
1431 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
1433 if (!options.findNext)
1434 frame()->page()->unmarkAllTextMatches();
1436 setMarkerActive(m_activeMatch.get(), false); // Active match is changing.
1438 // Starts the search from the current selection.
1439 bool startInSelection = true;
1441 // If the user has selected something since the last Find operation we want
1442 // to start from there. Otherwise, we start searching from where the last Find
1443 // operation left off (either a Find or a FindNext operation).
1444 VisibleSelection selection(frame()->selection()->selection());
1445 bool activeSelection = !selection.isNone();
1446 if (!activeSelection && m_activeMatch) {
1447 selection = VisibleSelection(m_activeMatch.get());
1448 frame()->selection()->setSelection(selection);
1451 ASSERT(frame() && frame()->view());
1452 bool found = frame()->editor()->findString(
1453 searchText, options.forward, options.matchCase, wrapWithinFrame,
1456 // Store which frame was active. This will come in handy later when we
1457 // change the active match ordinal below.
1458 WebFrameImpl* oldActiveFrame = mainFrameImpl->m_activeMatchFrame;
1459 // Set this frame as the active frame (the one with the active highlight).
1460 mainFrameImpl->m_activeMatchFrame = this;
1462 // We found something, so we can now query the selection for its position.
1463 VisibleSelection newSelection(frame()->selection()->selection());
1464 IntRect currSelectionRect;
1466 // If we thought we found something, but it couldn't be selected (perhaps
1467 // because it was marked -webkit-user-select: none), we can't set it to
1468 // be active but we still continue searching. This matches Safari's
1469 // behavior, including some oddities when selectable and un-selectable text
1470 // are mixed on a page: see https://bugs.webkit.org/show_bug.cgi?id=19127.
1471 if (newSelection.isNone() || (newSelection.start() == newSelection.end()))
1474 m_activeMatch = newSelection.toNormalizedRange();
1475 currSelectionRect = m_activeMatch->boundingBox();
1476 setMarkerActive(m_activeMatch.get(), true); // Active.
1477 // WebKit draws the highlighting for all matches.
1478 executeCommand(WebString::fromUTF8("Unselect"));
1481 // Make sure no node is focused. See http://crbug.com/38700.
1482 frame()->document()->setFocusedNode(0);
1484 if (!options.findNext || activeSelection) {
1485 // This is either a Find operation or a Find-next from a new start point
1486 // due to a selection, so we set the flag to ask the scoping effort
1487 // to find the active rect for us so we can update the ordinal (n of m).
1488 m_locatingActiveRect = true;
1490 if (oldActiveFrame != this) {
1491 // If the active frame has changed it means that we have a multi-frame
1492 // page and we just switch to searching in a new frame. Then we just
1493 // want to reset the index.
1494 if (options.forward)
1495 m_activeMatchIndex = 0;
1497 m_activeMatchIndex = m_lastMatchCount - 1;
1499 // We are still the active frame, so increment (or decrement) the
1500 // |m_activeMatchIndex|, wrapping if needed (on single frame pages).
1501 options.forward ? ++m_activeMatchIndex : --m_activeMatchIndex;
1502 if (m_activeMatchIndex + 1 > m_lastMatchCount)
1503 m_activeMatchIndex = 0;
1504 if (m_activeMatchIndex == -1)
1505 m_activeMatchIndex = m_lastMatchCount - 1;
1507 if (selectionRect) {
1508 *selectionRect = frameView()->contentsToWindow(currSelectionRect);
1509 reportFindInPageSelection(*selectionRect, m_activeMatchIndex + 1, identifier);
1513 // Nothing was found in this frame.
1516 // Erase all previous tickmarks and highlighting.
1517 invalidateArea(InvalidateAll);
1523 void WebFrameImpl::stopFinding(bool clearSelection)
1525 if (!clearSelection)
1526 setFindEndstateFocusAndSelection();
1527 cancelPendingScopingEffort();
1529 // Remove all markers for matches found and turn off the highlighting.
1530 frame()->document()->markers()->removeMarkers(DocumentMarker::TextMatch);
1531 frame()->editor()->setMarkedTextMatchesAreHighlighted(false);
1533 // Let the frame know that we don't want tickmarks or highlighting anymore.
1534 invalidateArea(InvalidateAll);
1537 void WebFrameImpl::scopeStringMatches(int identifier,
1538 const WebString& searchText,
1539 const WebFindOptions& options,
1542 if (!shouldScopeMatches(searchText))
1545 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
1548 // This is a brand new search, so we need to reset everything.
1549 // Scoping is just about to begin.
1550 m_scopingComplete = false;
1551 // Clear highlighting for this frame.
1552 if (frame()->editor()->markedTextMatchesAreHighlighted())
1553 frame()->page()->unmarkAllTextMatches();
1554 // Clear the counters from last operation.
1555 m_lastMatchCount = 0;
1556 m_nextInvalidateAfter = 0;
1558 m_resumeScopingFromRange = 0;
1560 mainFrameImpl->m_framesScopingCount++;
1562 // Now, defer scoping until later to allow find operation to finish quickly.
1563 scopeStringMatchesSoon(
1567 false); // false=we just reset, so don't do it again.
1571 RefPtr<Range> searchRange(rangeOfContents(frame()->document()));
1573 Node* originalEndContainer = searchRange->endContainer();
1574 int originalEndOffset = searchRange->endOffset();
1576 ExceptionCode ec = 0, ec2 = 0;
1577 if (m_resumeScopingFromRange.get()) {
1578 // This is a continuation of a scoping operation that timed out and didn't
1579 // complete last time around, so we should start from where we left off.
1580 searchRange->setStart(m_resumeScopingFromRange->startContainer(),
1581 m_resumeScopingFromRange->startOffset(ec2) + 1,
1584 if (ec2) // A non-zero |ec| happens when navigating during search.
1585 ASSERT_NOT_REACHED();
1590 // This timeout controls how long we scope before releasing control. This
1591 // value does not prevent us from running for longer than this, but it is
1592 // periodically checked to see if we have exceeded our allocated time.
1593 const double maxScopingDuration = 0.1; // seconds
1596 bool timedOut = false;
1597 double startTime = currentTime();
1599 // Find next occurrence of the search string.
1600 // FIXME: (http://b/1088245) This WebKit operation may run for longer
1601 // than the timeout value, and is not interruptible as it is currently
1602 // written. We may need to rewrite it with interruptibility in mind, or
1603 // find an alternative.
1604 RefPtr<Range> resultRange(findPlainText(searchRange.get(),
1606 options.matchCase ? 0 : CaseInsensitive));
1607 if (resultRange->collapsed(ec)) {
1608 if (!resultRange->startContainer()->isInShadowTree())
1611 searchRange->setStartAfter(
1612 resultRange->startContainer()->shadowAncestorNode(), ec);
1613 searchRange->setEnd(originalEndContainer, originalEndOffset, ec);
1617 // Only treat the result as a match if it is visible
1618 if (frame()->editor()->insideVisibleArea(resultRange.get())) {
1621 // Catch a special case where Find found something but doesn't know what
1622 // the bounding box for it is. In this case we set the first match we find
1623 // as the active rect.
1624 IntRect resultBounds = resultRange->boundingBox();
1625 IntRect activeSelectionRect;
1626 if (m_locatingActiveRect) {
1627 activeSelectionRect = m_activeMatch.get() ?
1628 m_activeMatch->boundingBox() : resultBounds;
1631 // If the Find function found a match it will have stored where the
1632 // match was found in m_activeSelectionRect on the current frame. If we
1633 // find this rect during scoping it means we have found the active
1635 bool foundActiveMatch = false;
1636 if (m_locatingActiveRect && (activeSelectionRect == resultBounds)) {
1637 // We have found the active tickmark frame.
1638 mainFrameImpl->m_activeMatchFrame = this;
1639 foundActiveMatch = true;
1640 // We also know which tickmark is active now.
1641 m_activeMatchIndex = matchCount - 1;
1642 // To stop looking for the active tickmark, we set this flag.
1643 m_locatingActiveRect = false;
1645 // Notify browser of new location for the selected rectangle.
1646 reportFindInPageSelection(
1647 frameView()->contentsToWindow(resultBounds),
1648 m_activeMatchIndex + 1,
1652 addMarker(resultRange.get(), foundActiveMatch);
1655 // Set the new start for the search range to be the end of the previous
1656 // result range. There is no need to use a VisiblePosition here,
1657 // since findPlainText will use a TextIterator to go over the visible
1659 searchRange->setStart(resultRange->endContainer(ec), resultRange->endOffset(ec), ec);
1661 Node* shadowTreeRoot = searchRange->shadowTreeRootNode();
1662 if (searchRange->collapsed(ec) && shadowTreeRoot)
1663 searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), ec);
1665 m_resumeScopingFromRange = resultRange;
1666 timedOut = (currentTime() - startTime) >= maxScopingDuration;
1667 } while (!timedOut);
1669 // Remember what we search for last time, so we can skip searching if more
1670 // letters are added to the search string (and last outcome was 0).
1671 m_lastSearchString = searchText;
1673 if (matchCount > 0) {
1674 frame()->editor()->setMarkedTextMatchesAreHighlighted(true);
1676 m_lastMatchCount += matchCount;
1678 // Let the mainframe know how much we found during this pass.
1679 mainFrameImpl->increaseMatchCount(matchCount, identifier);
1683 // If we found anything during this pass, we should redraw. However, we
1684 // don't want to spam too much if the page is extremely long, so if we
1685 // reach a certain point we start throttling the redraw requests.
1687 invalidateIfNecessary();
1689 // Scoping effort ran out of time, lets ask for another time-slice.
1690 scopeStringMatchesSoon(
1694 false); // don't reset.
1695 return; // Done for now, resume work later.
1698 // This frame has no further scoping left, so it is done. Other frames might,
1699 // of course, continue to scope matches.
1700 m_scopingComplete = true;
1701 mainFrameImpl->m_framesScopingCount--;
1703 // If this is the last frame to finish scoping we need to trigger the final
1704 // update to be sent.
1705 if (!mainFrameImpl->m_framesScopingCount)
1706 mainFrameImpl->increaseMatchCount(0, identifier);
1708 // This frame is done, so show any scrollbar tickmarks we haven't drawn yet.
1709 invalidateArea(InvalidateScrollbar);
1712 void WebFrameImpl::cancelPendingScopingEffort()
1714 deleteAllValues(m_deferredScopingWork);
1715 m_deferredScopingWork.clear();
1717 m_activeMatchIndex = -1;
1720 void WebFrameImpl::increaseMatchCount(int count, int identifier)
1722 // This function should only be called on the mainframe.
1725 m_totalMatchCount += count;
1727 // Update the UI with the latest findings.
1729 client()->reportFindInPageMatchCount(identifier, m_totalMatchCount, !m_framesScopingCount);
1732 void WebFrameImpl::reportFindInPageSelection(const WebRect& selectionRect,
1733 int activeMatchOrdinal,
1736 // Update the UI with the latest selection rect.
1738 client()->reportFindInPageSelection(identifier, ordinalOfFirstMatchForFrame(this) + activeMatchOrdinal, selectionRect);
1741 void WebFrameImpl::resetMatchCount()
1743 m_totalMatchCount = 0;
1744 m_framesScopingCount = 0;
1747 WebString WebFrameImpl::contentAsText(size_t maxChars) const
1753 frameContentAsPlainText(maxChars, m_frame, &text);
1754 return String::adopt(text);
1757 WebString WebFrameImpl::contentAsMarkup() const
1759 return createFullMarkup(m_frame->document());
1762 WebString WebFrameImpl::renderTreeAsText(bool showDebugInfo) const
1764 RenderAsTextBehavior behavior = RenderAsTextBehaviorNormal;
1766 if (showDebugInfo) {
1767 behavior |= RenderAsTextShowCompositedLayers
1768 | RenderAsTextShowAddresses
1769 | RenderAsTextShowIDAndClass
1770 | RenderAsTextShowLayerNesting;
1773 return externalRepresentation(m_frame, behavior);
1776 WebString WebFrameImpl::counterValueForElementById(const WebString& id) const
1781 Element* element = m_frame->document()->getElementById(id);
1785 return counterValueForElement(element);
1788 WebString WebFrameImpl::markerTextForListItem(const WebElement& webElement) const
1790 return WebCore::markerTextForListItem(const_cast<Element*>(webElement.constUnwrap<Element>()));
1793 int WebFrameImpl::pageNumberForElementById(const WebString& id,
1794 float pageWidthInPixels,
1795 float pageHeightInPixels) const
1800 Element* element = m_frame->document()->getElementById(id);
1804 FloatSize pageSize(pageWidthInPixels, pageHeightInPixels);
1805 return PrintContext::pageNumberForElement(element, pageSize);
1808 WebRect WebFrameImpl::selectionBoundsRect() const
1811 return IntRect(frame()->selection()->bounds(false));
1816 bool WebFrameImpl::selectionStartHasSpellingMarkerFor(int from, int length) const
1820 return m_frame->editor()->selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length);
1823 bool WebFrameImpl::pauseSVGAnimation(const WebString& animationId, double time, const WebString& elementId)
1831 Document* document = m_frame->document();
1832 if (!document || !document->svgExtensions())
1835 Node* coreNode = document->getElementById(animationId);
1836 if (!coreNode || !SVGSMILElement::isSMILElement(coreNode))
1839 return document->accessSVGExtensions()->sampleAnimationAtTime(elementId, static_cast<SVGSMILElement*>(coreNode), time);
1843 WebString WebFrameImpl::layerTreeAsText(bool showDebugInfo) const
1847 return WebString(m_frame->layerTreeAsText(showDebugInfo));
1850 // WebFrameImpl public ---------------------------------------------------------
1852 PassRefPtr<WebFrameImpl> WebFrameImpl::create(WebFrameClient* client)
1854 return adoptRef(new WebFrameImpl(client));
1857 WebFrameImpl::WebFrameImpl(WebFrameClient* client)
1858 : m_frameLoaderClient(this)
1860 , m_activeMatchFrame(0)
1861 , m_activeMatchIndex(-1)
1862 , m_locatingActiveRect(false)
1863 , m_resumeScopingFromRange(0)
1864 , m_lastMatchCount(-1)
1865 , m_totalMatchCount(-1)
1866 , m_framesScopingCount(-1)
1867 , m_scopingComplete(false)
1868 , m_nextInvalidateAfter(0)
1869 , m_animationController(this)
1870 , m_identifier(generateFrameIdentifier())
1871 , m_inSameDocumentHistoryLoad(false)
1873 PlatformBridge::incrementStatsCounter(webFrameActiveCount);
1877 WebFrameImpl::~WebFrameImpl()
1879 PlatformBridge::decrementStatsCounter(webFrameActiveCount);
1882 cancelPendingScopingEffort();
1883 clearPasswordListeners();
1886 void WebFrameImpl::initializeAsMainFrame(WebViewImpl* webViewImpl)
1888 RefPtr<Frame> frame = Frame::create(webViewImpl->page(), 0, &m_frameLoaderClient);
1889 m_frame = frame.get();
1891 // Add reference on behalf of FrameLoader. See comments in
1892 // WebFrameLoaderClient::frameLoaderDestroyed for more info.
1895 // We must call init() after m_frame is assigned because it is referenced
1900 PassRefPtr<Frame> WebFrameImpl::createChildFrame(
1901 const FrameLoadRequest& request, HTMLFrameOwnerElement* ownerElement)
1903 RefPtr<WebFrameImpl> webframe(adoptRef(new WebFrameImpl(m_client)));
1905 // Add an extra ref on behalf of the Frame/FrameLoader, which references the
1906 // WebFrame via the FrameLoaderClient interface. See the comment at the top
1907 // of this file for more info.
1910 RefPtr<Frame> childFrame = Frame::create(
1911 m_frame->page(), ownerElement, &webframe->m_frameLoaderClient);
1912 webframe->m_frame = childFrame.get();
1914 childFrame->tree()->setName(request.frameName());
1916 m_frame->tree()->appendChild(childFrame);
1918 // Frame::init() can trigger onload event in the parent frame,
1919 // which may detach this frame and trigger a null-pointer access
1920 // in FrameTree::removeChild. Move init() after appendChild call
1921 // so that webframe->mFrame is in the tree before triggering
1922 // onload event handler.
1923 // Because the event handler may set webframe->mFrame to null,
1924 // it is necessary to check the value after calling init() and
1925 // return without loading URL.
1927 childFrame->init(); // create an empty document
1928 if (!childFrame->tree()->parent())
1931 m_frame->loader()->loadURLIntoChildFrame(
1932 request.resourceRequest().url(),
1933 request.resourceRequest().httpReferrer(),
1936 // A synchronous navigation (about:blank) would have already processed
1937 // onload, so it is possible for the frame to have already been destroyed by
1938 // script in the page.
1939 if (!childFrame->tree()->parent())
1942 return childFrame.release();
1945 void WebFrameImpl::layout()
1947 // layout this frame
1948 FrameView* view = m_frame->view();
1950 view->updateLayoutAndStyleIfNeededRecursive();
1953 void WebFrameImpl::paintWithContext(GraphicsContext& gc, const WebRect& rect)
1955 IntRect dirtyRect(rect);
1957 if (m_frame->document() && frameView()) {
1959 frameView()->paint(&gc, dirtyRect);
1960 if (viewImpl()->pageOverlay())
1961 viewImpl()->pageOverlay()->paintWebFrame(gc);
1963 gc.fillRect(dirtyRect, Color::white, ColorSpaceDeviceRGB);
1967 void WebFrameImpl::paint(WebCanvas* canvas, const WebRect& rect)
1971 paintWithContext(GraphicsContextBuilder(canvas).context(), rect);
1974 void WebFrameImpl::createFrameView()
1976 ASSERT(m_frame); // If m_frame doesn't exist, we probably didn't init properly.
1978 Page* page = m_frame->page();
1980 ASSERT(page->mainFrame());
1982 bool isMainFrame = m_frame == page->mainFrame();
1983 bool useFixedLayout = false;
1984 IntSize fixedLayoutSize;
1985 if (isMainFrame && m_frame->view()) {
1986 m_frame->view()->setParentVisible(false);
1987 // Save the fixed layout information before destroying the
1988 // existing FrameView of this frame.
1989 useFixedLayout = m_frame->view()->useFixedLayout();
1990 fixedLayoutSize = m_frame->view()->fixedLayoutSize();
1993 m_frame->setView(0);
1995 WebViewImpl* webView = viewImpl();
1997 RefPtr<FrameView> view;
1999 view = FrameView::create(m_frame, webView->size());
2001 view = FrameView::create(m_frame);
2003 m_frame->setView(view);
2005 if (webView->isTransparent())
2006 view->setTransparent(true);
2008 // FIXME: The Mac code has a comment about this possibly being unnecessary.
2009 // See installInFrame in WebCoreFrameBridge.mm
2010 if (m_frame->ownerRenderer())
2011 m_frame->ownerRenderer()->setWidget(view.get());
2013 if (HTMLFrameOwnerElement* owner = m_frame->ownerElement())
2014 view->setCanHaveScrollbars(owner->scrollingMode() != ScrollbarAlwaysOff);
2017 view->setParentVisible(true);
2019 #if ENABLE(GESTURE_RECOGNIZER)
2020 webView->resetGestureRecognizer();
2023 // Restore the saved fixed layout information.
2024 view->setUseFixedLayout(useFixedLayout);
2025 view->setFixedLayoutSize(fixedLayoutSize);
2028 WebFrameImpl* WebFrameImpl::fromFrame(Frame* frame)
2033 return static_cast<FrameLoaderClientImpl*>(frame->loader()->client())->webFrame();
2036 WebFrameImpl* WebFrameImpl::fromFrameOwnerElement(Element* element)
2039 || !element->isFrameOwnerElement()
2040 || (!element->hasTagName(HTMLNames::iframeTag)
2041 && !element->hasTagName(HTMLNames::frameTag)))
2044 HTMLFrameOwnerElement* frameElement =
2045 static_cast<HTMLFrameOwnerElement*>(element);
2046 return fromFrame(frameElement->contentFrame());
2049 WebViewImpl* WebFrameImpl::viewImpl() const
2054 return WebViewImpl::fromPage(m_frame->page());
2057 WebDataSourceImpl* WebFrameImpl::dataSourceImpl() const
2059 return static_cast<WebDataSourceImpl*>(dataSource());
2062 WebDataSourceImpl* WebFrameImpl::provisionalDataSourceImpl() const
2064 return static_cast<WebDataSourceImpl*>(provisionalDataSource());
2067 void WebFrameImpl::setFindEndstateFocusAndSelection()
2069 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
2071 if (this == mainFrameImpl->activeMatchFrame() && m_activeMatch.get()) {
2072 // If the user has set the selection since the match was found, we
2073 // don't focus anything.
2074 VisibleSelection selection(frame()->selection()->selection());
2075 if (!selection.isNone())
2078 // Try to find the first focusable node up the chain, which will, for
2079 // example, focus links if we have found text within the link.
2080 Node* node = m_activeMatch->firstNode();
2081 while (node && !node->isFocusable() && node != frame()->document())
2082 node = node->parentNode();
2084 if (node && node != frame()->document()) {
2085 // Found a focusable parent node. Set focus to it.
2086 frame()->document()->setFocusedNode(node);
2090 // Iterate over all the nodes in the range until we find a focusable node.
2091 // This, for example, sets focus to the first link if you search for
2092 // text and text that is within one or more links.
2093 node = m_activeMatch->firstNode();
2094 while (node && node != m_activeMatch->pastLastNode()) {
2095 if (node->isFocusable()) {
2096 frame()->document()->setFocusedNode(node);
2099 node = node->traverseNextNode();
2102 // No node related to the active match was focusable, so set the
2103 // active match as the selection (so that when you end the Find session,
2104 // you'll have the last thing you found highlighted) and make sure that
2105 // we have nothing focused (otherwise you might have text selected but
2106 // a link focused, which is weird).
2107 frame()->selection()->setSelection(m_activeMatch.get());
2108 frame()->document()->setFocusedNode(0);
2112 void WebFrameImpl::didFail(const ResourceError& error, bool wasProvisional)
2116 WebURLError webError = error;
2118 client()->didFailProvisionalLoad(this, webError);
2120 client()->didFailLoad(this, webError);
2123 void WebFrameImpl::setCanHaveScrollbars(bool canHaveScrollbars)
2125 m_frame->view()->setCanHaveScrollbars(canHaveScrollbars);
2128 bool WebFrameImpl::registerPasswordListener(
2129 WebInputElement inputElement,
2130 WebPasswordAutocompleteListener* listener)
2132 RefPtr<HTMLInputElement> element(inputElement.unwrap<HTMLInputElement>());
2133 if (!m_passwordListeners.add(element, listener).second) {
2140 void WebFrameImpl::notifiyPasswordListenerOfAutocomplete(
2141 const WebInputElement& inputElement)
2143 const HTMLInputElement* element = inputElement.constUnwrap<HTMLInputElement>();
2144 WebPasswordAutocompleteListener* listener = getPasswordListener(element);
2145 // Password listeners need to autocomplete other fields that depend on the
2146 // input element with autofill suggestions.
2148 listener->performInlineAutocomplete(element->value(), false, false);
2151 WebPasswordAutocompleteListener* WebFrameImpl::getPasswordListener(
2152 const HTMLInputElement* inputElement)
2154 return m_passwordListeners.get(RefPtr<HTMLInputElement>(const_cast<HTMLInputElement*>(inputElement)));
2157 // WebFrameImpl private --------------------------------------------------------
2159 void WebFrameImpl::closing()
2164 void WebFrameImpl::invalidateArea(AreaToInvalidate area)
2166 ASSERT(frame() && frame()->view());
2167 FrameView* view = frame()->view();
2169 if ((area & InvalidateAll) == InvalidateAll)
2170 view->invalidateRect(view->frameRect());
2172 if ((area & InvalidateContentArea) == InvalidateContentArea) {
2173 IntRect contentArea(
2174 view->x(), view->y(), view->visibleWidth(), view->visibleHeight());
2175 IntRect frameRect = view->frameRect();
2176 contentArea.move(-frameRect.x(), -frameRect.y());
2177 view->invalidateRect(contentArea);
2180 if ((area & InvalidateScrollbar) == InvalidateScrollbar) {
2181 // Invalidate the vertical scroll bar region for the view.
2182 Scrollbar* scrollbar = view->verticalScrollbar();
2184 scrollbar->invalidate();
2189 void WebFrameImpl::addMarker(Range* range, bool activeMatch)
2191 frame()->document()->markers()->addTextMatchMarker(range, activeMatch);
2194 void WebFrameImpl::setMarkerActive(Range* range, bool active)
2196 WebCore::ExceptionCode ec;
2197 if (!range || range->collapsed(ec))
2200 frame()->document()->markers()->setMarkersActive(range, active);
2203 int WebFrameImpl::ordinalOfFirstMatchForFrame(WebFrameImpl* frame) const
2206 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
2207 // Iterate from the main frame up to (but not including) |frame| and
2208 // add up the number of matches found so far.
2209 for (WebFrameImpl* it = mainFrameImpl;
2211 it = static_cast<WebFrameImpl*>(it->traverseNext(true))) {
2212 if (it->m_lastMatchCount > 0)
2213 ordinal += it->m_lastMatchCount;
2218 bool WebFrameImpl::shouldScopeMatches(const String& searchText)
2220 // Don't scope if we can't find a frame or a view or if the frame is not visible.
2221 // The user may have closed the tab/application, so abort.
2222 if (!frame() || !frame()->view() || !hasVisibleContent())
2225 ASSERT(frame()->document() && frame()->view());
2227 // If the frame completed the scoping operation and found 0 matches the last
2228 // time it was searched, then we don't have to search it again if the user is
2229 // just adding to the search string or sending the same search string again.
2230 if (m_scopingComplete && !m_lastSearchString.isEmpty() && !m_lastMatchCount) {
2231 // Check to see if the search string prefixes match.
2232 String previousSearchPrefix =
2233 searchText.substring(0, m_lastSearchString.length());
2235 if (previousSearchPrefix == m_lastSearchString)
2236 return false; // Don't search this frame, it will be fruitless.
2242 void WebFrameImpl::scopeStringMatchesSoon(int identifier, const WebString& searchText,
2243 const WebFindOptions& options, bool reset)
2245 m_deferredScopingWork.append(new DeferredScopeStringMatches(
2246 this, identifier, searchText, options, reset));
2249 void WebFrameImpl::callScopeStringMatches(DeferredScopeStringMatches* caller,
2250 int identifier, const WebString& searchText,
2251 const WebFindOptions& options, bool reset)
2253 m_deferredScopingWork.remove(m_deferredScopingWork.find(caller));
2255 scopeStringMatches(identifier, searchText, options, reset);
2257 // This needs to happen last since searchText is passed by reference.
2261 void WebFrameImpl::invalidateIfNecessary()
2263 if (m_lastMatchCount > m_nextInvalidateAfter) {
2264 // FIXME: (http://b/1088165) Optimize the drawing of the tickmarks and
2265 // remove this. This calculation sets a milestone for when next to
2266 // invalidate the scrollbar and the content area. We do this so that we
2267 // don't spend too much time drawing the scrollbar over and over again.
2268 // Basically, up until the first 500 matches there is no throttle.
2269 // After the first 500 matches, we set set the milestone further and
2270 // further out (750, 1125, 1688, 2K, 3K).
2271 static const int startSlowingDownAfter = 500;
2272 static const int slowdown = 750;
2273 int i = (m_lastMatchCount / startSlowingDownAfter);
2274 m_nextInvalidateAfter += i * slowdown;
2276 invalidateArea(InvalidateScrollbar);
2280 void WebFrameImpl::clearPasswordListeners()
2282 deleteAllValues(m_passwordListeners);
2283 m_passwordListeners.clear();
2286 void WebFrameImpl::loadJavaScriptURL(const KURL& url)
2288 // This is copied from ScriptController::executeIfJavaScriptURL.
2289 // Unfortunately, we cannot just use that method since it is private, and
2290 // it also doesn't quite behave as we require it to for bookmarklets. The
2291 // key difference is that we need to suppress loading the string result
2292 // from evaluating the JS URL if executing the JS URL resulted in a
2293 // location change. We also allow a JS URL to be loaded even if scripts on
2294 // the page are otherwise disabled.
2296 if (!m_frame->document() || !m_frame->page())
2299 // Protect privileged pages against bookmarklets and other javascript manipulations.
2300 if (SchemeRegistry::shouldTreatURLSchemeAsNotAllowingJavascriptURLs(m_frame->document()->url().protocol()))
2303 String script = decodeURLEscapeSequences(url.string().substring(strlen("javascript:")));
2304 ScriptValue result = m_frame->script()->executeScript(script, true);
2306 String scriptResult;
2307 if (!result.getString(scriptResult))
2310 if (!m_frame->navigationScheduler()->locationChangePending())
2311 m_frame->document()->loader()->writer()->replaceDocument(scriptResult);
2314 } // namespace WebKit