Debian Codegraph @

apicheck/apicheck.cpp

raw
1 /*
2 * Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
3 * Copyright (C) 2015 Canonical
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License as published by
7 * the Free Software Foundation; version 3.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include <QtQml/qqmlengine.h>
19 #include <QtQml/private/qqmlmetatype_p.h>
20 #include <QtQml/private/qqmlopenmetaobject_p.h>
21 #include <QtQuick/private/qquickevents_p_p.h>
22 #include <QtQuick/private/qquickpincharea_p.h>
23
24 #include <QtGui/QGuiApplication>
25 #include <QtCore/QLibraryInfo>
26 #include <QtCore/QDir>
27 #include <QtCore/QFileInfo>
28 #include <QtCore/QSet>
29 #include <QtCore/QStringList>
30 #include <QtCore/QTimer>
31 #include <QtCore/QMetaObject>
32 #include <QtCore/QMetaProperty>
33 #include <QtCore/private/qobject_p.h>
34 #include <QtCore/private/qmetaobject_p.h>
35 #include <QtQml/private/qqmldirparser_p.h>
36 #include <QJSEngine>
37 #include <QJsonDocument>
38 #include <QJsonObject>
39 #include <QJsonArray>
40 #include <QLoggingCategory>
41 #include <QRegularExpression>
42
43 #define foreach Q_FOREACH
44 #include <QtQml/private/qqmlengine_p.h>
45 #undef foreach
46
47 #include <iostream>
48 #include <algorithm>
49
50 #ifdef Q_OS_UNIX
51 #include <signal.h>
52 #endif
53
54 bool verbose = false;
55
56 QString currentProperty;
57 QString inObjectInstantiation;
58 QQmlEngine *currentEngine=0;
59
60 void collectReachableMetaObjects(const QMetaObject *meta, QSet<const QMetaObject *> *metas, bool extended = false)
61 {
62 if (! meta || metas->contains(meta))
63 return;
64
65 // dynamic meta objects can break things badly
66 // but extended types are usually fine
67 const QMetaObjectPrivate *mop = reinterpret_cast<const QMetaObjectPrivate *>(meta->d.data);
68 if (extended || !(mop->flags & DynamicMetaObject))
69 metas->insert(meta);
70
71 collectReachableMetaObjects(meta->superClass(), metas);
72 }
73
74 void collectReachableMetaObjects(QObject *object, QSet<const QMetaObject *> *metas)
75 {
76 if (! object)
77 return;
78
79 const QMetaObject *meta = object->metaObject();
80 collectReachableMetaObjects(meta, metas);
81
82 for (int index = 0; index < meta->propertyCount(); ++index) {
83 QMetaProperty prop = meta->property(index);
84 if (
85 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
86 prop.metaType().flags().testFlag(QMetaType::PointerToQObject)
87 #else
88 QQmlMetaType::isQObject(prop.userType())
89 #endif
90 ) {
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 = QQmlMetaType::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 QQmlType ty, QSet<const QMetaObject *> *metas)
104 {
105 collectReachableMetaObjects(ty.metaObject(), metas, ty.isExtendedType());
106
107 if (ty.attachedPropertiesType(
108 #if QT_VERSION >= QT_VERSION_CHECK(6, 11, 0)
109 QQmlTypeLoader::get(currentEngine)
110 #else
111 QQmlEnginePrivate::get(currentEngine)
112 #endif
113 )) {
114 collectReachableMetaObjects(ty.attachedPropertiesType(
115 #if QT_VERSION >= QT_VERSION_CHECK(6, 11, 0)
116 QQmlTypeLoader::get(currentEngine)
117 #else
118 QQmlEnginePrivate::get(currentEngine)
119 #endif
120 ), metas);
121 }
122 }
123
124 /* We want to add the MetaObject for 'Qt' to the list, this is a
125 simple way to access it.
126 */
127 class FriendlyQObject: public QObject
128 {
129 public:
130 static const QMetaObject *qtMeta() { return
131 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
132 &staticMetaObject
133 #else
134 &staticQtMetaObject
135 #endif
136 ; }
137 };
138
139 /* When we dump a QMetaObject, we want to list all the types it is exported as.
140 To do this, we need to find the QQmlTypes associated with this
141 QMetaObject.
142 */
143 static QHash<QByteArray, QSet<QQmlType> > qmlTypesByCppName;
144
145 static QMultiMap<QString, QQmlType> qmlTypesByCompositeName;
146
147 static QHash<QByteArray, QByteArray> cppToId;
148
149 bool typeNameSort(const QQmlType type1, const QQmlType type2)
150 {
151 return type1.qmlTypeName() > type2.qmlTypeName();
152 }
153
154 /* Takes a C++ type name, such as Qt::LayoutDirection or QString and
155 maps it to how it should appear in the description file.
156
157 These names need to be unique globally, so we don't change the C++ symbol's
158 name much. It is mostly used to for explicit translations such as
159 QString->string and translations for extended QML objects.
160 */
161 QByteArray convertToId(const QString &cppName)
162 {
163 QString qmlType(QString(qPrintable(cppName)).replace(QRegularExpression("(QQmlListProperty|QList)<(.+)>"), "\\2"));
164 QString typeFormat(qmlType != cppName ? "list<%1>" : "%1");
165
166 QList<QQmlType>types(qmlTypesByCppName[qPrintable(qmlType)].values());
167 std::sort(types.begin(), types.end(), typeNameSort);
168
169 if (qmlType.contains("::")) {
170 QStringList parts(qmlType.split("::"));
171 // Enum or Flags
172 if (parts.length() > 2) {
173 qmlType = convertToId(parts[0] + "::" + parts[1]) + "." + parts[2];
174 } else {
175 // Namespace
176 qmlType = parts[1];
177 // FIXME: Namespaces in properties?
178 if (parts[0] == "Qt" || parts[0] == "RenderTimer")
179 return qPrintable(typeFormat.arg(parts[0] + "." + qmlType));
180 }
181 }
182
183 if (types.isEmpty())
184 qmlType = cppToId.value(qPrintable(qmlType), qPrintable(qmlType));
185 else {
186 // Cache QML type name
187 QString newQmlType(QString(types[0].qmlTypeName()).split("/")[1].toUtf8());
188 cppToId.insert(qPrintable(qmlType), qPrintable(newQmlType));
189 qmlType = newQmlType;
190 }
191 // Strip internal _QMLTYPE_xy suffix
192 qmlType = qmlType.split("_")[0];
193 return qPrintable(typeFormat.arg(qmlType));
194 }
195
196 QByteArray convertToId(const QMetaObject *mo)
197 {
198 QByteArray className(mo->className());
199 if (!className.isEmpty())
200 return convertToId(className);
201
202 // likely a metaobject generated for an extended qml object
203 if (mo->superClass()) {
204 className = convertToId(mo->superClass());
205 className.append("_extended");
206 return className;
207 }
208
209 static QHash<const QMetaObject *, QByteArray> generatedNames;
210 className = generatedNames.value(mo);
211 if (!className.isEmpty())
212 return className;
213
214 std::cerr << "Found a QMetaObject without a className, generating a random name" << std::endl;
215 className = QByteArray("error-unknown-name-");
216 className.append(QByteArray::number(generatedNames.size()));
217 generatedNames.insert(mo, className);
218 return className;
219 }
220 // Collect all metaobjects for types registered with qmlRegisterType() without parameters
221 void collectReachableMetaObjectsWithoutQmlName( QSet<const QMetaObject *>& metas ) {
222 Q_FOREACH (QQmlType ty, QQmlMetaType::qmlAllTypes()) {
223 const QMetaObject *tyMeta = ty.metaObject();
224 if (tyMeta && !metas.contains(tyMeta)) {
225 if (!ty.isComposite()) {
226 collectReachableMetaObjects(ty, &metas);
227 } else {
228 qmlTypesByCompositeName.insert(ty.elementName(), ty);
229 }
230 }
231 }
232 }
233
234 QSet<const QMetaObject *> collectReachableMetaObjects(QQmlEngine *engine,
235 QSet<const QMetaObject *> &noncreatables,
236 QSet<const QMetaObject *> &singletons,
237 const QList<QQmlType> &skip = QList<QQmlType>())
238 {
239 QSet<const QMetaObject *> metas;
240 metas.insert(FriendlyQObject::qtMeta());
241
242 QHash<QByteArray, QSet<QByteArray> > extensions;
243 Q_FOREACH (const QQmlType ty, QQmlMetaType::qmlTypes()) {
244 const QMetaObject *tyMeta = ty.metaObject();
245 if (!ty.isCreatable() && tyMeta)
246 noncreatables.insert(tyMeta);
247 if (ty.isSingleton() && tyMeta)
248 singletons.insert(tyMeta);
249 if (!ty.isComposite()) {
250 if (tyMeta) {
251 qmlTypesByCppName[tyMeta->className()].insert(ty);
252 if (ty.isExtendedType())
253 extensions[ty.typeName()].insert(tyMeta->className());
254 }
255 collectReachableMetaObjects(ty, &metas);
256 } else {
257 qmlTypesByCompositeName.insert(ty.elementName(), ty);
258 }
259 }
260
261 // Adjust exports of the base object if there are extensions.
262 // For each export of a base object there can be a single extension object overriding it.
263 // Example: QDeclarativeGraphicsWidget overrides the QtQuick/QGraphicsWidget export
264 // of QGraphicsWidget.
265 Q_FOREACH (const QByteArray &baseCpp, extensions.keys()) {
266 QSet<QQmlType> baseExports = qmlTypesByCppName.value(baseCpp);
267
268 const QSet<QByteArray> extensionCppNames = extensions.value(baseCpp);
269 Q_FOREACH (const QByteArray &extensionCppName, extensionCppNames) {
270 const QSet<QQmlType> extensionExports = qmlTypesByCppName.value(extensionCppName);
271
272 // remove extension exports from base imports
273 // unfortunately the QQmlType pointers don't match, so can't use QSet::subtract
274 QSet<QQmlType> newBaseExports;
275 Q_FOREACH (QQmlType baseExport, baseExports) {
276 bool match = false;
277 Q_FOREACH (QQmlType extensionExport, extensionExports) {
278 if (baseExport.qmlTypeName() == extensionExport.qmlTypeName()
279 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
280 && baseExport.version().majorVersion() == extensionExport.version().majorVersion()
281 && baseExport.version().minorVersion() == extensionExport.version().minorVersion()
282 #else
283 && baseExport.majorVersion() == extensionExport.majorVersion()
284 && baseExport.minorVersion() == extensionExport.minorVersion()
285 #endif
286 ) {
287 match = true;
288 break;
289 }
290 }
291 if (!match)
292 newBaseExports.insert(baseExport);
293 }
294 baseExports = newBaseExports;
295 }
296 qmlTypesByCppName[baseCpp] = baseExports;
297 }
298
299 // find even more QMetaObjects by instantiating QML types and running
300 // over the instances
301 Q_FOREACH (QQmlType ty, QQmlMetaType::qmlTypes()) {
302 if (skip.contains(ty))
303 continue;
304 if (ty.isExtendedType())
305 continue;
306 if (!ty.isCreatable())
307 continue;
308 if (ty.typeName() == "QQmlComponent")
309 continue;
310
311 QString tyName = ty.qmlTypeName();
312 tyName = tyName.mid(tyName.lastIndexOf(QLatin1Char('/')) + 1);
313 if (tyName.isEmpty())
314 continue;
315
316 inObjectInstantiation = tyName;
317 QObject *object = 0;
318
319 if (ty.isSingleton()) {
320 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
321 QQmlType::SingletonInstanceInfo::ConstPtr siinfo = ty.singletonInstanceInfo();
322 if (siinfo.isNull()) {
323 #else
324 QQmlType::SingletonInstanceInfo *siinfo = ty.singletonInstanceInfo();
325 if (!siinfo) {
326 #endif
327 std::cerr << "Internal error, " << qPrintable(tyName)
328 << "(" << qPrintable( QString::fromUtf8(ty.typeName()) ) << ")"
329 << " is singleton, but has no singletonInstanceInfo" << std::endl;
330 continue;
331 }
332 if (ty.isQObjectSingleton()) {
333 collectReachableMetaObjects(object, &metas);
334 object = QQmlEnginePrivate::get(engine)->singletonInstance<QObject*>(ty);
335 } else {
336 inObjectInstantiation.clear();
337 continue; // we don't handle QJSValue singleton types.
338 }
339 } else {
340 object = ty.create();
341 }
342
343 inObjectInstantiation.clear();
344
345 if (object) {
346 collectReachableMetaObjects(object, &metas);
347 object->deleteLater();
348 } else {
349 std::cerr << "Could not create" << qPrintable(tyName) << std::endl;
350 }
351 }
352
353 collectReachableMetaObjectsWithoutQmlName(metas);
354
355 return metas;
356 }
357
358 class KnownAttributes {
359 QHash<QByteArray, int> m_properties;
360 QHash<QByteArray, QHash<int, int> > m_methods;
361 public:
362 bool knownMethod(const QByteArray &name, int nArgs, int revision)
363 {
364 if (m_methods.contains(name)) {
365 QHash<int, int> overloads = m_methods.value(name);
366 if (overloads.contains(nArgs) && overloads.value(nArgs) <= revision)
367 return true;
368 }
369 m_methods[name][nArgs] = revision;
370 return false;
371 }
372
373 bool knownProperty(const QByteArray &name, int revision)
374 {
375 if (m_properties.contains(name) && m_properties.value(name) <= revision)
376 return true;
377 m_properties[name] = revision;
378 return false;
379 }
380 };
381
382 class Dumper
383 {
384 QJsonObject* json;
385 QString relocatableModuleUri;
386 QString importVersion;
387
388 public:
389 Dumper(QJsonObject* json): json(json) {}
390
391 void setRelocatableModuleUri(const QString &uri)
392 {
393 relocatableModuleUri = uri;
394 }
395
396 void setImportVersion(const QString &version)
397 {
398 importVersion = version;
399 }
400
401 const QString getExportString(QString qmlTyName, int majorVersion, int minorVersion)
402 {
403 if (qmlTyName.startsWith(relocatableModuleUri + QLatin1Char('/'))) {
404 qmlTyName.remove(0, relocatableModuleUri.size() + 1);
405 }
406 if (qmlTyName.startsWith("./")) {
407 qmlTyName.remove(0, 2);
408 }
409 if (qmlTyName.startsWith("/")) {
410 qmlTyName.remove(0, 1);
411 }
412 // Work-around for version -1, -1
413 if (majorVersion == -1)
414 return QString("%1 %2").arg(qmlTyName).arg(importVersion);
415 return QString("%1 %2.%3").arg(qmlTyName).arg(majorVersion).arg(minorVersion);
416 }
417
418 void writeMetaContent(QJsonObject* object, const QMetaObject *meta, KnownAttributes *knownAttributes = 0)
419 {
420 QSet<QString> internalSignals;
421 QSet<QString> implicitSignals;
422 for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index) {
423 const QMetaProperty &property = meta->property(index);
424 const QMetaObject* superClass(meta->superClass());
425 // FIXME: Work-around to omit properties from Qt superclasses
426 bool isQtAPI(QString(superClass->className()) == "QQuickImageBase"
427 && QString("autoTransform,fillMode,horizontalAlignment,mipmap,paintedWidth,paintedHeight,verticalAlignment").contains(property.name()));
428 if (isQtAPI)
429 internalSignals.insert(property.notifySignal().name());
430 else if (!(superClass && superClass->indexOfProperty(property.name()) > -1))
431 dump(object, property, knownAttributes);
432 if (knownAttributes)
433 knownAttributes->knownMethod(property.notifySignal().name(),
434 0, property.revision());
435 implicitSignals.insert(property.notifySignal().name());
436 }
437
438 QJsonArray methods;
439 if (meta == &QObject::staticMetaObject) {
440 // for QObject, hide deleteLater() and onDestroyed
441 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index) {
442 QMetaMethod method = meta->method(index);
443 QByteArray signature = method.methodSignature();
444 if (signature == QByteArrayLiteral("destroyed(QObject*)")
445 || signature == QByteArrayLiteral("destroyed()")
446 || signature == QByteArrayLiteral("deleteLater()"))
447 continue;
448 dump(object, &methods, method, implicitSignals, knownAttributes);
449 }
450
451 // and add toString(), destroy() and destroy(int)
452 if (!knownAttributes || !knownAttributes->knownMethod(QByteArray("toString"), 0, 0)) {
453 QJsonObject method;
454 method["type"] = "function";
455 method["name"] = "toString";
456 methods.append(method);
457 }
458 if (!knownAttributes || !knownAttributes->knownMethod(QByteArray("destroy"), 0, 0)) {
459 QJsonObject method;
460 method["type"] = "function";
461 method["name"] = "destroy";
462 methods.append(method);
463 }
464 if (!knownAttributes || !knownAttributes->knownMethod(QByteArray("destroy"), 1, 0)) {
465 QJsonObject method;
466 method["type"] = "function";
467 method["name"] = "destroy";
468 QJsonArray parameters;
469 QJsonObject parameter;
470 parameter["type"] = "int";
471 parameter["name"] = "delay";
472 method.insert("parameters", parameters);
473 methods.append(method);
474 }
475 } else {
476 for (int index = meta->methodOffset(); index < meta->methodCount(); ++index) {
477 // Omit "Changed" methods of properties with no arguments
478 QMetaMethod meth(meta->method(index));
479 QByteArray methName(meth.name());
480 if (!methName.isEmpty() && methName.endsWith("Changed") && !meth.parameterCount())
481 continue;
482 if (internalSignals.contains(methName))
483 continue;
484 dump(object, &methods, meta->method(index), implicitSignals, knownAttributes);
485 }
486 }
487 if (!methods.empty())
488 object->insert("methods", methods);
489 }
490
491 void dumpQMLComponent(QObject* qtobject, const QString& qmlTyName, const QString& version, const QString& filename, bool isSingleton, const QStringList& internalTypes)
492 {
493 QStringList typeNameVersion(qmlTyName.split("/"));
494 QString nameSpace(typeNameVersion[0]);
495 QString typeName(typeNameVersion[1]);
496 if (internalTypes.contains(typeName))
497 return;
498
499 const QMetaObject *mainMeta = qtobject->metaObject();
500 QJsonObject object;
501 QStringList exportStrings(QStringList() << QString("%1 %2").arg(typeName).arg(version));
502 // Merge objects to get all exported versions of the same type
503 QString id(filename);
504 if (json->contains(id)) {
505 object = json->value(id).toObject();
506 QJsonArray exports(object["exports"].toArray());
507 Q_FOREACH(QJsonValue expor, exports) {
508 exportStrings.append(QString("%1").arg(expor.toString()));
509 }
510 }
511 exportStrings.removeDuplicates();
512 exportStrings.sort();
513 object.insert("exports", QJsonArray::fromStringList(exportStrings));
514 object.insert("prototype", mainMeta->superClass()->className());
515 object.insert("isComposite", true);
516 if (isSingleton) {
517 object.insert("isCreatable", false);
518 object.insert("isSingleton", true);
519 }
520
521 for (int index = mainMeta->classInfoCount() - 1 ; index >= 0 ; --index) {
522 QMetaClassInfo classInfo = mainMeta->classInfo(index);
523 if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
524 object.insert("defaultProperty", classInfo.value());
525 break;
526 }
527 }
528
529 KnownAttributes knownAttributes;
530 // Strip internal _QMLTYPE_xy suffix
531 QString prototype(QString(mainMeta->superClass()->className()).split("_")[0]);
532 // Merge internal base class
533 if (internalTypes.contains(prototype))
534 writeMetaContent(&object, mainMeta->superClass(), &knownAttributes);
535 writeMetaContent(&object, mainMeta, &knownAttributes);
536
537 object["namespace"] = nameSpace;
538 // The QML class name derived from the filename is used by AP.
539 QString className(QFileInfo(filename).baseName());
540 if (typeName != className)
541 object["className"] = className;
542 json->insert(id, object);
543 }
544
545 void dump(const QMetaObject *meta, bool isUncreatable, bool isSingleton)
546 {
547 QStringList exportStrings;
548 QSet<QQmlType> qmlTypes = qmlTypesByCppName.value(meta->className());
549 if (!qmlTypes.isEmpty()) {
550 bool foreignNamespace = false;
551
552 Q_FOREACH (QQmlType qmlTy, qmlTypes) {
553 const QString exportString = getExportString(qmlTy.qmlTypeName(),
554 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
555 qmlTy.version().majorVersion(), qmlTy.version().minorVersion()
556 #else
557 qmlTy.majorVersion(), qmlTy.minorVersion()
558 #endif
559 );
560 if (exportString.contains("/"))
561 foreignNamespace = true;
562 exportStrings.append(exportString);
563 }
564
565 // Ignore classes from different namespaces
566 if (foreignNamespace)
567 return;
568
569 // ensure exports are sorted and don't change order when the plugin is dumped again
570 std::sort(exportStrings.begin(), exportStrings.end());
571 }
572
573 QJsonObject object;
574
575 for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
576 QMetaClassInfo classInfo = meta->classInfo(index);
577 if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
578 object.insert("defaultProperty", classInfo.value());
579 break;
580 }
581 }
582
583 if (meta->superClass())
584 object.insert("prototype", meta->superClass()->className());
585
586 if (!qmlTypes.isEmpty()) {
587 object.insert("exports", QJsonArray::fromStringList(exportStrings));
588 object["namespace"] = qmlTypes.values()[0].qmlTypeName().split("/")[0];
589 object["#version"] = exportStrings.last().split(" ")[1];
590
591 if (isUncreatable)
592 object.insert("isCreatable", false);
593 if (isSingleton)
594 object.insert("isSingleton", true);
595
596 if (const QMetaObject *attachedType = (*qmlTypes.begin()).attachedPropertiesType(
597 #if QT_VERSION >= QT_VERSION_CHECK(6, 11, 0)
598 QQmlTypeLoader::get(currentEngine)
599 #else
600 QQmlEnginePrivate::get(currentEngine)
601 #endif
602 )) {
603 // Can happen when a type is registered that returns itself as attachedPropertiesType()
604 // because there is no creatable type to attach to.
605 if (attachedType != meta) {
606 object.insert("attachedType", attachedType->className());
607 }
608 }
609 }
610
611 for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
612 dump(meta->enumerator(index));
613
614 writeMetaContent(&object, meta);
615
616 QString id(meta->className());
617 // FIXME: Work-around to omit Qt types unintentionally included
618 if (convertToId(meta).startsWith("Q")) {
619 return;
620 }
621
622 // The C++ class is used by AP.
623 QString className(meta->className());
624 if (!(isSingleton || isUncreatable || exportStrings.empty()))
625 object["className"] = className;
626 json->insert(id, object);
627 }
628
629 private:
630 void writeTypeProperties(QJsonObject* object, QByteArray typeName, bool isWritable)
631 {
632 if (typeName.endsWith("*")) {
633 typeName.truncate(typeName.size() - 1);
634 object->insert("isPointer", true);
635 }
636 if (typeName.startsWith("QQmlListProperty<"))
637 object->insert("isList", true);
638 object->insert("type", QString(typeName));
639
640 if (!isWritable)
641 object->insert("isReadonly", true);
642 }
643
644 void dump(QJsonObject* object, const QMetaProperty &prop, KnownAttributes *knownAttributes = 0)
645 {
646 int revision = prop.revision();
647 QByteArray propName = prop.name();
648 if (knownAttributes && knownAttributes->knownProperty(propName, revision))
649 return;
650 // Two leading underscores: internal API
651 if (QString(propName).startsWith("__"))
652 return;
653
654 QJsonObject property;
655 if (revision)
656 property["revision"] = QString::number(revision);
657 if (revision && object->contains("#version"))
658 property["version"] = object->value("#version").toString();
659 writeTypeProperties(&property, prop.typeName(), prop.isWritable());
660 object->insert(prop.name(), property);
661 }
662
663 void dump(QJsonObject* object, QJsonArray* array, const QMetaMethod &meth, const QSet<QString> &implicitSignals,
664 KnownAttributes *knownAttributes = 0)
665 {
666 if (meth.methodType() == QMetaMethod::Signal) {
667 if (meth.access() != QMetaMethod::Public)
668 return; // nothing to do.
669 } else if (meth.access() != QMetaMethod::Public) {
670 return; // nothing to do.
671 }
672
673 QByteArray name = meth.name();
674 // Two leading underscores: internal API
675 if (name.startsWith("__"))
676 return;
677 QString typeName = meth.typeName();
678
679 if (implicitSignals.contains(name)
680 && !meth.revision()
681 && meth.methodType() == QMetaMethod::Signal
682 && meth.parameterNames().isEmpty()
683 && typeName == QLatin1String("void")) {
684 // don't mention implicit signals
685 return;
686 }
687
688 int revision = meth.revision();
689 if (knownAttributes && knownAttributes->knownMethod(name, meth.parameterNames().size(), revision))
690 return;
691
692 QJsonObject method;
693 if (meth.methodType() == QMetaMethod::Signal)
694 method["type"] = "signal";
695 else
696 method["type"] = "function";
697
698 if (revision)
699 method["revision"] = QString::number(revision);
700 if (revision && object->contains("#version"))
701 method["version"] = object->value("#version").toString();
702
703 if (typeName.endsWith("*"))
704 typeName.truncate(typeName.size() - 1);
705 if (typeName != QLatin1String("void"))
706 method["returns"] = typeName;
707
708 QJsonArray parameters;
709 for (int i = 0; i < meth.parameterTypes().size(); ++i) {
710 QByteArray argName = meth.parameterNames().at(i);
711 QJsonObject parameter;
712 parameter["name"] = QString(argName);
713 writeTypeProperties(&parameter, meth.parameterTypes().at(i), true);
714 parameters.append(parameter);
715 }
716 if (!parameters.empty())
717 method.insert("parameters", parameters);
718 method.insert("name", QString(name));
719 array->append(method);
720 }
721
722 void dump(const QMetaEnum &e)
723 {
724 // FIXME: Work-around to omit Qt types unintentionally included
725 if (QString(e.scope()).startsWith("Q"))
726 return;
727
728 QJsonObject object;
729 object["prototype"] = e.isFlag() ? "Flag" : "Enum";
730 object["namespace"] = relocatableModuleUri;
731
732 for (int index = 0; index < e.keyCount(); ++index) {
733 object[e.key(index)] = QString::number(e.value(index));
734 }
735 json->insert(QString("%1::%2").arg(e.scope()).arg(e.name()), object);
736 }
737 };
738
739 enum ExitCode {
740 EXIT_INVALIDARGUMENTS = 1,
741 EXIT_SEGV = 2,
742 EXIT_IMPORTERROR = 3
743 };
744
745 #ifdef Q_OS_UNIX
746 void sigSegvHandler(int) {
747 fprintf(stderr, "Error: SEGV\n");
748 if (!currentProperty.isEmpty())
749 fprintf(stderr, "While processing the property '%s', which probably has uninitialized data.\n", currentProperty.toLatin1().constData());
750 if (!inObjectInstantiation.isEmpty())
751 fprintf(stderr, "While instantiating the object '%s'.\n", inObjectInstantiation.toLatin1().constData());
752 exit(EXIT_SEGV);
753 }
754 #endif
755
756 void printUsage(const QString &appName)
757 {
758 std::cerr << qPrintable(QString(
759 "Usage: %1 [-v[v]] [-qml] [-json] IMPORT_URI [...IMPORT_URI]\n"
760 "\n"
761 "Generate an API description file of one or multiple components.\n"
762 "Example: %1 Lomiri.Components\n"
763 " %1 --json Lomiri.DownloadManager\n"
764 "\n"
765 "The following rules apply for inclusion of public API:\n"
766 " - Types not declared as internal in qmldir\n"
767 " - C++ types exported from a plugin\n"
768 " - Properties and functions not prefixed with __ (two underscores)\n"
769 " - Members of internal base classes become part of public components\n"
770 "").arg(
771 appName)) << std::endl;
772 }
773
774 inline std::wostream &operator<<(std::wostream &str, const QString &s)
775 {
776 str << s.toStdWString();
777 return str;
778 }
779
780 void printDebugMessage(QtMsgType, const QMessageLogContext &, const QString &msg)
781 {
782 std::wcerr << msg << std::endl;
783 // In case of QtFatalMsg the calling code will abort() when appropriate.
784 }
785
786 static QObject *s_testRootObject = 0;
787 static QObject *testRootObject(QQmlEngine *engine, QJSEngine *jsEngine)
788 {
789 Q_UNUSED(jsEngine);
790 if (!s_testRootObject) {
791 s_testRootObject = new QObject(engine);
792 }
793 return s_testRootObject;
794 }
795
796 int main(int argc, char *argv[])
797 {
798 // The default message handler might not print to console on some systems. Enforce this.
799 qInstallMessageHandler(printDebugMessage);
800 #ifdef Q_OS_UNIX
801 // qmldump may crash, but we don't want any crash handlers to pop up
802 // therefore we intercept the segfault and just exit() ourselves
803 struct sigaction sigAction;
804
805 sigemptyset(&sigAction.sa_mask);
806 sigAction.sa_handler = &sigSegvHandler;
807 sigAction.sa_flags = 0;
808
809 sigaction(SIGSEGV, &sigAction, 0);
810 #endif
811
812 // don't require a window manager even though we're a QGuiApplication
813 qputenv("QT_QPA_PLATFORM", QByteArrayLiteral("minimal"));
814
815 QGuiApplication app(argc, argv);
816 QStringList args = app.arguments();
817 args.removeFirst();
818 const QString appName = QFileInfo(app.applicationFilePath()).baseName();
819 if (args.size() < 1) {
820 printUsage(appName);
821 return EXIT_INVALIDARGUMENTS;
822 }
823
824 QLoggingCategory::setFilterRules(QStringLiteral("*=false"));
825 QStringList modules;
826 bool relocatable = true;
827 bool output_json = false, output_qml = false;
828 Q_FOREACH (const QString &arg, args) {
829 if (!arg.startsWith(QLatin1Char('-'))) {
830 modules << arg;
831 continue;
832 }
833
834 if (arg == QLatin1String("--json") || arg == QLatin1String("-json")) {
835 output_json = true;
836 } else if (arg == QLatin1String("--qml") || arg == QLatin1String("-qml")) {
837 output_qml = true;
838 } else if (arg == QLatin1String("-v")) {
839 verbose = true;
840 } else if (arg == QLatin1String("-vv")) {
841 verbose = true;
842 QLoggingCategory::setFilterRules("*");
843 } else {
844 std::cerr << "Invalid argument: " << qPrintable(arg) << std::endl;
845 return EXIT_INVALIDARGUMENTS;
846 }
847 }
848 if (modules.isEmpty()) {
849 std::cerr << "No import URI(s) provided" << std::endl;
850 printUsage(appName);
851 return EXIT_INVALIDARGUMENTS;
852 }
853
854 // By default output JSON
855 if (!output_json and !output_qml)
856 output_qml = true;
857
858 // Allow import of Qt.Test
859 qmlRegisterSingletonType<QObject>("Qt.test.qtestroot", 1, 0, "QTestRootObject", testRootObject);
860
861 QQmlEngine engine;
862 currentEngine = &engine;
863 QObject::connect(&engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
864
865 // load the QtQuick 2 plugin
866 {
867 QByteArray code("import QtQuick 2.0\nQtObject {}");
868 QQmlComponent c(&engine);
869 c.setData(code, QString("loadqtquick2.qml"));
870 c.create();
871 if (!c.errors().isEmpty()) {
872 std::cerr << "Failed to load QtQuick2 built-in" << std::endl;
873 Q_FOREACH (const QQmlError &error, c.errors())
874 std::cerr << qPrintable( error.toString() ) << std::endl;
875 return EXIT_IMPORTERROR;
876 }
877 }
878
879 // find all QMetaObjects reachable from the builtin module
880 QSet<const QMetaObject *> uncreatableMetas;
881 QSet<const QMetaObject *> singletonMetas;
882 QSet<const QMetaObject *> defaultReachable = collectReachableMetaObjects(&engine, uncreatableMetas, singletonMetas);
883
884 // add some otherwise unreachable QMetaObjects
885 defaultReachable.insert(&QQuickMouseEvent::staticMetaObject);
886 // QQuickKeyEvent, QQuickPinchEvent, QQuickDropEvent are not exported
887 QSet<QByteArray> defaultReachableNames;
888
889 // this will hold the meta objects we want to dump information of
890 QSet<const QMetaObject *> metas;
891
892 // setup static rewrites of type names
893 cppToId.insert("QString", "string");
894 cppToId.insert("QQuickItem", "Item");
895 cppToId.insert("QUrl", "url");
896 cppToId.insert("QVariant", "var");
897 cppToId.insert("QVector2D", "vector2d");
898 cppToId.insert("QVector3D", "vector3d");
899 cppToId.insert("QVector4D", "vector4d");
900 cppToId.insert("QPoint", "Qt.point");
901 cppToId.insert("QColor", "color");
902 cppToId.insert("QQmlEasingValueType::Type", "Type");
903 cppToId.insert("QTestRootObject", "QtObject");
904
905 // find a valid QtQuick import
906 QByteArray importCode;
907 QQmlType qtObjectType = QQmlMetaType::qmlType(&QObject::staticMetaObject);
908 QString module = qtObjectType.qmlTypeName();
909 module = module.mid(0, module.lastIndexOf(QLatin1Char('/')));
910 importCode = QString("import %1 %2.%3\n").arg(module,
911 QString::number(
912 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
913 qtObjectType.version().majorVersion()
914 #else
915 qtObjectType.majorVersion()
916 #endif
917 ),
918 QString::number(
919 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
920 qtObjectType.version().minorVersion())
921 #else
922 qtObjectType.minorVersion())
923 #endif
924 ).toUtf8();
925
926 QStringList internalTypes;
927 // create an object that will be the API description
928 QJsonObject json;
929
930 Q_FOREACH (const QString& pluginImportUri, modules) {
931 QString pluginImportVersion;
932 QStringList pathList((QString(getenv("QML2_IMPORT_PATH"))
933 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
934 + ":" + QLibraryInfo::location(QLibraryInfo::Qml2ImportsPath))
935 #else
936 + ":" + QLibraryInfo::path(QLibraryInfo::Qml2ImportsPath))
937 #endif
938 #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
939 .split(':', QString::SkipEmptyParts));
940 #else
941 .split(':', Qt::SkipEmptyParts));
942 #endif
943
944 QFile qmlDirFile;
945 QString pluginModulePath;
946 Q_FOREACH(const QString& path, pathList) {
947 // Bacon2D.1.0 → Bacon2D 1.0
948 pluginModulePath = path + "/" + QString(pluginImportUri) + ".1.0";
949 qmlDirFile.setFileName(pluginModulePath + "/qmldir");
950 if (qmlDirFile.exists() && qmlDirFile.open(QIODevice::ReadOnly)) {
951 engine.addImportPath(pluginModulePath);
952 break;
953 }
954 // com.Canonical.Oxide → com/Canonical/Oxide
955 pluginModulePath = path + "/" + QString(pluginImportUri).replace(".", "/");
956 qmlDirFile.setFileName(pluginModulePath + "/qmldir");
957 if (qmlDirFile.exists() && qmlDirFile.open(QIODevice::ReadOnly)) {
958 engine.addImportPath(pluginModulePath);
959 break;
960 }
961 }
962 if (verbose)
963 std::cout << "Reading " << qPrintable(qmlDirFile.fileName()) << std::endl;
964 if (!qmlDirFile.isOpen()) {
965 std::cerr << "Failed to read " << qPrintable(qmlDirFile.fileName()) << std::endl;
966 return EXIT_IMPORTERROR;
967 }
968
969 QQmlDirParser p;
970 p.parse(qmlDirFile.readAll());
971 if (p.hasError()) {
972 std::cerr << "Failed to read " << qPrintable(qmlDirFile.fileName()) << std::endl;
973 #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
974 Q_FOREACH (const QQmlJS::DiagnosticMessage &e, p.errors(qmlDirFile.fileName())) {
975 QString errorString = QLatin1String("qmldir");
976 #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
977 if (e.loc.startLine > 0) {
978 errorString += QLatin1Char(':') + QString::number(e.loc.startLine);
979 if (e.loc.startColumn > 0)
980 errorString += QLatin1Char(':') + QString::number(e.loc.startColumn);
981 }
982 #else
983 if (e.line > 0) {
984 errorString += QLatin1Char(':') + QString::number(e.line);
985 if (e.column > 0)
986 errorString += QLatin1Char(':') + QString::number(e.column);
987 }
988 #endif
989
990 errorString += QLatin1String(": ") + e.message;
991 std::cerr << qPrintable( errorString ) << std::endl;
992 }
993 #else
994 Q_FOREACH (const QQmlError &error, p.errors(qmlDirFile.fileName()))
995 std::cerr << qPrintable( error.toString() ) << std::endl;
996 #endif
997 return EXIT_IMPORTERROR;
998 }
999
1000 // find all QMetaObjects reachable when the specified module is imported
1001 QStringList importVersions;
1002 if (pluginImportVersion.isEmpty()) {
1003 // Collect all the available versioned imports
1004 int highestMajor = 0, highestMinor = 1;
1005 Q_FOREACH(QQmlDirParser::Component c, p.components()) {
1006 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1007 if (!c.version.hasMajorVersion() || !c.version.hasMinorVersion()) {
1008 continue;
1009 }
1010 int majorVersion = c.version.majorVersion();
1011 int minorVersion = c.version.minorVersion();
1012 #else
1013 // Work-around for version -1, -1
1014 if (c.majorVersion == -1) {
1015 continue;
1016 }
1017 int majorVersion = c.majorVersion;
1018 int minorVersion = c.minorVersion;
1019 #endif
1020 // pluginImportVersion can be empty, pick latest
1021 if (majorVersion > highestMajor) {
1022 highestMajor = majorVersion;
1023 highestMinor = minorVersion;
1024 } else if (majorVersion == highestMajor && minorVersion > highestMinor) {
1025 highestMinor = minorVersion;
1026 }
1027 importVersions << QString("%1.%2").arg(majorVersion).arg(minorVersion);
1028 }
1029 pluginImportVersion = QString("%1.%2").arg(highestMajor).arg(highestMinor);
1030 }
1031 importVersions << pluginImportVersion;
1032 importVersions.removeDuplicates();
1033
1034 // Create a component with all QML types to add them to the type system
1035 QByteArray code = importCode;
1036 Q_FOREACH(const QString& version, importVersions) {
1037 // First letter must be uppercase
1038 QString pluginAlias(QString("A%1.%2").arg(pluginImportUri).arg(version).replace(".", "_"));
1039 code += QString("import %1 %2 as %3\n").arg(pluginImportUri).arg(version).arg(pluginAlias).toUtf8();
1040 }
1041 code += "QtObject { }\n";
1042 if (verbose)
1043 std::cerr << "Importing QML components:" << std::endl << qPrintable(code) << std::endl;
1044
1045 QQmlComponent c(&engine);
1046 c.setData(code, QUrl::fromLocalFile(qmlDirFile.fileName()));
1047 std::cerr << "Creating QML component for " << qPrintable(pluginImportUri) << std::endl;
1048 c.create();
1049 if (!c.errors().isEmpty()) {
1050 Q_FOREACH (const QQmlError &error, c.errors()) {
1051 // Despite the error we get all type information we need from singletons
1052 if (error.description().contains(QRegularExpression("(Composite Singleton Type .+|Element) is not creatable")))
1053 std::cerr << qPrintable(error.toString()) << std::endl;
1054 if (error.description().contains(QRegularExpression("(Composite Singleton Type .+|Element) is not creatable")))
1055 continue;
1056 // If we guessed the version, we may have been wrong
1057 if (error.description().contains(QRegularExpression("version .+ is not installed"))) {
1058 // First letter must be uppercase
1059 QString pluginAlias(QString("A%1.%2").arg(pluginImportUri).replace(".", "_"));
1060 // 1.0 should work if 0.1 didn't and qmldir didn't specify
1061 code += QString("import %1 1.0 as %3\n").arg(pluginImportUri).arg(pluginAlias).toUtf8();
1062 c.setData(code, QUrl::fromLocalFile(qmlDirFile.fileName()));
1063 std::cerr << "Re-creating QML component for " << qPrintable(pluginImportUri) << std::endl;
1064 c.create();
1065 // This time around it worked
1066 if (!c.errors().isEmpty())
1067 continue;
1068 }
1069 std::cerr << "Failed to load " << qPrintable(pluginImportUri) << std::endl;
1070 std::cerr << qPrintable(code) << std::endl;
1071 std::cerr << qPrintable( error.toString() ) << std::endl;
1072 return EXIT_IMPORTERROR;
1073 }
1074 }
1075
1076 Q_FOREACH(QQmlDirParser::Component c, p.components()) {
1077 // Map filename-based PageHeadConfiguration11 to PageHeadConfiguration
1078 QString filename(QFileInfo(c.fileName).baseName());
1079 cppToId.insert(qPrintable(filename), qPrintable(c.typeName));
1080
1081 if (c.internal) {
1082 internalTypes.append(c.typeName);
1083 continue;
1084 }
1085 if (
1086 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1087 c.version.majorVersion()
1088 #else
1089 c.majorVersion
1090 #endif
1091 == -1) {
1092 std::cerr << "Public QML type " << qPrintable(c.typeName) << " in qmldir has no version!" << std::endl;
1093 return EXIT_IMPORTERROR;
1094 }
1095 }
1096
1097 QList<QQmlType> defaultTypes = QQmlMetaType::qmlTypes();
1098 QSet<const QMetaObject *> candidates = collectReachableMetaObjects(&engine, uncreatableMetas, singletonMetas, defaultTypes);
1099 candidates.subtract(defaultReachable);
1100
1101 // Also eliminate meta objects with the same classname.
1102 // This is required because extended objects seem not to share
1103 // a single meta object instance.
1104 Q_FOREACH (const QMetaObject *mo, defaultReachable)
1105 defaultReachableNames.insert(QByteArray(mo->className()));
1106 Q_FOREACH (const QMetaObject *mo, candidates) {
1107 if (!defaultReachableNames.contains(mo->className()))
1108 metas.insert(mo);
1109 }
1110
1111 QMultiMap<QString, QString> scripts;
1112 QString preferredPath = pluginModulePath + "/";
1113 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1114 if (!p.preferredPath().isEmpty())
1115 preferredPath = p.preferredPath();
1116 #endif
1117 Q_FOREACH(QQmlDirParser::Script s, p.scripts()) {
1118 QFile sf(s.fileName[0] == 'q' ? QString(s.fileName).replace("qrc:/", ":/") : preferredPath + s.fileName);
1119 if (!sf.open(QIODevice::ReadOnly)) {
1120 std::cerr << "Failed to read " << qPrintable(sf.fileName()) << std::endl;
1121 return EXIT_IMPORTERROR;
1122 }
1123 scripts.insert(s.nameSpace, QString("%1 %2.%3").arg(s.nameSpace).arg(
1124 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1125 s.version.majorVersion()
1126 #else
1127 s.majorVersion
1128 #endif
1129 ).arg(
1130 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1131 s.version.minorVersion()
1132 #else
1133 s.minorVersion
1134 #endif
1135 ));
1136 }
1137
1138 Q_FOREACH(QString nameSpace, scripts.uniqueKeys()) {
1139 QJsonObject script;
1140 script["type"] = "script";
1141 QJsonArray exports(QJsonArray::fromStringList(scripts.values(nameSpace)));
1142 script["exports"] = exports;
1143 script["namespace"] = pluginImportUri;
1144 json[nameSpace] = script;
1145 }
1146
1147 // put the metaobjects into a map so they are always dumped in the same order
1148 QMultiMap<QString, const QMetaObject *> nameToMeta;
1149 Q_FOREACH (const QMetaObject *meta, metas)
1150 nameToMeta.insert(convertToId(meta), meta);
1151
1152 Dumper dumper(&json);
1153 if (relocatable)
1154 dumper.setRelocatableModuleUri(pluginImportUri);
1155 dumper.setImportVersion(pluginImportVersion);
1156 Q_FOREACH (const QMetaObject *meta, nameToMeta) {
1157 dumper.dump(meta, uncreatableMetas.contains(meta), singletonMetas.contains(meta));
1158 }
1159 Q_FOREACH(QQmlDirParser::Component c, p.components()) {
1160 if (c.internal)
1161 continue;
1162 QString version(QString("%1.%2").arg(
1163 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1164 c.version.majorVersion()
1165 #else
1166 c.majorVersion
1167 #endif
1168 ).arg(
1169 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1170 c.version.minorVersion()
1171 #else
1172 c.minorVersion
1173 #endif
1174 ));
1175 // Work-around for version -1, -1
1176 if (
1177 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1178 c.version.majorVersion()
1179 #else
1180 c.majorVersion
1181 #endif
1182 == -1)
1183 version = pluginImportVersion;
1184 QQmlComponent e(&engine,
1185 c.fileName[0] == 'q' ? QUrl(c.fileName) : preferredPath[0] == ':' ?
1186 QUrl(QString("qrc") + preferredPath + c.fileName) :
1187 QUrl::fromLocalFile(preferredPath + c.fileName));
1188 QObject* qtobject(e.create());
1189 if (!qtobject) {
1190 std::cerr << "Failed to instantiate " << qPrintable(c.typeName) << " from " << qPrintable(e.url().toString()) << std::endl;
1191 Q_FOREACH (const QQmlError &error, e.errors())
1192 std::cerr << qPrintable(error.toString()) << std::endl;
1193 exit(1);
1194 }
1195 dumper.dumpQMLComponent(qtobject, pluginImportUri + "/" + c.typeName, version, e.url().toString(), c.singleton, internalTypes);
1196 }
1197 Q_FOREACH(const QQmlType compositeType, qmlTypesByCompositeName) {
1198 QQmlComponent e(&engine, compositeType.sourceUrl());
1199 if (!e.isReady()) {
1200 std::cerr << "Failed to create " << qPrintable(compositeType.qmlTypeName()) << " from " << qPrintable(e.url().toString()) << std::endl;
1201 exit(1);
1202 }
1203 QObject* qtobject(e.create());
1204 if (!qtobject) {
1205 std::cerr << "Failed to instantiate " << qPrintable(compositeType.qmlTypeName()) << " from " << qPrintable(e.url().toString()) << std::endl;
1206 Q_FOREACH (const QQmlError &error, e.errors())
1207 std::cerr << qPrintable(error.toString()) << std::endl;
1208 exit(1);
1209 }
1210 QString version(QString("%1.%2").arg(
1211 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1212 compositeType.version().majorVersion()
1213 #else
1214 compositeType.majorVersion()
1215 #endif
1216 ).arg(
1217 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1218 compositeType.version().minorVersion()
1219 #else
1220 compositeType.minorVersion()
1221 #endif
1222 ));
1223 // Work-around for version -1, -1
1224 if (
1225 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1226 compositeType.version().majorVersion()
1227 #else
1228 compositeType.majorVersion()
1229 #endif
1230 == -1)
1231 version = pluginImportVersion;
1232 QString typeName(compositeType.qmlTypeName());
1233 if (!json.contains(e.url().toString()) && typeName.contains("/"))
1234 dumper.dumpQMLComponent(qtobject, typeName, version, e.url().toString(), compositeType.isSingleton(), internalTypes);
1235 }
1236 }
1237
1238 if (output_json) {
1239 // write JSON representation of the API
1240 QJsonDocument jsonDoc(json);
1241 std::cout << qPrintable(jsonDoc.toJson());
1242 }
1243
1244 if (output_qml) {
1245 // write QML representation of the API
1246 QStringList keys(json.keys());
1247
1248 // Sort by exports
1249 QMultiMap<QString, QString>byExports;
1250 Q_FOREACH(const QString& key, keys) {
1251 QJsonValue value(json[key]);
1252 if (value.isObject()) {
1253 QJsonObject object(value.toObject());
1254 QStringList exports;
1255 Q_FOREACH (const QJsonValue& expor, object["exports"].toArray())
1256 exports.append(expor.toString());
1257 // Reverse exports: latest to oldest
1258 for(int k = 0; k < (exports.size() / 2); k++)
1259 #if QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)
1260 exports.swapItemsAt(k, exports.size() - (1 + k));
1261 #else
1262 exports.swap(k, exports.size() - (1 + k));
1263 #endif
1264 QStringList sortedExports;
1265 if (!exports.isEmpty()) {
1266 QString currentTypeName;
1267 Q_FOREACH(QJsonValue expor, exports) {
1268 QStringList nextType(expor.toString().split(" "));
1269 if (nextType[0] != currentTypeName) {
1270 currentTypeName = nextType[0];
1271 sortedExports.append(currentTypeName);
1272 }
1273 sortedExports.append(nextType[1]);
1274 }
1275 } else
1276 sortedExports.append(convertToId(key));
1277 // Exports may not be unique across namespaces ie. Header
1278 byExports.insert(sortedExports.join(" "), key);
1279 }
1280 }
1281
1282 QMultiMap<QString, QString>::const_iterator i = byExports.constBegin();
1283 while (i != byExports.constEnd()) {
1284 QString exports(i.key());
1285 QString key(i.value());
1286 QJsonValue value(json[key]);
1287 if (value.isObject()) {
1288 QJsonObject object(value.toObject());
1289 QString signature(exports);
1290 if (object.contains("namespace"))
1291 signature = object.take("namespace").toString() + "." + signature;
1292 if (object.contains("className"))
1293 signature += " " + object.take("className").toString();
1294 QString prototype(object.take("prototype").toString());
1295 if (!prototype.isEmpty())
1296 signature += ": " + convertToId(prototype);
1297 if (object.contains("isSingleton"))
1298 signature += " singleton";
1299 signature += "\n";
1300 Q_FOREACH(const QString& fieldName, object.keys()) {
1301 if (fieldName == "methods") {
1302 QJsonArray values(object[fieldName].toArray());
1303 Q_FOREACH(const QJsonValue& value, values) {
1304 QJsonObject valu(value.toObject());
1305 signature += " ";
1306 signature += valu["type"].toString() + " ";
1307 if (valu.contains("returns"))
1308 signature += convertToId(valu["returns"].toString()) + " ";
1309 QStringList args;
1310 if (valu.contains("parameters")) {
1311 Q_FOREACH(const QJsonValue& parameterValue, valu["parameters"].toArray()) {
1312 QJsonObject parameter(parameterValue.toObject());
1313 args.append(convertToId(parameter["type"].toString()) + " " + parameter["name"].toString());
1314 }
1315 }
1316 signature += valu["name"].toString() + "(" + args.join(", ") + ")";
1317 if (valu.contains("version"))
1318 signature += " " + valu["version"].toString();
1319 signature += "\n";
1320 }
1321 continue;
1322 }
1323 QJsonObject field(object[fieldName].toObject());
1324 if (!(field.contains("type") || prototype == "Enum" || prototype == "Flag"))
1325 continue;
1326 signature += " ";
1327 if (object["defaultProperty"] == fieldName)
1328 signature += "default ";
1329 // in QML semantics lists are not read-only
1330 if (field.contains("isReadonly") && !field.contains("isList"))
1331 signature += "readonly ";
1332 if (field.contains("type"))
1333 signature += "property " + QString(convertToId(field["type"].toString())) + " ";
1334 signature += fieldName;
1335 if (field.contains("version"))
1336 signature += " " + QString(field["version"].toString());
1337 signature += "\n";
1338 }
1339 std::cout << qPrintable(signature);
1340 }
1341 i++;
1342 }
1343 }
1344
1345 // workaround to avoid crashes on exit
1346 QTimer timer;
1347 timer.setSingleShot(true);
1348 timer.setInterval(0);
1349 QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));
1350 timer.start();
1351
1352 return app.exec();
1353 }