summaryrefslogtreecommitdiffstats
path: root/src/declarative/qml/qdeclarativeworkerscript.cpp
blob: 784353af2de1023275a61ec88d330dcc1dfede63 (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
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdeclarativeworkerscript_p.h"

#include "qdeclarativeengine_p.h"

#include <QtCore/qcoreevent.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qdebug.h>
#include <QtScript/qscriptengine.h>
#include <QtCore/qmutex.h>
#include <QtCore/qwaitcondition.h>
#include <QtScript/qscriptvalueiterator.h>
#include <QtCore/qfile.h>
#include <QtNetwork/qnetworkaccessmanager.h>
#include <QtDeclarative/qdeclarativeinfo.h>
#include "qdeclarativenetworkaccessmanagerfactory.h"


QT_BEGIN_NAMESPACE

class WorkerDataEvent : public QEvent
{
public:
    enum Type { WorkerData = QEvent::User };

    WorkerDataEvent(int workerId, const QVariant &data);
    virtual ~WorkerDataEvent();

    int workerId() const;
    QVariant data() const;

private:
    int m_id;
    QVariant m_data;
};

class WorkerLoadEvent : public QEvent
{
public:
    enum Type { WorkerLoad = WorkerDataEvent::WorkerData + 1 };

    WorkerLoadEvent(int workerId, const QUrl &url);

    int workerId() const;
    QUrl url() const;

private:
    int m_id;
    QUrl m_url;
};

class WorkerRemoveEvent : public QEvent
{
public:
    enum Type { WorkerRemove = WorkerLoadEvent::WorkerLoad + 1 };

    WorkerRemoveEvent(int workerId);

    int workerId() const;

private:
    int m_id;
};

class QDeclarativeWorkerScriptEnginePrivate : public QObject
{
public:
    QDeclarativeWorkerScriptEnginePrivate(QDeclarativeEngine *eng);

    struct ScriptEngine : public QDeclarativeScriptEngine 
    {
        ScriptEngine(QDeclarativeWorkerScriptEnginePrivate *parent) : QDeclarativeScriptEngine(0), p(parent), accessManager(0) {}
        ~ScriptEngine() { delete accessManager; }
        QDeclarativeWorkerScriptEnginePrivate *p;
        QNetworkAccessManager *accessManager;

        virtual QNetworkAccessManager *networkAccessManager() { 
            if (!accessManager) {
                if (p->qmlengine && p->qmlengine->networkAccessManagerFactory()) {
                    accessManager = p->qmlengine->networkAccessManagerFactory()->create(this);
                } else {
                    accessManager = new QNetworkAccessManager(this);
                }
            }
            return accessManager;
        }
    };
    ScriptEngine *workerEngine;
    static QDeclarativeWorkerScriptEnginePrivate *get(QScriptEngine *e) {
        return static_cast<ScriptEngine *>(e)->p;
    }

    QDeclarativeEngine *qmlengine;

    QMutex m_lock;
    QWaitCondition m_wait;

    struct WorkerScript {
        WorkerScript();

        int id;
        bool initialized;
        QDeclarativeWorkerScript *owner;
        QScriptValue object;

        QScriptValue callback;
    };

    QHash<int, WorkerScript *> workers;
    QScriptValue getWorker(int);

    int m_nextId;

    static QVariant scriptValueToVariant(const QScriptValue &);
    static QScriptValue variantToScriptValue(const QVariant &, QScriptEngine *);

    static QScriptValue onMessage(QScriptContext *ctxt, QScriptEngine *engine);
    static QScriptValue sendMessage(QScriptContext *ctxt, QScriptEngine *engine);

protected:
    virtual bool event(QEvent *);

private:
    void processMessage(int, const QVariant &);
    void processLoad(int, const QUrl &);
};

// Currently this will leak as no-one releases it in the worker thread 
class QDeclarativeWorkerListModelAgent : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int count READ count)

