-
Notifications
You must be signed in to change notification settings - Fork 2
/
qttimerjs_plugin.hpp
102 lines (78 loc) · 2.26 KB
/
qttimerjs_plugin.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#ifndef QTTIMERJS_PLUGIN_HPP
#define QTTIMERJS_PLUGIN_HPP
#include <type_traits>
#include <QJSValue>
#include <QMetaObject>
#include <QQmlContext>
#include <QQmlEngine>
#include <QQmlExtensionPlugin>
#include <QTimer>
#include <QVariant>
class TimerJS;
class Lambda;
class QtTimerJSPlugin : public QQmlExtensionPlugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID QQmlExtensionInterface_iid)
public:
QtTimerJSPlugin();
void initializeEngine(QQmlEngine *engine, const char *uri) override;
void registerTypes(const char *uri) override;
TimerJS *timerjs;
};
class Lambda {
public:
Lambda() = default;
~Lambda() = default;
Lambda(const Lambda &fn) { m_function = fn.m_function; }
Lambda(Lambda &&fn) { m_function = fn.m_function; };
template <class Fn, std::enable_if_t<
!std::is_same_v<std::decay_t<Fn>, Lambda>, int> = 0>
Lambda(Fn &&function) {
m_function.reset(new Callable(std::forward<Fn>(function)));
}
Lambda &operator=(Lambda &fn) {
std::swap(*this, fn);
return *this;
};
Lambda &operator=(const Lambda &fn) {
Lambda temp(fn);
std::swap(*this, temp);
return *this;
}
friend void swap(Lambda &l, Lambda &r) {
using std::swap;
swap(l.m_function, r.m_function);
}
void operator()() {
if (m_function) {
m_function->operator()();
}
}
struct Concept {
virtual ~Concept(){};
virtual void operator()() = 0;
};
template <class Fn> struct Callable : Concept {
Callable(Fn &&function) : m_fn(std::forward<Fn>(function)) {}
~Callable() override {}
void operator()() override { m_fn(); }
Fn m_fn;
};
private:
std::shared_ptr<Concept> m_function;
};
Q_DECLARE_METATYPE(Lambda);
class TimerJS : public QObject {
Q_OBJECT
public:
explicit TimerJS(QObject *parent = nullptr) : QObject(parent) {}
virtual ~TimerJS() override {}
inline QVariant setTimeout(const QVariant &handler, int delay,
bool singleShot) const;
Q_INVOKABLE QVariant setTimeout(const QVariant &handler, int time) const;
Q_INVOKABLE void clearTimeout(const QVariant &handler) const;
Q_INVOKABLE QVariant setInterval(const QVariant &handler, int delay) const;
Q_INVOKABLE void clearInterval(const QVariant &handler) const;
};
#endif // QTTIMERJS_PLUGIN_HPP