summaryrefslogtreecommitdiffstats
path: root/src/Authoring/Studio/Application/PresentationFile.cpp
blob: 3079447143b52bcd4e10ceb284e175d6ce9a6c03 (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
/****************************************************************************
**
** 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 "PresentationFile.h"
#include "ProjectFile.h"
#include "Dialogs.h"
#include "StudioApp.h"
#include "Core.h"
#include "Doc.h"
#include "StudioUtils.h"
#include "IDocumentReader.h"
#include <QtCore/qfile.h>
#include <QtCore/qsavefile.h>
#include <QtXml/qdom.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qdiriterator.h>
#include <QtCore/qxmlstream.h>
#include <QtCore/qlist.h>

// This class provides utility static methods for working with presentation files (.uip). Old uip
// functionality should be gradually moved here whenever feasible.

// static
QSize PresentationFile::readSize(const QString &uipPath)
{
    QFile file(uipPath);
    file.open(QFile::Text | QFile::ReadOnly);
    if (!file.isOpen()) {
        qWarning() << file.errorString();
        return QSize();
    }

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

    while (reader.readNextStartElement()) {
        if (reader.name() == QLatin1String("ProjectSettings")) {
            const auto attrs = reader.attributes();
            return QSize(attrs.value(QLatin1String("presentationWidth")).toInt(),
                         attrs.value(QLatin1String("presentationHeight")).toInt());
        }
    }

    return QSize();
}

/**
 * Find all occurrences of a presentation Id in a .uip file and replace them with a new value
 *
 * @param uipPath presentation file path
 * @param oldId the presentation Id to find
 * @param newId the presentation Id to replace
 */
// static
void PresentationFile::updatePresentationId(const QString &uipPath, const QString &oldId,
                                            const QString &newId)
{
    QDomDocument domDoc;
    QSaveFile file(uipPath);
    if (!StudioUtils::openDomDocumentSave(file, domDoc))
        return;

    QDomElement rootElem = domDoc.documentElement();
    QDomNodeList addNodes = rootElem.elementsByTagName(QStringLiteral("Add"));
    bool updated = false;

    if (!addNodes.isEmpty()) {
        for (int i = 0; i < addNodes.length(); ++i) {
            QDomElement elem = addNodes.at(i).toElement();
            if (elem.attribute(QStringLiteral("sourcepath")) == oldId) {
                elem.setAttribute(QStringLiteral("sourcepath"), newId);
                updated = true;
            }
            if (elem.attribute(QStringLiteral("subpresentation")) == oldId) {
                elem.setAttribute(QStringLiteral("subpresentation"), newId);
                updated = true;
            }
        }
    }

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

/**
 * Find the project file path matching the given presentation file path
 *
 * @param uipPath presentation file path
 * @return project file absolute path
 */
// static
QString PresentationFile::findProjectFile(const QString &uipPath)
{
    QFileInfo fi(uipPath);

    // first check if there is a uia in the same folder as the uip with the same name
    QString uiaPath = fi.dir().absoluteFilePath(fi.completeBaseName() + QStringLiteral(".uia"));
    if (QFile::exists(uiaPath))
        return uiaPath;

    // next search for a uia starting from uip folder and going up, the first found 1 is assumed
    // to be the project file
    QDir currDir = fi.dir();
    const int MAX_SEARCH_DEPTH = 3; // scan up to 3 levels up (for performance reasons)
    int searchDepth = 0;
    do {
        QDirIterator di(currDir.path(), QDir::NoDotAndDotDot | QDir::Files);
        while (di.hasNext()) {
            QFileInfo fi2 = di.next();
            if (fi2.suffix() == QLatin1String("uia"))
                return fi2.filePath();
        }
        ++searchDepth;
    } while (searchDepth < MAX_SEARCH_DEPTH && currDir.cdUp());

    return {};
}

// get all available child assets source paths (materials, images, effects, etc)
// static
void PresentationFile::getSourcePaths(const QFileInfo &uipSrc, const QFileInfo &uipTarget,
                                      QHash<QString, QString> &outPathMap,
                                      QString &outProjPathSrc,
                                      QHash<QString, QString> &outPresentationNodes)
{
    QDomDocument domDoc;
    if (!StudioUtils::readFileToDomDocument(uipTarget.filePath(), domDoc))
        return;

    QVector<SubPresentationRecord> subpresentations;
    QString uiaPath = findProjectFile(uipSrc.filePath());
    if (!uiaPath.isEmpty()) {
        outProjPathSrc = QFileInfo(uiaPath).path();
        QString uipPathRelative = QFileInfo(uiaPath).dir().relativeFilePath(uipSrc.filePath());
        ProjectFile::getPresentations(uiaPath, subpresentations, uipPathRelative);
    }

    // Map to cache effect and material properties during the presentation file parsing,
    // as we don't yet know which ones are actually assets.
    // Key: Material/effect class id
    // Value: Set of material/effect properties
    QHash<QString, QSet<QString>> matEffPropertyMap;

    // search <Classes>
    QDomElement classesElem = domDoc.documentElement().firstChild()
            .firstChildElement(QStringLiteral("Classes"));
    for (QDomElement p = classesElem.firstChild().toElement(); !p.isNull();
        p = p.nextSibling().toElement()) {
        const QString sourcepath = p.attribute(QStringLiteral("sourcepath"));
        if (!sourcepath.isEmpty() && !outPathMap.contains(sourcepath)) {
            outPathMap.insert(sourcepath, {});

            QFileInfo fi(sourcepath);
            QByteArray ext = fi.suffix().toLatin1();

            // if material or effect, find and add their dependents
            if (CDialogs::IsMaterialFileExtension(ext.data()) ||
                CDialogs::IsEffectFileExtension(ext.data())) {
                QSet<QString> propertySet;
                g_StudioApp.GetCore()->GetDoc()->GetDocumentReader()
                    .ParseSourcePathsOutOfEffectFile(
                            uipSrc.path() + QStringLiteral("/") + sourcepath,
                            outProjPathSrc, outPathMap, propertySet);
                matEffPropertyMap.insert(QStringLiteral("#") + p.attribute(QStringLiteral("id")),
                                         propertySet);
            }
        }
    }

    // mesh files for group imports, materials, and effects are found under <Graph>
    QDomElement graphElement = domDoc.documentElement().firstChild()
            .firstChildElement(QStringLiteral("Graph"));

    QDomNodeList modelElems = graphElement.elementsByTagName(QStringLiteral("Model"));
    for (int i = 0; i < modelElems.count(); ++i) {
        QDomElement elem = modelElems.at(i).toElement();
        const QString sourcePath = elem.attribute(QStringLiteral("sourcepath"));
        if (!sourcePath.isEmpty()) {
            QFileInfo fi(sourcePath);
            QByteArray ext = fi.suffix().toLatin1();
            if (CDialogs::isMeshFileExtension(ext.data())) {
                if (!outPathMap.contains(sourcePath))
                    outPathMap.insert(sourcePath, {});
                continue;
            }
        }
    }

    // find material and effect files instance ids
    QHash<QString, QString> matEffClassIdMap;
    auto parseMatEffIds = [&matEffClassIdMap](const QDomNodeList& nodes) {
        for (int i = 0; i < nodes.count(); ++i) {
            QDomElement elem = nodes.at(i).toElement();
            const QString classId = elem.attribute(QStringLiteral("class"));
            if (!classId.isEmpty()) {
                const QString id = elem.attribute(QStringLiteral("id"));
                matEffClassIdMap.insert(QStringLiteral("#") + id, classId);
            }
        }
    };

    parseMatEffIds(graphElement.elementsByTagName(QStringLiteral("Effect")));
    parseMatEffIds(graphElement.elementsByTagName(QStringLiteral("CustomMaterial")));

    // search <Logic> -> <State> -> <Add>
    QDomNodeList addElems = domDoc.documentElement().firstChild()
            .firstChildElement(QStringLiteral("Logic"))
            .elementsByTagName(QStringLiteral("Add"));

    for (int i = 0; i < addElems.count(); ++i) {
        QDomElement elem = addElems.at(i).toElement();
        const QString sourcePath = elem.attribute(QStringLiteral("sourcepath"));
        if (!sourcePath.isEmpty()) {
            QFileInfo fi(sourcePath);
            QByteArray ext = fi.suffix().toLatin1();
            // supported types:
            // images, custom mesh files for basic objects, import files, materialdef files
            if (CDialogs::IsImageFileExtension(ext.data())
                    || CDialogs::isMeshFileExtension(ext.data())
                    || CDialogs::isImportFileExtension(ext.data())
                    || CDialogs::IsMaterialFileExtension(ext.data())) {
                if (!outPathMap.contains(sourcePath))
                    outPathMap.insert(sourcePath, {});
            } else {
                // add layer subpresentations paths
                auto *sp = std::find_if(subpresentations.begin(), subpresentations.end(),
                                       [&sourcePath](const SubPresentationRecord &spr) -> bool {
                                           return spr.m_id == sourcePath;
                                       });
                if (sp != subpresentations.end()) { // has a subpresentation
                    QString spPath = sp->m_argsOrSrc;
                    // set as root path (if it is not root nor relative) to make sure importing
                    // works correctly
                    if (!spPath.startsWith(QLatin1String("../"))
                        && !spPath.startsWith(QLatin1String("./"))) {
                        spPath.prepend(QLatin1String("./"));
                    }

                    if (!outPathMap.contains(spPath)) {
                        outPathMap.insert(spPath, {});
                        outPresentationNodes.insert(sp->m_argsOrSrc, sp->m_id);
                    }
                }
            }
        }

        // add texture subpresentations paths
        QString subpresentation = elem.attribute(QStringLiteral("subpresentation"));
        if (!subpresentation.isEmpty()) {
            auto *sp = std::find_if(subpresentations.begin(), subpresentations.end(),
                                   [&subpresentation](const SubPresentationRecord &spr) -> bool {
                                       return spr.m_id == subpresentation;
                                   });
            if (sp != subpresentations.end()) { // has a subpresentation
                QString spPath = sp->m_argsOrSrc;
                // set as root path (if it is not root nor relative) to make sure importing works
                // correctly.
                if (!spPath.startsWith(QLatin1String("../"))
                    && !spPath.startsWith(QLatin1String("./"))) {
                    spPath.prepend(QLatin1String("./"));
                }

                if (!outPathMap.contains(spPath)) {
                    outPathMap.insert(spPath, {});
                    outPresentationNodes.insert(sp->m_argsOrSrc, sp->m_id);
                }
            }
        }

        // add fonts paths
        QString font = elem.attribute(QStringLiteral("font"));
        if (!font.isEmpty()) {
            // the .uip file only shows the font name, we search for the font file in the current
            // directory plus the 'fonts' directory at the same level or 1 level up.

            const QString TTF_EXT = QStringLiteral(".ttf"); // TODO: should we also consider .otf?
            const QString slashUipPath = uipSrc.path() + QLatin1Char('/');

            // this is the most probable place so lets search it first
            QString fontPath = QStringLiteral("../fonts/") + font + TTF_EXT;
            QFileInfo absFontPath(slashUipPath + fontPath);
            if (absFontPath.exists()) {
                if (!outPathMap.contains(fontPath))
                    outPathMap.insert(fontPath, absFontPath.absoluteFilePath());
            } else {
                fontPath = font + TTF_EXT;
                absFontPath = QFileInfo(slashUipPath + fontPath);
                if (absFontPath.exists()) {
                    if (!outPathMap.contains(fontPath))
                        outPathMap.insert(fontPath, absFontPath.absoluteFilePath());
                } else {
                    fontPath = QStringLiteral("fonts/") + font + TTF_EXT;
                    absFontPath = QFileInfo(slashUipPath + fontPath);
                    if (absFontPath.exists()) {
                        if (!outPathMap.contains(fontPath))
                            outPathMap.insert(fontPath, absFontPath.absoluteFilePath());
                    }
                }
            }
        }

        // add custom material/effect assets
        const QString ref = elem.attribute(QStringLiteral("ref"));
        const QString classId = matEffClassIdMap.value(ref, {});
        if (!classId.isEmpty()) {
            const QSet<QString> textureProps = matEffPropertyMap.value(classId, {});
            for (auto &prop : textureProps) {
                QString texturePath = elem.attribute(prop);
                if (!texturePath.isEmpty()) {
                    // Typically these paths have ./ prepended even though they are relative to uip
                    // Remove it as ./ at start interpreted as relative to project file
                    if (texturePath.startsWith(QLatin1String("./")))
                        texturePath = texturePath.mid(2);
                    QFileInfo absTexPath(uipSrc.path() + QLatin1Char('/') + texturePath);
                    if (absTexPath.exists() && !outPathMap.contains(texturePath))
                        outPathMap.insert(texturePath, absTexPath.absoluteFilePath());
                }
            }
        }
    }
}

/**
 * Find datainput use in subpresentation
 *
 * @param subpresentation subpresentation
 * @param outmap returned list of datainput - property name pairs
 */
// static
bool PresentationFile::getDataInputBindings(const SubPresentationRecord &subpresentation,
                                            QMultiMap<QString, QPair<QString, QString>> &outmap)
{
    QList<QString> ctrldPropList;

    QString spPath(g_StudioApp.getRenderableAbsolutePath(subpresentation.m_id));

    QDomDocument domDoc;
    if (!StudioUtils::readFileToDomDocument(spPath, domDoc))
        return false;

    // search <Graph>
    QDomElement graphElem = domDoc.documentElement().firstChild()
            .firstChildElement(QStringLiteral("Graph"));
    for (QDomElement p = graphElem.firstChild().toElement(); !p.isNull();
         p = p.nextSibling().toElement()) {
        QString ctrldPropStr = p.attribute(QStringLiteral("controlledproperty"));
        if (!ctrldPropStr.isEmpty())
            ctrldPropList.append(ctrldPropStr);
    }
    // Search Logic - State - Add
    QDomNodeList addElems = domDoc.documentElement().firstChild()
            .firstChildElement(QStringLiteral("Logic"))
            .elementsByTagName(QStringLiteral("Add"));

    for (int i = 0; i < addElems.count(); ++i) {
        QDomElement elem = addElems.at(i).toElement();
        QString ctrldPropStr = elem.attribute(QStringLiteral("controlledproperty"));
        if (!ctrldPropStr.isEmpty())
            ctrldPropList.append(ctrldPropStr);
    }

    for (auto di : qAsConst(ctrldPropList)) {
        QStringList split = di.split(QLatin1String(" "));
        for (int i = 0; i < split.size(); i += 2) {
            QString diName = split[i];
            // Datainput names indicated with prefix "$", remove
            // if found.
            if (diName.startsWith(QLatin1String("$")))
                diName = diName.mid(1, diName.size() - 1);
            QString propName = split[i + 1];
            // We should find the datainput from the global datainput list
            // parsed out from UIA file, but check just in case and do not insert
            // if not found.
            if (g_StudioApp.m_dataInputDialogItems.contains(diName)) {
                outmap.insert(subpresentation.m_id, QPair<QString, QString>(diName, propName));
            } else {
                qWarning() << "Subpresentation" << subpresentation.m_id
                           << "is using datainput" << diName << "that is "
                              "not found from the current UIA file";
            }
        }
    }
    return true;
}