public:
    QDeclarativeWorkerListModelAgent(QDeclarativeWorkerListModel *);
    ~QDeclarativeWorkerListModelAgent();

    void addref();
    void release();

    int count() const;

    Q_INVOKABLE void clear();
    Q_INVOKABLE void remove(int index);
    Q_INVOKABLE void append(const QScriptValue &);
    Q_INVOKABLE void insert(int index, const QScriptValue&);
    Q_INVOKABLE QScriptValue get(int index) const;
    Q_INVOKABLE void set(int index, const QScriptValue &);
    Q_INVOKABLE void sync();

    struct VariantRef
    {
        VariantRef() : a(0) {}
        VariantRef(const VariantRef &r) : a(r.a) { if (a) a->addref(); }
        VariantRef(QDeclarativeWorkerListModelAgent *_a) : a(_a) { if (a) a->addref(); }
        ~VariantRef() { if (a) a->release(); }

        VariantRef &operator=(const VariantRef &o) { 
            if (o.a) o.a->addref(); 
            if (a) a->release(); a = o.a; 
            return *this; 
        }

        QDeclarativeWorkerListModelAgent *a;
    };
protected:
    virtual bool event(QEvent *);

private:
    friend class QDeclarativeWorkerScriptEnginePrivate;
    friend class QDeclarativeWorkerListModel;
    QScriptEngine *m_engine;

    struct Change {
        enum { Inserted, Removed, Moved, Changed } type;
        int index; // Inserted/Removed/Moved/Changed
        int count; // Inserted/Removed/Moved/Changed
        int to;    // Moved
    };

    struct Data {
        QHash<int, QString> roles;
        QHash<QString, int> strings;
        QList<QHash<int, QVariant> > values;
        QList<Change> changes;

        void clearChange();
        void insertChange(int index, int count);
        void removeChange(int index, int count);
        void changedChange(int index, int count);
    };
    Data data;

    struct Sync : public QEvent {
        Sync() : QEvent(QEvent::User) {}
        Data data;
    };

    QAtomicInt m_ref;
    QDeclarativeWorkerListModel *m_model;
};

QT_END_NAMESPACE

Q_DECLARE_METATYPE(QDeclarativeWorkerListModelAgent::VariantRef);

QT_BEGIN_NAMESPACE

QDeclarativeWorkerScriptEnginePrivate::QDeclarativeWorkerScriptEnginePrivate(QDeclarativeEngine *engine)
: workerEngine(0), qmlengine(engine), m_nextId(0)
{
}

QScriptValue QDeclarativeWorkerScriptEnginePrivate::onMessage(QScriptContext *ctxt, QScriptEngine *engine)
{
    QDeclarativeWorkerScriptEnginePrivate *p = QDeclarativeWorkerScriptEnginePrivate::get(engine);

    int id = ctxt->thisObject().data().toVariant().toInt();

    WorkerScript *script = p->workers.value(id);
    if (!script)
        return engine->undefinedValue();

    if (ctxt->argumentCount() >= 1) 
        script->callback = ctxt->argument(0);

    return script->callback;
}

QScriptValue QDeclarativeWorkerScriptEnginePrivate::sendMessage(QScriptContext *ctxt, QScriptEngine *engine)
{
    if (!ctxt->argumentCount())
        return engine->undefinedValue();

    QDeclarativeWorkerScriptEnginePrivate *p = QDeclarativeWorkerScriptEnginePrivate::get(engine);

    int id = ctxt->thisObject().data().toVariant().toInt();

    WorkerScript *script = p->workers.value(id);
    if (!script) 
        return engine->undefinedValue();

    p->m_lock.lock();
    if (script->owner) 
        QCoreApplication::postEvent(script->owner, 
                                    new WorkerDataEvent(0, scriptValueToVariant(ctxt->argument(0))));
    p->m_lock.unlock();

    return engine->undefinedValue();
}

QScriptValue QDeclarativeWorkerScriptEnginePrivate::getWorker(int id)
{
    QHash<int, WorkerScript *>::ConstIterator iter = workers.find(id);

    if (iter == workers.end())
        return workerEngine->nullValue();

    WorkerScript *script = *iter;
    if (!script->initialized) {

        script->initialized = true;
        script->object = workerEngine->newObject();

        QScriptValue api = workerEngine->newObject();
        api.setData(script->id);

        api.setProperty(QLatin1String("onMessage"), workerEngine->newFunction(onMessage), 
                        QScriptValue::PropertyGetter | QScriptValue::PropertySetter);
        api.setProperty(QLatin1String("sendMessage"), workerEngine->newFunction(sendMessage));

        script->object.setProperty(QLatin1String("WorkerScript"), api);
    }

    return script->object;
}

