aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmlprojectmanager/qmlproject.cpp
blob: fe7542e8cbed95bd9679e4dea7f2f6a6b88a1617 (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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/

#include "qmlproject.h"

#include "fileformat/qmlprojectfileformat.h"
#include "fileformat/qmlprojectitem.h"
#include "qmlprojectrunconfiguration.h"
#include "qmlprojectconstants.h"
#include "qmlprojectmanagerconstants.h"
#include "qmlprojectnodes.h"

#include <coreplugin/documentmanager.h>
#include <coreplugin/editormanager/documentmodel.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>

#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/target.h>

#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtsupportconstants.h>

#include <qmljs/qmljsmodelmanagerinterface.h>

#include <texteditor/textdocument.h>

#include <utils/algorithm.h>

#include <QDebug>
#include <QRegularExpression>
#include <QTextCodec>
#include <QLoggingCategory>

using namespace Core;
using namespace ProjectExplorer;
using namespace QmlProjectManager::Internal;

namespace {
Q_LOGGING_CATEGORY(infoLogger, "QmlProjectManager.QmlBuildSystem", QtInfoMsg)
}

namespace QmlProjectManager {

QmlProject::QmlProject(const Utils::FilePath &fileName)
    : Project(QString::fromLatin1(Constants::QMLPROJECT_MIMETYPE), fileName)
{
    setId(QmlProjectManager::Constants::QML_PROJECT_ID);
    setProjectLanguages(Context(ProjectExplorer::Constants::QMLJS_LANGUAGE_ID));
    setDisplayName(fileName.toFileInfo().completeBaseName());

    setNeedsBuildConfigurations(false);
    setBuildSystemCreator([](Target *t) { return new QmlBuildSystem(t); });
}

QmlBuildSystem::QmlBuildSystem(Target *target)
    : BuildSystem(target)
{
    const QString normalized
            = Utils::FileUtils::normalizePathName(target->project()
                      ->projectFilePath().toFileInfo().canonicalFilePath());
    m_canonicalProjectDir = Utils::FilePath::fromString(normalized).parentDir();

    connect(target->project(), &Project::projectFileIsDirty,
            this, &QmlBuildSystem::refreshProjectFile);

    // refresh first - project information is used e.g. to decide the default RC's
    refresh(Everything);

// FIXME: Check. Probably bogus after the BuildSystem move.
//    // addedTarget calls updateEnabled on the runconfigurations
//    // which needs to happen after refresh
//    foreach (Target *t, targets())
//        addedTarget(t);

    connect(target->project(), &Project::activeTargetChanged,
            this, &QmlBuildSystem::onActiveTargetChanged);
    updateDeploymentData();
}

QmlBuildSystem::~QmlBuildSystem()
{
    delete m_projectItem.data();
}

void QmlBuildSystem::triggerParsing()
{
    refresh(Everything);
}

void QmlBuildSystem::onActiveTargetChanged(Target *)
{
    // make sure e.g. the default qml imports are adapted
    refresh(Configuration);
}

void QmlBuildSystem::onKitChanged()
{
    // make sure e.g. the default qml imports are adapted
    refresh(Configuration);
}

Utils::FilePath QmlBuildSystem::canonicalProjectDir() const
{
    return m_canonicalProjectDir;
}

void QmlBuildSystem::parseProject(RefreshOptions options)
{
    if (options & Files) {
        if (options & ProjectFile)
            delete m_projectItem.data();
        if (!m_projectItem) {
              QString errorMessage;
              m_projectItem = QmlProjectFileFormat::parseProjectFile(projectFilePath(), &errorMessage);
              if (m_projectItem) {
                  connect(m_projectItem.data(), &QmlProjectItem::qmlFilesChanged,
                          this, &QmlBuildSystem::refreshFiles);

              } else {
                  MessageManager::write(tr("Error while loading project file %1.")
                                        .arg(projectFilePath().toUserOutput()),
                                        MessageManager::NoModeSwitch);
                  MessageManager::write(errorMessage);
              }
        }
        if (m_projectItem) {
            m_projectItem.data()->setSourceDirectory(canonicalProjectDir().toString());
            if (m_projectItem->targetDirectory().isEmpty())
                m_projectItem->setTargetDirectory(canonicalProjectDir().toString());

            if (auto modelManager = QmlJS::ModelManagerInterface::instance())
                modelManager->updateSourceFiles(m_projectItem.data()->files(), true);

            QString mainFilePath = m_projectItem.data()->mainFile();
            if (!mainFilePath.isEmpty()) {
                mainFilePath
                        = QDir(canonicalProjectDir().toString()).absoluteFilePath(mainFilePath);
                Utils::FileReader reader;
                QString errorMessage;
                if (!reader.fetch(mainFilePath, &errorMessage)) {
                    MessageManager::write(tr("Warning while loading project file %1.")
                                          .arg(projectFilePath().toUserOutput()));
                    MessageManager::write(errorMessage);
                }
            }
        }
        generateProjectTree();
    }

    if (options & Configuration) {
        // update configuration
    }
}

void QmlBuildSystem::refresh(RefreshOptions options)
{
    ParseGuard guard = guardParsingRun();
    parseProject(options);

    if (options & Files)
        generateProjectTree();

    auto modelManager = QmlJS::ModelManagerInterface::instance();
    if (!modelManager)
        return;

    QmlJS::ModelManagerInterface::ProjectInfo projectInfo =
            modelManager->defaultProjectInfoForProject(project());
    foreach (const QString &searchPath, makeAbsolute(canonicalProjectDir(), customImportPaths()))
        projectInfo.importPaths.maybeInsert(Utils::FilePath::fromString(searchPath),
                                            QmlJS::Dialect::Qml);

    modelManager->updateProjectInfo(projectInfo, project());

    guard.markAsSuccess();
}

QString QmlBuildSystem::mainFile() const
{
    if (m_projectItem)
        return m_projectItem.data()->mainFile();
    return QString();
}

bool QmlBuildSystem::qtForMCUs() const
{
    if (m_projectItem)
        return m_projectItem.data()->qtForMCUs();
    return false;
}

void QmlBuildSystem::setMainFile(const QString &mainFilePath)
{
    if (m_projectItem)
        m_projectItem.data()->setMainFile(mainFilePath);
}

Utils::FilePath QmlBuildSystem::targetDirectory() const
{
    if (DeviceTypeKitAspect::deviceTypeId(target()->kit())
            == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE)
        return canonicalProjectDir();

    return m_projectItem ? Utils::FilePath::fromString(m_projectItem->targetDirectory())
                         : Utils::FilePath();
}

Utils::FilePath QmlBuildSystem::targetFile(const Utils::FilePath &sourceFile) const
{
    const QDir sourceDir(m_projectItem ? m_projectItem->sourceDirectory()
                                       : canonicalProjectDir().toString());
    const QDir targetDir(targetDirectory().toString());
    const QString relative = sourceDir.relativeFilePath(sourceFile.toString());
    return Utils::FilePath::fromString(QDir::cleanPath(targetDir.absoluteFilePath(relative)));
}

Utils::EnvironmentItems QmlBuildSystem::environment() const
{
    if (m_projectItem)
        return m_projectItem.data()->environment();
    return {};
}

QStringList QmlBuildSystem::customImportPaths() const
{
    if (m_projectItem)
        return m_projectItem.data()->importPaths();
    return {};
}

QStringList QmlBuildSystem::customFileSelectors() const
{
    if (m_projectItem)
        return m_projectItem.data()->fileSelectors();
    return {};
}

void QmlBuildSystem::refreshProjectFile()
{
    refresh(QmlBuildSystem::ProjectFile | Files);
}

QStringList QmlBuildSystem::makeAbsolute(const Utils::FilePath &path, const QStringList &relativePaths)
{
    if (path.isEmpty())
        return relativePaths;

    const QDir baseDir(path.toString());
    return Utils::transform(relativePaths, [&baseDir](const QString &path) {
        return QDir::cleanPath(baseDir.absoluteFilePath(path));
    });
}

void QmlBuildSystem::refreshFiles(const QSet<QString> &/*added*/, const QSet<QString> &removed)
{
    if (m_blockFilesUpdate) {
        qCDebug(infoLogger) << "Auto files refresh blocked.";
        return;
    }
    refresh(Files);
    if (!removed.isEmpty()) {
        if (auto modelManager = QmlJS::ModelManagerInterface::instance())
            modelManager->removeFiles(Utils::toList(removed));
    }
    refreshTargetDirectory();
}

void QmlBuildSystem::refreshTargetDirectory()
{
    updateDeploymentData();
}

Tasks QmlProject::projectIssues(const Kit *k) const
{
    Tasks result = Project::projectIssues(k);

    const QtSupport::BaseQtVersion *version = QtSupport::QtKitAspect::qtVersion(k);
    if (!version)
        result.append(createProjectTask(Task::TaskType::Error, tr("No Qt version set in kit.")));

    IDevice::ConstPtr dev = DeviceKitAspect::device(k);
    if (dev.isNull())
        result.append(createProjectTask(Task::TaskType::Error, tr("Kit has no device.")));

    if (version && version->qtVersion() < QtSupport::QtVersionNumber(5, 0, 0))
        result.append(createProjectTask(Task::TaskType::Error, tr("Qt version is too old.")));

    if (dev.isNull() || !version)
        return result; // No need to check deeper than this

    if (dev->type() == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE) {
        if (version->type() == QtSupport::Constants::DESKTOPQT) {
            if (version->qmlsceneCommand().isEmpty()) {
                result.append(createProjectTask(Task::TaskType::Error,
                                                tr("Qt version has no qmlscene command.")));
            }
        } else {
            // Non-desktop Qt on a desktop device? We don't support that.
            result.append(createProjectTask(Task::TaskType::Error,
                                            tr("Non-desktop Qt is used with a desktop device.")));
        }
    } else {
        // If not a desktop device, don't check the Qt version for qmlscene.
        // The device is responsible for providing it and we assume qmlscene can be found
        // in $PATH if it's not explicitly given.
    }

    return result;
}

Project::RestoreResult QmlProject::fromMap(const QVariantMap &map, QString *errorMessage)
{
    RestoreResult result = Project::fromMap(map, errorMessage);
    if (result != RestoreResult::Ok)
        return result;

    if (!activeTarget()) {
        // find a kit that matches prerequisites (prefer default one)
        const QList<Kit*> kits = Utils::filtered(KitManager::kits(), [this](const Kit *k) {
            return !containsType(projectIssues(k), Task::TaskType::Error);
        });

        if (!kits.isEmpty()) {
            if (kits.contains(KitManager::defaultKit()))
                addTargetForDefaultKit();
            else
                addTargetForKit(kits.first());
        }
    }

    return RestoreResult::Ok;
}

ProjectExplorer::DeploymentKnowledge QmlProject::deploymentKnowledge() const
{
    return DeploymentKnowledge::Perfect;
}

void QmlBuildSystem::generateProjectTree()
{
    if (!m_projectItem)
        return;

    auto newRoot = std::make_unique<QmlProjectNode>(project());

    for (const QString &f : m_projectItem.data()->files()) {
        const Utils::FilePath fileName = Utils::FilePath::fromString(f);
        const FileType fileType = (fileName == projectFilePath())
                ? FileType::Project : FileNode::fileTypeForFileName(fileName);
        newRoot->addNestedNode(std::make_unique<FileNode>(fileName, fileType));
    }
    newRoot->addNestedNode(std::make_unique<FileNode>(projectFilePath(), FileType::Project));

    setRootProjectNode(std::move(newRoot));
    refreshTargetDirectory();
}

void QmlBuildSystem::updateDeploymentData()
{
    if (!m_projectItem)
        return;

    if (DeviceTypeKitAspect::deviceTypeId(target()->kit())
            == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE) {
        return;
    }

    ProjectExplorer::DeploymentData deploymentData;
    for (const QString &file : m_projectItem->files()) {
        deploymentData.addFile(
                    file,
                    targetFile(Utils::FilePath::fromString(file)).parentDir().toString());
    }

    setDeploymentData(deploymentData);
}

QVariant QmlBuildSystem::additionalData(Id id) const
{
    if (id == Constants::customFileSelectorsData)
        return customFileSelectors();
    if (id == Constants::customForceFreeTypeData)
        return forceFreeType();
    if (id == Constants::customQtForMCUs)
        return qtForMCUs();
    return {};
}

bool QmlBuildSystem::supportsAction(Node *context, ProjectAction action, const Node *node) const
{
    if (dynamic_cast<QmlProjectNode *>(context)) {
        if (action == AddNewFile || action == EraseFile)
            return true;
        QTC_ASSERT(node, return false);

        if (action == Rename && node->asFileNode()) {
            const FileNode *fileNode = node->asFileNode();
            QTC_ASSERT(fileNode, return false);
            return fileNode->fileType() != FileType::Project;
        }

        return false;
    }

    return BuildSystem::supportsAction(context, action, node);
}

QmlProject *QmlBuildSystem::qmlProject() const
{
    return static_cast<QmlProject *>(BuildSystem::project());
}

bool QmlBuildSystem::forceFreeType() const
{
    if (m_projectItem)
        return m_projectItem.data()->forceFreeType();
    return false;
}

bool QmlBuildSystem::addFiles(Node *context, const QStringList &filePaths, QStringList *)
{
    if (!dynamic_cast<QmlProjectNode *>(context))
        return false;

    QStringList toAdd;
    foreach (const QString &filePath, filePaths) {
        if (!m_projectItem.data()->matchesFile(filePath))
            toAdd << filePaths;
    }
    return toAdd.isEmpty();
}

bool QmlBuildSystem::deleteFiles(Node *context, const QStringList &filePaths)
{
    if (dynamic_cast<QmlProjectNode *>(context))
        return true;

    return BuildSystem::deleteFiles(context, filePaths);
}

bool QmlBuildSystem::renameFile(Node * context, const QString &filePath, const QString &newFilePath)
{
    if (dynamic_cast<QmlProjectNode *>(context)) {
        if (filePath.endsWith(mainFile())) {
            setMainFile(newFilePath);

            // make sure to change it also in the qmlproject file
            const QString qmlProjectFilePath = project()->projectFilePath().toString();
            Core::FileChangeBlocker fileChangeBlocker(qmlProjectFilePath);
            const QList<Core::IEditor *> editors = Core::DocumentModel::editorsForFilePath(qmlProjectFilePath);
            TextEditor::TextDocument *document = nullptr;
            if (!editors.isEmpty()) {
                document = qobject_cast<TextEditor::TextDocument*>(editors.first()->document());
                if (document && document->isModified())
                    if (!Core::DocumentManager::saveDocument(document))
                        return false;
            }

            QString fileContent;
            QString error;
            Utils::TextFileFormat textFileFormat;
            const QTextCodec *codec = QTextCodec::codecForName("UTF-8"); // qml files are defined to be utf-8
            if (Utils::TextFileFormat::readFile(qmlProjectFilePath, codec, &fileContent, &textFileFormat, &error)
                    != Utils::TextFileFormat::ReadSuccess) {
                qWarning() << "Failed to read file" << qmlProjectFilePath << ":" << error;
            }

            // find the mainFile and do the file name with brackets in a capture group and mask the . with \.
            QString originalFileName = QFileInfo(filePath).fileName();
            originalFileName.replace(".", "\\.");
            const QRegularExpression expression(QString("mainFile:\\s*\"(%1)\"").arg(originalFileName));
            const QRegularExpressionMatch match = expression.match(fileContent);

            fileContent.replace(match.capturedStart(1), match.capturedLength(1), QFileInfo(newFilePath).fileName());

            if (!textFileFormat.writeFile(qmlProjectFilePath, fileContent, &error))
                qWarning() << "Failed to write file" << qmlProjectFilePath << ":" << error;

            refresh(Everything);
        }

        return true;
    }

    return BuildSystem::renameFile(context, filePath, newFilePath);
}

} // namespace QmlProjectManager