cmakeproject.cpp 28.3 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8 9 10 11
** 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
Eike Ziller's avatar
Eike Ziller committed
12 13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24
**
Eike Ziller's avatar
Eike Ziller committed
25 26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
con's avatar
con committed
27 28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
hjk's avatar
hjk committed
30

con's avatar
con committed
31
#include "cmakeproject.h"
Tobias Hunger's avatar
Tobias Hunger committed
32 33

#include "cmakebuildconfiguration.h"
con's avatar
con committed
34 35
#include "cmakeprojectconstants.h"
#include "cmakeprojectnodes.h"
hjk's avatar
hjk committed
36
#include "cmakerunconfiguration.h"
37
#include "makestep.h"
38
#include "cmakeopenprojectwizard.h"
39 40 41
#include "cmakecbpparser.h"
#include "cmakefile.h"
#include "cmakeprojectmanager.h"
hjk's avatar
hjk committed
42

43
#include <projectexplorer/projectexplorerconstants.h>
44
#include <projectexplorer/headerpath.h>
Tobias Hunger's avatar
Tobias Hunger committed
45
#include <projectexplorer/buildsteplist.h>
dt's avatar
dt committed
46
#include <projectexplorer/buildmanager.h>
47
#include <projectexplorer/buildtargetinfo.h>
Tobias Hunger's avatar
Tobias Hunger committed
48 49
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
50
#include <projectexplorer/toolchain.h>
51

52
#include <projectexplorer/deployconfiguration.h>
53
#include <projectexplorer/deploymentdata.h>
Tobias Hunger's avatar
Tobias Hunger committed
54
#include <qtsupport/customexecutablerunconfiguration.h>
55 56
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
57
#include <qtsupport/uicodemodelsupport.h>
58
#include <cpptools/cppmodelmanager.h>
dt's avatar
dt committed
59
#include <extensionsystem/pluginmanager.h>
60
#include <utils/algorithm.h>
hjk's avatar
hjk committed
61
#include <utils/qtcassert.h>
62
#include <utils/stringutils.h>
63
#include <utils/hostosinfo.h>
dt's avatar
dt committed
64
#include <coreplugin/icore.h>
65
#include <coreplugin/infobar.h>
dt's avatar
dt committed
66
#include <coreplugin/editormanager/editormanager.h>
hjk's avatar
hjk committed
67

68 69
#include <QDebug>
#include <QDir>
70
#include <QFileSystemWatcher>
con's avatar
con committed
71 72 73

using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;
74
using namespace ProjectExplorer;
75
using namespace Utils;
76 77 78 79 80 81 82 83 84 85

// QtCreator CMake Generator wishlist:
// Which make targets we need to build to get all executables
// What is the make we need to call
// What is the actual compiler executable
// DEFINES

// Open Questions
// Who sets up the environment for cl.exe ? INCLUDEPATH and so on

86 87 88
/*!
  \class CMakeProject
*/
89
CMakeProject::CMakeProject(CMakeManager *manager, const FileName &fileName)
90
    : m_manager(manager),
91
      m_activeTarget(0),
92
      m_fileName(fileName),
Tobias Hunger's avatar
Tobias Hunger committed
93 94
      m_rootNode(new CMakeProjectNode(fileName)),
      m_watcher(new QFileSystemWatcher(this))
con's avatar
con committed
95
{
96
    setId(Constants::CMAKEPROJECT_ID);
97
    setProjectContext(Core::Context(CMakeProjectManager::Constants::PROJECTCONTEXT));
98
    setProjectLanguages(Core::Context(ProjectExplorer::Constants::LANG_CXX));
99

100
    m_projectName = fileName.parentDir().fileName();
101

con's avatar
con committed
102
    m_file = new CMakeFile(this, fileName);
Tobias Hunger's avatar
Tobias Hunger committed
103

104 105
    connect(this, SIGNAL(buildTargetsChanged()),
            this, SLOT(updateRunConfigurations()));
Tobias Hunger's avatar
Tobias Hunger committed
106 107

    connect(m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(fileChanged(QString)));
108 109 110 111
}

CMakeProject::~CMakeProject()
{
112
    m_codeModelFuture.cancel();
113 114 115
    delete m_rootNode;
}

Tobias Hunger's avatar
Tobias Hunger committed
116
void CMakeProject::fileChanged(const QString &fileName)
dt's avatar
dt committed
117
{
Tobias Hunger's avatar
Tobias Hunger committed
118
    Q_UNUSED(fileName)
dt's avatar
dt committed
119

120
    parseCMakeLists();
121 122
}

