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