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