Tobias Hunger's avatar
Tobias Hunger committed
123
void CMakeProject::changeActiveBuildConfiguration(ProjectExplorer::BuildConfiguration *bc)
124
{
125
    if (!bc)
Tobias Hunger's avatar
Tobias Hunger committed
126 127
        return;

128
    CMakeBuildConfiguration *cmakebc = static_cast<CMakeBuildConfiguration *>(bc);
129

130
    // Pop up a dialog asking the user to rerun cmake
131
    QString cbpFile = CMakeManager::findCbpFile(QDir(bc->buildDirectory().toString()));
132
    QFileInfo cbpFileFi(cbpFile);
133 134
    CMakeOpenProjectWizard::Mode mode = CMakeOpenProjectWizard::Nothing;
    if (!cbpFileFi.exists()) {
135
        mode = CMakeOpenProjectWizard::NeedToCreate;
136
    } else {
137 138
        foreach (const FileName &file, m_watchedFiles) {
            if (file.toFileInfo().lastModified() > cbpFileFi.lastModified()) {
139 140 141 142 143
                mode = CMakeOpenProjectWizard::NeedToUpdate;
                break;
            }
        }
    }
144

145
    if (mode != CMakeOpenProjectWizard::Nothing) {
146
        CMakeBuildInfo info(cmakebc);
147
        CMakeOpenProjectWizard copw(Core::ICore::mainWindow(), m_manager, mode, &info);
148 149
        if (copw.exec() == QDialog::Accepted)
            cmakebc->setUseNinja(copw.useNinja()); // NeedToCreate can change the Ninja setting
150
    }
151

152
    // reparse
153
    parseCMakeLists();
154 155
}

156
void CMakeProject::activeTargetWasChanged(Target *target)
157
{
158 159 160 161 162 163 164 165
    if (m_activeTarget) {
        disconnect(m_activeTarget, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
                   this, SLOT(changeActiveBuildConfiguration(ProjectExplorer::BuildConfiguration*)));
    }

    m_activeTarget = target;

    if (!m_activeTarget)
166
        return;
Tobias Hunger's avatar
Tobias Hunger committed
167

168 169 170 171
    connect(m_activeTarget, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
            this, SLOT(changeActiveBuildConfiguration(ProjectExplorer::BuildConfiguration*)));

    changeActiveBuildConfiguration(m_activeTarget->activeBuildConfiguration());
172 173
}

174
void CMakeProject::changeBuildDirectory(CMakeBuildConfiguration *bc, const QString &newBuildDirectory)
175
{
176
    bc->setBuildDirectory(FileName::fromString(newBuildDirectory));
177
    parseCMakeLists();
178 179
}

180
QStringList CMakeProject::getCXXFlagsFor(const CMakeBuildTarget &buildTarget, QByteArray *cachedBuildNinja)
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
{
    QString makeCommand = QDir::fromNativeSeparators(buildTarget.makeCommand);
    int startIndex = makeCommand.indexOf(QLatin1Char('\"'));
    int endIndex = makeCommand.indexOf(QLatin1Char('\"'), startIndex + 1);
    if (startIndex != -1 && endIndex != -1) {
        startIndex += 1;
        QString makefile = makeCommand.mid(startIndex, endIndex - startIndex);
        int slashIndex = makefile.lastIndexOf(QLatin1Char('/'));
        makefile.truncate(slashIndex);
        makefile.append(QLatin1String("/CMakeFiles/") + buildTarget.title + QLatin1String(".dir/flags.make"));
        QFile file(makefile);
        if (file.exists()) {
            file.open(QIODevice::ReadOnly | QIODevice::Text);
            QTextStream stream(&file);
            while (!stream.atEnd()) {
                QString line = stream.readLine().trimmed();
                if (line.startsWith(QLatin1String("CXX_FLAGS ="))) {
                    // Skip past =
                    return line.mid(11).trimmed().split(QLatin1Char(' '), QString::SkipEmptyParts);
                }
            }
        }
    }

    // Attempt to find build.ninja file and obtain FLAGS (CXX_FLAGS) from there if no suitable flags.make were
    // found
    // Get "all" target's working directory
208
    if (!buildTargets().empty()) {
209 210 211 212 213 214 215 216 217 218 219 220
        if (cachedBuildNinja->isNull()) {
            QString buildNinjaFile = QDir::fromNativeSeparators(buildTargets().at(0).workingDirectory);
            buildNinjaFile += QLatin1String("/build.ninja");
            QFile buildNinja(buildNinjaFile);
            if (buildNinja.exists()) {
                buildNinja.open(QIODevice::ReadOnly | QIODevice::Text);
                *cachedBuildNinja = buildNinja.readAll();
                buildNinja.close();
            } else {
                *cachedBuildNinja = QByteArray();
            }
        }
221

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
        if (cachedBuildNinja->isEmpty())
            return QStringList();

        QTextStream stream(cachedBuildNinja);
        bool targetFound = false;
        bool cxxFound = false;
        QString targetSearchPattern = QString::fromLatin1("target %1").arg(buildTarget.title);

        while (!stream.atEnd()) {
            // 1. Look for a block that refers to the current target
            // 2. Look for a build rule which invokes CXX_COMPILER
            // 3. Return the FLAGS definition
            QString line = stream.readLine().trimmed();
            if (line.startsWith(QLatin1String("#"))) {
                if (!line.startsWith(QLatin1String("# Object build statements for"))) continue;
                targetFound = line.endsWith(targetSearchPattern);
            } else if (targetFound && line.startsWith(QLatin1String("build"))) {
                cxxFound = line.indexOf(QLatin1String("CXX_COMPILER")) != -1;
            } else if (cxxFound && line.startsWith(QLatin1String("FLAGS ="))) {
                // Skip past =
                return line.mid(7).trimmed().split(QLatin1Char(' '), QString::SkipEmptyParts);
243 244
            }
        }
245

246 247 248 249
    }
    return QStringList();
}

