File: RJSTools.cpp

package info (click to toggle)
actiona 3.11.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 54,580 kB
  • sloc: cpp: 969,398; xml: 52,881; javascript: 32,914; python: 23,909; sh: 550; ansic: 90; makefile: 9
file content (411 lines) | stat: -rw-r--r-- 11,641 bytes parent folder | download
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QTimer>
#include <QtConcurrent>
#include <QImage>

#include "RJSHelper.h"
#include "RJSTools.h"
// #include "RFileCache.h"

RJSTools::RJSTools(RJSApi &handler) : handler(handler), alwaysLoadScripts(false)
{
    alwaysLoadScripts = qApp->arguments().contains("-always-load-scripts");
}

RJSTools::~RJSTools() {}

bool RJSTools::isIncluded(const QString &className)
{
    if (alwaysLoadScripts && className != "library" && className != "EAction" && className != "WidgetFactory")
    {
        // always include (again) to reload potential changes:
        return false;
    }

    QVariant vAlreadyIncluded;

    QJSEngine *engine = handler.getEngine();
    if (engine == NULL)
    {
        qWarning() << "script handler not initialized";
    }
    vAlreadyIncluded = engine->property("alreadyIncluded");
    if (!vAlreadyIncluded.isValid())
    {
        return false;
    }

    QSet<QString> alreadyIncluded;
    alreadyIncluded = vAlreadyIncluded.value<QSet<QString>>();
    if (!alreadyIncluded.contains(className))
    {
        return false;
    }

    return true;
}

void RJSTools::markIncluded(const QString &className)
{
    QVariant vAlreadyIncluded;
    QSet<QString> alreadyIncluded;

    QJSEngine *engine = handler.getEngine();
    vAlreadyIncluded = engine->property("alreadyIncluded");
    if (vAlreadyIncluded.isValid())
    {
        alreadyIncluded = vAlreadyIncluded.value<QSet<QString>>();
    }

    if (alreadyIncluded.contains(className))
    {
        return;
    }

    alreadyIncluded.insert(className);
    vAlreadyIncluded.setValue(alreadyIncluded);
    engine->setProperty("alreadyIncluded", vAlreadyIncluded);
}

bool RJSTools::include(const QString &fileName, QString trContext, bool force)
{
    static int including = 0;

    // qDebug() << "RJSTools::include:" << fileName;

    // QScriptContext* context = engine->currentContext();

    QString className = QFileInfo(fileName).completeBaseName();

    if (!force && isIncluded(className))
    {
        // qDebug() << "RJSTools::include: already included";
        return true;
    }

    bool scriptsPath = fileName.startsWith("scripts");

    QJSEngine *engine = handler.getEngine();

    QStringList list;

    if (!scriptsPath)
    {
        // search based on the includeBasePath which changes depending on the plugin
        QJSValue includeBasePath = engine->globalObject().property("includeBasePath");
        // qDebug() << "includeBasePath:" << includeBasePath.toString();
        if (!includeBasePath.isUndefined())
        {
            list << engine->globalObject().property("includeBasePath").toString();
        }

        // ... then search based on the initial script path (does not change)
        QJSValue scriptFileBasePath = engine->globalObject().property("scriptFileBasePath");
        if (!scriptFileBasePath.isUndefined())
        {
            list << engine->globalObject().property("scriptFileBasePath").toString();
        }

        // ... then search based on the local data storage location path (does not change)
        QStringList candidates = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);
        list << candidates;
    }

    // ... then search based on the program path (does not change)
    list << QDir::currentPath();

    // ... then search based on the built in plugin values (does not change)
    list << ":";

    // Remove the duplicates and preserve the order
    list.removeDuplicates();

    QStringListIterator i(list);
    while (i.hasNext())
    {
        QString basePath = i.next();

        QString fileNameLocal;
        QFileInfo fi(fileName);
        if (fi.isAbsolute())
        {
            fileNameLocal = fileName;
        }
        else
        {
            if (basePath == ":")
            {
                fileNameLocal = basePath + fileName;
            }
            else
            {
                if (basePath.startsWith(":"))
                {
                    // workaround for Qt 4.7.4 bug with resource paths
                    // containing both \ and /:
                    fileNameLocal = basePath + "/" + fileName;
                }
                else
                {
                    fileNameLocal = basePath + QDir::separator() + fileName;
                }
            }
            fi = QFileInfo(fileNameLocal);
        }

        if (!fi.exists())
        {
            continue;
        }

        // qDebug() << "RJSTools::include: found at " << fileNameLocal;

        QFile file(fileNameLocal);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            continue;
        }
        QTextStream in(&file);
        QString contents = in.readAll();
        file.close();

        if (trContext.isNull())
        {
            trContext = fi.completeBaseName();
        }

        // post-processing for translation context:
#if QT_VERSION >= 0x050000
        contents.replace("qsTr(\"", QString("qsTranslate('%1', \"").arg(trContext));
#else
        // workaround for Qt 4 API / see library.js:
        contents.replace("qsTr(\"", QString("qsTranslate2('%1', \"").arg(trContext));
