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 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
340 if (int revision = prop.revision())
341 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
343 writeTypeProperties(prop.typeName(), prop.isWritable());
345 qml->writeEndObject();
348 void dump(const QMetaMethod &meth)
350 if (meth.methodType() == QMetaMethod::Signal) {
351 if (meth.access() != QMetaMethod::Protected)
352 return; // nothing to do.
353 } else if (meth.access() != QMetaMethod::Public) {
354 return; // nothing to do.
357 QByteArray name = meth.signature();
358 int lparenIndex = name.indexOf('(');
359 if (lparenIndex == -1) {
360 return; // invalid signature
362 name = name.left(lparenIndex);
364 if (meth.methodType() == QMetaMethod::Signal)
365 qml->writeStartObject(QLatin1String("Signal"));
367 qml->writeStartObject(QLatin1String("Method"));
369 qml->writeScriptBinding(QLatin1String("name"), enquote(name));
371 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
372 if (int revision = meth.revision())
373 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
376 const QString typeName = convertToId(meth.typeName());
377 if (! typeName.isEmpty())
378 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
380 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
381 QByteArray argName = meth.parameterNames().at(i);
383 qml->writeStartObject(QLatin1String("Parameter"));
384 if (! argName.isEmpty())
385 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
386 writeTypeProperties(meth.parameterTypes().at(i), true);
387 qml->writeEndObject();
390 qml->writeEndObject();
393 void dump(const QMetaEnum &e)
395 qml->writeStartObject(QLatin1String("Enum"));
396 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
398 QList<QPair<QString, QString> > namesValues;
399 for (int index = 0; index < e.keyCount(); ++index) {
400 namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
403 qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
404 qml->writeEndObject();
410 EXIT_INVALIDARGUMENTS = 1,
416 void sigSegvHandler(int) {
417 fprintf(stderr, "Error: SEGV\n");
418 if (!currentProperty.isEmpty())
419 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
424 void printUsage(const QString &appName)
426 qWarning() << qPrintable(QString(
427 "Usage: %1 [-notrelocatable] module.uri version [module/import/path]\n"
428 " %1 -path path/to/qmldir/directory [version]\n"
430 "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
434 int main(int argc, char *argv[])
437 // qmldump may crash, but we don't want any crash handlers to pop up
438 // therefore we intercept the segfault and just exit() ourselves
439 struct sigaction action;
441 sigemptyset(&action.sa_mask);
442 action.sa_handler = &sigSegvHandler;
445 sigaction(SIGSEGV, &action, 0);
449 // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
450 QtSimulatorPrivate::SimulatorConnection::createStubInstance();
452 QApplication app(argc, argv);
453 const QStringList args = app.arguments();
454 const QString appName = QFileInfo(app.applicationFilePath()).baseName();
455 if (!(args.size() >= 3
457 && (args.at(1) == QLatin1String("--builtins")
458 || args.at(1) == QLatin1String("-builtins"))))) {
460 return EXIT_INVALIDARGUMENTS;
463 QString pluginImportUri;
464 QString pluginImportVersion;
465 bool relocatable = true;
466 bool pathImport = false;
467 if (args.size() >= 3) {
468 QStringList positionalArgs;
469 foreach (const QString &arg, args) {
470 if (!arg.startsWith(QLatin1Char('-'))) {
471 positionalArgs.append(arg);
475 if (arg == QLatin1String("--notrelocatable")
476 || arg == QLatin1String("-notrelocatable")) {
478 } else if (arg == QLatin1String("--path")
479 || arg == QLatin1String("-path")) {
482 qWarning() << "Invalid argument: " << arg;
483 return EXIT_INVALIDARGUMENTS;
488 if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
489 qWarning() << "Incorrect number of positional arguments";
490 return EXIT_INVALIDARGUMENTS;
492 pluginImportUri = positionalArgs[1];
493 pluginImportVersion = positionalArgs[2];
494 if (positionalArgs.size() >= 4)
495 pluginImportPath = positionalArgs[3];
497 if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
498 qWarning() << "Incorrect number of positional arguments";
499 return EXIT_INVALIDARGUMENTS;
501 pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
502 if (positionalArgs.size() == 3)
503 pluginImportVersion = positionalArgs[2];
507 QDeclarativeView view;
508 QDeclarativeEngine *engine = view.engine();
509 if (!pluginImportPath.isEmpty())
510 engine->addImportPath(pluginImportPath);
512 // find all QMetaObjects reachable from the builtin module
513 QByteArray importCode("import QtQuick 1.1\n");
514 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(importCode, engine);
516 // this will hold the meta objects we want to dump information of
517 QSet<const QMetaObject *> metas;
519 if (pluginImportUri.isEmpty() && !pathImport) {
520 metas = defaultReachable;
522 // find all QMetaObjects reachable when the specified module is imported
524 importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
526 // pluginImportVersion can be empty
527 importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
530 // create a component with these imports to make sure the imports are valid
531 // and to populate the declarative meta type system
533 QByteArray code = importCode;
534 code += "QtObject {}";
535 QDeclarativeComponent c(engine);
537 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
539 if (!c.errors().isEmpty()) {
540 foreach (const QDeclarativeError &error, c.errors())
541 qWarning() << error.toString();
542 return EXIT_IMPORTERROR;
546 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(importCode, engine);
547 candidates.subtract(defaultReachable);
549 // Also eliminate meta objects with the same classname.
550 // This is required because extended objects seem not to share
551 // a single meta object instance.
552 QSet<QByteArray> defaultReachableNames;
553 foreach (const QMetaObject *mo, defaultReachable)
554 defaultReachableNames.insert(QByteArray(mo->className()));
555 foreach (const QMetaObject *mo, candidates) {
556 if (!defaultReachableNames.contains(mo->className()))
561 // setup static rewrites of type names
562 cppToId.insert("QString", "string");
563 cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
565 // start dumping data
567 QmlStreamWriter qml(&bytes);
569 qml.writeStartDocument();
570 qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 0);
572 "// This file describes the plugin-supplied types contained in the library.\n"
573 "// It is used for QML tooling purposes only.\n"
575 qml.writeStartObject("Module");
577 // put the metaobjects into a map so they are always dumped in the same order
578 QMap<QString, const QMetaObject *> nameToMeta;
579 foreach (const QMetaObject *meta, metas)
580 nameToMeta.insert(convertToId(meta->className()), meta);
584 dumper.setRelocatableModuleUri(pluginImportUri);
585 foreach (const QMetaObject *meta, nameToMeta) {
589 // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
590 // properties using the QEasingCurve type get useful type information.
591 if (pluginImportUri.isEmpty())
592 dumper.writeEasingCurve();
594 qml.writeEndObject();
595 qml.writeEndDocument();
597 std::cout << bytes.constData();
599 // workaround to avoid crashes on exit
601 timer.setSingleShot(true);
602 timer.setInterval(0);
603 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));