-
Notifications
You must be signed in to change notification settings - Fork 2
/
JsonHelpers.cpp
523 lines (413 loc) · 16.4 KB
/
JsonHelpers.cpp
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
#include "JsonHelpers.h"
#include "ComponentFactory.h"
#include "Constants.h"
#include "Document.h"
#include "DocumentEntry.h"
#include "Project.h"
#include "factories/DocumentEntryFactory.h"
#include "gui/ComponentGraphicsItem.h"
#include "gui/SchematicElement.h"
#include "model/Component.h"
#include "model/ModelElement.h"
#include "metamodel/Category.h"
#include "metamodel/ComponentDescriptor.h"
#include "metamodel/PortDescriptor.h"
#include <QFile>
#include <QJsonArray>
#include <QJsonValue>
#include <QStandardItemModel>
#include <QtDebug>
using namespace q2d::constants;
using namespace q2d::factories;
using namespace q2d::json;
void
q2d::json::writeJsonFile(QString path, QJsonDocument doc) {
QFile file(path);
file.open(QIODevice::WriteOnly | QIODevice::Text);
file.write(doc.toJson());
file.close();
}
/**
* @brief q2d::json::readJsonFile attempts to read a given file.
* If for some reason the reading fails, an empty document will be returned.
* The validity of the read QJsonDocument has to be checked by the caller.
* @param path
* @return
*/
QJsonDocument
q2d::json::readJsonFile(QString path) {
const QString logPrefix = "ReadJsonFile(" + path + ")";
if (path.isEmpty()) {
qWarning() << logPrefix << "file path was empty";
}
QFile jsonFile(path);
if (!jsonFile.exists()) {
qWarning() << logPrefix << "file does not exist";
}
if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qWarning() << logPrefix << "could not open file";
return QJsonDocument();
}
QByteArray rawText = jsonFile.readAll();
QJsonDocument result = QJsonDocument::fromJson(rawText);
jsonFile.close();
qDebug() << logPrefix << "successfully read file";
return result;
}
QJsonDocument
q2d::json::exportComponentHierarchy(QStandardItemModel* componentHierarchy) {
QJsonDocument result = QJsonDocument();
QJsonArray hierarchy = QJsonArray();
QStandardItem* rootItem = componentHierarchy->invisibleRootItem();
for (int rIndex = 0; rIndex < rootItem->rowCount(); ++rIndex) {
for (int cIndex = 0; cIndex < rootItem->columnCount(); ++cIndex) {
hierarchy.append(QJsonValue(fromHierarchyEntry(rootItem->child(rIndex, cIndex))));
}
}
result.setArray(hierarchy);
return result;
}
QJsonObject
q2d::json::fromPointF(QPointF point) {
QJsonObject result = QJsonObject();
result.insert(JSON_GENERAL_POSITION_X, QJsonValue(point.x()));
result.insert(JSON_GENERAL_POSITION_Y, QJsonValue(point.y()));
return result;
}
QJsonObject
q2d::json::fromPoint(QPoint point) {
Q_ASSERT(!point.isNull());
QJsonObject result = QJsonObject();
result.insert(JSON_GENERAL_POSITION_X, QJsonValue(point.x()));
result.insert(JSON_GENERAL_POSITION_Y, QJsonValue(point.y()));
return result;
}
QPointF
q2d::json::toPointF(QJsonObject json) {
float x = 0;
float y = 0;
if(json.contains(JSON_GENERAL_POSITION_X)){
x = json.value(JSON_GENERAL_POSITION_X).toInt();
}
if(json.contains(JSON_GENERAL_POSITION_Y)){
y = json.value(JSON_GENERAL_POSITION_Y).toInt();
}
return QPointF(x, y);
}
QPoint
q2d::json::toPoint(QJsonObject json) {
int x = 0;
int y = 0;
if(json.contains(JSON_GENERAL_POSITION_X)){
x = json.value(JSON_GENERAL_POSITION_X).toInt();
}
if(json.contains(JSON_GENERAL_POSITION_Y)){
y = json.value(JSON_GENERAL_POSITION_Y).toInt();
}
return QPoint(x, y);
}
QJsonObject
q2d::json::fromDocument(Document* doc) {
QJsonArray entriesArray = QJsonArray();
// Write the entries
// Since in JSON the entries are read from top to bottom, it is important to ensure,
// that parents were written before their children
// Also wires need to be written last
QList<DocumentEntry*> written = QList<DocumentEntry*>();
QList<DocumentEntry*> delayed = QList<DocumentEntry*>();
QList<DocumentEntry*> wires = QList<DocumentEntry*>();
for (DocumentEntry * entry : doc->entries()) {
if(entry->type() == enums::DocumentEntryType::WIRE){
wires.append(entry);
continue;
}
if(entry->parent() == nullptr ||
written.contains(entry->parent())){
entriesArray.append(QJsonValue(fromDocumentEntry(entry)));
written.append(entry);
qDebug() << "Wrote entry" << entry->fullId();
} else {
delayed.append(entry);
qDebug() << "Delayed entry" << entry->fullId();
}
}
while(!delayed.empty()){
int amountDelayed = delayed.size();
for(int i = 0; i < amountDelayed; ++i){
// do not iterate over the list, but indices
// since otherwise things might clas
DocumentEntry* current = delayed.takeFirst();
if(written.contains(current->parent())){
entriesArray.append(QJsonValue(fromDocumentEntry(current)));
written.append(current);
qDebug() << "Wrote entry" << current->fullId();
} else {
delayed.append(current);
qDebug() << "Delayed entry" << current->fullId();
}
}
Q_ASSERT(amountDelayed > delayed.size());
// if we could not reduce the delayed elements, there is a problem
}
// now for all the wires
for(DocumentEntry* wireEntry : wires){
entriesArray.append(QJsonValue(fromDocumentEntry(wireEntry)));
written.append(wireEntry);
qDebug() << "Wrote entry" << wireEntry->fullId();
}
QJsonObject entriesWrapper = QJsonObject();
entriesWrapper.insert(JSON_DOCENTRY, entriesArray);
return entriesWrapper;
}
/**
* @brief q2d::json::toDocument creates a new Document from the JSON representation.
* The resulting document will have no parent set, this has to be done by the caller himself.
* @param json
* @param name
* @param parent
* @return
*/
q2d::Document*
q2d::json::toDocument(QJsonObject json, QString name, Project* parent) {
Q_CHECK_PTR(parent);
Q_ASSERT(!name.isEmpty());
Document* doc = new Document(name, parent);
QJsonArray entries = json.value(JSON_DOCENTRY).toArray();
// Read the entries
for (QJsonValue jsonEntry : entries) {
toDocumentEntry(jsonEntry.toObject(), doc);
}
return doc;
}
QJsonObject
q2d::json::fromDocumentEntry(DocumentEntry* entry) {
Q_CHECK_PTR(entry);
QJsonObject result = QJsonObject();
// contain ID, ModelElement, SchematicItem, type, parent entry
// parentDocument is implicitly given by the JSON document,
// this object will be passed into.
result.insert(JSON_DOCENTRY_ID, QJsonValue(entry->localId()));
result.insert(JSON_DOCENTRY_SCHEMATIC_ELEMENT,
QJsonValue(SchematicsSceneChildToJson(
entry->schematicElement())));
// general type
result.insert(JSON_DOCENTRY_TYPE,
QJsonValue(DocumentEntryTypeToString(entry->type())));
// the parent id, if there is one
if (entry->parent() != nullptr) {
result.insert(JSON_DOCENTRY_PARENT, QJsonValue(entry->parent()->fullId()));
} else {
result.insert(JSON_DOCENTRY_PARENT, QJsonValue::Null);
}
// TODO is there something about the model to save?
return result;
}
void
q2d::json::toDocumentEntry(QJsonObject json, Document* document) {
Q_ASSERT(json.contains(JSON_DOCENTRY_ID));
QString id = json.value(JSON_DOCENTRY_ID).toString();
QString typeString = json.value(JSON_DOCENTRY_TYPE).toString();
enums::DocumentEntryType type = enums::StringToDocumentEntryType(typeString);
qDebug() << "Parsing document entry" << id << "of type" << typeString;
// TODO reconstruct the schematics element
QJsonObject schematicJson =
json.value(JSON_DOCENTRY_SCHEMATIC_ELEMENT).toObject();
QString typeId = schematicJson.value(JSON_SCHEMATIC_SUB_TYPE).toString();
QPointF position = toPointF(schematicJson.value(JSON_SCHEMATIC_POSITION).toObject());
// reconstruct the parent
QJsonValue parentValue = json.value(JSON_DOCENTRY_PARENT);
DocumentEntry* parent;
if (parentValue.isNull()) {
parent = nullptr;
} else {
parent = document->entryForFullId(parentValue.toString());
}
switch (type) {
case enums::DocumentEntryType::COMPONENT : {
metamodel::ComponentDescriptor* descriptor =
document->componentFactory()->componentDescriptor(typeId);
DocumentEntryFactory::instantiateComponent(document, descriptor, position, id, false);
}
break;
case enums::DocumentEntryType::PORT : {
Q_CHECK_PTR(parent);
model::InterfacingME* interfacing = dynamic_cast<model::InterfacingME*>(parent->modelElement());
Q_CHECK_PTR(interfacing);
QPoint position = interfacing->portPosition(id);
QString directionString = schematicJson.value(JSON_SCHEMATIC_SUB_TYPE).toString();
DocumentEntryFactory::instantiatePort(
document, parent, position, model::enums::StringToPortDirection(directionString), id);
}
break;
case enums::DocumentEntryType::MODULE_INTERFACE: {
QString directionString = schematicJson.value(JSON_SCHEMATIC_SUB_TYPE).toString();
model::enums::PortDirection direction = model::enums::StringToPortDirection(directionString);
DocumentEntryFactory::instantiateModuleInterface(document, position, direction, id);
}
break;
case enums::DocumentEntryType::WIRE : {
QJsonObject additional = schematicJson.value(JSON_SCHEMATIC_ADDITIONAL).toObject();
Q_ASSERT(!additional.isEmpty());
DocumentEntry* sender = document->entryForFullId(additional.value(JSON_WIRE_START).toString());
Q_CHECK_PTR(sender);
DocumentEntry* receiver = document->entryForFullId(additional.value(JSON_WIRE_END).toString());
Q_CHECK_PTR(receiver);
DocumentEntryFactory::instantiateWire(document, sender, receiver, id);
}
break;
default:
qDebug() << "Unknown type of component entry";
// ignore everything else for now
}
}
QJsonObject
q2d::SchematicsSceneChildToJson(gui::SchematicElement* ssc) {
QJsonObject result = QJsonObject();
result.insert(JSON_SCHEMATIC_SUB_TYPE, QJsonValue(ssc->specificType()));
if(ssc->savePosition()){
result.insert(JSON_SCHEMATIC_POSITION, fromPointF(ssc->pos()));
}
QJsonObject additionalInfo = ssc->additionalJson();
if (!additionalInfo.isEmpty()) {
result.insert(JSON_SCHEMATIC_ADDITIONAL, QJsonValue(additionalInfo));
}
return result;
}
q2d::metamodel::ConfigBitGroupDescriptor*
q2d::json::toConfigBitGroupDescriptor(QJsonObject json) {
Q_ASSERT(!json.isEmpty());
Q_ASSERT(json.contains(JSON_GENERAL_NAME));
Q_ASSERT(json.contains(JSON_GENERAL_SIZE));
QString groupName = json.value(JSON_GENERAL_NAME).toString();
int memberCount = json.value(JSON_GENERAL_SIZE).toInt();
Q_ASSERT(!groupName.isEmpty());
Q_ASSERT(memberCount > 0);
return new metamodel::ConfigBitGroupDescriptor(groupName, memberCount);
}
/**
* @brief ComponentFactory::createTypeFronJson attempts to create a new ComponentType from its JSON-description.
* @param jsonSource
* @param filePath is the path of the descriptor file.
* All paths in the JSON are treated as relative to its base directory
* @param parent
* @return a pointer to the newly created ComponentType; a nullptr on failure
*/
q2d::metamodel::ComponentDescriptor*
q2d::json::toComponentDescriptor (
const QJsonDocument jsonSource,
const QString filePath,
q2d::metamodel::Category* parent) {
// extract the base directory path from the file path
QString fileName = filePath.split(QDir::separator()).last();
QString baseDirPath = QString(filePath);
baseDirPath.chop(fileName.size());
Q_ASSERT(!jsonSource.isNull());
QJsonObject jsonObject = jsonSource.object();
// parse the name
QJsonValue nameValue = jsonObject.value(JSON_GENERAL_NAME);
QString componentName = nameValue.toString();
Q_ASSERT(!componentName.isEmpty());
q2d::metamodel::ComponentDescriptor* result =
new q2d::metamodel::ComponentDescriptor(componentName, parent);
Q_CHECK_PTR(result);
result->setDescriptorPath(filePath);
// load the symbol file
QJsonValue symbolPathValue = jsonObject.value(JSON_SYMBOL_PATH);
if (!symbolPathValue.isUndefined()) {
QString symbolFilePath =
baseDirPath + QDir::separator() + symbolPathValue.toString(NO_SYMBOL_FILE);
result->setSymbolPath(symbolFilePath);
}
// read ports
// defaults to an empty port array
QJsonArray portArray = jsonObject.value(JSON_PORTS).toArray(QJsonArray());
for (QJsonValue currentValue : portArray) {
if (currentValue.isUndefined()) {
continue;
}
metamodel::PortDescriptor* portDescriptor = json::toPortDescriptor(currentValue.toObject());
result->addPort(portDescriptor);
}
// get the config bits if there are some
if (jsonObject.contains(JSON_CONFIG_BIT_GROUP)) {
QJsonArray configBitsJson = jsonObject.value(JSON_CONFIG_BIT_GROUP).toArray();
for (QJsonValue currentGroup : configBitsJson) {
q2d::metamodel::ConfigBitGroupDescriptor* configBits =
json::toConfigBitGroupDescriptor(currentGroup.toObject());
Q_CHECK_PTR(configBits);
// TODO instead print a proper warning
result->addConfigBitGroup(configBits);
}
}
// read the contained functions, if there are some
if (jsonObject.contains(JSON_FUNCTIONS)) {
QJsonArray functionsJson = jsonObject.value(JSON_FUNCTIONS).toArray();
for (QJsonValue currentFunction : functionsJson) {
result->addFunction(currentFunction.toString());
}
}
return result;
}
q2d::metamodel::PortDescriptor*
q2d::json::toPortDescriptor(QJsonObject json) {
QString portName = json.value(JSON_GENERAL_NAME).toString();
QString dirString = json.value(JSON_PORT_DIRECTION).toString();
QPoint portPosition = QPoint();
// if no position is explicitly specified, the default (0, 0) will be used.
// this might be the case if the symbol is auto-generated anyway.
if(json.contains(JSON_GENERAL_POSITION)){
QJsonObject posObject = json.value(JSON_GENERAL_POSITION).toObject();
portPosition = json::toPoint(posObject);
}
model::enums::PortDirection portDirection = model::enums::StringToPortDirection(dirString);
metamodel::PortDescriptor* portDescriptor =
new metamodel::PortDescriptor(portName, portDirection, portPosition);
return portDescriptor;
}
QJsonObject
q2d::json::fromHierarchyEntry(QStandardItem* item) {
Q_CHECK_PTR(item);
QJsonObject result;
switch (item->type()) {
case (int)metamodel::enums::ElementType::COMPONENT:
result = fromTypeEntry(dynamic_cast<metamodel::ComponentDescriptor*>(item));
result.insert(JSON_HIERARCHY_TYPE, QJsonValue(JSON_HIERARCHY_TYPE_COMPONENT));
break;
case (int)metamodel::enums::ElementType::CATEGORY:
result = fromCategoryEntry(dynamic_cast<metamodel::Category*>(item));
result.insert(JSON_HIERARCHY_TYPE, QJsonValue(JSON_HIERARCHY_TYPE_CATEGORY));
break;
case (int)metamodel::enums::ElementType::PORT:
// nothing to save, since they are bound to the component
// this should not happen anyways
Q_ASSERT(false);
default:; // nothing useful to do, we should not end up here
Q_ASSERT(false);
}
return result;
}
QJsonObject
q2d::json::fromCategoryEntry(q2d::metamodel::Category* category) {
Q_CHECK_PTR(category);
QJsonObject result = QJsonObject();
QJsonArray children = QJsonArray();
result.insert(JSON_HIERARCHY_CATEGORY_NAME, QJsonValue(category->text()));
// child recursion
for (int rIndex = 0; rIndex < category->rowCount(); ++rIndex) {
for (int cIndex = 0; cIndex < category->columnCount(); ++cIndex) {
children.append(QJsonValue(
json::fromHierarchyEntry(category->child(rIndex, cIndex))
));
}
}
result.insert(JSON_HIERARCHY_CHILD, children);
return result;
}
QJsonObject
q2d::json::fromTypeEntry(metamodel::ComponentDescriptor* descriptor) {
Q_CHECK_PTR(descriptor);
QJsonObject result = QJsonObject();
result.insert(JSON_HIERARCHY_SOURCE,
QJsonValue(descriptor->descriptorPath()));
return result;
}