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 void clearTimeout(QJSValue id) {
22 // qDebug() << "Clearing timer" << id.toString();
23 auto timer = getTimers().take(id.toUInt());
28 qDebug() << "Unknown id" << id.toUInt();
31 // This should be static but cannot bind static functions to QJSEngine
32 Q_INVOKABLE QJSValue setTimeout(QJSValue callback, QJSValue delayTime, QJSValue args) {
33 qDebug() << callback.toString() << delayTime.toInt() << args.toString();
35 QJSValueList valueArgs;
37 const int argsLength = args.property("length").toInt();
38 for (int i = 0; i < argsLength; ++i) {
39 auto arg = args.property(i);
40 qDebug() << "Adding arg" << arg.toString();
45 auto timer = new JSTimer();
46 timer->setInterval(delayTime.toInt());
47 connect(timer, &JSTimer::timeout, this, [callback, valueArgs]() mutable {
48 qDebug() << "Calling" << callback.toString();
49 if (!callback.isCallable()) qDebug() << callback.toString() << "is not callable";
50 auto value = callback.call(valueArgs);
51 if (value.isError()) {
52 qWarning() << "Error" << value.toString();
53 qDebug() << value.property("stack").toString().splitRef('\n');
57 return timer->getId();
60 Q_INVOKABLE JSTimer(QObject *parent = nullptr) : QTimer(parent) {
61 setTimerType(Qt::PreciseTimer);
64 static uint counter = 1;
66 connect(this, &JSTimer::destroyed, this, [id = id] { getTimers().remove(id); });
67 connect(this, &JSTimer::timeout, this, &QTimer::deleteLater);
68 getTimers().insert(id, this);
75 class JS : public QObject {
79 static JS &instance();
81 explicit JS(QObject *parent = nullptr);
82 JSNAMFactory &getNamFactory() { return namFactory; };
84 void initialize(const QUrl &url);
85 bool checkError(const QJSValue &value);
88 QQmlEngine &getEngine() { return *engine; }
90 JSResult &callFunction(JSResult *result, const QString &name, const QJSValueList &args);
95 void initFailed(QString message);
101 JSNAMFactory namFactory;
102 bool initializing = false;