Ensure that variant property references keep QObjects alive
[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     setCallback(QQmlNotifierEndpoint::QQmlVMEMetaObjectEndpoint);
450 }
451
452 void QQmlVMEMetaObjectEndpoint_callback(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         metaObject->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             if (d->notifySignal != -1)
475                 connect(target, d->notifySignal, ctxt->engine);
476         }
477
478         metaObject.setFlag();
479     }
480 }
481
482 QAbstractDynamicMetaObject *QQmlVMEMetaObject::toDynamicMetaObject(QObject *o)
483 {
484     if (!hasAssignedMetaObjectData) {
485         *static_cast<QMetaObject *>(this) = *cache->createMetaObject();
486
487         if (parent.isT1())
488             this->d.superdata = parent.asT1()->toDynamicMetaObject(o);
489         else
490             this->d.superdata = parent.asT2();
491
492         hasAssignedMetaObjectData = true;
493     }
494
495     return this;
496 }
497
498 QQmlVMEMetaObject::QQmlVMEMetaObject(QObject *obj,
499                                      QQmlPropertyCache *cache,
500                                      const QQmlVMEMetaData *meta)
501 : QV8GCCallback::Node(GcPrologueCallback), object(obj),
502   ctxt(QQmlData::get(obj, true)->outerContext), cache(cache), metaData(meta),
503   hasAssignedMetaObjectData(false), data(0), aliasEndpoints(0), firstVarPropertyIndex(-1),
504   varPropertiesInitialized(false), interceptors(0), v8methods(0)
505 {
506     QObjectPrivate *op = QObjectPrivate::get(obj);
507
508     if (op->metaObject) parent = op->metaObject;
509     else parent = obj->metaObject();
510
511     op->metaObject = this;
512     QQmlData::get(obj)->hasVMEMetaObject = true;
513
514     data = new QQmlVMEVariant[metaData->propertyCount - metaData->varPropertyCount];
515
516     aConnected.resize(metaData->aliasCount);
517     int list_type = qMetaTypeId<QQmlListProperty<QObject> >();
518     int qobject_type = qMetaTypeId<QObject*>();
519     int variant_type = qMetaTypeId<QVariant>();
520     bool needsGcCallback = (metaData->varPropertyCount > 0);
521
522     // ### Optimize
523     for (int ii = 0; ii < metaData->propertyCount - metaData->varPropertyCount; ++ii) {
524         int t = (metaData->propertyData() + ii)->propertyType;
525         if (t == list_type) {
526             listProperties.append(List(methodOffset() + ii, this));
527             data[ii].setValue(listProperties.count() - 1);
528         } else if (!needsGcCallback && (t == qobject_type || t == variant_type)) {
529             needsGcCallback = true;
530         }
531     }
532
533     firstVarPropertyIndex = metaData->propertyCount - metaData->varPropertyCount;
534
535     // both var properties and variant properties can keep references to
536     // other QObjects, and var properties can also keep references to
537     // JavaScript objects.  If we have any properties, we need to hook
538     // the gc() to ensure that references keep objects alive as needed.
539     if (needsGcCallback) {
540         QV8GCCallback::addGcCallbackNode(this);
541     }
542 }
543
544 QQmlVMEMetaObject::~QQmlVMEMetaObject()
545 {
546     if (parent.isT1()) parent.asT1()->objectDestroyed(object);
547     delete [] data;
548     delete [] aliasEndpoints;
549
550     for (int ii = 0; v8methods && ii < metaData->methodCount; ++ii) {
551         qPersistentDispose(v8methods[ii]);
552     }
553     delete [] v8methods;
554
555     if (metaData->varPropertyCount)
556         qPersistentDispose(varProperties); // if not weak, will not have been cleaned up by the callback.
557 }
558
559 int QQmlVMEMetaObject::metaCall(QMetaObject::Call c, int _id, void **a)
560 {
561     int id = _id;
562     if (c == QMetaObject::WriteProperty && interceptors &&
563        !(*reinterpret_cast<int*>(a[3]) & QQmlPropertyPrivate::BypassInterceptor)) {
564
565         for (QQmlPropertyValueInterceptor *vi = interceptors; vi; vi = vi->m_next) {
566             if (vi->m_coreIndex != id)
567                 continue;
568
569             int valueIndex = vi->m_valueTypeCoreIndex;
570             int type = QQmlData::get(object)->propertyCache->property(id)->propType;
571
572             if (type != QVariant::Invalid) {
573                 if (valueIndex != -1) {
574                     QQmlEnginePrivate *ep = ctxt?QQmlEnginePrivate::get(ctxt->engine):0;
575                     QQmlValueType *valueType = 0;
576                     if (ep) valueType = ep->valueTypes[type];
577                     else valueType = QQmlValueTypeFactory::valueType(type);
578                     Q_ASSERT(valueType);
579
580                     valueType->setValue(QVariant(type, a[0]));
581                     QMetaProperty valueProp = valueType->metaObject()->property(valueIndex);
582                     vi->write(valueProp.read(valueType));
583
584                     if (!ep) delete valueType;
585                     return -1;
586                 } else {
587                     vi->write(QVariant(type, a[0]));
588                     return -1;
589                 }
590             }
591         }
592     }
593     if (c == QMetaObject::ReadProperty || c == QMetaObject::WriteProperty || c == QMetaObject::ResetProperty) {
594         if (id >= propOffset()) {
595             id -= propOffset();
596
597             if (id < metaData->propertyCount) {
598                int t = (metaData->propertyData() + id)->propertyType;
599                 bool needActivate = false;
600
601                 if (id >= firstVarPropertyIndex) {
602                     Q_ASSERT(t == QMetaType::QVariant);
603                     // the context can be null if accessing var properties from cpp after re-parenting an item.
604                     QQmlEnginePrivate *ep = (ctxt == 0 || ctxt->engine == 0) ? 0 : QQmlEnginePrivate::get(ctxt->engine);
605                     QV8Engine *v8e = (ep == 0) ? 0 : ep->v8engine();
606                     if (v8e) {
607                         v8::HandleScope handleScope;
608                         v8::Context::Scope contextScope(v8e->context());
609                         if (c == QMetaObject::ReadProperty) {
610                             *reinterpret_cast<QVariant *>(a[0]) = readPropertyAsVariant(id);
611                         } else if (c == QMetaObject::WriteProperty) {
612                             writeProperty(id, *reinterpret_cast<QVariant *>(a[0]));
613                         }
614                     } else if (c == QMetaObject::ReadProperty) {
615                         // if the context was disposed, we just return an invalid variant from read.
616                         *reinterpret_cast<QVariant *>(a[0]) = QVariant();
617                     }
618
619                 } else {
620
621                     if (c == QMetaObject::ReadProperty) {
622                         switch(t) {
623                         case QVariant::Int:
624                             *reinterpret_cast<int *>(a[0]) = data[id].asInt();
625                             break;
626                         case QVariant::Bool:
627                             *reinterpret_cast<bool *>(a[0]) = data[id].asBool();
628                             break;
629                         case QVariant::Double:
630                             *reinterpret_cast<double *>(a[0]) = data[id].asDouble();
631                             break;
632                         case QVariant::String:
633                             *reinterpret_cast<QString *>(a[0]) = data[id].asQString();
634                             break;
635                         case QVariant::Url:
636                             *reinterpret_cast<QUrl *>(a[0]) = data[id].asQUrl();
637                             break;
638                         case QVariant::Date:
639                             *reinterpret_cast<QDate *>(a[0]) = data[id].asQDate();
640                             break;
641                         case QVariant::DateTime:
642                             *reinterpret_cast<QDateTime *>(a[0]) = data[id].asQDateTime();
643                             break;
644                         case QVariant::RectF:
645                             *reinterpret_cast<QRectF *>(a[0]) = data[id].asQRectF();
646                             break;
647                         case QMetaType::QObjectStar:
648                             *reinterpret_cast<QObject **>(a[0]) = data[id].asQObject();
649                             break;
650                         case QMetaType::QVariant:
651                             *reinterpret_cast<QVariant *>(a[0]) = readPropertyAsVariant(id);
652                             break;
653                         default:
654                             QQml_valueTypeProvider()->readValueType(data[id].dataType(), data[id].dataPtr(), t, a[0]);
655                             break;
656                         }
657                         if (t == qMetaTypeId<QQmlListProperty<QObject> >()) {
658                             int listIndex = data[id].asInt();
659                             const List *list = &listProperties.at(listIndex);
660                             *reinterpret_cast<QQmlListProperty<QObject> *>(a[0]) = 
661                                 QQmlListProperty<QObject>(object, (void *)list,
662                                                                   list_append, list_count, list_at, 
663                                                                   list_clear);
664                         }
665
666                     } else if (c == QMetaObject::WriteProperty) {
667
668                         switch(t) {
669                         case QVariant::Int:
670                             needActivate = *reinterpret_cast<int *>(a[0]) != data[id].asInt();
671                             data[id].setValue(*reinterpret_cast<int *>(a[0]));
672                             break;
673                         case QVariant::Bool:
674                             needActivate = *reinterpret_cast<bool *>(a[0]) != data[id].asBool();
675                             data[id].setValue(*reinterpret_cast<bool *>(a[0]));
676                             break;
677                         case QVariant::Double:
678                             needActivate = *reinterpret_cast<double *>(a[0]) != data[id].asDouble();
679                             data[id].setValue(*reinterpret_cast<double *>(a[0]));
680                             break;
681                         case QVariant::String:
682                             needActivate = *reinterpret_cast<QString *>(a[0]) != data[id].asQString();
683                             data[id].setValue(*reinterpret_cast<QString *>(a[0]));
684                             break;
685                         case QVariant::Url:
686                             needActivate = *reinterpret_cast<QUrl *>(a[0]) != data[id].asQUrl();
687                             data[id].setValue(*reinterpret_cast<QUrl *>(a[0]));
688                             break;
689                         case QVariant::Date:
690                             needActivate = *reinterpret_cast<QDate *>(a[0]) != data[id].asQDate();
691                             data[id].setValue(*reinterpret_cast<QDate *>(a[0]));
692                             break;
693                         case QVariant::DateTime:
694                             needActivate = *reinterpret_cast<QDateTime *>(a[0]) != data[id].asQDateTime();
695                             data[id].setValue(*reinterpret_cast<QDateTime *>(a[0]));
696                             break;
697                         case QVariant::RectF:
698                             needActivate = *reinterpret_cast<QRectF *>(a[0]) != data[id].asQRectF();
699                             data[id].setValue(*reinterpret_cast<QRectF *>(a[0]));
700                             break;
701                         case QMetaType::QObjectStar:
702                             needActivate = *reinterpret_cast<QObject **>(a[0]) != data[id].asQObject();
703                             data[id].setValue(*reinterpret_cast<QObject **>(a[0]), this, id);
704                             break;
705                         case QMetaType::QVariant:
706                             writeProperty(id, *reinterpret_cast<QVariant *>(a[0]));
707                             break;
708                         default:
709                             data[id].ensureValueType(t);
710                             needActivate = !QQml_valueTypeProvider()->equalValueType(t, a[0], data[id].dataPtr());
711                             QQml_valueTypeProvider()->writeValueType(t, a[0], data[id].dataPtr(), data[id].dataSize());
712                             break;
713                         }
714                     }
715
716                 }
717
718                 if (c == QMetaObject::WriteProperty && needActivate) {
719                     activate(object, methodOffset() + id, 0);
720                 }
721
722                 return -1;
723             }
724
725             id -= metaData->propertyCount;
726
727             if (id < metaData->aliasCount) {
728
729                 QQmlVMEMetaData::AliasData *d = metaData->aliasData() + id;
730
731                 if (d->flags & QML_ALIAS_FLAG_PTR && c == QMetaObject::ReadProperty) 
732                         *reinterpret_cast<void **>(a[0]) = 0;
733
734                 if (!ctxt) return -1;
735
736                 QQmlContext *context = ctxt->asQQmlContext();
737                 QQmlContextPrivate *ctxtPriv = QQmlContextPrivate::get(context);
738
739                 QObject *target = ctxtPriv->data->idValues[d->contextIdx].data();
740                 if (!target) 
741                     return -1;
742
743                 connectAlias(id);
744
745                 if (d->isObjectAlias()) {
746                     *reinterpret_cast<QObject **>(a[0]) = target;
747                     return -1;
748                 } 
749                 
750                 // Remove binding (if any) on write
751                 if(c == QMetaObject::WriteProperty) {
752                     int flags = *reinterpret_cast<int*>(a[3]);
753                     if (flags & QQmlPropertyPrivate::RemoveBindingOnAliasWrite) {
754                         QQmlData *targetData = QQmlData::get(target);
755                         if (targetData && targetData->hasBindingBit(d->propertyIndex())) {
756                             QQmlAbstractBinding *binding = QQmlPropertyPrivate::setBinding(target, d->propertyIndex(), d->isValueTypeAlias()?d->valueTypeIndex():-1, 0);
757                             if (binding) binding->destroy();
758                         }
759                     }
760                 }
761                 
762                 if (d->isValueTypeAlias()) {
763                     // Value type property
764                     QQmlEnginePrivate *ep = QQmlEnginePrivate::get(ctxt->engine);
765
766                     QQmlValueType *valueType = ep->valueTypes[d->valueType()];
767                     Q_ASSERT(valueType);
768
769                     valueType->read(target, d->propertyIndex());
770                     int rv = QMetaObject::metacall(valueType, c, d->valueTypeIndex(), a);
771                     
772                     if (c == QMetaObject::WriteProperty)
773                         valueType->write(target, d->propertyIndex(), 0x00);
774
775                     return rv;
776
777                 } else {
778                     return QMetaObject::metacall(target, c, d->propertyIndex(), a);
779                 }
780
781             }
782             return -1;
783
784         }
785
786     } else if(c == QMetaObject::InvokeMetaMethod) {
787
788         if (id >= methodOffset()) {
789
790             id -= methodOffset();
791             int plainSignals = metaData->signalCount + metaData->propertyCount +
792                                metaData->aliasCount;
793             if (id < plainSignals) {
794                 activate(object, _id, a);
795                 return -1;
796             }
797
798             id -= plainSignals;
799
800             if (id < metaData->methodCount) {
801                 if (!ctxt->engine)
802                     return -1; // We can't run the method
803
804                 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(ctxt->engine);
805                 ep->referenceScarceResources(); // "hold" scarce resources in memory during evaluation.
806
807                 v8::Handle<v8::Function> function = method(id);
808                 if (function.IsEmpty()) {
809                     // The function was not compiled.  There are some exceptional cases which the
810                     // expression rewriter does not rewrite properly (e.g., \r-terminated lines
811                     // are not rewritten correctly but this bug is deemed out-of-scope to fix for
812                     // performance reasons; see QTBUG-24064) and thus compilation will have failed.
813                     QQmlError e;
814                     e.setDescription(QString(QLatin1String("Exception occurred during compilation of function: %1")).
815                                      arg(QLatin1String(QMetaObject::method(_id).methodSignature().constData())));
816                     ep->warning(e);
817                     return -1; // The dynamic method with that id is not available.
818                 }
819
820                 QQmlVMEMetaData::MethodData *data = metaData->methodData() + id;
821
822                 v8::HandleScope handle_scope;
823                 v8::Context::Scope scope(ep->v8engine()->context());
824                 v8::Handle<v8::Value> *args = 0;
825
826                 if (data->parameterCount) {
827                     args = new v8::Handle<v8::Value>[data->parameterCount];
828                     for (int ii = 0; ii < data->parameterCount; ++ii) 
829                         args[ii] = ep->v8engine()->fromVariant(*(QVariant *)a[ii + 1]);
830                 }
831
832                 v8::TryCatch try_catch;
833
834                 v8::Local<v8::Value> result = function->Call(ep->v8engine()->global(), data->parameterCount, args);
835
836                 QVariant rv;
837                 if (try_catch.HasCaught()) {
838                     QQmlError error;
839                     QQmlExpressionPrivate::exceptionToError(try_catch.Message(), error);
840                     if (error.isValid())
841                         ep->warning(error);
842                     if (a[0]) *(QVariant *)a[0] = QVariant();
843                 } else {
844                     if (a[0]) *(QVariant *)a[0] = ep->v8engine()->toVariant(result, 0);
845                 }
846
847                 ep->dereferenceScarceResources(); // "release" scarce resources if top-level expression evaluation is complete.
848                 return -1;
849             }
850             return -1;
851         }
852     }
853
854     if (parent.isT1())
855         return parent.asT1()->metaCall(object, c, _id, a);
856     else
857         return object->qt_metacall(c, _id, a);
858 }
859
860 v8::Handle<v8::Function> QQmlVMEMetaObject::method(int index)
861 {
862     if (!ctxt || !ctxt->isValid()) {
863         qWarning("QQmlVMEMetaObject: Internal error - attempted to evaluate a function in an invalid context");
864         return v8::Handle<v8::Function>();
865     }
866
867     if (!v8methods) 
868         v8methods = new v8::Persistent<v8::Function>[metaData->methodCount];
869
870     if (v8methods[index].IsEmpty()) {
871         QQmlVMEMetaData::MethodData *data = metaData->methodData() + index;
872
873         const char *body = ((const char*)metaData) + data->bodyOffset;
874         int bodyLength = data->bodyLength;
875
876         // XXX We should evaluate all methods in a single big script block to 
877         // improve the call time between dynamic methods defined on the same
878         // object
879         v8methods[index] = QQmlExpressionPrivate::evalFunction(ctxt, object, body,
880                                                                        bodyLength,
881                                                                        ctxt->urlString,
882                                                                        data->lineNumber);
883     }
884
885     return v8methods[index];
886 }
887
888 v8::Handle<v8::Value> QQmlVMEMetaObject::readVarProperty(int id)
889 {
890     Q_ASSERT(id >= firstVarPropertyIndex);
891
892     if (ensureVarPropertiesAllocated())
893         return varProperties->Get(id - firstVarPropertyIndex);
894     return v8::Handle<v8::Value>();
895 }
896
897 QVariant QQmlVMEMetaObject::readPropertyAsVariant(int id)
898 {
899     if (id >= firstVarPropertyIndex) {
900         if (ensureVarPropertiesAllocated())
901             return QQmlEnginePrivate::get(ctxt->engine)->v8engine()->toVariant(varProperties->Get(id - firstVarPropertyIndex), -1);
902         return QVariant();
903     } else {
904         if (data[id].dataType() == QMetaType::QObjectStar) {
905             return QVariant::fromValue(data[id].asQObject());
906         } else {
907             return data[id].asQVariant();
908         }
909     }
910 }
911
912 void QQmlVMEMetaObject::writeVarProperty(int id, v8::Handle<v8::Value> value)
913 {
914     Q_ASSERT(id >= firstVarPropertyIndex);
915     if (!ensureVarPropertiesAllocated())
916         return;
917
918     // Importantly, if the current value is a scarce resource, we need to ensure that it
919     // gets automatically released by the engine if no other references to it exist.
920     v8::Local<v8::Value> oldv = varProperties->Get(id - firstVarPropertyIndex);
921     if (oldv->IsObject()) {
922         QV8VariantResource *r = v8_resource_cast<QV8VariantResource>(v8::Handle<v8::Object>::Cast(oldv));
923         if (r) {
924             r->removeVmePropertyReference();
925         }
926     }
927
928     // And, if the new value is a scarce resource, we need to ensure that it does not get
929     // automatically released by the engine until no other references to it exist.
930     if (value->IsObject()) {
931         QV8VariantResource *r = v8_resource_cast<QV8VariantResource>(v8::Handle<v8::Object>::Cast(value));
932         if (r) {
933             r->addVmePropertyReference();
934         }
935     }
936
937     // Write the value and emit change signal as appropriate.
938     varProperties->Set(id - firstVarPropertyIndex, value);
939     activate(object, methodOffset() + id, 0);
940 }
941
942 void QQmlVMEMetaObject::writeProperty(int id, const QVariant &value)
943 {
944     if (id >= firstVarPropertyIndex) {
945         if (!ensureVarPropertiesAllocated())
946             return;
947
948         // Importantly, if the current value is a scarce resource, we need to ensure that it
949         // gets automatically released by the engine if no other references to it exist.
950         v8::Local<v8::Value> oldv = varProperties->Get(id - firstVarPropertyIndex);
951         if (oldv->IsObject()) {
952             QV8VariantResource *r = v8_resource_cast<QV8VariantResource>(v8::Handle<v8::Object>::Cast(oldv));
953             if (r) {
954                 r->removeVmePropertyReference();
955             }
956         }
957
958         // And, if the new value is a scarce resource, we need to ensure that it does not get
959         // automatically released by the engine until no other references to it exist.
960         v8::Handle<v8::Value> newv = QQmlEnginePrivate::get(ctxt->engine)->v8engine()->fromVariant(value);
961         if (newv->IsObject()) {
962             QV8VariantResource *r = v8_resource_cast<QV8VariantResource>(v8::Handle<v8::Object>::Cast(newv));
963             if (r) {
964                 r->addVmePropertyReference();
965             }
966         }
967
968         // Write the value and emit change signal as appropriate.
969         QVariant currentValue = readPropertyAsVariant(id);
970         varProperties->Set(id - firstVarPropertyIndex, newv);
971         if ((currentValue.userType() != value.userType() || currentValue != value))
972             activate(object, methodOffset() + id, 0);
973     } else {
974         bool needActivate = false;
975         if (value.userType() == QMetaType::QObjectStar) {
976             QObject *o = *(QObject **)value.data();
977             needActivate = (data[id].dataType() != QMetaType::QObjectStar || data[id].asQObject() != o);
978             data[id].setValue(o, this, id);
979         } else {
980             needActivate = (data[id].dataType() != qMetaTypeId<QVariant>() ||
981                             data[id].asQVariant().userType() != value.userType() ||
982                             data[id].asQVariant() != value);
983             data[id].setValue(value);
984         }
985
986         if (needActivate)
987             activate(object, methodOffset() + id, 0);
988     }
989 }
990
991 void QQmlVMEMetaObject::listChanged(int id)
992 {
993     activate(object, methodOffset() + id, 0);
994 }
995
996 void QQmlVMEMetaObject::list_append(QQmlListProperty<QObject> *prop, QObject *o)
997 {
998     List *list = static_cast<List *>(prop->data);
999     list->append(o);
1000     list->mo->activate(prop->object, list->notifyIndex, 0);
1001 }
1002
1003 int QQmlVMEMetaObject::list_count(QQmlListProperty<QObject> *prop)
1004 {
1005     return static_cast<List *>(prop->data)->count();
1006 }
1007
1008 QObject *QQmlVMEMetaObject::list_at(QQmlListProperty<QObject> *prop, int index)
1009 {
1010     return static_cast<List *>(prop->data)->at(index);
1011 }
1012
1013 void QQmlVMEMetaObject::list_clear(QQmlListProperty<QObject> *prop)
1014 {
1015     List *list = static_cast<List *>(prop->data);
1016     list->clear();
1017     list->mo->activate(prop->object, list->notifyIndex, 0);
1018 }
1019
1020 void QQmlVMEMetaObject::registerInterceptor(int index, int valueIndex, QQmlPropertyValueInterceptor *interceptor)
1021 {
1022     interceptor->m_coreIndex = index;
1023     interceptor->m_valueTypeCoreIndex = valueIndex;
1024     interceptor->m_next = interceptors;
1025     interceptors = interceptor;
1026 }
1027
1028 int QQmlVMEMetaObject::vmeMethodLineNumber(int index)
1029 {
1030     if (index < methodOffset()) {
1031         Q_ASSERT(parent.isT1());
1032         return static_cast<QQmlVMEMetaObject *>(parent.asT1())->vmeMethodLineNumber(index);
1033     }
1034
1035     int plainSignals = metaData->signalCount + metaData->propertyCount + metaData->aliasCount;
1036     Q_ASSERT(index >= (methodOffset() + plainSignals) && index < (methodOffset() + plainSignals + metaData->methodCount));
1037
1038     int rawIndex = index - methodOffset() - plainSignals;
1039
1040     QQmlVMEMetaData::MethodData *data = metaData->methodData() + rawIndex;
1041     return data->lineNumber;
1042 }
1043
1044 v8::Handle<v8::Function> QQmlVMEMetaObject::vmeMethod(int index)
1045 {
1046     if (index < methodOffset()) {
1047         Q_ASSERT(parent.isT1());
1048         return static_cast<QQmlVMEMetaObject *>(parent.asT1())->vmeMethod(index);
1049     }
1050     int plainSignals = metaData->signalCount + metaData->propertyCount + metaData->aliasCount;
1051     Q_ASSERT(index >= (methodOffset() + plainSignals) && index < (methodOffset() + plainSignals + metaData->methodCount));
1052     return method(index - methodOffset() - plainSignals);
1053 }
1054
1055 // Used by debugger
1056 void QQmlVMEMetaObject::setVmeMethod(int index, v8::Persistent<v8::Function> value)
1057 {
1058     if (index < methodOffset()) {
1059         Q_ASSERT(parent.isT1());
1060         return static_cast<QQmlVMEMetaObject *>(parent.asT1())->setVmeMethod(index, value);
1061     }
1062     int plainSignals = metaData->signalCount + metaData->propertyCount + metaData->aliasCount;
1063     Q_ASSERT(index >= (methodOffset() + plainSignals) && index < (methodOffset() + plainSignals + metaData->methodCount));
1064
1065     if (!v8methods) 
1066         v8methods = new v8::Persistent<v8::Function>[metaData->methodCount];
1067
1068     int methodIndex = index - methodOffset() - plainSignals;
1069     if (!v8methods[methodIndex].IsEmpty()) 
1070         qPersistentDispose(v8methods[methodIndex]);
1071     v8methods[methodIndex] = value;
1072 }
1073
1074 v8::Handle<v8::Value> QQmlVMEMetaObject::vmeProperty(int index)
1075 {
1076     if (index < propOffset()) {
1077         Q_ASSERT(parent.isT1());
1078         return static_cast<QQmlVMEMetaObject *>(parent.asT1())->vmeProperty(index);
1079     }
1080     return readVarProperty(index - propOffset());
1081 }
1082
1083 void QQmlVMEMetaObject::setVMEProperty(int index, v8::Handle<v8::Value> v)
1084 {
1085     if (index < propOffset()) {
1086         Q_ASSERT(parent.isT1());
1087         static_cast<QQmlVMEMetaObject *>(parent.asT1())->setVMEProperty(index, v);
1088         return;
1089     }
1090     return writeVarProperty(index - propOffset(), v);
1091 }
1092
1093 bool QQmlVMEMetaObject::ensureVarPropertiesAllocated()
1094 {
1095     if (!varPropertiesInitialized)
1096         allocateVarPropertiesArray();
1097
1098     // in some situations, the QObject's v8object (and associated v8 data,
1099     // such as the varProperties array) will have been cleaned up, but the
1100     // QObject ptr will not yet have been deleted (eg, waiting on deleteLater).
1101     // In this situation, the varProperties handle will be (and should remain)
1102     // empty.
1103     return !varProperties.IsEmpty();
1104 }
1105
1106 // see also: QV8GCCallback::garbageCollectorPrologueCallback()
1107 void QQmlVMEMetaObject::allocateVarPropertiesArray()
1108 {
1109     v8::HandleScope handleScope;
1110     v8::Context::Scope cs(QQmlEnginePrivate::get(ctxt->engine)->v8engine()->context());
1111     varProperties = qPersistentNew(v8::Array::New(metaData->varPropertyCount));
1112     varProperties.MakeWeak(static_cast<void*>(this), VarPropertiesWeakReferenceCallback);
1113     varPropertiesInitialized = true;
1114 }
1115
1116 /*
1117    The "var" properties are stored in a v8::Array which will be strong persistent if the object has cpp-ownership
1118    and the root QObject in the parent chain does not have JS-ownership.  In the weak persistent handle case,
1119    this callback will dispose the handle when the v8object which owns the lifetime of the var properties array
1120    is cleared as a result of all other handles to that v8object being released.
1121    See QV8GCCallback::garbageCollectorPrologueCallback() for more information.
1122  */
1123 void QQmlVMEMetaObject::VarPropertiesWeakReferenceCallback(v8::Persistent<v8::Value> object, void* parameter)
1124 {
1125     QQmlVMEMetaObject *vmemo = static_cast<QQmlVMEMetaObject*>(parameter);
1126     Q_ASSERT(vmemo);
1127     qPersistentDispose(object);
1128     vmemo->varProperties.Clear();
1129 }
1130
1131 void QQmlVMEMetaObject::GcPrologueCallback(QV8GCCallback::Node *node)
1132 {
1133     QQmlVMEMetaObject *vmemo = static_cast<QQmlVMEMetaObject*>(node);
1134     Q_ASSERT(vmemo);
1135
1136     if (!vmemo->ctxt || !vmemo->ctxt->engine)
1137         return;
1138     QQmlEnginePrivate *ep = QQmlEnginePrivate::get(vmemo->ctxt->engine);
1139
1140     // add references created by VMEVariant properties
1141     int maxDataIdx = vmemo->metaData->propertyCount - vmemo->metaData->varPropertyCount;
1142     for (int ii = 0; ii < maxDataIdx; ++ii) { // XXX TODO: optimise?
1143         if (vmemo->data[ii].dataType() == QMetaType::QObjectStar) {
1144             // possible QObject reference.
1145             QObject *ref = vmemo->data[ii].asQObject();
1146             if (ref) {
1147                 ep->v8engine()->addRelationshipForGC(vmemo->object, ref);
1148             }
1149         }
1150     }
1151
1152     // add references created by var properties
1153     if (!vmemo->varPropertiesInitialized || vmemo->varProperties.IsEmpty())
1154         return;
1155     ep->v8engine()->addRelationshipForGC(vmemo->object, vmemo->varProperties);
1156 }
1157
1158 bool QQmlVMEMetaObject::aliasTarget(int index, QObject **target, int *coreIndex, int *valueTypeIndex) const
1159 {
1160     Q_ASSERT(index >= propOffset() + metaData->propertyCount);
1161
1162     *target = 0;
1163     *coreIndex = -1;
1164     *valueTypeIndex = -1;
1165
1166     if (!ctxt)
1167         return false;
1168
1169     QQmlVMEMetaData::AliasData *d = metaData->aliasData() + (index - propOffset() - metaData->propertyCount);
1170     QQmlContext *context = ctxt->asQQmlContext();
1171     QQmlContextPrivate *ctxtPriv = QQmlContextPrivate::get(context);
1172
1173     *target = ctxtPriv->data->idValues[d->contextIdx].data();
1174     if (!*target)
1175         return false;
1176
1177     if (d->isObjectAlias()) {
1178     } else if (d->isValueTypeAlias()) {
1179         *coreIndex = d->propertyIndex();
1180         *valueTypeIndex = d->valueTypeIndex();
1181     } else {
1182         *coreIndex = d->propertyIndex();
1183     }
1184
1185     return true;
1186 }
1187
1188 void QQmlVMEMetaObject::connectAlias(int aliasId)
1189 {
1190     if (!aConnected.testBit(aliasId)) {
1191
1192         if (!aliasEndpoints)
1193             aliasEndpoints = new QQmlVMEMetaObjectEndpoint[metaData->aliasCount];
1194
1195         aConnected.setBit(aliasId);
1196
1197         QQmlVMEMetaData::AliasData *d = metaData->aliasData() + aliasId;
1198
1199         QQmlVMEMetaObjectEndpoint *endpoint = aliasEndpoints + aliasId;
1200         endpoint->metaObject = this;
1201
1202         endpoint->connect(&ctxt->idValues[d->contextIdx].bindings);
1203
1204         endpoint->tryConnect();
1205     }
1206 }
1207
1208 void QQmlVMEMetaObject::connectAliasSignal(int index)
1209 {
1210     int aliasId = (index - methodOffset()) - metaData->propertyCount;
1211     if (aliasId < 0 || aliasId >= metaData->aliasCount)
1212         return;
1213
1214     connectAlias(aliasId);
1215 }
1216
1217 void QQmlVMEMetaObject::activate(QObject *object, int index, void **args)
1218 {
1219     int signalOffset = cache->signalOffset();
1220     int methodOffset = cache->methodOffset();
1221
1222     QMetaObject::activate(object, methodOffset, signalOffset, index - methodOffset, args);
1223 }
1224
1225 QQmlVMEMetaObject *QQmlVMEMetaObject::getForProperty(QObject *o, int coreIndex)
1226 {
1227     QQmlVMEMetaObject *vme = QQmlVMEMetaObject::get(o);
1228     while (vme->propOffset() > coreIndex) {
1229         Q_ASSERT(vme->parent.isT1());
1230         vme = static_cast<QQmlVMEMetaObject *>(vme->parent.asT1());
1231     }
1232     return vme;
1233 }
1234
1235 QQmlVMEMetaObject *QQmlVMEMetaObject::getForMethod(QObject *o, int coreIndex)
1236 {
1237     QQmlVMEMetaObject *vme = QQmlVMEMetaObject::get(o);
1238     while (vme->methodOffset() > coreIndex) {
1239         Q_ASSERT(vme->parent.isT1());
1240         vme = static_cast<QQmlVMEMetaObject *>(vme->parent.asT1());
1241     }
1242     return vme;
1243 }
1244
1245 QT_END_NAMESPACE