summaryrefslogtreecommitdiffstats
path: root/src/Authoring/Studio/Application/ProjectFile.cpp
blob: 13a797a44261766fabdabf299cdd9ab6c193a5af (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
/****************************************************************************
**
** 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 "Core.h"
#include "Doc.h"
#include "PresentationFile.h"
#include <QtCore/qdiriterator.h>
#include <QtXml/qdom.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(const QString &uipPath)
{
    QString uiaPath = PresentationFile::findProjectFile(uipPath);

    if (!uiaPath.isEmpty()) // uia found
        m_fileInfo.setFile(uiaPath);
    else
        throw ProjectFileNotFoundException();
}

/**
 * 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)
{
    // open the uia file
    QFile file(getProjectFilePath());
    file.open(QIODevice::ReadWrite);
    QDomDocument doc;
    doc.setContent(&file);

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

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

    QString relativePresentationPath = QDir(getProjectPath()).relativeFilePath(pPath);

    // 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) {
        QString presentationId = pId.isEmpty()
                ? ensureUniquePresentationId(QFileInfo(pPath).completeBaseName()) : pId;

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

        file.resize(0);
        file.write(doc.toByteArray(4));

        // add to m_subpresentations
        g_StudioApp.m_subpresentations.push_back(
                    SubPresentationRecord(QStringLiteral("presentation-qml"), presentationId,
                                          relativePresentationPath));
    }

    file.close();
}

// get the path (relative) to the first presentation in a uia file
QString ProjectFile::getFirstPresentationPath(const QString &uiaPath) const
{
    QFile file(uiaPath);
    file.open(QIODevice::ReadOnly);
    QDomDocument doc;
    doc.setContent(&file);
    file.close();

    QDomElement assetsElem = doc.documentElement().firstChildElement(QStringLiteral("assets"));
    if (!assetsElem.isNull()) {
        QDomElement firstPresentationElem =
                assetsElem.firstChildElement(QStringLiteral("presentation"));

        if (!firstPresentationElem.isNull())
            return firstPresentationElem.attribute(QStringLiteral("src"));
    }

    return {};
}

/**
 * Write a presentation id to the project file.
 *
 * This also update the Doc presentation Id if the src param is empty
 *
 * @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)
{
    CDoc *doc = g_StudioApp.GetCore()->GetDoc();
    QString theSrc = src.isEmpty() ? doc->getRelativePath() : src;
    QString theId = id.isEmpty() ? doc->getPresentationId() : id;

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

    QFile file(getProjectFilePath());
    file.open(QIODevice::ReadWrite);
    QDomDocument domDoc;
    domDoc.setContent(&file);

    QDomElement rootElem = domDoc.documentElement();
    QDomNodeList pNodes = rootElem.firstChildElement(QStringLiteral("assets")).childNodes();
    QString oldId;
    if (!pNodes.isEmpty()) {
        for (int i = 0; i < pNodes.length(); ++i) {
            QDomElement pElem = pNodes.at(i).toElement();
            if (pElem.nodeName().startsWith(QLatin1String("presentation"))) {
                if (pElem.attribute(QStringLiteral("src")) == theSrc) {
                    oldId = pElem.attribute(QStringLiteral("id"));
                    pElem.setAttribute(QStringLiteral("id"), theId);
                    break;
                }
            }
        }
    }

    // overwrite the uia file
    file.resize(0);
    file.write(domDoc.toByteArray(4));
    file.close();

    // update in-memory values
    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 changed presentation Id in all .uip files if in-use
    if (!oldId.isEmpty()) {
        for (int i = 0; i < pNodes.length(); ++i) {
            QDomElement pElem = pNodes.at(i).toElement();
            QString path = getProjectPath() + QStringLiteral("/")
                           + pElem.attribute(QStringLiteral("src"));
            PresentationFile::updatePresentationId(path, oldId, theId);
        }
    }
}

// set the doc PresentationId from the project file, this is called after a document is loaded
void ProjectFile::updateDocPresentationId()
{
    QFile file(getProjectFilePath());
    file.open(QIODevice::ReadOnly);
    QDomDocument doc;
    doc.setContent(&file);
    file.close();

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

    if (!assetsElem.isNull()) {
        QString relativeDocPath = QDir(getProjectPath()).relativeFilePath(
                    g_StudioApp.GetCore()->GetDoc()->GetDocumentPath().GetPath().toQString());

        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")) == relativeDocPath) {
                // current presentation node
                g_StudioApp.GetCore()->GetDoc()->setPresentationId(
                            p.attribute(QStringLiteral("id")));
                return;
            }
        }
    }
}

// get a presentationId from the project file, that match a given src attribute
QString ProjectFile::getPresentationId(const QString &src) const
{
    QFile file(getProjectFilePath());
    file.open(QFile::Text | QFile::ReadOnly);
    if (!file.isOpen()) {
        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();
            if (attrs.value(QLatin1String("src")) == src)
                return attrs.value(QLatin1String("id")).toString();
        }
    }

    return {};
}

// create the project .uia file
void ProjectFile::create(const QString &projectName,
                         const Q3DStudio::CFilePath &projectPath)
{
    QDomDocument doc;
    doc.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>"));

    QString uiaPath = projectPath.toQString() + QStringLiteral("/") + projectName
                      + QStringLiteral(".uia");

    QFile file(uiaPath);
    file.open(QIODevice::WriteOnly);
    file.resize(0);
    file.write(doc.toByteArray(4));
    file.close();

    m_fileInfo.setFile(uiaPath);
}

void ProjectFile::loadSubpresentationsAndDatainputs(
                                                QVector<SubPresentationRecord> &subpresentations,
                                                QMap<QString, CDataInputDialogItem *> &datainputs)
{
    subpresentations.clear();
    datainputs.clear();

    QFile file(getProjectFilePath());
    file.open(QIODevice::ReadOnly);
    QDomDocument doc;
    doc.setContent(&file);
    file.close();

    QDomElement assetsElem = doc.documentElement().firstChildElement(QStringLiteral("assets"));
    if (!assetsElem.isNull()) {
        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 if (p.nodeName() == QLatin1String("dataInput")) {
                CDataInputDialogItem *item = new CDataInputDialogItem();
                item->name = p.attribute(QStringLiteral("name"));
                QString type = p.attribute(QStringLiteral("type"));
                if (type == QLatin1String("Ranged Number")) {
                    item->type = EDataType::DataTypeRangedNumber;
                    item->minValue = p.attribute(QStringLiteral("min")).toFloat();
                    item->maxValue = p.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 = p.attribute(QStringLiteral("evaluator"));
                }
#endif
                datainputs.insert(item->name, item);
            }
        }
    }
}

/**
 * Write a presentation id to the project file.
 *
 * Check that a given presentation is unique
 *
 * @param id presentation Id
 * @param src source node to exclude from the check, if empty the current document node is used
 */
bool ProjectFile::isUniquePresentationId(const QString &id, const QString &src) const
{
    QFile file(getProjectFilePath());
    file.open(QIODevice::ReadOnly);
    QDomDocument doc;
    doc.setContent(&file);
    file.close();

    QDomElement assetsElem = doc.documentElement().firstChildElement(QStringLiteral("assets"));
    if (!assetsElem.isNull()) {
        QString relativePath = !src.isEmpty() ? src
                                              : g_StudioApp.GetCore()->GetDoc()->getRelativePath();
        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")) == id
                    && p.attribute(QStringLiteral("src")) != relativePath) {
                return false;
            }
        }
    }

    return true;
}

QString ProjectFile::ensureUniquePresentationId(const QString &id) const
{
    QFile file(getProjectFilePath());
    file.open(QIODevice::ReadOnly);
    QDomDocument doc;
    doc.setContent(&file);
    file.close();
    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
QString ProjectFile::getProjectPath() const
{
    return m_fileInfo.path();
}

// Get the path to the project's .uia file
QString ProjectFile::getProjectFilePath() const
{
    return m_fileInfo.filePath();
}

QString ProjectFile::getProjectName() const
{
    return m_fileInfo.completeBaseName();
}

/**
 * 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);
    file.open(QFile::Text | QFile::ReadOnly);
    if (!file.isOpen()) {
        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>
        }
    }
}

QString ProjectFile::getResolvedPathTo(const QString &path) const
{
    auto projectPath = QDir(getProjectPath()).absoluteFilePath(path);
    return QDir::cleanPath(projectPath);
}