Permit signals to be emitted in a different thread
[profile/ivi/qtdeclarative.git] / src / qml / qml / qqmlvmemetaobject.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtQml module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qqmlvmemetaobject_p.h"
43
44
45 #include "qqml.h"
46 #include <private/qqmlrefcount_p.h>
47 #include "qqmlexpression.h"
48 #include "qqmlexpression_p.h"
49 #include "qqmlcontext_p.h"
50 #include "qqmlbinding_p.h"
51 #include "qqmlpropertyvalueinterceptor_p.h"
52
53 #include <private/qv8variantresource_p.h>
54 #include <private/qqmlglobal_p.h>
55
56 Q_DECLARE_METATYPE(QJSValue);
57
58 QT_BEGIN_NAMESPACE
59
60 QQmlVMEVariantQObjectPtr::QQmlVMEVariantQObjectPtr()
61     : QQmlGuard<QObject>(0), m_target(0), m_index(-1)
62 {
63 }
64
65 QQmlVMEVariantQObjectPtr::~QQmlVMEVariantQObjectPtr()
66 {
67 }
68
69 void QQmlVMEVariantQObjectPtr::objectDestroyed(QObject *)
70 {
71     if (m_target && m_index >= 0)
72         m_target->activate(m_target->object, m_target->methodOffset + m_index, 0);
73 }
74
75 void QQmlVMEVariantQObjectPtr::setGuardedValue(QObject *obj, QQmlVMEMetaObject *target, int index)
76 {
77     m_target = target;
78     m_index = index;
79     setObject(obj);
80 }
81
82 class QQmlVMEVariant
83 {
84 public:
85     inline QQmlVMEVariant();
86     inline ~QQmlVMEVariant();
87
88     inline const void *dataPtr() const;
89     inline void *dataPtr();
90     inline int dataType() const;
91     inline size_t dataSize() const;
92
93     inline QObject *asQObject();
94     inline const QVariant &asQVariant();
95     inline int asInt();
96     inline bool asBool();
97     inline double asDouble();
98     inline const QString &asQString();
99     inline const QUrl &asQUrl();
100     inline const QTime &asQTime();
101     inline const QDate &asQDate();
102     inline const QDateTime &asQDateTime();
103     inline const QRectF &asQRectF();
104     inline const QJSValue &asQJSValue();
105
106     inline void setValue(QObject *v, QQmlVMEMetaObject *target, int index);
107     inline void setValue(const QVariant &);
108     inline void setValue(int);
109     inline void setValue(bool);
110     inline void setValue(double);
111     inline void setValue(const QString &);
112     inline void setValue(const QUrl &);
113     inline void setValue(const QTime &);
114     inline void setValue(const QDate &);
115     inline void setValue(const QDateTime &);
116     inline void setValue(const QRectF &);
117     inline void setValue(const QJSValue &);
118
119     inline void setDataType(int t);
120
121     inline void ensureValueType(int);
122
123 private:
124     int type;
125     void *data[8]; // Large enough to hold all types
126
127     inline void cleanup();
128 };
129
130 class QQmlVMEMetaObjectEndpoint : public QQmlNotifierEndpoint
131 {
132 public:
133     QQmlVMEMetaObjectEndpoint();
134     static void vmecallback(QQmlNotifierEndpoint *, void **);
135     void tryConnect();
136
137     QFlagPointer<QQmlVMEMetaObject> metaObject;
138 };
139
140
141 QQmlVMEVariant::QQmlVMEVariant()
142 : type(QVariant::Invalid)
143 {
144 }
145
146 QQmlVMEVariant::~QQmlVMEVariant()
147 {
148     cleanup();
149 }
150
151 void QQmlVMEVariant::cleanup()
152 {
153     if (type == QVariant::Invalid) {
154     } else if (type == QMetaType::Int ||
155                type == QMetaType::Bool ||
156                type == QMetaType::Double) {
157         type = QVariant::Invalid;
158     } else if (type == QMetaType::QObjectStar) {
159         ((QQmlVMEVariantQObjectPtr*)dataPtr())->~QQmlVMEVariantQObjectPtr();
160         type = QVariant::Invalid;
161     } else if (type == QMetaType::QString) {
162         ((QString *)dataPtr())->~QString();
163         type = QVariant::Invalid;
164     } else if (type == QMetaType::QUrl) {
165         ((QUrl *)dataPtr())->~QUrl();
166         type = QVariant::Invalid;
167     } else if (type == QMetaType::QTime) {
168         ((QTime *)dataPtr())->~QTime();
169         type = QVariant::Invalid;
170     } else if (type == QMetaType::QDate) {
171         ((QDate *)dataPtr())->~QDate();
172         type = QVariant::Invalid;
173     } else if (type == QMetaType::QDateTime) {
174         ((QDateTime *)dataPtr())->~QDateTime();
175         type = QVariant::Invalid;
176     } else if (type == QMetaType::QRectF) {
177         ((QRectF *)dataPtr())->~QRectF();
178         type = QVariant::Invalid;
179     } else if (type == qMetaTypeId<QVariant>()) {
180         ((QVariant *)dataPtr())->~QVariant();
181         type = QVariant::Invalid;
182     } else if (type == qMetaTypeId<QJSValue>()) {
183         ((QJSValue *)dataPtr())->~QJSValue();
184         type = QVariant::Invalid;
185     } else {
186         if (QQml_valueTypeProvider()->destroyValueType(type, dataPtr(), dataSize())) {
187             type = QVariant::Invalid;
188         }
189     }
190 }
191
192 int QQmlVMEVariant::dataType() const
193 {
194     return type;
195 }
196
197 const void *QQmlVMEVariant::dataPtr() const
198 {
199     return &data;
200 }
201
202 void *QQmlVMEVariant::dataPtr() 
203 {
204     return &data;
205 }
206
207 size_t QQmlVMEVariant::dataSize() const
208 {
209     return sizeof(data);
210 }
211
212 QObject *QQmlVMEVariant::asQObject() 
213 {
214     if (type != QMetaType::QObjectStar)
215         setValue((QObject *)0, 0, -1);
216
217     return *(QQmlGuard<QObject> *)(dataPtr());
218 }
219
220 const QVariant &QQmlVMEVariant::asQVariant() 
221 {
222     if (type != QMetaType::QVariant)
223         setValue(QVariant());
224
225     return *(QVariant *)(dataPtr());
226 }
227
228 int QQmlVMEVariant::asInt() 
229 {
230     if (type != QMetaType::Int)
231         setValue(int(0));
232
233     return *(int *)(dataPtr());
234 }
235
236 bool QQmlVMEVariant::asBool() 
237 {
238     if (type != QMetaType::Bool)
239         setValue(bool(false));
240
241     return *(bool *)(dataPtr());
242 }
243
244 double QQmlVMEVariant::asDouble() 
245 {
246     if (type != QMetaType::Double)
247         setValue(double(0));
248
249     return *(double *)(dataPtr());
250 }
251
252 const QString &QQmlVMEVariant::asQString() 
253 {
254     if (type != QMetaType::QString)
255         setValue(QString());
256
257     return *(QString *)(dataPtr());
258 }
259
260 const QUrl &QQmlVMEVariant::asQUrl() 
261 {
262     if (type != QMetaType::QUrl)
263         setValue(QUrl());
264
265     return *(QUrl *)(dataPtr());
266 }
267
268 const QTime &QQmlVMEVariant::asQTime() 
269 {
270     if (type != QMetaType::QTime)
271         setValue(QTime());
272
273     return *(QTime *)(dataPtr());
274 }
275
276 const QDate &QQmlVMEVariant::asQDate() 
277 {
278     if (type != QMetaType::QDate)
279         setValue(QDate());
280
281     return *(QDate *)(dataPtr());
282 }
283
284 const QDateTime &QQmlVMEVariant::asQDateTime() 
285 {
286     if (type != QMetaType::QDateTime)
287         setValue(QDateTime());
288
289     return *(QDateTime *)(dataPtr());
290 }
291
292 const QRectF &QQmlVMEVariant::asQRectF()
293 {
294     if (type != QMetaType::QRectF)
295         setValue(QRectF());
296
297     return *(QRectF *)(dataPtr());
298 }
299
300 const QJSValue &QQmlVMEVariant::asQJSValue()
301 {
302     if (type != qMetaTypeId<QJSValue>())
303         setValue(QJSValue());
304
305     return *(QJSValue *)(dataPtr());
306 }
307
308 void QQmlVMEVariant::setValue(QObject *v, QQmlVMEMetaObject *target, int index)
309 {
310     if (type != QMetaType::QObjectStar) {
311         cleanup();
312         type = QMetaType::QObjectStar;
313         new (dataPtr()) QQmlVMEVariantQObjectPtr;
314     }
315     reinterpret_cast<QQmlVMEVariantQObjectPtr*>(dataPtr())->setGuardedValue(v, target, index);
316 }
317
318 void QQmlVMEVariant::setValue(const QVariant &v)
319 {
320     if (type != qMetaTypeId<QVariant>()) {
321         cleanup();
322         type = qMetaTypeId<QVariant>();
323         new (dataPtr()) QVariant(v);
324     } else {
325         *(QVariant *)(dataPtr()) = v;
326     }
327 }
328
329 void QQmlVMEVariant::setValue(int v)
330 {
331     if (type != QMetaType::Int) {
332         cleanup();
333         type = QMetaType::Int;
334     }
335     *(int *)(dataPtr()) = v;
336 }
337
338 void QQmlVMEVariant::setValue(bool v)
339 {
340     if (type != QMetaType::Bool) {
341         cleanup();
342         type = QMetaType::Bool;
343     }
344     *(bool *)(dataPtr()) = v;
345 }
346
347 void QQmlVMEVariant::setValue(double v)
348 {
349     if (type != QMetaType::Double) {
350         cleanup();
351         type = QMetaType::Double;
352     }
353     *(double *)(dataPtr()) = v;
354 }
355
356 void QQmlVMEVariant::setValue(const QString &v)
357 {
358     if (type != QMetaType::QString) {
359         cleanup();
360         type = QMetaType::QString;
361         new (dataPtr()) QString(v);
362     } else {
363         *(QString *)(dataPtr()) = v;
364     }
365 }
366
367 void QQmlVMEVariant::setValue(const QUrl &v)
368 {
369     if (type != QMetaType::QUrl) {
370         cleanup();
371         type = QMetaType::QUrl;
372         new (dataPtr()) QUrl(v);
373     } else {
374         *(QUrl *)(dataPtr()) = v;
375     }
376 }
377
378 void QQmlVMEVariant::setValue(const QTime &v)
379 {
380     if (type != QMetaType::QTime) {
381         cleanup();
382         type = QMetaType::QTime;
383         new (dataPtr()) QTime(v);
384     } else {
385         *(QTime *)(dataPtr()) = v;
386     }
387 }
388
389 void QQmlVMEVariant::setValue(const QDate &v)
390 {
391     if (type != QMetaType::QDate) {
392         cleanup();
393         type = QMetaType::QDate;
394         new (dataPtr()) QDate(v);
395     } else {
396         *(QDate *)(dataPtr()) = v;
397     }
398 }
399
400 void QQmlVMEVariant::setValue(const QDateTime &v)
401 {
402     if (type != QMetaType::QDateTime) {
403         cleanup();
404         type = QMetaType::QDateTime;
405         new (dataPtr()) QDateTime(v);
406     } else {
407         *(QDateTime *)(dataPtr()) = v;
408     }
409 }
410
411 void QQmlVMEVariant::setValue(const QRectF &v)
412 {
413     if (type != QMetaType::QRectF) {
414         cleanup();
415         type = QMetaType::QRectF;
416         new (dataPtr()) QRectF(v);
417     } else {
418         *(QRectF *)(dataPtr()) = v;
419     }
420 }
421
422 void QQmlVMEVariant::setValue(const QJSValue &v)
423 {
424     if (type != qMetaTypeId<QJSValue>()) {
425         cleanup();
426         type = qMetaTypeId<QJSValue>();
427         new (dataPtr()) QJSValue(v);
428     } else {
429         *(QJSValue *)(dataPtr()) = v;
430     }
431 }
432
433 void QQmlVMEVariant::setDataType(int t)
434 {
435     type = t;
436 }
437
438 void QQmlVMEVariant::ensureValueType(int t)
439 {
440     if (type != t) {
441         cleanup();
442         type = t;
443         QQml_valueTypeProvider()->initValueType(t, dataPtr(), dataSize());
444     }
445 }
446
447 QQmlVMEMetaObjectEndpoint::QQmlVMEMetaObjectEndpoint()
448 {
449     callback = &vmecallback;
450 }
451
452 void QQmlVMEMetaObjectEndpoint::vmecallback(QQmlNotifierEndpoint *e, void **)
453 {
454     QQmlVMEMetaObjectEndpoint *vmee = static_cast<QQmlVMEMetaObjectEndpoint*>(e);
455     vmee->tryConnect();
456 }
457
458 void QQmlVMEMetaObjectEndpoint::tryConnect()
459 {
460     int aliasId = this - metaObject->aliasEndpoints;
461
462     if (metaObject.flag()) {
463         // This is actually notify
464         int sigIdx = metaObject->methodOffset + aliasId + metaObject->metaData->propertyCount;
465         QMetaObject::activate(metaObject->object, sigIdx, 0);
466     } else {
467         QQmlVMEMetaData::AliasData *d = metaObject->metaData->aliasData() + aliasId;
468         if (!d->isObjectAlias()) {
469             QQmlContextData *ctxt = metaObject->ctxt;
470             QObject *target = ctxt->idValues[d->contextIdx].data();
471             if (!target)
472                 return;
473
474             QMetaProperty prop = target->metaObject()->property(d->propertyIndex());
475             if (prop.hasNotifySignal())
476                 connect(target, prop.notifySignalIndex(), ctxt->engine);
477         }
478
479         metaObject.setFlag();
480     }
481 }
482
483 QQmlVMEMetaObject::QQmlVMEMetaObject(QObject *obj,
484                                                      const QMetaObject *other, 
485                                                      const QQmlVMEMetaData *meta,
486                                                      QQmlCompiledData *cdata)
487 : QV8GCCallback::Node(GcPrologueCallback), object(obj), compiledData(cdata),
488   ctxt(QQmlData::get(obj, true)->outerContext), metaData(meta), data(0),
489   aliasEndpoints(0), firstVarPropertyIndex(-1), varPropertiesInitialized(false),
490   v8methods(0), parent(0)
491 {
492     compiledData->addref();
493
494     *static_cast<QMetaObject *>(this) = *other;
495     this->d.superdata = obj->metaObject();
496
497     QObjectPrivate *op = QObjectPrivate::get(obj);
498     if (op->metaObject)
499         parent = static_cast<QAbstractDynamicMetaObject*>(op->metaObject);
500     op->metaObject = this;
501
502     propOffset = QAbstractDynamicMetaObject::propertyOffset();
503     methodOffset = QAbstractDynamicMetaObject::methodOffset();
504
505     data = new QQmlVMEVariant[metaData->propertyCount - metaData->varPropertyCount];
506
507     aConnected.resize(metaData->aliasCount);
508     int list_type = qMetaTypeId<QQmlListProperty<QObject> >();
509
510     // ### Optimize
511     for (int ii = 0; ii < metaData->propertyCount - metaData->varPropertyCount; ++ii) {
512         int t = (metaData->propertyData() + ii)->propertyType;
513         if (t == list_type) {
514             listProperties.append(List(methodOffset + ii));
515             data[ii].setValue(listProperties.count() - 1);
516         } 
517     }
518
519     firstVarPropertyIndex = metaData->propertyCount - metaData->varPropertyCount;
520     if (metaData->varPropertyCount)
521         QV8GCCallback::addGcCallbackNode(this);
522 }
523
524 QQmlVMEMetaObject::~QQmlVMEMetaObject()
525 {
526     compiledData->release();
527     delete parent;
528     delete [] data;
529     delete [] aliasEndpoints;
530
531     for (int ii = 0; v8methods && ii < metaData->methodCount; ++ii) {
532         qPersistentDispose(v8methods[ii]);
533     }
534     delete [] v8methods;
535
536     if (metaData->varPropertyCount)
537         qPersistentDispose(varProperties); // if not weak, will not have been cleaned up by the callback.
538 }
539
540 int QQmlVMEMetaObject::metaCall(QMetaObject::Call c, int _id, void **a)
541 {
542     int id = _id;
543     if(c == QMetaObject::WriteProperty) {
544         int flags = *reinterpret_cast<int*>(a[3]);
545         if (!(flags & QQmlPropertyPrivate::BypassInterceptor)
546             && !aInterceptors.isEmpty()
547             && aInterceptors.testBit(id)) {
548             QPair<int, QQmlPropertyValueInterceptor*> pair = interceptors.value(id);
549             int valueIndex = pair.first;
550             QQmlPropertyValueInterceptor *vi = pair.second;
551             int type = property(id).userType();
552
553             if (type != QVariant::Invalid) {
554                 if (valueIndex != -1) {
555                     QQmlEnginePrivate *ep = ctxt?QQmlEnginePrivate::get(ctxt->engine):0;
556                     QQmlValueType *valueType = 0;
557                     if (ep) valueType = ep->valueTypes[type];
558                     else valueType = QQmlValueTypeFactory::valueType(type);
559                     Q_ASSERT(valueType);
560
561                     valueType->setValue(QVariant(type, a[0]));
562                     QMetaProperty valueProp = valueType->metaObject()->property(valueIndex);
563                     vi->write(valueProp.read(valueType));
564
565                     if (!ep) delete valueType;
566                     return -1;
567                 } else {
568                     vi->write(QVariant(type, a[0]));
569                     return -1;
570                 }
571             }
572         }
573     }
574     if (c == QMetaObject::ReadProperty || c == QMetaObject::WriteProperty || c == QMetaObject::ResetProperty) {
575         if (id >= propOffset) {
576             id -= propOffset;
577
578             if (id < metaData->propertyCount) {
579                int t = (metaData->propertyData() + id)->propertyType;
580                 bool needActivate = false;
581
582                 if (id >= firstVarPropertyIndex) {
583                     Q_ASSERT(t == QMetaType::QVariant);
584                     // the context can be null if accessing var properties from cpp after re-parenting an item.
585                     QQmlEnginePrivate *ep = (ctxt == 0 || ctxt->engine == 0) ? 0 : QQmlEnginePrivate::get(ctxt->engine);
586                     QV8Engine *v8e = (ep == 0) ? 0 : ep->v8engine();
587                     if (v8e) {
588                         v8::HandleScope handleScope;
589                         v8::Context::Scope contextScope(v8e->context());
590                         if (c == QMetaObject::ReadProperty) {
591                             *reinterpret_cast<QVariant *>(a[0]) = readPropertyAsVariant(id);
592                         } else if (c == QMetaObject::WriteProperty) {
593                             writeProperty(id, *reinterpret_cast<QVariant *>(a[0]));
594                         }
595                     } else if (c == QMetaObject::ReadProperty) {
596                         // if the context was disposed, we just return an invalid variant from read.
597                         *reinterpret_cast<QVariant *>(a[0]) = QVariant();
598                     }
599
600                 } else {
601
602                     if (c == QMetaObject::ReadProperty) {
603                         switch(t) {
604                         case QVariant::Int:
605                             *reinterpret_cast<int *>(a[0]) = data[id].asInt();
606                             break;
607                         case QVariant::Bool:
608                             *reinterpret_cast<bool *>(a[0]) = data[id].asBool();
609                             break;
610                         case QVariant::Double:
611                             *reinterpret_cast<double *>(a[0]) = data[id].asDouble();
612                             break;
613                         case QVariant::String:
614                             *reinterpret_cast<QString *>(a[0]) = data[id].asQString();
615                             break;
616                         case QVariant::Url:
617                             *reinterpret_cast<QUrl *>(a[0]) = data[id].asQUrl();
618                             break;
619                         case QVariant::Date:
620                             *reinterpret_cast<QDate *>(a[0]) = data[id].asQDate();
621                             break;
622                         case QVariant::DateTime:
623                             *reinterpret_cast<QDateTime *>(a[0]) = data[id].asQDateTime();
624                             break;
625                         case QVariant::RectF:
626                             *reinterpret_cast<QRectF *>(a[0]) = data[id].asQRectF();
627                             break;
628                         case QMetaType::QObjectStar:
629                             *reinterpret_cast<QObject **>(a[0]) = data[id].asQObject();
630                             break;
631                         case QMetaType::QVariant:
632                             *reinterpret_cast<QVariant *>(a[0]) = readPropertyAsVariant(id);
633                             break;
634                         default:
635                             QQml_valueTypeProvider()->readValueType(data[id].dataType(), data[id].dataPtr(), t, a[0]);
636                             break;
637                         }
638                         if (t == qMetaTypeId<QQmlListProperty<QObject> >()) {
639                             int listIndex = data[id].asInt();
640                             const List *list = &listProperties.at(listIndex);
641                             *reinterpret_cast<QQmlListProperty<QObject> *>(a[0]) = 
642                                 QQmlListProperty<QObject>(object, (void *)list,
643                                                                   list_append, list_count, list_at, 
644                                                                   list_clear);
645                         }
646
647                     } else if (c == QMetaObject::WriteProperty) {
648
649                         switch(t) {
650                         case QVariant::Int:
651                             needActivate = *reinterpret_cast<int *>(a[0]) != data[id].asInt();
652                             data[id].setValue(*reinterpret_cast<int *>(a[0]));
653                             break;
654                         case QVariant::Bool:
655                             needActivate = *reinterpret_cast<bool *>(a[0]) != data[id].asBool();
656                             data[id].setValue(*reinterpret_cast<bool *>(a[0]));
657                             break;
658                         case QVariant::Double:
659                             needActivate = *reinterpret_cast<double *>(a[0]) != data[id].asDouble();
660                             data[id].setValue(*reinterpret_cast<double *>(a[0]));
661                             break;
662                         case QVariant::String:
663                             needActivate = *reinterpret_cast<QString *>(a[0]) != data[id].asQString();
664                             data[id].setValue(*reinterpret_cast<QString *>(a[0]));
665                             break;
666                         case QVariant::Url:
667                             needActivate = *reinterpret_cast<QUrl *>(a[0]) != data[id].asQUrl();
668                             data[id].setValue(*reinterpret_cast<QUrl *>(a[0]));
669                             break;
670                         case QVariant::Date:
671                             needActivate = *reinterpret_cast<QDate *>(a[0]) != data[id].asQDate();
672                             data[id].setValue(*reinterpret_cast<QDate *>(a[0]));
673                             break;
674                         case QVariant::DateTime:
675                             needActivate = *reinterpret_cast<QDateTime *>(a[0]) != data[id].asQDateTime();
676                             data[id].setValue(*reinterpret_cast<QDateTime *>(a[0]));
677                             break;
678                         case QVariant::RectF:
679                             needActivate = *reinterpret_cast<QRectF *>(a[0]) != data[id].asQRectF();
680                             data[id].setValue(*reinterpret_cast<QRectF *>(a[0]));
681                             break;
682                         case QMetaType::QObjectStar:
683                             needActivate = *reinterpret_cast<QObject **>(a[0]) != data[id].asQObject();
684                             data[id].setValue(*reinterpret_cast<QObject **>(a[0]), this, id);
685                             break;
686                         case QMetaType::QVariant:
687                             writeProperty(id, *reinterpret_cast<QVariant *>(a[0]));
688                             break;
689                         default:
690                             data[id].ensureValueType(t);
691                             needActivate = !QQml_valueTypeProvider()->equalValueType(t, a[0], data[id].dataPtr());
692                             QQml_valueTypeProvider()->writeValueType(t, a[0], data[id].dataPtr(), data[id].dataSize());
693                             break;
694                         }
695                     }
696
697                 }
698
699                 if (c == QMetaObject::WriteProperty && needActivate) {
700                     activate(object, methodOffset + id, 0);
701                 }
702
703                 return -1;
704             }
705
706             id -= metaData->propertyCount;
707
708             if (id < metaData->aliasCount) {
709
710                 QQmlVMEMetaData::AliasData *d = metaData->aliasData() + id;
711
712                 if (d->flags & QML_ALIAS_FLAG_PTR && c == QMetaObject::ReadProperty) 
713                         *reinterpret_cast<void **>(a[0]) = 0;
714
715                 if (!ctxt) return -1;
716
717                 QQmlContext *context = ctxt->asQQmlContext();
718                 QQmlContextPrivate *ctxtPriv = QQmlContextPrivate::get(context);
719
720                 QObject *target = ctxtPriv->data->idValues[d->contextIdx].data();
721                 if (!target) 
722                     return -1;
723
724                 connectAlias(id);
725
726                 if (d->isObjectAlias()) {
727                     *reinterpret_cast<QObject **>(a[0]) = target;
728                     return -1;
729                 } 
730                 
731                 // Remove binding (if any) on write
732                 if(c == QMetaObject::WriteProperty) {
733                     int flags = *reinterpret_cast<int*>(a[3]);
734                     if (flags & QQmlPropertyPrivate::RemoveBindingOnAliasWrite) {
735                         QQmlData *targetData = QQmlData::get(target);
736                         if (targetData && targetData->hasBindingBit(d->propertyIndex())) {
737                             QQmlAbstractBinding *binding = QQmlPropertyPrivate::setBinding(target, d->propertyIndex(), d->isValueTypeAlias()?d->valueTypeIndex():-1, 0);
738                             if (binding) binding->destroy();
739                         }
740                     }
741                 }
742                 
743                 if (d->isValueTypeAlias()) {
744                     // Value type property
745                     QQmlEnginePrivate *ep = QQmlEnginePrivate::get(ctxt->engine);
746
747                     QQmlValueType *valueType = ep->valueTypes[d->valueType()];
748                     Q_ASSERT(valueType);
749
750                     valueType->read(target, d->propertyIndex());
751                     int rv = QMetaObject::metacall(valueType, c, d->valueTypeIndex(), a);
752                     
753                     if (c == QMetaObject::WriteProperty)
754                         valueType->write(target, d->propertyIndex(), 0x00);
755
756                     return rv;
757
758                 } else {
759                     return QMetaObject::metacall(target, c, d->propertyIndex(), a);
760                 }
761
762             }
763             return -1;
764
765         }
766
767     } else if(c == QMetaObject::InvokeMetaMethod) {
768
769         if (id >= methodOffset) {
770
771             id -= methodOffset;
772             int plainSignals = metaData->signalCount + metaData->propertyCount +
773                                metaData->aliasCount;
774             if (id < plainSignals) {
775                 QMetaObject::activate(object, _id, a);
776                 return -1;
777             }
778
779             id -= plainSignals;
780
781             if (id < metaData->methodCount) {
782                 if (!ctxt->engine)
783                     return -1; // We can't run the method
784
785                 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(ctxt->engine);
786                 ep->referenceScarceResources(); // "hold" scarce resources in memory during evaluation.
787
788                 v8::Handle<v8::Function> function = method(id);
789                 if (function.IsEmpty()) {
790                     // The function was not compiled.  There are some exceptional cases which the
791                     // expression rewriter does not rewrite properly (e.g., \r-terminated lines
792                     // are not rewritten correctly but this bug is deemed out-of-scope to fix for
793                     // performance reasons; see QTBUG-24064) and thus compilation will have failed.
794                     QQmlError e;
795                     e.setDescription(QString(QLatin1String("Exception occurred during compilation of function: %1")).
796                                      arg(QLatin1String(QMetaObject::method(_id).methodSignature().constData())));
797                     ep->warning(e);
798                     return -1; // The dynamic method with that id is not available.
799                 }
800
801                 QQmlVMEMetaData::MethodData *data = metaData->methodData() + id;
802
803                 v8::HandleScope handle_scope;
804                 v8::Context::Scope scope(ep->v8engine()->context());
805                 v8::Handle<v8::Value> *args = 0;
806
807                 if (data->parameterCount) {
808                     args = new v8::Handle<v8::Value>[data->parameterCount];
809                     for (int ii = 0; ii < data->parameterCount; ++ii) 
810                         args[ii] = ep->v8engine()->fromVariant(*(QVariant *)a[ii + 1]);
811                 }
812
813                 v8::TryCatch try_catch;
814
815                 v8::Local<v8::Value> result = function->Call(ep->v8engine()->global(), data->parameterCount, args);
816
817                 QVariant rv;
818                 if (try_catch.HasCaught()) {
819                     QQmlError error;
820                     QQmlExpressionPrivate::exceptionToError(try_catch.Message(), error);
821                     if (error.isValid())
822                         ep->warning(error);
823                     if (a[0]) *(QVariant *)a[0] = QVariant();
824                 } else {
825                     if (a[0]) *(QVariant *)a[0] = ep->v8engine()->toVariant(result, 0);
826                 }
827
828                 ep->dereferenceScarceResources(); // "release" scarce resources if top-level expression evaluation is complete.
829                 return -1;
830             }
831             return -1;
832         }
833     }
834
835     if (parent)
836         return parent->metaCall(c, _id, a);
837     else
838         return object->qt_metacall(c, _id, a);
839 }
840
841 v8::Handle<v8::Function> QQmlVMEMetaObject::method(int index)
842 {
843     if (!ctxt || !ctxt->isValid()) {
844         qWarning("QQmlVMEMetaObject: Internal error - attempted to evaluate a function in an invalid context");
845         return v8::Handle<v8::Function>();
846     }
847
848     if (!v8methods) 
849         v8methods = new v8::Persistent<v8::Function>[metaData->methodCount];
850
851     if (v8methods[index].IsEmpty()) {
852         QQmlVMEMetaData::MethodData *data = metaData->methodData() + index;
853
854         const char *body = ((const char*)metaData) + data->bodyOffset;
855         int bodyLength = data->bodyLength;
856
857         // XXX We should evaluate all methods in a single big script block to 
858         // improve the call time between dynamic methods defined on the same
859         // object
860         v8methods[index] = QQmlExpressionPrivate::evalFunction(ctxt, object, body,
861                                                                        bodyLength,
862                                                                        ctxt->urlString,
863                                                                        data->lineNumber);
864     }
865
866     return v8methods[index];
867 }
868
869 v8::Handle<v8::Value> QQmlVMEMetaObject::readVarProperty(int id)
870 {
871     Q_ASSERT(id >= firstVarPropertyIndex);
872
873     if (ensureVarPropertiesAllocated())
874         return varProperties->Get(id - firstVarPropertyIndex);
875     return v8::Handle<v8::Value>();
876 }
877
878 QVariant QQmlVMEMetaObject::readPropertyAsVariant(int id)
879 {
880     if (id >= firstVarPropertyIndex) {
881         if (ensureVarPropertiesAllocated())
882             return QQmlEnginePrivate::get(ctxt->engine)->v8engine()->toVariant(varProperties->Get(id - firstVarPropertyIndex), -1);
883         return QVariant();
884     } else {
885         if (data[id].dataType() == QMetaType::QObjectStar) {
886             return QVariant::fromValue(data[id].asQObject());
887         } else {
888             return data[id].asQVariant();
889         }
890     }
891 }
892
893 void QQmlVMEMetaObject::writeVarProperty(int id, v8::Handle<v8::Value> value)
894 {
895     Q_ASSERT(id >= firstVarPropertyIndex);
896     if (!ensureVarPropertiesAllocated())
897         return;
898
899     // Importantly, if the current value is a scarce resource, we need to ensure that it
900     // gets automatically released by the engine if no other references to it exist.
901     v8::Local<v8::Value> oldv = varProperties->Get(id - firstVarPropertyIndex);
902     if (oldv->IsObject()) {
903         QV8VariantResource *r = v8_resource_cast<QV8VariantResource>(v8::Handle<v8::Object>::Cast(oldv));
904         if (r) {
905             r->removeVmePropertyReference();
906         }
907     }
908
909     // And, if the new value is a scarce resource, we need to ensure that it does not get
910     // automatically released by the engine until no other references to it exist.
911     if (value->IsObject()) {
912         QV8VariantResource *r = v8_resource_cast<QV8VariantResource>(v8::Handle<v8::Object>::Cast(value));
913         if (r) {
914             r->addVmePropertyReference();
915         }
916     }
917
918     // Write the value and emit change signal as appropriate.
919     varProperties->Set(id - firstVarPropertyIndex, value);
920     activate(object, methodOffset + id, 0);
921 }
922
923 void QQmlVMEMetaObject::writeProperty(int id, const QVariant &value)
924 {
925     if (id >= firstVarPropertyIndex) {
926         if (!ensureVarPropertiesAllocated())
927             return;
928
929         // Importantly, if the current value is a scarce resource, we need to ensure that it
930         // gets automatically released by the engine if no other references to it exist.
931         v8::Local<v8::Value> oldv = varProperties->Get(id - firstVarPropertyIndex);
932         if (oldv->IsObject()) {
933             QV8VariantResource *r = v8_resource_cast<QV8VariantResource>(v8::Handle<v8::Object>::Cast(oldv));
934             if (r) {
935                 r->removeVmePropertyReference();
936             }
937         }
938
939         // And, if the new value is a scarce resource, we need to ensure that it does not get
940         // automatically released by the engine until no other references to it exist.
941         v8::Handle<v8::Value> newv = QQmlEnginePrivate::get(ctxt->engine)->v8engine()->fromVariant(value);
942         if (newv->IsObject()) {
943             QV8VariantResource *r = v8_resource_cast<QV8VariantResource>(v8::Handle<v8::Object>::Cast(newv));
944             if (r) {
945                 r->addVmePropertyReference();
946             }
947         }
948
949         // Write the value and emit change signal as appropriate.
950         QVariant currentValue = readPropertyAsVariant(id);
951         varProperties->Set(id - firstVarPropertyIndex, newv);
952         if ((currentValue.userType() != value.userType() || currentValue != value))
953             activate(object, methodOffset + id, 0);
954     } else {
955         bool needActivate = false;
956         if (value.userType() == QMetaType::QObjectStar) {
957             QObject *o = qvariant_cast<QObject *>(value);
958             needActivate = (data[id].dataType() != QMetaType::QObjectStar || data[id].asQObject() != o);
959             data[id].setValue(qvariant_cast<QObject *>(value), this, id);
960         } else {
961             needActivate = (data[id].dataType() != qMetaTypeId<QVariant>() ||
962                             data[id].asQVariant().userType() != value.userType() ||
963                             data[id].asQVariant() != value);
964             data[id].setValue(value);
965         }
966
967         if (needActivate)
968             activate(object, methodOffset + id, 0);
969     }
970 }
971
972 void QQmlVMEMetaObject::listChanged(int id)
973 {
974     activate(object, methodOffset + id, 0);
975 }
976
977 void QQmlVMEMetaObject::list_append(QQmlListProperty<QObject> *prop, QObject *o)
978 {
979     List *list = static_cast<List *>(prop->data);
980     list->append(o);
981     QMetaObject::activate(prop->object, list->notifyIndex, 0);
982 }
983
984 int QQmlVMEMetaObject::list_count(QQmlListProperty<QObject> *prop)
985 {
986     return static_cast<List *>(prop->data)->count();
987 }
988
989 QObject *QQmlVMEMetaObject::list_at(QQmlListProperty<QObject> *prop, int index)
990 {
991     return static_cast<List *>(prop->data)->at(index);
992 }
993
994 void QQmlVMEMetaObject::list_clear(QQmlListProperty<QObject> *prop)
995 {
996     List *list = static_cast<List *>(prop->data);
997     list->clear();
998     QMetaObject::activate(prop->object, list->notifyIndex, 0);
999 }
1000
1001 void QQmlVMEMetaObject::registerInterceptor(int index, int valueIndex, QQmlPropertyValueInterceptor *interceptor)
1002 {
1003     if (aInterceptors.isEmpty())
1004         aInterceptors.resize(propertyCount() + metaData->propertyCount);
1005     aInterceptors.setBit(index);
1006     interceptors.insert(index, qMakePair(valueIndex, interceptor));
1007 }
1008
1009 int QQmlVMEMetaObject::vmeMethodLineNumber(int index)
1010 {
1011     if (index < methodOffset) {
1012         Q_ASSERT(parent);
1013         return static_cast<QQmlVMEMetaObject *>(parent)->vmeMethodLineNumber(index);
1014     }
1015
1016     int plainSignals = metaData->signalCount + metaData->propertyCount + metaData->aliasCount;
1017     Q_ASSERT(index >= (methodOffset + plainSignals) && index < (methodOffset + plainSignals + metaData->methodCount));
1018
1019     int rawIndex = index - methodOffset - plainSignals;
1020
1021     QQmlVMEMetaData::MethodData *data = metaData->methodData() + rawIndex;
1022     return data->lineNumber;
1023 }
1024
1025 v8::Handle<v8::Function> QQmlVMEMetaObject::vmeMethod(int index)
1026 {
1027     if (index < methodOffset) {
1028         Q_ASSERT(parent);
1029         return static_cast<QQmlVMEMetaObject *>(parent)->vmeMethod(index);
1030     }
1031     int plainSignals = metaData->signalCount + metaData->propertyCount + metaData->aliasCount;
1032     Q_ASSERT(index >= (methodOffset + plainSignals) && index < (methodOffset + plainSignals + metaData->methodCount));
1033     return method(index - methodOffset - plainSignals);
1034 }
1035
1036 // Used by debugger
1037 void QQmlVMEMetaObject::setVmeMethod(int index, v8::Persistent<v8::Function> value)
1038 {
1039     if (index < methodOffset) {
1040         Q_ASSERT(parent);
1041         return static_cast<QQmlVMEMetaObject *>(parent)->setVmeMethod(index, value);
1042     }
1043     int plainSignals = metaData->signalCount + metaData->propertyCount + metaData->aliasCount;
1044     Q_ASSERT(index >= (methodOffset + plainSignals) && index < (methodOffset + plainSignals + metaData->methodCount));
1045
1046     if (!v8methods) 
1047         v8methods = new v8::Persistent<v8::Function>[metaData->methodCount];
1048
1049     int methodIndex = index - methodOffset - plainSignals;
1050     if (!v8methods[methodIndex].IsEmpty()) 
1051         qPersistentDispose(v8methods[methodIndex]);
1052     v8methods[methodIndex] = value;
1053 }
1054
1055 v8::Handle<v8::Value> QQmlVMEMetaObject::vmeProperty(int index)
1056 {
1057     if (index < propOffset) {
1058         Q_ASSERT(parent);
1059         return static_cast<QQmlVMEMetaObject *>(parent)->vmeProperty(index);
1060     }
1061     return readVarProperty(index - propOffset);
1062 }
1063
1064 void QQmlVMEMetaObject::setVMEProperty(int index, v8::Handle<v8::Value> v)
1065 {
1066     if (index < propOffset) {
1067         Q_ASSERT(parent);
1068         static_cast<QQmlVMEMetaObject *>(parent)->setVMEProperty(index, v);
1069         return;
1070     }
1071     return writeVarProperty(index - propOffset, v);
1072 }
1073
1074 bool QQmlVMEMetaObject::ensureVarPropertiesAllocated()
1075 {
1076     if (!varPropertiesInitialized)
1077         allocateVarPropertiesArray();
1078
1079     // in some situations, the QObject's v8object (and associated v8 data,
1080     // such as the varProperties array) will have been cleaned up, but the
1081     // QObject ptr will not yet have been deleted (eg, waiting on deleteLater).
1082     // In this situation, the varProperties handle will be (and should remain)
1083     // empty.
1084     return !varProperties.IsEmpty();
1085 }
1086
1087 // see also: QV8GCCallback::garbageCollectorPrologueCallback()
1088 void QQmlVMEMetaObject::allocateVarPropertiesArray()
1089 {
1090     v8::HandleScope handleScope;
1091     v8::Context::Scope cs(QQmlEnginePrivate::get(ctxt->engine)->v8engine()->context());
1092     varProperties = qPersistentNew(v8::Array::New(metaData->varPropertyCount));
1093     varProperties.MakeWeak(static_cast<void*>(this), VarPropertiesWeakReferenceCallback);
1094     varPropertiesInitialized = true;
1095 }
1096
1097 /*
1098    The "var" properties are stored in a v8::Array which will be strong persistent if the object has cpp-ownership
1099    and the root QObject in the parent chain does not have JS-ownership.  In the weak persistent handle case,
1100    this callback will dispose the handle when the v8object which owns the lifetime of the var properties array
1101    is cleared as a result of all other handles to that v8object being released.
1102    See QV8GCCallback::garbageCollectorPrologueCallback() for more information.
1103  */
1104 void QQmlVMEMetaObject::VarPropertiesWeakReferenceCallback(v8::Persistent<v8::Value> object, void* parameter)
1105 {
1106     QQmlVMEMetaObject *vmemo = static_cast<QQmlVMEMetaObject*>(parameter);
1107     Q_ASSERT(vmemo);
1108     qPersistentDispose(object);
1109     vmemo->varProperties.Clear();
1110 }
1111
1112 void QQmlVMEMetaObject::GcPrologueCallback(QV8GCCallback::Node *node)
1113 {
1114     QQmlVMEMetaObject *vmemo = static_cast<QQmlVMEMetaObject*>(node);
1115     Q_ASSERT(vmemo);
1116     if (!vmemo->varPropertiesInitialized || vmemo->varProperties.IsEmpty() || !vmemo->ctxt || !vmemo->ctxt->engine)
1117         return;
1118     QQmlEnginePrivate *ep = QQmlEnginePrivate::get(vmemo->ctxt->engine);
1119     ep->v8engine()->addRelationshipForGC(vmemo->object, vmemo->varProperties);
1120 }
1121
1122 bool QQmlVMEMetaObject::aliasTarget(int index, QObject **target, int *coreIndex, int *valueTypeIndex) const
1123 {
1124     Q_ASSERT(index >= propOffset + metaData->propertyCount);
1125
1126     *target = 0;
1127     *coreIndex = -1;
1128     *valueTypeIndex = -1;
1129
1130     if (!ctxt)
1131         return false;
1132
1133     QQmlVMEMetaData::AliasData *d = metaData->aliasData() + (index - propOffset - metaData->propertyCount);
1134     QQmlContext *context = ctxt->asQQmlContext();
1135     QQmlContextPrivate *ctxtPriv = QQmlContextPrivate::get(context);
1136
1137     *target = ctxtPriv->data->idValues[d->contextIdx].data();
1138     if (!*target)
1139         return false;
1140
1141     if (d->isObjectAlias()) {
1142     } else if (d->isValueTypeAlias()) {
1143         *coreIndex = d->propertyIndex();
1144         *valueTypeIndex = d->valueTypeIndex();
1145     } else {
1146         *coreIndex = d->propertyIndex();
1147     }
1148
1149     return true;
1150 }
1151
1152 void QQmlVMEMetaObject::connectAlias(int aliasId)
1153 {
1154     if (!aConnected.testBit(aliasId)) {
1155
1156         if (!aliasEndpoints)
1157             aliasEndpoints = new QQmlVMEMetaObjectEndpoint[metaData->aliasCount];
1158
1159         aConnected.setBit(aliasId);
1160
1161         QQmlVMEMetaData::AliasData *d = metaData->aliasData() + aliasId;
1162
1163         QQmlVMEMetaObjectEndpoint *endpoint = aliasEndpoints + aliasId;
1164         endpoint->metaObject = this;
1165
1166         endpoint->connect(&ctxt->idValues[d->contextIdx].bindings);
1167
1168         endpoint->tryConnect();
1169     }
1170 }
1171
1172 void QQmlVMEMetaObject::connectAliasSignal(int index)
1173 {
1174     int aliasId = (index - methodOffset) - metaData->propertyCount;
1175     if (aliasId < 0 || aliasId >= metaData->aliasCount)
1176         return;
1177
1178     connectAlias(aliasId);
1179 }
1180
1181 QT_END_NAMESPACE