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 "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"
148 #include "WebPerformance.h"
149 #include "WebPlugin.h"
150 #include "WebPluginContainerImpl.h"
151 #include "WebPoint.h"
152 #include "WebRange.h"
154 #include "WebScriptSource.h"
155 #include "WebSecurityOrigin.h"
157 #include "WebURLError.h"
158 #include "WebVector.h"
159 #include "WebViewImpl.h"
160 #include "XPathResult.h"
164 #include <wtf/CurrentTime.h>
166 #if OS(UNIX) && !OS(DARWIN) && !OS(ANDROID)
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"
182 using namespace WebCore;
186 static int frameCount = 0;
188 // Key for a StatsCounter tracking how many WebFrames are active.
189 static const char* const webFrameActiveCount = "WebFrameActiveCount";
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.
195 // The |frame| must be non-null.
196 static void frameContentAsPlainText(size_t maxChars, Frame* frame,
197 Vector<UChar>* output)
199 Document* doc = frame->document();
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();
211 // Select the document body.
212 RefPtr<Range> range(doc->createRange());
213 ExceptionCode exception = 0;
214 range->selectNodeContents(doc->body(), 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();
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.
230 // A null pointer and 0 length is common for some nodes.
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
236 ASSERT_NOT_REACHED();
240 // Just got a null node, we can forge ahead!
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.
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;
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)) {
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)
275 output->append(frameSeparator, frameSeparatorLen);
276 frameContentAsPlainText(maxChars, curChild, output);
277 if (output->size() >= maxChars)
278 return; // Filled up the buffer.
282 static long long generateFrameIdentifier()
284 static long long next = 0;
288 static WebPluginContainerImpl* pluginContainerFromNode(const WebNode& node)
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);
305 WebPluginContainerImpl* WebFrameImpl::pluginContainerFromFrame(Frame* frame)
309 if (!frame->document() || !frame->document()->isPluginDocument())
311 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
312 return static_cast<WebPluginContainerImpl *>(pluginDocument->pluginWidget());
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);
320 ChromePrintContext(Frame* frame)
321 : PrintContext(frame)
322 , m_printedPageWidth(0)
326 virtual ~ChromePrintContext() { }
328 virtual void begin(float width, float height)
330 ASSERT(!m_printedPageWidth);
331 m_printedPageWidth = width;
332 PrintContext::begin(m_printedPageWidth, height);
340 virtual float getPageShrink(int pageNumber) const
342 IntRect pageRect = m_pageRects[pageNumber];
343 return m_printedPageWidth / pageRect.width();
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)
353 IntRect pageRect = m_pageRects[pageNumber];
354 float scale = m_printedPageWidth / pageRect.width();
357 #if OS(UNIX) && !OS(DARWIN)
358 ctx.scale(WebCore::FloatSize(scale, scale));
360 ctx.translate(static_cast<float>(-pageRect.x()),
361 static_cast<float>(-pageRect.y()));
363 m_frame->view()->paintContents(&ctx, pageRect);
368 virtual void computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight)
370 return PrintContext::computePageRects(printRect, headerHeight, footerHeight, userScaleFactor, outPageHeight);
373 virtual int pageCount() const
375 return PrintContext::pageCount();
378 virtual bool shouldUseBrowserOverlays() const
384 // Set when printing.
385 float m_printedPageWidth;
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 {
393 ChromePluginPrintContext(Frame* frame, WebPluginContainerImpl* plugin, int printerDPI)
394 : ChromePrintContext(frame), m_plugin(plugin), m_pageCount(0), m_printerDPI(printerDPI)
398 virtual ~ChromePluginPrintContext() { }
400 virtual void begin(float width, float height)
406 m_plugin->printEnd();
409 virtual float getPageShrink(int pageNumber) const
411 // We don't shrink the page (maybe we should ask the widget ??)
415 virtual void computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight)
417 m_pageCount = m_plugin->printBegin(IntRect(printRect), m_printerDPI);
420 virtual int pageCount() const
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)
430 m_plugin->printPage(pageNumber, &ctx);
434 virtual bool shouldUseBrowserOverlays() const
440 // Set when printing.
441 WebPluginContainerImpl* m_plugin;
446 static WebDataSource* DataSourceForDocLoader(DocumentLoader* loader)
448 return loader ? WebDataSourceImpl::fromDocumentLoader(loader) : 0;
452 // WebFrame -------------------------------------------------------------------
454 class WebFrameImpl::DeferredScopeStringMatches {
456 DeferredScopeStringMatches(WebFrameImpl* webFrame,
458 const WebString& searchText,
459 const WebFindOptions& options,
461 : m_timer(this, &DeferredScopeStringMatches::doTimeout)
462 , m_webFrame(webFrame)
463 , m_identifier(identifier)
464 , m_searchText(searchText)
468 m_timer.startOneShot(0.0);
472 void doTimeout(Timer<DeferredScopeStringMatches>*)
474 m_webFrame->callScopeStringMatches(
475 this, m_identifier, m_searchText, m_options, m_reset);
478 Timer<DeferredScopeStringMatches> m_timer;
479 RefPtr<WebFrameImpl> m_webFrame;
481 WebString m_searchText;
482 WebFindOptions m_options;
487 // WebFrame -------------------------------------------------------------------
489 int WebFrame::instanceCount()
494 WebFrame* WebFrame::frameForEnteredContext()
497 ScriptController::retrieveFrameForEnteredContext();
498 return WebFrameImpl::fromFrame(frame);
501 WebFrame* WebFrame::frameForCurrentContext()
504 ScriptController::retrieveFrameForCurrentContext();
505 return WebFrameImpl::fromFrame(frame);
509 WebFrame* WebFrame::frameForContext(v8::Handle<v8::Context> context)
511 return WebFrameImpl::fromFrame(V8Proxy::retrieveFrame(context));
515 WebFrame* WebFrame::fromFrameOwnerElement(const WebElement& element)
517 return WebFrameImpl::fromFrameOwnerElement(
518 PassRefPtr<Element>(element).get());
521 WebString WebFrameImpl::name() const
523 return m_frame->tree()->uniqueName();
526 void WebFrameImpl::setName(const WebString& name)
528 m_frame->tree()->setName(name);
531 long long WebFrameImpl::identifier() const
536 WebVector<WebIconURL> WebFrameImpl::iconURLs(int iconTypes) const
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>();
546 WebSize WebFrameImpl::scrollOffset() const
548 FrameView* view = frameView();
550 return view->scrollOffset();
555 WebSize WebFrameImpl::minimumScrollOffset() const
557 FrameView* view = frameView();
559 return view->minimumScrollPosition() - IntPoint();
564 WebSize WebFrameImpl::maximumScrollOffset() const
566 FrameView* view = frameView();
568 return view->maximumScrollPosition() - IntPoint();
573 void WebFrameImpl::setScrollOffset(const WebSize& offset)
575 if (FrameView* view = frameView())
576 view->setScrollOffset(IntPoint(offset.width, offset.height));
579 WebSize WebFrameImpl::contentsSize() const
581 return frame()->view()->contentsSize();
584 int WebFrameImpl::contentsPreferredWidth() const
586 if (m_frame->document() && m_frame->document()->renderView())
587 return m_frame->document()->renderView()->minPreferredLogicalWidth();
591 int WebFrameImpl::documentElementScrollHeight() const
593 if (m_frame->document() && m_frame->document()->documentElement())
594 return m_frame->document()->documentElement()->scrollHeight();
598 bool WebFrameImpl::hasVisibleContent() const
600 return frame()->view()->visibleWidth() > 0 && frame()->view()->visibleHeight() > 0;
603 bool WebFrameImpl::hasHorizontalScrollbar() const
605 return m_frame && m_frame->view() && m_frame->view()->horizontalScrollbar();
608 bool WebFrameImpl::hasVerticalScrollbar() const
610 return m_frame && m_frame->view() && m_frame->view()->verticalScrollbar();
613 WebView* WebFrameImpl::view() const
618 void WebFrameImpl::clearOpener()
620 m_frame->loader()->setOpener(0);
623 WebFrame* WebFrameImpl::opener() const
627 opener = m_frame->loader()->opener();
628 return fromFrame(opener);
631 WebFrame* WebFrameImpl::parent() const
635 parent = m_frame->tree()->parent();
636 return fromFrame(parent);
639 WebFrame* WebFrameImpl::top() const
642 return fromFrame(m_frame->tree()->top());
647 WebFrame* WebFrameImpl::firstChild() const
649 return fromFrame(frame()->tree()->firstChild());
652 WebFrame* WebFrameImpl::lastChild() const
654 return fromFrame(frame()->tree()->lastChild());
657 WebFrame* WebFrameImpl::nextSibling() const
659 return fromFrame(frame()->tree()->nextSibling());
662 WebFrame* WebFrameImpl::previousSibling() const
664 return fromFrame(frame()->tree()->previousSibling());
667 WebFrame* WebFrameImpl::traverseNext(bool wrap) const
669 return fromFrame(frame()->tree()->traverseNextWithWrap(wrap));
672 WebFrame* WebFrameImpl::traversePrevious(bool wrap) const
674 return fromFrame(frame()->tree()->traversePreviousWithWrap(wrap));
677 WebFrame* WebFrameImpl::findChildByName(const WebString& name) const
679 return fromFrame(frame()->tree()->child(name));
682 WebFrame* WebFrameImpl::findChildByExpression(const WebString& xpath) const
687 Document* document = m_frame->document();
689 ExceptionCode ec = 0;
690 PassRefPtr<XPathResult> xpathResult =
691 document->evaluate(xpath,
694 XPathResult::ORDERED_NODE_ITERATOR_TYPE,
695 0, // XPathResult object
697 if (!xpathResult.get())
700 Node* node = xpathResult->iterateNext(ec);
702 if (!node || !node->isFrameOwnerElement())
704 HTMLFrameOwnerElement* frameElement =
705 static_cast<HTMLFrameOwnerElement*>(node);
706 return fromFrame(frameElement->contentFrame());
709 WebDocument WebFrameImpl::document() const
711 if (!m_frame || !m_frame->document())
712 return WebDocument();
713 return WebDocument(m_frame->document());
716 WebAnimationController* WebFrameImpl::animationController()
718 return &m_animationController;
721 WebPerformance WebFrameImpl::performance() const
723 if (!m_frame || !m_frame->domWindow())
724 return WebPerformance();
726 return WebPerformance(m_frame->domWindow()->performance());
729 NPObject* WebFrameImpl::windowObject() const
734 return m_frame->script()->windowScriptNPObject();
737 void WebFrameImpl::bindToWindowObject(const WebString& name, NPObject* object)
740 if (!m_frame || !m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
745 m_frame->script()->bindToWindowObject(m_frame, key, object);
751 void WebFrameImpl::executeScript(const WebScriptSource& source)
753 TextPosition1 position(WTF::OneBasedNumber::fromOneBasedInt(source.startLine), WTF::OneBasedNumber::base());
754 m_frame->script()->executeScript(
755 ScriptSourceCode(source.code, source.url, position));
758 void WebFrameImpl::executeScriptInIsolatedWorld(
759 int worldID, const WebScriptSource* sourcesIn, unsigned numSources,
762 Vector<ScriptSourceCode> sources;
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));
770 m_frame->script()->evaluateInIsolatedWorld(worldID, sources, extensionGroup);
773 void WebFrameImpl::setIsolatedWorldSecurityOrigin(int worldID, const WebSecurityOrigin& securityOrigin)
775 m_frame->script()->setIsolatedWorldSecurityOrigin(worldID, securityOrigin.get());
778 void WebFrameImpl::addMessageToConsole(const WebConsoleMessage& message)
782 MessageLevel webCoreMessageLevel;
783 switch (message.level) {
784 case WebConsoleMessage::LevelTip:
785 webCoreMessageLevel = TipMessageLevel;
787 case WebConsoleMessage::LevelLog:
788 webCoreMessageLevel = LogMessageLevel;
790 case WebConsoleMessage::LevelWarning:
791 webCoreMessageLevel = WarningMessageLevel;
793 case WebConsoleMessage::LevelError:
794 webCoreMessageLevel = ErrorMessageLevel;
797 ASSERT_NOT_REACHED();
801 frame()->domWindow()->console()->addMessage(
802 OtherMessageSource, LogMessageType, webCoreMessageLevel, message.text,
806 void WebFrameImpl::collectGarbage()
810 if (!m_frame->settings()->isJavaScriptEnabled())
812 // FIXME: Move this to the ScriptController and make it JS neutral.
814 m_frame->script()->collectGarbage();
820 bool WebFrameImpl::checkIfRunInsecureContent(const WebURL& url) const
822 FrameLoader* frameLoader = m_frame->loader();
823 return frameLoader->checkIfRunInsecureContent(m_frame->document()->securityOrigin(), url);
827 v8::Handle<v8::Value> WebFrameImpl::executeScriptAndReturnValue(const WebScriptSource& source)
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);
835 TextPosition1 position(WTF::OneBasedNumber::fromOneBasedInt(source.startLine), WTF::OneBasedNumber::base());
836 return m_frame->script()->executeScript(ScriptSourceCode(source.code, source.url, position)).v8Value();
839 // Returns the V8 context for this frame, or an empty handle if there is none.
840 v8::Local<v8::Context> WebFrameImpl::mainWorldScriptContext() const
843 return v8::Local<v8::Context>();
845 return V8Proxy::mainWorldContext(m_frame);
848 v8::Handle<v8::Value> WebFrameImpl::createFileSystem(WebFileSystem::Type type,
849 const WebString& name,
850 const WebString& path)
852 return toV8(DOMFileSystem::create(frame()->document(), name, AsyncFileSystemChromium::create(static_cast<AsyncFileSystem::Type>(type), KURL(ParsedURLString, path.utf8().data()))));
855 v8::Handle<v8::Value> WebFrameImpl::createFileEntry(WebFileSystem::Type type,
856 const WebString& fileSystemName,
857 const WebString& fileSystemPath,
858 const WebString& filePath,
861 RefPtr<DOMFileSystemBase> fileSystem = DOMFileSystem::create(frame()->document(), fileSystemName, AsyncFileSystemChromium::create(static_cast<AsyncFileSystem::Type>(type), KURL(ParsedURLString, fileSystemPath.utf8().data())));
863 return toV8(DirectoryEntry::create(fileSystem, filePath));
864 return toV8(FileEntry::create(fileSystem, filePath));
868 void WebFrameImpl::reload(bool ignoreCache)
870 m_frame->loader()->history()->saveDocumentAndScrollState();
871 m_frame->loader()->reload(ignoreCache);
874 void WebFrameImpl::loadRequest(const WebURLRequest& request)
876 ASSERT(!request.isNull());
877 const ResourceRequest& resourceRequest = request.toResourceRequest();
879 if (resourceRequest.url().protocolIs("javascript")) {
880 loadJavaScriptURL(resourceRequest.url());
884 m_frame->loader()->load(resourceRequest, false);
887 void WebFrameImpl::loadHistoryItem(const WebHistoryItem& item)
889 RefPtr<HistoryItem> historyItem = PassRefPtr<HistoryItem>(item);
890 ASSERT(historyItem.get());
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;
900 void WebFrameImpl::loadData(const WebData& data,
901 const WebString& mimeType,
902 const WebString& textEncoding,
903 const WebURL& baseURL,
904 const WebURL& unreachableURL,
907 SubstituteData substData(data, mimeType, textEncoding, unreachableURL);
908 ASSERT(substData.isValid());
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);
921 m_frame->loader()->load(request, substData, false);
923 // Do this to force WebKit to treat the load as replacing the currently
925 m_frame->loader()->setReplacing();
929 void WebFrameImpl::loadHTMLString(const WebData& data,
930 const WebURL& baseURL,
931 const WebURL& unreachableURL,
935 WebString::fromUTF8("text/html"),
936 WebString::fromUTF8("UTF-8"),
942 bool WebFrameImpl::isLoading() const
946 return m_frame->loader()->isLoading();
949 void WebFrameImpl::stopLoading()
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);
960 WebDataSource* WebFrameImpl::provisionalDataSource() const
962 FrameLoader* frameLoader = m_frame->loader();
964 // We regard the policy document loader as still provisional.
965 DocumentLoader* docLoader = frameLoader->provisionalDocumentLoader();
967 docLoader = frameLoader->policyDocumentLoader();
969 return DataSourceForDocLoader(docLoader);
972 WebDataSource* WebFrameImpl::dataSource() const
974 return DataSourceForDocLoader(m_frame->loader()->documentLoader());
977 WebHistoryItem WebFrameImpl::previousHistoryItem() const
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());
986 WebHistoryItem WebFrameImpl::currentHistoryItem() const
988 // We're shutting down.
989 if (!m_frame->loader()->activeDocumentLoader())
990 return WebHistoryItem();
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
997 if (!m_inSameDocumentHistoryLoad && (m_frame->loader()->loadType() == FrameLoadTypeStandard
998 || !m_frame->loader()->activeDocumentLoader()->isLoadingInAPISense()))
999 m_frame->loader()->history()->saveDocumentAndScrollState();
1001 return WebHistoryItem(m_frame->page()->backForward()->currentItem());
1004 void WebFrameImpl::enableViewSourceMode(bool enable)
1007 m_frame->setInViewSourceMode(enable);
1010 bool WebFrameImpl::isViewSourceModeEnabled() const
1013 return m_frame->inViewSourceMode();
1018 void WebFrameImpl::setReferrerForRequest(
1019 WebURLRequest& request, const WebURL& referrerURL) {
1021 if (referrerURL.isEmpty())
1022 referrer = m_frame->loader()->outgoingReferrer();
1024 referrer = referrerURL.spec().utf16();
1025 if (SecurityOrigin::shouldHideReferrer(request.url(), referrer))
1027 request.setHTTPHeaderField(WebString::fromUTF8("Referer"), referrer);
1030 void WebFrameImpl::dispatchWillSendRequest(WebURLRequest& request)
1032 ResourceResponse response;
1033 m_frame->loader()->client()->dispatchWillSendRequest(
1034 0, 0, request.toMutableResourceRequest(), response);
1037 WebURLLoader* WebFrameImpl::createAssociatedURLLoader(const WebURLLoaderOptions& options)
1039 return new AssociatedURLLoader(this, options);
1042 void WebFrameImpl::commitDocumentData(const char* data, size_t length)
1044 m_frame->loader()->documentLoader()->commitData(data, length);
1047 unsigned WebFrameImpl::unloadListenerCount() const
1049 return frame()->domWindow()->pendingUnloadEventListeners();
1052 bool WebFrameImpl::isProcessingUserGesture() const
1054 return ScriptController::processingUserGesture();
1057 bool WebFrameImpl::willSuppressOpenerInNewFrame() const
1059 return frame()->loader()->suppressOpenerInNewFrame();
1062 void WebFrameImpl::replaceSelection(const WebString& text)
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));
1070 void WebFrameImpl::insertText(const WebString& text)
1072 Editor* editor = frame()->editor();
1074 if (editor->hasComposition())
1075 editor->confirmComposition(text);
1077 editor->insertText(text, 0);
1080 void WebFrameImpl::setMarkedText(
1081 const WebString& text, unsigned location, unsigned length)
1083 Editor* editor = frame()->editor();
1085 Vector<CompositionUnderline> decorations;
1086 editor->setComposition(text, decorations, location, length);
1089 void WebFrameImpl::unmarkText()
1091 frame()->editor()->cancelComposition();
1094 bool WebFrameImpl::hasMarkedText() const
1096 return frame()->editor()->hasComposition();
1099 WebRange WebFrameImpl::markedRange() const
1101 return frame()->editor()->compositionRange();
1104 bool WebFrameImpl::firstRectForCharacterRange(unsigned location, unsigned length, WebRect& rect) const
1106 if ((location + length < location) && (location + length))
1109 Element* selectionRoot = frame()->selection()->rootEditableElement();
1110 Element* scope = selectionRoot ? selectionRoot : frame()->document()->documentElement();
1111 RefPtr<Range> range = TextIterator::rangeFromLocationAndLength(scope, location, length);
1114 IntRect intRect = frame()->editor()->firstRectForRange(range.get());
1115 rect = WebRect(intRect);
1116 rect = frame()->view()->contentsToWindow(rect);
1121 size_t WebFrameImpl::characterIndexForPoint(const WebPoint& webPoint) const
1126 IntPoint point = frame()->view()->windowToContents(webPoint);
1127 HitTestResult result = frame()->eventHandler()->hitTestResultAtPoint(point, false);
1128 RefPtr<Range> range = frame()->rangeForPoint(result.point());
1132 size_t location, length;
1133 TextIterator::locationAndLengthFromRange(range.get(), location, length);
1137 bool WebFrameImpl::executeCommand(const WebString& name, const WebNode& node)
1141 if (name.length() <= 2)
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;
1148 // Make sure the first letter is upper case.
1149 command.replace(0, 1, command.substring(0, 1).upper());
1151 // Remove the trailing ':' if existing.
1152 if (command[command.length() - 1] == UChar(':'))
1153 command = command.substring(0, command.length() - 1);
1155 if (command == "Copy") {
1156 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1157 if (!pluginContainer)
1158 pluginContainer = pluginContainerFromNode(node);
1159 if (pluginContainer) {
1160 pluginContainer->copy();
1167 // Specially handling commands that Editor::execCommand does not directly
1169 if (command == "DeleteToEndOfParagraph") {
1170 Editor* editor = frame()->editor();
1171 if (!editor->deleteWithDirection(DirectionForward,
1175 editor->deleteWithDirection(DirectionForward,
1176 CharacterGranularity,
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
1191 frame()->editor()->advanceToNextMisspelling(false);
1192 } else if (command == "ToggleSpellPanel")
1193 frame()->editor()->showSpellingGuessPanel();
1195 rv = frame()->editor()->command(command).execute();
1199 bool WebFrameImpl::executeCommand(const WebString& name, const WebString& value)
1202 String webName = name;
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);
1209 if (!frame()->editor()->canEdit() && webName == "moveToEndOfDocument")
1210 return viewImpl()->propagateScroll(ScrollDown, ScrollByDocument);
1212 return frame()->editor()->command(webName).execute(value);
1215 bool WebFrameImpl::isCommandEnabled(const WebString& name) const
1218 return frame()->editor()->command(name).isEnabled();
1221 void WebFrameImpl::enableContinuousSpellChecking(bool enable)
1223 if (enable == isContinuousSpellCheckingEnabled())
1225 frame()->editor()->toggleContinuousSpellChecking();
1228 bool WebFrameImpl::isContinuousSpellCheckingEnabled() const
1230 return frame()->editor()->isContinuousSpellCheckingEnabled();
1233 bool WebFrameImpl::hasSelection() const
1235 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1236 if (pluginContainer)
1237 return pluginContainer->plugin()->hasSelection();
1239 // frame()->selection()->isNone() never returns true.
1240 return (frame()->selection()->start() != frame()->selection()->end());
1243 WebRange WebFrameImpl::selectionRange() const
1245 return frame()->selection()->toNormalizedRange();
1248 WebString WebFrameImpl::selectionAsText() const
1250 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1251 if (pluginContainer)
1252 return pluginContainer->plugin()->selectionAsText();
1254 RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1258 String text = range->text();
1260 replaceNewlinesWithWindowsStyleNewlines(text);
1262 replaceNBSPWithSpace(text);
1266 WebString WebFrameImpl::selectionAsMarkup() const
1268 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1269 if (pluginContainer)
1270 return pluginContainer->plugin()->selectionAsMarkup();
1272 RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1276 return createMarkup(range.get(), 0);
1279 void WebFrameImpl::selectWordAroundPosition(Frame* frame, VisiblePosition pos)
1281 VisibleSelection selection(pos);
1282 selection.expandUsingGranularity(WordGranularity);
1284 if (frame->selection()->shouldChangeSelection(selection)) {
1285 TextGranularity granularity = selection.isRange() ? WordGranularity : CharacterGranularity;
1286 frame->selection()->setSelection(selection, granularity);
1290 bool WebFrameImpl::selectWordAroundCaret()
1292 FrameSelection* selection = frame()->selection();
1293 ASSERT(!selection->isNone());
1294 if (selection->isNone() || selection->isRange())
1296 selectWordAroundPosition(frame(), selection->selection().visibleStart());
1300 void WebFrameImpl::selectRange(const WebPoint& start, const WebPoint& end)
1302 VisibleSelection selection(visiblePositionForWindowPoint(start),
1303 visiblePositionForWindowPoint(end));
1305 if (frame()->selection()->shouldChangeSelection(selection))
1306 frame()->selection()->setSelection(selection, CharacterGranularity);
1309 VisiblePosition WebFrameImpl::visiblePositionForWindowPoint(const WebPoint& point)
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))));
1319 frame()->document()->renderView()->layer()->hitTest(request, result);
1321 // Matching the logic in MouseEventWithHitTestResults::targetNode()
1322 Node* node = result.innerNode();
1324 return VisiblePosition();
1325 Element* element = node->parentElement();
1326 if (!node->inDocument() && element && element->inDocument())
1329 return node->renderer()->positionForPoint(result.localPoint());
1332 int WebFrameImpl::printBegin(const WebSize& pageSize,
1333 const WebNode& constrainToNode,
1335 bool* useBrowserOverlays)
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());
1344 // We only support printing plugin nodes for now.
1345 pluginContainer = pluginContainerFromNode(constrainToNode);
1348 if (pluginContainer && pluginContainer->supportsPaginatedPrint())
1349 m_printContext = adoptPtr(new ChromePluginPrintContext(frame(), pluginContainer, printerDPI));
1351 m_printContext = adoptPtr(new ChromePrintContext(frame()));
1353 FloatRect rect(0, 0, static_cast<float>(pageSize.width),
1354 static_cast<float>(pageSize.height));
1355 m_printContext->begin(rect.width(), rect.height());
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();
1363 return m_printContext->pageCount();
1366 float WebFrameImpl::getPrintPageShrink(int page)
1368 // Ensure correct state.
1369 if (!m_printContext.get() || page < 0) {
1370 ASSERT_NOT_REACHED();
1374 return m_printContext->getPageShrink(page);
1377 float WebFrameImpl::printPage(int page, WebCanvas* canvas)
1379 // Ensure correct state.
1380 if (!m_printContext.get() || page < 0 || !frame() || !frame()->document()) {
1381 ASSERT_NOT_REACHED();
1385 GraphicsContextBuilder builder(canvas);
1386 GraphicsContext& gc = builder.context();
1387 #if WEBKIT_USING_SKIA
1388 gc.platformContext()->setPrinting(true);
1391 return m_printContext->spoolPage(gc, page);
1394 void WebFrameImpl::printEnd()
1396 ASSERT(m_printContext.get());
1397 if (m_printContext.get())
1398 m_printContext->end();
1399 m_printContext.clear();
1402 bool WebFrameImpl::isPageBoxVisible(int pageIndex)
1404 return frame()->document()->isPageBoxVisible(pageIndex);
1407 void WebFrameImpl::pageSizeAndMarginsInPixels(int pageIndex,
1414 IntSize size(pageSize.width, pageSize.height);
1415 frame()->document()->pageSizeAndMarginsInPixels(pageIndex,
1424 bool WebFrameImpl::find(int identifier,
1425 const WebString& searchText,
1426 const WebFindOptions& options,
1427 bool wrapWithinFrame,
1428 WebRect* selectionRect)
1430 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
1432 if (!options.findNext)
1433 frame()->page()->unmarkAllTextMatches();
1435 setMarkerActive(m_activeMatch.get(), false); // Active match is changing.
1437 // Starts the search from the current selection.
1438 bool startInSelection = true;
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);
1450 ASSERT(frame() && frame()->view());
1451 bool found = frame()->editor()->findString(
1452 searchText, options.forward, options.matchCase, wrapWithinFrame,
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;
1461 // We found something, so we can now query the selection for its position.
1462 VisibleSelection newSelection(frame()->selection()->selection());
1463 IntRect currSelectionRect;
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()))
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"));
1480 // Make sure no node is focused. See http://crbug.com/38700.
1481 frame()->document()->setFocusedNode(0);
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;
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;
1496 m_activeMatchIndex = m_lastMatchCount - 1;
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;
1506 if (selectionRect) {
1507 *selectionRect = frameView()->contentsToWindow(currSelectionRect);
1508 reportFindInPageSelection(*selectionRect, m_activeMatchIndex + 1, identifier);
1512 // Nothing was found in this frame.
1515 // Erase all previous tickmarks and highlighting.
1516 invalidateArea(InvalidateAll);
1522 void WebFrameImpl::stopFinding(bool clearSelection)
1524 if (!clearSelection)
1525 setFindEndstateFocusAndSelection();
1526 cancelPendingScopingEffort();
1528 // Remove all markers for matches found and turn off the highlighting.
1529 frame()->document()->markers()->removeMarkers(DocumentMarker::TextMatch);
1530 frame()->editor()->setMarkedTextMatchesAreHighlighted(false);
1532 // Let the frame know that we don't want tickmarks or highlighting anymore.
1533 invalidateArea(InvalidateAll);
1536 void WebFrameImpl::scopeStringMatches(int identifier,
1537 const WebString& searchText,
1538 const WebFindOptions& options,
1541 if (!shouldScopeMatches(searchText))
1544 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
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;
1557 m_resumeScopingFromRange = 0;
1559 mainFrameImpl->m_framesScopingCount++;
1561 // Now, defer scoping until later to allow find operation to finish quickly.
1562 scopeStringMatchesSoon(
1566 false); // false=we just reset, so don't do it again.
1570 RefPtr<Range> searchRange(rangeOfContents(frame()->document()));
1572 Node* originalEndContainer = searchRange->endContainer();
1573 int originalEndOffset = searchRange->endOffset();
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,
1583 if (ec2) // A non-zero |ec| happens when navigating during search.
1584 ASSERT_NOT_REACHED();
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
1595 bool timedOut = false;
1596 double startTime = currentTime();
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(),
1605 options.matchCase ? 0 : CaseInsensitive));
1606 if (resultRange->collapsed(ec)) {
1607 if (!resultRange->startContainer()->isInShadowTree())
1610 searchRange->setStartAfter(
1611 resultRange->startContainer()->shadowAncestorNode(), ec);
1612 searchRange->setEnd(originalEndContainer, originalEndOffset, ec);
1616 // Only treat the result as a match if it is visible
1617 if (frame()->editor()->insideVisibleArea(resultRange.get())) {
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;
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
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;
1644 // Notify browser of new location for the selected rectangle.
1645 reportFindInPageSelection(
1646 frameView()->contentsToWindow(resultBounds),
1647 m_activeMatchIndex + 1,
1651 addMarker(resultRange.get(), foundActiveMatch);
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
1658 searchRange->setStart(resultRange->endContainer(ec), resultRange->endOffset(ec), ec);
1660 Node* shadowTreeRoot = searchRange->shadowTreeRootNode();
1661 if (searchRange->collapsed(ec) && shadowTreeRoot)
1662 searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), ec);
1664 m_resumeScopingFromRange = resultRange;
1665 timedOut = (currentTime() - startTime) >= maxScopingDuration;
1666 } while (!timedOut);
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;
1672 if (matchCount > 0) {
1673 frame()->editor()->setMarkedTextMatchesAreHighlighted(true);
1675 m_lastMatchCount += matchCount;
1677 // Let the mainframe know how much we found during this pass.
1678 mainFrameImpl->increaseMatchCount(matchCount, identifier);
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.
1686 invalidateIfNecessary();
1688 // Scoping effort ran out of time, lets ask for another time-slice.
1689 scopeStringMatchesSoon(
1693 false); // don't reset.
1694 return; // Done for now, resume work later.
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--;
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);
1707 // This frame is done, so show any scrollbar tickmarks we haven't drawn yet.
1708 invalidateArea(InvalidateScrollbar);
1711 void WebFrameImpl::cancelPendingScopingEffort()
1713 deleteAllValues(m_deferredScopingWork);
1714 m_deferredScopingWork.clear();
1716 m_activeMatchIndex = -1;
1719 void WebFrameImpl::increaseMatchCount(int count, int identifier)
1721 // This function should only be called on the mainframe.
1724 m_totalMatchCount += count;
1726 // Update the UI with the latest findings.
1728 client()->reportFindInPageMatchCount(identifier, m_totalMatchCount, !m_framesScopingCount);
1731 void WebFrameImpl::reportFindInPageSelection(const WebRect& selectionRect,
1732 int activeMatchOrdinal,
1735 // Update the UI with the latest selection rect.
1737 client()->reportFindInPageSelection(identifier, ordinalOfFirstMatchForFrame(this) + activeMatchOrdinal, selectionRect);
1740 void WebFrameImpl::resetMatchCount()
1742 m_totalMatchCount = 0;
1743 m_framesScopingCount = 0;
1746 WebString WebFrameImpl::contentAsText(size_t maxChars) const
1752 frameContentAsPlainText(maxChars, m_frame, &text);
1753 return String::adopt(text);
1756 WebString WebFrameImpl::contentAsMarkup() const
1758 return createFullMarkup(m_frame->document());
1761 WebString WebFrameImpl::renderTreeAsText(bool showDebugInfo) const
1763 RenderAsTextBehavior behavior = RenderAsTextBehaviorNormal;
1765 if (showDebugInfo) {
1766 behavior |= RenderAsTextShowCompositedLayers
1767 | RenderAsTextShowAddresses
1768 | RenderAsTextShowIDAndClass
1769 | RenderAsTextShowLayerNesting;
1772 return externalRepresentation(m_frame, behavior);
1775 WebString WebFrameImpl::counterValueForElementById(const WebString& id) const
1780 Element* element = m_frame->document()->getElementById(id);
1784 return counterValueForElement(element);
1787 WebString WebFrameImpl::markerTextForListItem(const WebElement& webElement) const
1789 return WebCore::markerTextForListItem(const_cast<Element*>(webElement.constUnwrap<Element>()));
1792 int WebFrameImpl::pageNumberForElementById(const WebString& id,
1793 float pageWidthInPixels,
1794 float pageHeightInPixels) const
1799 Element* element = m_frame->document()->getElementById(id);
1803 FloatSize pageSize(pageWidthInPixels, pageHeightInPixels);
1804 return PrintContext::pageNumberForElement(element, pageSize);
1807 WebRect WebFrameImpl::selectionBoundsRect() const
1810 return IntRect(frame()->selection()->bounds(false));
1815 bool WebFrameImpl::selectionStartHasSpellingMarkerFor(int from, int length) const
1819 return m_frame->editor()->selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length);
1822 bool WebFrameImpl::pauseSVGAnimation(const WebString& animationId, double time, const WebString& elementId)
1830 Document* document = m_frame->document();
1831 if (!document || !document->svgExtensions())
1834 Node* coreNode = document->getElementById(animationId);
1835 if (!coreNode || !SVGSMILElement::isSMILElement(coreNode))
1838 return document->accessSVGExtensions()->sampleAnimationAtTime(elementId, static_cast<SVGSMILElement*>(coreNode), time);
1842 WebString WebFrameImpl::layerTreeAsText(bool showDebugInfo) const
1846 return WebString(m_frame->layerTreeAsText(showDebugInfo));
1849 // WebFrameImpl public ---------------------------------------------------------
1851 PassRefPtr<WebFrameImpl> WebFrameImpl::create(WebFrameClient* client)
1853 return adoptRef(new WebFrameImpl(client));
1856 WebFrameImpl::WebFrameImpl(WebFrameClient* client)
1857 : m_frameLoaderClient(this)
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)
1872 PlatformSupport::incrementStatsCounter(webFrameActiveCount);
1876 WebFrameImpl::~WebFrameImpl()
1878 PlatformSupport::decrementStatsCounter(webFrameActiveCount);
1881 cancelPendingScopingEffort();
1884 void WebFrameImpl::initializeAsMainFrame(WebViewImpl* webViewImpl)
1886 RefPtr<Frame> frame = Frame::create(webViewImpl->page(), 0, &m_frameLoaderClient);
1887 m_frame = frame.get();
1889 // Add reference on behalf of FrameLoader. See comments in
1890 // WebFrameLoaderClient::frameLoaderDestroyed for more info.
1893 // We must call init() after m_frame is assigned because it is referenced
1898 PassRefPtr<Frame> WebFrameImpl::createChildFrame(
1899 const FrameLoadRequest& request, HTMLFrameOwnerElement* ownerElement)
1901 RefPtr<WebFrameImpl> webframe(adoptRef(new WebFrameImpl(m_client)));
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.
1908 RefPtr<Frame> childFrame = Frame::create(
1909 m_frame->page(), ownerElement, &webframe->m_frameLoaderClient);
1910 webframe->m_frame = childFrame.get();
1912 childFrame->tree()->setName(request.frameName());
1914 m_frame->tree()->appendChild(childFrame);
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.
1925 childFrame->init(); // create an empty document
1926 if (!childFrame->tree()->parent())
1929 m_frame->loader()->loadURLIntoChildFrame(
1930 request.resourceRequest().url(),
1931 request.resourceRequest().httpReferrer(),
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())
1940 return childFrame.release();
1943 void WebFrameImpl::layout()
1945 // layout this frame
1946 FrameView* view = m_frame->view();
1948 view->updateLayoutAndStyleIfNeededRecursive();
1951 void WebFrameImpl::paintWithContext(GraphicsContext& gc, const WebRect& rect)
1953 IntRect dirtyRect(rect);
1955 if (m_frame->document() && frameView()) {
1957 frameView()->paint(&gc, dirtyRect);
1958 if (viewImpl()->pageOverlay())
1959 viewImpl()->pageOverlay()->paintWebFrame(gc);
1961 gc.fillRect(dirtyRect, Color::white, ColorSpaceDeviceRGB);
1965 void WebFrameImpl::paint(WebCanvas* canvas, const WebRect& rect)
1969 paintWithContext(GraphicsContextBuilder(canvas).context(), rect);
1972 void WebFrameImpl::createFrameView()
1974 ASSERT(m_frame); // If m_frame doesn't exist, we probably didn't init properly.
1976 Page* page = m_frame->page();
1978 ASSERT(page->mainFrame());
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();
1991 m_frame->setView(0);
1993 WebViewImpl* webView = viewImpl();
1995 RefPtr<FrameView> view;
1997 view = FrameView::create(m_frame, webView->size());
1999 view = FrameView::create(m_frame);
2001 m_frame->setView(view);
2003 if (webView->isTransparent())
2004 view->setTransparent(true);
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());
2011 if (HTMLFrameOwnerElement* owner = m_frame->ownerElement())
2012 view->setCanHaveScrollbars(owner->scrollingMode() != ScrollbarAlwaysOff);
2015 view->setParentVisible(true);
2017 #if ENABLE(GESTURE_RECOGNIZER)
2018 webView->resetGestureRecognizer();
2021 // Restore the saved fixed layout information.
2022 view->setUseFixedLayout(useFixedLayout);
2023 view->setFixedLayoutSize(fixedLayoutSize);
2026 WebFrameImpl* WebFrameImpl::fromFrame(Frame* frame)
2031 return static_cast<FrameLoaderClientImpl*>(frame->loader()->client())->webFrame();
2034 WebFrameImpl* WebFrameImpl::fromFrameOwnerElement(Element* element)
2037 || !element->isFrameOwnerElement()
2038 || (!element->hasTagName(HTMLNames::iframeTag)
2039 && !element->hasTagName(HTMLNames::frameTag)))
2042 HTMLFrameOwnerElement* frameElement =
2043 static_cast<HTMLFrameOwnerElement*>(element);
2044 return fromFrame(frameElement->contentFrame());
2047 WebViewImpl* WebFrameImpl::viewImpl() const
2052 return WebViewImpl::fromPage(m_frame->page());
2055 WebDataSourceImpl* WebFrameImpl::dataSourceImpl() const
2057 return static_cast<WebDataSourceImpl*>(dataSource());
2060 WebDataSourceImpl* WebFrameImpl::provisionalDataSourceImpl() const
2062 return static_cast<WebDataSourceImpl*>(provisionalDataSource());
2065 void WebFrameImpl::setFindEndstateFocusAndSelection()
2067 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
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())
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();
2082 if (node && node != frame()->document()) {
2083 // Found a focusable parent node. Set focus to it.
2084 frame()->document()->setFocusedNode(node);
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);
2097 node = node->traverseNextNode();
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);
2110 void WebFrameImpl::didFail(const ResourceError& error, bool wasProvisional)
2114 WebURLError webError = error;
2116 client()->didFailProvisionalLoad(this, webError);
2118 client()->didFailLoad(this, webError);
2121 void WebFrameImpl::setCanHaveScrollbars(bool canHaveScrollbars)
2123 m_frame->view()->setCanHaveScrollbars(canHaveScrollbars);
2126 // WebFrameImpl private --------------------------------------------------------
2128 void WebFrameImpl::closing()
2133 void WebFrameImpl::invalidateArea(AreaToInvalidate area)
2135 ASSERT(frame() && frame()->view());
2136 FrameView* view = frame()->view();
2138 if ((area & InvalidateAll) == InvalidateAll)
2139 view->invalidateRect(view->frameRect());
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);
2149 if ((area & InvalidateScrollbar) == InvalidateScrollbar) {
2150 // Invalidate the vertical scroll bar region for the view.
2151 Scrollbar* scrollbar = view->verticalScrollbar();
2153 scrollbar->invalidate();
2158 void WebFrameImpl::addMarker(Range* range, bool activeMatch)
2160 frame()->document()->markers()->addTextMatchMarker(range, activeMatch);
2163 void WebFrameImpl::setMarkerActive(Range* range, bool active)
2165 WebCore::ExceptionCode ec;
2166 if (!range || range->collapsed(ec))
2169 frame()->document()->markers()->setMarkersActive(range, active);
2172 int WebFrameImpl::ordinalOfFirstMatchForFrame(WebFrameImpl* frame) const
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;
2180 it = static_cast<WebFrameImpl*>(it->traverseNext(true))) {
2181 if (it->m_lastMatchCount > 0)
2182 ordinal += it->m_lastMatchCount;
2187 bool WebFrameImpl::shouldScopeMatches(const String& searchText)
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())
2194 ASSERT(frame()->document() && frame()->view());
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());
2204 if (previousSearchPrefix == m_lastSearchString)
2205 return false; // Don't search this frame, it will be fruitless.
2211 void WebFrameImpl::scopeStringMatchesSoon(int identifier, const WebString& searchText,
2212 const WebFindOptions& options, bool reset)
2214 m_deferredScopingWork.append(new DeferredScopeStringMatches(
2215 this, identifier, searchText, options, reset));
2218 void WebFrameImpl::callScopeStringMatches(DeferredScopeStringMatches* caller,
2219 int identifier, const WebString& searchText,
2220 const WebFindOptions& options, bool reset)
2222 m_deferredScopingWork.remove(m_deferredScopingWork.find(caller));
2224 scopeStringMatches(identifier, searchText, options, reset);
2226 // This needs to happen last since searchText is passed by reference.
2230 void WebFrameImpl::invalidateIfNecessary()
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;
2245 invalidateArea(InvalidateScrollbar);
2249 void WebFrameImpl::loadJavaScriptURL(const KURL& url)
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.
2259 if (!m_frame->document() || !m_frame->page())
2262 // Protect privileged pages against bookmarklets and other javascript manipulations.
2263 if (SchemeRegistry::shouldTreatURLSchemeAsNotAllowingJavascriptURLs(m_frame->document()->url().protocol()))
2266 String script = decodeURLEscapeSequences(url.string().substring(strlen("javascript:")));
2267 ScriptValue result = m_frame->script()->executeScript(script, true);
2269 String scriptResult;
2270 if (!result.getString(scriptResult))
2273 if (!m_frame->navigationScheduler()->locationChangePending())
2274 m_frame->document()->loader()->writer()->replaceDocument(scriptResult);
2277 } // namespace WebKit