qmlplugindump: Fix dumping empty names for generated QMetaObjects.
[profile/ivi/qtdeclarative.git] / tools / qmlplugindump / main.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the tools applications of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 **
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 **
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
29 **
30 ** Other Usage
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include <QtDeclarative/QtDeclarative>
43 #include <QtDeclarative/private/qdeclarativemetatype_p.h>
44 #include <QtDeclarative/private/qdeclarativeopenmetaobject_p.h>
45 #include <QtDeclarative/private/qquickevents_p_p.h>
46 #include <QtDeclarative/private/qquickpincharea_p.h>
47
48 #include <QtWidgets/QApplication>
49
50 #include <QtCore/QSet>
51 #include <QtCore/QMetaObject>
52 #include <QtCore/QMetaProperty>
53 #include <QtCore/QDebug>
54 #include <QtCore/private/qobject_p.h>
55 #include <QtCore/private/qmetaobject_p.h>
56
57 #include <iostream>
58
59 #include "qmlstreamwriter.h"
60
61 #ifdef QT_SIMULATOR
62 #include <QtGui/private/qsimulatorconnection_p.h>
63 #endif
64
65 #ifdef Q_OS_UNIX
66 #include <signal.h>
67 #endif
68
69 QString pluginImportPath;
70 bool verbose = false;
71
72 QString currentProperty;
73 QString inObjectInstantiation;
74
75 void collectReachableMetaObjects(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
76 {
77     if (! meta || metas->contains(meta))
78         return;
79
80     // dynamic meta objects break things badly, so just ignore them
81     const QMetaObjectPrivate *mop = reinterpret_cast<const QMetaObjectPrivate *>(meta->d.data);
82     if (!(mop->flags & DynamicMetaObject))
83         metas->insert(meta);
84
85     collectReachableMetaObjects(meta->superClass(), metas);
86 }
87
88 void collectReachableMetaObjects(QObject *object, QSet<const QMetaObject *> *metas)
89 {
90     if (! object)
91         return;
92
93     const QMetaObject *meta = object->metaObject();
94     if (verbose)
95         qDebug() << "Processing object" << meta->className();
96     collectReachableMetaObjects(meta, metas);
97
98     for (int index = 0; index < meta->propertyCount(); ++index) {
99         QMetaProperty prop = meta->property(index);
100         if (QDeclarativeMetaType::isQObject(prop.userType())) {
101             if (verbose)
102                 qDebug() << "  Processing property" << prop.name();
103             currentProperty = QString("%1::%2").arg(meta->className(), prop.name());
104
105             // if the property was not initialized during construction,
106             // accessing a member of oo is going to cause a segmentation fault
107             QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
108             if (oo && !metas->contains(oo->metaObject()))
109                 collectReachableMetaObjects(oo, metas);
110             currentProperty.clear();
111         }
112     }
113 }
114
115 void collectReachableMetaObjects(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
116 {
117     collectReachableMetaObjects(ty->metaObject(), metas);
118     if (ty->attachedPropertiesType())
119         collectReachableMetaObjects(ty->attachedPropertiesType(), metas);
120 }
121
122 /* We want to add the MetaObject for 'Qt' to the list, this is a
123    simple way to access it.
124 */
125 class FriendlyQObject: public QObject
126 {
127 public:
128     static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
129 };
130
131 /* When we dump a QMetaObject, we want to list all the types it is exported as.
132    To do this, we need to find the QDeclarativeTypes associated with this
133    QMetaObject.
134 */
135 static QHash<QByteArray, QSet<const QDeclarativeType *> > qmlTypesByCppName;
136
137 static QHash<QByteArray, QByteArray> cppToId;
138
139 /* Takes a C++ type name, such as Qt::LayoutDirection or QString and
140    maps it to how it should appear in the description file.
141
142    These names need to be unique globally, so we don't change the C++ symbol's
143    name much. It is mostly used to for explicit translations such as
144    QString->string and translations for extended QML objects.
145 */
146 QByteArray convertToId(const QByteArray &cppName)
147 {
148     return cppToId.value(cppName, cppName);
149 }
150
151 QByteArray convertToId(const QMetaObject *mo)
152 {
153     QByteArray className(mo->className());
154     if (!className.isEmpty())
155         return convertToId(className);
156
157     // likely a metaobject generated for an extended qml object
158     if (mo->superClass()) {
159         className = convertToId(mo->superClass());
160         className.append("_extended");
161         return className;
162     }
163
164     static QHash<const QMetaObject *, QByteArray> generatedNames;
165     className = generatedNames.value(mo);
166     if (!className.isEmpty())
167         return className;
168
169     qWarning() << "Found a QMetaObject without a className, generating a random name";
170     className = QByteArray("error-unknown-name-");
171     className.append(QByteArray::number(generatedNames.size()));
172     generatedNames.insert(mo, className);
173     return className;
174 }
175
176 /* All exported module APIs are collected into this list */
177 class ModuleApi {
178 public:
179     QString uri;
180     int majorVersion;
181     int minorVersion;
182     QByteArray objectId;
183 };
184 QList<ModuleApi> moduleApis;
185
186 QSet<const QMetaObject *> collectReachableMetaObjects(QDeclarativeEngine *engine, const QList<QDeclarativeType *> &skip = QList<QDeclarativeType *>())
187 {
188     QSet<const QMetaObject *> metas;
189     metas.insert(FriendlyQObject::qtMeta());
190
191     QHash<QByteArray, QSet<QByteArray> > extensions;
192     foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
193         qmlTypesByCppName[ty->metaObject()->className()].insert(ty);
194         if (ty->isExtendedType()) {
195             extensions[ty->typeName()].insert(ty->metaObject()->className());
196         }
197         collectReachableMetaObjects(ty, &metas);
198     }
199
200     // Adjust exports of the base object if there are extensions.
201     // For each export of a base object there can be a single extension object overriding it.
202     // Example: QDeclarativeGraphicsWidget overrides the QtQuick/QGraphicsWidget export
203     //          of QGraphicsWidget.
204     foreach (const QByteArray &baseCpp, extensions.keys()) {
205         QSet<const QDeclarativeType *> baseExports = qmlTypesByCppName.value(baseCpp);
206
207         const QSet<QByteArray> extensionCppNames = extensions.value(baseCpp);
208         foreach (const QByteArray &extensionCppName, extensionCppNames) {
209             const QSet<const QDeclarativeType *> extensionExports = qmlTypesByCppName.value(extensionCppName);
210
211             // remove extension exports from base imports
212             // unfortunately the QDeclarativeType pointers don't match, so can't use QSet::substract
213             QSet<const QDeclarativeType *> newBaseExports;
214             foreach (const QDeclarativeType *baseExport, baseExports) {
215                 bool match = false;
216                 foreach (const QDeclarativeType *extensionExport, extensionExports) {
217                     if (baseExport->qmlTypeName() == extensionExport->qmlTypeName()
218                             && baseExport->majorVersion() == extensionExport->majorVersion()
219                             && baseExport->minorVersion() == extensionExport->minorVersion()) {
220                         match = true;
221                         break;
222                     }
223                 }
224                 if (!match)
225                     newBaseExports.insert(baseExport);
226             }
227             baseExports = newBaseExports;
228         }
229         qmlTypesByCppName[baseCpp] = baseExports;
230     }
231
232     // find even more QMetaObjects by instantiating QML types and running
233     // over the instances
234     foreach (QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
235         if (skip.contains(ty))
236             continue;
237         if (ty->isExtendedType())
238             continue;
239         if (!ty->isCreatable())
240             continue;
241         if (ty->typeName() == "QDeclarativeComponent")
242             continue;
243
244         QString tyName = ty->qmlTypeName();
245         tyName = tyName.mid(tyName.lastIndexOf(QLatin1Char('/')) + 1);
246         if (tyName.isEmpty())
247             continue;
248
249         inObjectInstantiation = tyName;
250         QObject *object = ty->create();
251         inObjectInstantiation.clear();
252
253         if (object)
254             collectReachableMetaObjects(object, &metas);
255         else
256             qWarning() << "Could not create" << tyName;
257     }
258
259     // extract exported module api
260     QHashIterator<QString, QList<QDeclarativeMetaType::ModuleApi> > moduleApiIt(QDeclarativeMetaType::moduleApis());
261     while (moduleApiIt.hasNext()) {
262         moduleApiIt.next();
263         foreach (const QDeclarativeMetaType::ModuleApi &api, moduleApiIt.value()) {
264             ModuleApi moduleApi;
265             moduleApi.uri = moduleApiIt.key();
266             moduleApi.majorVersion = api.major;
267             moduleApi.minorVersion = api.minor;
268
269             if (api.qobject) {
270                 if (QObject *object = (*api.qobject)(engine, engine)) {
271                     collectReachableMetaObjects(object, &metas);
272                     moduleApi.objectId = convertToId(object->metaObject()->className());
273                     delete object;
274                 }
275             } else if (api.script) {
276                 qWarning() << "Can't dump the module api in " << moduleApi.uri << ". QJSValue based module API is not supported.";
277 //                QJSValue value = (*api.script)(engine, engine);
278 //                IdToObjectHash jsObjects;
279 //                collectReachableJSObjects(value, &jsObjects, &metas);
280             }
281
282             moduleApis += moduleApi;
283         }
284     }
285
286     return metas;
287 }
288
289
290 class Dumper
291 {
292     QmlStreamWriter *qml;
293     QString relocatableModuleUri;
294
295 public:
296     Dumper(QmlStreamWriter *qml) : qml(qml) {}
297
298     void setRelocatableModuleUri(const QString &uri)
299     {
300         relocatableModuleUri = uri;
301     }
302
303     void dump(const QMetaObject *meta)
304     {
305         qml->writeStartObject("Component");
306
307         QByteArray id = convertToId(meta);
308         qml->writeScriptBinding(QLatin1String("name"), enquote(id));
309
310         for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
311             QMetaClassInfo classInfo = meta->classInfo(index);
312             if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
313                 qml->writeScriptBinding(QLatin1String("defaultProperty"), enquote(QLatin1String(classInfo.value())));
314                 break;
315             }
316         }
317
318         if (meta->superClass())
319             qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass())));
320
321         QSet<const QDeclarativeType *> qmlTypes = qmlTypesByCppName.value(meta->className());
322         if (!qmlTypes.isEmpty()) {
323             QHash<QString, const QDeclarativeType *> exports;
324
325             foreach (const QDeclarativeType *qmlTy, qmlTypes) {
326                 QString qmlTyName = qmlTy->qmlTypeName();
327                 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
328                     qmlTyName.remove(0, relocatableModuleUri.size() + 1);
329                 }
330                 if (qmlTyName.startsWith("./")) {
331                     qmlTyName.remove(0, 2);
332                 }
333                 if (qmlTyName.startsWith("/")) {
334                     qmlTyName.remove(0, 1);
335                 }
336                 const QString exportString = enquote(
337                             QString("%1 %2.%3").arg(
338                                 qmlTyName,
339                                 QString::number(qmlTy->majorVersion()),
340                                 QString::number(qmlTy->minorVersion())));
341                 exports.insert(exportString, qmlTy);
342             }
343
344             // ensure exports are sorted and don't change order when the plugin is dumped again
345             QStringList exportStrings = exports.keys();
346             qSort(exportStrings);
347             qml->writeArrayBinding(QLatin1String("exports"), exportStrings);
348
349             // write meta object revisions unless they're all zero
350             QStringList metaObjectRevisions;
351             bool shouldWriteMetaObjectRevisions = false;
352             foreach (const QString &exportString, exportStrings) {
353                 int metaObjectRevision = exports[exportString]->metaObjectRevision();
354                 if (metaObjectRevision != 0)
355                     shouldWriteMetaObjectRevisions = true;
356                 metaObjectRevisions += QString::number(metaObjectRevision);
357             }
358             if (shouldWriteMetaObjectRevisions)
359                 qml->writeArrayBinding(QLatin1String("exportMetaObjectRevisions"), metaObjectRevisions);
360
361             if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
362                 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
363                                             convertToId(attachedType)));
364             }
365         }
366
367         for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
368             dump(meta->enumerator(index));
369
370         QSet<QString> implicitSignals;
371         for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index) {
372             const QMetaProperty &property = meta->property(index);
373             dump(property);
374             implicitSignals.insert(QString("%1Changed").arg(QString::fromUtf8(property.name())));
375         }
376
377         for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
378             dump(meta->method(index), implicitSignals);
379
380         qml->writeEndObject();
381     }
382
383     void dump(const ModuleApi &api)
384     {
385         qml->writeStartObject(QLatin1String("ModuleApi"));
386         if (api.uri != relocatableModuleUri)
387             qml->writeScriptBinding(QLatin1String("uri"), enquote(api.uri));
388         qml->writeScriptBinding(QLatin1String("version"), QString("%1.%2").arg(
389                                     QString::number(api.majorVersion),
390                                     QString::number(api.minorVersion)));
391         qml->writeScriptBinding(QLatin1String("name"), enquote(api.objectId));
392         qml->writeEndObject();
393     }
394
395     void writeEasingCurve()
396     {
397         qml->writeStartObject(QLatin1String("Component"));
398         qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
399         qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
400         qml->writeEndObject();
401     }
402
403 private:
404     static QString enquote(const QString &string)
405     {
406         return QString("\"%1\"").arg(string);
407     }
408
409     /* Removes pointer and list annotations from a type name, returning
410        what was removed in isList and isPointer
411     */
412     static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
413     {
414         static QByteArray declListPrefix = "QDeclarativeListProperty<";
415
416         if (typeName->endsWith('*')) {
417             *isPointer = true;
418             typeName->truncate(typeName->length() - 1);
419             removePointerAndList(typeName, isList, isPointer);
420         } else if (typeName->startsWith(declListPrefix)) {
421             *isList = true;
422             typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
423             *typeName = typeName->mid(declListPrefix.size());
424             removePointerAndList(typeName, isList, isPointer);
425         }
426
427         *typeName = convertToId(*typeName);
428     }
429
430     void writeTypeProperties(QByteArray typeName, bool isWritable)
431     {
432         bool isList = false, isPointer = false;
433         removePointerAndList(&typeName, &isList, &isPointer);
434
435         qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
436         if (isList)
437             qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
438         if (!isWritable)
439             qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
440         if (isPointer)
441             qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
442     }
443
444     void dump(const QMetaProperty &prop)
445     {
446         qml->writeStartObject("Property");
447
448         qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
449 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
450         if (int revision = prop.revision())
451             qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
452 #endif
453         writeTypeProperties(prop.typeName(), prop.isWritable());
454
455         qml->writeEndObject();
456     }
457
458     void dump(const QMetaMethod &meth, const QSet<QString> &implicitSignals)
459     {
460         if (meth.methodType() == QMetaMethod::Signal) {
461             if (meth.access() != QMetaMethod::Protected)
462                 return; // nothing to do.
463         } else if (meth.access() != QMetaMethod::Public) {
464             return; // nothing to do.
465         }
466
467         QByteArray name = meth.signature();
468         int lparenIndex = name.indexOf('(');
469         if (lparenIndex == -1) {
470             return; // invalid signature
471         }
472         name = name.left(lparenIndex);
473         const QString typeName = convertToId(meth.typeName());
474
475         if (implicitSignals.contains(name)
476                 && !meth.revision()
477                 && meth.methodType() == QMetaMethod::Signal
478                 && meth.parameterNames().isEmpty()
479                 && typeName.isEmpty()) {
480             // don't mention implicit signals
481             return;
482         }
483
484         if (meth.methodType() == QMetaMethod::Signal)
485             qml->writeStartObject(QLatin1String("Signal"));
486         else
487             qml->writeStartObject(QLatin1String("Method"));
488
489         qml->writeScriptBinding(QLatin1String("name"), enquote(name));
490
491 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
492         if (int revision = meth.revision())
493             qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
494 #endif
495
496         if (! typeName.isEmpty())
497             qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
498
499         for (int i = 0; i < meth.parameterTypes().size(); ++i) {
500             QByteArray argName = meth.parameterNames().at(i);
501
502             qml->writeStartObject(QLatin1String("Parameter"));
503             if (! argName.isEmpty())
504                 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
505             writeTypeProperties(meth.parameterTypes().at(i), true);
506             qml->writeEndObject();
507         }
508
509         qml->writeEndObject();
510     }
511
512     void dump(const QMetaEnum &e)
513     {
514         qml->writeStartObject(QLatin1String("Enum"));
515         qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
516
517         QList<QPair<QString, QString> > namesValues;
518         for (int index = 0; index < e.keyCount(); ++index) {
519             namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
520         }
521
522         qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
523         qml->writeEndObject();
524     }
525 };
526
527
528 enum ExitCode {
529     EXIT_INVALIDARGUMENTS = 1,
530     EXIT_SEGV = 2,
531     EXIT_IMPORTERROR = 3
532 };
533
534 #ifdef Q_OS_UNIX
535 void sigSegvHandler(int) {
536     fprintf(stderr, "Error: SEGV\n");
537     if (!currentProperty.isEmpty())
538         fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
539     if (!inObjectInstantiation.isEmpty())
540         fprintf(stderr, "While instantiating the object '%s'.\n", inObjectInstantiation.toLatin1().constData());
541     exit(EXIT_SEGV);
542 }
543 #endif
544
545 void printUsage(const QString &appName)
546 {
547     qWarning() << qPrintable(QString(
548                                  "Usage: %1 [-v] [-notrelocatable] module.uri version [module/import/path]\n"
549                                  "       %1 [-v] -path path/to/qmldir/directory [version]\n"
550                                  "       %1 [-v] -builtins\n"
551                                  "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
552                                  appName));
553 }
554
555 int main(int argc, char *argv[])
556 {
557 #ifdef Q_OS_UNIX
558     // qmldump may crash, but we don't want any crash handlers to pop up
559     // therefore we intercept the segfault and just exit() ourselves
560     struct sigaction sigAction;
561
562     sigemptyset(&sigAction.sa_mask);
563     sigAction.sa_handler = &sigSegvHandler;
564     sigAction.sa_flags   = 0;
565
566     sigaction(SIGSEGV, &sigAction, 0);
567 #endif
568
569 #ifdef QT_SIMULATOR
570     // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
571     QtSimulatorPrivate::SimulatorConnection::createStubInstance();
572 #endif
573     QApplication app(argc, argv);
574     const QStringList args = app.arguments();
575     const QString appName = QFileInfo(app.applicationFilePath()).baseName();
576     if (args.size() < 2) {
577         printUsage(appName);
578         return EXIT_INVALIDARGUMENTS;
579     }
580
581     QString pluginImportUri;
582     QString pluginImportVersion;
583     bool relocatable = true;
584     enum Action { Uri, Path, Builtins };
585     Action action = Uri;
586     {
587         QStringList positionalArgs;
588         foreach (const QString &arg, args) {
589             if (!arg.startsWith(QLatin1Char('-'))) {
590                 positionalArgs.append(arg);
591                 continue;
592             }
593
594             if (arg == QLatin1String("--notrelocatable")
595                     || arg == QLatin1String("-notrelocatable")) {
596                 relocatable = false;
597             } else if (arg == QLatin1String("--path")
598                        || arg == QLatin1String("-path")) {
599                 action = Path;
600             } else if (arg == QLatin1String("--builtins")
601                        || arg == QLatin1String("-builtins")) {
602                 action = Builtins;
603             } else if (arg == QLatin1String("-v")) {
604                 verbose = true;
605             } else {
606                 qWarning() << "Invalid argument: " << arg;
607                 return EXIT_INVALIDARGUMENTS;
608             }
609         }
610
611         if (action == Uri) {
612             if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
613                 qWarning() << "Incorrect number of positional arguments";
614                 return EXIT_INVALIDARGUMENTS;
615             }
616             pluginImportUri = positionalArgs[1];
617             pluginImportVersion = positionalArgs[2];
618             if (positionalArgs.size() >= 4)
619                 pluginImportPath = positionalArgs[3];
620         } else if (action == Path) {
621             if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
622                 qWarning() << "Incorrect number of positional arguments";
623                 return EXIT_INVALIDARGUMENTS;
624             }
625             pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
626             if (positionalArgs.size() == 3)
627                 pluginImportVersion = positionalArgs[2];
628         } else if (action == Builtins) {
629             if (positionalArgs.size() != 1) {
630                 qWarning() << "Incorrect number of positional arguments";
631                 return EXIT_INVALIDARGUMENTS;
632             }
633         }
634     }
635
636     QDeclarativeEngine engine;
637     if (!pluginImportPath.isEmpty()) {
638         QDir cur = QDir::current();
639         cur.cd(pluginImportPath);
640         pluginImportPath = cur.absolutePath();
641         QDir::setCurrent(pluginImportPath);
642         engine.addImportPath(pluginImportPath);
643     }
644
645     // load the QtQuick 1 plugin
646     {
647         QByteArray code("import QtQuick 1.0\nQtObject {}");
648         QDeclarativeComponent c(&engine);
649         c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/loadqtquick1.qml"));
650         c.create();
651         if (!c.errors().isEmpty()) {
652             foreach (const QDeclarativeError &error, c.errors())
653                 qWarning() << error.toString();
654             return EXIT_IMPORTERROR;
655         }
656     }
657
658     // find all QMetaObjects reachable from the builtin module
659     QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(&engine);
660     QList<QDeclarativeType *> defaultTypes = QDeclarativeMetaType::qmlTypes();
661
662     // add some otherwise unreachable QMetaObjects
663     defaultReachable.insert(&QQuickMouseEvent::staticMetaObject);
664     // QQuickKeyEvent, QQuickPinchEvent, QQuickDropEvent are not exported
665
666     // this will hold the meta objects we want to dump information of
667     QSet<const QMetaObject *> metas;
668
669     if (action == Builtins) {
670         metas = defaultReachable;
671     } else {
672         // find a valid QtQuick import
673         QByteArray importCode;
674         QDeclarativeType *qtObjectType = QDeclarativeMetaType::qmlType(&QObject::staticMetaObject);
675         if (!qtObjectType) {
676             qWarning() << "Could not find QtObject type";
677             importCode = QByteArray("import QtQuick 2.0\n");
678         } else {
679             QString module = qtObjectType->qmlTypeName();
680             module = module.mid(0, module.lastIndexOf(QLatin1Char('/')));
681             importCode = QString("import %1 %2.%3\n").arg(module,
682                                                           QString::number(qtObjectType->majorVersion()),
683                                                           QString::number(qtObjectType->minorVersion())).toUtf8();
684         }
685
686         // find all QMetaObjects reachable when the specified module is imported
687         if (action != Path) {
688             importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
689         } else {
690             // pluginImportVersion can be empty
691             importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
692         }
693
694         // create a component with these imports to make sure the imports are valid
695         // and to populate the declarative meta type system
696         {
697             QByteArray code = importCode;
698             code += "QtObject {}";
699             QDeclarativeComponent c(&engine);
700
701             c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
702             c.create();
703             if (!c.errors().isEmpty()) {
704                 foreach (const QDeclarativeError &error, c.errors())
705                     qWarning() << error.toString();
706                 return EXIT_IMPORTERROR;
707             }
708         }
709
710         QSet<const QMetaObject *> candidates = collectReachableMetaObjects(&engine, defaultTypes);
711         candidates.subtract(defaultReachable);
712
713         // Also eliminate meta objects with the same classname.
714         // This is required because extended objects seem not to share
715         // a single meta object instance.
716         QSet<QByteArray> defaultReachableNames;
717         foreach (const QMetaObject *mo, defaultReachable)
718             defaultReachableNames.insert(QByteArray(mo->className()));
719         foreach (const QMetaObject *mo, candidates) {
720             if (!defaultReachableNames.contains(mo->className()))
721                 metas.insert(mo);
722         }
723     }
724
725     // setup static rewrites of type names
726     cppToId.insert("QString", "string");
727     cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
728
729     // start dumping data
730     QByteArray bytes;
731     QmlStreamWriter qml(&bytes);
732
733     qml.writeStartDocument();
734     qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 1);
735     qml.write("\n"
736               "// This file describes the plugin-supplied types contained in the library.\n"
737               "// It is used for QML tooling purposes only.\n"
738               "\n");
739     qml.writeStartObject("Module");
740
741     // put the metaobjects into a map so they are always dumped in the same order
742     QMap<QString, const QMetaObject *> nameToMeta;
743     foreach (const QMetaObject *meta, metas)
744         nameToMeta.insert(convertToId(meta), meta);
745
746     Dumper dumper(&qml);
747     if (relocatable)
748         dumper.setRelocatableModuleUri(pluginImportUri);
749     foreach (const QMetaObject *meta, nameToMeta) {
750         dumper.dump(meta);
751     }
752
753     // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
754     // properties using the QEasingCurve type get useful type information.
755     if (pluginImportUri.isEmpty())
756         dumper.writeEasingCurve();
757
758     // write out module api elements
759     foreach (const ModuleApi &api, moduleApis) {
760         dumper.dump(api);
761     }
762
763     qml.writeEndObject();
764     qml.writeEndDocument();
765
766     std::cout << bytes.constData() << std::flush;
767
768     // workaround to avoid crashes on exit
769     QTimer timer;
770     timer.setSingleShot(true);
771     timer.setInterval(0);
772     QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));
773     timer.start();
774
775     return app.exec();
776 }