Merge branch 'master' into qtquick2
[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         writeTypeProperties(prop.typeName(), prop.isWritable());
340
341         qml->writeEndObject();
342     }
343
344     void dump(const QMetaMethod &meth)
345     {
346         if (meth.methodType() == QMetaMethod::Signal) {
347             if (meth.access() != QMetaMethod::Protected)
348                 return; // nothing to do.
349         } else if (meth.access() != QMetaMethod::Public) {
350             return; // nothing to do.
351         }
352
353         QByteArray name = meth.signature();
354         int lparenIndex = name.indexOf('(');
355         if (lparenIndex == -1) {
356             return; // invalid signature
357         }
358         name = name.left(lparenIndex);
359
360         if (meth.methodType() == QMetaMethod::Signal)
361             qml->writeStartObject(QLatin1String("Signal"));
362         else
363             qml->writeStartObject(QLatin1String("Method"));
364
365         qml->writeScriptBinding(QLatin1String("name"), enquote(name));
366
367         const QString typeName = convertToId(meth.typeName());
368         if (! typeName.isEmpty())
369             qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
370
371         for (int i = 0; i < meth.parameterTypes().size(); ++i) {
372             QByteArray argName = meth.parameterNames().at(i);
373
374             qml->writeStartObject(QLatin1String("Parameter"));
375             if (! argName.isEmpty())
376                 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
377             writeTypeProperties(meth.parameterTypes().at(i), true);
378             qml->writeEndObject();
379         }
380
381         qml->writeEndObject();
382     }
383
384     void dump(const QMetaEnum &e)
385     {
386         qml->writeStartObject(QLatin1String("Enum"));
387         qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
388
389         QList<QPair<QString, QString> > namesValues;
390         for (int index = 0; index < e.keyCount(); ++index) {
391             namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
392         }
393
394         qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
395         qml->writeEndObject();
396     }
397 };
398
399
400 enum ExitCode {
401     EXIT_INVALIDARGUMENTS = 1,
402     EXIT_SEGV = 2,
403     EXIT_IMPORTERROR = 3
404 };
405
406 #ifdef Q_OS_UNIX
407 void sigSegvHandler(int) {
408     fprintf(stderr, "Error: SEGV\n");
409     if (!currentProperty.isEmpty())
410         fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
411     exit(EXIT_SEGV);
412 }
413 #endif
414
415 void printUsage(const QString &appName)
416 {
417     qWarning() << qPrintable(QString(
418                                  "Usage: %1 [-notrelocatable] module.uri version [module/import/path]\n"
419                                  "       %1 -path path/to/qmldir/directory [version]\n"
420                                  "       %1 -builtins\n"
421                                  "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
422                                  appName));
423 }
424
425 int main(int argc, char *argv[])
426 {
427 #ifdef Q_OS_UNIX
428     // qmldump may crash, but we don't want any crash handlers to pop up
429     // therefore we intercept the segfault and just exit() ourselves
430     struct sigaction action;
431
432     sigemptyset(&action.sa_mask);
433     action.sa_handler = &sigSegvHandler;
434     action.sa_flags   = 0;
435
436     sigaction(SIGSEGV, &action, 0);
437 #endif
438
439 #ifdef QT_SIMULATOR
440     // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
441     QtSimulatorPrivate::SimulatorConnection::createStubInstance();
442 #endif
443     QApplication app(argc, argv);
444     const QStringList args = app.arguments();
445     const QString appName = QFileInfo(app.applicationFilePath()).baseName();
446     if (!(args.size() >= 3
447           || (args.size() == 2
448               && (args.at(1) == QLatin1String("--builtins")
449                   || args.at(1) == QLatin1String("-builtins"))))) {
450         printUsage(appName);
451         return EXIT_INVALIDARGUMENTS;
452     }
453
454     QString pluginImportUri;
455     QString pluginImportVersion;
456     bool relocatable = true;
457     bool pathImport = false;
458     if (args.size() >= 3) {
459         QStringList positionalArgs;
460         foreach (const QString &arg, args) {
461             if (!arg.startsWith(QLatin1Char('-'))) {
462                 positionalArgs.append(arg);
463                 continue;
464             }
465
466             if (arg == QLatin1String("--notrelocatable")
467                     || arg == QLatin1String("-notrelocatable")) {
468                 relocatable = false;
469             } else if (arg == QLatin1String("--path")
470                        || arg == QLatin1String("-path")) {
471                 pathImport = true;
472             } else {
473                 qWarning() << "Invalid argument: " << arg;
474                 return EXIT_INVALIDARGUMENTS;
475             }
476         }
477
478         if (!pathImport) {
479             if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
480                 qWarning() << "Incorrect number of positional arguments";
481                 return EXIT_INVALIDARGUMENTS;
482             }
483             pluginImportUri = positionalArgs[1];
484             pluginImportVersion = positionalArgs[2];
485             if (positionalArgs.size() >= 4)
486                 pluginImportPath = positionalArgs[3];
487         } else {
488             if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
489                 qWarning() << "Incorrect number of positional arguments";
490                 return EXIT_INVALIDARGUMENTS;
491             }
492             pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
493             if (positionalArgs.size() == 3)
494                 pluginImportVersion = positionalArgs[2];
495         }
496     }
497
498     QDeclarativeView view;
499     QDeclarativeEngine *engine = view.engine();
500     if (!pluginImportPath.isEmpty())
501         engine->addImportPath(pluginImportPath);
502
503     // find all QMetaObjects reachable from the builtin module
504     QByteArray importCode("import QtQuick 1.0\n");
505     QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(importCode, engine);
506
507     // this will hold the meta objects we want to dump information of
508     QSet<const QMetaObject *> metas;
509
510     if (pluginImportUri.isEmpty() && !pathImport) {
511         metas = defaultReachable;
512     } else {
513         // find all QMetaObjects reachable when the specified module is imported
514         if (!pathImport) {
515             importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
516         } else {
517             // pluginImportVersion can be empty
518             importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
519         }
520
521         // create a component with these imports to make sure the imports are valid
522         // and to populate the declarative meta type system
523         {
524             QByteArray code = importCode;
525             code += "QtObject {}";
526             QDeclarativeComponent c(engine);
527
528             c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
529             c.create();
530             if (!c.errors().isEmpty()) {
531                 foreach (const QDeclarativeError &error, c.errors())
532                     qWarning() << error.toString();
533                 return EXIT_IMPORTERROR;
534             }
535         }
536
537         QSet<const QMetaObject *> candidates = collectReachableMetaObjects(importCode, engine);
538         candidates.subtract(defaultReachable);
539
540         // Also eliminate meta objects with the same classname.
541         // This is required because extended objects seem not to share
542         // a single meta object instance.
543         QSet<QByteArray> defaultReachableNames;
544         foreach (const QMetaObject *mo, defaultReachable)
545             defaultReachableNames.insert(QByteArray(mo->className()));
546         foreach (const QMetaObject *mo, candidates) {
547             if (!defaultReachableNames.contains(mo->className()))
548                 metas.insert(mo);
549         }
550     }
551
552     // setup static rewrites of type names
553     cppToId.insert("QString", "string");
554     cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
555
556     // start dumping data
557     QByteArray bytes;
558     QmlStreamWriter qml(&bytes);
559
560     qml.writeStartDocument();
561     qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 0);
562     qml.write("\n"
563               "// This file describes the plugin-supplied types contained in the library.\n"
564               "// It is used for QML tooling purposes only.\n"
565               "\n");
566     qml.writeStartObject("Module");
567
568     // put the metaobjects into a map so they are always dumped in the same order
569     QMap<QString, const QMetaObject *> nameToMeta;
570     foreach (const QMetaObject *meta, metas)
571         nameToMeta.insert(convertToId(meta->className()), meta);
572
573     Dumper dumper(&qml);
574     if (relocatable)
575         dumper.setRelocatableModuleUri(pluginImportUri);
576     foreach (const QMetaObject *meta, nameToMeta) {
577         dumper.dump(meta);
578     }
579
580     // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
581     // properties using the QEasingCurve type get useful type information.
582     if (pluginImportUri.isEmpty())
583         dumper.writeEasingCurve();
584
585     qml.writeEndObject();
586     qml.writeEndDocument();
587
588     std::cout << bytes.constData();
589
590     // workaround to avoid crashes on exit
591     QTimer timer;
592     timer.setSingleShot(true);
593     timer.setInterval(0);
594     QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));
595     timer.start();
596
597     return app.exec();
598 }