Introduce QMetaType::UnknownType.
[profile/ivi/qtbase.git] / src / dbus / qdbusmetaobject.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 QtDBus 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 "qdbusmetaobject_p.h"
43
44 #include <QtCore/qbytearray.h>
45 #include <QtCore/qhash.h>
46 #include <QtCore/qstring.h>
47 #include <QtCore/qvarlengtharray.h>
48
49 #include "qdbusutil_p.h"
50 #include "qdbuserror.h"
51 #include "qdbusmetatype.h"
52 #include "qdbusargument.h"
53 #include "qdbusintrospection_p.h"
54 #include "qdbusabstractinterface_p.h"
55
56 #include <private/qmetaobject_p.h>
57 #include <private/qmetaobjectbuilder_p.h>
58
59 #ifndef QT_NO_DBUS
60
61 QT_BEGIN_NAMESPACE
62
63 class QDBusMetaObjectGenerator
64 {
65 public:
66     QDBusMetaObjectGenerator(const QString &interface,
67                              const QDBusIntrospection::Interface *parsedData);
68     void write(QDBusMetaObject *obj);
69     void writeWithoutXml(QDBusMetaObject *obj);
70
71 private:
72     struct Method {
73         QList<QByteArray> parameterNames;
74         QByteArray tag;
75         QByteArray name;
76         QVarLengthArray<int, 4> inputTypes;
77         QVarLengthArray<int, 4> outputTypes;
78         int flags;
79     };
80     
81     struct Property {
82         QByteArray typeName;
83         QByteArray signature;
84         int type;
85         int flags;
86     };
87     struct Type {
88         int id;
89         QByteArray name;
90     };
91
92     QMap<QByteArray, Method> signals_;
93     QMap<QByteArray, Method> methods;
94     QMap<QByteArray, Property> properties;
95     
96     const QDBusIntrospection::Interface *data;
97     QString interface;
98
99     Type findType(const QByteArray &signature,
100                   const QDBusIntrospection::Annotations &annotations,
101                   const char *direction = "Out", int id = -1);
102     
103     void parseMethods();
104     void parseSignals();
105     void parseProperties();
106
107     static int aggregateParameterCount(const QMap<QByteArray, Method> &map);
108 };
109
110 static const int intsPerProperty = 2;
111 static const int intsPerMethod = 2;
112
113 struct QDBusMetaObjectPrivate : public QMetaObjectPrivate
114 {
115     int propertyDBusData;
116     int methodDBusData;
117 };
118
119 QDBusMetaObjectGenerator::QDBusMetaObjectGenerator(const QString &interfaceName,
120                                                    const QDBusIntrospection::Interface *parsedData)
121     : data(parsedData), interface(interfaceName)
122 {
123     if (data) {
124         parseProperties();
125         parseSignals();             // call parseSignals first so that slots override signals
126         parseMethods();
127     }
128 }
129
130 Q_DBUS_EXPORT bool qt_dbus_metaobject_skip_annotations = false;
131
132 QDBusMetaObjectGenerator::Type
133 QDBusMetaObjectGenerator::findType(const QByteArray &signature,
134                                    const QDBusIntrospection::Annotations &annotations,
135                                    const char *direction, int id)
136 {
137     struct QDBusRawTypeHandler {
138         static void destroy(void *)
139         {
140             qFatal("Cannot destroy placeholder type QDBusRawType");
141         }
142
143         static void *create(const void *)
144         {
145             qFatal("Cannot create placeholder type QDBusRawType");
146             return 0;
147         }
148
149         static void destruct(void *)
150         {
151             qFatal("Cannot destruct placeholder type QDBusRawType");
152         }
153
154         static void *construct(void *, const void *)
155         {
156             qFatal("Cannot construct placeholder type QDBusRawType");
157             return 0;
158         }
159     };
160
161     Type result;
162     result.id = QVariant::Invalid;
163
164     int type = QDBusMetaType::signatureToType(signature);
165     if (type == QVariant::Invalid && !qt_dbus_metaobject_skip_annotations) {
166         // it's not a type normally handled by our meta type system
167         // it must contain an annotation
168         QString annotationName = QString::fromLatin1("com.trolltech.QtDBus.QtTypeName");
169         if (id >= 0)
170             annotationName += QString::fromLatin1(".%1%2")
171                               .arg(QLatin1String(direction))
172                               .arg(id);
173
174         // extract from annotations:
175         QByteArray typeName = annotations.value(annotationName).toLatin1();
176
177         // verify that it's a valid one
178         if (!typeName.isEmpty()) {
179             // type name found
180             type = QMetaType::type(typeName);
181         }
182
183         if (type == QVariant::Invalid || signature != QDBusMetaType::typeToSignature(type)) {
184             // type is still unknown or doesn't match back to the signature that it
185             // was expected to, so synthesize a fake type
186             typeName = "QDBusRawType<0x" + signature.toHex() + ">*";
187             type = QMetaType::registerType(typeName, QDBusRawTypeHandler::destroy,
188                                            QDBusRawTypeHandler::create,
189                                            QDBusRawTypeHandler::destruct,
190                                            QDBusRawTypeHandler::construct,
191                                            sizeof(void *),
192                                            QMetaType::MovableType);
193         }
194
195         result.name = typeName;
196     } else if (type == QVariant::Invalid) {
197         // this case is used only by the qdbus command-line tool
198         // invalid, let's create an impossible type that contains the signature
199
200         if (signature == "av") {
201             result.name = "QVariantList";
202             type = QVariant::List;
203         } else if (signature == "a{sv}") {
204             result.name = "QVariantMap";
205             type = QVariant::Map;
206         } else {
207             result.name = "QDBusRawType::" + signature;
208             type = -1;
209         }
210     } else {
211         result.name = QVariant::typeToName( QVariant::Type(type) );
212     }
213
214     result.id = type;
215     return result;              // success
216 }
217
218 void QDBusMetaObjectGenerator::parseMethods()
219 {
220     //
221     // TODO:
222     //  Add cloned methods when the remote object has return types
223     //
224
225     QDBusIntrospection::Methods::ConstIterator method_it = data->methods.constBegin();
226     QDBusIntrospection::Methods::ConstIterator method_end = data->methods.constEnd();
227     for ( ; method_it != method_end; ++method_it) {
228         const QDBusIntrospection::Method &m = *method_it;
229         Method mm;
230
231         mm.name = m.name.toLatin1();
232         QByteArray prototype = mm.name;
233         prototype += '(';
234
235         bool ok = true;
236
237         // build the input argument list
238         for (int i = 0; i < m.inputArgs.count(); ++i) {
239             const QDBusIntrospection::Argument &arg = m.inputArgs.at(i);
240
241             Type type = findType(arg.type.toLatin1(), m.annotations, "In", i);
242             if (type.id == QVariant::Invalid) {
243                 ok = false;
244                 break;
245             }
246
247             mm.inputTypes.append(type.id);
248
249             mm.parameterNames.append(arg.name.toLatin1());
250             
251             prototype.append(type.name);
252             prototype.append(',');
253         }
254         if (!ok) continue;
255
256         // build the output argument list:
257         for (int i = 0; i < m.outputArgs.count(); ++i) {
258             const QDBusIntrospection::Argument &arg = m.outputArgs.at(i);
259
260             Type type = findType(arg.type.toLatin1(), m.annotations, "Out", i);
261             if (type.id == QVariant::Invalid) {
262                 ok = false;
263                 break;
264             }
265
266             mm.outputTypes.append(type.id);
267
268             if (i != 0) {
269                 // non-const ref parameter
270                 mm.parameterNames.append(arg.name.toLatin1());
271
272                 prototype.append(type.name);
273                 prototype.append("&,");
274             }
275         }
276         if (!ok) continue;
277
278         // convert the last commas:
279         if (!mm.parameterNames.isEmpty())
280             prototype[prototype.length() - 1] = ')';
281         else
282             prototype.append(')');
283
284         // check the async tag
285         if (m.annotations.value(QLatin1String(ANNOTATION_NO_WAIT)) == QLatin1String("true"))
286             mm.tag = "Q_NOREPLY";
287
288         // meta method flags
289         mm.flags = AccessPublic | MethodSlot | MethodScriptable;
290
291         // add
292         methods.insert(QMetaObject::normalizedSignature(prototype), mm);
293     }
294 }
295
296 void QDBusMetaObjectGenerator::parseSignals()
297 {
298     QDBusIntrospection::Signals::ConstIterator signal_it = data->signals_.constBegin();
299     QDBusIntrospection::Signals::ConstIterator signal_end = data->signals_.constEnd();
300     for ( ; signal_it != signal_end; ++signal_it) {
301         const QDBusIntrospection::Signal &s = *signal_it;
302         Method mm;
303
304         mm.name = s.name.toLatin1();
305         QByteArray prototype = mm.name;
306         prototype += '(';
307
308         bool ok = true;
309
310         // build the output argument list
311         for (int i = 0; i < s.outputArgs.count(); ++i) {
312             const QDBusIntrospection::Argument &arg = s.outputArgs.at(i);
313
314             Type type = findType(arg.type.toLatin1(), s.annotations, "Out", i);
315             if (type.id == QVariant::Invalid) {
316                 ok = false;
317                 break;
318             }
319
320             mm.inputTypes.append(type.id);
321
322             mm.parameterNames.append(arg.name.toLatin1());
323             
324             prototype.append(type.name);
325             prototype.append(',');
326         }
327         if (!ok) continue;
328
329         // convert the last commas:
330         if (!mm.parameterNames.isEmpty())
331             prototype[prototype.length() - 1] = ')';
332         else
333             prototype.append(')');
334
335         // meta method flags
336         mm.flags = AccessProtected | MethodSignal | MethodScriptable;
337
338         // add
339         signals_.insert(QMetaObject::normalizedSignature(prototype), mm);
340     }
341 }
342
343 void QDBusMetaObjectGenerator::parseProperties()
344 {
345     QDBusIntrospection::Properties::ConstIterator prop_it = data->properties.constBegin();
346     QDBusIntrospection::Properties::ConstIterator prop_end = data->properties.constEnd();
347     for ( ; prop_it != prop_end; ++prop_it) {
348         const QDBusIntrospection::Property &p = *prop_it;
349         Property mp;
350         Type type = findType(p.type.toLatin1(), p.annotations);
351         if (type.id == QVariant::Invalid)
352             continue;
353         
354         QByteArray name = p.name.toLatin1();
355         mp.signature = p.type.toLatin1();
356         mp.type = type.id;
357         mp.typeName = type.name;
358
359         // build the flags:
360         mp.flags = StdCppSet | Scriptable | Stored | Designable;
361         if (p.access != QDBusIntrospection::Property::Write)
362             mp.flags |= Readable;
363         if (p.access != QDBusIntrospection::Property::Read)
364             mp.flags |= Writable;
365
366         // add the property:
367         properties.insert(name, mp);
368     }
369 }
370
371 // Returns the sum of all parameters (including return type) for the given
372 // \a map of methods. This is needed for calculating the size of the methods'
373 // parameter type/name meta-data.
374 int QDBusMetaObjectGenerator::aggregateParameterCount(const QMap<QByteArray, Method> &map)
375 {
376     int sum = 0;
377     QMap<QByteArray, Method>::const_iterator it;
378     for (it = map.constBegin(); it != map.constEnd(); ++it) {
379         const Method &m = it.value();
380         sum += m.inputTypes.size() + qMax(1, m.outputTypes.size());
381     }
382     return sum;
383 }
384
385 void QDBusMetaObjectGenerator::write(QDBusMetaObject *obj)
386 {
387     // this code here is mostly copied from qaxbase.cpp
388     // with a few modifications to make it cleaner
389
390     QString className = interface;
391     className.replace(QLatin1Char('.'), QLatin1String("::"));
392     if (className.isEmpty())
393         className = QLatin1String("QDBusInterface");
394
395     QVarLengthArray<int> idata;
396     idata.resize(sizeof(QDBusMetaObjectPrivate) / sizeof(int));
397
398     int methodParametersDataSize =
399             ((aggregateParameterCount(signals_)
400              + aggregateParameterCount(methods)) * 2) // types and parameter names
401             - signals_.count() // return "parameters" don't have names
402             - methods.count(); // ditto
403
404     QDBusMetaObjectPrivate *header = reinterpret_cast<QDBusMetaObjectPrivate *>(idata.data());
405     Q_STATIC_ASSERT_X(QMetaObjectPrivate::OutputRevision == 7, "QtDBus meta-object generator should generate the same version as moc");
406     header->revision = QMetaObjectPrivate::OutputRevision;
407     header->className = 0;
408     header->classInfoCount = 0;
409     header->classInfoData = 0;
410     header->methodCount = signals_.count() + methods.count();
411     header->methodData = idata.size();
412     header->propertyCount = properties.count();
413     header->propertyData = header->methodData + header->methodCount * 5 + methodParametersDataSize;
414     header->enumeratorCount = 0;
415     header->enumeratorData = 0;
416     header->constructorCount = 0;
417     header->constructorData = 0;
418     header->flags = RequiresVariantMetaObject;
419     header->signalCount = signals_.count();
420     // These are specific to QDBusMetaObject:
421     header->propertyDBusData = header->propertyData + header->propertyCount * 3;
422     header->methodDBusData = header->propertyDBusData + header->propertyCount * intsPerProperty;
423
424     int data_size = idata.size() +
425                     (header->methodCount * (5+intsPerMethod)) + methodParametersDataSize +
426                     (header->propertyCount * (3+intsPerProperty));
427     foreach (const Method &mm, signals_)
428         data_size += 2 + mm.inputTypes.count() + mm.outputTypes.count();
429     foreach (const Method &mm, methods)
430         data_size += 2 + mm.inputTypes.count() + mm.outputTypes.count();
431     idata.resize(data_size + 1);
432
433     QMetaStringTable strings;
434     strings.enter(className.toLatin1());
435
436     int offset = header->methodData;
437     int parametersOffset = offset + header->methodCount * 5;
438     int signatureOffset = header->methodDBusData;
439     int typeidOffset = header->methodDBusData + header->methodCount * intsPerMethod;
440     idata[typeidOffset++] = 0;                           // eod
441
442     // add each method:
443     for (int x = 0; x < 2; ++x) {
444         // Signals must be added before other methods, to match moc.
445         QMap<QByteArray, Method> &map = (x == 0) ? signals_ : methods;
446         for (QMap<QByteArray, Method>::ConstIterator it = map.constBegin();
447              it != map.constEnd(); ++it) {
448             const Method &mm = it.value();
449
450             int argc = mm.inputTypes.size() + qMax(0, mm.outputTypes.size() - 1);
451
452             idata[offset++] = strings.enter(mm.name);
453             idata[offset++] = argc;
454             idata[offset++] = parametersOffset;
455             idata[offset++] = strings.enter(mm.tag);
456             idata[offset++] = mm.flags;
457
458             // Parameter types
459             for (int i = -1; i < argc; ++i) {
460                 int type;
461                 QByteArray typeName;
462                 if (i < 0) { // Return type
463                     if (!mm.outputTypes.isEmpty())
464                         type = mm.outputTypes.first();
465                     else
466                         type = QMetaType::Void;
467                 } else if (i < mm.inputTypes.size()) {
468                     type = mm.inputTypes.at(i);
469                 } else {
470                     Q_ASSERT(mm.outputTypes.size() > 1);
471                     type = mm.outputTypes.at(i - mm.inputTypes.size() + 1);
472                     // Output parameters are references; type id not available
473                     typeName = QMetaType::typeName(type);
474                     typeName.append('&');
475                 }
476                 Q_ASSERT(type != QMetaType::UnknownType);
477                 int typeInfo;
478                 if (!typeName.isEmpty())
479                     typeInfo = IsUnresolvedType | strings.enter(typeName);
480                 else
481                     typeInfo = type;
482                 idata[parametersOffset++] = typeInfo;
483             }
484             // Parameter names
485             for (int i = 0; i < argc; ++i)
486                 idata[parametersOffset++] = strings.enter(mm.parameterNames.at(i));
487
488             idata[signatureOffset++] = typeidOffset;
489             idata[typeidOffset++] = mm.inputTypes.count();
490             memcpy(idata.data() + typeidOffset, mm.inputTypes.data(), mm.inputTypes.count() * sizeof(int));
491             typeidOffset += mm.inputTypes.count();
492
493             idata[signatureOffset++] = typeidOffset;
494             idata[typeidOffset++] = mm.outputTypes.count();
495             memcpy(idata.data() + typeidOffset, mm.outputTypes.data(), mm.outputTypes.count() * sizeof(int));
496             typeidOffset += mm.outputTypes.count();
497         }
498     }
499
500     Q_ASSERT(offset == header->methodData + header->methodCount * 5);
501     Q_ASSERT(parametersOffset = header->propertyData);
502     Q_ASSERT(signatureOffset == header->methodDBusData + header->methodCount * intsPerMethod);
503     Q_ASSERT(typeidOffset == idata.size());
504     offset += methodParametersDataSize;
505     Q_ASSERT(offset == header->propertyData);
506
507     // add each property
508     signatureOffset = header->propertyDBusData;
509     for (QMap<QByteArray, Property>::ConstIterator it = properties.constBegin();
510          it != properties.constEnd(); ++it) {
511         const Property &mp = it.value();
512
513         // form is name, typeinfo, flags
514         idata[offset++] = strings.enter(it.key()); // name
515         Q_ASSERT(mp.type != QMetaType::UnknownType);
516         idata[offset++] = mp.type;
517         idata[offset++] = mp.flags;
518
519         idata[signatureOffset++] = strings.enter(mp.signature);
520         idata[signatureOffset++] = mp.type;
521     }
522
523     Q_ASSERT(offset == header->propertyDBusData);
524     Q_ASSERT(signatureOffset == header->methodDBusData);
525
526     char *string_data = new char[strings.blobSize()];
527     strings.writeBlob(string_data);
528
529     uint *uint_data = new uint[idata.size()];
530     memcpy(uint_data, idata.data(), idata.size() * sizeof(int));
531
532     // put the metaobject together
533     obj->d.data = uint_data;
534     obj->d.extradata = 0;
535     obj->d.stringdata = reinterpret_cast<const QByteArrayData *>(string_data);
536     obj->d.superdata = &QDBusAbstractInterface::staticMetaObject;
537 }
538
539 #if 0
540 void QDBusMetaObjectGenerator::writeWithoutXml(const QString &interface)
541 {
542     // no XML definition
543     QString tmp(interface);
544     tmp.replace(QLatin1Char('.'), QLatin1String("::"));
545     QByteArray name(tmp.toLatin1());
546
547     QDBusMetaObjectPrivate *header = new QDBusMetaObjectPrivate;
548     memset(header, 0, sizeof *header);
549     header->revision = 1;
550     // leave the rest with 0
551
552     char *stringdata = new char[name.length() + 1];
553     stringdata[name.length()] = '\0';
554     
555     d.data = reinterpret_cast<uint*>(header);
556     d.extradata = 0;
557     d.stringdata = stringdata;
558     d.superdata = &QDBusAbstractInterface::staticMetaObject;
559     cached = false;
560 }
561 #endif
562
563 /////////
564 // class QDBusMetaObject
565
566 QDBusMetaObject *QDBusMetaObject::createMetaObject(const QString &interface, const QString &xml,
567                                                    QHash<QString, QDBusMetaObject *> &cache,
568                                                    QDBusError &error)
569 {
570     error = QDBusError();
571     QDBusIntrospection::Interfaces parsed = QDBusIntrospection::parseInterfaces(xml);
572
573     QDBusMetaObject *we = 0;
574     QDBusIntrospection::Interfaces::ConstIterator it = parsed.constBegin();
575     QDBusIntrospection::Interfaces::ConstIterator end = parsed.constEnd();
576     for ( ; it != end; ++it) {
577         // check if it's in the cache
578         bool us = it.key() == interface;
579
580         QDBusMetaObject *obj = cache.value(it.key(), 0);
581         if ( !obj && ( us || !interface.startsWith( QLatin1String("local.") ) ) ) {
582             // not in cache; create
583             obj = new QDBusMetaObject;
584             QDBusMetaObjectGenerator generator(it.key(), it.value().constData());
585             generator.write(obj);
586
587             if ( (obj->cached = !it.key().startsWith( QLatin1String("local.") )) )
588                 // cache it
589                 cache.insert(it.key(), obj);
590             else if (!us)
591                 delete obj;
592
593         }
594
595         if (us)
596             // it's us
597             we = obj;
598     }
599
600     if (we)
601         return we;
602     // still nothing?
603     
604     if (parsed.isEmpty()) {
605         // object didn't return introspection
606         we = new QDBusMetaObject;
607         QDBusMetaObjectGenerator generator(interface, 0);
608         generator.write(we);
609         we->cached = false;
610         return we;
611     } else if (interface.isEmpty()) {
612         // merge all interfaces
613         it = parsed.constBegin();
614         QDBusIntrospection::Interface merged = *it.value().constData();
615  
616         for (++it; it != end; ++it) {
617             merged.annotations.unite(it.value()->annotations);
618             merged.methods.unite(it.value()->methods);
619             merged.signals_.unite(it.value()->signals_);
620             merged.properties.unite(it.value()->properties);
621         }
622
623         merged.name = QLatin1String("local.Merged");
624         merged.introspection.clear();
625
626         we = new QDBusMetaObject;
627         QDBusMetaObjectGenerator generator(merged.name, &merged);
628         generator.write(we);
629         we->cached = false;
630         return we;
631     }
632
633     // mark as an error
634     error = QDBusError(QDBusError::UnknownInterface,
635         QString::fromLatin1("Interface '%1' was not found")
636                        .arg(interface));
637     return 0;
638 }
639
640 QDBusMetaObject::QDBusMetaObject()
641 {
642 }
643
644 static inline const QDBusMetaObjectPrivate *priv(const uint* data)
645 {
646     return reinterpret_cast<const QDBusMetaObjectPrivate *>(data);
647 }
648
649 const int *QDBusMetaObject::inputTypesForMethod(int id) const
650 {
651     //id -= methodOffset();
652     if (id >= 0 && id < priv(d.data)->methodCount) {
653         int handle = priv(d.data)->methodDBusData + id*intsPerMethod;
654         return reinterpret_cast<const int*>(d.data + d.data[handle]);
655     }
656     return 0;
657 }
658
659 const int *QDBusMetaObject::outputTypesForMethod(int id) const
660 {
661     //id -= methodOffset();
662     if (id >= 0 && id < priv(d.data)->methodCount) {
663         int handle = priv(d.data)->methodDBusData + id*intsPerMethod;
664         return reinterpret_cast<const int*>(d.data + d.data[handle + 1]);
665     }
666     return 0;
667 }
668
669 int QDBusMetaObject::propertyMetaType(int id) const
670 {
671     //id -= propertyOffset();
672     if (id >= 0 && id < priv(d.data)->propertyCount) {
673         int handle = priv(d.data)->propertyDBusData + id*intsPerProperty;
674         return d.data[handle + 1];
675     }
676     return 0;
677 }
678
679 QT_END_NAMESPACE
680
681 #endif // QT_NO_DBUS