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