summaryrefslogtreecommitdiffstats
path: root/src/Authoring/Studio/Application/ProjectFile.cpp
blob: ebec8b53467b1d7cb064b33f8fb52bab76277bae (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
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt 3D Studio.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt 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 "ProjectFile.h"
#include "Qt3DSFileTools.h"
#include "Exceptions.h"
#include "DataInputDlg.h"
#include "StudioApp.h"
#include "Qt3DSDMStudioSystem.h"
#include "ClientDataModelBridge.h"
#include "Core.h"
#include "Doc.h"
#include "IDocumentEditor.h"
#include "PresentationFile.h"
#include "IStudioRenderer.h"
#include "StudioUtils.h"
#include "Dispatch.h"
#include <QtCore/qdiriterator.h>
#include <QtCore/qsavefile.h>
#include <QtCore/qtimer.h>
#include <QtCore/qrandom.h>
#include <QtWidgets/qmessagebox.h>

ProjectFile::ProjectFile()
{

}

// find the 1st .uia file in the current or parent directories and assume this is the project file,
// as a project should have only 1 .uia file
void ProjectFile::ensureProjectFile()
{
    if (!m_fileInfo.exists()) {
        QFileInfo uipInfo(g_StudioApp.GetCore()->GetDoc()->GetDocumentPath());
        QString uiaPath(PresentationFile::findProjectFile(uipInfo.absoluteFilePath()));

        if (uiaPath.isEmpty()) {
            // .uia not found, create a new one in the same folder as uip. Creation sets file info.
            create(uipInfo.absoluteFilePath().replace(QLatin1String(".uip"),
                                                      QLatin1String(".uia")));
            addPresentationNode(uipInfo.absoluteFilePath());
            updateDocPresentationId();
        } else {
            // .uia found, set project file info
            m_fileInfo.setFile(uiaPath);
        }
    }
}

void ProjectFile::initProjectFile(const QString &presPath)
{
    QFileInfo uipFile(presPath);
    QString uiaPath(PresentationFile::findProjectFile(uipFile.absoluteFilePath()));

    if (uiaPath.isEmpty()) {
        // .uia not found, clear project file info
        m_fileInfo = QFileInfo();
    } else {
        // .uia found, set project file info
        m_fileInfo.setFile(uiaPath);
    }
}

/**
 * Add a presentation or presentation-qml node to the project file
 *
 * @param pPath the absolute path to the presentation file, it will be saved as relative
 * @param pId presentation Id
 */
void ProjectFile::addPresentationNode(const QString &pPath, const QString &pId)
{
    addPresentationNodes({{pPath, pId}});
}

// Add a list of presentation or presentation-qml nodes to the project file
void ProjectFile::addPresentationNodes(const QHash<QString, QString> &nodeList)
{
    ensureProjectFile();

    QDomDocument doc;
    QSaveFile file(getProjectFilePath());
    if (!StudioUtils::openDomDocumentSave(file, doc))
        return;

    QDomElement rootElem = doc.documentElement();
    QDomElement assetsElem = rootElem.firstChildElement(QStringLiteral("assets"));

    // create the <assets> node if it doesn't exist
    bool initial = false;
    if (assetsElem.isNull()) {
        assetsElem = doc.createElement(QStringLiteral("assets"));
        rootElem.insertBefore(assetsElem, {});
        initial = true;
    }

    QHash<QString, QString> changesList;
    QHashIterator<QString, QString> nodesIt(nodeList);
    while (nodesIt.hasNext()) {
        nodesIt.next();
        const QString presPath = nodesIt.key();
        const QString presId = nodesIt.value();
        QString relativePresentationPath
                = QDir(getProjectPath()).relativeFilePath(presPath);

        // make sure the node doesn't already exist
        bool nodeExists = false;
        for (QDomElement p = assetsElem.firstChild().toElement(); !p.isNull();
            p = p.nextSibling().toElement()) {
            if ((p.nodeName() == QLatin1String("presentation")
                 || p.nodeName() == QLatin1String("presentation-qml"))
                    && p.attribute(QStringLiteral("src")) == relativePresentationPath) {
                nodeExists = true;
                break;
            }
        }

        if (!nodeExists) {
            const QString presentationId
                    = ensureUniquePresentationId(presId.isEmpty()
                                                 ? QFileInfo(presPath).completeBaseName()
                                                 : presId);

            if (assetsElem.attribute(QStringLiteral("initial")).isEmpty()) {
                assetsElem.setAttribute(QStringLiteral("initial"), presentationId);
                m_initialPresentation = presentationId;
            }

            // add the presentation node
            bool isQml = presPath.endsWith(QLatin1String(".qml"));
            QDomElement pElem = isQml ? doc.createElement(QStringLiteral("presentation-qml"))
                                      : doc.createElement(QStringLiteral("presentation"));
            pElem.setAttribute(QStringLiteral("id"), presentationId);
            pElem.setAttribute(isQml ? QStringLiteral("args") : QStringLiteral("src"),
                               relativePresentationPath);
            assetsElem.appendChild(pElem);
            changesList.insert(relativePresentationPath, presentationId);

            if (!initial) {
                g_StudioApp.m_subpresentations.push_back(
                            SubPresentationRecord(isQml ? QStringLiteral("presentation-qml")
                                                        : QStringLiteral("presentation"),
                                                  presentationId, relativePresentationPath));
            }
        }
    }

    if (initial || changesList.size() > 0)
        StudioUtils::commitDomDocumentSave(file, doc);

    if (changesList.size() > 0) {
        g_StudioApp.getRenderer().RegisterSubpresentations(g_StudioApp.m_subpresentations);

        QHashIterator<QString, QString> changesIt(changesList);
        while (changesIt.hasNext()) {
            changesIt.next();
            Q_EMIT presentationIdChanged(changesIt.key(), changesIt.value());
        }
    }
}

// Get the src attribute (relative path) to the initial presentation in a uia file, if no initial
// presentation exists, the first one is returned. Returns empty string if file cannot be read.
QString ProjectFile::getInitialPresentationSrc(const QString &uiaPath)
{
    QDomDocument domDoc;
    if (!StudioUtils::readFileToDomDocument(uiaPath, domDoc))
        return {};

    QString firstPresentationSrc;
    QDomElement assetsElem = domDoc.documentElement().firstChildElement(QStringLiteral("assets"));
    if (!assetsElem.isNull()) {
        QString initialId = assetsElem.attribute(QStringLiteral("initial"));
        if (!initialId.isEmpty()) {
            QDomNodeList pNodes = assetsElem.elementsByTagName(QStringLiteral("presentation"));
            for (int i = 0; i < pNodes.count(); ++i) {
                QDomElement pElem = pNodes.at(i).toElement();
                if (pElem.attribute(QStringLiteral("id")) == initialId)
                    return pElem.attribute(QStringLiteral("src"));

                if (i == 0)
                    firstPresentationSrc = pElem.attribute(QStringLiteral("src"));
            }
        }
    }

    return firstPresentationSrc;
}

/**
 * Write a presentation id to the project file.
 * If the presentation id doesn't exist yet in project, it's added.
 *
 * This also updates the Doc presentation Id if the src param is empty
 * or same as current presentation.
 *
 * @param id presentation Id
 * @param src source node, if empty the current document node is used
 */
void ProjectFile::writePresentationId(const QString &id, const QString &src)
{
    ensureProjectFile();

    CDoc *doc = g_StudioApp.GetCore()->GetDoc();
    QString theSrc = src.isEmpty() ? doc->getRelativePath() : src;
    QString theId = id.isEmpty() ? doc->getPresentationId() : id;
    bool isQml = theSrc.endsWith(QLatin1String(".qml"));

    if (theSrc == doc->getRelativePath())
        doc->setPresentationId(id);

    QDomDocument domDoc;
    QSaveFile file(getProjectFilePath());
    if (!StudioUtils::openDomDocumentSave(file, domDoc))
        return;

    QDomElement assetsElem = domDoc.documentElement().firstChildElement(QStringLiteral("assets"));
    QDomNodeList pqNodes = isQml ? assetsElem.elementsByTagName(QStringLiteral("presentation-qml"))
                                 : assetsElem.elementsByTagName(QStringLiteral("presentation"));

    QString oldId;
    if (!pqNodes.isEmpty()) {
        for (int i = 0; i < pqNodes.count(); ++i) {
            QDomElement pqElem = pqNodes.at(i).toElement();
            QString srcOrArgs = isQml ? pqElem.attribute(QStringLiteral("args"))
                                      : pqElem.attribute(QStringLiteral("src"));
            if (srcOrArgs == theSrc) {
                oldId = pqElem.attribute(QStringLiteral("id"));
                pqElem.setAttribute(QStringLiteral("id"), theId);

                if (assetsElem.attribute(QStringLiteral("initial")) == oldId) {
                    assetsElem.setAttribute(QStringLiteral("initial"), theId);
                    m_initialPresentation = theId;
                }
                break;
            }
        }
    }

    if (!src.isEmpty() && oldId.isEmpty()) { // new presentation, add it
        StudioUtils::commitDomDocumentSave(file, domDoc);
        QDir projectDir(getProjectPath());
        addPresentationNode(QDir::cleanPath(projectDir.absoluteFilePath(theSrc)), theId);
    } else if (!oldId.isEmpty()) { // the presentation id changed
        StudioUtils::commitDomDocumentSave(file, domDoc);

        // update m_subpresentations
        auto *sp = std::find_if(g_StudioApp.m_subpresentations.begin(),
                                g_StudioApp.m_subpresentations.end(),
                               [&theSrc](const SubPresentationRecord &spr) -> bool {
                                   return spr.m_argsOrSrc == theSrc;
                               });
        if (sp != g_StudioApp.m_subpresentations.end())
            sp->m_id = theId;

        // update current doc instances (layers and images) that are using this presentation Id
        qt3dsdm::TInstanceHandleList instancesToRefresh;
        auto *bridge = doc->GetStudioSystem()->GetClientDataModelBridge();
        qt3dsdm::IPropertySystem *propSystem = doc->GetStudioSystem()->GetPropertySystem();
        std::function<void(qt3dsdm::Qt3DSDMInstanceHandle)>
        parseChildren = [&](qt3dsdm::Qt3DSDMInstanceHandle instance) {
            Q3DStudio::CGraphIterator iter;
            GetAssetChildren(doc, instance, iter);

            while (!iter.IsDone()) {
                qt3dsdm::Qt3DSDMInstanceHandle child = iter.GetCurrent();
                if (bridge->GetObjectType(child) & (OBJTYPE_LAYER | OBJTYPE_IMAGE)) {
                    bool add = false;
                    if (bridge->GetSourcePath(child).toQString() == oldId) {
                        propSystem->SetInstancePropertyValue(child, bridge->GetSourcePathProperty(),
                                                             qt3dsdm::SValue(QVariant(theId)));
                        add = true;
                    }
                    if (bridge->getSubpresentation(child).toQString() == oldId) {
                        propSystem->SetInstancePropertyValue(child,
                                                             bridge->getSubpresentationProperty(),
                                                             qt3dsdm::SValue(QVariant(theId)));
                        add = true;
                    }
                    if (add)
                        instancesToRefresh.push_back(child);
                }
                parseChildren(child);
                ++iter;
            }
        };
        parseChildren(doc->GetSceneInstance());

        // update changed presentation Id in all .uip files if in-use
        QDomNodeList pNodes = assetsElem.elementsByTagName(QStringLiteral("presentation"));
        for (int i = 0; i < pNodes.count(); ++i) {
            QDomElement pElem = pNodes.at(i).toElement();
            QString path = QDir(getProjectPath())
                                        .absoluteFilePath(pElem.attribute(QStringLiteral("src")));
            PresentationFile::updatePresentationId(path, oldId, theId);
        }
        Q_EMIT presentationIdChanged(theSrc, theId);

        g_StudioApp.getRenderer().RegisterSubpresentations(g_StudioApp.m_subpresentations);
        if (instancesToRefresh.size() > 0) {
            g_StudioApp.GetCore()->GetDispatch()->FireImmediateRefreshInstance(
                        &(instancesToRefresh[0]), long(instancesToRefresh.size()));
            for (auto &instance : instancesToRefresh)
                doc->getSceneEditor()->saveIfMaterial(instance);
        }
    }
}

// Set the doc PresentationId from the project file, this is called after a document is loaded.
// If there is no project file, it simply clears the id.
void ProjectFile::updateDocPresentationId()
{
    CDoc *doc = g_StudioApp.GetCore()->GetDoc();
    doc->setPresentationId({});

    if (!m_fileInfo.exists())
        return;

    QFile file(getProjectFilePath());
    if (!file.open(QFile::Text | QFile::ReadOnly)) {
        qWarning() << file.errorString();
        return;
    }

    QXmlStreamReader reader(&file);
    reader.setNamespaceProcessing(false);

    while (!reader.atEnd()) {
        if (reader.readNextStartElement() && reader.name() == QLatin1String("presentation")) {
            const auto attrs = reader.attributes();
            if (attrs.value(QLatin1String("src")) == doc->getRelativePath()) {
                // current presentation node
                doc->setPresentationId(attrs.value(QLatin1String("id")).toString());
                return;
            }
        }
    }
}

// get a presentationId that match a given src attribute
QString ProjectFile::getPresentationId(const QString &src) const
{
    if (!m_fileInfo.exists())
        return {};

    if (src == g_StudioApp.GetCore()->GetDoc()->getRelativePath()) {
        return g_StudioApp.GetCore()->GetDoc()->getPresentationId();
    } else {
        auto *sp = std::find_if(g_StudioApp.m_subpresentations.begin(),
                                g_StudioApp.m_subpresentations.end(),
                               [&src](const SubPresentationRecord &spr) -> bool {
                                   return spr.m_argsOrSrc == src;
                               });
        if (sp != g_StudioApp.m_subpresentations.end())
            return sp->m_id;
    }

    return {};
}

// create the project .uia file
void ProjectFile::create(const QString &uiaPath)
{
    QDomDocument domDoc;
    domDoc.setContent(QStringLiteral("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                                  "<application xmlns=\"http://qt.io/qt3dstudio/uia\">"
                                    "<statemachine ref=\"#logic\">"
                                      "<visual-states>"
                                        "<state ref=\"Initial\">"
                                          "<enter>"
                                            "<goto-slide element=\"main:Scene\" rel=\"next\"/>"
                                          "</enter>"
                                        "</state>"
                                      "</visual-states>"
                                    "</statemachine>"
                                  "</application>"));

    QSaveFile file(uiaPath);
    if (StudioUtils::openTextSave(file)) {
        StudioUtils::commitDomDocumentSave(file, domDoc);
        m_fileInfo.setFile(uiaPath);
    }
}

/**
 * Clone the project file with a preview suffix and set the initial attribute to the currently
 * open document
 *
 * @return path to the preview project file. Return path to .uip or preview .uip file if there
 * is no project file.
 */
QString ProjectFile::createPreview()
{
    CDoc *doc = g_StudioApp.GetCore()->GetDoc();
    QString uipPrvPath = doc->GetDocumentPath();
    // create a preview uip if doc modified
    if (doc->IsModified()) {
        uipPrvPath.replace(QLatin1String(".uip"), QLatin1String("_@preview@.uip"));
        g_StudioApp.GetCore()->OnSaveDocument(uipPrvPath, true);
    }

    // if no project file exist (.uia) just return the preview uip path
    if (!m_fileInfo.exists())
        return uipPrvPath;

    // create a preview project file
    QString prvPath = getProjectFilePath();
    prvPath.replace(QLatin1String(".uia"), QLatin1String("_@preview@.uia"));

    if (QFile::exists(prvPath))
        QFile::remove(prvPath);

    if (QFile::copy(getProjectFilePath(), prvPath)) {
        QDomDocument domDoc;
        QSaveFile file(prvPath);
        if (StudioUtils::openDomDocumentSave(file, domDoc)) {
            QDomElement assetsElem = domDoc.documentElement()
                                     .firstChildElement(QStringLiteral("assets"));
            assetsElem.setAttribute(QStringLiteral("initial"), doc->getPresentationId());

            if (doc->IsModified()) {
                // Set the preview uip path in the uia file
                QDomNodeList pNodes = assetsElem.elementsByTagName(QStringLiteral("presentation"));
                for (int i = 0; i < pNodes.count(); ++i) {
                    QDomElement pElem = pNodes.at(i).toElement();
                    if (pElem.attribute(QStringLiteral("id")) == doc->getPresentationId()) {
                        QString src = QDir(getProjectPath()).relativeFilePath(uipPrvPath);
                        pElem.setAttribute(QStringLiteral("src"), src);
                        break;
                    }
                }
            }
            StudioUtils::commitDomDocumentSave(file, domDoc);
        }

        return prvPath;
    } else {
        qWarning() << "Couldn't clone project file";
    }

    return {};
}

void ProjectFile::parseDataInputElem(const QDomElement &elem,
                                     QMap<QString, CDataInputDialogItem *> &dataInputs)
{
    if (elem.nodeName() == QLatin1String("dataInput")) {
        CDataInputDialogItem *item = new CDataInputDialogItem();
        item->name = elem.attribute(QStringLiteral("name"));
        QString type = elem.attribute(QStringLiteral("type"));
        if (type == QLatin1String("Ranged Number")) {
            item->type = EDataType::DataTypeRangedNumber;
            item->minValue = elem.attribute(QStringLiteral("min")).toFloat();
            item->maxValue = elem.attribute(QStringLiteral("max")).toFloat();
        } else if (type == QLatin1String("String")) {
            item->type = EDataType::DataTypeString;
        } else if (type == QLatin1String("Float")) {
            item->type = EDataType::DataTypeFloat;
        } else if (type == QLatin1String("Boolean")) {
            item->type = EDataType::DataTypeBoolean;
        } else if (type == QLatin1String("Vector3")) {
            item->type = EDataType::DataTypeVector3;
        } else if (type == QLatin1String("Vector2")) {
            item->type = EDataType::DataTypeVector2;
        } else if (type == QLatin1String("Variant")) {
            item->type = EDataType::DataTypeVariant;
        }
#ifdef DATAINPUT_EVALUATOR_ENABLED
        else if (type == QLatin1String("Evaluator")) {
            item->type = EDataType::DataTypeEvaluator;
            item->valueString = elem.attribute(QStringLiteral("evaluator"));
        }
#endif
        item->metaDataKey = elem.attribute((QStringLiteral("metadatakey")));
        item->metaData = elem.attribute((QStringLiteral("metadata")));
        dataInputs.insert(item->name, item);
    }
}

void ProjectFile::loadDataInputs(const QString &projFile,
                                 QMap<QString, CDataInputDialogItem *> &dataInputs)
{
    QFileInfo fi(projFile);
    if (fi.exists()) {
        QDomDocument doc;
        if (!StudioUtils::readFileToDomDocument(projFile, doc))
            return;
        QDomElement assetsElem = doc.documentElement().firstChildElement(QStringLiteral("assets"));
        if (!assetsElem.isNull()) {
            for (QDomElement p = assetsElem.firstChild().toElement(); !p.isNull();
                p = p.nextSibling().toElement()) {
                parseDataInputElem(p, dataInputs);
            }
        }
    }
}

void ProjectFile::loadSubpresentationsAndDatainputs(
        QVector<SubPresentationRecord> &subpresentations,
        QMap<QString, CDataInputDialogItem *> &datainputs)
{
    if (!m_fileInfo.exists())
        return;

    subpresentations.clear();
    datainputs.clear();

    m_initialPresentation = g_StudioApp.GetCore()->GetDoc()->getPresentationId();

    QDomDocument doc;
    if (!StudioUtils::readFileToDomDocument(getProjectFilePath(), doc))
        return;

    QDomElement assetsElem = doc.documentElement().firstChildElement(QStringLiteral("assets"));
    if (!assetsElem.isNull()) {
        QString initial = assetsElem.attribute(QStringLiteral("initial"));
        if (!initial.isEmpty())
            m_initialPresentation = initial;
        for (QDomElement p = assetsElem.firstChild().toElement(); !p.isNull();
            p = p.nextSibling().toElement()) {
            if ((p.nodeName() == QLatin1String("presentation")
                 || p.nodeName() == QLatin1String("presentation-qml"))
                    && p.attribute(QStringLiteral("id"))
                       != g_StudioApp.GetCore()->GetDoc()->getPresentationId()) {
                QString argsOrSrc = p.attribute(QStringLiteral("src"));
                if (argsOrSrc.isNull())
                    argsOrSrc = p.attribute(QStringLiteral("args"));
                subpresentations.push_back(
                            SubPresentationRecord(p.nodeName(), p.attribute("id"), argsOrSrc));
            } else {
                parseDataInputElem(p, datainputs);
            }
        }
    }
    g_StudioApp.GetCore()->GetDoc()->UpdateDatainputMap();
}

/**
 * Check that a given presentation's or Qml stream's id is unique
 *
 * @param id presentation's or Qml stream's Id
 * @param src source node to exclude from the check. Defaults to empty.
 */
bool ProjectFile::isUniquePresentationId(const QString &id, const QString &src) const
{
    if (!m_fileInfo.exists())
        return true;

    bool isCurrDoc = src == g_StudioApp.GetCore()->GetDoc()->getRelativePath();

    if (!isCurrDoc && id == g_StudioApp.GetCore()->GetDoc()->getPresentationId())
        return false;

    auto *sp = std::find_if(g_StudioApp.m_subpresentations.begin(),
                            g_StudioApp.m_subpresentations.end(),
                           [&id, &src](const SubPresentationRecord &spr) -> bool {
                               return spr.m_id == id && spr.m_argsOrSrc != src;
                           });
    return  sp == g_StudioApp.m_subpresentations.end();
}

// Returns unique presentation name based on given relative presentation path
// Only the file name base is returned, no path or suffix.
QString ProjectFile::getUniquePresentationName(const QString &presSrc) const
{
    if (!m_fileInfo.exists())
        return {};

    const QString fullPresSrc = getAbsoluteFilePathTo(presSrc);
    QFileInfo fi(fullPresSrc);
    const QStringList files = fi.dir().entryList(QDir::Files);
    QString checkName = fi.fileName();
    if (files.contains(checkName)) {
        const QString nameTemplate = QStringLiteral("%1%2.%3");
        const QString suffix = fi.suffix();
        QString base = fi.completeBaseName();
        int counter = 0;
        int checkIndex = base.size();
        while (checkIndex > 1 && base.at(checkIndex - 1).isDigit())
            --checkIndex;
        if (checkIndex < base.size())
            counter = base.mid(checkIndex).toInt();

        if (counter > 0)
            base = base.left(checkIndex);

        while (files.contains(checkName))
            checkName = nameTemplate.arg(base).arg(++counter).arg(suffix);
    }

    return QFileInfo(checkName).completeBaseName();
}

QString ProjectFile::ensureUniquePresentationId(const QString &id) const
{
    if (!m_fileInfo.exists())
        return id;

    QDomDocument doc;
    if (!StudioUtils::readFileToDomDocument(m_fileInfo.filePath(), doc))
        return id;

    QString newId = id;
    QDomElement assetsElem = doc.documentElement().firstChildElement(QStringLiteral("assets"));
    if (!assetsElem.isNull()) {
        bool unique;
        int n = 1;
        do {
            unique = true;
            for (QDomElement p = assetsElem.firstChild().toElement(); !p.isNull();
                p = p.nextSibling().toElement()) {
                if ((p.nodeName() == QLatin1String("presentation")
                     || p.nodeName() == QLatin1String("presentation-qml"))
                        && p.attribute(QStringLiteral("id")) == newId) {
                    newId = id + QString::number(n++);
                    unique = false;
                    break;
                }
            }
        } while (!unique);
    }

    return newId;
}

// Get the path to the project root. If .uia doesn't exist, return path to current presentation.
QString ProjectFile::getProjectPath() const
{
    if (m_fileInfo.exists())
        return m_fileInfo.path();
    else
        return QFileInfo(g_StudioApp.GetCore()->GetDoc()->GetDocumentPath()).absolutePath();
}

// Get the path to the project's .uia file. If .uia doesn't exist, return empty string.
QString ProjectFile::getProjectFilePath() const
{
    if (m_fileInfo.exists())
        return m_fileInfo.filePath();
    else
        return {};
}

// Returns current project name or empty string if there is no .uia file
QString ProjectFile::getProjectName() const
{
    if (m_fileInfo.exists())
        return m_fileInfo.completeBaseName();
    else
        return {};
}

/**
 * Get presentations out of a uia file
 *
 * @param inUiaPath uia file path
 * @param outSubpresentations list of collected presentations
 * @param excludePresentationSrc execluded presentation, (commonly the current presentation)
 */
// static
void ProjectFile::getPresentations(const QString &inUiaPath,
                                   QVector<SubPresentationRecord> &outSubpresentations,
                                   const QString &excludePresentationSrc)
{
    QFile file(inUiaPath);
    if (!file.open(QFile::Text | QFile::ReadOnly)) {
        qWarning() << file.errorString();
        return;
    }

    QXmlStreamReader reader(&file);
    reader.setNamespaceProcessing(false);

    while (!reader.atEnd()) {
        if (reader.readNextStartElement()
            && (reader.name() == QLatin1String("presentation")
                || reader.name() == QLatin1String("presentation-qml"))) {
            const auto attrs = reader.attributes();
            QString argsOrSrc = attrs.value(QLatin1String("src")).toString();
            if (excludePresentationSrc == argsOrSrc)
                continue;
            if (argsOrSrc.isNull())
                argsOrSrc = attrs.value(QLatin1String("args")).toString();

            outSubpresentations.push_back(
                        SubPresentationRecord(reader.name().toString(),
                                              attrs.value(QLatin1String("id")).toString(),
                                              argsOrSrc));
        } else if (reader.name() == QLatin1String("assets") && !reader.isStartElement()) {
            break; // reached end of <assets>
        }
    }
}

void ProjectFile::setInitialPresentation(const QString &initialId)
{
    if (!initialId.isEmpty() && m_initialPresentation != initialId) {
        m_initialPresentation = initialId;

        ensureProjectFile();

        QDomDocument domDoc;
        QSaveFile file(getProjectFilePath());
        if (!StudioUtils::openDomDocumentSave(file, domDoc))
            return;

        QDomElement assetsElem
                = domDoc.documentElement().firstChildElement(QStringLiteral("assets"));
        if (!assetsElem.isNull() && assetsElem.attribute(QStringLiteral("initial"))
                != m_initialPresentation) {
            assetsElem.setAttribute(QStringLiteral("initial"), m_initialPresentation);

            StudioUtils::commitDomDocumentSave(file, domDoc);
        }
    }
}

// Returns true if file rename was successful. The parameters are relative to project root.
bool ProjectFile::renamePresentationFile(const QString &oldName, const QString &newName)
{
    const QString fullOldPath = getAbsoluteFilePathTo(oldName);
    const QString fullNewPath = getAbsoluteFilePathTo(newName);
    QFile presFile(fullOldPath);
    const bool success = presFile.rename(fullNewPath);

    if (success) {
        // Update assets in .uia
        ensureProjectFile();

        const bool isQml = oldName.endsWith(QLatin1String(".qml"));

        if (isQml && g_StudioApp.m_qmlStreamMap.contains(fullOldPath)) {
            // Update Qml stream type cache
            g_StudioApp.m_qmlStreamMap.remove(fullOldPath);
            g_StudioApp.m_qmlStreamMap.insert(fullNewPath, true);
        }

        QDomDocument domDoc;
        QSaveFile file(getProjectFilePath());
        if (!StudioUtils::openDomDocumentSave(file, domDoc))
            return false;

        QDomElement assetsElem
                = domDoc.documentElement().firstChildElement(QStringLiteral("assets"));
        if (!assetsElem.isNull()) {
            QDomNodeList pqNodes
                    = isQml ? assetsElem.elementsByTagName(QStringLiteral("presentation-qml"))
                            : assetsElem.elementsByTagName(QStringLiteral("presentation"));
            if (!pqNodes.isEmpty()) {
                CDoc *doc = g_StudioApp.GetCore()->GetDoc();
                for (int i = 0; i < pqNodes.count(); ++i) {
                    QDomElement pqElem = pqNodes.at(i).toElement();
                    const QString attTag = isQml ? QStringLiteral("args") : QStringLiteral("src");
                    const QString srcOrArgs = pqElem.attribute(attTag);
                    if (srcOrArgs == oldName) {
                        pqElem.setAttribute(attTag, newName);

                        if (pqElem.attribute(QStringLiteral("id")) != doc->getPresentationId()) {
                            // update m_subpresentations
                            auto *sp = std::find_if(
                                        g_StudioApp.m_subpresentations.begin(),
                                        g_StudioApp.m_subpresentations.end(),
                                        [&oldName](const SubPresentationRecord &spr) -> bool {
                                            return spr.m_argsOrSrc == oldName;
                                        });
                            if (sp != g_StudioApp.m_subpresentations.end())
                                sp->m_argsOrSrc = newName;
                        } else {
                            // If renaming current presentation, need to update the doc path, too
                            doc->SetDocumentPath(fullNewPath);
                        }

                        StudioUtils::commitDomDocumentSave(file, domDoc);

                        Q_EMIT assetNameChanged();
                        break;
                    }
                }
            }
        }
    }

    return success;
}

/**
 * Delete a presentation (or qml-stream) file and remove references to it from the project file.
 * This function assumes the removed presentation is not referenced by any presentation
 * in the project and is not the current presentation.
 *
 * @param filePath Absolute file path to presentation to delete
 */
void ProjectFile::deletePresentationFile(const QString &filePath)
{
    QFile(filePath).remove();

    if (m_fileInfo.exists()) {
        const QString relPath = getRelativeFilePathTo(filePath);
        const bool isQml = relPath.endsWith(QLatin1String(".qml"));

        // Update records and caches
        if (isQml && g_StudioApp.m_qmlStreamMap.contains(filePath))
            g_StudioApp.m_qmlStreamMap.remove(filePath);
        for (int i = 0, count = g_StudioApp.m_subpresentations.size(); i < count; ++i) {
            SubPresentationRecord &rec = g_StudioApp.m_subpresentations[i];
            if (rec.m_argsOrSrc == relPath) {
                g_StudioApp.m_subpresentations.remove(i);
                break;
            }
        }

        // Update project file
        QDomDocument domDoc;
        QSaveFile projectFile(getProjectFilePath());
        if (!StudioUtils::openDomDocumentSave(projectFile, domDoc))
            return;

        QDomElement assetsElem
                = domDoc.documentElement().firstChildElement(QStringLiteral("assets"));
        if (!assetsElem.isNull()) {
            QDomNodeList pqNodes
                    = isQml ? assetsElem.elementsByTagName(QStringLiteral("presentation-qml"))
                            : assetsElem.elementsByTagName(QStringLiteral("presentation"));
            if (!pqNodes.isEmpty()) {
                for (int i = 0; i < pqNodes.count(); ++i) {
                    QDomElement pqElem = pqNodes.at(i).toElement();
                    const QString attTag = isQml ? QStringLiteral("args") : QStringLiteral("src");
                    const QString srcOrArgs = pqElem.attribute(attTag);
                    if (srcOrArgs == relPath) {
                        const QString id = pqElem.attribute(QStringLiteral("id"));
                        // If initial presentation is deleted, change current to initial
                        if (assetsElem.attribute(QStringLiteral("initial")) == id) {
                            m_initialPresentation
                                    = g_StudioApp.GetCore()->GetDoc()->getPresentationId();
                            assetsElem.setAttribute(QStringLiteral("initial"),
                                                    m_initialPresentation);
                        }
                        assetsElem.removeChild(pqNodes.at(i));
                        StudioUtils::commitDomDocumentSave(projectFile, domDoc);
                        break;
                    }
                }
            }
        }
        // Update registrations asynchronously, as it messes with event processing, which can
        // cause issues with file models elsewhere in the editor unless file removal is fully
        // handled.
        QTimer::singleShot(0, []() {
            g_StudioApp.getRenderer().RegisterSubpresentations(g_StudioApp.m_subpresentations);
        });
    }
}

void ProjectFile::renameMaterial(const QString &oldName, const QString &newName)
{
    for (auto &pres : qAsConst(g_StudioApp.m_subpresentations)) {
        if (pres.m_type == QLatin1String("presentation")) {
            PresentationFile::renameMaterial(getAbsoluteFilePathTo(pres.m_argsOrSrc),
                                             oldName, newName);
        }
    }
    Q_EMIT assetNameChanged();
}

// Copies oldPres presentation as newPres. The id for newPres will be autogenerated.
bool ProjectFile::duplicatePresentation(const QString &oldPres, const QString &newPres)
{
    const QString fullOldPath = getAbsoluteFilePathTo(oldPres);
    const QString fullNewPath = getAbsoluteFilePathTo(newPres);
    const bool success = QFile::copy(fullOldPath, fullNewPath);

    if (success)
        addPresentationNode(fullNewPath, {});

    return success;
}

/**
 * Returns an absolute file path for a given relative file path.
 *
 * @param relFilePath A file path relative to project root to convert.
 */
QString ProjectFile::getAbsoluteFilePathTo(const QString &relFilePath) const
{
    auto projectPath = QDir(getProjectPath()).absoluteFilePath(relFilePath);
    return QDir::cleanPath(projectPath);
}

/**
 * Returns a file path relative to the project root for given absolute file path.
 *
 * @param absFilePath An absolute file path to convert.
 */
QString ProjectFile::getRelativeFilePathTo(const QString &absFilePath) const
{
    return QDir(getProjectPath()).relativeFilePath(absFilePath);
}

// Return multimap of type subpresentationid - QPair<datainput, propertyname>
QMultiMap<QString, QPair<QString, QString>>
ProjectFile::getDiBindingtypesFromSubpresentations() const
{
    QMultiMap<QString, QPair<QString, QString>> map;
    for (auto sp : qAsConst(g_StudioApp.m_subpresentations))
        PresentationFile::getDataInputBindings(sp, map);

    return map;
}

/**
 * Load variants data to m_variantsDef
 *
 * @param filePath the file path to load the variants from. If empty, variants are loaded from the
 *                 project file and replace m_variantsDef. If a filePath is specified, the loaded
 *                 variants are merged with m_variantsDef
 */
void ProjectFile::loadVariants(const QString &filePath)
{
    if (!m_fileInfo.exists())
        return;

    bool isProj = filePath.isEmpty() || filePath == getProjectFilePath();
    QFile file(isProj ? getProjectFilePath() : filePath);
    if (!file.open(QFile::Text | QFile::ReadOnly)) {
        qWarning() << file.errorString();
        return;
    }

    if (isProj)
        m_variantsDef.clear();

    QXmlStreamReader reader(&file);
    reader.setNamespaceProcessing(false);

    VariantGroup *currentGroup = nullptr;
    while (!reader.atEnd()) {
        if (reader.readNextStartElement()) {
            if (reader.name() == QLatin1String("variantgroup")) {
                QString groupId = reader.attributes().value(QLatin1String("id")).toString();
                QString groupColor = reader.attributes().value(QLatin1String("color")).toString();
                currentGroup = &m_variantsDef[groupId];
                currentGroup->m_color = groupColor;
            } else if (reader.name() == QLatin1String("variant")) {
                if (currentGroup) {
                    QString tagId = reader.attributes().value(QLatin1String("id")).toString();
                    if (!currentGroup->m_tags.contains(tagId))
                        currentGroup->m_tags.append(tagId);
                } else {
                    qWarning() << "Error parsing variant tags.";
                }
            } else if (currentGroup) {
                break;
            }
        }
    }

    if (!isProj) {
        // if loading variants from a file, update the uia
        QDomDocument domDoc;
        QSaveFile fileProj(getProjectFilePath());
        if (!StudioUtils::openDomDocumentSave(fileProj, domDoc))
            return;

        QDomElement vElem = domDoc.documentElement().firstChildElement(QStringLiteral("variants"));
        if (!vElem.isNull())
            domDoc.documentElement().removeChild(vElem);

        vElem = domDoc.createElement(QStringLiteral("variants"));
        domDoc.documentElement().appendChild(vElem);

        const auto keys = m_variantsDef.keys();
        for (auto &g : keys) {
            QDomElement gElem = domDoc.createElement(QStringLiteral("variantgroup"));
            gElem.setAttribute(QStringLiteral("id"), g);
            gElem.setAttribute(QStringLiteral("color"), m_variantsDef[g].m_color);
            vElem.appendChild(gElem);

            for (auto &t : qAsConst(m_variantsDef[g].m_tags)) {
                QDomElement tElem = domDoc.createElement(QStringLiteral("variant"));
                tElem.setAttribute(QStringLiteral("id"), t);
                gElem.appendChild(tElem);
            }
        }

        StudioUtils::commitDomDocumentSave(fileProj, domDoc);
    }
}

// Add a new tag to a variants group
void ProjectFile::addVariantTag(const QString &group, const QString &newTag)
{
    QDomDocument domDoc;
    QSaveFile file(getProjectFilePath());
    if (!StudioUtils::openDomDocumentSave(file, domDoc))
        return;

    QDomElement newTagElem = domDoc.createElement(QStringLiteral("variant"));
    newTagElem.setAttribute(QStringLiteral("id"), newTag);

    QDomNodeList groupsElems = domDoc.documentElement()
                                     .firstChildElement(QStringLiteral("variants"))
                                     .elementsByTagName(QStringLiteral("variantgroup"));

    // update and save the uia
    for (int i = 0; i < groupsElems.count(); ++i) {
        QDomElement gElem = groupsElems.at(i).toElement();
        if (gElem.attribute(QStringLiteral("id")) == group) {
            gElem.appendChild(newTagElem);
            StudioUtils::commitDomDocumentSave(file, domDoc);
            break;
        }
    }

    // update m_variantsDef
    m_variantsDef[group].m_tags.append(newTag);
}

// Add a new group, it is assumes that the new group name is unique
void ProjectFile::addVariantGroup(const QString &newGroup)
{
    QDomDocument domDoc;
    QSaveFile file(getProjectFilePath());
    if (!StudioUtils::openDomDocumentSave(file, domDoc))
        return;

    QDomElement variantsElem = domDoc.documentElement()
                                     .firstChildElement(QStringLiteral("variants"));

    if (variantsElem.isNull()) {
        QDomElement newVariantsElem = domDoc.createElement(QStringLiteral("variants"));
        domDoc.documentElement().appendChild(newVariantsElem);
        variantsElem = newVariantsElem;
    }

    // generate random semi-bright color
    int r = 0x555555 + QRandomGenerator::global()->generate() % 0x555555; // 0x555555 = 0xffffff / 3
    QString newColor = QLatin1Char('#') + QString::number(r, 16);

    QDomElement newGroupElem = domDoc.createElement(QStringLiteral("variantgroup"));
    newGroupElem.setAttribute(QStringLiteral("id"), newGroup);
    newGroupElem.setAttribute(QStringLiteral("color"), newColor);
    variantsElem.appendChild(newGroupElem);
    StudioUtils::commitDomDocumentSave(file, domDoc);

    // update m_variantsDef
    VariantGroup g;
    g.m_color = newColor;
    m_variantsDef[newGroup] = g;
}

void ProjectFile::renameVariantTag(const QString &group, const QString &oldTag,
                                   const QString &newTag)
{
    QDomDocument domDoc;
    QSaveFile file(getProjectFilePath());
    if (!StudioUtils::openDomDocumentSave(file, domDoc))
        return;

    // rename the tag in all uip files
    QDomNodeList presElems = domDoc.documentElement()
                                   .firstChildElement(QStringLiteral("assets"))
                                   .elementsByTagName(QStringLiteral("presentation"));
    for (int i = 0; i < presElems.count(); ++i) {
        QString pPath = m_fileInfo.path() + QLatin1Char('/')
                + presElems.at(i).toElement().attribute(QStringLiteral("src"));
        renameTagInUip(pPath, group, oldTag, newTag);
    }

    // update and save the uia
    QDomNodeList groupsElems = domDoc.documentElement()
                                     .firstChildElement(QStringLiteral("variants"))
                                     .elementsByTagName(QStringLiteral("variantgroup"));

    bool renamed = false;
     for (int i = 0; i < groupsElems.count(); ++i) {
        QDomElement gElem = groupsElems.at(i).toElement();
        if (gElem.attribute(QStringLiteral("id")) == group) {
            QDomNodeList tagsElems = gElem.childNodes();
            for (int j = 0; j < tagsElems.count(); ++j) {
                QDomElement tElem = tagsElems.at(j).toElement();
                if (tElem.attribute(QStringLiteral("id")) == oldTag) {
                    tElem.setAttribute(QStringLiteral("id"), newTag);
                    StudioUtils::commitDomDocumentSave(file, domDoc);
                    renamed = true;
                    break;
                }
            }
            if (renamed)
                break;
        }
    }

    // update the property
    CDoc *doc = g_StudioApp.GetCore()->GetDoc();
    const auto propertySystem = doc->GetStudioSystem()->GetPropertySystem();
    const auto bridge = doc->GetStudioSystem()->GetClientDataModelBridge();
    const auto layers = doc->getLayers();
    auto property = bridge->GetLayer().m_variants;
    for (auto layer : layers) {
        qt3dsdm::SValue sValue;
        if (propertySystem->GetInstancePropertyValue(layer, property, sValue)) {
            QString propVal = qt3dsdm::get<qt3dsdm::TDataStrPtr>(sValue)->toQString();
            QString oldGroupTagPair = QStringLiteral("%1:%2").arg(group).arg(oldTag);
            if (propVal.contains(oldGroupTagPair)) {
                propVal.replace(oldGroupTagPair, QStringLiteral("%1:%2").arg(group).arg(newTag));
                qt3dsdm::SValue sVal
                    = std::make_shared<qt3dsdm::CDataStr>(Q3DStudio::CString::fromQString(propVal));
                propertySystem->SetInstancePropertyValue(layer, property, sVal);
            }
        }
    }

    // update m_variantsDef
    for (auto &t : m_variantsDef[group].m_tags) {
        if (t == oldTag) {
            t = newTag;
            renamed = true;
            break;
        }
    }
}

// rename a variant group, newGroup is assumed to be unique
void ProjectFile::renameVariantGroup(const QString &oldGroup, const QString &newGroup)
{
    QDomDocument domDoc;
    QSaveFile file(getProjectFilePath());
    if (!StudioUtils::openDomDocumentSave(file, domDoc))
        return;

    // rename the group in all uip files
    QDomNodeList presElems = domDoc.documentElement()
                                   .firstChildElement(QStringLiteral("assets"))
                                   .elementsByTagName(QStringLiteral("presentation"));
    for (int i = 0; i < presElems.count(); ++i) {
        QString pPath = m_fileInfo.path() + QLatin1Char('/')
                + presElems.at(i).toElement().attribute(QStringLiteral("src"));
        renameGroupInUip(pPath, oldGroup, newGroup);
    }

    // update and save the uia
    QDomNodeList groupsElems = domDoc.documentElement()
                                     .firstChildElement(QStringLiteral("variants"))
                                     .elementsByTagName(QStringLiteral("variantgroup"));

     for (int i = 0; i < groupsElems.count(); ++i) {
        QDomElement gElem = groupsElems.at(i).toElement();
        if (gElem.attribute(QStringLiteral("id")) == oldGroup) {
            gElem.setAttribute(QStringLiteral("id"), newGroup);
            StudioUtils::commitDomDocumentSave(file, domDoc);
            break;
        }
    }

     // update the property
     CDoc *doc = g_StudioApp.GetCore()->GetDoc();
     const auto propertySystem = doc->GetStudioSystem()->GetPropertySystem();
     const auto bridge = doc->GetStudioSystem()->GetClientDataModelBridge();
     const auto layers = doc->getLayers();
     auto property = bridge->GetLayer().m_variants;
     for (auto layer : layers) {
         qt3dsdm::SValue sValue;
         if (propertySystem->GetInstancePropertyValue(layer, property, sValue)) {
             QString propVal = qt3dsdm::get<qt3dsdm::TDataStrPtr>(sValue)->toQString();
             QString oldGroupWithColon = QStringLiteral("%1:").arg(oldGroup);
             if (propVal.contains(oldGroupWithColon)) {
                 propVal.replace(oldGroupWithColon, QStringLiteral("%1:").arg(newGroup));
                 qt3dsdm::SValue sVal = std::make_shared<qt3dsdm::CDataStr>(
                                        Q3DStudio::CString::fromQString(propVal));
                 propertySystem->SetInstancePropertyValue(layer, property, sVal);
             }
         }
     }

    // update m_variantsDef
    m_variantsDef[newGroup] = m_variantsDef[oldGroup];
    m_variantsDef.remove(oldGroup);
}

void ProjectFile::deleteVariantGroup(const QString &group)
{
    CDoc *doc = g_StudioApp.GetCore()->GetDoc();

    QDomDocument domDoc;
    QSaveFile file(getProjectFilePath());
    if (!StudioUtils::openDomDocumentSave(file, domDoc))
        return;

    // check if group is in use in other presentations in the porject
    int inUseIdx = -1; // index of first presentation that has the group in-use
    QDomNodeList presElems = domDoc.documentElement()
                                   .firstChildElement(QStringLiteral("assets"))
                                   .elementsByTagName(QStringLiteral("presentation"));
    for (int i = 0; i < presElems.count(); ++i) {
        QString pPath = m_fileInfo.path() + QLatin1Char('/')
                + presElems.at(i).toElement().attribute(QStringLiteral("src"));
        if (pPath != doc->GetDocumentPath() && groupExistsInUip(pPath, group)) {
            inUseIdx = i;
            break;
        }
    }

    if (inUseIdx != -1) {
        QMessageBox box;
        box.setWindowTitle(tr("Group tags in use"));
        box.setText(tr("Some tags in the Group '%1' are in use in the project, are you sure you"
                       " want to delete the group?").arg(group));
        box.setIcon(QMessageBox::Warning);
        box.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
        box.setButtonText(QMessageBox::Yes, QStringLiteral("Delete"));
        switch (box.exec()) {
        case QMessageBox::Yes:
            // delete the group from all uips that use it
            for (int i = inUseIdx; i < presElems.count(); ++i) {
                QString pPath = m_fileInfo.path() + QLatin1Char('/')
                        + presElems.at(i).toElement().attribute(QStringLiteral("src"));
                if (pPath != doc->GetDocumentPath())
                    deleteGroupFromUip(pPath, group);
            }
            break;

        default:
            // abort deletion
            return;
        }
    }

    // delete the group from current uip, if exists
    deleteGroupFromUip(doc->GetDocumentPath(), group);

    // delete the group from the property (if set)
    const auto propertySystem = doc->GetStudioSystem()->GetPropertySystem();
    const auto bridge = doc->GetStudioSystem()->GetClientDataModelBridge();
    const auto layers = doc->getLayers();
    auto property = bridge->GetLayer().m_variants;
    for (auto layer : layers) {
        qt3dsdm::SValue sValue;
        if (propertySystem->GetInstancePropertyValue(layer, property, sValue)) {
            QString propVal = qt3dsdm::get<qt3dsdm::TDataStrPtr>(sValue)->toQString();
            if (propVal.contains(QStringLiteral("%1:").arg(group))) {
                // property has the deleted group, need to update it, else the deleted group
                // will be saved the uip if the user saves the presentation.
                QRegExp rgx(QStringLiteral("%1:\\w*,*|,%1:\\w*").arg(group));
                propVal.replace(rgx, {});
                qt3dsdm::SValue sVal = std::make_shared<qt3dsdm::CDataStr>(
                                       Q3DStudio::CString::fromQString(propVal));
                propertySystem->SetInstancePropertyValue(layer, property, sVal);
            }
        }
    }

    // update and save the uia
    QDomElement variantsElem = domDoc.documentElement()
                               .firstChildElement(QStringLiteral("variants"));
    QDomNodeList groupsElems = variantsElem.elementsByTagName(QStringLiteral("variantgroup"));

    bool deleted = false;
    for (int i = 0; i < groupsElems.count(); ++i) {
        QDomElement gElem = groupsElems.at(i).toElement();
        if (gElem.attribute(QStringLiteral("id")) == group) {
            variantsElem.removeChild(gElem);
            StudioUtils::commitDomDocumentSave(file, domDoc);
            deleted = true;
            break;
        }
    }

    // update m_variantsDef
    m_variantsDef.remove(group);
}

void ProjectFile::changeVariantGroupColor(const QString &group, const QString &newColor)
{
    QDomDocument domDoc;
    QSaveFile file(getProjectFilePath());
    if (!StudioUtils::openDomDocumentSave(file, domDoc))
        return;

    // update and save the uia
    QDomNodeList groupsElems = domDoc.documentElement()
                                     .firstChildElement(QStringLiteral("variants"))
                                     .elementsByTagName(QStringLiteral("variantgroup"));

    for (int i = 0; i < groupsElems.count(); ++i) {
        QDomElement gElem = groupsElems.at(i).toElement();
        if (gElem.attribute(QStringLiteral("id")) == group) {
            gElem.setAttribute(QStringLiteral("color"), newColor);
            StudioUtils::commitDomDocumentSave(file, domDoc);
            break;
        }
    }

    // update m_variantsDef
    m_variantsDef[group].m_color = newColor;
}

bool ProjectFile::tagExistsInUip(const QString &src, const QString &group, const QString &tag) const
{
    QFile file(src);
    if (!file.open(QFile::Text | QFile::ReadOnly)) {
        qWarning() << file.errorString();
        return false;
    }

    QXmlStreamReader reader(&file);
    reader.setNamespaceProcessing(false);

    while (!reader.atEnd()) {
        if (reader.readNextStartElement()) {
            if (reader.name() == QLatin1String("Layer")
                && reader.attributes().hasAttribute(QLatin1String("variants"))) {
                QStringRef v = reader.attributes().value(QLatin1String("variants"));
                if (v.contains(group + QLatin1Char(':') + tag))
                    return true;
            } else if (reader.name() == QLatin1String("Logic")) {
                break;
            }
        }
    }

    return false;
}

bool ProjectFile::groupExistsInUip(const QString &src, const QString &group) const
{
    QFile file(src);
    if (!file.open(QFile::Text | QFile::ReadOnly)) {
        qWarning() << file.errorString();
        return false;
    }

    QXmlStreamReader reader(&file);
    reader.setNamespaceProcessing(false);

    while (!reader.atEnd()) {
        if (reader.readNextStartElement()) {
            if (reader.name() == QLatin1String("Layer")
                && reader.attributes().hasAttribute(QLatin1String("variants"))) {
                QStringRef v = reader.attributes().value(QLatin1String("variants"));
                if (v.contains(group + QLatin1Char(':')))
                    return true;
            } else if (reader.name() == QLatin1String("Logic")) {
                break;
            }
        }
    }

    return false;
}

// renames a tag (if exists) in all layers in a uip file
void ProjectFile::renameTagInUip(const QString &src, const QString &group, const QString &tag,
                                 const QString &newName)
{
    QDomDocument domDoc;
    QSaveFile file(src);
    if (!StudioUtils::openDomDocumentSave(file, domDoc))
        return;

    QDomNodeList layerElems = domDoc.documentElement()
                                    .elementsByTagName(QStringLiteral("Layer"));
    bool needSave = false;
    for (int i = 0; i < layerElems.count(); ++i) {
        QDomElement lElem = layerElems.at(i).toElement();
        if (lElem.hasAttribute(QStringLiteral("variants"))) {
            QStringList tagPairs = lElem.attribute(QStringLiteral("variants"))
                                   .split(QLatin1Char(','));
            QString tagFrom = group + QLatin1Char(':') + tag;
            QString tagTo = group + QLatin1Char(':') + newName;

            if (tagPairs.contains(tagFrom)) {
                tagPairs.replaceInStrings(tagFrom, tagTo);
                lElem.setAttribute(QStringLiteral("variants"), tagPairs.join(QLatin1Char(',')));
                needSave = true;
            }
        }
    }

    if (needSave)
        StudioUtils::commitDomDocumentSave(file, domDoc);
}

void ProjectFile::renameGroupInUip(const QString &src, const QString &group, const QString &newName)
{
    QDomDocument domDoc;
    QSaveFile file(src);
    if (!StudioUtils::openDomDocumentSave(file, domDoc))
        return;

    QDomNodeList layerElems = domDoc.documentElement()
                                    .elementsByTagName(QStringLiteral("Layer"));
    bool needSave = false;
    for (int i = 0; i < layerElems.count(); ++i) {
        QDomElement lElem = layerElems.at(i).toElement();
        if (lElem.hasAttribute(QStringLiteral("variants"))) {
            QString variants = lElem.attribute(QStringLiteral("variants"));
            if (variants.contains(group + QLatin1Char(':'))) {
                variants.replace(group + QLatin1Char(':'), newName + QLatin1Char(':'));
                lElem.setAttribute(QStringLiteral("variants"), variants);
                needSave = true;
            }
        }
    }

    if (needSave)
        StudioUtils::commitDomDocumentSave(file, domDoc);
}

// deletes a tag (if exists) from all layers in a uip file
void ProjectFile::deleteTagFromUip(const QString &src, const QString &group, const QString &tag)
{
    QDomDocument domDoc;
    QSaveFile file(src);
    if (!StudioUtils::openDomDocumentSave(file, domDoc))
        return;

    QDomNodeList layerElems = domDoc.documentElement()
                                    .elementsByTagName(QStringLiteral("Layer"));
    bool needSave = false;
    for (int i = 0; i < layerElems.count(); ++i) {
        QDomElement lElem = layerElems.at(i).toElement();
        if (lElem.hasAttribute(QStringLiteral("variants"))) {
            QStringList tagPairs = lElem.attribute(QStringLiteral("variants"))
                                                                        .split(QLatin1Char(','));
            QString tagPair = group + QLatin1Char(':') + tag;
            if (tagPairs.contains(tagPair)) {
                tagPairs.removeOne(tagPair);
                lElem.setAttribute(QStringLiteral("variants"), tagPairs.join(QLatin1Char(',')));
                needSave = true;
            }
        }
    }

    if (needSave)
        StudioUtils::commitDomDocumentSave(file, domDoc);
}

// deletes a group (if exists) from all layers in a uip file
void ProjectFile::deleteGroupFromUip(const QString &src, const QString &group)
{
    QDomDocument domDoc;
    QSaveFile file(src);
    if (!StudioUtils::openDomDocumentSave(file, domDoc))
        return;

    QDomNodeList layerElems = domDoc.documentElement()
                                    .elementsByTagName(QStringLiteral("Layer"));
    bool needSave = false;
    QRegExp rgx(group + ":\\w*,*|," + group + ":\\w*");
    for (int i = 0; i < layerElems.count(); ++i) {
        QDomElement lElem = layerElems.at(i).toElement();
        if (lElem.hasAttribute(QStringLiteral("variants"))) {
            QString val = lElem.attribute(QStringLiteral("variants"));
            if (rgx.indexIn(val) != -1) {
                val.replace(rgx, "");
                lElem.setAttribute(QStringLiteral("variants"), val);
                needSave = true;
            }
        }
    }

    if (needSave)
        StudioUtils::commitDomDocumentSave(file, domDoc);
}

bool ProjectFile::isVariantGroupUnique(const QString &group) const
{
    return !m_variantsDef.contains(group);
}

bool ProjectFile::isVariantTagUnique(const QString &group, const QString &tag) const
{
    if (!m_variantsDef.contains(group))
        return true;

    return !m_variantsDef[group].m_tags.contains(tag);
}

void ProjectFile::deleteVariantTag(const QString &group, const QString &tag)
{
    CDoc *doc = g_StudioApp.GetCore()->GetDoc();
    QDomDocument domDoc;
    QSaveFile file(getProjectFilePath());
    if (!StudioUtils::openDomDocumentSave(file, domDoc))
        return;

    // check if tag is in use in other presentations in the porject
    int inUseIdx = -1; // list of presentations that has the tag in use
    QDomNodeList presElems = domDoc.documentElement()
                                   .firstChildElement(QStringLiteral("assets"))
                                   .elementsByTagName(QStringLiteral("presentation"));
    for (int i = 0; i < presElems.count(); ++i) {
        QString pPath = m_fileInfo.path() + QLatin1Char('/')
                + presElems.at(i).toElement().attribute(QStringLiteral("src"));
        if (pPath != doc->GetDocumentPath()
                && tagExistsInUip(pPath, group, tag)) {
            inUseIdx = i;
            break;
        }
    }

    if (inUseIdx != -1) {
        QMessageBox box;
        box.setWindowTitle(tr("Tag in use"));
        box.setText(tr("The tag '%1' is in use in another presentation, are you sure you want to"
                       " delete it?").arg(tag));
        box.setIcon(QMessageBox::Warning);
        box.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
        box.setButtonText(QMessageBox::Yes, QStringLiteral("Delete"));
        switch (box.exec()) {
        case QMessageBox::Yes:
            // delete the tag from all uips that use it
            for (int i = inUseIdx; i < presElems.count(); ++i) {
                QString pPath = m_fileInfo.path() + QLatin1Char('/')
                        + presElems.at(i).toElement().attribute(QStringLiteral("src"));
                if (pPath != doc->GetDocumentPath())
                    deleteTagFromUip(pPath, group, tag);
            }
            break;

        default:
            // abort deletion
            return;
        }
    }

    // delete the tag from current doc, if exists
    deleteTagFromUip(doc->GetDocumentPath(), group, tag);

    QDomNodeList groupsElems = domDoc.documentElement()
                                     .firstChildElement(QStringLiteral("variants"))
                                     .elementsByTagName(QStringLiteral("variantgroup"));

    // delete the tag from the property (if set)
    const auto propertySystem = doc->GetStudioSystem()->GetPropertySystem();
    const auto bridge = doc->GetStudioSystem()->GetClientDataModelBridge();
    const auto layers = doc->getLayers();
    auto property = bridge->GetLayer().m_variants;
    for (auto layer : layers) {
        qt3dsdm::SValue sValue;
        if (propertySystem->GetInstancePropertyValue(layer, property, sValue)) {
            QString propVal = QString::fromWCharArray(qt3dsdm::get<qt3dsdm::TDataStrPtr>(sValue)
                                                      ->GetData());
            if (propVal.contains(QStringLiteral("%1:%2").arg(group).arg(tag))) {
                // property has the deleted tag, need to update it, else the deleted tag will be
                // saved in the uip if the user saves the presentation.
                QRegExp rgx(QStringLiteral("%1:%2,*|,%1:%2").arg(group).arg(tag));
                propVal.replace(rgx, {});
                qt3dsdm::SValue sVal = std::make_shared<qt3dsdm::CDataStr>(
                                       Q3DStudio::CString::fromQString(propVal));
                propertySystem->SetInstancePropertyValue(layer, property, sVal);
            }
        }
    }

    // update and save the uia
    bool deleted = false;
     for (int i = 0; i < groupsElems.count(); ++i) {
        QDomElement gElem = groupsElems.at(i).toElement();
        if (gElem.attribute(QStringLiteral("id")) == group) {
            QDomNodeList tagsElems = gElem.childNodes();
            for (int j = 0; j < tagsElems.count(); ++j) {
                QDomElement tElem = tagsElems.at(j).toElement();
                if (tElem.attribute(QStringLiteral("id")) == tag) {
                    gElem.removeChild(tElem);
                    StudioUtils::commitDomDocumentSave(file, domDoc);
                    deleted = true;
                    break;
                }
            }
            if (deleted)
                break;
        }
    }

    // update m_variantsDef
     m_variantsDef[group].m_tags.removeOne(tag);
}