1 /**************************************************************************
3 ** This file is part of Qt Creator
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
7 ** Contact: Nokia Corporation (qt-info@nokia.com)
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
16 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Nokia gives you certain additional
26 ** rights. These rights are described in the Nokia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** If you have questions regarding the use of this file, please contact
30 ** Nokia at qt-info@nokia.com.
32 **************************************************************************/
34 // WARNING: This code is shared with the qmlplugindump tool code in Qt.
35 // Modifications to this file need to be applied there.
37 #include <QtDeclarative/QtDeclarative>
38 #include <QtDeclarative/private/qdeclarativemetatype_p.h>
39 #include <QtDeclarative/private/qdeclarativeopenmetaobject_p.h>
40 #include <QtDeclarative/QDeclarativeView>
42 #include <QtGui/QApplication>
44 #include <QtCore/QSet>
45 #include <QtCore/QMetaObject>
46 #include <QtCore/QMetaProperty>
47 #include <QtCore/QDebug>
48 #include <QtCore/private/qobject_p.h>
49 #include <QtCore/private/qmetaobject_p.h>
53 #include "qmlstreamwriter.h"
56 #include <QtGui/private/qsimulatorconnection_p.h>
63 void collectReachableMetaObjects(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
65 if (! meta || metas->contains(meta))
68 // dynamic meta objects break things badly, so just ignore them
69 const QMetaObjectPrivate *mop = reinterpret_cast<const QMetaObjectPrivate *>(meta->d.data);
70 if (!(mop->flags & DynamicMetaObject))
73 collectReachableMetaObjects(meta->superClass(), metas);
76 QString currentProperty;
78 void collectReachableMetaObjects(QObject *object, QSet<const QMetaObject *> *metas)
83 const QMetaObject *meta = object->metaObject();
84 qDebug() << "Processing object" << meta->className();
85 collectReachableMetaObjects(meta, metas);
87 for (int index = 0; index < meta->propertyCount(); ++index) {
88 QMetaProperty prop = meta->property(index);
89 if (QDeclarativeMetaType::isQObject(prop.userType())) {
90 qDebug() << " Processing property" << prop.name();
91 currentProperty = QString("%1::%2").arg(meta->className(), prop.name());
93 // if the property was not initialized during construction,
94 // accessing a member of oo is going to cause a segmentation fault
95 QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
96 if (oo && !metas->contains(oo->metaObject()))
97 collectReachableMetaObjects(oo, metas);
98 currentProperty.clear();
103 void collectReachableMetaObjects(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
105 collectReachableMetaObjects(ty->metaObject(), metas);
106 if (ty->attachedPropertiesType())
107 collectReachableMetaObjects(ty->attachedPropertiesType(), metas);
110 /* We want to add the MetaObject for 'Qt' to the list, this is a
111 simple way to access it.
113 class FriendlyQObject: public QObject
116 static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
119 /* When we dump a QMetaObject, we want to list all the types it is exported as.
120 To do this, we need to find the QDeclarativeTypes associated with this
123 static QHash<QByteArray, QSet<const QDeclarativeType *> > qmlTypesByCppName;
125 static QHash<QByteArray, QByteArray> cppToId;
127 /* Takes a C++ type name, such as Qt::LayoutDirection or QString and
128 maps it to how it should appear in the description file.
130 These names need to be unique globally, so we don't change the C++ symbol's
131 name much. It is mostly used to for explicit translations such as
132 QString->string and translations for extended QML objects.
134 QByteArray convertToId(const QByteArray &cppName)
136 return cppToId.value(cppName, cppName);
139 QSet<const QMetaObject *> collectReachableMetaObjects(const QString &importCode, QDeclarativeEngine *engine)
141 QSet<const QMetaObject *> metas;
142 metas.insert(FriendlyQObject::qtMeta());
144 QHash<QByteArray, QSet<QByteArray> > extensions;
145 foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
146 qmlTypesByCppName[ty->metaObject()->className()].insert(ty);
147 if (ty->isExtendedType()) {
148 extensions[ty->typeName()].insert(ty->metaObject()->className());
150 collectReachableMetaObjects(ty, &metas);
153 // Adjust ids of extended objects.
154 // The chain ends up being:
155 // __extended__.originalname - the base object
156 // __extension_0_.originalname - first extension
158 // __extension_n-2_.originalname - second to last extension
159 // originalname - last extension
160 // ### does this actually work for multiple extensions? it seems like the prototypes might be wrong
161 foreach (const QByteArray &extendedCpp, extensions.keys()) {
162 cppToId.remove(extendedCpp);
163 const QByteArray extendedId = convertToId(extendedCpp);
164 cppToId.insert(extendedCpp, "__extended__." + extendedId);
165 QSet<QByteArray> extensionCppNames = extensions.value(extendedCpp);
167 foreach (const QByteArray &extensionCppName, extensionCppNames) {
168 if (c != extensionCppNames.size() - 1) {
169 QByteArray adjustedName = QString("__extension__%1.%2").arg(QString::number(c), QString(extendedId)).toAscii();
170 cppToId.insert(extensionCppName, adjustedName);
172 cppToId.insert(extensionCppName, extendedId);
178 // find even more QMetaObjects by instantiating QML types and running
179 // over the instances
180 foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
181 if (ty->isExtendedType())
184 QByteArray tyName = ty->qmlTypeName();
185 tyName = tyName.mid(tyName.lastIndexOf('/') + 1);
187 QByteArray code = importCode.toUtf8();
191 QDeclarativeComponent c(engine);
192 c.setData(code, QUrl("typeinstance"));
194 QObject *object = c.create();
196 collectReachableMetaObjects(object, &metas);
198 qDebug() << "Could not create" << tyName << ":" << c.errorString();
207 QmlStreamWriter *qml;
208 QString relocatableModuleUri;
211 Dumper(QmlStreamWriter *qml) : qml(qml) {}
213 void setRelocatableModuleUri(const QString &uri)
215 relocatableModuleUri = uri;
218 void dump(const QMetaObject *meta)
220 qml->writeStartObject("Component");
222 QByteArray id = convertToId(meta->className());
223 qml->writeScriptBinding(QLatin1String("name"), enquote(id));
225 for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
226 QMetaClassInfo classInfo = meta->classInfo(index);
227 if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
228 qml->writeScriptBinding(QLatin1String("defaultProperty"), enquote(QLatin1String(classInfo.value())));
233 if (meta->superClass())
234 qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass()->className())));
236 QSet<const QDeclarativeType *> qmlTypes = qmlTypesByCppName.value(meta->className());
237 if (!qmlTypes.isEmpty()) {
240 foreach (const QDeclarativeType *qmlTy, qmlTypes) {
241 QString qmlTyName = qmlTy->qmlTypeName();
242 // some qmltype names are missing the actual names, ignore that import
243 if (qmlTyName.endsWith('/'))
245 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
246 qmlTyName.remove(0, relocatableModuleUri.size() + 1);
248 exports += enquote(QString("%1 %2.%3").arg(
250 QString::number(qmlTy->majorVersion()),
251 QString::number(qmlTy->minorVersion())));
254 // ensure exports are sorted and don't change order when the plugin is dumped again
255 exports.removeDuplicates();
258 qml->writeArrayBinding(QLatin1String("exports"), exports);
260 if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
261 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
262 convertToId(attachedType->className())));
266 for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
267 dump(meta->enumerator(index));
269 for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
270 dump(meta->property(index));
272 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
273 dump(meta->method(index));
275 qml->writeEndObject();
278 void writeEasingCurve()
280 qml->writeStartObject("Component");
281 qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
282 qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
283 qml->writeEndObject();
287 static QString enquote(const QString &string)
289 return QString("\"%1\"").arg(string);
292 /* Removes pointer and list annotations from a type name, returning
293 what was removed in isList and isPointer
295 static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
297 static QByteArray declListPrefix = "QDeclarativeListProperty<";
299 if (typeName->endsWith('*')) {
301 typeName->truncate(typeName->length() - 1);
302 removePointerAndList(typeName, isList, isPointer);
303 } else if (typeName->startsWith(declListPrefix)) {
305 typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
306 *typeName = typeName->mid(declListPrefix.size());
307 removePointerAndList(typeName, isList, isPointer);
310 *typeName = convertToId(*typeName);
313 void writeTypeProperties(QByteArray typeName, bool isWritable)
315 bool isList = false, isPointer = false;
316 removePointerAndList(&typeName, &isList, &isPointer);
318 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
320 qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
322 qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
324 qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
327 void dump(const QMetaProperty &prop)
329 qml->writeStartObject("Property");
331 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
332 writeTypeProperties(prop.typeName(), prop.isWritable());
334 qml->writeEndObject();
337 void dump(const QMetaMethod &meth)
339 if (meth.methodType() == QMetaMethod::Signal) {
340 if (meth.access() != QMetaMethod::Protected)
341 return; // nothing to do.
342 } else if (meth.access() != QMetaMethod::Public) {
343 return; // nothing to do.
346 QByteArray name = meth.signature();
347 int lparenIndex = name.indexOf('(');
348 if (lparenIndex == -1) {
349 return; // invalid signature
351 name = name.left(lparenIndex);
353 if (meth.methodType() == QMetaMethod::Signal)
354 qml->writeStartObject(QLatin1String("Signal"));
356 qml->writeStartObject(QLatin1String("Method"));
358 qml->writeScriptBinding(QLatin1String("name"), enquote(name));
360 const QString typeName = convertToId(meth.typeName());
361 if (! typeName.isEmpty())
362 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
364 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
365 QByteArray argName = meth.parameterNames().at(i);
367 qml->writeStartObject(QLatin1String("Parameter"));
368 if (! argName.isEmpty())
369 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
370 writeTypeProperties(meth.parameterTypes().at(i), true);
371 qml->writeEndObject();
374 qml->writeEndObject();
377 void dump(const QMetaEnum &e)
379 qml->writeStartObject(QLatin1String("Enum"));
380 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
382 QList<QPair<QString, QString> > namesValues;
383 for (int index = 0; index < e.keyCount(); ++index) {
384 namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
387 qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
388 qml->writeEndObject();
394 EXIT_INVALIDARGUMENTS = 1,
400 void sigSegvHandler(int) {
401 fprintf(stderr, "Error: qmldump SEGV\n");
402 if (!currentProperty.isEmpty())
403 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
408 void printUsage(const QString &appName)
410 qWarning() << qPrintable(QString(
411 "Usage: %1 [--notrelocatable] module.uri version [module/import/path]\n"
412 " %1 --path path/to/qmldir/directory [version]\n"
414 "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
418 int main(int argc, char *argv[])
421 // qmldump may crash, but we don't want any crash handlers to pop up
422 // therefore we intercept the segfault and just exit() ourselves
423 struct sigaction action;
425 sigemptyset(&action.sa_mask);
426 action.sa_handler = &sigSegvHandler;
429 sigaction(SIGSEGV, &action, 0);
433 // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
434 QtSimulatorPrivate::SimulatorConnection::createStubInstance();
436 QApplication app(argc, argv);
437 const QStringList args = app.arguments();
438 const QString appName = QFileInfo(app.applicationFilePath()).baseName();
439 if (!(args.size() >= 3 || (args.size() == 2 && args.at(1) == QLatin1String("--builtins")))) {
441 return EXIT_INVALIDARGUMENTS;
444 QString pluginImportUri;
445 QString pluginImportVersion;
446 QString pluginImportPath;
447 bool relocatable = true;
448 bool pathImport = false;
449 if (args.size() >= 3) {
450 QStringList positionalArgs;
451 foreach (const QString &arg, args) {
452 if (!arg.startsWith("--")) {
453 positionalArgs.append(arg);
457 if (arg == QLatin1String("--notrelocatable")) {
459 } else if (arg == QLatin1String("--path")) {
462 qWarning() << "Invalid argument: " << arg;
463 return EXIT_INVALIDARGUMENTS;
468 if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
469 qWarning() << "Incorrect number of positional arguments";
470 return EXIT_INVALIDARGUMENTS;
472 pluginImportUri = positionalArgs[1];
473 pluginImportVersion = positionalArgs[2];
474 if (positionalArgs.size() >= 4)
475 pluginImportPath = positionalArgs[3];
477 if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
478 qWarning() << "Incorrect number of positional arguments";
479 return EXIT_INVALIDARGUMENTS;
481 pluginImportPath = positionalArgs[1];
482 if (positionalArgs.size() == 3)
483 pluginImportVersion = positionalArgs[2];
487 QDeclarativeView view;
488 QDeclarativeEngine *engine = view.engine();
489 if (!pluginImportPath.isEmpty())
490 engine->addImportPath(pluginImportPath);
492 // find all QMetaObjects reachable from the builtin module
493 QByteArray importCode("import QtQuick 1.0\n");
494 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(importCode, engine);
496 // this will hold the meta objects we want to dump information of
497 QSet<const QMetaObject *> metas;
499 if (pluginImportUri.isEmpty() && !pathImport) {
500 metas = defaultReachable;
502 // find all QMetaObjects reachable when the specified module is imported
504 importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
506 // pluginImportVersion can be empty
507 importCode += QString("import \"%1\" %2\n").arg(pluginImportPath, pluginImportVersion).toAscii();
510 // create a component with these imports to make sure the imports are valid
511 // and to populate the declarative meta type system
513 QByteArray code = importCode;
514 code += "QtObject {}";
515 QDeclarativeComponent c(engine);
517 c.setData(code, QUrl("typelist"));
519 if (!c.errors().isEmpty()) {
520 foreach (const QDeclarativeError &error, c.errors())
521 qWarning() << error.toString();
522 return EXIT_IMPORTERROR;
526 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(importCode, engine);
527 candidates.subtract(defaultReachable);
529 // Also eliminate meta objects with the same classname.
530 // This is required because extended objects seem not to share
531 // a single meta object instance.
532 QSet<QByteArray> defaultReachableNames;
533 foreach (const QMetaObject *mo, defaultReachable)
534 defaultReachableNames.insert(QByteArray(mo->className()));
535 foreach (const QMetaObject *mo, candidates) {
536 if (!defaultReachableNames.contains(mo->className()))
541 // setup static rewrites of type names
542 cppToId.insert("QString", "string");
543 cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
545 // start dumping data
547 QmlStreamWriter qml(&bytes);
549 qml.writeStartDocument();
550 qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 0);
552 "// This file describes the plugin-supplied types contained in the library.\n"
553 "// It is used for QML tooling purposes only.\n"
555 qml.writeStartObject("Module");
557 // put the metaobjects into a map so they are always dumped in the same order
558 QMap<QString, const QMetaObject *> nameToMeta;
559 foreach (const QMetaObject *meta, metas)
560 nameToMeta.insert(convertToId(meta->className()), meta);
564 dumper.setRelocatableModuleUri(pluginImportUri);
565 foreach (const QMetaObject *meta, nameToMeta) {
569 // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
570 // properties using the QEasingCurve type get useful type information.
571 if (pluginImportUri.isEmpty())
572 dumper.writeEasingCurve();
574 qml.writeEndObject();
575 qml.writeEndDocument();
577 std::cout << bytes.constData();
579 // workaround to avoid crashes on exit
581 timer.setSingleShot(true);
582 timer.setInterval(0);
583 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));