aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmlprojectmanager/qmlprojectgen/qmlprojectgenerator.cpp
blob: 0270a290fdd980fcd14abce59bd468025ddeb301 (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
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "qmlprojectgenerator.h"
#include "../cmakegen/cmakewriter.h"
#include "../qmlprojectmanagertr.h"

#include <coreplugin/documentmanager.h>
#include <coreplugin/icore.h>

#include <QMessageBox>

using namespace Utils;

namespace QmlProjectManager {
namespace GenerateQmlProject {

bool QmlProjectFileGenerator::prepareForUiQmlFile(const FilePath &uiQmlFilePath)
{
    return prepare(selectTargetFile(uiQmlFilePath));
}

bool QmlProjectFileGenerator::prepare(const FilePath &targetDir)
{
    m_targetFile = targetDir.isEmpty() ? selectTargetFile() : targetDir;
    m_targetDir = m_targetFile.parentDir();

    return true;
}

const char QMLPROJECT_FILE_TEMPLATE_PATH[] = ":/projectfiletemplates/qmlproject.tpl";
const char FILE_QML[] = "*.qml";
const char FILE_JS[] = "*.js";
const char FILE_JPG[] = "*.jpg";
const char FILE_PNG[] = "*.png";
const char FILE_GIF[] = "*.gif";
const char FILE_MESH[] = "*.mesh";
const char BLOCKTITLE_QML[] = "QmlFiles";
const char BLOCKTITLE_IMAGE[] = "ImageFiles";
const char BLOCKTITLE_JS[] = "JavaScriptFiles";
const char BLOCK_CONTENTDIR[] = "\n    %1 {\n        directory: \"%2\"\n    }\n";
const char BLOCK_FILTEREDDIR[] = "\n    Files {\n        filter: \"%1\"\n        directory: \"%2\"\n    }\n";
const char BLOCK_DIRARRAY[] = "\n    %1: [ %2 ]\n";

bool QmlProjectFileGenerator::execute()
{
    static const QStringList filesQml = {FILE_QML};
    static const QStringList filesImage = {FILE_PNG, FILE_JPG, FILE_GIF};
    static const QStringList filesJs = {FILE_QML, FILE_JS};
    static const QStringList filesAsset = {FILE_MESH};

    if (m_targetFile.isEmpty() || !m_targetDir.isWritableDir())
        return false;

    const QString contentEntry = createContentDirEntries(BLOCKTITLE_QML, filesQml);
    const QString imageEntry = createContentDirEntries(BLOCKTITLE_IMAGE, filesImage);
    const QString jsEntry = createContentDirEntries(BLOCKTITLE_JS, filesJs);
    const QString assetEntry = createFilteredDirEntries(filesAsset);
    QStringList importDirs = findContentDirs(filesQml + filesAsset);
    importDirs.removeAll(".");
    importDirs.removeAll("content");
    const QString importPaths = createDirArrayEntry("importPaths", importDirs);

    const QString fileContent = GenerateCmake::CMakeWriter::readTemplate(QMLPROJECT_FILE_TEMPLATE_PATH)
            .arg(contentEntry, imageEntry, jsEntry, assetEntry, importPaths);

    QFile file(m_targetFile.toString());
    file.open(QIODevice::WriteOnly);
    if (!file.isOpen())
        return false;

    file.reset();
    file.write(fileContent.toUtf8());
    file.close();

    QMessageBox::information(Core::ICore::dialogParent(),
                             Tr::tr("Project File Generated"),
                             Tr::tr("File created:\n\n%1").arg(m_targetFile.toString()),
                             QMessageBox::Ok);

    return true;
}

const FilePath QmlProjectFileGenerator::targetDir() const
{
    return m_targetDir;
}

const FilePath QmlProjectFileGenerator::targetFile() const
{
    return m_targetFile;
}

bool QmlProjectFileGenerator::isStandardStructure(const FilePath &projectDir) const
{
    if (projectDir.pathAppended("content").isDir() &&
        projectDir.pathAppended("imports").isDir())
            return true;

    return false;
}

const QString QmlProjectFileGenerator::createContentDirEntries(const QString &containerName,
                                                               const QStringList &suffixes) const
{
    QString entries;

    const QStringList contentDirs = findContentDirs(suffixes);
    for (const QString &dir : contentDirs)
        entries.append(QString(BLOCK_CONTENTDIR).arg(containerName, dir));

    return entries;
}

const QString QmlProjectFileGenerator::createFilteredDirEntries(const QStringList &suffixes) const
{
    QString entries;
    const QString filterList = suffixes.join(';');

    const QStringList contentDirs = findContentDirs(suffixes);
    for (const QString &dir : contentDirs)
        entries.append(QString(BLOCK_FILTEREDDIR).arg(filterList, dir));

    return entries;
}

const QString QmlProjectFileGenerator::createDirArrayEntry(const QString &arrayName,
                                                           const QStringList &relativePaths) const
{
    if (relativePaths.isEmpty())
        return {};

    QStringList formattedDirs = relativePaths;
    for (QString &dir : formattedDirs)
        dir.append('"').prepend('"');

    return QString(BLOCK_DIRARRAY).arg(arrayName, formattedDirs.join(", "));
}

const FilePath QmlProjectFileGenerator::selectTargetFile(const FilePath &uiFilePath)
{
    FilePath suggestedDir;

    if (!uiFilePath.isEmpty())
        if (uiFilePath.parentDir().parentDir().exists())
            suggestedDir = uiFilePath.parentDir().parentDir();

    if (suggestedDir.isEmpty())
        suggestedDir = FilePath::fromString(QDir::homePath());

    FilePath targetFile;
    bool selectionCompleted = false;
    do {
        targetFile = Core::DocumentManager::getSaveFileNameWithExtension(
                                    Tr::tr("Select File Location"),
                                    suggestedDir,
                                    Tr::tr("Qt Design Studio Project Files (*.qmlproject)"));
        selectionCompleted = isDirAcceptable(targetFile.parentDir(), uiFilePath);
    } while (!selectionCompleted);

    return targetFile;
}

bool QmlProjectFileGenerator::isDirAcceptable(const FilePath &dir, const FilePath &uiFile)
{
    const FilePath uiFileParentDir = uiFile.parentDir();

    if (dir.isChildOf(uiFileParentDir)) {
        QMessageBox::warning(Core::ICore::dialogParent(),
                             Tr::tr("Invalid Directory"),
                             Tr::tr("Project file must be placed in a parent directory of the QML files."),
                             QMessageBox::Ok);
        return false;
    }

    if (uiFileParentDir.isChildOf(dir)) {
        const FilePath relativePath = uiFileParentDir.relativeChildPath(dir);
        QStringList components = relativePath.toString().split("/");
        if (components.size() > 2) {
            QMessageBox::StandardButton sel = QMessageBox::question(Core::ICore::dialogParent(),
                                                  Tr::tr("Problem"),
                                                  Tr::tr("Selected directory is far away from the QML file. This can cause unexpected results.\n\nAre you sure?"),
                                                  QMessageBox::Yes | QMessageBox::No);
            if (sel == QMessageBox::No)
                return false;
        }
    }

    return true;
}

const int TOO_FAR_AWAY = 4;
const QDir::Filters FILES_ONLY = QDir::Files;
const QDir::Filters DIRS_ONLY = QDir::Dirs|QDir::Readable|QDir::NoDotAndDotDot;

const FilePath QmlProjectFileGenerator::findInDirTree(const FilePath &dir, const QStringList &suffixes, int currentSearchDepth) const
{
    if (currentSearchDepth > TOO_FAR_AWAY)
        return {};

    currentSearchDepth++;

    const FilePaths files = dir.dirEntries({suffixes, FILES_ONLY});
    if (!files.isEmpty())
        return dir;

    FilePaths subdirs = dir.dirEntries(DIRS_ONLY);
    for (const FilePath &subdir : subdirs) {
        const FilePath result = findInDirTree(subdir, suffixes, currentSearchDepth);
        if (!result.isEmpty())
            return result;
    }

    return {};
}

const QStringList QmlProjectFileGenerator::findContentDirs(const QStringList &suffixes) const
{
    FilePaths results;

    if (!isStandardStructure(m_targetDir))
        if (!m_targetDir.dirEntries({suffixes, FILES_ONLY}).isEmpty())
            return {"."};

    const FilePaths dirs = m_targetDir.dirEntries(DIRS_ONLY);
    for (const FilePath &dir : dirs) {
        const FilePath result = findInDirTree(dir, suffixes);
        if (!result.isEmpty())
            results.append(result);
    }

    QStringList relativePaths;
    for (const FilePath &fullPath : results) {
        if (fullPath == m_targetDir)
            relativePaths.append(".");
        else
            relativePaths.append(fullPath.relativeChildPath(m_targetDir).toString().split('/').first());
    }

    return relativePaths;
}

} // GenerateQmlProject
} // QmlProjectManager