250
bool CMakeProject::parseCMakeLists()
251
{
Tobias Hunger's avatar
Tobias Hunger committed
252
    if (!activeTarget() ||
Tobias Hunger's avatar
Tobias Hunger committed
253
        !activeTarget()->activeBuildConfiguration()) {
254
        return false;
Tobias Hunger's avatar
Tobias Hunger committed
255
    }
Tobias Hunger's avatar
Tobias Hunger committed
256

257
    CMakeBuildConfiguration *activeBC = static_cast<CMakeBuildConfiguration *>(activeTarget()->activeBuildConfiguration());
hjk's avatar
hjk committed
258
    foreach (Core::IDocument *document, Core::DocumentModel::openedDocuments())
259
        if (isProjectFile(document->filePath()))
260
            document->infoBar()->removeInfo("CMakeEditor.RunCMake");
261

262
    // Find cbp file
263
    QString cbpFile = CMakeManager::findCbpFile(activeBC->buildDirectory().toString());
264

265 266
    if (cbpFile.isEmpty()) {
        emit buildTargetsChanged();
267
        return false;
268 269
    }

270 271
    Kit *k = activeTarget()->kit();

272
    // setFolderName
273
    m_rootNode->setDisplayName(QFileInfo(cbpFile).completeBaseName());
274
    CMakeCbpParser cbpparser;
275 276
    // Parsing
    //qDebug()<<"Parsing file "<<cbpFile;
277
    if (!cbpparser.parseCbpFile(k,cbpFile, projectDirectory().toString())) {
Tobias Hunger's avatar
Tobias Hunger committed
278 279
        // TODO report error
        emit buildTargetsChanged();
280
        return false;
Tobias Hunger's avatar
Tobias Hunger committed
281
    }
282

283 284 285 286
    foreach (const QString &file, m_watcher->files())
        if (file != cbpFile)
            m_watcher->removePath(file);

287
    // how can we ensure that it is completely written?
288 289
    m_watcher->addPath(cbpFile);

Tobias Hunger's avatar
Tobias Hunger committed
290
    m_projectName = cbpparser.projectName();
291
    m_rootNode->setDisplayName(cbpparser.projectName());
292

Tobias Hunger's avatar
Tobias Hunger committed
293 294
    //qDebug()<<"Building Tree";
    QList<ProjectExplorer::FileNode *> fileList = cbpparser.fileList();
295
    QSet<FileName> projectFiles;
Tobias Hunger's avatar
Tobias Hunger committed
296 297
    if (cbpparser.hasCMakeFiles()) {
        fileList.append(cbpparser.cmakeFileList());
tomdeblauwe's avatar
tomdeblauwe committed
298
        foreach (const ProjectExplorer::FileNode *node, cbpparser.cmakeFileList())
Tobias Hunger's avatar
Tobias Hunger committed
299 300 301
            projectFiles.insert(node->path());
    } else {
        // Manually add the CMakeLists.txt file
302
        FileName cmakeListTxt = projectDirectory().appendPath(QLatin1String("CMakeLists.txt"));
303 304
        bool generated = false;
        fileList.append(new ProjectExplorer::FileNode(cmakeListTxt, ProjectExplorer::ProjectFileType, generated));
Tobias Hunger's avatar
Tobias Hunger committed
305 306
        projectFiles.insert(cmakeListTxt);
    }
307

Tobias Hunger's avatar
Tobias Hunger committed
308
    m_watchedFiles = projectFiles;
309

Tobias Hunger's avatar
Tobias Hunger committed
310 311
    m_files.clear();
    foreach (ProjectExplorer::FileNode *fn, fileList)
312
        m_files.append(fn->path().toString());
Tobias Hunger's avatar
Tobias Hunger committed
313
    m_files.sort();
con's avatar
con committed
314

Tobias Hunger's avatar
Tobias Hunger committed
315
    buildTree(m_rootNode, fileList);
316

Tobias Hunger's avatar
Tobias Hunger committed
317 318
    //qDebug()<<"Adding Targets";
    m_buildTargets = cbpparser.buildTargets();
dt's avatar
dt committed
319
//        qDebug()<<"Printing targets";
tomdeblauwe's avatar
tomdeblauwe committed
320
//        foreach (CMakeBuildTarget ct, m_buildTargets) {
dt's avatar
dt committed
321 322 323 324 325
//            qDebug()<<ct.title<<" with executable:"<<ct.executable;
//            qDebug()<<"WD:"<<ct.workingDirectory;
//            qDebug()<<ct.makeCommand<<ct.makeCleanCommand;
//            qDebug()<<"";
//        }
dt's avatar
dt committed
326

327
    updateApplicationAndDeploymentTargets();
dt's avatar
dt committed
328 329

    createUiCodeModelSupport();
330

331
    ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
Tobias Hunger's avatar
Tobias Hunger committed
332
    if (!tc) {
333 334 335
        emit buildTargetsChanged();
        emit fileListChanged();
        return true;
Tobias Hunger's avatar
Tobias Hunger committed
336
    }
337

338 339 340 341
    CppTools::CppModelManager *modelmanager = CppTools::CppModelManager::instance();
    CppTools::ProjectInfo pinfo(this);
    CppTools::ProjectPartBuilder ppBuilder(pinfo);

342 343 344 345 346 347 348 349 350 351
    CppTools::ProjectPart::QtVersion activeQtVersion = CppTools::ProjectPart::NoQt;
    if (QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(k)) {
        if (qtVersion->qtVersion() < QtSupport::QtVersionNumber(5,0,0))
            activeQtVersion = CppTools::ProjectPart::Qt4;
        else
            activeQtVersion = CppTools::ProjectPart::Qt5;
    }

    ppBuilder.setQtVersion(activeQtVersion);

352
    QByteArray cachedBuildNinja;
353 354 355 356 357
    foreach (const CMakeBuildTarget &cbt, m_buildTargets) {
        // This explicitly adds -I. to the include paths
        QStringList includePaths = cbt.includeFiles;
        includePaths += projectDirectory().toString();
        ppBuilder.setIncludePaths(includePaths);
358 359 360
        QStringList cxxflags = getCXXFlagsFor(cbt, &cachedBuildNinja);
        ppBuilder.setCFlags(cxxflags);
        ppBuilder.setCxxFlags(cxxflags);
361 362 363 364 365 366
        ppBuilder.setDefines(cbt.defines);
        ppBuilder.setDisplayName(cbt.title);

        const QList<Core::Id> languages = ppBuilder.createProjectPartsForFiles(cbt.files);
        foreach (Core::Id language, languages)
            setProjectLanguage(language, true);
Tobias Hunger's avatar
Tobias Hunger committed
367
    }
368

369 370 371 372
    m_codeModelFuture.cancel();
    pinfo.finish();
    m_codeModelFuture = modelmanager->updateProjectInfo(pinfo);

373
    emit displayNameChanged();
374
    emit buildTargetsChanged();
375
    emit fileListChanged();
Tobias Hunger's avatar
Tobias Hunger committed
376

377 378
    emit activeBC->emitBuildTypeChanged();

379
    return true;
con's avatar
con committed
380 381
}

