File indexing completed on 2025-02-09 04:28:38
0001 /* 0002 This file is part of the KTextTemplate library 0003 0004 SPDX-FileCopyrightText: 2010 Stephen Kelly <steveire@gmail.com> 0005 0006 SPDX-License-Identifier: LGPL-2.1-or-later 0007 0008 */ 0009 0010 #ifndef KTEXTTEMPLATE_PLUGINPOINTER_H 0011 #define KTEXTTEMPLATE_PLUGINPOINTER_H 0012 0013 #include <QPluginLoader> 0014 #include <QSharedPointer> 0015 0016 namespace KTextTemplate 0017 { 0018 0019 /** 0020 @brief A smart pointer for handling plugins. 0021 0022 @author Stephen Kelly <steveire@gmail.com> 0023 */ 0024 template<typename PluginType> 0025 class PluginPointer 0026 { 0027 class _Dummy; 0028 0029 public: 0030 // This allows returning 0 from a function returning a PluginType* 0031 PluginPointer(_Dummy * = {}) 0032 : m_plugin(nullptr) 0033 { 0034 } 0035 0036 explicit PluginPointer(const QString &fileName) 0037 : m_object(nullptr) 0038 , m_plugin(nullptr) 0039 { 0040 m_pluginLoader = QSharedPointer<QPluginLoader>(new QPluginLoader(fileName)); 0041 0042 // This causes a load of the plugin, and we never call unload() to 0043 // unload 0044 // it. Unloading it would cause the destructors of all types defined in 0045 // plugins 0046 // to be unreachable. If a Template object outlives the last engine, 0047 // that 0048 // causes segfaults if the plugin has been unloaded. 0049 m_object = m_pluginLoader->instance(); 0050 0051 m_plugin = qobject_cast<PluginType *>(m_object); 0052 } 0053 0054 QString errorString() 0055 { 0056 return m_pluginLoader->errorString(); 0057 } 0058 0059 QObject *object() 0060 { 0061 return m_object; 0062 } 0063 0064 PluginType *operator->() 0065 { 0066 return m_plugin; 0067 } 0068 0069 operator bool() 0070 { 0071 return m_plugin ? true : false; 0072 } 0073 0074 PluginType *data() const 0075 { 0076 return m_plugin; 0077 } 0078 0079 private: 0080 QObject *m_object; 0081 PluginType *m_plugin; 0082 QSharedPointer<QPluginLoader> m_pluginLoader; 0083 }; 0084 } 0085 0086 #endif