qbsproject.cpp 28.5 KB
Newer Older
Tobias Hunger's avatar
Tobias Hunger committed
1
2
/****************************************************************************
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
Tobias Hunger's avatar
Tobias Hunger committed
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
** Contact: http://www.qt-project.org/legal
**
** 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 Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "qbsproject.h"

#include "qbsbuildconfiguration.h"
33
#include "qbslogsink.h"
Tobias Hunger's avatar
Tobias Hunger committed
34
#include "qbsprojectfile.h"
35
#include "qbsprojectparser.h"
Tobias Hunger's avatar
Tobias Hunger committed
36
37
38
39
40
41
#include "qbsprojectmanagerconstants.h"
#include "qbsnodes.h"

#include <coreplugin/documentmanager.h>
#include <coreplugin/icontext.h>
#include <coreplugin/id.h>
42
43
44
#include <coreplugin/icore.h>
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/vcsmanager.h>
45
#include <coreplugin/messagemanager.h>
Tobias Hunger's avatar
Tobias Hunger committed
46
47
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/mimedatabase.h>
48
#include <cpptools/cppmodelmanagerinterface.h>
Tobias Hunger's avatar
Tobias Hunger committed
49
#include <projectexplorer/buildenvironmentwidget.h>
50
#include <projectexplorer/buildmanager.h>
51
52
#include <projectexplorer/buildtargetinfo.h>
#include <projectexplorer/deploymentdata.h>
Tobias Hunger's avatar
Tobias Hunger committed
53
54
55
56
#include <projectexplorer/kit.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
57
#include <projectexplorer/projectmacroexpander.h>
Tobias Hunger's avatar
Tobias Hunger committed
58
59
#include <projectexplorer/target.h>
#include <projectexplorer/taskhub.h>
60
#include <projectexplorer/toolchain.h>
61
#include <projectexplorer/headerpath.h>
Tobias Hunger's avatar
Tobias Hunger committed
62
#include <qtsupport/qtkitinformation.h>
Tobias Hunger's avatar
Tobias Hunger committed
63
#include <qtsupport/uicodemodelsupport.h>
64
#include <qmljstools/qmljsmodelmanager.h>
Tobias Hunger's avatar
Tobias Hunger committed
65
#include <qmljs/qmljsmodelmanagerinterface.h>
66
#include <utils/hostosinfo.h>
67
#include <utils/qtcassert.h>
Tobias Hunger's avatar
Tobias Hunger committed
68
69
70

#include <qbs.h>

71
72
#include <QCoreApplication>
#include <QDir>
Tobias Hunger's avatar
Tobias Hunger committed
73
#include <QFileInfo>
74
#include <QMessageBox>
75
#include <QVariantMap>
Tobias Hunger's avatar
Tobias Hunger committed
76

77
using namespace Core;
78
79
using namespace ProjectExplorer;
using namespace Utils;
80
81
82
83

namespace QbsProjectManager {
namespace Internal {

Tobias Hunger's avatar
Tobias Hunger committed
84
85
86
87
// --------------------------------------------------------------------
// Constants:
// --------------------------------------------------------------------

88
static const char CONFIG_CPP_MODULE[] = "cpp";
89
90
static const char CONFIG_CXXFLAGS[] = "cxxFlags";
static const char CONFIG_CFLAGS[] = "cFlags";
91
92
static const char CONFIG_DEFINES[] = "defines";
static const char CONFIG_INCLUDEPATHS[] = "includePaths";
93
static const char CONFIG_SYSTEM_INCLUDEPATHS[] = "systemIncludePaths";
94
static const char CONFIG_FRAMEWORKPATHS[] = "frameworkPaths";
95
static const char CONFIG_SYSTEM_FRAMEWORKPATHS[] = "systemFrameworkPaths";
96
static const char CONFIG_PRECOMPILEDHEADER[] = "precompiledHeader";
Tobias Hunger's avatar
Tobias Hunger committed
97
98
99
100
101
102
103
static const char CONFIGURATION_PATH[] = "<configuration>";

// --------------------------------------------------------------------
// QbsProject:
// --------------------------------------------------------------------

QbsProject::QbsProject(QbsManager *manager, const QString &fileName) :
104
105
106
    m_manager(manager),
    m_projectName(QFileInfo(fileName).completeBaseName()),
    m_fileName(fileName),
107
    m_rootProjectNode(0),
108
    m_qbsProjectParser(0),
Tobias Hunger's avatar
Tobias Hunger committed
109
    m_qbsUpdateFutureInterface(0),
110
    m_parsingScheduled(false),
111
    m_cancelStatus(CancelStatusNone),
Tobias Hunger's avatar
Tobias Hunger committed
112
113
    m_currentBc(0)
{
114
    m_parsingDelay.setInterval(1000); // delay parsing by 1s.
115

116
    setId(Constants::PROJECT_ID);
117
118
    setProjectContext(Context(Constants::PROJECT_ID));
    setProjectLanguages(Context(ProjectExplorer::Constants::LANG_CXX));
Tobias Hunger's avatar
Tobias Hunger committed
119
120
121
122
123

    connect(this, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
            this, SLOT(changeActiveTarget(ProjectExplorer::Target*)));
    connect(this, SIGNAL(addedTarget(ProjectExplorer::Target*)),
            this, SLOT(targetWasAdded(ProjectExplorer::Target*)));
124
125
    connect(this, SIGNAL(environmentChanged()), this, SLOT(delayParsing()));

126
    connect(&m_parsingDelay, SIGNAL(timeout()), this, SLOT(startParsing()));
Tobias Hunger's avatar
Tobias Hunger committed
127

128
    updateDocuments(QSet<QString>() << fileName);
129
130

    // NOTE: QbsProjectNode does not use this as a parent!
131
    m_rootProjectNode = new QbsRootProjectNode(this); // needs documents to be initialized!
Tobias Hunger's avatar
Tobias Hunger committed
132
133
134
135
136
}

QbsProject::~QbsProject()
{
    m_codeModelFuture.cancel();
137
    delete m_qbsProjectParser;
138
139
140
141
142
    if (m_qbsUpdateFutureInterface) {
        m_qbsUpdateFutureInterface->reportCanceled();
        delete m_qbsUpdateFutureInterface;
        m_qbsUpdateFutureInterface = 0;
    }
143
144
145
146
147
148

    // Deleting the root node triggers a few things, make sure rootProjectNode
    // returns 0 already
    QbsProjectNode *root = m_rootProjectNode;
    m_rootProjectNode = 0;
    delete root;
Tobias Hunger's avatar
Tobias Hunger committed
149
150
151
152
153
154
155
}

QString QbsProject::displayName() const
{
    return m_projectName;
}

156
IDocument *QbsProject::document() const
Tobias Hunger's avatar
Tobias Hunger committed
157
{
158
    foreach (IDocument *doc, m_qbsDocuments) {
159
        if (doc->filePath() == m_fileName)
Tobias Hunger's avatar
Tobias Hunger committed
160
161
162
163
164
165
166
167
168
169
            return doc;
    }
    QTC_ASSERT(false, return 0);
}

QbsManager *QbsProject::projectManager() const
{
    return m_manager;
}

170
ProjectNode *QbsProject::rootProjectNode() const
Tobias Hunger's avatar
Tobias Hunger committed
171
172
173
174
{
    return m_rootProjectNode;
}

175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
static void collectFilesForProject(const qbs::ProjectData &project, QSet<QString> &result)
{
    result.insert(project.location().fileName());
    foreach (const qbs::ProductData &prd, project.products()) {
        foreach (const qbs::GroupData &grp, prd.groups()) {
            foreach (const QString &file, grp.allFilePaths())
                result.insert(file);
            result.insert(grp.location().fileName());
        }
        result.insert(prd.location().fileName());
    }
    foreach (const qbs::ProjectData &subProject, project.subProjects())
        collectFilesForProject(subProject, result);
}

190
QStringList QbsProject::files(Project::FilesMode fileMode) const
Tobias Hunger's avatar
Tobias Hunger committed
191
192
{
    Q_UNUSED(fileMode);
193
    if (!m_qbsProject.isValid() || isParsing())
194
        return QStringList();
195
    QSet<QString> result;
196
197
    collectFilesForProject(m_projectData, result);
    result.unite(m_qbsProject.buildSystemFiles());
198
    return result.toList();
Tobias Hunger's avatar
Tobias Hunger committed
199
200
}

201
202
203
204
205
bool QbsProject::isProjectEditable() const
{
    return m_qbsProject.isValid() && !isParsing() && !ProjectExplorer::BuildManager::isBuilding();
}

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
class ChangeExpector
{
public:
    ChangeExpector(const QString &filePath, const QSet<Core::IDocument *> &documents)
        : m_document(0)
    {
        foreach (Core::IDocument * const doc, documents) {
            if (doc->filePath() == filePath) {
                m_document = doc;
                break;
            }
        }
        QTC_ASSERT(m_document, return);
        Core::DocumentManager::expectFileChange(filePath);
        m_wasInDocumentManager = Core::DocumentManager::removeDocument(m_document);
        QTC_CHECK(m_wasInDocumentManager);
    }

    ~ChangeExpector()
    {
        QTC_ASSERT(m_document, return);
        Core::DocumentManager::addDocument(m_document);
        Core::DocumentManager::unexpectFileChange(m_document->filePath());
    }

private:
    Core::IDocument *m_document;
    bool m_wasInDocumentManager;
};

236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
bool QbsProject::ensureWriteableQbsFile(const QString &file)
{
    // Ensure that the file is not read only
    QFileInfo fi(file);
    if (!fi.isWritable()) {
        // Try via vcs manager
        Core::IVersionControl *versionControl =
            Core::VcsManager::findVersionControlForDirectory(fi.absolutePath());
        if (!versionControl || !versionControl->vcsOpen(file)) {
            bool makeWritable = QFile::setPermissions(file, fi.permissions() | QFile::WriteUser);
            if (!makeWritable) {
                QMessageBox::warning(Core::ICore::mainWindow(),
                                     tr("Failed!"),
                                     tr("Could not write project file %1.").arg(file));
                return false;
            }
        }
    }
    return true;
}

257
258
259
260
261
262
263
bool QbsProject::addFilesToProduct(QbsBaseProjectNode *node, const QStringList &filePaths,
        const qbs::ProductData &productData, const qbs::GroupData &groupData, QStringList *notAdded)
{
    QTC_ASSERT(m_qbsProject.isValid(), return false);
    QStringList allPaths = groupData.allFilePaths();
    const QString productFilePath = productData.location().fileName();
    ChangeExpector expector(productFilePath, m_qbsDocuments);
264
    ensureWriteableQbsFile(productFilePath);
265
266
267
268
269
270
271
272
273
274
275
276
    foreach (const QString &path, filePaths) {
        qbs::ErrorInfo err = m_qbsProject.addFiles(productData, groupData, QStringList() << path);
        if (err.hasError()) {
            Core::MessageManager::write(err.toString());
            *notAdded += path;
        } else {
            allPaths += path;
        }
    }
    if (notAdded->count() != filePaths.count()) {
        m_projectData = m_qbsProject.projectData();
        QbsGroupNode::setupFiles(node, allPaths, QFileInfo(productFilePath).absolutePath(), true);
277
        m_rootProjectNode->update();
278
279
280
281
282
283
284
285
286
287
288
289
    }
    return notAdded->isEmpty();
}

bool QbsProject::removeFilesFromProduct(QbsBaseProjectNode *node, const QStringList &filePaths,
        const qbs::ProductData &productData, const qbs::GroupData &groupData,
        QStringList *notRemoved)
{
    QTC_ASSERT(m_qbsProject.isValid(), return false);
    QStringList allPaths = groupData.allFilePaths();
    const QString productFilePath = productData.location().fileName();
    ChangeExpector expector(productFilePath, m_qbsDocuments);
290
    ensureWriteableQbsFile(productFilePath);
291
292
293
294
295
296
297
298
299
300
301
302
303
    foreach (const QString &path, filePaths) {
        qbs::ErrorInfo err
                = m_qbsProject.removeFiles(productData, groupData, QStringList() << path);
        if (err.hasError()) {
            Core::MessageManager::write(err.toString());
            *notRemoved += path;
        } else {
            allPaths.removeOne(path);
        }
    }
    if (notRemoved->count() != filePaths.count()) {
        m_projectData = m_qbsProject.projectData();
        QbsGroupNode::setupFiles(node, allPaths, QFileInfo(productFilePath).absolutePath(), true);
304
        m_rootProjectNode->update();
305
306
307
308
    }
    return notRemoved->isEmpty();
}

Tobias Hunger's avatar
Tobias Hunger committed
309
310
311
312
313
void QbsProject::invalidate()
{
    prepareForParsing();
}

314
qbs::BuildJob *QbsProject::build(const qbs::BuildOptions &opts, QStringList productNames)
Tobias Hunger's avatar
Tobias Hunger committed
315
{
316
    if (!qbsProject().isValid() || isParsing())
Tobias Hunger's avatar
Tobias Hunger committed
317
        return 0;
318
    if (productNames.isEmpty()) {
319
        return qbsProject().buildAllProducts(opts);
320
321
322
323
    } else {
        QList<qbs::ProductData> products;
        foreach (const QString &productName, productNames) {
            bool found = false;
324
            foreach (const qbs::ProductData &data, qbsProjectData().allProducts()) {
325
326
327
328
329
330
331
332
333
334
                if (data.name() == productName) {
                    found = true;
                    products.append(data);
                    break;
                }
            }
            if (!found)
                return 0;
        }

335
        return qbsProject().buildSomeProducts(products, opts);
336
    }
Tobias Hunger's avatar
Tobias Hunger committed
337
338
}

339
qbs::CleanJob *QbsProject::clean(const qbs::CleanOptions &opts)
Tobias Hunger's avatar
Tobias Hunger committed
340
{
341
    if (!qbsProject().isValid())
Tobias Hunger's avatar
Tobias Hunger committed
342
        return 0;
343
    return qbsProject().cleanAllProducts(opts);
Tobias Hunger's avatar
Tobias Hunger committed
344
345
}

Tobias Hunger's avatar
Tobias Hunger committed
346
347
qbs::InstallJob *QbsProject::install(const qbs::InstallOptions &opts)
{
348
    if (!qbsProject().isValid())
Tobias Hunger's avatar
Tobias Hunger committed
349
        return 0;
350
    return qbsProject().installAllProducts(opts);
Tobias Hunger's avatar
Tobias Hunger committed
351
352
}

353
QString QbsProject::profileForTarget(const Target *t) const
Tobias Hunger's avatar
Tobias Hunger committed
354
355
356
357
358
359
360
361
362
363
364
{
    return m_manager->profileForKit(t->kit());
}

bool QbsProject::isParsing() const
{
    return m_qbsUpdateFutureInterface;
}

bool QbsProject::hasParseResult() const
{
365
    return qbsProject().isValid();
Tobias Hunger's avatar
Tobias Hunger committed
366
367
}

368
369
Utils::FileName QbsProject::defaultBuildDirectory(const QString &projectFilePath, const Kit *k,
                                                  const QString &bcName)
370
{
371
372
    const QString projectName = QFileInfo(projectFilePath).completeBaseName();
    ProjectExplorer::ProjectMacroExpander expander(projectFilePath, projectName, k, bcName);
373
    QString projectDir = projectDirectory(Utils::FileName::fromString(projectFilePath)).toString();
374
375
    QString buildPath = Utils::expandMacros(Core::DocumentManager::buildDirectory(), &expander);
    return Utils::FileName::fromString(Utils::FileUtils::resolvePath(projectDir, buildPath));
Tobias Hunger's avatar
Tobias Hunger committed
376
377
}

378
qbs::Project QbsProject::qbsProject() const
379
{
380
    return m_qbsProject;
381
382
}

383
qbs::ProjectData QbsProject::qbsProjectData() const
384
{
385
    return m_projectData;
386
387
}

388
389
390
391
392
bool QbsProject::needsSpecialDeployment() const
{
    return true;
}

Tobias Hunger's avatar
Tobias Hunger committed
393
394
void QbsProject::handleQbsParsingDone(bool success)
{
395
    QTC_ASSERT(m_qbsProjectParser, return);
Tobias Hunger's avatar
Tobias Hunger committed
396

397
398
399
400
401
    const CancelStatus cancelStatus = m_cancelStatus;
    m_cancelStatus = CancelStatusNone;

    // Start a new one parse operation right away, ignoring the old result.
    if (cancelStatus == CancelStatusCancelingForReparse) {
402
403
        m_qbsProjectParser->deleteLater();
        m_qbsProjectParser = 0;
404
        parseCurrentBuildConfiguration();
405
406
407
        return;
    }

408
409
    generateErrors(m_qbsProjectParser->error());

410
411
    if (success) {
        m_qbsProject = m_qbsProjectParser->qbsProject();
412
        const qbs::ProjectData &projectData = m_qbsProject.projectData();
413
        QTC_CHECK(m_qbsProject.isValid());
414
415
416
417
        if (projectData != m_projectData) {
            m_projectData = projectData;
            readQbsData();
        }
418
419
    } else {
        m_qbsUpdateFutureInterface->reportCanceled();
420
421
    }

422
423
424
425
426
427
428
429
    m_qbsProjectParser->deleteLater();
    m_qbsProjectParser = 0;

    if (m_qbsUpdateFutureInterface) {
        m_qbsUpdateFutureInterface->reportFinished();
        delete m_qbsUpdateFutureInterface;
        m_qbsUpdateFutureInterface = 0;
    }
Tobias Hunger's avatar
Tobias Hunger committed
430
431
432
433

    emit projectParsingDone(success);
}

434
void QbsProject::targetWasAdded(Target *t)
Tobias Hunger's avatar
Tobias Hunger committed
435
436
{
    connect(t, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
437
438
            this, SLOT(delayParsing()));
    connect(t, SIGNAL(buildDirectoryChanged()), this, SLOT(delayParsing()));
Tobias Hunger's avatar
Tobias Hunger committed
439
440
}

441
void QbsProject::changeActiveTarget(Target *t)
Tobias Hunger's avatar
Tobias Hunger committed
442
{
443
    BuildConfiguration *bc = 0;
Tobias Hunger's avatar
Tobias Hunger committed
444
445
446
447
448
    if (t && t->kit())
        bc = t->activeBuildConfiguration();
    buildConfigurationChanged(bc);
}

449
void QbsProject::buildConfigurationChanged(BuildConfiguration *bc)
Tobias Hunger's avatar
Tobias Hunger committed
450
451
{
    if (m_currentBc)
452
        disconnect(m_currentBc, SIGNAL(qbsConfigurationChanged()), this, SLOT(delayParsing()));
Tobias Hunger's avatar
Tobias Hunger committed
453
454
455

    m_currentBc = qobject_cast<QbsBuildConfiguration *>(bc);
    if (m_currentBc) {
456
457
        connect(m_currentBc, SIGNAL(qbsConfigurationChanged()), this, SLOT(delayParsing()));
        delayParsing();
Tobias Hunger's avatar
Tobias Hunger committed
458
459
460
461
462
    } else {
        invalidate();
    }
}

463
464
void QbsProject::startParsing()
{
465
466
    // Qbs does update the build graph during the build. So we cannot
    // start to parse while a build is running or we will lose information.
467
468
    if (ProjectExplorer::BuildManager::isBuilding(this)) {
        scheduleParsing();
469
        return;
470
    }
471

472
    parseCurrentBuildConfiguration();
473
474
}

475
476
477
478
479
void QbsProject::delayParsing()
{
    m_parsingDelay.start();
}

480
481
482
483
484
485
486
487
488
489
490
491
492
// Qbs may change its data
void QbsProject::readQbsData()
{
    QTC_ASSERT(m_rootProjectNode, return);

    m_rootProjectNode->update();

    qbs::Project project = m_rootProjectNode->qbsProject();
    updateDocuments(project.isValid() ? project.buildSystemFiles() : QSet<QString>() << m_fileName);

    qbs::ProjectData data = m_rootProjectNode->qbsProjectData();
    updateCppCodeModel(data);
    updateQmlJsCodeModel(data);
493
    updateBuildTargetData();
494
495
496
497

    emit fileListChanged();
}

498
void QbsProject::parseCurrentBuildConfiguration()
Tobias Hunger's avatar
Tobias Hunger committed
499
{
500
    m_parsingScheduled = false;
501
    if (m_cancelStatus == CancelStatusCancelingForReparse)
502
        return;
503

504
505
506
507
508
    // The CancelStatusCancelingAltoghether type can only be set by a build job, during
    // which no other parse requests come through to this point (except by the build job itself,
    // but of course not while canceling is in progress).
    QTC_ASSERT(m_cancelStatus == CancelStatusNone, return);

Tobias Hunger's avatar
Tobias Hunger committed
509
510
511
512
513
    if (!activeTarget())
        return;
    QbsBuildConfiguration *bc = qobject_cast<QbsBuildConfiguration *>(activeTarget()->activeBuildConfiguration());
    if (!bc)
        return;
514
515
516
517
518
519
520
521

    // New parse requests override old ones.
    // NOTE: We need to wait for the current operation to finish, since otherwise there could
    //       be a conflict. Consider the case where the old qbs::ProjectSetupJob is writing
    //       to the build graph file when the cancel request comes in. If we don't wait for
    //       acknowledgment, it might still be doing that when the new one already reads from the
    //       same file.
    if (m_qbsProjectParser) {
522
        m_cancelStatus = CancelStatusCancelingForReparse;
523
524
525
526
        m_qbsProjectParser->cancel();
        return;
    }

527
    parse(bc->qbsConfiguration(), bc->environment(), bc->buildDirectory().toString());
Tobias Hunger's avatar
Tobias Hunger committed
528
529
}

530
531
532
533
534
535
536
void QbsProject::cancelParsing()
{
    QTC_ASSERT(m_qbsProjectParser, return);
    m_cancelStatus = CancelStatusCancelingAltoghether;
    m_qbsProjectParser->cancel();
}

537
538
void QbsProject::updateAfterBuild()
{
539
540
    QTC_ASSERT(m_qbsProject.isValid(), return);
    m_projectData = m_qbsProject.projectData();
541
542
543
    updateBuildTargetData();
}

544
545
546
547
548
549
550
551
552
553
554
void QbsProject::registerQbsProjectParser(QbsProjectParser *p)
{
    m_parsingDelay.stop();

    if (m_qbsProjectParser) {
        m_qbsProjectParser->disconnect(this);
        m_qbsProjectParser->deleteLater();
    }

    m_qbsProjectParser = p;

555
    if (p)
556
557
558
        connect(m_qbsProjectParser, SIGNAL(done(bool)), this, SLOT(handleQbsParsingDone(bool)));
}

Tobias Hunger's avatar
Tobias Hunger committed
559
560
561
562
563
bool QbsProject::fromMap(const QVariantMap &map)
{
    if (!Project::fromMap(map))
        return false;

564
    Kit *defaultKit = KitManager::defaultKit();
565
    if (!activeTarget() && defaultKit) {
566
        Target *t = new Target(this, defaultKit);
Tobias Hunger's avatar
Tobias Hunger committed
567
568
569
570
571
572
573
574
575
        t->updateDefaultBuildConfigurations();
        t->updateDefaultDeployConfigurations();
        t->updateDefaultRunConfigurations();
        addTarget(t);
    }

    return true;
}

576
void QbsProject::generateErrors(const qbs::ErrorInfo &e)
Tobias Hunger's avatar
Tobias Hunger committed
577
{
578
    foreach (const qbs::ErrorItem &item, e.items())
579
580
581
582
583
        TaskHub::addTask(Task::Error, item.description(),
                         ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM,
                         FileName::fromString(item.codeLocation().fileName()),
                         item.codeLocation().line());

Tobias Hunger's avatar
Tobias Hunger committed
584
585
}

586
void QbsProject::parse(const QVariantMap &config, const Environment &env, const QString &dir)
Tobias Hunger's avatar
Tobias Hunger committed
587
{
588
    prepareForParsing();
589
    QTC_ASSERT(!m_qbsProjectParser, return);
Tobias Hunger's avatar
Tobias Hunger committed
590

591
    registerQbsProjectParser(new QbsProjectParser(this, m_qbsUpdateFutureInterface));
592

593
594
    m_qbsProjectParser->parse(config, env, dir);
    emit projectParsingStarted();
Tobias Hunger's avatar
Tobias Hunger committed
595
596
597
598
}

void QbsProject::prepareForParsing()
{
599
    TaskHub::clearTasks(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);
600
    if (m_qbsUpdateFutureInterface) {
Tobias Hunger's avatar
Tobias Hunger committed
601
        m_qbsUpdateFutureInterface->reportCanceled();
602
603
        m_qbsUpdateFutureInterface->reportFinished();
    }
Tobias Hunger's avatar
Tobias Hunger committed
604
605
606
    delete m_qbsUpdateFutureInterface;
    m_qbsUpdateFutureInterface = 0;

607
    m_qbsUpdateFutureInterface = new QFutureInterface<bool>();
Tobias Hunger's avatar
Tobias Hunger committed
608
    m_qbsUpdateFutureInterface->setProgressRange(0, 0);
609
    ProgressManager::addTask(m_qbsUpdateFutureInterface->future(),
610
        tr("Reading Project \"%1\"").arg(displayName()), "Qbs.QbsEvaluate");
Tobias Hunger's avatar
Tobias Hunger committed
611
612
613
    m_qbsUpdateFutureInterface->reportStarted();
}

614
void QbsProject::updateDocuments(const QSet<QString> &files)
Tobias Hunger's avatar
Tobias Hunger committed
615
616
{
    // Update documents:
617
618
    QSet<QString> newFiles = files;
    QTC_ASSERT(!newFiles.isEmpty(), newFiles << m_fileName);
Tobias Hunger's avatar
Tobias Hunger committed
619
    QSet<QString> oldFiles;
620
    foreach (IDocument *doc, m_qbsDocuments)
621
        oldFiles.insert(doc->filePath());
Tobias Hunger's avatar
Tobias Hunger committed
622
623
624
625
626
627

    QSet<QString> filesToAdd = newFiles;
    filesToAdd.subtract(oldFiles);
    QSet<QString> filesToRemove = oldFiles;
    filesToRemove.subtract(newFiles);

628
629
    QSet<IDocument *> currentDocuments = m_qbsDocuments;
    foreach (IDocument *doc, currentDocuments) {
630
        if (filesToRemove.contains(doc->filePath())) {
Tobias Hunger's avatar
Tobias Hunger committed
631
632
633
634
            m_qbsDocuments.remove(doc);
            delete doc;
        }
    }
635
    QSet<IDocument *> toAdd;
Tobias Hunger's avatar
Tobias Hunger committed
636
637
638
    foreach (const QString &f, filesToAdd)
        toAdd.insert(new QbsProjectFile(this, f));

639
    DocumentManager::addDocuments(toAdd.toList());
Tobias Hunger's avatar
Tobias Hunger committed
640
641
642
    m_qbsDocuments.unite(toAdd);
}

643
void QbsProject::updateCppCodeModel(const qbs::ProjectData &prj)
Tobias Hunger's avatar
Tobias Hunger committed
644
{
645
    if (!prj.isValid())
Tobias Hunger's avatar
Tobias Hunger committed
646
647
        return;

648
    Kit *k = 0;
Tobias Hunger's avatar
Tobias Hunger committed
649
    QtSupport::BaseQtVersion *qtVersion = 0;
650
    if (Target *target = activeTarget())
Tobias Hunger's avatar
Tobias Hunger committed
651
652
        k = target->kit();
    else
653
        k = KitManager::defaultKit();
Tobias Hunger's avatar
Tobias Hunger committed
654
655
    qtVersion = QtSupport::QtKitInformation::qtVersion(k);

656
657
    CppTools::CppModelManagerInterface *modelmanager =
        CppTools::CppModelManagerInterface::instance();
Tobias Hunger's avatar
Tobias Hunger committed
658
659
660
661

    if (!modelmanager)
        return;

662
    CppTools::CppModelManagerInterface::ProjectInfo pinfo = modelmanager->projectInfo(this);
Tobias Hunger's avatar
Tobias Hunger committed
663
    pinfo.clearProjectParts();
664
665
    CppTools::ProjectPart::QtVersion qtVersionForPart
            = CppTools::ProjectPart::NoQt;
Tobias Hunger's avatar
Tobias Hunger committed
666
667
    if (qtVersion) {
        if (qtVersion->qtVersion() < QtSupport::QtVersionNumber(5,0,0))
668
            qtVersionForPart = CppTools::ProjectPart::Qt4;
Tobias Hunger's avatar
Tobias Hunger committed
669
        else
670
            qtVersionForPart = CppTools::ProjectPart::Qt5;
Tobias Hunger's avatar
Tobias Hunger committed
671
672
    }

Tobias Hunger's avatar
Tobias Hunger committed
673
    QHash<QString, QString> uiFiles;
Tobias Hunger's avatar
Tobias Hunger committed
674
    QStringList allFiles;
675
    foreach (const qbs::ProductData &prd, prj.allProducts()) {
Tobias Hunger's avatar
Tobias Hunger committed
676
        foreach (const qbs::GroupData &grp, prd.groups()) {
677
            const qbs::PropertyMap &props = grp.properties();
Tobias Hunger's avatar
Tobias Hunger committed
678

679
680
681
            const QStringList cxxFlags = props.getModulePropertiesAsStringList(
                        QLatin1String(CONFIG_CPP_MODULE),
                        QLatin1String(CONFIG_CXXFLAGS));
Tobias Hunger's avatar
Tobias Hunger committed
682

683
684
685
686
            const QStringList cFlags = props.getModulePropertiesAsStringList(
                        QLatin1String(CONFIG_CPP_MODULE),
                        QLatin1String(CONFIG_CFLAGS));

687
688
689
            QStringList list = props.getModulePropertiesAsStringList(
                        QLatin1String(CONFIG_CPP_MODULE),
                        QLatin1String(CONFIG_DEFINES));
690
            QByteArray grpDefines;
691
692
693
694
695
696
697
            foreach (const QString &def, list) {
                QByteArray data = def.toUtf8();
                int pos = data.indexOf('=');
                if (pos >= 0)
                    data[pos] = ' ';
                grpDefines += (QByteArray("#define ") + data + '\n');
            }
Tobias Hunger's avatar
Tobias Hunger committed
698

699
700
            list = props.getModulePropertiesAsStringList(QLatin1String(CONFIG_CPP_MODULE),
                                                         QLatin1String(CONFIG_INCLUDEPATHS));
701
702
            list.append(props.getModulePropertiesAsStringList(QLatin1String(CONFIG_CPP_MODULE),
                                                              QLatin1String(CONFIG_SYSTEM_INCLUDEPATHS)));
703
704
705
706
707
            CppTools::ProjectPart::HeaderPaths grpHeaderPaths;
            foreach (const QString &p, list)
                grpHeaderPaths += CppTools::ProjectPart::HeaderPath(
                            FileName::fromUserInput(p).toString(),
                            CppTools::ProjectPart::HeaderPath::IncludePath);
Tobias Hunger's avatar
Tobias Hunger committed
708

709
710
            list = props.getModulePropertiesAsStringList(QLatin1String(CONFIG_CPP_MODULE),
                                                         QLatin1String(CONFIG_FRAMEWORKPATHS));
711
712
            list.append(props.getModulePropertiesAsStringList(QLatin1String(CONFIG_CPP_MODULE),
                                                              QLatin1String(CONFIG_SYSTEM_FRAMEWORKPATHS)));
713
714
715
716
            foreach (const QString &p, list)
                grpHeaderPaths += CppTools::ProjectPart::HeaderPath(
                            FileName::fromUserInput(p).toString(),
                            CppTools::ProjectPart::HeaderPath::FrameworkPath);
Tobias Hunger's avatar
Tobias Hunger committed
717

718
719
            const QString pch = props.getModuleProperty(QLatin1String(CONFIG_CPP_MODULE),
                    QLatin1String(CONFIG_PRECOMPILEDHEADER)).toString();
Tobias Hunger's avatar
Tobias Hunger committed
720

721
            CppTools::ProjectPart::Ptr part(new CppTools::ProjectPart);
722
723
724
725
726
727
            part->project = this;
            part->displayName = grp.name();
            part->projectFile = QString::fromLatin1("%1:%2:%3")
                    .arg(grp.location().fileName())
                    .arg(grp.location().line())
                    .arg(grp.location().column());
728
            part->evaluateToolchain(ToolChainKitInformation::toolChain(k),
729
                                    cxxFlags,
730
                                    cFlags,
731
                                    SysRootKitInformation::sysRoot(k));
732

733
            CppTools::ProjectFileAdder adder(part->files);
Tobias Hunger's avatar
Tobias Hunger committed
734
735
736
            foreach (const QString &file, grp.allFilePaths()) {
                if (file.endsWith(QLatin1String(".ui"))) {
                    QStringList generated = m_rootProjectNode->qbsProject()
737
                            .generatedFiles(prd, file, QStringList(QLatin1String("hpp")));
Tobias Hunger's avatar
Tobias Hunger committed
738
739
740
                    if (generated.count() == 1)
                        uiFiles.insert(file, generated.at(0));
                }
741
742
                if (adder.maybeAdd(file))
                    allFiles.append(file);
Tobias Hunger's avatar
Tobias Hunger committed
743
            }
744
745
            part->files << CppTools::ProjectFile(QLatin1String(CONFIGURATION_PATH),
                                                  CppTools::ProjectFile::CXXHeader);
746
747

            part->qtVersion = qtVersionForPart;
748
            part->headerPaths += grpHeaderPaths;
749
            part->precompiledHeaders = QStringList(pch);
750
            part->projectDefines += grpDefines;
751
            pinfo.appendProjectPart(part);
Tobias Hunger's avatar
Tobias Hunger committed
752
753
754
        }
    }

755
756
    setProjectLanguage(ProjectExplorer::Constants::LANG_CXX, !allFiles.isEmpty());

Tobias Hunger's avatar
Tobias Hunger committed
757
758
759
    if (pinfo.projectParts().isEmpty())
        return;

Tobias Hunger's avatar
Tobias Hunger committed
760
761
    QtSupport::UiCodeModelManager::update(this, uiFiles);

Tobias Hunger's avatar
Tobias Hunger committed
762
    // Register update the code model:
763
    m_codeModelFuture = modelmanager->updateProjectInfo(pinfo);
Tobias Hunger's avatar
Tobias Hunger committed
764
765
}

766
void QbsProject::updateQmlJsCodeModel(const qbs::ProjectData &prj)
Tobias Hunger's avatar
Tobias Hunger committed
767
768
{
    Q_UNUSED(prj);
769
770
771
772
    QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
    if (!modelManager)
        return;

773
774
    QmlJS::ModelManagerInterface::ProjectInfo projectInfo =
            QmlJSTools::defaultProjectInfoForProject(this);
775
776

    setProjectLanguage(ProjectExplorer::Constants::LANG_QMLJS, !projectInfo.sourceFiles.isEmpty());
777
    modelManager->updateProjectInfo(projectInfo, this);
Tobias Hunger's avatar
Tobias Hunger committed
778
779
}

780
781
782
783
void QbsProject::updateApplicationTargets(const qbs::ProjectData &projectData)
{
    ProjectExplorer::BuildTargetInfoList applications;
    foreach (const qbs::ProductData &productData, projectData.allProducts()) {
784
785
786
787
788
789
790
        if (!productData.isEnabled() || !productData.isRunnable())
            continue;
        if (productData.targetArtifacts().isEmpty()) { // No build yet.
            applications.list << ProjectExplorer::BuildTargetInfo(Utils::FileName(),
                    Utils::FileName::fromString(productData.location().fileName()));
            continue;
        }
791
792
793
794
795
796
797
798
799
800
801
        foreach (const qbs::TargetArtifact &ta, productData.targetArtifacts()) {
            QTC_ASSERT(ta.isValid(), continue);
            if (!ta.isExecutable())
                continue;
            applications.list << ProjectExplorer::BuildTargetInfo(Utils::FileName::fromString(ta.filePath()),
                    Utils::FileName::fromString(productData.location().fileName()));
        }
    }
    activeTarget()->setApplicationTargets(applications);
}

802
void QbsProject::updateDeploymentInfo(const qbs::Project &project)
803
804
{
    ProjectExplorer::DeploymentData deploymentData;
805
    if (project.isValid()) {
806
807
808
        qbs::InstallOptions installOptions;
        installOptions.setInstallRoot(QLatin1String("/"));
        foreach (const qbs::InstallableFile &f,
809
                 project.installableFilesForProject(m_projectData, installOptions)) {
810
811
812
813
814
815
816
817
            deploymentData.addFile(f.sourceFilePath(), f.targetDirectory(), f.isExecutable()
                                   ? ProjectExplorer::DeployableFile::TypeExecutable
                                   : ProjectExplorer::DeployableFile::TypeNormal);
        }
    }
    activeTarget()->setDeploymentData(deploymentData);
}

818
819
void QbsProject::updateBuildTargetData()
{
820
    updateApplicationTargets(m_projectData);
821
822
823
824
825
    updateDeploymentInfo(m_qbsProject);
    foreach (Target *t, targets())
        t->updateDefaultRunConfigurations();
}

Tobias Hunger's avatar
Tobias Hunger committed
826
827
} // namespace Internal
} // namespace QbsProjectManager