bool QDeclarativeWorkerScriptEnginePrivate::event(QEvent *event)
{
    if (event->type() == (QEvent::Type)WorkerDataEvent::WorkerData) {
        WorkerDataEvent *workerEvent = static_cast<WorkerDataEvent *>(event);
        processMessage(workerEvent->workerId(), workerEvent->data());
        return true;
    } else if (event->type() == (QEvent::Type)WorkerLoadEvent::WorkerLoad) {
        WorkerLoadEvent *workerEvent = static_cast<WorkerLoadEvent *>(event);
        processLoad(workerEvent->workerId(), workerEvent->url());
        return true;
    } else {
        return QObject::event(event);
    }
}

void QDeclarativeWorkerScriptEnginePrivate::processMessage(int id, const QVariant &data)
{
    WorkerScript *script = workers.value(id);
    if (!script)
        return;

    if (script->callback.isFunction()) {
        QScriptValue args = workerEngine->newArray(1);
        args.setProperty(0, variantToScriptValue(data, workerEngine));

        script->callback.call(script->object, args);
    }
}

void QDeclarativeWorkerScriptEnginePrivate::processLoad(int id, const QUrl &url)
{
    if (url.isRelative() || url.scheme() != QLatin1String("file"))
        return;

    QString fileName = url.toLocalFile();

    QFile f(fileName);
    if (f.open(QIODevice::ReadOnly)) {
        QByteArray data = f.readAll();
        QString script = QString::fromUtf8(data);

        QScriptValue activation = getWorker(id);

        QScriptContext *ctxt = workerEngine->pushContext();
        ctxt->setActivationObject(activation);

        workerEngine->baseUrl = url;
        workerEngine->evaluate(script);

        workerEngine->popContext();
    } else {
        qWarning().nospace() << "WorkerScript: Cannot find source file " << url.toString();
    }
}

QVariant QDeclarativeWorkerScriptEnginePrivate::scriptValueToVariant(const QScriptValue &value)
{
    if (value.isBool()) {
        return QVariant(value.toBool());
    } else if (value.isString()) {
        return QVariant(value.toString());
    } else if (value.isNumber()) {
        return QVariant((qreal)value.toNumber());
    } else if (value.isArray()) {
        QVariantList list;

        quint32 length = (quint32)value.property(QLatin1String("length")).toNumber();

        for (quint32 ii = 0; ii < length; ++ii) {
            QVariant v = scriptValueToVariant(value.property(ii));
            list << v;
        }

        return QVariant(list);
    } else if (value.isQObject()) {
        QDeclarativeWorkerListModel *lm = qobject_cast<QDeclarativeWorkerListModel *>(value.toQObject());
        if (lm) {
            QDeclarativeWorkerListModelAgent::VariantRef v(lm->agent());
            return qVariantFromValue(v);
        } else {
            // No other QObject's are allowed to be sent
            return QVariant();
        }
    } else if (value.isObject()) {
        QVariantHash hash;

        QScriptValueIterator iter(value);

        while (iter.hasNext()) {
            iter.next();
            hash.insert(iter.name(), scriptValueToVariant(iter.value()));
        }

        return QVariant(hash);
    }

    return QVariant();

}

QScriptValue QDeclarativeWorkerScriptEnginePrivate::variantToScriptValue(const QVariant &value, QScriptEngine *engine)
{
    if (value.userType() == QVariant::Bool) {
        return QScriptValue(value.toBool());
    } else if (value.userType() == QVariant::String) {
        return QScriptValue(value.toString());
    } else if (value.userType() == QMetaType::QReal) {
        return QScriptValue(value.toReal());
    } else if (value.userType() == qMetaTypeId<QDeclarativeWorkerListModelAgent::VariantRef>()) {
        QDeclarativeWorkerListModelAgent::VariantRef vr = qvariant_cast<QDeclarativeWorkerListModelAgent::VariantRef>(value);
        if (vr.a->m_engine == 0)
            vr.a->m_engine = engine;
        else if (vr.a->m_engine != engine)
            return engine->nullValue();
        QScriptValue o = engine->newQObject(vr.a);
        o.setData(engine->newVariant(value)); // Keeps the agent ref so that it is cleaned up on gc
        return o;
    } else if (value.userType() == QMetaType::QVariantList) {
        QVariantList list = qvariant_cast<QVariantList>(value);
        QScriptValue rv = engine->newArray(list.count());

        for (quint32 ii = 0; ii < quint32(list.count()); ++ii) 
            rv.setProperty(ii, variantToScriptValue(list.at(ii), engine));

        return rv;
    } else if (value.userType() == QMetaType::QVariantHash) {

        QVariantHash hash = qvariant_cast<QVariantHash>(value);

        QScriptValue rv = engine->newObject();

        for (QVariantHash::ConstIterator iter = hash.begin(); iter != hash.end(); ++iter) 
            rv.setProperty(iter.key(), variantToScriptValue(iter.value(), engine));

        return rv;
    } else {
        return engine->nullValue();
    }
}

