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