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;
70 void collectReachableMetaObjects(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
72 if (! meta || metas->contains(meta))
75 // dynamic meta objects break things badly, so just ignore them
76 const QMetaObjectPrivate *mop = reinterpret_cast<const QMetaObjectPrivate *>(meta->d.data);
77 if (!(mop->flags & DynamicMetaObject))
80 collectReachableMetaObjects(meta->superClass(), metas);
83 QString currentProperty;
85 void collectReachableMetaObjects(QObject *object, QSet<const QMetaObject *> *metas)
90 const QMetaObject *meta = object->metaObject();
91 qDebug() << "Processing object" << meta->className();
92 collectReachableMetaObjects(meta, metas);
94 for (int index = 0; index < meta->propertyCount(); ++index) {
95 QMetaProperty prop = meta->property(index);
96 if (QDeclarativeMetaType::isQObject(prop.userType())) {
97 qDebug() << " Processing property" << prop.name();
98 currentProperty = QString("%1::%2").arg(meta->className(), prop.name());
100 // if the property was not initialized during construction,
101 // accessing a member of oo is going to cause a segmentation fault
102 QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
103 if (oo && !metas->contains(oo->metaObject()))
104 collectReachableMetaObjects(oo, metas);
105 currentProperty.clear();
110 void collectReachableMetaObjects(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
112 collectReachableMetaObjects(ty->metaObject(), metas);
113 if (ty->attachedPropertiesType())
114 collectReachableMetaObjects(ty->attachedPropertiesType(), metas);
117 /* We want to add the MetaObject for 'Qt' to the list, this is a
118 simple way to access it.
120 class FriendlyQObject: public QObject
123 static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
126 /* When we dump a QMetaObject, we want to list all the types it is exported as.
127 To do this, we need to find the QDeclarativeTypes associated with this
130 static QHash<QByteArray, QSet<const QDeclarativeType *> > qmlTypesByCppName;
132 static QHash<QByteArray, QByteArray> cppToId;
134 /* Takes a C++ type name, such as Qt::LayoutDirection or QString and
135 maps it to how it should appear in the description file.
137 These names need to be unique globally, so we don't change the C++ symbol's
138 name much. It is mostly used to for explicit translations such as
139 QString->string and translations for extended QML objects.
141 QByteArray convertToId(const QByteArray &cppName)
143 return cppToId.value(cppName, cppName);
146 QSet<const QMetaObject *> collectReachableMetaObjects(const QString &importCode, QDeclarativeEngine *engine)
148 QSet<const QMetaObject *> metas;
149 metas.insert(FriendlyQObject::qtMeta());
151 QHash<QByteArray, QSet<QByteArray> > extensions;
152 foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
153 qmlTypesByCppName[ty->metaObject()->className()].insert(ty);
154 if (ty->isExtendedType()) {
155 extensions[ty->typeName()].insert(ty->metaObject()->className());
157 collectReachableMetaObjects(ty, &metas);
160 // Adjust ids of extended objects.
161 // The chain ends up being:
162 // __extended__.originalname - the base object
163 // __extension_0_.originalname - first extension
165 // __extension_n-2_.originalname - second to last extension
166 // originalname - last extension
167 // ### does this actually work for multiple extensions? it seems like the prototypes might be wrong
168 foreach (const QByteArray &extendedCpp, extensions.keys()) {
169 cppToId.remove(extendedCpp);
170 const QByteArray extendedId = convertToId(extendedCpp);
171 cppToId.insert(extendedCpp, "__extended__." + extendedId);
172 QSet<QByteArray> extensionCppNames = extensions.value(extendedCpp);
174 foreach (const QByteArray &extensionCppName, extensionCppNames) {
175 if (c != extensionCppNames.size() - 1) {
176 QByteArray adjustedName = QString("__extension__%1.%2").arg(QString::number(c), QString(extendedId)).toAscii();
177 cppToId.insert(extensionCppName, adjustedName);
179 cppToId.insert(extensionCppName, extendedId);
185 // find even more QMetaObjects by instantiating QML types and running
186 // over the instances
187 foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
188 if (ty->isExtendedType())
191 QByteArray tyName = ty->qmlTypeName();
192 tyName = tyName.mid(tyName.lastIndexOf('/') + 1);
194 QByteArray code = importCode.toUtf8();
198 QDeclarativeComponent c(engine);
199 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typeinstance.qml"));
201 QObject *object = c.create();
203 collectReachableMetaObjects(object, &metas);
205 qDebug() << "Could not create" << tyName << ":" << c.errorString();
214 QmlStreamWriter *qml;
215 QString relocatableModuleUri;
218 Dumper(QmlStreamWriter *qml) : qml(qml) {}
220 void setRelocatableModuleUri(const QString &uri)
222 relocatableModuleUri = uri;
225 void dump(const QMetaObject *meta)
227 qml->writeStartObject("Component");
229 QByteArray id = convertToId(meta->className());
230 qml->writeScriptBinding(QLatin1String("name"), enquote(id));
232 for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
233 QMetaClassInfo classInfo = meta->classInfo(index);
234 if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
235 qml->writeScriptBinding(QLatin1String("defaultProperty"), enquote(QLatin1String(classInfo.value())));
240 if (meta->superClass())
241 qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass()->className())));
243 QSet<const QDeclarativeType *> qmlTypes = qmlTypesByCppName.value(meta->className());
244 if (!qmlTypes.isEmpty()) {
247 foreach (const QDeclarativeType *qmlTy, qmlTypes) {
248 QString qmlTyName = qmlTy->qmlTypeName();
249 // some qmltype names are missing the actual names, ignore that import
250 if (qmlTyName.endsWith('/'))
252 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
253 qmlTyName.remove(0, relocatableModuleUri.size() + 1);
255 exports += enquote(QString("%1 %2.%3").arg(
257 QString::number(qmlTy->majorVersion()),
258 QString::number(qmlTy->minorVersion())));
261 // ensure exports are sorted and don't change order when the plugin is dumped again
262 exports.removeDuplicates();
265 qml->writeArrayBinding(QLatin1String("exports"), exports);
267 if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
268 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
269 convertToId(attachedType->className())));
273 for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
274 dump(meta->enumerator(index));
276 for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
277 dump(meta->property(index));
279 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
280 dump(meta->method(index));
282 qml->writeEndObject();
285 void writeEasingCurve()
287 qml->writeStartObject("Component");
288 qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
289 qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
290 qml->writeEndObject();
294 static QString enquote(const QString &string)
296 return QString("\"%1\"").arg(string);
299 /* Removes pointer and list annotations from a type name, returning
300 what was removed in isList and isPointer
302 static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
304 static QByteArray declListPrefix = "QDeclarativeListProperty<";
306 if (typeName->endsWith('*')) {
308 typeName->truncate(typeName->length() - 1);
309 removePointerAndList(typeName, isList, isPointer);
310 } else if (typeName->startsWith(declListPrefix)) {
312 typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
313 *typeName = typeName->mid(declListPrefix.size());
314 removePointerAndList(typeName, isList, isPointer);
317 *typeName = convertToId(*typeName);
320 void writeTypeProperties(QByteArray typeName, bool isWritable)
322 bool isList = false, isPointer = false;
323 removePointerAndList(&typeName, &isList, &isPointer);
325 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
327 qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
329 qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
331 qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
334 void dump(const QMetaProperty &prop)
336 qml->writeStartObject("Property");
338 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
339 writeTypeProperties(prop.typeName(), prop.isWritable());
341 qml->writeEndObject();
344 void dump(const QMetaMethod &meth)
346 if (meth.methodType() == QMetaMethod::Signal) {
347 if (meth.access() != QMetaMethod::Protected)
348 return; // nothing to do.
349 } else if (meth.access() != QMetaMethod::Public) {
350 return; // nothing to do.
353 QByteArray name = meth.signature();
354 int lparenIndex = name.indexOf('(');
355 if (lparenIndex == -1) {
356 return; // invalid signature
358 name = name.left(lparenIndex);
360 if (meth.methodType() == QMetaMethod::Signal)
361 qml->writeStartObject(QLatin1String("Signal"));
363 qml->writeStartObject(QLatin1String("Method"));
365 qml->writeScriptBinding(QLatin1String("name"), enquote(name));
367 const QString typeName = convertToId(meth.typeName());
368 if (! typeName.isEmpty())
369 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
371 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
372 QByteArray argName = meth.parameterNames().at(i);
374 qml->writeStartObject(QLatin1String("Parameter"));
375 if (! argName.isEmpty())
376 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
377 writeTypeProperties(meth.parameterTypes().at(i), true);
378 qml->writeEndObject();
381 qml->writeEndObject();
384 void dump(const QMetaEnum &e)
386 qml->writeStartObject(QLatin1String("Enum"));
387 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
389 QList<QPair<QString, QString> > namesValues;
390 for (int index = 0; index < e.keyCount(); ++index) {
391 namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
394 qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
395 qml->writeEndObject();
401 EXIT_INVALIDARGUMENTS = 1,
407 void sigSegvHandler(int) {
408 fprintf(stderr, "Error: SEGV\n");
409 if (!currentProperty.isEmpty())
410 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
415 void printUsage(const QString &appName)
417 qWarning() << qPrintable(QString(
418 "Usage: %1 [-notrelocatable] module.uri version [module/import/path]\n"
419 " %1 -path path/to/qmldir/directory [version]\n"
421 "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
425 int main(int argc, char *argv[])
428 // qmldump may crash, but we don't want any crash handlers to pop up
429 // therefore we intercept the segfault and just exit() ourselves
430 struct sigaction action;
432 sigemptyset(&action.sa_mask);
433 action.sa_handler = &sigSegvHandler;
436 sigaction(SIGSEGV, &action, 0);
440 // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
441 QtSimulatorPrivate::SimulatorConnection::createStubInstance();
443 QApplication app(argc, argv);
444 const QStringList args = app.arguments();
445 const QString appName = QFileInfo(app.applicationFilePath()).baseName();
446 if (!(args.size() >= 3
448 && (args.at(1) == QLatin1String("--builtins")
449 || args.at(1) == QLatin1String("-builtins"))))) {
451 return EXIT_INVALIDARGUMENTS;
454 QString pluginImportUri;
455 QString pluginImportVersion;
456 bool relocatable = true;
457 bool pathImport = false;
458 if (args.size() >= 3) {
459 QStringList positionalArgs;
460 foreach (const QString &arg, args) {
461 if (!arg.startsWith(QLatin1Char('-'))) {
462 positionalArgs.append(arg);
466 if (arg == QLatin1String("--notrelocatable")
467 || arg == QLatin1String("-notrelocatable")) {
469 } else if (arg == QLatin1String("--path")
470 || arg == QLatin1String("-path")) {
473 qWarning() << "Invalid argument: " << arg;
474 return EXIT_INVALIDARGUMENTS;
479 if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
480 qWarning() << "Incorrect number of positional arguments";
481 return EXIT_INVALIDARGUMENTS;
483 pluginImportUri = positionalArgs[1];
484 pluginImportVersion = positionalArgs[2];
485 if (positionalArgs.size() >= 4)
486 pluginImportPath = positionalArgs[3];
488 if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
489 qWarning() << "Incorrect number of positional arguments";
490 return EXIT_INVALIDARGUMENTS;
492 pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
493 if (positionalArgs.size() == 3)
494 pluginImportVersion = positionalArgs[2];
498 QDeclarativeView view;
499 QDeclarativeEngine *engine = view.engine();
500 if (!pluginImportPath.isEmpty())
501 engine->addImportPath(pluginImportPath);
503 // find all QMetaObjects reachable from the builtin module
504 QByteArray importCode("import QtQuick 1.0\n");
505 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(importCode, engine);
507 // this will hold the meta objects we want to dump information of
508 QSet<const QMetaObject *> metas;
510 if (pluginImportUri.isEmpty() && !pathImport) {
511 metas = defaultReachable;
513 // find all QMetaObjects reachable when the specified module is imported
515 importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
517 // pluginImportVersion can be empty
518 importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
521 // create a component with these imports to make sure the imports are valid
522 // and to populate the declarative meta type system
524 QByteArray code = importCode;
525 code += "QtObject {}";
526 QDeclarativeComponent c(engine);
528 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
530 if (!c.errors().isEmpty()) {
531 foreach (const QDeclarativeError &error, c.errors())
532 qWarning() << error.toString();
533 return EXIT_IMPORTERROR;
537 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(importCode, engine);
538 candidates.subtract(defaultReachable);
540 // Also eliminate meta objects with the same classname.
541 // This is required because extended objects seem not to share
542 // a single meta object instance.
543 QSet<QByteArray> defaultReachableNames;
544 foreach (const QMetaObject *mo, defaultReachable)
545 defaultReachableNames.insert(QByteArray(mo->className()));
546 foreach (const QMetaObject *mo, candidates) {
547 if (!defaultReachableNames.contains(mo->className()))
552 // setup static rewrites of type names
553 cppToId.insert("QString", "string");
554 cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
556 // start dumping data
558 QmlStreamWriter qml(&bytes);
560 qml.writeStartDocument();
561 qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 0);
563 "// This file describes the plugin-supplied types contained in the library.\n"
564 "// It is used for QML tooling purposes only.\n"
566 qml.writeStartObject("Module");
568 // put the metaobjects into a map so they are always dumped in the same order
569 QMap<QString, const QMetaObject *> nameToMeta;
570 foreach (const QMetaObject *meta, metas)
571 nameToMeta.insert(convertToId(meta->className()), meta);
575 dumper.setRelocatableModuleUri(pluginImportUri);
576 foreach (const QMetaObject *meta, nameToMeta) {
580 // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
581 // properties using the QEasingCurve type get useful type information.
582 if (pluginImportUri.isEmpty())
583 dumper.writeEasingCurve();
585 qml.writeEndObject();
586 qml.writeEndDocument();
588 std::cout << bytes.constData();
590 // workaround to avoid crashes on exit
592 timer.setSingleShot(true);
593 timer.setInterval(0);
594 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));