2 * Copyright (C) 2010 Apple 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
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 * THE POSSIBILITY OF SUCH DAMAGE.
27 #include "PluginView.h"
29 #include "NPRuntimeUtilities.h"
31 #include "ShareableBitmap.h"
34 #include "WebPageProxyMessages.h"
35 #include "WebProcess.h"
36 #include <WebCore/Chrome.h>
37 #include <WebCore/CookieJar.h>
38 #include <WebCore/Credential.h>
39 #include <WebCore/CredentialStorage.h>
40 #include <WebCore/DocumentLoader.h>
41 #include <WebCore/MouseEvent.h>
42 #include <WebCore/FocusController.h>
43 #include <WebCore/Frame.h>
44 #include <WebCore/FrameLoadRequest.h>
45 #include <WebCore/FrameLoaderClient.h>
46 #include <WebCore/FrameView.h>
47 #include <WebCore/GraphicsContext.h>
48 #include <WebCore/HTMLPlugInElement.h>
49 #include <WebCore/HostWindow.h>
50 #include <WebCore/NetscapePlugInStreamLoader.h>
51 #include <WebCore/NetworkingContext.h>
52 #include <WebCore/Page.h>
53 #include <WebCore/ProtectionSpace.h>
54 #include <WebCore/ProxyServer.h>
55 #include <WebCore/RenderEmbeddedObject.h>
56 #include <WebCore/RenderLayer.h>
57 #include <WebCore/ResourceLoadScheduler.h>
58 #include <WebCore/ScriptValue.h>
59 #include <WebCore/ScrollView.h>
60 #include <WebCore/Settings.h>
61 #include <WebCore/UserGestureIndicator.h>
64 using namespace WebCore;
68 class PluginView::URLRequest : public RefCounted<URLRequest> {
70 static PassRefPtr<PluginView::URLRequest> create(uint64_t requestID, const FrameLoadRequest& request, bool allowPopups)
72 return adoptRef(new URLRequest(requestID, request, allowPopups));
75 uint64_t requestID() const { return m_requestID; }
76 const String& target() const { return m_request.frameName(); }
77 const ResourceRequest & request() const { return m_request.resourceRequest(); }
78 bool allowPopups() const { return m_allowPopups; }
81 URLRequest(uint64_t requestID, const FrameLoadRequest& request, bool allowPopups)
82 : m_requestID(requestID)
84 , m_allowPopups(allowPopups)
89 FrameLoadRequest m_request;
93 class PluginView::Stream : public RefCounted<PluginView::Stream>, NetscapePlugInStreamLoaderClient {
95 static PassRefPtr<Stream> create(PluginView* pluginView, uint64_t streamID, const ResourceRequest& request)
97 return adoptRef(new Stream(pluginView, streamID, request));
104 uint64_t streamID() const { return m_streamID; }
107 Stream(PluginView* pluginView, uint64_t streamID, const ResourceRequest& request)
108 : m_pluginView(pluginView)
109 , m_streamID(streamID)
111 , m_streamWasCancelled(false)
115 // NetscapePluginStreamLoaderClient
116 virtual void didReceiveResponse(NetscapePlugInStreamLoader*, const ResourceResponse&);
117 virtual void didReceiveData(NetscapePlugInStreamLoader*, const char*, int);
118 virtual void didFail(NetscapePlugInStreamLoader*, const ResourceError&);
119 virtual void didFinishLoading(NetscapePlugInStreamLoader*);
121 PluginView* m_pluginView;
123 const ResourceRequest m_request;
125 // True if the stream was explicitly cancelled by calling cancel().
126 // (As opposed to being cancelled by the user hitting the stop button for example.
127 bool m_streamWasCancelled;
129 RefPtr<NetscapePlugInStreamLoader> m_loader;
132 PluginView::Stream::~Stream()
134 ASSERT(!m_pluginView);
137 void PluginView::Stream::start()
141 Frame* frame = m_pluginView->m_pluginElement->document()->frame();
144 m_loader = resourceLoadScheduler()->schedulePluginStreamLoad(frame, this, m_request);
147 void PluginView::Stream::cancel()
151 m_streamWasCancelled = true;
152 m_loader->cancel(m_loader->cancelledError());
156 static String buildHTTPHeaders(const ResourceResponse& response, long long& expectedContentLength)
158 if (!response.isHTTP())
161 Vector<UChar> stringBuilder;
162 String separator(": ");
164 String statusLine = String::format("HTTP %d ", response.httpStatusCode());
165 stringBuilder.append(statusLine.characters(), statusLine.length());
166 stringBuilder.append(response.httpStatusText().characters(), response.httpStatusText().length());
167 stringBuilder.append('\n');
169 HTTPHeaderMap::const_iterator end = response.httpHeaderFields().end();
170 for (HTTPHeaderMap::const_iterator it = response.httpHeaderFields().begin(); it != end; ++it) {
171 stringBuilder.append(it->first.characters(), it->first.length());
172 stringBuilder.append(separator.characters(), separator.length());
173 stringBuilder.append(it->second.characters(), it->second.length());
174 stringBuilder.append('\n');
177 String headers = String::adopt(stringBuilder);
179 // If the content is encoded (most likely compressed), then don't send its length to the plugin,
180 // which is only interested in the decoded length, not yet known at the moment.
181 // <rdar://problem/4470599> tracks a request for -[NSURLResponse expectedContentLength] to incorporate this logic.
182 String contentEncoding = response.httpHeaderField("Content-Encoding");
183 if (!contentEncoding.isNull() && contentEncoding != "identity")
184 expectedContentLength = -1;
189 void PluginView::Stream::didReceiveResponse(NetscapePlugInStreamLoader*, const ResourceResponse& response)
191 // Compute the stream related data from the resource response.
192 const KURL& responseURL = response.url();
193 const String& mimeType = response.mimeType();
194 long long expectedContentLength = response.expectedContentLength();
196 String headers = buildHTTPHeaders(response, expectedContentLength);
198 uint32_t streamLength = 0;
199 if (expectedContentLength > 0)
200 streamLength = expectedContentLength;
202 m_pluginView->m_plugin->streamDidReceiveResponse(m_streamID, responseURL, streamLength, response.lastModifiedDate(), mimeType, headers);
205 void PluginView::Stream::didReceiveData(NetscapePlugInStreamLoader*, const char* bytes, int length)
207 m_pluginView->m_plugin->streamDidReceiveData(m_streamID, bytes, length);
210 void PluginView::Stream::didFail(NetscapePlugInStreamLoader*, const ResourceError& error)
212 // Calling streamDidFail could cause us to be deleted, so we hold on to a reference here.
213 RefPtr<Stream> protect(this);
215 // We only want to call streamDidFail if the stream was not explicitly cancelled by the plug-in.
216 if (!m_streamWasCancelled)
217 m_pluginView->m_plugin->streamDidFail(m_streamID, error.isCancellation());
219 m_pluginView->removeStream(this);
223 void PluginView::Stream::didFinishLoading(NetscapePlugInStreamLoader*)
225 // Calling streamDidFinishLoading could cause us to be deleted, so we hold on to a reference here.
226 RefPtr<Stream> protectStream(this);
228 // Protect the plug-in while we're calling into it.
229 NPRuntimeObjectMap::PluginProtector pluginProtector(&m_pluginView->m_npRuntimeObjectMap);
230 m_pluginView->m_plugin->streamDidFinishLoading(m_streamID);
232 m_pluginView->removeStream(this);
236 static inline WebPage* webPage(HTMLPlugInElement* pluginElement)
238 Frame* frame = pluginElement->document()->frame();
241 WebPage* webPage = static_cast<WebFrameLoaderClient*>(frame->loader()->client())->webFrame()->page();
247 PassRefPtr<PluginView> PluginView::create(PassRefPtr<HTMLPlugInElement> pluginElement, PassRefPtr<Plugin> plugin, const Plugin::Parameters& parameters)
249 return adoptRef(new PluginView(pluginElement, plugin, parameters));
252 PluginView::PluginView(PassRefPtr<HTMLPlugInElement> pluginElement, PassRefPtr<Plugin> plugin, const Plugin::Parameters& parameters)
254 , m_pluginElement(pluginElement)
256 , m_webPage(webPage(m_pluginElement.get()))
257 , m_parameters(parameters)
258 , m_isInitialized(false)
259 , m_isWaitingUntilMediaCanStart(false)
260 , m_isBeingDestroyed(false)
261 , m_pendingURLRequestsTimer(RunLoop::main(), this, &PluginView::pendingURLRequestsTimerFired)
262 , m_npRuntimeObjectMap(this)
263 , m_manualStreamState(StreamStateInitial)
266 m_webPage->addPluginView(this);
270 PluginView::~PluginView()
273 m_webPage->removePluginView(this);
276 ASSERT(!m_isBeingDestroyed);
278 if (m_isWaitingUntilMediaCanStart)
279 m_pluginElement->document()->removeMediaCanStartListener(this);
281 // Cancel all pending frame loads.
282 for (FrameLoadMap::iterator it = m_pendingFrameLoads.begin(), end = m_pendingFrameLoads.end(); it != end; ++it)
283 it->first->setLoadListener(0);
285 if (m_plugin && m_isInitialized) {
286 m_isBeingDestroyed = true;
287 m_plugin->destroyPlugin();
288 m_isBeingDestroyed = false;
290 setComplexTextInputState(PluginComplexTextInputDisabled);
294 // Invalidate the object map.
295 m_npRuntimeObjectMap.invalidate();
299 // Null out the plug-in element explicitly so we'll crash earlier if we try to use
300 // the plug-in view after it's been destroyed.
301 m_pluginElement = nullptr;
304 Frame* PluginView::frame() const
306 return m_pluginElement->document()->frame();
309 void PluginView::manualLoadDidReceiveResponse(const ResourceResponse& response)
311 // The plug-in can be null here if it failed to initialize.
315 if (!m_isInitialized) {
316 ASSERT(m_manualStreamState == StreamStateInitial);
317 m_manualStreamState = StreamStateHasReceivedResponse;
318 m_manualStreamResponse = response;
322 // Compute the stream related data from the resource response.
323 const KURL& responseURL = response.url();
324 const String& mimeType = response.mimeType();
325 long long expectedContentLength = response.expectedContentLength();
327 String headers = buildHTTPHeaders(response, expectedContentLength);
329 uint32_t streamLength = 0;
330 if (expectedContentLength > 0)
331 streamLength = expectedContentLength;
333 m_plugin->manualStreamDidReceiveResponse(responseURL, streamLength, response.lastModifiedDate(), mimeType, headers);
336 void PluginView::manualLoadDidReceiveData(const char* bytes, int length)
338 // The plug-in can be null here if it failed to initialize.
342 if (!m_isInitialized) {
343 ASSERT(m_manualStreamState == StreamStateHasReceivedResponse);
344 if (!m_manualStreamData)
345 m_manualStreamData = SharedBuffer::create();
347 m_manualStreamData->append(bytes, length);
351 m_plugin->manualStreamDidReceiveData(bytes, length);
354 void PluginView::manualLoadDidFinishLoading()
356 // The plug-in can be null here if it failed to initialize.
360 if (!m_isInitialized) {
361 ASSERT(m_manualStreamState == StreamStateHasReceivedResponse);
362 m_manualStreamState = StreamStateFinished;
366 m_plugin->manualStreamDidFinishLoading();
369 void PluginView::manualLoadDidFail(const ResourceError& error)
371 // The plug-in can be null here if it failed to initialize.
375 if (!m_isInitialized) {
376 m_manualStreamState = StreamStateFinished;
377 m_manualStreamError = error;
378 m_manualStreamData = nullptr;
382 m_plugin->manualStreamDidFail(error.isCancellation());
386 void PluginView::setWindowIsVisible(bool windowIsVisible)
394 void PluginView::setWindowIsFocused(bool windowIsFocused)
396 if (!m_isInitialized || !m_plugin)
399 m_plugin->windowFocusChanged(windowIsFocused);
402 void PluginView::windowAndViewFramesChanged(const IntRect& windowFrameInScreenCoordinates, const IntRect& viewFrameInWindowCoordinates)
404 if (!m_isInitialized || !m_plugin)
407 m_plugin->windowAndViewFramesChanged(windowFrameInScreenCoordinates, viewFrameInWindowCoordinates);
410 bool PluginView::sendComplexTextInput(uint64_t pluginComplexTextInputIdentifier, const String& textInput)
415 if (m_plugin->pluginComplexTextInputIdentifier() != pluginComplexTextInputIdentifier)
418 m_plugin->sendComplexTextInput(textInput);
424 void PluginView::initializePlugin()
430 // We've already tried and failed to initialize the plug-in.
434 if (Frame* frame = m_pluginElement->document()->frame()) {
435 if (Page* page = frame->page()) {
437 // We shouldn't initialize the plug-in right now, add a listener.
438 if (!page->canStartMedia()) {
439 if (m_isWaitingUntilMediaCanStart)
442 m_isWaitingUntilMediaCanStart = true;
443 m_pluginElement->document()->addMediaCanStartListener(this);
449 if (!m_plugin->initialize(this, m_parameters)) {
450 // We failed to initialize the plug-in.
453 m_webPage->send(Messages::WebPageProxy::DidFailToInitializePlugin(m_parameters.mimeType));
457 m_isInitialized = true;
459 viewGeometryDidChange();
461 redeliverManualStream();
464 if (m_plugin->pluginLayer()) {
466 frame()->view()->enterCompositingMode();
467 m_pluginElement->setNeedsStyleRecalc(SyntheticStyleChange);
471 windowAndViewFramesChanged(m_webPage->windowFrameInScreenCoordinates(), m_webPage->viewFrameInWindowCoordinates());
472 setWindowIsVisible(m_webPage->windowIsVisible());
473 setWindowIsFocused(m_webPage->windowIsFocused());
478 PlatformLayer* PluginView::platformLayer() const
480 // The plug-in can be null here if it failed to initialize.
481 if (!m_isInitialized || !m_plugin)
484 return m_plugin->pluginLayer();
488 JSObject* PluginView::scriptObject(JSGlobalObject* globalObject)
490 // The plug-in can be null here if it failed to initialize.
491 if (!m_isInitialized || !m_plugin)
494 NPObject* scriptableNPObject = m_plugin->pluginScriptableNPObject();
495 if (!scriptableNPObject)
498 JSObject* jsObject = m_npRuntimeObjectMap.getOrCreateJSObject(globalObject, scriptableNPObject);
499 releaseNPObject(scriptableNPObject);
504 void PluginView::privateBrowsingStateChanged(bool privateBrowsingEnabled)
506 // The plug-in can be null here if it failed to initialize.
507 if (!m_isInitialized || !m_plugin)
510 m_plugin->privateBrowsingStateChanged(privateBrowsingEnabled);
513 bool PluginView::getFormValue(String& formValue)
515 // The plug-in can be null here if it failed to initialize.
516 if (!m_isInitialized || !m_plugin)
519 return m_plugin->getFormValue(formValue);
522 void PluginView::setFrameRect(const WebCore::IntRect& rect)
524 Widget::setFrameRect(rect);
525 viewGeometryDidChange();
528 void PluginView::setBoundsSize(const WebCore::IntSize& size)
530 Widget::setBoundsSize(size);
532 viewGeometryDidChange();
535 void PluginView::paint(GraphicsContext* context, const IntRect& dirtyRect)
537 if (context->paintingDisabled() || !m_plugin || !m_isInitialized)
540 IntRect dirtyRectInWindowCoordinates = parent()->contentsToWindow(dirtyRect);
541 IntRect paintRectInWindowCoordinates = intersection(dirtyRectInWindowCoordinates, clipRectInWindowCoordinates());
542 if (paintRectInWindowCoordinates.isEmpty())
546 m_snapshot->paint(*context, frameRect().location(), m_snapshot->bounds());
548 // The plugin is given a frame rect which is parent()->contentsToWindow(frameRect()),
549 // and un-translates by the its origin when painting. The current CTM reflects
550 // this widget's frame is its parent (the document), so we have to offset the CTM by
551 // the document's window coordinates.
552 IntPoint documentOriginInWindowCoordinates = parent()->contentsToWindow(IntPoint());
554 GraphicsContextStateSaver stateSaver(*context);
555 context->translate(-documentOriginInWindowCoordinates.x(), -documentOriginInWindowCoordinates.y());
556 m_plugin->paint(context, paintRectInWindowCoordinates);
560 void PluginView::frameRectsChanged()
562 Widget::frameRectsChanged();
563 viewGeometryDidChange();
566 void PluginView::setParent(ScrollView* scrollView)
568 Widget::setParent(scrollView);
574 void PluginView::handleEvent(Event* event)
576 if (!m_isInitialized || !m_plugin)
579 const WebEvent* currentEvent = WebPage::currentEvent();
583 bool didHandleEvent = false;
585 if ((event->type() == eventNames().mousemoveEvent && currentEvent->type() == WebEvent::MouseMove)
586 || (event->type() == eventNames().mousedownEvent && currentEvent->type() == WebEvent::MouseDown)
587 || (event->type() == eventNames().mouseupEvent && currentEvent->type() == WebEvent::MouseUp)) {
588 // We have a mouse event.
589 if (currentEvent->type() == WebEvent::MouseDown)
590 focusPluginElement();
592 // Adjust mouse coordinates to account for pageScaleFactor
593 WebMouseEvent eventWithScaledCoordinates(*static_cast<const WebMouseEvent*>(currentEvent), frame()->pageScaleFactor());
594 didHandleEvent = m_plugin->handleMouseEvent(eventWithScaledCoordinates);
595 } else if (event->type() == eventNames().mousewheelEvent && currentEvent->type() == WebEvent::Wheel) {
596 // We have a wheel event.
597 didHandleEvent = m_plugin->handleWheelEvent(static_cast<const WebWheelEvent&>(*currentEvent));
598 } else if (event->type() == eventNames().mouseoverEvent && currentEvent->type() == WebEvent::MouseMove) {
599 // We have a mouse enter event.
600 didHandleEvent = m_plugin->handleMouseEnterEvent(static_cast<const WebMouseEvent&>(*currentEvent));
601 } else if (event->type() == eventNames().mouseoutEvent && currentEvent->type() == WebEvent::MouseMove) {
602 // We have a mouse leave event.
603 didHandleEvent = m_plugin->handleMouseLeaveEvent(static_cast<const WebMouseEvent&>(*currentEvent));
604 } else if ((event->type() == eventNames().keydownEvent && currentEvent->type() == WebEvent::KeyDown)
605 || (event->type() == eventNames().keyupEvent && currentEvent->type() == WebEvent::KeyUp)) {
606 // We have a keyboard event.
607 didHandleEvent = m_plugin->handleKeyboardEvent(static_cast<const WebKeyboardEvent&>(*currentEvent));
611 event->setDefaultHandled();
614 void PluginView::notifyWidget(WidgetNotification notification)
616 switch (notification) {
617 case WillPaintFlattened:
618 if (m_plugin && m_isInitialized)
619 m_snapshot = m_plugin->snapshot();
621 case DidPaintFlattened:
622 m_snapshot = nullptr;
627 void PluginView::show()
629 bool wasVisible = isVisible();
631 setSelfVisible(true);
634 viewVisibilityDidChange();
639 void PluginView::hide()
641 bool wasVisible = isVisible();
643 setSelfVisible(false);
646 viewVisibilityDidChange();
651 void PluginView::viewGeometryDidChange()
653 if (!m_isInitialized || !m_plugin || !parent())
656 // Get the frame rect in window coordinates.
657 IntRect frameRectInWindowCoordinates = parent()->contentsToWindow(frameRect());
659 // Adjust bounds to account for pageScaleFactor
660 frameRectInWindowCoordinates.scale(1 / frame()->pageScaleFactor());
661 m_plugin->geometryDidChange(frameRectInWindowCoordinates, clipRectInWindowCoordinates());
664 void PluginView::viewVisibilityDidChange()
666 if (!m_isInitialized || !m_plugin || !parent())
669 m_plugin->visibilityDidChange();
672 IntRect PluginView::clipRectInWindowCoordinates() const
674 // Get the frame rect in window coordinates.
675 IntRect frameRectInWindowCoordinates = parent()->contentsToWindow(frameRect());
677 Frame* frame = this->frame();
679 // Get the window clip rect for the enclosing layer (in window coordinates).
680 RenderLayer* layer = m_pluginElement->renderer()->enclosingLayer();
681 IntRect windowClipRect = frame->view()->windowClipRectForLayer(layer, true);
683 // Intersect the two rects to get the view clip rect in window coordinates.
684 frameRectInWindowCoordinates.intersect(windowClipRect);
686 frameRectInWindowCoordinates.scale(1 / frame->pageScaleFactor());
687 return frameRectInWindowCoordinates;
690 void PluginView::focusPluginElement()
694 if (Page* page = frame()->page())
695 page->focusController()->setFocusedNode(m_pluginElement.get(), frame());
697 frame()->document()->setFocusedNode(m_pluginElement);
700 void PluginView::pendingURLRequestsTimerFired()
702 ASSERT(!m_pendingURLRequests.isEmpty());
704 RefPtr<URLRequest> urlRequest = m_pendingURLRequests.takeFirst();
706 // If there are more requests to perform, reschedule the timer.
707 if (!m_pendingURLRequests.isEmpty())
708 m_pendingURLRequestsTimer.startOneShot(0);
710 performURLRequest(urlRequest.get());
713 void PluginView::performURLRequest(URLRequest* request)
715 // First, check if this is a javascript: url.
716 if (protocolIsJavaScript(request->request().url())) {
717 performJavaScriptURLRequest(request);
721 if (!request->target().isNull()) {
722 performFrameLoadURLRequest(request);
726 // This request is to load a URL and create a stream.
727 RefPtr<Stream> stream = PluginView::Stream::create(this, request->requestID(), request->request());
728 addStream(stream.get());
732 void PluginView::performFrameLoadURLRequest(URLRequest* request)
734 ASSERT(!request->target().isNull());
736 Frame* frame = m_pluginElement->document()->frame();
740 if (!m_pluginElement->document()->securityOrigin()->canDisplay(request->request().url())) {
741 // We can't load the request, send back a reply to the plug-in.
742 m_plugin->frameDidFail(request->requestID(), false);
746 // First, try to find a target frame.
747 Frame* targetFrame = frame->loader()->findFrameForNavigation(request->target());
749 // We did not find a target frame. Ask our frame to load the page. This may or may not create a popup window.
750 frame->loader()->load(request->request(), request->target(), false);
752 // FIXME: We don't know whether the window was successfully created here so we just assume that it worked.
753 // It's better than not telling the plug-in anything.
754 m_plugin->frameDidFinishLoading(request->requestID());
758 // Now ask the frame to load the request.
759 targetFrame->loader()->load(request->request(), false);
761 WebFrame* targetWebFrame = static_cast<WebFrameLoaderClient*>(targetFrame->loader()->client())->webFrame();
762 if (WebFrame::LoadListener* loadListener = targetWebFrame->loadListener()) {
763 // Check if another plug-in view or even this view is waiting for the frame to load.
764 // If it is, tell it that the load was cancelled because it will be anyway.
765 loadListener->didFailLoad(targetWebFrame, true);
768 m_pendingFrameLoads.set(targetWebFrame, request);
769 targetWebFrame->setLoadListener(this);
772 void PluginView::performJavaScriptURLRequest(URLRequest* request)
774 ASSERT(protocolIsJavaScript(request->request().url()));
776 RefPtr<Frame> frame = m_pluginElement->document()->frame();
780 String jsString = decodeURLEscapeSequences(request->request().url().string().substring(sizeof("javascript:") - 1));
782 if (!request->target().isNull()) {
783 // For security reasons, only allow JS requests to be made on the frame that contains the plug-in.
784 if (frame->tree()->find(request->target()) != frame) {
785 // Let the plug-in know that its frame load failed.
786 m_plugin->frameDidFail(request->requestID(), false);
791 // Evaluate the JavaScript code. Note that running JavaScript here could cause the plug-in to be destroyed, so we
792 // grab references to the plug-in here.
793 RefPtr<Plugin> plugin = m_plugin;
794 ScriptValue result = frame->script()->executeScript(jsString, request->allowPopups());
796 // Check if evaluating the JavaScript destroyed the plug-in.
797 if (!plugin->controller())
800 // Don't notify the plug-in at all about targeted javascript: requests. This matches Mozilla and WebKit1.
801 if (!request->target().isNull())
804 ScriptState* scriptState = frame->script()->globalObject(pluginWorld())->globalExec();
806 result.getString(scriptState, resultString);
808 // Send the result back to the plug-in.
809 plugin->didEvaluateJavaScript(request->requestID(), resultString);
812 void PluginView::addStream(Stream* stream)
814 ASSERT(!m_streams.contains(stream->streamID()));
815 m_streams.set(stream->streamID(), stream);
818 void PluginView::removeStream(Stream* stream)
820 ASSERT(m_streams.get(stream->streamID()) == stream);
822 m_streams.remove(stream->streamID());
825 void PluginView::cancelAllStreams()
827 Vector<RefPtr<Stream> > streams;
828 copyValuesToVector(m_streams, streams);
830 for (size_t i = 0; i < streams.size(); ++i)
831 streams[i]->cancel();
833 // Cancelling a stream removes it from the m_streams map, so if we cancel all streams the map should be empty.
834 ASSERT(m_streams.isEmpty());
837 void PluginView::redeliverManualStream()
839 if (m_manualStreamState == StreamStateInitial) {
844 if (m_manualStreamState == StreamStateFailed) {
845 manualLoadDidFail(m_manualStreamError);
849 // Deliver the response.
850 manualLoadDidReceiveResponse(m_manualStreamResponse);
853 if (m_manualStreamData) {
855 unsigned position = 0;
857 while (unsigned length = m_manualStreamData->getSomeData(data, position)) {
858 manualLoadDidReceiveData(data, length);
862 m_manualStreamData = nullptr;
865 if (m_manualStreamState == StreamStateFinished)
866 manualLoadDidFinishLoading();
869 void PluginView::invalidateRect(const IntRect& dirtyRect)
871 if (!parent() || !m_plugin || !m_isInitialized)
875 if (m_plugin->pluginLayer())
879 RenderBoxModelObject* renderer = toRenderBoxModelObject(m_pluginElement->renderer());
883 IntRect contentRect(dirtyRect);
884 contentRect.move(renderer->borderLeft() + renderer->paddingLeft(), renderer->borderTop() + renderer->paddingTop());
885 renderer->repaintRectangle(contentRect);
888 void PluginView::setFocus(bool hasFocus)
890 Widget::setFocus(hasFocus);
892 if (!m_isInitialized || !m_plugin)
895 m_plugin->setFocus(hasFocus);
898 void PluginView::mediaCanStart()
900 ASSERT(m_isWaitingUntilMediaCanStart);
901 m_isWaitingUntilMediaCanStart = false;
906 bool PluginView::isPluginVisible()
911 void PluginView::invalidate(const IntRect& dirtyRect)
913 invalidateRect(dirtyRect);
916 String PluginView::userAgent()
918 Frame* frame = m_pluginElement->document()->frame();
922 return frame->loader()->client()->userAgent(KURL());
925 void PluginView::loadURL(uint64_t requestID, const String& method, const String& urlString, const String& target,
926 const HTTPHeaderMap& headerFields, const Vector<uint8_t>& httpBody, bool allowPopups)
928 FrameLoadRequest frameLoadRequest(m_pluginElement->document()->securityOrigin());
929 frameLoadRequest.resourceRequest().setHTTPMethod(method);
930 frameLoadRequest.resourceRequest().setURL(m_pluginElement->document()->completeURL(urlString));
931 frameLoadRequest.resourceRequest().addHTTPHeaderFields(headerFields);
932 frameLoadRequest.resourceRequest().setHTTPBody(FormData::create(httpBody.data(), httpBody.size()));
933 frameLoadRequest.setFrameName(target);
935 if (!SecurityOrigin::shouldHideReferrer(frameLoadRequest.resourceRequest().url(), frame()->loader()->outgoingReferrer()))
936 frameLoadRequest.resourceRequest().setHTTPReferrer(frame()->loader()->outgoingReferrer());
938 m_pendingURLRequests.append(URLRequest::create(requestID, frameLoadRequest, allowPopups));
939 m_pendingURLRequestsTimer.startOneShot(0);
942 void PluginView::cancelStreamLoad(uint64_t streamID)
944 // Keep a reference to the stream. Stream::cancel might remove the stream from the map, and thus
945 // releasing its last reference.
946 RefPtr<Stream> stream = m_streams.get(streamID).get();
950 // Cancelling the stream here will remove it from the map.
952 ASSERT(!m_streams.contains(streamID));
955 void PluginView::cancelManualStreamLoad()
960 DocumentLoader* documentLoader = frame()->loader()->activeDocumentLoader();
961 ASSERT(documentLoader);
963 if (documentLoader->isLoadingMainResource())
964 documentLoader->cancelMainResourceLoad(frame()->loader()->cancelledError(m_parameters.url));
967 NPObject* PluginView::windowScriptNPObject()
972 // FIXME: Handle JavaScript being disabled.
973 ASSERT(frame()->script()->canExecuteScripts(NotAboutToExecuteScript));
975 return m_npRuntimeObjectMap.getOrCreateNPObject(*pluginWorld()->globalData(), frame()->script()->windowShell(pluginWorld())->window());
978 NPObject* PluginView::pluginElementNPObject()
983 // FIXME: Handle JavaScript being disabled.
984 JSObject* object = frame()->script()->jsObjectForPluginElement(m_pluginElement.get());
987 return m_npRuntimeObjectMap.getOrCreateNPObject(*pluginWorld()->globalData(), object);
990 bool PluginView::evaluate(NPObject* npObject, const String& scriptString, NPVariant* result, bool allowPopups)
992 // FIXME: Is this check necessary?
993 if (!m_pluginElement->document()->frame())
996 // Calling evaluate will run JavaScript that can potentially remove the plug-in element, so we need to
997 // protect the plug-in view from destruction.
998 NPRuntimeObjectMap::PluginProtector pluginProtector(&m_npRuntimeObjectMap);
1000 UserGestureIndicator gestureIndicator(allowPopups ? DefinitelyProcessingUserGesture : PossiblyProcessingUserGesture);
1001 return m_npRuntimeObjectMap.evaluate(npObject, scriptString, result);
1004 bool PluginView::tryToShortCircuitInvoke(NPObject*, NPIdentifier methodName, const NPVariant* arguments, uint32_t argumentCount, bool& returnValue, NPVariant& result)
1006 // Never try to short-circuit invoke in the web process.
1010 void PluginView::setStatusbarText(const String& statusbarText)
1015 Page* page = frame()->page();
1019 page->chrome()->setStatusbarText(frame(), statusbarText);
1022 bool PluginView::isAcceleratedCompositingEnabled()
1027 Settings* settings = frame()->settings();
1031 return settings->acceleratedCompositingEnabled();
1034 void PluginView::pluginProcessCrashed()
1036 if (!m_pluginElement->renderer())
1039 // FIXME: The renderer could also be a RenderApplet, we should handle that.
1040 if (!m_pluginElement->renderer()->isEmbeddedObject())
1043 RenderEmbeddedObject* renderer = toRenderEmbeddedObject(m_pluginElement->renderer());
1044 renderer->setShowsCrashedPluginIndicator();
1046 Widget::invalidate();
1049 void PluginView::willSendEventToPlugin()
1051 // If we're sending an event to a plug-in, we can't control how long the plug-in
1052 // takes to process it (e.g. it may display a context menu), so we tell the UI process
1053 // to stop the responsiveness timer in this case.
1054 m_webPage->send(Messages::WebPageProxy::StopResponsivenessTimer());
1058 HWND PluginView::nativeParentWindow()
1060 return m_webPage->nativeWindow();
1063 void PluginView::scheduleWindowedPluginGeometryUpdate(const WindowGeometry& geometry)
1065 m_webPage->drawingArea()->scheduleChildWindowGeometryUpdate(geometry);
1070 void PluginView::pluginFocusOrWindowFocusChanged(bool pluginHasFocusAndWindowHasFocus)
1072 m_webPage->send(Messages::WebPageProxy::PluginFocusOrWindowFocusChanged(m_plugin->pluginComplexTextInputIdentifier(), pluginHasFocusAndWindowHasFocus));
1075 void PluginView::setComplexTextInputState(PluginComplexTextInputState pluginComplexTextInputState)
1077 m_webPage->send(Messages::WebPageProxy::SetPluginComplexTextInputState(m_plugin->pluginComplexTextInputIdentifier(), pluginComplexTextInputState));
1080 mach_port_t PluginView::compositingRenderServerPort()
1082 return WebProcess::shared().compositingRenderServerPort();
1086 String PluginView::proxiesForURL(const String& urlString)
1088 const FrameLoader* frameLoader = frame() ? frame()->loader() : 0;
1089 const NetworkingContext* context = frameLoader ? frameLoader->networkingContext() : 0;
1090 Vector<ProxyServer> proxyServers = proxyServersForURL(KURL(KURL(), urlString), context);
1091 return toString(proxyServers);
1094 String PluginView::cookiesForURL(const String& urlString)
1096 return cookies(m_pluginElement->document(), KURL(KURL(), urlString));
1099 void PluginView::setCookiesForURL(const String& urlString, const String& cookieString)
1101 setCookies(m_pluginElement->document(), KURL(KURL(), urlString), cookieString);
1104 bool PluginView::getAuthenticationInfo(const ProtectionSpace& protectionSpace, String& username, String& password)
1106 Credential credential = CredentialStorage::get(protectionSpace);
1107 if (credential.isEmpty())
1108 credential = CredentialStorage::getFromPersistentStorage(protectionSpace);
1110 if (!credential.hasPassword())
1113 username = credential.user();
1114 password = credential.password();
1119 bool PluginView::isPrivateBrowsingEnabled()
1121 // If we can't get the real setting, we'll assume that private browsing is enabled.
1125 Settings* settings = frame()->settings();
1129 return settings->privateBrowsingEnabled();
1132 void PluginView::protectPluginFromDestruction()
1134 if (!m_isBeingDestroyed)
1138 void PluginView::unprotectPluginFromDestruction()
1140 if (m_isBeingDestroyed)
1143 // A plug-in may ask us to evaluate JavaScript that removes the plug-in from the
1144 // page, but expect the object to still be alive when the call completes. Flash,
1145 // for example, may crash if the plug-in is destroyed and we return to code for
1146 // the destroyed object higher on the stack. To prevent this, if the plug-in has
1147 // only one remaining reference, call deref() asynchronously.
1149 RunLoop::main()->scheduleWork(WorkItem::createDeref(this));
1154 void PluginView::didFinishLoad(WebFrame* webFrame)
1156 RefPtr<URLRequest> request = m_pendingFrameLoads.take(webFrame);
1158 webFrame->setLoadListener(0);
1160 m_plugin->frameDidFinishLoading(request->requestID());
1163 void PluginView::didFailLoad(WebFrame* webFrame, bool wasCancelled)
1165 RefPtr<URLRequest> request = m_pendingFrameLoads.take(webFrame);
1167 webFrame->setLoadListener(0);
1169 m_plugin->frameDidFail(request->requestID(), wasCancelled);
1172 } // namespace WebKit