#endif
        contents.replace("QT_TR_NOOP(\"", QString("QT_TRANSLATE_NOOP('%1', \"").arg(trContext));

        QString includeBasePath = engine->globalObject().property("includeBasePath").toString();

        // qDebug() << "setting includeBasePath to: " << fi.absolutePath();

        engine->globalObject().setProperty("includeBasePath", fi.absolutePath());
        // context->setActivationObject(engine->globalObject());
        // context->setThisObject(engine->globalObject());
        including++;
        engine->globalObject().setProperty("including", true);
        // qDebug() << "eval include for " << fileName;
        QStringList trace;
        QJSValue res = engine->evaluate(contents, fileName, 1, &trace);

        if (res.isError())
        {
            qWarning() << "include exception: " << res.toString();
            for (int i = 0; i < trace.length(); i++)
            {
                qWarning() << trace[i];
            }
        }

        // qDebug() << "eval include for " << fileName << ": DONE";
        including--;
        engine->globalObject().setProperty("including", including != 0);

        engine->globalObject().setProperty("includeBasePath", includeBasePath);

        markIncluded(className);

        return true;
    }

    qDebug() << "RJSTools::include: not found:" << fileName;

    return false;

    //    return context->throwError(QString("include: cannot read file '%1'").arg(
    //                                   context->argument(0).toString()));
}

// void RJSTools::include(const QString& fileName) {
//     qDebug() << "RJSTools::include:" << fileName;

//    QString content = RFileCache::getContents(fileName, false);
//    QJSValue result = engine->evaluate(content);
//    if (result.isError()) {
//        qDebug() << "Uncaught exception in " << fileName << " at line "
//                 << result.property("lineNumber").toInt()
//                 << ":" << result.toString();
//    }
//}

bool RJSTools::isDeleted(const QJSValue &obj)
{
    if (!obj.isQObject())
    {
        return false;
    }

    QObject *qObj = obj.toQObject();
    return qObj == nullptr;
}

QString RJSTools::download(const QString &url, int timeout)
{
    QNetworkAccessManager manager;
    QEventLoop loop;
    QNetworkReply *reply = manager.get(QNetworkRequest(url));
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));

    // timeout:
    if (timeout > 0)
    {
        QTimer::singleShot(timeout, &loop, SLOT(quit()));
    }

    // run loop:
    loop.exec();

    if (reply->error() != QNetworkReply::NoError)
    {
        qDebug() << "Cannot download " << url << ": " << reply->errorString();
    }

    QString content = reply->readAll();

    delete reply;

    return content;
}

bool RJSTools::downloadToFile(const QString &url, const QString &path, const QString &fileName, int timeout)
{

    QString localFileName = fileName;
    QNetworkAccessManager manager;
    QEventLoop loop;
    QNetworkReply *reply = manager.get(QNetworkRequest(url));
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));

    // timeout:
    if (timeout > 0)
    {
        QTimer::singleShot(timeout, &loop, SLOT(quit()));
    }

    // run loop:
    loop.exec();

    if (reply->error() != QNetworkReply::NoError)
    {
        qWarning() << "Cannot download " << url << ": " << reply->errorString();
        delete reply;
        return false;
    }

    if (localFileName.isEmpty())
    {
        localFileName = QFileInfo(QUrl(url).path()).fileName();
    }

    localFileName = path + QDir::separator() + localFileName;
    QDir dir;
    if (!dir.mkpath(path))
    {
        qWarning() << "Cannot create dir " << path;
        delete reply;
        return false;
    }
    if (QFileInfo(localFileName).exists() && !QFile(localFileName).remove())
    {
        qWarning() << "Cannot remove file " << localFileName;
        delete reply;
        return false;
    }

    QByteArray contents = reply->readAll();
    if (contents.isEmpty())
    {
        qWarning() << "URL does not exist " << url;
        delete reply;
        return false;
    }

    QFile f(localFileName);
    if (!f.open(QIODevice::WriteOnly))
    {
        qWarning() << "Cannot write output file " << f.fileName();
        delete reply;
        return false;
    }
    f.write(contents);
    f.close();

    delete reply;
    return true;
}

void RJSTools::print(const QJSValue &args)
{
    // fprintf(stdout, "RJSTools::debug\n");
    // fflush(stdout);

    // QDebug deb = qDebug();
    for (int i = 0; i < args.property("length").toInt(); i++)
    {
        // deb << args.property(i).toString();
        // qDebug() << args.property(i).toString();
        printf("%s\n", args.property(i).toString().toUtf8().data());
    }
}

void RJSTools::debug(const QJSValue &args)
{
    QDebug deb = qDebug();
    for (int i = 0; i < args.property("length").toInt(); i++)
    {
        deb << args.property(i).toString();
        // qDebug() << args.property(i).toString();
    }
}

void RJSTools::warning(const QJSValue &args)
{
    QDebug deb = qWarning();
    for (int i = 0; i < args.property("length").toInt(); i++)
    {
        deb << args.property(i).toString();
    }
}

bool RJSTools::jsQThreadPoolWaitForDone(int msecs)
{
    return pool.waitForDone(msecs);
}

bool RJSTools::jsQImageSave(const QJSValue &jsImage, const QString &filePath, const QString &format, int quality)
{
    QImage image = RJSHelper::js2cpp_QImage(handler, jsImage);
    // return image.save(filePath, (const char*)format.toUtf8(), quality);
    // QFuture<bool> future = QtConcurrent::run(&QImage::save, &image, filePath, (const char*)format.toUtf8(), quality);
    // QFuture<bool> future = QtConcurrent::run(&QImage::save, &image, filePath);

    // QFuture<void> future = QtConcurrent::run(&QImage::invertPixels, &image, QImage::InvertRgba);

    // qDebug() << "saving image in bg: " << filePath;

    QFuture<bool> future = QtConcurrent::run(&pool, [=]
                                             {
        if (image.save(filePath, (const char*)format.toUtf8(), quality)) {
            //qDebug() << "image saved: " << filePath;
            //emit imageSaved(filename);
            return true;
        }
        else {
            qWarning() << "image NOT saved: " << filePath;
            //emit imageSaveFailed(filename);
            return false;
        } });

    // future.waitForFinished();

    return true;
}