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