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 QByteArray tyName = ty->qmlTypeName();
208 tyName = tyName.mid(tyName.lastIndexOf('/') + 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()) {
261 foreach (const QDeclarativeType *qmlTy, qmlTypes) {
262 QString qmlTyName = qmlTy->qmlTypeName();
263 // some qmltype names are missing the actual names, ignore that import
264 if (qmlTyName.endsWith('/'))
266 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
267 qmlTyName.remove(0, relocatableModuleUri.size() + 1);
269 if (qmlTyName.startsWith("./")) {
270 qmlTyName.remove(0, 2);
272 exports += enquote(QString("%1 %2.%3").arg(
274 QString::number(qmlTy->majorVersion()),
275 QString::number(qmlTy->minorVersion())));
278 // ensure exports are sorted and don't change order when the plugin is dumped again
279 exports.removeDuplicates();
282 qml->writeArrayBinding(QLatin1String("exports"), exports);
284 if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
285 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
286 convertToId(attachedType->className())));
290 for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
291 dump(meta->enumerator(index));
293 for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
294 dump(meta->property(index));
296 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
297 dump(meta->method(index));
299 qml->writeEndObject();
302 void writeEasingCurve()
304 qml->writeStartObject("Component");
305 qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
306 qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
307 qml->writeEndObject();
311 static QString enquote(const QString &string)
313 return QString("\"%1\"").arg(string);
316 /* Removes pointer and list annotations from a type name, returning
317 what was removed in isList and isPointer
319 static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
321 static QByteArray declListPrefix = "QDeclarativeListProperty<";
323 if (typeName->endsWith('*')) {
325 typeName->truncate(typeName->length() - 1);
326 removePointerAndList(typeName, isList, isPointer);
327 } else if (typeName->startsWith(declListPrefix)) {
329 typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
330 *typeName = typeName->mid(declListPrefix.size());
331 removePointerAndList(typeName, isList, isPointer);
334 *typeName = convertToId(*typeName);
337 void writeTypeProperties(QByteArray typeName, bool isWritable)
339 bool isList = false, isPointer = false;
340 removePointerAndList(&typeName, &isList, &isPointer);
342 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
344 qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
346 qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
348 qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
351 void dump(const QMetaProperty &prop)
353 qml->writeStartObject("Property");
355 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
356 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
357 if (int revision = prop.revision())
358 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
360 writeTypeProperties(prop.typeName(), prop.isWritable());
362 qml->writeEndObject();
365 void dump(const QMetaMethod &meth)
367 if (meth.methodType() == QMetaMethod::Signal) {
368 if (meth.access() != QMetaMethod::Protected)
369 return; // nothing to do.
370 } else if (meth.access() != QMetaMethod::Public) {
371 return; // nothing to do.
374 QByteArray name = meth.signature();
375 int lparenIndex = name.indexOf('(');
376 if (lparenIndex == -1) {
377 return; // invalid signature
379 name = name.left(lparenIndex);
381 if (meth.methodType() == QMetaMethod::Signal)
382 qml->writeStartObject(QLatin1String("Signal"));
384 qml->writeStartObject(QLatin1String("Method"));
386 qml->writeScriptBinding(QLatin1String("name"), enquote(name));
388 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
389 if (int revision = meth.revision())
390 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
393 const QString typeName = convertToId(meth.typeName());
394 if (! typeName.isEmpty())
395 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
397 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
398 QByteArray argName = meth.parameterNames().at(i);
400 qml->writeStartObject(QLatin1String("Parameter"));
401 if (! argName.isEmpty())
402 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
403 writeTypeProperties(meth.parameterTypes().at(i), true);
404 qml->writeEndObject();
407 qml->writeEndObject();
410 void dump(const QMetaEnum &e)
412 qml->writeStartObject(QLatin1String("Enum"));
413 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
415 QList<QPair<QString, QString> > namesValues;
416 for (int index = 0; index < e.keyCount(); ++index) {
417 namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
420 qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
421 qml->writeEndObject();
427 EXIT_INVALIDARGUMENTS = 1,
433 void sigSegvHandler(int) {
434 fprintf(stderr, "Error: SEGV\n");
435 if (!currentProperty.isEmpty())
436 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
437 if (!inObjectInstantiation.isEmpty())
438 fprintf(stderr, "While instantiating the object '%s'.\n", inObjectInstantiation.toLatin1().constData());
443 void printUsage(const QString &appName)
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(
453 int main(int argc, char *argv[])
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;
460 sigemptyset(&sigAction.sa_mask);
461 sigAction.sa_handler = &sigSegvHandler;
462 sigAction.sa_flags = 0;
464 sigaction(SIGSEGV, &sigAction, 0);
468 // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
469 QtSimulatorPrivate::SimulatorConnection::createStubInstance();
471 QApplication app(argc, argv);
472 const QStringList args = app.arguments();
473 const QString appName = QFileInfo(app.applicationFilePath()).baseName();
474 if (args.size() < 2) {
476 return EXIT_INVALIDARGUMENTS;
479 QString pluginImportUri;
480 QString pluginImportVersion;
481 bool relocatable = true;
482 enum Action { Uri, Path, Builtins };
485 QStringList positionalArgs;
486 foreach (const QString &arg, args) {
487 if (!arg.startsWith(QLatin1Char('-'))) {
488 positionalArgs.append(arg);
492 if (arg == QLatin1String("--notrelocatable")
493 || arg == QLatin1String("-notrelocatable")) {
495 } else if (arg == QLatin1String("--path")
496 || arg == QLatin1String("-path")) {
498 } else if (arg == QLatin1String("--builtins")
499 || arg == QLatin1String("-builtins")) {
501 } else if (arg == QLatin1String("-v")) {
504 qWarning() << "Invalid argument: " << arg;
505 return EXIT_INVALIDARGUMENTS;
510 if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
511 qWarning() << "Incorrect number of positional arguments";
512 return EXIT_INVALIDARGUMENTS;
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;
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;
534 QDeclarativeEngine engine;
535 if (!pluginImportPath.isEmpty()) {
536 QDir cur = QDir::current();
537 cur.cd(pluginImportPath);
538 pluginImportPath = cur.absolutePath();
539 QDir::setCurrent(pluginImportPath);
540 engine.addImportPath(pluginImportPath);
543 // load the QtQuick 1 plugin
545 QByteArray code("import QtQuick 1.0\nQtObject {}");
546 QDeclarativeComponent c(&engine);
547 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/loadqtquick1.qml"));
549 if (!c.errors().isEmpty()) {
550 foreach (const QDeclarativeError &error, c.errors())
551 qWarning() << error.toString();
552 return EXIT_IMPORTERROR;
556 // find all QMetaObjects reachable from the builtin module
557 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects();
558 QList<QDeclarativeType *> defaultTypes = QDeclarativeMetaType::qmlTypes();
560 // this will hold the meta objects we want to dump information of
561 QSet<const QMetaObject *> metas;
563 if (action == Builtins) {
564 metas = defaultReachable;
566 // find a valid QtQuick import
567 QByteArray importCode;
568 QDeclarativeType *qtObjectType = QDeclarativeMetaType::qmlType(&QObject::staticMetaObject);
570 qWarning() << "Could not find QtObject type";
571 importCode = QByteArray("import QtQuick 2.0\n");
573 QByteArray module = qtObjectType->qmlTypeName();
574 module = module.mid(0, module.lastIndexOf('/'));
575 importCode = QString("import %1 %2.%3\n").arg(module,
576 QString::number(qtObjectType->majorVersion()),
577 QString::number(qtObjectType->minorVersion())).toUtf8();
580 // find all QMetaObjects reachable when the specified module is imported
581 if (action != Path) {
582 importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
584 // pluginImportVersion can be empty
585 importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
588 // create a component with these imports to make sure the imports are valid
589 // and to populate the declarative meta type system
591 QByteArray code = importCode;
592 code += "QtObject {}";
593 QDeclarativeComponent c(&engine);
595 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
597 if (!c.errors().isEmpty()) {
598 foreach (const QDeclarativeError &error, c.errors())
599 qWarning() << error.toString();
600 return EXIT_IMPORTERROR;
604 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(defaultTypes);
605 candidates.subtract(defaultReachable);
607 // Also eliminate meta objects with the same classname.
608 // This is required because extended objects seem not to share
609 // a single meta object instance.
610 QSet<QByteArray> defaultReachableNames;
611 foreach (const QMetaObject *mo, defaultReachable)
612 defaultReachableNames.insert(QByteArray(mo->className()));
613 foreach (const QMetaObject *mo, candidates) {
614 if (!defaultReachableNames.contains(mo->className()))
619 // setup static rewrites of type names
620 cppToId.insert("QString", "string");
621 cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
623 // start dumping data
625 QmlStreamWriter qml(&bytes);
627 qml.writeStartDocument();
628 qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 1);
630 "// This file describes the plugin-supplied types contained in the library.\n"
631 "// It is used for QML tooling purposes only.\n"
633 qml.writeStartObject("Module");
635 // put the metaobjects into a map so they are always dumped in the same order
636 QMap<QString, const QMetaObject *> nameToMeta;
637 foreach (const QMetaObject *meta, metas)
638 nameToMeta.insert(convertToId(meta->className()), meta);
642 dumper.setRelocatableModuleUri(pluginImportUri);
643 foreach (const QMetaObject *meta, nameToMeta) {
647 // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
648 // properties using the QEasingCurve type get useful type information.
649 if (pluginImportUri.isEmpty())
650 dumper.writeEasingCurve();
652 qml.writeEndObject();
653 qml.writeEndDocument();
655 std::cout << bytes.constData();
657 // workaround to avoid crashes on exit
659 timer.setSingleShot(true);
660 timer.setInterval(0);
661 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));