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