Debian Codegraph @

tools/dconfig2cpp/main.cpp

raw
1 // SPDX-FileCopyrightText: 2024 UnionTech Software Technology Co., Ltd.
2 //
3 // SPDX-License-Identifier: LGPL-3.0-or-later
4
5 #include <QCoreApplication>
6 #include <QJsonDocument>
7 #include <QJsonObject>
8 #include <QJsonValue>
9 #include <QJsonArray>
10 #include <QFile>
11 #include <QDebug>
12 #include <QCommandLineParser>
13 #include <QFileInfo>
14
15 static QString toUnicodeEscape(const QString& input) {
16 QString result;
17 for (QChar ch : input) {
18 result += QString("\\u%1").arg(ch.unicode(), 4, 16, QChar('0'));
19 }
20 return result;
21 }
22
23 // Converts a QJsonValue to a corresponding C++ code representation
24 static QString jsonValueToCppCode(const QJsonValue &value){
25 if (value.isBool()) {
26 return value.toBool() ? QLatin1String("true") : QLatin1String("false");
27 } else if (value.isDouble()) {
28 const auto variantValue = value.toVariant();
29 if (variantValue.userType() == QVariant(static_cast<int>(1)).userType()) {
30 return QString::number(value.toInt());
31 } else if (variantValue.userType() == QVariant(static_cast<qint64>(1)).userType()) {
32 return QString::number(variantValue.toLongLong());
33 }
34
35 return QString::number(value.toDouble());
36 } else if (value.isString()) {
37 const auto string = value.toString();
38 if (string.isEmpty()) {
39 return QLatin1String("QLatin1String(\"\")");
40 }
41 return QString("QStringLiteral(u\"%1\")").arg(toUnicodeEscape(string));
42 } else if (value.isNull()) {
43 return "QVariant::fromValue(nullptr)";
44 } else if (value.isArray()) {
45 QStringList elements;
46 const auto array = value.toArray();
47 for (const QJsonValue &element : array) {
48 elements << "QVariant(" + jsonValueToCppCode(element) + ")";
49 }
50 return "QList<QVariant>{" + elements.join(", ") + "}";
51 } else if (value.isObject()) {
52 QStringList elements;
53 QJsonObject obj = value.toObject();
54 for (auto it = obj.begin(); it != obj.end(); ++it) {
55 elements << QString("{QStringLiteral(u\"%1\"), QVariant(%2)}")
56 .arg(toUnicodeEscape(it.key()),
57 jsonValueToCppCode(it.value()));
58 }
59 return "QVariantMap{" + elements.join(", ") + "}";
60 } else {
61 return "QVariant()";
62 }
63 }
64
65 int main(int argc, char *argv[]) {
66 QCoreApplication app(argc, argv);
67 QCommandLineParser parser;
68 parser.setApplicationDescription(QLatin1String("DConfig to C++ class generator"));
69 parser.addHelpOption();
70
71 // Define command line options
72 QCommandLineOption classNameOption(QStringList() << QLatin1String("c") << QLatin1String("class-name"),
73 QLatin1String("Name of the generated class"),
74 QLatin1String("className"));
75 parser.addOption(classNameOption);
76
77 QCommandLineOption sourceFileOption(QStringList() << QLatin1String("o") << QLatin1String("output"),
78 QLatin1String("Path to the output source(header only) file"),
79 QLatin1String("sourceFile"));
80 parser.addOption(sourceFileOption);
81
82 QCommandLineOption forceRequestThread(QStringList() << QLatin1String("force-request-thread"),
83 QLatin1String("Force request thread to create DConfig instance"));
84 parser.addOption(forceRequestThread);
85
86 QCommandLineOption noComment(QStringList() << QLatin1String("no-comment"),
87 QLatin1String("Do not generate comments in the generated code"));
88 parser.addOption(noComment);
89
90 parser.addPositionalArgument(QLatin1String("json-file"), QLatin1String("Path to the input JSON file"));
91 parser.process(app);
92
93 const QStringList args = parser.positionalArguments();
94 if (args.size() != 1) {
95 parser.showHelp(-1);
96 }
97
98 QString className = parser.value(classNameOption);
99 const QString jsonFileName = QFileInfo(args.first()).completeBaseName();
100 if (className.isEmpty()) {
101 className = QLatin1String("dconfig_") + QString(jsonFileName).replace('.', '_');
102 }
103
104 QString sourceFilePath = parser.value(sourceFileOption);
105 if (sourceFilePath.isEmpty()) {
106 sourceFilePath = className.toLower() + QLatin1String(".hpp");
107 }
108
109 QFile file(args.first());
110 if (!file.open(QIODevice::ReadOnly)) {
111 qWarning() << QLatin1String("Failed to open file:") << args.first();
112 return -1;
113 }
114
115 QByteArray data = file.readAll();
116 QJsonDocument doc = QJsonDocument::fromJson(data);
117 QJsonObject root = doc.object();
118
119 // Check magic value
120 if (root[QLatin1String("magic")].toString() != QLatin1String("dsg.config.meta")) {
121 qWarning() << QLatin1String("Invalid magic value in JSON file");
122 return -1;
123 }
124
125 // Generate header and source files
126 QFile headerFile(sourceFilePath);
127 if (!headerFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
128 qWarning() << QLatin1String("Failed to open file for writing:") << sourceFilePath;
129 return -1;
130 }
131
132 QTextStream headerStream(&headerFile);
133
134 // Extract version and add it as a comment in the generated code
135 QString version = root[QLatin1String("version")].toString();
136
137 // Generate header and source file comments
138 QString commandLineArgs = QCoreApplication::arguments().join(QLatin1String(" "));
139 QString generationTime = QDateTime::currentDateTime().toString(Qt::ISODate);
140
141 if (!parser.isSet(noComment)) {
142 QString headerComment = QString(
143 "/**\n"
144 " * This file is generated by dconfig2cpp.\n"
145 " * Command line arguments: %1\n"
146 " * Generation time: %2\n"
147 " * JSON file version: %3\n"
148 " *\n"
149 " * WARNING: DO NOT MODIFY THIS FILE MANUALLY.\n"
150 " * If you need to change the content, please modify the dconfig2cpp tool.\n"
151 " */\n\n"
152 ).arg(commandLineArgs, generationTime, version);
153
154 headerStream << headerComment;
155 }
156
157 QJsonObject contents = root[QLatin1String("contents")].toObject();
158
159 // Write header file content
160 headerStream << "#ifndef " << className.toUpper() << "_H\n";
161 headerStream << "#define " << className.toUpper() << "_H\n\n";
162 headerStream << "#include <QThread>\n";
163 headerStream << "#include <QVariant>\n";
164 headerStream << "#include <QDebug>\n";
165 headerStream << "#include <QAtomicPointer>\n";
166 headerStream << "#include <QAtomicInteger>\n";
167 headerStream << "#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)\n"
168 << "#include <QProperty>\n"
169 << "#endif\n";
170
171 headerStream << "#include <DConfig>\n\n";
172 headerStream << "class " << className << " : public QObject {\n";
173 headerStream << " Q_OBJECT\n\n";
174
175 struct Property {
176 QString typeName;
177 QString propertyName;
178 QString capitalizedPropertyName;
179 QString propertyNameString;
180 QJsonValue defaultValue;
181 };
182 QList<Property> properties;
183 QStringList propertyNames;
184 QStringList propertyNameStrings;
185
186 static QStringList usedKeywords = {
187 className,
188 "create",
189 "createByName",
190 "config",
191 "keyList",
192 "isInitializeSucceed",
193 "isInitializeFailed",
194 "isInitializing",
195 "isDefaultValue",
196 "m_config",
197 "m_status",
198 };
199
200 for (int i = 0; i <= (contents.size()) / 32; ++i) {
201 usedKeywords << QLatin1String("m_propertySetStatus") + QString::number(i);
202 }
203
204 // Iterate over JSON contents to extract properties
205 for (auto it = contents.begin(); it != contents.end(); ++it) {
206 QJsonObject obj = it.value().toObject();
207 QString propertyName = it.key();
208 QString typeName;
209 const auto value = obj[QLatin1String("value")];
210 if (value.isBool()) {
211 typeName = "bool";
212 } else if (value.isArray()) {
213 typeName = "QList<QVariant>";
214 } else if (value.isObject()) {
215 typeName = "QVariantMap";
216 } else if (value.isDouble()) {
217 const auto variantValue = value.toVariant();
218 typeName = QString::fromLatin1(variantValue.typeName());
219 } else if (value.isString()) {
220 typeName = "QString";
221 } else {
222 typeName = "QVariant";
223 }
224
225 QString capitalizedPropertyName = propertyName;
226 if (!capitalizedPropertyName.isEmpty() && capitalizedPropertyName[0].isLower()) {
227 capitalizedPropertyName[0] = capitalizedPropertyName[0].toUpper();
228 }
229
230 propertyNames << propertyName;
231 properties.append(Property({
232 typeName,
233 propertyName,
234 capitalizedPropertyName,
235 "QStringLiteral(\"" + propertyName + "\")",
236 obj[QLatin1String("value")]
237 }));
238 propertyNameStrings << properties.last().propertyNameString;
239
240 const QString readFunction = usedKeywords.contains(propertyName) ? QLatin1String(" READ get") + capitalizedPropertyName
241 : QLatin1String(" READ ") + propertyName;
242 headerStream << " Q_PROPERTY(" << typeName << " " << propertyName << readFunction
243 << " WRITE set" << capitalizedPropertyName << " NOTIFY " << propertyName << "Changed"
244 << " RESET reset" << capitalizedPropertyName << ")\n";
245 }
246
247 headerStream << " Q_CLASSINFO(\"DConfigKeyList\", \"" << propertyNames.join(";") <<"\")\n"
248 << " Q_CLASSINFO(\"DConfigFileName\", \"" << QString(jsonFileName).replace("\n", "\\n").replace("\r", "\\r") <<"\")\n"
249 << " Q_CLASSINFO(\"DConfigFileVersion\", \"" << version <<"\")\n\n"
250 << "public:\n"
251 << " explicit " << className
252 << R"((QThread *thread, DTK_CORE_NAMESPACE::DConfigBackend *backend, const QString &name, const QString &appId, const QString &subpath, QObject *parent)
253 : QObject(parent) {
254 if (!thread->isRunning()) {
255 qWarning() << QLatin1String("Warning: The provided thread is not running.");
256 }
257 Q_ASSERT(QThread::currentThread() != thread);
258 auto worker = new QObject();
259 worker->moveToThread(thread);
260 QMetaObject::invokeMethod(worker, [=, this]() {
261 DTK_CORE_NAMESPACE::DConfig *config = nullptr;
262 if (backend) {
263 if (appId.isNull()) {
264 config = DTK_CORE_NAMESPACE::DConfig::create(backend, name, subpath, nullptr);
265 } else {
266 config = DTK_CORE_NAMESPACE::DConfig::create(backend, appId, name, subpath, nullptr);
267 }
268 } else {
269 if (appId.isNull()) {
270 config = DTK_CORE_NAMESPACE::DConfig::create(name, subpath, nullptr);
271 } else {
272 config = DTK_CORE_NAMESPACE::DConfig::create(appId, name, subpath, nullptr);
273 }
274 }
275 if (!config) {
276 qWarning() << QLatin1String("Failed to create DConfig instance.");
277 worker->deleteLater();
278 return;
279 }
280 config->moveToThread(QThread::currentThread());
281 initializeInConfigThread(config);
282 worker->deleteLater();
283 });
284 }
285 )";
286
287 const QString jsonFileString = "QStringLiteral(u\"" + toUnicodeEscape(jsonFileName) + "\")";
288 // Generate constructors
289 if (parser.isSet(forceRequestThread))
290 headerStream << " static " << className << "* create(QThread *thread, const QString &appId = {}, const QString &subpath = {}, QObject *parent = nullptr)\n";
291 else
292 headerStream << " static " << className << "* create(const QString &appId = {}, const QString &subpath = {}, QObject *parent = nullptr, QThread *thread = DTK_CORE_NAMESPACE::DConfig::globalThread())\n";
293 headerStream << " { return new " << className << "(thread, nullptr, " << jsonFileString << ", appId, subpath, parent); }\n";
294 if (parser.isSet(forceRequestThread))
295 headerStream << " static " << className << "* create(QThread *thread, DTK_CORE_NAMESPACE::DConfigBackend *backend, const QString &appId = {}, const QString &subpath = {}, QObject *parent = nullptr)\n";
296 else
297 headerStream << " static " << className << "* create(DTK_CORE_NAMESPACE::DConfigBackend *backend, const QString &appId = {}, const QString &subpath = {}, QObject *parent = nullptr, QThread *thread = DTK_CORE_NAMESPACE::DConfig::globalThread())\n";
298 headerStream << " { return new " << className << "(thread, backend, " << jsonFileString << ", appId, subpath, parent); }\n";
299 if (parser.isSet(forceRequestThread))
300 headerStream << " static " << className << "* createByName(QThread *thread, const QString &name, const QString &appId = {}, const QString &subpath = {}, QObject *parent = nullptr)\n";
301 else
302 headerStream << " static " << className << "* createByName(const QString &name, const QString &appId = {}, const QString &subpath = {}, QObject *parent = nullptr, QThread *thread = DTK_CORE_NAMESPACE::DConfig::globalThread())\n";
303 headerStream << " { return new " << className << "(thread, nullptr, name, appId, subpath, parent); }\n";
304 if (parser.isSet(forceRequestThread))
305 headerStream << " static " << className << "* createByName(QThread *thread, DTK_CORE_NAMESPACE::DConfigBackend *backend, const QString &name, const QString &appId = {}, const QString &subpath = {}, QObject *parent = nullptr)\n";
306 else
307 headerStream << " static " << className << "* createByName(DTK_CORE_NAMESPACE::DConfigBackend *backend, const QString &name, const QString &appId = {}, const QString &subpath = {}, QObject *parent = nullptr, QThread *thread = DTK_CORE_NAMESPACE::DConfig::globalThread())\n";
308 headerStream << " { return new " << className << "(thread, backend, name, appId, subpath, parent); }\n";
309
310 // Destructor
311 headerStream << " ~" << className << R"(() {
312 if (m_config.loadRelaxed()) {
313 m_config.loadRelaxed()->deleteLater();
314 }
315 }
316
317 Q_INVOKABLE DTK_CORE_NAMESPACE::DConfig *config() const {
318 return m_config.loadRelaxed();
319 }
320
321 Q_INVOKABLE bool isInitializeSucceed() const {
322 return m_status.loadRelaxed() == static_cast<int>(Status::Succeed);
323 }
324
325 Q_INVOKABLE bool isInitializeFailed() const {
326 return m_status.loadRelaxed() == static_cast<int>(Status::Failed);
327 }
328
329 Q_INVOKABLE bool isInitializing() const {
330 return m_status.loadRelaxed() == static_cast<int>(Status::Invalid);
331 }
332
333 )";
334
335 headerStream << " Q_INVOKABLE QStringList keyList() const {\n"
336 << " return { " << propertyNameStrings.join(",\n ") << "};\n"
337 << " }\n\n";
338
339 headerStream << " Q_INVOKABLE bool isDefaultValue(const QString &key) const {\n";
340 for (int i = 0; i < properties.size(); ++i) {
341 headerStream << " if (key == " << properties.at(i).propertyNameString << ")\n"
342 << " return " << properties.at(i).propertyName << "IsDefaultValue();\n";
343 }
344 headerStream << " return false;\n"
345 << " }\n\n";
346
347 // Generate property getter and setter methods
348 for (int i = 0; i < properties.size(); ++i) {
349 const Property &property = properties[i];
350 const QString readFunction = usedKeywords.contains(property.propertyName)
351 ? "get" + property.capitalizedPropertyName
352 : property.propertyName;
353 assert(!usedKeywords.contains(readFunction));
354
355 headerStream << " " << property.typeName << " " << readFunction << "() const {\n"
356 << " return p_" << property.propertyName << ";\n }\n";
357 headerStream << " void set" << property.capitalizedPropertyName << "(const " << property.typeName << " &value) {\n"
358 << " auto oldValue = p_" << property.propertyName << ";\n"
359 << " p_" << property.propertyName << " = value;\n"
360 << " markPropertySet(" << i << ");\n"
361 << " if (auto config = m_config.loadRelaxed()) {\n"
362 << " QMetaObject::invokeMethod(config, [this, value]() {\n"
363 << " m_config.loadRelaxed()->setValue(" << property.propertyNameString << ", value);\n"
364 << " });\n"
365 << " }\n"
366 << " if (p_" << property.propertyName << " != oldValue) {\n"
367 << " Q_EMIT " << property.propertyName << "Changed();\n"
368 << " Q_EMIT valueChanged(" << property.propertyNameString << ", value);\n"
369 << " }\n"
370 << " }\n"
371 << " void reset" << property.capitalizedPropertyName << "() {\n"
372 << " if (auto config = m_config.loadRelaxed()) {\n"
373 << " QMetaObject::invokeMethod(config, [this]() {\n"
374 << " m_config.loadRelaxed()->reset(" << property.propertyNameString << ");\n"
375 << " });\n"
376 << " }\n"
377 << " }\n";
378 headerStream << "#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)\n";
379 headerStream << " QBindable<" << property.typeName << "> bindable" << property.capitalizedPropertyName << "() {\n"
380 << " return QBindable<" << property.typeName << ">(this, " << property.propertyNameString << ");\n"
381 << " }\n";
382 headerStream << "#endif\n";
383
384 headerStream << " Q_INVOKABLE bool " << property.propertyName << "IsDefaultValue() const {\n"
385 << " return !testPropertySet(" << i << ");\n"
386 << " }\n";
387 }
388
389 // Generate signals for property changes
390 headerStream << "Q_SIGNALS:\n"
391 << " void configInitializeFailed(DTK_CORE_NAMESPACE::DConfig *config);\n"
392 << " void configInitializeSucceed(DTK_CORE_NAMESPACE::DConfig *config);\n"
393 << " void valueChanged(const QString &key, const QVariant &value);\n\n";
394 for (const Property &property : std::as_const(properties)) {
395 headerStream << " void " << property.propertyName << "Changed();\n";
396 }
397
398 // Generate private methods and members
399 headerStream << "private:\n";
400
401 headerStream << " void initializeInConfigThread(DTK_CORE_NAMESPACE::DConfig *config) {\n"
402 << " Q_ASSERT(!m_config.loadRelaxed());\n"
403 << " m_config.storeRelaxed(config);\n"
404 << " if (!config->isValid()) {\n"
405 << " m_status.storeRelaxed(static_cast<int>(Status::Failed));\n"
406 << " Q_EMIT configInitializeFailed(config);\n"
407 << " return;\n"
408 << " }\n\n";
409 for (int i = 0; i < properties.size(); ++i) {
410 const Property &property = properties[i];
411 headerStream << " if (testPropertySet(" << i << ")) {\n";
412 headerStream << " config->setValue(" << property.propertyNameString << ", QVariant::fromValue(p_" << property.propertyName << "));\n";
413 headerStream << " } else {\n";
414 headerStream << " updateValue(" << property.propertyNameString << ", QVariant::fromValue(p_" << property.propertyName << "));\n";
415 headerStream << " }\n";
416 }
417 headerStream << R"(
418 connect(config, &DTK_CORE_NAMESPACE::DConfig::valueChanged, this, [this](const QString &key) {
419 updateValue(key);
420 }, Qt::DirectConnection);
421
422 m_status.storeRelaxed(static_cast<int>(Status::Succeed));
423 Q_EMIT configInitializeSucceed(config);
424 }
425 void updateValue(const QString &key, const QVariant &fallback = QVariant()) {
426 Q_ASSERT(QThread::currentThread() == m_config.loadRelaxed()->thread());
427 const QVariant &value = m_config.loadRelaxed()->value(key, fallback);
428 )";
429 for (int i = 0; i < properties.size(); ++i) {
430 const Property &property = properties.at(i);
431 headerStream << " if (key == " << property.propertyNameString << ") {\n";
432
433 headerStream << " markPropertySet(" << i << ", !m_config.loadRelaxed()->isDefaultValue(key));\n";
434
435 headerStream << " auto newValue = qvariant_cast<" << property.typeName << ">(value);\n"
436 << " QMetaObject::invokeMethod(this, [this, newValue, key, value]() {\n"
437 << " Q_ASSERT(QThread::currentThread() == this->thread());\n"
438 << " if (p_" << property.propertyName << " != newValue) {\n"
439 << " p_" << property.propertyName << " = newValue;\n"
440 << " Q_EMIT " << property.propertyName << "Changed();\n"
441 << " Q_EMIT valueChanged(key, value);\n"
442 << " }\n"
443 << " });\n"
444 << " return;\n"
445 << " }\n";
446 }
447 headerStream << " }\n";
448
449 // Mark property as set
450 headerStream << " inline void markPropertySet(const int index, bool on = true) {\n";
451 for (int i = 0; i <= (properties.size()) / 32; ++i) {
452 headerStream << " if (index < " << (i + 1) * 32 << ") {\n"
453 << " if (on)\n"
454 << " m_propertySetStatus" << QString::number(i) << ".fetchAndOrOrdered(1 << (index - " << i * 32 << "));\n"
455 << " else\n"
456 << " m_propertySetStatus" << QString::number(i) << ".fetchAndAndOrdered(1 << (index - " << i * 32 << "));\n"
457 << " return;\n"
458 << " }\n";
459 }
460 headerStream << " Q_UNREACHABLE();\n }\n";
461
462 // Test if property is set
463 headerStream << " inline bool testPropertySet(const int index) const {\n";
464 for (int i = 0; i <= (properties.size()) / 32; ++i) {
465 headerStream << " if (index < " << (i + 1) * 32 << ") {\n";
466 headerStream << " return (m_propertySetStatus" << QString::number(i) << ".loadRelaxed() & (1 << (index - " << i * 32 << ")));\n";
467 headerStream << " }\n";
468 }
469 headerStream << " Q_UNREACHABLE();\n"
470 << " }\n";
471
472 // Member variables
473 headerStream << R"(
474 QAtomicPointer<DTK_CORE_NAMESPACE::DConfig> m_config = nullptr;
475
476 public:
477 enum class Status {
478 Invalid = 0,
479 Succeed = 1,
480 Failed = 2
481 };
482 private:
483 QAtomicInteger<int> m_status = static_cast<int>(Status::Invalid);
484
485 )";
486
487 // Property variables
488 for (const Property &property : std::as_const(properties)) {
489 if (property.typeName == QLatin1String("int") || property.typeName == QLatin1String("qint64")) {
490 headerStream << " // Note: If you expect a double type, add 'e' to the number in the JSON value field, e.g., \"value\": 1.0e, not just 1.0\n";
491 } else if (property.typeName == QLatin1String("QString")) {
492 headerStream << " // Default value: \"" << property.defaultValue.toString().replace("\n", "\\n").replace("\r", "\\r") << "\"\n";
493 }
494 headerStream << " " << property.typeName << " p_" << property.propertyName << " { ";
495 headerStream << jsonValueToCppCode(property.defaultValue) << " };\n";
496 }
497
498 // Property set status variables
499 for (int i = 0; i <= (properties.size()) / 32; ++i) {
500 headerStream << " QAtomicInteger<quint32> m_propertySetStatus" << QString::number(i) << " = 0;\n";
501 }
502 headerStream << "};\n\n";
503 headerStream << "#endif // " << className.toUpper() << "_H\n";
504
505 return 0;
506 }