382
bool CMakeProject::isProjectFile(const FileName &fileName)
383 384 385 386
{
    return m_watchedFiles.contains(fileName);
}

Tobias Hunger's avatar
Tobias Hunger committed
387 388 389 390 391
QList<CMakeBuildTarget> CMakeProject::buildTargets() const
{
    return m_buildTargets;
}

392
QStringList CMakeProject::buildTargetTitles(bool runnable) const
con's avatar
con committed
393
{
394
    QStringList results;
395
    foreach (const CMakeBuildTarget &ct, m_buildTargets) {
396
        if (runnable && (ct.executable.isEmpty() || ct.targetType != ExecutableType))
397
            continue;
398
        results << ct.title;
399
    }
400
    return results;
con's avatar
con committed
401 402
}

403
bool CMakeProject::hasBuildTarget(const QString &title) const
404
{
405
    foreach (const CMakeBuildTarget &ct, m_buildTargets) {
406 407 408 409 410 411
        if (ct.title == title)
            return true;
    }
    return false;
}

412
void CMakeProject::gatherFileNodes(ProjectExplorer::FolderNode *parent, QList<ProjectExplorer::FileNode *> &list)
con's avatar
con committed
413
{
tomdeblauwe's avatar
tomdeblauwe committed
414
    foreach (ProjectExplorer::FolderNode *folder, parent->subFolderNodes())
415
        gatherFileNodes(folder, list);
tomdeblauwe's avatar
tomdeblauwe committed
416
    foreach (ProjectExplorer::FileNode *file, parent->fileNodes())
417 418 419
        list.append(file);
}