WorkerDataEvent::WorkerDataEvent(int workerId, const QVariant &data)
: QEvent((QEvent::Type)WorkerData), m_id(workerId), m_data(data)
{
}

WorkerDataEvent::~WorkerDataEvent()
{
}

int WorkerDataEvent::workerId() const
{
    return m_id;
}

QVariant WorkerDataEvent::data() const
{
    return m_data;
}

WorkerLoadEvent::WorkerLoadEvent(int workerId, const QUrl &url)
: QEvent((QEvent::Type)WorkerLoad), m_id(workerId), m_url(url)
{
}

int WorkerLoadEvent::workerId() const
{
    return m_id;
}

QUrl WorkerLoadEvent::url() const
{
    return m_url;
}

WorkerRemoveEvent::WorkerRemoveEvent(int workerId)
: QEvent((QEvent::Type)WorkerRemove), m_id(workerId)
{
}

int WorkerRemoveEvent::workerId() const
{
    return m_id;
}

QDeclarativeWorkerScriptEngine::QDeclarativeWorkerScriptEngine(QDeclarativeEngine *parent)
: QThread(parent), d(new QDeclarativeWorkerScriptEnginePrivate(parent))
{
    d->m_lock.lock();
    start(QThread::LowPriority);
    d->m_wait.wait(&d->m_lock);
    d->moveToThread(this);
    d->m_lock.unlock();
}

QDeclarativeWorkerScriptEngine::~QDeclarativeWorkerScriptEngine()
{
    qDeleteAll(d->workers);
    delete d; d = 0;
}

QDeclarativeWorkerScriptEnginePrivate::WorkerScript::WorkerScript()
: id(-1), initialized(false), owner(0)
{
}

int QDeclarativeWorkerScriptEngine::registerWorkerScript(QDeclarativeWorkerScript *owner)
{
    QDeclarativeWorkerScriptEnginePrivate::WorkerScript *script = new QDeclarativeWorkerScriptEnginePrivate::WorkerScript;
    script->id = d->m_nextId++;
    script->owner = owner;

    d->m_lock.lock();
    d->workers.insert(script->id, script);
    d->m_lock.unlock();

    return script->id;
}

void QDeclarativeWorkerScriptEngine::removeWorkerScript(int id)
{
    QCoreApplication::postEvent(d, new WorkerRemoveEvent(id));
}

void QDeclarativeWorkerScriptEngine::executeUrl(int id, const QUrl &url)
{
    QCoreApplication::postEvent(d, new WorkerLoadEvent(id, url));
}

void QDeclarativeWorkerScriptEngine::sendMessage(int id, const QVariant &data)
{
    QCoreApplication::postEvent(d, new WorkerDataEvent(id, data));
}

void QDeclarativeWorkerScriptEngine::run()
{
    d->m_lock.lock();

    d->workerEngine = new QDeclarativeWorkerScriptEnginePrivate::ScriptEngine(d);

    d->m_wait.wakeAll();

    d->m_lock.unlock();

    exec();

    delete d->workerEngine; d->workerEngine = 0;
}


/*!
    \qmlclass WorkerScript QDeclarativeWorkerScript
    \brief The WorkerScript element enables the use of threads in QML.

    Use WorkerScript to run operations in a new thread.
    This is useful for running operations in the background so
    that the main GUI thread is not blocked.

    Messages can be passed between the new thread and the parent thread
    using sendMessage() and the onMessage() handler.
    
    Here is an example:

    \qml
    import Qt 4.6

    Rectangle {
        width: 300
        height: 300

        Text {
            id: myText
            text: 'Click anywhere'
        }

        WorkerScript {
            id: myWorker
            source: "script.js"

            onMessage: {
                myText.text = messageObject.reply
            }
        }

        MouseArea { 
            anchors.fill: parent
            onClicked: myWorker.sendMessage( {'x': mouse.x, 'y': mouse.y} );
        }
    }
    \endqml

    The above worker script specifies a javascript file, "script.js", that handles
    the operations to be performed in the new thread:

    \qml
    WorkerScript.onMessage = function(message) {
        // ... long-running operations and calculations are done here
        WorkerScript.sendMessage( {'reply': 'Mouse is at ' + message.x + ',' + message.y} );
    }
    \endqml
    
    When the user clicks anywhere within the rectangle, \c sendMessage() is
    called, triggering the \tt WorkerScript.onMessage() handler in
    \tt source.js. This in turn sends a reply message that is then received
    by the \tt onMessage() handler of \tt myWorker.

    \sa WorkerListModel
*/
QDeclarativeWorkerScript::QDeclarativeWorkerScript(QObject *parent)
: QObject(parent), m_engine(0), m_scriptId(-1)
{
}

