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 ids of extended objects.
164 // The chain ends up being:
165 // __extended__.originalname - the base object
166 // __extension_0_.originalname - first extension
168 // __extension_n-2_.originalname - second to last extension
169 // originalname - last extension
170 // ### does this actually work for multiple extensions? it seems like the prototypes might be wrong
171 foreach (const QByteArray &extendedCpp, extensions.keys()) {
172 cppToId.remove(extendedCpp);
173 const QByteArray extendedId = convertToId(extendedCpp);
174 cppToId.insert(extendedCpp, "__extended__." + extendedId);
175 QSet<QByteArray> extensionCppNames = extensions.value(extendedCpp);
177 foreach (const QByteArray &extensionCppName, extensionCppNames) {
178 if (c != extensionCppNames.size() - 1) {
179 QByteArray adjustedName = QString("__extension__%1.%2").arg(QString::number(c), QString(extendedId)).toAscii();
180 cppToId.insert(extensionCppName, adjustedName);
182 cppToId.insert(extensionCppName, extendedId);
188 // find even more QMetaObjects by instantiating QML types and running
189 // over the instances
190 foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
191 if (ty->isExtendedType())
193 if (!ty->isCreatable())
195 if (ty->typeName() == "QDeclarativeComponent")
198 QByteArray tyName = ty->qmlTypeName();
199 tyName = tyName.mid(tyName.lastIndexOf('/') + 1);
200 if (tyName.isEmpty())
203 QByteArray code = importCode.toUtf8();
207 QDeclarativeComponent c(engine);
208 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typeinstance.qml"));
210 QObject *object = c.create();
212 collectReachableMetaObjects(object, &metas);
214 qWarning() << "Could not create" << tyName << ":" << c.errorString();
223 QmlStreamWriter *qml;
224 QString relocatableModuleUri;
227 Dumper(QmlStreamWriter *qml) : qml(qml) {}
229 void setRelocatableModuleUri(const QString &uri)
231 relocatableModuleUri = uri;
234 void dump(const QMetaObject *meta)
236 qml->writeStartObject("Component");
238 QByteArray id = convertToId(meta->className());
239 qml->writeScriptBinding(QLatin1String("name"), enquote(id));
241 for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
242 QMetaClassInfo classInfo = meta->classInfo(index);
243 if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
244 qml->writeScriptBinding(QLatin1String("defaultProperty"), enquote(QLatin1String(classInfo.value())));
249 if (meta->superClass())
250 qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass()->className())));
252 QSet<const QDeclarativeType *> qmlTypes = qmlTypesByCppName.value(meta->className());
253 if (!qmlTypes.isEmpty()) {
256 foreach (const QDeclarativeType *qmlTy, qmlTypes) {
257 QString qmlTyName = qmlTy->qmlTypeName();
258 // some qmltype names are missing the actual names, ignore that import
259 if (qmlTyName.endsWith('/'))
261 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
262 qmlTyName.remove(0, relocatableModuleUri.size() + 1);
264 exports += enquote(QString("%1 %2.%3").arg(
266 QString::number(qmlTy->majorVersion()),
267 QString::number(qmlTy->minorVersion())));
270 // ensure exports are sorted and don't change order when the plugin is dumped again
271 exports.removeDuplicates();
274 qml->writeArrayBinding(QLatin1String("exports"), exports);
276 if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
277 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
278 convertToId(attachedType->className())));
282 for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
283 dump(meta->enumerator(index));
285 for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
286 dump(meta->property(index));
288 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
289 dump(meta->method(index));
291 qml->writeEndObject();
294 void writeEasingCurve()
296 qml->writeStartObject("Component");
297 qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
298 qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
299 qml->writeEndObject();
303 static QString enquote(const QString &string)
305 return QString("\"%1\"").arg(string);
308 /* Removes pointer and list annotations from a type name, returning
309 what was removed in isList and isPointer
311 static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
313 static QByteArray declListPrefix = "QDeclarativeListProperty<";
315 if (typeName->endsWith('*')) {
317 typeName->truncate(typeName->length() - 1);
318 removePointerAndList(typeName, isList, isPointer);
319 } else if (typeName->startsWith(declListPrefix)) {
321 typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
322 *typeName = typeName->mid(declListPrefix.size());
323 removePointerAndList(typeName, isList, isPointer);
326 *typeName = convertToId(*typeName);
329 void writeTypeProperties(QByteArray typeName, bool isWritable)
331 bool isList = false, isPointer = false;
332 removePointerAndList(&typeName, &isList, &isPointer);
334 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
336 qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
338 qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
340 qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
343 void dump(const QMetaProperty &prop)
345 qml->writeStartObject("Property");
347 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
348 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
349 if (int revision = prop.revision())
350 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
352 writeTypeProperties(prop.typeName(), prop.isWritable());
354 qml->writeEndObject();
357 void dump(const QMetaMethod &meth)
359 if (meth.methodType() == QMetaMethod::Signal) {
360 if (meth.access() != QMetaMethod::Protected)
361 return; // nothing to do.
362 } else if (meth.access() != QMetaMethod::Public) {
363 return; // nothing to do.
366 QByteArray name = meth.signature();
367 int lparenIndex = name.indexOf('(');
368 if (lparenIndex == -1) {
369 return; // invalid signature
371 name = name.left(lparenIndex);
373 if (meth.methodType() == QMetaMethod::Signal)
374 qml->writeStartObject(QLatin1String("Signal"));
376 qml->writeStartObject(QLatin1String("Method"));
378 qml->writeScriptBinding(QLatin1String("name"), enquote(name));
380 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
381 if (int revision = meth.revision())
382 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
385 const QString typeName = convertToId(meth.typeName());
386 if (! typeName.isEmpty())
387 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
389 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
390 QByteArray argName = meth.parameterNames().at(i);
392 qml->writeStartObject(QLatin1String("Parameter"));
393 if (! argName.isEmpty())
394 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
395 writeTypeProperties(meth.parameterTypes().at(i), true);
396 qml->writeEndObject();
399 qml->writeEndObject();
402 void dump(const QMetaEnum &e)
404 qml->writeStartObject(QLatin1String("Enum"));
405 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
407 QList<QPair<QString, QString> > namesValues;
408 for (int index = 0; index < e.keyCount(); ++index) {
409 namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
412 qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
413 qml->writeEndObject();
419 EXIT_INVALIDARGUMENTS = 1,
425 void sigSegvHandler(int) {
426 fprintf(stderr, "Error: SEGV\n");
427 if (!currentProperty.isEmpty())
428 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
433 void printUsage(const QString &appName)
435 qWarning() << qPrintable(QString(
436 "Usage: %1 [-v] [-notrelocatable] module.uri version [module/import/path]\n"
437 " %1 [-v] -path path/to/qmldir/directory [version]\n"
438 " %1 [-v] -builtins\n"
439 "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
443 int main(int argc, char *argv[])
446 // qmldump may crash, but we don't want any crash handlers to pop up
447 // therefore we intercept the segfault and just exit() ourselves
448 struct sigaction sigAction;
450 sigemptyset(&sigAction.sa_mask);
451 sigAction.sa_handler = &sigSegvHandler;
452 sigAction.sa_flags = 0;
454 sigaction(SIGSEGV, &sigAction, 0);
458 // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
459 QtSimulatorPrivate::SimulatorConnection::createStubInstance();
461 QApplication app(argc, argv);
462 const QStringList args = app.arguments();
463 const QString appName = QFileInfo(app.applicationFilePath()).baseName();
464 if (args.size() < 2) {
466 return EXIT_INVALIDARGUMENTS;
469 QString pluginImportUri;
470 QString pluginImportVersion;
471 bool relocatable = true;
472 enum Action { Uri, Path, Builtins };
475 QStringList positionalArgs;
476 foreach (const QString &arg, args) {
477 if (!arg.startsWith(QLatin1Char('-'))) {
478 positionalArgs.append(arg);
482 if (arg == QLatin1String("--notrelocatable")
483 || arg == QLatin1String("-notrelocatable")) {
485 } else if (arg == QLatin1String("--path")
486 || arg == QLatin1String("-path")) {
488 } else if (arg == QLatin1String("--builtins")
489 || arg == QLatin1String("-builtins")) {
491 } else if (arg == QLatin1String("-v")) {
494 qWarning() << "Invalid argument: " << arg;
495 return EXIT_INVALIDARGUMENTS;
500 if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
501 qWarning() << "Incorrect number of positional arguments";
502 return EXIT_INVALIDARGUMENTS;
504 pluginImportUri = positionalArgs[1];
505 pluginImportVersion = positionalArgs[2];
506 if (positionalArgs.size() >= 4)
507 pluginImportPath = positionalArgs[3];
508 } else if (action == Path) {
509 if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
510 qWarning() << "Incorrect number of positional arguments";
511 return EXIT_INVALIDARGUMENTS;
513 pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
514 if (positionalArgs.size() == 3)
515 pluginImportVersion = positionalArgs[2];
516 } else if (action == Builtins) {
517 if (positionalArgs.size() != 1) {
518 qWarning() << "Incorrect number of positional arguments";
519 return EXIT_INVALIDARGUMENTS;
524 QDeclarativeView view;
525 QDeclarativeEngine *engine = view.engine();
526 if (!pluginImportPath.isEmpty())
527 engine->addImportPath(pluginImportPath);
529 // find all QMetaObjects reachable from the builtin module
530 QByteArray importCode("import QtQuick 1.1\n");
531 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(importCode, engine);
533 // this will hold the meta objects we want to dump information of
534 QSet<const QMetaObject *> metas;
536 if (action == Builtins) {
537 metas = defaultReachable;
539 // find all QMetaObjects reachable when the specified module is imported
540 if (action != Path) {
541 importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
543 // pluginImportVersion can be empty
544 importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
547 // create a component with these imports to make sure the imports are valid
548 // and to populate the declarative meta type system
550 QByteArray code = importCode;
551 code += "QtObject {}";
552 QDeclarativeComponent c(engine);
554 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
556 if (!c.errors().isEmpty()) {
557 foreach (const QDeclarativeError &error, c.errors())
558 qWarning() << error.toString();
559 return EXIT_IMPORTERROR;
563 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(importCode, engine);
564 candidates.subtract(defaultReachable);
566 // Also eliminate meta objects with the same classname.
567 // This is required because extended objects seem not to share
568 // a single meta object instance.
569 QSet<QByteArray> defaultReachableNames;
570 foreach (const QMetaObject *mo, defaultReachable)
571 defaultReachableNames.insert(QByteArray(mo->className()));
572 foreach (const QMetaObject *mo, candidates) {
573 if (!defaultReachableNames.contains(mo->className()))
578 // setup static rewrites of type names
579 cppToId.insert("QString", "string");
580 cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
582 // start dumping data
584 QmlStreamWriter qml(&bytes);
586 qml.writeStartDocument();
587 qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 1);
589 "// This file describes the plugin-supplied types contained in the library.\n"
590 "// It is used for QML tooling purposes only.\n"
592 qml.writeStartObject("Module");
594 // put the metaobjects into a map so they are always dumped in the same order
595 QMap<QString, const QMetaObject *> nameToMeta;
596 foreach (const QMetaObject *meta, metas)
597 nameToMeta.insert(convertToId(meta->className()), meta);
601 dumper.setRelocatableModuleUri(pluginImportUri);
602 foreach (const QMetaObject *meta, nameToMeta) {
606 // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
607 // properties using the QEasingCurve type get useful type information.
608 if (pluginImportUri.isEmpty())
609 dumper.writeEasingCurve();
611 qml.writeEndObject();
612 qml.writeEndDocument();
614 std::cout << bytes.constData();
616 // workaround to avoid crashes on exit
618 timer.setSingleShot(true);
619 timer.setInterval(0);
620 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));