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/QDeclarativeView>
47 #include <QtGui/QApplication>
49 #include <QtCore/QSet>
50 #include <QtCore/QMetaObject>
51 #include <QtCore/QMetaProperty>
52 #include <QtCore/QDebug>
53 #include <QtCore/private/qobject_p.h>
54 #include <QtCore/private/qmetaobject_p.h>
58 #include "qmlstreamwriter.h"
61 #include <QtGui/private/qsimulatorconnection_p.h>
68 QString pluginImportPath;
71 QString currentProperty;
72 QString inObjectInstantiation;
74 void collectReachableMetaObjects(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
76 if (! meta || metas->contains(meta))
79 // dynamic meta objects break things badly, so just ignore them
80 const QMetaObjectPrivate *mop = reinterpret_cast<const QMetaObjectPrivate *>(meta->d.data);
81 if (!(mop->flags & DynamicMetaObject))
84 collectReachableMetaObjects(meta->superClass(), metas);
87 void collectReachableMetaObjects(QObject *object, QSet<const QMetaObject *> *metas)
92 const QMetaObject *meta = object->metaObject();
94 qDebug() << "Processing object" << meta->className();
95 collectReachableMetaObjects(meta, metas);
97 for (int index = 0; index < meta->propertyCount(); ++index) {
98 QMetaProperty prop = meta->property(index);
99 if (QDeclarativeMetaType::isQObject(prop.userType())) {
101 qDebug() << " Processing property" << prop.name();
102 currentProperty = QString("%1::%2").arg(meta->className(), prop.name());
104 // if the property was not initialized during construction,
105 // accessing a member of oo is going to cause a segmentation fault
106 QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
107 if (oo && !metas->contains(oo->metaObject()))
108 collectReachableMetaObjects(oo, metas);
109 currentProperty.clear();
114 void collectReachableMetaObjects(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
116 collectReachableMetaObjects(ty->metaObject(), metas);
117 if (ty->attachedPropertiesType())
118 collectReachableMetaObjects(ty->attachedPropertiesType(), metas);
121 /* We want to add the MetaObject for 'Qt' to the list, this is a
122 simple way to access it.
124 class FriendlyQObject: public QObject
127 static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
130 /* When we dump a QMetaObject, we want to list all the types it is exported as.
131 To do this, we need to find the QDeclarativeTypes associated with this
134 static QHash<QByteArray, QSet<const QDeclarativeType *> > qmlTypesByCppName;
136 static QHash<QByteArray, QByteArray> cppToId;
138 /* Takes a C++ type name, such as Qt::LayoutDirection or QString and
139 maps it to how it should appear in the description file.
141 These names need to be unique globally, so we don't change the C++ symbol's
142 name much. It is mostly used to for explicit translations such as
143 QString->string and translations for extended QML objects.
145 QByteArray convertToId(const QByteArray &cppName)
147 return cppToId.value(cppName, cppName);
150 QSet<const QMetaObject *> collectReachableMetaObjects(const QString &importCode, QDeclarativeEngine *engine)
152 QSet<const QMetaObject *> metas;
153 metas.insert(FriendlyQObject::qtMeta());
155 QHash<QByteArray, QSet<QByteArray> > extensions;
156 foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
157 qmlTypesByCppName[ty->metaObject()->className()].insert(ty);
158 if (ty->isExtendedType()) {
159 extensions[ty->typeName()].insert(ty->metaObject()->className());
161 collectReachableMetaObjects(ty, &metas);
164 // Adjust exports of the base object if there are extensions.
165 // For each export of a base object there can be a single extension object overriding it.
166 // Example: QDeclarativeGraphicsWidget overrides the QtQuick/QGraphicsWidget export
167 // of QGraphicsWidget.
168 foreach (const QByteArray &baseCpp, extensions.keys()) {
169 QSet<const QDeclarativeType *> baseExports = qmlTypesByCppName.value(baseCpp);
171 const QSet<QByteArray> extensionCppNames = extensions.value(baseCpp);
172 foreach (const QByteArray &extensionCppName, extensionCppNames) {
173 const QSet<const QDeclarativeType *> extensionExports = qmlTypesByCppName.value(extensionCppName);
175 // remove extension exports from base imports
176 // unfortunately the QDeclarativeType pointers don't match, so can't use QSet::substract
177 QSet<const QDeclarativeType *> newBaseExports;
178 foreach (const QDeclarativeType *baseExport, baseExports) {
180 foreach (const QDeclarativeType *extensionExport, extensionExports) {
181 if (baseExport->qmlTypeName() == extensionExport->qmlTypeName()
182 && baseExport->majorVersion() == extensionExport->majorVersion()
183 && baseExport->minorVersion() == extensionExport->minorVersion()) {
189 newBaseExports.insert(baseExport);
191 baseExports = newBaseExports;
193 qmlTypesByCppName[baseCpp] = baseExports;
196 // find even more QMetaObjects by instantiating QML types and running
197 // over the instances
198 foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
199 if (ty->isExtendedType())
201 if (!ty->isCreatable())
203 if (ty->typeName() == "QDeclarativeComponent")
206 QByteArray tyName = ty->qmlTypeName();
207 tyName = tyName.mid(tyName.lastIndexOf('/') + 1);
208 if (tyName.isEmpty())
211 QByteArray code = importCode.toUtf8();
215 QDeclarativeComponent c(engine);
216 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typeinstance.qml"));
218 inObjectInstantiation = tyName;
219 QObject *object = c.create();
220 inObjectInstantiation.clear();
223 collectReachableMetaObjects(object, &metas);
225 qWarning() << "Could not create" << tyName << ":" << c.errorString();
234 QmlStreamWriter *qml;
235 QString relocatableModuleUri;
238 Dumper(QmlStreamWriter *qml) : qml(qml) {}
240 void setRelocatableModuleUri(const QString &uri)
242 relocatableModuleUri = uri;
245 void dump(const QMetaObject *meta)
247 qml->writeStartObject("Component");
249 QByteArray id = convertToId(meta->className());
250 qml->writeScriptBinding(QLatin1String("name"), enquote(id));
252 for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
253 QMetaClassInfo classInfo = meta->classInfo(index);
254 if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
255 qml->writeScriptBinding(QLatin1String("defaultProperty"), enquote(QLatin1String(classInfo.value())));
260 if (meta->superClass())
261 qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass()->className())));
263 QSet<const QDeclarativeType *> qmlTypes = qmlTypesByCppName.value(meta->className());
264 if (!qmlTypes.isEmpty()) {
267 foreach (const QDeclarativeType *qmlTy, qmlTypes) {
268 QString qmlTyName = qmlTy->qmlTypeName();
269 // some qmltype names are missing the actual names, ignore that import
270 if (qmlTyName.endsWith('/'))
272 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
273 qmlTyName.remove(0, relocatableModuleUri.size() + 1);
275 if (qmlTyName.startsWith("./")) {
276 qmlTyName.remove(0, 2);
278 exports += enquote(QString("%1 %2.%3").arg(
280 QString::number(qmlTy->majorVersion()),
281 QString::number(qmlTy->minorVersion())));
284 // ensure exports are sorted and don't change order when the plugin is dumped again
285 exports.removeDuplicates();
288 qml->writeArrayBinding(QLatin1String("exports"), exports);
290 if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
291 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
292 convertToId(attachedType->className())));
296 for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
297 dump(meta->enumerator(index));
299 for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
300 dump(meta->property(index));
302 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
303 dump(meta->method(index));
305 qml->writeEndObject();
308 void writeEasingCurve()
310 qml->writeStartObject("Component");
311 qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
312 qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
313 qml->writeEndObject();
317 static QString enquote(const QString &string)
319 return QString("\"%1\"").arg(string);
322 /* Removes pointer and list annotations from a type name, returning
323 what was removed in isList and isPointer
325 static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
327 static QByteArray declListPrefix = "QDeclarativeListProperty<";
329 if (typeName->endsWith('*')) {
331 typeName->truncate(typeName->length() - 1);
332 removePointerAndList(typeName, isList, isPointer);
333 } else if (typeName->startsWith(declListPrefix)) {
335 typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
336 *typeName = typeName->mid(declListPrefix.size());
337 removePointerAndList(typeName, isList, isPointer);
340 *typeName = convertToId(*typeName);
343 void writeTypeProperties(QByteArray typeName, bool isWritable)
345 bool isList = false, isPointer = false;
346 removePointerAndList(&typeName, &isList, &isPointer);
348 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
350 qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
352 qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
354 qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
357 void dump(const QMetaProperty &prop)
359 qml->writeStartObject("Property");
361 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
362 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
363 if (int revision = prop.revision())
364 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
366 writeTypeProperties(prop.typeName(), prop.isWritable());
368 qml->writeEndObject();
371 void dump(const QMetaMethod &meth)
373 if (meth.methodType() == QMetaMethod::Signal) {
374 if (meth.access() != QMetaMethod::Protected)
375 return; // nothing to do.
376 } else if (meth.access() != QMetaMethod::Public) {
377 return; // nothing to do.
380 QByteArray name = meth.signature();
381 int lparenIndex = name.indexOf('(');
382 if (lparenIndex == -1) {
383 return; // invalid signature
385 name = name.left(lparenIndex);
387 if (meth.methodType() == QMetaMethod::Signal)
388 qml->writeStartObject(QLatin1String("Signal"));
390 qml->writeStartObject(QLatin1String("Method"));
392 qml->writeScriptBinding(QLatin1String("name"), enquote(name));
394 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
395 if (int revision = meth.revision())
396 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
399 const QString typeName = convertToId(meth.typeName());
400 if (! typeName.isEmpty())
401 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
403 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
404 QByteArray argName = meth.parameterNames().at(i);
406 qml->writeStartObject(QLatin1String("Parameter"));
407 if (! argName.isEmpty())
408 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
409 writeTypeProperties(meth.parameterTypes().at(i), true);
410 qml->writeEndObject();
413 qml->writeEndObject();
416 void dump(const QMetaEnum &e)
418 qml->writeStartObject(QLatin1String("Enum"));
419 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
421 QList<QPair<QString, QString> > namesValues;
422 for (int index = 0; index < e.keyCount(); ++index) {
423 namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
426 qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
427 qml->writeEndObject();
433 EXIT_INVALIDARGUMENTS = 1,
439 void sigSegvHandler(int) {
440 fprintf(stderr, "Error: SEGV\n");
441 if (!currentProperty.isEmpty())
442 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
443 if (!inObjectInstantiation.isEmpty())
444 fprintf(stderr, "While instantiating the object '%s'.\n", inObjectInstantiation.toLatin1().constData());
449 void printUsage(const QString &appName)
451 qWarning() << qPrintable(QString(
452 "Usage: %1 [-v] [-notrelocatable] module.uri version [module/import/path]\n"
453 " %1 [-v] -path path/to/qmldir/directory [version]\n"
454 " %1 [-v] -builtins\n"
455 "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
459 int main(int argc, char *argv[])
462 // qmldump may crash, but we don't want any crash handlers to pop up
463 // therefore we intercept the segfault and just exit() ourselves
464 struct sigaction sigAction;
466 sigemptyset(&sigAction.sa_mask);
467 sigAction.sa_handler = &sigSegvHandler;
468 sigAction.sa_flags = 0;
470 sigaction(SIGSEGV, &sigAction, 0);
474 // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
475 QtSimulatorPrivate::SimulatorConnection::createStubInstance();
477 QApplication app(argc, argv);
478 const QStringList args = app.arguments();
479 const QString appName = QFileInfo(app.applicationFilePath()).baseName();
480 if (args.size() < 2) {
482 return EXIT_INVALIDARGUMENTS;
485 QString pluginImportUri;
486 QString pluginImportVersion;
487 bool relocatable = true;
488 enum Action { Uri, Path, Builtins };
491 QStringList positionalArgs;
492 foreach (const QString &arg, args) {
493 if (!arg.startsWith(QLatin1Char('-'))) {
494 positionalArgs.append(arg);
498 if (arg == QLatin1String("--notrelocatable")
499 || arg == QLatin1String("-notrelocatable")) {
501 } else if (arg == QLatin1String("--path")
502 || arg == QLatin1String("-path")) {
504 } else if (arg == QLatin1String("--builtins")
505 || arg == QLatin1String("-builtins")) {
507 } else if (arg == QLatin1String("-v")) {
510 qWarning() << "Invalid argument: " << arg;
511 return EXIT_INVALIDARGUMENTS;
516 if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
517 qWarning() << "Incorrect number of positional arguments";
518 return EXIT_INVALIDARGUMENTS;
520 pluginImportUri = positionalArgs[1];
521 pluginImportVersion = positionalArgs[2];
522 if (positionalArgs.size() >= 4)
523 pluginImportPath = positionalArgs[3];
524 } else if (action == Path) {
525 if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
526 qWarning() << "Incorrect number of positional arguments";
527 return EXIT_INVALIDARGUMENTS;
529 pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
530 if (positionalArgs.size() == 3)
531 pluginImportVersion = positionalArgs[2];
532 } else if (action == Builtins) {
533 if (positionalArgs.size() != 1) {
534 qWarning() << "Incorrect number of positional arguments";
535 return EXIT_INVALIDARGUMENTS;
540 QDeclarativeView view;
541 QDeclarativeEngine *engine = view.engine();
542 if (!pluginImportPath.isEmpty()) {
543 QDir cur = QDir::current();
544 cur.cd(pluginImportPath);
545 pluginImportPath = cur.absolutePath();
546 QDir::setCurrent(pluginImportPath);
547 engine->addImportPath(pluginImportPath);
550 // find all QMetaObjects reachable from the builtin module
551 QByteArray importCode("import QtQuick 2.0\n");
552 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(importCode, engine);
554 // this will hold the meta objects we want to dump information of
555 QSet<const QMetaObject *> metas;
557 if (action == Builtins) {
558 metas = defaultReachable;
560 // find all QMetaObjects reachable when the specified module is imported
561 if (action != Path) {
562 importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
564 // pluginImportVersion can be empty
565 importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
568 // create a component with these imports to make sure the imports are valid
569 // and to populate the declarative meta type system
571 QByteArray code = importCode;
572 code += "QtObject {}";
573 QDeclarativeComponent c(engine);
575 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
577 if (!c.errors().isEmpty()) {
578 foreach (const QDeclarativeError &error, c.errors())
579 qWarning() << error.toString();
580 return EXIT_IMPORTERROR;
584 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(importCode, engine);
585 candidates.subtract(defaultReachable);
587 // Also eliminate meta objects with the same classname.
588 // This is required because extended objects seem not to share
589 // a single meta object instance.
590 QSet<QByteArray> defaultReachableNames;
591 foreach (const QMetaObject *mo, defaultReachable)
592 defaultReachableNames.insert(QByteArray(mo->className()));
593 foreach (const QMetaObject *mo, candidates) {
594 if (!defaultReachableNames.contains(mo->className()))
599 // setup static rewrites of type names
600 cppToId.insert("QString", "string");
601 cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
603 // start dumping data
605 QmlStreamWriter qml(&bytes);
607 qml.writeStartDocument();
608 qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 1);
610 "// This file describes the plugin-supplied types contained in the library.\n"
611 "// It is used for QML tooling purposes only.\n"
613 qml.writeStartObject("Module");
615 // put the metaobjects into a map so they are always dumped in the same order
616 QMap<QString, const QMetaObject *> nameToMeta;
617 foreach (const QMetaObject *meta, metas)
618 nameToMeta.insert(convertToId(meta->className()), meta);
622 dumper.setRelocatableModuleUri(pluginImportUri);
623 foreach (const QMetaObject *meta, nameToMeta) {
627 // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
628 // properties using the QEasingCurve type get useful type information.
629 if (pluginImportUri.isEmpty())
630 dumper.writeEasingCurve();
632 qml.writeEndObject();
633 qml.writeEndDocument();
635 std::cout << bytes.constData();
637 // workaround to avoid crashes on exit
639 timer.setSingleShot(true);
640 timer.setInterval(0);
641 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));