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 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file. Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights. These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
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 void collectReachableMetaObjects(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
73 if (! meta || metas->contains(meta))
76 // dynamic meta objects break things badly, so just ignore them
77 const QMetaObjectPrivate *mop = reinterpret_cast<const QMetaObjectPrivate *>(meta->d.data);
78 if (!(mop->flags & DynamicMetaObject))
81 collectReachableMetaObjects(meta->superClass(), metas);
84 QString currentProperty;
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 QObject *object = c.create();
219 collectReachableMetaObjects(object, &metas);
221 qWarning() << "Could not create" << tyName << ":" << c.errorString();
230 QmlStreamWriter *qml;
231 QString relocatableModuleUri;
234 Dumper(QmlStreamWriter *qml) : qml(qml) {}
236 void setRelocatableModuleUri(const QString &uri)
238 relocatableModuleUri = uri;
241 void dump(const QMetaObject *meta)
243 qml->writeStartObject("Component");
245 QByteArray id = convertToId(meta->className());
246 qml->writeScriptBinding(QLatin1String("name"), enquote(id));
248 for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
249 QMetaClassInfo classInfo = meta->classInfo(index);
250 if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
251 qml->writeScriptBinding(QLatin1String("defaultProperty"), enquote(QLatin1String(classInfo.value())));
256 if (meta->superClass())
257 qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass()->className())));
259 QSet<const QDeclarativeType *> qmlTypes = qmlTypesByCppName.value(meta->className());
260 if (!qmlTypes.isEmpty()) {
263 foreach (const QDeclarativeType *qmlTy, qmlTypes) {
264 QString qmlTyName = qmlTy->qmlTypeName();
265 // some qmltype names are missing the actual names, ignore that import
266 if (qmlTyName.endsWith('/'))
268 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
269 qmlTyName.remove(0, relocatableModuleUri.size() + 1);
271 if (qmlTyName.startsWith("./")) {
272 qmlTyName.remove(0, 2);
274 exports += enquote(QString("%1 %2.%3").arg(
276 QString::number(qmlTy->majorVersion()),
277 QString::number(qmlTy->minorVersion())));
280 // ensure exports are sorted and don't change order when the plugin is dumped again
281 exports.removeDuplicates();
284 qml->writeArrayBinding(QLatin1String("exports"), exports);
286 if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
287 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
288 convertToId(attachedType->className())));
292 for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
293 dump(meta->enumerator(index));
295 for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
296 dump(meta->property(index));
298 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
299 dump(meta->method(index));
301 qml->writeEndObject();
304 void writeEasingCurve()
306 qml->writeStartObject("Component");
307 qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
308 qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
309 qml->writeEndObject();
313 static QString enquote(const QString &string)
315 return QString("\"%1\"").arg(string);
318 /* Removes pointer and list annotations from a type name, returning
319 what was removed in isList and isPointer
321 static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
323 static QByteArray declListPrefix = "QDeclarativeListProperty<";
325 if (typeName->endsWith('*')) {
327 typeName->truncate(typeName->length() - 1);
328 removePointerAndList(typeName, isList, isPointer);
329 } else if (typeName->startsWith(declListPrefix)) {
331 typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
332 *typeName = typeName->mid(declListPrefix.size());
333 removePointerAndList(typeName, isList, isPointer);
336 *typeName = convertToId(*typeName);
339 void writeTypeProperties(QByteArray typeName, bool isWritable)
341 bool isList = false, isPointer = false;
342 removePointerAndList(&typeName, &isList, &isPointer);
344 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
346 qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
348 qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
350 qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
353 void dump(const QMetaProperty &prop)
355 qml->writeStartObject("Property");
357 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
358 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
359 if (int revision = prop.revision())
360 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
362 writeTypeProperties(prop.typeName(), prop.isWritable());
364 qml->writeEndObject();
367 void dump(const QMetaMethod &meth)
369 if (meth.methodType() == QMetaMethod::Signal) {
370 if (meth.access() != QMetaMethod::Protected)
371 return; // nothing to do.
372 } else if (meth.access() != QMetaMethod::Public) {
373 return; // nothing to do.
376 QByteArray name = meth.signature();
377 int lparenIndex = name.indexOf('(');
378 if (lparenIndex == -1) {
379 return; // invalid signature
381 name = name.left(lparenIndex);
383 if (meth.methodType() == QMetaMethod::Signal)
384 qml->writeStartObject(QLatin1String("Signal"));
386 qml->writeStartObject(QLatin1String("Method"));
388 qml->writeScriptBinding(QLatin1String("name"), enquote(name));
390 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
391 if (int revision = meth.revision())
392 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
395 const QString typeName = convertToId(meth.typeName());
396 if (! typeName.isEmpty())
397 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
399 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
400 QByteArray argName = meth.parameterNames().at(i);
402 qml->writeStartObject(QLatin1String("Parameter"));
403 if (! argName.isEmpty())
404 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
405 writeTypeProperties(meth.parameterTypes().at(i), true);
406 qml->writeEndObject();
409 qml->writeEndObject();
412 void dump(const QMetaEnum &e)
414 qml->writeStartObject(QLatin1String("Enum"));
415 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
417 QList<QPair<QString, QString> > namesValues;
418 for (int index = 0; index < e.keyCount(); ++index) {
419 namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
422 qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
423 qml->writeEndObject();
429 EXIT_INVALIDARGUMENTS = 1,
435 void sigSegvHandler(int) {
436 fprintf(stderr, "Error: SEGV\n");
437 if (!currentProperty.isEmpty())
438 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.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 QDeclarativeView view;
535 QDeclarativeEngine *engine = view.engine();
536 if (!pluginImportPath.isEmpty()) {
537 QDir cur = QDir::current();
538 cur.cd(pluginImportPath);
539 pluginImportPath = cur.absolutePath();
540 QDir::setCurrent(pluginImportPath);
541 engine->addImportPath(pluginImportPath);
544 // find all QMetaObjects reachable from the builtin module
545 QByteArray importCode("import QtQuick 2.0\n");
546 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(importCode, engine);
548 // this will hold the meta objects we want to dump information of
549 QSet<const QMetaObject *> metas;
551 if (action == Builtins) {
552 metas = defaultReachable;
554 // find all QMetaObjects reachable when the specified module is imported
555 if (action != Path) {
556 importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
558 // pluginImportVersion can be empty
559 importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
562 // create a component with these imports to make sure the imports are valid
563 // and to populate the declarative meta type system
565 QByteArray code = importCode;
566 code += "QtObject {}";
567 QDeclarativeComponent c(engine);
569 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
571 if (!c.errors().isEmpty()) {
572 foreach (const QDeclarativeError &error, c.errors())
573 qWarning() << error.toString();
574 return EXIT_IMPORTERROR;
578 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(importCode, engine);
579 candidates.subtract(defaultReachable);
581 // Also eliminate meta objects with the same classname.
582 // This is required because extended objects seem not to share
583 // a single meta object instance.
584 QSet<QByteArray> defaultReachableNames;
585 foreach (const QMetaObject *mo, defaultReachable)
586 defaultReachableNames.insert(QByteArray(mo->className()));
587 foreach (const QMetaObject *mo, candidates) {
588 if (!defaultReachableNames.contains(mo->className()))
593 // setup static rewrites of type names
594 cppToId.insert("QString", "string");
595 cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
597 // start dumping data
599 QmlStreamWriter qml(&bytes);
601 qml.writeStartDocument();
602 qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 1);
604 "// This file describes the plugin-supplied types contained in the library.\n"
605 "// It is used for QML tooling purposes only.\n"
607 qml.writeStartObject("Module");
609 // put the metaobjects into a map so they are always dumped in the same order
610 QMap<QString, const QMetaObject *> nameToMeta;
611 foreach (const QMetaObject *meta, metas)
612 nameToMeta.insert(convertToId(meta->className()), meta);
616 dumper.setRelocatableModuleUri(pluginImportUri);
617 foreach (const QMetaObject *meta, nameToMeta) {
621 // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
622 // properties using the QEasingCurve type get useful type information.
623 if (pluginImportUri.isEmpty())
624 dumper.writeEasingCurve();
626 qml.writeEndObject();
627 qml.writeEndDocument();
629 std::cout << bytes.constData();
631 // workaround to avoid crashes on exit
633 timer.setSingleShot(true);
634 timer.setInterval(0);
635 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));