10 class JsTimer : public QTimer {
14 static auto &getTimers() {
15 static QHash<QString, JsTimer *> timers;
18 // This should be static but cannot bind static functions to QJSEngine
19 Q_INVOKABLE QJSValue clearTimeout(QJSValue id) {
20 // qDebug() << id.toString();
21 auto timer = getTimers().take(id.toString());
28 // This should be static but cannot bind static functions to QJSEngine
29 Q_INVOKABLE QJSValue setTimeout(QJSValue callback, QJSValue delayTime) {
30 // qDebug() << callback.toString() << delayTime.toInt();
31 auto timer = new JsTimer();
32 timer->setInterval(delayTime.toInt());
33 connect(timer, &JsTimer::timeout, this, [callback]() mutable {
34 // qDebug() << "Calling" << callback.toString();
35 auto value = callback.call();
36 if (value.isError()) {
37 qWarning() << "Error" << value.toString();
38 qDebug() << value.property("stack").toString().splitRef('\n');
42 return timer->hashString();
45 Q_INVOKABLE JsTimer(QObject *parent = nullptr) : QTimer(parent) {
46 setTimerType(Qt::VeryCoarseTimer);
48 connect(this, &JsTimer::destroyed, this, [this] { getTimers().remove(hashString()); });
49 connect(this, &JsTimer::timeout, this, &QTimer::deleteLater);
50 getTimers().insert(hashString(), this);
53 QString hashString() { return QString::number((std::uintptr_t)(this)); }
58 class ResultHandler : public QObject {
62 Q_INVOKABLE QJSValue setData(QJSValue value) {
63 qDebug() << "Success" << value.toString();
64 auto doc = QJsonDocument::fromVariant(value.toVariant());
66 qDebug() << value.toString();
67 emit error("Cannot parse JSON");
74 Q_INVOKABLE QJSValue setError(QJSValue value) {
75 QString message = value.toString();
76 qWarning() << "Error" << message;
77 qDebug() << value.property("stack").toString().splitRef('\n');
83 void data(const QJsonDocument &doc);
84 void error(const QString &message);
87 class YTJS : public QObject {
91 static YTJS &instance();
93 static Http &cachedHttp();
95 explicit YTJS(QObject *parent = nullptr);
96 bool checkError(const QJSValue &value);
99 QQmlEngine &getEngine() { return *engine; }
103 void initFailed(QString message);
107 QJSValue evaluate(const QString &js);
109 // QQmlEngine gives us XMLHttpRequest, console, JSON
111 bool initializing = false;