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 void collectReachableMetaObjects(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
70 if (! meta || metas->contains(meta))
73 // dynamic meta objects break things badly, so just ignore them
74 const QMetaObjectPrivate *mop = reinterpret_cast<const QMetaObjectPrivate *>(meta->d.data);
75 if (!(mop->flags & DynamicMetaObject))
78 collectReachableMetaObjects(meta->superClass(), metas);
81 QString currentProperty;
83 void collectReachableMetaObjects(QObject *object, QSet<const QMetaObject *> *metas)
88 const QMetaObject *meta = object->metaObject();
89 qDebug() << "Processing object" << meta->className();
90 collectReachableMetaObjects(meta, metas);
92 for (int index = 0; index < meta->propertyCount(); ++index) {
93 QMetaProperty prop = meta->property(index);
94 if (QDeclarativeMetaType::isQObject(prop.userType())) {
95 qDebug() << " Processing property" << prop.name();
96 currentProperty = QString("%1::%2").arg(meta->className(), prop.name());
98 // if the property was not initialized during construction,
99 // accessing a member of oo is going to cause a segmentation fault
100 QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
101 if (oo && !metas->contains(oo->metaObject()))
102 collectReachableMetaObjects(oo, metas);
103 currentProperty.clear();
108 void collectReachableMetaObjects(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
110 collectReachableMetaObjects(ty->metaObject(), metas);
111 if (ty->attachedPropertiesType())
112 collectReachableMetaObjects(ty->attachedPropertiesType(), metas);
115 /* We want to add the MetaObject for 'Qt' to the list, this is a
116 simple way to access it.
118 class FriendlyQObject: public QObject
121 static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
124 /* When we dump a QMetaObject, we want to list all the types it is exported as.
125 To do this, we need to find the QDeclarativeTypes associated with this
128 static QHash<QByteArray, QSet<const QDeclarativeType *> > qmlTypesByCppName;
130 static QHash<QByteArray, QByteArray> cppToId;
132 /* Takes a C++ type name, such as Qt::LayoutDirection or QString and
133 maps it to how it should appear in the description file.
135 These names need to be unique globally, so we don't change the C++ symbol's
136 name much. It is mostly used to for explicit translations such as
137 QString->string and translations for extended QML objects.
139 QByteArray convertToId(const QByteArray &cppName)
141 return cppToId.value(cppName, cppName);
144 QSet<const QMetaObject *> collectReachableMetaObjects(const QString &importCode, QDeclarativeEngine *engine)
146 QSet<const QMetaObject *> metas;
147 metas.insert(FriendlyQObject::qtMeta());
149 QHash<QByteArray, QSet<QByteArray> > extensions;
150 foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
151 qmlTypesByCppName[ty->metaObject()->className()].insert(ty);
152 if (ty->isExtendedType()) {
153 extensions[ty->typeName()].insert(ty->metaObject()->className());
155 collectReachableMetaObjects(ty, &metas);
158 // Adjust ids of extended objects.
159 // The chain ends up being:
160 // __extended__.originalname - the base object
161 // __extension_0_.originalname - first extension
163 // __extension_n-2_.originalname - second to last extension
164 // originalname - last extension
165 // ### does this actually work for multiple extensions? it seems like the prototypes might be wrong
166 foreach (const QByteArray &extendedCpp, extensions.keys()) {
167 cppToId.remove(extendedCpp);
168 const QByteArray extendedId = convertToId(extendedCpp);
169 cppToId.insert(extendedCpp, "__extended__." + extendedId);
170 QSet<QByteArray> extensionCppNames = extensions.value(extendedCpp);
172 foreach (const QByteArray &extensionCppName, extensionCppNames) {
173 if (c != extensionCppNames.size() - 1) {
174 QByteArray adjustedName = QString("__extension__%1.%2").arg(QString::number(c), QString(extendedId)).toAscii();
175 cppToId.insert(extensionCppName, adjustedName);
177 cppToId.insert(extensionCppName, extendedId);
183 // find even more QMetaObjects by instantiating QML types and running
184 // over the instances
185 foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
186 if (ty->isExtendedType())
189 QByteArray tyName = ty->qmlTypeName();
190 tyName = tyName.mid(tyName.lastIndexOf('/') + 1);
192 QByteArray code = importCode.toUtf8();
196 QDeclarativeComponent c(engine);
197 c.setData(code, QUrl("typeinstance"));
199 QObject *object = c.create();
201 collectReachableMetaObjects(object, &metas);
203 qDebug() << "Could not create" << tyName << ":" << c.errorString();
212 QmlStreamWriter *qml;
213 QString relocatableModuleUri;
216 Dumper(QmlStreamWriter *qml) : qml(qml) {}
218 void setRelocatableModuleUri(const QString &uri)
220 relocatableModuleUri = uri;
223 void dump(const QMetaObject *meta)
225 qml->writeStartObject("Component");
227 QByteArray id = convertToId(meta->className());
228 qml->writeScriptBinding(QLatin1String("name"), enquote(id));
230 for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
231 QMetaClassInfo classInfo = meta->classInfo(index);
232 if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
233 qml->writeScriptBinding(QLatin1String("defaultProperty"), enquote(QLatin1String(classInfo.value())));
238 if (meta->superClass())
239 qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass()->className())));
241 QSet<const QDeclarativeType *> qmlTypes = qmlTypesByCppName.value(meta->className());
242 if (!qmlTypes.isEmpty()) {
245 foreach (const QDeclarativeType *qmlTy, qmlTypes) {
246 QString qmlTyName = qmlTy->qmlTypeName();
247 // some qmltype names are missing the actual names, ignore that import
248 if (qmlTyName.endsWith('/'))
250 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
251 qmlTyName.remove(0, relocatableModuleUri.size() + 1);
253 exports += enquote(QString("%1 %2.%3").arg(
255 QString::number(qmlTy->majorVersion()),
256 QString::number(qmlTy->minorVersion())));
259 // ensure exports are sorted and don't change order when the plugin is dumped again
260 exports.removeDuplicates();
263 qml->writeArrayBinding(QLatin1String("exports"), exports);
265 if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
266 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
267 convertToId(attachedType->className())));
271 for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
272 dump(meta->enumerator(index));
274 for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
275 dump(meta->property(index));
277 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
278 dump(meta->method(index));
280 qml->writeEndObject();
283 void writeEasingCurve()
285 qml->writeStartObject("Component");
286 qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
287 qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
288 qml->writeEndObject();
292 static QString enquote(const QString &string)
294 return QString("\"%1\"").arg(string);
297 /* Removes pointer and list annotations from a type name, returning
298 what was removed in isList and isPointer
300 static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
302 static QByteArray declListPrefix = "QDeclarativeListProperty<";
304 if (typeName->endsWith('*')) {
306 typeName->truncate(typeName->length() - 1);
307 removePointerAndList(typeName, isList, isPointer);
308 } else if (typeName->startsWith(declListPrefix)) {
310 typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
311 *typeName = typeName->mid(declListPrefix.size());
312 removePointerAndList(typeName, isList, isPointer);
315 *typeName = convertToId(*typeName);
318 void writeTypeProperties(QByteArray typeName, bool isWritable)
320 bool isList = false, isPointer = false;
321 removePointerAndList(&typeName, &isList, &isPointer);
323 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
325 qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
327 qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
329 qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
332 void dump(const QMetaProperty &prop)
334 qml->writeStartObject("Property");
336 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
337 writeTypeProperties(prop.typeName(), prop.isWritable());
339 qml->writeEndObject();
342 void dump(const QMetaMethod &meth)
344 if (meth.methodType() == QMetaMethod::Signal) {
345 if (meth.access() != QMetaMethod::Protected)
346 return; // nothing to do.
347 } else if (meth.access() != QMetaMethod::Public) {
348 return; // nothing to do.
351 QByteArray name = meth.signature();
352 int lparenIndex = name.indexOf('(');
353 if (lparenIndex == -1) {
354 return; // invalid signature
356 name = name.left(lparenIndex);
358 if (meth.methodType() == QMetaMethod::Signal)
359 qml->writeStartObject(QLatin1String("Signal"));
361 qml->writeStartObject(QLatin1String("Method"));
363 qml->writeScriptBinding(QLatin1String("name"), enquote(name));
365 const QString typeName = convertToId(meth.typeName());
366 if (! typeName.isEmpty())
367 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
369 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
370 QByteArray argName = meth.parameterNames().at(i);
372 qml->writeStartObject(QLatin1String("Parameter"));
373 if (! argName.isEmpty())
374 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
375 writeTypeProperties(meth.parameterTypes().at(i), true);
376 qml->writeEndObject();
379 qml->writeEndObject();
382 void dump(const QMetaEnum &e)
384 qml->writeStartObject(QLatin1String("Enum"));
385 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
387 QList<QPair<QString, QString> > namesValues;
388 for (int index = 0; index < e.keyCount(); ++index) {
389 namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
392 qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
393 qml->writeEndObject();
399 EXIT_INVALIDARGUMENTS = 1,
405 void sigSegvHandler(int) {
406 fprintf(stderr, "Error: SEGV\n");
407 if (!currentProperty.isEmpty())
408 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
413 void printUsage(const QString &appName)
415 qWarning() << qPrintable(QString(
416 "Usage: %1 [-notrelocatable] module.uri version [module/import/path]\n"
417 " %1 -path path/to/qmldir/directory [version]\n"
419 "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
423 int main(int argc, char *argv[])
426 // qmldump may crash, but we don't want any crash handlers to pop up
427 // therefore we intercept the segfault and just exit() ourselves
428 struct sigaction action;
430 sigemptyset(&action.sa_mask);
431 action.sa_handler = &sigSegvHandler;
434 sigaction(SIGSEGV, &action, 0);
438 // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
439 QtSimulatorPrivate::SimulatorConnection::createStubInstance();
441 QApplication app(argc, argv);
442 const QStringList args = app.arguments();
443 const QString appName = QFileInfo(app.applicationFilePath()).baseName();
444 if (!(args.size() >= 3
446 && (args.at(1) == QLatin1String("--builtins")
447 || args.at(1) == QLatin1String("-builtins"))))) {
449 return EXIT_INVALIDARGUMENTS;
452 QString pluginImportUri;
453 QString pluginImportVersion;
454 QString pluginImportPath;
455 bool relocatable = true;
456 bool pathImport = false;
457 if (args.size() >= 3) {
458 QStringList positionalArgs;
459 foreach (const QString &arg, args) {
460 if (!arg.startsWith(QLatin1Char('-'))) {
461 positionalArgs.append(arg);
465 if (arg == QLatin1String("--notrelocatable")
466 || arg == QLatin1String("-notrelocatable")) {
468 } else if (arg == QLatin1String("--path")
469 || arg == QLatin1String("-path")) {
472 qWarning() << "Invalid argument: " << arg;
473 return EXIT_INVALIDARGUMENTS;
478 if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
479 qWarning() << "Incorrect number of positional arguments";
480 return EXIT_INVALIDARGUMENTS;
482 pluginImportUri = positionalArgs[1];
483 pluginImportVersion = positionalArgs[2];
484 if (positionalArgs.size() >= 4)
485 pluginImportPath = positionalArgs[3];
487 if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
488 qWarning() << "Incorrect number of positional arguments";
489 return EXIT_INVALIDARGUMENTS;
491 pluginImportPath = positionalArgs[1];
492 if (positionalArgs.size() == 3)
493 pluginImportVersion = positionalArgs[2];
497 QDeclarativeView view;
498 QDeclarativeEngine *engine = view.engine();
499 if (!pluginImportPath.isEmpty())
500 engine->addImportPath(pluginImportPath);
502 // find all QMetaObjects reachable from the builtin module
503 QByteArray importCode("import QtQuick 1.0\n");
504 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(importCode, engine);
506 // this will hold the meta objects we want to dump information of
507 QSet<const QMetaObject *> metas;
509 if (pluginImportUri.isEmpty() && !pathImport) {
510 metas = defaultReachable;
512 // find all QMetaObjects reachable when the specified module is imported
514 importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
516 // pluginImportVersion can be empty
517 importCode += QString("import \"%1\" %2\n").arg(pluginImportPath, pluginImportVersion).toAscii();
520 // create a component with these imports to make sure the imports are valid
521 // and to populate the declarative meta type system
523 QByteArray code = importCode;
524 code += "QtObject {}";
525 QDeclarativeComponent c(engine);
527 c.setData(code, QUrl("typelist"));
529 if (!c.errors().isEmpty()) {
530 foreach (const QDeclarativeError &error, c.errors())
531 qWarning() << error.toString();
532 return EXIT_IMPORTERROR;
536 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(importCode, engine);
537 candidates.subtract(defaultReachable);
539 // Also eliminate meta objects with the same classname.
540 // This is required because extended objects seem not to share
541 // a single meta object instance.
542 QSet<QByteArray> defaultReachableNames;
543 foreach (const QMetaObject *mo, defaultReachable)
544 defaultReachableNames.insert(QByteArray(mo->className()));
545 foreach (const QMetaObject *mo, candidates) {
546 if (!defaultReachableNames.contains(mo->className()))
551 // setup static rewrites of type names
552 cppToId.insert("QString", "string");
553 cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
555 // start dumping data
557 QmlStreamWriter qml(&bytes);
559 qml.writeStartDocument();
560 qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 0);
562 "// This file describes the plugin-supplied types contained in the library.\n"
563 "// It is used for QML tooling purposes only.\n"
565 qml.writeStartObject("Module");
567 // put the metaobjects into a map so they are always dumped in the same order
568 QMap<QString, const QMetaObject *> nameToMeta;
569 foreach (const QMetaObject *meta, metas)
570 nameToMeta.insert(convertToId(meta->className()), meta);
574 dumper.setRelocatableModuleUri(pluginImportUri);
575 foreach (const QMetaObject *meta, nameToMeta) {
579 // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
580 // properties using the QEasingCurve type get useful type information.
581 if (pluginImportUri.isEmpty())
582 dumper.writeEasingCurve();
584 qml.writeEndObject();
585 qml.writeEndDocument();
587 std::cout << bytes.constData();
589 // workaround to avoid crashes on exit
591 timer.setSingleShot(true);
592 timer.setInterval(0);
593 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));