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 <QtGui/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 QString &importCode, QDeclarativeEngine *engine)
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 (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
198 if (ty->isExtendedType())
200 if (!ty->isCreatable())
202 if (ty->typeName() == "QDeclarativeComponent")
205 QByteArray tyName = ty->qmlTypeName();
206 tyName = tyName.mid(tyName.lastIndexOf('/') + 1);
207 if (tyName.isEmpty())
210 QByteArray code = importCode.toUtf8();
214 QDeclarativeComponent c(engine);
215 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typeinstance.qml"));
217 inObjectInstantiation = tyName;
218 QObject *object = c.create();
219 inObjectInstantiation.clear();
222 collectReachableMetaObjects(object, &metas);
224 qWarning() << "Could not create" << tyName << ":" << c.errorString();
233 QmlStreamWriter *qml;
234 QString relocatableModuleUri;
237 Dumper(QmlStreamWriter *qml) : qml(qml) {}
239 void setRelocatableModuleUri(const QString &uri)
241 relocatableModuleUri = uri;
244 void dump(const QMetaObject *meta)
246 qml->writeStartObject("Component");
248 QByteArray id = convertToId(meta->className());
249 qml->writeScriptBinding(QLatin1String("name"), enquote(id));
251 for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
252 QMetaClassInfo classInfo = meta->classInfo(index);
253 if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
254 qml->writeScriptBinding(QLatin1String("defaultProperty"), enquote(QLatin1String(classInfo.value())));
259 if (meta->superClass())
260 qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass()->className())));
262 QSet<const QDeclarativeType *> qmlTypes = qmlTypesByCppName.value(meta->className());
263 if (!qmlTypes.isEmpty()) {
266 foreach (const QDeclarativeType *qmlTy, qmlTypes) {
267 QString qmlTyName = qmlTy->qmlTypeName();
268 // some qmltype names are missing the actual names, ignore that import
269 if (qmlTyName.endsWith('/'))
271 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
272 qmlTyName.remove(0, relocatableModuleUri.size() + 1);
274 if (qmlTyName.startsWith("./")) {
275 qmlTyName.remove(0, 2);
277 exports += enquote(QString("%1 %2.%3").arg(
279 QString::number(qmlTy->majorVersion()),
280 QString::number(qmlTy->minorVersion())));
283 // ensure exports are sorted and don't change order when the plugin is dumped again
284 exports.removeDuplicates();
287 qml->writeArrayBinding(QLatin1String("exports"), exports);
289 if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
290 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
291 convertToId(attachedType->className())));
295 for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
296 dump(meta->enumerator(index));
298 for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
299 dump(meta->property(index));
301 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
302 dump(meta->method(index));
304 qml->writeEndObject();
307 void writeEasingCurve()
309 qml->writeStartObject("Component");
310 qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
311 qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
312 qml->writeEndObject();
316 static QString enquote(const QString &string)
318 return QString("\"%1\"").arg(string);
321 /* Removes pointer and list annotations from a type name, returning
322 what was removed in isList and isPointer
324 static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
326 static QByteArray declListPrefix = "QDeclarativeListProperty<";
328 if (typeName->endsWith('*')) {
330 typeName->truncate(typeName->length() - 1);
331 removePointerAndList(typeName, isList, isPointer);
332 } else if (typeName->startsWith(declListPrefix)) {
334 typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
335 *typeName = typeName->mid(declListPrefix.size());
336 removePointerAndList(typeName, isList, isPointer);
339 *typeName = convertToId(*typeName);
342 void writeTypeProperties(QByteArray typeName, bool isWritable)
344 bool isList = false, isPointer = false;
345 removePointerAndList(&typeName, &isList, &isPointer);
347 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
349 qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
351 qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
353 qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
356 void dump(const QMetaProperty &prop)
358 qml->writeStartObject("Property");
360 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
361 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
362 if (int revision = prop.revision())
363 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
365 writeTypeProperties(prop.typeName(), prop.isWritable());
367 qml->writeEndObject();
370 void dump(const QMetaMethod &meth)
372 if (meth.methodType() == QMetaMethod::Signal) {
373 if (meth.access() != QMetaMethod::Protected)
374 return; // nothing to do.
375 } else if (meth.access() != QMetaMethod::Public) {
376 return; // nothing to do.
379 QByteArray name = meth.signature();
380 int lparenIndex = name.indexOf('(');
381 if (lparenIndex == -1) {
382 return; // invalid signature
384 name = name.left(lparenIndex);
386 if (meth.methodType() == QMetaMethod::Signal)
387 qml->writeStartObject(QLatin1String("Signal"));
389 qml->writeStartObject(QLatin1String("Method"));
391 qml->writeScriptBinding(QLatin1String("name"), enquote(name));
393 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
394 if (int revision = meth.revision())
395 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
398 const QString typeName = convertToId(meth.typeName());
399 if (! typeName.isEmpty())
400 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
402 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
403 QByteArray argName = meth.parameterNames().at(i);
405 qml->writeStartObject(QLatin1String("Parameter"));
406 if (! argName.isEmpty())
407 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
408 writeTypeProperties(meth.parameterTypes().at(i), true);
409 qml->writeEndObject();
412 qml->writeEndObject();
415 void dump(const QMetaEnum &e)
417 qml->writeStartObject(QLatin1String("Enum"));
418 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
420 QList<QPair<QString, QString> > namesValues;
421 for (int index = 0; index < e.keyCount(); ++index) {
422 namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
425 qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
426 qml->writeEndObject();
432 EXIT_INVALIDARGUMENTS = 1,
438 void sigSegvHandler(int) {
439 fprintf(stderr, "Error: SEGV\n");
440 if (!currentProperty.isEmpty())
441 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
442 if (!inObjectInstantiation.isEmpty())
443 fprintf(stderr, "While instantiating the object '%s'.\n", inObjectInstantiation.toLatin1().constData());
448 void printUsage(const QString &appName)
450 qWarning() << qPrintable(QString(
451 "Usage: %1 [-v] [-notrelocatable] module.uri version [module/import/path]\n"
452 " %1 [-v] -path path/to/qmldir/directory [version]\n"
453 " %1 [-v] -builtins\n"
454 "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
458 int main(int argc, char *argv[])
461 // qmldump may crash, but we don't want any crash handlers to pop up
462 // therefore we intercept the segfault and just exit() ourselves
463 struct sigaction sigAction;
465 sigemptyset(&sigAction.sa_mask);
466 sigAction.sa_handler = &sigSegvHandler;
467 sigAction.sa_flags = 0;
469 sigaction(SIGSEGV, &sigAction, 0);
473 // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
474 QtSimulatorPrivate::SimulatorConnection::createStubInstance();
476 QApplication app(argc, argv);
477 const QStringList args = app.arguments();
478 const QString appName = QFileInfo(app.applicationFilePath()).baseName();
479 if (args.size() < 2) {
481 return EXIT_INVALIDARGUMENTS;
484 QString pluginImportUri;
485 QString pluginImportVersion;
486 bool relocatable = true;
487 enum Action { Uri, Path, Builtins };
490 QStringList positionalArgs;
491 foreach (const QString &arg, args) {
492 if (!arg.startsWith(QLatin1Char('-'))) {
493 positionalArgs.append(arg);
497 if (arg == QLatin1String("--notrelocatable")
498 || arg == QLatin1String("-notrelocatable")) {
500 } else if (arg == QLatin1String("--path")
501 || arg == QLatin1String("-path")) {
503 } else if (arg == QLatin1String("--builtins")
504 || arg == QLatin1String("-builtins")) {
506 } else if (arg == QLatin1String("-v")) {
509 qWarning() << "Invalid argument: " << arg;
510 return EXIT_INVALIDARGUMENTS;
515 if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
516 qWarning() << "Incorrect number of positional arguments";
517 return EXIT_INVALIDARGUMENTS;
519 pluginImportUri = positionalArgs[1];
520 pluginImportVersion = positionalArgs[2];
521 if (positionalArgs.size() >= 4)
522 pluginImportPath = positionalArgs[3];
523 } else if (action == Path) {
524 if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
525 qWarning() << "Incorrect number of positional arguments";
526 return EXIT_INVALIDARGUMENTS;
528 pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
529 if (positionalArgs.size() == 3)
530 pluginImportVersion = positionalArgs[2];
531 } else if (action == Builtins) {
532 if (positionalArgs.size() != 1) {
533 qWarning() << "Incorrect number of positional arguments";
534 return EXIT_INVALIDARGUMENTS;
539 QDeclarativeEngine engine;
540 if (!pluginImportPath.isEmpty()) {
541 QDir cur = QDir::current();
542 cur.cd(pluginImportPath);
543 pluginImportPath = cur.absolutePath();
544 QDir::setCurrent(pluginImportPath);
545 engine.addImportPath(pluginImportPath);
548 // find all QMetaObjects reachable from the builtin module
549 QByteArray importCode("import QtQuick 2.0\n");
550 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(importCode, &engine);
552 // this will hold the meta objects we want to dump information of
553 QSet<const QMetaObject *> metas;
555 if (action == Builtins) {
556 metas = defaultReachable;
558 // find all QMetaObjects reachable when the specified module is imported
559 if (action != Path) {
560 importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
562 // pluginImportVersion can be empty
563 importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
566 // create a component with these imports to make sure the imports are valid
567 // and to populate the declarative meta type system
569 QByteArray code = importCode;
570 code += "QtObject {}";
571 QDeclarativeComponent c(&engine);
573 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
575 if (!c.errors().isEmpty()) {
576 foreach (const QDeclarativeError &error, c.errors())
577 qWarning() << error.toString();
578 return EXIT_IMPORTERROR;
582 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(importCode, &engine);
583 candidates.subtract(defaultReachable);
585 // Also eliminate meta objects with the same classname.
586 // This is required because extended objects seem not to share
587 // a single meta object instance.
588 QSet<QByteArray> defaultReachableNames;
589 foreach (const QMetaObject *mo, defaultReachable)
590 defaultReachableNames.insert(QByteArray(mo->className()));
591 foreach (const QMetaObject *mo, candidates) {
592 if (!defaultReachableNames.contains(mo->className()))
597 // setup static rewrites of type names
598 cppToId.insert("QString", "string");
599 cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
601 // start dumping data
603 QmlStreamWriter qml(&bytes);
605 qml.writeStartDocument();
606 qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 1);
608 "// This file describes the plugin-supplied types contained in the library.\n"
609 "// It is used for QML tooling purposes only.\n"
611 qml.writeStartObject("Module");
613 // put the metaobjects into a map so they are always dumped in the same order
614 QMap<QString, const QMetaObject *> nameToMeta;
615 foreach (const QMetaObject *meta, metas)
616 nameToMeta.insert(convertToId(meta->className()), meta);
620 dumper.setRelocatableModuleUri(pluginImportUri);
621 foreach (const QMetaObject *meta, nameToMeta) {
625 // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
626 // properties using the QEasingCurve type get useful type information.
627 if (pluginImportUri.isEmpty())
628 dumper.writeEasingCurve();
630 qml.writeEndObject();
631 qml.writeEndDocument();
633 std::cout << bytes.constData();
635 // workaround to avoid crashes on exit
637 timer.setSingleShot(true);
638 timer.setInterval(0);
639 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));