QDeclarativeWorkerScript::~QDeclarativeWorkerScript()
{
    if (m_scriptId != -1) m_engine->removeWorkerScript(m_scriptId);
}

/*!
    \qmlproperty url WorkerScript::source

    This holds the url of the javascript file that implements the
    \tt WorkerScript.onMessage() handler for threaded operations.
*/
QUrl QDeclarativeWorkerScript::source() const
{
    return m_source;
}

void QDeclarativeWorkerScript::setSource(const QUrl &source)
{
    if (m_source == source)
        return;

    m_source = source;

    if (m_engine) 
        m_engine->executeUrl(m_scriptId, m_source);

    emit sourceChanged();
}

/*
    \qmlmethod WorkerScript::sendMessage(jsobject message)

    Sends the given \a message to a worker script handler in another
    thread. The other worker script handler can receive this message
    through the onMessage() handler.
*/
void QDeclarativeWorkerScript::sendMessage(const QScriptValue &message)
{
    if (!m_engine) {
        qWarning("QDeclarativeWorkerScript: Attempt to send message before WorkerScript establishment");
        return;
    }

    m_engine->sendMessage(m_scriptId, QDeclarativeWorkerScriptEnginePrivate::scriptValueToVariant(message));
}

void QDeclarativeWorkerScript::componentComplete()
{
    if (!m_engine) {
        QDeclarativeEngine *engine = qmlEngine(this);
        if (!engine) {
            qWarning("QDeclarativeWorkerScript: componentComplete() called without qmlEngine() set");
            return;
        }

        m_engine = QDeclarativeEnginePrivate::get(engine)->getWorkerScriptEngine();
        m_scriptId = m_engine->registerWorkerScript(this);

        if (m_source.isValid())
            m_engine->executeUrl(m_scriptId, m_source);
    }
}

/*!
    \qmlsignal WorkerScript::onMessage(jsobject msg)

    This handler is called when a message \a msg is received from a worker
    script in another thread through a call to sendMessage().
*/

bool QDeclarativeWorkerScript::event(QEvent *event)
{
    if (event->type() == (QEvent::Type)WorkerDataEvent::WorkerData) {
        QDeclarativeEngine *engine = qmlEngine(this);
        if (engine) {
            QScriptEngine *scriptEngine = QDeclarativeEnginePrivate::getScriptEngine(engine);
            WorkerDataEvent *workerEvent = static_cast<WorkerDataEvent *>(event);
            QScriptValue value = 
                QDeclarativeWorkerScriptEnginePrivate::variantToScriptValue(workerEvent->data(), scriptEngine);
            emit message(value);
        }
        return true;
    } else {
        return QObject::event(event);
    }
}

void QDeclarativeWorkerListModelAgent::Data::clearChange() 
{ 
    changes.clear(); 
}

void QDeclarativeWorkerListModelAgent::Data::insertChange(int index, int count) 
{
    Change c = { Change::Inserted, index, count, 0 };
    changes << c;
}

void QDeclarativeWorkerListModelAgent::Data::removeChange(int index, int count) 
{
    Change c = { Change::Removed, index, count, 0 };
    changes << c;
}

void QDeclarativeWorkerListModelAgent::Data::changedChange(int index, int count)
{
    Change c = { Change::Changed, index, count, 0 };
    changes << c;
}

QDeclarativeWorkerListModelAgent::QDeclarativeWorkerListModelAgent(QDeclarativeWorkerListModel *m)
: m_engine(0), m_ref(1), m_model(m)
{
    data.roles = m_model->m_roles;
    data.strings = m_model->m_strings;
    data.values = m_model->m_values;
}

QDeclarativeWorkerListModelAgent::~QDeclarativeWorkerListModelAgent()
{
}

void QDeclarativeWorkerListModelAgent::addref()
{
    m_ref.ref();
}

