summaryrefslogtreecommitdiffstats
path: root/src/Authoring/Studio/Application/ProjectFile.cpp
blob: ecf5a065bc6f5bd2d180a6168784c04df52beb88 (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
/****************************************************************************
**
** 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>

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;
}