1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtDBus module of the Qt Toolkit.
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.
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.
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.
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.
40 ****************************************************************************/
42 #include "qdbusmetaobject_p.h"
44 #include <QtCore/qbytearray.h>
45 #include <QtCore/qhash.h>
46 #include <QtCore/qstring.h>
47 #include <QtCore/qvarlengtharray.h>
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"
56 #include <private/qmetaobject_p.h>
57 #include <private/qmetaobjectbuilder_p.h>
63 class QDBusMetaObjectGenerator
66 QDBusMetaObjectGenerator(const QString &interface,
67 const QDBusIntrospection::Interface *parsedData);
68 void write(QDBusMetaObject *obj);
69 void writeWithoutXml(QDBusMetaObject *obj);
73 QList<QByteArray> parameterNames;
76 QVarLengthArray<int, 4> inputTypes;
77 QVarLengthArray<int, 4> outputTypes;
92 QMap<QByteArray, Method> signals_;
93 QMap<QByteArray, Method> methods;
94 QMap<QByteArray, Property> properties;
96 const QDBusIntrospection::Interface *data;
99 Type findType(const QByteArray &signature,
100 const QDBusIntrospection::Annotations &annotations,
101 const char *direction = "Out", int id = -1);
105 void parseProperties();
107 static int aggregateParameterCount(const QMap<QByteArray, Method> &map);
110 static const int intsPerProperty = 2;
111 static const int intsPerMethod = 2;
113 struct QDBusMetaObjectPrivate : public QMetaObjectPrivate
115 int propertyDBusData;
119 QDBusMetaObjectGenerator::QDBusMetaObjectGenerator(const QString &interfaceName,
120 const QDBusIntrospection::Interface *parsedData)
121 : data(parsedData), interface(interfaceName)
125 parseSignals(); // call parseSignals first so that slots override signals
130 Q_DBUS_EXPORT bool qt_dbus_metaobject_skip_annotations = false;
132 QDBusMetaObjectGenerator::Type
133 QDBusMetaObjectGenerator::findType(const QByteArray &signature,
134 const QDBusIntrospection::Annotations &annotations,
135 const char *direction, int id)
137 struct QDBusRawTypeHandler {
138 static void destroy(void *)
140 qFatal("Cannot destroy placeholder type QDBusRawType");
143 static void *create(const void *)
145 qFatal("Cannot create placeholder type QDBusRawType");
149 static void destruct(void *)
151 qFatal("Cannot destruct placeholder type QDBusRawType");
154 static void *construct(void *, const void *)
156 qFatal("Cannot construct placeholder type QDBusRawType");
162 result.id = QVariant::Invalid;
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");
170 annotationName += QString::fromLatin1(".%1%2")
171 .arg(QLatin1String(direction))
174 // extract from annotations:
175 QByteArray typeName = annotations.value(annotationName).toLatin1();
177 // verify that it's a valid one
178 if (!typeName.isEmpty()) {
180 type = QMetaType::type(typeName);
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,
192 QMetaType::MovableType);
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
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;
207 result.name = "QDBusRawType::" + signature;
211 result.name = QVariant::typeToName( QVariant::Type(type) );
215 return result; // success
218 void QDBusMetaObjectGenerator::parseMethods()
222 // Add cloned methods when the remote object has return types
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;
231 mm.name = m.name.toLatin1();
232 QByteArray prototype = mm.name;
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);
241 Type type = findType(arg.type.toLatin1(), m.annotations, "In", i);
242 if (type.id == QVariant::Invalid) {
247 mm.inputTypes.append(type.id);
249 mm.parameterNames.append(arg.name.toLatin1());
251 prototype.append(type.name);
252 prototype.append(',');
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);
260 Type type = findType(arg.type.toLatin1(), m.annotations, "Out", i);
261 if (type.id == QVariant::Invalid) {
266 mm.outputTypes.append(type.id);
269 // non-const ref parameter
270 mm.parameterNames.append(arg.name.toLatin1());
272 prototype.append(type.name);
273 prototype.append("&,");
278 // convert the last commas:
279 if (!mm.parameterNames.isEmpty())
280 prototype[prototype.length() - 1] = ')';
282 prototype.append(')');
284 // check the async tag
285 if (m.annotations.value(QLatin1String(ANNOTATION_NO_WAIT)) == QLatin1String("true"))
286 mm.tag = "Q_NOREPLY";
289 mm.flags = AccessPublic | MethodSlot | MethodScriptable;
292 methods.insert(QMetaObject::normalizedSignature(prototype), mm);
296 void QDBusMetaObjectGenerator::parseSignals()
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;
304 mm.name = s.name.toLatin1();
305 QByteArray prototype = mm.name;
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);
314 Type type = findType(arg.type.toLatin1(), s.annotations, "Out", i);
315 if (type.id == QVariant::Invalid) {
320 mm.inputTypes.append(type.id);
322 mm.parameterNames.append(arg.name.toLatin1());
324 prototype.append(type.name);
325 prototype.append(',');
329 // convert the last commas:
330 if (!mm.parameterNames.isEmpty())
331 prototype[prototype.length() - 1] = ')';
333 prototype.append(')');
336 mm.flags = AccessProtected | MethodSignal | MethodScriptable;
339 signals_.insert(QMetaObject::normalizedSignature(prototype), mm);
343 void QDBusMetaObjectGenerator::parseProperties()
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;
350 Type type = findType(p.type.toLatin1(), p.annotations);
351 if (type.id == QVariant::Invalid)
354 QByteArray name = p.name.toLatin1();
355 mp.signature = p.type.toLatin1();
357 mp.typeName = type.name;
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;
367 properties.insert(name, mp);
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)
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());
385 void QDBusMetaObjectGenerator::write(QDBusMetaObject *obj)
387 // this code here is mostly copied from qaxbase.cpp
388 // with a few modifications to make it cleaner
390 QString className = interface;
391 className.replace(QLatin1Char('.'), QLatin1String("::"));
392 if (className.isEmpty())
393 className = QLatin1String("QDBusInterface");
395 QVarLengthArray<int> idata;
396 idata.resize(sizeof(QDBusMetaObjectPrivate) / sizeof(int));
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
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;
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);
433 QMetaStringTable strings;
434 strings.enter(className.toLatin1());
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
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();
450 int argc = mm.inputTypes.size() + qMax(0, mm.outputTypes.size() - 1);
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;
459 for (int i = -1; i < argc; ++i) {
462 if (i < 0) { // Return type
463 if (!mm.outputTypes.isEmpty())
464 type = mm.outputTypes.first();
466 type = QMetaType::Void;
467 } else if (i < mm.inputTypes.size()) {
468 type = mm.inputTypes.at(i);
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('&');
476 Q_ASSERT(type != QMetaType::UnknownType);
478 if (!typeName.isEmpty())
479 typeInfo = IsUnresolvedType | strings.enter(typeName);
482 idata[parametersOffset++] = typeInfo;
485 for (int i = 0; i < argc; ++i)
486 idata[parametersOffset++] = strings.enter(mm.parameterNames.at(i));
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();
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();
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);
508 signatureOffset = header->propertyDBusData;
509 for (QMap<QByteArray, Property>::ConstIterator it = properties.constBegin();
510 it != properties.constEnd(); ++it) {
511 const Property &mp = it.value();
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;
519 idata[signatureOffset++] = strings.enter(mp.signature);
520 idata[signatureOffset++] = mp.type;
523 Q_ASSERT(offset == header->propertyDBusData);
524 Q_ASSERT(signatureOffset == header->methodDBusData);
526 char *string_data = new char[strings.blobSize()];
527 strings.writeBlob(string_data);
529 uint *uint_data = new uint[idata.size()];
530 memcpy(uint_data, idata.data(), idata.size() * sizeof(int));
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;
540 void QDBusMetaObjectGenerator::writeWithoutXml(const QString &interface)
543 QString tmp(interface);
544 tmp.replace(QLatin1Char('.'), QLatin1String("::"));
545 QByteArray name(tmp.toLatin1());
547 QDBusMetaObjectPrivate *header = new QDBusMetaObjectPrivate;
548 memset(header, 0, sizeof *header);
549 header->revision = 1;
550 // leave the rest with 0
552 char *stringdata = new char[name.length() + 1];
553 stringdata[name.length()] = '\0';
555 d.data = reinterpret_cast<uint*>(header);
557 d.stringdata = stringdata;
558 d.superdata = &QDBusAbstractInterface::staticMetaObject;
564 // class QDBusMetaObject
566 QDBusMetaObject *QDBusMetaObject::createMetaObject(const QString &interface, const QString &xml,
567 QHash<QString, QDBusMetaObject *> &cache,
570 error = QDBusError();
571 QDBusIntrospection::Interfaces parsed = QDBusIntrospection::parseInterfaces(xml);
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;
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);
587 if ( (obj->cached = !it.key().startsWith( QLatin1String("local.") )) )
589 cache.insert(it.key(), obj);
604 if (parsed.isEmpty()) {
605 // object didn't return introspection
606 we = new QDBusMetaObject;
607 QDBusMetaObjectGenerator generator(interface, 0);
611 } else if (interface.isEmpty()) {
612 // merge all interfaces
613 it = parsed.constBegin();
614 QDBusIntrospection::Interface merged = *it.value().constData();
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);
623 merged.name = QLatin1String("local.Merged");
624 merged.introspection.clear();
626 we = new QDBusMetaObject;
627 QDBusMetaObjectGenerator generator(merged.name, &merged);
634 error = QDBusError(QDBusError::UnknownInterface,
635 QString::fromLatin1("Interface '%1' was not found")
640 QDBusMetaObject::QDBusMetaObject()
644 static inline const QDBusMetaObjectPrivate *priv(const uint* data)
646 return reinterpret_cast<const QDBusMetaObjectPrivate *>(data);
649 const int *QDBusMetaObject::inputTypesForMethod(int id) const
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]);
659 const int *QDBusMetaObject::outputTypesForMethod(int id) const
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]);
669 int QDBusMetaObject::propertyMetaType(int id) const
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];