CTK插件框架学习-插件注册调用(03)https://mp.csdn.net/mp_blog/creation/editor/136989802
一、主要流程
- 发送者注册消息事件
- 接收者订阅消息事件
- 接收者相应消息事件
事件监听比插件接口调用耦合性更弱,事件由框架维护,不需要指定发送方和接收方
二、发布订阅插件
2.1、事件发布插件
发送消息类
==========================Publish.ch================================
#pragma once#include "qstring.h"typedef struct
{QString _name;QString _message;
}ST_Msg;class ctkPluginContext;
class Publish
{
public:Publish(ctkPluginContext* context);//发布的消息void publishMessage(const ST_Msg& msg);private:ctkPluginContext* m_context;
};==========================Publish.cpp==============================
#include "Publish.h"
#include <qdebug.h>#include "service/event/ctkEventAdmin.h"
#include "ctkPluginContext.h"Publish::Publish(ctkPluginContext * context):m_context(context)
{
}void Publish::publishMessage(const ST_Msg & msg)
{ctkServiceReference ref = m_context->getServiceReference<ctkEventAdmin>();if (ref){ctkEventAdmin* eventAdmin = m_context->getService<ctkEventAdmin>(ref);if (eventAdmin){ctkDictionary dic;dic["name"] = msg._name;dic["message"] = msg._message;ctkEvent event("EVENT_MESSAGE", dic);qDebug() << "Publish message:" << dic;eventAdmin->sendEvent(event);//同步,消息发送后立即执行//eventAdmin->postEvent(event);//异步,由消息队列控制,有超时机制,超时后会被加入黑名单}}
}
激活器类
=============================PluginActivator.h===================================
#pragma once
#include <qobject.h>
#include "ctkPluginActivator.h"
#include "ctkPluginContext.h"#include "Publish.h"class PluginActivator :public QObject, ctkPluginActivator
{Q_OBJECTQ_INTERFACES(ctkPluginActivator)//向Qt的插件框架声明,希望将xxx插件放入到框架中。Q_PLUGIN_METADATA(IID "TestPublishPlugin")//向qt框架申明插件(qt5版本)public:PluginActivator();virtual void start(ctkPluginContext* context);virtual void stop(ctkPluginContext* context);private:QScopedPointer<Publish> m_publish;//智能指针,自动析构回收
};=============================PluginActivator.cpp=================================
#include "PluginActivator.h"
#include <qdebug.h>#include "ctkPluginFrameworkLauncher.h"PluginActivator::PluginActivator()
{
}void PluginActivator::start(ctkPluginContext* context)
{qDebug() << "my PublishPlugin start";m_publish.reset(new Publish(context));ST_Msg msg;msg._name = "Publish";msg._message = "hello Publish send message";m_publish.get()->publishMessage(msg);ctkPlugin::State sta = context->getPlugin()->getState();
}void PluginActivator::stop(ctkPluginContext* context)
{qDebug() << "my PublishPlugin stop";Q_UNUSED(context)// Q_UNUSED,如果一个函数的有些参数没有用到、某些变量只声明不使用,但是又不想编译器、编辑器报警报,其他没有什么实际性作用m_publish.reset(NULL);ctkPlugin::State sta = context->getPlugin()->getState();
}
2.2、事件订插件
接收消息类
==========================SubscribeEventHandler.h================================
#pragma once#include <qobject.h>
#include "service/event/ctkEventHandler.h"class SubscribeEventHandler: public QObject, public ctkEventHandler
{Q_OBJECTQ_INTERFACES(ctkEventHandler)public:SubscribeEventHandler();virtual void handleEvent(const ctkEvent& event);
};==========================SubscribeEventHandler.cpp==============================#include "SubscribeEventHandler.h"
#include <qdebug.h>#include "service/event/ctkEventAdmin.h"
#include "ctkPluginContext.h"SubscribeEventHandler::SubscribeEventHandler()
{
}void SubscribeEventHandler::handleEvent(const ctkEvent & event)
{QString name = event.getProperty("name").toString();QString message = event.getProperty("message").toString();qDebug() << "Subscribe name:" << name;qDebug() << "Subscribe message:" << message;
}
激活器类
=============================PluginActivator.h================================
#pragma once#include <QObject>
#include "ctkPluginActivator.h"
#include "ctkPluginContext.h"#include "SubscribeEventHandler.h"class PluginActivator : public QObject, public ctkPluginActivator
{Q_OBJECTQ_INTERFACES(ctkPluginActivator)//向Qt的插件框架声明,希望将xxx插件放入到框架中。Q_PLUGIN_METADATA(IID "TestSubscribePlugin")//向qt框架申明插件(qt5版本)public:PluginActivator();void start(ctkPluginContext *context);void stop(ctkPluginContext *context);private:QScopedPointer<SubscribeEventHandler> m_subscribeEventHandler;//智能指针,自动析构回收
};=============================PluginActivator.cpp==============================#include "PluginActivator.h"
#include <qdebug.h>#include "ctkPluginFrameworkLauncher.h"
#include "service/event/ctkEventConstants.h"PluginActivator::PluginActivator()
{}void PluginActivator::start(ctkPluginContext* context)
{qDebug() << "my SubscribePlugin start";m_subscribeEventHandler.reset(new SubscribeEventHandler());ctkDictionary dic;dic[ctkEventConstants::EVENT_TOPIC] = "EVENT_MESSAGE";//订阅的主题dic[ctkEventConstants::EVENT_FILTER] = "(name=Publish)";//过滤的事件context->registerService<ctkEventHandler>(m_subscribeEventHandler.get(), dic);ctkPlugin::State sta = context->getPlugin()->getState();
}void PluginActivator::stop(ctkPluginContext* context)
{qDebug() << "my SubscribePlugin stop";Q_UNUSED(context)// Q_UNUSED,如果一个函数的有些参数没有用到、某些变量只声明不使用,但是又不想编译器、编辑器报警报,其他没有什么实际性作用m_subscribeEventHandler.reset(NULL);ctkPlugin::State sta = context->getPlugin()->getState();
}
2.3、测试插件
#include "CTKPlugin.h"
#include <QtWidgets/QApplication>#include <iostream>
#include <QStyleFactory>
#include <QDir>
#include <QDirIterator>
#include <QDebug>
#include "ctkPluginFrameworkFactory.h"
#include "ctkPluginFramework.h"
#include "ctkPluginException.h"
#include "ctkPluginContext.h"
#include "ctkPluginFrameworkLauncher.h"
#include "../TestPlugin/iTestPlugin.h"
#include "../TestPlugin2/IService1.h"
#include "../TestPlugin2/IService2.h"
#include "../TestPlugin3/IService.h"
/*
* 1、注意:Plugin-SymbolicName要满足这里的前缀是:TARGET/META-INF格式。TARGET的名字最好和工程名一致,不然可能出现device not open错误。
* 2、如果CTK初始化、插件安装启动等是在一个类中,则与CTK相关的变量应定义成类的属性,不能是成员变量,否则获取不到服务
* 3、CTK插件组成:
(1)每个插件有自己的注册器Activator,继承自QObject和ctkPluginActivator的一个类,并实现ctkPluginActivator的start、stop函数
(2)每个插件必须有一个资源文件,名称一般与插件名称一致,前缀必须为TARGET/META-INF,例:插件名称/META-INF
(3)每个插件必须添加一个元数据文件,名字必须为MANIFEST.MF,并添加到资源文件中
* 4、QSharedPointer framework这个对象既可以作为对象也可以作为对象指针,但要作为插件框架使用必须要用指针方法调用
* 5、生成的插件名(TARGET)不要有下划线,因为CTK会默认将插件名中的下划线替换成点号,最后导致找不到插件
*/
int main(int argc, char *argv[])
{QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);QApplication a(argc, argv);a.setApplicationName("ctktest");//Linux下没有名称报错QString path = QCoreApplication::applicationDirPath();#ifdef _DEBUGctkPluginFrameworkLauncher::addSearchPath(path + "/CTKPlugins");
#elsectkPluginFrameworkLauncher::addSearchPath(path + "/CTKPlugins");
#endif // _DEBUG// 设置并启动 CTK 插件框架try {ctkPluginFrameworkLauncher::start("org.commontk.eventadmin");}catch (ctkException e){std::cout << e.message().toStdString() << std::endl;}// 启动插件工厂ctkPluginFrameworkFactory* ctkFrameWorkFactory = new ctkPluginFrameworkFactory;QSharedPointer<ctkPluginFramework> framework = ctkFrameWorkFactory->getFramework();try {framework->init();framework->start();}catch (const ctkPluginException& e){std::cout << "framework init fail" << std::endl;}QSharedPointer<ctkPlugin> plugin;/*
* 使用MANIFEST.MF启动依赖插件方法未成功,采用独立加载插件方法
*/
#if 0QDirIterator iter(path + "/plugins/", { "*.dll" }, QDir::NoFilter, QDirIterator::Subdirectories);while (iter.hasNext()) {//qDebug() << iter.next();QString dllPath = iter.next();QUrl url = QUrl::fromLocalFile(dllPath);try{plugin = framework->getPluginContext()->installPlugin(url);qDebug() << QString("Plugin[%1_%2] installed...").arg(plugin->getSymbolicName()).arg(plugin->getVersion().toString());//获取MANIFEST.MF中的数据QHash<QString, QString> headers = plugin->getHeaders();ctkVersion version = ctkVersion::parseVersion(headers.value(ctkPluginConstants::PLUGIN_VERSION));QString name = headers.value(ctkPluginConstants::PLUGIN_NAME);}catch (ctkPluginException e) {std::cout << e.message().toStdString() << e.getType() << std::endl;}try {plugin->start(ctkPlugin::START_TRANSIENT);//表示立即启用插件,不设置参数的话加载后也不会立即打印输出qDebug() << QString("Plugin[%1_%2] started").arg(plugin->getSymbolicName()).arg(plugin->getVersion().toString());}catch (ctkPluginException e) {std::cout << e.message().toStdString() << e.getType() << std::endl;}}#elsetry{QUrl url = QUrl::fromLocalFile(path + "/plugins/TestSubscribePlugin.dll");plugin = framework->getPluginContext()->installPlugin(url);qDebug() << QString("Plugin[%1_%2] installed...").arg(plugin->getSymbolicName()).arg(plugin->getVersion().toString());//获取MANIFEST.MF中的数据QHash<QString, QString> headers = plugin->getHeaders();ctkVersion version = ctkVersion::parseVersion(headers.value(ctkPluginConstants::PLUGIN_VERSION));QString name = headers.value(ctkPluginConstants::PLUGIN_NAME);}catch (ctkPluginException e) {std::cout << e.message().toStdString() << e.getType() << std::endl;}try {plugin->start(ctkPlugin::START_TRANSIENT);//表示立即启用插件,不设置参数的话加载后也不会立即打印输出qDebug() << QString("Plugin[%1_%2] started").arg(plugin->getSymbolicName()).arg(plugin->getVersion().toString());}catch (ctkPluginException e) {std::cout << e.message().toStdString() << e.getType() << std::endl;}try{QUrl url = QUrl::fromLocalFile(path + "/plugins/TestPublishPlugin.dll");plugin = framework->getPluginContext()->installPlugin(url);qDebug() << QString("Plugin[%1_%2] installed...").arg(plugin->getSymbolicName()).arg(plugin->getVersion().toString());//获取MANIFEST.MF中的数据QHash<QString, QString> headers = plugin->getHeaders();ctkVersion version = ctkVersion::parseVersion(headers.value(ctkPluginConstants::PLUGIN_VERSION));QString name = headers.value(ctkPluginConstants::PLUGIN_NAME);}catch (ctkPluginException e) {std::cout << e.message().toStdString() << e.getType() << std::endl;}try {plugin->start(ctkPlugin::START_TRANSIENT);//表示立即启用插件,不设置参数的话加载后也不会立即打印输出qDebug() << QString("Plugin[%1_%2] started").arg(plugin->getSymbolicName()).arg(plugin->getVersion().toString());}catch (ctkPluginException e) {std::cout << e.message().toStdString() << e.getType() << std::endl;}
#endif//ctkPlugin::State sta = plugin->getState();//ctkPluginFrameworkLauncher::stop();//plugin->stop(); //plugin->uninstall();//sta = plugin->getState();CTKPlugin c;c.show();return a.exec();
}
三、MANIFEST.MF文件参数
实现插件依赖启动
Plugin-SymbolicName:本插件名称
Plugin-Version:本插件版本号
Require-Plugin:依赖插件名称
Plugin-version=依赖插件版本号, 默认为1.0
resolution=mandatory为强依赖没有找到则本插件不能启动,optional为弱依赖没有找到也正常启动