void QDeclarativeWorkerListModelAgent::release()
{
    bool del = !m_ref.deref();

    if (del)
        delete this;
}

int QDeclarativeWorkerListModelAgent::count() const
{
    return data.values.count();
}

void QDeclarativeWorkerListModelAgent::clear()
{
    data.clearChange();
    data.removeChange(0, data.values.count());
    data.values.clear();
}

void QDeclarativeWorkerListModelAgent::remove(int index)
{
    if (data.values.count() <= index)
        return;

    data.values.removeAt(index);
    data.removeChange(index, 1);
}

void QDeclarativeWorkerListModelAgent::append(const QScriptValue &value)
{
    QHash<int, QVariant> row;

    QScriptValueIterator it(value);
    while (it.hasNext()) {
        it.next();
        QString name = it.name();
        QVariant v = it.value().toVariant();

        QHash<QString, int>::Iterator iter = data.strings.find(name);
        if (iter == data.strings.end()) {
            int role = data.roles.count();
            data.roles.insert(role, name);
            iter = data.strings.insert(name, role);
        }
        row.insert(*iter, v);
    }

    data.values.append(row);
    data.insertChange(data.values.count() - 1, 1);
}

void QDeclarativeWorkerListModelAgent::insert(int index, const QScriptValue &value)
{
    if (index > data.values.count())
        return;

    QHash<int, QVariant> row;

    QScriptValueIterator it(value);
    while (it.hasNext()) {
        it.next();
        QString name = it.name();
        QVariant v = it.value().toVariant();

        QHash<QString, int>::Iterator iter = data.strings.find(name);
        if (iter == data.strings.end()) {
            int role = data.roles.count();
            data.roles.insert(role, name);
            iter = data.strings.insert(name, role);
        }
        row.insert(*iter, v);
    }

    data.values.insert(index, row);
    data.insertChange(index, 1);
}

void QDeclarativeWorkerListModelAgent::set(int index, const QScriptValue &value)
{
    if (data.values.count() <= index)
        return;

    QHash<int, QVariant> row;

    QScriptValueIterator it(value);
    while (it.hasNext()) {
        it.next();
        QString name = it.name();
        QVariant v = it.value().toVariant();

        QHash<QString, int>::Iterator iter = data.strings.find(name);
        if (iter == data.strings.end()) {
            int role = data.roles.count();
            data.roles.insert(role, name);
            iter = data.strings.insert(name, role);
        }
        row.insert(*iter, v);
    }

    if (data.values.at(index) != row) {
        data.values[index] = row;
        data.changedChange(index, 1);
    }
}

QScriptValue QDeclarativeWorkerListModelAgent::get(int index) const
{
    if (data.values.count() <= index)
        return m_engine->undefinedValue();

    QScriptValue rv = m_engine->newObject();

    QHash<int, QVariant> row = data.values.at(index);
    for (QHash<int, QVariant>::ConstIterator iter = row.begin(); iter != row.end(); ++iter) 
        rv.setProperty(data.roles.value(iter.key()), qScriptValueFromValue(m_engine, iter.value()));

    return rv;
}

void QDeclarativeWorkerListModelAgent::sync()
{
    Sync *s = new Sync;
    s->data = data;
    data.changes.clear();
    QCoreApplication::postEvent(this, s);
}

bool QDeclarativeWorkerListModelAgent::event(QEvent *e)
{
    if (e->type() == QEvent::User) {
        Sync *s = static_cast<Sync *>(e);

        const QList<Change> &changes = s->data.changes;

        if (m_model) {
            bool cc = m_model->m_values.count() != s->data.values.count();

            m_model->m_roles = s->data.roles;
            m_model->m_strings = s->data.strings;
            m_model->m_values = s->data.values;

            for (int ii = 0; ii < changes.count(); ++ii) {
                const Change &change = changes.at(ii);
                switch (change.type) {
                case Change::Inserted:
                    emit m_model->itemsInserted(change.index, change.count);
                    break;
                case Change::Removed:
                    emit m_model->itemsRemoved(change.index, change.count);
                    break;
                case Change::Moved:
                    emit m_model->itemsMoved(change.index, change.to, change.count);
                    break;
                case Change::Changed:
                    emit m_model->itemsMoved(change.index, change.to, change.count);
                    break;
                }
            }

            if (cc)
                emit m_model->countChanged();
        }
    }

    return QObject::event(e);
}