420 421 422 423 424
bool sortNodesByPath(Node *a, Node *b)
{
    return a->path() < b->path();
}

425 426 427 428 429
void CMakeProject::buildTree(CMakeProjectNode *rootNode, QList<ProjectExplorer::FileNode *> newList)
{
    // Gather old list
    QList<ProjectExplorer::FileNode *> oldList;
    gatherFileNodes(rootNode, oldList);
430 431
    Utils::sort(oldList, sortNodesByPath);
    Utils::sort(newList, sortNodesByPath);
432 433 434 435

    QList<ProjectExplorer::FileNode *> added;
    QList<ProjectExplorer::FileNode *> deleted;

436
    ProjectExplorer::compareSortedLists(oldList, newList, deleted, added, sortNodesByPath);
437

438
    qDeleteAll(ProjectExplorer::subtractSortedList(newList, added, sortNodesByPath));
439 440 441 442

    // add added nodes
    foreach (ProjectExplorer::FileNode *fn, added) {
//        qDebug()<<"added"<<fn->path();
con's avatar
con committed
443
        // Get relative path to rootNode
444
        QString parentDir = fn->path().toFileInfo().absolutePath();
con's avatar
con committed
445
        ProjectExplorer::FolderNode *folder = findOrCreateFolder(rootNode, parentDir);
446
        folder->addFileNodes(QList<ProjectExplorer::FileNode *>()<< fn);
con's avatar
con committed
447
    }
448

Tobias Hunger's avatar
Tobias Hunger committed
449
    // remove old file nodes and check whether folder nodes can be removed
450 451 452
    foreach (ProjectExplorer::FileNode *fn, deleted) {
        ProjectExplorer::FolderNode *parent = fn->parentFolderNode();
//        qDebug()<<"removed"<<fn->path();
453
        parent->removeFileNodes(QList<ProjectExplorer::FileNode *>() << fn);
454 455 456
        // Check for empty parent
        while (parent->subFolderNodes().isEmpty() && parent->fileNodes().isEmpty()) {
            ProjectExplorer::FolderNode *grandparent = parent->parentFolderNode();
457
            grandparent->removeFolderNodes(QList<ProjectExplorer::FolderNode *>() << parent);
458 459 460 461 462
            parent = grandparent;
            if (parent == rootNode)
                break;
        }
    }
con's avatar
con committed
463 464 465 466
}

ProjectExplorer::FolderNode *CMakeProject::findOrCreateFolder(CMakeProjectNode *rootNode, QString directory)
{
467 468 469
    FileName path = rootNode->path().parentDir();
    QDir rootParentDir(path.toString());
    QString relativePath = rootParentDir.relativeFilePath(directory);
470
    QStringList parts = relativePath.split(QLatin1Char('/'), QString::SkipEmptyParts);
con's avatar
con committed
471
    ProjectExplorer::FolderNode *parent = rootNode;
hjk's avatar
hjk committed
472
    foreach (const QString &part, parts) {
473
        path.appendPath(part);
con's avatar
con committed
474 475
        // Find folder in subFolders
        bool found = false;
hjk's avatar
hjk committed
476
        foreach (ProjectExplorer::FolderNode *folder, parent->subFolderNodes()) {
477
            if (folder->path() == path) {
con's avatar
con committed
478 479 480 481 482 483 484 485
                // yeah found something :)
                parent = folder;
                found = true;
                break;
            }
        }
        if (!found) {
            // No FolderNode yet, so create it
486
            ProjectExplorer::FolderNode *tmp = new ProjectExplorer::FolderNode(path);
487
            tmp->setDisplayName(part);
488
            parent->addFolderNodes(QList<ProjectExplorer::FolderNode *>() << tmp);
con's avatar
con committed
489 490 491 492 493 494
            parent = tmp;
        }
    }
    return parent;
}

