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