/*!
    \qmlclass WorkerListModel QDeclarativeWorkerListModel
    \brief The WorkerListModel element provides a threaded list model.

    Use WorkerListModel together with WorkerScript to define a list model 
    that is controlled by a separate thread. This is useful if list modification 
    operations are synchronous and take some time: using WorkerListModel
    moves these operations to a different thread and avoids blocking of the
    main GUI thread.

    The thread that creates the WorkerListModel can modify the model for any
    initial set-up requirements. However, once the model has been modified by
    the associated WorkerScript, the model can only be modified by that worker
    script and becomes read-only to all other threads.
    
    Here is an example application that uses WorkerScript to append the
    current time to a WorkerListModel:

    \snippet examples/declarative/workerlistmodel/timedisplay.qml 0

    The included file, \tt dataloader.js, looks like this:

    \snippet examples/declarative/workerlistmodel/dataloader.js 0

    The application's \tt Timer object periodically sends a message to the
    worker script by calling \tt WorkerScript::sendMessage(). When this message
    is received, \tt WorkerScript.onMessage() is invoked in
    \tt dataloader.js, which appends the current time to the worker list
    model.

    Note that unlike ListModel, WorkerListModel does not have \tt move() and
    \tt setProperty() methods.

    \sa WorkerScript, ListModel
*/
QDeclarativeWorkerListModel::QDeclarativeWorkerListModel(QObject *parent)
: QListModelInterface(parent), m_agent(0)
{
}

QDeclarativeWorkerListModel::~QDeclarativeWorkerListModel()
{
    if (m_agent) {
        m_agent->m_model = 0;
        m_agent->release();
    }
}

/*!
    \qmlmethod WorkerListModel::clear()

    Deletes all content from the model. The properties are cleared such that
    different properties may be set on subsequent additions.

    \sa append() remove()
*/
void QDeclarativeWorkerListModel::clear()
{
    if (m_agent) {
        qmlInfo(this) << "List can only be modified from a WorkerScript";
        return;
    }

    int count = m_values.count();
    m_values.clear();
    if (count) {
        emit itemsRemoved(0, count);
        emit countChanged();
    }
}

/*!
    \qmlmethod WorkerListModel::remove(int index)

    Deletes the content at \a index from the model.

    \sa clear()
*/
void QDeclarativeWorkerListModel::remove(int index)
{
    if (m_agent) {
        qmlInfo(this) << "List can only be modified from a WorkerScript";
        return;
    }

    if (m_values.count() <= index)
        return;

    m_values.removeAt(index);
    emit itemsRemoved(index, 1);
    emit countChanged();
}

/*!
    \qmlmethod WorkerListModel::append(jsobject dict)

    Adds a new item to the end of the list model, with the
    values in \a dict.

    \code
        FruitModel.append({"cost": 5.95, "name":"Pizza"})
    \endcode

    \sa set() remove()
*/
void QDeclarativeWorkerListModel::append(const QScriptValue &value)
{
    if (m_agent) {
        qmlInfo(this) << "List can only be modified from a WorkerScript";
        return;
    }

    QHash<int, QVariant> data;

    QScriptValueIterator it(value);
    while (it.hasNext()) {
        it.next();
        QString name = it.name();
        QVariant v = it.value().toVariant();

        QHash<QString, int>::Iterator iter = m_strings.find(name);
        if (iter == m_strings.end()) {
            int role = m_roles.count();
            m_roles.insert(role, name);
            iter = m_strings.insert(name, role);
        }
        data.insert(*iter, v);
    }

    m_values.append(data);

    emit itemsInserted(m_values.count() - 1, 1);
    emit countChanged();
}

/*!
    \qmlmethod WorkerListModel::insert(int index, jsobject dict)

    Adds a new item to the list model at position \a index, with the
    values in \a dict.

    \code
        FruitModel.insert(2, {"cost": 5.95, "name":"Pizza"})
    \endcode

    The \a index must be to an existing item in the list, or one past
    the end of the list (equivalent to append).

    \sa set() append()
*/
void QDeclarativeWorkerListModel::insert(int index, const QScriptValue &value)
{
    if (m_agent) {
        qmlInfo(this) << "List can only be modified from a WorkerScript";
        return;
    }

    if (index > m_values.count())
        return;

    QHash<int, QVariant> data;

    QScriptValueIterator it(value);
    while (it.hasNext()) {
        it.next();
        QString name = it.name();
        QVariant v = it.value().toVariant();

        QHash<QString, int>::Iterator iter = m_strings.find(name);
        if (iter == m_strings.end()) {
            int role = m_roles.count();
            m_roles.insert(role, name);
            iter = m_strings.insert(name, role);
        }
        data.insert(*iter, v);
    }

    m_values.insert(index, data);
    emit itemsInserted(index, 1);
    emit countChanged();
}

