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 "ChromiumBridge.h"
78 #include "ClipboardUtilitiesChromium.h"
80 #include "DOMUtilitiesPrivate.h"
81 #include "DOMWindow.h"
83 #include "DocumentFragment.h" // Only needed for ReplaceSelectionCommand.h :(
84 #include "DocumentLoader.h"
85 #include "DocumentMarker.h"
86 #include "DocumentMarkerController.h"
88 #include "EventHandler.h"
89 #include "FormState.h"
90 #include "FrameLoadRequest.h"
91 #include "FrameLoader.h"
92 #include "FrameTree.h"
93 #include "FrameView.h"
94 #include "GraphicsContext.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 "InspectorController.h"
105 #include "Performance.h"
106 #include "PlatformContextSkia.h"
107 #include "PluginDocument.h"
108 #include "PrintContext.h"
109 #include "RenderFrame.h"
110 #include "RenderObject.h"
111 #include "RenderTreeAsText.h"
112 #include "RenderView.h"
113 #include "RenderWidget.h"
114 #include "ReplaceSelectionCommand.h"
115 #include "ResourceHandle.h"
116 #include "ResourceRequest.h"
117 #include "SVGDocumentExtensions.h"
118 #include "SVGSMILElement.h"
119 #include "ScriptController.h"
120 #include "ScriptSourceCode.h"
121 #include "ScriptValue.h"
122 #include "ScrollTypes.h"
123 #include "ScrollbarTheme.h"
124 #include "SelectionController.h"
125 #include "Settings.h"
126 #include "SkiaUtils.h"
127 #include "SubstituteData.h"
128 #include "TextAffinity.h"
129 #include "TextIterator.h"
130 #include "WebAnimationControllerImpl.h"
131 #include "WebConsoleMessage.h"
132 #include "WebDataSourceImpl.h"
133 #include "WebDocument.h"
134 #include "WebFindOptions.h"
135 #include "WebFormElement.h"
136 #include "WebFrameClient.h"
137 #include "WebHistoryItem.h"
138 #include "WebInputElement.h"
140 #include "WebPasswordAutocompleteListener.h"
141 #include "WebPerformance.h"
142 #include "WebPlugin.h"
143 #include "WebPluginContainerImpl.h"
144 #include "WebRange.h"
146 #include "WebScriptSource.h"
147 #include "WebSecurityOrigin.h"
149 #include "WebURLError.h"
150 #include "WebVector.h"
151 #include "WebViewImpl.h"
152 #include "XPathResult.h"
156 #include <wtf/CurrentTime.h>
159 #include "LocalCurrentGraphicsContext.h"
162 #if OS(LINUX) || OS(FREEBSD)
166 using namespace WebCore;
170 static int frameCount = 0;
172 // Key for a StatsCounter tracking how many WebFrames are active.
173 static const char* const webFrameActiveCount = "WebFrameActiveCount";
175 static const char* const osdType = "application/opensearchdescription+xml";
176 static const char* const osdRel = "search";
178 // Backend for contentAsPlainText, this is a recursive function that gets
179 // the text for the current frame and all of its subframes. It will append
180 // the text of each frame in turn to the |output| up to |maxChars| length.
182 // The |frame| must be non-null.
183 static void frameContentAsPlainText(size_t maxChars, Frame* frame,
184 Vector<UChar>* output)
186 Document* doc = frame->document();
193 // TextIterator iterates over the visual representation of the DOM. As such,
194 // it requires you to do a layout before using it (otherwise it'll crash).
195 if (frame->view()->needsLayout())
196 frame->view()->layout();
198 // Select the document body.
199 RefPtr<Range> range(doc->createRange());
200 ExceptionCode exception = 0;
201 range->selectNodeContents(doc->body(), exception);
204 // The text iterator will walk nodes giving us text. This is similar to
205 // the plainText() function in TextIterator.h, but we implement the maximum
206 // size and also copy the results directly into a wstring, avoiding the
207 // string conversion.
208 for (TextIterator it(range.get()); !it.atEnd(); it.advance()) {
209 const UChar* chars = it.characters();
212 // It appears from crash reports that an iterator can get into a state
213 // where the character count is nonempty but the character pointer is
214 // null. advance()ing it will then just add that many to the null
215 // pointer which won't be caught in a null check but will crash.
217 // A null pointer and 0 length is common for some nodes.
219 // IF YOU CATCH THIS IN A DEBUGGER please let brettw know. We don't
220 // currently understand the conditions for this to occur. Ideally, the
221 // iterators would never get into the condition so we should fix them
223 ASSERT_NOT_REACHED();
227 // Just got a null node, we can forge ahead!
231 std::min(static_cast<size_t>(it.length()), maxChars - output->size());
232 output->append(chars, toAppend);
233 if (output->size() >= maxChars)
234 return; // Filled up the buffer.
238 // The separator between frames when the frames are converted to plain text.
239 const UChar frameSeparator[] = { '\n', '\n' };
240 const size_t frameSeparatorLen = 2;
242 // Recursively walk the children.
243 FrameTree* frameTree = frame->tree();
244 for (Frame* curChild = frameTree->firstChild(); curChild; curChild = curChild->tree()->nextSibling()) {
245 // Ignore the text of non-visible frames.
246 RenderView* contentRenderer = curChild->contentRenderer();
247 RenderPart* ownerRenderer = curChild->ownerRenderer();
248 if (!contentRenderer || !contentRenderer->width() || !contentRenderer->height()
249 || (contentRenderer->x() + contentRenderer->width() <= 0) || (contentRenderer->y() + contentRenderer->height() <= 0)
250 || (ownerRenderer && ownerRenderer->style() && ownerRenderer->style()->visibility() != VISIBLE)) {
254 // Make sure the frame separator won't fill up the buffer, and give up if
255 // it will. The danger is if the separator will make the buffer longer than
256 // maxChars. This will cause the computation above:
257 // maxChars - output->size()
258 // to be a negative number which will crash when the subframe is added.
259 if (output->size() >= maxChars - frameSeparatorLen)
262 output->append(frameSeparator, frameSeparatorLen);
263 frameContentAsPlainText(maxChars, curChild, output);
264 if (output->size() >= maxChars)
265 return; // Filled up the buffer.
269 static long long generateFrameIdentifier()
271 static long long next = 0;
275 WebPluginContainerImpl* WebFrameImpl::pluginContainerFromFrame(Frame* frame)
279 if (!frame->document() || !frame->document()->isPluginDocument())
281 PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
282 return static_cast<WebPluginContainerImpl *>(pluginDocument->pluginWidget());
285 // Simple class to override some of PrintContext behavior. Some of the methods
286 // made virtual so that they can be overriden by ChromePluginPrintContext.
287 class ChromePrintContext : public PrintContext {
288 WTF_MAKE_NONCOPYABLE(ChromePrintContext);
290 ChromePrintContext(Frame* frame)
291 : PrintContext(frame)
292 , m_printedPageWidth(0)
296 virtual void begin(float width, float height)
298 ASSERT(!m_printedPageWidth);
299 m_printedPageWidth = width;
300 PrintContext::begin(m_printedPageWidth, height);
308 virtual float getPageShrink(int pageNumber) const
310 IntRect pageRect = m_pageRects[pageNumber];
311 return m_printedPageWidth / pageRect.width();
314 // Spools the printed page, a subrect of m_frame. Skip the scale step.
315 // NativeTheme doesn't play well with scaling. Scaling is done browser side
316 // instead. Returns the scale to be applied.
317 // On Linux, we don't have the problem with NativeTheme, hence we let WebKit
318 // do the scaling and ignore the return value.
319 virtual float spoolPage(GraphicsContext& ctx, int pageNumber)
321 IntRect pageRect = m_pageRects[pageNumber];
322 float scale = m_printedPageWidth / pageRect.width();
325 #if OS(LINUX) || OS(FREEBSD)
326 ctx.scale(WebCore::FloatSize(scale, scale));
328 ctx.translate(static_cast<float>(-pageRect.x()),
329 static_cast<float>(-pageRect.y()));
331 m_frame->view()->paintContents(&ctx, pageRect);
336 virtual void computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight)
338 return PrintContext::computePageRects(printRect, headerHeight, footerHeight, userScaleFactor, outPageHeight);
341 virtual int pageCount() const
343 return PrintContext::pageCount();
346 virtual bool shouldUseBrowserOverlays() const
352 // Set when printing.
353 float m_printedPageWidth;
356 // Simple class to override some of PrintContext behavior. This is used when
357 // the frame hosts a plugin that supports custom printing. In this case, we
358 // want to delegate all printing related calls to the plugin.
359 class ChromePluginPrintContext : public ChromePrintContext {
361 ChromePluginPrintContext(Frame* frame, WebPluginContainerImpl* plugin, int printerDPI)
362 : ChromePrintContext(frame), m_plugin(plugin), m_pageCount(0), m_printerDPI(printerDPI)
366 virtual void begin(float width)
372 m_plugin->printEnd();
375 virtual float getPageShrink(int pageNumber) const
377 // We don't shrink the page (maybe we should ask the widget ??)
381 virtual void computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight)
383 m_pageCount = m_plugin->printBegin(IntRect(printRect), m_printerDPI);
386 virtual int pageCount() const
391 // Spools the printed page, a subrect of m_frame. Skip the scale step.
392 // NativeTheme doesn't play well with scaling. Scaling is done browser side
393 // instead. Returns the scale to be applied.
394 virtual float spoolPage(GraphicsContext& ctx, int pageNumber)
396 m_plugin->printPage(pageNumber, &ctx);
400 virtual bool shouldUseBrowserOverlays() const
406 // Set when printing.
407 WebPluginContainerImpl* m_plugin;
412 static WebDataSource* DataSourceForDocLoader(DocumentLoader* loader)
414 return loader ? WebDataSourceImpl::fromDocumentLoader(loader) : 0;
418 // WebFrame -------------------------------------------------------------------
420 class WebFrameImpl::DeferredScopeStringMatches {
422 DeferredScopeStringMatches(WebFrameImpl* webFrame,
424 const WebString& searchText,
425 const WebFindOptions& options,
427 : m_timer(this, &DeferredScopeStringMatches::doTimeout)
428 , m_webFrame(webFrame)
429 , m_identifier(identifier)
430 , m_searchText(searchText)
434 m_timer.startOneShot(0.0);
438 void doTimeout(Timer<DeferredScopeStringMatches>*)
440 m_webFrame->callScopeStringMatches(
441 this, m_identifier, m_searchText, m_options, m_reset);
444 Timer<DeferredScopeStringMatches> m_timer;
445 RefPtr<WebFrameImpl> m_webFrame;
447 WebString m_searchText;
448 WebFindOptions m_options;
453 // WebFrame -------------------------------------------------------------------
455 int WebFrame::instanceCount()
460 WebFrame* WebFrame::frameForEnteredContext()
463 ScriptController::retrieveFrameForEnteredContext();
464 return WebFrameImpl::fromFrame(frame);
467 WebFrame* WebFrame::frameForCurrentContext()
470 ScriptController::retrieveFrameForCurrentContext();
471 return WebFrameImpl::fromFrame(frame);
474 WebFrame* WebFrame::fromFrameOwnerElement(const WebElement& element)
476 return WebFrameImpl::fromFrameOwnerElement(
477 PassRefPtr<Element>(element).get());
480 WebString WebFrameImpl::name() const
482 return m_frame->tree()->uniqueName();
485 void WebFrameImpl::setName(const WebString& name)
487 m_frame->tree()->setName(name);
490 long long WebFrameImpl::identifier() const
495 WebURL WebFrameImpl::url() const
497 const WebDataSource* ds = dataSource();
500 return ds->request().url();
503 WebURL WebFrameImpl::favIconURL() const
505 FrameLoader* frameLoader = m_frame->loader();
506 // The URL to the favicon may be in the header. As such, only
507 // ask the loader for the favicon if it's finished loading.
508 if (frameLoader->state() == FrameStateComplete) {
509 const KURL& url = frameLoader->iconURL();
516 WebURL WebFrameImpl::openSearchDescriptionURL() const
518 FrameLoader* frameLoader = m_frame->loader();
519 if (frameLoader->state() == FrameStateComplete
520 && m_frame->document() && m_frame->document()->head()
521 && !m_frame->tree()->parent()) {
522 HTMLHeadElement* head = m_frame->document()->head();
524 RefPtr<HTMLCollection> children = head->children();
525 for (Node* child = children->firstItem(); child; child = children->nextItem()) {
526 HTMLLinkElement* linkElement = toHTMLLinkElement(child);
528 && linkElement->type() == osdType
529 && linkElement->rel() == osdRel
530 && !linkElement->href().isEmpty())
531 return linkElement->href();
538 WebString WebFrameImpl::encoding() const
540 return frame()->loader()->writer()->encoding();
543 WebSize WebFrameImpl::scrollOffset() const
545 FrameView* view = frameView();
547 return view->scrollOffset();
552 WebSize WebFrameImpl::contentsSize() const
554 return frame()->view()->contentsSize();
557 int WebFrameImpl::contentsPreferredWidth() const
559 if (m_frame->document() && m_frame->document()->renderView())
560 return m_frame->document()->renderView()->minPreferredLogicalWidth();
564 int WebFrameImpl::documentElementScrollHeight() const
566 if (m_frame->document() && m_frame->document()->documentElement())
567 return m_frame->document()->documentElement()->scrollHeight();
571 bool WebFrameImpl::hasVisibleContent() const
573 return frame()->view()->visibleWidth() > 0 && frame()->view()->visibleHeight() > 0;
576 WebView* WebFrameImpl::view() const
581 WebFrame* WebFrameImpl::opener() const
585 opener = m_frame->loader()->opener();
586 return fromFrame(opener);
589 WebFrame* WebFrameImpl::parent() const
593 parent = m_frame->tree()->parent();
594 return fromFrame(parent);
597 WebFrame* WebFrameImpl::top() const
600 return fromFrame(m_frame->tree()->top());
605 WebFrame* WebFrameImpl::firstChild() const
607 return fromFrame(frame()->tree()->firstChild());
610 WebFrame* WebFrameImpl::lastChild() const
612 return fromFrame(frame()->tree()->lastChild());
615 WebFrame* WebFrameImpl::nextSibling() const
617 return fromFrame(frame()->tree()->nextSibling());
620 WebFrame* WebFrameImpl::previousSibling() const
622 return fromFrame(frame()->tree()->previousSibling());
625 WebFrame* WebFrameImpl::traverseNext(bool wrap) const
627 return fromFrame(frame()->tree()->traverseNextWithWrap(wrap));
630 WebFrame* WebFrameImpl::traversePrevious(bool wrap) const
632 return fromFrame(frame()->tree()->traversePreviousWithWrap(wrap));
635 WebFrame* WebFrameImpl::findChildByName(const WebString& name) const
637 return fromFrame(frame()->tree()->child(name));
640 WebFrame* WebFrameImpl::findChildByExpression(const WebString& xpath) const
645 Document* document = m_frame->document();
647 ExceptionCode ec = 0;
648 PassRefPtr<XPathResult> xpathResult =
649 document->evaluate(xpath,
652 XPathResult::ORDERED_NODE_ITERATOR_TYPE,
653 0, // XPathResult object
655 if (!xpathResult.get())
658 Node* node = xpathResult->iterateNext(ec);
660 if (!node || !node->isFrameOwnerElement())
662 HTMLFrameOwnerElement* frameElement =
663 static_cast<HTMLFrameOwnerElement*>(node);
664 return fromFrame(frameElement->contentFrame());
667 WebDocument WebFrameImpl::document() const
669 if (!m_frame || !m_frame->document())
670 return WebDocument();
671 return WebDocument(m_frame->document());
674 void WebFrameImpl::forms(WebVector<WebFormElement>& results) const
679 RefPtr<HTMLCollection> forms = m_frame->document()->forms();
680 size_t formCount = 0;
681 for (size_t i = 0; i < forms->length(); ++i) {
682 Node* node = forms->item(i);
683 if (node && node->isHTMLElement())
687 WebVector<WebFormElement> temp(formCount);
688 for (size_t i = 0; i < formCount; ++i) {
689 Node* node = forms->item(i);
690 // Strange but true, sometimes item can be 0.
691 if (node && node->isHTMLElement())
692 temp[i] = static_cast<HTMLFormElement*>(node);
697 WebAnimationController* WebFrameImpl::animationController()
699 return &m_animationController;
702 WebPerformance WebFrameImpl::performance() const
704 if (!m_frame || !m_frame->domWindow())
705 return WebPerformance();
707 return WebPerformance(m_frame->domWindow()->performance());
710 WebSecurityOrigin WebFrameImpl::securityOrigin() const
712 if (!m_frame || !m_frame->document())
713 return WebSecurityOrigin();
715 return WebSecurityOrigin(m_frame->document()->securityOrigin());
718 void WebFrameImpl::grantUniversalAccess()
720 ASSERT(m_frame && m_frame->document());
721 if (m_frame && m_frame->document())
722 m_frame->document()->securityOrigin()->grantUniversalAccess();
725 NPObject* WebFrameImpl::windowObject() const
730 return m_frame->script()->windowScriptNPObject();
733 void WebFrameImpl::bindToWindowObject(const WebString& name, NPObject* object)
736 if (!m_frame || !m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
741 m_frame->script()->bindToWindowObject(m_frame, key, object);
747 void WebFrameImpl::executeScript(const WebScriptSource& source)
749 TextPosition1 position(WTF::OneBasedNumber::fromOneBasedInt(source.startLine), WTF::OneBasedNumber::base());
750 m_frame->script()->executeScript(
751 ScriptSourceCode(source.code, source.url, position));
754 void WebFrameImpl::executeScriptInIsolatedWorld(
755 int worldId, const WebScriptSource* sourcesIn, unsigned numSources,
758 Vector<ScriptSourceCode> sources;
760 for (unsigned i = 0; i < numSources; ++i) {
761 TextPosition1 position(WTF::OneBasedNumber::fromOneBasedInt(sourcesIn[i].startLine), WTF::OneBasedNumber::base());
762 sources.append(ScriptSourceCode(
763 sourcesIn[i].code, sourcesIn[i].url, position));
766 m_frame->script()->evaluateInIsolatedWorld(worldId, sources, extensionGroup);
769 void WebFrameImpl::addMessageToConsole(const WebConsoleMessage& message)
773 MessageLevel webCoreMessageLevel;
774 switch (message.level) {
775 case WebConsoleMessage::LevelTip:
776 webCoreMessageLevel = TipMessageLevel;
778 case WebConsoleMessage::LevelLog:
779 webCoreMessageLevel = LogMessageLevel;
781 case WebConsoleMessage::LevelWarning:
782 webCoreMessageLevel = WarningMessageLevel;
784 case WebConsoleMessage::LevelError:
785 webCoreMessageLevel = ErrorMessageLevel;
788 ASSERT_NOT_REACHED();
792 frame()->domWindow()->console()->addMessage(
793 OtherMessageSource, LogMessageType, webCoreMessageLevel, message.text,
797 void WebFrameImpl::collectGarbage()
801 if (!m_frame->settings()->isJavaScriptEnabled())
803 // FIXME: Move this to the ScriptController and make it JS neutral.
805 m_frame->script()->collectGarbage();
812 v8::Handle<v8::Value> WebFrameImpl::executeScriptAndReturnValue(
813 const WebScriptSource& source)
815 TextPosition1 position(WTF::OneBasedNumber::fromOneBasedInt(source.startLine), WTF::OneBasedNumber::base());
816 return m_frame->script()->executeScript(
817 ScriptSourceCode(source.code, source.url, position)).v8Value();
820 // Returns the V8 context for this frame, or an empty handle if there is none.
821 v8::Local<v8::Context> WebFrameImpl::mainWorldScriptContext() const
824 return v8::Local<v8::Context>();
826 return V8Proxy::mainWorldContext(m_frame);
830 bool WebFrameImpl::insertStyleText(
831 const WebString& css, const WebString& id) {
832 Document* document = frame()->document();
835 Element* documentElement = document->documentElement();
836 if (!documentElement)
839 ExceptionCode err = 0;
842 Element* oldElement = document->getElementById(id);
844 Node* parent = oldElement->parentNode();
847 parent->removeChild(oldElement, err);
851 RefPtr<Element> stylesheet = document->createElement(
852 HTMLNames::styleTag, false);
854 stylesheet->setAttribute(HTMLNames::idAttr, id);
855 stylesheet->setTextContent(css, err);
857 Node* first = documentElement->firstChild();
858 bool success = documentElement->insertBefore(stylesheet, first, err);
863 void WebFrameImpl::reload(bool ignoreCache)
865 m_frame->loader()->history()->saveDocumentAndScrollState();
866 m_frame->loader()->reload(ignoreCache);
869 void WebFrameImpl::loadRequest(const WebURLRequest& request)
871 ASSERT(!request.isNull());
872 const ResourceRequest& resourceRequest = request.toResourceRequest();
874 if (resourceRequest.url().protocolIs("javascript")) {
875 loadJavaScriptURL(resourceRequest.url());
879 m_frame->loader()->load(resourceRequest, false);
882 void WebFrameImpl::loadHistoryItem(const WebHistoryItem& item)
884 RefPtr<HistoryItem> historyItem = PassRefPtr<HistoryItem>(item);
885 ASSERT(historyItem.get());
887 // If there is no currentItem, which happens when we are navigating in
888 // session history after a crash, we need to manufacture one otherwise WebKit
889 // hoarks. This is probably the wrong thing to do, but it seems to work.
890 RefPtr<HistoryItem> currentItem = m_frame->loader()->history()->currentItem();
892 currentItem = HistoryItem::create();
893 currentItem->setLastVisitWasFailure(true);
894 m_frame->loader()->history()->setCurrentItem(currentItem.get());
895 m_frame->page()->backForward()->setCurrentItem(currentItem.get());
898 m_frame->loader()->history()->goToItem(
899 historyItem.get(), FrameLoadTypeIndexedBackForward);
902 void WebFrameImpl::loadData(const WebData& data,
903 const WebString& mimeType,
904 const WebString& textEncoding,
905 const WebURL& baseURL,
906 const WebURL& unreachableURL,
909 SubstituteData substData(data, mimeType, textEncoding, unreachableURL);
910 ASSERT(substData.isValid());
912 // If we are loading substitute data to replace an existing load, then
913 // inherit all of the properties of that original request. This way,
914 // reload will re-attempt the original request. It is essential that
915 // we only do this when there is an unreachableURL since a non-empty
916 // unreachableURL informs FrameLoader::reload to load unreachableURL
917 // instead of the currently loaded URL.
918 ResourceRequest request;
919 if (replace && !unreachableURL.isEmpty())
920 request = m_frame->loader()->originalRequest();
921 request.setURL(baseURL);
923 m_frame->loader()->load(request, substData, false);
925 // Do this to force WebKit to treat the load as replacing the currently
927 m_frame->loader()->setReplacing();
931 void WebFrameImpl::loadHTMLString(const WebData& data,
932 const WebURL& baseURL,
933 const WebURL& unreachableURL,
937 WebString::fromUTF8("text/html"),
938 WebString::fromUTF8("UTF-8"),
944 bool WebFrameImpl::isLoading() const
948 return m_frame->loader()->isLoading();
951 void WebFrameImpl::stopLoading()
956 // FIXME: Figure out what we should really do here. It seems like a bug
957 // that FrameLoader::stopLoading doesn't call stopAllLoaders.
958 m_frame->loader()->stopAllLoaders();
959 m_frame->loader()->stopLoading(UnloadEventPolicyNone);
962 WebDataSource* WebFrameImpl::provisionalDataSource() const
964 FrameLoader* frameLoader = m_frame->loader();
966 // We regard the policy document loader as still provisional.
967 DocumentLoader* docLoader = frameLoader->provisionalDocumentLoader();
969 docLoader = frameLoader->policyDocumentLoader();
971 return DataSourceForDocLoader(docLoader);
974 WebDataSource* WebFrameImpl::dataSource() const
976 return DataSourceForDocLoader(m_frame->loader()->documentLoader());
979 WebHistoryItem WebFrameImpl::previousHistoryItem() const
981 // We use the previous item here because documentState (filled-out forms)
982 // only get saved to history when it becomes the previous item. The caller
983 // is expected to query the history item after a navigation occurs, after
984 // the desired history item has become the previous entry.
985 return WebHistoryItem(m_frame->loader()->history()->previousItem());
988 WebHistoryItem WebFrameImpl::currentHistoryItem() const
990 // If we are still loading, then we don't want to clobber the current
991 // history item as this could cause us to lose the scroll position and
992 // document state. However, it is OK for new navigations.
993 if (m_frame->loader()->loadType() == FrameLoadTypeStandard
994 || !m_frame->loader()->activeDocumentLoader()->isLoadingInAPISense())
995 m_frame->loader()->history()->saveDocumentAndScrollState();
997 return WebHistoryItem(m_frame->page()->backForward()->currentItem());
1000 void WebFrameImpl::enableViewSourceMode(bool enable)
1003 m_frame->setInViewSourceMode(enable);
1006 bool WebFrameImpl::isViewSourceModeEnabled() const
1009 return m_frame->inViewSourceMode();
1014 void WebFrameImpl::setReferrerForRequest(
1015 WebURLRequest& request, const WebURL& referrerURL) {
1017 if (referrerURL.isEmpty())
1018 referrer = m_frame->loader()->outgoingReferrer();
1020 referrer = referrerURL.spec().utf16();
1021 if (SecurityOrigin::shouldHideReferrer(request.url(), referrer))
1023 request.setHTTPHeaderField(WebString::fromUTF8("Referer"), referrer);
1026 void WebFrameImpl::dispatchWillSendRequest(WebURLRequest& request)
1028 ResourceResponse response;
1029 m_frame->loader()->client()->dispatchWillSendRequest(
1030 0, 0, request.toMutableResourceRequest(), response);
1033 WebURLLoader* WebFrameImpl::createAssociatedURLLoader()
1035 return new AssociatedURLLoader(this);
1038 void WebFrameImpl::commitDocumentData(const char* data, size_t length)
1040 m_frame->loader()->documentLoader()->commitData(data, length);
1043 unsigned WebFrameImpl::unloadListenerCount() const
1045 return frame()->domWindow()->pendingUnloadEventListeners();
1048 bool WebFrameImpl::isProcessingUserGesture() const
1050 return frame()->loader()->isProcessingUserGesture();
1053 bool WebFrameImpl::willSuppressOpenerInNewFrame() const
1055 return frame()->loader()->suppressOpenerInNewFrame();
1058 void WebFrameImpl::replaceSelection(const WebString& text)
1060 RefPtr<DocumentFragment> fragment = createFragmentFromText(
1061 frame()->selection()->toNormalizedRange().get(), text);
1062 applyCommand(ReplaceSelectionCommand::create(
1063 frame()->document(), fragment.get(), false, true, true));
1066 void WebFrameImpl::insertText(const WebString& text)
1068 Editor* editor = frame()->editor();
1070 if (editor->hasComposition())
1071 editor->confirmComposition(text);
1073 editor->insertText(text, 0);
1076 void WebFrameImpl::setMarkedText(
1077 const WebString& text, unsigned location, unsigned length)
1079 Editor* editor = frame()->editor();
1081 Vector<CompositionUnderline> decorations;
1082 editor->setComposition(text, decorations, location, length);
1085 void WebFrameImpl::unmarkText()
1087 frame()->editor()->confirmCompositionWithoutDisturbingSelection();
1090 bool WebFrameImpl::hasMarkedText() const
1092 return frame()->editor()->hasComposition();
1095 WebRange WebFrameImpl::markedRange() const
1097 return frame()->editor()->compositionRange();
1100 bool WebFrameImpl::firstRectForCharacterRange(unsigned location, unsigned length, WebRect& rect) const
1102 if ((location + length < location) && (location + length))
1105 Element* selectionRoot = frame()->selection()->rootEditableElement();
1106 Element* scope = selectionRoot ? selectionRoot : frame()->document()->documentElement();
1107 RefPtr<Range> range = TextIterator::rangeFromLocationAndLength(scope, location, length);
1110 IntRect intRect = frame()->editor()->firstRectForRange(range.get());
1111 rect = WebRect(intRect.x(), intRect.y(), intRect.width(), intRect.height());
1116 bool WebFrameImpl::executeCommand(const WebString& name)
1120 if (name.length() <= 2)
1123 // Since we don't have NSControl, we will convert the format of command
1124 // string and call the function on Editor directly.
1125 String command = name;
1127 // Make sure the first letter is upper case.
1128 command.replace(0, 1, command.substring(0, 1).upper());
1130 // Remove the trailing ':' if existing.
1131 if (command[command.length() - 1] == UChar(':'))
1132 command = command.substring(0, command.length() - 1);
1134 if (command == "Copy") {
1135 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1136 if (pluginContainer) {
1137 pluginContainer->copy();
1144 // Specially handling commands that Editor::execCommand does not directly
1146 if (command == "DeleteToEndOfParagraph") {
1147 Editor* editor = frame()->editor();
1148 if (!editor->deleteWithDirection(DirectionForward,
1152 editor->deleteWithDirection(DirectionForward,
1153 CharacterGranularity,
1157 } else if (command == "Indent")
1158 frame()->editor()->indent();
1159 else if (command == "Outdent")
1160 frame()->editor()->outdent();
1161 else if (command == "DeleteBackward")
1162 rv = frame()->editor()->command(AtomicString("BackwardDelete")).execute();
1163 else if (command == "DeleteForward")
1164 rv = frame()->editor()->command(AtomicString("ForwardDelete")).execute();
1165 else if (command == "AdvanceToNextMisspelling") {
1166 // False must be passed here, or the currently selected word will never be
1168 frame()->editor()->advanceToNextMisspelling(false);
1169 } else if (command == "ToggleSpellPanel")
1170 frame()->editor()->showSpellingGuessPanel();
1172 rv = frame()->editor()->command(command).execute();
1176 bool WebFrameImpl::executeCommand(const WebString& name, const WebString& value)
1179 String webName = name;
1181 // moveToBeginningOfDocument and moveToEndfDocument are only handled by WebKit
1182 // for editable nodes.
1183 if (!frame()->editor()->canEdit() && webName == "moveToBeginningOfDocument")
1184 return viewImpl()->propagateScroll(ScrollUp, ScrollByDocument);
1186 if (!frame()->editor()->canEdit() && webName == "moveToEndOfDocument")
1187 return viewImpl()->propagateScroll(ScrollDown, ScrollByDocument);
1189 return frame()->editor()->command(webName).execute(value);
1192 bool WebFrameImpl::isCommandEnabled(const WebString& name) const
1195 return frame()->editor()->command(name).isEnabled();
1198 void WebFrameImpl::enableContinuousSpellChecking(bool enable)
1200 if (enable == isContinuousSpellCheckingEnabled())
1202 frame()->editor()->toggleContinuousSpellChecking();
1205 bool WebFrameImpl::isContinuousSpellCheckingEnabled() const
1207 return frame()->editor()->isContinuousSpellCheckingEnabled();
1210 bool WebFrameImpl::hasSelection() const
1212 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1213 if (pluginContainer)
1214 return pluginContainer->plugin()->hasSelection();
1216 // frame()->selection()->isNone() never returns true.
1217 return (frame()->selection()->start() != frame()->selection()->end());
1220 WebRange WebFrameImpl::selectionRange() const
1222 return frame()->selection()->toNormalizedRange();
1225 WebString WebFrameImpl::selectionAsText() const
1227 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1228 if (pluginContainer)
1229 return pluginContainer->plugin()->selectionAsText();
1231 RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1235 String text = range->text();
1237 replaceNewlinesWithWindowsStyleNewlines(text);
1239 replaceNBSPWithSpace(text);
1243 WebString WebFrameImpl::selectionAsMarkup() const
1245 WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
1246 if (pluginContainer)
1247 return pluginContainer->plugin()->selectionAsMarkup();
1249 RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1253 return createMarkup(range.get(), 0);
1256 void WebFrameImpl::selectWordAroundPosition(Frame* frame, VisiblePosition pos)
1258 VisibleSelection selection(pos);
1259 selection.expandUsingGranularity(WordGranularity);
1261 if (frame->selection()->shouldChangeSelection(selection)) {
1262 TextGranularity granularity = selection.isRange() ? WordGranularity : CharacterGranularity;
1263 frame->selection()->setSelection(selection, granularity);
1267 bool WebFrameImpl::selectWordAroundCaret()
1269 SelectionController* controller = frame()->selection();
1270 ASSERT(!controller->isNone());
1271 if (controller->isNone() || controller->isRange())
1273 selectWordAroundPosition(frame(), controller->selection().visibleStart());
1277 int WebFrameImpl::printBegin(const WebSize& pageSize,
1278 const WebNode& constrainToNode,
1280 bool* useBrowserOverlays)
1282 ASSERT(!frame()->document()->isFrameSet());
1283 WebPluginContainerImpl* pluginContainer = 0;
1284 if (constrainToNode.isNull()) {
1285 // If this is a plugin document, check if the plugin supports its own
1286 // printing. If it does, we will delegate all printing to that.
1287 pluginContainer = pluginContainerFromFrame(frame());
1289 // We only support printing plugin nodes for now.
1290 const Node* coreNode = constrainToNode.constUnwrap<Node>();
1291 if (coreNode->hasTagName(HTMLNames::objectTag) || coreNode->hasTagName(HTMLNames::embedTag)) {
1292 RenderObject* object = coreNode->renderer();
1293 if (object && object->isWidget()) {
1294 Widget* widget = toRenderWidget(object)->widget();
1295 if (widget && widget->isPluginContainer())
1296 pluginContainer = static_cast<WebPluginContainerImpl*>(widget);
1301 if (pluginContainer && pluginContainer->supportsPaginatedPrint())
1302 m_printContext.set(new ChromePluginPrintContext(frame(), pluginContainer, printerDPI));
1304 m_printContext.set(new ChromePrintContext(frame()));
1306 FloatRect rect(0, 0, static_cast<float>(pageSize.width),
1307 static_cast<float>(pageSize.height));
1308 m_printContext->begin(rect.width(), rect.height());
1310 // We ignore the overlays calculation for now since they are generated in the
1311 // browser. pageHeight is actually an output parameter.
1312 m_printContext->computePageRects(rect, 0, 0, 1.0, pageHeight);
1313 if (useBrowserOverlays)
1314 *useBrowserOverlays = m_printContext->shouldUseBrowserOverlays();
1316 return m_printContext->pageCount();
1319 float WebFrameImpl::getPrintPageShrink(int page)
1321 // Ensure correct state.
1322 if (!m_printContext.get() || page < 0) {
1323 ASSERT_NOT_REACHED();
1327 return m_printContext->getPageShrink(page);
1330 float WebFrameImpl::printPage(int page, WebCanvas* canvas)
1332 // Ensure correct state.
1333 if (!m_printContext.get() || page < 0 || !frame() || !frame()->document()) {
1334 ASSERT_NOT_REACHED();
1338 #if OS(WINDOWS) || OS(LINUX) || OS(FREEBSD) || OS(SOLARIS)
1339 PlatformContextSkia context(canvas);
1340 GraphicsContext spool(&context);
1342 GraphicsContext spool(canvas);
1343 LocalCurrentGraphicsContext localContext(&spool);
1346 return m_printContext->spoolPage(spool, page);
1349 void WebFrameImpl::printEnd()
1351 ASSERT(m_printContext.get());
1352 if (m_printContext.get())
1353 m_printContext->end();
1354 m_printContext.clear();
1357 bool WebFrameImpl::isPageBoxVisible(int pageIndex)
1359 return frame()->document()->isPageBoxVisible(pageIndex);
1362 void WebFrameImpl::pageSizeAndMarginsInPixels(int pageIndex,
1369 IntSize size(pageSize.width, pageSize.height);
1370 frame()->document()->pageSizeAndMarginsInPixels(pageIndex,
1379 bool WebFrameImpl::find(int identifier,
1380 const WebString& searchText,
1381 const WebFindOptions& options,
1382 bool wrapWithinFrame,
1383 WebRect* selectionRect)
1385 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
1387 if (!options.findNext)
1388 frame()->page()->unmarkAllTextMatches();
1390 setMarkerActive(m_activeMatch.get(), false); // Active match is changing.
1392 // Starts the search from the current selection.
1393 bool startInSelection = true;
1395 // If the user has selected something since the last Find operation we want
1396 // to start from there. Otherwise, we start searching from where the last Find
1397 // operation left off (either a Find or a FindNext operation).
1398 VisibleSelection selection(frame()->selection()->selection());
1399 bool activeSelection = !selection.isNone();
1400 if (!activeSelection && m_activeMatch) {
1401 selection = VisibleSelection(m_activeMatch.get());
1402 frame()->selection()->setSelection(selection);
1405 ASSERT(frame() && frame()->view());
1406 bool found = frame()->editor()->findString(
1407 searchText, options.forward, options.matchCase, wrapWithinFrame,
1410 // Store which frame was active. This will come in handy later when we
1411 // change the active match ordinal below.
1412 WebFrameImpl* oldActiveFrame = mainFrameImpl->m_activeMatchFrame;
1413 // Set this frame as the active frame (the one with the active highlight).
1414 mainFrameImpl->m_activeMatchFrame = this;
1416 // We found something, so we can now query the selection for its position.
1417 VisibleSelection newSelection(frame()->selection()->selection());
1418 IntRect currSelectionRect;
1420 // If we thought we found something, but it couldn't be selected (perhaps
1421 // because it was marked -webkit-user-select: none), we can't set it to
1422 // be active but we still continue searching. This matches Safari's
1423 // behavior, including some oddities when selectable and un-selectable text
1424 // are mixed on a page: see https://bugs.webkit.org/show_bug.cgi?id=19127.
1425 if (newSelection.isNone() || (newSelection.start() == newSelection.end()))
1428 m_activeMatch = newSelection.toNormalizedRange();
1429 currSelectionRect = m_activeMatch->boundingBox();
1430 setMarkerActive(m_activeMatch.get(), true); // Active.
1431 // WebKit draws the highlighting for all matches.
1432 executeCommand(WebString::fromUTF8("Unselect"));
1435 // Make sure no node is focused. See http://crbug.com/38700.
1436 frame()->document()->setFocusedNode(0);
1438 if (!options.findNext || activeSelection) {
1439 // This is either a Find operation or a Find-next from a new start point
1440 // due to a selection, so we set the flag to ask the scoping effort
1441 // to find the active rect for us so we can update the ordinal (n of m).
1442 m_locatingActiveRect = true;
1444 if (oldActiveFrame != this) {
1445 // If the active frame has changed it means that we have a multi-frame
1446 // page and we just switch to searching in a new frame. Then we just
1447 // want to reset the index.
1448 if (options.forward)
1449 m_activeMatchIndex = 0;
1451 m_activeMatchIndex = m_lastMatchCount - 1;
1453 // We are still the active frame, so increment (or decrement) the
1454 // |m_activeMatchIndex|, wrapping if needed (on single frame pages).
1455 options.forward ? ++m_activeMatchIndex : --m_activeMatchIndex;
1456 if (m_activeMatchIndex + 1 > m_lastMatchCount)
1457 m_activeMatchIndex = 0;
1458 if (m_activeMatchIndex == -1)
1459 m_activeMatchIndex = m_lastMatchCount - 1;
1461 if (selectionRect) {
1462 WebRect rect = frame()->view()->convertToContainingWindow(currSelectionRect);
1463 rect.x -= frameView()->scrollOffset().width();
1464 rect.y -= frameView()->scrollOffset().height();
1465 *selectionRect = rect;
1467 reportFindInPageSelection(rect, m_activeMatchIndex + 1, identifier);
1471 // Nothing was found in this frame.
1474 // Erase all previous tickmarks and highlighting.
1475 invalidateArea(InvalidateAll);
1481 void WebFrameImpl::stopFinding(bool clearSelection)
1483 if (!clearSelection)
1484 setFindEndstateFocusAndSelection();
1485 cancelPendingScopingEffort();
1487 // Remove all markers for matches found and turn off the highlighting.
1488 frame()->document()->markers()->removeMarkers(DocumentMarker::TextMatch);
1489 frame()->editor()->setMarkedTextMatchesAreHighlighted(false);
1491 // Let the frame know that we don't want tickmarks or highlighting anymore.
1492 invalidateArea(InvalidateAll);
1495 void WebFrameImpl::scopeStringMatches(int identifier,
1496 const WebString& searchText,
1497 const WebFindOptions& options,
1500 if (!shouldScopeMatches(searchText))
1503 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
1506 // This is a brand new search, so we need to reset everything.
1507 // Scoping is just about to begin.
1508 m_scopingComplete = false;
1509 // Clear highlighting for this frame.
1510 if (frame()->editor()->markedTextMatchesAreHighlighted())
1511 frame()->page()->unmarkAllTextMatches();
1512 // Clear the counters from last operation.
1513 m_lastMatchCount = 0;
1514 m_nextInvalidateAfter = 0;
1516 m_resumeScopingFromRange = 0;
1518 mainFrameImpl->m_framesScopingCount++;
1520 // Now, defer scoping until later to allow find operation to finish quickly.
1521 scopeStringMatchesSoon(
1525 false); // false=we just reset, so don't do it again.
1529 RefPtr<Range> searchRange(rangeOfContents(frame()->document()));
1531 ExceptionCode ec = 0, ec2 = 0;
1532 if (m_resumeScopingFromRange.get()) {
1533 // This is a continuation of a scoping operation that timed out and didn't
1534 // complete last time around, so we should start from where we left off.
1535 searchRange->setStart(m_resumeScopingFromRange->startContainer(),
1536 m_resumeScopingFromRange->startOffset(ec2) + 1,
1539 if (ec2) // A non-zero |ec| happens when navigating during search.
1540 ASSERT_NOT_REACHED();
1545 Node* originalEndContainer = searchRange->endContainer();
1546 int originalEndOffset = searchRange->endOffset();
1548 // This timeout controls how long we scope before releasing control. This
1549 // value does not prevent us from running for longer than this, but it is
1550 // periodically checked to see if we have exceeded our allocated time.
1551 const double maxScopingDuration = 0.1; // seconds
1554 bool timedOut = false;
1555 double startTime = currentTime();
1557 // Find next occurrence of the search string.
1558 // FIXME: (http://b/1088245) This WebKit operation may run for longer
1559 // than the timeout value, and is not interruptible as it is currently
1560 // written. We may need to rewrite it with interruptibility in mind, or
1561 // find an alternative.
1562 RefPtr<Range> resultRange(findPlainText(searchRange.get(),
1565 options.matchCase));
1566 if (resultRange->collapsed(ec)) {
1567 if (!resultRange->startContainer()->isInShadowTree())
1570 searchRange->setStartAfter(
1571 resultRange->startContainer()->shadowAncestorNode(), ec);
1572 searchRange->setEnd(originalEndContainer, originalEndOffset, ec);
1576 // Only treat the result as a match if it is visible
1577 if (frame()->editor()->insideVisibleArea(resultRange.get())) {
1580 // Catch a special case where Find found something but doesn't know what
1581 // the bounding box for it is. In this case we set the first match we find
1582 // as the active rect.
1583 IntRect resultBounds = resultRange->boundingBox();
1584 IntRect activeSelectionRect;
1585 if (m_locatingActiveRect) {
1586 activeSelectionRect = m_activeMatch.get() ?
1587 m_activeMatch->boundingBox() : resultBounds;
1590 // If the Find function found a match it will have stored where the
1591 // match was found in m_activeSelectionRect on the current frame. If we
1592 // find this rect during scoping it means we have found the active
1594 bool foundActiveMatch = false;
1595 if (m_locatingActiveRect && (activeSelectionRect == resultBounds)) {
1596 // We have found the active tickmark frame.
1597 mainFrameImpl->m_activeMatchFrame = this;
1598 foundActiveMatch = true;
1599 // We also know which tickmark is active now.
1600 m_activeMatchIndex = matchCount - 1;
1601 // To stop looking for the active tickmark, we set this flag.
1602 m_locatingActiveRect = false;
1604 // Notify browser of new location for the selected rectangle.
1605 resultBounds.move(-frameView()->scrollOffset().width(),
1606 -frameView()->scrollOffset().height());
1607 reportFindInPageSelection(
1608 frame()->view()->convertToContainingWindow(resultBounds),
1609 m_activeMatchIndex + 1,
1613 addMarker(resultRange.get(), foundActiveMatch);
1616 // Set the new start for the search range to be the end of the previous
1617 // result range. There is no need to use a VisiblePosition here,
1618 // since findPlainText will use a TextIterator to go over the visible
1620 searchRange->setStart(resultRange->endContainer(ec), resultRange->endOffset(ec), ec);
1622 Node* shadowTreeRoot = searchRange->shadowTreeRootNode();
1623 if (searchRange->collapsed(ec) && shadowTreeRoot)
1624 searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), ec);
1626 m_resumeScopingFromRange = resultRange;
1627 timedOut = (currentTime() - startTime) >= maxScopingDuration;
1628 } while (!timedOut);
1630 // Remember what we search for last time, so we can skip searching if more
1631 // letters are added to the search string (and last outcome was 0).
1632 m_lastSearchString = searchText;
1634 if (matchCount > 0) {
1635 frame()->editor()->setMarkedTextMatchesAreHighlighted(true);
1637 m_lastMatchCount += matchCount;
1639 // Let the mainframe know how much we found during this pass.
1640 mainFrameImpl->increaseMatchCount(matchCount, identifier);
1644 // If we found anything during this pass, we should redraw. However, we
1645 // don't want to spam too much if the page is extremely long, so if we
1646 // reach a certain point we start throttling the redraw requests.
1648 invalidateIfNecessary();
1650 // Scoping effort ran out of time, lets ask for another time-slice.
1651 scopeStringMatchesSoon(
1655 false); // don't reset.
1656 return; // Done for now, resume work later.
1659 // This frame has no further scoping left, so it is done. Other frames might,
1660 // of course, continue to scope matches.
1661 m_scopingComplete = true;
1662 mainFrameImpl->m_framesScopingCount--;
1664 // If this is the last frame to finish scoping we need to trigger the final
1665 // update to be sent.
1666 if (!mainFrameImpl->m_framesScopingCount)
1667 mainFrameImpl->increaseMatchCount(0, identifier);
1669 // This frame is done, so show any scrollbar tickmarks we haven't drawn yet.
1670 invalidateArea(InvalidateScrollbar);
1673 void WebFrameImpl::cancelPendingScopingEffort()
1675 deleteAllValues(m_deferredScopingWork);
1676 m_deferredScopingWork.clear();
1678 m_activeMatchIndex = -1;
1681 void WebFrameImpl::increaseMatchCount(int count, int identifier)
1683 // This function should only be called on the mainframe.
1686 m_totalMatchCount += count;
1688 // Update the UI with the latest findings.
1690 client()->reportFindInPageMatchCount(identifier, m_totalMatchCount, !m_framesScopingCount);
1693 void WebFrameImpl::reportFindInPageSelection(const WebRect& selectionRect,
1694 int activeMatchOrdinal,
1697 // Update the UI with the latest selection rect.
1699 client()->reportFindInPageSelection(identifier, ordinalOfFirstMatchForFrame(this) + activeMatchOrdinal, selectionRect);
1702 void WebFrameImpl::resetMatchCount()
1704 m_totalMatchCount = 0;
1705 m_framesScopingCount = 0;
1708 WebString WebFrameImpl::contentAsText(size_t maxChars) const
1714 frameContentAsPlainText(maxChars, m_frame, &text);
1715 return String::adopt(text);
1718 WebString WebFrameImpl::contentAsMarkup() const
1720 return createFullMarkup(m_frame->document());
1723 WebString WebFrameImpl::renderTreeAsText() const
1725 return externalRepresentation(m_frame);
1728 WebString WebFrameImpl::counterValueForElementById(const WebString& id) const
1733 Element* element = m_frame->document()->getElementById(id);
1737 return counterValueForElement(element);
1740 WebString WebFrameImpl::markerTextForListItem(const WebElement& webElement) const
1742 return WebCore::markerTextForListItem(const_cast<Element*>(webElement.constUnwrap<Element>()));
1745 int WebFrameImpl::pageNumberForElementById(const WebString& id,
1746 float pageWidthInPixels,
1747 float pageHeightInPixels) const
1752 Element* element = m_frame->document()->getElementById(id);
1756 FloatSize pageSize(pageWidthInPixels, pageHeightInPixels);
1757 return PrintContext::pageNumberForElement(element, pageSize);
1760 WebRect WebFrameImpl::selectionBoundsRect() const
1763 return IntRect(frame()->selection()->bounds(false));
1768 bool WebFrameImpl::selectionStartHasSpellingMarkerFor(int from, int length) const
1772 return m_frame->editor()->selectionStartHasSpellingMarkerFor(from, length);
1775 bool WebFrameImpl::pauseSVGAnimation(const WebString& animationId, double time, const WebString& elementId)
1783 Document* document = m_frame->document();
1784 if (!document || !document->svgExtensions())
1787 Node* coreNode = document->getElementById(animationId);
1788 if (!coreNode || !SVGSMILElement::isSMILElement(coreNode))
1791 return document->accessSVGExtensions()->sampleAnimationAtTime(elementId, static_cast<SVGSMILElement*>(coreNode), time);
1795 WebString WebFrameImpl::layerTreeAsText() const
1799 return WebString(m_frame->layerTreeAsText());
1802 // WebFrameImpl public ---------------------------------------------------------
1804 PassRefPtr<WebFrameImpl> WebFrameImpl::create(WebFrameClient* client)
1806 return adoptRef(new WebFrameImpl(client));
1809 WebFrameImpl::WebFrameImpl(WebFrameClient* client)
1810 : m_frameLoaderClient(this)
1812 , m_activeMatchFrame(0)
1813 , m_activeMatchIndex(-1)
1814 , m_locatingActiveRect(false)
1815 , m_resumeScopingFromRange(0)
1816 , m_lastMatchCount(-1)
1817 , m_totalMatchCount(-1)
1818 , m_framesScopingCount(-1)
1819 , m_scopingComplete(false)
1820 , m_nextInvalidateAfter(0)
1821 , m_animationController(this)
1822 , m_identifier(generateFrameIdentifier())
1824 ChromiumBridge::incrementStatsCounter(webFrameActiveCount);
1828 WebFrameImpl::~WebFrameImpl()
1830 ChromiumBridge::decrementStatsCounter(webFrameActiveCount);
1833 cancelPendingScopingEffort();
1834 clearPasswordListeners();
1837 void WebFrameImpl::initializeAsMainFrame(WebViewImpl* webViewImpl)
1839 RefPtr<Frame> frame = Frame::create(webViewImpl->page(), 0, &m_frameLoaderClient);
1840 m_frame = frame.get();
1842 // Add reference on behalf of FrameLoader. See comments in
1843 // WebFrameLoaderClient::frameLoaderDestroyed for more info.
1846 // We must call init() after m_frame is assigned because it is referenced
1851 PassRefPtr<Frame> WebFrameImpl::createChildFrame(
1852 const FrameLoadRequest& request, HTMLFrameOwnerElement* ownerElement)
1854 RefPtr<WebFrameImpl> webframe(adoptRef(new WebFrameImpl(m_client)));
1856 // Add an extra ref on behalf of the Frame/FrameLoader, which references the
1857 // WebFrame via the FrameLoaderClient interface. See the comment at the top
1858 // of this file for more info.
1861 RefPtr<Frame> childFrame = Frame::create(
1862 m_frame->page(), ownerElement, &webframe->m_frameLoaderClient);
1863 webframe->m_frame = childFrame.get();
1865 childFrame->tree()->setName(request.frameName());
1867 m_frame->tree()->appendChild(childFrame);
1869 // Frame::init() can trigger onload event in the parent frame,
1870 // which may detach this frame and trigger a null-pointer access
1871 // in FrameTree::removeChild. Move init() after appendChild call
1872 // so that webframe->mFrame is in the tree before triggering
1873 // onload event handler.
1874 // Because the event handler may set webframe->mFrame to null,
1875 // it is necessary to check the value after calling init() and
1876 // return without loading URL.
1878 childFrame->init(); // create an empty document
1879 if (!childFrame->tree()->parent())
1882 m_frame->loader()->loadURLIntoChildFrame(
1883 request.resourceRequest().url(),
1884 request.resourceRequest().httpReferrer(),
1887 // A synchronous navigation (about:blank) would have already processed
1888 // onload, so it is possible for the frame to have already been destroyed by
1889 // script in the page.
1890 if (!childFrame->tree()->parent())
1893 return childFrame.release();
1896 void WebFrameImpl::layout()
1898 // layout this frame
1899 FrameView* view = m_frame->view();
1901 view->updateLayoutAndStyleIfNeededRecursive();
1904 void WebFrameImpl::paintWithContext(GraphicsContext& gc, const WebRect& rect)
1906 IntRect dirtyRect(rect);
1908 if (m_frame->document() && frameView()) {
1910 frameView()->paint(&gc, dirtyRect);
1911 m_frame->page()->inspectorController()->drawNodeHighlight(gc);
1913 gc.fillRect(dirtyRect, Color::white, ColorSpaceDeviceRGB);
1917 void WebFrameImpl::paint(WebCanvas* canvas, const WebRect& rect)
1922 GraphicsContext gc(canvas);
1923 LocalCurrentGraphicsContext localContext(&gc);
1924 #elif WEBKIT_USING_SKIA
1925 PlatformContextSkia context(canvas);
1927 // PlatformGraphicsContext is actually a pointer to PlatformContextSkia
1928 GraphicsContext gc(reinterpret_cast<PlatformGraphicsContext*>(&context));
1932 paintWithContext(gc, rect);
1935 void WebFrameImpl::createFrameView()
1937 ASSERT(m_frame); // If m_frame doesn't exist, we probably didn't init properly.
1939 Page* page = m_frame->page();
1941 ASSERT(page->mainFrame());
1943 bool isMainFrame = m_frame == page->mainFrame();
1944 if (isMainFrame && m_frame->view())
1945 m_frame->view()->setParentVisible(false);
1947 m_frame->setView(0);
1949 WebViewImpl* webView = viewImpl();
1951 RefPtr<FrameView> view;
1953 view = FrameView::create(m_frame, webView->size());
1955 view = FrameView::create(m_frame);
1957 m_frame->setView(view);
1959 if (webView->isTransparent())
1960 view->setTransparent(true);
1962 // FIXME: The Mac code has a comment about this possibly being unnecessary.
1963 // See installInFrame in WebCoreFrameBridge.mm
1964 if (m_frame->ownerRenderer())
1965 m_frame->ownerRenderer()->setWidget(view.get());
1967 if (HTMLFrameOwnerElement* owner = m_frame->ownerElement())
1968 view->setCanHaveScrollbars(owner->scrollingMode() != ScrollbarAlwaysOff);
1971 view->setParentVisible(true);
1974 WebFrameImpl* WebFrameImpl::fromFrame(Frame* frame)
1979 return static_cast<FrameLoaderClientImpl*>(frame->loader()->client())->webFrame();
1982 WebFrameImpl* WebFrameImpl::fromFrameOwnerElement(Element* element)
1985 || !element->isFrameOwnerElement()
1986 || (!element->hasTagName(HTMLNames::iframeTag)
1987 && !element->hasTagName(HTMLNames::frameTag)))
1990 HTMLFrameOwnerElement* frameElement =
1991 static_cast<HTMLFrameOwnerElement*>(element);
1992 return fromFrame(frameElement->contentFrame());
1995 WebViewImpl* WebFrameImpl::viewImpl() const
2000 return WebViewImpl::fromPage(m_frame->page());
2003 WebDataSourceImpl* WebFrameImpl::dataSourceImpl() const
2005 return static_cast<WebDataSourceImpl*>(dataSource());
2008 WebDataSourceImpl* WebFrameImpl::provisionalDataSourceImpl() const
2010 return static_cast<WebDataSourceImpl*>(provisionalDataSource());
2013 void WebFrameImpl::setFindEndstateFocusAndSelection()
2015 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
2017 if (this == mainFrameImpl->activeMatchFrame() && m_activeMatch.get()) {
2018 // If the user has set the selection since the match was found, we
2019 // don't focus anything.
2020 VisibleSelection selection(frame()->selection()->selection());
2021 if (!selection.isNone())
2024 // Try to find the first focusable node up the chain, which will, for
2025 // example, focus links if we have found text within the link.
2026 Node* node = m_activeMatch->firstNode();
2027 while (node && !node->isFocusable() && node != frame()->document())
2028 node = node->parentNode();
2030 if (node && node != frame()->document()) {
2031 // Found a focusable parent node. Set focus to it.
2032 frame()->document()->setFocusedNode(node);
2036 // Iterate over all the nodes in the range until we find a focusable node.
2037 // This, for example, sets focus to the first link if you search for
2038 // text and text that is within one or more links.
2039 node = m_activeMatch->firstNode();
2040 while (node && node != m_activeMatch->pastLastNode()) {
2041 if (node->isFocusable()) {
2042 frame()->document()->setFocusedNode(node);
2045 node = node->traverseNextNode();
2048 // No node related to the active match was focusable, so set the
2049 // active match as the selection (so that when you end the Find session,
2050 // you'll have the last thing you found highlighted) and make sure that
2051 // we have nothing focused (otherwise you might have text selected but
2052 // a link focused, which is weird).
2053 frame()->selection()->setSelection(m_activeMatch.get());
2054 frame()->document()->setFocusedNode(0);
2058 void WebFrameImpl::didFail(const ResourceError& error, bool wasProvisional)
2062 WebURLError webError = error;
2064 client()->didFailProvisionalLoad(this, webError);
2066 client()->didFailLoad(this, webError);
2069 void WebFrameImpl::setCanHaveScrollbars(bool canHaveScrollbars)
2071 m_frame->view()->setCanHaveScrollbars(canHaveScrollbars);
2074 bool WebFrameImpl::registerPasswordListener(
2075 WebInputElement inputElement,
2076 WebPasswordAutocompleteListener* listener)
2078 RefPtr<HTMLInputElement> element(inputElement.unwrap<HTMLInputElement>());
2079 if (!m_passwordListeners.add(element, listener).second) {
2086 void WebFrameImpl::notifiyPasswordListenerOfAutocomplete(
2087 const WebInputElement& inputElement)
2089 const HTMLInputElement* element = inputElement.constUnwrap<HTMLInputElement>();
2090 WebPasswordAutocompleteListener* listener = getPasswordListener(element);
2091 // Password listeners need to autocomplete other fields that depend on the
2092 // input element with autofill suggestions.
2094 listener->performInlineAutocomplete(element->value(), false, false);
2097 WebPasswordAutocompleteListener* WebFrameImpl::getPasswordListener(
2098 const HTMLInputElement* inputElement)
2100 return m_passwordListeners.get(RefPtr<HTMLInputElement>(const_cast<HTMLInputElement*>(inputElement)));
2103 // WebFrameImpl private --------------------------------------------------------
2105 void WebFrameImpl::closing()
2110 void WebFrameImpl::invalidateArea(AreaToInvalidate area)
2112 ASSERT(frame() && frame()->view());
2113 FrameView* view = frame()->view();
2115 if ((area & InvalidateAll) == InvalidateAll)
2116 view->invalidateRect(view->frameRect());
2118 if ((area & InvalidateContentArea) == InvalidateContentArea) {
2119 IntRect contentArea(
2120 view->x(), view->y(), view->visibleWidth(), view->visibleHeight());
2121 IntRect frameRect = view->frameRect();
2122 contentArea.move(-frameRect.topLeft().x(), -frameRect.topLeft().y());
2123 view->invalidateRect(contentArea);
2126 if ((area & InvalidateScrollbar) == InvalidateScrollbar) {
2127 // Invalidate the vertical scroll bar region for the view.
2128 IntRect scrollBarVert(
2129 view->x() + view->visibleWidth(), view->y(),
2130 ScrollbarTheme::nativeTheme()->scrollbarThickness(),
2131 view->visibleHeight());
2132 IntRect frameRect = view->frameRect();
2133 scrollBarVert.move(-frameRect.topLeft().x(), -frameRect.topLeft().y());
2134 view->invalidateRect(scrollBarVert);
2139 void WebFrameImpl::addMarker(Range* range, bool activeMatch)
2141 // Use a TextIterator to visit the potentially multiple nodes the range
2143 TextIterator markedText(range);
2144 for (; !markedText.atEnd(); markedText.advance()) {
2145 RefPtr<Range> textPiece = markedText.range();
2148 DocumentMarker marker = {
2149 DocumentMarker::TextMatch,
2150 textPiece->startOffset(exception),
2151 textPiece->endOffset(exception),
2156 if (marker.endOffset > marker.startOffset) {
2157 // Find the node to add a marker to and add it.
2158 Node* node = textPiece->startContainer(exception);
2159 frame()->document()->markers()->addMarker(node, marker);
2161 // Rendered rects for markers in WebKit are not populated until each time
2162 // the markers are painted. However, we need it to happen sooner, because
2163 // the whole purpose of tickmarks on the scrollbar is to show where
2164 // matches off-screen are (that haven't been painted yet).
2165 Vector<DocumentMarker> markers = frame()->document()->markers()->markersForNode(node);
2166 frame()->document()->markers()->setRenderedRectForMarker(
2167 textPiece->startContainer(exception),
2168 markers[markers.size() - 1],
2169 range->boundingBox());
2174 void WebFrameImpl::setMarkerActive(Range* range, bool active)
2176 WebCore::ExceptionCode ec;
2177 if (!range || range->collapsed(ec))
2180 frame()->document()->markers()->setMarkersActive(range, active);
2183 int WebFrameImpl::ordinalOfFirstMatchForFrame(WebFrameImpl* frame) const
2186 WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
2187 // Iterate from the main frame up to (but not including) |frame| and
2188 // add up the number of matches found so far.
2189 for (WebFrameImpl* it = mainFrameImpl;
2191 it = static_cast<WebFrameImpl*>(it->traverseNext(true))) {
2192 if (it->m_lastMatchCount > 0)
2193 ordinal += it->m_lastMatchCount;
2198 bool WebFrameImpl::shouldScopeMatches(const String& searchText)
2200 // Don't scope if we can't find a frame or a view or if the frame is not visible.
2201 // The user may have closed the tab/application, so abort.
2202 if (!frame() || !frame()->view() || !hasVisibleContent())
2205 ASSERT(frame()->document() && frame()->view());
2207 // If the frame completed the scoping operation and found 0 matches the last
2208 // time it was searched, then we don't have to search it again if the user is
2209 // just adding to the search string or sending the same search string again.
2210 if (m_scopingComplete && !m_lastSearchString.isEmpty() && !m_lastMatchCount) {
2211 // Check to see if the search string prefixes match.
2212 String previousSearchPrefix =
2213 searchText.substring(0, m_lastSearchString.length());
2215 if (previousSearchPrefix == m_lastSearchString)
2216 return false; // Don't search this frame, it will be fruitless.
2222 void WebFrameImpl::scopeStringMatchesSoon(int identifier, const WebString& searchText,
2223 const WebFindOptions& options, bool reset)
2225 m_deferredScopingWork.append(new DeferredScopeStringMatches(
2226 this, identifier, searchText, options, reset));
2229 void WebFrameImpl::callScopeStringMatches(DeferredScopeStringMatches* caller,
2230 int identifier, const WebString& searchText,
2231 const WebFindOptions& options, bool reset)
2233 m_deferredScopingWork.remove(m_deferredScopingWork.find(caller));
2235 scopeStringMatches(identifier, searchText, options, reset);
2237 // This needs to happen last since searchText is passed by reference.
2241 void WebFrameImpl::invalidateIfNecessary()
2243 if (m_lastMatchCount > m_nextInvalidateAfter) {
2244 // FIXME: (http://b/1088165) Optimize the drawing of the tickmarks and
2245 // remove this. This calculation sets a milestone for when next to
2246 // invalidate the scrollbar and the content area. We do this so that we
2247 // don't spend too much time drawing the scrollbar over and over again.
2248 // Basically, up until the first 500 matches there is no throttle.
2249 // After the first 500 matches, we set set the milestone further and
2250 // further out (750, 1125, 1688, 2K, 3K).
2251 static const int startSlowingDownAfter = 500;
2252 static const int slowdown = 750;
2253 int i = (m_lastMatchCount / startSlowingDownAfter);
2254 m_nextInvalidateAfter += i * slowdown;
2256 invalidateArea(InvalidateScrollbar);
2260 void WebFrameImpl::clearPasswordListeners()
2262 deleteAllValues(m_passwordListeners);
2263 m_passwordListeners.clear();
2266 void WebFrameImpl::loadJavaScriptURL(const KURL& url)
2268 // This is copied from ScriptController::executeIfJavaScriptURL.
2269 // Unfortunately, we cannot just use that method since it is private, and
2270 // it also doesn't quite behave as we require it to for bookmarklets. The
2271 // key difference is that we need to suppress loading the string result
2272 // from evaluating the JS URL if executing the JS URL resulted in a
2273 // location change. We also allow a JS URL to be loaded even if scripts on
2274 // the page are otherwise disabled.
2276 if (!m_frame->document() || !m_frame->page())
2279 String script = decodeURLEscapeSequences(url.string().substring(strlen("javascript:")));
2280 ScriptValue result = m_frame->script()->executeScript(script, true);
2282 String scriptResult;
2283 if (!result.getString(scriptResult))
2286 if (!m_frame->navigationScheduler()->locationChangePending())
2287 m_frame->loader()->writer()->replaceDocument(scriptResult);
2290 } // namespace WebKit