495
QString CMakeProject::displayName() const
con's avatar
con committed
496
{
497
    return m_projectName;
con's avatar
con committed
498 499
}

500
Core::IDocument *CMakeProject::document() const
con's avatar
con committed
501 502 503 504
{
    return m_file;
}

505
IProjectManager *CMakeProject::projectManager() const
con's avatar
con committed
506 507 508 509 510 511 512 513 514 515 516 517
{
    return m_manager;
}

ProjectExplorer::ProjectNode *CMakeProject::rootProjectNode() const
{
    return m_rootNode;
}


QStringList CMakeProject::files(FilesMode fileMode) const
{
518
    Q_UNUSED(fileMode)
con's avatar
con committed
519 520 521
    return m_files;
}

522
Project::RestoreResult CMakeProject::fromMap(const QVariantMap &map, QString *errorMessage)
con's avatar
con committed
523
{
524 525 526
    RestoreResult result = Project::fromMap(map, errorMessage);
    if (result != RestoreResult::Ok)
        return result;
con's avatar
con committed
527

528 529
    bool hasUserFile = activeTarget();
    if (!hasUserFile) {
530
        CMakeOpenProjectWizard copw(Core::ICore::mainWindow(), m_manager, projectDirectory().toString(), Environment::systemEnvironment());
531
        if (copw.exec() != QDialog::Accepted)
532
            return RestoreResult::UserAbort;
533 534 535
        Kit *k = copw.kit();
        Target *t = new Target(this, k);
        CMakeBuildConfiguration *bc(new CMakeBuildConfiguration(t));
536
        bc->setDefaultDisplayName(QLatin1String("all"));
537
        bc->setUseNinja(copw.useNinja());
538
        bc->setBuildDirectory(FileName::fromString(copw.buildDirectory()));
539 540 541 542 543 544 545 546
        ProjectExplorer::BuildStepList *buildSteps = bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
        ProjectExplorer::BuildStepList *cleanSteps = bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_CLEAN);

        // Now create a standard build configuration
        buildSteps->insertStep(0, new MakeStep(buildSteps));

        MakeStep *cleanMakeStep = new MakeStep(cleanSteps);
        cleanSteps->insertStep(0, cleanMakeStep);
547
        cleanMakeStep->setAdditionalArguments(QLatin1String("clean"));
548 549 550 551
        cleanMakeStep->setClean(true);

        t->addBuildConfiguration(bc);

552
        t->updateDefaultDeployConfigurations();
553 554 555 556 557 558

        addTarget(t);
    } else {
        // We have a user file, but we could still be missing the cbp file
        // or simply run createXml with the saved settings
        CMakeBuildConfiguration *activeBC = qobject_cast<CMakeBuildConfiguration *>(activeTarget()->activeBuildConfiguration());
559 560 561 562
        if (!activeBC) {
            *errorMessage = tr("Internal Error: No build configuration found in settings file.");
            return RestoreResult::Error;
        }
563
        QString cbpFile = CMakeManager::findCbpFile(QDir(activeBC->buildDirectory().toString()));
564 565 566 567 568
        QFileInfo cbpFileFi(cbpFile);

        CMakeOpenProjectWizard::Mode mode = CMakeOpenProjectWizard::Nothing;
        if (!cbpFileFi.exists())
            mode = CMakeOpenProjectWizard::NeedToCreate;
569
        else if (cbpFileFi.lastModified() < m_fileName.toFileInfo().lastModified())
570 571 572
            mode = CMakeOpenProjectWizard::NeedToUpdate;

        if (mode != CMakeOpenProjectWizard::Nothing) {
573
            CMakeBuildInfo info(activeBC);
574
            CMakeOpenProjectWizard copw(Core::ICore::mainWindow(), m_manager, mode, &info);
575
            if (copw.exec() != QDialog::Accepted)
576
                return RestoreResult::UserAbort;
577 578 579
            else
                activeBC->setUseNinja(copw.useNinja());
        }
dt's avatar
dt committed
580
    }
581

582
    parseCMakeLists();
583

584 585 586 587 588 589 590 591
    m_activeTarget = activeTarget();
    if (m_activeTarget)
        connect(m_activeTarget, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
                this, SLOT(changeActiveBuildConfiguration(ProjectExplorer::BuildConfiguration*)));

    connect(this, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
            this, SLOT(activeTargetWasChanged(ProjectExplorer::Target*)));

