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/qsgdragtarget_p.h>
47 #include <QtDeclarative/private/qsgpincharea_p.h>
49 #include <QtWidgets/QApplication>
51 #include <QtCore/QSet>
52 #include <QtCore/QMetaObject>
53 #include <QtCore/QMetaProperty>
54 #include <QtCore/QDebug>
55 #include <QtCore/private/qobject_p.h>
56 #include <QtCore/private/qmetaobject_p.h>
60 #include "qmlstreamwriter.h"
63 #include <QtGui/private/qsimulatorconnection_p.h>
70 QString pluginImportPath;
73 QString currentProperty;
74 QString inObjectInstantiation;
76 void collectReachableMetaObjects(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
78 if (! meta || metas->contains(meta))
81 // dynamic meta objects break things badly, so just ignore them
82 const QMetaObjectPrivate *mop = reinterpret_cast<const QMetaObjectPrivate *>(meta->d.data);
83 if (!(mop->flags & DynamicMetaObject))
86 collectReachableMetaObjects(meta->superClass(), metas);
89 void collectReachableMetaObjects(QObject *object, QSet<const QMetaObject *> *metas)
94 const QMetaObject *meta = object->metaObject();
96 qDebug() << "Processing object" << meta->className();
97 collectReachableMetaObjects(meta, metas);
99 for (int index = 0; index < meta->propertyCount(); ++index) {
100 QMetaProperty prop = meta->property(index);
101 if (QDeclarativeMetaType::isQObject(prop.userType())) {
103 qDebug() << " Processing property" << prop.name();
104 currentProperty = QString("%1::%2").arg(meta->className(), prop.name());
106 // if the property was not initialized during construction,
107 // accessing a member of oo is going to cause a segmentation fault
108 QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
109 if (oo && !metas->contains(oo->metaObject()))
110 collectReachableMetaObjects(oo, metas);
111 currentProperty.clear();
116 void collectReachableMetaObjects(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
118 collectReachableMetaObjects(ty->metaObject(), metas);
119 if (ty->attachedPropertiesType())
120 collectReachableMetaObjects(ty->attachedPropertiesType(), metas);
123 /* We want to add the MetaObject for 'Qt' to the list, this is a
124 simple way to access it.
126 class FriendlyQObject: public QObject
129 static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
132 /* When we dump a QMetaObject, we want to list all the types it is exported as.
133 To do this, we need to find the QDeclarativeTypes associated with this
136 static QHash<QByteArray, QSet<const QDeclarativeType *> > qmlTypesByCppName;
138 static QHash<QByteArray, QByteArray> cppToId;
140 /* Takes a C++ type name, such as Qt::LayoutDirection or QString and
141 maps it to how it should appear in the description file.
143 These names need to be unique globally, so we don't change the C++ symbol's
144 name much. It is mostly used to for explicit translations such as
145 QString->string and translations for extended QML objects.
147 QByteArray convertToId(const QByteArray &cppName)
149 return cppToId.value(cppName, cppName);
152 QSet<const QMetaObject *> collectReachableMetaObjects(const QList<QDeclarativeType *> &skip = QList<QDeclarativeType *>())
154 QSet<const QMetaObject *> metas;
155 metas.insert(FriendlyQObject::qtMeta());
157 QHash<QByteArray, QSet<QByteArray> > extensions;
158 foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
159 qmlTypesByCppName[ty->metaObject()->className()].insert(ty);
160 if (ty->isExtendedType()) {
161 extensions[ty->typeName()].insert(ty->metaObject()->className());
163 collectReachableMetaObjects(ty, &metas);
166 // Adjust exports of the base object if there are extensions.
167 // For each export of a base object there can be a single extension object overriding it.
168 // Example: QDeclarativeGraphicsWidget overrides the QtQuick/QGraphicsWidget export
169 // of QGraphicsWidget.
170 foreach (const QByteArray &baseCpp, extensions.keys()) {
171 QSet<const QDeclarativeType *> baseExports = qmlTypesByCppName.value(baseCpp);
173 const QSet<QByteArray> extensionCppNames = extensions.value(baseCpp);
174 foreach (const QByteArray &extensionCppName, extensionCppNames) {
175 const QSet<const QDeclarativeType *> extensionExports = qmlTypesByCppName.value(extensionCppName);
177 // remove extension exports from base imports
178 // unfortunately the QDeclarativeType pointers don't match, so can't use QSet::substract
179 QSet<const QDeclarativeType *> newBaseExports;
180 foreach (const QDeclarativeType *baseExport, baseExports) {
182 foreach (const QDeclarativeType *extensionExport, extensionExports) {
183 if (baseExport->qmlTypeName() == extensionExport->qmlTypeName()
184 && baseExport->majorVersion() == extensionExport->majorVersion()
185 && baseExport->minorVersion() == extensionExport->minorVersion()) {
191 newBaseExports.insert(baseExport);
193 baseExports = newBaseExports;
195 qmlTypesByCppName[baseCpp] = baseExports;
198 // find even more QMetaObjects by instantiating QML types and running
199 // over the instances
200 foreach (QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
201 if (skip.contains(ty))
203 if (ty->isExtendedType())
205 if (!ty->isCreatable())
207 if (ty->typeName() == "QDeclarativeComponent")
210 QString tyName = ty->qmlTypeName();
211 tyName = tyName.mid(tyName.lastIndexOf(QLatin1Char('/')) + 1);
212 if (tyName.isEmpty())
215 inObjectInstantiation = tyName;
216 QObject *object = ty->create();
217 inObjectInstantiation.clear();
220 collectReachableMetaObjects(object, &metas);
222 qWarning() << "Could not create" << tyName;
231 QmlStreamWriter *qml;
232 QString relocatableModuleUri;
235 Dumper(QmlStreamWriter *qml) : qml(qml) {}
237 void setRelocatableModuleUri(const QString &uri)
239 relocatableModuleUri = uri;
242 void dump(const QMetaObject *meta)
244 qml->writeStartObject("Component");
246 QByteArray id = convertToId(meta->className());
247 qml->writeScriptBinding(QLatin1String("name"), enquote(id));
249 for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
250 QMetaClassInfo classInfo = meta->classInfo(index);
251 if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
252 qml->writeScriptBinding(QLatin1String("defaultProperty"), enquote(QLatin1String(classInfo.value())));
257 if (meta->superClass())
258 qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass()->className())));
260 QSet<const QDeclarativeType *> qmlTypes = qmlTypesByCppName.value(meta->className());
261 if (!qmlTypes.isEmpty()) {
262 QHash<QString, const QDeclarativeType *> exports;
264 foreach (const QDeclarativeType *qmlTy, qmlTypes) {
265 QString qmlTyName = qmlTy->qmlTypeName();
266 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
267 qmlTyName.remove(0, relocatableModuleUri.size() + 1);
269 if (qmlTyName.startsWith("./")) {
270 qmlTyName.remove(0, 2);
272 if (qmlTyName.startsWith("/")) {
273 qmlTyName.remove(0, 1);
275 const QString exportString = enquote(
276 QString("%1 %2.%3").arg(
278 QString::number(qmlTy->majorVersion()),
279 QString::number(qmlTy->minorVersion())));
280 exports.insert(exportString, qmlTy);
283 // ensure exports are sorted and don't change order when the plugin is dumped again
284 QStringList exportStrings = exports.keys();
285 qSort(exportStrings);
286 qml->writeArrayBinding(QLatin1String("exports"), exportStrings);
288 // write meta object revisions unless they're all zero
289 QStringList metaObjectRevisions;
290 bool shouldWriteMetaObjectRevisions = false;
291 foreach (const QString &exportString, exportStrings) {
292 int metaObjectRevision = exports[exportString]->metaObjectRevision();
293 if (metaObjectRevision != 0)
294 shouldWriteMetaObjectRevisions = true;
295 metaObjectRevisions += QString::number(metaObjectRevision);
297 if (shouldWriteMetaObjectRevisions)
298 qml->writeArrayBinding(QLatin1String("exportMetaObjectRevisions"), metaObjectRevisions);
300 if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
301 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
302 convertToId(attachedType->className())));
306 for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
307 dump(meta->enumerator(index));
309 for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
310 dump(meta->property(index));
312 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
313 dump(meta->method(index));
315 qml->writeEndObject();
318 void writeEasingCurve()
320 qml->writeStartObject("Component");
321 qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
322 qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
323 qml->writeEndObject();
327 static QString enquote(const QString &string)
329 return QString("\"%1\"").arg(string);
332 /* Removes pointer and list annotations from a type name, returning
333 what was removed in isList and isPointer
335 static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
337 static QByteArray declListPrefix = "QDeclarativeListProperty<";
339 if (typeName->endsWith('*')) {
341 typeName->truncate(typeName->length() - 1);
342 removePointerAndList(typeName, isList, isPointer);
343 } else if (typeName->startsWith(declListPrefix)) {
345 typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
346 *typeName = typeName->mid(declListPrefix.size());
347 removePointerAndList(typeName, isList, isPointer);
350 *typeName = convertToId(*typeName);
353 void writeTypeProperties(QByteArray typeName, bool isWritable)
355 bool isList = false, isPointer = false;
356 removePointerAndList(&typeName, &isList, &isPointer);
358 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
360 qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
362 qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
364 qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
367 void dump(const QMetaProperty &prop)
369 qml->writeStartObject("Property");
371 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
372 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
373 if (int revision = prop.revision())
374 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
376 writeTypeProperties(prop.typeName(), prop.isWritable());
378 qml->writeEndObject();
381 void dump(const QMetaMethod &meth)
383 if (meth.methodType() == QMetaMethod::Signal) {
384 if (meth.access() != QMetaMethod::Protected)
385 return; // nothing to do.
386 } else if (meth.access() != QMetaMethod::Public) {
387 return; // nothing to do.
390 QByteArray name = meth.signature();
391 int lparenIndex = name.indexOf('(');
392 if (lparenIndex == -1) {
393 return; // invalid signature
395 name = name.left(lparenIndex);
397 if (meth.methodType() == QMetaMethod::Signal)
398 qml->writeStartObject(QLatin1String("Signal"));
400 qml->writeStartObject(QLatin1String("Method"));
402 qml->writeScriptBinding(QLatin1String("name"), enquote(name));
404 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
405 if (int revision = meth.revision())
406 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
409 const QString typeName = convertToId(meth.typeName());
410 if (! typeName.isEmpty())
411 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
413 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
414 QByteArray argName = meth.parameterNames().at(i);
416 qml->writeStartObject(QLatin1String("Parameter"));
417 if (! argName.isEmpty())
418 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
419 writeTypeProperties(meth.parameterTypes().at(i), true);
420 qml->writeEndObject();
423 qml->writeEndObject();
426 void dump(const QMetaEnum &e)
428 qml->writeStartObject(QLatin1String("Enum"));
429 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
431 QList<QPair<QString, QString> > namesValues;
432 for (int index = 0; index < e.keyCount(); ++index) {
433 namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
436 qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
437 qml->writeEndObject();
443 EXIT_INVALIDARGUMENTS = 1,
449 void sigSegvHandler(int) {
450 fprintf(stderr, "Error: SEGV\n");
451 if (!currentProperty.isEmpty())
452 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
453 if (!inObjectInstantiation.isEmpty())
454 fprintf(stderr, "While instantiating the object '%s'.\n", inObjectInstantiation.toLatin1().constData());
459 void printUsage(const QString &appName)
461 qWarning() << qPrintable(QString(
462 "Usage: %1 [-v] [-notrelocatable] module.uri version [module/import/path]\n"
463 " %1 [-v] -path path/to/qmldir/directory [version]\n"
464 " %1 [-v] -builtins\n"
465 "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
469 int main(int argc, char *argv[])
472 // qmldump may crash, but we don't want any crash handlers to pop up
473 // therefore we intercept the segfault and just exit() ourselves
474 struct sigaction sigAction;
476 sigemptyset(&sigAction.sa_mask);
477 sigAction.sa_handler = &sigSegvHandler;
478 sigAction.sa_flags = 0;
480 sigaction(SIGSEGV, &sigAction, 0);
484 // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
485 QtSimulatorPrivate::SimulatorConnection::createStubInstance();
487 QApplication app(argc, argv);
488 const QStringList args = app.arguments();
489 const QString appName = QFileInfo(app.applicationFilePath()).baseName();
490 if (args.size() < 2) {
492 return EXIT_INVALIDARGUMENTS;
495 QString pluginImportUri;
496 QString pluginImportVersion;
497 bool relocatable = true;
498 enum Action { Uri, Path, Builtins };
501 QStringList positionalArgs;
502 foreach (const QString &arg, args) {
503 if (!arg.startsWith(QLatin1Char('-'))) {
504 positionalArgs.append(arg);
508 if (arg == QLatin1String("--notrelocatable")
509 || arg == QLatin1String("-notrelocatable")) {
511 } else if (arg == QLatin1String("--path")
512 || arg == QLatin1String("-path")) {
514 } else if (arg == QLatin1String("--builtins")
515 || arg == QLatin1String("-builtins")) {
517 } else if (arg == QLatin1String("-v")) {
520 qWarning() << "Invalid argument: " << arg;
521 return EXIT_INVALIDARGUMENTS;
526 if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
527 qWarning() << "Incorrect number of positional arguments";
528 return EXIT_INVALIDARGUMENTS;
530 pluginImportUri = positionalArgs[1];
531 pluginImportVersion = positionalArgs[2];
532 if (positionalArgs.size() >= 4)
533 pluginImportPath = positionalArgs[3];
534 } else if (action == Path) {
535 if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
536 qWarning() << "Incorrect number of positional arguments";
537 return EXIT_INVALIDARGUMENTS;
539 pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
540 if (positionalArgs.size() == 3)
541 pluginImportVersion = positionalArgs[2];
542 } else if (action == Builtins) {
543 if (positionalArgs.size() != 1) {
544 qWarning() << "Incorrect number of positional arguments";
545 return EXIT_INVALIDARGUMENTS;
550 QDeclarativeEngine engine;
551 if (!pluginImportPath.isEmpty()) {
552 QDir cur = QDir::current();
553 cur.cd(pluginImportPath);
554 pluginImportPath = cur.absolutePath();
555 QDir::setCurrent(pluginImportPath);
556 engine.addImportPath(pluginImportPath);
559 // load the QtQuick 1 plugin
561 QByteArray code("import QtQuick 1.0\nQtObject {}");
562 QDeclarativeComponent c(&engine);
563 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/loadqtquick1.qml"));
565 if (!c.errors().isEmpty()) {
566 foreach (const QDeclarativeError &error, c.errors())
567 qWarning() << error.toString();
568 return EXIT_IMPORTERROR;
572 // find all QMetaObjects reachable from the builtin module
573 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects();
574 QList<QDeclarativeType *> defaultTypes = QDeclarativeMetaType::qmlTypes();
576 // add some otherwise unreachable QMetaObjects
577 defaultReachable.insert(&QSGMouseEvent::staticMetaObject);
578 // QSGKeyEvent, QSGPinchEvent, QSGDragTargetEvent are not exported
580 // this will hold the meta objects we want to dump information of
581 QSet<const QMetaObject *> metas;
583 if (action == Builtins) {
584 metas = defaultReachable;
586 // find a valid QtQuick import
587 QByteArray importCode;
588 QDeclarativeType *qtObjectType = QDeclarativeMetaType::qmlType(&QObject::staticMetaObject);
590 qWarning() << "Could not find QtObject type";
591 importCode = QByteArray("import QtQuick 2.0\n");
593 QString module = qtObjectType->qmlTypeName();
594 module = module.mid(0, module.lastIndexOf(QLatin1Char('/')));
595 importCode = QString("import %1 %2.%3\n").arg(module,
596 QString::number(qtObjectType->majorVersion()),
597 QString::number(qtObjectType->minorVersion())).toUtf8();
600 // find all QMetaObjects reachable when the specified module is imported
601 if (action != Path) {
602 importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
604 // pluginImportVersion can be empty
605 importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
608 // create a component with these imports to make sure the imports are valid
609 // and to populate the declarative meta type system
611 QByteArray code = importCode;
612 code += "QtObject {}";
613 QDeclarativeComponent c(&engine);
615 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
617 if (!c.errors().isEmpty()) {
618 foreach (const QDeclarativeError &error, c.errors())
619 qWarning() << error.toString();
620 return EXIT_IMPORTERROR;
624 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(defaultTypes);
625 candidates.subtract(defaultReachable);
627 // Also eliminate meta objects with the same classname.
628 // This is required because extended objects seem not to share
629 // a single meta object instance.
630 QSet<QByteArray> defaultReachableNames;
631 foreach (const QMetaObject *mo, defaultReachable)
632 defaultReachableNames.insert(QByteArray(mo->className()));
633 foreach (const QMetaObject *mo, candidates) {
634 if (!defaultReachableNames.contains(mo->className()))
639 // setup static rewrites of type names
640 cppToId.insert("QString", "string");
641 cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
643 // start dumping data
645 QmlStreamWriter qml(&bytes);
647 qml.writeStartDocument();
648 qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 1);
650 "// This file describes the plugin-supplied types contained in the library.\n"
651 "// It is used for QML tooling purposes only.\n"
653 qml.writeStartObject("Module");
655 // put the metaobjects into a map so they are always dumped in the same order
656 QMap<QString, const QMetaObject *> nameToMeta;
657 foreach (const QMetaObject *meta, metas)
658 nameToMeta.insert(convertToId(meta->className()), meta);
662 dumper.setRelocatableModuleUri(pluginImportUri);
663 foreach (const QMetaObject *meta, nameToMeta) {
667 // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
668 // properties using the QEasingCurve type get useful type information.
669 if (pluginImportUri.isEmpty())
670 dumper.writeEasingCurve();
672 qml.writeEndObject();
673 qml.writeEndDocument();
675 std::cout << bytes.constData();
677 // workaround to avoid crashes on exit
679 timer.setSingleShot(true);
680 timer.setInterval(0);
681 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));