aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmlprojectmanager/buildsystem/projectitem/converters.cpp
blob: 8487c00cd7e60d677ca271a52e3738d290ffe991 (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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0

#include "converters.h"

#include <QJsonArray>

namespace QmlProjectManager::Converters {

using PropsPair = QPair<QString, QStringList>;
struct FileProps
{
    const PropsPair image{"image",
                          QStringList{"*.jpeg", "*.jpg", "*.png", "*.svg", "*.hdr", ".ktx"}};
    const PropsPair qml{"qml", QStringList{"*.qml"}};
    const PropsPair qmlDir{"qmldir", QStringList{"qmldir"}};
    const PropsPair javaScr{"javaScript", QStringList{"*.js", "*.ts"}};
    const PropsPair video{"video", QStringList{"*.mp4"}};
    const PropsPair sound{"sound", QStringList{"*.mp3", "*.wav"}};
    const PropsPair font{"font", QStringList{"*.ttf", "*.otf"}};
    const PropsPair config{"config", QStringList{"*.conf"}};
    const PropsPair styling{"styling", QStringList{"*.css"}};
    const PropsPair mesh{"meshes", QStringList{"*.mesh"}};
    const PropsPair
        shader{"shader",
               QStringList{"*.glsl", "*.glslv", "*.glslf", "*.vsh", "*.fsh", "*.vert", "*.frag"}};
};

QString jsonToQmlProject(const QJsonObject &rootObject)
{
    QString qmlProjectString;
    QTextStream ts{&qmlProjectString};

    QJsonObject runConfig = rootObject["runConfig"].toObject();
    QJsonObject languageConfig = rootObject["language"].toObject();
    QJsonObject shaderConfig = rootObject["shaderTool"].toObject();
    QJsonObject versionConfig = rootObject["versions"].toObject();
    QJsonObject environmentConfig = rootObject["environment"].toObject();
    QJsonObject deploymentConfig = rootObject["deployment"].toObject();
    QJsonObject filesConfig = rootObject["fileGroups"].toObject();

    int indentationLevel = 0;

    auto appendBreak = [&ts]() { ts << Qt::endl; };

    auto appendComment = [&ts, &indentationLevel](const QString &comment) {
        ts << QString(" ").repeated(indentationLevel * 4) << "// " << comment << Qt::endl;
    };

    auto appendItem =
        [&ts, &indentationLevel](const QString &key, const QString &value, const bool isEnclosed) {
            ts << QString(" ").repeated(indentationLevel * 4) << key << ": "
               << (isEnclosed ? "\"" : "") << value << (isEnclosed ? "\"" : "") << Qt::endl;
        };

    auto appendString = [&appendItem](const QString &key, const QString &val) {
        appendItem(key, val, true);
    };

    auto appendBool = [&appendItem](const QString &key, const bool &val) {
        appendItem(key, QString::fromStdString(val ? "true" : "false"), false);
    };

    auto appendArray = [&appendItem](const QString &key, const QStringList &vals) {
        QString finalString;
        foreach (const QString &value, vals) {
            finalString.append("\"").append(value).append("\"").append(",");
        }
        finalString.remove(finalString.length() - 1, 1);
        finalString.prepend("[ ").append(" ]");
        appendItem(key, finalString, false);
    };

    auto startObject = [&ts, &indentationLevel](const QString &objectName) {
        ts << Qt::endl
           << QString(" ").repeated(indentationLevel * 4) << objectName << " {" << Qt::endl;
        indentationLevel++;
    };

    auto endObject = [&ts, &indentationLevel]() {
        indentationLevel--;
        ts << QString(" ").repeated(indentationLevel * 4) << "}" << Qt::endl;
    };

    auto appendDirectories =
        [&startObject, &endObject, &appendString, &filesConfig](const QString &jsonKey,
                                                                const QString &qmlKey) {
            QJsonValue dirsObj = filesConfig[jsonKey].toObject()["directories"];
            QStringList dirs = dirsObj.toVariant().toStringList();
            foreach (const QString &directory, dirs) {
                startObject(qmlKey);
                appendString("directory", directory);
                endObject();
            }
        };

    auto appendFiles = [&startObject,
                        &endObject,
                        &appendString,
                        &appendArray,
                        &filesConfig](const QString &jsonKey, const QString &qmlKey) {
        QJsonValue dirsObj = filesConfig[jsonKey].toObject()["directories"];
        QJsonValue filesObj = filesConfig[jsonKey].toObject()["files"];
        QJsonValue filtersObj = filesConfig[jsonKey].toObject()["filters"];

        foreach (const QString &directory, dirsObj.toVariant().toStringList()) {
            startObject(qmlKey);
            appendString("directory", directory);
            appendString("filters", filtersObj.toVariant().toStringList().join(";"));

            if (!filesObj.toArray().isEmpty()) {
                QStringList fileList;
                foreach (const QJsonValue &file, filesObj.toArray()) {
                    fileList.append(file.toObject()["name"].toString());
                }
                appendArray("files", fileList);
            }
            endObject();
        }
    };

    // start creating the file content
    appendComment("prop: json-converted");
    appendComment("prop: auto-generated");

    ts << Qt::endl << "import QmlProject" << Qt::endl;
    {
        startObject("Project");

        { // append non-object props
            appendString("mainFile", runConfig["mainFile"].toString());
            appendString("mainUiFile", runConfig["mainUiFile"].toString());
            appendString("targetDirectory", deploymentConfig["targetDirectory"].toString());
            appendBool("widgetApp", runConfig["widgetApp"].toBool());
            appendArray("importPaths", rootObject["importPaths"].toVariant().toStringList());
            appendBreak();
            appendString("qdsVersion", versionConfig["designStudio"].toString());
            appendString("quickVersion", versionConfig["qtQuick"].toString());
            appendBool("qt6Project", versionConfig["qt"].toString() == "6");
            appendBool("qtForMCUs", !(rootObject["mcuConfig"].toObject().isEmpty()));
            appendBreak();
            appendBool("multilanguageSupport", languageConfig["multiLanguageSupport"].toBool());
            appendString("primaryLanguage", languageConfig["primaryLanguage"].toString());
            appendArray("supportedLanguages",
                        languageConfig["supportedLanguages"].toVariant().toStringList());
        }

        { // append Environment object
            startObject("Environment");
            foreach (const QString &key, environmentConfig.keys()) {
                appendItem(key, environmentConfig[key].toString(), true);
            }
            endObject();
        }

        { // append ShaderTool object
            if (!shaderConfig["args"].toVariant().toStringList().isEmpty()) {
                startObject("ShaderTool");
                appendString("args",
                             shaderConfig["args"].toVariant().toStringList().join(" ").replace(
                                 "\"", "\\\""));
                appendArray("files", shaderConfig["files"].toVariant().toStringList());
                endObject();
            }
        }

        { // append files objects
            appendDirectories("qml", "QmlFiles");
            appendDirectories("javaScript", "JavaScriptFiles");
            appendDirectories("image", "ImageFiles");
            appendFiles("config", "Files");
            appendFiles("font", "Files");
            appendFiles("meshes", "Files");
            appendFiles("qmldir", "Files");
            appendFiles("shader", "Files");
            appendFiles("sound", "Files");
            appendFiles("video", "Files");
        }

        endObject(); // Closing 'Project'
    }
    return qmlProjectString;
}

QJsonObject qmlProjectTojson(const Utils::FilePath &projectFile)
{
    QmlJS::SimpleReader simpleQmlJSReader;

    const QmlJS::SimpleReaderNode::Ptr rootNode = simpleQmlJSReader.readFile(projectFile.toString());

    if (!simpleQmlJSReader.errors().isEmpty() || !rootNode->isValid()) {
        qCritical() << "Unable to parse:" << projectFile;
        qCritical() << simpleQmlJSReader.errors();
        return {};
    }

    if (rootNode->name() != QLatin1String("Project")) {
        qCritical() << "Cannot find root 'Project' item in the project file: " << projectFile;
        return {};
    }

    auto nodeToJsonObject = [](const QmlJS::SimpleReaderNode::Ptr &node) {
        QJsonObject tObj;
        foreach (const QString &childPropName, node->propertyNames()) {
            tObj.insert(childPropName, node->property(childPropName).value.toJsonValue());
        }
        return tObj;
    };

    auto toCamelCase = [](const QString &s) { return QString(s).replace(0, 1, s[0].toLower()); };

    QJsonObject rootObject; // root object
    QJsonObject fileGroupsObject;
    QJsonObject languageObject;
    QJsonObject versionObject;
    QJsonObject runConfigObject;
    QJsonObject deploymentObject;
    QJsonObject mcuObject;
    QJsonObject shaderToolObject;

    // convert the the non-object props
    for (const QString &propName : rootNode->propertyNames()) {
        QJsonObject *currentObj = &rootObject;
        QString objKey = QString(propName).remove("QDS.", Qt::CaseInsensitive);
        QJsonValue value = rootNode->property(propName).value.toJsonValue();

        if (propName.startsWith("mcu.", Qt::CaseInsensitive)) {
            currentObj = &mcuObject;
            objKey = QString(propName).remove("MCU.");
        } else if (propName.contains("language", Qt::CaseInsensitive)) {
            currentObj = &languageObject;
            if (propName.contains("multilanguagesupport", Qt::CaseInsensitive))
                // fixing the camelcase
                objKey = "multiLanguageSupport";
        } else if (propName.contains("version", Qt::CaseInsensitive)) {
            currentObj = &versionObject;
            if (propName.contains("qdsversion", Qt::CaseInsensitive))
                objKey = "designStudio";
            else if (propName.contains("quickversion", Qt::CaseInsensitive))
                objKey = "qtQuick";
        } else if (propName.contains("widgetapp", Qt::CaseInsensitive)
                   || propName.contains("fileselector", Qt::CaseInsensitive)
                   || propName.contains("mainfile", Qt::CaseInsensitive)
                   || propName.contains("mainuifile", Qt::CaseInsensitive)
                   || propName.contains("forcefreetype", Qt::CaseInsensitive)) {
            currentObj = &runConfigObject;
        } else if (propName.contains("targetdirectory", Qt::CaseInsensitive)) {
            currentObj = &deploymentObject;
        } else if (propName.contains("qtformcus", Qt::CaseInsensitive)) {
            currentObj = &mcuObject;
            objKey = "mcuEnabled";
        } else if (propName.contains("qt6project", Qt::CaseInsensitive)) {
            currentObj = &versionObject;
            objKey = "qt";
            value = rootNode->property(propName).value.toBool() ? "6" : "5";
        }

        currentObj->insert(objKey, value);
    }

    // add missing non-object props if any
    if (!runConfigObject.contains("fileSelectors")) {
        runConfigObject.insert("fileSelectors", QJsonArray{});
    }

    if (!versionObject.contains("qt")) {
        versionObject.insert("qt", "5");
    }

    // convert the the object props
    for (const QmlJS::SimpleReaderNode::Ptr &childNode : rootNode->children()) {
        if (childNode->name().contains("files", Qt::CaseInsensitive)) {
            PropsPair propsPair;
            FileProps fileProps;
            const QString childNodeName = childNode->name().toLower();
            const QmlJS::SimpleReaderNode::Property childNodeFilter = childNode->property("filter");
            const QmlJS::SimpleReaderNode::Property childNodeDirectory = childNode->property(
                "directory");
            const QmlJS::SimpleReaderNode::Property childNodeFiles = childNode->property("files");
            const QString childNodeFilterValue = childNodeFilter.value.toString();

            if (childNodeName == "qmlfiles" || childNodeFilterValue.contains("*.qml")) {
                propsPair = fileProps.qml;
            } else if (childNodeName == "javascriptfiles") {
                propsPair = fileProps.javaScr;
            } else if (childNodeName == "imagefiles") {
                propsPair = fileProps.image;
            } else {
                if (childNodeFilter.isValid()) {
                    if (childNodeFilterValue.contains(".conf"))
                        propsPair = fileProps.config;
                    else if (childNodeFilterValue.contains(".ttf"))
                        propsPair = fileProps.font;
                    else if (childNodeFilterValue.contains("qmldir"))
                        propsPair = fileProps.qmlDir;
                    else if (childNodeFilterValue.contains(".wav"))
                        propsPair = fileProps.sound;
                    else if (childNodeFilterValue.contains(".mp4"))
                        propsPair = fileProps.video;
                    else if (childNodeFilterValue.contains(".mesh"))
                        propsPair = fileProps.mesh;
                    else if (childNodeFilterValue.contains(".glsl"))
                        propsPair = fileProps.shader;
                    else if (childNodeFilterValue.contains(".css"))
                        propsPair = fileProps.styling;
                }
            }

            // get all objects we'll work on
            QJsonObject targetObject = fileGroupsObject[propsPair.first].toObject();
            QJsonArray directories = targetObject["directories"].toArray();
            QJsonArray filters = targetObject["filters"].toArray();
            QJsonArray files = targetObject["files"].toArray();

            // populate & update filters
            if (filters.isEmpty()) {
                filters = QJsonArray::fromStringList(
                    propsPair.second); // populate the filters with the predefined ones
            }

            if (childNodeFilter.isValid()) { // append filters from qmlproject (merge)
                const QStringList filtersFromProjectFile = childNodeFilterValue.split(";");
                for (const QString &filter : filtersFromProjectFile) {
                    if (!filters.contains(QJsonValue(filter))) {
                        filters.append(QJsonValue(filter));
                    }
                }
            }

            // populate & update directories
            if (childNodeDirectory.isValid()) {
                directories.append(childNodeDirectory.value.toJsonValue());
            }
            if (directories.isEmpty())
                directories.append(".");

            // populate & update files
            if (childNodeFiles.isValid()) {
                foreach (const QJsonValue &file, childNodeFiles.value.toJsonArray()) {
                    files.append(QJsonObject{{"name", file.toString()}});
                }
            }

            // put everything back into the root object
            targetObject.insert("directories", directories);
            targetObject.insert("filters", filters);
            targetObject.insert("files", files);
            fileGroupsObject.insert(propsPair.first, targetObject);
        } else if (childNode->name().contains("shadertool", Qt::CaseInsensitive)) {
            QStringList quotedArgs
                = childNode->property("args").value.toString().split('\"', Qt::SkipEmptyParts);
            QStringList args;
            for (int i = 0; i < quotedArgs.size(); ++i) {
                // Each odd arg in this list is a single quoted argument, which we should
                // not be split further
                if (i % 2 == 0)
                    args.append(quotedArgs[i].trimmed().split(' '));
                else
                    args.append(quotedArgs[i].prepend("\"").append("\""));
            }

            shaderToolObject.insert("args", QJsonArray::fromStringList(args));
            shaderToolObject.insert("files", childNode->property("files").value.toJsonValue());
        } else {
            rootObject.insert(toCamelCase(childNode->name().remove("qds.", Qt::CaseInsensitive)),
                              nodeToJsonObject(childNode));
        }
    }

    rootObject.insert("fileGroups", fileGroupsObject);
    rootObject.insert("language", languageObject);
    rootObject.insert("versions", versionObject);
    rootObject.insert("runConfig", runConfigObject);
    rootObject.insert("deployment", deploymentObject);
    rootObject.insert("mcuConfig", mcuObject);
    if (!shaderToolObject.isEmpty())
        rootObject.insert("shaderTool", shaderToolObject);
    rootObject.insert("fileVersion", 1);
    return rootObject;
}
} // namespace QmlProjectManager::Converters