6 #include "jsnamfactory.h"
9 class JSTimer : public QTimer {
13 static auto &getTimers() {
14 static QHash<uint, JSTimer *> timers;
18 auto getId() const { return id; }
20 // This should be static but cannot bind static functions to QJSEngine
21 Q_INVOKABLE QJSValue clearTimeout(QJSValue id) {
22 auto timer = getTimers().take(id.toUInt());
27 qDebug() << "Unknown id" << id.toUInt();
30 // This should be static but cannot bind static functions to QJSEngine
31 Q_INVOKABLE QJSValue setTimeout(QJSValue callback, QJSValue delayTime, QJSValue args) {
32 qDebug() << callback.toString() << delayTime.toInt() << args.toString();
34 QJSValueList valueArgs;
36 const int argsLength = args.property("length").toInt();
37 for (int i = 0; i < argsLength; ++i) {
38 auto arg = args.property(i);
39 qDebug() << "Adding arg" << arg.toString();
44 auto timer = new JSTimer();
45 timer->setInterval(delayTime.toInt());
46 connect(timer, &JSTimer::timeout, this, [callback, valueArgs]() mutable {
47 qDebug() << "Calling" << callback.toString();
48 if (!callback.isCallable()) qDebug() << callback.toString() << "is not callable";
49 auto value = callback.call(valueArgs);
50 if (value.isError()) {
51 qWarning() << "Error" << value.toString();
52 qDebug() << value.property("stack").toString().splitRef('\n');
56 return timer->getId();
59 Q_INVOKABLE JSTimer(QObject *parent = nullptr) : QTimer(parent) {
60 setTimerType(Qt::CoarseTimer);
63 static uint counter = 1;
65 connect(this, &JSTimer::destroyed, this, [id = id] { getTimers().remove(id); });
66 connect(this, &JSTimer::timeout, this, &QTimer::deleteLater);
67 getTimers().insert(id, this);
74 class JS : public QObject {
78 static JS &instance();
80 explicit JS(QObject *parent = nullptr);
81 JSNAMFactory &getNamFactory() { return namFactory; };
83 void initialize(const QUrl &url);
84 bool checkError(const QJSValue &value);
87 QQmlEngine &getEngine() { return *engine; }
89 JSResult &callFunction(JSResult *result, const QString &name, const QJSValueList &args);
93 void initFailed(QString message);
99 JSNAMFactory namFactory;
100 bool initializing = false;