2 * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 Collabora Ltd. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "PluginView.h"
33 #include "DocumentLoader.h"
35 #include "FocusController.h"
37 #include "FrameLoader.h"
38 #include "FrameLoaderClient.h"
39 #include "FrameTree.h"
40 #include "FrameView.h"
41 #include "GraphicsContext.h"
42 #include "HTMLNames.h"
43 #include "HTMLPlugInElement.h"
45 #include "KeyboardEvent.h"
46 #include "MIMETypeRegistry.h"
47 #include "MouseEvent.h"
48 #include "NotImplemented.h"
50 #include "PlatformMouseEvent.h"
51 #include "PluginDatabase.h"
52 #include "PluginDebug.h"
53 #include "PluginMainThreadScheduler.h"
54 #include "PluginPackage.h"
55 #include "RenderBox.h"
56 #include "RenderObject.h"
57 #include "ScriptController.h"
58 #include "ScriptValue.h"
59 #include "SecurityOrigin.h"
61 #include "npruntime_impl.h"
62 #include <wtf/ASCIICType.h>
64 #if OS(WINDOWS) && ENABLE(NETSCAPE_PLUGIN_API)
65 #include "PluginMessageThrottlerWin.h"
69 #if defined(ANDROID_PLUGINS)
70 #include "TouchEvent.h"
74 >>>>>>> webkit.org at r60074
76 #include "JSDOMBinding.h"
77 #include "JSDOMWindow.h"
78 #include "c_instance.h"
79 #include "runtime_root.h"
80 #include <runtime/JSLock.h>
81 #include <runtime/JSValue.h>
96 using namespace HTMLNames;
98 static int s_callingPlugin;
100 typedef HashMap<NPP, PluginView*> InstanceMap;
102 static InstanceMap& instanceMap()
104 static InstanceMap& map = *new InstanceMap;
108 static String scriptStringIfJavaScriptURL(const KURL& url)
110 if (!protocolIsJavaScript(url))
113 // This returns an unescaped string
114 return decodeURLEscapeSequences(url.string().substring(11));
117 PluginView* PluginView::s_currentPluginView = 0;
119 void PluginView::popPopupsStateTimerFired(Timer<PluginView>*)
121 popPopupsEnabledState();
124 IntRect PluginView::windowClipRect() const
126 // Start by clipping to our bounds.
127 IntRect clipRect(m_windowRect);
129 // Take our element and get the clip rect from the enclosing layer and frame view.
130 RenderLayer* layer = m_element->renderer()->enclosingLayer();
131 FrameView* parentView = m_element->document()->view();
132 clipRect.intersect(parentView->windowClipRectForLayer(layer, true));
137 void PluginView::setFrameRect(const IntRect& rect)
139 if (m_element->document()->printing())
142 if (rect != frameRect())
143 Widget::setFrameRect(rect);
145 updatePluginWidget();
147 #if OS(WINDOWS) || OS(SYMBIAN)
148 // On Windows and Symbian, always call plugin to change geometry.
149 setNPWindowRect(rect);
150 #elif defined(XP_UNIX)
151 // On Unix, multiple calls to setNPWindow() in windowed mode causes Flash to crash
152 if (m_mode == NP_FULL || !m_isWindowed)
153 setNPWindowRect(rect);
157 void PluginView::frameRectsChanged()
159 updatePluginWidget();
162 void PluginView::handleEvent(Event* event)
164 if (!m_plugin || m_isWindowed)
167 // Protect the plug-in from deletion while dispatching the event.
168 RefPtr<PluginView> protect(this);
170 if (event->isMouseEvent())
171 handleMouseEvent(static_cast<MouseEvent*>(event));
172 else if (event->isKeyboardEvent())
173 handleKeyboardEvent(static_cast<KeyboardEvent*>(event));
174 #if defined(ANDROID_PLUGINS)
175 #if ENABLE(TOUCH_EVENTS)
176 else if (event->isTouchEvent())
177 handleTouchEvent(static_cast<TouchEvent*>(event));
179 else if (event->type() == eventNames().DOMFocusOutEvent)
180 handleFocusEvent(false);
181 else if (event->type() == eventNames().DOMFocusInEvent)
182 handleFocusEvent(true);
184 #if defined(XP_UNIX) && ENABLE(NETSCAPE_PLUGIN_API)
185 else if (event->type() == eventNames().DOMFocusOutEvent)
186 handleFocusOutEvent();
187 else if (event->type() == eventNames().DOMFocusInEvent)
188 handleFocusInEvent();
192 void PluginView::init()
194 if (m_haveInitialized)
197 m_haveInitialized = true;
200 ASSERT(m_status == PluginStatusCanNotFindPlugin);
204 LOG(Plugins, "PluginView::init(): Initializing plug-in '%s'", m_plugin->name().utf8().data());
206 if (!m_plugin->load()) {
208 m_status = PluginStatusCanNotLoadPlugin;
212 if (!startOrAddToUnstartedList()) {
213 m_status = PluginStatusCanNotLoadPlugin;
217 m_status = PluginStatusLoadedSuccessfully;
220 bool PluginView::startOrAddToUnstartedList()
222 if (!m_parentFrame->page())
225 // We only delay starting the plug-in if we're going to kick off the load
226 // ourselves. Otherwise, the loader will try to deliver data before we've
227 // started the plug-in.
228 if (!m_loadManually && !m_parentFrame->page()->canStartMedia()) {
229 m_parentFrame->document()->addMediaCanStartListener(this);
230 m_isWaitingToStart = true;
237 bool PluginView::start()
242 m_isWaitingToStart = false;
244 PluginMainThreadScheduler::scheduler().registerPlugin(m_instance);
247 ASSERT(m_plugin->pluginFuncs()->newp);
251 PluginView::setCurrentPluginView(this);
253 JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
255 setCallingPlugin(true);
256 npErr = m_plugin->pluginFuncs()->newp((NPMIMEType)m_mimeType.utf8().data(), m_instance, m_mode, m_paramCount, m_paramNames, m_paramValues, NULL);
257 setCallingPlugin(false);
259 PluginView::setCurrentPluginView(0);
262 if (npErr != NPERR_NO_ERROR) {
263 m_status = PluginStatusCanNotLoadPlugin;
264 PluginMainThreadScheduler::scheduler().unregisterPlugin(m_instance);
270 if (!m_url.isEmpty() && !m_loadManually) {
271 FrameLoadRequest frameLoadRequest;
272 frameLoadRequest.resourceRequest().setHTTPMethod("GET");
273 frameLoadRequest.resourceRequest().setURL(m_url);
274 #ifdef ANDROID_PLUGINS
275 if (!SecurityOrigin::shouldHideReferrer(
276 m_url, m_parentFrame->loader()->outgoingReferrer()))
277 frameLoadRequest.resourceRequest().setHTTPReferrer(
278 m_parentFrame->loader()->outgoingReferrer());
280 load(frameLoadRequest, false, 0);
283 m_status = PluginStatusLoadedSuccessfully;
285 if (!platformStart())
286 m_status = PluginStatusCanNotLoadPlugin;
288 if (m_status != PluginStatusLoadedSuccessfully)
291 if (parentFrame()->page())
292 parentFrame()->page()->didStartPlugin(this);
297 void PluginView::mediaCanStart()
299 ASSERT(!m_isStarted);
301 parentFrame()->loader()->client()->dispatchDidFailToStartPlugin(this);
304 PluginView::~PluginView()
306 LOG(Plugins, "PluginView::~PluginView()");
308 ASSERT(!m_lifeSupportTimer.isActive());
310 instanceMap().remove(m_instance);
312 if (m_isWaitingToStart)
313 m_parentFrame->document()->removeMediaCanStartListener(this);
317 deleteAllValues(m_requests);
319 freeStringArray(m_paramNames, m_paramCount);
320 freeStringArray(m_paramValues, m_paramCount);
324 m_parentFrame->script()->cleanupScriptObjectsForPlugin(this);
326 #if PLATFORM(ANDROID)
327 // Since we have no legacy plugins to check, we ignore the quirks check.
330 if (m_plugin && !(m_plugin->quirks().contains(PluginQuirkDontUnloadPlugin)))
335 void PluginView::stop()
340 if (parentFrame()->page())
341 parentFrame()->page()->didStopPlugin(this);
343 LOG(Plugins, "PluginView::stop(): Stopping plug-in '%s'", m_plugin->name().utf8().data());
345 HashSet<RefPtr<PluginStream> > streams = m_streams;
346 HashSet<RefPtr<PluginStream> >::iterator end = streams.end();
347 for (HashSet<RefPtr<PluginStream> >::iterator it = streams.begin(); it != end; ++it) {
349 disconnectStream((*it).get());
352 ASSERT(m_streams.isEmpty());
357 JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
360 #if ENABLE(NETSCAPE_PLUGIN_API)
362 // Unsubclass the window
365 WNDPROC currentWndProc = (WNDPROC)GetWindowLong(platformPluginWidget(), GWL_WNDPROC);
367 if (currentWndProc == PluginViewWndProc)
368 SetWindowLong(platformPluginWidget(), GWL_WNDPROC, (LONG)m_pluginWndProc);
370 WNDPROC currentWndProc = (WNDPROC)GetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC);
372 if (currentWndProc == PluginViewWndProc)
373 SetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC, (LONG_PTR)m_pluginWndProc);
377 #endif // ENABLE(NETSCAPE_PLUGIN_API)
379 #if !defined(XP_MACOSX)
381 m_npWindow.window = 0;
383 if (m_plugin->pluginFuncs()->setwindow && !m_plugin->quirks().contains(PluginQuirkDontSetNullWindowHandleOnDestroy)) {
384 PluginView::setCurrentPluginView(this);
385 setCallingPlugin(true);
386 m_plugin->pluginFuncs()->setwindow(m_instance, &m_npWindow);
387 setCallingPlugin(false);
388 PluginView::setCurrentPluginView(0);
392 if (m_isWindowed && m_npWindow.ws_info)
393 delete (NPSetWindowCallbackStruct *)m_npWindow.ws_info;
394 m_npWindow.ws_info = 0;
397 #endif // !defined(XP_MACOSX)
399 PluginMainThreadScheduler::scheduler().unregisterPlugin(m_instance);
401 NPSavedData* savedData = 0;
402 PluginView::setCurrentPluginView(this);
403 setCallingPlugin(true);
404 NPError npErr = m_plugin->pluginFuncs()->destroy(m_instance, &savedData);
405 setCallingPlugin(false);
407 PluginView::setCurrentPluginView(0);
409 #if ENABLE(NETSCAPE_PLUGIN_API)
411 // TODO: Actually save this data instead of just discarding it
413 NPN_MemFree(savedData->buf);
414 NPN_MemFree(savedData);
418 m_instance->pdata = 0;
421 void PluginView::setCurrentPluginView(PluginView* pluginView)
423 s_currentPluginView = pluginView;
426 PluginView* PluginView::currentPluginView()
428 return s_currentPluginView;
431 static char* createUTF8String(const String& str)
433 CString cstr = str.utf8();
434 char* result = reinterpret_cast<char*>(fastMalloc(cstr.length() + 1));
436 strncpy(result, cstr.data(), cstr.length() + 1);
441 void PluginView::performRequest(PluginRequest* request)
446 // don't let a plugin start any loads if it is no longer part of a document that is being
447 // displayed unless the loads are in the same frame as the plugin.
448 const String& targetFrameName = request->frameLoadRequest().frameName();
449 if (m_parentFrame->loader()->documentLoader() != m_parentFrame->loader()->activeDocumentLoader() &&
450 (targetFrameName.isNull() || m_parentFrame->tree()->find(targetFrameName) != m_parentFrame))
453 KURL requestURL = request->frameLoadRequest().resourceRequest().url();
454 String jsString = scriptStringIfJavaScriptURL(requestURL);
456 if (jsString.isNull()) {
457 // if this is not a targeted request, create a stream for it. otherwise,
458 // just pass it off to the loader
459 if (targetFrameName.isEmpty()) {
460 RefPtr<PluginStream> stream = PluginStream::create(this, m_parentFrame.get(), request->frameLoadRequest().resourceRequest(), request->sendNotification(), request->notifyData(), plugin()->pluginFuncs(), instance(), m_plugin->quirks());
461 m_streams.add(stream);
464 // If the target frame is our frame, we could destroy the
465 // PluginView, so we protect it. <rdar://problem/6991251>
466 RefPtr<PluginView> protect(this);
468 m_parentFrame->loader()->load(request->frameLoadRequest().resourceRequest(), targetFrameName, false);
470 // FIXME: <rdar://problem/4807469> This should be sent when the document has finished loading
471 if (request->sendNotification()) {
472 PluginView::setCurrentPluginView(this);
474 JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
476 setCallingPlugin(true);
477 m_plugin->pluginFuncs()->urlnotify(m_instance, requestURL.string().utf8().data(), NPRES_DONE, request->notifyData());
478 setCallingPlugin(false);
479 PluginView::setCurrentPluginView(0);
485 // Targeted JavaScript requests are only allowed on the frame that contains the JavaScript plugin
486 // and this has been made sure in ::load.
487 ASSERT(targetFrameName.isEmpty() || m_parentFrame->tree()->find(targetFrameName) == m_parentFrame);
489 // Executing a script can cause the plugin view to be destroyed, so we keep a reference to the parent frame.
490 RefPtr<Frame> parentFrame = m_parentFrame;
491 ScriptValue result = m_parentFrame->script()->executeScript(jsString, request->shouldAllowPopups());
493 if (targetFrameName.isNull()) {
497 ScriptState* scriptState = parentFrame->script()->globalObject(pluginWorld())->globalExec();
499 ScriptState* scriptState = 0; // Not used with V8
502 if (result.getString(scriptState, resultString))
503 cstr = resultString.utf8();
505 RefPtr<PluginStream> stream = PluginStream::create(this, m_parentFrame.get(), request->frameLoadRequest().resourceRequest(), request->sendNotification(), request->notifyData(), plugin()->pluginFuncs(), instance(), m_plugin->quirks());
506 m_streams.add(stream);
507 stream->sendJavaScriptStream(requestURL, cstr);
511 void PluginView::requestTimerFired(Timer<PluginView>* timer)
513 ASSERT(timer == &m_requestTimer);
514 ASSERT(m_requests.size() > 0);
515 ASSERT(!m_isJavaScriptPaused);
517 PluginRequest* request = m_requests[0];
518 m_requests.remove(0);
520 // Schedule a new request before calling performRequest since the call to
521 // performRequest can cause the plugin view to be deleted.
522 if (m_requests.size() > 0)
523 m_requestTimer.startOneShot(0);
525 performRequest(request);
529 void PluginView::scheduleRequest(PluginRequest* request)
531 m_requests.append(request);
533 if (!m_isJavaScriptPaused)
534 m_requestTimer.startOneShot(0);
537 NPError PluginView::load(const FrameLoadRequest& frameLoadRequest, bool sendNotification, void* notifyData)
539 ASSERT(frameLoadRequest.resourceRequest().httpMethod() == "GET" || frameLoadRequest.resourceRequest().httpMethod() == "POST");
541 KURL url = frameLoadRequest.resourceRequest().url();
544 return NPERR_INVALID_URL;
546 // Don't allow requests to be made when the document loader is stopping all loaders.
547 DocumentLoader* loader = m_parentFrame->loader()->documentLoader();
548 if (!loader || loader->isStopping())
549 return NPERR_GENERIC_ERROR;
551 const String& targetFrameName = frameLoadRequest.frameName();
552 String jsString = scriptStringIfJavaScriptURL(url);
554 if (!jsString.isNull()) {
555 // Return NPERR_GENERIC_ERROR if JS is disabled. This is what Mozilla does.
556 if (!m_parentFrame->script()->canExecuteScripts(NotAboutToExecuteScript))
557 return NPERR_GENERIC_ERROR;
559 // For security reasons, only allow JS requests to be made on the frame that contains the plug-in.
560 if (!targetFrameName.isNull() && m_parentFrame->tree()->find(targetFrameName) != m_parentFrame)
561 return NPERR_INVALID_PARAM;
562 } else if (!SecurityOrigin::canLoad(url, String(), m_parentFrame->document()))
563 return NPERR_GENERIC_ERROR;
565 PluginRequest* request = new PluginRequest(frameLoadRequest, sendNotification, notifyData, arePopupsAllowed());
566 scheduleRequest(request);
568 return NPERR_NO_ERROR;
571 static KURL makeURL(const KURL& baseURL, const char* relativeURLString)
573 String urlString = relativeURLString;
575 // Strip return characters.
576 urlString.replace('\n', "");
577 urlString.replace('\r', "");
579 return KURL(baseURL, urlString);
582 NPError PluginView::getURLNotify(const char* url, const char* target, void* notifyData)
584 FrameLoadRequest frameLoadRequest;
586 frameLoadRequest.setFrameName(target);
587 frameLoadRequest.resourceRequest().setHTTPMethod("GET");
588 frameLoadRequest.resourceRequest().setURL(makeURL(m_baseURL, url));
589 #ifdef ANDROID_PLUGINS
590 if (!SecurityOrigin::shouldHideReferrer(
591 frameLoadRequest.resourceRequest().url(), m_url))
592 frameLoadRequest.resourceRequest().setHTTPReferrer(m_url);
595 return load(frameLoadRequest, true, notifyData);
598 NPError PluginView::getURL(const char* url, const char* target)
600 FrameLoadRequest frameLoadRequest;
602 frameLoadRequest.setFrameName(target);
603 frameLoadRequest.resourceRequest().setHTTPMethod("GET");
604 frameLoadRequest.resourceRequest().setURL(makeURL(m_baseURL, url));
605 #ifdef ANDROID_PLUGINS
606 if (!SecurityOrigin::shouldHideReferrer(
607 frameLoadRequest.resourceRequest().url(), m_url))
608 frameLoadRequest.resourceRequest().setHTTPReferrer(m_url);
611 return load(frameLoadRequest, false, 0);
614 NPError PluginView::postURLNotify(const char* url, const char* target, uint32_t len, const char* buf, NPBool file, void* notifyData)
616 return handlePost(url, target, len, buf, file, notifyData, true, true);
619 NPError PluginView::postURL(const char* url, const char* target, uint32_t len, const char* buf, NPBool file)
621 // As documented, only allow headers to be specified via NPP_PostURL when using a file.
622 return handlePost(url, target, len, buf, file, 0, false, file);
625 NPError PluginView::newStream(NPMIMEType type, const char* target, NPStream** stream)
629 return NPERR_GENERIC_ERROR;
632 int32_t PluginView::write(NPStream* stream, int32_t len, void* buffer)
639 NPError PluginView::destroyStream(NPStream* stream, NPReason reason)
641 if (!stream || PluginStream::ownerForStream(stream) != m_instance)
642 return NPERR_INVALID_INSTANCE_ERROR;
644 PluginStream* browserStream = static_cast<PluginStream*>(stream->ndata);
645 browserStream->cancelAndDestroyStream(reason);
647 return NPERR_NO_ERROR;
650 void PluginView::status(const char* message)
652 if (Page* page = m_parentFrame->page())
653 page->chrome()->setStatusbarText(m_parentFrame.get(), String::fromUTF8(message));
656 NPError PluginView::setValue(NPPVariable variable, void* value)
658 LOG(Plugins, "PluginView::setValue(%s): ", prettyNameForNPPVariable(variable, value).data());
661 case NPPVpluginWindowBool:
662 m_isWindowed = value;
663 return NPERR_NO_ERROR;
664 case NPPVpluginTransparentBool:
665 m_isTransparent = value;
666 return NPERR_NO_ERROR;
667 #if defined(XP_MACOSX)
668 case NPPVpluginDrawingModel: {
669 // Can only set drawing model inside NPP_New()
670 if (this != currentPluginView())
671 return NPERR_GENERIC_ERROR;
673 NPDrawingModel newDrawingModel = NPDrawingModel(uintptr_t(value));
674 switch (newDrawingModel) {
675 case NPDrawingModelCoreGraphics:
676 m_drawingModel = newDrawingModel;
677 return NPERR_NO_ERROR;
678 #ifndef NP_NO_QUICKDRAW
679 case NPDrawingModelQuickDraw:
681 case NPDrawingModelCoreAnimation:
683 LOG(Plugins, "Plugin asked for unsupported drawing model: %s",
684 prettyNameForDrawingModel(newDrawingModel));
685 return NPERR_GENERIC_ERROR;
689 case NPPVpluginEventModel: {
690 // Can only set event model inside NPP_New()
691 if (this != currentPluginView())
692 return NPERR_GENERIC_ERROR;
694 NPEventModel newEventModel = NPEventModel(uintptr_t(value));
695 switch (newEventModel) {
697 case NPEventModelCarbon:
699 case NPEventModelCocoa:
700 m_eventModel = newEventModel;
701 return NPERR_NO_ERROR;
704 LOG(Plugins, "Plugin asked for unsupported event model: %s",
705 prettyNameForEventModel(newEventModel));
706 return NPERR_GENERIC_ERROR;
709 #endif // defined(XP_MACOSX)
712 #ifdef PLUGIN_PLATFORM_SETVALUE
713 return platformSetValue(variable, value);
716 return NPERR_GENERIC_ERROR;
721 void PluginView::invalidateTimerFired(Timer<PluginView>* timer)
723 ASSERT(timer == &m_invalidateTimer);
725 for (unsigned i = 0; i < m_invalidRects.size(); i++)
726 invalidateRect(m_invalidRects[i]);
727 m_invalidRects.clear();
731 void PluginView::pushPopupsEnabledState(bool state)
733 m_popupStateStack.append(state);
736 void PluginView::popPopupsEnabledState()
738 m_popupStateStack.removeLast();
741 bool PluginView::arePopupsAllowed() const
743 if (!m_popupStateStack.isEmpty())
744 return m_popupStateStack.last();
749 void PluginView::setJavaScriptPaused(bool paused)
751 if (m_isJavaScriptPaused == paused)
753 m_isJavaScriptPaused = paused;
755 if (m_isJavaScriptPaused)
756 m_requestTimer.stop();
757 else if (!m_requests.isEmpty())
758 m_requestTimer.startOneShot(0);
762 PassRefPtr<JSC::Bindings::Instance> PluginView::bindingInstance()
764 #if ENABLE(NETSCAPE_PLUGIN_API)
765 NPObject* object = 0;
767 if (!m_isStarted || !m_plugin || !m_plugin->pluginFuncs()->getvalue)
770 // On Windows, calling Java's NPN_GetValue can allow the message loop to
771 // run, allowing loading to take place or JavaScript to run. Protect the
772 // PluginView from destruction. <rdar://problem/6978804>
773 RefPtr<PluginView> protect(this);
777 PluginView::setCurrentPluginView(this);
778 JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
779 setCallingPlugin(true);
780 npErr = m_plugin->pluginFuncs()->getvalue(m_instance, NPPVpluginScriptableNPObject, &object);
781 setCallingPlugin(false);
782 PluginView::setCurrentPluginView(0);
786 // The renderer for the PluginView was destroyed during the above call, and
787 // the PluginView will be destroyed when this function returns, so we
792 if (npErr != NPERR_NO_ERROR || !object)
795 RefPtr<JSC::Bindings::RootObject> root = m_parentFrame->script()->createRootObject(this);
796 RefPtr<JSC::Bindings::Instance> instance = JSC::Bindings::CInstance::create(object, root.release());
798 _NPN_ReleaseObject(object);
800 return instance.release();
803 #endif // NETSCAPE_PLUGIN_API
809 // This is really JS engine independent
810 NPObject* PluginView::getNPObject() {
811 #if ENABLE(NETSCAPE_PLUGIN_API)
812 if (!m_plugin || !m_plugin->pluginFuncs()->getvalue)
815 NPObject* object = 0;
819 PluginView::setCurrentPluginView(this);
820 setCallingPlugin(true);
821 npErr = m_plugin->pluginFuncs()->getvalue(m_instance, NPPVpluginScriptableNPObject, &object);
822 setCallingPlugin(false);
823 PluginView::setCurrentPluginView(0);
826 if (npErr != NPERR_NO_ERROR || !object)
829 // Bindings::CInstance (used in JSC version) retains the object, so in ~PluginView() it calls
830 // cleanupScriptObjectsForPlugin() to releases the object. To maintain the reference count,
831 // don't call _NPN_ReleaseObject(object) here.
835 #endif // NETSCAPE_PLUGIN_API
840 >>>>>>> webkit.org at r60074
842 void PluginView::disconnectStream(PluginStream* stream)
844 ASSERT(m_streams.contains(stream));
846 m_streams.remove(stream);
849 void PluginView::setParameters(const Vector<String>& paramNames, const Vector<String>& paramValues)
851 ASSERT(paramNames.size() == paramValues.size());
853 unsigned size = paramNames.size();
854 unsigned paramCount = 0;
856 m_paramNames = reinterpret_cast<char**>(fastMalloc(sizeof(char*) * size));
857 m_paramValues = reinterpret_cast<char**>(fastMalloc(sizeof(char*) * size));
859 for (unsigned i = 0; i < size; i++) {
860 if (m_plugin->quirks().contains(PluginQuirkRemoveWindowlessVideoParam) && equalIgnoringCase(paramNames[i], "windowlessvideo"))
863 if (paramNames[i] == "pluginspage")
864 m_pluginsPage = paramValues[i];
866 m_paramNames[paramCount] = createUTF8String(paramNames[i]);
867 m_paramValues[paramCount] = createUTF8String(paramValues[i]);
872 m_paramCount = paramCount;
875 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)
876 : m_parentFrame(parentFrame)
881 , m_baseURL(m_parentFrame->loader()->completeURL(m_parentFrame->document()->baseURL().string()))
882 , m_status(PluginStatusLoadedSuccessfully)
883 , m_requestTimer(this, &PluginView::requestTimerFired)
884 , m_invalidateTimer(this, &PluginView::invalidateTimerFired)
885 , m_popPopupsStateTimer(this, &PluginView::popPopupsStateTimerFired)
886 , m_lifeSupportTimer(this, &PluginView::lifeSupportTimerFired)
887 , m_mode(loadManually ? NP_FULL : NP_EMBED)
890 , m_mimeType(mimeType)
891 #if defined(XP_MACOSX)
892 , m_isWindowed(false)
896 , m_isTransparent(false)
897 , m_haveInitialized(false)
898 , m_isWaitingToStart(false)
900 , m_needsXEmbed(false)
902 #if OS(WINDOWS) && ENABLE(NETSCAPE_PLUGIN_API)
905 , m_isCallingPluginWndProc(false)
907 , m_haveUpdatedPluginWidget(false)
909 #if (PLATFORM(QT) && OS(WINDOWS)) || defined(XP_MACOSX)
912 #if defined(XP_MACOSX)
913 , m_drawingModel(NPDrawingModel(-1))
914 , m_eventModel(NPEventModel(-1))
918 #if defined(XP_UNIX) && ENABLE(NETSCAPE_PLUGIN_API)
919 , m_hasPendingGeometryChange(true)
925 , m_loadManually(loadManually)
927 , m_isJavaScriptPaused(false)
929 , m_hasBeenHalted(false)
930 , m_haveCalledSetWindow(false)
932 #if defined(ANDROID_PLUGINS)
937 m_status = PluginStatusCanNotFindPlugin;
941 m_instance = &m_instanceStruct;
942 m_instance->ndata = this;
943 m_instance->pdata = 0;
945 instanceMap().add(m_instance, this);
947 setParameters(paramNames, paramValues);
949 memset(&m_npWindow, 0, sizeof(m_npWindow));
950 #if defined(XP_MACOSX)
951 memset(&m_npCgContext, 0, sizeof(m_npCgContext));
957 void PluginView::focusPluginElement()
960 if (Page* page = m_parentFrame->page())
961 page->focusController()->setFocusedFrame(m_parentFrame);
962 m_parentFrame->document()->setFocusedNode(m_element);
965 void PluginView::didReceiveResponse(const ResourceResponse& response)
967 if (m_status != PluginStatusLoadedSuccessfully)
970 ASSERT(m_loadManually);
971 ASSERT(!m_manualStream);
973 m_manualStream = PluginStream::create(this, m_parentFrame.get(), m_parentFrame->loader()->activeDocumentLoader()->request(), false, 0, plugin()->pluginFuncs(), instance(), m_plugin->quirks());
974 m_manualStream->setLoadManually(true);
976 m_manualStream->didReceiveResponse(0, response);
979 void PluginView::didReceiveData(const char* data, int length)
981 if (m_status != PluginStatusLoadedSuccessfully)
984 ASSERT(m_loadManually);
985 ASSERT(m_manualStream);
987 m_manualStream->didReceiveData(0, data, length);
990 void PluginView::didFinishLoading()
992 if (m_status != PluginStatusLoadedSuccessfully)
995 ASSERT(m_loadManually);
996 ASSERT(m_manualStream);
998 m_manualStream->didFinishLoading(0);
1001 void PluginView::didFail(const ResourceError& error)
1003 if (m_status != PluginStatusLoadedSuccessfully)
1006 ASSERT(m_loadManually);
1007 ASSERT(m_manualStream);
1009 m_manualStream->didFail(0, error);
1012 void PluginView::setCallingPlugin(bool b) const
1014 if (!m_plugin->quirks().contains(PluginQuirkHasModalMessageLoop))
1022 ASSERT(s_callingPlugin >= 0);
1025 bool PluginView::isCallingPlugin()
1027 return s_callingPlugin > 0;
1030 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)
1032 // if we fail to find a plugin for this MIME type, findPlugin will search for
1033 // a plugin by the file extension and update the MIME type, so pass a mutable String
1034 String mimeTypeCopy = mimeType;
1035 PluginPackage* plugin = PluginDatabase::installedPlugins()->findPlugin(url, mimeTypeCopy);
1037 // No plugin was found, try refreshing the database and searching again
1038 if (!plugin && PluginDatabase::installedPlugins()->refresh()) {
1039 mimeTypeCopy = mimeType;
1040 plugin = PluginDatabase::installedPlugins()->findPlugin(url, mimeTypeCopy);
1043 return adoptRef(new PluginView(parentFrame, size, plugin, element, url, paramNames, paramValues, mimeTypeCopy, loadManually));
1046 void PluginView::freeStringArray(char** stringArray, int length)
1051 for (int i = 0; i < length; i++)
1052 fastFree(stringArray[i]);
1054 fastFree(stringArray);
1057 static inline bool startsWithBlankLine(const Vector<char>& buffer)
1059 return buffer.size() > 0 && buffer[0] == '\n';
1062 static inline int locationAfterFirstBlankLine(const Vector<char>& buffer)
1064 const char* bytes = buffer.data();
1065 unsigned length = buffer.size();
1067 for (unsigned i = 0; i < length - 4; i++) {
1068 // Support for Acrobat. It sends "\n\n".
1069 if (bytes[i] == '\n' && bytes[i + 1] == '\n')
1072 // Returns the position after 2 CRLF's or 1 CRLF if it is the first line.
1073 if (bytes[i] == '\r' && bytes[i + 1] == '\n') {
1077 else if (bytes[i] == '\n')
1078 // Support for Director. It sends "\r\n\n" (3880387).
1080 else if (bytes[i] == '\r' && bytes[i + 1] == '\n')
1081 // Support for Flash. It sends "\r\n\r\n" (3758113).
1089 static inline const char* findEOL(const char* bytes, unsigned length)
1091 // According to the HTTP specification EOL is defined as
1092 // a CRLF pair. Unfortunately, some servers will use LF
1093 // instead. Worse yet, some servers will use a combination
1094 // of both (e.g. <header>CRLFLF<body>), so findEOL needs
1095 // to be more forgiving. It will now accept CRLF, LF or
1098 // It returns NULL if EOLF is not found or it will return
1099 // a pointer to the first terminating character.
1100 for (unsigned i = 0; i < length; i++) {
1101 if (bytes[i] == '\n')
1103 if (bytes[i] == '\r') {
1104 // Check to see if spanning buffer bounds
1105 // (CRLF is across reads). If so, wait for
1107 if (i + 1 == length)
1117 static inline String capitalizeRFC822HeaderFieldName(const String& name)
1119 bool capitalizeCharacter = true;
1122 for (unsigned i = 0; i < name.length(); i++) {
1125 if (capitalizeCharacter && name[i] >= 'a' && name[i] <= 'z')
1126 c = toASCIIUpper(name[i]);
1127 else if (!capitalizeCharacter && name[i] >= 'A' && name[i] <= 'Z')
1128 c = toASCIILower(name[i]);
1133 capitalizeCharacter = true;
1135 capitalizeCharacter = false;
1143 static inline HTTPHeaderMap parseRFC822HeaderFields(const Vector<char>& buffer, unsigned length)
1145 const char* bytes = buffer.data();
1148 HTTPHeaderMap headerFields;
1150 // Loop ove rlines until we're past the header, or we can't find any more end-of-lines
1151 while ((eol = findEOL(bytes, length))) {
1152 const char* line = bytes;
1153 int lineLength = eol - bytes;
1155 // Move bytes to the character after the terminator as returned by findEOL.
1157 if ((*eol == '\r') && (*bytes == '\n'))
1158 bytes++; // Safe since findEOL won't return a spanning CRLF.
1160 length -= (bytes - line);
1161 if (lineLength == 0)
1162 // Blank line; we're at the end of the header
1164 else if (*line == ' ' || *line == '\t') {
1165 // Continuation of the previous header
1166 if (lastKey.isNull()) {
1167 // malformed header; ignore it and continue
1170 // Merge the continuation of the previous header
1171 String currentValue = headerFields.get(lastKey);
1172 String newValue(line, lineLength);
1174 headerFields.set(lastKey, currentValue + newValue);
1179 for (colon = line; *colon != ':' && colon != eol; colon++) {
1183 // malformed header; ignore it and continue
1186 lastKey = capitalizeRFC822HeaderFieldName(String(line, colon - line));
1189 for (colon++; colon != eol; colon++) {
1190 if (*colon != ' ' && *colon != '\t')
1196 value = String(colon, eol - colon);
1198 String oldValue = headerFields.get(lastKey);
1199 if (!oldValue.isNull()) {
1200 String tmp = oldValue;
1206 headerFields.set(lastKey, value);
1211 return headerFields;
1214 NPError PluginView::handlePost(const char* url, const char* target, uint32_t len, const char* buf, bool file, void* notifyData, bool sendNotification, bool allowHeaders)
1216 if (!url || !len || !buf)
1217 return NPERR_INVALID_PARAM;
1219 FrameLoadRequest frameLoadRequest;
1221 HTTPHeaderMap headerFields;
1222 Vector<char> buffer;
1225 NPError readResult = handlePostReadFile(buffer, len, buf);
1226 if(readResult != NPERR_NO_ERROR)
1230 memcpy(buffer.data(), buf, len);
1233 const char* postData = buffer.data();
1234 int postDataLength = buffer.size();
1237 if (startsWithBlankLine(buffer)) {
1241 int location = locationAfterFirstBlankLine(buffer);
1242 if (location != -1) {
1243 // If the blank line is somewhere in the middle of the buffer, everything before is the header
1244 headerFields = parseRFC822HeaderFields(buffer, location);
1245 unsigned dataLength = buffer.size() - location;
1247 // Sometimes plugins like to set Content-Length themselves when they post,
1248 // but WebFoundation does not like that. So we will remove the header
1249 // and instead truncate the data to the requested length.
1250 String contentLength = headerFields.get("Content-Length");
1252 if (!contentLength.isNull())
1253 dataLength = min(contentLength.toInt(), (int)dataLength);
1254 headerFields.remove("Content-Length");
1256 postData += location;
1257 postDataLength = dataLength;
1262 frameLoadRequest.resourceRequest().setHTTPMethod("POST");
1263 frameLoadRequest.resourceRequest().setURL(makeURL(m_baseURL, url));
1264 frameLoadRequest.resourceRequest().addHTTPHeaderFields(headerFields);
1265 frameLoadRequest.resourceRequest().setHTTPBody(FormData::create(postData, postDataLength));
1266 frameLoadRequest.setFrameName(target);
1268 return load(frameLoadRequest, sendNotification, notifyData);
1271 #ifdef PLUGIN_SCHEDULE_TIMER
1272 uint32_t PluginView::scheduleTimer(NPP instance, uint32_t interval, bool repeat,
1273 void (*timerFunc)(NPP, uint32_t timerID))
1275 return m_timerList.schedule(instance, interval, repeat, timerFunc);
1278 void PluginView::unscheduleTimer(NPP instance, uint32_t timerID)
1280 m_timerList.unschedule(instance, timerID);
1284 void PluginView::invalidateWindowlessPluginRect(const IntRect& rect)
1289 if (!m_element->renderer())
1291 RenderBox* renderer = toRenderBox(m_element->renderer());
1293 IntRect dirtyRect = rect;
1294 dirtyRect.move(renderer->borderLeft() + renderer->paddingLeft(), renderer->borderTop() + renderer->paddingTop());
1295 renderer->repaintRectangle(dirtyRect);
1298 void PluginView::paintMissingPluginIcon(GraphicsContext* context, const IntRect& rect)
1300 static RefPtr<Image> nullPluginImage;
1301 if (!nullPluginImage)
1302 nullPluginImage = Image::loadPlatformResource("nullPlugin");
1304 IntRect imageRect(frameRect().x(), frameRect().y(), nullPluginImage->width(), nullPluginImage->height());
1306 int xOffset = (frameRect().width() - imageRect.width()) / 2;
1307 int yOffset = (frameRect().height() - imageRect.height()) / 2;
1309 imageRect.move(xOffset, yOffset);
1311 if (!rect.intersects(imageRect))
1315 context->clip(windowClipRect());
1316 context->drawImage(nullPluginImage.get(), DeviceColorSpace, imageRect.location());
1320 static const char* MozillaUserAgent = "Mozilla/5.0 ("
1321 #if defined(XP_MACOSX)
1322 "Macintosh; U; Intel Mac OS X;"
1323 #elif defined(XP_WIN)
1324 "Windows; U; Windows NT 5.1;"
1325 #elif defined(XP_UNIX)
1326 // The Gtk port uses X11 plugins in Mac.
1327 #if OS(DARWIN) && PLATFORM(GTK)
1328 "X11; U; Intel Mac OS X;"
1330 "X11; U; Linux i686;"
1333 " en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0";
1335 const char* PluginView::userAgent()
1337 #if !PLATFORM(ANDROID)
1338 if (m_plugin->quirks().contains(PluginQuirkWantsMozillaUserAgent))
1339 return MozillaUserAgent;
1342 if (m_userAgent.isNull())
1343 m_userAgent = m_parentFrame->loader()->userAgent(m_url).utf8();
1345 return m_userAgent.data();
1348 #if ENABLE(NETSCAPE_PLUGIN_API)
1349 const char* PluginView::userAgentStatic()
1351 return MozillaUserAgent;
1356 Node* PluginView::node() const
1361 String PluginView::pluginName() const
1363 return m_plugin->name();
1366 void PluginView::lifeSupportTimerFired(Timer<PluginView>*)
1371 void PluginView::keepAlive()
1373 if (m_lifeSupportTimer.isActive())
1377 m_lifeSupportTimer.startOneShot(0);
1380 #if ENABLE(NETSCAPE_PLUGIN_API)
1381 void PluginView::keepAlive(NPP instance)
1383 PluginView* view = instanceMap().get(instance);
1390 NPError PluginView::getValueStatic(NPNVariable variable, void* value)
1392 LOG(Plugins, "PluginView::getValueStatic(%s)", prettyNameForNPNVariable(variable).data());
1395 if (platformGetValueStatic(variable, value, &result))
1398 return NPERR_GENERIC_ERROR;
1401 NPError PluginView::getValue(NPNVariable variable, void* value)
1403 LOG(Plugins, "PluginView::getValue(%s)", prettyNameForNPNVariable(variable).data());
1406 if (platformGetValue(variable, value, &result))
1409 if (platformGetValueStatic(variable, value, &result))
1413 case NPNVWindowNPObject: {
1414 if (m_isJavaScriptPaused)
1415 return NPERR_GENERIC_ERROR;
1417 NPObject* windowScriptObject = m_parentFrame->script()->windowScriptNPObject();
1419 // Return value is expected to be retained, as described here: <http://www.mozilla.org/projects/plugin/npruntime.html>
1420 if (windowScriptObject)
1421 _NPN_RetainObject(windowScriptObject);
1423 void** v = (void**)value;
1424 *v = windowScriptObject;
1426 return NPERR_NO_ERROR;
1429 case NPNVPluginElementNPObject: {
1430 if (m_isJavaScriptPaused)
1431 return NPERR_GENERIC_ERROR;
1433 NPObject* pluginScriptObject = 0;
1435 if (m_element->hasTagName(appletTag) || m_element->hasTagName(embedTag) || m_element->hasTagName(objectTag))
1436 pluginScriptObject = static_cast<HTMLPlugInElement*>(m_element)->getNPObject();
1438 // Return value is expected to be retained, as described here: <http://www.mozilla.org/projects/plugin/npruntime.html>
1439 if (pluginScriptObject)
1440 _NPN_RetainObject(pluginScriptObject);
1442 void** v = (void**)value;
1443 *v = pluginScriptObject;
1445 return NPERR_NO_ERROR;
1448 case NPNVprivateModeBool: {
1449 Page* page = m_parentFrame->page();
1451 return NPERR_GENERIC_ERROR;
1452 *((NPBool*)value) = !page->settings() || page->settings()->privateBrowsingEnabled();
1453 return NPERR_NO_ERROR;
1457 return NPERR_GENERIC_ERROR;
1462 void PluginView::privateBrowsingStateChanged(bool privateBrowsingEnabled)
1464 NPP_SetValueProcPtr setValue = m_plugin->pluginFuncs()->setvalue;
1468 PluginView::setCurrentPluginView(this);
1470 // Upstream to webkit.org
1472 JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly);
1474 setCallingPlugin(true);
1475 NPBool value = privateBrowsingEnabled;
1476 setValue(m_instance, NPNVprivateModeBool, &value);
1477 setCallingPlugin(false);
1478 PluginView::setCurrentPluginView(0);
1481 } // namespace WebCore