diff options
author | Lorry Tar Creator <lorry-tar-importer@lorry> | 2017-06-27 06:07:23 +0000 |
---|---|---|
committer | Lorry Tar Creator <lorry-tar-importer@lorry> | 2017-06-27 06:07:23 +0000 |
commit | 1bf1084f2b10c3b47fd1a588d85d21ed0eb41d0c (patch) | |
tree | 46dcd36c86e7fbc6e5df36deb463b33e9967a6f7 /Source/WebCore/plugins | |
parent | 32761a6cee1d0dee366b885b7b9c777e67885688 (diff) | |
download | WebKitGtk-tarball-master.tar.gz |
webkitgtk-2.16.5HEADwebkitgtk-2.16.5master
Diffstat (limited to 'Source/WebCore/plugins')
44 files changed, 493 insertions, 9360 deletions
diff --git a/Source/WebCore/plugins/DOMMimeType.cpp b/Source/WebCore/plugins/DOMMimeType.cpp index 3e1ef9af5..3b2901689 100644 --- a/Source/WebCore/plugins/DOMMimeType.cpp +++ b/Source/WebCore/plugins/DOMMimeType.cpp @@ -21,35 +21,37 @@ #include "DOMPlugin.h" #include "FrameLoader.h" -#include "FrameLoaderClient.h" #include "MainFrame.h" #include "Page.h" #include "PluginData.h" -#include "Settings.h" #include "SubframeLoader.h" #include <wtf/text/StringBuilder.h> namespace WebCore { -DOMMimeType::DOMMimeType(PassRefPtr<PluginData> pluginData, Frame* frame, unsigned index) +DOMMimeType::DOMMimeType(RefPtr<PluginData>&& pluginData, Frame* frame, unsigned index) : FrameDestructionObserver(frame) - , m_pluginData(pluginData) - , m_index(index) + , m_pluginData(WTFMove(pluginData)) { + Vector<MimeClassInfo> mimes; + Vector<size_t> mimePluginIndices; + m_pluginData->getWebVisibleMimesAndPluginIndices(mimes, mimePluginIndices); + m_mimeClassInfo = mimes[index]; + m_pluginInfo = m_pluginData->webVisiblePlugins()[mimePluginIndices[index]]; } DOMMimeType::~DOMMimeType() { } -const String &DOMMimeType::type() const +String DOMMimeType::type() const { - return mimeClassInfo().type; + return m_mimeClassInfo.type; } String DOMMimeType::suffixes() const { - const Vector<String>& extensions = mimeClassInfo().extensions; + const Vector<String>& extensions = m_mimeClassInfo.extensions; StringBuilder builder; for (size_t i = 0; i < extensions.size(); ++i) { @@ -60,17 +62,20 @@ String DOMMimeType::suffixes() const return builder.toString(); } -const String &DOMMimeType::description() const +String DOMMimeType::description() const { - return mimeClassInfo().desc; + return m_mimeClassInfo.desc; } -PassRefPtr<DOMPlugin> DOMMimeType::enabledPlugin() const +RefPtr<DOMPlugin> DOMMimeType::enabledPlugin() const { - if (!m_frame || !m_frame->page() || !m_frame->page()->mainFrame().loader().subframeLoader().allowPlugins(NotAboutToInstantiatePlugin)) - return 0; + if (!m_frame || !m_frame->page() || !m_frame->page()->mainFrame().loader().subframeLoader().allowPlugins()) + return nullptr; - return DOMPlugin::create(m_pluginData.get(), m_frame, m_pluginData->mimePluginIndices()[m_index]); + Vector<MimeClassInfo> mimes; + Vector<size_t> mimePluginIndices; + m_pluginData->getWebVisibleMimesAndPluginIndices(mimes, mimePluginIndices); + return DOMPlugin::create(m_pluginData.get(), m_frame, m_pluginInfo); } } // namespace WebCore diff --git a/Source/WebCore/plugins/DOMMimeType.h b/Source/WebCore/plugins/DOMMimeType.h index d3cf0a5cb..d5e15eb66 100644 --- a/Source/WebCore/plugins/DOMMimeType.h +++ b/Source/WebCore/plugins/DOMMimeType.h @@ -17,14 +17,10 @@ Boston, MA 02110-1301, USA. */ -#ifndef DOMMimeType_h -#define DOMMimeType_h +#pragma once #include "FrameDestructionObserver.h" #include "PluginData.h" - -#include <wtf/Forward.h> -#include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> #include <wtf/RefPtr.h> @@ -34,22 +30,19 @@ class DOMPlugin; class DOMMimeType : public RefCounted<DOMMimeType>, public FrameDestructionObserver { public: - static PassRefPtr<DOMMimeType> create(PassRefPtr<PluginData> pluginData, Frame* frame, unsigned index) { return adoptRef(new DOMMimeType(pluginData, frame, index)); } + static Ref<DOMMimeType> create(RefPtr<PluginData>&& pluginData, Frame* frame, unsigned index) { return adoptRef(*new DOMMimeType(WTFMove(pluginData), frame, index)); } ~DOMMimeType(); - const String &type() const; + String type() const; String suffixes() const; - const String &description() const; - PassRefPtr<DOMPlugin> enabledPlugin() const; + String description() const; + RefPtr<DOMPlugin> enabledPlugin() const; private: - const MimeClassInfo& mimeClassInfo() const { return m_pluginData->mimes()[m_index]; } - - DOMMimeType(PassRefPtr<PluginData>, Frame*, unsigned index); + DOMMimeType(RefPtr<PluginData>&&, Frame*, unsigned index); + MimeClassInfo m_mimeClassInfo; RefPtr<PluginData> m_pluginData; - unsigned m_index; + PluginInfo m_pluginInfo; }; -} - -#endif +} // namespace WebCore diff --git a/Source/WebCore/plugins/DOMMimeTypeArray.cpp b/Source/WebCore/plugins/DOMMimeTypeArray.cpp index d64382566..1e316afcb 100644 --- a/Source/WebCore/plugins/DOMMimeTypeArray.cpp +++ b/Source/WebCore/plugins/DOMMimeTypeArray.cpp @@ -26,6 +26,12 @@ #include "PluginData.h" #include <wtf/text/AtomicString.h> +#if ENABLE(WEB_REPLAY) +#include "Document.h" +#include "WebReplayInputs.h" +#include <replay/InputCursor.h> +#endif + namespace WebCore { DOMMimeTypeArray::DOMMimeTypeArray(Frame* frame) @@ -42,54 +48,75 @@ unsigned DOMMimeTypeArray::length() const PluginData* data = getPluginData(); if (!data) return 0; - return data->mimes().size(); + + Vector<MimeClassInfo> mimes; + Vector<size_t> mimePluginIndices; + data->getWebVisibleMimesAndPluginIndices(mimes, mimePluginIndices); + return mimes.size(); } -PassRefPtr<DOMMimeType> DOMMimeTypeArray::item(unsigned index) +RefPtr<DOMMimeType> DOMMimeTypeArray::item(unsigned index) { PluginData* data = getPluginData(); if (!data) - return 0; - const Vector<MimeClassInfo>& mimes = data->mimes(); + return nullptr; + + Vector<MimeClassInfo> mimes; + Vector<size_t> mimePluginIndices; + data->getWebVisibleMimesAndPluginIndices(mimes, mimePluginIndices); + if (index >= mimes.size()) - return 0; - return DOMMimeType::create(data, m_frame, index).get(); + return nullptr; + return DOMMimeType::create(data, m_frame, index); } -bool DOMMimeTypeArray::canGetItemsForName(const AtomicString& propertyName) +RefPtr<DOMMimeType> DOMMimeTypeArray::namedItem(const AtomicString& propertyName) { - PluginData *data = getPluginData(); + PluginData* data = getPluginData(); if (!data) - return 0; - const Vector<MimeClassInfo>& mimes = data->mimes(); + return nullptr; + + Vector<MimeClassInfo> mimes; + Vector<size_t> mimePluginIndices; + data->getWebVisibleMimesAndPluginIndices(mimes, mimePluginIndices); for (unsigned i = 0; i < mimes.size(); ++i) { if (mimes[i].type == propertyName) - return true; + return DOMMimeType::create(data, m_frame, i); } - return false; + return nullptr; } -PassRefPtr<DOMMimeType> DOMMimeTypeArray::namedItem(const AtomicString& propertyName) +Vector<AtomicString> DOMMimeTypeArray::supportedPropertyNames() { - PluginData *data = getPluginData(); - if (!data) - return 0; - const Vector<MimeClassInfo>& mimes = data->mimes(); - for (unsigned i = 0; i < mimes.size(); ++i) { - if (mimes[i].type == propertyName) - return DOMMimeType::create(data, m_frame, i).get(); - } - return 0; + // FIXME: Should be implemented. + return Vector<AtomicString>(); } PluginData* DOMMimeTypeArray::getPluginData() const { if (!m_frame) - return 0; + return nullptr; + Page* page = m_frame->page(); if (!page) - return 0; - return &page->pluginData(); + return nullptr; + + PluginData* pluginData = &page->pluginData(); + +#if ENABLE(WEB_REPLAY) + if (!m_frame->document()) + return pluginData; + + InputCursor& cursor = m_frame->document()->inputCursor(); + if (cursor.isCapturing()) + cursor.appendInput<FetchPluginData>(pluginData); + else if (cursor.isReplaying()) { + if (FetchPluginData* input = cursor.fetchInput<FetchPluginData>()) + pluginData = input->pluginData().get(); + } +#endif + + return pluginData; } } // namespace WebCore diff --git a/Source/WebCore/plugins/DOMMimeTypeArray.h b/Source/WebCore/plugins/DOMMimeTypeArray.h index 58161df20..6a374b0a2 100644 --- a/Source/WebCore/plugins/DOMMimeTypeArray.h +++ b/Source/WebCore/plugins/DOMMimeTypeArray.h @@ -18,16 +18,12 @@ Boston, MA 02110-1301, USA. */ -#ifndef DOMMimeTypeArray_h -#define DOMMimeTypeArray_h +#pragma once #include "DOMMimeType.h" #include "DOMWindowProperty.h" #include "ScriptWrappable.h" -#include <wtf/Forward.h> -#include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> -#include <wtf/Vector.h> namespace WebCore { @@ -36,13 +32,13 @@ class PluginData; class DOMMimeTypeArray : public ScriptWrappable, public RefCounted<DOMMimeTypeArray>, public DOMWindowProperty { public: - static PassRefPtr<DOMMimeTypeArray> create(Frame* frame) { return adoptRef(new DOMMimeTypeArray(frame)); } + static Ref<DOMMimeTypeArray> create(Frame* frame) { return adoptRef(*new DOMMimeTypeArray(frame)); } ~DOMMimeTypeArray(); unsigned length() const; - PassRefPtr<DOMMimeType> item(unsigned index); - bool canGetItemsForName(const AtomicString& propertyName); - PassRefPtr<DOMMimeType> namedItem(const AtomicString& propertyName); + RefPtr<DOMMimeType> item(unsigned index); + RefPtr<DOMMimeType> namedItem(const AtomicString& propertyName); + Vector<AtomicString> supportedPropertyNames(); private: explicit DOMMimeTypeArray(Frame*); @@ -50,5 +46,3 @@ private: }; } // namespace WebCore - -#endif // MimeTypeArray_h diff --git a/Source/WebCore/plugins/DOMMimeTypeArray.idl b/Source/WebCore/plugins/DOMMimeTypeArray.idl index cdce50a3d..e5efc5686 100644 --- a/Source/WebCore/plugins/DOMMimeTypeArray.idl +++ b/Source/WebCore/plugins/DOMMimeTypeArray.idl @@ -20,10 +20,10 @@ [ GenerateIsReachable=ImplFrame, + LegacyUnenumerableNamedProperties, InterfaceName=MimeTypeArray, ] interface DOMMimeTypeArray { readonly attribute unsigned long length; - getter DOMMimeType item([Default=Undefined] optional unsigned long index); - getter DOMMimeType namedItem([Default=Undefined] optional DOMString name); + getter DOMMimeType? item(unsigned long index); + getter DOMMimeType? namedItem(DOMString name); }; - diff --git a/Source/WebCore/plugins/DOMPlugin.cpp b/Source/WebCore/plugins/DOMPlugin.cpp index ef5ab4cd7..ef73c2838 100644 --- a/Source/WebCore/plugins/DOMPlugin.cpp +++ b/Source/WebCore/plugins/DOMPlugin.cpp @@ -25,10 +25,10 @@ namespace WebCore { -DOMPlugin::DOMPlugin(PluginData* pluginData, Frame* frame, unsigned index) +DOMPlugin::DOMPlugin(PluginData* pluginData, Frame* frame, PluginInfo pluginInfo) : FrameDestructionObserver(frame) , m_pluginData(pluginData) - , m_index(index) + , m_pluginInfo(WTFMove(pluginInfo)) { } @@ -38,55 +38,60 @@ DOMPlugin::~DOMPlugin() String DOMPlugin::name() const { - return pluginInfo().name; + return m_pluginInfo.name; } String DOMPlugin::filename() const { - return pluginInfo().file; + return m_pluginInfo.file; } String DOMPlugin::description() const { - return pluginInfo().desc; + return m_pluginInfo.desc; } unsigned DOMPlugin::length() const { - return pluginInfo().mimes.size(); + return m_pluginInfo.mimes.size(); } -PassRefPtr<DOMMimeType> DOMPlugin::item(unsigned index) +RefPtr<DOMMimeType> DOMPlugin::item(unsigned index) { - if (index >= pluginInfo().mimes.size()) - return 0; + if (index >= m_pluginInfo.mimes.size() || !m_frame || !m_frame->page()) + return nullptr; - const MimeClassInfo& mime = pluginInfo().mimes[index]; + MimeClassInfo mime = m_pluginInfo.mimes[index]; - const Vector<MimeClassInfo>& mimes = m_pluginData->mimes(); + Vector<MimeClassInfo> mimes; + Vector<size_t> mimePluginIndices; + Vector<PluginInfo> plugins = m_pluginData->webVisiblePlugins(); + m_pluginData->getWebVisibleMimesAndPluginIndices(mimes, mimePluginIndices); for (unsigned i = 0; i < mimes.size(); ++i) { - if (mimes[i] == mime && m_pluginData->mimePluginIndices()[i] == m_index) - return DOMMimeType::create(m_pluginData.get(), m_frame, i).get(); + if (mimes[i] == mime && plugins[mimePluginIndices[i]] == m_pluginInfo) + return DOMMimeType::create(m_pluginData.get(), m_frame, i); } - return 0; + return nullptr; } -bool DOMPlugin::canGetItemsForName(const AtomicString& propertyName) +RefPtr<DOMMimeType> DOMPlugin::namedItem(const AtomicString& propertyName) { - const Vector<MimeClassInfo>& mimes = m_pluginData->mimes(); + if (!m_frame || !m_frame->page()) + return nullptr; + + Vector<MimeClassInfo> mimes; + Vector<size_t> mimePluginIndices; + m_pluginData->getWebVisibleMimesAndPluginIndices(mimes, mimePluginIndices); for (unsigned i = 0; i < mimes.size(); ++i) if (mimes[i].type == propertyName) - return true; - return false; + return DOMMimeType::create(m_pluginData.get(), m_frame, i); + return nullptr; } -PassRefPtr<DOMMimeType> DOMPlugin::namedItem(const AtomicString& propertyName) +Vector<AtomicString> DOMPlugin::supportedPropertyNames() { - const Vector<MimeClassInfo>& mimes = m_pluginData->mimes(); - for (unsigned i = 0; i < mimes.size(); ++i) - if (mimes[i].type == propertyName) - return DOMMimeType::create(m_pluginData.get(), m_frame, i).get(); - return 0; + // FIXME: Should be implemented. + return Vector<AtomicString>(); } } // namespace WebCore diff --git a/Source/WebCore/plugins/DOMPlugin.h b/Source/WebCore/plugins/DOMPlugin.h index 908b94f91..91124eea1 100644 --- a/Source/WebCore/plugins/DOMPlugin.h +++ b/Source/WebCore/plugins/DOMPlugin.h @@ -17,15 +17,13 @@ Boston, MA 02110-1301, USA. */ -#ifndef DOMPlugin_h -#define DOMPlugin_h +#pragma once #include "FrameDestructionObserver.h" #include "DOMMimeType.h" #include "ScriptWrappable.h" -#include <wtf/Forward.h> -#include <wtf/RefPtr.h> #include <wtf/RefCounted.h> +#include <wtf/RefPtr.h> namespace WebCore { @@ -34,7 +32,7 @@ class PluginData; class DOMPlugin : public ScriptWrappable, public RefCounted<DOMPlugin>, public FrameDestructionObserver { public: - static PassRefPtr<DOMPlugin> create(PluginData* pluginData, Frame* frame, unsigned index) { return adoptRef(new DOMPlugin(pluginData, frame, index)); } + static Ref<DOMPlugin> create(PluginData* pluginData, Frame* frame, PluginInfo pluginInfo) { return adoptRef(*new DOMPlugin(pluginData, frame, WTFMove(pluginInfo))); } ~DOMPlugin(); String name() const; @@ -43,18 +41,14 @@ public: unsigned length() const; - PassRefPtr<DOMMimeType> item(unsigned index); - bool canGetItemsForName(const AtomicString& propertyName); - PassRefPtr<DOMMimeType> namedItem(const AtomicString& propertyName); + RefPtr<DOMMimeType> item(unsigned index); + RefPtr<DOMMimeType> namedItem(const AtomicString& propertyName); + Vector<AtomicString> supportedPropertyNames(); private: - const PluginInfo& pluginInfo() const { return m_pluginData->plugins()[m_index]; } - - DOMPlugin(PluginData*, Frame*, unsigned index); + DOMPlugin(PluginData*, Frame*, PluginInfo); RefPtr<PluginData> m_pluginData; - unsigned m_index; + PluginInfo m_pluginInfo; }; } // namespace WebCore - -#endif // Plugin_h diff --git a/Source/WebCore/plugins/DOMPlugin.idl b/Source/WebCore/plugins/DOMPlugin.idl index a1b624091..0f5a0b2a3 100644 --- a/Source/WebCore/plugins/DOMPlugin.idl +++ b/Source/WebCore/plugins/DOMPlugin.idl @@ -20,12 +20,13 @@ [ InterfaceName=Plugin, + LegacyUnenumerableNamedProperties ] interface DOMPlugin { readonly attribute DOMString name; readonly attribute DOMString filename; readonly attribute DOMString description; readonly attribute unsigned long length; - getter DOMMimeType item([Default=Undefined] optional unsigned long index); - getter DOMMimeType namedItem([Default=Undefined] optional DOMString name); + getter DOMMimeType? item(unsigned long index); + getter DOMMimeType? namedItem(DOMString name); }; diff --git a/Source/WebCore/plugins/DOMPluginArray.cpp b/Source/WebCore/plugins/DOMPluginArray.cpp index cca94b281..c1e4e6fa9 100644 --- a/Source/WebCore/plugins/DOMPluginArray.cpp +++ b/Source/WebCore/plugins/DOMPluginArray.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) - * Copyright (C) 2008 Apple Inc. All rights reserved. + * Copyright (C) 2008, 2015 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -26,6 +26,12 @@ #include "PluginData.h" #include <wtf/text/AtomicString.h> +#if ENABLE(WEB_REPLAY) +#include "Document.h" +#include "WebReplayInputs.h" +#include <replay/InputCursor.h> +#endif + namespace WebCore { DOMPluginArray::DOMPluginArray(Frame* frame) @@ -42,59 +48,77 @@ unsigned DOMPluginArray::length() const PluginData* data = pluginData(); if (!data) return 0; - return data->plugins().size(); + + return data->publiclyVisiblePlugins().size(); } -PassRefPtr<DOMPlugin> DOMPluginArray::item(unsigned index) +RefPtr<DOMPlugin> DOMPluginArray::item(unsigned index) { PluginData* data = pluginData(); if (!data) - return 0; - const Vector<PluginInfo>& plugins = data->plugins(); + return nullptr; + + const Vector<PluginInfo>& plugins = data->publiclyVisiblePlugins(); if (index >= plugins.size()) - return 0; - return DOMPlugin::create(data, m_frame, index).get(); + return nullptr; + return DOMPlugin::create(data, m_frame, plugins[index]); } -bool DOMPluginArray::canGetItemsForName(const AtomicString& propertyName) +RefPtr<DOMPlugin> DOMPluginArray::namedItem(const AtomicString& propertyName) { PluginData* data = pluginData(); if (!data) - return 0; - const Vector<PluginInfo>& plugins = data->plugins(); - for (unsigned i = 0; i < plugins.size(); ++i) { - if (plugins[i].name == propertyName) - return true; + return nullptr; + + for (auto& plugin : data->webVisiblePlugins()) { + if (plugin.name == propertyName) + return DOMPlugin::create(data, m_frame, plugin); } - return false; + return nullptr; } -PassRefPtr<DOMPlugin> DOMPluginArray::namedItem(const AtomicString& propertyName) +Vector<AtomicString> DOMPluginArray::supportedPropertyNames() { - PluginData* data = pluginData(); - if (!data) - return 0; - const Vector<PluginInfo>& plugins = data->plugins(); - for (unsigned i = 0; i < plugins.size(); ++i) { - if (plugins[i].name == propertyName) - return DOMPlugin::create(data, m_frame, i).get(); - } - return 0; + // FIXME: Should be implemented. + return Vector<AtomicString>(); } -void DOMPluginArray::refresh(bool reload) +void DOMPluginArray::refresh(bool reloadPages) { - Page::refreshPlugins(reload); + if (!m_frame) + return; + + if (!m_frame->page()) + return; + + Page::refreshPlugins(reloadPages); } PluginData* DOMPluginArray::pluginData() const { if (!m_frame) - return 0; + return nullptr; + Page* page = m_frame->page(); if (!page) - return 0; - return &page->pluginData(); + return nullptr; + + PluginData* pluginData = &page->pluginData(); + +#if ENABLE(WEB_REPLAY) + if (!m_frame->document()) + return pluginData; + + InputCursor& cursor = m_frame->document()->inputCursor(); + if (cursor.isCapturing()) + cursor.appendInput<FetchPluginData>(pluginData); + else if (cursor.isReplaying()) { + if (FetchPluginData* input = cursor.fetchInput<FetchPluginData>()) + pluginData = input->pluginData().get(); + } +#endif + + return pluginData; } } // namespace WebCore diff --git a/Source/WebCore/plugins/DOMPluginArray.h b/Source/WebCore/plugins/DOMPluginArray.h index 447c3cfb1..9b803fdea 100644 --- a/Source/WebCore/plugins/DOMPluginArray.h +++ b/Source/WebCore/plugins/DOMPluginArray.h @@ -18,16 +18,12 @@ Boston, MA 02110-1301, USA. */ -#ifndef DOMPluginArray_h -#define DOMPluginArray_h +#pragma once #include "DOMPlugin.h" #include "DOMWindowProperty.h" #include "ScriptWrappable.h" -#include <wtf/Forward.h> -#include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> -#include <wtf/Vector.h> namespace WebCore { @@ -36,15 +32,15 @@ class PluginData; class DOMPluginArray : public ScriptWrappable, public RefCounted<DOMPluginArray>, public DOMWindowProperty { public: - static PassRefPtr<DOMPluginArray> create(Frame* frame) { return adoptRef(new DOMPluginArray(frame)); } + static Ref<DOMPluginArray> create(Frame* frame) { return adoptRef(*new DOMPluginArray(frame)); } ~DOMPluginArray(); unsigned length() const; - PassRefPtr<DOMPlugin> item(unsigned index); - bool canGetItemsForName(const AtomicString& propertyName); - PassRefPtr<DOMPlugin> namedItem(const AtomicString& propertyName); + RefPtr<DOMPlugin> item(unsigned index); + RefPtr<DOMPlugin> namedItem(const AtomicString& propertyName); + Vector<AtomicString> supportedPropertyNames(); - void refresh(bool reload); + void refresh(bool reloadPages); private: explicit DOMPluginArray(Frame*); @@ -52,5 +48,3 @@ private: }; } // namespace WebCore - -#endif // PluginArray_h diff --git a/Source/WebCore/plugins/DOMPluginArray.idl b/Source/WebCore/plugins/DOMPluginArray.idl index 85d05223c..6946ff515 100644 --- a/Source/WebCore/plugins/DOMPluginArray.idl +++ b/Source/WebCore/plugins/DOMPluginArray.idl @@ -20,11 +20,13 @@ [ GenerateIsReachable=ImplFrame, + LegacyUnenumerableNamedProperties, InterfaceName=PluginArray, ] interface DOMPluginArray { readonly attribute unsigned long length; - getter DOMPlugin item([Default=Undefined] optional unsigned long index); - getter DOMPlugin namedItem([Default=Undefined] optional DOMString name); - void refresh([Default=Undefined] optional boolean reload); + getter DOMPlugin? item(unsigned long index); + getter DOMPlugin? namedItem(DOMString name); + + void refresh(optional boolean reload = false); }; diff --git a/Source/WebCore/plugins/PluginData.cpp b/Source/WebCore/plugins/PluginData.cpp index 6dd4eaadb..26e498c23 100644 --- a/Source/WebCore/plugins/PluginData.cpp +++ b/Source/WebCore/plugins/PluginData.cpp @@ -2,7 +2,7 @@ Copyright (C) 2000 Harri Porten (porten@kde.org) Copyright (C) 2000 Daniel Molkentin (molkentin@kde.org) Copyright (C) 2000 Stefan Schimanski (schimmi@kde.org) - Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All Rights Reserved. + Copyright (C) 2003, 2004, 2005, 2006, 2007, 2015 Apple Inc. All Rights Reserved. Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) This library is free software; you can redistribute it and/or @@ -24,69 +24,157 @@ #include "config.h" #include "PluginData.h" -#include "PlatformStrategies.h" -#include "PluginStrategy.h" +#include "LocalizedStrings.h" +#include "Page.h" +#include "PluginInfoProvider.h" namespace WebCore { -PluginData::PluginData(const Page* page) +PluginData::PluginData(Page& page) + : m_page(page) { - initPlugins(page); + initPlugins(); +} + +Vector<PluginInfo> PluginData::webVisiblePlugins() const +{ + Vector<PluginInfo> plugins; + m_page.pluginInfoProvider().getWebVisiblePluginInfo(m_page, plugins); + return plugins; +} + +#if PLATFORM(COCOA) +static inline bool isBuiltInPDFPlugIn(const PluginInfo& plugIn) +{ + return plugIn.name == builtInPDFPluginName(); +} +#else +static inline bool isBuiltInPDFPlugIn(const PluginInfo&) +{ + return false; +} +#endif + +static bool shouldBePubliclyVisible(const PluginInfo& plugin) +{ + // We can greatly reduce fingerprinting opportunities by only advertising plug-ins + // that are widely needed for general website compatibility. Since many users + // will have these plug-ins, we are not revealing much user-specific information. + // + // Web compatibility data indicate that Flash, QuickTime, Java, and PDF support + // are frequently accessed through the bad practice of iterating over the contents + // of the navigator.plugins list. Luckily, these plug-ins happen to be the least + // user-specific. + return plugin.name.containsIgnoringASCIICase("Shockwave") + || plugin.name.containsIgnoringASCIICase("QuickTime") + || plugin.name.containsIgnoringASCIICase("Java") + || isBuiltInPDFPlugIn(plugin); +} + +Vector<PluginInfo> PluginData::publiclyVisiblePlugins() const +{ + if (m_page.showAllPlugins()) + return webVisiblePlugins(); + + Vector<PluginInfo> allPlugins; + m_page.pluginInfoProvider().getWebVisiblePluginInfo(m_page, allPlugins); + + Vector<PluginInfo> plugins; + for (auto&& plugin : allPlugins) { + if (shouldBePubliclyVisible(plugin)) + plugins.append(WTFMove(plugin)); + } + + std::sort(plugins.begin(), plugins.end(), [](const PluginInfo& a, const PluginInfo& b) { + return codePointCompareLessThan(a.name, b.name); + }); + return plugins; +} + +void PluginData::getWebVisibleMimesAndPluginIndices(Vector<MimeClassInfo>& mimes, Vector<size_t>& mimePluginIndices) const +{ + getMimesAndPluginIndiciesForPlugins(webVisiblePlugins(), mimes, mimePluginIndices); +} - for (unsigned i = 0; i < m_plugins.size(); ++i) { - const PluginInfo& plugin = m_plugins[i]; - for (unsigned j = 0; j < plugin.mimes.size(); ++j) { - m_mimes.append(plugin.mimes[j]); - m_mimePluginIndices.append(i); +void PluginData::getMimesAndPluginIndices(Vector<MimeClassInfo>& mimes, Vector<size_t>& mimePluginIndices) const +{ + getMimesAndPluginIndiciesForPlugins(plugins(), mimes, mimePluginIndices); +} + +void PluginData::getMimesAndPluginIndiciesForPlugins(const Vector<PluginInfo>& plugins, Vector<MimeClassInfo>& mimes, Vector<size_t>& mimePluginIndices) const +{ + ASSERT_ARG(mimes, mimes.isEmpty()); + ASSERT_ARG(mimePluginIndices, mimePluginIndices.isEmpty()); + + for (unsigned i = 0; i < plugins.size(); ++i) { + const PluginInfo& plugin = plugins[i]; + for (auto& mime : plugin.mimes) { + mimes.append(mime); + mimePluginIndices.append(i); } } } -bool PluginData::supportsMimeType(const String& mimeType, const AllowedPluginTypes allowedPluginTypes) const +bool PluginData::supportsWebVisibleMimeType(const String& mimeType, const AllowedPluginTypes allowedPluginTypes) const { - for (unsigned i = 0; i < m_mimes.size(); ++i) { - if (m_mimes[i].type == mimeType && (allowedPluginTypes == AllPlugins || m_plugins[m_mimePluginIndices[i]].isApplicationPlugin)) + Vector<MimeClassInfo> mimes; + Vector<size_t> mimePluginIndices; + const Vector<PluginInfo>& plugins = webVisiblePlugins(); + getWebVisibleMimesAndPluginIndices(mimes, mimePluginIndices); + + for (unsigned i = 0; i < mimes.size(); ++i) { + if (mimes[i].type == mimeType && (allowedPluginTypes == AllPlugins || plugins[mimePluginIndices[i]].isApplicationPlugin)) return true; } return false; } -const PluginInfo* PluginData::pluginInfoForMimeType(const String& mimeType) const +bool PluginData::getPluginInfoForWebVisibleMimeType(const String& mimeType, PluginInfo& pluginInfoRef) const { - for (unsigned i = 0; i < m_mimes.size(); ++i) { - const MimeClassInfo& info = m_mimes[i]; - - if (info.type == mimeType) - return &m_plugins[m_mimePluginIndices[i]]; + Vector<MimeClassInfo> mimes; + Vector<size_t> mimePluginIndices; + const Vector<PluginInfo>& plugins = webVisiblePlugins(); + getWebVisibleMimesAndPluginIndices(mimes, mimePluginIndices); + + for (unsigned i = 0; i < mimes.size(); ++i) { + const MimeClassInfo& info = mimes[i]; + + if (info.type == mimeType) { + pluginInfoRef = plugins[mimePluginIndices[i]]; + return true; + } } - return 0; + return false; } -String PluginData::pluginNameForMimeType(const String& mimeType) const +String PluginData::pluginFileForWebVisibleMimeType(const String& mimeType) const { - if (const PluginInfo* info = pluginInfoForMimeType(mimeType)) - return info->name; + PluginInfo info; + if (getPluginInfoForWebVisibleMimeType(mimeType, info)) + return info.file; return String(); } -String PluginData::pluginFileForMimeType(const String& mimeType) const +bool PluginData::supportsMimeType(const String& mimeType, const AllowedPluginTypes allowedPluginTypes) const { - if (const PluginInfo* info = pluginInfoForMimeType(mimeType)) - return info->file; - return String(); -} + Vector<MimeClassInfo> mimes; + Vector<size_t> mimePluginIndices; + const Vector<PluginInfo>& plugins = this->plugins(); + getMimesAndPluginIndices(mimes, mimePluginIndices); -void PluginData::refresh() -{ - platformStrategies()->pluginStrategy()->refreshPlugins(); + for (unsigned i = 0; i < mimes.size(); ++i) { + if (mimes[i].type == mimeType && (allowedPluginTypes == AllPlugins || plugins[mimePluginIndices[i]].isApplicationPlugin)) + return true; + } + return false; } -void PluginData::initPlugins(const Page* page) +void PluginData::initPlugins() { ASSERT(m_plugins.isEmpty()); - - platformStrategies()->pluginStrategy()->getPluginInfo(page, m_plugins); -} + m_page.pluginInfoProvider().getPluginInfo(m_page, m_plugins); } + +} // namespace WebCore diff --git a/Source/WebCore/plugins/PluginData.h b/Source/WebCore/plugins/PluginData.h index fec7ace74..0893fc99a 100644 --- a/Source/WebCore/plugins/PluginData.h +++ b/Source/WebCore/plugins/PluginData.h @@ -1,5 +1,6 @@ /* Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + Copyright (C) 2015 Apple Inc. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public @@ -17,8 +18,7 @@ Boston, MA 02110-1301, USA. */ -#ifndef PluginData_h -#define PluginData_h +#pragma once #include <wtf/RefCounted.h> #include <wtf/Vector.h> @@ -29,6 +29,24 @@ namespace WebCore { class Page; struct PluginInfo; +enum PluginLoadClientPolicy : uint8_t { + // No client-specific plug-in load policy has been defined. The plug-in should be visible in navigator.plugins and WebKit should synchronously + // ask the client whether the plug-in should be loaded. + PluginLoadClientPolicyUndefined = 0, + + // The plug-in module should be blocked from being instantiated. The plug-in should be hidden in navigator.plugins. + PluginLoadClientPolicyBlock, + + // WebKit should synchronously ask the client whether the plug-in should be loaded. The plug-in should be visible in navigator.plugins. + PluginLoadClientPolicyAsk, + + // The plug-in module may be loaded if WebKit is not blocking it. + PluginLoadClientPolicyAllow, + + // The plug-in module should be loaded irrespective of whether WebKit has asked it to be blocked. + PluginLoadClientPolicyAllowAlways, +}; + struct MimeClassInfo { String type; String desc; @@ -46,38 +64,54 @@ struct PluginInfo { String desc; Vector<MimeClassInfo> mimes; bool isApplicationPlugin; + + PluginLoadClientPolicy clientLoadPolicy; + +#if PLATFORM(MAC) + String bundleIdentifier; + String versionString; +#endif }; +inline bool operator==(PluginInfo& a, PluginInfo& b) +{ + bool result = a.name == b.name && a.file == b.file && a.desc == b.desc && a.mimes == b.mimes && a.isApplicationPlugin == b.isApplicationPlugin && a.clientLoadPolicy == b.clientLoadPolicy; +#if PLATFORM(MAC) + result = result && a.bundleIdentifier == b.bundleIdentifier && a.versionString == b.versionString; +#endif + return result; +} + // FIXME: merge with PluginDatabase in the future class PluginData : public RefCounted<PluginData> { public: - static PassRefPtr<PluginData> create(const Page* page) { return adoptRef(new PluginData(page)); } + static Ref<PluginData> create(Page& page) { return adoptRef(*new PluginData(page)); } const Vector<PluginInfo>& plugins() const { return m_plugins; } - const Vector<MimeClassInfo>& mimes() const { return m_mimes; } - const Vector<size_t>& mimePluginIndices() const { return m_mimePluginIndices; } + Vector<PluginInfo> webVisiblePlugins() const; + Vector<PluginInfo> publiclyVisiblePlugins() const; + WEBCORE_EXPORT void getWebVisibleMimesAndPluginIndices(Vector<MimeClassInfo>&, Vector<size_t>&) const; enum AllowedPluginTypes { AllPlugins, OnlyApplicationPlugins }; - bool supportsMimeType(const String& mimeType, const AllowedPluginTypes) const; - String pluginNameForMimeType(const String& mimeType) const; - String pluginFileForMimeType(const String& mimeType) const; + WEBCORE_EXPORT bool supportsWebVisibleMimeType(const String& mimeType, const AllowedPluginTypes) const; + String pluginFileForWebVisibleMimeType(const String& mimeType) const; - static void refresh(); + WEBCORE_EXPORT bool supportsMimeType(const String& mimeType, const AllowedPluginTypes) const; private: - explicit PluginData(const Page*); - void initPlugins(const Page*); - const PluginInfo* pluginInfoForMimeType(const String& mimeType) const; - + explicit PluginData(Page&); + void initPlugins(); + bool getPluginInfoForWebVisibleMimeType(const String& mimeType, PluginInfo&) const; + void getMimesAndPluginIndices(Vector<MimeClassInfo>&, Vector<size_t>&) const; + void getMimesAndPluginIndiciesForPlugins(const Vector<PluginInfo>&, Vector<MimeClassInfo>&, Vector<size_t>&) const; + +protected: + Page& m_page; Vector<PluginInfo> m_plugins; - Vector<MimeClassInfo> m_mimes; - Vector<size_t> m_mimePluginIndices; }; -} - -#endif +} // namespace WebCore diff --git a/Source/WebCore/plugins/PluginDatabase.cpp b/Source/WebCore/plugins/PluginDatabase.cpp deleted file mode 100644 index a5fa84cc0..000000000 --- a/Source/WebCore/plugins/PluginDatabase.cpp +++ /dev/null @@ -1,677 +0,0 @@ -/* - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. - * Copyright (C) 2008 Collabora, Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginDatabase.h" - -#include "Frame.h" -#include "URL.h" -#include "PluginPackage.h" -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) -#include "FileSystem.h" -#endif -#include <stdlib.h> -#include <wtf/text/CString.h> - -namespace WebCore { - -typedef HashMap<String, RefPtr<PluginPackage> > PluginPackageByNameMap; - -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) -static const size_t maximumPersistentPluginMetadataCacheSize = 32768; - -static bool gPersistentPluginMetadataCacheIsEnabled; - -String& persistentPluginMetadataCachePath() -{ - DEFINE_STATIC_LOCAL(String, cachePath, ()); - return cachePath; -} -#endif - -PluginDatabase::PluginDatabase() -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - : m_persistentMetadataCacheIsLoaded(false) -#endif -{ -} - -PluginDatabase* PluginDatabase::installedPlugins(bool populate) -{ - static PluginDatabase* plugins = 0; - - if (!plugins) { - plugins = new PluginDatabase; - - if (populate) { - plugins->setPluginDirectories(PluginDatabase::defaultPluginDirectories()); - plugins->refresh(); - } - } - - return plugins; -} - -bool PluginDatabase::isMIMETypeRegistered(const String& mimeType) -{ - if (mimeType.isNull()) - return false; - if (m_registeredMIMETypes.contains(mimeType)) - return true; - // No plugin was found, try refreshing the database and searching again - return (refresh() && m_registeredMIMETypes.contains(mimeType)); -} - -void PluginDatabase::addExtraPluginDirectory(const String& directory) -{ - m_pluginDirectories.append(directory); - refresh(); -} - -bool PluginDatabase::refresh() -{ -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - if (!m_persistentMetadataCacheIsLoaded) - loadPersistentMetadataCache(); -#endif - bool pluginSetChanged = false; - - if (!m_plugins.isEmpty()) { - PluginSet pluginsToUnload; - getDeletedPlugins(pluginsToUnload); - - // Unload plugins - PluginSet::const_iterator end = pluginsToUnload.end(); - for (PluginSet::const_iterator it = pluginsToUnload.begin(); it != end; ++it) - remove(it->get()); - - pluginSetChanged = !pluginsToUnload.isEmpty(); - } - - HashSet<String> paths; - getPluginPathsInDirectories(paths); - - HashMap<String, time_t> pathsWithTimes; - - // We should only skip unchanged files if we didn't remove any plugins above. If we did remove - // any plugins, we need to look at every plugin file so that, e.g., if the user has two versions - // of RealPlayer installed and just removed the newer one, we'll pick up the older one. - bool shouldSkipUnchangedFiles = !pluginSetChanged; - - HashSet<String>::const_iterator pathsEnd = paths.end(); - for (HashSet<String>::const_iterator it = paths.begin(); it != pathsEnd; ++it) { - time_t lastModified; - if (!getFileModificationTime(*it, lastModified)) - continue; - - pathsWithTimes.add(*it, lastModified); - - // If the path's timestamp hasn't changed since the last time we ran refresh(), we don't have to do anything. - if (shouldSkipUnchangedFiles && m_pluginPathsWithTimes.get(*it) == lastModified) - continue; - - if (RefPtr<PluginPackage> oldPackage = m_pluginsByPath.get(*it)) { - ASSERT(!shouldSkipUnchangedFiles || oldPackage->lastModified() != lastModified); - remove(oldPackage.get()); - } - - RefPtr<PluginPackage> package = PluginPackage::createPackage(*it, lastModified); - if (package && add(package.release())) - pluginSetChanged = true; - } - - // Cache all the paths we found with their timestamps for next time. - pathsWithTimes.swap(m_pluginPathsWithTimes); - - if (!pluginSetChanged) - return false; - -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - updatePersistentMetadataCache(); -#endif - - m_registeredMIMETypes.clear(); - - // Register plug-in MIME types - PluginSet::const_iterator end = m_plugins.end(); - for (PluginSet::const_iterator it = m_plugins.begin(); it != end; ++it) { - // Get MIME types - MIMEToDescriptionsMap::const_iterator map_it = (*it)->mimeToDescriptions().begin(); - MIMEToDescriptionsMap::const_iterator map_end = (*it)->mimeToDescriptions().end(); - for (; map_it != map_end; ++map_it) - m_registeredMIMETypes.add(map_it->key); - } - - return true; -} - -Vector<PluginPackage*> PluginDatabase::plugins() const -{ - Vector<PluginPackage*> result; - - PluginSet::const_iterator end = m_plugins.end(); - for (PluginSet::const_iterator it = m_plugins.begin(); it != end; ++it) - result.append((*it).get()); - - return result; -} - -int PluginDatabase::preferredPluginCompare(const void* a, const void* b) -{ - PluginPackage* pluginA = *static_cast<PluginPackage* const*>(a); - PluginPackage* pluginB = *static_cast<PluginPackage* const*>(b); - - return pluginA->compare(*pluginB); -} - -PluginPackage* PluginDatabase::pluginForMIMEType(const String& mimeType) -{ - if (mimeType.isEmpty()) - return 0; - - String key = mimeType.lower(); - PluginSet::const_iterator end = m_plugins.end(); - PluginPackage* preferredPlugin = m_preferredPlugins.get(key); - if (preferredPlugin - && preferredPlugin->isEnabled() - && preferredPlugin->mimeToDescriptions().contains(key)) { - return preferredPlugin; - } - - Vector<PluginPackage*, 2> pluginChoices; - - for (PluginSet::const_iterator it = m_plugins.begin(); it != end; ++it) { - PluginPackage* plugin = (*it).get(); - - if (!plugin->isEnabled()) - continue; - - if (plugin->mimeToDescriptions().contains(key)) { -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - if (!plugin->ensurePluginLoaded()) - continue; -#endif - pluginChoices.append(plugin); - } - } - - if (pluginChoices.isEmpty()) - return 0; - - qsort(pluginChoices.data(), pluginChoices.size(), sizeof(PluginPackage*), PluginDatabase::preferredPluginCompare); - - return pluginChoices[0]; -} - -String PluginDatabase::MIMETypeForExtension(const String& extension) const -{ - if (extension.isEmpty()) - return String(); - - PluginSet::const_iterator end = m_plugins.end(); - String mimeType; - Vector<PluginPackage*, 2> pluginChoices; - HashMap<PluginPackage*, String> mimeTypeForPlugin; - - for (PluginSet::const_iterator it = m_plugins.begin(); it != end; ++it) { - if (!(*it)->isEnabled()) - continue; - - MIMEToExtensionsMap::const_iterator mime_end = (*it)->mimeToExtensions().end(); - - for (MIMEToExtensionsMap::const_iterator mime_it = (*it)->mimeToExtensions().begin(); mime_it != mime_end; ++mime_it) { - mimeType = mime_it->key; - PluginPackage* preferredPlugin = m_preferredPlugins.get(mimeType); - const Vector<String>& extensions = mime_it->value; - bool foundMapping = false; - for (unsigned i = 0; i < extensions.size(); i++) { - if (equalIgnoringCase(extensions[i], extension)) { - PluginPackage* plugin = (*it).get(); - - if (preferredPlugin && PluginPackage::equal(*plugin, *preferredPlugin)) - return mimeType; - -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - if (!plugin->ensurePluginLoaded()) - continue; -#endif - pluginChoices.append(plugin); - mimeTypeForPlugin.add(plugin, mimeType); - foundMapping = true; - break; - } - } - if (foundMapping) - break; - } - } - - if (pluginChoices.isEmpty()) - return String(); - - qsort(pluginChoices.data(), pluginChoices.size(), sizeof(PluginPackage*), PluginDatabase::preferredPluginCompare); - - return mimeTypeForPlugin.get(pluginChoices[0]); -} - -PluginPackage* PluginDatabase::findPlugin(const URL& url, String& mimeType) -{ - if (!mimeType.isEmpty()) - return pluginForMIMEType(mimeType); - - String filename = url.lastPathComponent(); - if (filename.endsWith('/')) - return 0; - - int extensionPos = filename.reverseFind('.'); - if (extensionPos == -1) - return 0; - - String mimeTypeForExtension = MIMETypeForExtension(filename.substring(extensionPos + 1)); - PluginPackage* plugin = pluginForMIMEType(mimeTypeForExtension); - if (!plugin) { - // FIXME: if no plugin could be found, query Windows for the mime type - // corresponding to the extension. - return 0; - } - - mimeType = mimeTypeForExtension; - return plugin; -} - -void PluginDatabase::setPreferredPluginForMIMEType(const String& mimeType, PluginPackage* plugin) -{ - if (!plugin || plugin->mimeToExtensions().contains(mimeType)) - m_preferredPlugins.set(mimeType.lower(), plugin); -} - -bool PluginDatabase::fileExistsAndIsNotDisabled(const String& filePath) const -{ - // Skip plugin files that are disabled by filename. - if (m_disabledPluginFiles.contains(pathGetFileName(filePath))) - return false; - - return fileExists(filePath); -} - -void PluginDatabase::getDeletedPlugins(PluginSet& plugins) const -{ - PluginSet::const_iterator end = m_plugins.end(); - for (PluginSet::const_iterator it = m_plugins.begin(); it != end; ++it) { - if (!fileExistsAndIsNotDisabled((*it)->path())) - plugins.add(*it); - } -} - -bool PluginDatabase::add(PassRefPtr<PluginPackage> prpPackage) -{ - ASSERT_ARG(prpPackage, prpPackage); - - RefPtr<PluginPackage> package = prpPackage; - - if (!m_plugins.add(package).isNewEntry) - return false; - - m_pluginsByPath.add(package->path(), package); - return true; -} - -void PluginDatabase::remove(PluginPackage* package) -{ - MIMEToExtensionsMap::const_iterator it = package->mimeToExtensions().begin(); - MIMEToExtensionsMap::const_iterator end = package->mimeToExtensions().end(); - for ( ; it != end; ++it) { - PluginPackageByNameMap::iterator packageInMap = m_preferredPlugins.find(it->key); - if (packageInMap != m_preferredPlugins.end() && packageInMap->value == package) - m_preferredPlugins.remove(packageInMap); - } - - m_plugins.remove(package); - m_pluginsByPath.remove(package->path()); -} - -void PluginDatabase::clear() -{ - m_plugins.clear(); - m_pluginsByPath.clear(); - m_pluginPathsWithTimes.clear(); - m_registeredMIMETypes.clear(); - m_preferredPlugins.clear(); -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - m_persistentMetadataCacheIsLoaded = false; -#endif -} - -bool PluginDatabase::removeDisabledPluginFile(const String& fileName) -{ - return m_disabledPluginFiles.remove(fileName); -} - -bool PluginDatabase::addDisabledPluginFile(const String& fileName) -{ - return m_disabledPluginFiles.add(fileName).isNewEntry; -} - -#if (!OS(WINCE)) && (!OS(WINDOWS) || !ENABLE(NETSCAPE_PLUGIN_API)) -// For Safari/Win the following three methods are implemented -// in PluginDatabaseWin.cpp, but if we can use WebCore constructs -// for the logic we should perhaps move it here under XP_WIN? - -Vector<String> PluginDatabase::defaultPluginDirectories() -{ - Vector<String> paths; - - // Add paths specific to each platform -#if defined(XP_UNIX) - String userPluginPath = homeDirectoryPath(); - userPluginPath.append(String("/.mozilla/plugins")); - paths.append(userPluginPath); - - userPluginPath = homeDirectoryPath(); - userPluginPath.append(String("/.netscape/plugins")); - paths.append(userPluginPath); - - paths.append("/usr/lib/browser/plugins"); - paths.append("/usr/local/lib/mozilla/plugins"); - paths.append("/usr/lib/firefox/plugins"); - paths.append("/usr/lib64/browser-plugins"); - paths.append("/usr/lib/browser-plugins"); - paths.append("/usr/lib/mozilla/plugins"); - paths.append("/usr/local/netscape/plugins"); - paths.append("/opt/mozilla/plugins"); - paths.append("/opt/mozilla/lib/plugins"); - paths.append("/opt/netscape/plugins"); - paths.append("/opt/netscape/communicator/plugins"); - paths.append("/usr/lib/netscape/plugins"); - paths.append("/usr/lib/netscape/plugins-libc5"); - paths.append("/usr/lib/netscape/plugins-libc6"); - paths.append("/usr/lib64/netscape/plugins"); - paths.append("/usr/lib64/mozilla/plugins"); - paths.append("/usr/lib/nsbrowser/plugins"); - paths.append("/usr/lib64/nsbrowser/plugins"); - - String mozHome(getenv("MOZILLA_HOME")); - mozHome.append("/plugins"); - paths.append(mozHome); - - Vector<String> mozPaths; - String mozPath(getenv("MOZ_PLUGIN_PATH")); - mozPath.split(UChar(':'), /* allowEmptyEntries */ false, mozPaths); - paths.appendVector(mozPaths); -#elif defined(XP_MACOSX) - String userPluginPath = homeDirectoryPath(); - userPluginPath.append(String("/Library/Internet Plug-Ins")); - paths.append(userPluginPath); - paths.append("/Library/Internet Plug-Ins"); -#elif defined(XP_WIN) - String userPluginPath = homeDirectoryPath(); - userPluginPath.append(String("\\Application Data\\Mozilla\\plugins")); - paths.append(userPluginPath); -#endif - - return paths; -} - -bool PluginDatabase::isPreferredPluginDirectory(const String& path) -{ - String preferredPath = homeDirectoryPath(); - -#if defined(XP_UNIX) - preferredPath.append(String("/.mozilla/plugins")); -#elif defined(XP_MACOSX) - preferredPath.append(String("/Library/Internet Plug-Ins")); -#elif defined(XP_WIN) - preferredPath.append(String("\\Application Data\\Mozilla\\plugins")); -#endif - - // TODO: We should normalize the path before doing a comparison. - return path == preferredPath; -} - -void PluginDatabase::getPluginPathsInDirectories(HashSet<String>& paths) const -{ - // FIXME: This should be a case insensitive set. - HashSet<String> uniqueFilenames; - -#if defined(XP_UNIX) - String fileNameFilter("*.so"); -#else - String fileNameFilter(""); -#endif - - Vector<String>::const_iterator dirsEnd = m_pluginDirectories.end(); - for (Vector<String>::const_iterator dIt = m_pluginDirectories.begin(); dIt != dirsEnd; ++dIt) { - Vector<String> pluginPaths = listDirectory(*dIt, fileNameFilter); - Vector<String>::const_iterator pluginsEnd = pluginPaths.end(); - for (Vector<String>::const_iterator pIt = pluginPaths.begin(); pIt != pluginsEnd; ++pIt) { - if (!fileExistsAndIsNotDisabled(*pIt)) - continue; - - paths.add(*pIt); - } - } -} - -#endif // !OS(WINDOWS) - -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - -static void fillBufferWithContentsOfFile(PlatformFileHandle file, Vector<char>& buffer) -{ - size_t bufferSize = 0; - size_t bufferCapacity = 1024; - buffer.resize(bufferCapacity); - - do { - bufferSize += readFromFile(file, buffer.data() + bufferSize, bufferCapacity - bufferSize); - if (bufferSize == bufferCapacity) { - if (bufferCapacity < maximumPersistentPluginMetadataCacheSize) { - bufferCapacity *= 2; - buffer.resize(bufferCapacity); - } else { - buffer.clear(); - return; - } - } else - break; - } while (true); - - buffer.shrink(bufferSize); -} - -static bool readUTF8String(String& resultString, char*& start, const char* end) -{ - if (start >= end) - return false; - - int len = strlen(start); - resultString = String::fromUTF8(start, len); - start += len + 1; - - return true; -} - -static bool readTime(time_t& resultTime, char*& start, const char* end) -{ - if (start + sizeof(time_t) >= end) - return false; - - // The stream is not necessary aligned. - memcpy(&resultTime, start, sizeof(time_t)); - start += sizeof(time_t); - - return true; -} - -static const char schemaVersion = '1'; -static const char persistentPluginMetadataCacheFilename[] = "PluginMetadataCache.bin"; - -void PluginDatabase::loadPersistentMetadataCache() -{ - if (!isPersistentMetadataCacheEnabled() || persistentMetadataCachePath().isEmpty()) - return; - - PlatformFileHandle file; - String absoluteCachePath = pathByAppendingComponent(persistentMetadataCachePath(), persistentPluginMetadataCacheFilename); - file = openFile(absoluteCachePath, OpenForRead); - - if (!isHandleValid(file)) - return; - - // Mark cache as loaded regardless of success or failure. If - // there's error in the cache, we won't try to load it anymore. - m_persistentMetadataCacheIsLoaded = true; - - Vector<char> fileContents; - fillBufferWithContentsOfFile(file, fileContents); - closeFile(file); - - if (fileContents.size() < 2 || fileContents.first() != schemaVersion || fileContents.last() != '\0') { - LOG_ERROR("Unable to read plugin metadata cache: corrupt schema"); - deleteFile(absoluteCachePath); - return; - } - - char* bufferPos = fileContents.data() + 1; - char* end = fileContents.data() + fileContents.size(); - - PluginSet cachedPlugins; - HashMap<String, time_t> cachedPluginPathsWithTimes; - HashMap<String, RefPtr<PluginPackage> > cachedPluginsByPath; - - while (bufferPos < end) { - String path; - time_t lastModified; - String name; - String desc; - String mimeDesc; - if (!(readUTF8String(path, bufferPos, end) - && readTime(lastModified, bufferPos, end) - && readUTF8String(name, bufferPos, end) - && readUTF8String(desc, bufferPos, end) - && readUTF8String(mimeDesc, bufferPos, end))) { - LOG_ERROR("Unable to read plugin metadata cache: corrupt data"); - deleteFile(absoluteCachePath); - return; - } - - // Skip metadata that points to plugins from directories that - // are not part of plugin directory list anymore. - String pluginDirectoryName = directoryName(path); - if (m_pluginDirectories.find(pluginDirectoryName) == WTF::notFound) - continue; - - RefPtr<PluginPackage> package = PluginPackage::createPackageFromCache(path, lastModified, name, desc, mimeDesc); - - if (package && cachedPlugins.add(package).isNewEntry) { - cachedPluginPathsWithTimes.add(package->path(), package->lastModified()); - cachedPluginsByPath.add(package->path(), package); - } - } - - m_plugins.swap(cachedPlugins); - m_pluginsByPath.swap(cachedPluginsByPath); - m_pluginPathsWithTimes.swap(cachedPluginPathsWithTimes); -} - -static bool writeUTF8String(PlatformFileHandle file, const String& string) -{ - CString utf8String = string.utf8(); - int length = utf8String.length() + 1; - return writeToFile(file, utf8String.data(), length) == length; -} - -static bool writeTime(PlatformFileHandle file, const time_t& time) -{ - return writeToFile(file, reinterpret_cast<const char*>(&time), sizeof(time_t)) == sizeof(time_t); -} - -void PluginDatabase::updatePersistentMetadataCache() -{ - if (!isPersistentMetadataCacheEnabled() || persistentMetadataCachePath().isEmpty()) - return; - - makeAllDirectories(persistentMetadataCachePath()); - String absoluteCachePath = pathByAppendingComponent(persistentMetadataCachePath(), persistentPluginMetadataCacheFilename); - deleteFile(absoluteCachePath); - - if (m_plugins.isEmpty()) - return; - - PlatformFileHandle file; - file = openFile(absoluteCachePath, OpenForWrite); - - if (!isHandleValid(file)) { - LOG_ERROR("Unable to open plugin metadata cache for saving"); - return; - } - - char localSchemaVersion = schemaVersion; - if (writeToFile(file, &localSchemaVersion, 1) != 1) { - LOG_ERROR("Unable to write plugin metadata cache schema"); - closeFile(file); - deleteFile(absoluteCachePath); - return; - } - - PluginSet::const_iterator end = m_plugins.end(); - for (PluginSet::const_iterator it = m_plugins.begin(); it != end; ++it) { - if (!(writeUTF8String(file, (*it)->path()) - && writeTime(file, (*it)->lastModified()) - && writeUTF8String(file, (*it)->name()) - && writeUTF8String(file, (*it)->description()) - && writeUTF8String(file, (*it)->fullMIMEDescription()))) { - LOG_ERROR("Unable to write plugin metadata to cache"); - closeFile(file); - deleteFile(absoluteCachePath); - return; - } - } - - closeFile(file); -} - -bool PluginDatabase::isPersistentMetadataCacheEnabled() -{ - return gPersistentPluginMetadataCacheIsEnabled; -} - -void PluginDatabase::setPersistentMetadataCacheEnabled(bool isEnabled) -{ - gPersistentPluginMetadataCacheIsEnabled = isEnabled; -} - -String PluginDatabase::persistentMetadataCachePath() -{ - return WebCore::persistentPluginMetadataCachePath(); -} - -void PluginDatabase::setPersistentMetadataCachePath(const String& persistentMetadataCachePath) -{ - WebCore::persistentPluginMetadataCachePath() = persistentMetadataCachePath; -} -#endif -} diff --git a/Source/WebCore/plugins/PluginDatabase.h b/Source/WebCore/plugins/PluginDatabase.h deleted file mode 100644 index 8d7ed0840..000000000 --- a/Source/WebCore/plugins/PluginDatabase.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. - * Copyright (C) 2008 Collabora, Ltd. All rights reserved. - * Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef PluginDatabase_h -#define PluginDatabase_h - -#include "PluginPackage.h" -#include <wtf/HashSet.h> -#include <wtf/Vector.h> -#include <wtf/text/StringHash.h> -#include <wtf/text/WTFString.h> - -namespace WebCore { - class Element; - class Frame; - class IntSize; - class URL; - class PluginDatabaseClient; - class PluginPackage; - - typedef HashSet<RefPtr<PluginPackage>, PluginPackageHash, PluginPackageHashTraits> PluginSet; - - class PluginDatabase { - WTF_MAKE_NONCOPYABLE(PluginDatabase); WTF_MAKE_FAST_ALLOCATED; - public: - PluginDatabase(); - - // The first call to installedPlugins creates the plugin database - // and by default populates it with the plugins installed on the system. - // For testing purposes, it is possible to not populate the database - // automatically, as the plugins might affect the DRT results by - // writing to a.o. stderr. - static PluginDatabase* installedPlugins(bool populate = true); - - bool refresh(); - void clear(); - Vector<PluginPackage*> plugins() const; - bool isMIMETypeRegistered(const String& mimeType); - void addExtraPluginDirectory(const String&); - - static bool isPreferredPluginDirectory(const String& directory); - static int preferredPluginCompare(const void*, const void*); - - PluginPackage* findPlugin(const URL&, String& mimeType); - PluginPackage* pluginForMIMEType(const String& mimeType); - void setPreferredPluginForMIMEType(const String& mimeType, PluginPackage* plugin); - - void setPluginDirectories(const Vector<String>& directories) - { - clear(); - m_pluginDirectories = directories; - } - - bool removeDisabledPluginFile(const String& fileName); - bool addDisabledPluginFile(const String& fileName); - static Vector<String> defaultPluginDirectories(); - Vector<String> pluginDirectories() const { return m_pluginDirectories; } - - String MIMETypeForExtension(const String& extension) const; -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - static bool isPersistentMetadataCacheEnabled(); - static void setPersistentMetadataCacheEnabled(bool isEnabled); - static String persistentMetadataCachePath(); - static void setPersistentMetadataCachePath(const String& persistentMetadataCachePath); -#endif - - private: - void getPluginPathsInDirectories(HashSet<String>&) const; - void getDeletedPlugins(PluginSet&) const; - bool fileExistsAndIsNotDisabled(const String&) const; - - // Returns whether the plugin was actually added or not (it won't be added if it's a duplicate of an existing plugin). - bool add(PassRefPtr<PluginPackage>); - void remove(PluginPackage*); -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - void loadPersistentMetadataCache(); - void updatePersistentMetadataCache(); -#endif - - HashSet<String> m_disabledPluginFiles; - Vector<String> m_pluginDirectories; - HashSet<String> m_registeredMIMETypes; - PluginSet m_plugins; - HashMap<String, RefPtr<PluginPackage> > m_pluginsByPath; - HashMap<String, time_t> m_pluginPathsWithTimes; - HashMap<String, RefPtr<PluginPackage> > m_preferredPlugins; -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - bool m_persistentMetadataCacheIsLoaded; -#endif - }; - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/plugins/PluginDebug.cpp b/Source/WebCore/plugins/PluginDebug.cpp deleted file mode 100644 index a2e1f56d2..000000000 --- a/Source/WebCore/plugins/PluginDebug.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. - * Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginDebug.h" - -#include <wtf/text/WTFString.h> - -#if !LOG_DISABLED - -namespace WebCore { - -static const char* const errorStrings[] = { - "No errors occurred.", /* NPERR_NO_ERROR */ - "Error with no specific error code occurred.", /* NPERR_GENERIC_ERROR */ - "Invalid instance passed to the plug-in.", /* NPERR_INVALID_INSTANCE_ERROR */ - "Function table invalid.", /* NPERR_INVALID_FUNCTABLE_ERROR */ - "Loading of plug-in failed.", /* NPERR_MODULE_LOAD_FAILED_ERROR */ - "Memory allocation failed.", /* NPERR_OUT_OF_MEMORY_ERROR */ - "Plug-in missing or invalid.", /* NPERR_INVALID_PLUGIN_ERROR */ - "Plug-in directory missing or invalid.", /* NPERR_INVALID_PLUGIN_DIR_ERROR */ - "Versions of plug-in and Communicator do not match.", /* NPERR_INCOMPATIBLE_VERSION_ERROR */ - "Parameter missing or invalid.", /* NPERR_INVALID_PARAM */ - "URL missing or invalid.", /* NPERR_INVALID_URL */ - "File missing or invalid.", /* NPERR_FILE_NOT_FOUND */ - "Stream contains no data.", /* NPERR_NO_DATA */ - "Seekable stream expected.", /* NPERR_STREAM_NOT_SEEKABLE */ - "Unknown error code" -}; - -#ifdef XP_MACOSX -static const char* const drawingModels[] = { - "NPDrawingModelQuickDraw", - "NPDrawingModelCoreGraphics", - "NPDrawingModelOpenGL", - "NPDrawingModelCoreAnimation" -}; - -static const char* const eventModels[] = { - "NPEventModelCarbon", - "NPEventModelCocoa" -}; -#endif //XP_MACOSX - -const char* prettyNameForNPError(NPError error) -{ - return errorStrings[error]; -} - -#ifdef XP_MACOSX -const char* prettyNameForDrawingModel(NPDrawingModel drawingModel) -{ - return drawingModels[drawingModel]; -} - -const char* prettyNameForEventModel(NPEventModel eventModel) -{ - return eventModels[eventModel]; -} -#endif //XP_MACOSX - -CString prettyNameForNPNVariable(NPNVariable variable) -{ - switch (variable) { - case NPNVxDisplay: return "NPNVxDisplay"; - case NPNVxtAppContext: return "NPNVxtAppContext"; - case NPNVnetscapeWindow: return "NPNVnetscapeWindow"; - case NPNVjavascriptEnabledBool: return "NPNVjavascriptEnabledBool"; - case NPNVasdEnabledBool: return "NPNVasdEnabledBool"; - case NPNVisOfflineBool: return "NPNVisOfflineBool"; - - case NPNVserviceManager: return "NPNVserviceManager (not supported)"; - case NPNVDOMElement: return "NPNVDOMElement (not supported)"; - case NPNVDOMWindow: return "NPNVDOMWindow (not supported)"; - case NPNVToolkit: return "NPNVToolkit (not supported)"; - case NPNVSupportsXEmbedBool: return "NPNVSupportsXEmbedBool (not supported)"; - - case NPNVWindowNPObject: return "NPNVWindowNPObject"; - case NPNVPluginElementNPObject: return "NPNVPluginElementNPObject"; - case NPNVSupportsWindowless: return "NPNVSupportsWindowless"; - case NPNVprivateModeBool: return "NPNVprivateModeBool"; - -#ifdef XP_MACOSX - case NPNVpluginDrawingModel: return "NPNVpluginDrawingModel"; -#ifndef NP_NO_QUICKDRAW - case NPNVsupportsQuickDrawBool: return "NPNVsupportsQuickDrawBool"; -#endif - case NPNVsupportsCoreGraphicsBool: return "NPNVsupportsCoreGraphicsBool"; - case NPNVsupportsOpenGLBool: return "NPNVsupportsOpenGLBool"; - case NPNVsupportsCoreAnimationBool: return "NPNVsupportsCoreAnimationBool"; -#ifndef NP_NO_CARBON - case NPNVsupportsCarbonBool: return "NPNVsupportsCarbonBool"; -#endif - case NPNVsupportsCocoaBool: return "NPNVsupportsCocoaBool"; -#endif - - default: return "Unknown variable"; - } -} - -CString prettyNameForNPPVariable(NPPVariable variable, void* value) -{ - switch (variable) { - case NPPVpluginNameString: return "NPPVpluginNameString"; - case NPPVpluginDescriptionString: return "NPPVpluginDescriptionString"; - case NPPVpluginWindowBool: return "NPPVpluginWindowBool"; - case NPPVpluginTransparentBool: return "NPPVpluginTransparentBool"; - - case NPPVjavaClass: return "NPPVjavaClass (not supported)"; - case NPPVpluginWindowSize: return "NPPVpluginWindowSize (not supported)"; - case NPPVpluginTimerInterval: return "NPPVpluginTimerInterval (not supported)"; - case NPPVpluginScriptableInstance: return "NPPVpluginScriptableInstance (not supported)"; - case NPPVpluginScriptableIID: return "NPPVpluginScriptableIID (not supported)"; - case NPPVjavascriptPushCallerBool: return "NPPVjavascriptPushCallerBool (not supported)"; - case NPPVpluginKeepLibraryInMemory: return "NPPVpluginKeepLibraryInMemory (not supported)"; - case NPPVpluginNeedsXEmbed: return "NPPVpluginNeedsXEmbed (not supported)"; - - case NPPVpluginScriptableNPObject: return "NPPVpluginScriptableNPObject"; - - case NPPVformValue: return "NPPVformValue (not supported)"; - case NPPVpluginUrlRequestsDisplayedBool: return "NPPVpluginUrlRequestsDisplayedBool (not supported)"; - - case NPPVpluginWantsAllNetworkStreams: return "NPPVpluginWantsAllNetworkStreams"; - case NPPVpluginCancelSrcStream: return "NPPVpluginCancelSrcStream"; - -#ifdef XP_MACOSX - case NPPVpluginDrawingModel: { - String result("NPPVpluginDrawingModel, "); - result.append(prettyNameForDrawingModel(NPDrawingModel(uintptr_t(value)))); - return result.latin1(); - } - case NPPVpluginEventModel: { - String result("NPPVpluginEventModel, "); - result.append(prettyNameForEventModel(NPEventModel(uintptr_t(value)))); - return result.latin1(); - } - case NPPVpluginCoreAnimationLayer: return "NPPVpluginCoreAnimationLayer"; -#else - UNUSED_PARAM(value); -#endif - - default: return "Unknown variable"; - } -} - -CString prettyNameForNPNURLVariable(NPNURLVariable variable) -{ - switch (variable) { - case NPNURLVCookie: return "NPNURLVCookie"; - case NPNURLVProxy: return "NPNURLVProxy"; - default: return "Unknown variable"; - } -} -} // namespace WebCore - -#endif // !LOG_DISABLED diff --git a/Source/WebCore/plugins/PluginDebug.h b/Source/WebCore/plugins/PluginDebug.h deleted file mode 100644 index 017e6867c..000000000 --- a/Source/WebCore/plugins/PluginDebug.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef PluginDebug_h -#define PluginDebug_h - -#include "Logging.h" -#include "npruntime_internal.h" -#include <wtf/text/CString.h> - -#define LOG_NPERROR(err) if (err != NPERR_NO_ERROR) LOG_VERBOSE(Plugins, "%s\n", prettyNameForNPError(err)) -#define LOG_PLUGIN_NET_ERROR() LOG_VERBOSE(Plugins, "Stream failed due to problems with network, disk I/O, lack of memory, or other problems.\n") - -#if !LOG_DISABLED - -namespace WebCore { - -const char* prettyNameForNPError(NPError error); - -CString prettyNameForNPNVariable(NPNVariable variable); -CString prettyNameForNPPVariable(NPPVariable variable, void* value); -CString prettyNameForNPNURLVariable(NPNURLVariable variable); - -#ifdef XP_MACOSX -const char* prettyNameForDrawingModel(NPDrawingModel drawingModel); -const char* prettyNameForEventModel(NPEventModel eventModel); -#endif - -} // namespace WebCore - -#endif // !LOG_DISABLED - -#endif // PluginDebug_h diff --git a/Source/WebCore/plugins/PluginInfoProvider.cpp b/Source/WebCore/plugins/PluginInfoProvider.cpp new file mode 100644 index 000000000..5ac7349c4 --- /dev/null +++ b/Source/WebCore/plugins/PluginInfoProvider.cpp @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2016 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PluginInfoProvider.h" + +#include "MainFrame.h" +#include "Page.h" +#include "SubframeLoader.h" + +namespace WebCore { + +PluginInfoProvider::~PluginInfoProvider() +{ + ASSERT(m_pages.isEmpty()); +} + +void PluginInfoProvider::refresh(bool reloadPages) +{ + refreshPlugins(); + + Vector<Ref<MainFrame>> framesNeedingReload; + + for (auto& page : m_pages) { + page->clearPluginData(); + + if (!reloadPages) + continue; + + for (Frame* frame = &page->mainFrame(); frame; frame = frame->tree().traverseNext()) { + if (frame->loader().subframeLoader().containsPlugins()) + framesNeedingReload.append(page->mainFrame()); + } + } + + for (auto& frame : framesNeedingReload) + frame->loader().reload(); +} + +void PluginInfoProvider::addPage(Page& page) +{ + ASSERT(!m_pages.contains(&page)); + + m_pages.add(&page); +} + +void PluginInfoProvider::removePage(Page& page) +{ + ASSERT(m_pages.contains(&page)); + + m_pages.remove(&page); +} + +} diff --git a/Source/WebCore/plugins/PluginStrategy.h b/Source/WebCore/plugins/PluginInfoProvider.h index 05d199f20..dafa16568 100644 --- a/Source/WebCore/plugins/PluginStrategy.h +++ b/Source/WebCore/plugins/PluginInfoProvider.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -23,24 +23,29 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef PluginStrategy_h -#define PluginStrategy_h +#pragma once #include "PluginData.h" +#include <wtf/HashSet.h> namespace WebCore { -class Page; - -class PluginStrategy { +class WEBCORE_EXPORT PluginInfoProvider : public RefCounted<PluginInfoProvider> { public: + virtual ~PluginInfoProvider(); + + void refresh(bool reloadPages); + + void addPage(Page&); + void removePage(Page&); + + virtual void getPluginInfo(Page&, Vector<PluginInfo>&) = 0; + virtual void getWebVisiblePluginInfo(Page&, Vector<PluginInfo>&) = 0; + +private: virtual void refreshPlugins() = 0; - virtual void getPluginInfo(const Page*, Vector<PluginInfo>&) = 0; -protected: - virtual ~PluginStrategy() { } + HashSet<Page*> m_pages; }; -} // namespace WebCore - -#endif // PluginStrategy_h +} diff --git a/Source/WebCore/plugins/PluginMainThreadScheduler.cpp b/Source/WebCore/plugins/PluginMainThreadScheduler.cpp deleted file mode 100644 index 39ae794e2..000000000 --- a/Source/WebCore/plugins/PluginMainThreadScheduler.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2008 Apple Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginMainThreadScheduler.h" -#include <wtf/StdLibExtras.h> - -namespace WebCore { - -PluginMainThreadScheduler& PluginMainThreadScheduler::scheduler() -{ - DEFINE_STATIC_LOCAL(PluginMainThreadScheduler, scheduler, ()); - - return scheduler; -} - -PluginMainThreadScheduler::PluginMainThreadScheduler() - : m_callPending(false) -{ -} - -void PluginMainThreadScheduler::scheduleCall(NPP npp, MainThreadFunction function, void* userData) -{ - MutexLocker lock(m_queueMutex); - - CallQueueMap::iterator it = m_callQueueMap.find(npp); - if (it == m_callQueueMap.end()) - return; - - it->value.append(Call(function, userData)); - - if (!m_callPending) { - callOnMainThread(mainThreadCallback, this); - m_callPending = true; - } -} - -void PluginMainThreadScheduler::registerPlugin(NPP npp) -{ - MutexLocker lock(m_queueMutex); - - ASSERT(!m_callQueueMap.contains(npp)); - m_callQueueMap.set(npp, Deque<Call>()); -} - -void PluginMainThreadScheduler::unregisterPlugin(NPP npp) -{ - MutexLocker lock(m_queueMutex); - - ASSERT(m_callQueueMap.contains(npp)); - m_callQueueMap.remove(npp); -} - -void PluginMainThreadScheduler::dispatchCallsForPlugin(NPP npp, const Deque<Call>& calls) -{ - Deque<Call>::const_iterator end = calls.end(); - for (Deque<Call>::const_iterator it = calls.begin(); it != end; ++it) { - // Check if the plug-in has been destroyed. - { - MutexLocker lock(m_queueMutex); - if (!m_callQueueMap.contains(npp)) - return; - } - - (*it).performCall(); - } -} - -void PluginMainThreadScheduler::dispatchCalls() -{ - m_queueMutex.lock(); - CallQueueMap copy(m_callQueueMap); - - { - // Empty all the queues in the original map - CallQueueMap::iterator end = m_callQueueMap.end(); - for (CallQueueMap::iterator it = m_callQueueMap.begin(); it != end; ++it) - it->value.clear(); - } - - m_callPending = false; - m_queueMutex.unlock(); - - CallQueueMap::iterator end = copy.end(); - for (CallQueueMap::iterator it = copy.begin(); it != end; ++it) - dispatchCallsForPlugin(it->key, it->value); -} - -void PluginMainThreadScheduler::mainThreadCallback(void* context) -{ - static_cast<PluginMainThreadScheduler*>(context)->dispatchCalls(); -} - -} // namespace WebCore diff --git a/Source/WebCore/plugins/PluginMainThreadScheduler.h b/Source/WebCore/plugins/PluginMainThreadScheduler.h deleted file mode 100644 index aafc491ac..000000000 --- a/Source/WebCore/plugins/PluginMainThreadScheduler.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2008 Apple Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef PluginMainThreadScheduler_h -#define PluginMainThreadScheduler_h - -#include <wtf/Deque.h> -#include <wtf/HashMap.h> -#include <wtf/MainThread.h> -#include <wtf/Threading.h> - -typedef struct _NPP NPP_t; -typedef NPP_t* NPP; - -namespace WebCore { - -class PluginMainThreadScheduler { - WTF_MAKE_NONCOPYABLE(PluginMainThreadScheduler); WTF_MAKE_FAST_ALLOCATED; -public: - typedef void MainThreadFunction(void*); - - static PluginMainThreadScheduler& scheduler(); - - void scheduleCall(NPP, MainThreadFunction*, void* userData); - - void registerPlugin(NPP); - void unregisterPlugin(NPP); - -private: - PluginMainThreadScheduler(); - void dispatchCalls(); - - class Call; - - void dispatchCallsForPlugin(NPP, const Deque<Call>& calls); - typedef HashMap<NPP, Deque<Call>> CallQueueMap; - - static void mainThreadCallback(void* context); - - class Call { - public: - Call(MainThreadFunction* function, void* userData) - : m_function(function) - , m_userData(userData) - { - } - - void performCall() const - { - m_function(m_userData); - } - - private: - MainThreadFunction* m_function; - void* m_userData; - }; - - bool m_callPending; - CallQueueMap m_callQueueMap; - Mutex m_queueMutex; -}; - -} // namespace WebCore - -#endif // PluginMainThreadScheduler_h diff --git a/Source/WebCore/plugins/PluginPackage.cpp b/Source/WebCore/plugins/PluginPackage.cpp deleted file mode 100644 index d077aecc5..000000000 --- a/Source/WebCore/plugins/PluginPackage.cpp +++ /dev/null @@ -1,558 +0,0 @@ -/* - * Copyright (C) 2006, 2008 Apple Inc. All rights reserved. - * Copyright (C) 2008 Collabora Ltd. All rights reserved. - * Copyright (C) 2009 Holger Hans Peter Freyther - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginPackage.h" - -#include "MIMETypeRegistry.h" -#include "Page.h" -#include "PluginDatabase.h" -#include "PluginDebug.h" -#include "PluginMainThreadScheduler.h" -#include "PluginView.h" -#include "Timer.h" -#include "npruntime_impl.h" -#include <string.h> -#include <wtf/text/CString.h> - -namespace WebCore { - -PluginPackage::~PluginPackage() -{ - // This destructor gets called during refresh() if PluginDatabase's - // PluginSet hash is already populated, as it removes items from - // the hash table. Calling the destructor on a loaded plug-in of - // course would cause a crash, so we check to call unload before we - // ASSERT. - // FIXME: There is probably a better way to fix this. - if (!m_loadCount) - unloadWithoutShutdown(); - else - unload(); - - ASSERT(!m_isLoaded); -} - -void PluginPackage::freeLibrarySoon() -{ - ASSERT(!m_freeLibraryTimer.isActive()); - ASSERT(m_module); - ASSERT(!m_loadCount); - - m_freeLibraryTimer.startOneShot(0); -} - -void PluginPackage::freeLibraryTimerFired(Timer<PluginPackage>*) -{ - ASSERT(m_module); - // Do nothing if the module got loaded again meanwhile - if (!m_loadCount) { - unloadModule(m_module); - m_module = 0; - } -} - - -int PluginPackage::compare(const PluginPackage& compareTo) const -{ - // Sort plug-ins that allow multiple instances first. - bool AallowsMultipleInstances = !quirks().contains(PluginQuirkDontAllowMultipleInstances); - bool BallowsMultipleInstances = !compareTo.quirks().contains(PluginQuirkDontAllowMultipleInstances); - if (AallowsMultipleInstances != BallowsMultipleInstances) - return AallowsMultipleInstances ? -1 : 1; - - // Sort plug-ins in a preferred path first. - bool AisInPreferredDirectory = PluginDatabase::isPreferredPluginDirectory(parentDirectory()); - bool BisInPreferredDirectory = PluginDatabase::isPreferredPluginDirectory(compareTo.parentDirectory()); - if (AisInPreferredDirectory != BisInPreferredDirectory) - return AisInPreferredDirectory ? -1 : 1; - - int diff = strcmp(name().utf8().data(), compareTo.name().utf8().data()); - if (diff) - return diff; - - diff = compareFileVersion(compareTo.version()); - if (diff) - return diff; - - return strcmp(parentDirectory().utf8().data(), compareTo.parentDirectory().utf8().data()); -} - -PluginPackage::PluginPackage(const String& path, const time_t& lastModified) - : m_isEnabled(true) - , m_isLoaded(false) - , m_loadCount(0) - , m_path(path) - , m_moduleVersion(0) - , m_module(0) - , m_lastModified(lastModified) - , m_freeLibraryTimer(this, &PluginPackage::freeLibraryTimerFired) -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - , m_infoIsFromCache(true) -#endif -{ - m_fileName = pathGetFileName(m_path); - m_parentDirectory = m_path.left(m_path.length() - m_fileName.length() - 1); -} - -void PluginPackage::unload() -{ - if (!m_isLoaded) - return; - - if (--m_loadCount > 0) - return; - -#if ENABLE(NETSCAPE_PLUGIN_API) - m_NPP_Shutdown(); -#endif - - unloadWithoutShutdown(); -} - -void PluginPackage::unloadWithoutShutdown() -{ - if (!m_isLoaded) - return; - - ASSERT(!m_loadCount); - ASSERT(m_module); - - // <rdar://5530519>: Crash when closing tab with pdf file (Reader 7 only) - // If the plugin has subclassed its parent window, as with Reader 7, we may have - // gotten here by way of the plugin's internal window proc forwarding a message to our - // original window proc. If we free the plugin library from here, we will jump back - // to code we just freed when we return, so delay calling FreeLibrary at least until - // the next message loop - freeLibrarySoon(); - - m_isLoaded = false; -} - -void PluginPackage::setEnabled(bool enabled) -{ - m_isEnabled = enabled; -} - -PassRefPtr<PluginPackage> PluginPackage::createPackage(const String& path, const time_t& lastModified) -{ - RefPtr<PluginPackage> package = adoptRef(new PluginPackage(path, lastModified)); - - if (!package->fetchInfo()) - return 0; - - return package.release(); -} - -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) -PassRefPtr<PluginPackage> PluginPackage::createPackageFromCache(const String& path, const time_t& lastModified, const String& name, const String& description, const String& mimeDescription) -{ - RefPtr<PluginPackage> package = adoptRef(new PluginPackage(path, lastModified)); - package->m_name = name; - package->m_description = description; - package->determineModuleVersionFromDescription(); - package->setMIMEDescription(mimeDescription); - package->m_infoIsFromCache = true; - return package.release(); -} -#endif - -#if defined(XP_UNIX) -void PluginPackage::determineQuirks(const String& mimeType) -{ - if (MIMETypeRegistry::isJavaAppletMIMEType(mimeType)) { - // Because a single process cannot create multiple VMs, and we cannot reliably unload a - // Java VM, we cannot unload the Java plugin, or we'll lose reference to our only VM - m_quirks.add(PluginQuirkDontUnloadPlugin); - - // Setting the window region to an empty region causes bad scrolling repaint problems - // with the Java plug-in. - m_quirks.add(PluginQuirkDontClipToZeroRectWhenScrolling); - return; - } - - if (mimeType == "application/x-shockwave-flash") { - static const PlatformModuleVersion flashTenVersion(0x0a000000); - - if (compareFileVersion(flashTenVersion) >= 0) { - // Flash 10.0 b218 doesn't like having a NULL window handle - m_quirks.add(PluginQuirkDontSetNullWindowHandleOnDestroy); - } else { - // Flash 9 and older requests windowless plugins if we return a mozilla user agent - m_quirks.add(PluginQuirkWantsMozillaUserAgent); - } - -#if CPU(X86_64) - // 64-bit Flash freezes if right-click is sent in windowless mode - m_quirks.add(PluginQuirkIgnoreRightClickInWindowlessMode); -#endif - - m_quirks.add(PluginQuirkRequiresDefaultScreenDepth); - m_quirks.add(PluginQuirkThrottleInvalidate); - m_quirks.add(PluginQuirkThrottleWMUserPlusOneMessages); - m_quirks.add(PluginQuirkFlashURLNotifyBug); - } -} -#endif - -#if !OS(WINDOWS) -void PluginPackage::determineModuleVersionFromDescription() -{ - // It's a bit lame to detect the plugin version by parsing it - // from the plugin description string, but it doesn't seem that - // version information is available in any standardized way at - // the module level, like in Windows - - if (m_description.isEmpty()) - return; - - if (m_description.startsWith("Shockwave Flash") && m_description.length() >= 19) { - // The flash version as a PlatformModuleVersion differs on Unix from Windows - // since the revision can be larger than a 8 bits, so we allow it 16 here and - // push the major/minor up 8 bits. Thus on Unix, Flash's version may be - // 0x0a000000 instead of 0x000a0000. - - Vector<String> versionParts; - m_description.substring(16).split(' ', /*allowEmptyEntries =*/ false, versionParts); - if (versionParts.isEmpty()) - return; - - if (versionParts.size() >= 1) { - Vector<String> majorMinorParts; - versionParts[0].split('.', majorMinorParts); - if (majorMinorParts.size() >= 1) { - bool converted = false; - unsigned major = majorMinorParts[0].toUInt(&converted); - if (converted) - m_moduleVersion = (major & 0xff) << 24; - } - if (majorMinorParts.size() == 2) { - bool converted = false; - unsigned minor = majorMinorParts[1].toUInt(&converted); - if (converted) - m_moduleVersion |= (minor & 0xff) << 16; - } - } - - if (versionParts.size() >= 2) { - String revision = versionParts[1]; - if (revision.length() > 1 && (revision[0] == 'r' || revision[0] == 'b')) { - revision.remove(0, 1); - m_moduleVersion |= revision.toInt() & 0xffff; - } - } - } -} -#endif - -#if ENABLE(NETSCAPE_PLUGIN_API) -static PluginView* pluginViewForInstance(NPP instance) -{ - if (instance && instance->ndata) - return static_cast<PluginView*>(instance->ndata); - return PluginView::currentPluginView(); -} - -static void* NPN_MemAlloc(uint32_t size) -{ - return malloc(size); -} - -static void NPN_MemFree(void* ptr) -{ - free(ptr); -} - -static uint32_t NPN_MemFlush(uint32_t) -{ - // Do nothing - return 0; -} - -static void NPN_ReloadPlugins(NPBool reloadPages) -{ - Page::refreshPlugins(reloadPages); -} - -static NPError NPN_RequestRead(NPStream*, NPByteRange*) -{ - return NPERR_STREAM_NOT_SEEKABLE; -} - -static NPError NPN_GetURLNotify(NPP instance, const char* url, const char* target, void* notifyData) -{ - return pluginViewForInstance(instance)->getURLNotify(url, target, notifyData); -} - -static NPError NPN_GetURL(NPP instance, const char* url, const char* target) -{ - return pluginViewForInstance(instance)->getURL(url, target); -} - -static NPError NPN_PostURLNotify(NPP instance, const char* url, const char* target, uint32_t len, const char* buf, NPBool file, void* notifyData) -{ - return pluginViewForInstance(instance)->postURLNotify(url, target, len, buf, file, notifyData); -} - -static NPError NPN_PostURL(NPP instance, const char* url, const char* target, uint32_t len, const char* buf, NPBool file) -{ - return pluginViewForInstance(instance)->postURL(url, target, len, buf, file); -} - -static NPError NPN_NewStream(NPP instance, NPMIMEType type, const char* target, NPStream** stream) -{ - return pluginViewForInstance(instance)->newStream(type, target, stream); -} - -static int32_t NPN_Write(NPP instance, NPStream* stream, int32_t len, void* buffer) -{ - return pluginViewForInstance(instance)->write(stream, len, buffer); -} - -static NPError NPN_DestroyStream(NPP instance, NPStream* stream, NPReason reason) -{ - return pluginViewForInstance(instance)->destroyStream(stream, reason); -} - -static const char* NPN_UserAgent(NPP instance) -{ - PluginView* view = pluginViewForInstance(instance); - - if (!view) - return PluginView::userAgentStatic(); - - return view->userAgent(); -} - -static void NPN_Status(NPP instance, const char* message) -{ - pluginViewForInstance(instance)->status(message); -} - -static void NPN_InvalidateRect(NPP instance, NPRect* invalidRect) -{ - PluginView* view = pluginViewForInstance(instance); -#if defined(XP_UNIX) - // NSPluginWrapper, a plugin wrapper binary that allows running 32-bit plugins - // on 64-bit architectures typically used in X11, will sometimes give us a null NPP here. - if (!view) - return; -#endif - view->invalidateRect(invalidRect); -} - -static void NPN_InvalidateRegion(NPP instance, NPRegion invalidRegion) -{ - pluginViewForInstance(instance)->invalidateRegion(invalidRegion); -} - -static void NPN_ForceRedraw(NPP instance) -{ - pluginViewForInstance(instance)->forceRedraw(); -} - -static NPError NPN_GetValue(NPP instance, NPNVariable variable, void* value) -{ - PluginView* view = pluginViewForInstance(instance); - - if (!view) - return PluginView::getValueStatic(variable, value); - - return pluginViewForInstance(instance)->getValue(variable, value); -} - -static NPError NPN_SetValue(NPP instance, NPPVariable variable, void* value) -{ - return pluginViewForInstance(instance)->setValue(variable, value); -} - -static void* NPN_GetJavaEnv() -{ - // Unsupported - return 0; -} - -static void* NPN_GetJavaPeer(NPP) -{ - // Unsupported - return 0; -} - -static void NPN_PushPopupsEnabledState(NPP instance, NPBool enabled) -{ - pluginViewForInstance(instance)->pushPopupsEnabledState(enabled); -} - -static void NPN_PopPopupsEnabledState(NPP instance) -{ - pluginViewForInstance(instance)->popPopupsEnabledState(); -} - -extern "C" typedef void PluginThreadAsyncCallFunction(void*); -static void NPN_PluginThreadAsyncCall(NPP instance, PluginThreadAsyncCallFunction func, void* userData) -{ - // Callback function type only differs from MainThreadFunction by being extern "C", which doesn't affect calling convention on any compilers we use. - PluginMainThreadScheduler::scheduler().scheduleCall(instance, reinterpret_cast<PluginMainThreadScheduler::MainThreadFunction*>(func), userData); -} - -static NPError NPN_GetValueForURL(NPP instance, NPNURLVariable variable, const char* url, char** value, uint32_t* len) -{ - return pluginViewForInstance(instance)->getValueForURL(variable, url, value, len); -} - -static NPError NPN_SetValueForURL(NPP instance, NPNURLVariable variable, const char* url, const char* value, uint32_t len) -{ - return pluginViewForInstance(instance)->setValueForURL(variable, url, value, len); -} - -static NPError NPN_GetAuthenticationInfo(NPP instance, 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) -{ - return pluginViewForInstance(instance)->getAuthenticationInfo(protocol, host, port, scheme, realm, username, ulen, password, plen); -} - -static NPError NPN_PopUpContextMenu(NPP instance, NPMenu* menu) -{ - UNUSED_PARAM(instance); - UNUSED_PARAM(menu); - return NPERR_NO_ERROR; -} - -void PluginPackage::initializeBrowserFuncs() -{ - memset(&m_browserFuncs, 0, sizeof(m_browserFuncs)); - m_browserFuncs.size = sizeof(m_browserFuncs); - m_browserFuncs.version = NPVersion(); - - m_browserFuncs.geturl = NPN_GetURL; - m_browserFuncs.posturl = NPN_PostURL; - m_browserFuncs.requestread = NPN_RequestRead; - m_browserFuncs.newstream = NPN_NewStream; - m_browserFuncs.write = NPN_Write; - m_browserFuncs.destroystream = NPN_DestroyStream; - m_browserFuncs.status = NPN_Status; - m_browserFuncs.uagent = NPN_UserAgent; - m_browserFuncs.memalloc = NPN_MemAlloc; - m_browserFuncs.memfree = NPN_MemFree; - m_browserFuncs.memflush = NPN_MemFlush; - m_browserFuncs.reloadplugins = NPN_ReloadPlugins; - m_browserFuncs.geturlnotify = NPN_GetURLNotify; - m_browserFuncs.posturlnotify = NPN_PostURLNotify; - m_browserFuncs.getvalue = NPN_GetValue; - m_browserFuncs.setvalue = NPN_SetValue; - m_browserFuncs.invalidaterect = NPN_InvalidateRect; - m_browserFuncs.invalidateregion = NPN_InvalidateRegion; - m_browserFuncs.forceredraw = NPN_ForceRedraw; - m_browserFuncs.getJavaEnv = NPN_GetJavaEnv; - m_browserFuncs.getJavaPeer = NPN_GetJavaPeer; - m_browserFuncs.pushpopupsenabledstate = NPN_PushPopupsEnabledState; - m_browserFuncs.poppopupsenabledstate = NPN_PopPopupsEnabledState; - m_browserFuncs.pluginthreadasynccall = NPN_PluginThreadAsyncCall; - - m_browserFuncs.releasevariantvalue = _NPN_ReleaseVariantValue; - m_browserFuncs.getstringidentifier = _NPN_GetStringIdentifier; - m_browserFuncs.getstringidentifiers = _NPN_GetStringIdentifiers; - m_browserFuncs.getintidentifier = _NPN_GetIntIdentifier; - m_browserFuncs.identifierisstring = _NPN_IdentifierIsString; - m_browserFuncs.utf8fromidentifier = _NPN_UTF8FromIdentifier; - m_browserFuncs.intfromidentifier = _NPN_IntFromIdentifier; - m_browserFuncs.createobject = _NPN_CreateObject; - m_browserFuncs.retainobject = _NPN_RetainObject; - m_browserFuncs.releaseobject = _NPN_ReleaseObject; - m_browserFuncs.invoke = _NPN_Invoke; - m_browserFuncs.invokeDefault = _NPN_InvokeDefault; - m_browserFuncs.evaluate = _NPN_Evaluate; - m_browserFuncs.getproperty = _NPN_GetProperty; - m_browserFuncs.setproperty = _NPN_SetProperty; - m_browserFuncs.removeproperty = _NPN_RemoveProperty; - m_browserFuncs.hasproperty = _NPN_HasProperty; - m_browserFuncs.hasmethod = _NPN_HasMethod; - m_browserFuncs.setexception = _NPN_SetException; - m_browserFuncs.enumerate = _NPN_Enumerate; - m_browserFuncs.construct = _NPN_Construct; - m_browserFuncs.getvalueforurl = NPN_GetValueForURL; - m_browserFuncs.setvalueforurl = NPN_SetValueForURL; - m_browserFuncs.getauthenticationinfo = NPN_GetAuthenticationInfo; - - m_browserFuncs.popupcontextmenu = NPN_PopUpContextMenu; -} -#endif // ENABLE(NETSCAPE_PLUGIN_API) - -#if ENABLE(PLUGIN_PACKAGE_SIMPLE_HASH) -unsigned PluginPackage::hash() const -{ - struct HashCodes { - unsigned hash; - time_t modifiedDate; - } hashCodes; - - hashCodes.hash = m_path.impl()->hash(); - hashCodes.modifiedDate = m_lastModified; - - return StringHasher::hashMemory<sizeof(hashCodes)>(&hashCodes); -} - -bool PluginPackage::equal(const PluginPackage& a, const PluginPackage& b) -{ - return a.m_description == b.m_description; -} -#endif - -int PluginPackage::compareFileVersion(const PlatformModuleVersion& compareVersion) const -{ - // return -1, 0, or 1 if plug-in version is less than, equal to, or greater than - // the passed version - -#if OS(WINDOWS) - if (m_moduleVersion.mostSig != compareVersion.mostSig) - return m_moduleVersion.mostSig > compareVersion.mostSig ? 1 : -1; - if (m_moduleVersion.leastSig != compareVersion.leastSig) - return m_moduleVersion.leastSig > compareVersion.leastSig ? 1 : -1; -#else - if (m_moduleVersion != compareVersion) - return m_moduleVersion > compareVersion ? 1 : -1; -#endif - - return 0; -} - -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) -bool PluginPackage::ensurePluginLoaded() -{ - if (!m_infoIsFromCache) - return m_isLoaded; - - m_quirks = PluginQuirkSet(); - m_name = String(); - m_description = String(); - m_fullMIMEDescription = String(); - m_moduleVersion = 0; - - return fetchInfo(); -} -#endif - -} diff --git a/Source/WebCore/plugins/PluginPackage.h b/Source/WebCore/plugins/PluginPackage.h deleted file mode 100644 index 2431c4b7f..000000000 --- a/Source/WebCore/plugins/PluginPackage.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. - * Copyright (C) 2008 Collabora, Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef PluginPackage_h -#define PluginPackage_h - -#include "FileSystem.h" -#include "PluginQuirkSet.h" -#include "Timer.h" -#if ENABLE(NETSCAPE_PLUGIN_API) -#include "npruntime_internal.h" -#endif -#include <wtf/HashMap.h> -#include <wtf/RefCounted.h> -#include <wtf/text/StringHash.h> -#include <wtf/text/WTFString.h> - -namespace WebCore { - typedef HashMap<String, String> MIMEToDescriptionsMap; - typedef HashMap<String, Vector<String> > MIMEToExtensionsMap; - - class PluginPackage : public RefCounted<PluginPackage> { - public: - ~PluginPackage(); - static PassRefPtr<PluginPackage> createPackage(const String& path, const time_t& lastModified); -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - static PassRefPtr<PluginPackage> createPackageFromCache(const String& path, const time_t& lastModified, const String& name, const String& description, const String& mimeDescription); -#endif - - const String& name() const { return m_name; } - const String& description() const { return m_description; } - const String& path() const { return m_path; } - const String& fileName() const { return m_fileName; } - const String& parentDirectory() const { return m_parentDirectory; } - PlatformModule module() const { return m_module; } - uint16_t NPVersion() const; - time_t lastModified() const { return m_lastModified; } - - const MIMEToDescriptionsMap& mimeToDescriptions() const { return m_mimeToDescriptions; } - const MIMEToExtensionsMap& mimeToExtensions() const { return m_mimeToExtensions; } - - unsigned hash() const; - static bool equal(const PluginPackage& a, const PluginPackage& b); - - bool load(); - void unload(); - void unloadWithoutShutdown(); - - bool isEnabled() const { return m_isEnabled; } - void setEnabled(bool); - -#if ENABLE(NETSCAPE_PLUGIN_API) - const NPPluginFuncs* pluginFuncs() const { return &m_pluginFuncs; } - const NPNetscapeFuncs* browserFuncs() const { return &m_browserFuncs; } -#endif - int compareFileVersion(const PlatformModuleVersion&) const; - int compare(const PluginPackage&) const; - PluginQuirkSet quirks() const { return m_quirks; } - const PlatformModuleVersion& version() const { return m_moduleVersion; } - -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - bool ensurePluginLoaded(); - void setMIMEDescription(const String& mimeDescription); - String fullMIMEDescription() const { return m_fullMIMEDescription;} -#endif - private: - PluginPackage(const String& path, const time_t& lastModified); - - bool fetchInfo(); - bool isPluginBlacklisted(); - void determineQuirks(const String& mimeType); - - void determineModuleVersionFromDescription(); - void initializeBrowserFuncs(); - - bool m_isEnabled; - bool m_isLoaded; - int m_loadCount; - - String m_description; - String m_path; - String m_fileName; - String m_name; - String m_parentDirectory; - - PlatformModuleVersion m_moduleVersion; - - MIMEToDescriptionsMap m_mimeToDescriptions; - MIMEToExtensionsMap m_mimeToExtensions; - - PlatformModule m_module; - time_t m_lastModified; - -#if ENABLE(NETSCAPE_PLUGIN_API) - NPP_ShutdownProcPtr m_NPP_Shutdown; - NPPluginFuncs m_pluginFuncs; - NPNetscapeFuncs m_browserFuncs; -#endif - - void freeLibrarySoon(); - void freeLibraryTimerFired(Timer<PluginPackage>*); - Timer<PluginPackage> m_freeLibraryTimer; - - PluginQuirkSet m_quirks; -#if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) - String m_fullMIMEDescription; - bool m_infoIsFromCache; -#endif - }; - - // FIXME: This is a workaround because PluginPackageHash is broken and may consider keys with different hashes as equal. - struct PluginPackageHashTraits : HashTraits<RefPtr<PluginPackage> > { - static const int minimumTableSize = 64; - }; - - struct PluginPackageHash { - static unsigned hash(const uintptr_t key) { return reinterpret_cast<PluginPackage*>(key)->hash(); } - static unsigned hash(const RefPtr<PluginPackage>& key) { return key->hash(); } - - static bool equal(const uintptr_t a, const uintptr_t b) { return equal(reinterpret_cast<PluginPackage*>(a), reinterpret_cast<PluginPackage*>(b)); } - static bool equal(const RefPtr<PluginPackage>& a, const RefPtr<PluginPackage>& b) { return PluginPackage::equal(*a.get(), *b.get()); } - static const bool safeToCompareToEmptyOrDeleted = false; - }; - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/plugins/PluginPackageNone.cpp b/Source/WebCore/plugins/PluginPackageNone.cpp deleted file mode 100644 index 4fcb0e51a..000000000 --- a/Source/WebCore/plugins/PluginPackageNone.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2008 Kevin Ollivier <kevino@theolliviers.com> All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginPackage.h" - -namespace WebCore { - -bool PluginPackage::fetchInfo() -{ - return false; -} - -bool PluginPackage::load() -{ - return false; -} - -#if ENABLE(NETSCAPE_PLUGIN_API) -uint16_t PluginPackage::NPVersion() const -{ - return 0; -} -#endif - -} diff --git a/Source/WebCore/plugins/PluginQuirkSet.h b/Source/WebCore/plugins/PluginQuirkSet.h deleted file mode 100644 index 7e296dc25..000000000 --- a/Source/WebCore/plugins/PluginQuirkSet.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2008 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef PluginQuirkSet_h -#define PluginQuirkSet_h - - -namespace WebCore { - - enum PluginQuirk { - PluginQuirkWantsMozillaUserAgent = 1 << 0, - PluginQuirkDeferFirstSetWindowCall = 1 << 1, - PluginQuirkThrottleInvalidate = 1 << 2, - PluginQuirkRemoveWindowlessVideoParam = 1 << 3, - PluginQuirkThrottleWMUserPlusOneMessages = 1 << 4, - PluginQuirkDontUnloadPlugin = 1 << 5, - PluginQuirkDontCallWndProcForSameMessageRecursively = 1 << 6, - PluginQuirkHasModalMessageLoop = 1 << 7, - PluginQuirkFlashURLNotifyBug = 1 << 8, - PluginQuirkDontClipToZeroRectWhenScrolling = 1 << 9, - PluginQuirkDontSetNullWindowHandleOnDestroy = 1 << 10, - PluginQuirkDontAllowMultipleInstances = 1 << 11, - PluginQuirkRequiresGtkToolKit = 1 << 12, - PluginQuirkRequiresDefaultScreenDepth = 1 << 13, - PluginQuirkDontCallSetWindowMoreThanOnce = 1 << 14, - PluginQuirkIgnoreRightClickInWindowlessMode = 1 << 15, - PluginQuirkWantsChromeUserAgent = 1 << 16 - }; - - class PluginQuirkSet { - public: - PluginQuirkSet() : m_quirks(0) { } - void add(PluginQuirk quirk) { m_quirks |= quirk; } - bool contains(PluginQuirk quirk) const { return m_quirks & quirk; } - private: - unsigned m_quirks; - }; - -} // namespace WebCore - -#endif // PluginQuirkSet_h diff --git a/Source/WebCore/plugins/PluginStream.cpp b/Source/WebCore/plugins/PluginStream.cpp deleted file mode 100644 index 8b3bd9929..000000000 --- a/Source/WebCore/plugins/PluginStream.cpp +++ /dev/null @@ -1,483 +0,0 @@ -/* - * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. - * Copyright (C) 2008 Collabora, Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginStream.h" - -#include "DocumentLoader.h" -#include "Frame.h" -#include "FrameLoader.h" -#include "PluginDebug.h" -#include "ResourceLoadScheduler.h" -#include "SharedBuffer.h" -#include "SubresourceLoader.h" -#include <wtf/StringExtras.h> -#include <wtf/text/CString.h> -#include <wtf/text/StringBuilder.h> -#include <wtf/text/WTFString.h> - -// We use -2 here because some plugins like to return -1 to indicate error -// and this way we won't clash with them. -static const int WebReasonNone = -2; - -using std::max; -using std::min; - -namespace WebCore { - -typedef HashMap<NPStream*, NPP> StreamMap; -static StreamMap& streams() -{ - static StreamMap staticStreams; - return staticStreams; -} - -PluginStream::PluginStream(PluginStreamClient* client, Frame* frame, const ResourceRequest& resourceRequest, bool sendNotification, void* notifyData, const NPPluginFuncs* pluginFuncs, NPP instance, const PluginQuirkSet& quirks) - : m_resourceRequest(resourceRequest) - , m_client(client) - , m_frame(frame) - , m_notifyData(notifyData) - , m_sendNotification(sendNotification) - , m_streamState(StreamBeforeStarted) - , m_loadManually(false) - , m_delayDeliveryTimer(this, &PluginStream::delayDeliveryTimerFired) - , m_tempFileHandle(invalidPlatformFileHandle) - , m_pluginFuncs(pluginFuncs) - , m_instance(instance) - , m_quirks(quirks) -{ - ASSERT(m_instance); - - m_stream.url = 0; - m_stream.ndata = 0; - m_stream.pdata = 0; - m_stream.end = 0; - m_stream.notifyData = 0; - m_stream.lastmodified = 0; - m_stream.headers = 0; - - streams().add(&m_stream, m_instance); -} - -PluginStream::~PluginStream() -{ - ASSERT(m_streamState != StreamStarted); - ASSERT(!m_loader); - - fastFree((char*)m_stream.url); - - streams().remove(&m_stream); -} - -void PluginStream::start() -{ - ASSERT(!m_loadManually); - m_loader = resourceLoadScheduler()->schedulePluginStreamLoad(m_frame, this, m_resourceRequest); -} - -void PluginStream::stop() -{ - m_streamState = StreamStopped; - - if (m_loadManually) { - ASSERT(!m_loader); - - DocumentLoader* documentLoader = m_frame->loader().activeDocumentLoader(); - ASSERT(documentLoader); - - if (documentLoader->isLoadingMainResource()) - documentLoader->cancelMainResourceLoad(m_frame->loader().cancelledError(m_resourceRequest)); - - return; - } - - if (m_loader) { - m_loader->cancel(); - m_loader = 0; - } - - m_client = 0; -} - -static uint32_t lastModifiedDate(const ResourceResponse& response) -{ - double lastModified = response.lastModified(); - if (!std::isfinite(lastModified)) - return 0; - - return lastModified * 1000; -} - -void PluginStream::startStream() -{ - ASSERT(m_streamState == StreamBeforeStarted); - - const URL& responseURL = m_resourceResponse.url(); - - // Some plugins (Flash) expect that javascript URLs are passed back decoded as this is the - // format used when requesting the URL. - if (protocolIsJavaScript(responseURL)) - m_stream.url = fastStrDup(decodeURLEscapeSequences(responseURL.string()).utf8().data()); - else - m_stream.url = fastStrDup(responseURL.string().utf8().data()); - - CString mimeTypeStr = m_resourceResponse.mimeType().utf8(); - - long long expectedContentLength = m_resourceResponse.expectedContentLength(); - - if (m_resourceResponse.isHTTP()) { - StringBuilder stringBuilder; - String separator = ASCIILiteral(": "); - - String statusLine = "HTTP " + String::number(m_resourceResponse.httpStatusCode()) + " OK\n"; - stringBuilder.append(statusLine); - - HTTPHeaderMap::const_iterator end = m_resourceResponse.httpHeaderFields().end(); - for (HTTPHeaderMap::const_iterator it = m_resourceResponse.httpHeaderFields().begin(); it != end; ++it) { - stringBuilder.append(it->key); - stringBuilder.append(separator); - stringBuilder.append(it->value); - stringBuilder.append('\n'); - } - - m_headers = stringBuilder.toString().utf8(); - - // If the content is encoded (most likely compressed), then don't send its length to the plugin, - // which is only interested in the decoded length, not yet known at the moment. - // <rdar://problem/4470599> tracks a request for -[NSURLResponse expectedContentLength] to incorporate this logic. - String contentEncoding = m_resourceResponse.httpHeaderField("Content-Encoding"); - if (!contentEncoding.isNull() && contentEncoding != "identity") - expectedContentLength = -1; - } - - m_stream.headers = m_headers.data(); - m_stream.pdata = 0; - m_stream.ndata = this; - m_stream.end = max(expectedContentLength, 0LL); - m_stream.lastmodified = lastModifiedDate(m_resourceResponse); - m_stream.notifyData = m_notifyData; - - m_transferMode = NP_NORMAL; - m_offset = 0; - m_reason = WebReasonNone; - - // Protect the stream if destroystream is called from within the newstream handler - RefPtr<PluginStream> protect(this); - - // calling into a plug-in could result in re-entrance if the plug-in yields - // control to the system (rdar://5744899). prevent this by deferring further - // loading while calling into the plug-in. - if (m_loader) - m_loader->setDefersLoading(true); - NPError npErr = m_pluginFuncs->newstream(m_instance, (NPMIMEType)mimeTypeStr.data(), &m_stream, false, &m_transferMode); - if (m_loader) - m_loader->setDefersLoading(false); - - // If the stream was destroyed in the call to newstream we return - if (m_reason != WebReasonNone) - return; - - if (npErr != NPERR_NO_ERROR) { - cancelAndDestroyStream(npErr); - return; - } - - m_streamState = StreamStarted; - - if (m_transferMode == NP_NORMAL) - return; - - m_path = openTemporaryFile("WKP", m_tempFileHandle); - - // Something went wrong, cancel loading the stream - if (!isHandleValid(m_tempFileHandle)) - cancelAndDestroyStream(NPRES_NETWORK_ERR); -} - -NPP PluginStream::ownerForStream(NPStream* stream) -{ - return streams().get(stream); -} - -void PluginStream::cancelAndDestroyStream(NPReason reason) -{ - RefPtr<PluginStream> protect(this); - - destroyStream(reason); - stop(); -} - -void PluginStream::destroyStream(NPReason reason) -{ - m_reason = reason; - if (m_reason != NPRES_DONE) { - // Stop any pending data from being streamed - if (m_deliveryData) - m_deliveryData->resize(0); - } else if (m_deliveryData && m_deliveryData->size() > 0) { - // There is more data to be streamed, don't destroy the stream now. - return; - } - destroyStream(); -} - -void PluginStream::destroyStream() -{ - if (m_streamState == StreamStopped) - return; - - ASSERT(m_reason != WebReasonNone); - ASSERT(!m_deliveryData || m_deliveryData->size() == 0); - - closeFile(m_tempFileHandle); - - bool newStreamCalled = m_stream.ndata; - - // Protect from destruction if: - // NPN_DestroyStream is called from NPP_NewStream or - // PluginStreamClient::streamDidFinishLoading() removes the last reference - RefPtr<PluginStream> protect(this); - - if (newStreamCalled) { - if (m_reason == NPRES_DONE && (m_transferMode == NP_ASFILE || m_transferMode == NP_ASFILEONLY)) { - ASSERT(!m_path.isNull()); - - if (m_loader) - m_loader->setDefersLoading(true); - m_pluginFuncs->asfile(m_instance, &m_stream, m_path.utf8().data()); - if (m_loader) - m_loader->setDefersLoading(false); - } - - if (m_streamState != StreamBeforeStarted) { - if (m_loader) - m_loader->setDefersLoading(true); - - NPError npErr = m_pluginFuncs->destroystream(m_instance, &m_stream, m_reason); - - if (m_loader) - m_loader->setDefersLoading(false); - - LOG_NPERROR(npErr); - } - - m_stream.ndata = 0; - } - - if (m_sendNotification) { - // Flash 9 can dereference null if we call NPP_URLNotify without first calling NPP_NewStream - // for requests made with NPN_PostURLNotify; see <rdar://5588807> - if (m_loader) - m_loader->setDefersLoading(true); - if (!newStreamCalled && m_quirks.contains(PluginQuirkFlashURLNotifyBug) && - equalIgnoringCase(m_resourceRequest.httpMethod(), "POST")) { - m_transferMode = NP_NORMAL; - m_stream.url = ""; - m_stream.notifyData = m_notifyData; - - static char emptyMimeType[] = ""; - m_pluginFuncs->newstream(m_instance, emptyMimeType, &m_stream, false, &m_transferMode); - m_pluginFuncs->destroystream(m_instance, &m_stream, m_reason); - - // in successful requests, the URL is dynamically allocated and freed in our - // destructor, so reset it to 0 - m_stream.url = 0; - } - m_pluginFuncs->urlnotify(m_instance, m_resourceRequest.url().string().utf8().data(), m_reason, m_notifyData); - if (m_loader) - m_loader->setDefersLoading(false); - } - - m_streamState = StreamStopped; - - if (!m_loadManually && m_client) - m_client->streamDidFinishLoading(this); - - if (!m_path.isNull()) - deleteFile(m_path); -} - -void PluginStream::delayDeliveryTimerFired(Timer<PluginStream>* timer) -{ - ASSERT_UNUSED(timer, timer == &m_delayDeliveryTimer); - - deliverData(); -} - -void PluginStream::deliverData() -{ - ASSERT(m_deliveryData); - - if (m_streamState == StreamStopped) - // FIXME: We should cancel our job in the SubresourceLoader on error so we don't reach this case - return; - - ASSERT(m_streamState != StreamBeforeStarted); - - if (!m_stream.ndata || m_deliveryData->size() == 0) - return; - - int32_t totalBytes = m_deliveryData->size(); - int32_t totalBytesDelivered = 0; - - if (m_loader) - m_loader->setDefersLoading(true); - while (totalBytesDelivered < totalBytes) { - int32_t deliveryBytes = m_pluginFuncs->writeready(m_instance, &m_stream); - - if (deliveryBytes <= 0) { - m_delayDeliveryTimer.startOneShot(0); - break; - } else { - deliveryBytes = min(deliveryBytes, totalBytes - totalBytesDelivered); - int32_t dataLength = deliveryBytes; - char* data = m_deliveryData->data() + totalBytesDelivered; - - // Write the data - deliveryBytes = m_pluginFuncs->write(m_instance, &m_stream, m_offset, dataLength, (void*)data); - if (deliveryBytes < 0) { - LOG_PLUGIN_NET_ERROR(); - if (m_loader) - m_loader->setDefersLoading(false); - cancelAndDestroyStream(NPRES_NETWORK_ERR); - return; - } - deliveryBytes = min(deliveryBytes, dataLength); - m_offset += deliveryBytes; - totalBytesDelivered += deliveryBytes; - } - } - if (m_loader) - m_loader->setDefersLoading(false); - - if (totalBytesDelivered > 0) { - if (totalBytesDelivered < totalBytes) { - int remainingBytes = totalBytes - totalBytesDelivered; - memmove(m_deliveryData->data(), m_deliveryData->data() + totalBytesDelivered, remainingBytes); - m_deliveryData->resize(remainingBytes); - } else { - m_deliveryData->resize(0); - if (m_reason != WebReasonNone) - destroyStream(); - } - } -} - -void PluginStream::sendJavaScriptStream(const URL& requestURL, const CString& resultString) -{ - didReceiveResponse(0, ResourceResponse(requestURL, "text/plain", resultString.length(), "", "")); - - if (m_streamState == StreamStopped) - return; - - if (!resultString.isNull()) { - didReceiveData(0, resultString.data(), resultString.length()); - if (m_streamState == StreamStopped) - return; - } - - m_loader = 0; - - destroyStream(resultString.isNull() ? NPRES_NETWORK_ERR : NPRES_DONE); -} - -void PluginStream::didReceiveResponse(NetscapePlugInStreamLoader* loader, const ResourceResponse& response) -{ - ASSERT_UNUSED(loader, loader == m_loader); - ASSERT(m_streamState == StreamBeforeStarted); - - m_resourceResponse = response; - - startStream(); -} - -void PluginStream::didReceiveData(NetscapePlugInStreamLoader* loader, const char* data, int length) -{ - ASSERT_UNUSED(loader, loader == m_loader); - ASSERT(m_streamState == StreamStarted); - - // If the plug-in cancels the stream in deliverData it could be deleted, - // so protect it here. - RefPtr<PluginStream> protect(this); - - if (m_transferMode != NP_ASFILEONLY) { - if (!m_deliveryData) - m_deliveryData = adoptPtr(new Vector<char>); - - int oldSize = m_deliveryData->size(); - m_deliveryData->resize(oldSize + length); - memcpy(m_deliveryData->data() + oldSize, data, length); - - deliverData(); - } - - if (m_streamState != StreamStopped && isHandleValid(m_tempFileHandle)) { - int bytesWritten = writeToFile(m_tempFileHandle, data, length); - if (bytesWritten != length) - cancelAndDestroyStream(NPRES_NETWORK_ERR); - } -} - -void PluginStream::didFail(NetscapePlugInStreamLoader* loader, const ResourceError&) -{ - ASSERT_UNUSED(loader, loader == m_loader); - - LOG_PLUGIN_NET_ERROR(); - - // destroyStream can result in our being deleted - RefPtr<PluginStream> protect(this); - - destroyStream(NPRES_NETWORK_ERR); - - m_loader = 0; -} - -void PluginStream::didFinishLoading(NetscapePlugInStreamLoader* loader) -{ - ASSERT_UNUSED(loader, loader == m_loader); - ASSERT(m_streamState == StreamStarted); - - // destroyStream can result in our being deleted - RefPtr<PluginStream> protect(this); - - destroyStream(NPRES_DONE); - - m_loader = 0; -} - -bool PluginStream::wantsAllStreams() const -{ - if (!m_pluginFuncs->getvalue) - return false; - - void* result = 0; - if (m_pluginFuncs->getvalue(m_instance, NPPVpluginWantsAllNetworkStreams, &result) != NPERR_NO_ERROR) - return false; - - return result != 0; -} - -} diff --git a/Source/WebCore/plugins/PluginStream.h b/Source/WebCore/plugins/PluginStream.h deleted file mode 100644 index 7c04866a8..000000000 --- a/Source/WebCore/plugins/PluginStream.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. - * Copyright (C) 2008 Collabora, Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef PluginStream_h -#define PluginStream_h - -#include "FileSystem.h" -#include "URL.h" -#include "NetscapePlugInStreamLoader.h" -#include "PluginQuirkSet.h" -#include "ResourceRequest.h" -#include "ResourceResponse.h" -#include "Timer.h" -#include "npruntime_internal.h" -#include <wtf/HashMap.h> -#include <wtf/OwnPtr.h> -#include <wtf/RefCounted.h> -#include <wtf/Vector.h> -#include <wtf/text/CString.h> -#include <wtf/text/StringHash.h> -#include <wtf/text/WTFString.h> - -namespace WebCore { - class Frame; - class PluginStream; - - enum PluginStreamState { StreamBeforeStarted, StreamStarted, StreamStopped }; - - class PluginStreamClient { - public: - virtual ~PluginStreamClient() {} - virtual void streamDidFinishLoading(PluginStream*) {} - }; - - class PluginStream : public RefCounted<PluginStream>, private NetscapePlugInStreamLoaderClient { - public: - static PassRefPtr<PluginStream> create(PluginStreamClient* client, Frame* frame, const ResourceRequest& request, bool sendNotification, void* notifyData, const NPPluginFuncs* functions, NPP instance, const PluginQuirkSet& quirks) - { - return adoptRef(new PluginStream(client, frame, request, sendNotification, notifyData, functions, instance, quirks)); - } - virtual ~PluginStream(); - - void start(); - void stop(); - - void startStream(); - - void setLoadManually(bool loadManually) { m_loadManually = loadManually; } - - void sendJavaScriptStream(const URL& requestURL, const WTF::CString& resultString); - void cancelAndDestroyStream(NPReason); - - static NPP ownerForStream(NPStream*); - - // NetscapePlugInStreamLoaderClient - virtual void didReceiveResponse(NetscapePlugInStreamLoader*, const ResourceResponse&); - virtual void didReceiveData(NetscapePlugInStreamLoader*, const char*, int); - virtual void didFail(NetscapePlugInStreamLoader*, const ResourceError&); - virtual void didFinishLoading(NetscapePlugInStreamLoader*); - virtual bool wantsAllStreams() const; - - private: - PluginStream(PluginStreamClient*, Frame*, const ResourceRequest&, bool sendNotification, void* notifyData, const NPPluginFuncs*, NPP instance, const PluginQuirkSet&); - - void deliverData(); - void destroyStream(NPReason); - void destroyStream(); - - ResourceRequest m_resourceRequest; - ResourceResponse m_resourceResponse; - - PluginStreamClient* m_client; - Frame* m_frame; - RefPtr<NetscapePlugInStreamLoader> m_loader; - void* m_notifyData; - bool m_sendNotification; - PluginStreamState m_streamState; - bool m_loadManually; - - Timer<PluginStream> m_delayDeliveryTimer; - void delayDeliveryTimerFired(Timer<PluginStream>*); - - OwnPtr< Vector<char> > m_deliveryData; - - PlatformFileHandle m_tempFileHandle; - - const NPPluginFuncs* m_pluginFuncs; - NPP m_instance; - uint16_t m_transferMode; - int32_t m_offset; - CString m_headers; - String m_path; - NPReason m_reason; - NPStream m_stream; - PluginQuirkSet m_quirks; - }; - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/plugins/PluginView.cpp b/Source/WebCore/plugins/PluginView.cpp deleted file mode 100644 index 33c0f3d58..000000000 --- a/Source/WebCore/plugins/PluginView.cpp +++ /dev/null @@ -1,1496 +0,0 @@ -/* - * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved. - * Copyright (C) 2008 Collabora Ltd. All rights reserved. - * Copyright (C) 2010 Girish Ramakrishnan <girish@forwardbias.in> - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginView.h" - -#include "BridgeJSC.h" -#include "Chrome.h" -#include "CookieJar.h" -#include "Document.h" -#include "DocumentLoader.h" -#include "Element.h" -#include "FocusController.h" -#include "Frame.h" -#include "FrameLoadRequest.h" -#include "FrameLoader.h" -#include "FrameLoaderClient.h" -#include "FrameTree.h" -#include "FrameView.h" -#include "GraphicsContext.h" -#include "HTMLNames.h" -#include "HTMLPlugInElement.h" -#include "Image.h" -#include "JSDOMBinding.h" -#include "JSDOMWindow.h" -#include "KeyboardEvent.h" -#include "MIMETypeRegistry.h" -#include "MouseEvent.h" -#include "NotImplemented.h" -#include "Page.h" -#include "PlatformMouseEvent.h" -#include "PluginDatabase.h" -#include "PluginDebug.h" -#include "PluginMainThreadScheduler.h" -#include "PluginPackage.h" -#include "ProxyServer.h" -#include "RenderBox.h" -#include "RenderObject.h" -#include "ScriptController.h" -#include "SecurityOrigin.h" -#include "Settings.h" -#include "UserGestureIndicator.h" -#include "WheelEvent.h" -#include "c_instance.h" -#include "npruntime_impl.h" -#include "runtime_root.h" -#include <bindings/ScriptValue.h> -#include <runtime/JSCJSValue.h> -#include <runtime/JSLock.h> -#include <wtf/ASCIICType.h> -#include <wtf/text/WTFString.h> - -#if OS(WINDOWS) && ENABLE(NETSCAPE_PLUGIN_API) -#include "PluginMessageThrottlerWin.h" -#endif - -using JSC::ExecState; -using JSC::JSLock; -using JSC::JSObject; -using JSC::JSValue; - -#if ENABLE(NETSCAPE_PLUGIN_API) - -using std::min; - -using namespace WTF; - -namespace WebCore { - -using namespace HTMLNames; - -static int s_callingPlugin; - -typedef HashMap<NPP, PluginView*> InstanceMap; - -static InstanceMap& instanceMap() -{ - static InstanceMap& map = *new InstanceMap; - return map; -} - -static String scriptStringIfJavaScriptURL(const URL& url) -{ - if (!protocolIsJavaScript(url)) - return String(); - - // This returns an unescaped string - return decodeURLEscapeSequences(url.string().substring(11)); -} - -PluginView* PluginView::s_currentPluginView = 0; - -void PluginView::popPopupsStateTimerFired(Timer<PluginView>*) -{ - popPopupsEnabledState(); -} - -IntRect PluginView::windowClipRect() const -{ - // Start by clipping to our bounds. - IntRect clipRect(m_windowRect); - - // Take our element and get the clip rect from the enclosing layer and frame view. - FrameView* parentView = m_element->document().view(); - clipRect.intersect(parentView->windowClipRectForFrameOwner(m_element, true)); - - return clipRect; -} - -void PluginView::setFrameRect(const IntRect& rect) -{ - if (m_element->document().printing()) - return; - - if (rect != frameRect()) - Widget::setFrameRect(rect); - - updatePluginWidget(); - -#if OS(WINDOWS) - // On Windows always call plugin to change geometry. - setNPWindowRect(rect); -#elif defined(XP_UNIX) - // On Unix, multiple calls to setNPWindow() in windowed mode causes Flash to crash - if (m_mode == NP_FULL || !m_isWindowed) - setNPWindowRect(rect); -#endif -} - -void PluginView::frameRectsChanged() -{ - updatePluginWidget(); -} - -void PluginView::clipRectChanged() -{ - updatePluginWidget(); -} - -void PluginView::handleEvent(Event* event) -{ - if (!m_plugin || m_isWindowed) - return; - - // Protect the plug-in from deletion while dispatching the event. - RefPtr<PluginView> protect(this); - - if (event->isMouseEvent()) - handleMouseEvent(static_cast<MouseEvent*>(event)); - else if (event->isKeyboardEvent()) - handleKeyboardEvent(static_cast<KeyboardEvent*>(event)); -#if defined(XP_MACOSX) - else if (event->type() == eventNames().wheelEvent || event->type() == eventNames().mousewheelEvent) - handleWheelEvent(static_cast<WheelEvent*>(event)); -#endif - else if (event->type() == eventNames().contextmenuEvent) - event->setDefaultHandled(); // We don't know if the plug-in has handled mousedown event by displaying a context menu, so we never want WebKit to show a default one. -#if defined(XP_UNIX) && ENABLE(NETSCAPE_PLUGIN_API) - else if (event->type() == eventNames().focusoutEvent) - handleFocusOutEvent(); - else if (event->type() == eventNames().focusinEvent) - handleFocusInEvent(); -#endif -} - -void PluginView::init() -{ - if (m_haveInitialized) - return; - - m_haveInitialized = true; - - if (!m_plugin) { - ASSERT(m_status == PluginStatusCanNotFindPlugin); - return; - } - - LOG(Plugins, "PluginView::init(): Initializing plug-in '%s'", m_plugin->name().utf8().data()); - - if (!m_plugin->load()) { - m_plugin = 0; - m_status = PluginStatusCanNotLoadPlugin; - return; - } - - if (!startOrAddToUnstartedList()) { - m_status = PluginStatusCanNotLoadPlugin; - return; - } - - m_status = PluginStatusLoadedSuccessfully; -} - -bool PluginView::startOrAddToUnstartedList() -{ - if (!m_parentFrame->page()) - return false; - - // We only delay starting the plug-in if we're going to kick off the load - // ourselves. Otherwise, the loader will try to deliver data before we've - // started the plug-in. - if (!m_loadManually && !m_parentFrame->page()->canStartMedia()) { - m_parentFrame->document()->addMediaCanStartListener(this); - m_isWaitingToStart = true; - return true; - } - - return start(); -} - -bool PluginView::start() -{ - if (m_isStarted) - return false; - - m_isWaitingToStart = false; - - PluginMainThreadScheduler::scheduler().registerPlugin(m_instance); - - ASSERT(m_plugin); - ASSERT(m_plugin->pluginFuncs()->newp); - - NPError npErr; - { - PluginView::setCurrentPluginView(this); - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - setCallingPlugin(true); - npErr = m_plugin->pluginFuncs()->newp((NPMIMEType)m_mimeType.utf8().data(), m_instance, m_mode, m_paramCount, m_paramNames, m_paramValues, NULL); - setCallingPlugin(false); - LOG_NPERROR(npErr); - PluginView::setCurrentPluginView(0); - } - - if (npErr != NPERR_NO_ERROR) { - m_status = PluginStatusCanNotLoadPlugin; - PluginMainThreadScheduler::scheduler().unregisterPlugin(m_instance); - return false; - } - - m_isStarted = true; - - if (!m_url.isEmpty() && !m_loadManually) { - FrameLoadRequest frameLoadRequest(m_parentFrame->document()->securityOrigin()); - frameLoadRequest.resourceRequest().setHTTPMethod("GET"); - frameLoadRequest.resourceRequest().setURL(m_url); - load(frameLoadRequest, false, 0); - } - - m_status = PluginStatusLoadedSuccessfully; - - if (!platformStart()) - m_status = PluginStatusCanNotLoadPlugin; - - if (m_status != PluginStatusLoadedSuccessfully) - return false; - - return true; -} - -void PluginView::mediaCanStart() -{ - ASSERT(!m_isStarted); - if (!start()) - parentFrame()->loader().client().dispatchDidFailToStartPlugin(this); -} - -PluginView::~PluginView() -{ - LOG(Plugins, "PluginView::~PluginView()"); - - ASSERT(!m_lifeSupportTimer.isActive()); - - // If we failed to find the plug-in, we'll return early in our constructor, and - // m_instance will be 0. - if (m_instance) - instanceMap().remove(m_instance); - - if (m_isWaitingToStart) - m_parentFrame->document()->removeMediaCanStartListener(this); - - stop(); - - freeStringArray(m_paramNames, m_paramCount); - freeStringArray(m_paramValues, m_paramCount); - - platformDestroy(); - - m_parentFrame->script().cleanupScriptObjectsForPlugin(this); - - if (m_plugin && !(m_plugin->quirks().contains(PluginQuirkDontUnloadPlugin))) - m_plugin->unload(); -} - -void PluginView::stop() -{ - if (!m_isStarted) - return; - - LOG(Plugins, "PluginView::stop(): Stopping plug-in '%s'", m_plugin->name().utf8().data()); - - HashSet<RefPtr<PluginStream> > streams = m_streams; - HashSet<RefPtr<PluginStream> >::iterator end = streams.end(); - for (HashSet<RefPtr<PluginStream> >::iterator it = streams.begin(); it != end; ++it) { - (*it)->stop(); - disconnectStream((*it).get()); - } - - ASSERT(m_streams.isEmpty()); - - m_isStarted = false; - - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - -#if ENABLE(NETSCAPE_PLUGIN_API) -#if defined(XP_WIN) && !PLATFORM(GTK) - // Unsubclass the window - if (m_isWindowed) { -#if OS(WINCE) - WNDPROC currentWndProc = (WNDPROC)GetWindowLong(platformPluginWidget(), GWL_WNDPROC); - - if (currentWndProc == PluginViewWndProc) - SetWindowLong(platformPluginWidget(), GWL_WNDPROC, (LONG)m_pluginWndProc); -#else - WNDPROC currentWndProc = (WNDPROC)GetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC); - - if (currentWndProc == PluginViewWndProc) - SetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC, (LONG_PTR)m_pluginWndProc); -#endif - } -#endif // !defined(XP_WIN) || PLATFORM(GTK) -#endif // ENABLE(NETSCAPE_PLUGIN_API) - -#if !defined(XP_MACOSX) - // Clear the window - m_npWindow.window = 0; - - if (m_plugin->pluginFuncs()->setwindow && !m_plugin->quirks().contains(PluginQuirkDontSetNullWindowHandleOnDestroy)) { - PluginView::setCurrentPluginView(this); - setCallingPlugin(true); - m_plugin->pluginFuncs()->setwindow(m_instance, &m_npWindow); - setCallingPlugin(false); - PluginView::setCurrentPluginView(0); - } - -#ifdef XP_UNIX - delete static_cast<NPSetWindowCallbackStruct*>(m_npWindow.ws_info); - m_npWindow.ws_info = 0; -#endif - -#endif // !defined(XP_MACOSX) - - PluginMainThreadScheduler::scheduler().unregisterPlugin(m_instance); - - NPSavedData* savedData = 0; - PluginView::setCurrentPluginView(this); - setCallingPlugin(true); - NPError npErr = m_plugin->pluginFuncs()->destroy(m_instance, &savedData); - setCallingPlugin(false); - LOG_NPERROR(npErr); - PluginView::setCurrentPluginView(0); - -#if ENABLE(NETSCAPE_PLUGIN_API) - if (savedData) { - // TODO: Actually save this data instead of just discarding it - if (savedData->buf) - m_plugin->browserFuncs()->memfree(savedData->buf); - m_plugin->browserFuncs()->memfree(savedData); - } -#endif - - m_instance->pdata = 0; -} - -void PluginView::setCurrentPluginView(PluginView* pluginView) -{ - s_currentPluginView = pluginView; -} - -PluginView* PluginView::currentPluginView() -{ - return s_currentPluginView; -} - -static char* createUTF8String(const String& str) -{ - CString cstr = str.utf8(); - char* result = reinterpret_cast<char*>(fastMalloc(cstr.length() + 1)); - - strncpy(result, cstr.data(), cstr.length() + 1); - - return result; -} - -void PluginView::performRequest(PluginRequest* request) -{ - if (!m_isStarted) - return; - - // don't let a plugin start any loads if it is no longer part of a document that is being - // displayed unless the loads are in the same frame as the plugin. - const String& targetFrameName = request->frameLoadRequest().frameName(); - if (m_parentFrame->loader().documentLoader() != m_parentFrame->loader().activeDocumentLoader() && (targetFrameName.isNull() || m_parentFrame->tree().find(targetFrameName) != m_parentFrame)) - return; - - URL requestURL = request->frameLoadRequest().resourceRequest().url(); - String jsString = scriptStringIfJavaScriptURL(requestURL); - - UserGestureIndicator gestureIndicator(request->shouldAllowPopups() ? DefinitelyProcessingUserGesture : PossiblyProcessingUserGesture); - - if (jsString.isNull()) { - // if this is not a targeted request, create a stream for it. otherwise, - // just pass it off to the loader - if (targetFrameName.isEmpty()) { - RefPtr<PluginStream> stream = PluginStream::create(this, m_parentFrame.get(), request->frameLoadRequest().resourceRequest(), request->sendNotification(), request->notifyData(), plugin()->pluginFuncs(), instance(), m_plugin->quirks()); - m_streams.add(stream); - stream->start(); - } else { - // If the target frame is our frame, we could destroy the - // PluginView, so we protect it. <rdar://problem/6991251> - RefPtr<PluginView> protect(this); - - FrameLoadRequest frameRequest(m_parentFrame.get(), request->frameLoadRequest().resourceRequest()); - frameRequest.setFrameName(targetFrameName); - frameRequest.setShouldCheckNewWindowPolicy(true); - m_parentFrame->loader().load(frameRequest); - - // FIXME: <rdar://problem/4807469> This should be sent when the document has finished loading - if (request->sendNotification()) { - PluginView::setCurrentPluginView(this); - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - setCallingPlugin(true); - m_plugin->pluginFuncs()->urlnotify(m_instance, requestURL.string().utf8().data(), NPRES_DONE, request->notifyData()); - setCallingPlugin(false); - PluginView::setCurrentPluginView(0); - } - } - return; - } - - // Targeted JavaScript requests are only allowed on the frame that contains the JavaScript plugin - // and this has been made sure in ::load. - ASSERT(targetFrameName.isEmpty() || m_parentFrame->tree().find(targetFrameName) == m_parentFrame); - - // Executing a script can cause the plugin view to be destroyed, so we keep a reference to it. - RefPtr<PluginView> protector(this); - Deprecated::ScriptValue result = m_parentFrame->script().executeScript(jsString, request->shouldAllowPopups()); - - if (targetFrameName.isNull()) { - String resultString; - - JSC::ExecState* scriptState = m_parentFrame->script().globalObject(pluginWorld())->globalExec(); - CString cstr; - if (result.getString(scriptState, resultString)) - cstr = resultString.utf8(); - - RefPtr<PluginStream> stream = PluginStream::create(this, m_parentFrame.get(), request->frameLoadRequest().resourceRequest(), request->sendNotification(), request->notifyData(), plugin()->pluginFuncs(), instance(), m_plugin->quirks()); - m_streams.add(stream); - stream->sendJavaScriptStream(requestURL, cstr); - } -} - -void PluginView::requestTimerFired(Timer<PluginView>* timer) -{ - ASSERT_UNUSED(timer, timer == &m_requestTimer); - ASSERT(!m_requests.isEmpty()); - ASSERT(!m_isJavaScriptPaused); - - OwnPtr<PluginRequest> request = m_requests[0].release(); - m_requests.remove(0); - - // Schedule a new request before calling performRequest since the call to - // performRequest can cause the plugin view to be deleted. - if (!m_requests.isEmpty()) - m_requestTimer.startOneShot(0); - - performRequest(request.get()); -} - -void PluginView::scheduleRequest(PassOwnPtr<PluginRequest> request) -{ - m_requests.append(request); - - if (!m_isJavaScriptPaused) - m_requestTimer.startOneShot(0); -} - -NPError PluginView::load(const FrameLoadRequest& frameLoadRequest, bool sendNotification, void* notifyData) -{ - ASSERT(frameLoadRequest.resourceRequest().httpMethod() == "GET" || frameLoadRequest.resourceRequest().httpMethod() == "POST"); - - URL url = frameLoadRequest.resourceRequest().url(); - - if (url.isEmpty()) - return NPERR_INVALID_URL; - - // Don't allow requests to be made when the document loader is stopping all loaders. - DocumentLoader* loader = m_parentFrame->loader().documentLoader(); - if (!loader || loader->isStopping()) - return NPERR_GENERIC_ERROR; - - const String& targetFrameName = frameLoadRequest.frameName(); - String jsString = scriptStringIfJavaScriptURL(url); - - if (!jsString.isNull()) { - // Return NPERR_GENERIC_ERROR if JS is disabled. This is what Mozilla does. - if (!m_parentFrame->script().canExecuteScripts(NotAboutToExecuteScript)) - return NPERR_GENERIC_ERROR; - - // For security reasons, only allow JS requests to be made on the frame that contains the plug-in. - if (!targetFrameName.isNull() && m_parentFrame->tree().find(targetFrameName) != m_parentFrame) - return NPERR_INVALID_PARAM; - } else if (!m_parentFrame->document()->securityOrigin()->canDisplay(url)) - return NPERR_GENERIC_ERROR; - - scheduleRequest(adoptPtr(new PluginRequest(frameLoadRequest, sendNotification, notifyData, arePopupsAllowed()))); - - return NPERR_NO_ERROR; -} - -static URL makeURL(const URL& baseURL, const char* relativeURLString) -{ - String urlString = relativeURLString; - - // Strip return characters. - urlString.replaceWithLiteral('\n', ""); - urlString.replaceWithLiteral('\r', ""); - - return URL(baseURL, urlString); -} - -NPError PluginView::getURLNotify(const char* url, const char* target, void* notifyData) -{ - FrameLoadRequest frameLoadRequest(m_parentFrame->document()->securityOrigin()); - - frameLoadRequest.setFrameName(target); - frameLoadRequest.resourceRequest().setHTTPMethod("GET"); - frameLoadRequest.resourceRequest().setURL(makeURL(m_parentFrame->document()->baseURL(), url)); - - return load(frameLoadRequest, true, notifyData); -} - -NPError PluginView::getURL(const char* url, const char* target) -{ - FrameLoadRequest frameLoadRequest(m_parentFrame->document()->securityOrigin()); - - frameLoadRequest.setFrameName(target); - frameLoadRequest.resourceRequest().setHTTPMethod("GET"); - frameLoadRequest.resourceRequest().setURL(makeURL(m_parentFrame->document()->baseURL(), url)); - - return load(frameLoadRequest, false, 0); -} - -NPError PluginView::postURLNotify(const char* url, const char* target, uint32_t len, const char* buf, NPBool file, void* notifyData) -{ - return handlePost(url, target, len, buf, file, notifyData, true, true); -} - -NPError PluginView::postURL(const char* url, const char* target, uint32_t len, const char* buf, NPBool file) -{ - // As documented, only allow headers to be specified via NPP_PostURL when using a file. - return handlePost(url, target, len, buf, file, 0, false, file); -} - -NPError PluginView::newStream(NPMIMEType, const char* /* target */, NPStream**) -{ - notImplemented(); - // Unsupported - return NPERR_GENERIC_ERROR; -} - -int32_t PluginView::write(NPStream*, int32_t /* len */, void* /* buffer */) -{ - notImplemented(); - // Unsupported - return -1; -} - -NPError PluginView::destroyStream(NPStream* stream, NPReason reason) -{ - if (!stream || PluginStream::ownerForStream(stream) != m_instance) - return NPERR_INVALID_INSTANCE_ERROR; - - PluginStream* browserStream = static_cast<PluginStream*>(stream->ndata); - browserStream->cancelAndDestroyStream(reason); - - return NPERR_NO_ERROR; -} - -void PluginView::status(const char* message) -{ - if (Page* page = m_parentFrame->page()) - page->chrome().setStatusbarText(m_parentFrame.get(), String::fromUTF8(message)); -} - -NPError PluginView::setValue(NPPVariable variable, void* value) -{ - LOG(Plugins, "PluginView::setValue(%s): ", prettyNameForNPPVariable(variable, value).data()); - - switch (variable) { - case NPPVpluginWindowBool: - m_isWindowed = value; - return NPERR_NO_ERROR; - case NPPVpluginTransparentBool: - m_isTransparent = value; - return NPERR_NO_ERROR; -#if defined(XP_MACOSX) - case NPPVpluginDrawingModel: { - // Can only set drawing model inside NPP_New() - if (this != currentPluginView()) - return NPERR_GENERIC_ERROR; - - NPDrawingModel newDrawingModel = NPDrawingModel(uintptr_t(value)); - switch (newDrawingModel) { - case NPDrawingModelCoreGraphics: - return NPERR_NO_ERROR; - case NPDrawingModelCoreAnimation: - default: - LOG(Plugins, "Plugin asked for unsupported drawing model: %s", - prettyNameForDrawingModel(newDrawingModel)); - return NPERR_GENERIC_ERROR; - } - } - - case NPPVpluginEventModel: { - // Can only set event model inside NPP_New() - if (this != currentPluginView()) - return NPERR_GENERIC_ERROR; - - NPEventModel newEventModel = NPEventModel(uintptr_t(value)); - switch (newEventModel) { - case NPEventModelCocoa: - return NPERR_NO_ERROR; - default: - LOG(Plugins, "Plugin asked for unsupported event model: %s", - prettyNameForEventModel(newEventModel)); - return NPERR_GENERIC_ERROR; - } - } -#endif // defined(XP_MACOSX) - - default: - notImplemented(); - return NPERR_GENERIC_ERROR; - } -} - -void PluginView::invalidateTimerFired(Timer<PluginView>* timer) -{ - ASSERT_UNUSED(timer, timer == &m_invalidateTimer); - - for (unsigned i = 0; i < m_invalidRects.size(); i++) - invalidateRect(m_invalidRects[i]); - m_invalidRects.clear(); -} - - -void PluginView::pushPopupsEnabledState(bool state) -{ - m_popupStateStack.append(state); -} - -void PluginView::popPopupsEnabledState() -{ - m_popupStateStack.removeLast(); -} - -bool PluginView::arePopupsAllowed() const -{ - if (!m_popupStateStack.isEmpty()) - return m_popupStateStack.last(); - - return false; -} - -void PluginView::setJavaScriptPaused(bool paused) -{ - if (m_isJavaScriptPaused == paused) - return; - m_isJavaScriptPaused = paused; - - if (m_isJavaScriptPaused) - m_requestTimer.stop(); - else if (!m_requests.isEmpty()) - m_requestTimer.startOneShot(0); -} - -#if ENABLE(NETSCAPE_PLUGIN_API) -NPObject* PluginView::npObject() -{ - NPObject* object = 0; - - if (!m_isStarted || !m_plugin || !m_plugin->pluginFuncs()->getvalue) - return 0; - - // On Windows, calling Java's NPN_GetValue can allow the message loop to - // run, allowing loading to take place or JavaScript to run. Protect the - // PluginView from destruction. <rdar://problem/6978804> - RefPtr<PluginView> protect(this); - - NPError npErr; - { - PluginView::setCurrentPluginView(this); - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - setCallingPlugin(true); - npErr = m_plugin->pluginFuncs()->getvalue(m_instance, NPPVpluginScriptableNPObject, &object); - setCallingPlugin(false); - PluginView::setCurrentPluginView(0); - } - - if (npErr != NPERR_NO_ERROR) - return 0; - - return object; -} -#endif - -PassRefPtr<JSC::Bindings::Instance> PluginView::bindingInstance() -{ -#if ENABLE(NETSCAPE_PLUGIN_API) - NPObject* object = npObject(); - if (!object) - return 0; - - if (hasOneRef()) { - // The renderer for the PluginView was destroyed during the above call, and - // the PluginView will be destroyed when this function returns, so we - // return null. - return 0; - } - - RefPtr<JSC::Bindings::RootObject> root = m_parentFrame->script().createRootObject(this); - RefPtr<JSC::Bindings::Instance> instance = JSC::Bindings::CInstance::create(object, root.release()); - - _NPN_ReleaseObject(object); - - return instance.release(); -#else - return 0; -#endif -} - -void PluginView::disconnectStream(PluginStream* stream) -{ - ASSERT(m_streams.contains(stream)); - - m_streams.remove(stream); -} - -void PluginView::setParameters(const Vector<String>& paramNames, const Vector<String>& paramValues) -{ - ASSERT(paramNames.size() == paramValues.size()); - - unsigned size = paramNames.size(); - unsigned paramCount = 0; - - m_paramNames = reinterpret_cast<char**>(fastMalloc(sizeof(char*) * size)); - m_paramValues = reinterpret_cast<char**>(fastMalloc(sizeof(char*) * size)); - - for (unsigned i = 0; i < size; i++) { - if (m_plugin->quirks().contains(PluginQuirkRemoveWindowlessVideoParam) && equalIgnoringCase(paramNames[i], "windowlessvideo")) - continue; - - if (paramNames[i] == "pluginspage") - m_pluginsPage = paramValues[i]; - - m_paramNames[paramCount] = createUTF8String(paramNames[i]); - m_paramValues[paramCount] = createUTF8String(paramValues[i]); - - paramCount++; - } - - m_paramCount = paramCount; -} - -PluginView::PluginView(Frame* parentFrame, const IntSize& size, PluginPackage* plugin, HTMLPlugInElement* element, const URL& url, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType, bool loadManually) - : m_parentFrame(parentFrame) - , m_plugin(plugin) - , m_element(element) - , m_isStarted(false) - , m_url(url) - , m_status(PluginStatusLoadedSuccessfully) - , m_requestTimer(this, &PluginView::requestTimerFired) - , m_invalidateTimer(this, &PluginView::invalidateTimerFired) - , m_popPopupsStateTimer(this, &PluginView::popPopupsStateTimerFired) - , m_lifeSupportTimer(this, &PluginView::lifeSupportTimerFired) - , m_mode(loadManually ? NP_FULL : NP_EMBED) - , m_paramNames(0) - , m_paramValues(0) - , m_mimeType(mimeType) - , m_instance(0) -#if defined(XP_MACOSX) - , m_isWindowed(false) - , m_updatedCocoaTextInputRequested(false) - , m_keyDownSent(false) - , m_disregardKeyUpCounter(0) -#else - , m_isWindowed(true) -#endif - , m_isTransparent(false) - , m_haveInitialized(false) - , m_isWaitingToStart(false) -#if defined(XP_UNIX) - , m_needsXEmbed(false) -#endif -#if OS(WINDOWS) && ENABLE(NETSCAPE_PLUGIN_API) - , m_pluginWndProc(0) - , m_lastMessage(0) - , m_isCallingPluginWndProc(false) - , m_wmPrintHDC(0) - , m_haveUpdatedPluginWidget(false) -#endif -#if PLATFORM(EFL) - , m_window(0) -#endif -#if defined(XP_MACOSX) - , m_contextRef(0) -#endif -#if defined(XP_UNIX) && ENABLE(NETSCAPE_PLUGIN_API) - , m_hasPendingGeometryChange(true) - , m_drawable(0) - , m_visual(0) - , m_colormap(0) - , m_pluginDisplay(0) -#endif - , m_loadManually(loadManually) - , m_manualStream(0) - , m_isJavaScriptPaused(false) - , m_haveCalledSetWindow(false) -{ - if (!m_plugin) { - m_status = PluginStatusCanNotFindPlugin; - return; - } - - m_instance = &m_instanceStruct; - m_instance->ndata = this; - m_instance->pdata = 0; - - instanceMap().add(m_instance, this); - - setParameters(paramNames, paramValues); - - memset(&m_npWindow, 0, sizeof(m_npWindow)); -#if defined(XP_MACOSX) - memset(&m_npCgContext, 0, sizeof(m_npCgContext)); -#endif - - resize(size); -} - -void PluginView::focusPluginElement() -{ - if (Page* page = m_parentFrame->page()) - page->focusController().setFocusedElement(m_element, m_parentFrame); - else - m_parentFrame->document()->setFocusedElement(m_element); -} - -void PluginView::didReceiveResponse(const ResourceResponse& response) -{ - if (m_status != PluginStatusLoadedSuccessfully) - return; - - ASSERT(m_loadManually); - ASSERT(!m_manualStream); - - m_manualStream = PluginStream::create(this, m_parentFrame.get(), m_parentFrame->loader().activeDocumentLoader()->request(), false, 0, plugin()->pluginFuncs(), instance(), m_plugin->quirks()); - m_manualStream->setLoadManually(true); - - m_manualStream->didReceiveResponse(0, response); -} - -void PluginView::didReceiveData(const char* data, int length) -{ - if (m_status != PluginStatusLoadedSuccessfully) - return; - - ASSERT(m_loadManually); - ASSERT(m_manualStream); - - m_manualStream->didReceiveData(0, data, length); -} - -void PluginView::didFinishLoading() -{ - if (m_status != PluginStatusLoadedSuccessfully) - return; - - ASSERT(m_loadManually); - ASSERT(m_manualStream); - - m_manualStream->didFinishLoading(0); -} - -void PluginView::didFail(const ResourceError& error) -{ - if (m_status != PluginStatusLoadedSuccessfully) - return; - - ASSERT(m_loadManually); - - if (m_manualStream) - m_manualStream->didFail(0, error); -} - -void PluginView::setCallingPlugin(bool b) const -{ - if (!m_plugin->quirks().contains(PluginQuirkHasModalMessageLoop)) - return; - - if (b) - ++s_callingPlugin; - else - --s_callingPlugin; - - ASSERT(s_callingPlugin >= 0); -} - -bool PluginView::isCallingPlugin() -{ - return s_callingPlugin > 0; -} - -PassRefPtr<PluginView> PluginView::create(Frame* parentFrame, const IntSize& size, HTMLPlugInElement* element, const URL& url, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType, bool loadManually) -{ - // if we fail to find a plugin for this MIME type, findPlugin will search for - // a plugin by the file extension and update the MIME type, so pass a mutable String - String mimeTypeCopy = mimeType; - PluginPackage* plugin = PluginDatabase::installedPlugins()->findPlugin(url, mimeTypeCopy); - - // No plugin was found, try refreshing the database and searching again - if (!plugin && PluginDatabase::installedPlugins()->refresh()) { - mimeTypeCopy = mimeType; - plugin = PluginDatabase::installedPlugins()->findPlugin(url, mimeTypeCopy); - } - - return adoptRef(new PluginView(parentFrame, size, plugin, element, url, paramNames, paramValues, mimeTypeCopy, loadManually)); -} - -void PluginView::freeStringArray(char** stringArray, int length) -{ - if (!stringArray) - return; - - for (int i = 0; i < length; i++) - fastFree(stringArray[i]); - - fastFree(stringArray); -} - -static inline bool startsWithBlankLine(const Vector<char>& buffer) -{ - return buffer.size() > 0 && buffer[0] == '\n'; -} - -static inline int locationAfterFirstBlankLine(const Vector<char>& buffer) -{ - const char* bytes = buffer.data(); - unsigned length = buffer.size(); - - for (unsigned i = 0; i < length - 4; i++) { - // Support for Acrobat. It sends "\n\n". - if (bytes[i] == '\n' && bytes[i + 1] == '\n') - return i + 2; - - // Returns the position after 2 CRLF's or 1 CRLF if it is the first line. - if (bytes[i] == '\r' && bytes[i + 1] == '\n') { - i += 2; - if (i == 2) - return i; - else if (bytes[i] == '\n') - // Support for Director. It sends "\r\n\n" (3880387). - return i + 1; - else if (bytes[i] == '\r' && bytes[i + 1] == '\n') - // Support for Flash. It sends "\r\n\r\n" (3758113). - return i + 2; - } - } - - return -1; -} - -static inline const char* findEOL(const char* bytes, unsigned length) -{ - // According to the HTTP specification EOL is defined as - // a CRLF pair. Unfortunately, some servers will use LF - // instead. Worse yet, some servers will use a combination - // of both (e.g. <header>CRLFLF<body>), so findEOL needs - // to be more forgiving. It will now accept CRLF, LF or - // CR. - // - // It returns NULL if EOLF is not found or it will return - // a pointer to the first terminating character. - for (unsigned i = 0; i < length; i++) { - if (bytes[i] == '\n') - return bytes + i; - if (bytes[i] == '\r') { - // Check to see if spanning buffer bounds - // (CRLF is across reads). If so, wait for - // next read. - if (i + 1 == length) - break; - - return bytes + i; - } - } - - return 0; -} - -static inline String capitalizeRFC822HeaderFieldName(const String& name) -{ - bool capitalizeCharacter = true; - String result; - - for (unsigned i = 0; i < name.length(); i++) { - UChar c; - - if (capitalizeCharacter && name[i] >= 'a' && name[i] <= 'z') - c = toASCIIUpper(name[i]); - else if (!capitalizeCharacter && name[i] >= 'A' && name[i] <= 'Z') - c = toASCIILower(name[i]); - else - c = name[i]; - - if (name[i] == '-') - capitalizeCharacter = true; - else - capitalizeCharacter = false; - - result.append(c); - } - - return result; -} - -static inline HTTPHeaderMap parseRFC822HeaderFields(const Vector<char>& buffer, unsigned length) -{ - const char* bytes = buffer.data(); - const char* eol; - String lastKey; - HTTPHeaderMap headerFields; - - // Loop ove rlines until we're past the header, or we can't find any more end-of-lines - while ((eol = findEOL(bytes, length))) { - const char* line = bytes; - int lineLength = eol - bytes; - - // Move bytes to the character after the terminator as returned by findEOL. - bytes = eol + 1; - if ((*eol == '\r') && (*bytes == '\n')) - bytes++; // Safe since findEOL won't return a spanning CRLF. - - length -= (bytes - line); - if (lineLength == 0) - // Blank line; we're at the end of the header - break; - else if (*line == ' ' || *line == '\t') { - // Continuation of the previous header - if (lastKey.isNull()) { - // malformed header; ignore it and continue - continue; - } else { - // Merge the continuation of the previous header - String currentValue = headerFields.get(lastKey); - String newValue(line, lineLength); - - headerFields.set(lastKey, currentValue + newValue); - } - } else { - // Brand new header - const char* colon; - for (colon = line; *colon != ':' && colon != eol; colon++) { - // empty loop - } - if (colon == eol) - // malformed header; ignore it and continue - continue; - else { - lastKey = capitalizeRFC822HeaderFieldName(String(line, colon - line)); - String value; - - for (colon++; colon != eol; colon++) { - if (*colon != ' ' && *colon != '\t') - break; - } - if (colon == eol) - value = ""; - else - value = String(colon, eol - colon); - - String oldValue = headerFields.get(lastKey); - if (!oldValue.isNull()) - value = oldValue + ", " + value; - - headerFields.set(lastKey, value); - } - } - } - - return headerFields; -} - -NPError PluginView::handlePost(const char* url, const char* target, uint32_t len, const char* buf, bool file, void* notifyData, bool sendNotification, bool allowHeaders) -{ - if (!url || !len || !buf) - return NPERR_INVALID_PARAM; - - FrameLoadRequest frameLoadRequest(m_parentFrame->document()->securityOrigin()); - - HTTPHeaderMap headerFields; - Vector<char> buffer; - - if (file) { - NPError readResult = handlePostReadFile(buffer, len, buf); - if(readResult != NPERR_NO_ERROR) - return readResult; - } else { - buffer.resize(len); - memcpy(buffer.data(), buf, len); - } - - const char* postData = buffer.data(); - int postDataLength = buffer.size(); - - if (allowHeaders) { - if (startsWithBlankLine(buffer)) { - postData++; - postDataLength--; - } else { - int location = locationAfterFirstBlankLine(buffer); - if (location != -1) { - // If the blank line is somewhere in the middle of the buffer, everything before is the header - headerFields = parseRFC822HeaderFields(buffer, location); - unsigned dataLength = buffer.size() - location; - - // Sometimes plugins like to set Content-Length themselves when they post, - // but WebFoundation does not like that. So we will remove the header - // and instead truncate the data to the requested length. - String contentLength = headerFields.get("Content-Length"); - - if (!contentLength.isNull()) - dataLength = min(contentLength.toInt(), (int)dataLength); - headerFields.remove("Content-Length"); - - postData += location; - postDataLength = dataLength; - } - } - } - - frameLoadRequest.resourceRequest().setHTTPMethod("POST"); - frameLoadRequest.resourceRequest().setURL(makeURL(m_parentFrame->document()->baseURL(), url)); - frameLoadRequest.resourceRequest().addHTTPHeaderFields(headerFields); - frameLoadRequest.resourceRequest().setHTTPBody(FormData::create(postData, postDataLength)); - frameLoadRequest.setFrameName(target); - - return load(frameLoadRequest, sendNotification, notifyData); -} - -void PluginView::invalidateWindowlessPluginRect(const IntRect& rect) -{ - if (!isVisible()) - return; - - if (!m_element->renderer()) - return; - RenderBox* renderer = toRenderBox(m_element->renderer()); - - IntRect dirtyRect = rect; - dirtyRect.move(renderer->borderLeft() + renderer->paddingLeft(), renderer->borderTop() + renderer->paddingTop()); - renderer->repaintRectangle(dirtyRect); -} - -void PluginView::paintMissingPluginIcon(GraphicsContext* context, const IntRect& rect) -{ - static RefPtr<Image> nullPluginImage; - if (!nullPluginImage) - nullPluginImage = Image::loadPlatformResource("nullPlugin"); - - IntRect imageRect(frameRect().x(), frameRect().y(), nullPluginImage->width(), nullPluginImage->height()); - - int xOffset = (frameRect().width() - imageRect.width()) / 2; - int yOffset = (frameRect().height() - imageRect.height()) / 2; - - imageRect.move(xOffset, yOffset); - - if (!rect.intersects(imageRect)) - return; - - context->save(); - context->clip(windowClipRect()); - context->drawImage(nullPluginImage.get(), ColorSpaceDeviceRGB, imageRect.location()); - context->restore(); -} - -static const char* MozillaUserAgent = "Mozilla/5.0 (" -#if defined(XP_MACOSX) - "Macintosh; U; Intel Mac OS X;" -#elif defined(XP_WIN) - "Windows; U; Windows NT 5.1;" -#elif defined(XP_UNIX) -// The Gtk port uses X11 plugins in Mac. -#if OS(DARWIN) && PLATFORM(GTK) - "X11; U; Intel Mac OS X;" -#else - "X11; U; Linux i686;" -#endif -#endif - " en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0"; - -static const char* const ChromeUserAgent = "Mozilla/5.0 (" -#if defined(XP_MACOSX) - "Macintosh; U; Intel Mac OS X;" -#elif defined(XP_WIN) - "Windows; U; Windows NT 5.1;" -#elif defined(XP_UNIX) - // The Gtk port uses X11 plugins in Mac. -#if OS(DARWIN) && PLATFORM(GTK) - "X11; U; Intel Mac OS X;" -#else - "X11; U; Linux i686;" -#endif -#endif - " AppleWebKit/534.34 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/534.34"; - -const char* PluginView::userAgent() -{ - if (m_plugin->quirks().contains(PluginQuirkWantsMozillaUserAgent)) - return MozillaUserAgent; - else if (m_plugin->quirks().contains(PluginQuirkWantsChromeUserAgent)) - return ChromeUserAgent; - if (m_userAgent.isNull()) - m_userAgent = m_parentFrame->loader().userAgent(m_url).utf8(); - - return m_userAgent.data(); -} - -#if ENABLE(NETSCAPE_PLUGIN_API) -const char* PluginView::userAgentStatic() -{ - return MozillaUserAgent; -} -#endif - - -void PluginView::lifeSupportTimerFired(Timer<PluginView>*) -{ - deref(); -} - -void PluginView::keepAlive() -{ - if (m_lifeSupportTimer.isActive()) - return; - - ref(); - m_lifeSupportTimer.startOneShot(0); -} - -#if ENABLE(NETSCAPE_PLUGIN_API) -void PluginView::keepAlive(NPP instance) -{ - PluginView* view = instanceMap().get(instance); - if (!view) - return; - - view->keepAlive(); -} - -NPError PluginView::getValueStatic(NPNVariable variable, void* value) -{ - LOG(Plugins, "PluginView::getValueStatic(%s)", prettyNameForNPNVariable(variable).data()); - - NPError result; - if (platformGetValueStatic(variable, value, &result)) - return result; - - return NPERR_GENERIC_ERROR; -} - -NPError PluginView::getValue(NPNVariable variable, void* value) -{ - LOG(Plugins, "PluginView::getValue(%s)", prettyNameForNPNVariable(variable).data()); - - NPError result; - if (platformGetValue(variable, value, &result)) - return result; - - if (platformGetValueStatic(variable, value, &result)) - return result; - - switch (variable) { - case NPNVWindowNPObject: { - if (m_isJavaScriptPaused) - return NPERR_GENERIC_ERROR; - - NPObject* windowScriptObject = m_parentFrame->script().windowScriptNPObject(); - - // Return value is expected to be retained, as described here: <http://www.mozilla.org/projects/plugin/npruntime.html> - if (windowScriptObject) - _NPN_RetainObject(windowScriptObject); - - void** v = (void**)value; - *v = windowScriptObject; - - return NPERR_NO_ERROR; - } - - case NPNVPluginElementNPObject: { - if (m_isJavaScriptPaused) - return NPERR_GENERIC_ERROR; - - NPObject* pluginScriptObject = 0; - - if (m_element->hasTagName(appletTag) || m_element->hasTagName(embedTag) || m_element->hasTagName(objectTag)) - pluginScriptObject = m_element->getNPObject(); - - // Return value is expected to be retained, as described here: <http://www.mozilla.org/projects/plugin/npruntime.html> - if (pluginScriptObject) - _NPN_RetainObject(pluginScriptObject); - - void** v = (void**)value; - *v = pluginScriptObject; - - return NPERR_NO_ERROR; - } - - case NPNVprivateModeBool: { - Page* page = m_parentFrame->page(); - if (!page) - return NPERR_GENERIC_ERROR; - *((NPBool*)value) = page->settings().privateBrowsingEnabled(); - return NPERR_NO_ERROR; - } - - default: - return NPERR_GENERIC_ERROR; - } -} - -static Frame* getFrame(Frame* parentFrame, Element* element) -{ - if (parentFrame) - return parentFrame; - - return element->document().frame(); -} - -NPError PluginView::getValueForURL(NPNURLVariable variable, const char* url, char** value, uint32_t* len) -{ - LOG(Plugins, "PluginView::getValueForURL(%s)", prettyNameForNPNURLVariable(variable).data()); - - NPError result = NPERR_NO_ERROR; - - switch (variable) { - case NPNURLVCookie: { - URL u(m_parentFrame->document()->baseURL(), url); - if (u.isValid()) { - Frame* frame = getFrame(parentFrame(), m_element); - if (frame) { - const CString cookieStr = cookies(frame->document(), u).utf8(); - if (!cookieStr.isNull()) { - const int size = cookieStr.length(); - *value = static_cast<char*>(m_plugin->browserFuncs()->memalloc(size+1)); - if (*value) { - memset(*value, 0, size+1); - memcpy(*value, cookieStr.data(), size+1); - if (len) - *len = size; - } else - result = NPERR_OUT_OF_MEMORY_ERROR; - } - } - } else - result = NPERR_INVALID_URL; - break; - } - case NPNURLVProxy: { - URL u(m_parentFrame->document()->baseURL(), url); - if (u.isValid()) { - Frame* frame = getFrame(parentFrame(), m_element); - const FrameLoader* frameLoader = frame ? &frame->loader() : 0; - const NetworkingContext* context = frameLoader ? frameLoader->networkingContext() : 0; - const CString proxyStr = toString(proxyServersForURL(u, context)).utf8(); - if (!proxyStr.isNull()) { - const int size = proxyStr.length(); - *value = static_cast<char*>(m_plugin->browserFuncs()->memalloc(size+1)); - if (*value) { - memset(*value, 0, size+1); - memcpy(*value, proxyStr.data(), size+1); - if (len) - *len = size; - } else - result = NPERR_OUT_OF_MEMORY_ERROR; - } - } else - result = NPERR_INVALID_URL; - break; - } - default: - result = NPERR_GENERIC_ERROR; - LOG(Plugins, "PluginView::getValueForURL: %s", prettyNameForNPNURLVariable(variable).data()); - break; - } - - return result; -} - - -NPError PluginView::setValueForURL(NPNURLVariable variable, const char* url, const char* value, uint32_t len) -{ - LOG(Plugins, "PluginView::setValueForURL(%s)", prettyNameForNPNURLVariable(variable).data()); - - NPError result = NPERR_NO_ERROR; - - switch (variable) { - case NPNURLVCookie: { - URL u(m_parentFrame->document()->baseURL(), url); - if (u.isValid()) { - const String cookieStr = String::fromUTF8(value, len); - Frame* frame = getFrame(parentFrame(), m_element); - if (frame && !cookieStr.isEmpty()) - setCookies(frame->document(), u, cookieStr); - } else - result = NPERR_INVALID_URL; - break; - } - case NPNURLVProxy: - LOG(Plugins, "PluginView::setValueForURL(%s): Plugins are NOT allowed to set proxy information.", prettyNameForNPNURLVariable(variable).data()); - result = NPERR_GENERIC_ERROR; - break; - default: - LOG(Plugins, "PluginView::setValueForURL: %s", prettyNameForNPNURLVariable(variable).data()); - result = NPERR_GENERIC_ERROR; - break; - } - - return result; -} - -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 */) -{ -#if LOG_DISABLED - UNUSED_PARAM(protocol); - UNUSED_PARAM(host); - UNUSED_PARAM(port); -#endif - LOG(Plugins, "PluginView::getAuthenticationInfo: protocol=%s, host=%s, port=%d", protocol, host, port); - notImplemented(); - return NPERR_GENERIC_ERROR; -} -#endif - -void PluginView::privateBrowsingStateChanged(bool privateBrowsingEnabled) -{ - NPP_SetValueProcPtr setValue = m_plugin->pluginFuncs()->setvalue; - if (!setValue) - return; - - PluginView::setCurrentPluginView(this); - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - setCallingPlugin(true); - NPBool value = privateBrowsingEnabled; - setValue(m_instance, NPNVprivateModeBool, &value); - setCallingPlugin(false); - PluginView::setCurrentPluginView(0); -} - -} // namespace WebCore - -#endif // ENABLE(NETSCAPE_PLUGIN_API) diff --git a/Source/WebCore/plugins/PluginView.h b/Source/WebCore/plugins/PluginView.h deleted file mode 100644 index 5fd38d2fd..000000000 --- a/Source/WebCore/plugins/PluginView.h +++ /dev/null @@ -1,429 +0,0 @@ -/* - * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved. - * Copyright (C) 2008 Collabora Ltd. All rights reserved. - * Copyright (C) 2009 Girish Ramakrishnan <girish@forwardbias.in> - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef PluginView_h -#define PluginView_h - -#include "FrameLoadRequest.h" -#include "IntRect.h" -#include "MediaCanStartListener.h" -#include "PluginViewBase.h" -#include "ResourceRequest.h" -#include "Timer.h" -#include <wtf/HashMap.h> -#include <wtf/HashSet.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassRefPtr.h> -#include <wtf/RefPtr.h> -#include <wtf/Vector.h> -#include <wtf/text/CString.h> - -#if ENABLE(NETSCAPE_PLUGIN_API) -#include "PluginStream.h" -#include "npruntime_internal.h" -#endif - -#if OS(WINDOWS) && PLATFORM(GTK) -typedef struct HWND__* HWND; -typedef HWND PlatformPluginWidget; -#else -typedef PlatformWidget PlatformPluginWidget; -#endif -#if PLATFORM(GTK) -typedef struct _GtkSocket GtkSocket; -#endif - -namespace JSC { - namespace Bindings { - class Instance; - } -} - -namespace WebCore { - class Frame; - class Image; - class HTMLPlugInElement; - class KeyboardEvent; - class MouseEvent; - class URL; -#if OS(WINDOWS) && ENABLE(NETSCAPE_PLUGIN_API) - class PluginMessageThrottlerWin; -#endif - class PluginPackage; - class PluginRequest; - class PluginStream; - class ResourceError; - class ResourceResponse; - class WheelEvent; - - enum PluginStatus { - PluginStatusCanNotFindPlugin, - PluginStatusCanNotLoadPlugin, - PluginStatusLoadedSuccessfully - }; - - class PluginRequest { - WTF_MAKE_NONCOPYABLE(PluginRequest); WTF_MAKE_FAST_ALLOCATED; - public: - PluginRequest(const FrameLoadRequest& frameLoadRequest, bool sendNotification, void* notifyData, bool shouldAllowPopups) - : m_frameLoadRequest(frameLoadRequest) - , m_notifyData(notifyData) - , m_sendNotification(sendNotification) - , m_shouldAllowPopups(shouldAllowPopups) { } - public: - const FrameLoadRequest& frameLoadRequest() const { return m_frameLoadRequest; } - void* notifyData() const { return m_notifyData; } - bool sendNotification() const { return m_sendNotification; } - bool shouldAllowPopups() const { return m_shouldAllowPopups; } - private: - FrameLoadRequest m_frameLoadRequest; - void* m_notifyData; - bool m_sendNotification; - bool m_shouldAllowPopups; - }; - - class PluginManualLoader { - public: - virtual ~PluginManualLoader() {} - virtual void didReceiveResponse(const ResourceResponse&) = 0; - virtual void didReceiveData(const char*, int) = 0; - virtual void didFinishLoading() = 0; - virtual void didFail(const ResourceError&) = 0; - }; - - class PluginView : public PluginViewBase -#if ENABLE(NETSCAPE_PLUGIN_API) - , private PluginStreamClient -#endif - , public PluginManualLoader - , private MediaCanStartListener { - public: - static PassRefPtr<PluginView> create(Frame* parentFrame, const IntSize&, HTMLPlugInElement*, const URL&, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType, bool loadManually); - virtual ~PluginView(); - - PluginPackage* plugin() const { return m_plugin.get(); } -#if ENABLE(NETSCAPE_PLUGIN_API) - NPP instance() const { return m_instance; } -#endif - - void setNPWindowRect(const IntRect&); - static PluginView* currentPluginView(); - -#if ENABLE(NETSCAPE_PLUGIN_API) - NPObject* npObject(); -#endif - PassRefPtr<JSC::Bindings::Instance> bindingInstance(); - - PluginStatus status() const { return m_status; } - -#if ENABLE(NETSCAPE_PLUGIN_API) - // NPN functions - NPError getURLNotify(const char* url, const char* target, void* notifyData); - NPError getURL(const char* url, const char* target); - NPError postURLNotify(const char* url, const char* target, uint32_t len, const char* but, NPBool file, void* notifyData); - NPError postURL(const char* url, const char* target, uint32_t len, const char* but, NPBool file); - NPError newStream(NPMIMEType type, const char* target, NPStream** stream); - int32_t write(NPStream* stream, int32_t len, void* buffer); - NPError destroyStream(NPStream* stream, NPReason reason); -#endif - const char* userAgent(); -#if ENABLE(NETSCAPE_PLUGIN_API) - static const char* userAgentStatic(); -#endif - void status(const char* message); - -#if ENABLE(NETSCAPE_PLUGIN_API) - NPError getValue(NPNVariable variable, void* value); - static NPError getValueStatic(NPNVariable variable, void* value); - NPError setValue(NPPVariable variable, void* value); - NPError getValueForURL(NPNURLVariable variable, const char* url, char** value, uint32_t* len); - NPError setValueForURL(NPNURLVariable variable, const char* url, const char* value, uint32_t len); - NPError 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); - void invalidateRect(NPRect*); - void invalidateRegion(NPRegion); -#endif - void forceRedraw(); - void pushPopupsEnabledState(bool state); - void popPopupsEnabledState(); - - virtual void invalidateRect(const IntRect&); - - bool arePopupsAllowed() const; - - void setJavaScriptPaused(bool); - - void privateBrowsingStateChanged(bool); - - void disconnectStream(PluginStream*); - void streamDidFinishLoading(PluginStream* stream) { disconnectStream(stream); } - - // Widget functions - virtual void setFrameRect(const IntRect&); - virtual void frameRectsChanged(); - virtual void setFocus(bool); - virtual void show(); - virtual void hide(); - virtual void paint(GraphicsContext*, const IntRect&); - virtual void clipRectChanged() override; - - // This method is used by plugins on all platforms to obtain a clip rect that includes clips set by WebCore, - // e.g., in overflow:auto sections. The clip rects coordinates are in the containing window's coordinate space. - // This clip includes any clips that the widget itself sets up for its children. - IntRect windowClipRect() const; - - virtual void handleEvent(Event*); - virtual void setParent(ScrollView*); - virtual void setParentVisible(bool); - - virtual bool isPluginView() const override { return true; } - - Frame* parentFrame() const { return m_parentFrame.get(); } - - void focusPluginElement(); - - const String& pluginsPage() const { return m_pluginsPage; } - const String& mimeType() const { return m_mimeType; } - const URL& url() const { return m_url; } - -#if defined(XP_MACOSX) && ENABLE(NETSCAPE_PLUGIN_API) - bool popUpContextMenu(NPMenu*); -#endif - -#if OS(WINDOWS) && ENABLE(NETSCAPE_PLUGIN_API) - static LRESULT CALLBACK PluginViewWndProc(HWND, UINT, WPARAM, LPARAM); - LRESULT wndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - WNDPROC pluginWndProc() const { return m_pluginWndProc; } -#endif - - // Used for manual loading - void didReceiveResponse(const ResourceResponse&); - void didReceiveData(const char*, int); - void didFinishLoading(); - void didFail(const ResourceError&); - - static bool isCallingPlugin(); - - bool start(); - -#if ENABLE(NETSCAPE_PLUGIN_API) - static void keepAlive(NPP); -#endif - void keepAlive(); - - private: - PluginView(Frame* parentFrame, const IntSize&, PluginPackage*, HTMLPlugInElement*, const URL&, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType, bool loadManually); - - void setParameters(const Vector<String>& paramNames, const Vector<String>& paramValues); - bool startOrAddToUnstartedList(); - void init(); - bool platformStart(); - void stop(); - void platformDestroy(); - static void setCurrentPluginView(PluginView*); -#if ENABLE(NETSCAPE_PLUGIN_API) - NPError load(const FrameLoadRequest&, bool sendNotification, void* notifyData); - NPError handlePost(const char* url, const char* target, uint32_t len, const char* buf, bool file, void* notifyData, bool sendNotification, bool allowHeaders); - NPError handlePostReadFile(Vector<char>& buffer, uint32_t len, const char* buf); -#endif - static void freeStringArray(char** stringArray, int length); - void setCallingPlugin(bool) const; - - void invalidateWindowlessPluginRect(const IntRect&); - - virtual void mediaCanStart(); - -#if OS(WINDOWS) && ENABLE(NETSCAPE_PLUGIN_API) - void paintWindowedPluginIntoContext(GraphicsContext*, const IntRect&); - static HDC WINAPI hookedBeginPaint(HWND, PAINTSTRUCT*); - static BOOL WINAPI hookedEndPaint(HWND, const PAINTSTRUCT*); -#endif - -#if ENABLE(NETSCAPE_PLUGIN_API) - static bool platformGetValueStatic(NPNVariable variable, void* value, NPError* result); - bool platformGetValue(NPNVariable variable, void* value, NPError* result); -#endif - - RefPtr<Frame> m_parentFrame; - RefPtr<PluginPackage> m_plugin; - HTMLPlugInElement* m_element; - bool m_isStarted; - URL m_url; - PluginStatus m_status; - Vector<IntRect> m_invalidRects; - - void performRequest(PluginRequest*); - void scheduleRequest(PassOwnPtr<PluginRequest>); - void requestTimerFired(Timer<PluginView>*); - void invalidateTimerFired(Timer<PluginView>*); - Timer<PluginView> m_requestTimer; - Timer<PluginView> m_invalidateTimer; - - void popPopupsStateTimerFired(Timer<PluginView>*); - Timer<PluginView> m_popPopupsStateTimer; - - void lifeSupportTimerFired(Timer<PluginView>*); - Timer<PluginView> m_lifeSupportTimer; - -#if ENABLE(NETSCAPE_PLUGIN_API) - bool dispatchNPEvent(NPEvent&); -#endif -#if defined(XP_MACOSX) && ENABLE(NETSCAPE_PLUGIN_API) - int16_t dispatchNPCocoaEvent(NPCocoaEvent&); - bool m_updatedCocoaTextInputRequested; - bool m_keyDownSent; - uint16_t m_disregardKeyUpCounter; -#endif - -#if defined(XP_MACOSX) - void handleWheelEvent(WheelEvent*); -#endif - void updatePluginWidget(); - void paintMissingPluginIcon(GraphicsContext*, const IntRect&); - - void handleKeyboardEvent(KeyboardEvent*); - void handleMouseEvent(MouseEvent*); -#if defined(XP_UNIX) && ENABLE(NETSCAPE_PLUGIN_API) - void handleFocusInEvent(); - void handleFocusOutEvent(); -#endif - -#if OS(WINDOWS) - void paintIntoTransformedContext(HDC); - PassRefPtr<Image> snapshot(); -#endif - - int m_mode; - int m_paramCount; - char** m_paramNames; - char** m_paramValues; - String m_pluginsPage; - - String m_mimeType; - WTF::CString m_userAgent; - -#if ENABLE(NETSCAPE_PLUGIN_API) - NPP m_instance; - NPP_t m_instanceStruct; - NPWindow m_npWindow; -#endif - - Vector<bool, 4> m_popupStateStack; - - HashSet<RefPtr<PluginStream> > m_streams; - Vector<OwnPtr<PluginRequest> > m_requests; - - bool m_isWindowed; - bool m_isTransparent; - bool m_haveInitialized; - bool m_isWaitingToStart; - -#if defined(XP_UNIX) - bool m_needsXEmbed; -#endif - -#if OS(WINDOWS) && ENABLE(NETSCAPE_PLUGIN_API) - OwnPtr<PluginMessageThrottlerWin> m_messageThrottler; - WNDPROC m_pluginWndProc; - unsigned m_lastMessage; - bool m_isCallingPluginWndProc; - HDC m_wmPrintHDC; - bool m_haveUpdatedPluginWidget; -#endif - -#if (PLATFORM(GTK) && OS(WINDOWS)) || PLATFORM(EFL) - // On Mac OSX and Qt/Windows the plugin does not have its own native widget, - // but is using the containing window as its reference for positioning/painting. - PlatformPluginWidget m_window; -public: - PlatformPluginWidget platformPluginWidget() const { return m_window; } - void setPlatformPluginWidget(PlatformPluginWidget widget) { m_window = widget; } -#else -public: - void setPlatformPluginWidget(PlatformPluginWidget widget) { setPlatformWidget(widget); } - PlatformPluginWidget platformPluginWidget() const { return platformWidget(); } -#endif - -private: - -#if defined(XP_UNIX) || PLATFORM(GTK) - void setNPWindowIfNeeded(); -#elif defined(XP_MACOSX) - NP_CGContext m_npCgContext; - CGContextRef m_contextRef; - - void setNPWindowIfNeeded(); -#endif - -#if defined(XP_UNIX) && ENABLE(NETSCAPE_PLUGIN_API) - bool m_hasPendingGeometryChange; - Pixmap m_drawable; - Visual* m_visual; - Colormap m_colormap; - Display* m_pluginDisplay; - - void initXEvent(XEvent* event); -#endif - -#if PLATFORM(GTK) - static gboolean plugRemovedCallback(GtkSocket*, PluginView*); - static void plugAddedCallback(GtkSocket*, PluginView*); - void updateWidgetAllocationAndClip(); - bool m_plugAdded; - IntRect m_delayedAllocation; -#endif - - IntRect m_clipRect; // The clip rect to apply to a windowed plug-in - IntRect m_windowRect; // Our window rect. - - bool m_loadManually; - RefPtr<PluginStream> m_manualStream; - - bool m_isJavaScriptPaused; - - bool m_haveCalledSetWindow; - - static PluginView* s_currentPluginView; - }; - -inline PluginView* toPluginView(Widget* widget) -{ - ASSERT(!widget || widget->isPluginView()); - return static_cast<PluginView*>(widget); -} - -inline const PluginView* toPluginView(const Widget* widget) -{ - ASSERT(!widget || widget->isPluginView()); - return static_cast<const PluginView*>(widget); -} - -// This will catch anyone doing an unnecessary cast. -void toPluginView(const PluginView*); - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/plugins/PluginViewBase.h b/Source/WebCore/plugins/PluginViewBase.h index 84cd5f81b..5d8e321b6 100644 --- a/Source/WebCore/plugins/PluginViewBase.h +++ b/Source/WebCore/plugins/PluginViewBase.h @@ -22,9 +22,10 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef PluginWidget_h -#define PluginWidget_h +#pragma once +#include "AudioHardwareListener.h" +#include "BridgeJSC.h" #include "PlatformLayer.h" #include "ScrollTypes.h" #include "Widget.h" @@ -44,14 +45,12 @@ class Scrollbar; // It's intended as a stopgap measure until we can merge all plug-in views into a single plug-in view. class PluginViewBase : public Widget { public: -#if USE(ACCELERATED_COMPOSITING) virtual PlatformLayer* platformLayer() const { return 0; } #if PLATFORM(IOS) virtual bool willProvidePluginLayer() const { return false; } virtual void attachPluginLayer() { } virtual void detachPluginLayer() { } #endif -#endif virtual JSC::JSObject* scriptObject(JSC::JSGlobalObject*) { return 0; } virtual void storageBlockingStateChanged() { } @@ -73,15 +72,21 @@ public: virtual bool shouldAllowNavigationFromDrags() const { return false; } - virtual bool isPluginViewBase() const { return true; } + bool isPluginViewBase() const override { return true; } virtual bool shouldNotAddLayer() const { return false; } + virtual AudioHardwareActivityType audioHardwareActivity() const { return AudioHardwareActivityType::Unknown; } + + virtual void setJavaScriptPaused(bool) { } + + virtual RefPtr<JSC::Bindings::Instance> bindingInstance() { return nullptr; } + + virtual void willDetatchRenderer() { } + protected: explicit PluginViewBase(PlatformWidget widget = 0) : Widget(widget) { } }; -WIDGET_TYPE_CASTS(PluginViewBase, isPluginViewBase()); - } // namespace WebCore -#endif // PluginWidget_h +SPECIALIZE_TYPE_TRAITS_WIDGET(PluginViewBase, isPluginViewBase()) diff --git a/Source/WebCore/plugins/PluginViewNone.cpp b/Source/WebCore/plugins/PluginViewNone.cpp deleted file mode 100644 index 993541e49..000000000 --- a/Source/WebCore/plugins/PluginViewNone.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (C) 2008 Kevin Ollivier <kevino@theolliviers.com> All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginView.h" - -#include "BridgeJSC.h" -#include <runtime/JSObject.h> - -using namespace WTF; - -namespace WebCore { - -void PluginView::setFocus(bool) -{ -} - -void PluginView::show() -{ -} - -void PluginView::hide() -{ -} - -void PluginView::paint(GraphicsContext*, const IntRect&) -{ -} - -void PluginView::handleKeyboardEvent(KeyboardEvent*) -{ -} - -void PluginView::handleMouseEvent(MouseEvent*) -{ -} - -void PluginView::setParent(ScrollView*) -{ -} - -void PluginView::setNPWindowRect(const IntRect&) -{ -} - -#if ENABLE(NETSCAPE_PLUGIN_API) -NPError PluginView::handlePostReadFile(Vector<char>&, uint32_t, const char*) -{ - return 0; -} - -bool PluginView::platformGetValue(NPNVariable, void*, NPError*) -{ - return false; -} - -bool PluginView::platformGetValueStatic(NPNVariable, void*, NPError*) -{ - return false; -} - -void PluginView::invalidateRect(NPRect*) -{ -} -#endif - -void PluginView::invalidateRect(const IntRect&) -{ -} - -#if ENABLE(NETSCAPE_PLUGIN_API) -void PluginView::invalidateRegion(NPRegion) -{ -} -#endif - -void PluginView::forceRedraw() -{ -} - -bool PluginView::platformStart() -{ - return true; -} - -void PluginView::platformDestroy() -{ -} - -void PluginView::setParentVisible(bool) -{ -} - -void PluginView::updatePluginWidget() -{ -} - -#if defined(XP_UNIX) && ENABLE(NETSCAPE_PLUGIN_API) -void PluginView::handleFocusInEvent() -{ -} - -void PluginView::handleFocusOutEvent() -{ -} -#endif - -// The functions below are for platforms that do not use PluginView for plugins -// due to architectural differences. The plan is to eventually have all -// ports using PluginView, but until then, if new functions like this are -// added, please make sure they have the proper platform #ifs so that changes -// do not break ports who compile both this file and PluginView.cpp. -#if PLATFORM(MAC) || PLATFORM(EFL) || OS(WINCE) -#if ENABLE(NETSCAPE_PLUGIN_API) -void PluginView::keepAlive(NPP) -{ -} -#endif - -PassRefPtr<JSC::Bindings::Instance> PluginView::bindingInstance() -{ - return 0; -} - -void PluginView::privateBrowsingStateChanged(bool) -{ -} - -void PluginView::setJavaScriptPaused(bool) -{ -} -#endif - -} // namespace WebCore diff --git a/Source/WebCore/plugins/gtk/PluginPackageGtk.cpp b/Source/WebCore/plugins/gtk/PluginPackageGtk.cpp deleted file mode 100644 index a81f5a10c..000000000 --- a/Source/WebCore/plugins/gtk/PluginPackageGtk.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. - * Copyright (C) 2008 Collabora Ltd. All rights reserved. - * Copyright (C) 2008 Nuanti Ltd. - * Copyright (C) 2008 Novell Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginPackage.h" - -#include "GRefPtrGtk.h" -#include "MIMETypeRegistry.h" -#include "NotImplemented.h" -#include "npruntime_impl.h" -#include "PluginDebug.h" -#include <gio/gio.h> -#include <wtf/gobject/GUniquePtr.h> -#include <wtf/text/CString.h> - -namespace WebCore { - -bool PluginPackage::fetchInfo() -{ - if (!load()) - return false; - - NP_GetMIMEDescriptionFuncPtr NP_GetMIMEDescription = 0; - NPP_GetValueProcPtr NPP_GetValue = 0; - - g_module_symbol(m_module, "NP_GetMIMEDescription", (void**)&NP_GetMIMEDescription); - g_module_symbol(m_module, "NP_GetValue", (void**)&NPP_GetValue); - - if (!NP_GetMIMEDescription || !NPP_GetValue) - return false; - - char* buffer = 0; - NPError err = NPP_GetValue(0, NPPVpluginNameString, &buffer); - if (err == NPERR_NO_ERROR) - m_name = String::fromUTF8(buffer); - - buffer = 0; - err = NPP_GetValue(0, NPPVpluginDescriptionString, &buffer); - if (err == NPERR_NO_ERROR) { - m_description = String::fromUTF8(buffer); - determineModuleVersionFromDescription(); - } - - const gchar* types = NP_GetMIMEDescription(); - if (!types) - return true; - - gchar** mimeDescs = g_strsplit(types, ";", -1); - for (int i = 0; mimeDescs[i] && mimeDescs[i][0]; i++) { - GUniquePtr<char> mime(g_utf8_strdown(mimeDescs[i], -1)); - gchar** mimeData = g_strsplit(mime.get(), ":", 3); - if (g_strv_length(mimeData) < 3) { - g_strfreev(mimeData); - continue; - } - - String description = String::fromUTF8(mimeData[2]); - gchar** extensions = g_strsplit(mimeData[1], ",", -1); - - Vector<String> extVector; - for (int j = 0; extensions[j]; j++) - extVector.append(String::fromUTF8(extensions[j])); - - determineQuirks(mimeData[0]); - m_mimeToExtensions.add(mimeData[0], extVector); - m_mimeToDescriptions.add(mimeData[0], description); - - g_strfreev(extensions); - g_strfreev(mimeData); - } - g_strfreev(mimeDescs); - - return true; -} - -static int webkitgtkXError(Display* xdisplay, XErrorEvent* error) -{ - gchar errorMessage[64]; - XGetErrorText(xdisplay, error->error_code, errorMessage, 63); - g_warning("The program '%s' received an X Window System error.\n" - "This probably reflects a bug in the Adobe Flash plugin.\n" - "The error was '%s'.\n" - " (Details: serial %ld error_code %d request_code %d minor_code %d)\n", - g_get_prgname(), errorMessage, - error->serial, error->error_code, - error->request_code, error->minor_code); - return 0; -} - -static bool moduleMixesGtkSymbols(GModule* module) -{ - void* symbol; -#ifdef GTK_API_VERSION_2 - return g_module_symbol(module, "gtk_application_get_type", &symbol); -#else - return g_module_symbol(module, "gtk_object_get_type", &symbol); -#endif -} - -bool PluginPackage::load() -{ - if (m_isLoaded) { - m_loadCount++; - return true; - } - - GUniquePtr<gchar> finalPath(g_strdup(m_path.utf8().data())); - while (g_file_test(finalPath.get(), G_FILE_TEST_IS_SYMLINK)) { - GRefPtr<GFile> file = adoptGRef(g_file_new_for_path(finalPath.get())); - GRefPtr<GFile> dir = adoptGRef(g_file_get_parent(file.get())); - GUniquePtr<gchar> linkPath(g_file_read_link(finalPath.get(), 0)); - GRefPtr<GFile> resolvedFile = adoptGRef(g_file_resolve_relative_path(dir.get(), linkPath.get())); - finalPath.reset(g_file_get_path(resolvedFile.get())); - } - - // No joke. If there is a netscape component in the path, go back - // to the symlink, as flash breaks otherwise. - // See http://src.chromium.org/viewvc/chrome/trunk/src/webkit/glue/plugins/plugin_list_posix.cc - GUniquePtr<gchar> baseName(g_path_get_basename(finalPath.get())); - if (!g_strcmp0(baseName.get(), "libflashplayer.so") - && g_strstr_len(finalPath.get(), -1, "/netscape/")) - finalPath.reset(g_strdup(m_path.utf8().data())); - - m_module = g_module_open(finalPath.get(), G_MODULE_BIND_LOCAL); - - if (!m_module) { - LOG(Plugins,"Module Load Failed :%s, Error:%s\n", (m_path.utf8()).data(), g_module_error()); - return false; - } - - if (moduleMixesGtkSymbols(m_module)) { - LOG(Plugins, "Ignoring module '%s' to avoid mixing GTK+ 2 and GTK+ 3 symbols.\n", m_path.utf8().data()); - return false; - } - - m_isLoaded = true; - - if (!g_strcmp0(baseName.get(), "libflashplayer.so")) { - // Flash plugin can produce X errors that are handled by the GDK X error handler, which - // exits the process. Since we don't want to crash due to flash bugs, we install a - // custom error handler to show a warning when a X error happens without aborting. - XSetErrorHandler(webkitgtkXError); - } - - NP_InitializeFuncPtr NP_Initialize = 0; - m_NPP_Shutdown = 0; - - NPError npErr; - - g_module_symbol(m_module, "NP_Initialize", (void**)&NP_Initialize); - g_module_symbol(m_module, "NP_Shutdown", (void**)&m_NPP_Shutdown); - - if (!NP_Initialize || !m_NPP_Shutdown) - goto abort; - - memset(&m_pluginFuncs, 0, sizeof(m_pluginFuncs)); - m_pluginFuncs.size = sizeof(m_pluginFuncs); - - initializeBrowserFuncs(); - - npErr = NP_Initialize(&m_browserFuncs, &m_pluginFuncs); - if (npErr != NPERR_NO_ERROR) - goto abort; - - m_loadCount++; - return true; - -abort: - unloadWithoutShutdown(); - return false; -} - -uint16_t PluginPackage::NPVersion() const -{ - return NPVERS_HAS_PLUGIN_THREAD_ASYNC_CALL; -} -} diff --git a/Source/WebCore/plugins/gtk/PluginViewGtk.cpp b/Source/WebCore/plugins/gtk/PluginViewGtk.cpp deleted file mode 100644 index 0bbbee3fe..000000000 --- a/Source/WebCore/plugins/gtk/PluginViewGtk.cpp +++ /dev/null @@ -1,896 +0,0 @@ -/* - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. - * Copyright (C) 2008 Collabora Ltd. All rights reserved. - * Copyright (C) 2009, 2010 Kakai, Inc. <brian@kakai.com> - * Copyright (C) 2010 Igalia S.L. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginView.h" - -#include "BridgeJSC.h" -#include "Document.h" -#include "DocumentLoader.h" -#include "Element.h" -#include "FocusController.h" -#include "Frame.h" -#include "FrameLoadRequest.h" -#include "FrameLoader.h" -#include "FrameTree.h" -#include "FrameView.h" -#include "GRefPtrGtk.h" -#include "GraphicsContext.h" -#include "GtkVersioning.h" -#include "HTMLNames.h" -#include "HTMLPlugInElement.h" -#include "HostWindow.h" -#include "Image.h" -#include "JSDOMBinding.h" -#include "JSDOMWindowBase.h" -#include "KeyboardEvent.h" -#include "MouseEvent.h" -#include "NotImplemented.h" -#include "Page.h" -#include "PlatformContextCairo.h" -#include "PlatformKeyboardEvent.h" -#include "PlatformMouseEvent.h" -#include "PluginDebug.h" -#include "PluginMainThreadScheduler.h" -#include "PluginPackage.h" -#include "RenderElement.h" -#include "Settings.h" -#include "SpatialNavigation.h" -#include "npruntime_impl.h" -#include "runtime_root.h" -#include <runtime/JSCJSValue.h> -#include <runtime/JSLock.h> - -#ifdef GTK_API_VERSION_2 -#include <gdkconfig.h> -#endif -#include <gtk/gtk.h> - -#define String XtStringType -#include "RefPtrCairo.h" -#include "gtk2xtbin.h" -#define Bool int // this got undefined somewhere -#define Status int // ditto -#include <X11/extensions/Xrender.h> -#include <cairo-xlib.h> -#include <gdk/gdkx.h> - -using JSC::ExecState; -using JSC::Interpreter; -using JSC::JSLock; -using JSC::JSObject; - -using std::min; - -using namespace WTF; - -namespace WebCore { - -using namespace HTMLNames; - -bool PluginView::dispatchNPEvent(NPEvent& event) -{ - // sanity check - if (!m_plugin->pluginFuncs()->event) - return false; - - PluginView::setCurrentPluginView(this); - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - setCallingPlugin(true); - - bool accepted = !m_plugin->pluginFuncs()->event(m_instance, &event); - - setCallingPlugin(false); - PluginView::setCurrentPluginView(0); - return accepted; -} - -static Window getRootWindow(Frame* parentFrame) -{ - GtkWidget* parentWidget = parentFrame->view()->hostWindow()->platformPageClient(); - GdkScreen* gscreen = gtk_widget_get_screen(parentWidget); - return GDK_WINDOW_XWINDOW(gdk_screen_get_root_window(gscreen)); -} - -void PluginView::updatePluginWidget() -{ - if (!parent()) - return; - - ASSERT(parent()->isFrameView()); - FrameView* frameView = toFrameView(parent()); - - IntRect oldWindowRect = m_windowRect; - IntRect oldClipRect = m_clipRect; - - m_windowRect = IntRect(frameView->contentsToWindow(frameRect().location()), frameRect().size()); - m_clipRect = windowClipRect(); - m_clipRect.move(-m_windowRect.x(), -m_windowRect.y()); - - if (m_windowRect == oldWindowRect && m_clipRect == oldClipRect) - return; - - if (m_status != PluginStatusLoadedSuccessfully) - return; - - if (!m_isWindowed && !m_windowRect.isEmpty()) { - Display* display = GDK_DISPLAY_XDISPLAY(gdk_display_get_default()); - if (m_drawable) - XFreePixmap(display, m_drawable); - - m_drawable = XCreatePixmap(display, getRootWindow(m_parentFrame.get()), - m_windowRect.width(), m_windowRect.height(), - ((NPSetWindowCallbackStruct*)m_npWindow.ws_info)->depth); - XSync(display, false); // make sure that the server knows about the Drawable - } - - setNPWindowIfNeeded(); -} - -void PluginView::setFocus(bool focused) -{ - ASSERT(platformPluginWidget() == platformWidget()); - if (focused && platformWidget()) - gtk_widget_grab_focus(platformWidget()); - Widget::setFocus(focused); -} - -void PluginView::show() -{ - ASSERT(platformPluginWidget() == platformWidget()); - Widget::show(); -} - -void PluginView::hide() -{ - ASSERT(platformPluginWidget() == platformWidget()); - Widget::hide(); -} - -void PluginView::paint(GraphicsContext* context, const IntRect& rect) -{ - if (!m_isStarted || m_status != PluginStatusLoadedSuccessfully) { - paintMissingPluginIcon(context, rect); - return; - } - - if (context->paintingDisabled()) - return; - - setNPWindowIfNeeded(); - - if (m_isWindowed) - return; - - if (!m_drawable) - return; - - Display* display = GDK_DISPLAY_XDISPLAY(gdk_display_get_default()); - const bool syncX = m_pluginDisplay && m_pluginDisplay != display; - - IntRect exposedRect(rect); - exposedRect.intersect(frameRect()); - exposedRect.move(-frameRect().x(), -frameRect().y()); - - RefPtr<cairo_surface_t> drawableSurface = adoptRef(cairo_xlib_surface_create(display, - m_drawable, - m_visual, - m_windowRect.width(), - m_windowRect.height())); - - if (m_isTransparent) { - // If we have a 32 bit drawable and the plugin wants transparency, - // we'll clear the exposed area to transparent first. Otherwise, - // we'd end up with junk in there from the last paint, or, worse, - // uninitialized data. - RefPtr<cairo_t> cr = adoptRef(cairo_create(drawableSurface.get())); - - if (!(cairo_surface_get_content(drawableSurface.get()) & CAIRO_CONTENT_ALPHA)) { - // Attempt to fake it when we don't have an alpha channel on our - // pixmap. If that's not possible, at least clear the window to - // avoid drawing artifacts. - - // This Would not work without double buffering, but we always use it. - cairo_set_source_surface(cr.get(), cairo_get_group_target(context->platformContext()->cr()), - -m_windowRect.x(), -m_windowRect.y()); - cairo_set_operator(cr.get(), CAIRO_OPERATOR_SOURCE); - } else - cairo_set_operator(cr.get(), CAIRO_OPERATOR_CLEAR); - - cairo_rectangle(cr.get(), exposedRect.x(), exposedRect.y(), - exposedRect.width(), exposedRect.height()); - cairo_fill(cr.get()); - } - - XEvent xevent; - memset(&xevent, 0, sizeof(XEvent)); - XGraphicsExposeEvent& exposeEvent = xevent.xgraphicsexpose; - exposeEvent.type = GraphicsExpose; - exposeEvent.display = display; - exposeEvent.drawable = m_drawable; - exposeEvent.x = exposedRect.x(); - exposeEvent.y = exposedRect.y(); - exposeEvent.width = exposedRect.x() + exposedRect.width(); // flash bug? it thinks width is the right in transparent mode - exposeEvent.height = exposedRect.y() + exposedRect.height(); // flash bug? it thinks height is the bottom in transparent mode - - dispatchNPEvent(xevent); - - if (syncX) - XSync(m_pluginDisplay, false); // sync changes by plugin - - cairo_t* cr = context->platformContext()->cr(); - cairo_save(cr); - - cairo_set_source_surface(cr, drawableSurface.get(), frameRect().x(), frameRect().y()); - - cairo_rectangle(cr, - frameRect().x() + exposedRect.x(), frameRect().y() + exposedRect.y(), - exposedRect.width(), exposedRect.height()); - cairo_clip(cr); - - if (m_isTransparent) - cairo_set_operator(cr, CAIRO_OPERATOR_OVER); - else - cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE); - cairo_paint(cr); - - cairo_restore(cr); -} - -void PluginView::handleKeyboardEvent(KeyboardEvent* event) -{ - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - - if (!m_isStarted || m_status != PluginStatusLoadedSuccessfully) - return; - - if (event->type() != eventNames().keydownEvent && event->type() != eventNames().keyupEvent) - return; - - NPEvent xEvent; - initXEvent(&xEvent); - GdkEventKey* gdkEvent = event->keyEvent()->gdkEventKey(); - - xEvent.type = (event->type() == eventNames().keydownEvent) ? 2 : 3; // KeyPress/Release get unset somewhere - xEvent.xkey.root = getRootWindow(m_parentFrame.get()); - xEvent.xkey.subwindow = 0; // we have no child window - xEvent.xkey.time = event->timeStamp(); - xEvent.xkey.state = gdkEvent->state; // GdkModifierType mirrors xlib state masks - xEvent.xkey.keycode = gdkEvent->hardware_keycode; - xEvent.xkey.same_screen = true; - - // NOTE: As the XEvents sent to the plug-in are synthesized and there is not a native window - // corresponding to the plug-in rectangle, some of the members of the XEvent structures are not - // set to their normal Xserver values. e.g. Key events don't have a position. - // source: https://developer.mozilla.org/en/NPEvent - xEvent.xkey.x = 0; - xEvent.xkey.y = 0; - xEvent.xkey.x_root = 0; - xEvent.xkey.y_root = 0; - - if (dispatchNPEvent(xEvent)) - event->setDefaultHandled(); -} - -static unsigned int inputEventState(MouseEvent* event) -{ - unsigned int state = 0; - if (event->ctrlKey()) - state |= ControlMask; - if (event->shiftKey()) - state |= ShiftMask; - if (event->altKey()) - state |= Mod1Mask; - if (event->metaKey()) - state |= Mod4Mask; - return state; -} - -void PluginView::initXEvent(XEvent* xEvent) -{ - memset(xEvent, 0, sizeof(XEvent)); - - xEvent->xany.serial = 0; // we are unaware of the last request processed by X Server - xEvent->xany.send_event = false; - GtkWidget* widget = m_parentFrame->view()->hostWindow()->platformPageClient(); - xEvent->xany.display = GDK_DISPLAY_XDISPLAY(gtk_widget_get_display(widget)); - - // Mozilla also sends None here for windowless plugins. See nsObjectFrame.cpp in the Mozilla sources. - // This method also sets up FocusIn and FocusOut events for windows plugins, but Mozilla doesn't - // even send these types of events to windowed plugins. In the future, it may be good to only - // send them to windowless plugins. - xEvent->xany.window = None; -} - -static void setXButtonEventSpecificFields(XEvent* xEvent, MouseEvent* event, const IntPoint& postZoomPos, Frame* parentFrame) -{ - XButtonEvent& xbutton = xEvent->xbutton; - xbutton.type = event->type() == eventNames().mousedownEvent ? ButtonPress : ButtonRelease; - xbutton.root = getRootWindow(parentFrame); - xbutton.subwindow = 0; - xbutton.time = event->timeStamp(); - xbutton.x = postZoomPos.x(); - xbutton.y = postZoomPos.y(); - xbutton.x_root = event->screenX(); - xbutton.y_root = event->screenY(); - xbutton.state = inputEventState(event); - switch (event->button()) { - case MiddleButton: - xbutton.button = Button2; - break; - case RightButton: - xbutton.button = Button3; - break; - case LeftButton: - default: - xbutton.button = Button1; - break; - } - xbutton.same_screen = true; -} - -static void setXMotionEventSpecificFields(XEvent* xEvent, MouseEvent* event, const IntPoint& postZoomPos, Frame* parentFrame) -{ - XMotionEvent& xmotion = xEvent->xmotion; - xmotion.type = MotionNotify; - xmotion.root = getRootWindow(parentFrame); - xmotion.subwindow = 0; - xmotion.time = event->timeStamp(); - xmotion.x = postZoomPos.x(); - xmotion.y = postZoomPos.y(); - xmotion.x_root = event->screenX(); - xmotion.y_root = event->screenY(); - xmotion.state = inputEventState(event); - xmotion.is_hint = NotifyNormal; - xmotion.same_screen = true; -} - -static void setXCrossingEventSpecificFields(XEvent* xEvent, MouseEvent* event, const IntPoint& postZoomPos, Frame* parentFrame) -{ - XCrossingEvent& xcrossing = xEvent->xcrossing; - xcrossing.type = event->type() == eventNames().mouseoverEvent ? EnterNotify : LeaveNotify; - xcrossing.root = getRootWindow(parentFrame); - xcrossing.subwindow = 0; - xcrossing.time = event->timeStamp(); - xcrossing.x = postZoomPos.y(); - xcrossing.y = postZoomPos.x(); - xcrossing.x_root = event->screenX(); - xcrossing.y_root = event->screenY(); - xcrossing.state = inputEventState(event); - xcrossing.mode = NotifyNormal; - xcrossing.detail = NotifyDetailNone; - xcrossing.same_screen = true; - xcrossing.focus = false; -} - -void PluginView::handleMouseEvent(MouseEvent* event) -{ - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - - if (!m_isStarted || m_status != PluginStatusLoadedSuccessfully) - return; - - if (event->button() == RightButton && m_plugin->quirks().contains(PluginQuirkIgnoreRightClickInWindowlessMode)) - return; - - if (event->type() == eventNames().mousedownEvent) { - if (Page* page = m_parentFrame->page()) - page->focusController().setActive(true); - focusPluginElement(); - } - - NPEvent xEvent; - initXEvent(&xEvent); - - IntPoint postZoomPos = roundedIntPoint(m_element->renderer()->absoluteToLocal(event->absoluteLocation())); - - if (event->type() == eventNames().mousedownEvent || event->type() == eventNames().mouseupEvent) - setXButtonEventSpecificFields(&xEvent, event, postZoomPos, m_parentFrame.get()); - else if (event->type() == eventNames().mousemoveEvent) - setXMotionEventSpecificFields(&xEvent, event, postZoomPos, m_parentFrame.get()); - else if (event->type() == eventNames().mouseoutEvent || event->type() == eventNames().mouseoverEvent) { - setXCrossingEventSpecificFields(&xEvent, event, postZoomPos, m_parentFrame.get()); - - // This is a work-around for plugins which change the cursor. When that happens we - // get out of sync with GDK somehow. Resetting the cursor here seems to fix the issue. - if (event->type() == eventNames().mouseoutEvent) - gdk_window_set_cursor(gtk_widget_get_window(m_parentFrame->view()->hostWindow()->platformPageClient()), 0); - } - else - return; - - if (dispatchNPEvent(xEvent)) - event->setDefaultHandled(); -} - -void PluginView::handleFocusInEvent() -{ - if (!m_isStarted || m_status != PluginStatusLoadedSuccessfully) - return; - - XEvent npEvent; - initXEvent(&npEvent); - - XFocusChangeEvent& event = npEvent.xfocus; - event.type = 9; // FocusIn gets unset somewhere - event.mode = NotifyNormal; - event.detail = NotifyDetailNone; - - dispatchNPEvent(npEvent); -} - -void PluginView::handleFocusOutEvent() -{ - if (!m_isStarted || m_status != PluginStatusLoadedSuccessfully) - return; - - XEvent npEvent; - initXEvent(&npEvent); - - XFocusChangeEvent& event = npEvent.xfocus; - event.type = 10; // FocusOut gets unset somewhere - event.mode = NotifyNormal; - event.detail = NotifyDetailNone; - - dispatchNPEvent(npEvent); -} - -void PluginView::setParent(ScrollView* parent) -{ - Widget::setParent(parent); - - if (parent) - init(); -} - -void PluginView::setNPWindowRect(const IntRect&) -{ - if (!m_isWindowed) - setNPWindowIfNeeded(); -} - -void PluginView::setNPWindowIfNeeded() -{ - if (!m_isStarted || !parent() || !m_plugin->pluginFuncs()->setwindow) - return; - - // If the plugin didn't load sucessfully, no point in calling setwindow - if (m_status != PluginStatusLoadedSuccessfully) - return; - - // On Unix, only call plugin's setwindow if it's full-page or windowed - if (m_mode != NP_FULL && m_mode != NP_EMBED) - return; - - // Check if the platformPluginWidget still exists - if (m_isWindowed && !platformPluginWidget()) - return; - - if (m_clipRect.isEmpty()) { - // If width or height are null, set the clipRect to null, - // indicating that the plugin is not visible/scrolled out. - m_npWindow.clipRect.left = 0; - m_npWindow.clipRect.right = 0; - m_npWindow.clipRect.top = 0; - m_npWindow.clipRect.bottom = 0; - } else { - // Clipping rectangle of the plug-in; the origin is the top left corner of the drawable or window. - m_npWindow.clipRect.left = m_npWindow.x + m_clipRect.x(); - m_npWindow.clipRect.top = m_npWindow.y + m_clipRect.y(); - m_npWindow.clipRect.right = m_npWindow.x + m_clipRect.x() + m_clipRect.width(); - m_npWindow.clipRect.bottom = m_npWindow.y + m_clipRect.y() + m_clipRect.height(); - } - - // FLASH WORKAROUND: Only set initially. Multiple calls to - // setNPWindow() cause the plugin to crash in windowed mode. - if (!m_plugin->quirks().contains(PluginQuirkDontCallSetWindowMoreThanOnce) || !m_isWindowed - || m_npWindow.width == static_cast<uint32_t>(-1) || m_npWindow.height == static_cast<uint32_t>(-1)) { - m_npWindow.width = m_windowRect.width(); - m_npWindow.height = m_windowRect.height(); - } - - PluginView::setCurrentPluginView(this); - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - setCallingPlugin(true); - m_plugin->pluginFuncs()->setwindow(m_instance, &m_npWindow); - setCallingPlugin(false); - PluginView::setCurrentPluginView(0); - - if (!m_isWindowed) - return; - - // GtkXtBin will call gtk_widget_size_allocate, so we don't need to do it here. - if (!m_needsXEmbed) { - gtk_xtbin_set_position(GTK_XTBIN(platformPluginWidget()), m_windowRect.x(), m_windowRect.y()); - gtk_xtbin_resize(platformPluginWidget(), m_windowRect.width(), m_windowRect.height()); - return; - } - - m_delayedAllocation = m_windowRect; - updateWidgetAllocationAndClip(); -} - -void PluginView::updateWidgetAllocationAndClip() -{ - // If the window has not been embedded yet (the plug added), we delay setting its allocation until - // that point. This fixes issues with some Java plugin instances not rendering immediately. - if (!m_plugAdded || m_delayedAllocation.isEmpty()) - return; - - GtkWidget* widget = platformPluginWidget(); - if (gtk_widget_get_realized(widget)) { - GdkRectangle clipRect = m_clipRect; -#ifdef GTK_API_VERSION_2 - GdkRegion* clipRegion = gdk_region_rectangle(&clipRect); - gdk_window_shape_combine_region(gtk_widget_get_window(widget), clipRegion, 0, 0); - gdk_region_destroy(clipRegion); -#else - cairo_region_t* clipRegion = cairo_region_create_rectangle(&clipRect); - gdk_window_shape_combine_region(gtk_widget_get_window(widget), clipRegion, 0, 0); - cairo_region_destroy(clipRegion); -#endif - } - - // The goal is to try to avoid calling gtk_widget_size_allocate in the WebView's - // size-allocate method. It blocks the main loop and if the widget is offscreen - // or hasn't moved it isn't required. - - // Don't do anything if the allocation has not changed. - GtkAllocation currentAllocation; - gtk_widget_get_allocation(widget, ¤tAllocation); - if (currentAllocation == m_delayedAllocation) - return; - - // Don't do anything if both the old and the new allocations are outside the frame. - IntRect currentAllocationRect(currentAllocation); - currentAllocationRect.intersect(frameRect()); - if (currentAllocationRect.isEmpty() && m_clipRect.isEmpty()) - return; - - g_object_set_data(G_OBJECT(widget), "delayed-allocation", &m_delayedAllocation); -} - -void PluginView::setParentVisible(bool visible) -{ - if (isParentVisible() == visible) - return; - - Widget::setParentVisible(visible); - - if (isSelfVisible() && platformPluginWidget()) { - if (visible) - gtk_widget_show(platformPluginWidget()); - else - gtk_widget_hide(platformPluginWidget()); - } -} - -NPError PluginView::handlePostReadFile(Vector<char>& outputBuffer, uint32_t filenameLength, const char* filenameBuffer) -{ - // There doesn't seem to be any documentation about what encoding the filename - // is in, but most ports seem to assume UTF-8 here and the test plugin is definitely - // sending the path in UTF-8 encoding. - CString filename(filenameBuffer, filenameLength); - - GRefPtr<GFile> file = adoptGRef(g_file_new_for_commandline_arg(filename.data())); - if (g_file_query_file_type(file.get(), G_FILE_QUERY_INFO_NONE, 0) != G_FILE_TYPE_REGULAR) - return NPERR_FILE_NOT_FOUND; - - GRefPtr<GFileInfo> fileInfo = adoptGRef(g_file_query_info(file.get(), - G_FILE_ATTRIBUTE_STANDARD_SIZE, - G_FILE_QUERY_INFO_NONE, - 0, 0)); - if (!fileInfo) - return NPERR_FILE_NOT_FOUND; - - GRefPtr<GFileInputStream> inputStream = adoptGRef(g_file_read(file.get(), 0, 0)); - if (!inputStream) - return NPERR_FILE_NOT_FOUND; - - outputBuffer.resize(g_file_info_get_size(fileInfo.get())); - gsize bytesRead = 0; - if (!g_input_stream_read_all(G_INPUT_STREAM(inputStream.get()), - outputBuffer.data(), outputBuffer.size(), &bytesRead, 0, 0)) - return NPERR_FILE_NOT_FOUND; - - return NPERR_NO_ERROR; -} - -bool PluginView::platformGetValueStatic(NPNVariable variable, void* value, NPError* result) -{ - switch (variable) { - case NPNVToolkit: - *static_cast<uint32_t*>(value) = 2; - *result = NPERR_NO_ERROR; - return true; - - case NPNVSupportsXEmbedBool: - *static_cast<NPBool*>(value) = true; - *result = NPERR_NO_ERROR; - return true; - - case NPNVjavascriptEnabledBool: - *static_cast<NPBool*>(value) = true; - *result = NPERR_NO_ERROR; - return true; - - case NPNVSupportsWindowless: - *static_cast<NPBool*>(value) = true; - *result = NPERR_NO_ERROR; - return true; - - default: - return false; - } -} - -bool PluginView::platformGetValue(NPNVariable variable, void* value, NPError* result) -{ - switch (variable) { - case NPNVxDisplay: - if (m_needsXEmbed) - *(void **)value = (void *)GDK_DISPLAY_XDISPLAY(gdk_display_get_default()); - else - *(void **)value = (void *)GTK_XTBIN(platformPluginWidget())->xtclient.xtdisplay; - *result = NPERR_NO_ERROR; - return true; - - case NPNVxtAppContext: - if (!m_needsXEmbed) { - *(void **)value = XtDisplayToApplicationContext (GTK_XTBIN(platformPluginWidget())->xtclient.xtdisplay); - - *result = NPERR_NO_ERROR; - } else - *result = NPERR_GENERIC_ERROR; - return true; - - case NPNVnetscapeWindow: { - GdkWindow* gdkWindow = gtk_widget_get_window(m_parentFrame->view()->hostWindow()->platformPageClient()); - GdkWindow* toplevelWindow = gdk_window_get_toplevel(gdkWindow); - if (!toplevelWindow) { - *result = NPERR_GENERIC_ERROR; - return true; - } - *static_cast<Window*>(value) = GDK_WINDOW_XWINDOW(toplevelWindow); - *result = NPERR_NO_ERROR; - return true; - } - - default: - return false; - } -} - -void PluginView::invalidateRect(const IntRect& rect) -{ - if (m_isWindowed) { - gtk_widget_queue_draw_area(GTK_WIDGET(platformPluginWidget()), rect.x(), rect.y(), rect.width(), rect.height()); - return; - } - - invalidateWindowlessPluginRect(rect); -} - -void PluginView::invalidateRect(NPRect* rect) -{ - if (!rect) { - invalidate(); - return; - } - - IntRect r(rect->left, rect->top, rect->right - rect->left, rect->bottom - rect->top); - invalidateWindowlessPluginRect(r); -} - -void PluginView::invalidateRegion(NPRegion) -{ - // TODO: optimize - invalidate(); -} - -void PluginView::forceRedraw() -{ - if (m_isWindowed) - gtk_widget_queue_draw(platformPluginWidget()); - else - gtk_widget_queue_draw(m_parentFrame->view()->hostWindow()->platformPageClient()); -} - -static Display* getPluginDisplay() -{ - // The plugin toolkit might have a different X connection open. Since we're - // a gdk/gtk app, we'll (probably?) have the same X connection as any gdk-based - // plugins, so we can return that. We might want to add other implementations here - // later. - - return GDK_DISPLAY_XDISPLAY(gdk_display_get_default()); -} - -static void getVisualAndColormap(int depth, Visual** visual, Colormap* colormap) -{ - *visual = 0; - *colormap = 0; - - Display* display = GDK_DISPLAY_XDISPLAY(gdk_display_get_default()); - int rmaj, rmin; - if (depth == 32 && (!XRenderQueryVersion(display, &rmaj, &rmin) || (rmaj == 0 && rmin < 5))) - return; - - XVisualInfo templ; - templ.screen = gdk_screen_get_number(gdk_screen_get_default()); - templ.depth = depth; - templ.c_class = TrueColor; - int nVisuals; - XVisualInfo* visualInfo = XGetVisualInfo(display, VisualScreenMask | VisualDepthMask | VisualClassMask, &templ, &nVisuals); - - if (!nVisuals) - return; - - if (depth == 32) { - for (int idx = 0; idx < nVisuals; ++idx) { - XRenderPictFormat* format = XRenderFindVisualFormat(display, visualInfo[idx].visual); - if (format->type == PictTypeDirect && format->direct.alphaMask) { - *visual = visualInfo[idx].visual; - break; - } - } - } else - *visual = visualInfo[0].visual; - - XFree(visualInfo); - - if (*visual) - *colormap = XCreateColormap(display, GDK_ROOT_WINDOW(), *visual, AllocNone); -} - -gboolean PluginView::plugRemovedCallback(GtkSocket* socket, PluginView* view) -{ - view->m_plugAdded = false; - return TRUE; -} - -void PluginView::plugAddedCallback(GtkSocket* socket, PluginView* view) -{ - ASSERT(socket); - ASSERT(view); - view->m_plugAdded = true; - view->updateWidgetAllocationAndClip(); -} - -bool PluginView::platformStart() -{ - ASSERT(m_isStarted); - ASSERT(m_status == PluginStatusLoadedSuccessfully); - - if (m_plugin->pluginFuncs()->getvalue) { - PluginView::setCurrentPluginView(this); - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - setCallingPlugin(true); - m_plugin->pluginFuncs()->getvalue(m_instance, NPPVpluginNeedsXEmbed, &m_needsXEmbed); - setCallingPlugin(false); - PluginView::setCurrentPluginView(0); - } - - if (m_isWindowed) { - GtkWidget* pageClient = m_parentFrame->view()->hostWindow()->platformPageClient(); - if (m_needsXEmbed) { - // If our parent is not anchored the startup process will - // fail miserably for XEmbed plugins a bit later on when - // we try to get the ID of our window (since realize will - // fail), so let's just abort here. - if (!gtk_widget_get_parent(pageClient)) - return false; - - m_plugAdded = false; - setPlatformWidget(gtk_socket_new()); - gtk_container_add(GTK_CONTAINER(pageClient), platformPluginWidget()); - g_signal_connect(platformPluginWidget(), "plug-added", G_CALLBACK(PluginView::plugAddedCallback), this); - g_signal_connect(platformPluginWidget(), "plug-removed", G_CALLBACK(PluginView::plugRemovedCallback), this); - } else - setPlatformWidget(gtk_xtbin_new(pageClient, 0)); - } else { - setPlatformWidget(0); - m_pluginDisplay = getPluginDisplay(); - } - - show(); - - NPSetWindowCallbackStruct* ws = new NPSetWindowCallbackStruct(); - ws->type = 0; - - if (m_isWindowed) { - m_npWindow.type = NPWindowTypeWindow; - if (m_needsXEmbed) { - GtkWidget* widget = platformPluginWidget(); - gtk_widget_realize(widget); - m_npWindow.window = reinterpret_cast<void*>(gtk_socket_get_id(GTK_SOCKET(platformPluginWidget()))); - GdkWindow* window = gtk_widget_get_window(widget); - ws->display = GDK_WINDOW_XDISPLAY(window); - ws->visual = GDK_VISUAL_XVISUAL(gdk_window_get_visual(window)); - ws->depth = gdk_visual_get_depth(gdk_window_get_visual(window)); - ws->colormap = XCreateColormap(ws->display, GDK_ROOT_WINDOW(), ws->visual, AllocNone); - } else { - m_npWindow.window = reinterpret_cast<void*>((GTK_XTBIN(platformPluginWidget())->xtwindow)); - ws->display = GTK_XTBIN(platformPluginWidget())->xtdisplay; - ws->visual = GTK_XTBIN(platformPluginWidget())->xtclient.xtvisual; - ws->depth = GTK_XTBIN(platformPluginWidget())->xtclient.xtdepth; - ws->colormap = GTK_XTBIN(platformPluginWidget())->xtclient.xtcolormap; - } - XFlush (ws->display); - } else { - m_npWindow.type = NPWindowTypeDrawable; - m_npWindow.window = 0; // Not used? - - GdkScreen* gscreen = gdk_screen_get_default(); - GdkVisual* gvisual = gdk_screen_get_system_visual(gscreen); - - if (gdk_visual_get_depth(gvisual) == 32 || !m_plugin->quirks().contains(PluginQuirkRequiresDefaultScreenDepth)) { - getVisualAndColormap(32, &m_visual, &m_colormap); - ws->depth = 32; - } - - if (!m_visual) { - getVisualAndColormap(gdk_visual_get_depth(gvisual), &m_visual, &m_colormap); - ws->depth = gdk_visual_get_depth(gvisual); - } - - ws->display = GDK_DISPLAY_XDISPLAY(gdk_display_get_default()); - ws->visual = m_visual; - ws->colormap = m_colormap; - - m_npWindow.x = 0; - m_npWindow.y = 0; - m_npWindow.width = -1; - m_npWindow.height = -1; - } - - m_npWindow.ws_info = ws; - - // TODO remove in favor of null events, like mac port? - if (!(m_plugin->quirks().contains(PluginQuirkDeferFirstSetWindowCall))) - updatePluginWidget(); // was: setNPWindowIfNeeded(), but this doesn't produce 0x0 rects at first go - - return true; -} - -void PluginView::platformDestroy() -{ - if (m_drawable) { - XFreePixmap(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()), m_drawable); - m_drawable = 0; - } - - GtkWidget* widget = platformWidget(); - if (widget) { - GtkWidget* parent = gtk_widget_get_parent(widget); - ASSERT(parent); - gtk_container_remove(GTK_CONTAINER(parent), widget); - } -} - -} // namespace WebCore diff --git a/Source/WebCore/plugins/gtk/gtk2xtbin.c b/Source/WebCore/plugins/gtk/gtk2xtbin.c deleted file mode 100644 index ef75a1fe2..000000000 --- a/Source/WebCore/plugins/gtk/gtk2xtbin.c +++ /dev/null @@ -1,956 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * vim:expandtab:shiftwidth=2:tabstop=2: */ - -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Gtk2XtBin Widget Implementation. - * - * The Initial Developer of the Original Code is - * Sun Microsystems, Inc. - * Portions created by the Initial Developer are Copyright (C) 2002 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -/* - * The GtkXtBin widget allows for Xt toolkit code to be used - * inside a GTK application. - */ - -#include "config.h" -#include "GtkVersioning.h" -#include "xembed.h" -#include "gtk2xtbin.h" -#include <gtk/gtk.h> -#ifdef GTK_API_VERSION_2 -#include <gdk/gdkx.h> -#endif -#include <glib.h> -#include <assert.h> -#include <sys/time.h> -#include <sys/types.h> -#include <stdio.h> -#include <stdlib.h> -#include <unistd.h> - -/* Xlib/Xt stuff */ -#include <X11/Xlib.h> -#include <X11/Xutil.h> -#include <X11/Shell.h> -#include <X11/Intrinsic.h> -#include <X11/StringDefs.h> - -/* uncomment this if you want debugging information about widget - creation and destruction */ -#undef DEBUG_XTBIN - -#define XTBIN_MAX_EVENTS 30 - -static void gtk_xtbin_class_init (GtkXtBinClass *klass); -static void gtk_xtbin_init (GtkXtBin *xtbin); -static void gtk_xtbin_realize (GtkWidget *widget); -static void gtk_xtbin_unrealize (GtkWidget *widget); -static void gtk_xtbin_dispose (GObject *object); - -/* Xt aware XEmbed */ -static void xt_client_init (XtClient * xtclient, - Visual *xtvisual, - Colormap xtcolormap, - int xtdepth); -static void xt_client_create (XtClient * xtclient, - Window embeder, - int height, - int width ); -static void xt_client_unrealize (XtClient* xtclient); -static void xt_client_destroy (XtClient* xtclient); -static void xt_client_set_info (Widget xtplug, - unsigned long flags); -static void xt_client_event_handler (Widget w, - XtPointer client_data, - XEvent *event); -static void xt_client_handle_xembed_message (Widget w, - XtPointer client_data, - XEvent *event); -static void xt_client_focus_listener (Widget w, - XtPointer user_data, - XEvent *event); -static void xt_add_focus_listener( Widget w, XtPointer user_data ); -static void xt_add_focus_listener_tree ( Widget treeroot, XtPointer user_data); -static void xt_remove_focus_listener(Widget w, XtPointer user_data); -static void send_xembed_message (XtClient *xtclient, - long message, - long detail, - long data1, - long data2, - long time); -static int error_handler (Display *display, - XErrorEvent *error); -/* For error trap of XEmbed */ -static void trap_errors(void); -static int untrap_error(void); -static int (*old_error_handler) (Display *, XErrorEvent *); -static int trapped_error_code = 0; - -static GtkWidgetClass *parent_class = NULL; - -static Display *xtdisplay = NULL; -static String *fallback = NULL; -static gboolean xt_is_initialized = FALSE; -static gint num_widgets = 0; - -static GPollFD xt_event_poll_fd; -static gint xt_polling_timer_id = 0; -static guint tag = 0; - -static gboolean -xt_event_prepare (GSource* source_data, - gint *timeout) -{ - int mask; - - gdk_threads_enter(); - mask = XPending(xtdisplay); - gdk_threads_leave(); - - return (gboolean)mask; -} - -static gboolean -xt_event_check (GSource* source_data) -{ - gdk_threads_enter(); - - if (xt_event_poll_fd.revents & G_IO_IN) { - int mask; - mask = XPending(xtdisplay); - gdk_threads_leave(); - return (gboolean)mask; - } - - gdk_threads_leave(); - return FALSE; -} - -static gboolean -xt_event_dispatch (GSource* source_data, - GSourceFunc call_back, - gpointer user_data) -{ - XtAppContext ac; - int i = 0; - - ac = XtDisplayToApplicationContext(xtdisplay); - - gdk_threads_enter(); - - /* Process only real X traffic here. We only look for data on the - * pipe, limit it to XTBIN_MAX_EVENTS and only call - * XtAppProcessEvent so that it will look for X events. There's no - * timer processing here since we already have a timer callback that - * does it. */ - for (i=0; i < XTBIN_MAX_EVENTS && XPending(xtdisplay); i++) { - XtAppProcessEvent(ac, XtIMXEvent); - } - - gdk_threads_leave(); - - return TRUE; -} - -typedef void (*GSourceFuncsFinalize) (GSource* source); - -static GSourceFuncs xt_event_funcs = { - xt_event_prepare, - xt_event_check, - xt_event_dispatch, - (GSourceFuncsFinalize)g_free, - (GSourceFunc)NULL, - (GSourceDummyMarshal)NULL -}; - -static gboolean -xt_event_polling_timer_callback(gpointer user_data) -{ - Display * display; - XtAppContext ac; - int eventsToProcess = 20; - - display = (Display *)user_data; - ac = XtDisplayToApplicationContext(display); - - /* We need to process many Xt events here. If we just process - one event we might starve one or more Xt consumers. On the other hand - this could hang the whole app if Xt events come pouring in. So process - up to 20 Xt events right now and save the rest for later. This is a hack, - but it oughta work. We *really* should have out of process plugins. - */ - while (eventsToProcess-- && XtAppPending(ac)) - XtAppProcessEvent(ac, XtIMAll); - return TRUE; -} - -GType -gtk_xtbin_get_type (void) -{ - static GType xtbin_type = 0; - - if (!xtbin_type) { - static const GTypeInfo xtbin_info = - { - sizeof (GtkXtBinClass), - NULL, - NULL, - - (GClassInitFunc)gtk_xtbin_class_init, - NULL, - NULL, - - sizeof (GtkXtBin), - 0, - (GInstanceInitFunc)gtk_xtbin_init, - NULL - }; - xtbin_type = g_type_register_static (GTK_TYPE_SOCKET, - "GtkXtBin", - &xtbin_info, - 0); - } - return xtbin_type; -} - -static void -gtk_xtbin_class_init (GtkXtBinClass *klass) -{ - GtkWidgetClass *widget_class; - GObjectClass *object_class; - - parent_class = g_type_class_peek_parent (klass); - - widget_class = GTK_WIDGET_CLASS (klass); - widget_class->realize = gtk_xtbin_realize; - widget_class->unrealize = gtk_xtbin_unrealize; - - object_class = G_OBJECT_CLASS (klass); - object_class->dispose = gtk_xtbin_dispose; -} - -static void -gtk_xtbin_init (GtkXtBin *xtbin) -{ - xtbin->xtdisplay = NULL; - xtbin->parent_window = NULL; - xtbin->xtwindow = 0; - xtbin->x = 0; - xtbin->y = 0; -} - -static void -gtk_xtbin_realize (GtkWidget *widget) -{ - GtkXtBin *xtbin; - GtkAllocation allocation = { 0, 0, 200, 200 }; - GtkAllocation widget_allocation; - -#ifdef DEBUG_XTBIN - printf("gtk_xtbin_realize()\n"); -#endif - - g_return_if_fail (GTK_IS_XTBIN (widget)); - - xtbin = GTK_XTBIN (widget); - - /* caculate the allocation before realize */ - allocation.width = gdk_window_get_width(xtbin->parent_window); - allocation.height = gdk_window_get_height(xtbin->parent_window); - gtk_widget_size_allocate (widget, &allocation); - -#ifdef DEBUG_XTBIN - printf("initial allocation %d %d %d %d\n", x, y, w, h); -#endif - - gtk_widget_get_allocation(widget, &widget_allocation); - xtbin->width = widget_allocation.width; - xtbin->height = widget_allocation.height; - - /* use GtkSocket's realize */ - (*GTK_WIDGET_CLASS(parent_class)->realize)(widget); - - /* create the Xt client widget */ - xt_client_create(&(xtbin->xtclient), - gtk_socket_get_id(GTK_SOCKET(xtbin)), - xtbin->height, - xtbin->width); - xtbin->xtwindow = XtWindow(xtbin->xtclient.child_widget); - - gdk_flush(); - - /* now that we have created the xt client, add it to the socket. */ - gtk_socket_add_id(GTK_SOCKET(widget), xtbin->xtwindow); -} - - - -GtkWidget* -gtk_xtbin_new (GtkWidget *parent_widget, String *f) -{ - GtkXtBin *xtbin; - gpointer user_data; - GdkScreen *screen; - GdkVisual* visual; - Colormap colormap; - GdkWindow* parent_window = gtk_widget_get_window(parent_widget); - - assert(parent_window != NULL); - xtbin = g_object_new (GTK_TYPE_XTBIN, NULL); - - if (!xtbin) - return (GtkWidget*)NULL; - - if (f) - fallback = f; - - /* Initialize the Xt toolkit */ - xtbin->parent_window = parent_window; - - screen = gtk_widget_get_screen(parent_widget); - visual = gdk_screen_get_system_visual(screen); - colormap = XCreateColormap(GDK_DISPLAY_XDISPLAY(gdk_screen_get_display(screen)), - GDK_WINDOW_XWINDOW(gdk_screen_get_root_window(screen)), - GDK_VISUAL_XVISUAL(visual), AllocNone); - - xt_client_init(&(xtbin->xtclient), - GDK_VISUAL_XVISUAL(visual), - colormap, - gdk_visual_get_depth(visual)); - - if (!xtbin->xtclient.xtdisplay) { - /* If XtOpenDisplay failed, we can't go any further. - * Bail out. - */ -#ifdef DEBUG_XTBIN - printf("gtk_xtbin_init: XtOpenDisplay() returned NULL.\n"); -#endif - g_free (xtbin); - return (GtkWidget *)NULL; - } - - /* If this is the first running widget, hook this display into the - mainloop */ - if (0 == num_widgets) { - int cnumber; - /* - * hook Xt event loop into the glib event loop. - */ - - /* the assumption is that gtk_init has already been called */ - GSource* gs = g_source_new(&xt_event_funcs, sizeof(GSource)); - if (!gs) { - return NULL; - } - - g_source_set_priority(gs, GDK_PRIORITY_EVENTS); - g_source_set_can_recurse(gs, TRUE); - tag = g_source_attach(gs, (GMainContext*)NULL); -#ifdef VMS - cnumber = XConnectionNumber(xtdisplay); -#else - cnumber = ConnectionNumber(xtdisplay); -#endif - xt_event_poll_fd.fd = cnumber; - xt_event_poll_fd.events = G_IO_IN; - xt_event_poll_fd.revents = 0; /* hmm... is this correct? */ - - g_main_context_add_poll ((GMainContext*)NULL, - &xt_event_poll_fd, - G_PRIORITY_LOW); - /* add a timer so that we can poll and process Xt timers */ - xt_polling_timer_id = - g_timeout_add(25, - (GSourceFunc)xt_event_polling_timer_callback, - xtdisplay); - g_source_set_name_by_id(xt_polling_timer_id, "[WebKit] xt_event_polling_timer_callback"); - } - - /* Bump up our usage count */ - num_widgets++; - - /* Build the hierachy */ - xtbin->xtdisplay = xtbin->xtclient.xtdisplay; - gtk_widget_set_parent_window(GTK_WIDGET(xtbin), parent_window); - gdk_window_get_user_data(xtbin->parent_window, &user_data); - if (user_data) - gtk_container_add(GTK_CONTAINER(user_data), GTK_WIDGET(xtbin)); - - return GTK_WIDGET (xtbin); -} - -void -gtk_xtbin_set_position (GtkXtBin *xtbin, - gint x, - gint y) -{ - xtbin->x = x; - xtbin->y = y; - - if (gtk_widget_get_realized (GTK_WIDGET(xtbin))) - gdk_window_move (gtk_widget_get_window(GTK_WIDGET (xtbin)), x, y); -} - -void -gtk_xtbin_resize (GtkWidget *widget, - gint width, - gint height) -{ - Arg args[2]; - GtkXtBin *xtbin = GTK_XTBIN (widget); - GtkAllocation allocation; - -#ifdef DEBUG_XTBIN - printf("gtk_xtbin_resize %p %d %d\n", (void *)widget, width, height); -#endif - - xtbin->height = height; - xtbin->width = width; - - // Avoid BadValue errors in XtSetValues - if (height <= 0 || width <=0) { - height = 1; - width = 1; - } - XtSetArg(args[0], XtNheight, height); - XtSetArg(args[1], XtNwidth, width); - XtSetValues(xtbin->xtclient.top_widget, args, 2); - - /* we need to send a size allocate so the socket knows about the - size changes */ - allocation.x = xtbin->x; - allocation.y = xtbin->y; - allocation.width = xtbin->width; - allocation.height = xtbin->height; - - gtk_widget_size_allocate(widget, &allocation); -} - -static void -gtk_xtbin_unrealize (GtkWidget *object) -{ - GtkXtBin *xtbin; - GtkWidget *widget; - -#ifdef DEBUG_XTBIN - printf("gtk_xtbin_unrealize()\n"); -#endif - - /* gtk_object_destroy() will already hold a refcount on object - */ - xtbin = GTK_XTBIN(object); - widget = GTK_WIDGET(object); - - gtk_widget_set_visible(widget, FALSE); - if (gtk_widget_get_realized (widget)) { - xt_client_unrealize(&(xtbin->xtclient)); - } - - (*GTK_WIDGET_CLASS (parent_class)->unrealize)(widget); -} - -static void -gtk_xtbin_dispose (GObject *object) -{ - GtkXtBin *xtbin; - -#ifdef DEBUG_XTBIN - printf("gtk_xtbin_destroy()\n"); -#endif - - g_return_if_fail (object != NULL); - g_return_if_fail (GTK_IS_XTBIN (object)); - - xtbin = GTK_XTBIN (object); - - if(xtbin->xtwindow) { - /* remove the event handler */ - xt_client_destroy(&(xtbin->xtclient)); - xtbin->xtwindow = 0; - - num_widgets--; /* reduce our usage count */ - - /* If this is the last running widget, remove the Xt display - connection from the mainloop */ - if (0 == num_widgets) { -#ifdef DEBUG_XTBIN - printf("removing the Xt connection from the main loop\n"); -#endif - g_main_context_remove_poll((GMainContext*)NULL, &xt_event_poll_fd); - g_source_remove(tag); - - g_source_remove(xt_polling_timer_id); - xt_polling_timer_id = 0; - } - } - - G_OBJECT_CLASS(parent_class)->dispose(object); -} - -/* -* Following is the implementation of Xt XEmbedded for client side -*/ - -/* Initial Xt plugin */ -static void -xt_client_init( XtClient * xtclient, - Visual *xtvisual, - Colormap xtcolormap, - int xtdepth) -{ - XtAppContext app_context; - char *mArgv[1]; - int mArgc = 0; - - /* - * Initialize Xt stuff - */ - xtclient->top_widget = NULL; - xtclient->child_widget = NULL; - xtclient->xtdisplay = NULL; - xtclient->xtvisual = NULL; - xtclient->xtcolormap = 0; - xtclient->xtdepth = 0; - - if (!xt_is_initialized) { -#ifdef DEBUG_XTBIN - printf("starting up Xt stuff\n"); -#endif - XtToolkitInitialize(); - app_context = XtCreateApplicationContext(); - if (fallback) - XtAppSetFallbackResources(app_context, fallback); - - xtdisplay = XtOpenDisplay(app_context, gdk_get_display(), NULL, - "Wrapper", NULL, 0, &mArgc, mArgv); - if (xtdisplay) - xt_is_initialized = TRUE; - } - xtclient->xtdisplay = xtdisplay; - xtclient->xtvisual = xtvisual; - xtclient->xtcolormap = xtcolormap; - xtclient->xtdepth = xtdepth; -} - -/* Create the Xt client widgets -* */ -static void -xt_client_create ( XtClient* xtclient , - Window embedderid, - int height, - int width ) -{ - int n; - Arg args[6]; - Widget child_widget; - Widget top_widget; - -#ifdef DEBUG_XTBIN - printf("xt_client_create() \n"); -#endif - top_widget = XtAppCreateShell("drawingArea", "Wrapper", - applicationShellWidgetClass, - xtclient->xtdisplay, - NULL, 0); - xtclient->top_widget = top_widget; - - /* set size of Xt window */ - n = 0; - XtSetArg(args[n], XtNheight, height);n++; - XtSetArg(args[n], XtNwidth, width);n++; - XtSetValues(top_widget, args, n); - - child_widget = XtVaCreateWidget("form", - compositeWidgetClass, - top_widget, NULL); - - n = 0; - XtSetArg(args[n], XtNheight, height);n++; - XtSetArg(args[n], XtNwidth, width);n++; - XtSetArg(args[n], XtNvisual, xtclient->xtvisual ); n++; - XtSetArg(args[n], XtNdepth, xtclient->xtdepth ); n++; - XtSetArg(args[n], XtNcolormap, xtclient->xtcolormap ); n++; - XtSetArg(args[n], XtNborderWidth, 0); n++; - XtSetValues(child_widget, args, n); - - XSync(xtclient->xtdisplay, FALSE); - xtclient->oldwindow = top_widget->core.window; - top_widget->core.window = embedderid; - - /* this little trick seems to finish initializing the widget */ -#if XlibSpecificationRelease >= 6 - XtRegisterDrawable(xtclient->xtdisplay, - embedderid, - top_widget); -#else - _XtRegisterWindow( embedderid, - top_widget); -#endif - XtRealizeWidget(child_widget); - - /* listen to all Xt events */ - XSelectInput(xtclient->xtdisplay, - XtWindow(top_widget), - 0x0FFFFF); - xt_client_set_info (child_widget, 0); - - XtManageChild(child_widget); - xtclient->child_widget = child_widget; - - /* set the event handler */ - XtAddEventHandler(child_widget, - 0x0FFFFF & ~ResizeRedirectMask, - TRUE, - (XtEventHandler)xt_client_event_handler, xtclient); - XtAddEventHandler(child_widget, - SubstructureNotifyMask | ButtonReleaseMask, - TRUE, - (XtEventHandler)xt_client_focus_listener, - xtclient); - XSync(xtclient->xtdisplay, FALSE); -} - -static void -xt_client_unrealize ( XtClient* xtclient ) -{ -#if XlibSpecificationRelease >= 6 - XtUnregisterDrawable(xtclient->xtdisplay, - xtclient->top_widget->core.window); -#else - _XtUnregisterWindow(xtclient->top_widget->core.window, - xtclient->top_widget); -#endif - - /* flush the queue before we returning origin top_widget->core.window - or we can get X error since the window is gone */ - XSync(xtclient->xtdisplay, False); - - xtclient->top_widget->core.window = xtclient->oldwindow; - XtUnrealizeWidget(xtclient->top_widget); -} - -static void -xt_client_destroy (XtClient* xtclient) -{ - if(xtclient->top_widget) { - XtRemoveEventHandler(xtclient->child_widget, 0x0FFFFF, TRUE, - (XtEventHandler)xt_client_event_handler, xtclient); - XtDestroyWidget(xtclient->top_widget); - xtclient->top_widget = NULL; - } -} - -static void -xt_client_set_info (Widget xtplug, unsigned long flags) -{ - unsigned long buffer[2]; - - Atom infoAtom = XInternAtom(XtDisplay(xtplug), "_XEMBED_INFO", False); - - buffer[1] = 0; /* Protocol version */ - buffer[1] = flags; - - XChangeProperty (XtDisplay(xtplug), XtWindow(xtplug), - infoAtom, infoAtom, 32, - PropModeReplace, - (unsigned char *)buffer, 2); -} - -static void -xt_client_handle_xembed_message(Widget w, XtPointer client_data, XEvent *event) -{ - XtClient *xtplug = (XtClient*)client_data; - switch (event->xclient.data.l[1]) - { - case XEMBED_EMBEDDED_NOTIFY: - break; - case XEMBED_WINDOW_ACTIVATE: -#ifdef DEBUG_XTBIN - printf("Xt client get XEMBED_WINDOW_ACTIVATE\n"); -#endif - break; - case XEMBED_WINDOW_DEACTIVATE: -#ifdef DEBUG_XTBIN - printf("Xt client get XEMBED_WINDOW_DEACTIVATE\n"); -#endif - break; - case XEMBED_MODALITY_ON: -#ifdef DEBUG_XTBIN - printf("Xt client get XEMBED_MODALITY_ON\n"); -#endif - break; - case XEMBED_MODALITY_OFF: -#ifdef DEBUG_XTBIN - printf("Xt client get XEMBED_MODALITY_OFF\n"); -#endif - break; - case XEMBED_FOCUS_IN: - case XEMBED_FOCUS_OUT: - { - XEvent xevent; - memset(&xevent, 0, sizeof(xevent)); - - if(event->xclient.data.l[1] == XEMBED_FOCUS_IN) { -#ifdef DEBUG_XTBIN - printf("XTEMBED got focus in\n"); -#endif - xevent.xfocus.type = FocusIn; - } - else { -#ifdef DEBUG_XTBIN - printf("XTEMBED got focus out\n"); -#endif - xevent.xfocus.type = FocusOut; - } - - xevent.xfocus.window = XtWindow(xtplug->child_widget); - xevent.xfocus.display = XtDisplay(xtplug->child_widget); - XSendEvent(XtDisplay(xtplug->child_widget), - xevent.xfocus.window, - False, NoEventMask, - &xevent ); - XSync( XtDisplay(xtplug->child_widget), False); - } - break; - default: - break; - } /* End of XEmbed Message */ -} - -static void -xt_client_event_handler( Widget w, XtPointer client_data, XEvent *event) -{ - XtClient *xtplug = (XtClient*)client_data; - - switch(event->type) - { - case ClientMessage: - /* Handle xembed message */ - if (event->xclient.message_type== - XInternAtom (XtDisplay(xtplug->child_widget), - "_XEMBED", False)) { - xt_client_handle_xembed_message(w, client_data, event); - } - break; - case ReparentNotify: - break; - case MappingNotify: - xt_client_set_info (w, XEMBED_MAPPED); - break; - case UnmapNotify: - xt_client_set_info (w, 0); - break; - case FocusIn: - send_xembed_message ( xtplug, - XEMBED_REQUEST_FOCUS, 0, 0, 0, 0); - break; - case FocusOut: - break; - case KeyPress: -#ifdef DEBUG_XTBIN - printf("Key Press Got!\n"); -#endif - break; - default: - break; - } /* End of switch(event->type) */ -} - -static void -send_xembed_message (XtClient *xtclient, - long message, - long detail, - long data1, - long data2, - long time) -{ - XEvent xevent; - Window w=XtWindow(xtclient->top_widget); - Display* dpy=xtclient->xtdisplay; - int errorcode; - - memset(&xevent,0,sizeof(xevent)); - xevent.xclient.window = w; - xevent.xclient.type = ClientMessage; - xevent.xclient.message_type = XInternAtom(dpy,"_XEMBED",False); - xevent.xclient.format = 32; - xevent.xclient.data.l[0] = time; - xevent.xclient.data.l[1] = message; - xevent.xclient.data.l[2] = detail; - xevent.xclient.data.l[3] = data1; - xevent.xclient.data.l[4] = data2; - - trap_errors (); - XSendEvent (dpy, w, False, NoEventMask, &xevent); - XSync (dpy,False); - - if((errorcode = untrap_error())) { -#ifdef DEBUG_XTBIN - printf("send_xembed_message error(%d)!!!\n",errorcode); -#endif - } -} - -static int -error_handler(Display *display, XErrorEvent *error) -{ - trapped_error_code = error->error_code; - return 0; -} - -static void -trap_errors(void) -{ - trapped_error_code =0; - old_error_handler = XSetErrorHandler(error_handler); -} - -static int -untrap_error(void) -{ - XSetErrorHandler(old_error_handler); - if(trapped_error_code) { -#ifdef DEBUG_XTBIN - printf("Get X Window Error = %d\n", trapped_error_code); -#endif - } - return trapped_error_code; -} - -static void -xt_client_focus_listener( Widget w, XtPointer user_data, XEvent *event) -{ - Display *dpy = XtDisplay(w); - XtClient *xtclient = user_data; - Window win = XtWindow(w); - - switch(event->type) - { - case CreateNotify: - if(event->xcreatewindow.parent == win) { - Widget child=XtWindowToWidget( dpy, event->xcreatewindow.window); - if (child) - xt_add_focus_listener_tree(child, user_data); - } - break; - case DestroyNotify: - xt_remove_focus_listener( w, user_data); - break; - case ReparentNotify: - if(event->xreparent.parent == win) { - /* I am the new parent */ - Widget child=XtWindowToWidget(dpy, event->xreparent.window); - if (child) - xt_add_focus_listener_tree( child, user_data); - } - else if(event->xreparent.window == win) { - /* I am the new child */ - } - else { - /* I am the old parent */ - } - break; - case ButtonRelease: -#if 0 - XSetInputFocus(dpy, XtWindow(xtclient->child_widget), RevertToParent, event->xbutton.time); -#endif - send_xembed_message ( xtclient, - XEMBED_REQUEST_FOCUS, 0, 0, 0, 0); - break; - default: - break; - } /* End of switch(event->type) */ -} - -static void -xt_add_focus_listener( Widget w, XtPointer user_data) -{ - XWindowAttributes attr; - long eventmask; - XtClient *xtclient = user_data; - - trap_errors (); - XGetWindowAttributes(XtDisplay(w), XtWindow(w), &attr); - eventmask = attr.your_event_mask | SubstructureNotifyMask | ButtonReleaseMask; - XSelectInput(XtDisplay(w), - XtWindow(w), - eventmask); - - XtAddEventHandler(w, - SubstructureNotifyMask | ButtonReleaseMask, - TRUE, - (XtEventHandler)xt_client_focus_listener, - xtclient); - untrap_error(); -} - -static void -xt_remove_focus_listener(Widget w, XtPointer user_data) -{ - trap_errors (); - XtRemoveEventHandler(w, SubstructureNotifyMask | ButtonReleaseMask, TRUE, - (XtEventHandler)xt_client_focus_listener, user_data); - - untrap_error(); -} - -static void -xt_add_focus_listener_tree ( Widget treeroot, XtPointer user_data) -{ - Window win = XtWindow(treeroot); - Window *children; - Window root, parent; - Display *dpy = XtDisplay(treeroot); - unsigned int i, nchildren; - - /* ensure we don't add more than once */ - xt_remove_focus_listener( treeroot, user_data); - xt_add_focus_listener( treeroot, user_data); - trap_errors(); - if(!XQueryTree(dpy, win, &root, &parent, &children, &nchildren)) { - untrap_error(); - return; - } - - if(untrap_error()) - return; - - for(i=0; i<nchildren; ++i) { - Widget child = XtWindowToWidget(dpy, children[i]); - if (child) - xt_add_focus_listener_tree( child, user_data); - } - XFree((void*)children); - - return; -} diff --git a/Source/WebCore/plugins/gtk/gtk2xtbin.h b/Source/WebCore/plugins/gtk/gtk2xtbin.h deleted file mode 100644 index 937cd7745..000000000 --- a/Source/WebCore/plugins/gtk/gtk2xtbin.h +++ /dev/null @@ -1,161 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * vim: set expandtab shiftwidth=2 tabstop=2: */ - -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Gtk2XtBin Widget Implementation. - * - * The Initial Developer of the Original Code is - * Sun Microsystems, Inc. - * Portions created by the Initial Developer are Copyright (C) 2002 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -#ifndef __GTK_XTBIN_H__ -#define __GTK_XTBIN_H__ - -#include <gtk/gtk.h> -#ifndef GTK_API_VERSION_2 -#include <gtk/gtkx.h> -#endif -#include <X11/Intrinsic.h> -#include <X11/Xutil.h> -#include <X11/Xlib.h> -#ifdef MOZILLA_CLIENT -#include "nscore.h" -#ifdef _IMPL_GTKXTBIN_API -#define GTKXTBIN_API(type) NS_EXPORT_(type) -#else -#define GTKXTBIN_API(type) NS_IMPORT_(type) -#endif -#else -#define GTKXTBIN_API(type) type -#endif - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -typedef struct _GtkXtBin GtkXtBin; -typedef struct _GtkXtBinClass GtkXtBinClass; - -#define GTK_TYPE_XTBIN (gtk_xtbin_get_type ()) -#define GTK_XTBIN(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), \ - GTK_TYPE_XTBIN, GtkXtBin)) -#define GTK_XTBIN_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), \ - GTK_TYPE_XTBIN, GtkXtBinClass)) -#define GTK_IS_XTBIN(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), \ - GTK_TYPE_XTBIN)) -#define GTK_IS_XTBIN_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), \ - GTK_TYPE_XTBIN)) -typedef struct _XtClient XtClient; - -struct _XtClient { - Display *xtdisplay; - Widget top_widget; /* The toplevel widget */ - Widget child_widget; /* The embedded widget */ - Visual *xtvisual; - int xtdepth; - Colormap xtcolormap; - Window oldwindow; -}; - -struct _GtkXtBin -{ - GtkSocket gsocket; - GdkWindow *parent_window; - Display *xtdisplay; /* Xt Toolkit Display */ - - Window xtwindow; /* Xt Toolkit XWindow */ - gint x, y; - gint width, height; - XtClient xtclient; /* Xt Client for XEmbed */ -}; - -struct _GtkXtBinClass -{ - GtkSocketClass widget_class; -}; - -GTKXTBIN_API(GType) gtk_xtbin_get_type (void); -GTKXTBIN_API(GtkWidget *) gtk_xtbin_new (GtkWidget *parent_widget, String *f); -GTKXTBIN_API(void) gtk_xtbin_set_position (GtkXtBin *xtbin, - gint x, - gint y); -GTKXTBIN_API(void) gtk_xtbin_resize (GtkWidget *widget, - gint width, - gint height); - -typedef struct _XtTMRec { - XtTranslations translations; /* private to Translation Manager */ - XtBoundActions proc_table; /* procedure bindings for actions */ - struct _XtStateRec *current_state; /* Translation Manager state ptr */ - unsigned long lastEventTime; -} XtTMRec, *XtTM; - -typedef struct _CorePart { - Widget self; /* pointer to widget itself */ - WidgetClass widget_class; /* pointer to Widget's ClassRec */ - Widget parent; /* parent widget */ - XrmName xrm_name; /* widget resource name quarkified */ - Boolean being_destroyed; /* marked for destroy */ - XtCallbackList destroy_callbacks; /* who to call when widget destroyed */ - XtPointer constraints; /* constraint record */ - Position x, y; /* window position */ - Dimension width, height; /* window dimensions */ - Dimension border_width; /* window border width */ - Boolean managed; /* is widget geometry managed? */ - Boolean sensitive; /* is widget sensitive to user events*/ - Boolean ancestor_sensitive; /* are all ancestors sensitive? */ - XtEventTable event_table; /* private to event dispatcher */ - XtTMRec tm; /* translation management */ - XtTranslations accelerators; /* accelerator translations */ - Pixel border_pixel; /* window border pixel */ - Pixmap border_pixmap; /* window border pixmap or NULL */ - WidgetList popup_list; /* list of popups */ - Cardinal num_popups; /* how many popups */ - String name; /* widget resource name */ - Screen *screen; /* window's screen */ - Colormap colormap; /* colormap */ - Window window; /* window ID */ - Cardinal depth; /* number of planes in window */ - Pixel background_pixel; /* window background pixel */ - Pixmap background_pixmap; /* window background pixmap or NULL */ - Boolean visible; /* is window mapped and not occluded?*/ - Boolean mapped_when_managed;/* map window if it's managed? */ -} CorePart; - -typedef struct _WidgetRec { - CorePart core; - } WidgetRec, CoreRec; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* __GTK_XTBIN_H__ */ diff --git a/Source/WebCore/plugins/gtk/xembed.h b/Source/WebCore/plugins/gtk/xembed.h deleted file mode 100644 index dff7be9cd..000000000 --- a/Source/WebCore/plugins/gtk/xembed.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- - * vim:expandtab:shiftwidth=2:tabstop=2: */ - -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the XEMBED Declaration. - * - * The Initial Developer of the Original Code is - * Sun Microsystems, Inc. - * Portions created by the Initial Developer are Copyright (C) 2002 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -/* XEMBED messages */ -#define XEMBED_EMBEDDED_NOTIFY 0 -#define XEMBED_WINDOW_ACTIVATE 1 -#define XEMBED_WINDOW_DEACTIVATE 2 -#define XEMBED_REQUEST_FOCUS 3 -#define XEMBED_FOCUS_IN 4 -#define XEMBED_FOCUS_OUT 5 -#define XEMBED_FOCUS_NEXT 6 -#define XEMBED_FOCUS_PREV 7 -#define XEMBED_GRAB_KEY 8 -#define XEMBED_UNGRAB_KEY 9 -#define XEMBED_MODALITY_ON 10 -#define XEMBED_MODALITY_OFF 11 - -/* Non standard messages*/ -#define XEMBED_GTK_GRAB_KEY 108 -#define XEMBED_GTK_UNGRAB_KEY 109 - -/* Details for XEMBED_FOCUS_IN: */ -#define XEMBED_FOCUS_CURRENT 0 -#define XEMBED_FOCUS_FIRST 1 -#define XEMBED_FOCUS_LAST 2 - -/* Flags for _XEMBED_INFO */ -#define XEMBED_MAPPED (1 << 0) diff --git a/Source/WebCore/plugins/npapi.h b/Source/WebCore/plugins/npapi.h index 8d36f8ba5..e9e532b0f 100644 --- a/Source/WebCore/plugins/npapi.h +++ b/Source/WebCore/plugins/npapi.h @@ -96,7 +96,7 @@ /*----------------------------------------------------------------------*/ #define NP_VERSION_MAJOR 0 -#define NP_VERSION_MINOR 24 +#define NP_VERSION_MINOR 26 /* The OS/2 version of Netscape uses RC_DATA to define the @@ -379,9 +379,9 @@ typedef enum { , NPPVpluginCoreAnimationLayer = 1003 #endif -#if defined(MOZ_PLATFORM_MAEMO) && (MOZ_PLATFORM_MAEMO >= 5) - , NPPVpluginWindowlessLocalBool = 2002 -#endif + /* Used for figuring out whether a plug-in is playing audio. */ + , NPPVpluginIsPlayingAudio = 4000 + } NPPVariable; /* @@ -432,9 +432,9 @@ typedef enum { , NPNVsupportsCompositingCoreAnimationPluginsBool = 74656 /* TRUE if the browser supports CA model compositing */ #endif /* XP_MACOSX */ -#if defined(MOZ_PLATFORM_MAEMO) && (MOZ_PLATFORM_MAEMO >= 5) - , NPNVSupportsWindowlessLocal = 2002 -#endif + + , NPNVmuteAudioBool = 4000 + } NPNVariable; typedef enum { @@ -475,22 +475,6 @@ typedef struct _NPWindow NPWindowType type; /* Is this a window or a drawable? */ } NPWindow; -typedef struct _NPImageExpose -{ - char* data; /* image pointer */ - int32_t stride; /* Stride of data image pointer */ - int32_t depth; /* Depth of image pointer */ - int32_t x; /* Expose x */ - int32_t y; /* Expose y */ - uint32_t width; /* Expose width */ - uint32_t height; /* Expose height */ - NPSize dataSize; /* Data buffer size */ - float translateX; /* translate X matrix value */ - float translateY; /* translate Y matrix value */ - float scaleX; /* scale X matrix value */ - float scaleY; /* scale Y matrix value */ -} NPImageExpose; - typedef struct _NPFullPrint { NPBool pluginPrinted;/* Set TRUE if plugin handled fullscreen printing */ @@ -884,6 +868,9 @@ uint32_t NP_LOADDS NPN_ScheduleTimer(NPP instance, uint32_t interval, NPBool void NP_LOADDS NPN_UnscheduleTimer(NPP instance, uint32_t timerID); NPError NP_LOADDS NPN_PopUpContextMenu(NPP instance, NPMenu* menu); NPBool NP_LOADDS NPN_ConvertPoint(NPP instance, double sourceX, double sourceY, NPCoordinateSpace sourceSpace, double *destX, double *destY, NPCoordinateSpace destSpace); +NPBool NP_LOADDS NPN_HandleEvent(NPP instance, void *event, NPBool handled); +NPBool NP_LOADDS NPN_UnfocusInstance(NPP instance, NPFocusDirection direction); +void NP_LOADDS NPN_URLRedirectResponse(NPP instance, void* notifyData, NPBool allow); #ifdef __cplusplus } /* end extern "C" */ diff --git a/Source/WebCore/plugins/npfunctions.h b/Source/WebCore/plugins/npfunctions.h index 0d4f3fc02..d65f76b0d 100644 --- a/Source/WebCore/plugins/npfunctions.h +++ b/Source/WebCore/plugins/npfunctions.h @@ -10,10 +10,10 @@ * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR @@ -71,6 +71,9 @@ typedef uint32_t (*NPN_ScheduleTimerProcPtr)(NPP npp, uint32_t interval, NPBool typedef void (*NPN_UnscheduleTimerProcPtr)(NPP npp, uint32_t timerID); typedef NPError (*NPN_PopUpContextMenuProcPtr)(NPP instance, NPMenu* menu); typedef NPBool (*NPN_ConvertPointProcPtr)(NPP npp, double sourceX, double sourceY, NPCoordinateSpace sourceSpace, double *destX, double *destY, NPCoordinateSpace destSpace); +typedef NPBool (*NPN_HandleEventPtr)(NPP instance, void *event, NPBool handled); +typedef NPBool (*NPN_UnfocusInstancePtr)(NPP instance, NPFocusDirection direction); +typedef void (*NPN_URLRedirectResponsePtr)(NPP instance, void* notifyData, NPBool allow); typedef void (*NPN_ReleaseVariantValueProcPtr) (NPVariant *variant); @@ -175,6 +178,9 @@ typedef struct _NPNetscapeFuncs { NPN_UnscheduleTimerProcPtr unscheduletimer; NPN_PopUpContextMenuProcPtr popupcontextmenu; NPN_ConvertPointProcPtr convertpoint; + NPN_HandleEventPtr handleevent; + NPN_UnfocusInstancePtr unfocusinstance; + NPN_URLRedirectResponsePtr urlredirectresponse; } NPNetscapeFuncs; typedef struct _NPPluginFuncs { diff --git a/Source/WebCore/plugins/npruntime.h b/Source/WebCore/plugins/npruntime.h index 828a34093..b0ec6c6ba 100644 --- a/Source/WebCore/plugins/npruntime.h +++ b/Source/WebCore/plugins/npruntime.h @@ -1,6 +1,6 @@ /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* - * Copyright (c) 2004, Apple Computer, Inc. and The Mozilla Foundation. + * Copyright (c) 2004, Apple Inc. and The Mozilla Foundation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -12,7 +12,7 @@ * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * 3. Neither the names of Apple Computer, Inc. ("Apple") or The Mozilla + * 3. Neither the names of Apple Inc. ("Apple") or The Mozilla * Foundation ("Mozilla") nor the names of their contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. diff --git a/Source/WebCore/plugins/win/PluginDatabaseWin.cpp b/Source/WebCore/plugins/win/PluginDatabaseWin.cpp deleted file mode 100644 index 5cd6d1443..000000000 --- a/Source/WebCore/plugins/win/PluginDatabaseWin.cpp +++ /dev/null @@ -1,436 +0,0 @@ -/* - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. - * Copyright (C) 2008 Collabora, Ltd. All rights reserved. - * Copyright (C) 2008-2009 Torch Mobile, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginDatabase.h" - -#include "Frame.h" -#include "URL.h" -#include "PluginPackage.h" -#include <wtf/WindowsExtras.h> - -#if OS(WINCE) -// WINCE doesn't support Registry Key Access Rights. The parameter should always be 0 -#ifndef KEY_ENUMERATE_SUB_KEYS -#define KEY_ENUMERATE_SUB_KEYS 0 -#endif - -BOOL PathRemoveFileSpec(LPWSTR moduleFileNameStr) -{ - if (!*moduleFileNameStr) - return FALSE; - - LPWSTR lastPos = 0; - LPWSTR curPos = moduleFileNameStr; - do { - if (*curPos == L'/' || *curPos == L'\\') - lastPos = curPos; - } while (*++curPos); - - if (lastPos == curPos - 1) - return FALSE; - - if (lastPos) - *lastPos = 0; - else { - moduleFileNameStr[0] = L'\\'; - moduleFileNameStr[1] = 0; - } - - return TRUE; -} -#endif - -namespace WebCore { - -static inline void addPluginPathsFromRegistry(HKEY rootKey, HashSet<String>& paths) -{ - HKEY key; - HRESULT result = RegOpenKeyExW(rootKey, L"Software\\MozillaPlugins", 0, KEY_ENUMERATE_SUB_KEYS, &key); - - if (result != ERROR_SUCCESS) - return; - - wchar_t name[128]; - FILETIME lastModified; - - // Enumerate subkeys - for (int i = 0;; i++) { - DWORD nameLen = WTF_ARRAY_LENGTH(name); - result = RegEnumKeyExW(key, i, name, &nameLen, 0, 0, 0, &lastModified); - - if (result != ERROR_SUCCESS) - break; - - WCHAR pathStr[_MAX_PATH]; - DWORD pathStrSize = sizeof(pathStr); - DWORD type; - - result = getRegistryValue(key, name, L"Path", &type, pathStr, &pathStrSize); - if (result != ERROR_SUCCESS || type != REG_SZ) - continue; - - paths.add(String(pathStr, pathStrSize / sizeof(WCHAR) - 1)); - } - - RegCloseKey(key); -} - -void PluginDatabase::getPluginPathsInDirectories(HashSet<String>& paths) const -{ - // FIXME: This should be a case insensitive set. - HashSet<String> uniqueFilenames; - - HANDLE hFind = INVALID_HANDLE_VALUE; - WIN32_FIND_DATAW findFileData; - - String oldWMPPluginPath; - String newWMPPluginPath; - - Vector<String>::const_iterator end = m_pluginDirectories.end(); - for (Vector<String>::const_iterator it = m_pluginDirectories.begin(); it != end; ++it) { - String pattern = *it + "\\*"; - - hFind = FindFirstFileW(pattern.charactersWithNullTermination().data(), &findFileData); - - if (hFind == INVALID_HANDLE_VALUE) - continue; - - do { - if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - continue; - - String filename = String(findFileData.cFileName, wcslen(findFileData.cFileName)); - if ((!filename.startsWith("np", false) || !filename.endsWith("dll", false)) && - (!equalIgnoringCase(filename, "Plugin.dll") || !it->endsWith("Shockwave 10", false))) - continue; - - String fullPath = *it + "\\" + filename; - if (!uniqueFilenames.add(fullPath).isNewEntry) - continue; - - paths.add(fullPath); - - if (equalIgnoringCase(filename, "npdsplay.dll")) - oldWMPPluginPath = fullPath; - else if (equalIgnoringCase(filename, "np-mswmp.dll")) - newWMPPluginPath = fullPath; - - } while (FindNextFileW(hFind, &findFileData) != 0); - - FindClose(hFind); - } - - addPluginPathsFromRegistry(HKEY_LOCAL_MACHINE, paths); - addPluginPathsFromRegistry(HKEY_CURRENT_USER, paths); - - // If both the old and new WMP plugin are present in the plugins set, - // we remove the old one so we don't end up choosing the old one. - if (!oldWMPPluginPath.isEmpty() && !newWMPPluginPath.isEmpty()) - paths.remove(oldWMPPluginPath); -} - -static inline Vector<int> parseVersionString(const String& versionString) -{ - Vector<int> version; - - unsigned startPos = 0; - unsigned endPos; - - while (startPos < versionString.length()) { - for (endPos = startPos; endPos < versionString.length(); ++endPos) - if (versionString[endPos] == '.' || versionString[endPos] == '_') - break; - - int versionComponent = versionString.substring(startPos, endPos - startPos).toInt(); - version.append(versionComponent); - - startPos = endPos + 1; - } - - return version; -} - -// This returns whether versionA is higher than versionB -static inline bool compareVersions(const Vector<int>& versionA, const Vector<int>& versionB) -{ - for (unsigned i = 0; i < versionA.size(); i++) { - if (i >= versionB.size()) - return true; - - if (versionA[i] > versionB[i]) - return true; - else if (versionA[i] < versionB[i]) - return false; - } - - // If we come here, the versions are either the same or versionB has an extra component, just return false - return false; -} - -static inline void addMozillaPluginDirectories(Vector<String>& directories) -{ - // Enumerate all Mozilla plugin directories in the registry - HKEY key; - LONG result; - - result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("Software\\Mozilla"), 0, KEY_READ, &key); - if (result == ERROR_SUCCESS) { - WCHAR name[128]; - FILETIME lastModified; - - // Enumerate subkeys - for (int i = 0;; i++) { - DWORD nameLen = sizeof(name) / sizeof(WCHAR); - result = RegEnumKeyExW(key, i, name, &nameLen, 0, 0, 0, &lastModified); - - if (result != ERROR_SUCCESS) - break; - - String extensionsPath = String(name, nameLen) + "\\Extensions"; - HKEY extensionsKey; - - // Try opening the key - result = RegOpenKeyEx(key, extensionsPath.charactersWithNullTermination().data(), 0, KEY_READ, &extensionsKey); - - if (result == ERROR_SUCCESS) { - // Now get the plugins directory - WCHAR pluginsDirectoryStr[_MAX_PATH]; - DWORD pluginsDirectorySize = sizeof(pluginsDirectoryStr); - DWORD type; - - result = RegQueryValueEx(extensionsKey, TEXT("Plugins"), 0, &type, (LPBYTE)&pluginsDirectoryStr, &pluginsDirectorySize); - - if (result == ERROR_SUCCESS && type == REG_SZ) - directories.append(String(pluginsDirectoryStr, pluginsDirectorySize / sizeof(WCHAR) - 1)); - - RegCloseKey(extensionsKey); - } - } - - RegCloseKey(key); - } -} - -static inline void addWindowsMediaPlayerPluginDirectory(Vector<String>& directories) -{ -#if !OS(WINCE) - // The new WMP Firefox plugin is installed in \PFiles\Plugins if it can't find any Firefox installs - WCHAR pluginDirectoryStr[_MAX_PATH + 1]; - DWORD pluginDirectorySize = ::ExpandEnvironmentStringsW(TEXT("%SYSTEMDRIVE%\\PFiles\\Plugins"), pluginDirectoryStr, WTF_ARRAY_LENGTH(pluginDirectoryStr)); - - if (pluginDirectorySize > 0 && pluginDirectorySize <= WTF_ARRAY_LENGTH(pluginDirectoryStr)) - directories.append(String(pluginDirectoryStr, pluginDirectorySize - 1)); -#endif - - DWORD type; - WCHAR installationDirectoryStr[_MAX_PATH]; - DWORD installationDirectorySize = sizeof(installationDirectoryStr); - - HRESULT result = getRegistryValue(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\MediaPlayer", L"Installation Directory", &type, &installationDirectoryStr, &installationDirectorySize); - - if (result == ERROR_SUCCESS && type == REG_SZ) - directories.append(String(installationDirectoryStr, installationDirectorySize / sizeof(WCHAR) - 1)); -} - -static inline void addQuickTimePluginDirectory(Vector<String>& directories) -{ - DWORD type; - WCHAR installationDirectoryStr[_MAX_PATH]; - DWORD installationDirectorySize = sizeof(installationDirectoryStr); - - HRESULT result = getRegistryValue(HKEY_LOCAL_MACHINE, L"Software\\Apple Computer, Inc.\\QuickTime", L"InstallDir", &type, &installationDirectoryStr, &installationDirectorySize); - - if (result == ERROR_SUCCESS && type == REG_SZ) { - String pluginDir = String(installationDirectoryStr, installationDirectorySize / sizeof(WCHAR) - 1) + "\\plugins"; - directories.append(pluginDir); - } -} - -static inline void addAdobeAcrobatPluginDirectory(Vector<String>& directories) -{ - HKEY key; - HRESULT result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("Software\\Adobe\\Acrobat Reader"), 0, KEY_READ, &key); - if (result != ERROR_SUCCESS) - return; - - WCHAR name[128]; - FILETIME lastModified; - - Vector<int> latestAcrobatVersion; - String latestAcrobatVersionString; - - // Enumerate subkeys - for (int i = 0;; i++) { - DWORD nameLen = sizeof(name) / sizeof(WCHAR); - result = RegEnumKeyExW(key, i, name, &nameLen, 0, 0, 0, &lastModified); - - if (result != ERROR_SUCCESS) - break; - - Vector<int> acrobatVersion = parseVersionString(String(name, nameLen)); - if (compareVersions(acrobatVersion, latestAcrobatVersion)) { - latestAcrobatVersion = acrobatVersion; - latestAcrobatVersionString = String(name, nameLen); - } - } - - if (!latestAcrobatVersionString.isNull()) { - DWORD type; - WCHAR acrobatInstallPathStr[_MAX_PATH]; - DWORD acrobatInstallPathSize = sizeof(acrobatInstallPathStr); - - String acrobatPluginKeyPath = "Software\\Adobe\\Acrobat Reader\\" + latestAcrobatVersionString + "\\InstallPath"; - result = getRegistryValue(HKEY_LOCAL_MACHINE, acrobatPluginKeyPath.charactersWithNullTermination().data(), 0, &type, acrobatInstallPathStr, &acrobatInstallPathSize); - - if (result == ERROR_SUCCESS) { - String acrobatPluginDirectory = String(acrobatInstallPathStr, acrobatInstallPathSize / sizeof(WCHAR) - 1) + "\\browser"; - directories.append(acrobatPluginDirectory); - } - } - - RegCloseKey(key); -} - -static inline void addJavaPluginDirectory(Vector<String>& directories) -{ - HKEY key; - HRESULT result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("Software\\JavaSoft\\Java Plug-in"), 0, KEY_READ, &key); - if (result != ERROR_SUCCESS) - return; - - WCHAR name[128]; - FILETIME lastModified; - - Vector<int> latestJavaVersion; - String latestJavaVersionString; - - // Enumerate subkeys - for (int i = 0;; i++) { - DWORD nameLen = sizeof(name) / sizeof(WCHAR); - result = RegEnumKeyExW(key, i, name, &nameLen, 0, 0, 0, &lastModified); - - if (result != ERROR_SUCCESS) - break; - - Vector<int> javaVersion = parseVersionString(String(name, nameLen)); - if (compareVersions(javaVersion, latestJavaVersion)) { - latestJavaVersion = javaVersion; - latestJavaVersionString = String(name, nameLen); - } - } - - if (!latestJavaVersionString.isEmpty()) { - DWORD type; - WCHAR javaInstallPathStr[_MAX_PATH]; - DWORD javaInstallPathSize = sizeof(javaInstallPathStr); - DWORD useNewPluginValue; - DWORD useNewPluginSize; - - String javaPluginKeyPath = "Software\\JavaSoft\\Java Plug-in\\" + latestJavaVersionString; - result = getRegistryValue(HKEY_LOCAL_MACHINE, javaPluginKeyPath.charactersWithNullTermination().data(), L"UseNewJavaPlugin", &type, &useNewPluginValue, &useNewPluginSize); - - if (result == ERROR_SUCCESS && useNewPluginValue == 1) { - result = getRegistryValue(HKEY_LOCAL_MACHINE, javaPluginKeyPath.charactersWithNullTermination().data(), L"JavaHome", &type, javaInstallPathStr, &javaInstallPathSize); - if (result == ERROR_SUCCESS) { - String javaPluginDirectory = String(javaInstallPathStr, javaInstallPathSize / sizeof(WCHAR) - 1) + "\\bin\\new_plugin"; - directories.append(javaPluginDirectory); - } - } - } - - RegCloseKey(key); -} - -static inline String safariPluginsDirectory() -{ - WCHAR moduleFileNameStr[_MAX_PATH]; - static String pluginsDirectory; - static bool cachedPluginDirectory = false; - - if (!cachedPluginDirectory) { - cachedPluginDirectory = true; - - int moduleFileNameLen = GetModuleFileName(0, moduleFileNameStr, _MAX_PATH); - - if (!moduleFileNameLen || moduleFileNameLen == _MAX_PATH) - goto exit; - - if (!PathRemoveFileSpec(moduleFileNameStr)) - goto exit; - - pluginsDirectory = String(moduleFileNameStr) + "\\Plugins"; - } -exit: - return pluginsDirectory; -} - -static inline void addMacromediaPluginDirectories(Vector<String>& directories) -{ -#if !OS(WINCE) - WCHAR systemDirectoryStr[MAX_PATH]; - - if (!GetSystemDirectory(systemDirectoryStr, WTF_ARRAY_LENGTH(systemDirectoryStr))) - return; - - WCHAR macromediaDirectoryStr[MAX_PATH]; - - PathCombine(macromediaDirectoryStr, systemDirectoryStr, TEXT("macromed\\Flash")); - directories.append(macromediaDirectoryStr); - - PathCombine(macromediaDirectoryStr, systemDirectoryStr, TEXT("macromed\\Shockwave 10")); - directories.append(macromediaDirectoryStr); -#endif -} - -Vector<String> PluginDatabase::defaultPluginDirectories() -{ - Vector<String> directories; - String ourDirectory = safariPluginsDirectory(); - - if (!ourDirectory.isNull()) - directories.append(ourDirectory); - addQuickTimePluginDirectory(directories); - addAdobeAcrobatPluginDirectory(directories); - addMozillaPluginDirectories(directories); - addWindowsMediaPlayerPluginDirectory(directories); - addMacromediaPluginDirectories(directories); - - return directories; -} - -bool PluginDatabase::isPreferredPluginDirectory(const String& directory) -{ - String ourDirectory = safariPluginsDirectory(); - - if (!ourDirectory.isNull() && !directory.isNull()) - return ourDirectory == directory; - - return false; -} - -} diff --git a/Source/WebCore/plugins/win/PluginMessageThrottlerWin.cpp b/Source/WebCore/plugins/win/PluginMessageThrottlerWin.cpp deleted file mode 100644 index b32728980..000000000 --- a/Source/WebCore/plugins/win/PluginMessageThrottlerWin.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2006, 2007, 2008 Apple Inc. All Rights Reserved. - * Copyright (C) 2008 Collabora, Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginMessageThrottlerWin.h" - -#include "PluginView.h" -#include <wtf/ASCIICType.h> -#include <wtf/CurrentTime.h> - -using namespace WTF; - -namespace WebCore { - -// Set a timer to make sure we process any queued messages at least every 16ms. -// This value allows Flash 60 messages/second, which should be enough for video -// playback, and also gets us over the limit for kicking into high-resolution -// timer mode (see SharedTimerWin.cpp). -static const double MessageThrottleTimeInterval = 0.016; - -// During a continuous stream of messages, process one every 5ms. -static const double MessageDirectProcessingInterval = 0.005; - -PluginMessageThrottlerWin::PluginMessageThrottlerWin(PluginView* pluginView) - : m_pluginView(pluginView) - , m_back(0) - , m_front(0) - , m_messageThrottleTimer(this, &PluginMessageThrottlerWin::messageThrottleTimerFired) - , m_lastMessageTime(0) -{ - // Initialize the free list with our inline messages - for (unsigned i = 0; i < NumInlineMessages - 1; i++) - m_inlineMessages[i].next = &m_inlineMessages[i + 1]; - m_inlineMessages[NumInlineMessages - 1].next = 0; - m_freeInlineMessages = &m_inlineMessages[0]; -} - -PluginMessageThrottlerWin::~PluginMessageThrottlerWin() -{ - PluginMessage* next; - - for (PluginMessage* message = m_front; message; message = next) { - next = message->next; - freeMessage(message); - } -} - -void PluginMessageThrottlerWin::appendMessage(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) -{ - PluginMessage* message = allocateMessage(); - - message->hWnd = hWnd; - message->msg = msg; - message->wParam = wParam; - message->lParam = lParam; - message->next = 0; - - if (m_back) - m_back->next = message; - m_back = message; - if (!m_front) - m_front = message; - - // If it has been more than MessageDirectProcessingInterval between throttled messages, - // go ahead and process a message directly. - double currentTime = monotonicallyIncreasingTime(); - if (currentTime - m_lastMessageTime > MessageDirectProcessingInterval) { - processQueuedMessage(); - m_lastMessageTime = currentTime; - if (!m_front) - return; - } - - if (!m_messageThrottleTimer.isActive()) - m_messageThrottleTimer.startOneShot(MessageThrottleTimeInterval); -} - -void PluginMessageThrottlerWin::processQueuedMessage() -{ - PluginMessage* message = m_front; - m_front = m_front->next; - if (message == m_back) - m_back = 0; - - // Protect the PluginView from destruction while calling its window proc. - // <rdar://problem/6930280> - RefPtr<PluginView> protect(m_pluginView); - ::CallWindowProc(m_pluginView->pluginWndProc(), message->hWnd, message->msg, message->wParam, message->lParam); - - freeMessage(message); -} - -void PluginMessageThrottlerWin::messageThrottleTimerFired(Timer<PluginMessageThrottlerWin>*) -{ - processQueuedMessage(); - - if (m_front) - m_messageThrottleTimer.startOneShot(MessageThrottleTimeInterval); -} - -PluginMessage* PluginMessageThrottlerWin::allocateMessage() -{ - PluginMessage *message; - - if (m_freeInlineMessages) { - message = m_freeInlineMessages; - m_freeInlineMessages = message->next; - } else - message = new PluginMessage; - - return message; -} - -bool PluginMessageThrottlerWin::isInlineMessage(PluginMessage* message) -{ - return message >= &m_inlineMessages[0] && message <= &m_inlineMessages[NumInlineMessages - 1]; -} - -void PluginMessageThrottlerWin::freeMessage(PluginMessage* message) -{ - if (isInlineMessage(message)) { - message->next = m_freeInlineMessages; - m_freeInlineMessages = message; - } else - delete message; -} - -} // namespace WebCore diff --git a/Source/WebCore/plugins/win/PluginMessageThrottlerWin.h b/Source/WebCore/plugins/win/PluginMessageThrottlerWin.h deleted file mode 100644 index 0a7be70ca..000000000 --- a/Source/WebCore/plugins/win/PluginMessageThrottlerWin.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2006, 2007, 2008 Apple Inc. All Rights Reserved. - * Copyright (C) 2008 Collabora, Ltd. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef PluginMessageThrottlerWin_h -#define PluginMessageThrottlerWin_h - -#include "Timer.h" - -#include <windows.h> - -namespace WebCore { - class PluginView; - - struct PluginMessage { - HWND hWnd; - UINT msg; - WPARAM wParam; - LPARAM lParam; - - struct PluginMessage* next; - }; - - class PluginMessageThrottlerWin { - public: - PluginMessageThrottlerWin(PluginView*); - ~PluginMessageThrottlerWin(); - - void appendMessage(HWND, UINT msg, WPARAM, LPARAM); - - private: - void processQueuedMessage(); - void messageThrottleTimerFired(Timer<PluginMessageThrottlerWin>*); - PluginMessage* allocateMessage(); - bool isInlineMessage(PluginMessage* message); - void freeMessage(PluginMessage* message); - - PluginView* m_pluginView; - PluginMessage* m_back; - PluginMessage* m_front; - - static const int NumInlineMessages = 4; - PluginMessage m_inlineMessages[NumInlineMessages]; - PluginMessage* m_freeInlineMessages; - - Timer<PluginMessageThrottlerWin> m_messageThrottleTimer; - double m_lastMessageTime; - }; - -} // namespace WebCore - -#endif // PluginMessageThrottlerWin_h diff --git a/Source/WebCore/plugins/win/PluginPackageWin.cpp b/Source/WebCore/plugins/win/PluginPackageWin.cpp deleted file mode 100644 index 2270190f0..000000000 --- a/Source/WebCore/plugins/win/PluginPackageWin.cpp +++ /dev/null @@ -1,345 +0,0 @@ -/* - * Copyright (C) 2006, 2008 Apple Inc. All rights reserved. - * Copyright (C) 2008 Collabora, Ltd. All rights reserved. - * Copyright (C) 2009 Torch Mobile, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#include "config.h" -#include "PluginPackage.h" - -#include "MIMETypeRegistry.h" -#include "PluginDatabase.h" -#include "PluginDebug.h" -#include "Timer.h" -#include "npruntime_impl.h" -#include <string.h> -#include <wtf/StdLibExtras.h> -#include <wtf/text/CString.h> -#include <shlwapi.h> - -namespace WebCore { - -static String getVersionInfo(const LPVOID versionInfoData, const String& info) -{ - LPVOID buffer; - UINT bufferLength; - String subInfo = "\\StringfileInfo\\040904E4\\" + info; - bool retval = VerQueryValueW(versionInfoData, - const_cast<UChar*>(subInfo.charactersWithNullTermination().data()), - &buffer, &bufferLength); - if (!retval || bufferLength == 0) - return String(); - - // Subtract 1 from the length; we don't want the trailing null character. - return String(reinterpret_cast<UChar*>(buffer), bufferLength - 1); -} - -bool PluginPackage::isPluginBlacklisted() -{ - if (name() == "Citrix ICA Client") { - // The Citrix ICA Client plug-in requires a Mozilla-based browser; see <rdar://6418681>. - return true; - } - - if (name() == "Silverlight Plug-In") { - // workaround for <rdar://5557379> Crash in Silverlight when opening microsoft.com. - // the latest 1.0 version of Silverlight does not reproduce this crash, so allow it - // and any newer versions - static const PlatformModuleVersion slPluginMinRequired(0x51BE0000, 0x00010000); - - if (compareFileVersion(slPluginMinRequired) < 0) - return true; - } else if (equalIgnoringCase(fileName(), "npmozax.dll")) { - // Bug 15217: Mozilla ActiveX control complains about missing xpcom_core.dll - return true; - } else if (equalIgnoringCase(fileName(), "npwpf.dll")) { - // Bug 57119: Microsoft Windows Presentation Foundation (WPF) plug-in complains about missing xpcom.dll - return true; - } else if (name() == "Yahoo Application State Plugin") { - // https://bugs.webkit.org/show_bug.cgi?id=26860 - // Bug in Yahoo Application State plug-in earlier than 1.0.0.6 leads to heap corruption. - static const PlatformModuleVersion yahooAppStatePluginMinRequired(0x00000006, 0x00010000); - if (compareFileVersion(yahooAppStatePluginMinRequired) < 0) - return true; - } - - return false; -} - -void PluginPackage::determineQuirks(const String& mimeType) -{ - if (mimeType == "application/x-shockwave-flash") { - static const PlatformModuleVersion flashTenVersion(0x00000000, 0x000a0000); - - // Pre 10 Flash only requests windowless plugins if we return a mozilla user agent - if (compareFileVersion(flashTenVersion) < 0) - m_quirks.add(PluginQuirkWantsMozillaUserAgent); - - m_quirks.add(PluginQuirkThrottleInvalidate); - m_quirks.add(PluginQuirkThrottleWMUserPlusOneMessages); - m_quirks.add(PluginQuirkFlashURLNotifyBug); - } - - if (name().contains("Microsoft") && name().contains("Windows Media")) { - // The WMP plugin sets its size on the first NPP_SetWindow call and never updates its size, so - // call SetWindow when the plugin view has a correct size - m_quirks.add(PluginQuirkDeferFirstSetWindowCall); - - // Windowless mode does not work at all with the WMP plugin so just remove that parameter - // and don't pass it to the plug-in. - m_quirks.add(PluginQuirkRemoveWindowlessVideoParam); - - // WMP has a modal message loop that it enters whenever we call it or - // ask it to paint. This modal loop can deliver messages to other - // windows in WebKit at times when they are not expecting them (for - // example, delivering a WM_PAINT message during a layout), and these - // can cause crashes. - m_quirks.add(PluginQuirkHasModalMessageLoop); - } - - if (name() == "VLC Multimedia Plugin" || name() == "VLC Multimedia Plug-in") { - // VLC hangs on NPP_Destroy if we call NPP_SetWindow with a null window handle - m_quirks.add(PluginQuirkDontSetNullWindowHandleOnDestroy); - - // VLC 0.8.6d and 0.8.6e crash if multiple instances are created. - // <rdar://problem/5773070> tracks allowing multiple instances when this - // bug is fixed. - m_quirks.add(PluginQuirkDontAllowMultipleInstances); - } - - // The DivX plugin sets its size on the first NPP_SetWindow call and never updates its size, so - // call SetWindow when the plugin view has a correct size - if (mimeType == "video/divx") - m_quirks.add(PluginQuirkDeferFirstSetWindowCall); - - // FIXME: This is a workaround for a problem in our NPRuntime bindings; if a plug-in creates an - // NPObject and passes it to a function it's not possible to see what root object that NPObject belongs to. - // Thus, we don't know that the object should be invalidated when the plug-in instance goes away. - // See <rdar://problem/5487742>. - if (mimeType == "application/x-silverlight") - m_quirks.add(PluginQuirkDontUnloadPlugin); - - if (MIMETypeRegistry::isJavaAppletMIMEType(mimeType)) { - // Because a single process cannot create multiple VMs, and we cannot reliably unload a - // Java VM, we cannot unload the Java plugin, or we'll lose reference to our only VM - m_quirks.add(PluginQuirkDontUnloadPlugin); - - // Setting the window region to an empty region causes bad scrolling repaint problems - // with the Java plug-in. - m_quirks.add(PluginQuirkDontClipToZeroRectWhenScrolling); - } - - if (mimeType == "audio/x-pn-realaudio-plugin") { - // Prevent the Real plugin from calling the Window Proc recursively, causing the stack to overflow. - m_quirks.add(PluginQuirkDontCallWndProcForSameMessageRecursively); - - static const PlatformModuleVersion lastKnownUnloadableRealPlayerVersion(0x000B0B24, 0x00060000); - - // Unloading RealPlayer versions newer than 10.5 can cause a hang; see rdar://5669317. - // FIXME: Resume unloading when this bug in the RealPlayer Plug-In is fixed (rdar://5713147) - if (compareFileVersion(lastKnownUnloadableRealPlayerVersion) > 0) - m_quirks.add(PluginQuirkDontUnloadPlugin); - } -} - -bool PluginPackage::fetchInfo() -{ - DWORD versionInfoSize, zeroHandle; - versionInfoSize = GetFileVersionInfoSizeW(const_cast<UChar*>(m_path.charactersWithNullTermination().data()), &zeroHandle); - if (versionInfoSize == 0) - return false; - - auto versionInfoData = std::make_unique<char[]>(versionInfoSize); - - if (!GetFileVersionInfoW(const_cast<UChar*>(m_path.charactersWithNullTermination().data()), - 0, versionInfoSize, versionInfoData.get())) - return false; - - m_name = getVersionInfo(versionInfoData.get(), "ProductName"); - m_description = getVersionInfo(versionInfoData.get(), "FileDescription"); - if (m_name.isNull() || m_description.isNull()) - return false; - - VS_FIXEDFILEINFO* info; - UINT infoSize; - if (!VerQueryValueW(versionInfoData.get(), L"\\", (LPVOID*) &info, &infoSize) || infoSize < sizeof(VS_FIXEDFILEINFO)) - return false; - m_moduleVersion.leastSig = info->dwFileVersionLS; - m_moduleVersion.mostSig = info->dwFileVersionMS; - - if (isPluginBlacklisted()) - return false; - - Vector<String> types; - getVersionInfo(versionInfoData.get(), "MIMEType").split('|', types); - Vector<String> extensionLists; - getVersionInfo(versionInfoData.get(), "FileExtents").split('|', extensionLists); - Vector<String> descriptions; - getVersionInfo(versionInfoData.get(), "FileOpenName").split('|', descriptions); - - for (unsigned i = 0; i < types.size(); i++) { - String type = types[i].lower(); - String description = i < descriptions.size() ? descriptions[i] : ""; - String extensionList = i < extensionLists.size() ? extensionLists[i] : ""; - - Vector<String> extensionsVector; - extensionList.split(',', extensionsVector); - - // Get rid of the extension list that may be at the end of the description string. - int pos = description.find("(*"); - if (pos != -1) { - // There might be a space that we need to get rid of. - if (pos > 1 && description[pos - 1] == ' ') - pos--; - description = description.left(pos); - } - - // Determine the quirks for the MIME types this plug-in supports - determineQuirks(type); - - m_mimeToExtensions.add(type, extensionsVector); - m_mimeToDescriptions.add(type, description); - } - - return true; -} - -bool PluginPackage::load() -{ - if (m_freeLibraryTimer.isActive()) { - ASSERT(m_module); - m_freeLibraryTimer.stop(); - } else if (m_isLoaded) { - if (m_quirks.contains(PluginQuirkDontAllowMultipleInstances)) - return false; - m_loadCount++; - return true; - } else { -#if OS(WINCE) - m_module = ::LoadLibraryW(m_path.charactersWithNullTermination().data()); -#else - WCHAR currentPath[MAX_PATH]; - - if (!::GetCurrentDirectoryW(MAX_PATH, currentPath)) - return false; - - String path = m_path.substring(0, m_path.reverseFind('\\')); - - if (!::SetCurrentDirectoryW(path.charactersWithNullTermination().data())) - return false; - - // Load the library - m_module = ::LoadLibraryExW(m_path.charactersWithNullTermination().data(), 0, LOAD_WITH_ALTERED_SEARCH_PATH); - - if (!::SetCurrentDirectoryW(currentPath)) { - if (m_module) - ::FreeLibrary(m_module); - return false; - } -#endif - } - - if (!m_module) - return false; - - m_isLoaded = true; - - NP_GetEntryPointsFuncPtr NP_GetEntryPoints = 0; - NP_InitializeFuncPtr NP_Initialize = 0; - NPError npErr; - -#if OS(WINCE) - NP_Initialize = (NP_InitializeFuncPtr)GetProcAddress(m_module, L"NP_Initialize"); - NP_GetEntryPoints = (NP_GetEntryPointsFuncPtr)GetProcAddress(m_module, L"NP_GetEntryPoints"); - m_NPP_Shutdown = (NPP_ShutdownProcPtr)GetProcAddress(m_module, L"NP_Shutdown"); -#else - NP_Initialize = (NP_InitializeFuncPtr)GetProcAddress(m_module, "NP_Initialize"); - NP_GetEntryPoints = (NP_GetEntryPointsFuncPtr)GetProcAddress(m_module, "NP_GetEntryPoints"); - m_NPP_Shutdown = (NPP_ShutdownProcPtr)GetProcAddress(m_module, "NP_Shutdown"); -#endif - - if (!NP_Initialize || !NP_GetEntryPoints || !m_NPP_Shutdown) - goto abort; - - memset(&m_pluginFuncs, 0, sizeof(m_pluginFuncs)); - m_pluginFuncs.size = sizeof(m_pluginFuncs); - - npErr = NP_GetEntryPoints(&m_pluginFuncs); - LOG_NPERROR(npErr); - if (npErr != NPERR_NO_ERROR) - goto abort; - - initializeBrowserFuncs(); - - npErr = NP_Initialize(&m_browserFuncs); - LOG_NPERROR(npErr); - - if (npErr != NPERR_NO_ERROR) - goto abort; - - m_loadCount++; - return true; - -abort: - unloadWithoutShutdown(); - return false; -} - -unsigned PluginPackage::hash() const -{ - const unsigned hashCodes[] = { - m_name.impl()->hash(), - m_description.impl()->hash(), - m_mimeToExtensions.size() - }; - - return StringHasher::hashMemory<sizeof(hashCodes)>(hashCodes); -} - -bool PluginPackage::equal(const PluginPackage& a, const PluginPackage& b) -{ - if (a.m_name != b.m_name) - return false; - - if (a.m_description != b.m_description) - return false; - - if (a.m_mimeToExtensions.size() != b.m_mimeToExtensions.size()) - return false; - - MIMEToExtensionsMap::const_iterator::Keys end = a.m_mimeToExtensions.end().keys(); - for (MIMEToExtensionsMap::const_iterator::Keys it = a.m_mimeToExtensions.begin().keys(); it != end; ++it) { - if (!b.m_mimeToExtensions.contains(*it)) - return false; - } - - return true; -} - -uint16_t PluginPackage::NPVersion() const -{ - return NP_VERSION_MINOR; -} -} diff --git a/Source/WebCore/plugins/win/PluginViewWin.cpp b/Source/WebCore/plugins/win/PluginViewWin.cpp deleted file mode 100644 index fa3ad1855..000000000 --- a/Source/WebCore/plugins/win/PluginViewWin.cpp +++ /dev/null @@ -1,1081 +0,0 @@ -/* - * Copyright (C) 2006, 2007, 2008, 2013 Apple Inc. All rights reserved. - * Copyright (C) 2008 Collabora Ltd. All rights reserved. - * Copyright (C) 2008-2009 Torch Mobile, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "PluginView.h" - -#include "BitmapImage.h" -#include "BitmapInfo.h" -#include "BridgeJSC.h" -#include "Chrome.h" -#include "ChromeClient.h" -#include "Document.h" -#include "DocumentLoader.h" -#include "Element.h" -#include "EventNames.h" -#include "FocusController.h" -#include "Frame.h" -#include "FrameLoadRequest.h" -#include "FrameLoader.h" -#include "FrameTree.h" -#include "FrameView.h" -#include "GraphicsContext.h" -#include "HTMLNames.h" -#include "HTMLPlugInElement.h" -#include "HostWindow.h" -#include "Image.h" -#include "JSDOMBinding.h" -#include "JSDOMWindow.h" -#include "KeyboardEvent.h" -#include "LocalWindowsContext.h" -#include "MIMETypeRegistry.h" -#include "MouseEvent.h" -#include "Page.h" -#include "PlatformMouseEvent.h" -#include "PluginDatabase.h" -#include "PluginDebug.h" -#include "PluginMainThreadScheduler.h" -#include "PluginMessageThrottlerWin.h" -#include "PluginPackage.h" -#include "RenderWidget.h" -#include "Settings.h" -#include "WebCoreInstanceHandle.h" -#include "c_instance.h" -#include "npruntime_impl.h" -#include "runtime_root.h" -#include <runtime/JSCJSValue.h> -#include <runtime/JSLock.h> -#include <wtf/ASCIICType.h> -#include <wtf/text/WTFString.h> -#include <wtf/win/GDIObject.h> - -#if OS(WINCE) -#undef LOG_NPERROR -#define LOG_NPERROR(x) -#undef LOG_PLUGIN_NET_ERROR -#define LOG_PLUGIN_NET_ERROR() -#endif - -#if USE(CAIRO) -#include "PlatformContextCairo.h" -#include <cairo-win32.h> -#endif - -#if PLATFORM(GTK) -#include <gdk/gdkwin32.h> -#include <gtk/gtk.h> -#endif - -static inline HWND windowHandleForPageClient(PlatformPageClient client) -{ -#if PLATFORM(GTK) - if (!client) - return 0; - if (GdkWindow* window = gtk_widget_get_window(client)) - return static_cast<HWND>(GDK_WINDOW_HWND(window)); - return 0; -#else - return client; -#endif -} - -using JSC::ExecState; -using JSC::JSLock; -using JSC::JSObject; - -using std::min; - -using namespace WTF; - -namespace WebCore { - -using namespace HTMLNames; - -const LPCWSTR kWebPluginViewdowClassName = L"WebPluginView"; -const LPCWSTR kWebPluginViewProperty = L"WebPluginViewProperty"; - -#if !OS(WINCE) -// The code used to hook BeginPaint/EndPaint originally came from -// <http://www.fengyuan.com/article/wmprint.html>. -// Copyright (C) 2000 by Feng Yuan (www.fengyuan.com). - -static unsigned beginPaintSysCall; -static BYTE* beginPaint; - -static unsigned endPaintSysCall; -static BYTE* endPaint; - -typedef HDC (WINAPI *PtrBeginPaint)(HWND, PAINTSTRUCT*); -typedef BOOL (WINAPI *PtrEndPaint)(HWND, const PAINTSTRUCT*); - -#if OS(WINDOWS) && CPU(X86_64) && COMPILER(MSVC) -extern "C" HDC __stdcall _HBeginPaint(HWND hWnd, LPPAINTSTRUCT lpPaint); -extern "C" BOOL __stdcall _HEndPaint(HWND hWnd, const PAINTSTRUCT* lpPaint); -#endif - -HDC WINAPI PluginView::hookedBeginPaint(HWND hWnd, PAINTSTRUCT* lpPaint) -{ - PluginView* pluginView = reinterpret_cast<PluginView*>(GetProp(hWnd, kWebPluginViewProperty)); - if (pluginView && pluginView->m_wmPrintHDC) { - // We're secretly handling WM_PRINTCLIENT, so set up the PAINTSTRUCT so - // that the plugin will paint into the HDC we provide. - memset(lpPaint, 0, sizeof(PAINTSTRUCT)); - lpPaint->hdc = pluginView->m_wmPrintHDC; - GetClientRect(hWnd, &lpPaint->rcPaint); - return pluginView->m_wmPrintHDC; - } - -#if COMPILER(GCC) - HDC result; - asm ("push %2\n" - "push %3\n" - "call *%4\n" - : "=a" (result) - : "a" (beginPaintSysCall), "g" (lpPaint), "g" (hWnd), "m" (beginPaint) - : "memory" - ); - return result; -#elif defined(_M_IX86) - // Call through to the original BeginPaint. - __asm mov eax, beginPaintSysCall - __asm push lpPaint - __asm push hWnd - __asm call beginPaint -#else - return _HBeginPaint(hWnd, lpPaint); -#endif -} - -BOOL WINAPI PluginView::hookedEndPaint(HWND hWnd, const PAINTSTRUCT* lpPaint) -{ - PluginView* pluginView = reinterpret_cast<PluginView*>(GetProp(hWnd, kWebPluginViewProperty)); - if (pluginView && pluginView->m_wmPrintHDC) { - // We're secretly handling WM_PRINTCLIENT, so we don't have to do any - // cleanup. - return TRUE; - } - -#if COMPILER(GCC) - BOOL result; - asm ("push %2\n" - "push %3\n" - "call *%4\n" - : "=a" (result) - : "a" (endPaintSysCall), "g" (lpPaint), "g" (hWnd), "m" (endPaint) - ); - return result; -#elif defined (_M_IX86) - // Call through to the original EndPaint. - __asm mov eax, endPaintSysCall - __asm push lpPaint - __asm push hWnd - __asm call endPaint -#else - return _HEndPaint(hWnd, lpPaint); -#endif -} - -static void hook(const char* module, const char* proc, unsigned& sysCallID, BYTE*& pProc, const void* pNewProc) -{ - // See <http://www.fengyuan.com/article/wmprint.html> for an explanation of - // how this function works. - - HINSTANCE hMod = GetModuleHandleA(module); - - pProc = reinterpret_cast<BYTE*>(reinterpret_cast<ptrdiff_t>(GetProcAddress(hMod, proc))); - -#if COMPILER(GCC) || defined(_M_IX86) - if (pProc[0] != 0xB8) - return; - - // FIXME: Should we be reading the bytes one-by-one instead of doing an - // unaligned read? - sysCallID = *reinterpret_cast<unsigned*>(pProc + 1); - - DWORD flOldProtect; - if (!VirtualProtect(pProc, 5, PAGE_EXECUTE_READWRITE, &flOldProtect)) - return; - - pProc[0] = 0xE9; - *reinterpret_cast<unsigned*>(pProc + 1) = reinterpret_cast<intptr_t>(pNewProc) - reinterpret_cast<intptr_t>(pProc + 5); - - pProc += 5; -#else - /* Disassembly of BeginPaint() - 00000000779FC5B0 4C 8B D1 mov r10,rcx - 00000000779FC5B3 B8 17 10 00 00 mov eax,1017h - 00000000779FC5B8 0F 05 syscall - 00000000779FC5BA C3 ret - 00000000779FC5BB 90 nop - 00000000779FC5BC 90 nop - 00000000779FC5BD 90 nop - 00000000779FC5BE 90 nop - 00000000779FC5BF 90 nop - 00000000779FC5C0 90 nop - 00000000779FC5C1 90 nop - 00000000779FC5C2 90 nop - 00000000779FC5C3 90 nop - */ - // Check for the signature as in the above disassembly - DWORD guard = 0xB8D18B4C; - if (*reinterpret_cast<DWORD*>(pProc) != guard) - return; - - DWORD flOldProtect; - VirtualProtect(pProc, 12, PAGE_EXECUTE_READWRITE, & flOldProtect); - pProc[0] = 0x48; // mov rax, this - pProc[1] = 0xb8; - *(__int64*)(pProc+2) = (__int64)pNewProc; - pProc[10] = 0xff; // jmp rax - pProc[11] = 0xe0; -#endif -} - -static void setUpOffscreenPaintingHooks(HDC (WINAPI*hookedBeginPaint)(HWND, PAINTSTRUCT*), BOOL (WINAPI*hookedEndPaint)(HWND, const PAINTSTRUCT*)) -{ - static bool haveHooked = false; - if (haveHooked) - return; - haveHooked = true; - - // Most (all?) windowed plugins don't seem to respond to WM_PRINTCLIENT, so - // we hook into BeginPaint/EndPaint to allow their normal WM_PAINT handling - // to draw into a given HDC. Note that this hooking affects the entire - // process. - hook("user32.dll", "BeginPaint", beginPaintSysCall, beginPaint, reinterpret_cast<const void *>(reinterpret_cast<ptrdiff_t>(hookedBeginPaint))); - hook("user32.dll", "EndPaint", endPaintSysCall, endPaint, reinterpret_cast<const void *>(reinterpret_cast<ptrdiff_t>(hookedEndPaint))); - -} -#endif - -static bool registerPluginView() -{ - static bool haveRegisteredWindowClass = false; - if (haveRegisteredWindowClass) - return true; - - haveRegisteredWindowClass = true; - -#if PLATFORM(GTK) - WebCore::setInstanceHandle((HINSTANCE)(GetModuleHandle(0))); -#endif - - ASSERT(WebCore::instanceHandle()); - -#if OS(WINCE) - WNDCLASS wcex = { 0 }; -#else - WNDCLASSEX wcex; - wcex.cbSize = sizeof(WNDCLASSEX); - wcex.hIconSm = 0; -#endif - - wcex.style = CS_DBLCLKS; -#if OS(WINCE) - wcex.style |= CS_PARENTDC; -#endif - wcex.lpfnWndProc = DefWindowProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = 0; - wcex.hInstance = WebCore::instanceHandle(); - wcex.hIcon = 0; - wcex.hCursor = LoadCursor(0, IDC_ARROW); - wcex.hbrBackground = (HBRUSH)COLOR_WINDOW; - wcex.lpszMenuName = 0; - wcex.lpszClassName = kWebPluginViewdowClassName; - -#if OS(WINCE) - return !!RegisterClass(&wcex); -#else - return !!RegisterClassEx(&wcex); -#endif -} - -LRESULT CALLBACK PluginView::PluginViewWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - PluginView* pluginView = reinterpret_cast<PluginView*>(GetProp(hWnd, kWebPluginViewProperty)); - - return pluginView->wndProc(hWnd, message, wParam, lParam); -} - -static bool isWindowsMessageUserGesture(UINT message) -{ - switch (message) { - case WM_LBUTTONUP: - case WM_MBUTTONUP: - case WM_RBUTTONUP: - case WM_KEYUP: - return true; - default: - return false; - } -} - -static inline IntPoint contentsToNativeWindow(FrameView* view, const IntPoint& point) -{ - return view->contentsToWindow(point); -} - -static inline IntRect contentsToNativeWindow(FrameView* view, const IntRect& rect) -{ - return view->contentsToWindow(rect); -} - -LRESULT -PluginView::wndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - // <rdar://5711136> Sometimes Flash will call SetCapture before creating - // a full-screen window and will not release it, which causes the - // full-screen window to never receive mouse events. We set/release capture - // on mouse down/up before sending the event to the plug-in to prevent that. - switch (message) { - case WM_LBUTTONDOWN: - case WM_MBUTTONDOWN: - case WM_RBUTTONDOWN: - ::SetCapture(hWnd); - break; - case WM_LBUTTONUP: - case WM_MBUTTONUP: - case WM_RBUTTONUP: - ::ReleaseCapture(); - break; - } - - if (message == m_lastMessage && - m_plugin->quirks().contains(PluginQuirkDontCallWndProcForSameMessageRecursively) && - m_isCallingPluginWndProc) - return 1; - - if (message == WM_USER + 1 && - m_plugin->quirks().contains(PluginQuirkThrottleWMUserPlusOneMessages)) { - if (!m_messageThrottler) - m_messageThrottler = adoptPtr(new PluginMessageThrottlerWin(this)); - - m_messageThrottler->appendMessage(hWnd, message, wParam, lParam); - return 0; - } - - m_lastMessage = message; - m_isCallingPluginWndProc = true; - - // If the plug-in doesn't explicitly support changing the pop-up state, we enable - // popups for all user gestures. - // Note that we need to pop the state in a timer, because the Flash plug-in - // pops up windows in response to a posted message. - if (m_plugin->pluginFuncs()->version < NPVERS_HAS_POPUPS_ENABLED_STATE && - isWindowsMessageUserGesture(message) && !m_popPopupsStateTimer.isActive()) { - - pushPopupsEnabledState(true); - - m_popPopupsStateTimer.startOneShot(0); - } - -#if !OS(WINCE) - if (message == WM_PRINTCLIENT) { - // Most (all?) windowed plugins don't respond to WM_PRINTCLIENT, so we - // change the message to WM_PAINT and rely on our hooked versions of - // BeginPaint/EndPaint to make the plugin draw into the given HDC. - message = WM_PAINT; - m_wmPrintHDC = reinterpret_cast<HDC>(wParam); - } -#endif - - // Call the plug-in's window proc. - LRESULT result = ::CallWindowProc(m_pluginWndProc, hWnd, message, wParam, lParam); - - m_wmPrintHDC = 0; - - m_isCallingPluginWndProc = false; - - return result; -} - -void PluginView::updatePluginWidget() -{ - if (!parent()) - return; - - ASSERT(parent()->isFrameView()); - FrameView* frameView = toFrameView(parent()); - - IntRect oldWindowRect = m_windowRect; - IntRect oldClipRect = m_clipRect; - -#if OS(WINCE) - m_windowRect = frameView->contentsToWindow(frameRect()); -#else - m_windowRect = IntRect(frameView->contentsToWindow(frameRect().location()), frameRect().size()); -#endif - m_clipRect = windowClipRect(); - m_clipRect.move(-m_windowRect.x(), -m_windowRect.y()); - - if (platformPluginWidget() && (!m_haveUpdatedPluginWidget || m_windowRect != oldWindowRect || m_clipRect != oldClipRect)) { - - setCallingPlugin(true); - - // To prevent flashes while scrolling, we disable drawing during the window - // update process by clipping the window to the zero rect. - - bool clipToZeroRect = !m_plugin->quirks().contains(PluginQuirkDontClipToZeroRectWhenScrolling); - - if (clipToZeroRect) { - auto rgn = adoptGDIObject(::CreateRectRgn(0, 0, 0, 0)); - ::SetWindowRgn(platformPluginWidget(), rgn.leak(), FALSE); - } else { - auto rgn = adoptGDIObject(::CreateRectRgn(m_clipRect.x(), m_clipRect.y(), m_clipRect.maxX(), m_clipRect.maxY())); - ::SetWindowRgn(platformPluginWidget(), rgn.leak(), TRUE); - } - - if (!m_haveUpdatedPluginWidget || m_windowRect != oldWindowRect) - ::MoveWindow(platformPluginWidget(), m_windowRect.x(), m_windowRect.y(), m_windowRect.width(), m_windowRect.height(), TRUE); - - if (clipToZeroRect) { - auto rgn = adoptGDIObject(::CreateRectRgn(m_clipRect.x(), m_clipRect.y(), m_clipRect.maxX(), m_clipRect.maxY())); - ::SetWindowRgn(platformPluginWidget(), rgn.leak(), TRUE); - } - - setCallingPlugin(false); - - m_haveUpdatedPluginWidget = true; - } -} - -void PluginView::setFocus(bool focused) -{ - if (focused && platformPluginWidget()) - SetFocus(platformPluginWidget()); - - Widget::setFocus(focused); - - if (!m_plugin || m_isWindowed) - return; - - NPEvent npEvent; - - npEvent.event = focused ? WM_SETFOCUS : WM_KILLFOCUS; - npEvent.wParam = 0; - npEvent.lParam = 0; - - dispatchNPEvent(npEvent); -} - -void PluginView::show() -{ - setSelfVisible(true); - - if (isParentVisible() && platformPluginWidget()) - ShowWindow(platformPluginWidget(), SW_SHOWNA); - - Widget::show(); -} - -void PluginView::hide() -{ - setSelfVisible(false); - - if (isParentVisible() && platformPluginWidget()) - ShowWindow(platformPluginWidget(), SW_HIDE); - - Widget::hide(); -} - -bool PluginView::dispatchNPEvent(NPEvent& npEvent) -{ - if (!m_plugin->pluginFuncs()->event) - return true; - - bool shouldPop = false; - - if (m_plugin->pluginFuncs()->version < NPVERS_HAS_POPUPS_ENABLED_STATE && isWindowsMessageUserGesture(npEvent.event)) { - pushPopupsEnabledState(true); - shouldPop = true; - } - - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - setCallingPlugin(true); - bool accepted = !m_plugin->pluginFuncs()->event(m_instance, &npEvent); - setCallingPlugin(false); - - if (shouldPop) - popPopupsEnabledState(); - - return accepted; -} - -void PluginView::paintIntoTransformedContext(HDC hdc) -{ - if (m_isWindowed) { -#if !OS(WINCE) - SendMessage(platformPluginWidget(), WM_PRINTCLIENT, reinterpret_cast<WPARAM>(hdc), PRF_CLIENT | PRF_CHILDREN | PRF_OWNED); -#endif - return; - } - - m_npWindow.type = NPWindowTypeDrawable; - m_npWindow.window = hdc; - - WINDOWPOS windowpos = { 0, 0, 0, 0, 0, 0, 0 }; - - IntRect r = contentsToNativeWindow(toFrameView(parent()), frameRect()); - - windowpos.x = r.x(); - windowpos.y = r.y(); - windowpos.cx = r.width(); - windowpos.cy = r.height(); - - NPEvent npEvent; - npEvent.event = WM_WINDOWPOSCHANGED; - npEvent.lParam = reinterpret_cast<uintptr_t>(&windowpos); - npEvent.wParam = 0; - - dispatchNPEvent(npEvent); - - setNPWindowRect(frameRect()); - - npEvent.event = WM_PAINT; - npEvent.wParam = reinterpret_cast<uintptr_t>(hdc); - - // This is supposed to be a pointer to the dirty rect, but it seems that the Flash plugin - // ignores it so we just pass null. - npEvent.lParam = 0; - - dispatchNPEvent(npEvent); -} - -void PluginView::paintWindowedPluginIntoContext(GraphicsContext* context, const IntRect& rect) -{ -#if !USE(WINGDI) - ASSERT(m_isWindowed); - ASSERT(context->shouldIncludeChildWindows()); - - ASSERT(parent()->isFrameView()); - IntPoint locationInWindow = toFrameView(parent())->convertToContainingWindow(frameRect().location()); - - LocalWindowsContext windowsContext(context, frameRect(), false); - -#if USE(CAIRO) - // Must flush drawings up to this point to the backing metafile, otherwise the - // plugin region will be overwritten with any clear regions specified in the - // cairo-controlled portions of the rendering. - cairo_show_page(context->platformContext()->cr()); -#endif - - HDC hdc = windowsContext.hdc(); - XFORM originalTransform; - GetWorldTransform(hdc, &originalTransform); - - // The plugin expects the DC to be in client coordinates, so we translate - // the DC to make that so. - AffineTransform ctm = context->getCTM(); - ctm.translate(locationInWindow.x(), locationInWindow.y()); - XFORM transform = static_cast<XFORM>(ctm.toTransformationMatrix()); - - SetWorldTransform(hdc, &transform); - - paintIntoTransformedContext(hdc); - - SetWorldTransform(hdc, &originalTransform); -#endif -} - -void PluginView::paint(GraphicsContext* context, const IntRect& rect) -{ - if (!m_isStarted) { - // Draw the "missing plugin" image - paintMissingPluginIcon(context, rect); - return; - } - - if (context->paintingDisabled()) - return; - - // Ensure that we have called SetWindow before we try to paint. - if (!m_haveCalledSetWindow) - setNPWindowRect(frameRect()); - - if (m_isWindowed) { -#if !USE(WINGDI) - if (context->shouldIncludeChildWindows()) - paintWindowedPluginIntoContext(context, rect); -#endif - return; - } - - ASSERT(parent()->isFrameView()); - - // In the GTK and Qt ports we draw in an offscreen buffer and don't want to use the window - // coordinates. -#if PLATFORM(GTK) - IntRect rectInWindow(rect); - rectInWindow.intersect(frameRect()); -#else - IntRect rectInWindow = toFrameView(parent())->contentsToWindow(frameRect()); -#endif - LocalWindowsContext windowsContext(context, rectInWindow, m_isTransparent); - - // On Safari/Windows without transparency layers the GraphicsContext returns the HDC - // of the window and the plugin expects that the passed in DC has window coordinates. - // In the GTK and Qt ports we always draw in an offscreen buffer and therefore need - // to preserve the translation set in getWindowsContext. -#if !PLATFORM(GTK) && !OS(WINCE) - if (!context->isInTransparencyLayer()) { - XFORM transform; - GetWorldTransform(windowsContext.hdc(), &transform); - transform.eDx = 0; - transform.eDy = 0; - SetWorldTransform(windowsContext.hdc(), &transform); - } -#endif - - paintIntoTransformedContext(windowsContext.hdc()); -} - -void PluginView::handleKeyboardEvent(KeyboardEvent* event) -{ - ASSERT(m_plugin && !m_isWindowed); - - NPEvent npEvent; - - npEvent.wParam = event->keyCode(); - - if (event->type() == eventNames().keydownEvent) { - npEvent.event = WM_KEYDOWN; - npEvent.lParam = 0; - } else if (event->type() == eventNames().keypressEvent) { - npEvent.event = WM_CHAR; - npEvent.lParam = 0; - } else if (event->type() == eventNames().keyupEvent) { - npEvent.event = WM_KEYUP; - npEvent.lParam = 0x8000; - } else - return; - - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - if (dispatchNPEvent(npEvent)) - event->setDefaultHandled(); -} - -#if !OS(WINCE) -extern bool ignoreNextSetCursor; -#endif - -void PluginView::handleMouseEvent(MouseEvent* event) -{ - ASSERT(m_plugin && !m_isWindowed); - - NPEvent npEvent; - - IntPoint p = contentsToNativeWindow(toFrameView(parent()), IntPoint(event->pageX(), event->pageY())); - - npEvent.lParam = MAKELPARAM(p.x(), p.y()); - npEvent.wParam = 0; - - if (event->ctrlKey()) - npEvent.wParam |= MK_CONTROL; - if (event->shiftKey()) - npEvent.wParam |= MK_SHIFT; - - if (event->type() == eventNames().mousemoveEvent || - event->type() == eventNames().mouseoutEvent || - event->type() == eventNames().mouseoverEvent) { - npEvent.event = WM_MOUSEMOVE; - if (event->buttonDown()) - switch (event->button()) { - case LeftButton: - npEvent.wParam |= MK_LBUTTON; - break; - case MiddleButton: - npEvent.wParam |= MK_MBUTTON; - break; - case RightButton: - npEvent.wParam |= MK_RBUTTON; - break; - } - } - else if (event->type() == eventNames().mousedownEvent) { - focusPluginElement(); - switch (event->button()) { - case 0: - npEvent.event = WM_LBUTTONDOWN; - break; - case 1: - npEvent.event = WM_MBUTTONDOWN; - break; - case 2: - npEvent.event = WM_RBUTTONDOWN; - break; - } - } else if (event->type() == eventNames().mouseupEvent) { - switch (event->button()) { - case 0: - npEvent.event = WM_LBUTTONUP; - break; - case 1: - npEvent.event = WM_MBUTTONUP; - break; - case 2: - npEvent.event = WM_RBUTTONUP; - break; - } - } else - return; - - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - // FIXME: Consider back porting the http://webkit.org/b/58108 fix here. - if (dispatchNPEvent(npEvent)) - event->setDefaultHandled(); - -#if !PLATFORM(GTK) && !OS(WINCE) - // Currently, Widget::setCursor is always called after this function in EventHandler.cpp - // and since we don't want that we set ignoreNextSetCursor to true here to prevent that. - ignoreNextSetCursor = true; - if (Page* page = m_parentFrame->page()) - page->chrome().client().setLastSetCursorToCurrentCursor(); -#endif -} - -void PluginView::setParent(ScrollView* parent) -{ - Widget::setParent(parent); - -#if OS(WINCE) - if (parent) { - init(); - if (parent->isVisible()) - show(); - else - hide(); - } -#else - if (parent) - init(); - else { - if (!platformPluginWidget()) - return; - - // If the plug-in window or one of its children have the focus, we need to - // clear it to prevent the web view window from being focused because that can - // trigger a layout while the plugin element is being detached. - HWND focusedWindow = ::GetFocus(); - if (platformPluginWidget() == focusedWindow || ::IsChild(platformPluginWidget(), focusedWindow)) - ::SetFocus(0); - } -#endif -} - -void PluginView::setParentVisible(bool visible) -{ - if (isParentVisible() == visible) - return; - - Widget::setParentVisible(visible); - - if (isSelfVisible() && platformPluginWidget()) { - if (visible) - ShowWindow(platformPluginWidget(), SW_SHOWNA); - else - ShowWindow(platformPluginWidget(), SW_HIDE); - } -} - -void PluginView::setNPWindowRect(const IntRect& rect) -{ - if (!m_isStarted) - return; - -#if OS(WINCE) - IntRect r = toFrameView(parent())->contentsToWindow(rect); - m_npWindow.x = r.x(); - m_npWindow.y = r.y(); - - m_npWindow.width = r.width(); - m_npWindow.height = r.height(); - - m_npWindow.clipRect.right = r.width(); - m_npWindow.clipRect.bottom = r.height(); -#else - // In the GTK and Qt ports we draw in an offscreen buffer and don't want to use the window - // coordinates. -# if PLATFORM(GTK) - IntPoint p = rect.location(); -# else - IntPoint p = toFrameView(parent())->contentsToWindow(rect.location()); -# endif - m_npWindow.x = p.x(); - m_npWindow.y = p.y(); - - m_npWindow.width = rect.width(); - m_npWindow.height = rect.height(); - - m_npWindow.clipRect.right = rect.width(); - m_npWindow.clipRect.bottom = rect.height(); -#endif - m_npWindow.clipRect.left = 0; - m_npWindow.clipRect.top = 0; - - if (m_plugin->pluginFuncs()->setwindow) { - JSC::JSLock::DropAllLocks dropAllLocks(JSDOMWindowBase::commonVM()); - setCallingPlugin(true); - m_plugin->pluginFuncs()->setwindow(m_instance, &m_npWindow); - setCallingPlugin(false); - - m_haveCalledSetWindow = true; - - if (!m_isWindowed) - return; - - ASSERT(platformPluginWidget()); - -#if OS(WINCE) - if (!m_pluginWndProc) { - WNDPROC currentWndProc = (WNDPROC)GetWindowLong(platformPluginWidget(), GWL_WNDPROC); - if (currentWndProc != PluginViewWndProc) - m_pluginWndProc = (WNDPROC)SetWindowLong(platformPluginWidget(), GWL_WNDPROC, (LONG)PluginViewWndProc); - } -#else - WNDPROC currentWndProc = (WNDPROC)GetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC); - if (currentWndProc != PluginViewWndProc) - m_pluginWndProc = (WNDPROC)SetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC, (LONG_PTR)PluginViewWndProc); -#endif - } -} - -NPError PluginView::handlePostReadFile(Vector<char>& buffer, uint32_t len, const char* buf) -{ - String filename(buf, len); - - if (filename.startsWith("file:///")) - filename = filename.substring(8); - - // Get file info - WIN32_FILE_ATTRIBUTE_DATA attrs; - if (GetFileAttributesExW(filename.charactersWithNullTermination().data(), GetFileExInfoStandard, &attrs) == 0) - return NPERR_FILE_NOT_FOUND; - - if (attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - return NPERR_FILE_NOT_FOUND; - - HANDLE fileHandle = CreateFileW(filename.charactersWithNullTermination().data(), FILE_READ_DATA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); - - if (fileHandle == INVALID_HANDLE_VALUE) - return NPERR_FILE_NOT_FOUND; - - buffer.resize(attrs.nFileSizeLow); - - DWORD bytesRead; - int retval = ReadFile(fileHandle, buffer.data(), attrs.nFileSizeLow, &bytesRead, 0); - - CloseHandle(fileHandle); - - if (retval == 0 || bytesRead != attrs.nFileSizeLow) - return NPERR_FILE_NOT_FOUND; - - return NPERR_NO_ERROR; -} - -bool PluginView::platformGetValueStatic(NPNVariable, void*, NPError*) -{ - return false; -} - -bool PluginView::platformGetValue(NPNVariable variable, void* value, NPError* result) -{ - switch (variable) { - case NPNVnetscapeWindow: { - HWND* w = reinterpret_cast<HWND*>(value); - *w = windowHandleForPageClient(parent() ? parent()->hostWindow()->platformPageClient() : 0); - *result = NPERR_NO_ERROR; - return true; - } - - case NPNVSupportsWindowless: { - NPBool* flag = reinterpret_cast<NPBool*>(value); - *flag = TRUE; - *result = NPERR_NO_ERROR; - return true; - } - - default: - return false; - } -} - -void PluginView::invalidateRect(const IntRect& rect) -{ - if (m_isWindowed) { - RECT invalidRect = { rect.x(), rect.y(), rect.maxX(), rect.maxY() }; - ::InvalidateRect(platformPluginWidget(), &invalidRect, false); - return; - } - - invalidateWindowlessPluginRect(rect); -} - -void PluginView::invalidateRect(NPRect* rect) -{ - if (!rect) { - invalidate(); - return; - } - - IntRect r(rect->left, rect->top, rect->right - rect->left, rect->bottom - rect->top); - - if (m_isWindowed) { - RECT invalidRect = { r.x(), r.y(), r.maxX(), r.maxY() }; - InvalidateRect(platformPluginWidget(), &invalidRect, FALSE); - } else { - if (m_plugin->quirks().contains(PluginQuirkThrottleInvalidate)) { - m_invalidRects.append(r); - if (!m_invalidateTimer.isActive()) - m_invalidateTimer.startOneShot(0.001); - } else - invalidateRect(r); - } -} - -void PluginView::invalidateRegion(NPRegion region) -{ - if (m_isWindowed) - return; - - RECT r; - - if (GetRgnBox(region, &r) == 0) { - invalidate(); - return; - } - - IntRect rect(IntPoint(r.left, r.top), IntSize(r.right-r.left, r.bottom-r.top)); - invalidateRect(rect); -} - -void PluginView::forceRedraw() -{ - if (m_isWindowed) - ::UpdateWindow(platformPluginWidget()); - else - ::UpdateWindow(windowHandleForPageClient(parent() ? parent()->hostWindow()->platformPageClient() : 0)); -} - -bool PluginView::platformStart() -{ - ASSERT(m_isStarted); - ASSERT(m_status == PluginStatusLoadedSuccessfully); - - if (m_isWindowed) { - registerPluginView(); -#if !OS(WINCE) - setUpOffscreenPaintingHooks(hookedBeginPaint, hookedEndPaint); -#endif - - DWORD flags = WS_CHILD; - if (isSelfVisible()) - flags |= WS_VISIBLE; - - HWND parentWindowHandle = windowHandleForPageClient(m_parentFrame->view()->hostWindow()->platformPageClient()); - HWND window = ::CreateWindowEx(0, kWebPluginViewdowClassName, 0, flags, - 0, 0, 0, 0, parentWindowHandle, 0, WebCore::instanceHandle(), 0); - -#if OS(WINDOWS) && PLATFORM(GTK) - m_window = window; -#else - setPlatformWidget(window); -#endif - - // Calling SetWindowLongPtrA here makes the window proc ASCII, which is required by at least - // the Shockwave Director plug-in. -#if OS(WINDOWS) && CPU(X86_64) - ::SetWindowLongPtrA(platformPluginWidget(), GWLP_WNDPROC, (LONG_PTR)DefWindowProcA); -#elif OS(WINCE) - ::SetWindowLong(platformPluginWidget(), GWL_WNDPROC, (LONG)DefWindowProc); -#else - ::SetWindowLongPtrA(platformPluginWidget(), GWL_WNDPROC, (LONG)DefWindowProcA); -#endif - SetProp(platformPluginWidget(), kWebPluginViewProperty, this); - - m_npWindow.type = NPWindowTypeWindow; - m_npWindow.window = platformPluginWidget(); - } else { - m_npWindow.type = NPWindowTypeDrawable; - m_npWindow.window = 0; - } - - updatePluginWidget(); - - if (!m_plugin->quirks().contains(PluginQuirkDeferFirstSetWindowCall)) - setNPWindowRect(frameRect()); - - return true; -} - -void PluginView::platformDestroy() -{ - if (!platformPluginWidget()) - return; - - DestroyWindow(platformPluginWidget()); - setPlatformPluginWidget(0); -} - -PassRefPtr<Image> PluginView::snapshot() -{ -#if !PLATFORM(GTK) && !USE(WINGDI) - auto hdc = adoptGDIObject(::CreateCompatibleDC(0)); - - if (!m_isWindowed) { - // Enable world transforms. - SetGraphicsMode(hdc.get(), GM_ADVANCED); - - XFORM transform; - GetWorldTransform(hdc.get(), &transform); - - // Windowless plug-ins assume that they're drawing onto the view's DC. - // Translate the context so that the plug-in draws at (0, 0). - ASSERT(parent()->isFrameView()); - IntPoint position = toFrameView(parent())->contentsToWindow(frameRect()).location(); - transform.eDx = -position.x(); - transform.eDy = -position.y(); - SetWorldTransform(hdc.get(), &transform); - } - - void* bits; - BitmapInfo bmp = BitmapInfo::createBottomUp(frameRect().size()); - auto hbmp = adoptGDIObject(::CreateDIBSection(0, &bmp, DIB_RGB_COLORS, &bits, 0, 0)); - - HBITMAP hbmpOld = static_cast<HBITMAP>(SelectObject(hdc.get(), hbmp.get())); - - paintIntoTransformedContext(hdc.get()); - - SelectObject(hdc.get(), hbmpOld); - - return BitmapImage::create(hbmp.get()); -#else - return 0; -#endif -} - -} // namespace WebCore |