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 exports += enquote(QString("%1 %2.%3").arg(
273 QString::number(qmlTy->majorVersion()),
274 QString::number(qmlTy->minorVersion())));
277 // ensure exports are sorted and don't change order when the plugin is dumped again
278 exports.removeDuplicates();
281 qml->writeArrayBinding(QLatin1String("exports"), exports);
283 if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
284 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
285 convertToId(attachedType->className())));
289 for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
290 dump(meta->enumerator(index));
292 for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
293 dump(meta->property(index));
295 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
296 dump(meta->method(index));
298 qml->writeEndObject();
301 void writeEasingCurve()
303 qml->writeStartObject("Component");
304 qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
305 qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
306 qml->writeEndObject();
310 static QString enquote(const QString &string)
312 return QString("\"%1\"").arg(string);
315 /* Removes pointer and list annotations from a type name, returning
316 what was removed in isList and isPointer
318 static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
320 static QByteArray declListPrefix = "QDeclarativeListProperty<";
322 if (typeName->endsWith('*')) {
324 typeName->truncate(typeName->length() - 1);
325 removePointerAndList(typeName, isList, isPointer);
326 } else if (typeName->startsWith(declListPrefix)) {
328 typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
329 *typeName = typeName->mid(declListPrefix.size());
330 removePointerAndList(typeName, isList, isPointer);
333 *typeName = convertToId(*typeName);
336 void writeTypeProperties(QByteArray typeName, bool isWritable)
338 bool isList = false, isPointer = false;
339 removePointerAndList(&typeName, &isList, &isPointer);
341 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
343 qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
345 qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
347 qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
350 void dump(const QMetaProperty &prop)
352 qml->writeStartObject("Property");
354 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
355 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
356 if (int revision = prop.revision())
357 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
359 writeTypeProperties(prop.typeName(), prop.isWritable());
361 qml->writeEndObject();
364 void dump(const QMetaMethod &meth)
366 if (meth.methodType() == QMetaMethod::Signal) {
367 if (meth.access() != QMetaMethod::Protected)
368 return; // nothing to do.
369 } else if (meth.access() != QMetaMethod::Public) {
370 return; // nothing to do.
373 QByteArray name = meth.signature();
374 int lparenIndex = name.indexOf('(');
375 if (lparenIndex == -1) {
376 return; // invalid signature
378 name = name.left(lparenIndex);
380 if (meth.methodType() == QMetaMethod::Signal)
381 qml->writeStartObject(QLatin1String("Signal"));
383 qml->writeStartObject(QLatin1String("Method"));
385 qml->writeScriptBinding(QLatin1String("name"), enquote(name));
387 #if (QT_VERSION >= QT_VERSION_CHECK(4, 7, 4))
388 if (int revision = meth.revision())
389 qml->writeScriptBinding(QLatin1String("revision"), QString::number(revision));
392 const QString typeName = convertToId(meth.typeName());
393 if (! typeName.isEmpty())
394 qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
396 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
397 QByteArray argName = meth.parameterNames().at(i);
399 qml->writeStartObject(QLatin1String("Parameter"));
400 if (! argName.isEmpty())
401 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
402 writeTypeProperties(meth.parameterTypes().at(i), true);
403 qml->writeEndObject();
406 qml->writeEndObject();
409 void dump(const QMetaEnum &e)
411 qml->writeStartObject(QLatin1String("Enum"));
412 qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
414 QList<QPair<QString, QString> > namesValues;
415 for (int index = 0; index < e.keyCount(); ++index) {
416 namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
419 qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
420 qml->writeEndObject();
426 EXIT_INVALIDARGUMENTS = 1,
432 void sigSegvHandler(int) {
433 fprintf(stderr, "Error: SEGV\n");
434 if (!currentProperty.isEmpty())
435 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
440 void printUsage(const QString &appName)
442 qWarning() << qPrintable(QString(
443 "Usage: %1 [-v] [-notrelocatable] module.uri version [module/import/path]\n"
444 " %1 [-v] -path path/to/qmldir/directory [version]\n"
445 " %1 [-v] -builtins\n"
446 "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
450 int main(int argc, char *argv[])
453 // qmldump may crash, but we don't want any crash handlers to pop up
454 // therefore we intercept the segfault and just exit() ourselves
455 struct sigaction sigAction;
457 sigemptyset(&sigAction.sa_mask);
458 sigAction.sa_handler = &sigSegvHandler;
459 sigAction.sa_flags = 0;
461 sigaction(SIGSEGV, &sigAction, 0);
465 // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
466 QtSimulatorPrivate::SimulatorConnection::createStubInstance();
468 QApplication app(argc, argv);
469 const QStringList args = app.arguments();
470 const QString appName = QFileInfo(app.applicationFilePath()).baseName();
471 if (args.size() < 2) {
473 return EXIT_INVALIDARGUMENTS;
476 QString pluginImportUri;
477 QString pluginImportVersion;
478 bool relocatable = true;
479 enum Action { Uri, Path, Builtins };
482 QStringList positionalArgs;
483 foreach (const QString &arg, args) {
484 if (!arg.startsWith(QLatin1Char('-'))) {
485 positionalArgs.append(arg);
489 if (arg == QLatin1String("--notrelocatable")
490 || arg == QLatin1String("-notrelocatable")) {
492 } else if (arg == QLatin1String("--path")
493 || arg == QLatin1String("-path")) {
495 } else if (arg == QLatin1String("--builtins")
496 || arg == QLatin1String("-builtins")) {
498 } else if (arg == QLatin1String("-v")) {
501 qWarning() << "Invalid argument: " << arg;
502 return EXIT_INVALIDARGUMENTS;
507 if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
508 qWarning() << "Incorrect number of positional arguments";
509 return EXIT_INVALIDARGUMENTS;
511 pluginImportUri = positionalArgs[1];
512 pluginImportVersion = positionalArgs[2];
513 if (positionalArgs.size() >= 4)
514 pluginImportPath = positionalArgs[3];
515 } else if (action == Path) {
516 if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
517 qWarning() << "Incorrect number of positional arguments";
518 return EXIT_INVALIDARGUMENTS;
520 pluginImportPath = QDir::fromNativeSeparators(positionalArgs[1]);
521 if (positionalArgs.size() == 3)
522 pluginImportVersion = positionalArgs[2];
523 } else if (action == Builtins) {
524 if (positionalArgs.size() != 1) {
525 qWarning() << "Incorrect number of positional arguments";
526 return EXIT_INVALIDARGUMENTS;
531 QDeclarativeView view;
532 QDeclarativeEngine *engine = view.engine();
533 if (!pluginImportPath.isEmpty())
534 engine->addImportPath(pluginImportPath);
536 // find all QMetaObjects reachable from the builtin module
537 QByteArray importCode("import QtQuick 1.1\n");
538 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(importCode, engine);
540 // this will hold the meta objects we want to dump information of
541 QSet<const QMetaObject *> metas;
543 if (action == Builtins) {
544 metas = defaultReachable;
546 // find all QMetaObjects reachable when the specified module is imported
547 if (action != Path) {
548 importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
550 // pluginImportVersion can be empty
551 importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
554 // create a component with these imports to make sure the imports are valid
555 // and to populate the declarative meta type system
557 QByteArray code = importCode;
558 code += "QtObject {}";
559 QDeclarativeComponent c(engine);
561 c.setData(code, QUrl::fromLocalFile(pluginImportPath + "/typelist.qml"));
563 if (!c.errors().isEmpty()) {
564 foreach (const QDeclarativeError &error, c.errors())
565 qWarning() << error.toString();
566 return EXIT_IMPORTERROR;
570 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(importCode, engine);
571 candidates.subtract(defaultReachable);
573 // Also eliminate meta objects with the same classname.
574 // This is required because extended objects seem not to share
575 // a single meta object instance.
576 QSet<QByteArray> defaultReachableNames;
577 foreach (const QMetaObject *mo, defaultReachable)
578 defaultReachableNames.insert(QByteArray(mo->className()));
579 foreach (const QMetaObject *mo, candidates) {
580 if (!defaultReachableNames.contains(mo->className()))
585 // setup static rewrites of type names
586 cppToId.insert("QString", "string");
587 cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
589 // start dumping data
591 QmlStreamWriter qml(&bytes);
593 qml.writeStartDocument();
594 qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 1);
596 "// This file describes the plugin-supplied types contained in the library.\n"
597 "// It is used for QML tooling purposes only.\n"
599 qml.writeStartObject("Module");
601 // put the metaobjects into a map so they are always dumped in the same order
602 QMap<QString, const QMetaObject *> nameToMeta;
603 foreach (const QMetaObject *meta, metas)
604 nameToMeta.insert(convertToId(meta->className()), meta);
608 dumper.setRelocatableModuleUri(pluginImportUri);
609 foreach (const QMetaObject *meta, nameToMeta) {
613 // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
614 // properties using the QEasingCurve type get useful type information.
615 if (pluginImportUri.isEmpty())
616 dumper.writeEasingCurve();
618 qml.writeEndObject();
619 qml.writeEndDocument();
621 std::cout << bytes.constData();
623 // workaround to avoid crashes on exit
625 timer.setSingleShot(true);
626 timer.setInterval(0);
627 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));