/*!
    \qmlmethod object ListModel::get(int index)

    Returns the item at \a index in the list model.

    \code
        FruitModel.append({"cost": 5.95, "name":"Jackfruit"})
        FruitModel.get(0).cost
    \endcode

    The \a index must be an element in the list.

    Note that properties of the returned object that are themselves objects
    will also be models, and this get() method is used to access elements:

    \code
        FruitModel.append(..., "attributes":
            [{"name":"spikes","value":"7mm"},
             {"name":"color","value":"green"}]);
        FruitModel.get(0).attributes.get(1).value; // == "green"
    \endcode

    \sa append()
*/
QScriptValue QDeclarativeWorkerListModel::get(int index) const
{
    QDeclarativeEngine *engine = qmlEngine(this);
    if (!engine || m_values.count() <= index)
        return QScriptValue();

    QScriptEngine *scriptEngine = QDeclarativeEnginePrivate::getScriptEngine(engine);
    QScriptValue rv = scriptEngine->newObject();

    QHash<int, QVariant> data = m_values.at(index);
    for (QHash<int, QVariant>::ConstIterator iter = data.begin(); iter != data.end(); ++iter) 
        rv.setProperty(m_roles.value(iter.key()), qScriptValueFromValue(scriptEngine, iter.value()));

    return rv;
}

/*!
    \qmlmethod WorkerListModel::set(int index, jsobject dict)

    Changes the item at \a index in the list model with the
    values in \a dict. Properties not appearing in \a valuemap
    are left unchanged.

    \code
        FruitModel.set(3, {"cost": 5.95, "name":"Pizza"})
    \endcode

    The \a index must be an element in the list.

    \sa append()
*/
void QDeclarativeWorkerListModel::set(int index, const QScriptValue &value)
{
    if (m_agent) {
        qmlInfo(this) << "List can only be modified from a WorkerScript";
        return;
    }

    if (m_values.count() <= index)
        return;

    QHash<int, QVariant> data;

    QScriptValueIterator it(value);
    while (it.hasNext()) {
        it.next();
        QString name = it.name();
        QVariant v = it.value().toVariant();

        QHash<QString, int>::Iterator iter = m_strings.find(name);
        if (iter == m_strings.end()) {
            int role = m_roles.count();
            m_roles.insert(role, name);
            iter = m_strings.insert(name, role);
        }
        data.insert(*iter, v);
    }

    if (m_values.at(index) != data) {
        m_values[index] = data;
        emit itemsChanged(index, 1, m_roles.keys());
    }
}

/*!
    \qmlmethod WorkerListModel::sync()

    Writes any unsaved changes to the list model. This must be called after
    changes have been made to the list model in the worker script.

    Note that this method can only be called from the associated worker script.
*/
void QDeclarativeWorkerListModel::sync()
{
    // This is really a dummy method to make it look like sync() exists in
    // WorkerListModel (and not QDeclarativeWorkerListModelAgent) and to let
    // us document sync().
    qmlInfo(this) << "sync() can only be called from a WorkerScript";
}

QDeclarativeWorkerListModelAgent *QDeclarativeWorkerListModel::agent()
{
    if (!m_agent) 
        m_agent = new QDeclarativeWorkerListModelAgent(this);

    return m_agent;
}

QList<int> QDeclarativeWorkerListModel::roles() const
{
    return m_roles.keys();
}

QString QDeclarativeWorkerListModel::toString(int role) const
{
    return m_roles.value(role);
}

/*!
    \qmlproperty int ListModel::count
    The number of data entries in the model.
*/
int QDeclarativeWorkerListModel::count() const
{
    return m_values.count();
}

QHash<int,QVariant> QDeclarativeWorkerListModel::data(int index, const QList<int> &) const
{
    if (m_values.count() <= index)
        return QHash<int, QVariant>();
    else
        return m_values.at(index);
}

QVariant QDeclarativeWorkerListModel::data(int index, int role) const
{
    if (m_values.count() <= index)
        return QVariant();
    else
        return m_values.at(index).value(role);
}

QT_END_NAMESPACE

#include "qdeclarativeworkerscript.moc"