592
    return RestoreResult::Ok;
con's avatar
con committed
593 594
}

595 596
bool CMakeProject::setupTarget(Target *t)
{
597
    t->updateDefaultBuildConfigurations();
598 599
    if (t->buildConfigurations().isEmpty())
        return false;
600
    t->updateDefaultDeployConfigurations();
601 602 603 604

    return true;
}

605
CMakeBuildTarget CMakeProject::buildTargetForTitle(const QString &title)
606
{
tomdeblauwe's avatar
tomdeblauwe committed
607
    foreach (const CMakeBuildTarget &ct, m_buildTargets)
608 609
        if (ct.title == title)
            return ct;
610
    return CMakeBuildTarget();
611 612
}

dt's avatar
dt committed
613 614
QString CMakeProject::uiHeaderFile(const QString &uiFile)
{
615
    QFileInfo fi(uiFile);
616 617
    FileName project = projectDirectory();
    FileName baseDirectory = FileName::fromString(fi.absolutePath());
618 619

    while (baseDirectory.isChildOf(project)) {
620
        FileName cmakeListsTxt = baseDirectory;
621
        cmakeListsTxt.appendPath(QLatin1String("CMakeLists.txt"));
hjk's avatar
hjk committed
622
        if (cmakeListsTxt.exists())
623 624 625
            break;
        QDir dir(baseDirectory.toString());
        dir.cdUp();
626
        baseDirectory = FileName::fromString(dir.absolutePath());
627 628 629 630
    }

    QDir srcDirRoot = QDir(project.toString());
    QString relativePath = srcDirRoot.relativeFilePath(baseDirectory.toString());
631
    QDir buildDir = QDir(activeTarget()->activeBuildConfiguration()->buildDirectory().toString());
dt's avatar
dt committed
632 633 634 635
    QString uiHeaderFilePath = buildDir.absoluteFilePath(relativePath);
    uiHeaderFilePath += QLatin1String("/ui_");
    uiHeaderFilePath += fi.completeBaseName();
    uiHeaderFilePath += QLatin1String(".h");
636

dt's avatar
dt committed
637 638 639
    return QDir::cleanPath(uiHeaderFilePath);
}

640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
void CMakeProject::updateRunConfigurations()
{
    foreach (Target *t, targets())
        updateRunConfigurations(t);
}

// TODO Compare with updateDefaultRunConfigurations();
void CMakeProject::updateRunConfigurations(Target *t)
{
    // *Update* runconfigurations:
    QMultiMap<QString, CMakeRunConfiguration*> existingRunConfigurations;
    QList<ProjectExplorer::RunConfiguration *> toRemove;
    foreach (ProjectExplorer::RunConfiguration *rc, t->runConfigurations()) {
        if (CMakeRunConfiguration* cmakeRC = qobject_cast<CMakeRunConfiguration *>(rc))
            existingRunConfigurations.insert(cmakeRC->title(), cmakeRC);
        QtSupport::CustomExecutableRunConfiguration *ceRC =
                qobject_cast<QtSupport::CustomExecutableRunConfiguration *>(rc);
        if (ceRC && !ceRC->isConfigured())
            toRemove << rc;
    }

    foreach (const CMakeBuildTarget &ct, buildTargets()) {
662
        if (ct.targetType != ExecutableType)
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
            continue;
        if (ct.executable.isEmpty())
            continue;
        QList<CMakeRunConfiguration *> list = existingRunConfigurations.values(ct.title);
        if (!list.isEmpty()) {
            // Already exists, so override the settings...
            foreach (CMakeRunConfiguration *rc, list) {
                rc->setExecutable(ct.executable);
                rc->setBaseWorkingDirectory(ct.workingDirectory);
                rc->setEnabled(true);
            }
            existingRunConfigurations.remove(ct.title);
        } else {
            // Does not exist yet
            Core::Id id = CMakeRunConfigurationFactory::idFromBuildTarget(ct.title);
            CMakeRunConfiguration *rc = new CMakeRunConfiguration(t, id, ct.executable,
                                                                  ct.workingDirectory, ct.title);
            t->addRunConfiguration(rc);
        }
    }
    QMultiMap<QString, CMakeRunConfiguration *>::const_iterator it =
            existingRunConfigurations.constBegin();
    for ( ; it != existingRunConfigurations.constEnd(); ++it) {
        CMakeRunConfiguration *rc = it.value();
        // The executables for those runconfigurations aren't build by the current buildconfiguration
        // We just set a disable flag and show that in the display name
        rc->setEnabled(false);
        // removeRunConfiguration(rc);
    }

    foreach (ProjectExplorer::RunConfiguration *rc, toRemove)
        t->removeRunConfiguration(rc);

    if (t->runConfigurations().isEmpty()) {
        // Oh no, no run configuration,
        // create a custom executable run configuration
        t->addRunConfiguration(new QtSupport::CustomExecutableRunConfiguration(t));
    }
}

