#include "config.h"
#include "WebFrameImpl.h"
#include "AssociatedURLLoader.h"
#include "BackForwardController.h"
#include "Chrome.h"
#include "ClipboardUtilitiesChromium.h"
#include "Console.h"
#include "DOMUtilitiesPrivate.h"
#include "DOMWindow.h"
#include "Document.h"
#include "DocumentLoader.h"
#include "DocumentMarker.h"
#include "DocumentMarkerController.h"
#include "Editor.h"
#include "EventHandler.h"
#include "EventListenerWrapper.h"
#include "FocusController.h"
#include "FontCache.h"
#include "FormState.h"
#include "FrameLoadRequest.h"
#include "FrameLoader.h"
#include "FrameSelection.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "HTMLCollection.h"
#include "HTMLFormElement.h"
#include "HTMLFrameOwnerElement.h"
#include "HTMLHeadElement.h"
#include "HTMLInputElement.h"
#include "HTMLLinkElement.h"
#include "HTMLNames.h"
#include "HistoryItem.h"
#include "HitTestResult.h"
#include "IconURL.h"
#include "InspectorController.h"
#include "KURL.h"
#include "Node.h"
#include "Page.h"
#include "PageOverlay.h"
#include "Performance.h"
#include "PlatformSupport.h"
#include "PluginDocument.h"
#include "PrintContext.h"
#include "RenderFrame.h"
#include "RenderLayer.h"
#include "RenderObject.h"
#include "RenderTreeAsText.h"
#include "RenderView.h"
#include "RenderWidget.h"
#include "ResourceHandle.h"
#include "ResourceRequest.h"
#include "SchemeRegistry.h"
#include "ScriptController.h"
#include "ScriptSourceCode.h"
#include "ScriptValue.h"
#include "ScrollTypes.h"
#include "ScrollbarTheme.h"
#include "SecurityPolicy.h"
#include "Settings.h"
#include "SkiaUtils.h"
#include "SpellChecker.h"
#include "SubstituteData.h"
#include "TextAffinity.h"
#include "TextIterator.h"
#include "UserGestureIndicator.h"
#include "WebAnimationControllerImpl.h"
#include "WebConsoleMessage.h"
#include "WebDOMEvent.h"
#include "WebDOMEventListener.h"
#include "WebDataSourceImpl.h"
#include "WebDevToolsAgentPrivate.h"
#include "WebDocument.h"
#include "WebFindOptions.h"
#include "WebFormElement.h"
#include "WebFrameClient.h"
#include "WebHistoryItem.h"
#include "WebIconURL.h"
#include "WebInputElement.h"
#include "WebNode.h"
#include "WebPerformance.h"
#include "WebPlugin.h"
#include "WebPluginContainerImpl.h"
#include "WebRange.h"
#include "WebScriptSource.h"
#include "WebSecurityOrigin.h"
#include "WebViewImpl.h"
#include "XPathResult.h"
#include "markup.h"
#include "painting/GraphicsContextBuilder.h"
#include "platform/WebPoint.h"
#include "platform/WebRect.h"
#include "platform/WebSize.h"
#include "platform/WebURLError.h"
#include "platform/WebVector.h"
#include <algorithm>
#include <public/Platform.h>
#include <wtf/CurrentTime.h>
#if USE(V8)
#include "AsyncFileSystem.h"
#include "AsyncFileSystemChromium.h"
#include "DirectoryEntry.h"
#include "DOMFileSystem.h"
#include "FileEntry.h"
#include "V8DirectoryEntry.h"
#include "V8DOMFileSystem.h"
#include "V8FileEntry.h"
#include "platform/WebFileSystem.h"
#endif
using namespace WebCore;
namespace WebKit {
static int frameCount = 0;
static const char* const webFrameActiveCount = "WebFrameActiveCount";
static void frameContentAsPlainText(size_t maxChars, Frame* frame,
Vector<UChar>* output)
{
Document* doc = frame->document();
if (!doc)
return;
if (!frame->view())
return;
if (frame->view()->needsLayout())
frame->view()->layout();
RefPtr<Range> range(doc->createRange());
ExceptionCode exception = 0;
range->selectNodeContents(doc->body(), exception);
if (!exception) {
for (TextIterator it(range.get()); !it.atEnd(); it.advance()) {
const UChar* chars = it.characters();
if (!chars) {
if (it.length()) {
ASSERT_NOT_REACHED();
break;
}
continue;
}
size_t toAppend =
std::min(static_cast<size_t>(it.length()), maxChars - output->size());
output->append(chars, toAppend);
if (output->size() >= maxChars)
return; }
}
const UChar frameSeparator[] = { '\n', '\n' };
const size_t frameSeparatorLen = 2;
FrameTree* frameTree = frame->tree();
for (Frame* curChild = frameTree->firstChild(); curChild; curChild = curChild->tree()->nextSibling()) {
RenderView* contentRenderer = curChild->contentRenderer();
RenderPart* ownerRenderer = curChild->ownerRenderer();
if (!contentRenderer || !contentRenderer->width() || !contentRenderer->height()
|| (contentRenderer->x() + contentRenderer->width() <= 0) || (contentRenderer->y() + contentRenderer->height() <= 0)
|| (ownerRenderer && ownerRenderer->style() && ownerRenderer->style()->visibility() != VISIBLE)) {
continue;
}
if (output->size() >= maxChars - frameSeparatorLen)
return;
output->append(frameSeparator, frameSeparatorLen);
frameContentAsPlainText(maxChars, curChild, output);
if (output->size() >= maxChars)
return; }
}
static long long generateFrameIdentifier()
{
static long long next = 0;
return ++next;
}
static WebPluginContainerImpl* pluginContainerFromNode(const WebNode& node)
{
if (node.isNull())
return 0;
const Node* coreNode = node.constUnwrap<Node>();
if (coreNode->hasTagName(HTMLNames::objectTag) || coreNode->hasTagName(HTMLNames::embedTag)) {
RenderObject* object = coreNode->renderer();
if (object && object->isWidget()) {
Widget* widget = toRenderWidget(object)->widget();
if (widget && widget->isPluginContainer())
return static_cast<WebPluginContainerImpl*>(widget);
}
}
return 0;
}
WebPluginContainerImpl* WebFrameImpl::pluginContainerFromFrame(Frame* frame)
{
if (!frame)
return 0;
if (!frame->document() || !frame->document()->isPluginDocument())
return 0;
PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document());
return static_cast<WebPluginContainerImpl *>(pluginDocument->pluginWidget());
}
class ChromePrintContext : public PrintContext {
WTF_MAKE_NONCOPYABLE(ChromePrintContext);
public:
ChromePrintContext(Frame* frame)
: PrintContext(frame)
, m_printedPageWidth(0)
{
}
virtual ~ChromePrintContext() { }
virtual void begin(float width, float height)
{
ASSERT(!m_printedPageWidth);
m_printedPageWidth = width;
PrintContext::begin(m_printedPageWidth, height);
}
virtual void end()
{
PrintContext::end();
}
virtual float getPageShrink(int pageNumber) const
{
IntRect pageRect = m_pageRects[pageNumber];
return m_printedPageWidth / pageRect.width();
}
virtual float spoolPage(GraphicsContext& ctx, int pageNumber)
{
IntRect pageRect = m_pageRects[pageNumber];
float scale = m_printedPageWidth / pageRect.width();
ctx.save();
#if OS(UNIX) && !OS(DARWIN)
ctx.scale(WebCore::FloatSize(scale, scale));
#endif
ctx.translate(static_cast<float>(-pageRect.x()),
static_cast<float>(-pageRect.y()));
ctx.clip(pageRect);
m_frame->view()->paintContents(&ctx, pageRect);
ctx.restore();
return scale;
}
void spoolAllPagesWithBoundaries(GraphicsContext& graphicsContext, const FloatSize& pageSizeInPixels)
{
if (!m_frame->document() || !m_frame->view() || !m_frame->document()->renderer())
return;
m_frame->document()->updateLayout();
float pageHeight;
computePageRects(FloatRect(FloatPoint(0, 0), pageSizeInPixels), 0, 0, 1, pageHeight);
const float pageWidth = pageSizeInPixels.width();
size_t numPages = pageRects().size();
int totalHeight = numPages * (pageSizeInPixels.height() + 1) - 1;
graphicsContext.setFillColor(Color(255, 255, 255), ColorSpaceDeviceRGB);
graphicsContext.fillRect(FloatRect(0, 0, pageWidth, totalHeight));
graphicsContext.save();
int currentHeight = 0;
for (size_t pageIndex = 0; pageIndex < numPages; pageIndex++) {
if (pageIndex > 0) {
graphicsContext.save();
graphicsContext.setStrokeColor(Color(0, 0, 255), ColorSpaceDeviceRGB);
graphicsContext.setFillColor(Color(0, 0, 255), ColorSpaceDeviceRGB);
graphicsContext.drawLine(IntPoint(0, currentHeight),
IntPoint(pageWidth, currentHeight));
graphicsContext.restore();
}
graphicsContext.save();
graphicsContext.translate(0, currentHeight);
#if !OS(UNIX) || OS(DARWIN)
float scale = getPageShrink(pageIndex);
graphicsContext.scale(WebCore::FloatSize(scale, scale));
#endif
spoolPage(graphicsContext, pageIndex);
graphicsContext.restore();
currentHeight += pageSizeInPixels.height() + 1;
}
graphicsContext.restore();
}
virtual void computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight)
{
PrintContext::computePageRects(printRect, headerHeight, footerHeight, userScaleFactor, outPageHeight);
}
virtual int pageCount() const
{
return PrintContext::pageCount();
}
virtual bool shouldUseBrowserOverlays() const
{
return true;
}
private:
float m_printedPageWidth;
};
class ChromePluginPrintContext : public ChromePrintContext {
public:
ChromePluginPrintContext(Frame* frame, WebPluginContainerImpl* plugin, int printerDPI)
: ChromePrintContext(frame), m_plugin(plugin), m_pageCount(0), m_printerDPI(printerDPI)
{
}
virtual ~ChromePluginPrintContext() { }
virtual void begin(float width, float height)
{
}
virtual void end()
{
m_plugin->printEnd();
}
virtual float getPageShrink(int pageNumber) const
{
return 1.0;
}
virtual void computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight)
{
m_pageCount = m_plugin->printBegin(IntRect(printRect), m_printerDPI);
}
virtual int pageCount() const
{
return m_pageCount;
}
virtual float spoolPage(GraphicsContext& ctx, int pageNumber)
{
m_plugin->printPage(pageNumber, &ctx);
return 1.0;
}
virtual bool shouldUseBrowserOverlays() const
{
return false;
}
private:
WebPluginContainerImpl* m_plugin;
int m_pageCount;
int m_printerDPI;
};
static WebDataSource* DataSourceForDocLoader(DocumentLoader* loader)
{
return loader ? WebDataSourceImpl::fromDocumentLoader(loader) : 0;
}
class WebFrameImpl::DeferredScopeStringMatches {
public:
DeferredScopeStringMatches(WebFrameImpl* webFrame,
int identifier,
const WebString& searchText,
const WebFindOptions& options,
bool reset)
: m_timer(this, &DeferredScopeStringMatches::doTimeout)
, m_webFrame(webFrame)
, m_identifier(identifier)
, m_searchText(searchText)
, m_options(options)
, m_reset(reset)
{
m_timer.startOneShot(0.0);
}
private:
void doTimeout(Timer<DeferredScopeStringMatches>*)
{
m_webFrame->callScopeStringMatches(
this, m_identifier, m_searchText, m_options, m_reset);
}
Timer<DeferredScopeStringMatches> m_timer;
RefPtr<WebFrameImpl> m_webFrame;
int m_identifier;
WebString m_searchText;
WebFindOptions m_options;
bool m_reset;
};
int WebFrame::instanceCount()
{
return frameCount;
}
WebFrame* WebFrame::frameForEnteredContext()
{
Frame* frame =
ScriptController::retrieveFrameForEnteredContext();
return WebFrameImpl::fromFrame(frame);
}
WebFrame* WebFrame::frameForCurrentContext()
{
Frame* frame =
ScriptController::retrieveFrameForCurrentContext();
return WebFrameImpl::fromFrame(frame);
}
#if WEBKIT_USING_V8
WebFrame* WebFrame::frameForContext(v8::Handle<v8::Context> context)
{
return WebFrameImpl::fromFrame(V8Proxy::retrieveFrame(context));
}
#endif
WebFrame* WebFrame::fromFrameOwnerElement(const WebElement& element)
{
return WebFrameImpl::fromFrameOwnerElement(
PassRefPtr<Element>(element).get());
}
WebString WebFrameImpl::name() const
{
return m_frame->tree()->uniqueName();
}
void WebFrameImpl::setName(const WebString& name)
{
m_frame->tree()->setName(name);
}
long long WebFrameImpl::identifier() const
{
return m_identifier;
}
WebVector<WebIconURL> WebFrameImpl::iconURLs(int iconTypes) const
{
FrameLoader* frameLoader = m_frame->loader();
if (frameLoader->state() == FrameStateComplete)
return frameLoader->icon()->urlsForTypes(iconTypes);
return WebVector<WebIconURL>();
}
WebReferrerPolicy WebFrameImpl::referrerPolicy() const
{
return static_cast<WebReferrerPolicy>(m_frame->document()->referrerPolicy());
}
WebSize WebFrameImpl::scrollOffset() const
{
FrameView* view = frameView();
if (view)
return view->scrollOffset();
return WebSize();
}
WebSize WebFrameImpl::minimumScrollOffset() const
{
FrameView* view = frameView();
if (view)
return view->minimumScrollPosition() - IntPoint();
return WebSize();
}
WebSize WebFrameImpl::maximumScrollOffset() const
{
FrameView* view = frameView();
if (view)
return view->maximumScrollPosition() - IntPoint();
return WebSize();
}
void WebFrameImpl::setScrollOffset(const WebSize& offset)
{
if (FrameView* view = frameView())
view->setScrollOffset(IntPoint(offset.width, offset.height));
}
WebSize WebFrameImpl::contentsSize() const
{
return frame()->view()->contentsSize();
}
int WebFrameImpl::contentsPreferredWidth() const
{
if (m_frame->document() && m_frame->document()->renderView()) {
FontCachePurgePreventer fontCachePurgePreventer;
return m_frame->document()->renderView()->minPreferredLogicalWidth();
}
return 0;
}
int WebFrameImpl::documentElementScrollHeight() const
{
if (m_frame->document() && m_frame->document()->documentElement())
return m_frame->document()->documentElement()->scrollHeight();
return 0;
}
bool WebFrameImpl::hasVisibleContent() const
{
return frame()->view()->visibleWidth() > 0 && frame()->view()->visibleHeight() > 0;
}
bool WebFrameImpl::hasHorizontalScrollbar() const
{
return m_frame && m_frame->view() && m_frame->view()->horizontalScrollbar();
}
bool WebFrameImpl::hasVerticalScrollbar() const
{
return m_frame && m_frame->view() && m_frame->view()->verticalScrollbar();
}
WebView* WebFrameImpl::view() const
{
return viewImpl();
}
WebFrame* WebFrameImpl::opener() const
{
Frame* opener = 0;
if (m_frame)
opener = m_frame->loader()->opener();
return fromFrame(opener);
}
void WebFrameImpl::setOpener(const WebFrame* frame)
{
m_frame->loader()->setOpener(frame ?
static_cast<const WebFrameImpl*>(frame)->m_frame : 0);
}
WebFrame* WebFrameImpl::parent() const
{
Frame* parent = 0;
if (m_frame)
parent = m_frame->tree()->parent();
return fromFrame(parent);
}
WebFrame* WebFrameImpl::top() const
{
if (m_frame)
return fromFrame(m_frame->tree()->top());
return 0;
}
WebFrame* WebFrameImpl::firstChild() const
{
return fromFrame(frame()->tree()->firstChild());
}
WebFrame* WebFrameImpl::lastChild() const
{
return fromFrame(frame()->tree()->lastChild());
}
WebFrame* WebFrameImpl::nextSibling() const
{
return fromFrame(frame()->tree()->nextSibling());
}
WebFrame* WebFrameImpl::previousSibling() const
{
return fromFrame(frame()->tree()->previousSibling());
}
WebFrame* WebFrameImpl::traverseNext(bool wrap) const
{
return fromFrame(frame()->tree()->traverseNextWithWrap(wrap));
}
WebFrame* WebFrameImpl::traversePrevious(bool wrap) const
{
return fromFrame(frame()->tree()->traversePreviousWithWrap(wrap));
}
WebFrame* WebFrameImpl::findChildByName(const WebString& name) const
{
return fromFrame(frame()->tree()->child(name));
}
WebFrame* WebFrameImpl::findChildByExpression(const WebString& xpath) const
{
if (xpath.isEmpty())
return 0;
Document* document = m_frame->document();
ExceptionCode ec = 0;
PassRefPtr<XPathResult> xpathResult =
document->evaluate(xpath,
document,
0, XPathResult::ORDERED_NODE_ITERATOR_TYPE,
0, ec);
if (!xpathResult)
return 0;
Node* node = xpathResult->iterateNext(ec);
if (!node || !node->isFrameOwnerElement())
return 0;
HTMLFrameOwnerElement* frameElement =
static_cast<HTMLFrameOwnerElement*>(node);
return fromFrame(frameElement->contentFrame());
}
WebDocument WebFrameImpl::document() const
{
if (!m_frame || !m_frame->document())
return WebDocument();
return WebDocument(m_frame->document());
}
WebAnimationController* WebFrameImpl::animationController()
{
return &m_animationController;
}
WebPerformance WebFrameImpl::performance() const
{
if (!m_frame || !m_frame->domWindow())
return WebPerformance();
return WebPerformance(m_frame->domWindow()->performance());
}
NPObject* WebFrameImpl::windowObject() const
{
if (!m_frame)
return 0;
return m_frame->script()->windowScriptNPObject();
}
void WebFrameImpl::bindToWindowObject(const WebString& name, NPObject* object)
{
ASSERT(m_frame);
if (!m_frame || !m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
return;
String key = name;
#if USE(V8)
m_frame->script()->bindToWindowObject(m_frame, key, object);
#else
notImplemented();
#endif
}
void WebFrameImpl::executeScript(const WebScriptSource& source)
{
TextPosition position(OrdinalNumber::fromOneBasedInt(source.startLine), OrdinalNumber::first());
m_frame->script()->executeScript(
ScriptSourceCode(source.code, source.url, position));
}
void WebFrameImpl::executeScriptInIsolatedWorld(
int worldID, const WebScriptSource* sourcesIn, unsigned numSources,
int extensionGroup)
{
Vector<ScriptSourceCode> sources;
for (unsigned i = 0; i < numSources; ++i) {
TextPosition position(OrdinalNumber::fromOneBasedInt(sourcesIn[i].startLine), OrdinalNumber::first());
sources.append(ScriptSourceCode(
sourcesIn[i].code, sourcesIn[i].url, position));
}
m_frame->script()->evaluateInIsolatedWorld(worldID, sources, extensionGroup, 0);
}
void WebFrameImpl::setIsolatedWorldSecurityOrigin(int worldID, const WebSecurityOrigin& securityOrigin)
{
m_frame->script()->setIsolatedWorldSecurityOrigin(worldID, securityOrigin.get());
}
void WebFrameImpl::addMessageToConsole(const WebConsoleMessage& message)
{
ASSERT(frame());
MessageLevel webCoreMessageLevel;
switch (message.level) {
case WebConsoleMessage::LevelTip:
webCoreMessageLevel = TipMessageLevel;
break;
case WebConsoleMessage::LevelLog:
webCoreMessageLevel = LogMessageLevel;
break;
case WebConsoleMessage::LevelWarning:
webCoreMessageLevel = WarningMessageLevel;
break;
case WebConsoleMessage::LevelError:
webCoreMessageLevel = ErrorMessageLevel;
break;
default:
ASSERT_NOT_REACHED();
return;
}
frame()->domWindow()->console()->addMessage(OtherMessageSource, LogMessageType, webCoreMessageLevel, message.text);
}
void WebFrameImpl::collectGarbage()
{
if (!m_frame)
return;
if (!m_frame->settings()->isScriptEnabled())
return;
#if USE(V8)
m_frame->script()->collectGarbage();
#else
notImplemented();
#endif
}
bool WebFrameImpl::checkIfRunInsecureContent(const WebURL& url) const
{
FrameLoader* frameLoader = m_frame->loader();
return frameLoader->checkIfRunInsecureContent(m_frame->document()->securityOrigin(), url);
}
#if USE(V8)
v8::Handle<v8::Value> WebFrameImpl::executeScriptAndReturnValue(const WebScriptSource& source)
{
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
TextPosition position(OrdinalNumber::fromOneBasedInt(source.startLine), OrdinalNumber::first());
return m_frame->script()->executeScript(ScriptSourceCode(source.code, source.url, position)).v8Value();
}
void WebFrameImpl::executeScriptInIsolatedWorld(
int worldID, const WebScriptSource* sourcesIn, unsigned numSources,
int extensionGroup, WebVector<v8::Local<v8::Value> >* results)
{
Vector<ScriptSourceCode> sources;
for (unsigned i = 0; i < numSources; ++i) {
TextPosition position(OrdinalNumber::fromOneBasedInt(sourcesIn[i].startLine), OrdinalNumber::first());
sources.append(ScriptSourceCode(sourcesIn[i].code, sourcesIn[i].url, position));
}
if (results) {
Vector<ScriptValue> scriptResults;
m_frame->script()->evaluateInIsolatedWorld(worldID, sources, extensionGroup, &scriptResults);
WebVector<v8::Local<v8::Value> > v8Results(scriptResults.size());
for (unsigned i = 0; i < scriptResults.size(); i++)
v8Results[i] = v8::Local<v8::Value>::New(scriptResults[i].v8Value());
results->swap(v8Results);
} else
m_frame->script()->evaluateInIsolatedWorld(worldID, sources, extensionGroup, 0);
}
v8::Handle<v8::Value> WebFrameImpl::callFunctionEvenIfScriptDisabled(v8::Handle<v8::Function> function,
v8::Handle<v8::Object> receiver,
int argc,
v8::Handle<v8::Value> argv[])
{
return m_frame->script()->callFunctionEvenIfScriptDisabled(function, receiver, argc, argv).v8Value();
}
v8::Local<v8::Context> WebFrameImpl::mainWorldScriptContext() const
{
if (!m_frame)
return v8::Local<v8::Context>();
return V8Proxy::mainWorldContext(m_frame);
}
v8::Handle<v8::Value> WebFrameImpl::createFileSystem(WebFileSystem::Type type,
const WebString& name,
const WebString& path)
{
return toV8(DOMFileSystem::create(frame()->document(), name, AsyncFileSystemChromium::create(static_cast<AsyncFileSystem::Type>(type), KURL(ParsedURLString, path.utf8().data()))));
}
v8::Handle<v8::Value> WebFrameImpl::createFileEntry(WebFileSystem::Type type,
const WebString& fileSystemName,
const WebString& fileSystemPath,
const WebString& filePath,
bool isDirectory)
{
RefPtr<DOMFileSystemBase> fileSystem = DOMFileSystem::create(frame()->document(), fileSystemName, AsyncFileSystemChromium::create(static_cast<AsyncFileSystem::Type>(type), KURL(ParsedURLString, fileSystemPath.utf8().data())));
if (isDirectory)
return toV8(DirectoryEntry::create(fileSystem, filePath));
return toV8(FileEntry::create(fileSystem, filePath));
}
#endif
void WebFrameImpl::reload(bool ignoreCache)
{
m_frame->loader()->history()->saveDocumentAndScrollState();
m_frame->loader()->reload(ignoreCache);
}
void WebFrameImpl::loadRequest(const WebURLRequest& request)
{
ASSERT(!request.isNull());
const ResourceRequest& resourceRequest = request.toResourceRequest();
if (resourceRequest.url().protocolIs("javascript")) {
loadJavaScriptURL(resourceRequest.url());
return;
}
m_frame->loader()->load(resourceRequest, false);
}
void WebFrameImpl::loadHistoryItem(const WebHistoryItem& item)
{
RefPtr<HistoryItem> historyItem = PassRefPtr<HistoryItem>(item);
ASSERT(historyItem);
m_frame->loader()->prepareForHistoryNavigation();
RefPtr<HistoryItem> currentItem = m_frame->loader()->history()->currentItem();
m_inSameDocumentHistoryLoad = currentItem->shouldDoSameDocumentNavigationTo(historyItem.get());
m_frame->page()->goToItem(historyItem.get(),
FrameLoadTypeIndexedBackForward);
m_inSameDocumentHistoryLoad = false;
}
void WebFrameImpl::loadData(const WebData& data,
const WebString& mimeType,
const WebString& textEncoding,
const WebURL& baseURL,
const WebURL& unreachableURL,
bool replace)
{
SubstituteData substData(data, mimeType, textEncoding, unreachableURL);
ASSERT(substData.isValid());
ResourceRequest request;
if (replace && !unreachableURL.isEmpty())
request = m_frame->loader()->originalRequest();
request.setURL(baseURL);
m_frame->loader()->load(request, substData, false);
if (replace) {
m_frame->loader()->setReplacing();
}
}
void WebFrameImpl::loadHTMLString(const WebData& data,
const WebURL& baseURL,
const WebURL& unreachableURL,
bool replace)
{
loadData(data,
WebString::fromUTF8("text/html"),
WebString::fromUTF8("UTF-8"),
baseURL,
unreachableURL,
replace);
}
bool WebFrameImpl::isLoading() const
{
if (!m_frame)
return false;
return m_frame->loader()->isLoading();
}
void WebFrameImpl::stopLoading()
{
if (!m_frame)
return;
m_frame->loader()->stopAllLoaders();
m_frame->loader()->stopLoading(UnloadEventPolicyNone);
}
WebDataSource* WebFrameImpl::provisionalDataSource() const
{
FrameLoader* frameLoader = m_frame->loader();
DocumentLoader* docLoader = frameLoader->provisionalDocumentLoader();
if (!docLoader)
docLoader = frameLoader->policyDocumentLoader();
return DataSourceForDocLoader(docLoader);
}
WebDataSource* WebFrameImpl::dataSource() const
{
return DataSourceForDocLoader(m_frame->loader()->documentLoader());
}
WebHistoryItem WebFrameImpl::previousHistoryItem() const
{
return WebHistoryItem(m_frame->loader()->history()->previousItem());
}
WebHistoryItem WebFrameImpl::currentHistoryItem() const
{
if (!m_frame->loader()->activeDocumentLoader())
return WebHistoryItem();
if (!m_inSameDocumentHistoryLoad && (m_frame->loader()->loadType() == FrameLoadTypeStandard
|| !m_frame->loader()->activeDocumentLoader()->isLoadingInAPISense()))
m_frame->loader()->history()->saveDocumentAndScrollState();
return WebHistoryItem(m_frame->page()->backForward()->currentItem());
}
void WebFrameImpl::enableViewSourceMode(bool enable)
{
if (m_frame)
m_frame->setInViewSourceMode(enable);
}
bool WebFrameImpl::isViewSourceModeEnabled() const
{
if (m_frame)
return m_frame->inViewSourceMode();
return false;
}
void WebFrameImpl::setReferrerForRequest(WebURLRequest& request, const WebURL& referrerURL)
{
String referrer;
if (referrerURL.isEmpty())
referrer = m_frame->loader()->outgoingReferrer();
else
referrer = referrerURL.spec().utf16();
referrer = SecurityPolicy::generateReferrerHeader(m_frame->document()->referrerPolicy(), request.url(), referrer);
if (referrer.isEmpty())
return;
request.setHTTPHeaderField(WebString::fromUTF8("Referer"), referrer);
}
void WebFrameImpl::dispatchWillSendRequest(WebURLRequest& request)
{
ResourceResponse response;
m_frame->loader()->client()->dispatchWillSendRequest(
0, 0, request.toMutableResourceRequest(), response);
}
WebURLLoader* WebFrameImpl::createAssociatedURLLoader(const WebURLLoaderOptions& options)
{
return new AssociatedURLLoader(this, options);
}
void WebFrameImpl::commitDocumentData(const char* data, size_t length)
{
m_frame->loader()->documentLoader()->commitData(data, length);
}
unsigned WebFrameImpl::unloadListenerCount() const
{
return frame()->domWindow()->pendingUnloadEventListeners();
}
bool WebFrameImpl::isProcessingUserGesture() const
{
return ScriptController::processingUserGesture();
}
bool WebFrameImpl::willSuppressOpenerInNewFrame() const
{
return frame()->loader()->suppressOpenerInNewFrame();
}
void WebFrameImpl::replaceSelection(const WebString& text)
{
bool selectReplacement = false;
bool smartReplace = true;
return frame()->editor()->replaceSelectionWithText(text, selectReplacement, smartReplace);
}
void WebFrameImpl::insertText(const WebString& text)
{
Editor* editor = frame()->editor();
if (editor->hasComposition())
editor->confirmComposition(text);
else
editor->insertText(text, 0);
}
void WebFrameImpl::setMarkedText(
const WebString& text, unsigned location, unsigned length)
{
Editor* editor = frame()->editor();
Vector<CompositionUnderline> decorations;
editor->setComposition(text, decorations, location, length);
}
void WebFrameImpl::unmarkText()
{
frame()->editor()->cancelComposition();
}
bool WebFrameImpl::hasMarkedText() const
{
return frame()->editor()->hasComposition();
}
WebRange WebFrameImpl::markedRange() const
{
return frame()->editor()->compositionRange();
}
void WebFrameImpl::setSelectionToRange(const WebRange& range)
{
if (frame()->selection()->isContentEditable()) {
RefPtr<Range> replacementRange = PassRefPtr<Range>(range);
frame()->selection()->setSelection(VisibleSelection(replacementRange.get(), SEL_DEFAULT_AFFINITY));
}
}
bool WebFrameImpl::firstRectForCharacterRange(unsigned location, unsigned length, WebRect& rect) const
{
if ((location + length < location) && (location + length))
length = 0;
RefPtr<Range> range = TextIterator::rangeFromLocationAndLength(frame()->selection()->rootEditableElementOrDocumentElement(), location, length);
if (!range)
return false;
IntRect intRect = frame()->editor()->firstRectForRange(range.get());
rect = WebRect(intRect);
rect = frame()->view()->contentsToWindow(rect);
return true;
}
size_t WebFrameImpl::characterIndexForPoint(const WebPoint& webPoint) const
{
if (!frame())
return notFound;
IntPoint point = frame()->view()->windowToContents(webPoint);
HitTestResult result = frame()->eventHandler()->hitTestResultAtPoint(point, false);
RefPtr<Range> range = frame()->rangeForPoint(result.roundedPoint());
if (!range)
return notFound;
size_t location, length;
TextIterator::getLocationAndLengthFromRange(frame()->selection()->rootEditableElementOrDocumentElement(), range.get(), location, length);
return location;
}
bool WebFrameImpl::executeCommand(const WebString& name, const WebNode& node)
{
ASSERT(frame());
if (name.length() <= 2)
return false;
String command = name;
command.replace(0, 1, command.substring(0, 1).upper());
if (command[command.length() - 1] == UChar(':'))
command = command.substring(0, command.length() - 1);
if (command == "Copy") {
WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
if (!pluginContainer)
pluginContainer = pluginContainerFromNode(node);
if (pluginContainer) {
pluginContainer->copy();
return true;
}
}
bool rv = true;
if (command == "DeleteToEndOfParagraph") {
Editor* editor = frame()->editor();
if (!editor->deleteWithDirection(DirectionForward,
ParagraphBoundary,
true,
false)) {
editor->deleteWithDirection(DirectionForward,
CharacterGranularity,
true,
false);
}
} else if (command == "Indent")
frame()->editor()->indent();
else if (command == "Outdent")
frame()->editor()->outdent();
else if (command == "DeleteBackward")
rv = frame()->editor()->command(AtomicString("BackwardDelete")).execute();
else if (command == "DeleteForward")
rv = frame()->editor()->command(AtomicString("ForwardDelete")).execute();
else if (command == "AdvanceToNextMisspelling") {
frame()->editor()->advanceToNextMisspelling(false);
} else if (command == "ToggleSpellPanel")
frame()->editor()->showSpellingGuessPanel();
else
rv = frame()->editor()->command(command).execute();
return rv;
}
bool WebFrameImpl::executeCommand(const WebString& name, const WebString& value)
{
ASSERT(frame());
String webName = name;
if (!frame()->editor()->canEdit() && webName == "moveToBeginningOfDocument")
return viewImpl()->propagateScroll(ScrollUp, ScrollByDocument);
if (!frame()->editor()->canEdit() && webName == "moveToEndOfDocument")
return viewImpl()->propagateScroll(ScrollDown, ScrollByDocument);
return frame()->editor()->command(webName).execute(value);
}
bool WebFrameImpl::isCommandEnabled(const WebString& name) const
{
ASSERT(frame());
return frame()->editor()->command(name).isEnabled();
}
void WebFrameImpl::enableContinuousSpellChecking(bool enable)
{
if (enable == isContinuousSpellCheckingEnabled())
return;
frame()->editor()->toggleContinuousSpellChecking();
}
bool WebFrameImpl::isContinuousSpellCheckingEnabled() const
{
return frame()->editor()->isContinuousSpellCheckingEnabled();
}
void WebFrameImpl::requestTextChecking(const WebElement& webElem)
{
if (webElem.isNull())
return;
RefPtr<Range> rangeToCheck = rangeOfContents(const_cast<Element*>(webElem.constUnwrap<Element>()));
frame()->editor()->spellChecker()->requestCheckingFor(SpellCheckRequest::create(TextCheckingTypeSpelling | TextCheckingTypeGrammar, TextCheckingProcessBatch, rangeToCheck, rangeToCheck));
}
bool WebFrameImpl::hasSelection() const
{
WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
if (pluginContainer)
return pluginContainer->plugin()->hasSelection();
return (frame()->selection()->start() != frame()->selection()->end());
}
WebRange WebFrameImpl::selectionRange() const
{
return frame()->selection()->toNormalizedRange();
}
WebString WebFrameImpl::selectionAsText() const
{
WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
if (pluginContainer)
return pluginContainer->plugin()->selectionAsText();
RefPtr<Range> range = frame()->selection()->toNormalizedRange();
if (!range)
return WebString();
String text = range->text();
#if OS(WINDOWS)
replaceNewlinesWithWindowsStyleNewlines(text);
#endif
replaceNBSPWithSpace(text);
return text;
}
WebString WebFrameImpl::selectionAsMarkup() const
{
WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame());
if (pluginContainer)
return pluginContainer->plugin()->selectionAsMarkup();
RefPtr<Range> range = frame()->selection()->toNormalizedRange();
if (!range)
return WebString();
return createMarkup(range.get(), 0, AnnotateForInterchange, false, ResolveNonLocalURLs);
}
void WebFrameImpl::selectWordAroundPosition(Frame* frame, VisiblePosition pos)
{
VisibleSelection selection(pos);
selection.expandUsingGranularity(WordGranularity);
if (frame->selection()->shouldChangeSelection(selection)) {
TextGranularity granularity = selection.isRange() ? WordGranularity : CharacterGranularity;
frame->selection()->setSelection(selection, granularity);
}
}
bool WebFrameImpl::selectWordAroundCaret()
{
FrameSelection* selection = frame()->selection();
ASSERT(!selection->isNone());
if (selection->isNone() || selection->isRange())
return false;
selectWordAroundPosition(frame(), selection->selection().visibleStart());
return true;
}
void WebFrameImpl::selectRange(const WebPoint& start, const WebPoint& end)
{
VisibleSelection selection(visiblePositionForWindowPoint(start),
visiblePositionForWindowPoint(end));
if (frame()->selection()->shouldChangeSelection(selection))
frame()->selection()->setSelection(selection, CharacterGranularity);
}
void WebFrameImpl::selectRange(const WebRange& webRange)
{
RefPtr<Range> range = static_cast<PassRefPtr<Range> >(webRange);
if (range)
frame()->selection()->setSelectedRange(range.get(), WebCore::VP_DEFAULT_AFFINITY, false);
}
VisiblePosition WebFrameImpl::visiblePositionForWindowPoint(const WebPoint& point)
{
HitTestRequest::HitTestRequestType hitType = HitTestRequest::Move;
hitType |= HitTestRequest::ReadOnly;
hitType |= HitTestRequest::Active;
HitTestRequest request(hitType);
FrameView* view = frame()->view();
HitTestResult result(view->windowToContents(
view->convertFromContainingWindow(IntPoint(point.x, point.y))));
frame()->document()->renderView()->layer()->hitTest(request, result);
Node* node = result.innerNode();
if (!node)
return VisiblePosition();
Element* element = node->parentElement();
if (!node->inDocument() && element && element->inDocument())
node = element;
return node->renderer()->positionForPoint(result.localPoint());
}
int WebFrameImpl::printBegin(const WebSize& pageSize,
const WebNode& constrainToNode,
int printerDPI,
bool* useBrowserOverlays)
{
ASSERT(!frame()->document()->isFrameSet());
WebPluginContainerImpl* pluginContainer = 0;
if (constrainToNode.isNull()) {
pluginContainer = pluginContainerFromFrame(frame());
} else {
pluginContainer = pluginContainerFromNode(constrainToNode);
}
if (pluginContainer && pluginContainer->supportsPaginatedPrint())
m_printContext = adoptPtr(new ChromePluginPrintContext(frame(), pluginContainer, printerDPI));
else
m_printContext = adoptPtr(new ChromePrintContext(frame()));
FloatRect rect(0, 0, static_cast<float>(pageSize.width),
static_cast<float>(pageSize.height));
m_printContext->begin(rect.width(), rect.height());
float pageHeight;
m_printContext->computePageRects(rect, 0, 0, 1.0, pageHeight);
if (useBrowserOverlays)
*useBrowserOverlays = m_printContext->shouldUseBrowserOverlays();
return m_printContext->pageCount();
}
float WebFrameImpl::getPrintPageShrink(int page)
{
if (!m_printContext || page < 0) {
ASSERT_NOT_REACHED();
return 0;
}
return m_printContext->getPageShrink(page);
}
float WebFrameImpl::printPage(int page, WebCanvas* canvas)
{
if (!m_printContext || page < 0 || !frame() || !frame()->document()) {
ASSERT_NOT_REACHED();
return 0;
}
GraphicsContextBuilder builder(canvas);
GraphicsContext& gc = builder.context();
#if WEBKIT_USING_SKIA
gc.platformContext()->setPrinting(true);
#endif
return m_printContext->spoolPage(gc, page);
}
void WebFrameImpl::printEnd()
{
ASSERT(m_printContext);
if (m_printContext)
m_printContext->end();
m_printContext.clear();
}
bool WebFrameImpl::isPrintScalingDisabledForPlugin(const WebNode& node)
{
WebPluginContainerImpl* pluginContainer = 0;
if (node.isNull())
pluginContainer = pluginContainerFromFrame(frame());
else
pluginContainer = pluginContainerFromNode(node);
if (!pluginContainer || !pluginContainer->supportsPaginatedPrint())
return false;
return pluginContainer->isPrintScalingDisabled();
}
bool WebFrameImpl::hasCustomPageSizeStyle(int pageIndex)
{
return frame()->document()->styleForPage(pageIndex)->pageSizeType() != PAGE_SIZE_AUTO;
}
bool WebFrameImpl::isPageBoxVisible(int pageIndex)
{
return frame()->document()->isPageBoxVisible(pageIndex);
}
void WebFrameImpl::pageSizeAndMarginsInPixels(int pageIndex,
WebSize& pageSize,
int& marginTop,
int& marginRight,
int& marginBottom,
int& marginLeft)
{
IntSize size(pageSize.width, pageSize.height);
frame()->document()->pageSizeAndMarginsInPixels(pageIndex,
size,
marginTop,
marginRight,
marginBottom,
marginLeft);
pageSize = size;
}
WebString WebFrameImpl::pageProperty(const WebString& propertyName, int pageIndex)
{
ASSERT(m_printContext);
return m_printContext->pageProperty(m_frame, propertyName.utf8().data(), pageIndex);
}
bool WebFrameImpl::find(int identifier,
const WebString& searchText,
const WebFindOptions& options,
bool wrapWithinFrame,
WebRect* selectionRect)
{
WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
if (!options.findNext) {
frame()->page()->unmarkAllTextMatches();
m_activeMatch = 0;
} else
setMarkerActive(m_activeMatch.get(), false);
VisibleSelection selection(frame()->selection()->selection());
bool activeSelection = !selection.isNone();
if (activeSelection) {
m_activeMatch = selection.firstRange().get();
frame()->selection()->clear();
}
ASSERT(frame() && frame()->view());
const FindOptions findOptions = (options.forward ? 0 : Backwards)
| (options.matchCase ? 0 : CaseInsensitive)
| (wrapWithinFrame ? WrapAround : 0)
| (!options.findNext ? StartInSelection : 0);
m_activeMatch = frame()->editor()->findStringAndScrollToVisible(searchText, m_activeMatch.get(), findOptions);
if (!m_activeMatch) {
invalidateArea(InvalidateAll);
return false;
}
setMarkerActive(m_activeMatch.get(), true);
WebFrameImpl* oldActiveFrame = mainFrameImpl->m_currentActiveMatchFrame;
mainFrameImpl->m_currentActiveMatchFrame = this;
frame()->document()->setFocusedNode(0);
if (!options.findNext || activeSelection) {
m_locatingActiveRect = true;
} else {
if (oldActiveFrame != this) {
if (options.forward)
m_activeMatchIndexInCurrentFrame = 0;
else
m_activeMatchIndexInCurrentFrame = m_lastMatchCount - 1;
} else {
if (options.forward)
++m_activeMatchIndexInCurrentFrame;
else
--m_activeMatchIndexInCurrentFrame;
if (m_activeMatchIndexInCurrentFrame + 1 > m_lastMatchCount)
m_activeMatchIndexInCurrentFrame = 0;
if (m_activeMatchIndexInCurrentFrame == -1)
m_activeMatchIndexInCurrentFrame = m_lastMatchCount - 1;
}
if (selectionRect) {
*selectionRect = frameView()->contentsToWindow(m_activeMatch->boundingBox());
reportFindInPageSelection(*selectionRect, m_activeMatchIndexInCurrentFrame + 1, identifier);
}
}
return true;
}
void WebFrameImpl::stopFinding(bool clearSelection)
{
if (!clearSelection)
setFindEndstateFocusAndSelection();
cancelPendingScopingEffort();
frame()->document()->markers()->removeMarkers(DocumentMarker::TextMatch);
frame()->editor()->setMarkedTextMatchesAreHighlighted(false);
invalidateArea(InvalidateAll);
}
void WebFrameImpl::scopeStringMatches(int identifier,
const WebString& searchText,
const WebFindOptions& options,
bool reset)
{
if (!shouldScopeMatches(searchText))
return;
WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
if (reset) {
m_scopingComplete = false;
if (frame()->editor()->markedTextMatchesAreHighlighted())
frame()->page()->unmarkAllTextMatches();
m_lastMatchCount = 0;
m_nextInvalidateAfter = 0;
m_resumeScopingFromRange = 0;
mainFrameImpl->m_framesScopingCount++;
scopeStringMatchesSoon(
identifier,
searchText,
options,
false); return;
}
RefPtr<Range> searchRange(rangeOfContents(frame()->document()));
Node* originalEndContainer = searchRange->endContainer();
int originalEndOffset = searchRange->endOffset();
ExceptionCode ec = 0, ec2 = 0;
if (m_resumeScopingFromRange) {
searchRange->setStart(m_resumeScopingFromRange->startContainer(),
m_resumeScopingFromRange->startOffset(ec2) + 1,
ec);
if (ec || ec2) {
if (ec2) ASSERT_NOT_REACHED();
return;
}
}
const double maxScopingDuration = 0.1;
int matchCount = 0;
bool timedOut = false;
double startTime = currentTime();
do {
RefPtr<Range> resultRange(findPlainText(searchRange.get(),
searchText,
options.matchCase ? 0 : CaseInsensitive));
if (resultRange->collapsed(ec)) {
if (!resultRange->startContainer()->isInShadowTree())
break;
searchRange->setStartAfter(
resultRange->startContainer()->shadowAncestorNode(), ec);
searchRange->setEnd(originalEndContainer, originalEndOffset, ec);
continue;
}
if (frame()->editor()->insideVisibleArea(resultRange.get())) {
++matchCount;
IntRect resultBounds = resultRange->boundingBox();
IntRect activeSelectionRect;
if (m_locatingActiveRect) {
activeSelectionRect = m_activeMatch.get() ?
m_activeMatch->boundingBox() : resultBounds;
}
bool foundActiveMatch = false;
if (m_locatingActiveRect && (activeSelectionRect == resultBounds)) {
mainFrameImpl->m_currentActiveMatchFrame = this;
foundActiveMatch = true;
m_activeMatchIndexInCurrentFrame = matchCount - 1;
m_locatingActiveRect = false;
reportFindInPageSelection(
frameView()->contentsToWindow(resultBounds),
m_activeMatchIndexInCurrentFrame + 1,
identifier);
}
addMarker(resultRange.get(), foundActiveMatch);
}
searchRange->setStart(resultRange->endContainer(ec), resultRange->endOffset(ec), ec);
Node* shadowTreeRoot = searchRange->shadowTreeRootNode();
if (searchRange->collapsed(ec) && shadowTreeRoot)
searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), ec);
m_resumeScopingFromRange = resultRange;
timedOut = (currentTime() - startTime) >= maxScopingDuration;
} while (!timedOut);
m_lastSearchString = searchText;
if (matchCount > 0) {
frame()->editor()->setMarkedTextMatchesAreHighlighted(true);
m_lastMatchCount += matchCount;
mainFrameImpl->increaseMatchCount(matchCount, identifier);
}
if (timedOut) {
if (matchCount > 0)
invalidateIfNecessary();
scopeStringMatchesSoon(
identifier,
searchText,
options,
false); return; }
m_scopingComplete = true;
mainFrameImpl->m_framesScopingCount--;
if (!mainFrameImpl->m_framesScopingCount)
mainFrameImpl->increaseMatchCount(0, identifier);
invalidateArea(InvalidateScrollbar);
}
void WebFrameImpl::cancelPendingScopingEffort()
{
deleteAllValues(m_deferredScopingWork);
m_deferredScopingWork.clear();
m_activeMatchIndexInCurrentFrame = -1;
}
void WebFrameImpl::increaseMatchCount(int count, int identifier)
{
ASSERT(!parent());
m_totalMatchCount += count;
if (client())
client()->reportFindInPageMatchCount(identifier, m_totalMatchCount, !m_framesScopingCount);
}
void WebFrameImpl::reportFindInPageSelection(const WebRect& selectionRect,
int activeMatchOrdinal,
int identifier)
{
if (client())
client()->reportFindInPageSelection(identifier, ordinalOfFirstMatchForFrame(this) + activeMatchOrdinal, selectionRect);
}
void WebFrameImpl::resetMatchCount()
{
m_totalMatchCount = 0;
m_framesScopingCount = 0;
}
void WebFrameImpl::handleIntentResult(int intentIdentifier, const WebString& reply)
{
}
void WebFrameImpl::handleIntentFailure(int intentIdentifier, const WebString& reply)
{
}
void WebFrameImpl::addEventListener(const WebString& eventType, WebDOMEventListener* listener, bool useCapture)
{
DOMWindow* window = m_frame->domWindow();
EventListenerWrapper* listenerWrapper =
listener->createEventListenerWrapper(eventType, useCapture, window);
m_frame->domWindow()->addEventListener(eventType, adoptRef(listenerWrapper), useCapture);
}
void WebFrameImpl::removeEventListener(const WebString& eventType, WebDOMEventListener* listener, bool useCapture)
{
DOMWindow* window = m_frame->domWindow();
EventListenerWrapper* listenerWrapper =
listener->getEventListenerWrapper(eventType, useCapture, window);
window->removeEventListener(eventType, listenerWrapper, useCapture);
}
bool WebFrameImpl::dispatchEvent(const WebDOMEvent& event)
{
ASSERT(!event.isNull());
return m_frame->domWindow()->dispatchEvent(event);
}
WebString WebFrameImpl::contentAsText(size_t maxChars) const
{
if (!m_frame)
return WebString();
Vector<UChar> text;
frameContentAsPlainText(maxChars, m_frame, &text);
return String::adopt(text);
}
WebString WebFrameImpl::contentAsMarkup() const
{
return createFullMarkup(m_frame->document());
}
WebString WebFrameImpl::renderTreeAsText(RenderAsTextControls toShow) const
{
RenderAsTextBehavior behavior = RenderAsTextBehaviorNormal;
if (toShow & RenderAsTextDebug) {
behavior |= RenderAsTextShowCompositedLayers
| RenderAsTextShowAddresses
| RenderAsTextShowIDAndClass
| RenderAsTextShowLayerNesting;
}
if (toShow & RenderAsTextPrinting)
behavior |= RenderAsTextPrintingMode;
return externalRepresentation(m_frame, behavior);
}
WebString WebFrameImpl::counterValueForElementById(const WebString& id) const
{
if (!m_frame)
return WebString();
Element* element = m_frame->document()->getElementById(id);
if (!element)
return WebString();
return counterValueForElement(element);
}
WebString WebFrameImpl::markerTextForListItem(const WebElement& webElement) const
{
return WebCore::markerTextForListItem(const_cast<Element*>(webElement.constUnwrap<Element>()));
}
int WebFrameImpl::pageNumberForElementById(const WebString& id,
float pageWidthInPixels,
float pageHeightInPixels) const
{
if (!m_frame)
return -1;
Element* element = m_frame->document()->getElementById(id);
if (!element)
return -1;
FloatSize pageSize(pageWidthInPixels, pageHeightInPixels);
return PrintContext::pageNumberForElement(element, pageSize);
}
void WebFrameImpl::printPagesWithBoundaries(WebCanvas* canvas, const WebSize& pageSizeInPixels)
{
ASSERT(m_printContext.get());
GraphicsContextBuilder builder(canvas);
GraphicsContext& graphicsContext = builder.context();
#if WEBKIT_USING_SKIA
graphicsContext.platformContext()->setPrinting(true);
#endif
m_printContext->spoolAllPagesWithBoundaries(graphicsContext,
FloatSize(pageSizeInPixels.width, pageSizeInPixels.height));
}
WebRect WebFrameImpl::selectionBoundsRect() const
{
if (hasSelection())
return IntRect(frame()->selection()->bounds(false));
return WebRect();
}
bool WebFrameImpl::selectionStartHasSpellingMarkerFor(int from, int length) const
{
if (!m_frame)
return false;
return m_frame->editor()->selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length);
}
WebString WebFrameImpl::layerTreeAsText(bool showDebugInfo) const
{
if (!m_frame)
return WebString();
return WebString(m_frame->layerTreeAsText(showDebugInfo));
}
PassRefPtr<WebFrameImpl> WebFrameImpl::create(WebFrameClient* client)
{
return adoptRef(new WebFrameImpl(client));
}
WebFrameImpl::WebFrameImpl(WebFrameClient* client)
: m_frameLoaderClient(this)
, m_client(client)
, m_currentActiveMatchFrame(0)
, m_activeMatchIndexInCurrentFrame(-1)
, m_locatingActiveRect(false)
, m_resumeScopingFromRange(0)
, m_lastMatchCount(-1)
, m_totalMatchCount(-1)
, m_framesScopingCount(-1)
, m_scopingComplete(false)
, m_nextInvalidateAfter(0)
, m_animationController(this)
, m_identifier(generateFrameIdentifier())
, m_inSameDocumentHistoryLoad(false)
{
WebKit::Platform::current()->incrementStatsCounter(webFrameActiveCount);
frameCount++;
}
WebFrameImpl::~WebFrameImpl()
{
WebKit::Platform::current()->decrementStatsCounter(webFrameActiveCount);
frameCount--;
cancelPendingScopingEffort();
}
void WebFrameImpl::initializeAsMainFrame(WebViewImpl* webViewImpl)
{
RefPtr<Frame> frame = Frame::create(webViewImpl->page(), 0, &m_frameLoaderClient);
m_frame = frame.get();
ref();
m_frame->init();
}
PassRefPtr<Frame> WebFrameImpl::createChildFrame(
const FrameLoadRequest& request, HTMLFrameOwnerElement* ownerElement)
{
RefPtr<WebFrameImpl> webframe(adoptRef(new WebFrameImpl(m_client)));
webframe->ref();
RefPtr<Frame> childFrame = Frame::create(
m_frame->page(), ownerElement, &webframe->m_frameLoaderClient);
webframe->m_frame = childFrame.get();
childFrame->tree()->setName(request.frameName());
m_frame->tree()->appendChild(childFrame);
childFrame->init(); if (!childFrame->tree()->parent())
return 0;
m_frame->loader()->loadURLIntoChildFrame(
request.resourceRequest().url(),
request.resourceRequest().httpReferrer(),
childFrame.get());
if (!childFrame->tree()->parent())
return 0;
return childFrame.release();
}
void WebFrameImpl::createFrameView()
{
ASSERT(m_frame);
WebViewImpl* webView = viewImpl();
bool isMainFrame = webView->mainFrameImpl()->frame() == m_frame;
m_frame->createView(webView->size(), Color::white, webView->isTransparent(), webView->fixedLayoutSize(), isMainFrame ? webView->isFixedLayoutModeEnabled() : 0);
if (webView->shouldAutoResize() && isMainFrame)
m_frame->view()->enableAutoSizeMode(true, webView->minAutoSize(), webView->maxAutoSize());
if (isMainFrame && webView->devToolsAgentPrivate())
webView->devToolsAgentPrivate()->mainFrameViewCreated(this);
}
WebFrameImpl* WebFrameImpl::fromFrame(Frame* frame)
{
if (!frame)
return 0;
return static_cast<FrameLoaderClientImpl*>(frame->loader()->client())->webFrame();
}
WebFrameImpl* WebFrameImpl::fromFrameOwnerElement(Element* element)
{
if (!element
|| !element->isFrameOwnerElement()
|| (!element->hasTagName(HTMLNames::iframeTag)
&& !element->hasTagName(HTMLNames::frameTag)))
return 0;
HTMLFrameOwnerElement* frameElement =
static_cast<HTMLFrameOwnerElement*>(element);
return fromFrame(frameElement->contentFrame());
}
WebViewImpl* WebFrameImpl::viewImpl() const
{
if (!m_frame)
return 0;
return WebViewImpl::fromPage(m_frame->page());
}
WebDataSourceImpl* WebFrameImpl::dataSourceImpl() const
{
return static_cast<WebDataSourceImpl*>(dataSource());
}
WebDataSourceImpl* WebFrameImpl::provisionalDataSourceImpl() const
{
return static_cast<WebDataSourceImpl*>(provisionalDataSource());
}
void WebFrameImpl::setFindEndstateFocusAndSelection()
{
WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
if (this == mainFrameImpl->activeMatchFrame() && m_activeMatch.get()) {
VisibleSelection selection(frame()->selection()->selection());
if (!selection.isNone())
return;
Node* node = m_activeMatch->firstNode();
if (node && node->isInShadowTree()) {
Node* host = node->shadowAncestorNode();
if (host->hasTagName(HTMLNames::inputTag) || host->hasTagName(HTMLNames::textareaTag))
node = host;
}
while (node && !node->isFocusable() && node != frame()->document())
node = node->parentNode();
if (node && node != frame()->document()) {
frame()->selection()->setSelection(m_activeMatch.get());
frame()->document()->setFocusedNode(node);
return;
}
node = m_activeMatch->firstNode();
while (node && node != m_activeMatch->pastLastNode()) {
if (node->isFocusable()) {
frame()->document()->setFocusedNode(node);
return;
}
node = node->traverseNextNode();
}
frame()->selection()->setSelection(m_activeMatch.get());
frame()->document()->setFocusedNode(0);
}
}
void WebFrameImpl::didFail(const ResourceError& error, bool wasProvisional)
{
if (!client())
return;
WebURLError webError = error;
if (wasProvisional)
client()->didFailProvisionalLoad(this, webError);
else
client()->didFailLoad(this, webError);
}
void WebFrameImpl::setCanHaveScrollbars(bool canHaveScrollbars)
{
m_frame->view()->setCanHaveScrollbars(canHaveScrollbars);
}
void WebFrameImpl::closing()
{
m_frame = 0;
}
void WebFrameImpl::invalidateArea(AreaToInvalidate area)
{
ASSERT(frame() && frame()->view());
FrameView* view = frame()->view();
if ((area & InvalidateAll) == InvalidateAll)
view->invalidateRect(view->frameRect());
else {
if ((area & InvalidateContentArea) == InvalidateContentArea) {
IntRect contentArea(
view->x(), view->y(), view->visibleWidth(), view->visibleHeight());
IntRect frameRect = view->frameRect();
contentArea.move(-frameRect.x(), -frameRect.y());
view->invalidateRect(contentArea);
}
if ((area & InvalidateScrollbar) == InvalidateScrollbar) {
Scrollbar* scrollbar = view->verticalScrollbar();
if (scrollbar)
scrollbar->invalidate();
}
}
}
void WebFrameImpl::addMarker(Range* range, bool activeMatch)
{
frame()->document()->markers()->addTextMatchMarker(range, activeMatch);
}
void WebFrameImpl::setMarkerActive(Range* range, bool active)
{
WebCore::ExceptionCode ec;
if (!range || range->collapsed(ec))
return;
frame()->document()->markers()->setMarkersActive(range, active);
}
int WebFrameImpl::ordinalOfFirstMatchForFrame(WebFrameImpl* frame) const
{
int ordinal = 0;
WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl();
for (WebFrameImpl* it = mainFrameImpl;
it != frame;
it = static_cast<WebFrameImpl*>(it->traverseNext(true))) {
if (it->m_lastMatchCount > 0)
ordinal += it->m_lastMatchCount;
}
return ordinal;
}
bool WebFrameImpl::shouldScopeMatches(const String& searchText)
{
if (!frame() || !frame()->view() || !hasVisibleContent())
return false;
ASSERT(frame()->document() && frame()->view());
if (m_scopingComplete && !m_lastSearchString.isEmpty() && !m_lastMatchCount) {
String previousSearchPrefix =
searchText.substring(0, m_lastSearchString.length());
if (previousSearchPrefix == m_lastSearchString)
return false; }
return true;
}
void WebFrameImpl::scopeStringMatchesSoon(int identifier, const WebString& searchText,
const WebFindOptions& options, bool reset)
{
m_deferredScopingWork.append(new DeferredScopeStringMatches(
this, identifier, searchText, options, reset));
}
void WebFrameImpl::callScopeStringMatches(DeferredScopeStringMatches* caller,
int identifier, const WebString& searchText,
const WebFindOptions& options, bool reset)
{
m_deferredScopingWork.remove(m_deferredScopingWork.find(caller));
scopeStringMatches(identifier, searchText, options, reset);
delete caller;
}
void WebFrameImpl::invalidateIfNecessary()
{
if (m_lastMatchCount > m_nextInvalidateAfter) {
static const int startSlowingDownAfter = 500;
static const int slowdown = 750;
int i = (m_lastMatchCount / startSlowingDownAfter);
m_nextInvalidateAfter += i * slowdown;
invalidateArea(InvalidateScrollbar);
}
}
void WebFrameImpl::loadJavaScriptURL(const KURL& url)
{
if (!m_frame->document() || !m_frame->page())
return;
RefPtr<Document> ownerDocument(m_frame->document());
if (SchemeRegistry::shouldTreatURLSchemeAsNotAllowingJavascriptURLs(m_frame->document()->url().protocol()))
return;
String script = decodeURLEscapeSequences(url.string().substring(strlen("javascript:")));
ScriptValue result = m_frame->script()->executeScript(script, true);
String scriptResult;
if (!result.getString(scriptResult))
return;
if (!m_frame->navigationScheduler()->locationChangePending())
m_frame->document()->loader()->writer()->replaceDocument(scriptResult, ownerDocument.get());
}
}