OSDN Git Service

56bce64f6687a4fd1d09241e3b89498bbb6bd8c4
[qt-creator-jp/qt-creator-jp.git] / share / qtcreator / qml / qmldump / main.cpp
1 /**************************************************************************
2 **
3 ** This file is part of Qt Creator
4 **
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6 **
7 ** Contact: Nokia Corporation (qt-info@nokia.com)
8 **
9 ** No Commercial Usage
10 **
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
14 ** this package.
15 **
16 ** GNU Lesser General Public License Usage
17 **
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file.  Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Nokia gives you certain additional
26 ** rights.  These rights are described in the Nokia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** If you have questions regarding the use of this file, please contact
30 ** Nokia at qt-info@nokia.com.
31 **
32 **************************************************************************/
33
34 // WARNING: This code is shared with the qmlplugindump tool code in Qt.
35 //          Modifications to this file need to be applied there.
36
37 #include <QtDeclarative/QtDeclarative>
38 #include <QtDeclarative/private/qdeclarativemetatype_p.h>
39 #include <QtDeclarative/private/qdeclarativeopenmetaobject_p.h>
40 #include <QtDeclarative/QDeclarativeView>
41
42 #include <QtGui/QApplication>
43
44 #include <QtCore/QSet>
45 #include <QtCore/QMetaObject>
46 #include <QtCore/QMetaProperty>
47 #include <QtCore/QDebug>
48 #include <QtCore/private/qobject_p.h>
49 #include <QtCore/private/qmetaobject_p.h>
50
51 #include <iostream>
52
53 #include "qmlstreamwriter.h"
54
55 #ifdef QT_SIMULATOR
56 #include <QtGui/private/qsimulatorconnection_p.h>
57 #endif
58
59 #ifdef Q_OS_UNIX
60 #include <signal.h>
61 #endif
62
63 void collectReachableMetaObjects(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
64 {
65     if (! meta || metas->contains(meta))
66         return;
67
68     // dynamic meta objects break things badly, so just ignore them
69     const QMetaObjectPrivate *mop = reinterpret_cast<const QMetaObjectPrivate *>(meta->d.data);
70     if (!(mop->flags & DynamicMetaObject))
71         metas->insert(meta);
72
73     collectReachableMetaObjects(meta->superClass(), metas);
74 }
75
76 QString currentProperty;
77
78 void collectReachableMetaObjects(QObject *object, QSet<const QMetaObject *> *metas)
79 {
80     if (! object)
81         return;
82
83     const QMetaObject *meta = object->metaObject();
84     qDebug() << "Processing object" << meta->className();
85     collectReachableMetaObjects(meta, metas);
86
87     for (int index = 0; index < meta->propertyCount(); ++index) {
88         QMetaProperty prop = meta->property(index);
89         if (QDeclarativeMetaType::isQObject(prop.userType())) {
90             qDebug() << "  Processing property" << prop.name();
91             currentProperty = QString("%1::%2").arg(meta->className(), prop.name());
92
93             // if the property was not initialized during construction,
94             // accessing a member of oo is going to cause a segmentation fault
95             QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
96             if (oo && !metas->contains(oo->metaObject()))
97                 collectReachableMetaObjects(oo, metas);
98             currentProperty.clear();
99         }
100     }
101 }
102
103 void collectReachableMetaObjects(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
104 {
105     collectReachableMetaObjects(ty->metaObject(), metas);
106     if (ty->attachedPropertiesType())
107         collectReachableMetaObjects(ty->attachedPropertiesType(), metas);
108 }
109
110 /* We want to add the MetaObject for 'Qt' to the list, this is a
111    simple way to access it.
112 */
113 class FriendlyQObject: public QObject
114 {
115 public:
116     static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
117 };
118
119 /* When we dump a QMetaObject, we want to list all the types it is exported as.
120    To do this, we need to find the QDeclarativeTypes associated with this
121    QMetaObject.
122 */
123 static QHash<QByteArray, QSet<const QDeclarativeType *> > qmlTypesByCppName;
124
125 static QHash<QByteArray, QByteArray> cppToId;
126
127 /* Takes a C++ type name, such as Qt::LayoutDirection or QString and
128    maps it to how it should appear in the description file.
129
130    These names need to be unique globally, so we don't change the C++ symbol's
131    name much. It is mostly used to for explicit translations such as
132    QString->string and translations for extended QML objects.
133 */
134 QByteArray convertToId(const QByteArray &cppName)
135 {
136     return cppToId.value(cppName, cppName);
137 }
138
139 QSet<const QMetaObject *> collectReachableMetaObjects(const QString &importCode, QDeclarativeEngine *engine)
140 {
141     QSet<const QMetaObject *> metas;
142     metas.insert(FriendlyQObject::qtMeta());
143
144     QHash<QByteArray, QSet<QByteArray> > extensions;
145     foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
146         qmlTypesByCppName[ty->metaObject()->className()].insert(ty);
147         if (ty->isExtendedType()) {
148             extensions[ty->typeName()].insert(ty->metaObject()->className());
149         }
150         collectReachableMetaObjects(ty, &metas);
151     }
152
153     // Adjust ids of extended objects.
154     // The chain ends up being:
155     // __extended__.originalname - the base object
156     // __extension_0_.originalname - first extension
157     // ..
158     // __extension_n-2_.originalname - second to last extension
159     // originalname - last extension
160     // ### does this actually work for multiple extensions? it seems like the prototypes might be wrong
161     foreach (const QByteArray &extendedCpp, extensions.keys()) {
162         cppToId.remove(extendedCpp);
163         const QByteArray extendedId = convertToId(extendedCpp);
164         cppToId.insert(extendedCpp, "__extended__." + extendedId);
165         QSet<QByteArray> extensionCppNames = extensions.value(extendedCpp);
166         int c = 0;
167         foreach (const QByteArray &extensionCppName, extensionCppNames) {
168             if (c != extensionCppNames.size() - 1) {
169                 QByteArray adjustedName = QString("__extension__%1.%2").arg(QString::number(c), QString(extendedId)).toAscii();
170                 cppToId.insert(extensionCppName, adjustedName);
171             } else {
172                 cppToId.insert(extensionCppName, extendedId);
173             }
174             ++c;
175         }
176     }
177
178     // find even more QMetaObjects by instantiating QML types and running
179     // over the instances
180     foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
181         if (ty->isExtendedType())
182             continue;
183
184         QByteArray tyName = ty->qmlTypeName();
185         tyName = tyName.mid(tyName.lastIndexOf('/') + 1);
186
187         QByteArray code = importCode.toUtf8();
188         code += tyName;
189         code += " {}\n";
190
191         QDeclarativeComponent c(engine);
192         c.setData(code, QUrl("typeinstance"));
193
194         QObject *object = c.create();
195         if (object)
196             collectReachableMetaObjects(object, &metas);
197         else
198             qDebug() << "Could not create" << tyName << ":" << c.errorString();
199     }
200
201     return metas;
202 }
203
204
205 class Dumper
206 {
207     QmlStreamWriter *qml;
208     QString relocatableModuleUri;
209
210 public:
211     Dumper(QmlStreamWriter *qml) : qml(qml) {}
212
213     void setRelocatableModuleUri(const QString &uri)
214     {
215         relocatableModuleUri = uri;
216     }
217
218     void dump(const QMetaObject *meta)
219     {
220         qml->writeStartObject("Component");
221
222         QByteArray id = convertToId(meta->className());
223         qml->writeScriptBinding(QLatin1String("name"), enquote(id));
224
225         for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
226             QMetaClassInfo classInfo = meta->classInfo(index);
227             if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
228                 qml->writeScriptBinding(QLatin1String("defaultProperty"), enquote(QLatin1String(classInfo.value())));
229                 break;
230             }
231         }
232
233         if (meta->superClass())
234             qml->writeScriptBinding(QLatin1String("prototype"), enquote(convertToId(meta->superClass()->className())));
235
236         QSet<const QDeclarativeType *> qmlTypes = qmlTypesByCppName.value(meta->className());
237         if (!qmlTypes.isEmpty()) {
238             QStringList exports;
239
240             foreach (const QDeclarativeType *qmlTy, qmlTypes) {
241                 QString qmlTyName = qmlTy->qmlTypeName();
242                 // some qmltype names are missing the actual names, ignore that import
243                 if (qmlTyName.endsWith('/'))
244                     continue;
245                 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
246                     qmlTyName.remove(0, relocatableModuleUri.size() + 1);
247                 }
248                 exports += enquote(QString("%1 %2.%3").arg(
249                                        qmlTyName,
250                                        QString::number(qmlTy->majorVersion()),
251                                        QString::number(qmlTy->minorVersion())));
252             }
253
254             // ensure exports are sorted and don't change order when the plugin is dumped again
255             exports.removeDuplicates();
256             qSort(exports);
257
258             qml->writeArrayBinding(QLatin1String("exports"), exports);
259
260             if (const QMetaObject *attachedType = (*qmlTypes.begin())->attachedPropertiesType()) {
261                 qml->writeScriptBinding(QLatin1String("attachedType"), enquote(
262                                             convertToId(attachedType->className())));
263             }
264         }
265
266         for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
267             dump(meta->enumerator(index));
268
269         for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
270             dump(meta->property(index));
271
272         for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
273             dump(meta->method(index));
274
275         qml->writeEndObject();
276     }
277
278     void writeEasingCurve()
279     {
280         qml->writeStartObject("Component");
281         qml->writeScriptBinding(QLatin1String("name"), enquote(QLatin1String("QEasingCurve")));
282         qml->writeScriptBinding(QLatin1String("prototype"), enquote(QLatin1String("QDeclarativeEasingValueType")));
283         qml->writeEndObject();
284     }
285
286 private:
287     static QString enquote(const QString &string)
288     {
289         return QString("\"%1\"").arg(string);
290     }
291
292     /* Removes pointer and list annotations from a type name, returning
293        what was removed in isList and isPointer
294     */
295     static void removePointerAndList(QByteArray *typeName, bool *isList, bool *isPointer)
296     {
297         static QByteArray declListPrefix = "QDeclarativeListProperty<";
298
299         if (typeName->endsWith('*')) {
300             *isPointer = true;
301             typeName->truncate(typeName->length() - 1);
302             removePointerAndList(typeName, isList, isPointer);
303         } else if (typeName->startsWith(declListPrefix)) {
304             *isList = true;
305             typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
306             *typeName = typeName->mid(declListPrefix.size());
307             removePointerAndList(typeName, isList, isPointer);
308         }
309
310         *typeName = convertToId(*typeName);
311     }
312
313     void writeTypeProperties(QByteArray typeName, bool isWritable)
314     {
315         bool isList = false, isPointer = false;
316         removePointerAndList(&typeName, &isList, &isPointer);
317
318         qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
319         if (isList)
320             qml->writeScriptBinding(QLatin1String("isList"), QLatin1String("true"));
321         if (!isWritable)
322             qml->writeScriptBinding(QLatin1String("isReadonly"), QLatin1String("true"));
323         if (isPointer)
324             qml->writeScriptBinding(QLatin1String("isPointer"), QLatin1String("true"));
325     }
326
327     void dump(const QMetaProperty &prop)
328     {
329         qml->writeStartObject("Property");
330
331         qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(prop.name())));
332         writeTypeProperties(prop.typeName(), prop.isWritable());
333
334         qml->writeEndObject();
335     }
336
337     void dump(const QMetaMethod &meth)
338     {
339         if (meth.methodType() == QMetaMethod::Signal) {
340             if (meth.access() != QMetaMethod::Protected)
341                 return; // nothing to do.
342         } else if (meth.access() != QMetaMethod::Public) {
343             return; // nothing to do.
344         }
345
346         QByteArray name = meth.signature();
347         int lparenIndex = name.indexOf('(');
348         if (lparenIndex == -1) {
349             return; // invalid signature
350         }
351         name = name.left(lparenIndex);
352
353         if (meth.methodType() == QMetaMethod::Signal)
354             qml->writeStartObject(QLatin1String("Signal"));
355         else
356             qml->writeStartObject(QLatin1String("Method"));
357
358         qml->writeScriptBinding(QLatin1String("name"), enquote(name));
359
360         const QString typeName = convertToId(meth.typeName());
361         if (! typeName.isEmpty())
362             qml->writeScriptBinding(QLatin1String("type"), enquote(typeName));
363
364         for (int i = 0; i < meth.parameterTypes().size(); ++i) {
365             QByteArray argName = meth.parameterNames().at(i);
366
367             qml->writeStartObject(QLatin1String("Parameter"));
368             if (! argName.isEmpty())
369                 qml->writeScriptBinding(QLatin1String("name"), enquote(argName));
370             writeTypeProperties(meth.parameterTypes().at(i), true);
371             qml->writeEndObject();
372         }
373
374         qml->writeEndObject();
375     }
376
377     void dump(const QMetaEnum &e)
378     {
379         qml->writeStartObject(QLatin1String("Enum"));
380         qml->writeScriptBinding(QLatin1String("name"), enquote(QString::fromUtf8(e.name())));
381
382         QList<QPair<QString, QString> > namesValues;
383         for (int index = 0; index < e.keyCount(); ++index) {
384             namesValues.append(qMakePair(enquote(QString::fromUtf8(e.key(index))), QString::number(e.value(index))));
385         }
386
387         qml->writeScriptObjectLiteralBinding(QLatin1String("values"), namesValues);
388         qml->writeEndObject();
389     }
390 };
391
392
393 enum ExitCode {
394     EXIT_INVALIDARGUMENTS = 1,
395     EXIT_SEGV = 2,
396     EXIT_IMPORTERROR = 3
397 };
398
399 #ifdef Q_OS_UNIX
400 void sigSegvHandler(int) {
401     fprintf(stderr, "Error: qmldump SEGV\n");
402     if (!currentProperty.isEmpty())
403         fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
404     exit(EXIT_SEGV);
405 }
406 #endif
407
408 void printUsage(const QString &appName)
409 {
410     qWarning() << qPrintable(QString(
411                                  "Usage: %1 [--notrelocatable] module.uri version [module/import/path]\n"
412                                  "       %1 --path path/to/qmldir/directory [version]\n"
413                                  "       %1 --builtins\n"
414                                  "Example: %1 Qt.labs.particles 4.7 /home/user/dev/qt-install/imports").arg(
415                                  appName));
416 }
417
418 int main(int argc, char *argv[])
419 {
420 #ifdef Q_OS_UNIX
421     // qmldump may crash, but we don't want any crash handlers to pop up
422     // therefore we intercept the segfault and just exit() ourselves
423     struct sigaction action;
424
425     sigemptyset(&action.sa_mask);
426     action.sa_handler = &sigSegvHandler;
427     action.sa_flags   = 0;
428
429     sigaction(SIGSEGV, &action, 0);
430 #endif
431
432 #ifdef QT_SIMULATOR
433     // Running this application would bring up the Qt Simulator (since it links QtGui), avoid that!
434     QtSimulatorPrivate::SimulatorConnection::createStubInstance();
435 #endif
436     QApplication app(argc, argv);
437     const QStringList args = app.arguments();
438     const QString appName = QFileInfo(app.applicationFilePath()).baseName();
439     if (!(args.size() >= 3 || (args.size() == 2 && args.at(1) == QLatin1String("--builtins")))) {
440         printUsage(appName);
441         return EXIT_INVALIDARGUMENTS;
442     }
443
444     QString pluginImportUri;
445     QString pluginImportVersion;
446     QString pluginImportPath;
447     bool relocatable = true;
448     bool pathImport = false;
449     if (args.size() >= 3) {
450         QStringList positionalArgs;
451         foreach (const QString &arg, args) {
452             if (!arg.startsWith("--")) {
453                 positionalArgs.append(arg);
454                 continue;
455             }
456
457             if (arg == QLatin1String("--notrelocatable")) {
458                 relocatable = false;
459             } else if (arg == QLatin1String("--path")) {
460                 pathImport = true;
461             } else {
462                 qWarning() << "Invalid argument: " << arg;
463                 return EXIT_INVALIDARGUMENTS;
464             }
465         }
466
467         if (!pathImport) {
468             if (positionalArgs.size() != 3 && positionalArgs.size() != 4) {
469                 qWarning() << "Incorrect number of positional arguments";
470                 return EXIT_INVALIDARGUMENTS;
471             }
472             pluginImportUri = positionalArgs[1];
473             pluginImportVersion = positionalArgs[2];
474             if (positionalArgs.size() >= 4)
475                 pluginImportPath = positionalArgs[3];
476         } else {
477             if (positionalArgs.size() != 2 && positionalArgs.size() != 3) {
478                 qWarning() << "Incorrect number of positional arguments";
479                 return EXIT_INVALIDARGUMENTS;
480             }
481             pluginImportPath = positionalArgs[1];
482             if (positionalArgs.size() == 3)
483                 pluginImportVersion = positionalArgs[2];
484         }
485     }
486
487     QDeclarativeView view;
488     QDeclarativeEngine *engine = view.engine();
489     if (!pluginImportPath.isEmpty())
490         engine->addImportPath(pluginImportPath);
491
492     // find all QMetaObjects reachable from the builtin module
493     QByteArray importCode("import QtQuick 1.0\n");
494     QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(importCode, engine);
495
496     // this will hold the meta objects we want to dump information of
497     QSet<const QMetaObject *> metas;
498
499     if (pluginImportUri.isEmpty() && !pathImport) {
500         metas = defaultReachable;
501     } else {
502         // find all QMetaObjects reachable when the specified module is imported
503         if (!pathImport) {
504             importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
505         } else {
506             // pluginImportVersion can be empty
507             importCode += QString("import \"%1\" %2\n").arg(pluginImportPath, pluginImportVersion).toAscii();
508         }
509
510         // create a component with these imports to make sure the imports are valid
511         // and to populate the declarative meta type system
512         {
513             QByteArray code = importCode;
514             code += "QtObject {}";
515             QDeclarativeComponent c(engine);
516
517             c.setData(code, QUrl("typelist"));
518             c.create();
519             if (!c.errors().isEmpty()) {
520                 foreach (const QDeclarativeError &error, c.errors())
521                     qWarning() << error.toString();
522                 return EXIT_IMPORTERROR;
523             }
524         }
525
526         QSet<const QMetaObject *> candidates = collectReachableMetaObjects(importCode, engine);
527         candidates.subtract(defaultReachable);
528
529         // Also eliminate meta objects with the same classname.
530         // This is required because extended objects seem not to share
531         // a single meta object instance.
532         QSet<QByteArray> defaultReachableNames;
533         foreach (const QMetaObject *mo, defaultReachable)
534             defaultReachableNames.insert(QByteArray(mo->className()));
535         foreach (const QMetaObject *mo, candidates) {
536             if (!defaultReachableNames.contains(mo->className()))
537                 metas.insert(mo);
538         }
539     }
540
541     // setup static rewrites of type names
542     cppToId.insert("QString", "string");
543     cppToId.insert("QDeclarativeEasingValueType::Type", "Type");
544
545     // start dumping data
546     QByteArray bytes;
547     QmlStreamWriter qml(&bytes);
548
549     qml.writeStartDocument();
550     qml.writeLibraryImport(QLatin1String("QtQuick.tooling"), 1, 0);
551     qml.write("\n"
552               "// This file describes the plugin-supplied types contained in the library.\n"
553               "// It is used for QML tooling purposes only.\n"
554               "\n");
555     qml.writeStartObject("Module");
556
557     // put the metaobjects into a map so they are always dumped in the same order
558     QMap<QString, const QMetaObject *> nameToMeta;
559     foreach (const QMetaObject *meta, metas)
560         nameToMeta.insert(convertToId(meta->className()), meta);
561
562     Dumper dumper(&qml);
563     if (relocatable)
564         dumper.setRelocatableModuleUri(pluginImportUri);
565     foreach (const QMetaObject *meta, nameToMeta) {
566         dumper.dump(meta);
567     }
568
569     // define QEasingCurve as an extension of QDeclarativeEasingValueType, this way
570     // properties using the QEasingCurve type get useful type information.
571     if (pluginImportUri.isEmpty())
572         dumper.writeEasingCurve();
573
574     qml.writeEndObject();
575     qml.writeEndDocument();
576
577     std::cout << bytes.constData();
578
579     // workaround to avoid crashes on exit
580     QTimer timer;
581     timer.setSingleShot(true);
582     timer.setInterval(0);
583     QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));
584     timer.start();
585
586     return app.exec();
587 }