703 704 705 706 707 708 709 710
void CMakeProject::updateApplicationAndDeploymentTargets()
{
    Target *t = activeTarget();

    QFile deploymentFile;
    QTextStream deploymentStream;
    QString deploymentPrefix;

711 712 713
    QDir sourceDir(t->project()->projectDirectory().toString());
    QDir buildDir(t->activeBuildConfiguration()->buildDirectory().toString());

714
    deploymentFile.setFileName(sourceDir.filePath(QLatin1String("QtCreatorDeployment.txt")));
715 716 717
    // If we don't have a global QtCreatorDeployment.txt check for one created by the active build configuration
    if (!deploymentFile.exists())
        deploymentFile.setFileName(buildDir.filePath(QLatin1String("QtCreatorDeployment.txt")));
718 719 720 721 722 723 724 725 726
    if (deploymentFile.open(QFile::ReadOnly | QFile::Text)) {
        deploymentStream.setDevice(&deploymentFile);
        deploymentPrefix = deploymentStream.readLine();
        if (!deploymentPrefix.endsWith(QLatin1Char('/')))
            deploymentPrefix.append(QLatin1Char('/'));
    }

    BuildTargetInfoList appTargetList;
    DeploymentData deploymentData;
727

728 729 730 731
    foreach (const CMakeBuildTarget &ct, m_buildTargets) {
        if (ct.executable.isEmpty())
            continue;

732 733 734
        if (ct.targetType == ExecutableType || ct.targetType == DynamicLibraryType)
            deploymentData.addFile(ct.executable, deploymentPrefix + buildDir.relativeFilePath(QFileInfo(ct.executable).dir().path()), DeployableFile::TypeExecutable);
        if (ct.targetType == ExecutableType) {
735
            // TODO: Put a path to corresponding .cbp file into projectFilePath?
736
            appTargetList.list << BuildTargetInfo(ct.title,
737 738
                                                  FileName::fromString(ct.executable),
                                                  FileName::fromString(ct.executable));
739 740 741 742 743 744
        }
    }

    QString absoluteSourcePath = sourceDir.absolutePath();
    if (!absoluteSourcePath.endsWith(QLatin1Char('/')))
        absoluteSourcePath.append(QLatin1Char('/'));
Nikita Baryshnikov's avatar
Nikita Baryshnikov committed
745 746
    if (deploymentStream.device()) {
        while (!deploymentStream.atEnd()) {
Nikita Baryshnikov's avatar
Nikita Baryshnikov committed
747 748 749 750
            QString line = deploymentStream.readLine();
            if (!line.contains(QLatin1Char(':')))
                continue;
            QStringList file = line.split(QLatin1Char(':'));
Nikita Baryshnikov's avatar
Nikita Baryshnikov committed
751 752
            deploymentData.addFile(absoluteSourcePath + file.at(0), deploymentPrefix + file.at(1));
        }
753 754 755 756 757 758
    }

    t->setApplicationTargets(appTargetList);
    t->setDeploymentData(deploymentData);
}

dt's avatar
dt committed
759 760
void CMakeProject::createUiCodeModelSupport()
{
Tobias Hunger's avatar
Tobias Hunger committed
761
    QHash<QString, QString> uiFileHash;
dt's avatar
dt committed
762 763 764

    // Find all ui files
    foreach (const QString &uiFile, m_files) {
Tobias Hunger's avatar
Tobias Hunger committed
765 766
        if (uiFile.endsWith(QLatin1String(".ui")))
            uiFileHash.insert(uiFile, uiHeaderFile(uiFile));
dt's avatar
dt committed
767 768
    }

769
    QtSupport::UiCodeModelManager::update(this, uiFileHash);
dt's avatar
dt committed
770 771
}

772
void CMakeBuildTarget::clear()
dt's avatar
dt committed
773
{
774 775 776 777
    executable.clear();
    makeCommand.clear();
    makeCleanCommand.clear();
    workingDirectory.clear();
778
    sourceDirectory.clear();
779
    title.clear();
780
    targetType = ExecutableType;
781 782 783
    includeFiles.clear();
    compilerOptions.clear();
    defines.clear();
dt's avatar
dt committed
784
}