2 * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 Collabora Ltd. All rights reserved.
4 * Copyright (C) 2010 Girish Ramakrishnan <girish@forwardbias.in>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
16 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
19 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include "PluginView.h"
32 #include "BridgeJSC.h"
35 #include "CookieJar.h"
37 #include "DocumentLoader.h"
39 #include "FocusController.h"
41 #include "FrameLoader.h"
42 #include "FrameLoaderClient.h"
43 #include "FrameTree.h"
44 #include "FrameView.h"
45 #include "GraphicsContext.h"
46 #include "HTMLNames.h"
47 #include "HTMLPlugInElement.h"
49 #include "KeyboardEvent.h"
50 #include "MIMETypeRegistry.h"
51 #include "MouseEvent.h"
52 #include "NotImplemented.h"
54 #include "PlatformMouseEvent.h"
55 #include "PluginDatabase.h"
56 #include "PluginDebug.h"
57 #include "PluginMainThreadScheduler.h"
58 #include "PluginPackage.h"
59 #include "ProxyServer.h"
60 #include "RenderBox.h"
61 #include "RenderObject.h"
62 #include "ScriptValue.h"
63 #include "SecurityOrigin.h"
65 #include "npruntime_impl.h"
66 #include <wtf/ASCIICType.h>
68 #if OS(WINDOWS) && ENABLE(NETSCAPE_PLUGIN_API)
69 #include "PluginMessageThrottlerWin.h"
73 #include "JSDOMBinding.h"
74 #include "JSDOMWindow.h"
75 #include "c_instance.h"
76 #include "runtime_root.h"
77 #include <runtime/JSLock.h>
78 #include <runtime/JSValue.h>
87 #if ENABLE(NETSCAPE_PLUGIN_API)
95 using namespace HTMLNames;
97 static int s_callingPlugin;
99 typedef HashMap<NPP, PluginView*> InstanceMap;
101 static InstanceMap& instanceMap()
103 static InstanceMap& map = *new InstanceMap;
107 static String scriptStringIfJavaScriptURL(const KURL& url)
109 if (!protocolIsJavaScript(url))
112 // This returns an unescaped string
113 return decodeURLEscapeSequences(url.string().substring(11));
116 PluginView* PluginView::s_currentPluginView = 0;
118 void PluginView::popPopupsStateTimerFired(Timer<PluginView>*)
120 popPopupsEnabledState();
123 IntRect PluginView::windowClipRect() const
125 // Start by clipping to our bounds.
126 IntRect clipRect(m_windowRect);
128 // Take our element and get the clip rect from the enclosing layer and frame view.
129 RenderLayer* layer = m_element->renderer()->enclosingLayer();
130 FrameView* parentView = m_element->document()->view();
131 clipRect.intersect(parentView->windowClipRectForLayer(layer, true));
136 void PluginView::setFrameRect(const IntRect& rect)
138 if (m_element->document()->printing())
141 if (rect != frameRect())
142 Widget::setFrameRect(rect);
144 updatePluginWidget();
146 #if OS(WINDOWS) || OS(SYMBIAN)
147 // On Windows and Symbian, always call plugin to change geometry.
148 setNPWindowRect(rect);
149 #elif defined(XP_UNIX)
150 // On Unix, multiple calls to setNPWindow() in windowed mode causes Flash to crash
151 if (m_mode == NP_FULL || !m_isWindowed)
152 setNPWindowRect(rect);
156 void PluginView::frameRectsChanged()
158 updatePluginWidget();
161 void PluginView::handleEvent(Event* event)
163 if (!m_plugin || m_isWindowed)
166 // Protect the plug-in from deletion while dispatching the event.
167 RefPtr<PluginView> protect(this);
169 if (event->isMouseEvent())
170 handleMouseEvent(static_cast<MouseEvent*>(event));
171 else if (event->isKeyboardEvent())
172 handleKeyboardEvent(static_cast<KeyboardEvent*>(event));
173 #if defined(XP_UNIX) && ENABLE(NETSCAPE_PLUGIN_API)
174 else if (event->type() == eventNames().focusoutEvent)
175 handleFocusOutEvent();
176 else if (event->type() == eventNames().focusinEvent)
177 handleFocusInEvent();
181 void PluginView::init()
183 if (m_haveInitialized)
186 m_haveInitialized = true;
189 ASSERT(m_status == PluginStatusCanNotFindPlugin);
193 LOG(Plugins, "PluginView::init(): Initializing plug-in '%s'", m_plugin->name().utf8().data());
195 if (!m_plugin->load()) {
197 m_status = PluginStatusCanNotLoadPlugin;
201 if (!startOrAddToUnstartedList()) {
202 m_status = PluginStatusCanNotLoadPlugin;
206 m_status = PluginStatusLoadedSuccessfully;
209 bool PluginView::startOrAddToUnstartedList()
211 if (!m_parentFrame->page())
214 // We only delay starting the plug-in if we're going to kick off the load
215 // ourselves. Otherwise, the loader will try to deliver data before we've
216 // started the plug-in.
217 if (!m_loadManually && !m_parentFrame->page()->canStartMedia()) {
218 m_parentFrame->document()->addMediaCanStartListener(this);
219 m_isWaitingToStart = true;
226 bool PluginView::start()
231 m_isWaitingToStart = false;
233 PluginMainThreadScheduler::scheduler().registerPlugin(m_instance);
236 ASSERT(m_plugin->pluginFuncs()->newp);
240 PluginView::setCurrentPluginView(this);
242 JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
244 setCallingPlugin(true);
245 npErr = m_plugin->pluginFuncs()->newp((NPMIMEType)m_mimeType.utf8().data(), m_instance, m_mode, m_paramCount, m_paramNames, m_paramValues, NULL);
246 setCallingPlugin(false);
248 PluginView::setCurrentPluginView(0);
251 if (npErr != NPERR_NO_ERROR) {
252 m_status = PluginStatusCanNotLoadPlugin;
253 PluginMainThreadScheduler::scheduler().unregisterPlugin(m_instance);
259 if (!m_url.isEmpty() && !m_loadManually) {
260 FrameLoadRequest frameLoadRequest(m_parentFrame->document()->securityOrigin());
261 frameLoadRequest.resourceRequest().setHTTPMethod("GET");
262 frameLoadRequest.resourceRequest().setURL(m_url);
263 load(frameLoadRequest, false, 0);
266 m_status = PluginStatusLoadedSuccessfully;
268 if (!platformStart())
269 m_status = PluginStatusCanNotLoadPlugin;
271 if (m_status != PluginStatusLoadedSuccessfully)
277 void PluginView::mediaCanStart()
279 ASSERT(!m_isStarted);
281 parentFrame()->loader()->client()->dispatchDidFailToStartPlugin(this);
284 PluginView::~PluginView()
286 LOG(Plugins, "PluginView::~PluginView()");
288 ASSERT(!m_lifeSupportTimer.isActive());
290 // If we failed to find the plug-in, we'll return early in our constructor, and
291 // m_instance will be 0.
293 instanceMap().remove(m_instance);
295 if (m_isWaitingToStart)
296 m_parentFrame->document()->removeMediaCanStartListener(this);
300 deleteAllValues(m_requests);
302 freeStringArray(m_paramNames, m_paramCount);
303 freeStringArray(m_paramValues, m_paramCount);
307 m_parentFrame->script()->cleanupScriptObjectsForPlugin(this);
309 if (m_plugin && !(m_plugin->quirks().contains(PluginQuirkDontUnloadPlugin)))
313 void PluginView::stop()
318 LOG(Plugins, "PluginView::stop(): Stopping plug-in '%s'", m_plugin->name().utf8().data());
320 HashSet<RefPtr<PluginStream> > streams = m_streams;
321 HashSet<RefPtr<PluginStream> >::iterator end = streams.end();
322 for (HashSet<RefPtr<PluginStream> >::iterator it = streams.begin(); it != end; ++it) {
324 disconnectStream((*it).get());
327 ASSERT(m_streams.isEmpty());
332 JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
335 #if ENABLE(NETSCAPE_PLUGIN_API)
336 #if defined(XP_WIN) && !PLATFORM(GTK)
337 // Unsubclass the window
340 WNDPROC currentWndProc = (WNDPROC)GetWindowLong(platformPluginWidget(), GWL_WNDPROC);
342 if (currentWndProc == PluginViewWndProc)
343 SetWindowLong(platformPluginWidget(), GWL_WNDPROC, (LONG)m_pluginWndProc);
345 WNDPROC currentWndProc = (WNDPROC)GetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC);
347 if (currentWndProc == PluginViewWndProc)
348 SetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC, (LONG_PTR)m_pluginWndProc);
351 #endif // !defined(XP_WIN) || PLATFORM(GTK)
352 #endif // ENABLE(NETSCAPE_PLUGIN_API)
354 #if !defined(XP_MACOSX)
356 m_npWindow.window = 0;
358 if (m_plugin->pluginFuncs()->setwindow && !m_plugin->quirks().contains(PluginQuirkDontSetNullWindowHandleOnDestroy)) {
359 PluginView::setCurrentPluginView(this);
360 setCallingPlugin(true);
361 m_plugin->pluginFuncs()->setwindow(m_instance, &m_npWindow);
362 setCallingPlugin(false);
363 PluginView::setCurrentPluginView(0);
367 if (m_isWindowed && m_npWindow.ws_info)
368 delete (NPSetWindowCallbackStruct *)m_npWindow.ws_info;
369 m_npWindow.ws_info = 0;
372 #endif // !defined(XP_MACOSX)
374 PluginMainThreadScheduler::scheduler().unregisterPlugin(m_instance);
376 NPSavedData* savedData = 0;
377 PluginView::setCurrentPluginView(this);
378 setCallingPlugin(true);
379 NPError npErr = m_plugin->pluginFuncs()->destroy(m_instance, &savedData);
380 setCallingPlugin(false);
382 PluginView::setCurrentPluginView(0);
384 #if ENABLE(NETSCAPE_PLUGIN_API)
386 // TODO: Actually save this data instead of just discarding it
388 NPN_MemFree(savedData->buf);
389 NPN_MemFree(savedData);
393 m_instance->pdata = 0;
396 void PluginView::setCurrentPluginView(PluginView* pluginView)
398 s_currentPluginView = pluginView;
401 PluginView* PluginView::currentPluginView()
403 return s_currentPluginView;
406 static char* createUTF8String(const String& str)
408 CString cstr = str.utf8();
409 char* result = reinterpret_cast<char*>(fastMalloc(cstr.length() + 1));
411 strncpy(result, cstr.data(), cstr.length() + 1);
416 void PluginView::performRequest(PluginRequest* request)
421 // don't let a plugin start any loads if it is no longer part of a document that is being
422 // displayed unless the loads are in the same frame as the plugin.
423 const String& targetFrameName = request->frameLoadRequest().frameName();
424 if (m_parentFrame->loader()->documentLoader() != m_parentFrame->loader()->activeDocumentLoader() &&
425 (targetFrameName.isNull() || m_parentFrame->tree()->find(targetFrameName) != m_parentFrame))
428 KURL requestURL = request->frameLoadRequest().resourceRequest().url();
429 String jsString = scriptStringIfJavaScriptURL(requestURL);
431 if (jsString.isNull()) {
432 // if this is not a targeted request, create a stream for it. otherwise,
433 // just pass it off to the loader
434 if (targetFrameName.isEmpty()) {
435 RefPtr<PluginStream> stream = PluginStream::create(this, m_parentFrame.get(), request->frameLoadRequest().resourceRequest(), request->sendNotification(), request->notifyData(), plugin()->pluginFuncs(), instance(), m_plugin->quirks());
436 m_streams.add(stream);
439 // If the target frame is our frame, we could destroy the
440 // PluginView, so we protect it. <rdar://problem/6991251>
441 RefPtr<PluginView> protect(this);
443 m_parentFrame->loader()->load(request->frameLoadRequest().resourceRequest(), targetFrameName, false);
445 // FIXME: <rdar://problem/4807469> This should be sent when the document has finished loading
446 if (request->sendNotification()) {
447 PluginView::setCurrentPluginView(this);
449 JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
451 setCallingPlugin(true);
452 m_plugin->pluginFuncs()->urlnotify(m_instance, requestURL.string().utf8().data(), NPRES_DONE, request->notifyData());
453 setCallingPlugin(false);
454 PluginView::setCurrentPluginView(0);
460 // Targeted JavaScript requests are only allowed on the frame that contains the JavaScript plugin
461 // and this has been made sure in ::load.
462 ASSERT(targetFrameName.isEmpty() || m_parentFrame->tree()->find(targetFrameName) == m_parentFrame);
464 // Executing a script can cause the plugin view to be destroyed, so we keep a reference to it.
465 RefPtr<PluginView> protector(this);
466 ScriptValue result = m_parentFrame->script()->executeScript(jsString, request->shouldAllowPopups());
468 if (targetFrameName.isNull()) {
472 ScriptState* scriptState = m_parentFrame->script()->globalObject(pluginWorld())->globalExec();
474 ScriptState* scriptState = 0; // Not used with V8
477 if (result.getString(scriptState, resultString))
478 cstr = resultString.utf8();
480 RefPtr<PluginStream> stream = PluginStream::create(this, m_parentFrame.get(), request->frameLoadRequest().resourceRequest(), request->sendNotification(), request->notifyData(), plugin()->pluginFuncs(), instance(), m_plugin->quirks());
481 m_streams.add(stream);
482 stream->sendJavaScriptStream(requestURL, cstr);
486 void PluginView::requestTimerFired(Timer<PluginView>* timer)
488 ASSERT(timer == &m_requestTimer);
489 ASSERT(m_requests.size() > 0);
490 ASSERT(!m_isJavaScriptPaused);
492 PluginRequest* request = m_requests[0];
493 m_requests.remove(0);
495 // Schedule a new request before calling performRequest since the call to
496 // performRequest can cause the plugin view to be deleted.
497 if (m_requests.size() > 0)
498 m_requestTimer.startOneShot(0);
500 performRequest(request);
504 void PluginView::scheduleRequest(PluginRequest* request)
506 m_requests.append(request);
508 if (!m_isJavaScriptPaused)
509 m_requestTimer.startOneShot(0);
512 NPError PluginView::load(const FrameLoadRequest& frameLoadRequest, bool sendNotification, void* notifyData)
514 ASSERT(frameLoadRequest.resourceRequest().httpMethod() == "GET" || frameLoadRequest.resourceRequest().httpMethod() == "POST");
516 KURL url = frameLoadRequest.resourceRequest().url();
519 return NPERR_INVALID_URL;
521 // Don't allow requests to be made when the document loader is stopping all loaders.
522 DocumentLoader* loader = m_parentFrame->loader()->documentLoader();
523 if (!loader || loader->isStopping())
524 return NPERR_GENERIC_ERROR;
526 const String& targetFrameName = frameLoadRequest.frameName();
527 String jsString = scriptStringIfJavaScriptURL(url);
529 if (!jsString.isNull()) {
530 // Return NPERR_GENERIC_ERROR if JS is disabled. This is what Mozilla does.
531 if (!m_parentFrame->script()->canExecuteScripts(NotAboutToExecuteScript))
532 return NPERR_GENERIC_ERROR;
534 // For security reasons, only allow JS requests to be made on the frame that contains the plug-in.
535 if (!targetFrameName.isNull() && m_parentFrame->tree()->find(targetFrameName) != m_parentFrame)
536 return NPERR_INVALID_PARAM;
537 } else if (!m_parentFrame->document()->securityOrigin()->canDisplay(url))
538 return NPERR_GENERIC_ERROR;
540 PluginRequest* request = new PluginRequest(frameLoadRequest, sendNotification, notifyData, arePopupsAllowed());
541 scheduleRequest(request);
543 return NPERR_NO_ERROR;
546 static KURL makeURL(const KURL& baseURL, const char* relativeURLString)
548 String urlString = relativeURLString;
550 // Strip return characters.
551 urlString.replace('\n', "");
552 urlString.replace('\r', "");
554 return KURL(baseURL, urlString);
557 NPError PluginView::getURLNotify(const char* url, const char* target, void* notifyData)
559 FrameLoadRequest frameLoadRequest(m_parentFrame->document()->securityOrigin());
561 frameLoadRequest.setFrameName(target);
562 frameLoadRequest.resourceRequest().setHTTPMethod("GET");
563 frameLoadRequest.resourceRequest().setURL(makeURL(m_baseURL, url));
565 return load(frameLoadRequest, true, notifyData);
568 NPError PluginView::getURL(const char* url, const char* target)
570 FrameLoadRequest frameLoadRequest(m_parentFrame->document()->securityOrigin());
572 frameLoadRequest.setFrameName(target);
573 frameLoadRequest.resourceRequest().setHTTPMethod("GET");
574 frameLoadRequest.resourceRequest().setURL(makeURL(m_baseURL, url));
576 return load(frameLoadRequest, false, 0);
579 NPError PluginView::postURLNotify(const char* url, const char* target, uint32_t len, const char* buf, NPBool file, void* notifyData)
581 return handlePost(url, target, len, buf, file, notifyData, true, true);
584 NPError PluginView::postURL(const char* url, const char* target, uint32_t len, const char* buf, NPBool file)
586 // As documented, only allow headers to be specified via NPP_PostURL when using a file.
587 return handlePost(url, target, len, buf, file, 0, false, file);
590 NPError PluginView::newStream(NPMIMEType type, const char* target, NPStream** stream)
594 return NPERR_GENERIC_ERROR;
597 int32_t PluginView::write(NPStream* stream, int32_t len, void* buffer)
604 NPError PluginView::destroyStream(NPStream* stream, NPReason reason)
606 if (!stream || PluginStream::ownerForStream(stream) != m_instance)
607 return NPERR_INVALID_INSTANCE_ERROR;
609 PluginStream* browserStream = static_cast<PluginStream*>(stream->ndata);
610 browserStream->cancelAndDestroyStream(reason);
612 return NPERR_NO_ERROR;
615 void PluginView::status(const char* message)
617 if (Page* page = m_parentFrame->page())
618 page->chrome()->setStatusbarText(m_parentFrame.get(), String::fromUTF8(message));
621 NPError PluginView::setValue(NPPVariable variable, void* value)
623 LOG(Plugins, "PluginView::setValue(%s): ", prettyNameForNPPVariable(variable, value).data());
626 case NPPVpluginWindowBool:
627 m_isWindowed = value;
628 return NPERR_NO_ERROR;
629 case NPPVpluginTransparentBool:
630 m_isTransparent = value;
631 return NPERR_NO_ERROR;
632 #if defined(XP_MACOSX)
633 case NPPVpluginDrawingModel: {
634 // Can only set drawing model inside NPP_New()
635 if (this != currentPluginView())
636 return NPERR_GENERIC_ERROR;
638 NPDrawingModel newDrawingModel = NPDrawingModel(uintptr_t(value));
639 switch (newDrawingModel) {
640 case NPDrawingModelCoreGraphics:
641 m_drawingModel = newDrawingModel;
642 return NPERR_NO_ERROR;
643 #ifndef NP_NO_QUICKDRAW
644 case NPDrawingModelQuickDraw:
646 case NPDrawingModelCoreAnimation:
648 LOG(Plugins, "Plugin asked for unsupported drawing model: %s",
649 prettyNameForDrawingModel(newDrawingModel));
650 return NPERR_GENERIC_ERROR;
654 case NPPVpluginEventModel: {
655 // Can only set event model inside NPP_New()
656 if (this != currentPluginView())
657 return NPERR_GENERIC_ERROR;
659 NPEventModel newEventModel = NPEventModel(uintptr_t(value));
660 switch (newEventModel) {
662 case NPEventModelCarbon:
664 case NPEventModelCocoa:
665 m_eventModel = newEventModel;
666 return NPERR_NO_ERROR;
669 LOG(Plugins, "Plugin asked for unsupported event model: %s",
670 prettyNameForEventModel(newEventModel));
671 return NPERR_GENERIC_ERROR;
674 #endif // defined(XP_MACOSX)
676 #if PLATFORM(QT) && defined(MOZ_PLATFORM_MAEMO) && (MOZ_PLATFORM_MAEMO >= 5)
677 case NPPVpluginWindowlessLocalBool:
678 m_renderToImage = true;
679 return NPERR_NO_ERROR;
684 return NPERR_GENERIC_ERROR;
688 void PluginView::invalidateTimerFired(Timer<PluginView>* timer)
690 ASSERT(timer == &m_invalidateTimer);
692 for (unsigned i = 0; i < m_invalidRects.size(); i++)
693 invalidateRect(m_invalidRects[i]);
694 m_invalidRects.clear();
698 void PluginView::pushPopupsEnabledState(bool state)
700 m_popupStateStack.append(state);
703 void PluginView::popPopupsEnabledState()
705 m_popupStateStack.removeLast();
708 bool PluginView::arePopupsAllowed() const
710 if (!m_popupStateStack.isEmpty())
711 return m_popupStateStack.last();
716 void PluginView::setJavaScriptPaused(bool paused)
718 if (m_isJavaScriptPaused == paused)
720 m_isJavaScriptPaused = paused;
722 if (m_isJavaScriptPaused)
723 m_requestTimer.stop();
724 else if (!m_requests.isEmpty())
725 m_requestTimer.startOneShot(0);
728 #if ENABLE(NETSCAPE_PLUGIN_API)
729 NPObject* PluginView::npObject()
731 NPObject* object = 0;
733 if (!m_isStarted || !m_plugin || !m_plugin->pluginFuncs()->getvalue)
736 // On Windows, calling Java's NPN_GetValue can allow the message loop to
737 // run, allowing loading to take place or JavaScript to run. Protect the
738 // PluginView from destruction. <rdar://problem/6978804>
739 RefPtr<PluginView> protect(this);
743 PluginView::setCurrentPluginView(this);
745 JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
747 setCallingPlugin(true);
748 npErr = m_plugin->pluginFuncs()->getvalue(m_instance, NPPVpluginScriptableNPObject, &object);
749 setCallingPlugin(false);
750 PluginView::setCurrentPluginView(0);
753 if (npErr != NPERR_NO_ERROR)
761 PassRefPtr<JSC::Bindings::Instance> PluginView::bindingInstance()
763 #if ENABLE(NETSCAPE_PLUGIN_API)
764 NPObject* object = npObject();
769 // The renderer for the PluginView was destroyed during the above call, and
770 // the PluginView will be destroyed when this function returns, so we
775 RefPtr<JSC::Bindings::RootObject> root = m_parentFrame->script()->createRootObject(this);
776 RefPtr<JSC::Bindings::Instance> instance = JSC::Bindings::CInstance::create(object, root.release());
778 _NPN_ReleaseObject(object);
780 return instance.release();
787 void PluginView::disconnectStream(PluginStream* stream)
789 ASSERT(m_streams.contains(stream));
791 m_streams.remove(stream);
794 void PluginView::setParameters(const Vector<String>& paramNames, const Vector<String>& paramValues)
796 ASSERT(paramNames.size() == paramValues.size());
798 unsigned size = paramNames.size();
799 unsigned paramCount = 0;
801 m_paramNames = reinterpret_cast<char**>(fastMalloc(sizeof(char*) * size));
802 m_paramValues = reinterpret_cast<char**>(fastMalloc(sizeof(char*) * size));
804 for (unsigned i = 0; i < size; i++) {
805 if (m_plugin->quirks().contains(PluginQuirkRemoveWindowlessVideoParam) && equalIgnoringCase(paramNames[i], "windowlessvideo"))
808 if (paramNames[i] == "pluginspage")
809 m_pluginsPage = paramValues[i];
811 m_paramNames[paramCount] = createUTF8String(paramNames[i]);
812 m_paramValues[paramCount] = createUTF8String(paramValues[i]);
817 m_paramCount = paramCount;
820 PluginView::PluginView(Frame* parentFrame, const IntSize& size, PluginPackage* plugin, Element* element, const KURL& url, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType, bool loadManually)
821 : m_parentFrame(parentFrame)
826 , m_baseURL(m_parentFrame->document()->baseURL()) // FIXME: No need for this member variable!
827 , m_status(PluginStatusLoadedSuccessfully)
828 , m_requestTimer(this, &PluginView::requestTimerFired)
829 , m_invalidateTimer(this, &PluginView::invalidateTimerFired)
830 , m_popPopupsStateTimer(this, &PluginView::popPopupsStateTimerFired)
831 , m_lifeSupportTimer(this, &PluginView::lifeSupportTimerFired)
832 , m_mode(loadManually ? NP_FULL : NP_EMBED)
835 , m_mimeType(mimeType)
837 #if defined(XP_MACOSX)
838 , m_isWindowed(false)
842 , m_isTransparent(false)
843 , m_haveInitialized(false)
844 , m_isWaitingToStart(false)
846 , m_needsXEmbed(false)
848 #if OS(WINDOWS) && ENABLE(NETSCAPE_PLUGIN_API)
851 , m_isCallingPluginWndProc(false)
853 , m_haveUpdatedPluginWidget(false)
855 #if (PLATFORM(QT) && OS(WINDOWS)) || defined(XP_MACOSX) || PLATFORM(EFL)
858 #if defined(XP_MACOSX)
859 , m_drawingModel(NPDrawingModel(-1))
860 , m_eventModel(NPEventModel(-1))
864 #if defined(XP_UNIX) && ENABLE(NETSCAPE_PLUGIN_API)
865 , m_hasPendingGeometryChange(true)
871 #if PLATFORM(QT) && defined(MOZ_PLATFORM_MAEMO) && (MOZ_PLATFORM_MAEMO >= 5)
872 , m_renderToImage(false)
874 , m_loadManually(loadManually)
876 , m_isJavaScriptPaused(false)
877 , m_haveCalledSetWindow(false)
880 m_status = PluginStatusCanNotFindPlugin;
884 m_instance = &m_instanceStruct;
885 m_instance->ndata = this;
886 m_instance->pdata = 0;
888 instanceMap().add(m_instance, this);
890 setParameters(paramNames, paramValues);
892 memset(&m_npWindow, 0, sizeof(m_npWindow));
893 #if defined(XP_MACOSX)
894 memset(&m_npCgContext, 0, sizeof(m_npCgContext));
900 void PluginView::focusPluginElement()
903 if (Page* page = m_parentFrame->page())
904 page->focusController()->setFocusedNode(m_element, m_parentFrame);
906 m_parentFrame->document()->setFocusedNode(m_element);
909 void PluginView::didReceiveResponse(const ResourceResponse& response)
911 if (m_status != PluginStatusLoadedSuccessfully)
914 ASSERT(m_loadManually);
915 ASSERT(!m_manualStream);
917 m_manualStream = PluginStream::create(this, m_parentFrame.get(), m_parentFrame->loader()->activeDocumentLoader()->request(), false, 0, plugin()->pluginFuncs(), instance(), m_plugin->quirks());
918 m_manualStream->setLoadManually(true);
920 m_manualStream->didReceiveResponse(0, response);
923 void PluginView::didReceiveData(const char* data, int length)
925 if (m_status != PluginStatusLoadedSuccessfully)
928 ASSERT(m_loadManually);
929 ASSERT(m_manualStream);
931 m_manualStream->didReceiveData(0, data, length);
934 void PluginView::didFinishLoading()
936 if (m_status != PluginStatusLoadedSuccessfully)
939 ASSERT(m_loadManually);
940 ASSERT(m_manualStream);
942 m_manualStream->didFinishLoading(0);
945 void PluginView::didFail(const ResourceError& error)
947 if (m_status != PluginStatusLoadedSuccessfully)
950 ASSERT(m_loadManually);
953 m_manualStream->didFail(0, error);
956 void PluginView::setCallingPlugin(bool b) const
958 if (!m_plugin->quirks().contains(PluginQuirkHasModalMessageLoop))
966 ASSERT(s_callingPlugin >= 0);
969 bool PluginView::isCallingPlugin()
971 return s_callingPlugin > 0;
974 PassRefPtr<PluginView> PluginView::create(Frame* parentFrame, const IntSize& size, Element* element, const KURL& url, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType, bool loadManually)
976 // if we fail to find a plugin for this MIME type, findPlugin will search for
977 // a plugin by the file extension and update the MIME type, so pass a mutable String
978 String mimeTypeCopy = mimeType;
979 PluginPackage* plugin = PluginDatabase::installedPlugins()->findPlugin(url, mimeTypeCopy);
981 // No plugin was found, try refreshing the database and searching again
982 if (!plugin && PluginDatabase::installedPlugins()->refresh()) {
983 mimeTypeCopy = mimeType;
984 plugin = PluginDatabase::installedPlugins()->findPlugin(url, mimeTypeCopy);
987 return adoptRef(new PluginView(parentFrame, size, plugin, element, url, paramNames, paramValues, mimeTypeCopy, loadManually));
990 void PluginView::freeStringArray(char** stringArray, int length)
995 for (int i = 0; i < length; i++)
996 fastFree(stringArray[i]);
998 fastFree(stringArray);
1001 static inline bool startsWithBlankLine(const Vector<char>& buffer)
1003 return buffer.size() > 0 && buffer[0] == '\n';
1006 static inline int locationAfterFirstBlankLine(const Vector<char>& buffer)
1008 const char* bytes = buffer.data();
1009 unsigned length = buffer.size();
1011 for (unsigned i = 0; i < length - 4; i++) {
1012 // Support for Acrobat. It sends "\n\n".
1013 if (bytes[i] == '\n' && bytes[i + 1] == '\n')
1016 // Returns the position after 2 CRLF's or 1 CRLF if it is the first line.
1017 if (bytes[i] == '\r' && bytes[i + 1] == '\n') {
1021 else if (bytes[i] == '\n')
1022 // Support for Director. It sends "\r\n\n" (3880387).
1024 else if (bytes[i] == '\r' && bytes[i + 1] == '\n')
1025 // Support for Flash. It sends "\r\n\r\n" (3758113).
1033 static inline const char* findEOL(const char* bytes, unsigned length)
1035 // According to the HTTP specification EOL is defined as
1036 // a CRLF pair. Unfortunately, some servers will use LF
1037 // instead. Worse yet, some servers will use a combination
1038 // of both (e.g. <header>CRLFLF<body>), so findEOL needs
1039 // to be more forgiving. It will now accept CRLF, LF or
1042 // It returns NULL if EOLF is not found or it will return
1043 // a pointer to the first terminating character.
1044 for (unsigned i = 0; i < length; i++) {
1045 if (bytes[i] == '\n')
1047 if (bytes[i] == '\r') {
1048 // Check to see if spanning buffer bounds
1049 // (CRLF is across reads). If so, wait for
1051 if (i + 1 == length)
1061 static inline String capitalizeRFC822HeaderFieldName(const String& name)
1063 bool capitalizeCharacter = true;
1066 for (unsigned i = 0; i < name.length(); i++) {
1069 if (capitalizeCharacter && name[i] >= 'a' && name[i] <= 'z')
1070 c = toASCIIUpper(name[i]);
1071 else if (!capitalizeCharacter && name[i] >= 'A' && name[i] <= 'Z')
1072 c = toASCIILower(name[i]);
1077 capitalizeCharacter = true;
1079 capitalizeCharacter = false;
1087 static inline HTTPHeaderMap parseRFC822HeaderFields(const Vector<char>& buffer, unsigned length)
1089 const char* bytes = buffer.data();
1092 HTTPHeaderMap headerFields;
1094 // Loop ove rlines until we're past the header, or we can't find any more end-of-lines
1095 while ((eol = findEOL(bytes, length))) {
1096 const char* line = bytes;
1097 int lineLength = eol - bytes;
1099 // Move bytes to the character after the terminator as returned by findEOL.
1101 if ((*eol == '\r') && (*bytes == '\n'))
1102 bytes++; // Safe since findEOL won't return a spanning CRLF.
1104 length -= (bytes - line);
1105 if (lineLength == 0)
1106 // Blank line; we're at the end of the header
1108 else if (*line == ' ' || *line == '\t') {
1109 // Continuation of the previous header
1110 if (lastKey.isNull()) {
1111 // malformed header; ignore it and continue
1114 // Merge the continuation of the previous header
1115 String currentValue = headerFields.get(lastKey);
1116 String newValue(line, lineLength);
1118 headerFields.set(lastKey, currentValue + newValue);
1123 for (colon = line; *colon != ':' && colon != eol; colon++) {
1127 // malformed header; ignore it and continue
1130 lastKey = capitalizeRFC822HeaderFieldName(String(line, colon - line));
1133 for (colon++; colon != eol; colon++) {
1134 if (*colon != ' ' && *colon != '\t')
1140 value = String(colon, eol - colon);
1142 String oldValue = headerFields.get(lastKey);
1143 if (!oldValue.isNull()) {
1144 String tmp = oldValue;
1150 headerFields.set(lastKey, value);
1155 return headerFields;
1158 NPError PluginView::handlePost(const char* url, const char* target, uint32_t len, const char* buf, bool file, void* notifyData, bool sendNotification, bool allowHeaders)
1160 if (!url || !len || !buf)
1161 return NPERR_INVALID_PARAM;
1163 FrameLoadRequest frameLoadRequest(m_parentFrame->document()->securityOrigin());
1165 HTTPHeaderMap headerFields;
1166 Vector<char> buffer;
1169 NPError readResult = handlePostReadFile(buffer, len, buf);
1170 if(readResult != NPERR_NO_ERROR)
1174 memcpy(buffer.data(), buf, len);
1177 const char* postData = buffer.data();
1178 int postDataLength = buffer.size();
1181 if (startsWithBlankLine(buffer)) {
1185 int location = locationAfterFirstBlankLine(buffer);
1186 if (location != -1) {
1187 // If the blank line is somewhere in the middle of the buffer, everything before is the header
1188 headerFields = parseRFC822HeaderFields(buffer, location);
1189 unsigned dataLength = buffer.size() - location;
1191 // Sometimes plugins like to set Content-Length themselves when they post,
1192 // but WebFoundation does not like that. So we will remove the header
1193 // and instead truncate the data to the requested length.
1194 String contentLength = headerFields.get("Content-Length");
1196 if (!contentLength.isNull())
1197 dataLength = min(contentLength.toInt(), (int)dataLength);
1198 headerFields.remove("Content-Length");
1200 postData += location;
1201 postDataLength = dataLength;
1206 frameLoadRequest.resourceRequest().setHTTPMethod("POST");
1207 frameLoadRequest.resourceRequest().setURL(makeURL(m_baseURL, url));
1208 frameLoadRequest.resourceRequest().addHTTPHeaderFields(headerFields);
1209 frameLoadRequest.resourceRequest().setHTTPBody(FormData::create(postData, postDataLength));
1210 frameLoadRequest.setFrameName(target);
1212 return load(frameLoadRequest, sendNotification, notifyData);
1215 void PluginView::invalidateWindowlessPluginRect(const IntRect& rect)
1220 if (!m_element->renderer())
1222 RenderBox* renderer = toRenderBox(m_element->renderer());
1224 IntRect dirtyRect = rect;
1225 dirtyRect.move(renderer->borderLeft() + renderer->paddingLeft(), renderer->borderTop() + renderer->paddingTop());
1226 renderer->repaintRectangle(dirtyRect);
1229 void PluginView::paintMissingPluginIcon(GraphicsContext* context, const IntRect& rect)
1231 static RefPtr<Image> nullPluginImage;
1232 if (!nullPluginImage)
1233 nullPluginImage = Image::loadPlatformResource("nullPlugin");
1235 IntRect imageRect(frameRect().x(), frameRect().y(), nullPluginImage->width(), nullPluginImage->height());
1237 int xOffset = (frameRect().width() - imageRect.width()) / 2;
1238 int yOffset = (frameRect().height() - imageRect.height()) / 2;
1240 imageRect.move(xOffset, yOffset);
1242 if (!rect.intersects(imageRect))
1246 context->clip(windowClipRect());
1247 context->drawImage(nullPluginImage.get(), ColorSpaceDeviceRGB, imageRect.location());
1251 static const char* MozillaUserAgent = "Mozilla/5.0 ("
1252 #if defined(XP_MACOSX)
1253 "Macintosh; U; Intel Mac OS X;"
1254 #elif defined(XP_WIN)
1255 "Windows; U; Windows NT 5.1;"
1256 #elif defined(XP_UNIX)
1257 // The Gtk port uses X11 plugins in Mac.
1258 #if OS(DARWIN) && PLATFORM(GTK)
1259 "X11; U; Intel Mac OS X;"
1261 "X11; U; Linux i686;"
1264 " en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0";
1266 const char* PluginView::userAgent()
1268 if (m_plugin->quirks().contains(PluginQuirkWantsMozillaUserAgent))
1269 return MozillaUserAgent;
1271 if (m_userAgent.isNull())
1272 m_userAgent = m_parentFrame->loader()->userAgent(m_url).utf8();
1274 return m_userAgent.data();
1277 #if ENABLE(NETSCAPE_PLUGIN_API)
1278 const char* PluginView::userAgentStatic()
1280 return MozillaUserAgent;
1285 void PluginView::lifeSupportTimerFired(Timer<PluginView>*)
1290 void PluginView::keepAlive()
1292 if (m_lifeSupportTimer.isActive())
1296 m_lifeSupportTimer.startOneShot(0);
1299 #if ENABLE(NETSCAPE_PLUGIN_API)
1300 void PluginView::keepAlive(NPP instance)
1302 PluginView* view = instanceMap().get(instance);
1309 NPError PluginView::getValueStatic(NPNVariable variable, void* value)
1311 LOG(Plugins, "PluginView::getValueStatic(%s)", prettyNameForNPNVariable(variable).data());
1314 if (platformGetValueStatic(variable, value, &result))
1317 return NPERR_GENERIC_ERROR;
1320 NPError PluginView::getValue(NPNVariable variable, void* value)
1322 LOG(Plugins, "PluginView::getValue(%s)", prettyNameForNPNVariable(variable).data());
1325 if (platformGetValue(variable, value, &result))
1328 if (platformGetValueStatic(variable, value, &result))
1332 case NPNVWindowNPObject: {
1333 if (m_isJavaScriptPaused)
1334 return NPERR_GENERIC_ERROR;
1336 NPObject* windowScriptObject = m_parentFrame->script()->windowScriptNPObject();
1338 // Return value is expected to be retained, as described here: <http://www.mozilla.org/projects/plugin/npruntime.html>
1339 if (windowScriptObject)
1340 _NPN_RetainObject(windowScriptObject);
1342 void** v = (void**)value;
1343 *v = windowScriptObject;
1345 return NPERR_NO_ERROR;
1348 case NPNVPluginElementNPObject: {
1349 if (m_isJavaScriptPaused)
1350 return NPERR_GENERIC_ERROR;
1352 NPObject* pluginScriptObject = 0;
1354 if (m_element->hasTagName(appletTag) || m_element->hasTagName(embedTag) || m_element->hasTagName(objectTag))
1355 pluginScriptObject = static_cast<HTMLPlugInElement*>(m_element)->getNPObject();
1357 // Return value is expected to be retained, as described here: <http://www.mozilla.org/projects/plugin/npruntime.html>
1358 if (pluginScriptObject)
1359 _NPN_RetainObject(pluginScriptObject);
1361 void** v = (void**)value;
1362 *v = pluginScriptObject;
1364 return NPERR_NO_ERROR;
1367 case NPNVprivateModeBool: {
1368 Page* page = m_parentFrame->page();
1370 return NPERR_GENERIC_ERROR;
1371 *((NPBool*)value) = !page->settings() || page->settings()->privateBrowsingEnabled();
1372 return NPERR_NO_ERROR;
1376 return NPERR_GENERIC_ERROR;
1380 static Frame* getFrame(Frame* parentFrame, Element* element)
1385 Document* document = element->document();
1387 document = element->ownerDocument();
1389 return document->frame();
1394 NPError PluginView::getValueForURL(NPNURLVariable variable, const char* url, char** value, uint32_t* len)
1396 LOG(Plugins, "PluginView::getValueForURL(%s)", prettyNameForNPNURLVariable(variable).data());
1398 NPError result = NPERR_NO_ERROR;
1401 case NPNURLVCookie: {
1402 KURL u(m_baseURL, url);
1404 Frame* frame = getFrame(parentFrame(), m_element);
1406 const CString cookieStr = cookies(frame->document(), u).utf8();
1407 if (!cookieStr.isNull()) {
1408 const int size = cookieStr.length();
1409 *value = static_cast<char*>(NPN_MemAlloc(size+1));
1411 memset(*value, 0, size+1);
1412 memcpy(*value, cookieStr.data(), size+1);
1416 result = NPERR_OUT_OF_MEMORY_ERROR;
1420 result = NPERR_INVALID_URL;
1423 case NPNURLVProxy: {
1424 KURL u(m_baseURL, url);
1426 Frame* frame = getFrame(parentFrame(), m_element);
1427 const FrameLoader* frameLoader = frame ? frame->loader() : 0;
1428 const NetworkingContext* context = frameLoader ? frameLoader->networkingContext() : 0;
1429 const CString proxyStr = toString(proxyServersForURL(u, context)).utf8();
1430 if (!proxyStr.isNull()) {
1431 const int size = proxyStr.length();
1432 *value = static_cast<char*>(NPN_MemAlloc(size+1));
1434 memset(*value, 0, size+1);
1435 memcpy(*value, proxyStr.data(), size+1);
1439 result = NPERR_OUT_OF_MEMORY_ERROR;
1442 result = NPERR_INVALID_URL;
1446 result = NPERR_GENERIC_ERROR;
1447 LOG(Plugins, "PluginView::getValueForURL: %s", prettyNameForNPNURLVariable(variable).data());
1455 NPError PluginView::setValueForURL(NPNURLVariable variable, const char* url, const char* value, uint32_t len)
1457 LOG(Plugins, "PluginView::setValueForURL(%s)", prettyNameForNPNURLVariable(variable).data());
1459 NPError result = NPERR_NO_ERROR;
1462 case NPNURLVCookie: {
1463 KURL u(m_baseURL, url);
1465 const String cookieStr = String::fromUTF8(value, len);
1466 Frame* frame = getFrame(parentFrame(), m_element);
1467 if (frame && !cookieStr.isEmpty())
1468 setCookies(frame->document(), u, cookieStr);
1470 result = NPERR_INVALID_URL;
1474 LOG(Plugins, "PluginView::setValueForURL(%s): Plugins are NOT allowed to set proxy information.", prettyNameForNPNURLVariable(variable).data());
1475 result = NPERR_GENERIC_ERROR;
1478 LOG(Plugins, "PluginView::setValueForURL: %s", prettyNameForNPNURLVariable(variable).data());
1479 result = NPERR_GENERIC_ERROR;
1486 NPError PluginView::getAuthenticationInfo(const char* protocol, const char* host, int32_t port, const char* scheme, const char* realm, char** username, uint32_t* ulen, char** password, uint32_t* plen)
1488 LOG(Plugins, "PluginView::getAuthenticationInfo: protocol=%s, host=%s, port=%d", protocol, host, port);
1490 return NPERR_GENERIC_ERROR;
1494 void PluginView::privateBrowsingStateChanged(bool privateBrowsingEnabled)
1496 NPP_SetValueProcPtr setValue = m_plugin->pluginFuncs()->setvalue;
1500 PluginView::setCurrentPluginView(this);
1502 JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
1504 setCallingPlugin(true);
1505 NPBool value = privateBrowsingEnabled;
1506 setValue(m_instance, NPNVprivateModeBool, &value);
1507 setCallingPlugin(false);
1508 PluginView::setCurrentPluginView(0);
1511 } // namespace WebCore
1513 #endif // ENABLE(NETSCAPE_PLUGIN_API)