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>
46 #include <QtWidgets/QApplication>
48 #include <QtCore/QSet>
49 #include <QtCore/QMetaObject>
50 #include <QtCore/QMetaProperty>
51 #include <QtCore/QDebug>
52 #include <QtCore/private/qobject_p.h>
53 #include <QtCore/private/qmetaobject_p.h>
57 #include "qmlstreamwriter.h"
60 #include <QtGui/private/qsimulatorconnection_p.h>
67 QString pluginImportPath;
70 QString currentProperty;
71 QString inObjectInstantiation;
73 void collectReachableMetaObjects(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
75 if (! meta || metas->contains(meta))
78 // dynamic meta objects break things badly, so just ignore them
79 const QMetaObjectPrivate *mop = reinterpret_cast<const QMetaObjectPrivate *>(meta->d.data);
80 if (!(mop->flags & DynamicMetaObject))
83 collectReachableMetaObjects(meta->superClass(), metas);
86 void collectReachableMetaObjects(QObject *object, QSet<const QMetaObject *> *metas)
91 const QMetaObject *meta = object->metaObject();
93 qDebug() << "Processing object" << meta->className();
94 collectReachableMetaObjects(meta, metas);
96 for (int index = 0; index < meta->propertyCount(); ++index) {
97 QMetaProperty prop = meta->property(index);
98 if (QDeclarativeMetaType::isQObject(prop.userType())) {
100 qDebug() << " Processing property" << prop.name();
101 currentProperty = QString("%1::%2").arg(meta->className(), prop.name());
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();
113 void collectReachableMetaObjects(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
115 collectReachableMetaObjects(ty->metaObject(), metas);
116 if (ty->attachedPropertiesType())
117 collectReachableMetaObjects(ty->attachedPropertiesType(), metas);
120 /* We want to add the MetaObject for 'Qt' to the list, this is a
121 simple way to access it.
123 class FriendlyQObject: public QObject
126 static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
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
133 static QHash<QByteArray, QSet<const QDeclarativeType *> > qmlTypesByCppName;
135 static QHash<QByteArray, QByteArray> cppToId;
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.
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.
144 QByteArray convertToId(const QByteArray &cppName)
146 return cppToId.value(cppName, cppName);
149 QSet<const QMetaObject *> collectReachableMetaObjects(const QList<QDeclarativeType *> &skip = QList<QDeclarativeType *>())
151 QSet<const QMetaObject *> metas;
152 metas.insert(FriendlyQObject::qtMeta());
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());
160 collectReachableMetaObjects(ty, &metas);
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);
170 const QSet<QByteArray> extensionCppNames = extensions.value(baseCpp);
171 foreach (const QByteArray &extensionCppName, extensionCppNames) {
172 const QSet<const QDeclarativeType *> extensionExports = qmlTypesByCppName.value(extensionCppName);
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) {
179 foreach (const QDeclarativeType *extensionExport, extensionExports) {
180 if (baseExport->qmlTypeName() == extensionExport->qmlTypeName()
181 && baseExport->majorVersion() == extensionExport->majorVersion()
182 && baseExport->minorVersion() == extensionExport->minorVersion()) {
188 newBaseExports.insert(baseExport);
190 baseExports = newBaseExports;
192 qmlTypesByCppName[baseCpp] = baseExports;
195 // find even more QMetaObjects by instantiating QML types and running
196 // over the instances
197 foreach (QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
198 if (skip.contains(ty))
200 if (ty->isExtendedType())
202 if (!ty->isCreatable())
204 if (ty->typeName() == "QDeclarativeComponent")
207 QString tyName = ty->qmlTypeName();
208 tyName = tyName.mid(tyName.lastIndexOf(QLatin1Char('/')) + 1);
209 if (tyName.isEmpty())
212 inObjectInstantiation = tyName;
213 QObject *object = ty->create();
214 inObjectInstantiation.clear();
217 collectReachableMetaObjects(object, &metas);
219 qWarning() << "Could not create" << tyName;
228 QmlStreamWriter *qml;
229 QString relocatableModuleUri;
232 Dumper(QmlStreamWriter *qml) : qml(qml) {}
234 void setRelocatableModuleUri(const QString &uri)
236 relocatableModuleUri = uri;
239 void dump(const QMetaObject *meta)
241 qml->writeStartObject("Component");
243 QByteArray id = convertToId(meta->className());
244 qml->writeScriptBinding(QLatin1String("name"), enquote(id));
246 for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
247 QMetaClassInfo classInfo = meta->classInfo(index);
248 if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
249 qml->writeScriptBinding(QLatin1String("defaultProperty"), enquote(QLatin1String(classInfo.value())));
254 if (meta->superClass())
255 qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass()->className())));
257 QSet<const QDeclarativeType *> qmlTypes = qmlTypesByCppName.value(meta->className());
258 if (!qmlTypes.isEmpty()) {
259 QHash<QString, const QDeclarativeType *> exports;
261 foreach (const QDeclarativeType *qmlTy, qmlTypes) {
262 QString qmlTyName = qmlTy->qmlTypeName();
263 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
264 qmlTyName.remove(0, relocatableModuleUri.size() + 1);
266 if (qmlTyName.startsWith("./")) {
267 qmlTyName.remove(0, 2);
269 if (qmlTyName.startsWith("/")) {
270 qmlTyName.remove(0, 1);
272 const QString exportString = enquote(
273 QString("%1 %2.%3").arg(
275 QString::number(qmlTy->majorVersion()),
276 QString::number(qmlTy->minorVersion())));
277 exports.insert(exportString, qmlTy);
280 // ensure exports are sorted and don't change order when the plugin is dumped again
281 QStringList exportStrings = exports.keys();
282 qSort(exportStrings);
283 qml->writeArrayBinding(QLatin1String("exports"), exportStrings);
285 // write meta object revisions unless they're all zero
286 QStringList metaObjectRevisions;
287 bool shouldWriteMetaObjectRevisions = false;
288 foreach (const QString &exportString, exportStrings) {
289 int metaObjectRevision = exports[exportString]->metaObjectRevision();
290 if (metaObjectRevision != 0)
291 shouldWriteMetaObjectRevisions = true;
292 metaObjectRevisions += QString::number(metaObjectRevision);
294 if (shouldWriteMetaObjectRevisions)
295 qml->writeArrayBinding(QLatin1String("exportMetaObjectRevisions"), metaObjectRevisions);
297 if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
298 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
299 convertToId(attachedType->className())));
303 for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
304 dump(meta->enumerator(index));
306 for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
307 dump(meta->property(index));
309 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
310 dump(meta->method(index));
312 qml->writeEndObject();
315 void writeEasingCurve()
317 qml->writeStartObject("Component");
318 qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
319 qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
320 qml->writeEndObject();
324 static QString enquote(const QString &string)
326 return QString("\"%1\"").arg(string);
329 /* Removes pointer and list annotations from a type name, returning
330 what was removed in isList and isPointer
332 static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
334 static QByteArray declListPrefix = "QDeclarativeListProperty<";
336 if (typeName->endsWith('*')) {
338 typeName->truncate(typeName->length() - 1);
339 removePointerAndList(typeName, isList, isPointer);
340 } else if (typeName->startsWith(declListPrefix)) {
342 typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
343 *typeName = typeName->mid(declListPrefix.size());
344 removePointerAndList(typeName, isList, isPointer);
347 *typeName = convertToId(*typeName);
350 void writeTypeProperties(QByteArray typeName, bool isWritable)
352 bool isList = false, isPointer = false;
353 removePointerAndList(&typeName, &isList, &isPointer);
355 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
357 qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
359 qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
361 qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
364 void dump(const QMetaProperty &prop)
366 qml->writeStartObject("Property");
368 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
369 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
370 if (int revision = prop.revision())
371 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
373 writeTypeProperties(prop.typeName(), prop.isWritable());
375 qml->writeEndObject();
378 void dump(const QMetaMethod &meth)
380 if (meth.methodType() == QMetaMethod::Signal) {
381 if (meth.access() != QMetaMethod::Protected)
382 return; // nothing to do.
383 } else if (meth.access() != QMetaMethod::Public) {
384 return; // nothing to do.
387 QByteArray name = meth.signature();
388 int lparenIndex = name.indexOf('(');
389 if (lparenIndex == -1) {
390 return; // invalid signature
392 name = name.left(lparenIndex);
394 if (meth.methodType() == QMetaMethod::Signal)
395 qml->writeStartObject(QLatin1String("Signal"));
397 qml->writeStartObject(QLatin1String("Method"));
399 qml->writeScriptBinding(QLatin1String("name"), enquote(name));
401 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
402 if (int revision = meth.revision())
403 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
406 const QString typeName = convertToId(meth.typeName());
407 if (! typeName.isEmpty())
408 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
410 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
411 QByteArray argName = meth.parameterNames().at(i);
413 qml->writeStartObject(QLatin1String("Parameter"));
414 if (! argName.isEmpty())
415 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
416 writeTypeProperties(meth.parameterTypes().at(i), true);
417 qml->writeEndObject();
420 qml->writeEndObject();
423 void dump(const QMetaEnum &e)
425 qml->writeStartObject(QLatin1String("Enum"));
426 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
428 QList<QPair<QString, QString> > namesValues;
429 for (int index = 0; index < e.keyCount(); ++index) {
430 namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
433 qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
434 qml->writeEndObject();
440 EXIT_INVALIDARGUMENTS = 1,
446 void sigSegvHandler(int) {
447 fprintf(stderr, "Error: SEGV\n");
448 if (!currentProperty.isEmpty())
449 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
450 if (!inObjectInstantiation.isEmpty())
451 fprintf(stderr, "While instantiating the object '%s'.\n", inObjectInstantiation.toLatin1().constData());
456 void printUsage(const QString &appName)
458 qWarning() << qPrintable(QString(
459 "Usage: %1 [-v] [-notrelocatable] module.uri version [module/import/path]\n"
460 " %1 [-v] -path path/to/qmldir/directory [version]\n"
461 " %1 [-v] -builtins\n"
462 "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
466 int main(int argc, char *argv[])
469 // qmldump may crash, but we don't want any crash handlers to pop up
470 // therefore we intercept the segfault and just exit() ourselves
471 struct sigaction sigAction;
473 sigemptyset(&sigAction.sa_mask);
474 sigAction.sa_handler = &sigSegvHandler;
475 sigAction.sa_flags = 0;
477 sigaction(SIGSEGV, &sigAction, 0);
481 // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
482 QtSimulatorPrivate::SimulatorConnection::createStubInstance();
484 QApplication app(argc, argv);
485 const QStringList args = app.arguments();
486 const QString appName = QFileInfo(app.applicationFilePath()).baseName();
487 if (args.size() < 2) {
489 return EXIT_INVALIDARGUMENTS;
492 QString pluginImportUri;
493 QString pluginImportVersion;
494 bool relocatable = true;
495 enum Action { Uri, Path, Builtins };
498 QStringList positionalArgs;
499 foreach (const QString &arg, args) {
500 if (!arg.startsWith(QLatin1Char('-'))) {
501 positionalArgs.append(arg);
505 if (arg == QLatin1String("--notrelocatable")
506 || arg == QLatin1String("-notrelocatable")) {
508 } else if (arg == QLatin1String("--path")
509 || arg == QLatin1String("-path")) {
511 } else if (arg == QLatin1String("--builtins")
512 || arg == QLatin1String("-builtins")) {
514 } else if (arg == QLatin1String("-v")) {
517 qWarning() << "Invalid argument: " << arg;
518 return EXIT_INVALIDARGUMENTS;
523 if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
524 qWarning() << "Incorrect number of positional arguments";
525 return EXIT_INVALIDARGUMENTS;
527 pluginImportUri = positionalArgs[1];
528 pluginImportVersion = positionalArgs[2];
529 if (positionalArgs.size() >= 4)
530 pluginImportPath = positionalArgs[3];
531 } else if (action == Path) {
532 if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
533 qWarning() << "Incorrect number of positional arguments";
534 return EXIT_INVALIDARGUMENTS;
536 pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
537 if (positionalArgs.size() == 3)
538 pluginImportVersion = positionalArgs[2];
539 } else if (action == Builtins) {
540 if (positionalArgs.size() != 1) {
541 qWarning() << "Incorrect number of positional arguments";
542 return EXIT_INVALIDARGUMENTS;
547 QDeclarativeEngine engine;
548 if (!pluginImportPath.isEmpty()) {
549 QDir cur = QDir::current();
550 cur.cd(pluginImportPath);
551 pluginImportPath = cur.absolutePath();
552 QDir::setCurrent(pluginImportPath);
553 engine.addImportPath(pluginImportPath);
556 // load the QtQuick 1 plugin
558 QByteArray code("import QtQuick 1.0\nQtObject {}");
559 QDeclarativeComponent c(&engine);
560 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/loadqtquick1.qml"));
562 if (!c.errors().isEmpty()) {
563 foreach (const QDeclarativeError &error, c.errors())
564 qWarning() << error.toString();
565 return EXIT_IMPORTERROR;
569 // find all QMetaObjects reachable from the builtin module
570 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects();
571 QList<QDeclarativeType *> defaultTypes = QDeclarativeMetaType::qmlTypes();
573 // this will hold the meta objects we want to dump information of
574 QSet<const QMetaObject *> metas;
576 if (action == Builtins) {
577 metas = defaultReachable;
579 // find a valid QtQuick import
580 QByteArray importCode;
581 QDeclarativeType *qtObjectType = QDeclarativeMetaType::qmlType(&QObject::staticMetaObject);
583 qWarning() << "Could not find QtObject type";
584 importCode = QByteArray("import QtQuick 2.0\n");
586 QString module = qtObjectType->qmlTypeName();
587 module = module.mid(0, module.lastIndexOf(QLatin1Char('/')));
588 importCode = QString("import %1 %2.%3\n").arg(module,
589 QString::number(qtObjectType->majorVersion()),
590 QString::number(qtObjectType->minorVersion())).toUtf8();
593 // find all QMetaObjects reachable when the specified module is imported
594 if (action != Path) {
595 importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
597 // pluginImportVersion can be empty
598 importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
601 // create a component with these imports to make sure the imports are valid
602 // and to populate the declarative meta type system
604 QByteArray code = importCode;
605 code += "QtObject {}";
606 QDeclarativeComponent c(&engine);
608 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
610 if (!c.errors().isEmpty()) {
611 foreach (const QDeclarativeError &error, c.errors())
612 qWarning() << error.toString();
613 return EXIT_IMPORTERROR;
617 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(defaultTypes);
618 candidates.subtract(defaultReachable);
620 // Also eliminate meta objects with the same classname.
621 // This is required because extended objects seem not to share
622 // a single meta object instance.
623 QSet<QByteArray> defaultReachableNames;
624 foreach (const QMetaObject *mo, defaultReachable)
625 defaultReachableNames.insert(QByteArray(mo->className()));
626 foreach (const QMetaObject *mo, candidates) {
627 if (!defaultReachableNames.contains(mo->className()))
632 // setup static rewrites of type names
633 cppToId.insert("QString", "string");
634 cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
636 // start dumping data
638 QmlStreamWriter qml(&bytes);
640 qml.writeStartDocument();
641 qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 1);
643 "// This file describes the plugin-supplied types contained in the library.\n"
644 "// It is used for QML tooling purposes only.\n"
646 qml.writeStartObject("Module");
648 // put the metaobjects into a map so they are always dumped in the same order
649 QMap<QString, const QMetaObject *> nameToMeta;
650 foreach (const QMetaObject *meta, metas)
651 nameToMeta.insert(convertToId(meta->className()), meta);
655 dumper.setRelocatableModuleUri(pluginImportUri);
656 foreach (const QMetaObject *meta, nameToMeta) {
660 // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
661 // properties using the QEasingCurve type get useful type information.
662 if (pluginImportUri.isEmpty())
663 dumper.writeEasingCurve();
665 qml.writeEndObject();
666 qml.writeEndDocument();
668 std::cout << bytes.constData();
670 // workaround to avoid crashes on exit
672 timer.setSingleShot(true);
673 timer.setInterval(0);
674 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));