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