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