File indexing completed on 2025-01-05 04:46:24

0001 /*
0002     This file is part of akonadiresources.
0003 
0004     SPDX-FileCopyrightText: 2006 Till Adam <adam@kde.org>
0005     SPDX-FileCopyrightText: 2007 Volker Krause <vkrause@kde.org>
0006 
0007     SPDX-License-Identifier: LGPL-2.0-or-later
0008 */
0009 
0010 #pragma once
0011 
0012 #include "agentbase.h"
0013 #include "akonadiagentbase_export.h"
0014 
0015 #include <QObject>
0016 
0017 #include <memory>
0018 
0019 namespace Akonadi
0020 {
0021 class AgentFactoryBasePrivate;
0022 
0023 /**
0024  * @short A factory base class for in-process agents.
0025  *
0026  * @see AKONADI_AGENT_FACTORY()
0027  * @internal
0028  * @since 4.6
0029  */
0030 class AKONADIAGENTBASE_EXPORT AgentFactoryBase : public QObject
0031 {
0032     Q_OBJECT
0033 
0034 public:
0035     /**
0036      * Creates a new agent factory.
0037      * Executed in the main thread, performs KDE infrastructure setup.
0038      *
0039      * @param catalogName The translation catalog of this resource.
0040      * @param parent The parent object.
0041      */
0042     explicit AgentFactoryBase(const char *catalogName, QObject *parent = nullptr);
0043 
0044     ~AgentFactoryBase() override;
0045 
0046 public Q_SLOTS:
0047     /**
0048      * Creates a new agent instance with the given identifier.
0049      */
0050     virtual QObject *createInstance(const QString &identifier) const = 0;
0051 
0052 protected:
0053     void createComponentData(const QString &identifier) const;
0054 
0055 private:
0056     std::unique_ptr<AgentFactoryBasePrivate> const d;
0057 };
0058 
0059 /**
0060  * @short A factory for in-process agents.
0061  *
0062  * @see AKONADI_AGENT_FACTORY()
0063  * @internal
0064  * @since 4.6
0065  */
0066 template<typename T>
0067 class AgentFactory : public AgentFactoryBase
0068 {
0069 public:
0070     /** reimplemented */
0071     explicit AgentFactory(const char *catalogName, QObject *parent = nullptr)
0072         : AgentFactoryBase(catalogName, parent)
0073     {
0074     }
0075 
0076     QObject *createInstance(const QString &identifier) const override
0077     {
0078         createComponentData(identifier);
0079         T *instance = new T(identifier);
0080 
0081         // check if T also inherits AgentBase::Observer and
0082         // if it does, automatically register it on itself
0083         auto observer = dynamic_cast<Akonadi::AgentBase::Observer *>(instance);
0084         if (observer != nullptr) {
0085             instance->registerObserver(observer);
0086         }
0087 
0088         return instance;
0089     }
0090 };
0091 
0092 }