diff options
Diffstat (limited to 'WebCore/plugins')
52 files changed, 10663 insertions, 0 deletions
diff --git a/WebCore/plugins/MimeType.cpp b/WebCore/plugins/MimeType.cpp new file mode 100644 index 0000000..c4b051c --- /dev/null +++ b/WebCore/plugins/MimeType.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "MimeType.h" + +#include "Frame.h" +#include "Page.h" +#include "Plugin.h" +#include "PluginData.h" +#include "Settings.h" + +namespace WebCore { + +MimeType::MimeType(PassRefPtr<PluginData> pluginData, unsigned index) + : m_pluginData(pluginData) + , m_index(index) +{ +} + +MimeType::~MimeType() +{ +} + +const String &MimeType::type() const +{ + return m_pluginData->mimes()[m_index]->type; +} + +const String &MimeType::suffixes() const +{ + return m_pluginData->mimes()[m_index]->suffixes; +} + +const String &MimeType::description() const +{ + return m_pluginData->mimes()[m_index]->desc; +} + +PassRefPtr<Plugin> MimeType::enabledPlugin() const +{ + const Page* p = m_pluginData->page(); + if (!p || !p->settings()->arePluginsEnabled()) + return 0; + + const PluginInfo *info = m_pluginData->mimes()[m_index]->plugin; + const Vector<PluginInfo*>& plugins = m_pluginData->plugins(); + for (size_t i = 0; i < plugins.size(); ++i) { + if (plugins[i] == info) + return Plugin::create(m_pluginData.get(), i); + } + return 0; +} + +} // namespace WebCore diff --git a/WebCore/plugins/MimeType.h b/WebCore/plugins/MimeType.h new file mode 100644 index 0000000..5207918 --- /dev/null +++ b/WebCore/plugins/MimeType.h @@ -0,0 +1,52 @@ +/* + Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#ifndef MimeType_h +#define MimeType_h + +#include <wtf/PassRefPtr.h> +#include <wtf/RefPtr.h> +#include <wtf/RefCounted.h> + +#include "PluginData.h" + +namespace WebCore { + + class Plugin; + class String; + + class MimeType : public RefCounted<MimeType> { + public: + static PassRefPtr<MimeType> create(PassRefPtr<PluginData> pluginData, unsigned index) { return adoptRef(new MimeType(pluginData, index)); } + ~MimeType(); + + const String &type() const; + const String &suffixes() const; + const String &description() const; + PassRefPtr<Plugin> enabledPlugin() const; + + private: + MimeType(PassRefPtr<PluginData>, unsigned index); + RefPtr<PluginData> m_pluginData; + unsigned m_index; + }; + +} + +#endif diff --git a/WebCore/plugins/MimeType.idl b/WebCore/plugins/MimeType.idl new file mode 100644 index 0000000..ac75cc2 --- /dev/null +++ b/WebCore/plugins/MimeType.idl @@ -0,0 +1,29 @@ +/* + Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +module window { + + interface MimeType { + readonly attribute DOMString type; + readonly attribute DOMString suffixes; + readonly attribute DOMString description; + readonly attribute Plugin enabledPlugin; + }; + +} diff --git a/WebCore/plugins/MimeTypeArray.cpp b/WebCore/plugins/MimeTypeArray.cpp new file mode 100644 index 0000000..9bc4fcf --- /dev/null +++ b/WebCore/plugins/MimeTypeArray.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "MimeTypeArray.h" + +#include "AtomicString.h" +#include "Frame.h" +#include "Page.h" +#include "Plugin.h" +#include "PluginData.h" + +namespace WebCore { + +MimeTypeArray::MimeTypeArray(Frame* frame) + : m_frame(frame) +{ +} + +MimeTypeArray::~MimeTypeArray() +{ +} + +unsigned MimeTypeArray::length() const +{ + PluginData* data = getPluginData(); + if (!data) + return 0; + return data->mimes().size(); +} + +PassRefPtr<MimeType> MimeTypeArray::item(unsigned index) +{ + PluginData* data = getPluginData(); + if (!data) + return 0; + const Vector<MimeClassInfo*>& mimes = data->mimes(); + if (index >= mimes.size()) + return 0; + return MimeType::create(data, index).get(); +} + +bool MimeTypeArray::canGetItemsForName(const AtomicString& propertyName) +{ + 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 true; + } + return false; +} + +PassRefPtr<MimeType> MimeTypeArray::nameGetter(const AtomicString& propertyName) +{ + 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 MimeType::create(data, i).get(); + } + return 0; +} + +PluginData* MimeTypeArray::getPluginData() const +{ + if (!m_frame) + return 0; + Page* p = m_frame->page(); + if (!p) + return 0; + return p->pluginData(); +} + +} // namespace WebCore diff --git a/WebCore/plugins/MimeTypeArray.h b/WebCore/plugins/MimeTypeArray.h new file mode 100644 index 0000000..392a812 --- /dev/null +++ b/WebCore/plugins/MimeTypeArray.h @@ -0,0 +1,60 @@ +/* + Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#ifndef MimeTypeArray_h +#define MimeTypeArray_h + +#include "MimeType.h" +#include <wtf/PassRefPtr.h> +#include <wtf/RefCounted.h> +#include <wtf/Vector.h> + +namespace JSC { + class ExecState; +}; + +namespace WebCore { + + class AtomicString; + class Frame; + class PluginData; + + // FIXME: Generated JSMimeTypeArray.cpp doesn't include JSMimeType.h for toJS + JSC::JSValue* toJS(JSC::ExecState*, MimeType*); + + class MimeTypeArray : public RefCounted<MimeTypeArray> { + public: + static PassRefPtr<MimeTypeArray> create(Frame* frame) { return adoptRef(new MimeTypeArray(frame)); } + ~MimeTypeArray(); + + void disconnectFrame() { m_frame = 0; } + + unsigned length() const; + PassRefPtr<MimeType> item(unsigned index); + bool canGetItemsForName(const AtomicString& propertyName); + PassRefPtr<MimeType> nameGetter(const AtomicString& propertyName); + private: + MimeTypeArray(Frame*); + PluginData* getPluginData() const; + + Frame* m_frame; + }; +} + +#endif diff --git a/WebCore/plugins/MimeTypeArray.idl b/WebCore/plugins/MimeTypeArray.idl new file mode 100644 index 0000000..067f2a8 --- /dev/null +++ b/WebCore/plugins/MimeTypeArray.idl @@ -0,0 +1,26 @@ +/* + Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +module window { + + interface [HasNameGetter, HasIndexGetter] MimeTypeArray { + readonly attribute unsigned long length; + }; + +} diff --git a/WebCore/plugins/Plugin.cpp b/WebCore/plugins/Plugin.cpp new file mode 100644 index 0000000..d095c55 --- /dev/null +++ b/WebCore/plugins/Plugin.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "Plugin.h" + +#include "AtomicString.h" +#include "PluginData.h" +#include "Frame.h" + +namespace WebCore { + +Plugin::Plugin(PluginData* pluginData, unsigned index) + : m_pluginData(pluginData) + , m_index(index) +{ +} + +Plugin::~Plugin() +{ +} + +String Plugin::name() const +{ + return m_pluginData->plugins()[m_index]->name; +} + +String Plugin::filename() const +{ + return m_pluginData->plugins()[m_index]->file; +} + +String Plugin::description() const +{ + return m_pluginData->plugins()[m_index]->desc; +} + +unsigned Plugin::length() const +{ + return m_pluginData->plugins()[m_index]->mimes.size(); +} + +PassRefPtr<MimeType> Plugin::item(unsigned index) +{ + const Vector<PluginInfo*>& plugins = m_pluginData->plugins(); + if (index >= plugins[m_index]->mimes.size()) + return 0; + + MimeClassInfo* mime = plugins[m_index]->mimes[index]; + + const Vector<MimeClassInfo*>& mimes = m_pluginData->mimes(); + for (unsigned i = 0; i < mimes.size(); ++i) + if (mimes[i] == mime) + return MimeType::create(m_pluginData.get(), i).get(); + return 0; +} + +bool Plugin::canGetItemsForName(const AtomicString& propertyName) +{ + const Vector<MimeClassInfo*>& mimes = m_pluginData->mimes(); + for (unsigned i = 0; i < mimes.size(); ++i) + if (mimes[i]->type == propertyName) + return true; + return false; +} + +PassRefPtr<MimeType> Plugin::nameGetter(const AtomicString& propertyName) +{ + const Vector<MimeClassInfo*>& mimes = m_pluginData->mimes(); + for (unsigned i = 0; i < mimes.size(); ++i) + if (mimes[i]->type == propertyName) + return MimeType::create(m_pluginData.get(), i).get(); + return 0; +} + +} // namespace WebCore diff --git a/WebCore/plugins/Plugin.h b/WebCore/plugins/Plugin.h new file mode 100644 index 0000000..1d1384a --- /dev/null +++ b/WebCore/plugins/Plugin.h @@ -0,0 +1,65 @@ +/* + Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#ifndef Plugin_h +#define Plugin_h + +#include "MimeType.h" +#include <wtf/RefPtr.h> +#include <wtf/RefCounted.h> + +namespace JSC { + class ExecState; +} + +namespace WebCore { + + class AtomicString; + class Plugin; + class String; + + // FIXME: Generated JSPlugin.cpp doesn't include JSMimeType.h for toJS + JSC::JSValue* toJS(JSC::ExecState*, MimeType*); + + class PluginData; + + class Plugin : public RefCounted<Plugin> { + public: + static PassRefPtr<Plugin> create(PluginData* pluginData, unsigned index) { return adoptRef(new Plugin(pluginData, index)); } + ~Plugin(); + + String name() const; + String filename() const; + String description() const; + + unsigned length() const; + + PassRefPtr<MimeType> item(unsigned index); + bool canGetItemsForName(const AtomicString& propertyName); + PassRefPtr<MimeType> nameGetter(const AtomicString& propertyName); + + private: + Plugin(PluginData*, unsigned index); + RefPtr<PluginData> m_pluginData; + unsigned m_index; + }; + +} + +#endif diff --git a/WebCore/plugins/Plugin.idl b/WebCore/plugins/Plugin.idl new file mode 100644 index 0000000..988f371 --- /dev/null +++ b/WebCore/plugins/Plugin.idl @@ -0,0 +1,29 @@ +/* + Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +module window { + + interface [HasNameGetter, HasIndexGetter] Plugin { + readonly attribute DOMString name; + readonly attribute DOMString filename; + readonly attribute DOMString description; + readonly attribute unsigned long length; + }; + +} diff --git a/WebCore/plugins/PluginArray.cpp b/WebCore/plugins/PluginArray.cpp new file mode 100644 index 0000000..d304829 --- /dev/null +++ b/WebCore/plugins/PluginArray.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "PluginArray.h" + +#include "AtomicString.h" +#include "Frame.h" +#include "Page.h" +#include "Plugin.h" +#include "PluginData.h" + +namespace WebCore { + +PluginArray::PluginArray(Frame* frame) + : m_frame(frame) +{ +} + +PluginArray::~PluginArray() +{ +} + +unsigned PluginArray::length() const +{ + PluginData* data = getPluginData(); + if (!data) + return 0; + return data->plugins().size(); +} + +PassRefPtr<Plugin> PluginArray::item(unsigned index) +{ + PluginData* data = getPluginData(); + if (!data) + return 0; + const Vector<PluginInfo*>& plugins = data->plugins(); + if (index >= plugins.size()) + return 0; + return Plugin::create(data, index).get(); +} + +bool PluginArray::canGetItemsForName(const AtomicString& propertyName) +{ + PluginData* data = getPluginData(); + 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 false; +} + +PassRefPtr<Plugin> PluginArray::nameGetter(const AtomicString& propertyName) +{ + PluginData* data = getPluginData(); + if (!data) + return 0; + const Vector<PluginInfo*>& plugins = data->plugins(); + for (unsigned i = 0; i < plugins.size(); ++i) { + if (plugins[i]->name == propertyName) + return Plugin::create(data, i).get(); + } + return 0; +} + +void PluginArray::refresh(bool reload) +{ + Page::refreshPlugins(reload); +} + +PluginData* PluginArray::getPluginData() const +{ + if (!m_frame) + return 0; + Page* p = m_frame->page(); + if (!p) + return 0; + return p->pluginData(); +} + +} // namespace WebCore diff --git a/WebCore/plugins/PluginArray.h b/WebCore/plugins/PluginArray.h new file mode 100644 index 0000000..e51775d --- /dev/null +++ b/WebCore/plugins/PluginArray.h @@ -0,0 +1,62 @@ +/* + Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#ifndef PluginArray_h +#define PluginArray_h + +#include "Plugin.h" +#include <wtf/PassRefPtr.h> +#include <wtf/RefCounted.h> +#include <wtf/Vector.h> + +namespace JSC { + class ExecState; +} + +namespace WebCore { + + class AtomicString; + class Frame; + class PluginData; + + // FIXME: Generated JSPluginArray.cpp doesn't include JSPlugin.h for toJS + JSC::JSValue* toJS(JSC::ExecState*, Plugin*); + + class PluginArray : public RefCounted<PluginArray> { + public: + static PassRefPtr<PluginArray> create(Frame* frame) { return adoptRef(new PluginArray(frame)); } + ~PluginArray(); + + void disconnectFrame() { m_frame = 0; } + + unsigned length() const; + PassRefPtr<Plugin> item(unsigned index); + bool canGetItemsForName(const AtomicString& propertyName); + PassRefPtr<Plugin> nameGetter(const AtomicString& propertyName); + + void refresh(bool reload); + private: + PluginArray(Frame*); + PluginData* getPluginData() const; + + Frame* m_frame; + }; +} + +#endif diff --git a/WebCore/plugins/PluginArray.idl b/WebCore/plugins/PluginArray.idl new file mode 100644 index 0000000..58f68b5 --- /dev/null +++ b/WebCore/plugins/PluginArray.idl @@ -0,0 +1,27 @@ +/* + Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +module window { + + interface [HasNameGetter, HasIndexGetter] PluginArray { + readonly attribute unsigned long length; + void refresh(in boolean reload); + }; + +} diff --git a/WebCore/plugins/PluginData.cpp b/WebCore/plugins/PluginData.cpp new file mode 100644 index 0000000..ca4bda5 --- /dev/null +++ b/WebCore/plugins/PluginData.cpp @@ -0,0 +1,63 @@ +/* + 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) 2008 Nokia Corporation and/or its subsidiary(-ies) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "config.h" +#include "PluginData.h" + +namespace WebCore { + +PluginData::PluginData(const Page* page) + : m_page(page) +{ + initPlugins(); + + 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]); + } +} + +PluginData::~PluginData() +{ + deleteAllValues(m_plugins); + deleteAllValues(m_mimes); +} + +bool PluginData::supportsMimeType(const String& mimeType) const +{ + for (unsigned i = 0; i < m_mimes.size(); ++i) + if (m_mimes[i]->type == mimeType) + return true; + return false; +} + +String PluginData::pluginNameForMimeType(const String& mimeType) const +{ + for (unsigned i = 0; i < m_mimes.size(); ++i) + if (m_mimes[i]->type == mimeType) + return m_mimes[i]->plugin->name; + return String(); +} + +} diff --git a/WebCore/plugins/PluginData.h b/WebCore/plugins/PluginData.h new file mode 100644 index 0000000..b2866bf --- /dev/null +++ b/WebCore/plugins/PluginData.h @@ -0,0 +1,74 @@ +/* + Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#ifndef PluginData_h +#define PluginData_h + +#include <wtf/RefCounted.h> +#include <wtf/Vector.h> +#include "PlatformString.h" + +namespace WebCore { + + class Page; + struct PluginInfo; + + struct MimeClassInfo { + String type; + String desc; + String suffixes; + PluginInfo* plugin; + }; + + struct PluginInfo { + String name; + String file; + String desc; + Vector<MimeClassInfo*> mimes; + }; + + // 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)); } + ~PluginData(); + + void disconnectPage() { m_page = 0; } + const Page* page() const { return m_page; } + + const Vector<PluginInfo*>& plugins() const { return m_plugins; } + const Vector<MimeClassInfo*>& mimes() const { return m_mimes; } + + bool supportsMimeType(const String& mimeType) const; + String pluginNameForMimeType(const String& mimeType) const; + + static void refresh(); + + private: + PluginData(const Page*); + void initPlugins(); + + Vector<PluginInfo*> m_plugins; + Vector<MimeClassInfo*> m_mimes; + const Page* m_page; + }; + +} + +#endif diff --git a/WebCore/plugins/PluginDatabase.cpp b/WebCore/plugins/PluginDatabase.cpp new file mode 100644 index 0000000..e3b86ae --- /dev/null +++ b/WebCore/plugins/PluginDatabase.cpp @@ -0,0 +1,375 @@ +/* + * 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 "KURL.h" +#include "PluginPackage.h" +#include <stdlib.h> + +namespace WebCore { + +PluginDatabase* PluginDatabase::installedPlugins() +{ + static PluginDatabase* plugins = 0; + + if (!plugins) { + plugins = new PluginDatabase; + 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() +{ + 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; + + 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_end = (*it)->mimeToDescriptions().end(); + for (MIMEToDescriptionsMap::const_iterator map_it = (*it)->mimeToDescriptions().begin(); map_it != map_end; ++map_it) { + m_registeredMIMETypes.add(map_it->first); + } + } + + 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(); + + Vector<PluginPackage*, 2> pluginChoices; + + for (PluginSet::const_iterator it = m_plugins.begin(); it != end; ++it) { + if ((*it)->mimeToDescriptions().contains(key)) + pluginChoices.append((*it).get()); + } + + 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) { + MIMEToExtensionsMap::const_iterator mime_end = (*it)->mimeToExtensions().end(); + + for (MIMEToExtensionsMap::const_iterator mime_it = (*it)->mimeToExtensions().begin(); mime_it != mime_end; ++mime_it) { + const Vector<String>& extensions = mime_it->second; + bool foundMapping = false; + for (unsigned i = 0; i < extensions.size(); i++) { + if (equalIgnoringCase(extensions[i], extension)) { + PluginPackage* plugin = (*it).get(); + pluginChoices.append(plugin); + mimeTypeForPlugin.add(plugin, mime_it->first); + 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 KURL& url, String& mimeType) +{ + PluginPackage* plugin = pluginForMIMEType(mimeType); + String filename = url.string(); + + if (!plugin) { + String filename = url.lastPathComponent(); + if (!filename.endsWith("/")) { + int extensionPos = filename.reverseFind('.'); + if (extensionPos != -1) { + String extension = filename.substring(extensionPos + 1); + + mimeType = MIMETypeForExtension(extension); + plugin = pluginForMIMEType(mimeType); + } + } + } + + // FIXME: if no plugin could be found, query Windows for the mime type + // corresponding to the extension. + + return plugin; +} + +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 (!fileExists((*it)->path())) + plugins.add(*it); + } +} + +bool PluginDatabase::add(PassRefPtr<PluginPackage> prpPackage) +{ + ASSERT_ARG(prpPackage, prpPackage); + + RefPtr<PluginPackage> package = prpPackage; + + if (!m_plugins.add(package).second) + return false; + + m_pluginsByPath.add(package->path(), package); + return true; +} + +void PluginDatabase::remove(PluginPackage* package) +{ + m_plugins.remove(package); + m_pluginsByPath.remove(package->path()); +} + +#if !PLATFORM(WIN_OS) || PLATFORM(WX) +// 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"); + + 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.append(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 + + // Add paths specific to each port +#if PLATFORM(QT) + Vector<String> qtPaths; + String qtPath(getenv("QTWEBKIT_PLUGIN_PATH")); + qtPath.split(UChar(':'), /* allowEmptyEntries */ false, qtPaths); + paths.append(qtPaths); +#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) || defined(ANDROID) + 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 (!fileExists(*pIt)) + continue; + + paths.add(*pIt); + } + } +} + +#endif // !PLATFORM(WIN_OS) + +} diff --git a/WebCore/plugins/PluginDatabase.h b/WebCore/plugins/PluginDatabase.h new file mode 100644 index 0000000..ccb3821 --- /dev/null +++ b/WebCore/plugins/PluginDatabase.h @@ -0,0 +1,96 @@ +/* + * 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 PluginDatabase_H +#define PluginDatabase_H + +#include "PlatformString.h" +#include "PluginPackage.h" +#include "StringHash.h" + +#include <wtf/Vector.h> +#include <wtf/HashSet.h> + +#if defined(ANDROID_PLUGINS) +namespace android { + class WebSettings; +} +#endif + +namespace WebCore { + class Element; + class Frame; + class IntSize; + class KURL; + class PluginPackage; + + typedef HashSet<RefPtr<PluginPackage>, PluginPackageHash> PluginSet; + + class PluginDatabase { + public: + static PluginDatabase* installedPlugins(); + + bool refresh(); + 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 KURL&, String& mimeType); + + private: + void setPluginDirectories(const Vector<String>& directories) { m_pluginDirectories = directories; } + + void getPluginPathsInDirectories(HashSet<String>&) const; + void getDeletedPlugins(PluginSet&) 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*); + + PluginPackage* pluginForMIMEType(const String& mimeType); + String MIMETypeForExtension(const String& extension) const; + + static Vector<String> defaultPluginDirectories(); + + Vector<String> m_pluginDirectories; + HashSet<String> m_registeredMIMETypes; + PluginSet m_plugins; + HashMap<String, RefPtr<PluginPackage> > m_pluginsByPath; + HashMap<String, time_t> m_pluginPathsWithTimes; + +#if defined(ANDROID_PLUGINS) + // Need access to setPluginDirectories() to change the default + // path after startup. + friend class ::android::WebSettings; +#endif + }; + +} // namespace WebCore + +#endif diff --git a/WebCore/plugins/PluginDebug.h b/WebCore/plugins/PluginDebug.h new file mode 100644 index 0000000..a57c209 --- /dev/null +++ b/WebCore/plugins/PluginDebug.h @@ -0,0 +1,57 @@ +/* + * 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" + +#if !LOG_DISABLED + +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" +}; + +#endif + +#define LOG_NPERROR(err) if (err != NPERR_NO_ERROR) LOG_VERBOSE(Plugin, "%s\n", errorStrings[err]) +#define LOG_PLUGIN_NET_ERROR() LOG_VERBOSE(Plugin, "Stream failed due to problems with network, disk I/O, lack of memory, or other problems.\n") + +#endif diff --git a/WebCore/plugins/PluginInfoStore.cpp b/WebCore/plugins/PluginInfoStore.cpp new file mode 100644 index 0000000..bd2f2d0 --- /dev/null +++ b/WebCore/plugins/PluginInfoStore.cpp @@ -0,0 +1,110 @@ +/* + * 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. + */ + +#include "config.h" +#include "PluginInfoStore.h" + +#include "KURL.h" +#if PLATFORM(ANDROID) +#include "Page.h" +#endif +#include "PluginData.h" +#include "PluginDatabase.h" +#include "PluginPackage.h" + +namespace WebCore { + +PluginInfo* PluginInfoStore::createPluginInfoForPluginAtIndex(unsigned i) +{ + PluginDatabase *db = PluginDatabase::installedPlugins(); + PluginInfo* info = new PluginInfo; + PluginPackage* package = db->plugins()[i]; + + info->name = package->name(); + info->file = package->fileName(); + info->desc = package->description(); + + const MIMEToDescriptionsMap& mimeToDescriptions = package->mimeToDescriptions(); + MIMEToDescriptionsMap::const_iterator end = mimeToDescriptions.end(); + for (MIMEToDescriptionsMap::const_iterator it = mimeToDescriptions.begin(); it != end; ++it) { + MimeClassInfo* mime = new MimeClassInfo; + info->mimes.append(mime); + + mime->type = it->first; + mime->desc = it->second; + mime->plugin = info; + + Vector<String> extensions = package->mimeToExtensions().get(mime->type); + + for (unsigned i = 0; i < extensions.size(); i++) { + if (i > 0) + mime->suffixes += ","; + + mime->suffixes += extensions[i]; + } + } + + return info; +} + +unsigned PluginInfoStore::pluginCount() const +{ + return PluginDatabase::installedPlugins()->plugins().size(); +} + + +String PluginInfoStore::pluginNameForMIMEType(const String& mimeType) +{ + String mimeTypeCopy(mimeType); + + if (PluginPackage* package = PluginDatabase::installedPlugins()->findPlugin(KURL(), mimeTypeCopy)) { + ASSERT(mimeType == mimeTypeCopy); + + return package->name(); + } + + return String(); +} + + +bool PluginInfoStore::supportsMIMEType(const WebCore::String& mimeType) +{ + return PluginDatabase::installedPlugins()->isMIMETypeRegistered(mimeType); +} + +void refreshPlugins(bool reloadOpenPages) +{ +#if PLATFORM(ANDROID) + Page::refreshPlugins(reloadOpenPages); +#else + PluginDatabase::installedPlugins()->refresh(); + + if (reloadOpenPages) { + // FIXME: reload open pages + } +#endif +} + +} diff --git a/WebCore/plugins/PluginInfoStore.h b/WebCore/plugins/PluginInfoStore.h new file mode 100644 index 0000000..302cf8c --- /dev/null +++ b/WebCore/plugins/PluginInfoStore.h @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2004, 2006 Apple Computer, 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 PluginInfoStore_h +#define PluginInfoStore_h + +#include "PlatformString.h" +#include <wtf/Vector.h> + +namespace WebCore { + +struct PluginInfo; + +class PluginInfoStore { +public: + PluginInfo *createPluginInfoForPluginAtIndex(unsigned); + unsigned pluginCount() const; + static String pluginNameForMIMEType(const String& mimeType); + static bool supportsMIMEType(const String& mimeType); +}; + +void refreshPlugins(bool reloadOpenPages); + +} + +#endif diff --git a/WebCore/plugins/PluginMainThreadScheduler.cpp b/WebCore/plugins/PluginMainThreadScheduler.cpp new file mode 100644 index 0000000..a7067f1 --- /dev/null +++ b/WebCore/plugins/PluginMainThreadScheduler.cpp @@ -0,0 +1,115 @@ +/* + * 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" + +namespace WebCore { + +PluginMainThreadScheduler& PluginMainThreadScheduler::scheduler() +{ + static PluginMainThreadScheduler& scheduler = *new PluginMainThreadScheduler; + + 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->second.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->second.clear(); + } + + m_callPending = false; + m_queueMutex.unlock(); + + CallQueueMap::iterator end = copy.end(); + for (CallQueueMap::iterator it = copy.begin(); it != end; ++it) + dispatchCallsForPlugin(it->first, it->second); +} + +void PluginMainThreadScheduler::mainThreadCallback(void* context) +{ + static_cast<PluginMainThreadScheduler*>(context)->dispatchCalls(); +} + +} // namespace WebCore diff --git a/WebCore/plugins/PluginMainThreadScheduler.h b/WebCore/plugins/PluginMainThreadScheduler.h new file mode 100644 index 0000000..8872d56 --- /dev/null +++ b/WebCore/plugins/PluginMainThreadScheduler.h @@ -0,0 +1,86 @@ +/* + * 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 { +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/WebCore/plugins/PluginPackage.cpp b/WebCore/plugins/PluginPackage.cpp new file mode 100644 index 0000000..f3c9075 --- /dev/null +++ b/WebCore/plugins/PluginPackage.cpp @@ -0,0 +1,166 @@ +/* + * Copyright (C) 2006, 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 "PluginPackage.h" + +#include "CString.h" +#include "MIMETypeRegistry.h" +#include "PluginDatabase.h" +#include "PluginDebug.h" +#include "Timer.h" +#include "npruntime_impl.h" +#include <string.h> +#include <wtf/OwnArrayPtr.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 == 0) + unloadWithoutShutdown(); + else + unload(); + + ASSERT(!m_isLoaded); +} + +void PluginPackage::freeLibrarySoon() +{ + ASSERT(!m_freeLibraryTimer.isActive()); + ASSERT(m_module); + ASSERT(m_loadCount == 0); + +#ifdef ANDROID_PLUGINS + // TODO(jripley): Timer<T> is broken. Unload immediately for now. + unloadModule(m_module); + m_module = 0; +#else + m_freeLibraryTimer.startOneShot(0); +#endif +} + +void PluginPackage::freeLibraryTimerFired(Timer<PluginPackage>*) +{ + ASSERT(m_module); + ASSERT(m_loadCount == 0); + + 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; + + if (diff = compareFileVersion(compareTo.version())) + return diff; + + return strcmp(parentDirectory().utf8().data(), compareTo.parentDirectory().utf8().data()); +} + +PluginPackage::PluginPackage(const String& path, const time_t& lastModified) + : m_isLoaded(false) + , m_loadCount(0) + , m_path(path) + , m_moduleVersion(0) + , m_module(0) + , m_lastModified(lastModified) + , m_freeLibraryTimer(this, &PluginPackage::freeLibraryTimerFired) +{ + 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; + + m_NPP_Shutdown(); + + unloadWithoutShutdown(); +} + +void PluginPackage::unloadWithoutShutdown() +{ + if (!m_isLoaded) + return; + + ASSERT(m_loadCount == 0); + ASSERT(m_module); + +#if defined(ANDROID_PLUGINS) + // Remove the Java object from PluginList. + unregisterPluginObject(); +#endif + + // <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; +} + +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(); +} + +} diff --git a/WebCore/plugins/PluginPackage.h b/WebCore/plugins/PluginPackage.h new file mode 100644 index 0000000..4cf5e9e --- /dev/null +++ b/WebCore/plugins/PluginPackage.h @@ -0,0 +1,127 @@ +/* + * 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 "PlatformString.h" +#include "PluginQuirkSet.h" +#include "StringHash.h" +#include "Timer.h" +#include "npruntime_internal.h" +#include <wtf/HashMap.h> +#include <wtf/RefCounted.h> +#if defined(ANDROID_PLUGINS) +#include <nativehelper/jni.h> +#endif + +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); + + 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; } + 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(); + + const NPPluginFuncs* pluginFuncs() const { return &m_pluginFuncs; } + int compareFileVersion(const PlatformModuleVersion&) const; + int compare(const PluginPackage&) const; + PluginQuirkSet quirks() const { return m_quirks; } + const PlatformModuleVersion& version() const { return m_moduleVersion; } + + private: + PluginPackage(const String& path, const time_t& lastModified); + bool fetchInfo(); + bool isPluginBlacklisted(); + void determineQuirks(const String& mimeType); + + 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; + + NPP_ShutdownProcPtr m_NPP_Shutdown; + NPPluginFuncs m_pluginFuncs; + NPNetscapeFuncs m_browserFuncs; + + void freeLibrarySoon(); + void freeLibraryTimerFired(Timer<PluginPackage>*); + Timer<PluginPackage> m_freeLibraryTimer; + + PluginQuirkSet m_quirks; + +#if defined(ANDROID_PLUGINS) + // Java Plugin object. + jobject m_pluginObject; + // Called from unloadWithoutShutdown() to remove the object + // from the PluginList. + void unregisterPluginObject(); +#endif + }; + + 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/WebCore/plugins/PluginQuirkSet.h b/WebCore/plugins/PluginQuirkSet.h new file mode 100644 index 0000000..e93f6e0 --- /dev/null +++ b/WebCore/plugins/PluginQuirkSet.h @@ -0,0 +1,61 @@ +/* + * 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, + }; + + 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/WebCore/plugins/PluginStream.cpp b/WebCore/plugins/PluginStream.cpp new file mode 100644 index 0000000..4bf2db4 --- /dev/null +++ b/WebCore/plugins/PluginStream.cpp @@ -0,0 +1,474 @@ +/* + * 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 "CString.h" +#include "DocumentLoader.h" +#include "Frame.h" +#include "FrameLoader.h" +#include "PluginDebug.h" +#include "SharedBuffer.h" +#include "SubresourceLoader.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_deliveryData(0) + , 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; + + streams().add(&m_stream, m_instance); +} + +PluginStream::~PluginStream() +{ + ASSERT(m_streamState != StreamStarted); + ASSERT(!m_loader); + + free((char*)m_stream.url); + + streams().remove(&m_stream); +} + +void PluginStream::start() +{ + ASSERT(!m_loadManually); + + m_loader = NetscapePlugInStreamLoader::create(m_frame, this); + + m_loader->setShouldBufferData(false); + m_loader->documentLoader()->addPlugInStreamLoader(m_loader.get()); + m_loader->load(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; + } +} + +void PluginStream::startStream() +{ + ASSERT(m_streamState == StreamBeforeStarted); + + const KURL& 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 (responseURL.protocolIs("javascript")) + m_stream.url = strdup(decodeURLEscapeSequences(responseURL.string()).utf8().data()); + else + m_stream.url = strdup(responseURL.string().utf8().data()); + + CString mimeTypeStr = m_resourceResponse.mimeType().utf8(); + + long long expectedContentLength = m_resourceResponse.expectedContentLength(); + + if (m_resourceResponse.isHTTP()) { + Vector<UChar> stringBuilder; + String separator(": "); + + String statusLine = String::format("HTTP %lu OK\n", m_resourceResponse.httpStatusCode()); + + stringBuilder.append(statusLine.characters(), statusLine.length()); + + HTTPHeaderMap::const_iterator end = m_resourceResponse.httpHeaderFields().end(); + for (HTTPHeaderMap::const_iterator it = m_resourceResponse.httpHeaderFields().begin(); it != end; ++it) { + stringBuilder.append(it->first.characters(), it->first.length()); + stringBuilder.append(separator.characters(), separator.length()); + stringBuilder.append(it->second.characters(), it->second.length()); + stringBuilder.append('\n'); + } + + m_headers = String::adopt(stringBuilder).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 = m_resourceResponse.lastModifiedDate(); + 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; + + 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.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")) { + // Protect the stream if NPN_DestroyStream is called from NPP_NewStream + RefPtr<PluginStream> protect(this); + + m_transferMode = NP_NORMAL; + m_stream.url = ""; + m_stream.notifyData = m_notifyData; + + m_pluginFuncs->newstream(m_instance, "", &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; + + // streamDidFinishLoading can cause us to be deleted. + RefPtr<PluginStream> protect(this); + if (!m_loadManually) + m_client->streamDidFinishLoading(this); + + if (!m_path.isNull()) { + String tempFilePath = String::fromUTF8(m_path.data()); + deleteFile(tempFilePath); + } +} + +void PluginStream::delayDeliveryTimerFired(Timer<PluginStream>* timer) +{ + ASSERT(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 totalBytes = m_deliveryData->size(); + int32 totalBytesDelivered = 0; + + if (m_loader) + m_loader->setDefersLoading(true); + while (totalBytesDelivered < totalBytes) { + int32 deliveryBytes = m_pluginFuncs->writeready(m_instance, &m_stream); + + if (deliveryBytes <= 0) { + m_delayDeliveryTimer.startOneShot(0); + break; + } else { + deliveryBytes = min(deliveryBytes, totalBytes - totalBytesDelivered); + int32 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(); + 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 KURL& 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(loader == m_loader); + ASSERT(m_streamState == StreamBeforeStarted); + + m_resourceResponse = response; + + startStream(); +} + +void PluginStream::didReceiveData(NetscapePlugInStreamLoader* loader, const char* data, int length) +{ + ASSERT(loader == m_loader); + ASSERT(length > 0); + 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.set(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(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(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/WebCore/plugins/PluginStream.h b/WebCore/plugins/PluginStream.h new file mode 100644 index 0000000..dc08f01 --- /dev/null +++ b/WebCore/plugins/PluginStream.h @@ -0,0 +1,123 @@ +/* + * 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 "CString.h" +#include "FileSystem.h" +#include "KURL.h" +#include "NetscapePlugInStreamLoader.h" +#include "PlatformString.h" +#include "PluginQuirkSet.h" +#include "ResourceRequest.h" +#include "ResourceResponse.h" +#include "StringHash.h" +#include "Timer.h" +#include "npruntime_internal.h" +#include <wtf/HashMap.h> +#include <wtf/OwnPtr.h> +#include <wtf/RefCounted.h> +#include <wtf/Vector.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 KURL& requestURL, const 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 m_transferMode; + int32 m_offset; + CString m_headers; + CString m_path; + NPReason m_reason; + NPStream m_stream; + PluginQuirkSet m_quirks; + }; + +} // namespace WebCore + +#endif diff --git a/WebCore/plugins/PluginView.cpp b/WebCore/plugins/PluginView.cpp new file mode 100644 index 0000000..459b11e --- /dev/null +++ b/WebCore/plugins/PluginView.cpp @@ -0,0 +1,922 @@ +/* + * 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 "PluginView.h" + +#include "Document.h" +#include "DocumentLoader.h" +#include "Element.h" +#include "FrameLoader.h" +#include "FrameTree.h" +#include "Frame.h" +#include "FrameView.h" +#include "GraphicsContext.h" +#include "Image.h" +#include "HTMLNames.h" +#include "HTMLPlugInElement.h" +#include "JSDOMWindow.h" +#include "KeyboardEvent.h" +#include "MIMETypeRegistry.h" +#include "MouseEvent.h" +#include "NotImplemented.h" +#include "Page.h" +#include "FocusController.h" +#include "PlatformMouseEvent.h" +#if PLATFORM(WIN_OS) && !PLATFORM(WX) && ENABLE(NETSCAPE_PLUGIN_API) +#include "PluginMessageThrottlerWin.h" +#endif +#include "PluginPackage.h" +#include "JSDOMBinding.h" +#include "ScriptController.h" +#include "PluginDatabase.h" +#include "PluginDebug.h" +#include "PluginMainThreadScheduler.h" +#include "PluginPackage.h" +#include "RenderObject.h" +#include "c_instance.h" +#include "npruntime_impl.h" +#include "runtime_root.h" +#include "Settings.h" +#include "runtime.h" +#include <runtime/JSLock.h> +#include <runtime/JSValue.h> +#include <wtf/ASCIICType.h> + +using JSC::ExecState; +using JSC::JSLock; +using JSC::JSObject; +using JSC::JSValue; +using JSC::UString; + +using std::min; + +using namespace WTF; + +namespace WebCore { + +using namespace HTMLNames; + +static int s_callingPlugin; + +static String scriptStringIfJavaScriptURL(const KURL& url) +{ + if (!url.protocolIs("javascript")) + 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. + RenderLayer* layer = m_element->renderer()->enclosingLayer(); + FrameView* parentView = m_element->document()->view(); + clipRect.intersect(parentView->windowClipRectForLayer(layer, true)); + + return clipRect; +} + +void PluginView::setFrameRect(const IntRect& rect) +{ + if (m_element->document()->printing()) + return; + +#if defined(ANDROID_PLUGINS) + if (rect != frameRect()) { + Widget::setFrameRect(rect); + setNPWindowRect(rect); // only call when it changes + } +#else + if (rect != frameRect()) + Widget::setFrameRect(rect); +#endif + + updatePluginWidget(); + +#if PLATFORM(WIN_OS) + // On Windows, always call plugin to change geometry. + setNPWindowRect(rect); +#elif XP_UNIX + // On Unix, only call plugin if it's full-page. + if (m_mode == NP_FULL) + setNPWindowRect(rect); +#endif +} + +void PluginView::frameRectsChanged() const +{ + updatePluginWidget(); +} + +void PluginView::handleEvent(Event* event) +{ + if (!m_plugin || m_isWindowed) + return; + + if (event->isMouseEvent()) + handleMouseEvent(static_cast<MouseEvent*>(event)); + else if (event->isKeyboardEvent()) + handleKeyboardEvent(static_cast<KeyboardEvent*>(event)); +} + +bool PluginView::start() +{ + if (m_isStarted) + return false; + + PluginMainThreadScheduler::scheduler().registerPlugin(m_instance); + + ASSERT(m_plugin); + ASSERT(m_plugin->pluginFuncs()->newp); + + NPError npErr; + { + PluginView::setCurrentPluginView(this); + JSC::JSLock::DropAllLocks dropAllLocks(false); + setCallingPlugin(true); + npErr = m_plugin->pluginFuncs()->newp((NPMIMEType)m_mimeType.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) + return false; + + m_isStarted = true; + + if (!m_url.isEmpty() && !m_loadManually) { + FrameLoadRequest frameLoadRequest; + frameLoadRequest.resourceRequest().setHTTPMethod("GET"); + frameLoadRequest.resourceRequest().setURL(m_url); + load(frameLoadRequest, false, 0); + } + + return true; +} + +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; +} + +static bool getString(ScriptController* proxy, JSValue* result, String& string) +{ + if (!proxy || !result || result->isUndefined()) + return false; + JSLock lock(false); + + ExecState* exec = proxy->globalObject()->globalExec(); + UString ustring = result->toString(exec); + exec->clearException(); + + string = ustring; + return true; +} + +void PluginView::performRequest(PluginRequest* request) +{ + // 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; + + KURL requestURL = request->frameLoadRequest().resourceRequest().url(); + String jsString = scriptStringIfJavaScriptURL(requestURL); + + 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, request->frameLoadRequest().resourceRequest(), request->sendNotification(), request->notifyData(), plugin()->pluginFuncs(), instance(), m_plugin->quirks()); + m_streams.add(stream); + stream->start(); + } else { + m_parentFrame->loader()->load(request->frameLoadRequest().resourceRequest(), targetFrameName); + + // FIXME: <rdar://problem/4807469> This should be sent when the document has finished loading + if (request->sendNotification()) { + PluginView::setCurrentPluginView(this); + JSC::JSLock::DropAllLocks dropAllLocks(false); + 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 the parent frame. + RefPtr<Frame> parentFrame = m_parentFrame; + JSValue* result = m_parentFrame->loader()->executeScript(jsString, request->shouldAllowPopups()); + + if (targetFrameName.isNull()) { + String resultString; + + CString cstr; + if (getString(parentFrame->script(), result, resultString)) + cstr = resultString.utf8(); + + RefPtr<PluginStream> stream = PluginStream::create(this, m_parentFrame, 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(timer == &m_requestTimer); + ASSERT(m_requests.size() > 0); + ASSERT(!m_isJavaScriptPaused); + + PluginRequest* request = m_requests[0]; + 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.size() > 0) + m_requestTimer.startOneShot(0); + + performRequest(request); + delete request; +} + +void PluginView::scheduleRequest(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"); + + KURL 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. + if (m_parentFrame->loader()->documentLoader()->isStopping()) + return NPERR_GENERIC_ERROR; + + const String& targetFrameName = frameLoadRequest.frameName(); + String jsString = scriptStringIfJavaScriptURL(url); + + if (!jsString.isNull()) { + Settings* settings = m_parentFrame->settings(); + + // Return NPERR_GENERIC_ERROR if JS is disabled. This is what Mozilla does. + if (!settings || !settings->isJavaScriptEnabled()) + 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 (!FrameLoader::canLoad(url, String(), m_parentFrame->document())) { + return NPERR_GENERIC_ERROR; + } + + PluginRequest* request = new PluginRequest(frameLoadRequest, sendNotification, notifyData, arePopupsAllowed()); + scheduleRequest(request); + + return NPERR_NO_ERROR; +} + +static KURL makeURL(const KURL& baseURL, const char* relativeURLString) +{ + String urlString = relativeURLString; + + // Strip return characters. + urlString.replace('\n', ""); + urlString.replace('\r', ""); + + return KURL(baseURL, urlString); +} + +NPError PluginView::getURLNotify(const char* url, const char* target, void* notifyData) +{ + FrameLoadRequest frameLoadRequest; + + frameLoadRequest.setFrameName(target); + frameLoadRequest.resourceRequest().setHTTPMethod("GET"); + frameLoadRequest.resourceRequest().setURL(makeURL(m_baseURL, url)); + + return load(frameLoadRequest, true, notifyData); +} + +NPError PluginView::getURL(const char* url, const char* target) +{ + FrameLoadRequest frameLoadRequest; + + frameLoadRequest.setFrameName(target); + frameLoadRequest.resourceRequest().setHTTPMethod("GET"); + frameLoadRequest.resourceRequest().setURL(makeURL(m_baseURL, url)); + + return load(frameLoadRequest, false, 0); +} + +NPError PluginView::postURLNotify(const char* url, const char* target, uint32 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 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 type, const char* target, NPStream** stream) +{ + notImplemented(); + // Unsupported + return NPERR_GENERIC_ERROR; +} + +int32 PluginView::write(NPStream* stream, int32 len, void* buffer) +{ + notImplemented(); + // Unsupported + return -1; +} + +NPError PluginView::destroyStream(NPStream* stream, NPReason reason) +{ + PluginStream* browserStream = static_cast<PluginStream*>(stream->ndata); + + if (!stream || PluginStream::ownerForStream(stream) != m_instance) + return NPERR_INVALID_INSTANCE_ERROR; + + browserStream->cancelAndDestroyStream(reason); + return NPERR_NO_ERROR; +} + +void PluginView::status(const char* message) +{ + if (Page* page = m_parentFrame->page()) + page->chrome()->setStatusbarText(m_parentFrame, String(message)); +} + +NPError PluginView::setValue(NPPVariable variable, void* value) +{ + switch (variable) { + case NPPVpluginWindowBool: + m_isWindowed = value; + return NPERR_NO_ERROR; + case NPPVpluginTransparentBool: + m_isTransparent = value; + return NPERR_NO_ERROR; + default: +#ifdef PLUGIN_PLATFORM_SETVALUE + return platformSetValue(variable, value); +#else + notImplemented(); + return NPERR_GENERIC_ERROR; +#endif + } +} + +void PluginView::invalidateTimerFired(Timer<PluginView>* timer) +{ + ASSERT(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); +} + +PassRefPtr<JSC::Bindings::Instance> PluginView::bindingInstance() +{ +#if ENABLE(NETSCAPE_PLUGIN_API) + NPObject* object = 0; + + if (!m_plugin || !m_plugin->pluginFuncs()->getvalue) + return 0; + + NPError npErr; + { + PluginView::setCurrentPluginView(this); + JSC::JSLock::DropAllLocks dropAllLocks(false); + setCallingPlugin(true); + npErr = m_plugin->pluginFuncs()->getvalue(m_instance, NPPVpluginScriptableNPObject, &object); + setCallingPlugin(false); + PluginView::setCurrentPluginView(0); + } + + if (npErr != NPERR_NO_ERROR || !object) + 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; + + 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, Element* element, const KURL& 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_baseURL(m_parentFrame->loader()->completeURL(m_parentFrame->document()->baseURL().string())) + , m_status(PluginStatusLoadedSuccessfully) + , m_requestTimer(this, &PluginView::requestTimerFired) + , m_invalidateTimer(this, &PluginView::invalidateTimerFired) + , m_popPopupsStateTimer(this, &PluginView::popPopupsStateTimerFired) + , m_paramNames(0) + , m_paramValues(0) + , m_isWindowed(true) + , m_isTransparent(false) + , m_haveInitialized(false) +#if PLATFORM(GTK) || defined(Q_WS_X11) + , m_needsXEmbed(false) +#endif +#if PLATFORM(QT) + , m_isNPAPIPlugin(false) +#endif +#if PLATFORM(WIN_OS) && !PLATFORM(WX) && ENABLE(NETSCAPE_PLUGIN_API) + , m_pluginWndProc(0) + , m_lastMessage(0) + , m_isCallingPluginWndProc(false) +#endif +#if PLATFORM(WIN_OS) && PLATFORM(QT) + , m_window(0) +#endif + , m_loadManually(loadManually) + , m_manualStream(0) + , m_isJavaScriptPaused(false) +{ +#if defined(ANDROID_PLUGINS) + platformInit(); +#endif + + if (!m_plugin) { + m_status = PluginStatusCanNotFindPlugin; + return; + } + + m_instance = &m_instanceStruct; + m_instance->ndata = this; + m_instance->pdata = 0; + + m_mimeType = mimeType.utf8(); + + setParameters(paramNames, paramValues); + +#ifdef XP_UNIX + m_npWindow.ws_info = 0; +#endif + + m_mode = m_loadManually ? NP_FULL : NP_EMBED; + + resize(size); +} + +void PluginView::didReceiveResponse(const ResourceResponse& response) +{ + ASSERT(m_loadManually); + ASSERT(!m_manualStream); + + m_manualStream = PluginStream::create(this, m_parentFrame, 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) +{ + ASSERT(m_loadManually); + ASSERT(m_manualStream); + + m_manualStream->didReceiveData(0, data, length); +} + +void PluginView::didFinishLoading() +{ + ASSERT(m_loadManually); + ASSERT(m_manualStream); + + m_manualStream->didFinishLoading(0); +} + +void PluginView::didFail(const ResourceError& error) +{ + ASSERT(m_loadManually); + ASSERT(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; +} + +PluginView* PluginView::create(Frame* parentFrame, const IntSize& size, Element* element, const KURL& url, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType, bool loadManually) +{ + // 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 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()) { + String tmp = oldValue; + tmp += ", "; + tmp += value; + value = tmp; + } + + headerFields.set(lastKey, value); + } + } + } + + return headerFields; +} + +NPError PluginView::handlePost(const char* url, const char* target, uint32 len, const char* buf, bool file, void* notifyData, bool sendNotification, bool allowHeaders) +{ + if (!url || !len || !buf) + return NPERR_INVALID_PARAM; + + FrameLoadRequest frameLoadRequest; + + 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_baseURL, url)); + frameLoadRequest.resourceRequest().addHTTPHeaderFields(headerFields); + frameLoadRequest.resourceRequest().setHTTPBody(FormData::create(postData, postDataLength)); + frameLoadRequest.setFrameName(target); + + return load(frameLoadRequest, sendNotification, notifyData); +} + +#ifdef PLUGIN_SCHEDULE_TIMER +uint32 PluginView::scheduleTimer(NPP instance, uint32 interval, bool repeat, + void (*timerFunc)(NPP, uint32 timerID)) +{ + return m_timerList.schedule(instance, interval, repeat, timerFunc); +} + +void PluginView::unscheduleTimer(NPP instance, uint32 timerID) +{ + m_timerList.unschedule(instance, timerID); +} +#endif + +void PluginView::invalidateWindowlessPluginRect(const IntRect& rect) +{ + if (!isVisible()) + return; + + RenderObject* renderer = m_element->renderer(); + if (!renderer) + return; + + IntRect dirtyRect = rect; + dirtyRect.move(renderer->borderLeft() + renderer->paddingLeft(), renderer->borderTop() + renderer->paddingTop()); + renderer->repaintRectangle(dirtyRect); +} + +} // namespace WebCore diff --git a/WebCore/plugins/PluginView.h b/WebCore/plugins/PluginView.h new file mode 100644 index 0000000..1a189e8 --- /dev/null +++ b/WebCore/plugins/PluginView.h @@ -0,0 +1,320 @@ + +/* + * 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 PluginView_H +#define PluginView_H + +#include "CString.h" +#include "FrameLoadRequest.h" +#include "IntRect.h" +#include "KURL.h" +#include "PlatformString.h" +#include "PluginStream.h" +#include "ResourceRequest.h" +#include "Timer.h" +#include "Widget.h" +#include "npruntime_internal.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> + +#ifdef PLUGIN_SCHEDULE_TIMER +#include "PluginTimer.h" +#endif + +#if PLATFORM(WIN_OS) && PLATFORM(QT) +typedef struct HWND__* HWND; +typedef HWND PlatformPluginWidget; +#elif defined(ANDROID_PLUGINS) +typedef struct PluginWidgetAndroid* PlatformPluginWidget; +#else +typedef PlatformWidget PlatformPluginWidget; +#endif + +namespace JSC { + namespace Bindings { + class Instance; + } +} + +namespace WebCore { + class Element; + class Frame; + class KeyboardEvent; + class MouseEvent; + class KURL; +#if PLATFORM(WIN_OS) && !PLATFORM(WX) && ENABLE(NETSCAPE_PLUGIN_API) + class PluginMessageThrottlerWin; +#endif + class PluginPackage; + class PluginRequest; + class PluginStream; + class ResourceError; + class ResourceResponse; + + enum PluginStatus { + PluginStatusCanNotFindPlugin, + PluginStatusCanNotLoadPlugin, + PluginStatusLoadedSuccessfully + }; + + class PluginRequest { + 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 PluginView : public Widget, private PluginStreamClient { + public: + static PluginView* create(Frame* parentFrame, const IntSize&, Element*, const KURL&, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType, bool loadManually); + virtual ~PluginView(); + + PluginPackage* plugin() const { return m_plugin.get(); } + NPP instance() const { return m_instance; } + + void setNPWindowRect(const IntRect&); + static PluginView* currentPluginView(); + + PassRefPtr<JSC::Bindings::Instance> bindingInstance(); + + PluginStatus status() const { return m_status; } + + // 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 len, const char* but, NPBool file, void* notifyData); + NPError postURL(const char* url, const char* target, uint32 len, const char* but, NPBool file); + NPError newStream(NPMIMEType type, const char* target, NPStream** stream); + int32 write(NPStream* stream, int32 len, void* buffer); + NPError destroyStream(NPStream* stream, NPReason reason); + const char* userAgent(); +#if ENABLE(NETSCAPE_PLUGIN_API) + static const char* userAgentStatic(); +#endif + void status(const char* message); + NPError getValue(NPNVariable variable, void* value); +#if ENABLE(NETSCAPE_PLUGIN_API) + static NPError getValueStatic(NPNVariable variable, void* value); +#endif + NPError setValue(NPPVariable variable, void* value); + void invalidateRect(NPRect*); + void invalidateRegion(NPRegion); + void forceRedraw(); + void pushPopupsEnabledState(bool state); + void popPopupsEnabledState(); +#ifdef PLUGIN_SCHEDULE_TIMER + uint32 scheduleTimer(NPP, uint32 interval, bool repeat, + void (*timerFunc)(NPP, uint32 timerID)); + void unscheduleTimer(NPP, uint32 timerID); +#endif + + virtual void invalidateRect(const IntRect&); + + bool arePopupsAllowed() const; + + void setJavaScriptPaused(bool); + + void disconnectStream(PluginStream*); + void streamDidFinishLoading(PluginStream* stream) { disconnectStream(stream); } + + // Widget functions + virtual void setFrameRect(const IntRect&); + virtual void frameRectsChanged() const; + virtual void setFocus(); + virtual void show(); + virtual void hide(); + virtual void paint(GraphicsContext*, const IntRect&); + + // 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 { return true; } + +#if PLATFORM(WIN_OS) && !PLATFORM(WX) && 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(); + +#if PLATFORM(QT) + bool isNPAPIPlugin() const { return m_isNPAPIPlugin; } + void setIsNPAPIPlugin(bool b) { m_isNPAPIPlugin = b; } +#endif + + private: + PluginView(Frame* parentFrame, const IntSize&, PluginPackage*, Element*, const KURL&, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType, bool loadManually); + + void setParameters(const Vector<String>& paramNames, const Vector<String>& paramValues); + void init(); + bool start(); + void stop(); + static void setCurrentPluginView(PluginView*); + NPError load(const FrameLoadRequest&, bool sendNotification, void* notifyData); + NPError handlePost(const char* url, const char* target, uint32 len, const char* buf, bool file, void* notifyData, bool sendNotification, bool allowHeaders); + NPError handlePostReadFile(Vector<char>& buffer, uint32 len, const char* buf); + static void freeStringArray(char** stringArray, int length); + void setCallingPlugin(bool) const; + + void invalidateWindowlessPluginRect(const IntRect&); + + Frame* m_parentFrame; + RefPtr<PluginPackage> m_plugin; + Element* m_element; + bool m_isStarted; + KURL m_url; + KURL m_baseURL; + PluginStatus m_status; + Vector<IntRect> m_invalidRects; + + void performRequest(PluginRequest*); + void scheduleRequest(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; + +#ifndef NP_NO_CARBON + bool dispatchNPEvent(NPEvent&); +#endif + void updatePluginWidget() const; + void paintMissingPluginIcon(GraphicsContext*, const IntRect&); + + void handleKeyboardEvent(KeyboardEvent*); + void handleMouseEvent(MouseEvent*); + +#ifdef ANDROID_PLUGINS + // called at the end of the base constructor + void platformInit(); +#endif +#ifdef PLUGIN_PLATFORM_SETVALUE + // called if the default setValue does not recognize the variable + NPError platformSetValue(NPPVariable variable, void* value); +#endif + + int m_mode; + int m_paramCount; + char** m_paramNames; + char** m_paramValues; + + CString m_mimeType; + CString m_userAgent; + + NPP m_instance; + NPP_t m_instanceStruct; + NPWindow m_npWindow; + + Vector<bool, 4> m_popupStateStack; + + HashSet<RefPtr<PluginStream> > m_streams; + Vector<PluginRequest*> m_requests; + + bool m_isWindowed; + bool m_isTransparent; + bool m_haveInitialized; + +#if PLATFORM(QT) + bool m_isNPAPIPlugin; +#endif + +#if PLATFORM(GTK) || defined(Q_WS_X11) + bool m_needsXEmbed; +#endif + +#if PLATFORM(WIN_OS) && !PLATFORM(WX) && ENABLE(NETSCAPE_PLUGIN_API) + OwnPtr<PluginMessageThrottlerWin> m_messageThrottler; + WNDPROC m_pluginWndProc; + unsigned m_lastMessage; + bool m_isCallingPluginWndProc; +#endif + +#ifdef PLUGIN_SCHEDULE_TIMER + PluginTimerList m_timerList; +#endif + +#if PLATFORM(WIN_OS) && PLATFORM(QT) + // Only under Qt on Windows, the plugin widget (HWND) does not match the native widget (QWidget). + PlatformPluginWidget m_window; // for windowed plug-ins +public: + PlatformPluginWidget platformPluginWidget() const { return m_window; } +#elif defined(ANDROID_PLUGINS) +public: + PlatformPluginWidget m_window; + PlatformPluginWidget platformPluginWidget() const { return m_window; } // MANUAL MERGE FIXME +#else +public: + PlatformPluginWidget platformPluginWidget() const { return platformWidget(); } +#endif + +private: + + mutable IntRect m_clipRect; // The clip rect to apply to a windowed plug-in + mutable IntRect m_windowRect; // Our window rect. + + bool m_loadManually; + RefPtr<PluginStream> m_manualStream; + + bool m_isJavaScriptPaused; + + static PluginView* s_currentPluginView; + }; + +} // namespace WebCore + +#endif diff --git a/WebCore/plugins/android/PluginDataAndroid.cpp b/WebCore/plugins/android/PluginDataAndroid.cpp new file mode 100644 index 0000000..23bed89 --- /dev/null +++ b/WebCore/plugins/android/PluginDataAndroid.cpp @@ -0,0 +1,73 @@ +/* + * Copyright 2009, The Android Open Source Project + Copyright (C) 2008 Trolltech ASA + Copyright (C) 2006, 2007 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 + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "config.h" +#include "PluginData.h" + +#include "PluginDatabase.h" +#include "PluginPackage.h" + +namespace WebCore { + +void PluginData::initPlugins() +{ + PluginDatabase *db = PluginDatabase::installedPlugins(); + const Vector<PluginPackage*> &plugins = db->plugins(); + + for (unsigned int i = 0; i < plugins.size(); ++i) { + PluginInfo* info = new PluginInfo; + PluginPackage* package = plugins[i]; + + info->name = package->name(); + info->file = package->fileName(); + info->desc = package->description(); + + const MIMEToDescriptionsMap& mimeToDescriptions = package->mimeToDescriptions(); + MIMEToDescriptionsMap::const_iterator end = mimeToDescriptions.end(); + for (MIMEToDescriptionsMap::const_iterator it = mimeToDescriptions.begin(); it != end; ++it) { + MimeClassInfo* mime = new MimeClassInfo; + info->mimes.append(mime); + + mime->type = it->first; + mime->desc = it->second; + mime->plugin = info; + + Vector<String> extensions = package->mimeToExtensions().get(mime->type); + + for (unsigned i = 0; i < extensions.size(); i++) { + if (i > 0) + mime->suffixes += ","; + + mime->suffixes += extensions[i]; + } + } + + m_plugins.append(info); + } +} + +void PluginData::refresh() +{ + PluginDatabase *db = PluginDatabase::installedPlugins(); + db->refresh(); +} + +}; diff --git a/WebCore/plugins/android/PluginPackageAndroid.cpp b/WebCore/plugins/android/PluginPackageAndroid.cpp new file mode 100644 index 0000000..aac687c --- /dev/null +++ b/WebCore/plugins/android/PluginPackageAndroid.cpp @@ -0,0 +1,582 @@ +/* + * Copyright 2009, The Android Open Source Project + * 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. + */ + +#ifdef ANDROID_PLUGINS + +#define LOG_TAG "WebKit" + +#include "config.h" +#include "PluginDatabase.h" +#include "PluginPackage.h" + +#include "Timer.h" +#include "PlatformString.h" +#include "PluginMainThreadScheduler.h" +#include "CString.h" +#include "jni_utility.h" +#include "npruntime_impl.h" +#include "npfunctions.h" +#include <dlfcn.h> +#include <errno.h> + +#include "PluginDebug.h" +#include "PluginDebugAndroid.h" + +namespace WebCore { + +// Simple class which calls dlclose() on a dynamic library when going +// out of scope. Call ok() if the handle should stay open. +class DynamicLibraryCloser +{ + public: + DynamicLibraryCloser(PlatformModule *module) : m_module(module) { } + ~DynamicLibraryCloser() + { + // Close the library if non-NULL reference and open. + if (m_module && *m_module) + { + dlclose(*m_module); + *m_module = 0; + } + } + void ok() { m_module = NULL; } + + private: + PlatformModule *m_module; +}; + +// A container for a dummy npp instance. This is used to allow +// NPN_PluginThreadAsyncCall() to be used with NULL passed as the npp +// instance. This is substituted instead, and is shared between all +// plugins which behave in this way. This will be lazily created in +// the first call to NPN_PluginThreadAsyncCall(). +class DummyNpp { + public: + DummyNpp() { + m_npp = new NPP_t(); + m_npp->pdata = NULL; + m_npp->ndata = NULL; + PluginMainThreadScheduler::scheduler().registerPlugin(m_npp); + } + ~DummyNpp() { + PluginMainThreadScheduler::scheduler().unregisterPlugin(m_npp); + delete m_npp; + } + NPP_t *getInstance() { return m_npp; } + + private: + NPP_t *m_npp; +}; + +static bool getEntryPoint(PlatformModule module, + const char *name, + void **entry_point) +{ + dlerror(); + *entry_point = dlsym(module, name); + const char *error = dlerror(); + if(error == NULL && *entry_point != NULL) { + return true; + } else { + PLUGIN_LOG("Couldn't get entry point \"%s\": %s\n", + name, error); + return false; + } +} + +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 (m_moduleVersion != compareVersion) + return m_moduleVersion > compareVersion ? 1 : -1; + else + return 0; +} + +bool PluginPackage::isPluginBlacklisted() +{ + // No blacklisted Android plugins... yet! + return false; +} + +void PluginPackage::determineQuirks(const String& mimeType) +{ + // The Gears implementation relies on it being loaded *all the time*, + // so check to see if this package represents the Gears plugin and + // load it. + if (mimeType == "application/x-googlegears") { + m_quirks.add(PluginQuirkDontUnloadPlugin); + } +} + +static void Android_NPN_PluginThreadAsyncCall(NPP instance, + void (*func) (void *), + void *userData) +{ + // Translate all instance == NULL to a dummy actual npp. + static DummyNpp dummyNpp; + if (instance == NULL) { + instance = dummyNpp.getInstance(); + } + // Call through to the wrapped function. + NPN_PluginThreadAsyncCall(instance, func, userData); +} + +static void initializeBrowserFuncs(NPNetscapeFuncs *funcs) +{ + // Initialize the NPN function pointers that we hand over to the + // plugin. + memset(funcs, 0, sizeof(*funcs)); + + funcs->size = sizeof(*funcs); + funcs->version = NP_VERSION_MINOR; + funcs->geturl = NPN_GetURL; + funcs->posturl = NPN_PostURL; + funcs->requestread = NPN_RequestRead; + funcs->newstream = NPN_NewStream; + funcs->write = NPN_Write; + funcs->destroystream = NPN_DestroyStream; + funcs->status = NPN_Status; + funcs->uagent = NPN_UserAgent; + funcs->memalloc = NPN_MemAlloc; + funcs->memfree = NPN_MemFree; + funcs->memflush = NPN_MemFlush; + funcs->reloadplugins = NPN_ReloadPlugins; + funcs->geturlnotify = NPN_GetURLNotify; + funcs->posturlnotify = NPN_PostURLNotify; + funcs->getvalue = NPN_GetValue; + funcs->setvalue = NPN_SetValue; + funcs->invalidaterect = NPN_InvalidateRect; + funcs->invalidateregion = NPN_InvalidateRegion; + funcs->forceredraw = NPN_ForceRedraw; + funcs->getJavaEnv = NPN_GetJavaEnv; + funcs->getJavaPeer = NPN_GetJavaPeer; + funcs->pushpopupsenabledstate = NPN_PushPopupsEnabledState; + funcs->poppopupsenabledstate = NPN_PopPopupsEnabledState; + funcs->pluginthreadasynccall = Android_NPN_PluginThreadAsyncCall; + funcs->scheduletimer = NPN_ScheduleTimer; + funcs->unscheduletimer = NPN_UnscheduleTimer; + + funcs->releasevariantvalue = _NPN_ReleaseVariantValue; + funcs->getstringidentifier = _NPN_GetStringIdentifier; + funcs->getstringidentifiers = _NPN_GetStringIdentifiers; + funcs->getintidentifier = _NPN_GetIntIdentifier; + funcs->identifierisstring = _NPN_IdentifierIsString; + funcs->utf8fromidentifier = _NPN_UTF8FromIdentifier; + funcs->intfromidentifier = _NPN_IntFromIdentifier; + funcs->createobject = _NPN_CreateObject; + funcs->retainobject = _NPN_RetainObject; + funcs->releaseobject = _NPN_ReleaseObject; + funcs->invoke = _NPN_Invoke; + funcs->invokeDefault = _NPN_InvokeDefault; + funcs->evaluate = _NPN_Evaluate; + funcs->getproperty = _NPN_GetProperty; + funcs->setproperty = _NPN_SetProperty; + funcs->removeproperty = _NPN_RemoveProperty; + funcs->hasproperty = _NPN_HasProperty; + funcs->hasmethod = _NPN_HasMethod; + funcs->setexception = _NPN_SetException; + funcs->enumerate = _NPN_Enumerate; +} + +static jobject createPluginObject(const char *name, + const char *path, + const char *fileName, + const char *description) +{ + JNIEnv *env = JSC::Bindings::getJNIEnv(); + // Create a Java "class Plugin" object instance + jclass pluginClass = env->FindClass("android/webkit/Plugin"); + if(!pluginClass) { + PLUGIN_LOG("Couldn't find class android.webkit.Plugin\n"); + return 0; + } + // Get Plugin(String, String, String, String, Context) + jmethodID pluginConstructor = env->GetMethodID( + pluginClass, + "<init>", + "(Ljava/lang/String;" + "Ljava/lang/String;" + "Ljava/lang/String;" + "Ljava/lang/String;)V"); + if(!pluginConstructor) { + PLUGIN_LOG("Couldn't get android.webkit.Plugin constructor\n"); + return 0; + } + // Make Java strings of name, path, fileName, description + jstring javaName = env->NewStringUTF(name); + jstring javaPath = env->NewStringUTF(path); + jstring javaFileName = env->NewStringUTF(fileName); + jstring javaDescription = env->NewStringUTF(description); + // Make a plugin instance + jobject pluginObject = env->NewObject(pluginClass, + pluginConstructor, + javaName, + javaPath, + javaFileName, + javaDescription); + return pluginObject; +} + +static jobject getPluginListObject() +{ + JNIEnv *env = JSC::Bindings::getJNIEnv(); + // Get WebView.getPluginList() + jclass webViewClass = env->FindClass("android/webkit/WebView"); + if(!webViewClass) { + PLUGIN_LOG("Couldn't find class android.webkit.WebView\n"); + return 0; + } + jmethodID getPluginList = env->GetStaticMethodID( + webViewClass, + "getPluginList", + "()Landroid/webkit/PluginList;"); + if(!getPluginList) { + PLUGIN_LOG("Couldn't find android.webkit.WebView.getPluginList()\n"); + return 0; + } + // Get the PluginList instance + jobject pluginListObject = env->CallStaticObjectMethod(webViewClass, + getPluginList); + if(!pluginListObject) { + PLUGIN_LOG("Couldn't get PluginList object\n"); + return 0; + } + return pluginListObject; +} + +static bool addPluginObjectToList(jobject pluginList, jobject plugin) +{ + // Add the Plugin object + JNIEnv *env = JSC::Bindings::getJNIEnv(); + jclass pluginListClass = env->FindClass("android/webkit/PluginList"); + if(!pluginListClass) { + PLUGIN_LOG("Couldn't find class android.webkit.PluginList\n"); + return false; + } + jmethodID addPlugin = env->GetMethodID( + pluginListClass, + "addPlugin", + "(Landroid/webkit/Plugin;)V"); + if(!addPlugin) { + PLUGIN_LOG("Couldn't find android.webkit.PluginList.addPlugin()\n"); + return false; + } + env->CallVoidMethod(pluginList, addPlugin, plugin); + return true; +} + +static void removePluginObjectFromList(jobject pluginList, jobject plugin) +{ + // Remove the Plugin object + JNIEnv *env = JSC::Bindings::getJNIEnv(); + jclass pluginListClass = env->FindClass("android/webkit/PluginList"); + if(!pluginListClass) { + PLUGIN_LOG("Couldn't find class android.webkit.PluginList\n"); + return; + } + jmethodID removePlugin = env->GetMethodID( + pluginListClass, + "removePlugin", + "(Landroid/webkit/Plugin;)V"); + if(!removePlugin) { + PLUGIN_LOG("Couldn't find android.webkit.PluginList.removePlugin()\n"); + return; + } + env->CallVoidMethod(pluginList, removePlugin, plugin); +} + +bool PluginPackage::load() +{ + PLUGIN_LOG("tid:%d isActive:%d isLoaded:%d loadCount:%d\n", + gettid(), + m_freeLibraryTimer.isActive(), + m_isLoaded, + m_loadCount); + if (m_freeLibraryTimer.isActive()) { + ASSERT(m_module); + m_freeLibraryTimer.stop(); + } else if (m_isLoaded) { + if (m_quirks.contains(PluginQuirkDontAllowMultipleInstances)) + return false; + m_loadCount++; + PLUGIN_LOG("Already loaded, count now %d\n", m_loadCount); + return true; + } + ASSERT(m_loadCount == 0); + ASSERT(m_module == NULL); + + PLUGIN_LOG("Loading \"%s\"\n", m_path.utf8().data()); + + // Open the library + void *handle = dlopen(m_path.utf8().data(), RTLD_NOW); + if(!handle) { + PLUGIN_LOG("Couldn't load plugin library \"%s\": %s\n", + m_path.utf8().data(), dlerror()); + return false; + } + m_module = handle; + PLUGIN_LOG("Fetch Info Loaded %p\n", m_module); + // This object will call dlclose() and set m_module to NULL + // when going out of scope. + DynamicLibraryCloser dlCloser(&m_module); + + + NP_InitializeFuncPtr NP_Initialize; + if(!getEntryPoint(m_module, "NP_Initialize", (void **) &NP_Initialize) || + !getEntryPoint(handle, "NP_Shutdown", (void **) &m_NPP_Shutdown)) { + PLUGIN_LOG("Couldn't find Initialize function\n"); + return false; + } + + // Provide the plugin with our browser function table and grab its + // plugin table. Provide the Java environment and the Plugin which + // can be used to override the defaults if the plugin wants. + initializeBrowserFuncs(&m_browserFuncs); + memset(&m_pluginFuncs, 0, sizeof(m_pluginFuncs)); + m_pluginFuncs.size = sizeof(m_pluginFuncs); + if(NP_Initialize(&m_browserFuncs, + &m_pluginFuncs, + JSC::Bindings::getJNIEnv(), + m_pluginObject) != NPERR_NO_ERROR) { + PLUGIN_LOG("Couldn't initialize plugin\n"); + return false; + } + + // Don't close the library - loaded OK. + dlCloser.ok(); + // Retain the handle so we can close it in the future. + m_module = handle; + m_isLoaded = true; + ++m_loadCount; + PLUGIN_LOG("Initial load ok, count now %d\n", m_loadCount); + return true; +} + +void PluginPackage::unregisterPluginObject() +{ + PLUGIN_LOG("unregisterPluginObject\n"); + // Called by unloadWithoutShutdown(). Remove the plugin from the + // PluginList + if(m_pluginObject) { + jobject pluginListObject = getPluginListObject(); + if(pluginListObject) { + removePluginObjectFromList(pluginListObject, m_pluginObject); + } + // Remove a reference to the Plugin object so it can + // garbage collect. + JSC::Bindings::getJNIEnv()->DeleteGlobalRef(m_pluginObject); + m_pluginObject = 0; + } +} + +bool PluginPackage::fetchInfo() +{ + PLUGIN_LOG("Fetch Info Loading \"%s\"\n", m_path.utf8().data()); + + // Open the library + void *handle = dlopen(m_path.utf8().data(), RTLD_NOW); + if(!handle) { + PLUGIN_LOG("Couldn't load plugin library \"%s\": %s\n", + m_path.utf8().data(), dlerror()); + return false; + } + PLUGIN_LOG("Fetch Info Loaded %p\n", handle); + + // This object will call dlclose() and set m_module to NULL + // when going out of scope. + DynamicLibraryCloser dlCloser(&handle); + + // Get the three entry points we need for Linux Netscape Plug-ins + NP_GetMIMEDescriptionFuncPtr NP_GetMIMEDescription; + NPP_GetValueProcPtr NP_GetValue; + if(!getEntryPoint(handle, "NP_GetMIMEDescription", + (void **) &NP_GetMIMEDescription) || + !getEntryPoint(handle, "NP_GetValue", (void **) &NP_GetValue)) { + // If any of those failed to resolve, fail the entire load + return false; + } + + // Get the plugin name and description using NP_GetValue + const char *name; + const char *description; + if(NP_GetValue(NULL, NPPVpluginNameString, &name) != NPERR_NO_ERROR || + NP_GetValue(NULL, NPPVpluginDescriptionString, &description) != + NPERR_NO_ERROR) { + PLUGIN_LOG("Couldn't get name/description using NP_GetValue\n"); + return false; + } + + PLUGIN_LOG("Plugin name: \"%s\"\n", name); + PLUGIN_LOG("Plugin description: \"%s\"\n", description); + m_name = name; + m_description = description; + + // fileName is just the trailing part of the path + int last_slash = m_path.reverseFind('/'); + if(last_slash < 0) + m_fileName = m_path; + else + m_fileName = m_path.substring(last_slash + 1); + + // Grab the MIME description. This is in the format, e.g: + // application/x-somescriptformat:ssf:Some Script Format + String mimeDescription(NP_GetMIMEDescription()); + PLUGIN_LOG("MIME description: \"%s\"\n", mimeDescription.utf8().data()); + // Clear out the current mappings. + m_mimeToDescriptions.clear(); + m_mimeToExtensions.clear(); + // Split the description into its component entries, separated by + // semicolons. + Vector<String> mimeEntries; + mimeDescription.split(';', true, mimeEntries); + // Iterate through the entries, adding them to the MIME mappings. + for(Vector<String>::const_iterator it = mimeEntries.begin(); + it != mimeEntries.end(); ++it) { + // Each part is split into 3 fields separated by colons + // Field 1 is the MIME type (e.g "application/x-shockwave-flash"). + // Field 2 is a comma separated list of file extensions. + // Field 3 is a human readable short description. + const String &mimeEntry = *it; + Vector<String> fields; + mimeEntry.split(':', true, fields); + if(fields.size() != 3) { + PLUGIN_LOG("Bad MIME entry \"%s\"\n", mimeEntry.utf8().data()); + return false; + } + + const String& mimeType = fields[0]; + Vector<String> extensions; + fields[1].split(',', true, extensions); + const String& description = fields[2]; + + determineQuirks(mimeType); + + PLUGIN_LOG("mime_type: \"%s\"\n", mimeType.utf8().data()); + PLUGIN_LOG("extensions: \"%s\"\n", fields[1].utf8().data()); + PLUGIN_LOG("description: \"%s\"\n", description.utf8().data()); + + // Map the mime type to the vector of extensions and the description + if(!extensions.isEmpty()) + m_mimeToExtensions.set(mimeType, extensions); + if(!description.isEmpty()) + m_mimeToDescriptions.set(mimeType, description); + } + + // Create a new Java Plugin object, this object is an instance of + // android.os.WebView.Plugin + CString path = m_path.utf8(); + CString filename = m_fileName.utf8(); + jobject pluginObject = createPluginObject(name, + path.data(), + filename.data(), + description); + if(!pluginObject) { + PLUGIN_LOG("Couldn't create Java Plugin\n"); + return false; + } + + // Add the Plugin to the PluginList. This list is used to show the + // user the list of plugins installed in the webkit. + + // The list of plugins are also available from the global static + // function PluginDatabase::installedPlugins(). However, the method + // on WebView to get the plugin list is a static method, and runs in the + // UI thread. We can not easily drop all the GlobalRefs this implementation + // has and switch to just calling through JNI to aforementioned API as + // WebKit runs in another thread and the WebView call would need to change + // to being async. + jobject pluginListObject = getPluginListObject(); + if(!pluginListObject) { + PLUGIN_LOG("Couldn't get PluginList object\n"); + return false; + } + if(!addPluginObjectToList(pluginListObject, pluginObject)) { + PLUGIN_LOG("Couldn't add Plugin to PluginList\n"); + m_NPP_Shutdown(); + return false; + } + + // Retain the Java Plugin object + m_pluginObject = JSC::Bindings::getJNIEnv()->NewGlobalRef(pluginObject); + + PLUGIN_LOG("Fetch Info Loaded plugin details ok \"%s\"\n", + m_path.utf8().data()); + + // If this plugin needs to be kept in memory, unload the module now + // and load it permanently. + if (m_quirks.contains(PluginQuirkDontUnloadPlugin)) { + dlCloser.ok(); + dlclose(handle); + load(); + } + + // dlCloser will unload the plugin if required. + return true; +} + +unsigned PluginPackage::hash() const +{ + const unsigned hashCodes[] = { + m_name.impl()->hash(), + m_description.impl()->hash(), + m_mimeToExtensions.size(), + }; + + return StringImpl::computeHash(reinterpret_cast<const UChar*>(hashCodes), + sizeof(hashCodes) / sizeof(UChar)); +} + +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; +} + +} // namespace WebCore + +#endif diff --git a/WebCore/plugins/android/PluginViewAndroid.cpp b/WebCore/plugins/android/PluginViewAndroid.cpp new file mode 100644 index 0000000..19416c9 --- /dev/null +++ b/WebCore/plugins/android/PluginViewAndroid.cpp @@ -0,0 +1,572 @@ +/* + * Copyright 2009, The Android Open Source Project + * 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. + */ +#define LOG_TAG "WebCore" + +#include "config.h" +#include "PluginView.h" + +#include "Document.h" +#include "Element.h" +#include "EventNames.h" +#include "FrameLoader.h" +#include "FrameLoadRequest.h" +#include "FrameTree.h" +#include "Frame.h" +#include "FrameView.h" +#include "GraphicsContext.h" +#include "HTMLNames.h" +#include "HTMLPlugInElement.h" +#include "Image.h" +#include "KeyboardEvent.h" +#include "MIMETypeRegistry.h" +#include "MouseEvent.h" +#include "NotImplemented.h" +#include "Page.h" +#include "PlatformGraphicsContext.h" +#include "PlatformKeyboardEvent.h" +#include "PluginMainThreadScheduler.h" +#include "PluginPackage.h" +// #include "kjs_binding.h" +// #include "kjs_proxy.h" +#include "android_graphics.h" +#include "SkCanvas.h" +#include "npruntime_impl.h" +#include "runtime_root.h" +#include "utils/SystemClock.h" +#include "ScriptController.h" +#include "Settings.h" +#include <runtime/JSLock.h> +// #include <kjs/value.h> +#include <wtf/ASCIICType.h> +#include "runtime.h" +#include "WebViewCore.h" + +#include "PluginDebug.h" +#include "PluginDebugAndroid.h" +#include "PluginViewBridgeAndroid.h" +#include "PluginWidgetAndroid.h" + +#include "android_npapi.h" +#include "SkANP.h" +#include "SkFlipPixelRef.h" + +/////////////////////////////////////////////////////////////////////////////// + +extern void ANPAudioTrackInterfaceV0_Init(ANPInterface* value); +extern void ANPCanvasInterfaceV0_Init(ANPInterface* value); +extern void ANPLogInterfaceV0_Init(ANPInterface* value); +extern void ANPMatrixInterfaceV0_Init(ANPInterface* value); +extern void ANPOffscreenInterfaceV0_Init(ANPInterface* value); +extern void ANPPaintInterfaceV0_Init(ANPInterface* value); +extern void ANPTypefaceInterfaceV0_Init(ANPInterface* value); +extern void ANPWindowInterfaceV0_Init(ANPInterface* value); + +struct VarProcPair { + int enumValue; + size_t size; + void (*proc)(ANPInterface*); +}; + +#define VARPROCLINE(name) \ + k##name##_ANPGetValue, sizeof(ANP##name), ANP##name##_Init + +static const VarProcPair gVarProcs[] = { + { VARPROCLINE(AudioTrackInterfaceV0) }, + { VARPROCLINE(LogInterfaceV0) }, + { VARPROCLINE(CanvasInterfaceV0) }, + { VARPROCLINE(MatrixInterfaceV0) }, + { VARPROCLINE(PaintInterfaceV0) }, + { VARPROCLINE(TypefaceInterfaceV0) }, + { VARPROCLINE(WindowInterfaceV0) }, +}; + +/* return true if var was an interface request (error will be set accordingly) + return false if var is not a recognized interface (and ignore error param) + */ +static bool anp_getInterface(NPNVariable var, void* value, NPError* error) { + const VarProcPair* iter = gVarProcs; + const VarProcPair* stop = gVarProcs + SK_ARRAY_COUNT(gVarProcs); + while (iter < stop) { + if (iter->enumValue == var) { + ANPInterface* i = reinterpret_cast<ANPInterface*>(value); + if (i->inSize < iter->size) { + SkDebugf("------- interface %d, expected size %d, allocated %d\n", + var, iter->size, i->inSize); + *error = NPERR_INCOMPATIBLE_VERSION_ERROR; + } else { + iter->proc(i); + *error = NPERR_NO_ERROR; + } + return true; + } + iter += 1; + } + SkDebugf("------ unknown NPNVariable %d\n", var); + return false; +} + +/////////////////////////////////////////////////////////////////////////////// + +using JSC::ExecState; +using JSC::Interpreter; +using JSC::JSLock; +using JSC::JSObject; +using JSC::JSValue; +using JSC::UString; + +using std::min; + +using namespace WTF; + +namespace WebCore { + +using namespace HTMLNames; + +void PluginView::platformInit() +{ + setPlatformWidget(new PluginViewBridgeAndroid()); + + m_isWindowed = false; // we don't support windowed yet + + m_window = new PluginWidgetAndroid(this); + + m_npWindow.type = NPWindowTypeDrawable; + m_npWindow.window = 0; +} + +PluginView::~PluginView() +{ + stop(); + + deleteAllValues(m_requests); + + freeStringArray(m_paramNames, m_paramCount); + freeStringArray(m_paramValues, m_paramCount); + + m_parentFrame->script()->cleanupScriptObjectsForPlugin(this); + +// Since we have no legacy plugins to check, we ignore the quirks check +// if (m_plugin && !m_plugin->quirks().contains(PluginQuirkDontUnloadPlugin)) + if (m_plugin) { + m_plugin->unload(); + } + delete m_window; +} + +void PluginView::init() +{ + if (m_haveInitialized) + return; + m_haveInitialized = true; + + android::WebViewCore* c = android::WebViewCore::getWebViewCore(this->parent()); + m_window->init(c); + + if (!m_plugin) { + ASSERT(m_status == PluginStatusCanNotFindPlugin); + return; + } + + if (!m_plugin->load()) { + m_plugin = 0; + m_status = PluginStatusCanNotLoadPlugin; + return; + } + + if (!start()) { + m_status = PluginStatusCanNotLoadPlugin; + return; + } + + m_status = PluginStatusLoadedSuccessfully; +} + +void PluginView::handleMouseEvent(MouseEvent* event) +{ + const AtomicString& type = event->type(); + bool isDown = (eventNames().mousedownEvent == type); + bool isUp = (eventNames().mouseupEvent == type); + if (!isDown && !isUp) { + return; + } + + ANPEvent evt; + SkANP::InitEvent(&evt, kTouch_ANPEventType); + + evt.data.touch.action = isDown ? kDown_ANPTouchAction : kUp_ANPTouchAction; + evt.data.touch.modifiers = 0; // todo + // these are relative to plugin + evt.data.touch.x = event->pageX() - m_npWindow.x; + evt.data.touch.y = event->pageY() - m_npWindow.y; + if (m_plugin->pluginFuncs()->event(m_instance, &evt)) { + event->setDefaultHandled(); + } +} + +static ANPKeyModifier make_modifiers(bool shift, bool alt) { + ANPKeyModifier mod = 0; + if (shift) { + mod |= kShift_ANPKeyModifier; + } + if (alt) { + mod |= kAlt_ANPKeyModifier; + } + return mod; +} + +void PluginView::handleKeyboardEvent(KeyboardEvent* event) +{ + const PlatformKeyboardEvent* pke = event->keyEvent(); + if (NULL == pke) { + return; + } + + ANPEvent evt; + SkANP::InitEvent(&evt, kKey_ANPEventType); + + switch (pke->type()) { + case PlatformKeyboardEvent::KeyDown: +#ifdef TRACE_KEY_EVENTS + SkDebugf("--------- KeyDown, ignore\n"); +#endif + return; + case PlatformKeyboardEvent::RawKeyDown: + evt.data.key.action = kDown_ANPKeyAction; + break; + case PlatformKeyboardEvent::Char: +#ifdef TRACE_KEY_EVENTS + SkDebugf("--------- Char, ignore\n"); +#endif + return; + case PlatformKeyboardEvent::KeyUp: + evt.data.key.action = kUp_ANPKeyAction; + break; + default: +#ifdef TRACE_KEY_EVENTS + SkDebugf("------ unexpected keyevent type %d\n", pke->type()); +#endif + return; + } + evt.data.key.nativeCode = pke->nativeVirtualKeyCode(); + evt.data.key.virtualCode = pke->windowsVirtualKeyCode(); + evt.data.key.repeatCount = pke->repeatCount(); + evt.data.key.modifiers = make_modifiers(pke->shiftKey(), pke->altKey()); + evt.data.key.unichar = pke->unichar(); + + if (m_plugin->pluginFuncs()->event(m_instance, &evt)) { + event->setDefaultHandled(); + } +} + +NPError PluginView::handlePostReadFile(Vector<char>& buffer, uint32 len, const char* buf) +{ + notImplemented(); + return NPERR_GENERIC_ERROR; +} + +NPError PluginView::getValueStatic(NPNVariable variable, void* value) +{ + // our interface query is valid with no NPP instance + NPError error = NPERR_GENERIC_ERROR; + (void)anp_getInterface(variable, value, &error); + return error; +} + +void PluginView::setParent(ScrollView* parent) +{ + Widget::setParent(parent); + + if (parent) + init(); +} + +void PluginView::setNPWindowRect(const IntRect& rect) +{ + if (!m_isStarted) + return; + + const int width = rect.width(); + const int height = rect.height(); + + // the rect is relative to the frameview's (0,0), so use convertToContainingWindow + IntPoint p = parent()->convertToContainingWindow(rect.location()); + m_npWindow.x = p.x(); + m_npWindow.y = p.y(); + + m_npWindow.width = width; + m_npWindow.height = height; + + m_npWindow.clipRect.left = 0; + m_npWindow.clipRect.top = 0; + m_npWindow.clipRect.right = width; + m_npWindow.clipRect.bottom = height; + + if (m_plugin->pluginFuncs()->setwindow) { + JSC::JSLock::DropAllLocks dropAllLocks(false); + setCallingPlugin(true); + m_plugin->pluginFuncs()->setwindow(m_instance, &m_npWindow); + setCallingPlugin(false); + } + + m_window->setWindow(m_npWindow.x, m_npWindow.y, width, height, + m_isTransparent); +} + +void PluginView::stop() +{ + if (!m_isStarted) + return; + + 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(false); + + PluginMainThreadScheduler::scheduler().unregisterPlugin(m_instance); + + // Destroy the plugin + NPSavedData* savedData = 0; + setCallingPlugin(true); + NPError npErr = m_plugin->pluginFuncs()->destroy(m_instance, &savedData); + setCallingPlugin(false); + LOG_NPERROR(npErr); + + if (savedData) { + if (savedData->buf) + NPN_MemFree(savedData->buf); + NPN_MemFree(savedData); + } + + m_instance->pdata = 0; +} + +const char* PluginView::userAgentStatic() +{ + return 0; +} + +const char* PluginView::userAgent() +{ + if (m_userAgent.isNull()) + m_userAgent = m_parentFrame->loader()->userAgent(m_url).utf8(); + return m_userAgent.data(); +} + +NPError PluginView::getValue(NPNVariable variable, void* value) +{ + switch (variable) { + case NPNVWindowNPObject: { + 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: { + NPObject* pluginScriptObject = 0; + + if (m_element->hasTagName(appletTag) || + m_element->hasTagName(embedTag) || + m_element->hasTagName(objectTag)) { + HTMLPlugInElement* pluginElement = + static_cast<HTMLPlugInElement*>(m_element); + pluginScriptObject = pluginElement->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 NPNVnetscapeWindow: { + // Return the top level WebView Java object associated + // with this instance. + jobject *retObject = static_cast<jobject*>(value); + *retObject = android::WebViewCore::getWebViewCore(parent())->getWebViewJavaObject(); + return NPERR_NO_ERROR; + } + + case kSupportedDrawingModel_ANPGetValue: { + uint32_t* bits = reinterpret_cast<uint32_t*>(value); + *bits = (1 << kBitmap_ANPDrawingModel); + return NPERR_NO_ERROR; + } + + default: { + NPError error = NPERR_GENERIC_ERROR; + (void)anp_getInterface(variable, value, &error); + return error; + } + } +} + +NPError PluginView::platformSetValue(NPPVariable variable, void* value) +{ + NPError error = NPERR_GENERIC_ERROR; + + switch (variable) { + case kRequestDrawingModel_ANPSetValue: { + ANPDrawingModel model = reinterpret_cast<ANPDrawingModel>(value); + switch (model) { + case kBitmap_ANPDrawingModel: + m_window->setDrawingModel(model); + error = NPERR_NO_ERROR; + break; + default: + break; + } + } + default: + break; + } + return error; +} + +void PluginView::invalidateRect(const IntRect& r) +{ + m_window->inval(r, true); +} + +void PluginView::invalidateRect(NPRect* rect) +{ + IntRect r; + + if (rect) { + r = IntRect(rect->left, rect->top, + rect->right - rect->left, rect->bottom - rect->top); + } else { + r = IntRect(0, 0, m_npWindow.width, m_npWindow.height); + } + + m_window->inval(r, true); +// android::WebViewCore::getWebViewCore(parent())->contentInvalidate(r); +} + +void PluginView::invalidateRegion(NPRegion region) +{ + // we don't support/define regions (yet), so do nothing +} + +void PluginView::forceRedraw() +{ + this->invalidateRect(0); +} + +void PluginView::setFocus() +{ + Widget::setFocus(); +// SkDebugf("------------- setFocus %p\n", this); +} + +void PluginView::show() +{ + setSelfVisible(true); + Widget::show(); +} + +void PluginView::hide() +{ + setSelfVisible(false); + Widget::hide(); +} + +void PluginView::paintMissingPluginIcon(GraphicsContext* context, + const IntRect& rect) +{ + static RefPtr<Image> gNullPluginImage; + if (!gNullPluginImage) { + gNullPluginImage = Image::loadPlatformResource("nullplugin"); + } + Image* image = gNullPluginImage.get(); + + IntRect imageRect(frameRect().x(), frameRect().y(), + image->width(), image->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->drawImage(image, imageRect.location()); +} + +void PluginView::paint(GraphicsContext* context, const IntRect& rect) +{ + if (!m_isStarted) { + // Draw the "missing plugin" image + paintMissingPluginIcon(context, rect); + return; + } + + IntRect frame = frameRect(); + if (!frame.width() || !frame.height()) { + return; + } + + m_window->inval(rect, false); + m_window->draw(android_gc2canvas(context)); +} + +// new as of SVN 38068, Nov 5 2008 +void PluginView::updatePluginWidget() const +{ + notImplemented(); +} + +// new as of SVN 38068, Nov 5 2008 +void PluginView::setParentVisible(bool) { + notImplemented(); +} + +} // namespace WebCore + diff --git a/WebCore/plugins/gtk/PluginDataGtk.cpp b/WebCore/plugins/gtk/PluginDataGtk.cpp new file mode 100644 index 0000000..0d477cd --- /dev/null +++ b/WebCore/plugins/gtk/PluginDataGtk.cpp @@ -0,0 +1,73 @@ +/* + Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + Copyright (C) 2006, 2007 Apple Inc. All rights reserved. + Copyright (C) 2008 Collabora Ltd. 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 + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "config.h" +#include "PluginData.h" + +#include "PluginDatabase.h" +#include "PluginPackage.h" +#include <stdio.h> +namespace WebCore { + +void PluginData::initPlugins() +{ + PluginDatabase *db = PluginDatabase::installedPlugins(); + const Vector<PluginPackage*> &plugins = db->plugins(); + + for (unsigned int i = 0; i < plugins.size(); ++i) { + PluginInfo* info = new PluginInfo; + PluginPackage* package = plugins[i]; + + info->name = package->name(); + info->file = package->fileName(); + info->desc = package->description(); + + const MIMEToDescriptionsMap& mimeToDescriptions = package->mimeToDescriptions(); + MIMEToDescriptionsMap::const_iterator end = mimeToDescriptions.end(); + for (MIMEToDescriptionsMap::const_iterator it = mimeToDescriptions.begin(); it != end; ++it) { + MimeClassInfo* mime = new MimeClassInfo; + info->mimes.append(mime); + + mime->type = it->first; + mime->desc = it->second; + mime->plugin = info; + + Vector<String> extensions = package->mimeToExtensions().get(mime->type); + + for (unsigned i = 0; i < extensions.size(); i++) { + if (i > 0) + mime->suffixes += ","; + + mime->suffixes += extensions[i]; + } + } + + m_plugins.append(info); + } +} + +void PluginData::refresh() +{ + PluginDatabase *db = PluginDatabase::installedPlugins(); + db->refresh(); +} + +}; diff --git a/WebCore/plugins/gtk/PluginPackageGtk.cpp b/WebCore/plugins/gtk/PluginPackageGtk.cpp new file mode 100644 index 0000000..5a097b2 --- /dev/null +++ b/WebCore/plugins/gtk/PluginPackageGtk.cpp @@ -0,0 +1,284 @@ +/* + * 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 "CString.h" +#include "MIMETypeRegistry.h" +#include "NotImplemented.h" +#include "npruntime_impl.h" +#include "PluginDebug.h" + +namespace WebCore { + +static PlatformModuleVersion getModuleVersion(const char *description) +{ + // 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 + + PlatformModuleVersion version = 0; + + if (!description) + return 0; + + if (g_str_has_prefix(description, "Shockwave Flash ") && strlen(description) >= 19) { + // The flash version as a PlatformModuleVersion differs in GTK 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 in GTK, Flash's version may be + // 0x0a000000 instead of 0x000a0000. This avoids having to modify + // PlatformModuleVersion in the GTK port + + char **version_parts = g_strsplit(description + 16, " ", -1); + if (!version_parts) + return 0; + + int parts_length = g_strv_length(version_parts); + + if (parts_length >= 1) { + guint16 major = 0, minor = 0; + if (sscanf(version_parts[0], "%" G_GUINT16_FORMAT ".%" G_GUINT16_FORMAT, &major, &minor) == 2) + version = ((guint8)major << 24) | ((guint8)minor << 16); + } + + if (parts_length >= 2) { + char *rev_str = version_parts[1]; + if (strlen(rev_str) > 1 && (rev_str[0] == 'r' || rev_str[0] == 'b')) + version |= (guint16)atoi(rev_str + 1); + } + + g_strfreev(version_parts); + } + + return version; +} + +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); + } + + m_quirks.add(PluginQuirkThrottleInvalidate); + m_quirks.add(PluginQuirkThrottleWMUserPlusOneMessages); + m_quirks.add(PluginQuirkFlashURLNotifyBug); + } +} + +bool PluginPackage::fetchInfo() +{ +#if defined(XP_UNIX) + if (!load()) + return false; + + NP_GetMIMEDescriptionFuncPtr NP_GetMIMEDescription; + NPP_GetValueProcPtr NPP_GetValue; + + g_module_symbol(m_module, "NP_GetMIMEDescription", (void**)&NP_GetMIMEDescription); + g_module_symbol(m_module, "NP_GetValue", (void**)&NPP_GetValue); + + char* buffer = 0; + NPError err = NPP_GetValue(0, NPPVpluginNameString, &buffer); + if (err == NPERR_NO_ERROR) + m_name = buffer; + + buffer = 0; + err = NPP_GetValue(0, NPPVpluginDescriptionString, &buffer); + if (err == NPERR_NO_ERROR) { + m_description = buffer; + m_moduleVersion = getModuleVersion(buffer); + } + + const gchar* types = NP_GetMIMEDescription(); + gchar** mimeDescs = g_strsplit(types, ";", -1); + for (int i = 0; mimeDescs[i] && mimeDescs[i][0]; i++) { + gchar** mimeData = g_strsplit(mimeDescs[i], ":", 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; +#else + notImplemented(); + return false; +#endif +} + +bool PluginPackage::load() +{ + if (m_isLoaded) { + m_loadCount++; + return true; + } + + m_module = g_module_open((m_path.utf8()).data(), G_MODULE_BIND_LOCAL); + + if (!m_module) { + LOG(Plugin,"Module Load Failed :%s, Error:%s\n", (m_path.utf8()).data(), g_module_error()); + return false; + } + + m_isLoaded = true; + + NP_InitializeFuncPtr NP_Initialize; + 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); + + m_browserFuncs.size = sizeof (m_browserFuncs); + m_browserFuncs.version = NP_VERSION_MINOR; + 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.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.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_HasMethod; + m_browserFuncs.hasmethod = _NPN_HasProperty; + m_browserFuncs.setexception = _NPN_SetException; + m_browserFuncs.enumerate = _NPN_Enumerate; + m_browserFuncs.construct = _NPN_Construct; + +#if defined(XP_UNIX) + npErr = NP_Initialize(&m_browserFuncs, &m_pluginFuncs); +#else + npErr = NP_Initialize(&m_browserFuncs); +#endif + if (npErr != NPERR_NO_ERROR) + goto abort; + + m_loadCount++; + return true; + +abort: + unloadWithoutShutdown(); + return false; +} + +unsigned PluginPackage::hash() const +{ + unsigned hashCodes[2] = { + m_path.impl()->hash(), + m_lastModified + }; + + return StringImpl::computeHash(reinterpret_cast<UChar*>(hashCodes), 2 * sizeof(unsigned) / sizeof(UChar)); +} + +bool PluginPackage::equal(const PluginPackage& a, const PluginPackage& b) +{ + return a.m_description == b.m_description; +} + +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 (m_moduleVersion != compareVersion) + return m_moduleVersion > compareVersion ? 1 : -1; + return 0; +} + +} diff --git a/WebCore/plugins/gtk/PluginViewGtk.cpp b/WebCore/plugins/gtk/PluginViewGtk.cpp new file mode 100644 index 0000000..904e935 --- /dev/null +++ b/WebCore/plugins/gtk/PluginViewGtk.cpp @@ -0,0 +1,586 @@ +/* + * 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 "PluginView.h" + +#include "Document.h" +#include "DocumentLoader.h" +#include "Element.h" +#include "FrameLoader.h" +#include "FrameLoadRequest.h" +#include "FrameTree.h" +#include "Frame.h" +#include "FrameView.h" +#include "GraphicsContext.h" +#include "Image.h" +#include "HTMLNames.h" +#include "HTMLPlugInElement.h" +#include "KeyboardEvent.h" +#include "MouseEvent.h" +#include "NotImplemented.h" +#include "Page.h" +#include "PlatformMouseEvent.h" +#include "PluginDebug.h" +#include "PluginPackage.h" +#include "RenderLayer.h" +#include "Settings.h" +#include "JSDOMBinding.h" +#include "ScriptController.h" +#include "npruntime_impl.h" +#include "runtime.h" +#include "runtime_root.h" +#include <runtime/JSLock.h> +#include <runtime/JSValue.h> + +#include <gdkconfig.h> +#include <gtk/gtk.h> + +#if PLATFORM(X11) +#include "gtk2xtbin.h" +#include <gdk/gdkx.h> +#endif +#ifdef GDK_WINDOWING_WIN32 +#include "PluginMessageThrottlerWin.h" +#include <gdk/gdkwin32.h> +#endif + +using JSC::ExecState; +using JSC::Interpreter; +using JSC::JSLock; +using JSC::JSObject; +using JSC::UString; + +using std::min; + +using namespace WTF; + +namespace WebCore { + +using namespace HTMLNames; + +void PluginView::updatePluginWidget() const +{ + if (!parent() || !m_isWindowed) + return; + + ASSERT(parent()->isFrameView()); + FrameView* frameView = static_cast<FrameView*>(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()); + + GtkAllocation allocation = { m_windowRect.x(), m_windowRect.y(), m_windowRect.width(), m_windowRect.height() }; + if (platformPluginWidget()) { + gtk_widget_size_allocate(platformPluginWidget(), &allocation); +#if PLATFORM(X11) + 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()); + } +#endif + } +} + +void PluginView::setFocus() +{ + if (platformPluginWidget()) + gtk_widget_grab_focus(platformPluginWidget()); + + Widget::setFocus(); +} + +void PluginView::show() +{ + setSelfVisible(true); + + if (isParentVisible() && platformPluginWidget()) + gtk_widget_show(platformPluginWidget()); + + Widget::show(); +} + +void PluginView::hide() +{ + setSelfVisible(false); + + if (isParentVisible() && platformPluginWidget()) + gtk_widget_hide(platformPluginWidget()); + + Widget::hide(); +} + +void PluginView::paint(GraphicsContext* context, const IntRect& rect) +{ + if (!m_isStarted) { + // Draw the "missing plugin" image + //paintMissingPluginIcon(context, rect); + return; + } + + if (m_isWindowed || context->paintingDisabled()) + return; + + NPEvent npEvent; + /* Need to synthesize Xevents here */ + + m_npWindow.type = NPWindowTypeDrawable; + + ASSERT(parent()->isFrameView()); + + if (m_plugin->pluginFuncs()->event) { + JSC::JSLock::DropAllLocks dropAllLocks(false); + m_plugin->pluginFuncs()->event(m_instance, &npEvent); + } + + setNPWindowRect(frameRect()); +} + +void PluginView::handleKeyboardEvent(KeyboardEvent* event) +{ + NPEvent npEvent; + + /* FIXME: Synthesize an XEvent to pass through */ + + JSC::JSLock::DropAllLocks dropAllLocks(false); + if (!m_plugin->pluginFuncs()->event(m_instance, &npEvent)) + event->setDefaultHandled(); +} + +void PluginView::handleMouseEvent(MouseEvent* event) +{ + NPEvent npEvent; + + if (!m_isWindowed) + return; + + /* FIXME: Synthesize an XEvent to pass through */ + IntPoint p = static_cast<FrameView*>(parent())->contentsToWindow(IntPoint(event->pageX(), event->pageY())); + + JSC::JSLock::DropAllLocks dropAllLocks(false); + if (!m_plugin->pluginFuncs()->event(m_instance, &npEvent)) + event->setDefaultHandled(); +} + +void PluginView::setParent(ScrollView* parent) +{ + Widget::setParent(parent); + + if (parent) + init(); + else { + if (!platformPluginWidget()) + return; + } +} + +void PluginView::setNPWindowRect(const IntRect& rect) +{ + if (!m_isStarted || !parent()) + return; + + IntPoint p = static_cast<FrameView*>(parent())->contentsToWindow(rect.location()); + m_npWindow.x = p.x(); + m_npWindow.y = p.y(); + + m_npWindow.width = rect.width(); + m_npWindow.height = rect.height(); + + m_npWindow.clipRect.left = 0; + m_npWindow.clipRect.top = 0; + m_npWindow.clipRect.right = rect.width(); + m_npWindow.clipRect.bottom = rect.height(); + + if (m_npWindow.x < 0 || m_npWindow.y < 0 || + m_npWindow.width <= 0 || m_npWindow.height <= 0) + return; + + if (m_plugin->pluginFuncs()->setwindow) { + PluginView::setCurrentPluginView(this); + JSC::JSLock::DropAllLocks dropAllLocks(false); + setCallingPlugin(true); + m_plugin->pluginFuncs()->setwindow(m_instance, &m_npWindow); + setCallingPlugin(false); + PluginView::setCurrentPluginView(0); + + if (!m_isWindowed) + return; + + ASSERT(platformPluginWidget()); + } +} + +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()); + } +} + +void PluginView::stop() +{ + if (!m_isStarted) + return; + + 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(false); + + // 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 + if (m_isWindowed && m_npWindow.ws_info) + delete (NPSetWindowCallbackStruct *)m_npWindow.ws_info; + m_npWindow.ws_info = 0; +#endif + + // Destroy the plugin + { + PluginView::setCurrentPluginView(this); + setCallingPlugin(true); + m_plugin->pluginFuncs()->destroy(m_instance, 0); + setCallingPlugin(false); + PluginView::setCurrentPluginView(0); + } + + m_instance->pdata = 0; +} + +static const char* MozillaUserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0"; + +const char* PluginView::userAgent() +{ + if (m_plugin->quirks().contains(PluginQuirkWantsMozillaUserAgent)) + return MozillaUserAgent; + + if (m_userAgent.isNull()) + m_userAgent = m_parentFrame->loader()->userAgent(m_url).utf8(); + + return m_userAgent.data(); +} + +const char* PluginView::userAgentStatic() +{ + //FIXME - Lie and say we are Mozilla + return MozillaUserAgent; +} + +NPError PluginView::handlePostReadFile(Vector<char>& buffer, uint32 len, const char* buf) +{ + String filename(buf, len); + + if (filename.startsWith("file:///")) + filename = filename.substring(8); + + // Get file info + if (!g_file_test ((filename.utf8()).data(), (GFileTest)(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR))) + return NPERR_FILE_NOT_FOUND; + + //FIXME - read the file data into buffer + FILE* fileHandle = fopen((filename.utf8()).data(), "r"); + + if (fileHandle == 0) + return NPERR_FILE_NOT_FOUND; + + //buffer.resize(); + + int bytesRead = fread(buffer.data(), 1, 0, fileHandle); + + fclose(fileHandle); + + if (bytesRead <= 0) + return NPERR_FILE_NOT_FOUND; + + return NPERR_NO_ERROR; +} + +NPError PluginView::getValueStatic(NPNVariable variable, void* value) +{ + switch (variable) { + case NPNVToolkit: +#if PLATFORM(GTK) + *((uint32 *)value) = 2; +#else + *((uint32 *)value) = 0; +#endif + return NPERR_NO_ERROR; + + case NPNVSupportsXEmbedBool: +#if PLATFORM(X11) + *((uint32 *)value) = true; +#else + *((uint32 *)value) = false; +#endif + return NPERR_NO_ERROR; + + case NPNVjavascriptEnabledBool: + *((uint32 *)value) = true; + return NPERR_NO_ERROR; + + default: + return NPERR_GENERIC_ERROR; + } +} + +NPError PluginView::getValue(NPNVariable variable, void* value) +{ + switch (variable) { + case NPNVxDisplay: +#if PLATFORM(X11) + if (m_needsXEmbed) + *(void **)value = (void *)GDK_DISPLAY(); + else + *(void **)value = (void *)GTK_XTBIN(platformPluginWidget())->xtclient.xtdisplay; + return NPERR_NO_ERROR; +#else + return NPERR_GENERIC_ERROR; +#endif + +#if PLATFORM(X11) + case NPNVxtAppContext: + if (!m_needsXEmbed) { + *(void **)value = XtDisplayToApplicationContext (GTK_XTBIN(platformPluginWidget())->xtclient.xtdisplay); + + return NPERR_NO_ERROR; + } else + return NPERR_GENERIC_ERROR; +#endif + +#if ENABLE(NETSCAPE_PLUGIN_API) + 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 = static_cast<HTMLPlugInElement*>(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; + } +#endif + + case NPNVnetscapeWindow: { +#if PLATFORM(X11) + void* w = reinterpret_cast<void*>(value); + *((XID *)w) = GDK_WINDOW_XWINDOW(m_parentFrame->view()->hostWindow()->platformWindow()->window); +#endif +#ifdef GDK_WINDOWING_WIN32 + HGDIOBJ* w = reinterpret_cast<HGDIOBJ*>(value); + *w = GDK_WINDOW_HWND(m_parentFrame->view()->hostWindow()->platformWindow()->window); +#endif + return NPERR_NO_ERROR; + } + + default: + return getValueStatic(variable, value); + } +} + +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); + invalidateRect(r); +} + +void PluginView::forceRedraw() +{ + if (m_isWindowed) + gtk_widget_queue_draw(platformPluginWidget()); + else + gtk_widget_queue_draw(m_parentFrame->view()->hostWindow()->platformWindow()); +} + +PluginView::~PluginView() +{ + stop(); + + deleteAllValues(m_requests); + + freeStringArray(m_paramNames, m_paramCount); + freeStringArray(m_paramValues, m_paramCount); + + m_parentFrame->script()->cleanupScriptObjectsForPlugin(this); + + if (m_plugin && !(m_plugin->quirks().contains(PluginQuirkDontUnloadPlugin))) + m_plugin->unload(); +} + +static gboolean +plug_removed_cb(GtkSocket *socket, gpointer) +{ + return TRUE; +} + +void PluginView::init() +{ + if (m_haveInitialized) + return; + m_haveInitialized = true; + + if (!m_plugin) { + ASSERT(m_status == PluginStatusCanNotFindPlugin); + return; + } + + if (!m_plugin->load()) { + m_plugin = 0; + m_status = PluginStatusCanNotLoadPlugin; + return; + } + + if (!start()) { + m_status = PluginStatusCanNotLoadPlugin; + return; + } + + if (m_plugin->pluginFuncs()->getvalue) { + PluginView::setCurrentPluginView(this); + JSC::JSLock::DropAllLocks dropAllLocks(false); + setCallingPlugin(true); + m_plugin->pluginFuncs()->getvalue(m_instance, NPPVpluginNeedsXEmbed, &m_needsXEmbed); + setCallingPlugin(false); + PluginView::setCurrentPluginView(0); + } + +#if PLATFORM(X11) + if (m_needsXEmbed) { + setPlatformWidget(gtk_socket_new()); + gtk_container_add(GTK_CONTAINER(m_parentFrame->view()->hostWindow()->platformWindow()), platformPluginWidget()); + g_signal_connect(platformPluginWidget(), "plug_removed", G_CALLBACK(plug_removed_cb), NULL); + } else if (m_isWindowed) + setPlatformWidget(gtk_xtbin_new(m_parentFrame->view()->hostWindow()->platformWindow()->window, 0)); +#else + setPlatformWidget(gtk_socket_new()); + gtk_container_add(GTK_CONTAINER(m_parentFrame->view()->hostWindow()->platformWindow()), platformPluginWidget()); +#endif + show(); + + if (m_isWindowed) { + m_npWindow.type = NPWindowTypeWindow; +#if PLATFORM(X11) + NPSetWindowCallbackStruct *ws = new NPSetWindowCallbackStruct(); + + ws->type = 0; + + if (m_needsXEmbed) { + gtk_widget_realize(platformPluginWidget()); + m_npWindow.window = (void*)gtk_socket_get_id(GTK_SOCKET(platformPluginWidget())); + ws->display = GDK_WINDOW_XDISPLAY(platformPluginWidget()->window); + ws->visual = GDK_VISUAL_XVISUAL(gdk_drawable_get_visual(GDK_DRAWABLE(platformPluginWidget()->window))); + ws->depth = gdk_drawable_get_visual(GDK_DRAWABLE(platformPluginWidget()->window))->depth; + ws->colormap = GDK_COLORMAP_XCOLORMAP(gdk_drawable_get_colormap(GDK_DRAWABLE(platformPluginWidget()->window))); + } else { + m_npWindow.window = (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); + + m_npWindow.ws_info = ws; +#elif defined(GDK_WINDOWING_WIN32) + m_npWindow.window = (void*)GDK_WINDOW_HWND(platformPluginWidget()->window); +#endif + } else { + m_npWindow.type = NPWindowTypeDrawable; + m_npWindow.window = 0; + } + + if (!(m_plugin->quirks().contains(PluginQuirkDeferFirstSetWindowCall))) + setNPWindowRect(frameRect()); + + m_status = PluginStatusLoadedSuccessfully; +} + +} // namespace WebCore diff --git a/WebCore/plugins/gtk/gtk2xtbin.c b/WebCore/plugins/gtk/gtk2xtbin.c new file mode 100644 index 0000000..4247345 --- /dev/null +++ b/WebCore/plugins/gtk/gtk2xtbin.c @@ -0,0 +1,946 @@ +/* -*- 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. + */ + +#undef GTK_DISABLE_DEPRECATED + +#include "xembed.h" +#include "gtk2xtbin.h" +#include <gtk/gtkmain.h> +#include <gtk/gtkprivate.h> +#include <gdk/gdkx.h> +#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_destroy (GtkObject *object); +static void gtk_xtbin_shutdown (GtkObject *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) +{ + XEvent event; + 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; +} + +static GSourceFuncs xt_event_funcs = { + xt_event_prepare, + xt_event_check, + xt_event_dispatch, + 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, + }; + 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; + GtkObjectClass *object_class; + + parent_class = gtk_type_class (GTK_TYPE_SOCKET); + + widget_class = GTK_WIDGET_CLASS (klass); + widget_class->realize = gtk_xtbin_realize; + widget_class->unrealize = gtk_xtbin_unrealize; + + object_class = GTK_OBJECT_CLASS (klass); + object_class->destroy = gtk_xtbin_destroy; +} + +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 }; + gint x, y, w, h, d; /* geometry of window */ + +#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 */ + gdk_window_get_geometry(xtbin->parent_window, &x, &y, &w, &h, &d); + allocation.width = w; + allocation.height = h; + gtk_widget_size_allocate (widget, &allocation); + +#ifdef DEBUG_XTBIN + printf("initial allocation %d %d %d %d\n", x, y, w, h); +#endif + + 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 (GdkWindow *parent_window, String * f) +{ + GtkXtBin *xtbin; + gpointer user_data; + + assert(parent_window != NULL); + xtbin = gtk_type_new (GTK_TYPE_XTBIN); + + if (!xtbin) + return (GtkWidget*)NULL; + + if (f) + fallback = f; + + /* Initialize the Xt toolkit */ + xtbin->parent_window = parent_window; + + xt_client_init(&(xtbin->xtclient), + GDK_VISUAL_XVISUAL(gdk_rgb_get_visual()), + GDK_COLORMAP_XCOLORMAP(gdk_rgb_get_colormap()), + gdk_rgb_get_visual()->depth); + + 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 = + gtk_timeout_add(25, + (GtkFunction)xt_event_polling_timer_callback, + xtdisplay); + } + + /* 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_REALIZED (xtbin)) + gdk_window_move (GTK_WIDGET (xtbin)->window, 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_UNSET_FLAGS (widget, GTK_VISIBLE); + if (GTK_WIDGET_REALIZED (widget)) { + xt_client_unrealize(&(xtbin->xtclient)); + } + + (*GTK_WIDGET_CLASS (parent_class)->unrealize)(widget); +} + +static void +gtk_xtbin_destroy (GtkObject *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); + + gtk_timeout_remove(xt_polling_timer_id); + xt_polling_timer_id = 0; + } + } + + GTK_OBJECT_CLASS(parent_class)->destroy(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; + int errorcode; + + 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) +{ + int errorcode; + + 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/WebCore/plugins/gtk/gtk2xtbin.h b/WebCore/plugins/gtk/gtk2xtbin.h new file mode 100644 index 0000000..2a2b92c --- /dev/null +++ b/WebCore/plugins/gtk/gtk2xtbin.h @@ -0,0 +1,158 @@ +/* -*- 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/gtksocket.h> +#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 (GdkWindow *parent_window, 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/WebCore/plugins/gtk/xembed.h b/WebCore/plugins/gtk/xembed.h new file mode 100644 index 0000000..dff7be9 --- /dev/null +++ b/WebCore/plugins/gtk/xembed.h @@ -0,0 +1,64 @@ +/* -*- 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/WebCore/plugins/mac/PluginDataMac.mm b/WebCore/plugins/mac/PluginDataMac.mm new file mode 100644 index 0000000..ec76c37 --- /dev/null +++ b/WebCore/plugins/mac/PluginDataMac.mm @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2004 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2008 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. + */ + +#import "config.h" +#import "PluginData.h" + +#import "BlockExceptions.h" +#import "Logging.h" +#import "WebCoreViewFactory.h" + +namespace WebCore { + +void PluginData::initPlugins() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + + NSArray* plugins = [[WebCoreViewFactory sharedFactory] pluginsInfo]; + for (unsigned int i = 0; i < [plugins count]; ++i) { + PluginInfo* pluginInfo = new PluginInfo; + + id <WebCorePluginInfo> plugin = [plugins objectAtIndex:i]; + + pluginInfo->name = [plugin name]; + pluginInfo->file = [plugin filename]; + pluginInfo->desc = [plugin pluginDescription]; + + NSEnumerator* MIMETypeEnumerator = [plugin MIMETypeEnumerator]; + while (NSString* MIME = [MIMETypeEnumerator nextObject]) { + MimeClassInfo* mime = new MimeClassInfo; + pluginInfo->mimes.append(mime); + mime->type = String(MIME).lower(); + mime->suffixes = [[plugin extensionsForMIMEType:MIME] componentsJoinedByString:@","]; + mime->desc = [plugin descriptionForMIMEType:MIME]; + mime->plugin = pluginInfo; + } + + m_plugins.append(pluginInfo); + } + + END_BLOCK_OBJC_EXCEPTIONS; + + return; +} + +void PluginData::refresh() +{ + BEGIN_BLOCK_OBJC_EXCEPTIONS; + [[WebCoreViewFactory sharedFactory] refreshPlugins]; + END_BLOCK_OBJC_EXCEPTIONS; +} + +} + diff --git a/WebCore/plugins/npapi.cpp b/WebCore/plugins/npapi.cpp new file mode 100644 index 0000000..05d7c06 --- /dev/null +++ b/WebCore/plugins/npapi.cpp @@ -0,0 +1,193 @@ +/* + * 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. + */ + +#include "config.h" + +#include "PluginInfoStore.h" +#include "PluginMainThreadScheduler.h" +#include "PluginView.h" +#include "npruntime_internal.h" + +using namespace WebCore; + +// The plugin view is always the ndata of the instance,. Sometimes, plug-ins will call an instance-specific function +// with a NULL instance. To workaround this, call the last plug-in view that made a call to a plug-in. +// Currently, the current plug-in view is only set before NPP_New in PluginView::start. +// This specifically works around Flash and Shockwave. When we call NPP_New, they call NPN_Useragent with a NULL instance. +static PluginView* pluginViewForInstance(NPP instance) +{ + if (instance && instance->ndata) + return static_cast<PluginView*>(instance->ndata); + return PluginView::currentPluginView(); +} + +void* NPN_MemAlloc(uint32 size) +{ + return malloc(size); +} + +void NPN_MemFree(void* ptr) +{ + free(ptr); +} + +uint32 NPN_MemFlush(uint32 size) +{ + // Do nothing + return 0; +} + +void NPN_ReloadPlugins(NPBool reloadPages) +{ + refreshPlugins(reloadPages); +} + +NPError NPN_RequestRead(NPStream* stream, NPByteRange* rangeList) +{ + return NPERR_STREAM_NOT_SEEKABLE; +} + +NPError NPN_GetURLNotify(NPP instance, const char* url, const char* target, void* notifyData) +{ + return pluginViewForInstance(instance)->getURLNotify(url, target, notifyData); +} + +NPError NPN_GetURL(NPP instance, const char* url, const char* target) +{ + return pluginViewForInstance(instance)->getURL(url, target); +} + +NPError NPN_PostURLNotify(NPP instance, const char* url, const char* target, uint32 len, const char* buf, NPBool file, void* notifyData) +{ + return pluginViewForInstance(instance)->postURLNotify(url, target, len, buf, file, notifyData); +} + +NPError NPN_PostURL(NPP instance, const char* url, const char* target, uint32 len, const char* buf, NPBool file) +{ + return pluginViewForInstance(instance)->postURL(url, target, len, buf, file); +} + +NPError NPN_NewStream(NPP instance, NPMIMEType type, const char* target, NPStream** stream) +{ + return pluginViewForInstance(instance)->newStream(type, target, stream); +} + +int32 NPN_Write(NPP instance, NPStream* stream, int32 len, void* buffer) +{ + return pluginViewForInstance(instance)->write(stream, len, buffer); +} + +NPError NPN_DestroyStream(NPP instance, NPStream* stream, NPReason reason) +{ + return pluginViewForInstance(instance)->destroyStream(stream, reason); +} + +const char* NPN_UserAgent(NPP instance) +{ + PluginView* view = pluginViewForInstance(instance); + + if (!view) + return PluginView::userAgentStatic(); + + return view->userAgent(); +} + +void NPN_Status(NPP instance, const char* message) +{ + pluginViewForInstance(instance)->status(message); +} + +void NPN_InvalidateRect(NPP instance, NPRect* invalidRect) +{ + pluginViewForInstance(instance)->invalidateRect(invalidRect); +} + +void NPN_InvalidateRegion(NPP instance, NPRegion invalidRegion) +{ + pluginViewForInstance(instance)->invalidateRegion(invalidRegion); +} + +void NPN_ForceRedraw(NPP instance) +{ + pluginViewForInstance(instance)->forceRedraw(); +} + +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); +} + +NPError NPN_SetValue(NPP instance, NPPVariable variable, void* value) +{ + return pluginViewForInstance(instance)->setValue(variable, value); +} + +void* NPN_GetJavaEnv() +{ + // Unsupported + return 0; +} + +void* NPN_GetJavaPeer(NPP instance) +{ + // Unsupported + return 0; +} + +void NPN_PushPopupsEnabledState(NPP instance, NPBool enabled) +{ + pluginViewForInstance(instance)->pushPopupsEnabledState(enabled); +} + +void NPN_PopPopupsEnabledState(NPP instance) +{ + pluginViewForInstance(instance)->popPopupsEnabledState(); +} + +void NPN_PluginThreadAsyncCall(NPP instance, void (*func) (void *), void *userData) +{ + PluginMainThreadScheduler::scheduler().scheduleCall(instance, func, userData); +} + +#ifdef PLUGIN_SCHEDULE_TIMER +uint32 NPN_ScheduleTimer(NPP instance, uint32 interval, NPBool repeat, + void (*timerFunc)(NPP npp, uint32 timerID)) +{ + return pluginViewForInstance(instance)->scheduleTimer(instance, interval, + repeat != 0, timerFunc); +} + +void NPN_UnscheduleTimer(NPP instance, uint32 timerID) +{ + pluginViewForInstance(instance)->unscheduleTimer(instance, timerID); +} +#endif + + diff --git a/WebCore/plugins/npfunctions.h b/WebCore/plugins/npfunctions.h new file mode 100644 index 0000000..21e2e15 --- /dev/null +++ b/WebCore/plugins/npfunctions.h @@ -0,0 +1,210 @@ +/* + * Copyright (C) 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 NPFUNCTIONS_H +#define NPFUNCTIONS_H + + +#include "npruntime.h" +#include "npapi.h" +#if defined(ANDROID_PLUGINS) +#include "nativehelper/jni.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(XP_WIN) +#define EXPORTED_CALLBACK(_type, _name) _type (__stdcall * _name) +#else +#define EXPORTED_CALLBACK(_type, _name) _type (* _name) +#endif + +typedef NPError (*NPN_GetURLNotifyProcPtr)(NPP instance, const char* URL, const char* window, void* notifyData); +typedef NPError (*NPN_PostURLNotifyProcPtr)(NPP instance, const char* URL, const char* window, uint32 len, const char* buf, NPBool file, void* notifyData); +typedef NPError (*NPN_RequestReadProcPtr)(NPStream* stream, NPByteRange* rangeList); +typedef NPError (*NPN_NewStreamProcPtr)(NPP instance, NPMIMEType type, const char* window, NPStream** stream); +typedef int32 (*NPN_WriteProcPtr)(NPP instance, NPStream* stream, int32 len, void* buffer); +typedef NPError (*NPN_DestroyStreamProcPtr)(NPP instance, NPStream* stream, NPReason reason); +typedef void (*NPN_StatusProcPtr)(NPP instance, const char* message); +typedef const char*(*NPN_UserAgentProcPtr)(NPP instance); +typedef void* (*NPN_MemAllocProcPtr)(uint32 size); +typedef void (*NPN_MemFreeProcPtr)(void* ptr); +typedef uint32 (*NPN_MemFlushProcPtr)(uint32 size); +typedef void (*NPN_ReloadPluginsProcPtr)(NPBool reloadPages); +typedef NPError (*NPN_GetValueProcPtr)(NPP instance, NPNVariable variable, void *ret_value); +typedef NPError (*NPN_SetValueProcPtr)(NPP instance, NPPVariable variable, void *value); +typedef void (*NPN_InvalidateRectProcPtr)(NPP instance, NPRect *rect); +typedef void (*NPN_InvalidateRegionProcPtr)(NPP instance, NPRegion region); +typedef void (*NPN_ForceRedrawProcPtr)(NPP instance); +typedef NPError (*NPN_GetURLProcPtr)(NPP instance, const char* URL, const char* window); +typedef NPError (*NPN_PostURLProcPtr)(NPP instance, const char* URL, const char* window, uint32 len, const char* buf, NPBool file); +typedef void* (*NPN_GetJavaEnvProcPtr)(void); +typedef void* (*NPN_GetJavaPeerProcPtr)(NPP instance); +typedef void (*NPN_PushPopupsEnabledStateProcPtr)(NPP instance, NPBool enabled); +typedef void (*NPN_PopPopupsEnabledStateProcPtr)(NPP instance); +typedef void (*NPN_PluginThreadAsyncCallProcPtr)(NPP npp, void (*func)(void *), void *userData); +typedef uint32 (*NPN_ScheduleTimerProcPtr)(NPP npp, uint32 interval, NPBool repeat, void (*timerFunc)(NPP npp, uint32 timerID)); +typedef void (*NPN_UnscheduleTimerProcPtr)(NPP npp, uint32 timerID); +typedef NPError (*NPN_PopUpContextMenuProcPtr)(NPP instance, NPMenu* menu); + +typedef void (*NPN_ReleaseVariantValueProcPtr) (NPVariant *variant); + +typedef NPIdentifier (*NPN_GetStringIdentifierProcPtr) (const NPUTF8 *name); +typedef void (*NPN_GetStringIdentifiersProcPtr) (const NPUTF8 **names, int32_t nameCount, NPIdentifier *identifiers); +typedef NPIdentifier (*NPN_GetIntIdentifierProcPtr) (int32_t intid); +typedef int32_t (*NPN_IntFromIdentifierProcPtr) (NPIdentifier identifier); +typedef bool (*NPN_IdentifierIsStringProcPtr) (NPIdentifier identifier); +typedef NPUTF8 *(*NPN_UTF8FromIdentifierProcPtr) (NPIdentifier identifier); + +typedef NPObject* (*NPN_CreateObjectProcPtr) (NPP, NPClass *aClass); +typedef NPObject* (*NPN_RetainObjectProcPtr) (NPObject *obj); +typedef void (*NPN_ReleaseObjectProcPtr) (NPObject *obj); +typedef bool (*NPN_InvokeProcPtr) (NPP npp, NPObject *obj, NPIdentifier methodName, const NPVariant *args, unsigned argCount, NPVariant *result); +typedef bool (*NPN_InvokeDefaultProcPtr) (NPP npp, NPObject *obj, const NPVariant *args, unsigned argCount, NPVariant *result); +typedef bool (*NPN_EvaluateProcPtr) (NPP npp, NPObject *obj, NPString *script, NPVariant *result); +typedef bool (*NPN_GetPropertyProcPtr) (NPP npp, NPObject *obj, NPIdentifier propertyName, NPVariant *result); +typedef bool (*NPN_SetPropertyProcPtr) (NPP npp, NPObject *obj, NPIdentifier propertyName, const NPVariant *value); +typedef bool (*NPN_HasPropertyProcPtr) (NPP, NPObject *npobj, NPIdentifier propertyName); +typedef bool (*NPN_HasMethodProcPtr) (NPP npp, NPObject *npobj, NPIdentifier methodName); +typedef bool (*NPN_RemovePropertyProcPtr) (NPP npp, NPObject *obj, NPIdentifier propertyName); +typedef void (*NPN_SetExceptionProcPtr) (NPObject *obj, const NPUTF8 *message); +typedef bool (*NPN_EnumerateProcPtr) (NPP npp, NPObject *npobj, NPIdentifier **identifier, uint32_t *count); +typedef bool (*NPN_ConstructProcPtr)(NPP npp, NPObject* obj, const NPVariant *args, uint32_t argCount, NPVariant *result); + +typedef NPError (*NPP_NewProcPtr)(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved); +typedef NPError (*NPP_DestroyProcPtr)(NPP instance, NPSavedData** save); +typedef NPError (*NPP_SetWindowProcPtr)(NPP instance, NPWindow* window); +typedef NPError (*NPP_NewStreamProcPtr)(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype); +typedef NPError (*NPP_DestroyStreamProcPtr)(NPP instance, NPStream* stream, NPReason reason); +typedef void (*NPP_StreamAsFileProcPtr)(NPP instance, NPStream* stream, const char* fname); +typedef int32 (*NPP_WriteReadyProcPtr)(NPP instance, NPStream* stream); +typedef int32 (*NPP_WriteProcPtr)(NPP instance, NPStream* stream, int32_t offset, int32_t len, void* buffer); +typedef void (*NPP_PrintProcPtr)(NPP instance, NPPrint* platformPrint); +typedef int16 (*NPP_HandleEventProcPtr)(NPP instance, void* event); +typedef void (*NPP_URLNotifyProcPtr)(NPP instance, const char* URL, NPReason reason, void* notifyData); +typedef NPError (*NPP_GetValueProcPtr)(NPP instance, NPPVariable variable, void *ret_value); +typedef NPError (*NPP_SetValueProcPtr)(NPP instance, NPNVariable variable, void *value); + +typedef void *(*NPP_GetJavaClassProcPtr)(void); +typedef void* JRIGlobalRef; //not using this right now + +typedef struct _NPNetscapeFuncs { + uint16 size; + uint16 version; + + NPN_GetURLProcPtr geturl; + NPN_PostURLProcPtr posturl; + NPN_RequestReadProcPtr requestread; + NPN_NewStreamProcPtr newstream; + NPN_WriteProcPtr write; + NPN_DestroyStreamProcPtr destroystream; + NPN_StatusProcPtr status; + NPN_UserAgentProcPtr uagent; + NPN_MemAllocProcPtr memalloc; + NPN_MemFreeProcPtr memfree; + NPN_MemFlushProcPtr memflush; + NPN_ReloadPluginsProcPtr reloadplugins; + NPN_GetJavaEnvProcPtr getJavaEnv; + NPN_GetJavaPeerProcPtr getJavaPeer; + NPN_GetURLNotifyProcPtr geturlnotify; + NPN_PostURLNotifyProcPtr posturlnotify; + NPN_GetValueProcPtr getvalue; + NPN_SetValueProcPtr setvalue; + NPN_InvalidateRectProcPtr invalidaterect; + NPN_InvalidateRegionProcPtr invalidateregion; + NPN_ForceRedrawProcPtr forceredraw; + + NPN_GetStringIdentifierProcPtr getstringidentifier; + NPN_GetStringIdentifiersProcPtr getstringidentifiers; + NPN_GetIntIdentifierProcPtr getintidentifier; + NPN_IdentifierIsStringProcPtr identifierisstring; + NPN_UTF8FromIdentifierProcPtr utf8fromidentifier; + NPN_IntFromIdentifierProcPtr intfromidentifier; + NPN_CreateObjectProcPtr createobject; + NPN_RetainObjectProcPtr retainobject; + NPN_ReleaseObjectProcPtr releaseobject; + NPN_InvokeProcPtr invoke; + NPN_InvokeDefaultProcPtr invokeDefault; + NPN_EvaluateProcPtr evaluate; + NPN_GetPropertyProcPtr getproperty; + NPN_SetPropertyProcPtr setproperty; + NPN_RemovePropertyProcPtr removeproperty; + NPN_HasPropertyProcPtr hasproperty; + NPN_HasMethodProcPtr hasmethod; + NPN_ReleaseVariantValueProcPtr releasevariantvalue; + NPN_SetExceptionProcPtr setexception; + NPN_PushPopupsEnabledStateProcPtr pushpopupsenabledstate; + NPN_PopPopupsEnabledStateProcPtr poppopupsenabledstate; + NPN_EnumerateProcPtr enumerate; + NPN_PluginThreadAsyncCallProcPtr pluginthreadasynccall; + NPN_ConstructProcPtr construct; + NPN_ScheduleTimerProcPtr scheduletimer; + NPN_UnscheduleTimerProcPtr unscheduletimer; + NPN_PopUpContextMenuProcPtr popupcontextmenu; +} NPNetscapeFuncs; + +typedef struct _NPPluginFuncs { + uint16 size; + uint16 version; + NPP_NewProcPtr newp; + NPP_DestroyProcPtr destroy; + NPP_SetWindowProcPtr setwindow; + NPP_NewStreamProcPtr newstream; + NPP_DestroyStreamProcPtr destroystream; + NPP_StreamAsFileProcPtr asfile; + NPP_WriteReadyProcPtr writeready; + NPP_WriteProcPtr write; + NPP_PrintProcPtr print; + NPP_HandleEventProcPtr event; + NPP_URLNotifyProcPtr urlnotify; + JRIGlobalRef javaClass; + NPP_GetValueProcPtr getvalue; + NPP_SetValueProcPtr setvalue; +} NPPluginFuncs; + +typedef EXPORTED_CALLBACK(NPError, NP_GetEntryPointsFuncPtr)(NPPluginFuncs*); +typedef EXPORTED_CALLBACK(void, NPP_ShutdownProcPtr)(void); + +#if defined(XP_MACOSX) +typedef void (*BP_CreatePluginMIMETypesPreferencesFuncPtr)(void); +typedef NPError (*MainFuncPtr)(NPNetscapeFuncs*, NPPluginFuncs*, NPP_ShutdownProcPtr*); +#endif + +#if defined(XP_UNIX) +typedef EXPORTED_CALLBACK(NPError, NP_InitializeFuncPtr)(NPNetscapeFuncs*, NPPluginFuncs*); +typedef EXPORTED_CALLBACK(char*, NP_GetMIMEDescriptionFuncPtr)(void); +#elif defined(ANDROID_PLUGINS) +typedef EXPORTED_CALLBACK(NPError, NP_InitializeFuncPtr)(NPNetscapeFuncs*, NPPluginFuncs*, JNIEnv *java_environment, jobject application_context); +typedef EXPORTED_CALLBACK(char*, NP_GetMIMEDescriptionFuncPtr)(void); +#else +typedef EXPORTED_CALLBACK(NPError, NP_InitializeFuncPtr)(NPNetscapeFuncs*); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/WebCore/plugins/qt/PluginDataQt.cpp b/WebCore/plugins/qt/PluginDataQt.cpp new file mode 100644 index 0000000..13f1442 --- /dev/null +++ b/WebCore/plugins/qt/PluginDataQt.cpp @@ -0,0 +1,108 @@ +/* + Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + Copyright (C) 2008 Collabora Ltd. 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 + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "config.h" +#include "PluginData.h" + +#include "PluginDatabase.h" +#include "PluginPackage.h" + +#if QT_VERSION >= 0x040400 +#include "ChromeClientQt.h" +#include "Page.h" +#include <qwebpage.h> +#include <qwebpluginfactory.h> +#endif + +namespace WebCore { + +void PluginData::initPlugins() +{ +#if QT_VERSION >= 0x040400 + QWebPage* webPage = static_cast<ChromeClientQt*>(m_page->chrome()->client())->m_webPage; + QWebPluginFactory* factory = webPage->pluginFactory(); + if (factory) { + + QList<QWebPluginFactory::Plugin> qplugins = factory->plugins(); + for (int i = 0; i < qplugins.count(); ++i) { + const QWebPluginFactory::Plugin& qplugin = qplugins.at(i); + + PluginInfo* info = new PluginInfo; + info->name = qplugin.name; + info->desc = qplugin.description; + + for (int j = 0; j < qplugin.mimeTypes.count(); ++j) { + const QWebPluginFactory::MimeType& mimeType = qplugin.mimeTypes.at(j); + + MimeClassInfo* mimeInfo = new MimeClassInfo; + mimeInfo->type = mimeType.name; + mimeInfo->desc = mimeType.description; + mimeInfo->suffixes = mimeType.fileExtensions.join("; "); + + info->mimes.append(mimeInfo); + } + + m_plugins.append(info); + } + } +#endif + + PluginDatabase *db = PluginDatabase::installedPlugins(); + const Vector<PluginPackage*> &plugins = db->plugins(); + + for (unsigned int i = 0; i < plugins.size(); ++i) { + PluginInfo* info = new PluginInfo; + PluginPackage* package = plugins[i]; + + info->name = package->name(); + info->file = package->fileName(); + info->desc = package->description(); + + const MIMEToDescriptionsMap& mimeToDescriptions = package->mimeToDescriptions(); + MIMEToDescriptionsMap::const_iterator end = mimeToDescriptions.end(); + for (MIMEToDescriptionsMap::const_iterator it = mimeToDescriptions.begin(); it != end; ++it) { + MimeClassInfo* mime = new MimeClassInfo; + info->mimes.append(mime); + + mime->type = it->first; + mime->desc = it->second; + mime->plugin = info; + + Vector<String> extensions = package->mimeToExtensions().get(mime->type); + + for (unsigned i = 0; i < extensions.size(); i++) { + if (i > 0) + mime->suffixes += ","; + + mime->suffixes += extensions[i]; + } + } + + m_plugins.append(info); + } +} + +void PluginData::refresh() +{ + PluginDatabase *db = PluginDatabase::installedPlugins(); + db->refresh(); +} + +}; diff --git a/WebCore/plugins/qt/PluginPackageQt.cpp b/WebCore/plugins/qt/PluginPackageQt.cpp new file mode 100644 index 0000000..423c4e1 --- /dev/null +++ b/WebCore/plugins/qt/PluginPackageQt.cpp @@ -0,0 +1,220 @@ +/* + * 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 "PluginPackage.h" + +#include "CString.h" +#include "MIMETypeRegistry.h" +#include "NotImplemented.h" +#include "npruntime_impl.h" +#include "PluginDatabase.h" +#include "PluginDebug.h" + +namespace WebCore { + +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); + } + + if (mimeType == "application/x-shockwave-flash") { + // The flash plugin only requests windowless plugins if we return a mozilla user agent + m_quirks.add(PluginQuirkWantsMozillaUserAgent); + m_quirks.add(PluginQuirkThrottleInvalidate); + m_quirks.add(PluginQuirkThrottleWMUserPlusOneMessages); + m_quirks.add(PluginQuirkFlashURLNotifyBug); + } + +} + +bool PluginPackage::fetchInfo() +{ + if (!load()) + return false; + + NPP_GetValueProcPtr gv = (NPP_GetValueProcPtr)m_module->resolve("NP_GetValue"); + typedef char *(*NPP_GetMIMEDescriptionProcPtr)(); + NPP_GetMIMEDescriptionProcPtr gm = + (NPP_GetMIMEDescriptionProcPtr)m_module->resolve("NP_GetMIMEDescription"); + if (!gm || !gv) { + return false; + } + char *buf = 0; + NPError err = gv(0, NPPVpluginNameString, (void *)&buf); + if (err != NPERR_NO_ERROR) { + return false; + } + m_name = buf; + err = gv(0, NPPVpluginDescriptionString, (void *)&buf); + if (err != NPERR_NO_ERROR) { + return false; + } + m_description = buf; + + String s = gm(); + Vector<String> types; + s.split(UChar(';'), false, types); + for (int i = 0; i < types.size(); ++i) { + Vector<String> mime; + types[i].split(UChar(':'), true, mime); + if (mime.size() > 0) { + Vector<String> exts; + if (mime.size() > 1) + mime[1].split(UChar(','), false, exts); + determineQuirks(mime[0]); + m_mimeToExtensions.add(mime[0], exts); + if (mime.size() > 2) + m_mimeToDescriptions.add(mime[0], mime[2]); + } + } + + return true; +} + +bool PluginPackage::load() +{ + if (m_isLoaded) { + m_loadCount++; + return true; + } + + m_module = new QLibrary((QString)m_path); + m_module->setLoadHints(QLibrary::ResolveAllSymbolsHint); + if (!m_module->load()) { + LOG(Plugin, "%s not loaded", m_path.utf8().data()); + return false; + } + + m_isLoaded = true; + + NP_InitializeFuncPtr NP_Initialize; + NPError npErr; + + NP_Initialize = (NP_InitializeFuncPtr)m_module->resolve("NP_Initialize"); + m_NPP_Shutdown = (NPP_ShutdownProcPtr)m_module->resolve("NP_Shutdown"); + + if (!NP_Initialize || !m_NPP_Shutdown) + goto abort; + + memset(&m_pluginFuncs, 0, sizeof(m_pluginFuncs)); + m_pluginFuncs.size = sizeof(m_pluginFuncs); + + m_browserFuncs.size = sizeof (m_browserFuncs); + m_browserFuncs.version = NP_VERSION_MINOR; + 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.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.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_HasMethod; + m_browserFuncs.hasmethod = _NPN_HasProperty; + m_browserFuncs.setexception = _NPN_SetException; + m_browserFuncs.enumerate = _NPN_Enumerate; + m_browserFuncs.construct = _NPN_Construct; + +#if defined(XP_UNIX) + npErr = NP_Initialize(&m_browserFuncs, &m_pluginFuncs); +#else + npErr = NP_Initialize(&m_browserFuncs); +#endif + if (npErr != NPERR_NO_ERROR) + goto abort; + + m_loadCount++; + return true; + +abort: + unloadWithoutShutdown(); + return false; +} + +unsigned PluginPackage::hash() const +{ + unsigned hashCodes[2] = { + m_path.impl()->hash(), + m_lastModified + }; + + return StringImpl::computeHash(reinterpret_cast<UChar*>(hashCodes), 2 * sizeof(unsigned) / sizeof(UChar)); +} + +bool PluginPackage::equal(const PluginPackage& a, const PluginPackage& b) +{ + return a.m_description == b.m_description; +} + +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 (m_moduleVersion != compareVersion) + return m_moduleVersion > compareVersion ? 1 : -1; + return 0; +} + +} diff --git a/WebCore/plugins/qt/PluginViewQt.cpp b/WebCore/plugins/qt/PluginViewQt.cpp new file mode 100644 index 0000000..819fd36 --- /dev/null +++ b/WebCore/plugins/qt/PluginViewQt.cpp @@ -0,0 +1,483 @@ +/* + * 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 "PluginView.h" + +#include <QWidget> +#include <QX11EmbedContainer> +#include <QX11Info> + +#include "NotImplemented.h" +#include "PluginDebug.h" +#include "PluginPackage.h" +#include "npruntime_impl.h" +#include "runtime.h" +#include "runtime_root.h" +#include <runtime/JSLock.h> +#include <runtime/JSValue.h> +#include "JSDOMBinding.h" +#include "ScriptController.h" + +#include "Document.h" +#include "DocumentLoader.h" +#include "Element.h" +#include "FrameLoader.h" +#include "FrameLoadRequest.h" +#include "FrameTree.h" +#include "Frame.h" +#include "FrameView.h" +#include "GraphicsContext.h" +#include "Image.h" +#include "HTMLNames.h" +#include "HTMLPlugInElement.h" +#include "KeyboardEvent.h" +#include "MouseEvent.h" +#include "Page.h" +#include "PlatformMouseEvent.h" +#include "RenderLayer.h" +#include "Settings.h" + +using JSC::ExecState; +using JSC::Interpreter; +using JSC::JSLock; +using JSC::JSObject; +using JSC::UString; + +using std::min; + +using namespace WTF; + +namespace WebCore { + +using namespace HTMLNames; + +void PluginView::updatePluginWidget() const +{ + if (!parent() || !m_isWindowed) + return; + + ASSERT(parent()->isFrameView()); + FrameView* frameView = static_cast<FrameView*>(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 (platformPluginWidget()) { + platformPluginWidget()->move(m_windowRect.x(), m_windowRect.y()); + platformPluginWidget()->resize(m_windowRect.width(), m_windowRect.height()); + platformPluginWidget()->setMask(QRegion(m_clipRect.x(), m_clipRect.y(), m_clipRect.width(), m_clipRect.height())); + } +} + +void PluginView::setFocus() +{ + if (platformPluginWidget()) + platformPluginWidget()->setFocus(Qt::OtherFocusReason); + else + Widget::setFocus(); +} + +void PluginView::show() +{ + setSelfVisible(true); + + if (isParentVisible() && platformPluginWidget()) + platformPluginWidget()->setVisible(true); + + Widget::show(); +} + +void PluginView::hide() +{ + setSelfVisible(false); + + if (isParentVisible() && platformPluginWidget()) + platformPluginWidget()->setVisible(false); + + Widget::hide(); +} + +void PluginView::paint(GraphicsContext* context, const IntRect& rect) +{ + if (!m_isStarted) { + // Draw the "missing plugin" image + //paintMissingPluginIcon(context, rect); + return; + } + + if (m_isWindowed || context->paintingDisabled()) + return; + + notImplemented(); +} + +void PluginView::handleKeyboardEvent(KeyboardEvent* event) +{ + notImplemented(); +} + +void PluginView::handleMouseEvent(MouseEvent* event) +{ + notImplemented(); +} + +void PluginView::setParent(ScrollView* parent) +{ + Widget::setParent(parent); + + if (parent) + init(); + else { + if (!platformPluginWidget()) + return; + } +} + +void PluginView::setNPWindowRect(const IntRect& rect) +{ + if (!m_isStarted || !parent()) + return; + + IntPoint p = static_cast<FrameView*>(parent())->contentsToWindow(rect.location()); + m_npWindow.x = p.x(); + m_npWindow.y = p.y(); + + m_npWindow.width = rect.width(); + m_npWindow.height = rect.height(); + + m_npWindow.clipRect.left = 0; + m_npWindow.clipRect.top = 0; + m_npWindow.clipRect.right = rect.width(); + m_npWindow.clipRect.bottom = rect.height(); + + if (m_npWindow.x < 0 || m_npWindow.y < 0 || + m_npWindow.width <= 0 || m_npWindow.height <= 0) + return; + + if (m_plugin->pluginFuncs()->setwindow) { + PluginView::setCurrentPluginView(this); + JSC::JSLock::DropAllLocks dropAllLocks(false); + setCallingPlugin(true); + m_plugin->pluginFuncs()->setwindow(m_instance, &m_npWindow); + setCallingPlugin(false); + PluginView::setCurrentPluginView(0); + + if (!m_isWindowed) + return; + + ASSERT(platformPluginWidget()); + } +} + +void PluginView::setParentVisible(bool visible) +{ + if (isParentVisible() == visible) + return; + + Widget::setParentVisible(visible); + + if (isSelfVisible() && platformPluginWidget()) + platformPluginWidget()->setVisible(visible); +} + +void PluginView::stop() +{ + if (!m_isStarted) + return; + + 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(false); + + // Clear the window + m_npWindow.window = 0; + delete (NPSetWindowCallbackStruct *)m_npWindow.ws_info; + m_npWindow.ws_info = 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); + } + + // Destroy the plugin + { + PluginView::setCurrentPluginView(this); + setCallingPlugin(true); + m_plugin->pluginFuncs()->destroy(m_instance, 0); + setCallingPlugin(false); + PluginView::setCurrentPluginView(0); + } + + m_instance->pdata = 0; +} + +static const char* MozillaUserAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0"; + +const char* PluginView::userAgent() +{ + if (m_plugin->quirks().contains(PluginQuirkWantsMozillaUserAgent)) + return MozillaUserAgent; + + if (m_userAgent.isNull()) + m_userAgent = m_parentFrame->loader()->userAgent(m_url).utf8(); + + return m_userAgent.data(); +} + +const char* PluginView::userAgentStatic() +{ + //FIXME - Just say we are Mozilla + return MozillaUserAgent; +} + +NPError PluginView::handlePostReadFile(Vector<char>& buffer, uint32 len, const char* buf) +{ + String filename(buf, len); + + if (filename.startsWith("file:///")) + filename = filename.substring(8); + + if (!fileExists(filename)) + return NPERR_FILE_NOT_FOUND; + + //FIXME - read the file data into buffer + FILE* fileHandle = fopen((filename.utf8()).data(), "r"); + + if (fileHandle == 0) + return NPERR_FILE_NOT_FOUND; + + //buffer.resize(); + + int bytesRead = fread(buffer.data(), 1, 0, fileHandle); + + fclose(fileHandle); + + if (bytesRead <= 0) + return NPERR_FILE_NOT_FOUND; + + return NPERR_NO_ERROR; +} + +NPError PluginView::getValueStatic(NPNVariable variable, void* value) +{ + switch (variable) { + case NPNVToolkit: + *((uint32 *)value) = 0; + return NPERR_NO_ERROR; + + case NPNVSupportsXEmbedBool: + *((uint32 *)value) = true; + return NPERR_NO_ERROR; + + case NPNVjavascriptEnabledBool: + *((uint32 *)value) = true; + return NPERR_NO_ERROR; + + default: + return NPERR_GENERIC_ERROR; + } +} + +NPError PluginView::getValue(NPNVariable variable, void* value) +{ + switch (variable) { + case NPNVxDisplay: + if (platformPluginWidget()) + *(void **)value = platformPluginWidget()->x11Info().display(); + else + *(void **)value = m_parentFrame->view()->hostWindow()->platformWindow()->x11Info().display(); + return NPERR_NO_ERROR; + + case NPNVxtAppContext: + return NPERR_GENERIC_ERROR; + +#if ENABLE(NETSCAPE_PLUGIN_API) + 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 = static_cast<HTMLPlugInElement*>(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; + } +#endif + + case NPNVnetscapeWindow: { + void* w = reinterpret_cast<void*>(value); + *((XID *)w) = m_parentFrame->view()->hostWindow()->platformWindow()->winId(); + return NPERR_NO_ERROR; + } + + default: + return getValueStatic(variable, value); + } +} + +void PluginView::invalidateRect(const IntRect& rect) +{ + if (platformWidget()) { + platformWidget()->update(rect); + return; + } + + invalidateWindowlessPluginRect(rect); +} + +void PluginView::invalidateRect(NPRect* rect) +{ + notImplemented(); +} + +void PluginView::invalidateRegion(NPRegion region) +{ + notImplemented(); +} + +void PluginView::forceRedraw() +{ + notImplemented(); +} + +PluginView::~PluginView() +{ + stop(); + + deleteAllValues(m_requests); + + freeStringArray(m_paramNames, m_paramCount); + freeStringArray(m_paramValues, m_paramCount); + + m_parentFrame->script()->cleanupScriptObjectsForPlugin(this); + + if (m_plugin && !(m_plugin->quirks().contains(PluginQuirkDontUnloadPlugin))) + m_plugin->unload(); + + delete platformPluginWidget(); +} + +void PluginView::init() +{ + if (m_haveInitialized) + return; + m_haveInitialized = true; + + if (!m_plugin) { + ASSERT(m_status == PluginStatusCanNotFindPlugin); + return; + } + + if (!m_plugin->load()) { + m_plugin = 0; + m_status = PluginStatusCanNotLoadPlugin; + return; + } + + if (!start()) { + m_status = PluginStatusCanNotLoadPlugin; + return; + } + + if (m_plugin->pluginFuncs()->getvalue) { + PluginView::setCurrentPluginView(this); + JSC::JSLock::DropAllLocks dropAllLocks(false); + setCallingPlugin(true); + m_plugin->pluginFuncs()->getvalue(m_instance, NPPVpluginNeedsXEmbed, &m_needsXEmbed); + setCallingPlugin(false); + PluginView::setCurrentPluginView(0); + } + + if (m_needsXEmbed) { + setPlatformWidget(new QX11EmbedContainer(m_parentFrame->view()->hostWindow()->platformWindow())); + setIsNPAPIPlugin(true); + } else { + notImplemented(); + m_status = PluginStatusCanNotLoadPlugin; + return; + } + show (); + + NPSetWindowCallbackStruct *wsi = new NPSetWindowCallbackStruct(); + + wsi->type = 0; + + wsi->display = platformPluginWidget()->x11Info().display(); + wsi->visual = (Visual*)platformPluginWidget()->x11Info().visual(); + wsi->depth = platformPluginWidget()->x11Info().depth(); + wsi->colormap = platformPluginWidget()->x11Info().colormap(); + m_npWindow.ws_info = wsi; + + m_npWindow.type = NPWindowTypeWindow; + m_npWindow.window = (void*)platformPluginWidget()->winId(); + + if (!(m_plugin->quirks().contains(PluginQuirkDeferFirstSetWindowCall))) + setNPWindowRect(frameRect()); + + m_status = PluginStatusLoadedSuccessfully; +} + +} // namespace WebCore diff --git a/WebCore/plugins/win/PluginDataWin.cpp b/WebCore/plugins/win/PluginDataWin.cpp new file mode 100644 index 0000000..4ec4b6d --- /dev/null +++ b/WebCore/plugins/win/PluginDataWin.cpp @@ -0,0 +1,72 @@ +/* + Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + Copyright (C) 2006, 2007 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 + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "config.h" +#include "PluginData.h" + +#include "PluginDatabase.h" +#include "PluginPackage.h" + +namespace WebCore { + +void PluginData::initPlugins() +{ + PluginDatabase *db = PluginDatabase::installedPlugins(); + const Vector<PluginPackage*> &plugins = db->plugins(); + + for (unsigned int i = 0; i < plugins.size(); ++i) { + PluginInfo* info = new PluginInfo; + PluginPackage* package = plugins[i]; + + info->name = package->name(); + info->file = package->fileName(); + info->desc = package->description(); + + const MIMEToDescriptionsMap& mimeToDescriptions = package->mimeToDescriptions(); + MIMEToDescriptionsMap::const_iterator end = mimeToDescriptions.end(); + for (MIMEToDescriptionsMap::const_iterator it = mimeToDescriptions.begin(); it != end; ++it) { + MimeClassInfo* mime = new MimeClassInfo; + info->mimes.append(mime); + + mime->type = it->first; + mime->desc = it->second; + mime->plugin = info; + + Vector<String> extensions = package->mimeToExtensions().get(mime->type); + + for (unsigned i = 0; i < extensions.size(); i++) { + if (i > 0) + mime->suffixes += ","; + + mime->suffixes += extensions[i]; + } + } + + m_plugins.append(info); + } +} + +void PluginData::refresh() +{ + PluginDatabase *db = PluginDatabase::installedPlugins(); + db->refresh(); +} + +}; diff --git a/WebCore/plugins/win/PluginDatabaseWin.cpp b/WebCore/plugins/win/PluginDatabaseWin.cpp new file mode 100644 index 0000000..c59f133 --- /dev/null +++ b/WebCore/plugins/win/PluginDatabaseWin.cpp @@ -0,0 +1,354 @@ +/* + * 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 "KURL.h" +#include "PluginPackage.h" +#include <windows.h> +#include <shlwapi.h> + +#if COMPILER(MINGW) +#define _countof(x) (sizeof(x)/sizeof(x[0])) +#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 = _countof(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 = SHGetValue(key, name, TEXT("Path"), &type, (LPBYTE)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(), &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).second) + 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(), 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) +{ + // 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, _countof(pluginDirectoryStr)); + + if (pluginDirectorySize > 0 && pluginDirectorySize <= _countof(pluginDirectoryStr)) + directories.append(String(pluginDirectoryStr, pluginDirectorySize - 1)); + + DWORD type; + WCHAR installationDirectoryStr[_MAX_PATH]; + DWORD installationDirectorySize = sizeof(installationDirectoryStr); + + HRESULT result = SHGetValue(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\MediaPlayer"), TEXT("Installation Directory"), &type, (LPBYTE)&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 = SHGetValue(HKEY_LOCAL_MACHINE, TEXT("Software\\Apple Computer, Inc.\\QuickTime"), TEXT("InstallDir"), &type, (LPBYTE)&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 = SHGetValue(HKEY_LOCAL_MACHINE, acrobatPluginKeyPath.charactersWithNullTermination(), 0, &type, (LPBYTE)acrobatInstallPathStr, &acrobatInstallPathSize); + + if (result == ERROR_SUCCESS) { + String acrobatPluginDirectory = String(acrobatInstallPathStr, acrobatInstallPathSize / sizeof(WCHAR) - 1) + "\\browser"; + directories.append(acrobatPluginDirectory); + } + } + + 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) +{ + WCHAR systemDirectoryStr[MAX_PATH]; + + if (GetSystemDirectory(systemDirectoryStr, _countof(systemDirectoryStr)) == 0) + return; + + WCHAR macromediaDirectoryStr[MAX_PATH]; + + PathCombine(macromediaDirectoryStr, systemDirectoryStr, TEXT("macromed\\Flash")); + directories.append(macromediaDirectoryStr); + + PathCombine(macromediaDirectoryStr, systemDirectoryStr, TEXT("macromed\\Shockwave 10")); + directories.append(macromediaDirectoryStr); +} + +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/WebCore/plugins/win/PluginMessageThrottlerWin.cpp b/WebCore/plugins/win/PluginMessageThrottlerWin.cpp new file mode 100644 index 0000000..27bf5b9 --- /dev/null +++ b/WebCore/plugins/win/PluginMessageThrottlerWin.cpp @@ -0,0 +1,123 @@ +/* + * 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> + +using namespace WTF; + +namespace WebCore { + +static const double MessageThrottleTimeInterval = 0.001; + +PluginMessageThrottlerWin::PluginMessageThrottlerWin(PluginView* pluginView) + : m_back(0), m_front(0) + , m_pluginView(pluginView) + , m_messageThrottleTimer(this, &PluginMessageThrottlerWin::messageThrottleTimerFired) +{ + // 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 (!m_messageThrottleTimer.isActive()) + m_messageThrottleTimer.startOneShot(MessageThrottleTimeInterval); +} + +void PluginMessageThrottlerWin::messageThrottleTimerFired(Timer<PluginMessageThrottlerWin>*) +{ + PluginMessage* message = m_front; + m_front = m_front->next; + if (message == m_back) + m_back = 0; + + ::CallWindowProc(m_pluginView->pluginWndProc(), message->hWnd, message->msg, message->wParam, message->lParam); + + freeMessage(message); + + 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/WebCore/plugins/win/PluginMessageThrottlerWin.h b/WebCore/plugins/win/PluginMessageThrottlerWin.h new file mode 100644 index 0000000..c74beab --- /dev/null +++ b/WebCore/plugins/win/PluginMessageThrottlerWin.h @@ -0,0 +1,72 @@ +/* + * 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 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; + }; + +} // namespace WebCore + +#endif // PluginMessageThrottlerWin_h diff --git a/WebCore/plugins/win/PluginPackageWin.cpp b/WebCore/plugins/win/PluginPackageWin.cpp new file mode 100644 index 0000000..d2c26e2 --- /dev/null +++ b/WebCore/plugins/win/PluginPackageWin.cpp @@ -0,0 +1,374 @@ +/* + * Copyright (C) 2006, 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 "PluginPackage.h" + +#include "CString.h" +#include "MIMETypeRegistry.h" +#include "PluginDatabase.h" +#include "PluginDebug.h" +#include "Timer.h" +#include "npruntime_impl.h" +#include <string.h> +#include <wtf/OwnArrayPtr.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()), + &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); +} + +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 (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; + return 0; +} + +bool PluginPackage::isPluginBlacklisted() +{ + 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 (fileName() == "npmozax.dll") + // Bug 15217: Mozilla ActiveX control complains about missing xpcom_core.dll + 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") { + // 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(m_path.charactersWithNullTermination(), &zeroHandle); + if (versionInfoSize == 0) + return false; + + OwnArrayPtr<char> versionInfoData(new char[versionInfoSize]); + + if (!GetFileVersionInfoW(m_path.charactersWithNullTermination(), 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 (!VerQueryValue(versionInfoData.get(), TEXT("\\"), (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 { + WCHAR currentPath[MAX_PATH]; + + if (!::GetCurrentDirectoryW(MAX_PATH, currentPath)) + return false; + + String path = m_path.substring(0, m_path.reverseFind('\\')); + + if (!::SetCurrentDirectoryW(path.charactersWithNullTermination())) + return false; + + // Load the library + m_module = ::LoadLibraryW(m_path.charactersWithNullTermination()); + + if (!::SetCurrentDirectoryW(currentPath)) { + if (m_module) + ::FreeLibrary(m_module); + return false; + } + } + + if (!m_module) + return false; + + m_isLoaded = true; + + NP_GetEntryPointsFuncPtr NP_GetEntryPoints = 0; + NP_InitializeFuncPtr NP_Initialize = 0; + NPError npErr; + + 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"); + + 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; + + memset(&m_browserFuncs, 0, sizeof(m_browserFuncs)); + m_browserFuncs.size = sizeof (m_browserFuncs); + m_browserFuncs.version = NP_VERSION_MINOR; + + 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; + + 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 StringImpl::computeHash(reinterpret_cast<const UChar*>(hashCodes), sizeof(hashCodes) / sizeof(UChar)); +} + +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; +} + +} diff --git a/WebCore/plugins/win/PluginViewWin.cpp b/WebCore/plugins/win/PluginViewWin.cpp new file mode 100644 index 0000000..127d3fc --- /dev/null +++ b/WebCore/plugins/win/PluginViewWin.cpp @@ -0,0 +1,861 @@ +/* + * 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 "PluginView.h" + +#include "Document.h" +#include "DocumentLoader.h" +#include "Element.h" +#include "EventNames.h" +#include "FrameLoader.h" +#include "FrameLoadRequest.h" +#include "FrameTree.h" +#include "Frame.h" +#include "FrameView.h" +#include "GraphicsContext.h" +#include "Image.h" +#include "HTMLNames.h" +#include "HTMLPlugInElement.h" +#include "JSDOMWindow.h" +#include "KeyboardEvent.h" +#include "MIMETypeRegistry.h" +#include "MouseEvent.h" +#include "NotImplemented.h" +#include "Page.h" +#include "FocusController.h" +#include "PlatformMouseEvent.h" +#include "PluginMessageThrottlerWin.h" +#include "PluginPackage.h" +#include "PluginMainThreadScheduler.h" +#include "JSDOMBinding.h" +#include "ScriptController.h" +#include "PluginDatabase.h" +#include "PluginDebug.h" +#include "PluginPackage.h" +#include "c_instance.h" +#include "npruntime_impl.h" +#include "runtime_root.h" +#include "Settings.h" +#include "runtime.h" +#include <runtime/JSLock.h> +#include <runtime/JSValue.h> +#include <wtf/ASCIICType.h> + +#if PLATFORM(QT) +#include <QWidget.h> +#endif + +static inline HWND windowHandleForPlatformWidget(PlatformWidget widget) +{ +#if PLATFORM(QT) + if (!widget) + return 0; + return widget->winId(); +#else + return widget; +#endif +} + +using JSC::ExecState; +using JSC::JSLock; +using JSC::JSObject; +using JSC::UString; + +using std::min; + +using namespace WTF; + +namespace WebCore { + +using namespace HTMLNames; + +const LPCWSTR kWebPluginViewdowClassName = L"WebPluginView"; +const LPCWSTR kWebPluginViewProperty = L"WebPluginViewProperty"; + +static const char* MozillaUserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0"; + +static bool registerPluginView() +{ + static bool haveRegisteredWindowClass = false; + if (haveRegisteredWindowClass) + return true; + + haveRegisteredWindowClass = true; + +#if PLATFORM(QT) + Page::setInstanceHandle((HINSTANCE)(qWinAppInst())); +#endif + + ASSERT(Page::instanceHandle()); + + WNDCLASSEX wcex; + + wcex.cbSize = sizeof(WNDCLASSEX); + + wcex.style = CS_DBLCLKS; + wcex.lpfnWndProc = DefWindowProc; + wcex.cbClsExtra = 0; + wcex.cbWndExtra = 0; + wcex.hInstance = Page::instanceHandle(); + wcex.hIcon = 0; + wcex.hCursor = LoadCursor(0, IDC_ARROW); + wcex.hbrBackground = (HBRUSH)COLOR_WINDOW; + wcex.lpszMenuName = 0; + wcex.lpszClassName = kWebPluginViewdowClassName; + wcex.hIconSm = 0; + + return !!RegisterClassEx(&wcex); +} + +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; + } +} + +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.set(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); + } + + // Call the plug-in's window proc. + LRESULT result = ::CallWindowProc(m_pluginWndProc, hWnd, message, wParam, lParam); + + m_isCallingPluginWndProc = false; + + return result; +} + +void PluginView::updatePluginWidget() const +{ + if (!parent()) + return; + + ASSERT(parent()->isFrameView()); + FrameView* frameView = static_cast<FrameView*>(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 (platformPluginWidget() && (m_windowRect != oldWindowRect || m_clipRect != oldClipRect)) { + HRGN rgn; + + 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) { + rgn = ::CreateRectRgn(0, 0, 0, 0); + ::SetWindowRgn(platformPluginWidget(), rgn, FALSE); + } else { + rgn = ::CreateRectRgn(m_clipRect.x(), m_clipRect.y(), m_clipRect.right(), m_clipRect.bottom()); + ::SetWindowRgn(platformPluginWidget(), rgn, TRUE); + } + + if (m_windowRect != oldWindowRect) + ::MoveWindow(platformPluginWidget(), m_windowRect.x(), m_windowRect.y(), m_windowRect.width(), m_windowRect.height(), TRUE); + + if (clipToZeroRect) { + rgn = ::CreateRectRgn(m_clipRect.x(), m_clipRect.y(), m_clipRect.right(), m_clipRect.bottom()); + ::SetWindowRgn(platformPluginWidget(), rgn, TRUE); + } + + setCallingPlugin(false); + } +} + +void PluginView::setFocus() +{ + if (platformPluginWidget()) + SetFocus(platformPluginWidget()); + + Widget::setFocus(); +} + +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(); +} + +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(), imageRect.location()); + context->restore(); +} + +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(false); + setCallingPlugin(true); + bool result = m_plugin->pluginFuncs()->event(m_instance, &npEvent); + setCallingPlugin(false); + + if (shouldPop) + popPopupsEnabledState(); + + return result; +} + +void PluginView::paint(GraphicsContext* context, const IntRect& rect) +{ + if (!m_isStarted) { + // Draw the "missing plugin" image + paintMissingPluginIcon(context, rect); + return; + } + + if (m_isWindowed || context->paintingDisabled()) + return; + + ASSERT(parent()->isFrameView()); + IntRect rectInWindow = static_cast<FrameView*>(parent())->contentsToWindow(frameRect()); + HDC hdc = context->getWindowsContext(rectInWindow, m_isTransparent); + NPEvent npEvent; + + // 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 Qt port we always draw in an offscreen buffer and therefore need to preserve + // the translation set in getWindowsContext. +#if !PLATFORM(QT) + if (!context->inTransparencyLayer()) { + XFORM transform; + GetWorldTransform(hdc, &transform); + transform.eDx = 0; + transform.eDy = 0; + SetWorldTransform(hdc, &transform); + } +#endif + + m_npWindow.type = NPWindowTypeDrawable; + m_npWindow.window = hdc; + + IntPoint p = static_cast<FrameView*>(parent())->contentsToWindow(frameRect().location()); + + WINDOWPOS windowpos; + memset(&windowpos, 0, sizeof(windowpos)); + + windowpos.x = p.x(); + windowpos.y = p.y(); + windowpos.cx = frameRect().width(); + windowpos.cy = frameRect().height(); + + npEvent.event = WM_WINDOWPOSCHANGED; + npEvent.lParam = reinterpret_cast<uint32>(&windowpos); + npEvent.wParam = 0; + + dispatchNPEvent(npEvent); + + setNPWindowRect(frameRect()); + + npEvent.event = WM_PAINT; + npEvent.wParam = reinterpret_cast<uint32>(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); + + context->releaseWindowsContext(hdc, frameRect(), m_isTransparent); +} + +void PluginView::handleKeyboardEvent(KeyboardEvent* event) +{ + NPEvent npEvent; + + npEvent.wParam = event->keyCode(); + + if (event->type() == eventNames().keydownEvent) { + npEvent.event = WM_KEYDOWN; + npEvent.lParam = 0; + } else if (event->type() == eventNames().keyupEvent) { + npEvent.event = WM_KEYUP; + npEvent.lParam = 0x8000; + } + + JSC::JSLock::DropAllLocks dropAllLocks(false); + if (!dispatchNPEvent(npEvent)) + event->setDefaultHandled(); +} + +extern HCURSOR lastSetCursor; +extern bool ignoreNextSetCursor; + +void PluginView::handleMouseEvent(MouseEvent* event) +{ + NPEvent npEvent; + + IntPoint p = static_cast<FrameView*>(parent())->contentsToWindow(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) { + // Focus the plugin + if (Page* page = m_parentFrame->page()) + page->focusController()->setFocusedFrame(m_parentFrame); + m_parentFrame->document()->setFocusedNode(m_element); + 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; + + HCURSOR currentCursor = ::GetCursor(); + + JSC::JSLock::DropAllLocks dropAllLocks(false); + if (!dispatchNPEvent(npEvent)) + event->setDefaultHandled(); + +#if !PLATFORM(QT) + // 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; + lastSetCursor = ::GetCursor(); +#endif +} + +void PluginView::setParent(ScrollView* parent) +{ + Widget::setParent(parent); + + 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); + } + +} + +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; + + IntPoint p = static_cast<FrameView*>(parent())->contentsToWindow(rect.location()); + m_npWindow.x = p.x(); + m_npWindow.y = p.y(); + + m_npWindow.width = rect.width(); + m_npWindow.height = rect.height(); + + m_npWindow.clipRect.left = 0; + m_npWindow.clipRect.top = 0; + m_npWindow.clipRect.right = rect.width(); + m_npWindow.clipRect.bottom = rect.height(); + + if (m_plugin->pluginFuncs()->setwindow) { + JSC::JSLock::DropAllLocks dropAllLocks(false); + setCallingPlugin(true); + m_plugin->pluginFuncs()->setwindow(m_instance, &m_npWindow); + setCallingPlugin(false); + + if (!m_isWindowed) + return; + + ASSERT(platformPluginWidget()); + + WNDPROC currentWndProc = (WNDPROC)GetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC); + if (currentWndProc != PluginViewWndProc) + m_pluginWndProc = (WNDPROC)SetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC, (LONG)PluginViewWndProc); + } +} + +void PluginView::stop() +{ + if (!m_isStarted) + return; + + 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; + + // Unsubclass the window + if (m_isWindowed) { + WNDPROC currentWndProc = (WNDPROC)GetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC); + + if (currentWndProc == PluginViewWndProc) + SetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC, (LONG)m_pluginWndProc); + } + + JSC::JSLock::DropAllLocks dropAllLocks(false); + + // Clear the window + m_npWindow.window = 0; + if (m_plugin->pluginFuncs()->setwindow && !m_plugin->quirks().contains(PluginQuirkDontSetNullWindowHandleOnDestroy)) { + setCallingPlugin(true); + m_plugin->pluginFuncs()->setwindow(m_instance, &m_npWindow); + setCallingPlugin(false); + } + + PluginMainThreadScheduler::scheduler().unregisterPlugin(m_instance); + + // Destroy the plugin + NPSavedData* savedData = 0; + setCallingPlugin(true); + NPError npErr = m_plugin->pluginFuncs()->destroy(m_instance, &savedData); + setCallingPlugin(false); + LOG_NPERROR(npErr); + + if (savedData) { + if (savedData->buf) + NPN_MemFree(savedData->buf); + NPN_MemFree(savedData); + } + + m_instance->pdata = 0; +} + +const char* PluginView::userAgentStatic() +{ + return 0; +} + +const char* PluginView::userAgent() +{ + if (m_plugin->quirks().contains(PluginQuirkWantsMozillaUserAgent)) + return MozillaUserAgent; + + if (m_userAgent.isNull()) + m_userAgent = m_parentFrame->loader()->userAgent(m_url).utf8(); + return m_userAgent.data(); +} + +NPError PluginView::handlePostReadFile(Vector<char>& buffer, uint32 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(), GetFileExInfoStandard, &attrs) == 0) + return NPERR_FILE_NOT_FOUND; + + if (attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + return NPERR_FILE_NOT_FOUND; + + HANDLE fileHandle = CreateFileW(filename.charactersWithNullTermination(), 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; +} + +NPError PluginView::getValueStatic(NPNVariable variable, void* value) +{ + return NPERR_GENERIC_ERROR; +} + +NPError PluginView::getValue(NPNVariable variable, void* value) +{ + switch (variable) { +#if ENABLE(NETSCAPE_PLUGIN_API) + 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 = static_cast<HTMLPlugInElement*>(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; + } +#endif + + case NPNVnetscapeWindow: { + HWND* w = reinterpret_cast<HWND*>(value); + + *w = windowHandleForPlatformWidget(parent() ? parent()->hostWindow()->platformWindow() : 0); + + return NPERR_NO_ERROR; + } + + case NPNVSupportsWindowless: { + NPBool *result = reinterpret_cast<NPBool*>(value); + + *result = TRUE; + + return NPERR_NO_ERROR; + } + + default: + return NPERR_GENERIC_ERROR; + } +} + +void PluginView::invalidateRect(const IntRect& rect) +{ + if (m_isWindowed) { + RECT invalidRect = { rect.x(), rect.y(), rect.right(), rect.bottom() }; + ::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.right(), r.bottom() }; + 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(windowHandleForPlatformWidget(parent() ? parent()->hostWindow()->platformWindow() : 0)); +} + +PluginView::~PluginView() +{ + stop(); + + deleteAllValues(m_requests); + + freeStringArray(m_paramNames, m_paramCount); + freeStringArray(m_paramValues, m_paramCount); + + if (platformPluginWidget()) + DestroyWindow(platformPluginWidget()); + + m_parentFrame->script()->cleanupScriptObjectsForPlugin(this); + + if (m_plugin && !m_plugin->quirks().contains(PluginQuirkDontUnloadPlugin)) + m_plugin->unload(); +} + +void PluginView::init() +{ + if (m_haveInitialized) + return; + m_haveInitialized = true; + + if (!m_plugin) { + ASSERT(m_status == PluginStatusCanNotFindPlugin); + return; + } + + if (!m_plugin->load()) { + m_plugin = 0; + m_status = PluginStatusCanNotLoadPlugin; + return; + } + + if (!start()) { + m_status = PluginStatusCanNotLoadPlugin; + return; + } + + if (m_isWindowed) { + registerPluginView(); + + DWORD flags = WS_CHILD; + if (isSelfVisible()) + flags |= WS_VISIBLE; + + HWND parentWindowHandle = windowHandleForPlatformWidget(m_parentFrame->view()->hostWindow()->platformWindow()); + HWND window = ::CreateWindowEx(0, kWebPluginViewdowClassName, 0, flags, + 0, 0, 0, 0, parentWindowHandle, 0, Page::instanceHandle(), 0); +#if PLATFORM(WIN_OS) && PLATFORM(QT) + 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 PLATFORM(WIN_OS) && PLATFORM(X86_64) && COMPILER(MSVC) + ::SetWindowLongPtrA(platformPluginWidget(), GWLP_WNDPROC, (LONG_PTR)DefWindowProcA); +#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; + } + + if (!m_plugin->quirks().contains(PluginQuirkDeferFirstSetWindowCall)) + setNPWindowRect(frameRect()); + + m_status = PluginStatusLoadedSuccessfully; +} + +} // namespace WebCore diff --git a/WebCore/plugins/wx/PluginDataWx.cpp b/WebCore/plugins/wx/PluginDataWx.cpp new file mode 100644 index 0000000..28e3967 --- /dev/null +++ b/WebCore/plugins/wx/PluginDataWx.cpp @@ -0,0 +1,44 @@ +/* + * 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 "PluginData.h" + +#include "NotImplemented.h" + +namespace WebCore { + +void PluginData::initPlugins() +{ + notImplemented(); +} + +void PluginData::refresh() +{ + notImplemented(); +} + +}; diff --git a/WebCore/plugins/wx/PluginPackageWx.cpp b/WebCore/plugins/wx/PluginPackageWx.cpp new file mode 100644 index 0000000..b93ead2 --- /dev/null +++ b/WebCore/plugins/wx/PluginPackageWx.cpp @@ -0,0 +1,74 @@ +/* + * 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" + +#include "CString.h" +#include "MIMETypeRegistry.h" +#include "NotImplemented.h" +#include "npruntime_impl.h" +#include "PluginDatabase.h" +#include "PluginDebug.h" + +namespace WebCore { + +void PluginPackage::determineQuirks(const String& mimeType) +{ + notImplemented(); +} + +bool PluginPackage::fetchInfo() +{ + notImplemented(); + return false; +} + +bool PluginPackage::load() +{ + notImplemented(); + return false; +} + +unsigned PluginPackage::hash() const +{ + notImplemented(); + + return 0; +} + +bool PluginPackage::equal(const PluginPackage& a, const PluginPackage& b) +{ + notImplemented(); + return false; +} + +int PluginPackage::compareFileVersion(const PlatformModuleVersion& compareVersion) const +{ + notImplemented(); + return 0; +} + +} diff --git a/WebCore/plugins/wx/PluginViewWx.cpp b/WebCore/plugins/wx/PluginViewWx.cpp new file mode 100644 index 0000000..834761c --- /dev/null +++ b/WebCore/plugins/wx/PluginViewWx.cpp @@ -0,0 +1,140 @@ +/* + * 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 "NotImplemented.h" +#include "PluginPackage.h" + +using namespace WTF; + +namespace WebCore { + +void PluginView::setFocus() +{ + notImplemented(); +} + +void PluginView::show() +{ + notImplemented(); +} + +void PluginView::hide() +{ + notImplemented(); +} + +void PluginView::paint(GraphicsContext* context, const IntRect& rect) +{ + notImplemented(); +} + +void PluginView::handleKeyboardEvent(KeyboardEvent* event) +{ + notImplemented(); +} + +void PluginView::handleMouseEvent(MouseEvent* event) +{ + notImplemented(); +} + +void PluginView::setParent(ScrollView* parent) +{ + notImplemented(); +} + +void PluginView::setNPWindowRect(const IntRect& rect) +{ + notImplemented(); +} + +void PluginView::stop() +{ + notImplemented(); +} + +const char* PluginView::userAgent() +{ + notImplemented(); + return 0; +} + +NPError PluginView::handlePostReadFile(Vector<char>& buffer, uint32 len, const char* buf) +{ + notImplemented(); + + return 0; +} + +NPError PluginView::getValue(NPNVariable variable, void* value) +{ + notImplemented(); + return 0; +} + +void PluginView::invalidateRect(NPRect* rect) +{ + notImplemented(); +} + +void PluginView::invalidateRect(const IntRect&) +{ + notImplemented(); +} + +void PluginView::invalidateRegion(NPRegion region) +{ + notImplemented(); +} + +void PluginView::forceRedraw() +{ + notImplemented(); +} + +PluginView::~PluginView() +{ + notImplemented(); +} + +void PluginView::init() +{ + notImplemented(); +} + +void PluginView::setParentVisible(bool) +{ + notImplemented(); +} + +void PluginView::updatePluginWidget() const +{ + notImplemented(); +} + +} // namespace WebCore |