summaryrefslogtreecommitdiffstats
path: root/src/tools/dumpqmltypes/dumpqmltypes.cpp
blob: e767b7c219c564cbf032bd70565625a68baf35f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/****************************************************************************
**
** Copyright (C) 2019 Luxoft Sweden AB
** Copyright (C) 2018 Pelagicore AG
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Luxoft Application Manager.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT-QTAS$
** Commercial License Usage
** Licensees holding valid commercial Qt Automotive Suite licenses may use
** this file in accordance with the commercial license agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and The Qt Company.  For
** licensing terms and conditions see https://www.qt.io/terms-conditions.
** For further information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtAppManInstaller/applicationinstaller.h>
#include <QtAppManManager/applicationmanager.h>
#include <QtAppManManager/applicationmodel.h>
#include <QtAppManManager/amnamespace.h>
#include <QtAppManManager/applicationipcmanager.h>
#include <QtAppManManager/applicationipcinterface.h>
#include <QtAppManManager/application.h>
#include <QtAppManManager/abstractruntime.h>
#include <QtAppManManager/abstractcontainer.h>
#include <QtAppManManager/notificationmanager.h>
#include <QtAppManNotification/notification.h>
#include <QtAppManManager/notificationmanager.h>
#include <QtAppManManager/qmlinprocessapplicationinterface.h>
#include <QtAppManWindow/windowmanager.h>
#include <QtAppManWindow/window.h>
#include <QtAppManWindow/windowitem.h>
#include <QtAppManLauncher/qmlapplicationinterface.h>
#include <QtAppManLauncher/qmlapplicationinterfaceextension.h>
#include <QtAppManLauncher/private/applicationmanagerwindow_p.h>
#include <QtAppManIntentServer/intent.h>
#include <QtAppManIntentServer/intentserver.h>
#include <QtAppManIntentClient/intentclient.h>
#include <QtAppManIntentClient/intentclientrequest.h>
#include <QtAppManIntentClient/intenthandler.h>
#include <QtAppManMonitor/cpustatus.h>
#include <QtAppManMonitor/gpustatus.h>
#include <QtAppManMonitor/memorystatus.h>
#include <QtAppManMonitor/iostatus.h>
#include <QtAppManMonitor/processstatus.h>
#include <QtAppManMonitor/frametimer.h>
#include <QtAppManMonitor/monitormodel.h>
#include <QtAppManCommon/global.h>
#include <QtAppManCommon/exception.h>

#include <QCoreApplication>
#include <QCommandLineParser>
#include <QLibraryInfo>
#include <stdio.h>

QT_USE_NAMESPACE_AM

static const QVector<const QMetaObject *> all = {
    // manager-lib
    &ApplicationManager::staticMetaObject,
    &ApplicationInstaller::staticMetaObject,
    &NotificationManager::staticMetaObject,
    &ApplicationIPCManager::staticMetaObject,
    &AbstractApplication::staticMetaObject,
    &AbstractRuntime::staticMetaObject,
    &AbstractContainer::staticMetaObject,
    &Notification::staticMetaObject,
    &QmlApplicationInterface::staticMetaObject,
    &QmlApplicationInterfaceExtension::staticMetaObject,
    &ApplicationManagerWindow::staticMetaObject,
    &ApplicationModel::staticMetaObject,
    &Am::staticMetaObject,
    &ApplicationIPCInterface::staticMetaObject,
    &ApplicationIPCInterfaceAttached::staticMetaObject,

    // window-lib
    &WindowManager::staticMetaObject,
    &Window::staticMetaObject,
    &WindowItem::staticMetaObject,

    // intent-client-lib
    &IntentClient::staticMetaObject,
    &IntentClientRequest::staticMetaObject,
    &IntentHandler::staticMetaObject,

    // intent-server-lib
    &IntentServer::staticMetaObject,
    &Intent::staticMetaObject,

    // monitor-lib
    &CpuStatus::staticMetaObject,
    &GpuStatus::staticMetaObject,
    &MemoryStatus::staticMetaObject,
    &IoStatus::staticMetaObject,
    &ProcessStatus::staticMetaObject,
    &FrameTimer::staticMetaObject,
    &MonitorModel::staticMetaObject
};


static QByteArray qmlTypeForMetaObect(const QMetaObject *mo, int level, bool indentFirstLine)
{
    static auto stripNamespace = [](const QByteArray &identifier) -> QByteArray {
        int pos = identifier.lastIndexOf("::");
        return pos < 0 ? identifier : identifier.mid(pos + 2);
    };
    static auto mapTypeName = [](const QByteArray &type, bool stripPointer) -> QByteArray {
        if (type == "QString") {
            return "string";
        } else if (type == "qlonglong") {
            return "int";
        } else {
            QByteArray ba = type;
            if (ba.startsWith("const "))
                ba = ba.mid(6);
            ba = stripNamespace(ba);
            if (stripPointer && ba.endsWith('*'))
                ba.chop(1);
            return ba;
        }
    };

    QByteArray str;
    QByteArray indent1 = QByteArray(level * 4, ' ');
    QByteArray indent2 = QByteArray((level + 1) * 4, ' ');
    QByteArray indent3 = QByteArray((level + 2) * 4, ' ');

    if (indentFirstLine)
        str.append(indent1);

    str = str + "Component {\n";
    str = str
            + indent2
            + "name: \""
            + stripNamespace(mo->className())
            + "\"\n";

    if (mo->superClass()) {
        str = str
                + indent2
                + "prototype: \""
                + stripNamespace(mo->superClass()->className())
                + "\"\n";
    }

    for (int i = mo->classInfoOffset(); i < mo->classInfoCount(); ++i) {
        QMetaClassInfo c = mo->classInfo(i);
        if (qstrcmp(c.name(), "AM-QmlType") == 0) {
            QByteArray type = c.value();
            int rev = type.mid(type.lastIndexOf('.')).toInt();

            str = str + indent2 + "exports: [ \"" + type + "\" ]\n";
            str = str + indent2 + "exportMetaObjectRevisions: [ " + QByteArray::number(rev) + " ]\n";
            break;
        }
    }

    for (int i = mo->propertyOffset(); i < mo->propertyCount(); ++i) {
        QMetaProperty p = mo->property(i);
        str = str
                + indent2
                + "Property { name: \"" + p.name()
                + "\"; type: \"" + mapTypeName(p.typeName(), true) + "\";";
        if (QByteArray(p.typeName()).endsWith('*'))
            str += " isPointer: true;";
        if (!p.isWritable())
            str += " isReadonly: true";
        str = str + " }\n";
    }

    for (int i = mo->methodOffset(); i < mo->methodCount(); ++i) {
        QMetaMethod m = mo->method(i);

        // suppress D-Bus interfaces
        if (isupper(m.name().at(0)))
            continue;

        QByteArray methodtype;
        if (m.methodType() == QMetaMethod::Signal) {
            methodtype = "Signal";
            if (m.access() == QMetaMethod::Private)
                continue;
        } else {
            if (m.access() != QMetaMethod::Public)
                continue;
            methodtype = "Method";
        }

        str = str
                + indent2
                + methodtype + " {\n" + indent3 + "name: \"" + m.name() + "\"\n";
        if (qstrcmp(m.typeName(), "void") != 0)
            str = str + indent3 + "type: \"" + mapTypeName(m.typeName(), false) + "\"\n";

        for (int j = 0; j < m.parameterCount(); ++j) {
            str = str
                    + indent3 + "Parameter { name: \""
                    + m.parameterNames().at(j) + "\"; type: \"" + mapTypeName(m.parameterTypes().at(j), true) + "\";";
            if (m.parameterTypes().at(j).endsWith('*'))
                str += " isPointer: true;";
            str = str + " }\n";
        }

        str = str + indent2 + "}\n";
    }

    str.append(indent1);
    str.append("}\n");
    return str;
}

int main(int argc, char **argv)
{
    try {
        QCoreApplication::setApplicationName(qSL("ApplicationManager qmltypes dumper"));
        QCoreApplication::setOrganizationName(qSL("Luxoft Sweden AB"));
        QCoreApplication::setOrganizationDomain(qSL("luxoft.com"));
        QCoreApplication::setApplicationVersion(qSL(AM_VERSION));

        QCoreApplication a(argc, argv);
        Q_UNUSED(a)
        QCommandLineParser clp;

        const char *desc =
                "Luxoft ApplicationManager qmltypes dumper"
                "\n\n"
                "This tool is used to generate the qmltypes type information for all ApplicationManager\n"
                "classes to get auto-completion in QtCreator.\n"
                "Either install the resulting output as $QTDIR/qml/QtApplicationManager/plugins.qmltypes\n"
                "or simply run this tool with the --install option.\n";

        clp.setApplicationDescription(qL1S(desc));
        clp.addHelpOption();
        clp.addVersionOption();
        clp.addOption({ qSL("install"), qSL("directly install into the Qt directory.") });
        clp.addPositionalArgument(qSL("destination"), qSL("Destination directory where the qmltypes information is created."), qSL("dir"));

        if (!clp.parse(QCoreApplication::arguments()))
            throw Exception(clp.errorText());

        if (clp.isSet(qSL("version")))
            clp.showVersion();
        if (clp.isSet(qSL("help")))
            clp.showHelp();

        QDir outDir;

        if (clp.isSet(qSL("install")) && clp.positionalArguments().isEmpty()) {
            outDir = QLibraryInfo::location(QLibraryInfo::Qml2ImportsPath);
            if (!outDir.exists())
                throw Exception("Qt's QML2 imports directory (%1) is missing.")
                    .arg(outDir.absolutePath());
        } else if (clp.positionalArguments().count() == 1) {
            outDir = clp.positionalArguments().first();
            if (!outDir.mkpath(qSL(".")))
                throw Exception("Cannot create destination directory %1.").arg(outDir.absolutePath());
        } else {
            throw Exception("You need to either specify a destination directory or run with --install.");
        }


        QMultiMap<QString, const QMetaObject *> imports;
        QVector<QByteArray> sanityCheck; // check for copy&paste errors

        for (const auto &mo : all) {
            bool foundType = false;
            for (int i = mo->classInfoOffset(); (i < mo->classInfoCount()) && !foundType; ++i) {
                QMetaClassInfo c = mo->classInfo(i);
                if (qstrcmp(c.name(), "AM-QmlType") == 0) {
                    QByteArray type = c.value();
                    QByteArray import = type.left(type.indexOf('/'));

                    imports.insert(QString::fromLatin1(import), mo);
                    foundType = true;

                    if (sanityCheck.contains(type))
                        throw Exception("Q_CLASSINFO(\"AM-QmlType\", \"%1\") was found multiple times").arg(type);
                    sanityCheck << type;
                }
            }
            if (!foundType)
                throw Exception("Missing Q_CLASSINFO(\"AM-QmlType\", \"...\") on class %1").arg(mo->className());
        }

        for (auto it = imports.keyBegin(); it != imports.keyEnd(); ++it) {
            QString importPath = *it;
            importPath.replace(qL1C('.'), qL1C('/'));

            QDir importDir = outDir;
            if (!importDir.mkpath(importPath))
                throw Exception("Cannot create directory %1/%2").arg(importDir.absolutePath(), importPath);
            if (!importDir.cd(importPath))
                throw Exception("Cannot cd into directory %1/%2").arg(importDir.absolutePath(), importPath);

            QFile qmldirFile(importDir.absoluteFilePath(qSL("qmldir")));
            if (!qmldirFile.open(QFile::WriteOnly))
                throw Exception(qmldirFile, "Failed to open for writing");
            QTextStream qmldirOut(&qmldirFile);
            qmldirOut << "typeinfo plugins.qmltypes\n";
            qmldirFile.close();

            QFile typesFile(importDir.absoluteFilePath(qSL("plugins.qmltypes")));
            if (!typesFile.open(QFile::WriteOnly))
                throw Exception(typesFile, "Failed to open for writing");
            QTextStream typesOut(&typesFile);

            const char *header = \
                    "import QtQuick.tooling 1.2\n"
                    "\n"
                    "// This file describes the plugin-supplied types contained in the application-manager.\n"
                    "// It is used for QML tooling purposes only.\n"
                    "//\n"
                    "// This file was auto-generated by:\n"
                    "// appman-dumpqmltypes\n"
                    "\n"
                    "Module {\n"
                    "    dependencies: []\n";
            const char *footer = "}\n";

            typesOut << header;

            auto mos = imports.values(*it);
            for (const auto &mo : qAsConst(mos))
                typesOut << qmlTypeForMetaObect(mo, 1, true);

            typesOut << footer;
        }
    } catch (const Exception &e) {
        fprintf(stderr, "%s\n", qPrintable(e.errorString()));
        return 1;
    }
    return 0;
}