qmlplugindump: Dump revision property.
[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 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
14 ** this package.
15 **
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file.  Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23 **
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights.  These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27 **
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
30 **
31 **
32 **
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/QDeclarativeView>
46
47 #include <QtGui/QApplication>
48
49 #include <QtCore/QSet>
50 #include <QtCore/QMetaObject>
51 #include <QtCore/QMetaProperty>
52 #include <QtCore/QDebug>
53 #include <QtCore/private/qobject_p.h>
54 #include <QtCore/private/qmetaobject_p.h>
55
56 #include <iostream>
57
58 #include "qmlstreamwriter.h"
59
60 #ifdef QT_SIMULATOR
61 #include <QtGui/private/qsimulatorconnection_p.h>
62 #endif
63
64 #ifdef Q_OS_UNIX
65 #include <signal.h>
66 #endif
67
68 QString pluginImportPath;
69
70 void collectReachableMetaObjects(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
71 {
72     if (! meta || metas->contains(meta))
73         return;
74
75     // dynamic meta objects break things badly, so just ignore them
76     const QMetaObjectPrivate *mop = reinterpret_cast<const QMetaObjectPrivate *>(meta->d.data);
77     if (!(mop->flags & DynamicMetaObject))
78         metas->insert(meta);
79
80     collectReachableMetaObjects(meta->superClass(), metas);
81 }
82
83 QString currentProperty;
84
85 void collectReachableMetaObjects(QObject *object, QSet<const QMetaObject *> *metas)
86 {
87     if (! object)
88         return;
89
90     const QMetaObject *meta = object->metaObject();
91     qDebug() << "Processing object" << meta->className();
92     collectReachableMetaObjects(meta, metas);
93
94     for (int index = 0; index < meta->propertyCount(); ++index) {
95         QMetaProperty prop = meta->property(index);
96         if (QDeclarativeMetaType::isQObject(prop.userType())) {
97             qDebug() << "  Processing property" << prop.name();
98             currentProperty = QString("%1::%2").arg(meta->className(), prop.name());
99
100             // if the property was not initialized during construction,
101             // accessing a member of oo is going to cause a segmentation fault
102             QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
103             if (oo && !metas->contains(oo->metaObject()))
104                 collectReachableMetaObjects(oo, metas);
105             currentProperty.clear();
106         }
107     }
108 }
109
110 void collectReachableMetaObjects(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
111 {
112     collectReachableMetaObjects(ty->metaObject(), metas);
113     if (ty->attachedPropertiesType())
114         collectReachableMetaObjects(ty->attachedPropertiesType(), metas);
115 }
116
117 /* We want to add the MetaObject for 'Qt' to the list, this is a
118    simple way to access it.
119 */
120 class FriendlyQObject: public QObject
121 {
122 public:
123     static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
124 };
125
126 /* When we dump a QMetaObject, we want to list all the types it is exported as.
127    To do this, we need to find the QDeclarativeTypes associated with this
128    QMetaObject.
129 */
130 static QHash<QByteArray, QSet<const QDeclarativeType *> > qmlTypesByCppName;
131
132 static QHash<QByteArray, QByteArray> cppToId;
133
134 /* Takes a C++ type name, such as Qt::LayoutDirection or QString and
135    maps it to how it should appear in the description file.
136
137    These names need to be unique globally, so we don't change the C++ symbol's
138    name much. It is mostly used to for explicit translations such as
139    QString->string and translations for extended QML objects.
140 */
141 QByteArray convertToId(const QByteArray &cppName)
142 {
143     return cppToId.value(cppName, cppName);
144 }
145
146 QSet<const QMetaObject *> collectReachableMetaObjects(const QString &importCode, QDeclarativeEngine *engine)
147 {
148     QSet<const QMetaObject *> metas;
149     metas.insert(FriendlyQObject::qtMeta());
150
151     QHash<QByteArray, QSet<QByteArray> > extensions;
152     foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
153         qmlTypesByCppName[ty->metaObject()->className()].insert(ty);
154         if (ty->isExtendedType()) {
155             extensions[ty->typeName()].insert(ty->metaObject()->className());
156         }
157         collectReachableMetaObjects(ty, &metas);
158     }
159
160     // Adjust ids of extended objects.
161     // The chain ends up being:
162     // __extended__.originalname - the base object
163     // __extension_0_.originalname - first extension
164     // ..
165     // __extension_n-2_.originalname - second to last extension
166     // originalname - last extension
167     // ### does this actually work for multiple extensions? it seems like the prototypes might be wrong
168     foreach (const QByteArray &extendedCpp, extensions.keys()) {
169         cppToId.remove(extendedCpp);
170         const QByteArray extendedId = convertToId(extendedCpp);
171         cppToId.insert(extendedCpp, "__extended__." + extendedId);
172         QSet<QByteArray> extensionCppNames = extensions.value(extendedCpp);
173         int c = 0;
174         foreach (const QByteArray &extensionCppName, extensionCppNames) {
175             if (c != extensionCppNames.size() - 1) {
176                 QByteArray adjustedName = QString("__extension__%1.%2").arg(QString::number(c), QString(extendedId)).toAscii();
177                 cppToId.insert(extensionCppName, adjustedName);
178             } else {
179                 cppToId.insert(extensionCppName, extendedId);
180             }
181             ++c;
182         }
183     }
184
185     // find even more QMetaObjects by instantiating QML types and running
186     // over the instances
187     foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
188         if (ty->isExtendedType())
189             continue;
190
191         QByteArray tyName = ty->qmlTypeName();
192         tyName = tyName.mid(tyName.lastIndexOf('/') + 1);
193
194         QByteArray code = importCode.toUtf8();
195         code += tyName;
196         code += " {}\n";
197
198         QDeclarativeComponent c(engine);
199         c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typeinstance.qml"));
200
201         QObject *object = c.create();
202         if (object)
203             collectReachableMetaObjects(object, &metas);
204         else
205             qDebug() << "Could not create" << tyName << ":" << c.errorString();
206     }
207
208     return metas;
209 }
210
211
212 class Dumper
213 {
214     QmlStreamWriter *qml;
215     QString relocatableModuleUri;
216
217 public:
218     Dumper(QmlStreamWriter *qml) : qml(qml) {}
219
220     void setRelocatableModuleUri(const QString &uri)
221     {
222         relocatableModuleUri = uri;
223     }
224
225     void dump(const QMetaObject *meta)
226     {
227         qml->writeStartObject("Component");
228
229         QByteArray id = convertToId(meta->className());
230         qml->writeScriptBinding(QLatin1String("name"), enquote(id));
231
232         for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
233             QMetaClassInfo classInfo = meta->classInfo(index);
234             if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
235                 qml->writeScriptBinding(QLatin1String("defaultProperty"), enquote(QLatin1String(classInfo.value())));
236                 break;
237             }
238         }
239
240         if (meta->superClass())
241             qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass()->className())));
242
243         QSet<const QDeclarativeType *> qmlTypes = qmlTypesByCppName.value(meta->className());
244         if (!qmlTypes.isEmpty()) {
245             QStringList exports;
246
247             foreach (const QDeclarativeType *qmlTy, qmlTypes) {
248                 QString qmlTyName = qmlTy->qmlTypeName();
249                 // some qmltype names are missing the actual names, ignore that import
250                 if (qmlTyName.endsWith('/'))
251                     continue;
252                 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
253                     qmlTyName.remove(0, relocatableModuleUri.size() + 1);
254                 }
255                 exports += enquote(QString("%1 %2.%3").arg(
256                                        qmlTyName,
257                                        QString::number(qmlTy->majorVersion()),
258                                        QString::number(qmlTy->minorVersion())));
259             }
260
261             // ensure exports are sorted and don't change order when the plugin is dumped again
262             exports.removeDuplicates();
263             qSort(exports);
264
265             qml->writeArrayBinding(QLatin1String("exports"), exports);
266
267             if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
268                 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
269                                             convertToId(attachedType->className())));
270             }
271         }
272
273         for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
274             dump(meta->enumerator(index));
275
276         for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
277             dump(meta->property(index));
278
279         for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
280             dump(meta->method(index));
281
282         qml->writeEndObject();
283     }
284
285     void writeEasingCurve()
286     {
287         qml->writeStartObject("Component");
288         qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
289         qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
290         qml->writeEndObject();
291     }
292
293 private:
294     static QString enquote(const QString &string)
295     {
296         return QString("\"%1\"").arg(string);
297     }
298
299     /* Removes pointer and list annotations from a type name, returning
300        what was removed in isList and isPointer
301     */
302     static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
303     {
304         static QByteArray declListPrefix = "QDeclarativeListProperty<";
305
306         if (typeName->endsWith('*')) {
307             *isPointer = true;
308             typeName->truncate(typeName->length() - 1);
309             removePointerAndList(typeName, isList, isPointer);
310         } else if (typeName->startsWith(declListPrefix)) {
311             *isList = true;
312             typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
313             *typeName = typeName->mid(declListPrefix.size());
314             removePointerAndList(typeName, isList, isPointer);
315         }
316
317         *typeName = convertToId(*typeName);
318     }
319
320     void writeTypeProperties(QByteArray typeName, bool isWritable)
321     {
322         bool isList = false, isPointer = false;
323         removePointerAndList(&typeName, &isList, &isPointer);
324
325         qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
326         if (isList)
327             qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
328         if (!isWritable)
329             qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
330         if (isPointer)
331             qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
332     }
333
334     void dump(const QMetaProperty &prop)
335     {
336         qml->writeStartObject("Property");
337
338         qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
339 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
340         if (int revision = prop.revision())
341             qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
342 #endif
343         writeTypeProperties(prop.typeName(), prop.isWritable());
344
345         qml->writeEndObject();
346     }
347
348     void dump(const QMetaMethod &meth)
349     {
350         if (meth.methodType() == QMetaMethod::Signal) {
351             if (meth.access() != QMetaMethod::Protected)
352                 return; // nothing to do.
353         } else if (meth.access() != QMetaMethod::Public) {
354             return; // nothing to do.
355         }
356
357         QByteArray name = meth.signature();
358         int lparenIndex = name.indexOf('(');
359         if (lparenIndex == -1) {
360             return; // invalid signature
361         }
362         name = name.left(lparenIndex);
363
364         if (meth.methodType() == QMetaMethod::Signal)
365             qml->writeStartObject(QLatin1String("Signal"));
366         else
367             qml->writeStartObject(QLatin1String("Method"));
368
369         qml->writeScriptBinding(QLatin1String("name"), enquote(name));
370
371 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
372         if (int revision = meth.revision())
373             qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
374 #endif
375
376         const QString typeName = convertToId(meth.typeName());
377         if (! typeName.isEmpty())
378             qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
379
380         for (int i = 0; i < meth.parameterTypes().size(); ++i) {
381             QByteArray argName = meth.parameterNames().at(i);
382
383             qml->writeStartObject(QLatin1String("Parameter"));
384             if (! argName.isEmpty())
385                 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
386             writeTypeProperties(meth.parameterTypes().at(i), true);
387             qml->writeEndObject();
388         }
389
390         qml->writeEndObject();
391     }
392
393     void dump(const QMetaEnum &e)
394     {
395         qml->writeStartObject(QLatin1String("Enum"));
396         qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
397
398         QList<QPair<QString, QString> > namesValues;
399         for (int index = 0; index < e.keyCount(); ++index) {
400             namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
401         }
402
403         qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
404         qml->writeEndObject();
405     }
406 };
407
408
409 enum ExitCode {
410     EXIT_INVALIDARGUMENTS = 1,
411     EXIT_SEGV = 2,
412     EXIT_IMPORTERROR = 3
413 };
414
415 #ifdef Q_OS_UNIX
416 void sigSegvHandler(int) {
417     fprintf(stderr, "Error: SEGV\n");
418     if (!currentProperty.isEmpty())
419         fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
420     exit(EXIT_SEGV);
421 }
422 #endif
423
424 void printUsage(const QString &appName)
425 {
426     qWarning() << qPrintable(QString(
427                                  "Usage: %1 [-notrelocatable] module.uri version [module/import/path]\n"
428                                  "       %1 -path path/to/qmldir/directory [version]\n"
429                                  "       %1 -builtins\n"
430                                  "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
431                                  appName));
432 }
433
434 int main(int argc, char *argv[])
435 {
436 #ifdef Q_OS_UNIX
437     // qmldump may crash, but we don't want any crash handlers to pop up
438     // therefore we intercept the segfault and just exit() ourselves
439     struct sigaction action;
440
441     sigemptyset(&action.sa_mask);
442     action.sa_handler = &sigSegvHandler;
443     action.sa_flags   = 0;
444
445     sigaction(SIGSEGV, &action, 0);
446 #endif
447
448 #ifdef QT_SIMULATOR
449     // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
450     QtSimulatorPrivate::SimulatorConnection::createStubInstance();
451 #endif
452     QApplication app(argc, argv);
453     const QStringList args = app.arguments();
454     const QString appName = QFileInfo(app.applicationFilePath()).baseName();
455     if (!(args.size() >= 3
456           || (args.size() == 2
457               && (args.at(1) == QLatin1String("--builtins")
458                   || args.at(1) == QLatin1String("-builtins"))))) {
459         printUsage(appName);
460         return EXIT_INVALIDARGUMENTS;
461     }
462
463     QString pluginImportUri;
464     QString pluginImportVersion;
465     bool relocatable = true;
466     bool pathImport = false;
467     if (args.size() >= 3) {
468         QStringList positionalArgs;
469         foreach (const QString &arg, args) {
470             if (!arg.startsWith(QLatin1Char('-'))) {
471                 positionalArgs.append(arg);
472                 continue;
473             }
474
475             if (arg == QLatin1String("--notrelocatable")
476                     || arg == QLatin1String("-notrelocatable")) {
477                 relocatable = false;
478             } else if (arg == QLatin1String("--path")
479                        || arg == QLatin1String("-path")) {
480                 pathImport = true;
481             } else {
482                 qWarning() << "Invalid argument: " << arg;
483                 return EXIT_INVALIDARGUMENTS;
484             }
485         }
486
487         if (!pathImport) {
488             if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
489                 qWarning() << "Incorrect number of positional arguments";
490                 return EXIT_INVALIDARGUMENTS;
491             }
492             pluginImportUri = positionalArgs[1];
493             pluginImportVersion = positionalArgs[2];
494             if (positionalArgs.size() >= 4)
495                 pluginImportPath = positionalArgs[3];
496         } else {
497             if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
498                 qWarning() << "Incorrect number of positional arguments";
499                 return EXIT_INVALIDARGUMENTS;
500             }
501             pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
502             if (positionalArgs.size() == 3)
503                 pluginImportVersion = positionalArgs[2];
504         }
505     }
506
507     QDeclarativeView view;
508     QDeclarativeEngine *engine = view.engine();
509     if (!pluginImportPath.isEmpty())
510         engine->addImportPath(pluginImportPath);
511
512     // find all QMetaObjects reachable from the builtin module
513     QByteArray importCode("import QtQuick 1.0\n");
514     QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(importCode, engine);
515
516     // this will hold the meta objects we want to dump information of
517     QSet<const QMetaObject *> metas;
518
519     if (pluginImportUri.isEmpty() && !pathImport) {
520         metas = defaultReachable;
521     } else {
522         // find all QMetaObjects reachable when the specified module is imported
523         if (!pathImport) {
524             importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
525         } else {
526             // pluginImportVersion can be empty
527             importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
528         }
529
530         // create a component with these imports to make sure the imports are valid
531         // and to populate the declarative meta type system
532         {
533             QByteArray code = importCode;
534             code += "QtObject {}";
535             QDeclarativeComponent c(engine);
536
537             c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
538             c.create();
539             if (!c.errors().isEmpty()) {
540                 foreach (const QDeclarativeError &error, c.errors())
541                     qWarning() << error.toString();
542                 return EXIT_IMPORTERROR;
543             }
544         }
545
546         QSet<const QMetaObject *> candidates = collectReachableMetaObjects(importCode, engine);
547         candidates.subtract(defaultReachable);
548
549         // Also eliminate meta objects with the same classname.
550         // This is required because extended objects seem not to share
551         // a single meta object instance.
552         QSet<QByteArray> defaultReachableNames;
553         foreach (const QMetaObject *mo, defaultReachable)
554             defaultReachableNames.insert(QByteArray(mo->className()));
555         foreach (const QMetaObject *mo, candidates) {
556             if (!defaultReachableNames.contains(mo->className()))
557                 metas.insert(mo);
558         }
559     }
560
561     // setup static rewrites of type names
562     cppToId.insert("QString", "string");
563     cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
564
565     // start dumping data
566     QByteArray bytes;
567     QmlStreamWriter qml(&bytes);
568
569     qml.writeStartDocument();
570     qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 0);
571     qml.write("\n"
572               "// This file describes the plugin-supplied types contained in the library.\n"
573               "// It is used for QML tooling purposes only.\n"
574               "\n");
575     qml.writeStartObject("Module");
576
577     // put the metaobjects into a map so they are always dumped in the same order
578     QMap<QString, const QMetaObject *> nameToMeta;
579     foreach (const QMetaObject *meta, metas)
580         nameToMeta.insert(convertToId(meta->className()), meta);
581
582     Dumper dumper(&qml);
583     if (relocatable)
584         dumper.setRelocatableModuleUri(pluginImportUri);
585     foreach (const QMetaObject *meta, nameToMeta) {
586         dumper.dump(meta);
587     }
588
589     // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
590     // properties using the QEasingCurve type get useful type information.
591     if (pluginImportUri.isEmpty())
592         dumper.writeEasingCurve();
593
594     qml.writeEndObject();
595     qml.writeEndDocument();
596
597     std::cout << bytes.constData();
598
599     // workaround to avoid crashes on exit
600     QTimer timer;
601     timer.setSingleShot(true);
602     timer.setInterval(0);
603     QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));
604     timer.start();
605
606     return app.exec();
607 }