summaryrefslogtreecommitdiffstats
path: root/library/scriptadapter.cpp
blob: ba196c79c1f728c7e1bd11c705e32be044414d65 (plain)
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
/**************************************************************************
**
** This file is part of Remote Control Widget
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "scriptadapter.h"

#include "optionsitem.h"

#include <coroutine/coroutine.h>

#include <QtCore/QMetaEnum>
#include <QtCore/QCoreApplication>
#include <QtCore/QTimer>
#include <QtCore/QTime>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QDebug>
#include <QtGui/QMessageBox>

#ifdef Q_OS_WIN
#include <windows.h>
#endif

template <typename Enum>
static void scriptToEnum(const QScriptValue &obj, Enum &e)
{
    e = static_cast<Enum>(obj.toInt32());
}

template <typename Enum>
static QScriptValue enumToScript(QScriptEngine *engine, const Enum &e)
{
    QScriptValue obj = engine->newVariant(e);
    return obj;
}

// Adds a property 'name' to 'to' that contains all the values of the enum 'name',
// which must be registered in 'mo'. Also registers the type 'Enum' to the QScriptEngine.
template <typename Enum>
static void exposeEnum(QScriptEngine *engine, QScriptValue *to, const char *name, const QMetaObject *mo)
{
    qScriptRegisterMetaType<Enum>(engine, &enumToScript<Enum>, &scriptToEnum<Enum>);
    QScriptValue enumvals = engine->newObject();
    int enumIndex = mo->indexOfEnumerator(name);
    Q_ASSERT(enumIndex != -1 && "enum not found in meta object");
    QMetaEnum metaEnum = mo->enumerator(enumIndex);
    for (int i = 0; i < metaEnum.keyCount(); ++i)
        enumvals.setProperty(metaEnum.key(i), metaEnum.value(i));
    to->setProperty(name, enumvals);
}

ScriptAdapter::ScriptAdapter(QObject *parent)
        : QObject(parent)
{
    mScriptRunner = new QTimer(this);
    mScriptRunner->setSingleShot(true);
    mScriptRunner->setInterval(100);
    connect(mScriptRunner, SIGNAL(timeout()), this, SLOT(continueScripts()));
    mScriptRunner->start();

    mMessageBox = new QMessageBox;
}

ScriptAdapter::~ScriptAdapter()
{
    delete mMessageBox;
}

void ScriptAdapter::addScriptInterface(const QString &name, QObject *interface)
{
    mScriptInterfaces.insert(name, interface);
}

Script *ScriptAdapter::script(int index)
{
    if (index >= 0 && index < mActiveScripts.length())
        return mActiveScripts[index];
    else
        return 0;
}

void ScriptAdapter::runAutostartScripts()
{
    QDir dir(QCoreApplication::applicationDirPath());
    dir.cd(QLatin1String("scripts"));
    dir.cd(QLatin1String("autostart"));

    QStringList scriptPatterns;
    scriptPatterns << "*.js" << "*.qs";
    foreach (const QFileInfo &file, dir.entryInfoList(scriptPatterns, QDir::Files)) {
        run(file.filePath());
    }
}

Script *ScriptAdapter::run(const QString &filePath)
{
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "Could not read script file: " << filePath;
        return 0;
    }

    QFileInfo fileInfo(file);
    Script *script = new Script(fileInfo.baseName(), file.readAll(), this);
    mActiveScripts += script;

    emit scriptStart(script);

    return script;
}

void ScriptAdapter::continueScripts() {
    for (int i = 0; i < mActiveScripts.length(); ++i) {
        Script *script = mActiveScripts[i];

        if (script->mCoroutine->status() == Coroutine::Terminated) {
            emit scriptStop(i);

            mActiveScripts.removeOne(script);
            delete script;
            break;
        }

        if (!script->isPaused() || script->isTerminating()) {
            mCurrentScript = script;
            script->mCoroutine->cont();
            mCurrentScript = 0;
        }
    }

    mScriptRunner->start();
}

void ScriptAdapter::yield(int ms)
{
    if (!mCurrentScript)
        return;

    QTime timer;
    timer.start();
    while (timer.elapsed() < ms && !mCurrentScript->isTerminating()) {
        mCurrentScript->suspend();
    }
}

void ScriptAdapter::messageBox(const QString &text)
{
    if (!mCurrentScript)
        return;

    mMessageBox->setText(text);

    // message boxes should block
    mCurrentScript->beginBlocking();
    mMessageBox->exec();
    mCurrentScript->endBlocking();
}

static QScriptValue safePrint(QScriptContext *context, QScriptEngine *engine)
{
    QString result;
    for (int i = 0; i < context->argumentCount(); ++i) {
        if (i != 0)
            result.append(QLatin1Char(' '));
        QString s(context->argument(i).toString());
        if (engine->hasUncaughtException())
            break;
        result.append(s);
    }
    if (engine->hasUncaughtException())
        return engine->uncaughtException();

#ifdef Q_OS_WIN
    if (IsDebuggerPresent())
        qDebug("%s", qPrintable(result));
#else
    qDebug("%s", qPrintable(result));
#endif

    return engine->undefinedValue();
}

Script::Script(const QString &name, const QString &scriptCode,
                           ScriptAdapter *adapter)
    : QObject(adapter)
    , mName(name)
    , mScriptCode(scriptCode)
    , mAdapter(adapter)
    , mPaused(false)
    , mTerminate(false)
{
    mCoroutine = Coroutine::build(this, &Script::run);
    mCoroutine->createStack(524228);

    mStopTimer.setInterval(10);
    connect(&mStopTimer, SIGNAL(timeout()), this, SLOT(suspend()));

    // trigger event processing during script evaluation
    mEngine.setProcessEventsInterval(10);

    // inject the ScriptAdapters functions into the global scope
    QScriptValue adapterValue = mEngine.newQObject(adapter);
    QStringList exposedFunctions = QStringList() << "yield" << "messageBox";
    foreach (const QString &functionName, exposedFunctions) {
        QScriptValue functionValue = adapterValue.property(functionName);
        mEngine.globalObject().setProperty(functionName, functionValue);
    }

    // override print, the default uses qDebug and that is not allowed in coroutines!
    QScriptValue printFn = mEngine.newFunction(safePrint, 1);
    mEngine.globalObject().setProperty("print", printFn);

    QHashIterator<QString, QObject *> iter(mAdapter->mScriptInterfaces);
    while (iter.hasNext()) {
        iter.next();
        QScriptValue interface = mEngine.newQObject(iter.value());
        mEngine.globalObject().setProperty(iter.key(), interface);
    }
}

void Script::run()
{
    mStopTimer.start();
    QScriptValue value = mEngine.evaluate(mScriptCode);
    if (value.isError()) {
        qWarning() << "Script execution resulted in an error:" << value.toString();
    }
    mStopTimer.stop();
}

void Script::requestTerminate()
{
    mTerminate = true;
}

void Script::togglePause()
{
    mPaused = !mPaused;
}

void Script::suspend()
{
    if (Coroutine::currentCoroutine() == mCoroutine) {
        Coroutine::yield();

        if (mTerminate) {
            mEngine.abortEvaluation(mEngine.currentContext()->throwError("Aborted"));
            mStopTimer.stop();
        }
    }
}

void Script::beginBlocking()
{
    mStopTimer.stop();
}

void Script::endBlocking()
{
    mStopTimer.start();
}