1 /*
2  * %kadu copyright begin%
3  * Copyright 2016 Rafał Przemysław Malinowski (rafal.przemyslaw.malinowski@gmail.com)
4  * %kadu copyright end%
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #pragma once
21 
22 #include "misc/memory.h"
23 #include "exports.h"
24 
25 #include <QtCore/QObject>
26 #include <QtCore/QPointer>
27 #include <injeqt/injector.h>
28 #include <memory>
29 
30 class InjectorProvider;
31 
32 class KADUAPI InjectedFactory : public QObject
33 {
34 	Q_OBJECT
35 
36 public:
37 	Q_INVOKABLE explicit InjectedFactory(QObject *parent = nullptr);
38 	virtual ~InjectedFactory();
39 
40 	template<typename T, typename ...Args>
makeInjected(Args &&...args)41 	T * makeInjected(Args&& ...args)
42 	{
43 		auto result = new T(std::forward<Args>(args)...);
44 		injectInto(result);
45 		return result;
46 	}
47 
48 	template<typename T, typename ...Args>
makeOwned(Args &&...args)49 	owned_qptr<T> makeOwned(Args&& ...args)
50 	{
51 		auto result = make_owned<T>(std::forward<Args>(args)...);
52 		injectInto(result);
53 		return result;
54 	}
55 
56 	template<typename T, typename ...Args>
makeNotOwned(Args &&...args)57 	not_owned_qptr<T> makeNotOwned(Args&& ...args)
58 	{
59 		auto result = make_not_owned<T>(std::forward<Args>(args)...);
60 		injectInto(result);
61 		return result;
62 	}
63 
64 	template<typename T, typename ...Args>
makeUnique(Args &&...args)65 	std::unique_ptr<T> makeUnique(Args&& ...args)
66 	{
67 		auto result = std::make_unique<T>(std::forward<Args>(args)...);
68 		injectInto(result.get());
69 		return result;
70 	}
71 
72 private:
73 	QPointer<InjectorProvider> m_injectorProvider;
74 
75 	void injectInto(QObject *object);
76 
77 private slots:
78 	INJEQT_SET void setInjectorProvider(InjectorProvider *injectorProvider);
79 
80 };
81