1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the tools applications of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include <QtDeclarative/QtDeclarative>
43 #include <QtDeclarative/private/qdeclarativemetatype_p.h>
44 #include <QtDeclarative/private/qdeclarativeopenmetaobject_p.h>
45 #include <QtDeclarative/private/qsgevents_p_p.h>
46 #include <QtDeclarative/private/qsgpincharea_p.h>
48 #include <QtWidgets/QApplication>
50 #include <QtCore/QSet>
51 #include <QtCore/QMetaObject>
52 #include <QtCore/QMetaProperty>
53 #include <QtCore/QDebug>
54 #include <QtCore/private/qobject_p.h>
55 #include <QtCore/private/qmetaobject_p.h>
59 #include "qmlstreamwriter.h"
62 #include <QtGui/private/qsimulatorconnection_p.h>
69 QString pluginImportPath;
72 QString currentProperty;
73 QString inObjectInstantiation;
75 void collectReachableMetaObjects(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
77 if (! meta || metas->contains(meta))
80 // dynamic meta objects break things badly, so just ignore them
81 const QMetaObjectPrivate *mop = reinterpret_cast<const QMetaObjectPrivate *>(meta->d.data);
82 if (!(mop->flags & DynamicMetaObject))
85 collectReachableMetaObjects(meta->superClass(), metas);
88 void collectReachableMetaObjects(QObject *object, QSet<const QMetaObject *> *metas)
93 const QMetaObject *meta = object->metaObject();
95 qDebug() << "Processing object" << meta->className();
96 collectReachableMetaObjects(meta, metas);
98 for (int index = 0; index < meta->propertyCount(); ++index) {
99 QMetaProperty prop = meta->property(index);
100 if (QDeclarativeMetaType::isQObject(prop.userType())) {
102 qDebug() << " Processing property" << prop.name();
103 currentProperty = QString("%1::%2").arg(meta->className(), prop.name());
105 // if the property was not initialized during construction,
106 // accessing a member of oo is going to cause a segmentation fault
107 QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
108 if (oo && !metas->contains(oo->metaObject()))
109 collectReachableMetaObjects(oo, metas);
110 currentProperty.clear();
115 void collectReachableMetaObjects(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
117 collectReachableMetaObjects(ty->metaObject(), metas);
118 if (ty->attachedPropertiesType())
119 collectReachableMetaObjects(ty->attachedPropertiesType(), metas);
122 /* We want to add the MetaObject for 'Qt' to the list, this is a
123 simple way to access it.
125 class FriendlyQObject: public QObject
128 static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
131 /* When we dump a QMetaObject, we want to list all the types it is exported as.
132 To do this, we need to find the QDeclarativeTypes associated with this
135 static QHash<QByteArray, QSet<const QDeclarativeType *> > qmlTypesByCppName;
137 static QHash<QByteArray, QByteArray> cppToId;
139 /* Takes a C++ type name, such as Qt::LayoutDirection or QString and
140 maps it to how it should appear in the description file.
142 These names need to be unique globally, so we don't change the C++ symbol's
143 name much. It is mostly used to for explicit translations such as
144 QString->string and translations for extended QML objects.
146 QByteArray convertToId(const QByteArray &cppName)
148 return cppToId.value(cppName, cppName);
151 QSet<const QMetaObject *> collectReachableMetaObjects(const QList<QDeclarativeType *> &skip = QList<QDeclarativeType *>())
153 QSet<const QMetaObject *> metas;
154 metas.insert(FriendlyQObject::qtMeta());
156 QHash<QByteArray, QSet<QByteArray> > extensions;
157 foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
158 qmlTypesByCppName[ty->metaObject()->className()].insert(ty);
159 if (ty->isExtendedType()) {
160 extensions[ty->typeName()].insert(ty->metaObject()->className());
162 collectReachableMetaObjects(ty, &metas);
165 // Adjust exports of the base object if there are extensions.
166 // For each export of a base object there can be a single extension object overriding it.
167 // Example: QDeclarativeGraphicsWidget overrides the QtQuick/QGraphicsWidget export
168 // of QGraphicsWidget.
169 foreach (const QByteArray &baseCpp, extensions.keys()) {
170 QSet<const QDeclarativeType *> baseExports = qmlTypesByCppName.value(baseCpp);
172 const QSet<QByteArray> extensionCppNames = extensions.value(baseCpp);
173 foreach (const QByteArray &extensionCppName, extensionCppNames) {
174 const QSet<const QDeclarativeType *> extensionExports = qmlTypesByCppName.value(extensionCppName);
176 // remove extension exports from base imports
177 // unfortunately the QDeclarativeType pointers don't match, so can't use QSet::substract
178 QSet<const QDeclarativeType *> newBaseExports;
179 foreach (const QDeclarativeType *baseExport, baseExports) {
181 foreach (const QDeclarativeType *extensionExport, extensionExports) {
182 if (baseExport->qmlTypeName() == extensionExport->qmlTypeName()
183 && baseExport->majorVersion() == extensionExport->majorVersion()
184 && baseExport->minorVersion() == extensionExport->minorVersion()) {
190 newBaseExports.insert(baseExport);
192 baseExports = newBaseExports;
194 qmlTypesByCppName[baseCpp] = baseExports;
197 // find even more QMetaObjects by instantiating QML types and running
198 // over the instances
199 foreach (QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
200 if (skip.contains(ty))
202 if (ty->isExtendedType())
204 if (!ty->isCreatable())
206 if (ty->typeName() == "QDeclarativeComponent")
209 QString tyName = ty->qmlTypeName();
210 tyName = tyName.mid(tyName.lastIndexOf(QLatin1Char('/')) + 1);
211 if (tyName.isEmpty())
214 inObjectInstantiation = tyName;
215 QObject *object = ty->create();
216 inObjectInstantiation.clear();
219 collectReachableMetaObjects(object, &metas);
221 qWarning() << "Could not create" << tyName;
230 QmlStreamWriter *qml;
231 QString relocatableModuleUri;
234 Dumper(QmlStreamWriter *qml) : qml(qml) {}
236 void setRelocatableModuleUri(const QString &uri)
238 relocatableModuleUri = uri;
241 void dump(const QMetaObject *meta)
243 qml->writeStartObject("Component");
245 QByteArray id = convertToId(meta->className());
246 qml->writeScriptBinding(QLatin1String("name"), enquote(id));
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())));
256 if (meta->superClass())
257 qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass()->className())));
259 QSet<const QDeclarativeType *> qmlTypes = qmlTypesByCppName.value(meta->className());
260 if (!qmlTypes.isEmpty()) {
261 QHash<QString, const QDeclarativeType *> exports;
263 foreach (const QDeclarativeType *qmlTy, qmlTypes) {
264 QString qmlTyName = qmlTy->qmlTypeName();
265 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
266 qmlTyName.remove(0, relocatableModuleUri.size() + 1);
268 if (qmlTyName.startsWith("./")) {
269 qmlTyName.remove(0, 2);
271 if (qmlTyName.startsWith("/")) {
272 qmlTyName.remove(0, 1);
274 const QString exportString = enquote(
275 QString("%1 %2.%3").arg(
277 QString::number(qmlTy->majorVersion()),
278 QString::number(qmlTy->minorVersion())));
279 exports.insert(exportString, qmlTy);
282 // ensure exports are sorted and don't change order when the plugin is dumped again
283 QStringList exportStrings = exports.keys();
284 qSort(exportStrings);
285 qml->writeArrayBinding(QLatin1String("exports"), exportStrings);
287 // write meta object revisions unless they're all zero
288 QStringList metaObjectRevisions;
289 bool shouldWriteMetaObjectRevisions = false;
290 foreach (const QString &exportString, exportStrings) {
291 int metaObjectRevision = exports[exportString]->metaObjectRevision();
292 if (metaObjectRevision != 0)
293 shouldWriteMetaObjectRevisions = true;
294 metaObjectRevisions += QString::number(metaObjectRevision);
296 if (shouldWriteMetaObjectRevisions)
297 qml->writeArrayBinding(QLatin1String("exportMetaObjectRevisions"), metaObjectRevisions);
299 if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
300 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
301 convertToId(attachedType->className())));
305 for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
306 dump(meta->enumerator(index));
308 QSet<QString> implicitSignals;
309 for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index) {
310 const QMetaProperty &property = meta->property(index);
312 implicitSignals.insert(QString("%1Changed").arg(QString::fromUtf8(property.name())));
315 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
316 dump(meta->method(index), implicitSignals);
318 qml->writeEndObject();
321 void writeEasingCurve()
323 qml->writeStartObject("Component");
324 qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
325 qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
326 qml->writeEndObject();
330 static QString enquote(const QString &string)
332 return QString("\"%1\"").arg(string);
335 /* Removes pointer and list annotations from a type name, returning
336 what was removed in isList and isPointer
338 static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
340 static QByteArray declListPrefix = "QDeclarativeListProperty<";
342 if (typeName->endsWith('*')) {
344 typeName->truncate(typeName->length() - 1);
345 removePointerAndList(typeName, isList, isPointer);
346 } else if (typeName->startsWith(declListPrefix)) {
348 typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
349 *typeName = typeName->mid(declListPrefix.size());
350 removePointerAndList(typeName, isList, isPointer);
353 *typeName = convertToId(*typeName);
356 void writeTypeProperties(QByteArray typeName, bool isWritable)
358 bool isList = false, isPointer = false;
359 removePointerAndList(&typeName, &isList, &isPointer);
361 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
363 qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
365 qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
367 qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
370 void dump(const QMetaProperty &prop)
372 qml->writeStartObject("Property");
374 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
375 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
376 if (int revision = prop.revision())
377 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
379 writeTypeProperties(prop.typeName(), prop.isWritable());
381 qml->writeEndObject();
384 void dump(const QMetaMethod &meth, const QSet<QString> &implicitSignals)
386 if (meth.methodType() == QMetaMethod::Signal) {
387 if (meth.access() != QMetaMethod::Protected)
388 return; // nothing to do.
389 } else if (meth.access() != QMetaMethod::Public) {
390 return; // nothing to do.
393 QByteArray name = meth.signature();
394 int lparenIndex = name.indexOf('(');
395 if (lparenIndex == -1) {
396 return; // invalid signature
398 name = name.left(lparenIndex);
399 const QString typeName = convertToId(meth.typeName());
401 if (implicitSignals.contains(name)
403 && meth.methodType() == QMetaMethod::Signal
404 && meth.parameterNames().isEmpty()
405 && typeName.isEmpty()) {
406 // don't mention implicit signals
410 if (meth.methodType() == QMetaMethod::Signal)
411 qml->writeStartObject(QLatin1String("Signal"));
413 qml->writeStartObject(QLatin1String("Method"));
415 qml->writeScriptBinding(QLatin1String("name"), enquote(name));
417 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
418 if (int revision = meth.revision())
419 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
422 if (! typeName.isEmpty())
423 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
425 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
426 QByteArray argName = meth.parameterNames().at(i);
428 qml->writeStartObject(QLatin1String("Parameter"));
429 if (! argName.isEmpty())
430 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
431 writeTypeProperties(meth.parameterTypes().at(i), true);
432 qml->writeEndObject();
435 qml->writeEndObject();
438 void dump(const QMetaEnum &e)
440 qml->writeStartObject(QLatin1String("Enum"));
441 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
443 QList<QPair<QString, QString> > namesValues;
444 for (int index = 0; index < e.keyCount(); ++index) {
445 namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
448 qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
449 qml->writeEndObject();
455 EXIT_INVALIDARGUMENTS = 1,
461 void sigSegvHandler(int) {
462 fprintf(stderr, "Error: SEGV\n");
463 if (!currentProperty.isEmpty())
464 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
465 if (!inObjectInstantiation.isEmpty())
466 fprintf(stderr, "While instantiating the object '%s'.\n", inObjectInstantiation.toLatin1().constData());
471 void printUsage(const QString &appName)
473 qWarning() << qPrintable(QString(
474 "Usage: %1 [-v] [-notrelocatable] module.uri version [module/import/path]\n"
475 " %1 [-v] -path path/to/qmldir/directory [version]\n"
476 " %1 [-v] -builtins\n"
477 "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
481 int main(int argc, char *argv[])
484 // qmldump may crash, but we don't want any crash handlers to pop up
485 // therefore we intercept the segfault and just exit() ourselves
486 struct sigaction sigAction;
488 sigemptyset(&sigAction.sa_mask);
489 sigAction.sa_handler = &sigSegvHandler;
490 sigAction.sa_flags = 0;
492 sigaction(SIGSEGV, &sigAction, 0);
496 // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
497 QtSimulatorPrivate::SimulatorConnection::createStubInstance();
499 QApplication app(argc, argv);
500 const QStringList args = app.arguments();
501 const QString appName = QFileInfo(app.applicationFilePath()).baseName();
502 if (args.size() < 2) {
504 return EXIT_INVALIDARGUMENTS;
507 QString pluginImportUri;
508 QString pluginImportVersion;
509 bool relocatable = true;
510 enum Action { Uri, Path, Builtins };
513 QStringList positionalArgs;
514 foreach (const QString &arg, args) {
515 if (!arg.startsWith(QLatin1Char('-'))) {
516 positionalArgs.append(arg);
520 if (arg == QLatin1String("--notrelocatable")
521 || arg == QLatin1String("-notrelocatable")) {
523 } else if (arg == QLatin1String("--path")
524 || arg == QLatin1String("-path")) {
526 } else if (arg == QLatin1String("--builtins")
527 || arg == QLatin1String("-builtins")) {
529 } else if (arg == QLatin1String("-v")) {
532 qWarning() << "Invalid argument: " << arg;
533 return EXIT_INVALIDARGUMENTS;
538 if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
539 qWarning() << "Incorrect number of positional arguments";
540 return EXIT_INVALIDARGUMENTS;
542 pluginImportUri = positionalArgs[1];
543 pluginImportVersion = positionalArgs[2];
544 if (positionalArgs.size() >= 4)
545 pluginImportPath = positionalArgs[3];
546 } else if (action == Path) {
547 if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
548 qWarning() << "Incorrect number of positional arguments";
549 return EXIT_INVALIDARGUMENTS;
551 pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
552 if (positionalArgs.size() == 3)
553 pluginImportVersion = positionalArgs[2];
554 } else if (action == Builtins) {
555 if (positionalArgs.size() != 1) {
556 qWarning() << "Incorrect number of positional arguments";
557 return EXIT_INVALIDARGUMENTS;
562 QDeclarativeEngine engine;
563 if (!pluginImportPath.isEmpty()) {
564 QDir cur = QDir::current();
565 cur.cd(pluginImportPath);
566 pluginImportPath = cur.absolutePath();
567 QDir::setCurrent(pluginImportPath);
568 engine.addImportPath(pluginImportPath);
571 // load the QtQuick 1 plugin
573 QByteArray code("import QtQuick 1.0\nQtObject {}");
574 QDeclarativeComponent c(&engine);
575 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/loadqtquick1.qml"));
577 if (!c.errors().isEmpty()) {
578 foreach (const QDeclarativeError &error, c.errors())
579 qWarning() << error.toString();
580 return EXIT_IMPORTERROR;
584 // find all QMetaObjects reachable from the builtin module
585 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects();
586 QList<QDeclarativeType *> defaultTypes = QDeclarativeMetaType::qmlTypes();
588 // add some otherwise unreachable QMetaObjects
589 defaultReachable.insert(&QSGMouseEvent::staticMetaObject);
590 // QSGKeyEvent, QSGPinchEvent, QSGDropEvent are not exported
592 // this will hold the meta objects we want to dump information of
593 QSet<const QMetaObject *> metas;
595 if (action == Builtins) {
596 metas = defaultReachable;
598 // find a valid QtQuick import
599 QByteArray importCode;
600 QDeclarativeType *qtObjectType = QDeclarativeMetaType::qmlType(&QObject::staticMetaObject);
602 qWarning() << "Could not find QtObject type";
603 importCode = QByteArray("import QtQuick 2.0\n");
605 QString module = qtObjectType->qmlTypeName();
606 module = module.mid(0, module.lastIndexOf(QLatin1Char('/')));
607 importCode = QString("import %1 %2.%3\n").arg(module,
608 QString::number(qtObjectType->majorVersion()),
609 QString::number(qtObjectType->minorVersion())).toUtf8();
612 // find all QMetaObjects reachable when the specified module is imported
613 if (action != Path) {
614 importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
616 // pluginImportVersion can be empty
617 importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
620 // create a component with these imports to make sure the imports are valid
621 // and to populate the declarative meta type system
623 QByteArray code = importCode;
624 code += "QtObject {}";
625 QDeclarativeComponent c(&engine);
627 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
629 if (!c.errors().isEmpty()) {
630 foreach (const QDeclarativeError &error, c.errors())
631 qWarning() << error.toString();
632 return EXIT_IMPORTERROR;
636 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(defaultTypes);
637 candidates.subtract(defaultReachable);
639 // Also eliminate meta objects with the same classname.
640 // This is required because extended objects seem not to share
641 // a single meta object instance.
642 QSet<QByteArray> defaultReachableNames;
643 foreach (const QMetaObject *mo, defaultReachable)
644 defaultReachableNames.insert(QByteArray(mo->className()));
645 foreach (const QMetaObject *mo, candidates) {
646 if (!defaultReachableNames.contains(mo->className()))
651 // setup static rewrites of type names
652 cppToId.insert("QString", "string");
653 cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
655 // start dumping data
657 QmlStreamWriter qml(&bytes);
659 qml.writeStartDocument();
660 qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 1);
662 "// This file describes the plugin-supplied types contained in the library.\n"
663 "// It is used for QML tooling purposes only.\n"
665 qml.writeStartObject("Module");
667 // put the metaobjects into a map so they are always dumped in the same order
668 QMap<QString, const QMetaObject *> nameToMeta;
669 foreach (const QMetaObject *meta, metas)
670 nameToMeta.insert(convertToId(meta->className()), meta);
674 dumper.setRelocatableModuleUri(pluginImportUri);
675 foreach (const QMetaObject *meta, nameToMeta) {
679 // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
680 // properties using the QEasingCurve type get useful type information.
681 if (pluginImportUri.isEmpty())
682 dumper.writeEasingCurve();
684 qml.writeEndObject();
685 qml.writeEndDocument();
687 std::cout << bytes.constData();
689 // workaround to avoid crashes on exit
691 timer.setSingleShot(true);
692 timer.setInterval(0);
693 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));