d52469a5c597a60931c6f30885f01ecc96324e7a
[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         if (meta == &QObject::staticMetaObject) {
378             // for QObject, hide deleteLater() and onDestroyed
379             for (int index = meta->methodOffset(); index < meta->methodCount(); ++index) {
380                 QMetaMethod method = meta->method(index);
381                 const char *signature(method.signature());
382                 if (signature == QLatin1String("destroyed(QObject*)")
383                         || signature == QLatin1String("destroyed()")
384                         || signature == QLatin1String("deleteLater()"))
385                     continue;
386                 dump(method, implicitSignals);
387             }
388
389             // and add toString(), destroy() and destroy(int)
390             qml->writeStartObject(QLatin1String("Method"));
391             qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("toString")));
392             qml->writeEndObject();
393             qml->writeStartObject(QLatin1String("Method"));
394             qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("destroy")));
395             qml->writeEndObject();
396             qml->writeStartObject(QLatin1String("Method"));
397             qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("destroy")));
398             qml->writeStartObject(QLatin1String("Parameter"));
399             qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("delay")));
400             qml->writeScriptBinding(QLatin1String("type"), enquote(QLatin1String("int")));
401             qml->writeEndObject();
402             qml->writeEndObject();
403         } else {
404             for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
405                 dump(meta->method(index), implicitSignals);
406         }
407
408         qml->writeEndObject();
409     }
410
411     void dump(const ModuleApi &api)
412     {
413         qml->writeStartObject(QLatin1String("ModuleApi"));
414         if (api.uri != relocatableModuleUri)
415             qml->writeScriptBinding(QLatin1String("uri"), enquote(api.uri));
416         qml->writeScriptBinding(QLatin1String("version"), QString("%1.%2").arg(
417                                     QString::number(api.majorVersion),
418                                     QString::number(api.minorVersion)));
419         qml->writeScriptBinding(QLatin1String("name"), enquote(api.objectId));
420         qml->writeEndObject();
421     }
422
423     void writeEasingCurve()
424     {
425         qml->writeStartObject(QLatin1String("Component"));
426         qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
427         qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
428         qml->writeEndObject();
429     }
430
431 private:
432     static QString enquote(const QString &string)
433     {
434         return QString("\"%1\"").arg(string);
435     }
436
437     /* Removes pointer and list annotations from a type name, returning
438        what was removed in isList and isPointer
439     */
440     static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
441     {
442         static QByteArray declListPrefix = "QDeclarativeListProperty<";
443
444         if (typeName->endsWith('*')) {
445             *isPointer = true;
446             typeName->truncate(typeName->length() - 1);
447             removePointerAndList(typeName, isList, isPointer);
448         } else if (typeName->startsWith(declListPrefix)) {
449             *isList = true;
450             typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
451             *typeName = typeName->mid(declListPrefix.size());
452             removePointerAndList(typeName, isList, isPointer);
453         }
454
455         *typeName = convertToId(*typeName);
456     }
457
458     void writeTypeProperties(QByteArray typeName, bool isWritable)
459     {
460         bool isList = false, isPointer = false;
461         removePointerAndList(&typeName, &isList, &isPointer);
462
463         qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
464         if (isList)
465             qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
466         if (!isWritable)
467             qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
468         if (isPointer)
469             qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
470     }
471
472     void dump(const QMetaProperty &prop)
473     {
474         qml->writeStartObject("Property");
475
476         qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
477 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
478         if (int revision = prop.revision())
479             qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
480 #endif
481         writeTypeProperties(prop.typeName(), prop.isWritable());
482
483         qml->writeEndObject();
484     }
485
486     void dump(const QMetaMethod &meth, const QSet<QString> &implicitSignals)
487     {
488         if (meth.methodType() == QMetaMethod::Signal) {
489             if (meth.access() != QMetaMethod::Protected)
490                 return; // nothing to do.
491         } else if (meth.access() != QMetaMethod::Public) {
492             return; // nothing to do.
493         }
494
495         QByteArray name = meth.signature();
496         int lparenIndex = name.indexOf('(');
497         if (lparenIndex == -1) {
498             return; // invalid signature
499         }
500         name = name.left(lparenIndex);
501         const QString typeName = convertToId(meth.typeName());
502
503         if (implicitSignals.contains(name)
504                 && !meth.revision()
505                 && meth.methodType() == QMetaMethod::Signal
506                 && meth.parameterNames().isEmpty()
507                 && typeName.isEmpty()) {
508             // don't mention implicit signals
509             return;
510         }
511
512         if (meth.methodType() == QMetaMethod::Signal)
513             qml->writeStartObject(QLatin1String("Signal"));
514         else
515             qml->writeStartObject(QLatin1String("Method"));
516
517         qml->writeScriptBinding(QLatin1String("name"), enquote(name));
518
519 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
520         if (int revision = meth.revision())
521             qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
522 #endif
523
524         if (! typeName.isEmpty())
525             qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
526
527         for (int i = 0; i < meth.parameterTypes().size(); ++i) {
528             QByteArray argName = meth.parameterNames().at(i);
529
530             qml->writeStartObject(QLatin1String("Parameter"));
531             if (! argName.isEmpty())
532                 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
533             writeTypeProperties(meth.parameterTypes().at(i), true);
534             qml->writeEndObject();
535         }
536
537         qml->writeEndObject();
538     }
539
540     void dump(const QMetaEnum &e)
541     {
542         qml->writeStartObject(QLatin1String("Enum"));
543         qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
544
545         QList<QPair<QString, QString> > namesValues;
546         for (int index = 0; index < e.keyCount(); ++index) {
547             namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
548         }
549
550         qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
551         qml->writeEndObject();
552     }
553 };
554
555
556 enum ExitCode {
557     EXIT_INVALIDARGUMENTS = 1,
558     EXIT_SEGV = 2,
559     EXIT_IMPORTERROR = 3
560 };
561
562 #ifdef Q_OS_UNIX
563 void sigSegvHandler(int) {
564     fprintf(stderr, "Error: SEGV\n");
565     if (!currentProperty.isEmpty())
566         fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
567     if (!inObjectInstantiation.isEmpty())
568         fprintf(stderr, "While instantiating the object '%s'.\n", inObjectInstantiation.toLatin1().constData());
569     exit(EXIT_SEGV);
570 }
571 #endif
572
573 void printUsage(const QString &appName)
574 {
575     qWarning() << qPrintable(QString(
576                                  "Usage: %1 [-v] [-notrelocatable] module.uri version [module/import/path]\n"
577                                  "       %1 [-v] -path path/to/qmldir/directory [version]\n"
578                                  "       %1 [-v] -builtins\n"
579                                  "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
580                                  appName));
581 }
582
583 int main(int argc, char *argv[])
584 {
585 #ifdef Q_OS_UNIX
586     // qmldump may crash, but we don't want any crash handlers to pop up
587     // therefore we intercept the segfault and just exit() ourselves
588     struct sigaction sigAction;
589
590     sigemptyset(&sigAction.sa_mask);
591     sigAction.sa_handler = &sigSegvHandler;
592     sigAction.sa_flags   = 0;
593
594     sigaction(SIGSEGV, &sigAction, 0);
595 #endif
596
597 #ifdef QT_SIMULATOR
598     // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
599     QtSimulatorPrivate::SimulatorConnection::createStubInstance();
600 #endif
601     QApplication app(argc, argv);
602     const QStringList args = app.arguments();
603     const QString appName = QFileInfo(app.applicationFilePath()).baseName();
604     if (args.size() < 2) {
605         printUsage(appName);
606         return EXIT_INVALIDARGUMENTS;
607     }
608
609     QString pluginImportUri;
610     QString pluginImportVersion;
611     bool relocatable = true;
612     enum Action { Uri, Path, Builtins };
613     Action action = Uri;
614     {
615         QStringList positionalArgs;
616         foreach (const QString &arg, args) {
617             if (!arg.startsWith(QLatin1Char('-'))) {
618                 positionalArgs.append(arg);
619                 continue;
620             }
621
622             if (arg == QLatin1String("--notrelocatable")
623                     || arg == QLatin1String("-notrelocatable")) {
624                 relocatable = false;
625             } else if (arg == QLatin1String("--path")
626                        || arg == QLatin1String("-path")) {
627                 action = Path;
628             } else if (arg == QLatin1String("--builtins")
629                        || arg == QLatin1String("-builtins")) {
630                 action = Builtins;
631             } else if (arg == QLatin1String("-v")) {
632                 verbose = true;
633             } else {
634                 qWarning() << "Invalid argument: " << arg;
635                 return EXIT_INVALIDARGUMENTS;
636             }
637         }
638
639         if (action == Uri) {
640             if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
641                 qWarning() << "Incorrect number of positional arguments";
642                 return EXIT_INVALIDARGUMENTS;
643             }
644             pluginImportUri = positionalArgs[1];
645             pluginImportVersion = positionalArgs[2];
646             if (positionalArgs.size() >= 4)
647                 pluginImportPath = positionalArgs[3];
648         } else if (action == Path) {
649             if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
650                 qWarning() << "Incorrect number of positional arguments";
651                 return EXIT_INVALIDARGUMENTS;
652             }
653             pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
654             if (positionalArgs.size() == 3)
655                 pluginImportVersion = positionalArgs[2];
656         } else if (action == Builtins) {
657             if (positionalArgs.size() != 1) {
658                 qWarning() << "Incorrect number of positional arguments";
659                 return EXIT_INVALIDARGUMENTS;
660             }
661         }
662     }
663
664     QDeclarativeEngine engine;
665     if (!pluginImportPath.isEmpty()) {
666         QDir cur = QDir::current();
667         cur.cd(pluginImportPath);
668         pluginImportPath = cur.absolutePath();
669         QDir::setCurrent(pluginImportPath);
670         engine.addImportPath(pluginImportPath);
671     }
672
673     // load the QtQuick 1 plugin
674     {
675         QByteArray code("import QtQuick 1.0\nQtObject {}");
676         QDeclarativeComponent c(&engine);
677         c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/loadqtquick1.qml"));
678         c.create();
679         if (!c.errors().isEmpty()) {
680             foreach (const QDeclarativeError &error, c.errors())
681                 qWarning() << error.toString();
682             return EXIT_IMPORTERROR;
683         }
684     }
685
686     // find all QMetaObjects reachable from the builtin module
687     QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(&engine);
688     QList<QDeclarativeType *> defaultTypes = QDeclarativeMetaType::qmlTypes();
689
690     // add some otherwise unreachable QMetaObjects
691     defaultReachable.insert(&QQuickMouseEvent::staticMetaObject);
692     // QQuickKeyEvent, QQuickPinchEvent, QQuickDropEvent are not exported
693
694     // this will hold the meta objects we want to dump information of
695     QSet<const QMetaObject *> metas;
696
697     if (action == Builtins) {
698         metas = defaultReachable;
699     } else {
700         // find a valid QtQuick import
701         QByteArray importCode;
702         QDeclarativeType *qtObjectType = QDeclarativeMetaType::qmlType(&QObject::staticMetaObject);
703         if (!qtObjectType) {
704             qWarning() << "Could not find QtObject type";
705             importCode = QByteArray("import QtQuick 2.0\n");
706         } else {
707             QString module = qtObjectType->qmlTypeName();
708             module = module.mid(0, module.lastIndexOf(QLatin1Char('/')));
709             importCode = QString("import %1 %2.%3\n").arg(module,
710                                                           QString::number(qtObjectType->majorVersion()),
711                                                           QString::number(qtObjectType->minorVersion())).toUtf8();
712         }
713
714         // find all QMetaObjects reachable when the specified module is imported
715         if (action != Path) {
716             importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
717         } else {
718             // pluginImportVersion can be empty
719             importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
720         }
721
722         // create a component with these imports to make sure the imports are valid
723         // and to populate the declarative meta type system
724         {
725             QByteArray code = importCode;
726             code += "QtObject {}";
727             QDeclarativeComponent c(&engine);
728
729             c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
730             c.create();
731             if (!c.errors().isEmpty()) {
732                 foreach (const QDeclarativeError &error, c.errors())
733                     qWarning() << error.toString();
734                 return EXIT_IMPORTERROR;
735             }
736         }
737
738         QSet<const QMetaObject *> candidates = collectReachableMetaObjects(&engine, defaultTypes);
739         candidates.subtract(defaultReachable);
740
741         // Also eliminate meta objects with the same classname.
742         // This is required because extended objects seem not to share
743         // a single meta object instance.
744         QSet<QByteArray> defaultReachableNames;
745         foreach (const QMetaObject *mo, defaultReachable)
746             defaultReachableNames.insert(QByteArray(mo->className()));
747         foreach (const QMetaObject *mo, candidates) {
748             if (!defaultReachableNames.contains(mo->className()))
749                 metas.insert(mo);
750         }
751     }
752
753     // setup static rewrites of type names
754     cppToId.insert("QString", "string");
755     cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
756
757     // start dumping data
758     QByteArray bytes;
759     QmlStreamWriter qml(&bytes);
760
761     qml.writeStartDocument();
762     qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 1);
763     qml.write("\n"
764               "// This file describes the plugin-supplied types contained in the library.\n"
765               "// It is used for QML tooling purposes only.\n"
766               "\n");
767     qml.writeStartObject("Module");
768
769     // put the metaobjects into a map so they are always dumped in the same order
770     QMap<QString, const QMetaObject *> nameToMeta;
771     foreach (const QMetaObject *meta, metas)
772         nameToMeta.insert(convertToId(meta), meta);
773
774     Dumper dumper(&qml);
775     if (relocatable)
776         dumper.setRelocatableModuleUri(pluginImportUri);
777     foreach (const QMetaObject *meta, nameToMeta) {
778         dumper.dump(meta);
779     }
780
781     // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
782     // properties using the QEasingCurve type get useful type information.
783     if (pluginImportUri.isEmpty())
784         dumper.writeEasingCurve();
785
786     // write out module api elements
787     foreach (const ModuleApi &api, moduleApis) {
788         dumper.dump(api);
789     }
790
791     qml.writeEndObject();
792     qml.writeEndDocument();
793
794     std::cout << bytes.constData() << std::flush;
795
796     // workaround to avoid crashes on exit
797     QTimer timer;
798     timer.setSingleShot(true);
799     timer.setInterval(0);
800     QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));
801     timer.start();
802
803     return app.exec();
804 }