Adapt to Qt5 meta-object changes
[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 /* All exported module APIs are collected into this list */
181 class ModuleApi {
182 public:
183     QString uri;
184     int majorVersion;
185     int minorVersion;
186     QByteArray objectId;
187 };
188 QList<ModuleApi> moduleApis;
189
190 QSet<const QMetaObject *> collectReachableMetaObjects(QQmlEngine *engine, const QList<QQmlType *> &skip = QList<QQmlType *>())
191 {
192     QSet<const QMetaObject *> metas;
193     metas.insert(FriendlyQObject::qtMeta());
194
195     QHash<QByteArray, QSet<QByteArray> > extensions;
196     foreach (const QQmlType *ty, QQmlMetaType::qmlTypes()) {
197         qmlTypesByCppName[ty->metaObject()->className()].insert(ty);
198         if (ty->isExtendedType()) {
199             extensions[ty->typeName()].insert(ty->metaObject()->className());
200         }
201         collectReachableMetaObjects(ty, &metas);
202     }
203
204     // Adjust exports of the base object if there are extensions.
205     // For each export of a base object there can be a single extension object overriding it.
206     // Example: QDeclarativeGraphicsWidget overrides the QtQuick/QGraphicsWidget export
207     //          of QGraphicsWidget.
208     foreach (const QByteArray &baseCpp, extensions.keys()) {
209         QSet<const QQmlType *> baseExports = qmlTypesByCppName.value(baseCpp);
210
211         const QSet<QByteArray> extensionCppNames = extensions.value(baseCpp);
212         foreach (const QByteArray &extensionCppName, extensionCppNames) {
213             const QSet<const QQmlType *> extensionExports = qmlTypesByCppName.value(extensionCppName);
214
215             // remove extension exports from base imports
216             // unfortunately the QQmlType pointers don't match, so can't use QSet::substract
217             QSet<const QQmlType *> newBaseExports;
218             foreach (const QQmlType *baseExport, baseExports) {
219                 bool match = false;
220                 foreach (const QQmlType *extensionExport, extensionExports) {
221                     if (baseExport->qmlTypeName() == extensionExport->qmlTypeName()
222                             && baseExport->majorVersion() == extensionExport->majorVersion()
223                             && baseExport->minorVersion() == extensionExport->minorVersion()) {
224                         match = true;
225                         break;
226                     }
227                 }
228                 if (!match)
229                     newBaseExports.insert(baseExport);
230             }
231             baseExports = newBaseExports;
232         }
233         qmlTypesByCppName[baseCpp] = baseExports;
234     }
235
236     // find even more QMetaObjects by instantiating QML types and running
237     // over the instances
238     foreach (QQmlType *ty, QQmlMetaType::qmlTypes()) {
239         if (skip.contains(ty))
240             continue;
241         if (ty->isExtendedType())
242             continue;
243         if (!ty->isCreatable())
244             continue;
245         if (ty->typeName() == "QQmlComponent")
246             continue;
247
248         QString tyName = ty->qmlTypeName();
249         tyName = tyName.mid(tyName.lastIndexOf(QLatin1Char('/')) + 1);
250         if (tyName.isEmpty())
251             continue;
252
253         inObjectInstantiation = tyName;
254         QObject *object = ty->create();
255         inObjectInstantiation.clear();
256
257         if (object)
258             collectReachableMetaObjects(object, &metas);
259         else
260             qWarning() << "Could not create" << tyName;
261     }
262
263     // extract exported module api
264     QHashIterator<QString, QList<QQmlMetaType::ModuleApi> > moduleApiIt(QQmlMetaType::moduleApis());
265     while (moduleApiIt.hasNext()) {
266         moduleApiIt.next();
267         foreach (const QQmlMetaType::ModuleApi &api, moduleApiIt.value()) {
268             ModuleApi moduleApi;
269             moduleApi.uri = moduleApiIt.key();
270             moduleApi.majorVersion = api.major;
271             moduleApi.minorVersion = api.minor;
272
273             if (api.qobject) {
274                 if (QObject *object = (*api.qobject)(engine, engine)) {
275                     collectReachableMetaObjects(object, &metas);
276                     moduleApi.objectId = convertToId(object->metaObject()->className());
277                     delete object;
278                 }
279             } else if (api.script) {
280                 qWarning() << "Can't dump the module api in " << moduleApi.uri << ". QJSValue based module API is not supported.";
281 //                QJSValue value = (*api.script)(engine, engine);
282 //                IdToObjectHash jsObjects;
283 //                collectReachableJSObjects(value, &jsObjects, &metas);
284             }
285
286             moduleApis += moduleApi;
287         }
288     }
289
290     return metas;
291 }
292
293
294 class Dumper
295 {
296     QmlStreamWriter *qml;
297     QString relocatableModuleUri;
298
299 public:
300     Dumper(QmlStreamWriter *qml) : qml(qml) {}
301
302     void setRelocatableModuleUri(const QString &uri)
303     {
304         relocatableModuleUri = uri;
305     }
306
307     void dump(const QMetaObject *meta)
308     {
309         qml->writeStartObject("Component");
310
311         QByteArray id = convertToId(meta);
312         qml->writeScriptBinding(QLatin1String("name"), enquote(id));
313
314         for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
315             QMetaClassInfo classInfo = meta->classInfo(index);
316             if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
317                 qml->writeScriptBinding(QLatin1String("defaultProperty"), enquote(QLatin1String(classInfo.value())));
318                 break;
319             }
320         }
321
322         if (meta->superClass())
323             qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass())));
324
325         QSet<const QQmlType *> qmlTypes = qmlTypesByCppName.value(meta->className());
326         if (!qmlTypes.isEmpty()) {
327             QHash<QString, const QQmlType *> exports;
328
329             foreach (const QQmlType *qmlTy, qmlTypes) {
330                 QString qmlTyName = qmlTy->qmlTypeName();
331                 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
332                     qmlTyName.remove(0, relocatableModuleUri.size() + 1);
333                 }
334                 if (qmlTyName.startsWith("./")) {
335                     qmlTyName.remove(0, 2);
336                 }
337                 if (qmlTyName.startsWith("/")) {
338                     qmlTyName.remove(0, 1);
339                 }
340                 const QString exportString = enquote(
341                             QString("%1 %2.%3").arg(
342                                 qmlTyName,
343                                 QString::number(qmlTy->majorVersion()),
344                                 QString::number(qmlTy->minorVersion())));
345                 exports.insert(exportString, qmlTy);
346             }
347
348             // ensure exports are sorted and don't change order when the plugin is dumped again
349             QStringList exportStrings = exports.keys();
350             qSort(exportStrings);
351             qml->writeArrayBinding(QLatin1String("exports"), exportStrings);
352
353             // write meta object revisions unless they're all zero
354             QStringList metaObjectRevisions;
355             bool shouldWriteMetaObjectRevisions = false;
356             foreach (const QString &exportString, exportStrings) {
357                 int metaObjectRevision = exports[exportString]->metaObjectRevision();
358                 if (metaObjectRevision != 0)
359                     shouldWriteMetaObjectRevisions = true;
360                 metaObjectRevisions += QString::number(metaObjectRevision);
361             }
362             if (shouldWriteMetaObjectRevisions)
363                 qml->writeArrayBinding(QLatin1String("exportMetaObjectRevisions"), metaObjectRevisions);
364
365             if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
366                 // Can happen when a type is registered that returns itself as attachedPropertiesType()
367                 // because there is no creatable type to attach to.
368                 if (attachedType != meta) {
369                     qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
370                                                 convertToId(attachedType)));
371                 }
372             }
373         }
374
375         for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
376             dump(meta->enumerator(index));
377
378         QSet<QString> implicitSignals;
379         for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index) {
380             const QMetaProperty &property = meta->property(index);
381             dump(property);
382             implicitSignals.insert(QString("%1Changed").arg(QString::fromUtf8(property.name())));
383         }
384
385         if (meta == &QObject::staticMetaObject) {
386             // for QObject, hide deleteLater() and onDestroyed
387             for (int index = meta->methodOffset(); index < meta->methodCount(); ++index) {
388                 QMetaMethod method = meta->method(index);
389                 QByteArray signature = method.methodSignature();
390                 if (signature == QByteArrayLiteral("destroyed(QObject*)")
391                         || signature == QByteArrayLiteral("destroyed()")
392                         || signature == QByteArrayLiteral("deleteLater()"))
393                     continue;
394                 dump(method, implicitSignals);
395             }
396
397             // and add toString(), destroy() and destroy(int)
398             qml->writeStartObject(QLatin1String("Method"));
399             qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("toString")));
400             qml->writeEndObject();
401             qml->writeStartObject(QLatin1String("Method"));
402             qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("destroy")));
403             qml->writeEndObject();
404             qml->writeStartObject(QLatin1String("Method"));
405             qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("destroy")));
406             qml->writeStartObject(QLatin1String("Parameter"));
407             qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("delay")));
408             qml->writeScriptBinding(QLatin1String("type"), enquote(QLatin1String("int")));
409             qml->writeEndObject();
410             qml->writeEndObject();
411         } else {
412             for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
413                 dump(meta->method(index), implicitSignals);
414         }
415
416         qml->writeEndObject();
417     }
418
419     void dump(const ModuleApi &api)
420     {
421         qml->writeStartObject(QLatin1String("ModuleApi"));
422         if (api.uri != relocatableModuleUri)
423             qml->writeScriptBinding(QLatin1String("uri"), enquote(api.uri));
424         qml->writeScriptBinding(QLatin1String("version"), QString("%1.%2").arg(
425                                     QString::number(api.majorVersion),
426                                     QString::number(api.minorVersion)));
427         qml->writeScriptBinding(QLatin1String("name"), enquote(api.objectId));
428         qml->writeEndObject();
429     }
430
431     void writeEasingCurve()
432     {
433         qml->writeStartObject(QLatin1String("Component"));
434         qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
435         qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QQmlEasingValueType")));
436         qml->writeEndObject();
437     }
438
439 private:
440     static QString enquote(const QString &string)
441     {
442         return QString("\"%1\"").arg(string);
443     }
444
445     /* Removes pointer and list annotations from a type name, returning
446        what was removed in isList and isPointer
447     */
448     static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
449     {
450         static QByteArray declListPrefix = "QQmlListProperty<";
451
452         if (typeName->endsWith('*')) {
453             *isPointer = true;
454             typeName->truncate(typeName->length() - 1);
455             removePointerAndList(typeName, isList, isPointer);
456         } else if (typeName->startsWith(declListPrefix)) {
457             *isList = true;
458             typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
459             *typeName = typeName->mid(declListPrefix.size());
460             removePointerAndList(typeName, isList, isPointer);
461         }
462
463         *typeName = convertToId(*typeName);
464     }
465
466     void writeTypeProperties(QByteArray typeName, bool isWritable)
467     {
468         bool isList = false, isPointer = false;
469         removePointerAndList(&typeName, &isList, &isPointer);
470
471         qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
472         if (isList)
473             qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
474         if (!isWritable)
475             qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
476         if (isPointer)
477             qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
478     }
479
480     void dump(const QMetaProperty &prop)
481     {
482         qml->writeStartObject("Property");
483
484         qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
485 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
486         if (int revision = prop.revision())
487             qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
488 #endif
489         writeTypeProperties(prop.typeName(), prop.isWritable());
490
491         qml->writeEndObject();
492     }
493
494     void dump(const QMetaMethod &meth, const QSet<QString> &implicitSignals)
495     {
496         if (meth.methodType() == QMetaMethod::Signal) {
497             if (meth.access() != QMetaMethod::Protected)
498                 return; // nothing to do.
499         } else if (meth.access() != QMetaMethod::Public) {
500             return; // nothing to do.
501         }
502
503         QByteArray name = meth.name();
504         const QString typeName = convertToId(meth.typeName());
505
506         if (implicitSignals.contains(name)
507                 && !meth.revision()
508                 && meth.methodType() == QMetaMethod::Signal
509                 && meth.parameterNames().isEmpty()
510                 && typeName.isEmpty()) {
511             // don't mention implicit signals
512             return;
513         }
514
515         if (meth.methodType() == QMetaMethod::Signal)
516             qml->writeStartObject(QLatin1String("Signal"));
517         else
518             qml->writeStartObject(QLatin1String("Method"));
519
520         qml->writeScriptBinding(QLatin1String("name"), enquote(name));
521
522 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
523         if (int revision = meth.revision())
524             qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
525 #endif
526
527         if (! typeName.isEmpty())
528             qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
529
530         for (int i = 0; i < meth.parameterTypes().size(); ++i) {
531             QByteArray argName = meth.parameterNames().at(i);
532
533             qml->writeStartObject(QLatin1String("Parameter"));
534             if (! argName.isEmpty())
535                 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
536             writeTypeProperties(meth.parameterTypes().at(i), true);
537             qml->writeEndObject();
538         }
539
540         qml->writeEndObject();
541     }
542
543     void dump(const QMetaEnum &e)
544     {
545         qml->writeStartObject(QLatin1String("Enum"));
546         qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
547
548         QList<QPair<QString, QString> > namesValues;
549         for (int index = 0; index < e.keyCount(); ++index) {
550             namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
551         }
552
553         qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
554         qml->writeEndObject();
555     }
556 };
557
558
559 enum ExitCode {
560     EXIT_INVALIDARGUMENTS = 1,
561     EXIT_SEGV = 2,
562     EXIT_IMPORTERROR = 3
563 };
564
565 #ifdef Q_OS_UNIX
566 void sigSegvHandler(int) {
567     fprintf(stderr, "Error: SEGV\n");
568     if (!currentProperty.isEmpty())
569         fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
570     if (!inObjectInstantiation.isEmpty())
571         fprintf(stderr, "While instantiating the object '%s'.\n", inObjectInstantiation.toLatin1().constData());
572     exit(EXIT_SEGV);
573 }
574 #endif
575
576 void printUsage(const QString &appName)
577 {
578     qWarning() << qPrintable(QString(
579                                  "Usage: %1 [-v] [-notrelocatable] module.uri version [module/import/path]\n"
580                                  "       %1 [-v] -path path/to/qmldir/directory [version]\n"
581                                  "       %1 [-v] -builtins\n"
582                                  "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
583                                  appName));
584 }
585
586 int main(int argc, char *argv[])
587 {
588 #ifdef Q_OS_UNIX
589     // qmldump may crash, but we don't want any crash handlers to pop up
590     // therefore we intercept the segfault and just exit() ourselves
591     struct sigaction sigAction;
592
593     sigemptyset(&sigAction.sa_mask);
594     sigAction.sa_handler = &sigSegvHandler;
595     sigAction.sa_flags   = 0;
596
597     sigaction(SIGSEGV, &sigAction, 0);
598 #endif
599
600 #ifdef QT_SIMULATOR
601     // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
602     QtSimulatorPrivate::SimulatorConnection::createStubInstance();
603 #endif
604
605     QGuiApplication app(argc, argv);
606     const QStringList args = app.arguments();
607     const QString appName = QFileInfo(app.applicationFilePath()).baseName();
608     if (args.size() < 2) {
609         printUsage(appName);
610         return EXIT_INVALIDARGUMENTS;
611     }
612
613     QString pluginImportUri;
614     QString pluginImportVersion;
615     bool relocatable = true;
616     enum Action { Uri, Path, Builtins };
617     Action action = Uri;
618     {
619         QStringList positionalArgs;
620         foreach (const QString &arg, args) {
621             if (!arg.startsWith(QLatin1Char('-'))) {
622                 positionalArgs.append(arg);
623                 continue;
624             }
625
626             if (arg == QLatin1String("--notrelocatable")
627                     || arg == QLatin1String("-notrelocatable")) {
628                 relocatable = false;
629             } else if (arg == QLatin1String("--path")
630                        || arg == QLatin1String("-path")) {
631                 action = Path;
632             } else if (arg == QLatin1String("--builtins")
633                        || arg == QLatin1String("-builtins")) {
634                 action = Builtins;
635             } else if (arg == QLatin1String("-v")) {
636                 verbose = true;
637             } else {
638                 qWarning() << "Invalid argument: " << arg;
639                 return EXIT_INVALIDARGUMENTS;
640             }
641         }
642
643         if (action == Uri) {
644             if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
645                 qWarning() << "Incorrect number of positional arguments";
646                 return EXIT_INVALIDARGUMENTS;
647             }
648             pluginImportUri = positionalArgs[1];
649             pluginImportVersion = positionalArgs[2];
650             if (positionalArgs.size() >= 4)
651                 pluginImportPath = positionalArgs[3];
652         } else if (action == Path) {
653             if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
654                 qWarning() << "Incorrect number of positional arguments";
655                 return EXIT_INVALIDARGUMENTS;
656             }
657             pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
658             if (positionalArgs.size() == 3)
659                 pluginImportVersion = positionalArgs[2];
660         } else if (action == Builtins) {
661             if (positionalArgs.size() != 1) {
662                 qWarning() << "Incorrect number of positional arguments";
663                 return EXIT_INVALIDARGUMENTS;
664             }
665         }
666     }
667
668     QQmlEngine engine;
669     if (!pluginImportPath.isEmpty()) {
670         QDir cur = QDir::current();
671         cur.cd(pluginImportPath);
672         pluginImportPath = cur.absolutePath();
673         QDir::setCurrent(pluginImportPath);
674         engine.addImportPath(pluginImportPath);
675     }
676
677     // load the QtQuick 2 plugin
678     {
679         QByteArray code("import QtQuick 2.0\nQtObject {}");
680         QQmlComponent c(&engine);
681         c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/loadqtquick2.qml"));
682         c.create();
683         if (!c.errors().isEmpty()) {
684             foreach (const QQmlError &error, c.errors())
685                 qWarning() << error.toString();
686             return EXIT_IMPORTERROR;
687         }
688     }
689
690     // find all QMetaObjects reachable from the builtin module
691     QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(&engine);
692     QList<QQmlType *> defaultTypes = QQmlMetaType::qmlTypes();
693
694     // add some otherwise unreachable QMetaObjects
695     defaultReachable.insert(&QQuickMouseEvent::staticMetaObject);
696     // QQuickKeyEvent, QQuickPinchEvent, QQuickDropEvent are not exported
697
698     // this will hold the meta objects we want to dump information of
699     QSet<const QMetaObject *> metas;
700
701     if (action == Builtins) {
702         metas = defaultReachable;
703     } else {
704         // find a valid QtQuick import
705         QByteArray importCode;
706         QQmlType *qtObjectType = QQmlMetaType::qmlType(&QObject::staticMetaObject);
707         if (!qtObjectType) {
708             qWarning() << "Could not find QtObject type";
709             importCode = QByteArray("import QtQuick 2.0\n");
710         } else {
711             QString module = qtObjectType->qmlTypeName();
712             module = module.mid(0, module.lastIndexOf(QLatin1Char('/')));
713             importCode = QString("import %1 %2.%3\n").arg(module,
714                                                           QString::number(qtObjectType->majorVersion()),
715                                                           QString::number(qtObjectType->minorVersion())).toUtf8();
716         }
717
718         // find all QMetaObjects reachable when the specified module is imported
719         if (action != Path) {
720             importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
721         } else {
722             // pluginImportVersion can be empty
723             importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
724         }
725
726         // create a component with these imports to make sure the imports are valid
727         // and to populate the declarative meta type system
728         {
729             QByteArray code = importCode;
730             code += "QtObject {}";
731             QQmlComponent c(&engine);
732
733             c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
734             c.create();
735             if (!c.errors().isEmpty()) {
736                 foreach (const QQmlError &error, c.errors())
737                     qWarning() << error.toString();
738                 return EXIT_IMPORTERROR;
739             }
740         }
741
742         QSet<const QMetaObject *> candidates = collectReachableMetaObjects(&engine, defaultTypes);
743         candidates.subtract(defaultReachable);
744
745         // Also eliminate meta objects with the same classname.
746         // This is required because extended objects seem not to share
747         // a single meta object instance.
748         QSet<QByteArray> defaultReachableNames;
749         foreach (const QMetaObject *mo, defaultReachable)
750             defaultReachableNames.insert(QByteArray(mo->className()));
751         foreach (const QMetaObject *mo, candidates) {
752             if (!defaultReachableNames.contains(mo->className()))
753                 metas.insert(mo);
754         }
755     }
756
757     // setup static rewrites of type names
758     cppToId.insert("QString", "string");
759     cppToId.insert("QQmlEasingValueType::Type", "Type");
760
761     // start dumping data
762     QByteArray bytes;
763     QmlStreamWriter qml(&bytes);
764
765     qml.writeStartDocument();
766     qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 1);
767     qml.write("\n"
768               "// This file describes the plugin-supplied types contained in the library.\n"
769               "// It is used for QML tooling purposes only.\n"
770               "\n");
771     qml.writeStartObject("Module");
772
773     // put the metaobjects into a map so they are always dumped in the same order
774     QMap<QString, const QMetaObject *> nameToMeta;
775     foreach (const QMetaObject *meta, metas)
776         nameToMeta.insert(convertToId(meta), meta);
777
778     Dumper dumper(&qml);
779     if (relocatable)
780         dumper.setRelocatableModuleUri(pluginImportUri);
781     foreach (const QMetaObject *meta, nameToMeta) {
782         dumper.dump(meta);
783     }
784
785     // define QEasingCurve as an extension of QQmlEasingValueType, this way
786     // properties using the QEasingCurve type get useful type information.
787     if (pluginImportUri.isEmpty())
788         dumper.writeEasingCurve();
789
790     // write out module api elements
791     foreach (const ModuleApi &api, moduleApis) {
792         dumper.dump(api);
793     }
794
795     qml.writeEndObject();
796     qml.writeEndDocument();
797
798     std::cout << bytes.constData() << std::flush;
799
800     // workaround to avoid crashes on exit
801     QTimer timer;
802     timer.setSingleShot(true);
803     timer.setInterval(0);
804     QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));
805     timer.start();
806
807     return app.exec();
808 }