Пример #1
0
ISCORE_LIB_BASE_EXPORT
std::pair<QString, iscore::Plugin_QtInterface*> PluginLoader::loadPlugin(
        const QString &fileName,
        const std::vector<iscore::Plugin_QtInterface*>& availablePlugins)
{
#if !defined(ISCORE_STATIC_QT)
    auto blacklist = pluginsBlacklist();
    QPluginLoader loader {fileName};

    if(QObject* plugin = loader.instance())
    {
        auto iscore_plugin = dynamic_cast<iscore::Plugin_QtInterface*>(plugin);
        if(!iscore_plugin)
        {
            qDebug() << "Warning: plugin"
                     << plugin->metaObject()->className()
                     << "is not an i-score plug-in.";
            return {};
        }

        // Check if the plugin is not already loaded
        auto plug_it =
                find_if(availablePlugins,
                        [&] (iscore::Plugin_QtInterface* obj)
        { return obj->key() == iscore_plugin->key(); });

        if(plug_it != availablePlugins.end())
        {
            qDebug() << "Warning: plugin"
                     << plugin->metaObject()->className()
                     << "was already loaded. Not reloading.";

            return std::make_pair(fileName, nullptr);
        }

        // Check if it is blacklisted
        if(blacklist.contains(fileName))
        {
            plugin->deleteLater();
            return std::make_pair(fileName, nullptr);
        }

        // We can load the plug-in
        return std::make_pair(fileName, iscore_plugin);
    }
    else
    {
        QString s = loader.errorString();
        if(!s.contains("Plugin verification data mismatch") && !s.contains("is not a Qt plugin"))
            qDebug() << "Error while loading" << fileName << ": " << loader.errorString();
        return {};
    }
#endif

    return {};
}
void PluginLoaderThread::run()
{
    if (m_queue.empty() || m_targetThread == 0) {
        qCritical() << "Invalid plugin loading parameters";
        return;
    }

    while (!m_queue.isEmpty()) {
        QPluginLoader * loader = new QPluginLoader ();
        loader->setFileName (m_queue.takeFirst());
        loader->setLoadHints (QLibrary::ExportExternalSymbolsHint);

        if (loader->load()) {
            QMutexLocker locker(&m_mutex);
            if (!m_abort) {
                loader->moveToThread(m_targetThread);
                //loader->setParent(parent());
            }
            else {
                qDebug() << "Plugin loading aborted, exiting loader thread";
                delete loader;
                loader = 0;
                break;
            }
        }
        else {
            qCritical() << "Failed to load plugin:" << loader->errorString();
            delete loader;
            loader = 0;
        }

        Q_EMIT(pluginLoaded(loader, m_queue.isEmpty()));
    }
}
Пример #3
0
void loadMySqlDriver()
{
    QPluginLoader loader;
    loader.setFileName("/opt/qtsdk-2010.04/qt/plugins/sqldrivers/libqsqlmysql.so");
    qDebug()<<loader.load();
    qDebug()<<loader.errorString();
}
Пример #4
0
static QList<VirtualKeyboardFactory *> getVKBFactories()
{
    QList<VirtualKeyboardFactory *> list;
    QString path("/usr/lib/luna");
    qDebug() << "\033[1;33;45m" << Q_FUNC_INFO << "Searching for VKB plugins in" << path << "\033[0m";

    QDir plugindir = QDir(path);
    QStringList files = plugindir.entryList(QDir::Files);
    qDebug() << "\033[1;33;45m" << Q_FUNC_INFO << "Found" << files.count() << "files" << "\033[0m";

    QPluginLoader loader;
    QStringList::const_iterator it = files.constBegin();

    while (it != files.constEnd()) {
        qDebug() << "\033[1;33;40m" << Q_FUNC_INFO << "Checking" << (*it) << "\033[0m";
        loader.setFileName(plugindir.absoluteFilePath(*it));

        VirtualKeyboardFactory *factory =
            qobject_cast<VirtualKeyboardFactory *>(loader.instance());

        if (factory) {
            qDebug() << "\033[1;32;40m" << Q_FUNC_INFO << "Loaded plugin"
                     << (*it) << "successfully" << "\033[0m";
            list.append(factory);
        } else {
            qWarning() << "\033[1;31;40m" << Q_FUNC_INFO << "Failed to load"
                       << (*it) << "\n" << loader.errorString() << "\033[0m";

        }

        ++it;
    }

    return list;
}
Пример #5
0
void PluginManager::loadPlugin(QString const & path)
{
    qDebug() << "Load plugin: " << path;

    Q_ASSERT(mPluginLoaders.find(path) == mPluginLoaders.end());

    QPluginLoader * loader = new QPluginLoader(path, this);

    if (!loader->load())
    {
        qDebug() << loader->errorString();
        qDebug() << QString("Can't load plugin '%1'").arg(path);
    }

    // process instances
    PluginInterface *plugInterface = qobject_cast<PluginInterface*>(loader->instance());
    if (plugInterface != 0)
    {
        mPluginLoaders[path] = loader;
        processLoadPlugin(plugInterface);
    }else
    {
        delete loader;
        qDebug() << QString("There are no plugin interface in '%1'").arg(path);
    }

}
void AbstractPluginLoader::loadPlugins(const QRegExp& fileRx, QVector<QString>* errors)
{
  Q_D(AbstractPluginLoader);
  const QDir pluginsFolder(this->loadingFolder());
  QStringList entries(pluginsFolder.entryList(QDir::Files));
  foreach (const QString& entry, entries) {
    if (fileRx.indexIn(entry) != -1 && ::isLibrary(entry)) {
      // Try to load the plugin
#ifdef DEBUG_ABSTRACT_PLUGIN_LOADER
      qDebug() << "try to load" << entry;
#endif // DEBUG_ABSTRACT_PLUGIN_LOADER
      QPluginLoader* pluginLoader = new QPluginLoader(pluginsFolder.absoluteFilePath(entry));
      QObject* plugin = pluginLoader->instance();
      // Is the plugin compatible ?
      if (this->isPluginCompatible(plugin)) {
        d->m_plugins.append(plugin);
        d->m_pluginLoaders.append(pluginLoader);
        d->m_pluginFilenames.insert(plugin, entry);
      }
      else {
#ifdef DEBUG_ABSTRACT_PLUGIN_LOADER
        qDebug() << "  not added";
#endif // DEBUG_ABSTRACT_PLUGIN_LOADER
        if (errors != NULL)
          //: %1 holds the path to a plugin (DLL)
          //: %2 holds an error description
          errors->append(QObject::tr("Failed to load plugin (maybe wrong interface) %1 : %2")
                         .arg(pluginLoader->fileName())
                         .arg(pluginLoader->errorString()));
        pluginLoader->unload();
        delete pluginLoader;
      } // end if (this->isPluginCompatible(plugin))
    } // end if (fileRx.indexIn(entry) != -1)
  } // end foreach ()
}
Пример #7
0
void suiPluginManager::loadPlugin(const QString &fileName)
{
    qDebug() << "Load plugin: " << fileName;

    if (mPluginLoaders.find(fileName) != mPluginLoaders.end())
        SuiExcept(SuiExceptionDuplicateItem,
                  QString("Plugin '%1' already loaded").arg(fileName),
                  "void suiPluginManager::loadPlugin(const QString &fileName)");

    QPluginLoader *loader = new QPluginLoader(fileName, this);

    if (!loader->load())
    {
        qDebug() << loader->errorString();
        SuiExcept(SuiExceptionInternalError,
                  QString("Can't load plugin '%1'").arg(fileName),
                  "void suiPluginManager::loadPlugin(const QString &fileName)");
    }

    // process instances
    UiPluginInterface *plugInterface = qobject_cast<UiPluginInterface*>(loader->instance());
    if (plugInterface != 0)
    {
        mPluginLoaders[fileName] = loader;
        processLoadPlugin(plugInterface);
    }else
    {
        delete loader;
        SuiExcept(SuiExceptionInternalError,
                  QString("There are no plugin interface in '%1'").arg(fileName),
                  "void suiPluginManager::loadPlugin(const QString &fileName)");
    }
}
Пример #8
0
void GLWidget::loadPlugins(const QStringList& list) {
    QStringList::ConstIterator it = list.constBegin();
    while(it != list.constEnd()) 
    {
        QString name = *it;
        QPluginLoader *loader = new QPluginLoader(name);
        if (! loader->load()) {
        	  qDebug() << "Could not load plugin " << name << "\n";
                qDebug() << loader->errorString() << "\n";

	        }
        if (loader->isLoaded()) 
        {
            qDebug() << "Loaded plugin: " << loader->fileName(); // << 	endl;
            QObject *plugin = loader->instance();
            if (plugin) 
            {
                plugins.push_back(loader); 
                BasicPlugin *plugin = qobject_cast<BasicPlugin *>(loader->instance());
                // initialize plugin
                if (plugin)
                {
                    plugin->setWidget(this);
                    plugin->setArgs(mainArgs);
                    plugin->onPluginLoad();
                    if (plugin->drawScene()) // overrides drawScene?
                        drawPlugin = plugin;
                }
            }
        }
        else 
        {
            qDebug() << "Load error: " << name << endl;
	        delete loader;
        }
        
        ++it;
    }

    // make sure all plugins know about the latest plugin that overrides drawScene
    for (unsigned int i=0; i<plugins.size(); ++i)
    {
        BasicPlugin *plugin = qobject_cast<BasicPlugin *>(plugins[i]->instance());
        if (plugin)
            plugin->setDrawPlugin(drawPlugin);
        else
        {
            qDebug() << "Error: the plugin must implement the BasicPlugin interface" << endl <<
            " Example: " << endl << 
            "   Q_INTERFACES(BasicPlugin)" << endl;
        }
    }

    resetCamera();
}
Пример #9
0
QObject *PluginLoader::createForName(const QString &name)
{
    if (!mPluginInfos.contains(name)) {
        qCWarning(AKONADICORE_LOG) << "plugin name \"" << name << "\" is unknown to the plugin loader." << endl;
        return 0;
    }

    PluginMetaData &info = mPluginInfos[name];

    //First try to load it staticly
    foreach (QObject *plugin, QPluginLoader::staticInstances()) {
        if (QLatin1String(plugin->metaObject()->className()) == info.className) {
            info.loaded = true;
            return plugin;
            break;
        }
    }

    if (!info.loaded) {
        QPluginLoader *loader = new QPluginLoader(info.library);
        if (loader->fileName().isEmpty()) {
            qCWarning(AKONADICORE_LOG) << loader->errorString();
            delete loader;
            return 0;
        }

        mPluginLoaders.insert(name, loader);
        info.loaded = true;
    }

    QPluginLoader *loader = mPluginLoaders.value(name);
    Q_ASSERT(loader);

    QObject *object = loader->instance();
    if (!object) {
        qCWarning(AKONADICORE_LOG) << "unable to load plugin" << info.library << "for plugin name" << name << ".";
        qCWarning(AKONADICORE_LOG) << "Error was:\"" << loader->errorString() << "\".";
        return 0;
    }

    return object;
}
Пример #10
0
void PluginManagerPrivate::loadPlugins()
{
    if (m_pluginsLoaded)
    {
        return;
    }

    QTime t;
    t.start();
    mDebug() << "Starting to load Plugins.";

    QStringList pluginFileNameList = MarbleDirs::pluginEntryList( "", QDir::Files );

    MarbleDirs::debug();

    Q_ASSERT( m_renderPluginTemplates.isEmpty() );
    Q_ASSERT( m_positionProviderPluginTemplates.isEmpty() );
    Q_ASSERT( m_searchRunnerPlugins.isEmpty() );
    Q_ASSERT( m_reverseGeocodingRunnerPlugins.isEmpty() );
    Q_ASSERT( m_routingRunnerPlugins.isEmpty() );
    Q_ASSERT( m_parsingRunnerPlugins.isEmpty() );

    foreach( const QString &fileName, pluginFileNameList ) {
        // mDebug() << fileName << " - " << MarbleDirs::pluginPath( fileName );
        QString const path = MarbleDirs::pluginPath( fileName );
        QPluginLoader* loader = new QPluginLoader( path );

        QObject * obj = loader->instance();

        if ( obj ) {
            bool isPlugin = appendPlugin<RenderPlugin, RenderPluginInterface>
                       ( obj, loader, m_renderPluginTemplates );
            isPlugin = isPlugin || appendPlugin<PositionProviderPlugin, PositionProviderPluginInterface>
                       ( obj, loader, m_positionProviderPluginTemplates );
            isPlugin = isPlugin || appendPlugin<SearchRunnerPlugin, SearchRunnerPlugin>
                       ( obj, loader, m_searchRunnerPlugins ); // intentionally T==U
            isPlugin = isPlugin || appendPlugin<ReverseGeocodingRunnerPlugin, ReverseGeocodingRunnerPlugin>
                       ( obj, loader, m_reverseGeocodingRunnerPlugins ); // intentionally T==U
            isPlugin = isPlugin || appendPlugin<RoutingRunnerPlugin, RoutingRunnerPlugin>
                       ( obj, loader, m_routingRunnerPlugins ); // intentionally T==U
            isPlugin = isPlugin || appendPlugin<ParseRunnerPlugin, ParseRunnerPlugin>
                       ( obj, loader, m_parsingRunnerPlugins ); // intentionally T==U
            if ( !isPlugin ) {
                qWarning() << "Ignoring the following plugin since it couldn't be loaded:" << path;
                mDebug() << "Plugin failure:" << path << "is a plugin, but it does not implement the "
                        << "right interfaces or it was compiled against an old version of Marble. Ignoring it.";
                delete loader;
            }
        } else {
            qWarning() << "Ignoring to load the following file since it doesn't look like a valid Marble plugin:" << path << endl
                       << "Reason:" << loader->errorString();
            delete loader;
        }
    }
Пример #11
0
void PluginManagerPrivate::loadPlugins()
{
    if (m_pluginsLoaded)
    {
        return;
    }

    QTime t;
    t.start();
    mDebug() << "Starting to load Plugins.";

    QStringList pluginFileNameList = MarbleDirs::pluginEntryList( "", QDir::Files );

    MarbleDirs::debug();

    qDeleteAll( m_renderPluginTemplates );
    m_renderPluginTemplates.clear();

    qDeleteAll( m_networkPluginTemplates );
    m_networkPluginTemplates.clear();

    qDeleteAll( m_positionProviderPluginTemplates );
    m_positionProviderPluginTemplates.clear();

    // No need to delete runner plugins

    foreach( const QString &fileName, pluginFileNameList ) {
        // mDebug() << fileName << " - " << MarbleDirs::pluginPath( fileName );
        QString const path = MarbleDirs::pluginPath( fileName );
        QPluginLoader* loader = new QPluginLoader( path );

        QObject * obj = loader->instance();

        if ( obj ) {
            bool isPlugin = appendPlugin<RenderPlugin, RenderPluginInterface>
                       ( obj, loader, m_renderPluginTemplates );
            isPlugin = isPlugin || appendPlugin<NetworkPlugin, NetworkPluginInterface>
                       ( obj, loader, m_networkPluginTemplates );
            isPlugin = isPlugin || appendPlugin<PositionProviderPlugin, PositionProviderPluginInterface>
                       ( obj, loader, m_positionProviderPluginTemplates );
            isPlugin = isPlugin || appendPlugin<RunnerPlugin, RunnerPlugin>
                       ( obj, loader, m_runnerPlugins ); // intentionally T==U
            if ( !isPlugin ) {
                mDebug() << "Plugin failure:" << fileName << "is a plugin, but it does not implement the "
                        << "right interfaces or it was compiled against an old version of Marble. Ignoring it.";
                delete loader;
            }
        } else {
            mDebug() << "Plugin failure:" << fileName << "is not a valid Marble Plugin:"
                     << loader->errorString();
        }
    }
Пример #12
0
 // looking for dynamic plugins
 foreach(const QFileInfo & fileName, files)
 {
     emit log((int)LogDebug, MODULENAME, QString("Loading plugin: %1").arg(fileName.fileName()), "");
     QPluginLoader loader;
     loader.setLoadHints(QLibrary::ResolveAllSymbolsHint|QLibrary::ExportExternalSymbolsHint);
     loader.setFileName( fileName.absoluteFilePath());
     if (!loader.load())
     {
         qCritical() << loader.errorString();
         continue;
     }
     QObject *plugin = loader.instance();
     if (plugin && qobject_cast<PropertyInterface*>(plugin))
         m_plugins.push_back(qobject_cast<PropertyInterface*>(plugin));
     else
         emit log((int)LogWarning, MODULENAME, QString("It\'s not a PropertyEditor plugin: %1").arg(fileName.fileName()), "");
 }
void QAudioPluginLoader::load()
{
    if (!m_plugins.isEmpty())
        return;

    QStringList plugins = pluginList();
    for (int i=0; i < plugins.count(); i++) {
        QPluginLoader* loader = new QPluginLoader(plugins.at(i));
        QObject *o = loader->instance();
        if (o != 0 && o->qt_metacast(m_iid) != 0)
            m_plugins.append(loader);
        else {
            qWarning() << "QAudioPluginLoader: Failed to load plugin: "
                << plugins.at(i) << loader->errorString();
        }
    }
}
Пример #14
0
bool EditorManager::unloadPlugin(QString const &pluginName)
{
	QPluginLoader *loader = mLoaders[mPluginFileName[pluginName]];
	if (loader != NULL) {
		mLoaders.remove(mPluginFileName[pluginName]);
		mPluginIface.remove(pluginName);
		mPluginFileName.remove(pluginName);
		mPluginsLoaded.removeAll(pluginName);
		if (!loader->unload()) {
			QMessageBox::warning(NULL, tr("error"), tr("Plugin unloading failed: ") + loader->errorString());
			delete loader;
			return false;
		}
		delete loader;
		return true;
	}
	return false;
}
Пример #15
0
QString PluginManagerImplementation::unloadPlugin(QString const &pluginName)
{
	QPluginLoader *loader = mLoaders[pluginName];

	if (loader) {
		mLoaders.remove(pluginName);

		if (!loader->unload()) {
			QString const error = loader->errorString();
			delete loader;
			return error;
		}

		delete loader;
		return QString();
	}

	return QString("Plugin was not found");
}
Пример #16
0
PluginInterface *Agros2D::loadPlugin(const QString &pluginName)
{
    QPluginLoader *loader = NULL;

#ifdef Q_WS_X11
    if (QFile::exists(QString("%1/libs/libagros2d_plugin_%2.so").arg(datadir()).arg(pluginName)))
        loader = new QPluginLoader(QString("%1/libs/libagros2d_plugin_%2.so").arg(datadir()).arg(pluginName));

    if (!loader)
    {
        if (QFile::exists(QString("/usr/local/lib/libagros2d_plugin_%1.so").arg(pluginName)))
            loader = new QPluginLoader(QString("/usr/local/lib/libagros2d_plugin_%1.so").arg(pluginName));
        else if (QFile::exists(QString("/usr/lib/libagros2d_plugin_%1.so").arg(pluginName)))
            loader = new QPluginLoader(QString("/usr/lib/libagros2d_plugin_%1.so").arg(pluginName));
    }
#endif

#ifdef Q_WS_WIN
    if (QFile::exists(QString("%1/libs/agros2d_plugin_%2.dll").arg(datadir()).arg(pluginName)))
        loader = new QPluginLoader(QString("%1/libs/agros2d_plugin_%2.dll").arg(datadir()).arg(pluginName));
#endif

    if (!loader)
    {
        throw AgrosPluginException(QObject::tr("Could not find 'agros2d_plugin_%1'").arg(pluginName));
    }

    if (!loader->load())
    {
        QString error = loader->errorString();
        delete loader;
        throw AgrosPluginException(QObject::tr("Could not load 'agros2d_plugin_%1' (%2)").arg(pluginName).arg(error));
    }

    assert(loader->instance());
    PluginInterface *plugin = qobject_cast<PluginInterface *>(loader->instance());

    // loader->unload();
    delete loader;

    return plugin;
}
Пример #17
0
bool EditorManager::loadPlugin(QString const &pluginName)
{
	QPluginLoader *loader = new QPluginLoader(mPluginsDir.absoluteFilePath(pluginName));
	loader->load();
	QObject *plugin = loader->instance();

	if (plugin) {
		EditorInterface *iEditor = qobject_cast<EditorInterface *>(plugin);
		if (iEditor) {
			mPluginsLoaded += iEditor->id();
			mPluginFileName.insert(iEditor->id(), pluginName);
			mPluginIface[iEditor->id()] = iEditor;
			mLoaders.insert(pluginName, loader);
			return true;
		}
	}

	QMessageBox::warning(NULL, tr("error"), tr("Plugin loading failed: ") + loader->errorString());
	loader->unload();
	delete loader;
	return false;
}
Пример #18
0
// read forms
void readCustomForms(QMenu *menu)
{
    QDir dir(datadir() + "/libs/");

    QStringList filter;
    filter << "*agros2d_forms_*";
    QStringList list = dir.entryList(filter);

    foreach (QString filename, list)
    {
        QString fn = QString("%1/%2").arg(dir.absolutePath()).arg(filename);
        if (QFile::exists(fn))
        {
            QPluginLoader *loader = new QPluginLoader(fn);

            if (!loader)
            {
                throw AgrosException(QObject::tr("Could not find '%1'").arg(fn));
            }


            if (!loader->load())
            {
                qDebug() << loader->errorString();
                delete loader;
                throw AgrosException(QObject::tr("Could not load '%1'. %2").arg(fn).arg(loader->errorString()));
            }

            assert(loader->instance());
            FormInterface *form = qobject_cast<FormInterface *>(loader->instance());
            delete loader;

            if (form)
            {
                qDebug() << QString("Form '%1' loaded.").arg(form->formId());
                menu->addAction(form->action());
            }
        }
    }
Пример #19
0
EditorManager::EditorManager(QObject *parent) : QObject(parent)
{
	mPluginsDir = QDir(qApp->applicationDirPath());

	while (!mPluginsDir.isRoot() && !mPluginsDir.entryList(QDir::Dirs).contains("plugins")) {
		mPluginsDir.cdUp();
	}

	mPluginsDir.cd("plugins");

	foreach (QString const &fileName, mPluginsDir.entryList(QDir::Files)) {
		QPluginLoader *loader  = new QPluginLoader(mPluginsDir.absoluteFilePath(fileName));
		QObject *plugin = loader->instance();

		if (plugin) {
			EditorInterface *iEditor = qobject_cast<EditorInterface *>(plugin);
			if (iEditor) {
				mPluginsLoaded += iEditor->id();
				mPluginFileName.insert(iEditor->id(), fileName);
				mPluginIface[iEditor->id()] = iEditor;
				mLoaders.insert(fileName, loader);
			} else {
				// TODO: Just does not work under Linux. Seems to be memory corruption when
				// loading, unloading, and then loading .so file again.
				// To reproduce, uncomment this, build VisualInterpreter, and try to launch QReal.
				// With some tool plugins, like MetaEditorSupport or Exterminatus, works fine,
				// also works fine on Windows. Investigation required.
				// loader->unload();
				delete loader;
			}
		} else {
			qDebug() << "Plugin loading failed: " << loader->errorString();
			loader->unload();
			delete loader;
		}
	}
}
Пример #20
0
QPair<QObject *, QString> PluginManagerImplementation::pluginLoadedByName(QString const &pluginName)
{
	QPluginLoader *loader = new QPluginLoader(mPluginsDir.absoluteFilePath(pluginName));
	loader->load();
	QObject *plugin = loader->instance();

	if (plugin) {
		mFileNameAndPlugin.insert(pluginName, plugin);
		return qMakePair(plugin, QString());
	}

	QString const loaderError = loader->errorString();

	// Unloading of plugins is currently (Qt 5.3) broken due to a bug in metatype system: calling Q_DECLARE_METATYPE
	// from plugin registers some data from plugin address space in Qt metatype system, which is not being updated
	// when plugin is unloaded and loaded again. Any subsequent calls to QVariant or other template classes/methods
	// which use metainformation will result in a crash. It is likely (but not verified) that qRegisterMetaType leads
	// to the same issue. Since we can not guarantee that plugin does not use Q_DECLARE_METATYPE or qRegisterMetaType
	// we shall not unload plugin at all, to be safe rather than sorry.
	//
	// But it seems also that metainformation gets deleted BEFORE plugins are unloaded on application exit, so we can
	// not call any metainformation-using code in destructors that get called on unloading. Since Qt classes themselves
	// are using such calls (QGraphicsViewScene, for example), random crashes on exit may be a symptom of this problem.
	//
	// EditorManager is an exception, because it really needs to unload editor plugins, to be able to load new versions
	// compiled by metaeditor. Editor plugins are generated, so we can guarantee to some extent that there will be no
	// metatype registrations.
	//
	// See:
	// http://stackoverflow.com/questions/19234703/using-q-declare-metatype-with-a-dll-that-may-be-loaded-multiple-times
	// (and http://qt-project.org/forums/viewthread/35587)
	// https://bugreports.qt-project.org/browse/QTBUG-32442

	delete loader;
	return qMakePair(nullptr, loaderError);
}
Пример #21
0
void tst_QPluginLoader::errorString()
{
#if defined(Q_OS_WINCE)
    // On WinCE we need an QCoreApplication object for current dir
    int argc = 0;
    QCoreApplication app(argc,0);
#endif
    const QString unknown(QLatin1String("Unknown error"));

    {
    QPluginLoader loader; // default constructed
    bool loaded = loader.load();
#ifdef SHOW_ERRORS
    qDebug() << loader.errorString();
#endif
    QCOMPARE(loaded, false);
    QCOMPARE(loader.errorString(), unknown);

    QObject *obj = loader.instance();
#ifdef SHOW_ERRORS
    qDebug() << loader.errorString();
#endif
    QCOMPARE(obj, static_cast<QObject*>(0));
    QCOMPARE(loader.errorString(), unknown);

    bool unloaded = loader.unload();
#ifdef SHOW_ERRORS
    qDebug() << loader.errorString();
#endif
    QCOMPARE(unloaded, false);
    QCOMPARE(loader.errorString(), unknown);
    }
    {
    QPluginLoader loader( sys_qualifiedLibraryName("tst_qpluginloaderlib"));     //not a plugin
    bool loaded = loader.load();
#ifdef SHOW_ERRORS
    qDebug() << loader.errorString();
#endif
    QCOMPARE(loaded, false);
    QVERIFY(loader.errorString() != unknown);

    QObject *obj = loader.instance();
#ifdef SHOW_ERRORS
    qDebug() << loader.errorString();
#endif
    QCOMPARE(obj, static_cast<QObject*>(0));
    QVERIFY(loader.errorString() != unknown);

    bool unloaded = loader.unload();
#ifdef SHOW_ERRORS
    qDebug() << loader.errorString();
#endif
    QCOMPARE(unloaded, false);
    QVERIFY(loader.errorString() != unknown);
    }

    {
    QPluginLoader loader( sys_qualifiedLibraryName("nosuchfile"));     //not a file
    bool loaded = loader.load();
#ifdef SHOW_ERRORS
    qDebug() << loader.errorString();
#endif
    QCOMPARE(loaded, false);
    QVERIFY(loader.errorString() != unknown);

    QObject *obj = loader.instance();
#ifdef SHOW_ERRORS
    qDebug() << loader.errorString();
#endif
    QCOMPARE(obj, static_cast<QObject*>(0));
    QVERIFY(loader.errorString() != unknown);

    bool unloaded = loader.unload();
#ifdef SHOW_ERRORS
    qDebug() << loader.errorString();
#endif
    QCOMPARE(unloaded, false);
    QVERIFY(loader.errorString() != unknown);
    }

#if !defined Q_OS_WIN && !defined Q_OS_MAC && !defined Q_OS_HPUX && !defined Q_OS_SYMBIAN && !defined Q_OS_QNX
    {
    QPluginLoader loader( sys_qualifiedLibraryName("almostplugin"));     //a plugin with unresolved symbols
    loader.setLoadHints(QLibrary::ResolveAllSymbolsHint);
    QCOMPARE(loader.load(), false);
#ifdef SHOW_ERRORS
    qDebug() << loader.errorString();
#endif
    QVERIFY(loader.errorString() != unknown);

    QCOMPARE(loader.instance(), static_cast<QObject*>(0));
#ifdef SHOW_ERRORS
    qDebug() << loader.errorString();
#endif
    QVERIFY(loader.errorString() != unknown);

    QCOMPARE(loader.unload(), false);
#ifdef SHOW_ERRORS
    qDebug() << loader.errorString();
#endif
    QVERIFY(loader.errorString() != unknown);
    }
#endif

    {
    QPluginLoader loader( sys_qualifiedLibraryName("theplugin"));     //a plugin
    QCOMPARE(loader.load(), true);
    QCOMPARE(loader.errorString(), unknown);

    QVERIFY(loader.instance() !=  static_cast<QObject*>(0));
    QCOMPARE(loader.errorString(), unknown);

    // Make sure that plugin really works
    PluginInterface* theplugin = qobject_cast<PluginInterface*>(loader.instance());
    QString pluginName = theplugin->pluginName();
    QCOMPARE(pluginName, QLatin1String("Plugin ok"));

    QCOMPARE(loader.unload(), true);
    QCOMPARE(loader.errorString(), unknown);
    }
}
Пример #22
0
void PluginManager::loadAllPlugins(EnvisionManager& envisionManager)
{
	int lastCountLoaded = -1;

	// Holds the ids of plugins which are not yet loaded.
	QStringList plugins;
	for (auto p_meta : pluginMetaData)
		plugins.append(p_meta.id);

	QTextStream out(stdout);

	while ( lastCountLoaded != loadedPlugins.length() && loadedPlugins.length() < pluginMetaData.length() )
	{
		lastCountLoaded = loadedPlugins.length();

		for (int i = plugins.length() - 1; i >= 0; i--)
		{
			QList<PluginDependency> depList = idToMetaDataMap.value(plugins.at(i))->dependencies;

			bool allDependenciesLoaded = true;
			for (QList<PluginDependency>::iterator dep = depList.begin(); dep != depList.end(); dep++)
			{
				// Check if this dependency is already loaded
				if ( idToPluginLoaderMap.contains(dep->id) == false )
				{
					allDependenciesLoaded = false;
					break;
				}

				// Check if the version of the non-dependent plugin matches the version the current plugin depends on
				if ( !idToMetaDataMap.value(dep->id)->version.startsWith(dep->majorVersion + ".", Qt::CaseSensitive) )
					throw EnvisionException("Plugin " + plugins.at(i) + " depends on version " + dep->majorVersion
							+ " of " + dep->id + " but a different version is installed.");
			}

			if ( allDependenciesLoaded )
			{
				out << "Loading plug-in " << plugins.at(i) << "... " << endl;

				QPluginLoader* plugin = new QPluginLoader(pluginsDir.absoluteFilePath(getLibraryFileName(plugins.at(i))));
				plugin->setLoadHints(QLibrary::ExportExternalSymbolsHint);

				plugin->load();

				if ( plugin->isLoaded() == false )
					throw EnvisionException("Could not load plugin: " + plugin->errorString());

				EnvisionPlugin* p = qobject_cast<EnvisionPlugin*> (plugin->instance());
				p->initialize(envisionManager);

				out << plugins.at(i) << " loaded OK" << endl;

				loadedPlugins.append(plugin);
				idToPluginLoaderMap.insert(plugins.at(i), plugin);
				plugins.removeAt(i);
			}
		}
	}

	// Check if there are any plug-ins with unmet dependencies
	if (plugins.size() > 0)
	{
		out<< "Warning: The following plug-ins have not been loaded because their dependencies are not satisfied" << endl;
		for (int i = 0; i< plugins.size(); ++i) out << "  " << plugins.at(i) << endl;
	}
	else out << "All plug-ins loaded." << endl;
}
Пример #23
0
void PluginManagerPrivate::loadPlugins()
{
    if (m_pluginsLoaded)
    {
        return;
    }

    QTime t;
    t.start();
    mDebug() << "Starting to load Plugins.";

    QStringList pluginFileNameList = MarbleDirs::pluginEntryList( "", QDir::Files );

    MarbleDirs::debug();

    Q_ASSERT( m_renderPluginTemplates.isEmpty() );
    Q_ASSERT( m_positionProviderPluginTemplates.isEmpty() );
    Q_ASSERT( m_searchRunnerPlugins.isEmpty() );
    Q_ASSERT( m_reverseGeocodingRunnerPlugins.isEmpty() );
    Q_ASSERT( m_routingRunnerPlugins.isEmpty() );
    Q_ASSERT( m_parsingRunnerPlugins.isEmpty() );

    bool foundPlugin = false;
    foreach( const QString &fileName, pluginFileNameList ) {
        QString const baseName = QFileInfo(fileName).baseName();
        if (!m_whitelist.isEmpty() && !m_whitelist.contains(baseName)) {
            mDebug() << "Ignoring non-whitelisted plugin " << fileName;
            continue;
        }
        if (m_blacklist.contains(baseName)) {
            mDebug() << "Ignoring blacklisted plugin " << fileName;
            continue;
        }

        // mDebug() << fileName << " - " << MarbleDirs::pluginPath( fileName );
        QString const path = MarbleDirs::pluginPath( fileName );
#ifdef Q_OS_ANDROID
        QFileInfo targetFile( path );
        if ( !m_pluginPaths.contains( targetFile.canonicalFilePath() ) ) {
            // @todo Delete the file here?
            qDebug() << "Ignoring file " << path << " which is not among the currently installed plugins";
            continue;
        }
#endif
        QPluginLoader* loader = new QPluginLoader( path );

        QObject * obj = loader->instance();

        if ( obj ) {
            bool isPlugin = appendPlugin<RenderPlugin, RenderPluginInterface>
                       ( obj, loader, m_renderPluginTemplates );
            isPlugin = isPlugin || appendPlugin<PositionProviderPlugin, PositionProviderPluginInterface>
                       ( obj, loader, m_positionProviderPluginTemplates );
            isPlugin = isPlugin || appendPlugin<SearchRunnerPlugin, SearchRunnerPlugin>
                       ( obj, loader, m_searchRunnerPlugins ); // intentionally T==U
            isPlugin = isPlugin || appendPlugin<ReverseGeocodingRunnerPlugin, ReverseGeocodingRunnerPlugin>
                       ( obj, loader, m_reverseGeocodingRunnerPlugins ); // intentionally T==U
            isPlugin = isPlugin || appendPlugin<RoutingRunnerPlugin, RoutingRunnerPlugin>
                       ( obj, loader, m_routingRunnerPlugins ); // intentionally T==U
            isPlugin = isPlugin || appendPlugin<ParseRunnerPlugin, ParseRunnerPlugin>
                       ( obj, loader, m_parsingRunnerPlugins ); // intentionally T==U
            if ( !isPlugin ) {
                qWarning() << "Ignoring the following plugin since it couldn't be loaded:" << path;
                mDebug() << "Plugin failure:" << path << "is a plugin, but it does not implement the "
                        << "right interfaces or it was compiled against an old version of Marble. Ignoring it.";
                delete loader;
            } else {
                foundPlugin = true;
            }
        } else {
            qWarning() << "Ignoring to load the following file since it doesn't look like a valid Marble plugin:" << path << endl
                       << "Reason:" << loader->errorString();
            delete loader;
        }
    }
Пример #24
0
void Core::ExtensionLoad()
{
    QString path_ = Configuration::GetExtensionsRootPath();
    if (QDir().exists(path_))
    {
        QDir d(path_);
        QStringList extensions = d.entryList();
        int xx = 0;
        while (xx < extensions.count())
        {
            QString name = extensions.at(xx).toLower();
            if (name.endsWith(".so") || name.endsWith(".dll"))
            {
                name = QString(path_) + extensions.at(xx);
                QPluginLoader *extension = new QPluginLoader(name);
                if (extension->load())
                {
                    QObject* root = extension->instance();
                    if (root)
                    {
                        iExtension *interface = qobject_cast<iExtension*>(root);
                        if (!interface)
                        {
                            Huggle::Syslog::HuggleLogs->Log("Unable to cast the library to extension");
                        }else
                        {
                            if (interface->RequestNetwork())
                            {
                                interface->Networking = Query::NetworkManager;
                            }
                            if (interface->RequestConfiguration())
                            {
                                interface->Configuration = Configuration::HuggleConfiguration;
                            }
                            if (interface->RequestCore())
                            {
                                interface->HuggleCore = Core::HuggleCore;
                            }
                            if (interface->Register())
                            {
                                Core::Extensions.append(interface);
                                Huggle::Syslog::HuggleLogs->Log("Successfully loaded: " + extensions.at(xx));
                            }
                            else
                            {
                                Huggle::Syslog::HuggleLogs->Log("Unable to register: " + extensions.at(xx));
                            }
                        }
                    }
                } else
                {
                    Huggle::Syslog::HuggleLogs->Log("Failed to load (reason: " + extension->errorString() + "): " + extensions.at(xx));
                    delete extension;
                }
            } else if (name.endsWith(".py"))
            {
#ifdef PYTHONENGINE
                name = QString(path_) + extensions.at(xx);
                if (Core::Python->LoadScript(name))
                {
                    Huggle::Syslog::HuggleLogs->Log("Loaded python script: " + name);
                } else
                {
                    Huggle::Syslog::HuggleLogs->Log("Failed to load a python script: " + name);
                }
#endif
            }
            xx++;
        }
    } else
    {
        Huggle::Syslog::HuggleLogs->Log("There is no extensions folder, skipping load");
    }
    Huggle::Syslog::HuggleLogs->Log("Extensions: " + QString::number(Core::Extensions.count()));
}
Пример #25
0
void TransferEnginePrivate::enabledPluginsCheck()
{
    Q_Q(TransferEngine);
    if (m_fileWatcherTimer->isActive()) {
        m_fileWatcherTimer->stop();
    }

    if (m_infoObjects.count() > 0) {
        qWarning() << Q_FUNC_INFO << "Already quering account info" << m_infoObjects.count();
        return;
    }

    // First clear old data
    m_enabledPlugins.clear();
    qDeleteAll(m_infoObjects);
    m_infoObjects.clear();

    QPluginLoader loader;
    loader.setLoadHints(QLibrary::ResolveAllSymbolsHint | QLibrary::ExportExternalSymbolsHint);

    // Handle the case if all the plugins have been removed.
    QStringList plugins = pluginList();
    if (plugins.isEmpty()) {
        emit q->transferMethodListChanged();
        return;
    }

    // We have plugins
    Q_FOREACH(QString plugin, plugins) {
        loader.setFileName(plugin);
        TransferPluginInterface *interface =
                qobject_cast<TransferPluginInterface*>(loader.instance());

        if (interface && interface->enabled()) {

            TransferPluginInfo *info = interface->infoObject();
            if (!info) {
                qWarning() << Q_FUNC_INFO << "NULL Info object!";
                continue;
            }

            if (info->ready()) {
                if (info->info().count() > 0) {
                    m_enabledPlugins << info->info();
                } else {
                    // Plugin has nothing to provide, just ignore it
                    delete info;
                }
            } else {
                // These object will be cleaned in pluginInfoReady() slot.
                m_infoObjects << info;
                connect(info, SIGNAL(infoReady()), this, SLOT(pluginInfoReady()));
                connect(info, SIGNAL(infoError(QString)), this, SLOT(pluginInfoError(QString)));
                info->query();
            }
        }

        if (!interface) {
            qWarning() << Q_FUNC_INFO << loader.errorString();
        }
    }
/*!
 * This function will do the basic loading/unloading tests on the applet.
 */
void
Ft_AppletLoader::DoAppletTest (const char *soname, bool hasBrief)
{
    QPluginLoader loader;

    loader.setFileName (QString (APPLET_PATH) + QString (soname));
    loader.setLoadHints (QLibrary::ResolveAllSymbolsHint);

    /*
     * Getting the DcpAppletIf applet interface object. Checking if the applet
     * loaded, the type of the applet interface is right.
     */
    QVERIFY2 (loader.load (), qPrintable (loader.errorString ()));

    DcpAppletIf *applet = qobject_cast<DcpAppletIf *>(loader.instance ());

    QVERIFY (applet != 0);

    /*
     * Do initialization... in the same way how controlpanel doing:
     */
    applet->init ();

#ifndef TEST_NEW_TITLE_METHODS
    QVERIFY (! applet->title ().isEmpty ());
#endif

    /*
     * Checking if the applet brief is constructed.
     */
    DcpBrief *brief = applet->constructBrief ();
    if (hasBrief)
    {
        QVERIFY2(brief, 
		    "Error when creating brief widget");
#ifdef TEST_NEW_TITLE_METHODS
        /*
         * Checking if the applet has a non-empty title string.
         */
        QVERIFY (! brief->titleText ().isEmpty ());
#endif
    }
    else
        QVERIFY2(!brief, 
		    "This applet should not have a Brief");

    /*
     * Checking if the the main view (the applet widget) is constructed. FIXME:
     * We should call the getMainWidgetId here, but I'm not sure how it is done
     * after the refactoring.
     */
    DcpWidget *widget = applet->constructWidget (0);
    QVERIFY2 (widget, "Error when creating applet's main widget");

#ifdef TEST_NEW_TITLE_METHODS
    /*
     * Check if the applet widget has a non-empty title string.
     */
    QVERIFY (! widget->title ().isEmpty ());
#endif

    QTest::qWait (1000);

//    loader.unload ();
//    delete widget;
//    delete brief;
}
Пример #27
0
//!
//! Loads the XML description of a widget type from the file with the given
//! name.
//!
//! \param filename The name of an XML file describing a widget type.
//!
bool WidgetFactory::registerType ( const QString &filename )
{
	QFile file (filename);
    if (!file.exists()) {
        Log::error(QString("widget plugin file not found: \"%1\"").arg(filename), "WidgetFactory::registerType");
        return false;
    }
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        Log::error(QString("Error loading widget plugin file \"%1\".").arg(filename), "WidgetFactory::registerType");
        return false;
    }

    // read the content of the file using a simple XML reader
    QDomDocument description;
    QXmlInputSource source (&file);
    QXmlSimpleReader xmlReader;
    QString errorMessage;
    int errorLine = 0;
    int errorColumn = 0;
    if (!description.setContent(&source, &xmlReader, &errorMessage, &errorLine, &errorColumn)) {
        Log::error(QString("Error parsing \"%1\": %2, line %3, char %4").arg(filename).arg(errorMessage).arg(errorLine).arg(errorColumn), "WidgetFactory::registerType");
        return false;
    }

    // obtain node type information from attributes
    QDomElement rootElement = description.documentElement();
    QString PluginName = rootElement.attribute("name");
    QString PluginDLL = rootElement.attribute("plugin");
	QString PluginCall = rootElement.attribute("call");


	//// decode the full filename into its path and base file name
    QString filePath = file.fileName().mid(0, file.fileName().lastIndexOf('/') + 1);
    QString baseFilename = file.fileName().mid(file.fileName().lastIndexOf('/') + 1);
    Log::debug(QString("Parsing \"%1\"...").arg(baseFilename), "WidgetFactory::registerType");

    // load plugin if a plugin filename is given
    if (filename != "") {
        QString pluginFilename =  filePath  + PluginDLL;

#ifdef _DEBUG
        // adjust the plugin filename to load the debug version of the DLL
        pluginFilename = pluginFilename.replace(".dll", "_d.dll");
#endif
        if (QFile::exists(pluginFilename)) {
            Log::debug(QString("Loading plugin \"%1\"...").arg(pluginFilename), "WidgetFactory::registerType");
            QPluginLoader loader (pluginFilename);
            WidgetTypeInterface *widgetTypeInterface = qobject_cast<WidgetTypeInterface *>(loader.instance());
            if (!widgetTypeInterface) {
                Log::error(QString("Plugin \"%1\" could not be loaded: %2").arg(pluginFilename).arg(loader.errorString()), "WidgetFactory::registerType");
                return false;
            }
			if(!m_widgetTypeMap.contains(PluginCall)){
				m_widgetTypeMap[PluginCall] = widgetTypeInterface;
			}
        } else {
            Log::error(QString("Plugin file \"%1\" could not be found.").arg(pluginFilename), "WidgetFactory::registerType");
            return false;
        }
    }

    return true;
}