cmakeproject.cpp 44.8 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
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
12
13
14
** 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.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** 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
con's avatar
con committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

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

#include "cmakebuildconfiguration.h"
con's avatar
con committed
33
34
#include "cmakeprojectconstants.h"
#include "cmakeprojectnodes.h"
hjk's avatar
hjk committed
35
#include "cmakerunconfiguration.h"
36
#include "makestep.h"
37
#include "cmakeopenprojectwizard.h"
hjk's avatar
hjk committed
38

39
#include <projectexplorer/projectexplorerconstants.h>
dt's avatar
dt committed
40
#include <projectexplorer/projectexplorer.h>
41
#include <projectexplorer/headerpath.h>
Tobias Hunger's avatar
Tobias Hunger committed
42
#include <projectexplorer/buildsteplist.h>
dt's avatar
dt committed
43
#include <projectexplorer/buildmanager.h>
Tobias Hunger's avatar
Tobias Hunger committed
44
45
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
46
#include <projectexplorer/toolchain.h>
Tobias Hunger's avatar
Tobias Hunger committed
47
#include <projectexplorer/target.h>
48
#include <projectexplorer/deployconfiguration.h>
49
#include <projectexplorer/projectmacroexpander.h>
Tobias Hunger's avatar
Tobias Hunger committed
50
#include <qtsupport/customexecutablerunconfiguration.h>
51
52
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
53
#include <qtsupport/uicodemodelsupport.h>
54
#include <cpptools/cppmodelmanagerinterface.h>
dt's avatar
dt committed
55
#include <extensionsystem/pluginmanager.h>
hjk's avatar
hjk committed
56
#include <utils/qtcassert.h>
57
#include <utils/stringutils.h>
58
#include <utils/hostosinfo.h>
dt's avatar
dt committed
59
#include <coreplugin/icore.h>
60
#include <coreplugin/infobar.h>
61
#include <coreplugin/documentmanager.h>
dt's avatar
dt committed
62
#include <coreplugin/editormanager/editormanager.h>
63
#include <coreplugin/variablemanager.h>
hjk's avatar
hjk committed
64

65
66
67
68
69
70
71
#include <QMap>
#include <QDebug>
#include <QDir>
#include <QDateTime>
#include <QProcess>
#include <QFormLayout>
#include <QInputDialog>
72
#include <QFileSystemWatcher>
con's avatar
con committed
73
74
75

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

// 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

87
// Test for form editor (loosely coupled)
88
static inline bool isFormWindowDocument(const QObject *o)
89
{
90
    return o && !qstrcmp(o->metaObject()->className(), "Designer::Internal::FormWindowFile");
91
92
93
94
95
96
}

// Return contents of form editor (loosely coupled)
static inline QString formWindowEditorContents(const QObject *editor)
{
    const QVariant contentV = editor->property("contents");
97
    QTC_ASSERT(contentV.isValid(), return QString());
98
99
100
    return contentV.toString();
}

101
102
103
/*!
  \class CMakeProject
*/
con's avatar
con committed
104
CMakeProject::CMakeProject(CMakeManager *manager, const QString &fileName)
105
    : m_manager(manager),
106
      m_activeTarget(0),
107
      m_fileName(fileName),
108
      m_rootNode(new CMakeProjectNode(fileName)),
dt's avatar
dt committed
109
      m_lastEditor(0)
con's avatar
con committed
110
{
111
    setProjectContext(Core::Context(CMakeProjectManager::Constants::PROJECTCONTEXT));
112
    setProjectLanguages(Core::Context(ProjectExplorer::Constants::LANG_CXX));
113

114
115
    m_projectName = QFileInfo(fileName).absoluteDir().dirName();

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

118
119
    connect(this, SIGNAL(buildTargetsChanged()),
            this, SLOT(updateRunConfigurations()));
120
121
122
123
}

CMakeProject::~CMakeProject()
{
dt's avatar
dt committed
124
    // Remove CodeModel support
125
126
    CppTools::CppModelManagerInterface *modelManager
            = CppTools::CppModelManagerInterface::instance();
127
    QMap<QString, QtSupport::UiCodeModelSupport *>::const_iterator it, end;
dt's avatar
dt committed
128
129
130
    it = m_uiCodeModelSupport.constBegin();
    end = m_uiCodeModelSupport.constEnd();
    for (; it!=end; ++it) {
131
        modelManager->removeExtraEditorSupport(it.value());
dt's avatar
dt committed
132
133
134
        delete it.value();
    }

135
    m_codeModelFuture.cancel();
136
137
138
    delete m_rootNode;
}

Tobias Hunger's avatar
Tobias Hunger committed
139
void CMakeProject::fileChanged(const QString &fileName)
dt's avatar
dt committed
140
{
Tobias Hunger's avatar
Tobias Hunger committed
141
    Q_UNUSED(fileName)
dt's avatar
dt committed
142

143
    parseCMakeLists();
144
145
}

Tobias Hunger's avatar
Tobias Hunger committed
146
void CMakeProject::changeActiveBuildConfiguration(ProjectExplorer::BuildConfiguration *bc)
147
{
148
    if (!bc)
Tobias Hunger's avatar
Tobias Hunger committed
149
150
        return;

151
    CMakeBuildConfiguration *cmakebc = static_cast<CMakeBuildConfiguration *>(bc);
152

153
    // Pop up a dialog asking the user to rerun cmake
Tobias Hunger's avatar
Tobias Hunger committed
154
    QString cbpFile = CMakeManager::findCbpFile(QDir(bc->buildDirectory()));
155
    QFileInfo cbpFileFi(cbpFile);
156
157
    CMakeOpenProjectWizard::Mode mode = CMakeOpenProjectWizard::Nothing;
    if (!cbpFileFi.exists()) {
158
        mode = CMakeOpenProjectWizard::NeedToCreate;
159
    } else {
tomdeblauwe's avatar
tomdeblauwe committed
160
        foreach (const QString &file, m_watchedFiles) {
161
            if (QFileInfo(file).lastModified() > cbpFileFi.lastModified()) {
162
163
164
165
166
                mode = CMakeOpenProjectWizard::NeedToUpdate;
                break;
            }
        }
    }
167

168
    if (mode != CMakeOpenProjectWizard::Nothing) {
169
170
171
172
        CMakeOpenProjectWizard copw(m_manager, mode,
                                    CMakeOpenProjectWizard::BuildInfo(cmakebc));
        if (copw.exec() == QDialog::Accepted)
            cmakebc->setUseNinja(copw.useNinja()); // NeedToCreate can change the Ninja setting
173
    }
174

175
    // reparse
176
    parseCMakeLists();
177
178
}

179
void CMakeProject::activeTargetWasChanged(Target *target)
180
{
181
182
183
184
185
186
187
188
    if (m_activeTarget) {
        disconnect(m_activeTarget, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
                   this, SLOT(changeActiveBuildConfiguration(ProjectExplorer::BuildConfiguration*)));
    }

    m_activeTarget = target;

    if (!m_activeTarget)
189
        return;
Tobias Hunger's avatar
Tobias Hunger committed
190

191
192
193
194
    connect(m_activeTarget, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
            this, SLOT(changeActiveBuildConfiguration(ProjectExplorer::BuildConfiguration*)));

    changeActiveBuildConfiguration(m_activeTarget->activeBuildConfiguration());
195
196
}

197
void CMakeProject::changeBuildDirectory(CMakeBuildConfiguration *bc, const QString &newBuildDirectory)
198
{
199
    bc->setBuildDirectory(newBuildDirectory);
200
    parseCMakeLists();
201
202
}

203
QString CMakeProject::shadowBuildDirectory(const QString &projectFilePath, const Kit *k, const QString &bcName)
204
{
205
206
207
208
209
    if (projectFilePath.isEmpty())
        return QString();
    QFileInfo info(projectFilePath);

    const QString projectName = QFileInfo(info.absolutePath()).fileName();
210
    ProjectExplorer::ProjectMacroExpander expander(projectFilePath, projectName, k, bcName);
211
212
213
    QDir projectDir = QDir(projectDirectory(projectFilePath));
    QString buildPath = Utils::expandMacros(Core::DocumentManager::buildDirectory(), &expander);
    return QDir::cleanPath(projectDir.absoluteFilePath(buildPath));
214
215
}

216
bool CMakeProject::parseCMakeLists()
217
{
Tobias Hunger's avatar
Tobias Hunger committed
218
    if (!activeTarget() ||
Tobias Hunger's avatar
Tobias Hunger committed
219
        !activeTarget()->activeBuildConfiguration()) {
220
        return false;
Tobias Hunger's avatar
Tobias Hunger committed
221
    }
Tobias Hunger's avatar
Tobias Hunger committed
222

223
    CMakeBuildConfiguration *activeBC = static_cast<CMakeBuildConfiguration *>(activeTarget()->activeBuildConfiguration());
224
225
226
    foreach (Core::IDocument *document, Core::EditorManager::documentModel()->openedDocuments())
        if (isProjectFile(document->filePath()))
            document->infoBar()->removeInfo(Core::Id("CMakeEditor.RunCMake"));
227

228
    // Find cbp file
dt's avatar
dt committed
229
    QString cbpFile = CMakeManager::findCbpFile(activeBC->buildDirectory());
230

231
232
    if (cbpFile.isEmpty()) {
        emit buildTargetsChanged();
233
        return false;
234
235
    }

236
    // setFolderName
237
    m_rootNode->setDisplayName(QFileInfo(cbpFile).completeBaseName());
238
    CMakeCbpParser cbpparser;
239
240
    // Parsing
    //qDebug()<<"Parsing file "<<cbpFile;
Tobias Hunger's avatar
Tobias Hunger committed
241
242
243
    if (!cbpparser.parseCbpFile(cbpFile)) {
        // TODO report error
        emit buildTargetsChanged();
244
        return false;
Tobias Hunger's avatar
Tobias Hunger committed
245
    }
246

247
248
249
250
    foreach (const QString &file, m_watcher->files())
        if (file != cbpFile)
            m_watcher->removePath(file);

251
    // how can we ensure that it is completely written?
252
253
    m_watcher->addPath(cbpFile);

Tobias Hunger's avatar
Tobias Hunger committed
254
    m_projectName = cbpparser.projectName();
255
    m_rootNode->setDisplayName(cbpparser.projectName());
256

Tobias Hunger's avatar
Tobias Hunger committed
257
258
259
260
261
    //qDebug()<<"Building Tree";
    QList<ProjectExplorer::FileNode *> fileList = cbpparser.fileList();
    QSet<QString> projectFiles;
    if (cbpparser.hasCMakeFiles()) {
        fileList.append(cbpparser.cmakeFileList());
tomdeblauwe's avatar
tomdeblauwe committed
262
        foreach (const ProjectExplorer::FileNode *node, cbpparser.cmakeFileList())
Tobias Hunger's avatar
Tobias Hunger committed
263
264
265
            projectFiles.insert(node->path());
    } else {
        // Manually add the CMakeLists.txt file
266
        QString cmakeListTxt = projectDirectory() + QLatin1String("/CMakeLists.txt");
267
268
        bool generated = false;
        fileList.append(new ProjectExplorer::FileNode(cmakeListTxt, ProjectExplorer::ProjectFileType, generated));
Tobias Hunger's avatar
Tobias Hunger committed
269
270
        projectFiles.insert(cmakeListTxt);
    }
271

Tobias Hunger's avatar
Tobias Hunger committed
272
    m_watchedFiles = projectFiles;
273

Tobias Hunger's avatar
Tobias Hunger committed
274
275
276
277
    m_files.clear();
    foreach (ProjectExplorer::FileNode *fn, fileList)
        m_files.append(fn->path());
    m_files.sort();
con's avatar
con committed
278

Tobias Hunger's avatar
Tobias Hunger committed
279
    buildTree(m_rootNode, fileList);
280

Tobias Hunger's avatar
Tobias Hunger committed
281
282
    //qDebug()<<"Adding Targets";
    m_buildTargets = cbpparser.buildTargets();
dt's avatar
dt committed
283
//        qDebug()<<"Printing targets";
tomdeblauwe's avatar
tomdeblauwe committed
284
//        foreach (CMakeBuildTarget ct, m_buildTargets) {
dt's avatar
dt committed
285
286
287
288
289
//            qDebug()<<ct.title<<" with executable:"<<ct.executable;
//            qDebug()<<"WD:"<<ct.workingDirectory;
//            qDebug()<<ct.makeCommand<<ct.makeCleanCommand;
//            qDebug()<<"";
//        }
dt's avatar
dt committed
290

dt's avatar
dt committed
291
292

    createUiCodeModelSupport();
293

294
295
    Kit *k = activeTarget()->kit();
    ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
Tobias Hunger's avatar
Tobias Hunger committed
296
    if (!tc) {
297
298
299
        emit buildTargetsChanged();
        emit fileListChanged();
        return true;
Tobias Hunger's avatar
Tobias Hunger committed
300
    }
301

302
    QStringList cxxflags;
303
    bool found = false;
304
305
306
307
308
309
310
311
312
313
314
315
316
317
    foreach (const CMakeBuildTarget &buildTarget, m_buildTargets) {
        QString makeCommand = QDir::fromNativeSeparators(buildTarget.makeCommand);
        int startIndex = makeCommand.indexOf(QLatin1Char('\"'));
        int endIndex = makeCommand.indexOf(QLatin1Char('\"'), startIndex + 1);
        if (startIndex == -1 || endIndex == -1)
            continue;
        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);
318
319
320
            QTextStream stream(&file);
            while (!stream.atEnd()) {
                QString line = stream.readLine().trimmed();
321
                if (line.startsWith(QLatin1String("CXX_FLAGS ="))) {
322
323
                    // Skip past =
                    cxxflags = line.mid(11).trimmed().split(QLatin1Char(' '), QString::SkipEmptyParts);
324
325
326
327
328
329
330
331
                    found = true;
                    break;
                }
            }
        }
        if (found)
            break;
    }
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
    // Attempt to find build.ninja file and obtain FLAGS (CXX_FLAGS) from there if no suitable flags.make were
    // found
    if (!found && !cbpparser.buildTargets().isEmpty()) {
        // Get "all" target's working directory
        QString buildNinjaFile = QDir::fromNativeSeparators(cbpparser.buildTargets().at(0).workingDirectory);
        buildNinjaFile += QLatin1String("/build.ninja");
        QFile buildNinja(buildNinjaFile);
        if (buildNinja.exists()) {
            buildNinja.open(QIODevice::ReadOnly | QIODevice::Text);
            QTextStream stream(&buildNinja);
            bool cxxFound = false;
            while (!stream.atEnd()) {
                QString line = stream.readLine().trimmed();
                // Look for a build rule which invokes CXX_COMPILER
                if (line.startsWith(QLatin1String("build"))) {
                    cxxFound = line.indexOf(QLatin1String("CXX_COMPILER")) != -1;
                } else if (cxxFound && line.startsWith(QLatin1String("FLAGS ="))) {
                    // Skip past =
                    cxxflags = line.mid(7).trimmed().split(QLatin1Char(' '), QString::SkipEmptyParts);
                    break;
                }
            }
        }
    }
356

357
358
    CppTools::CppModelManagerInterface *modelmanager =
            CppTools::CppModelManagerInterface::instance();
Tobias Hunger's avatar
Tobias Hunger committed
359
    if (modelmanager) {
360
        CppTools::CppModelManagerInterface::ProjectInfo pinfo = modelmanager->projectInfo(this);
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
        pinfo.clearProjectParts();

        CppTools::ProjectPart::Ptr part(new CppTools::ProjectPart);

        part->evaluateToolchain(tc,
                                cxxflags,
                                cxxflags,
                                SysRootKitInformation::sysRoot(k));

        // This explicitly adds -I. to the include paths
        part->includePaths += projectDirectory();
        part->includePaths += cbpparser.includeFiles();
        part->defines += cbpparser.defines();

        CppTools::ProjectFileAdder adder(part->files);
        foreach (const QString &file, m_files)
            adder.maybeAdd(file);

        pinfo.appendProjectPart(part);
        m_codeModelFuture.cancel();
381
        m_codeModelFuture = modelmanager->updateProjectInfo(pinfo);
382
383

        setProjectLanguage(ProjectExplorer::Constants::LANG_CXX, !part->files.isEmpty());
Tobias Hunger's avatar
Tobias Hunger committed
384
    }
385

386
    emit buildTargetsChanged();
387
    emit fileListChanged();
Tobias Hunger's avatar
Tobias Hunger committed
388

389
    return true;
con's avatar
con committed
390
391
}

392
393
394
395
396
bool CMakeProject::isProjectFile(const QString &fileName)
{
    return m_watchedFiles.contains(fileName);
}

Tobias Hunger's avatar
Tobias Hunger committed
397
398
399
400
401
QList<CMakeBuildTarget> CMakeProject::buildTargets() const
{
    return m_buildTargets;
}

402
QStringList CMakeProject::buildTargetTitles(bool runnable) const
con's avatar
con committed
403
{
404
    QStringList results;
405
    foreach (const CMakeBuildTarget &ct, m_buildTargets) {
406
        if (runnable && (ct.executable.isEmpty() || ct.library))
407
            continue;
408
        results << ct.title;
409
    }
410
    return results;
con's avatar
con committed
411
412
}

413
bool CMakeProject::hasBuildTarget(const QString &title) const
414
{
415
    foreach (const CMakeBuildTarget &ct, m_buildTargets) {
416
417
418
419
420
421
        if (ct.title == title)
            return true;
    }
    return false;
}

422
void CMakeProject::gatherFileNodes(ProjectExplorer::FolderNode *parent, QList<ProjectExplorer::FileNode *> &list)
con's avatar
con committed
423
{
tomdeblauwe's avatar
tomdeblauwe committed
424
    foreach (ProjectExplorer::FolderNode *folder, parent->subFolderNodes())
425
        gatherFileNodes(folder, list);
tomdeblauwe's avatar
tomdeblauwe committed
426
    foreach (ProjectExplorer::FileNode *file, parent->fileNodes())
427
428
429
        list.append(file);
}

430
431
432
433
434
bool sortNodesByPath(Node *a, Node *b)
{
    return a->path() < b->path();
}

435
436
437
438
439
void CMakeProject::buildTree(CMakeProjectNode *rootNode, QList<ProjectExplorer::FileNode *> newList)
{
    // Gather old list
    QList<ProjectExplorer::FileNode *> oldList;
    gatherFileNodes(rootNode, oldList);
440
441
    qSort(oldList.begin(), oldList.end(), sortNodesByPath);
    qSort(newList.begin(), newList.end(), sortNodesByPath);
442
443
444
445
446
447
448
449
450
451

    // generate added and deleted list
    QList<ProjectExplorer::FileNode *>::const_iterator oldIt  = oldList.constBegin();
    QList<ProjectExplorer::FileNode *>::const_iterator oldEnd = oldList.constEnd();
    QList<ProjectExplorer::FileNode *>::const_iterator newIt  = newList.constBegin();
    QList<ProjectExplorer::FileNode *>::const_iterator newEnd = newList.constEnd();

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

tomdeblauwe's avatar
tomdeblauwe committed
452
    while (oldIt != oldEnd && newIt != newEnd) {
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
        if ( (*oldIt)->path() == (*newIt)->path()) {
            delete *newIt;
            ++oldIt;
            ++newIt;
        } else if ((*oldIt)->path() < (*newIt)->path()) {
            deleted.append(*oldIt);
            ++oldIt;
        } else {
            added.append(*newIt);
            ++newIt;
        }
    }

    while (oldIt != oldEnd) {
        deleted.append(*oldIt);
        ++oldIt;
    }

    while (newIt != newEnd) {
        added.append(*newIt);
        ++newIt;
    }

    // add added nodes
    foreach (ProjectExplorer::FileNode *fn, added) {
//        qDebug()<<"added"<<fn->path();
con's avatar
con committed
479
480
481
482
483
        // Get relative path to rootNode
        QString parentDir = QFileInfo(fn->path()).absolutePath();
        ProjectExplorer::FolderNode *folder = findOrCreateFolder(rootNode, parentDir);
        rootNode->addFileNodes(QList<ProjectExplorer::FileNode *>()<< fn, folder);
    }
484

Tobias Hunger's avatar
Tobias Hunger committed
485
    // remove old file nodes and check whether folder nodes can be removed
486
487
488
489
490
491
492
493
494
495
496
497
498
    foreach (ProjectExplorer::FileNode *fn, deleted) {
        ProjectExplorer::FolderNode *parent = fn->parentFolderNode();
//        qDebug()<<"removed"<<fn->path();
        rootNode->removeFileNodes(QList<ProjectExplorer::FileNode *>() << fn, parent);
        // Check for empty parent
        while (parent->subFolderNodes().isEmpty() && parent->fileNodes().isEmpty()) {
            ProjectExplorer::FolderNode *grandparent = parent->parentFolderNode();
            rootNode->removeFolderNodes(QList<ProjectExplorer::FolderNode *>() << parent, grandparent);
            parent = grandparent;
            if (parent == rootNode)
                break;
        }
    }
con's avatar
con committed
499
500
501
502
503
}

ProjectExplorer::FolderNode *CMakeProject::findOrCreateFolder(CMakeProjectNode *rootNode, QString directory)
{
    QString relativePath = QDir(QFileInfo(rootNode->path()).path()).relativeFilePath(directory);
504
    QStringList parts = relativePath.split(QLatin1Char('/'), QString::SkipEmptyParts);
con's avatar
con committed
505
    ProjectExplorer::FolderNode *parent = rootNode;
506
    QString path = QFileInfo(rootNode->path()).path();
hjk's avatar
hjk committed
507
    foreach (const QString &part, parts) {
508
509
        path += QLatin1Char('/');
        path += part;
con's avatar
con committed
510
511
        // Find folder in subFolders
        bool found = false;
hjk's avatar
hjk committed
512
        foreach (ProjectExplorer::FolderNode *folder, parent->subFolderNodes()) {
513
            if (folder->path() == path) {
con's avatar
con committed
514
515
516
517
518
519
520
521
                // yeah found something :)
                parent = folder;
                found = true;
                break;
            }
        }
        if (!found) {
            // No FolderNode yet, so create it
522
            ProjectExplorer::FolderNode *tmp = new ProjectExplorer::FolderNode(path);
523
            tmp->setDisplayName(part);
con's avatar
con committed
524
525
526
527
528
529
530
            rootNode->addFolderNodes(QList<ProjectExplorer::FolderNode *>() << tmp, parent);
            parent = tmp;
        }
    }
    return parent;
}

531
QString CMakeProject::displayName() const
con's avatar
con committed
532
{
533
    return m_projectName;
con's avatar
con committed
534
535
}

536
Core::Id CMakeProject::id() const
Tobias Hunger's avatar
Tobias Hunger committed
537
{
538
    return Core::Id(Constants::CMAKEPROJECT_ID);
Tobias Hunger's avatar
Tobias Hunger committed
539
540
}

541
Core::IDocument *CMakeProject::document() const
con's avatar
con committed
542
543
544
545
{
    return m_file;
}

546
CMakeManager *CMakeProject::projectManager() const
con's avatar
con committed
547
548
549
550
551
552
553
554
555
556
557
558
{
    return m_manager;
}

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


QStringList CMakeProject::files(FilesMode fileMode) const
{
559
    Q_UNUSED(fileMode)
con's avatar
con committed
560
561
562
    return m_files;
}

563
bool CMakeProject::fromMap(const QVariantMap &map)
con's avatar
con committed
564
{
565
566
    if (!Project::fromMap(map))
        return false;
con's avatar
con committed
567

568
569
570
    bool hasUserFile = activeTarget();
    if (!hasUserFile) {
        CMakeOpenProjectWizard copw(m_manager, projectDirectory(), Utils::Environment::systemEnvironment());
571
572
        if (copw.exec() != QDialog::Accepted)
            return false;
573
574
575
        Kit *k = copw.kit();
        Target *t = new Target(this, k);
        CMakeBuildConfiguration *bc(new CMakeBuildConfiguration(t));
576
        bc->setDefaultDisplayName(QLatin1String("all"));
577
578
579
580
581
582
583
584
585
586
        bc->setUseNinja(copw.useNinja());
        bc->setBuildDirectory(copw.buildDirectory());
        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);
587
        cleanMakeStep->setAdditionalArguments(QLatin1String("clean"));
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
        cleanMakeStep->setClean(true);

        t->addBuildConfiguration(bc);

        DeployConfigurationFactory *fac = ExtensionSystem::PluginManager::instance()->getObject<DeployConfigurationFactory>();
        ProjectExplorer::DeployConfiguration *dc = fac->create(t, ProjectExplorer::Constants::DEFAULT_DEPLOYCONFIGURATION_ID);
        t->addDeployConfiguration(dc);

        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
        QFileInfo sourceFileInfo(m_fileName);
        CMakeBuildConfiguration *activeBC = qobject_cast<CMakeBuildConfiguration *>(activeTarget()->activeBuildConfiguration());
        if (!activeBC)
            return false;
        QString cbpFile = CMakeManager::findCbpFile(QDir(activeBC->buildDirectory()));
        QFileInfo cbpFileFi(cbpFile);

        CMakeOpenProjectWizard::Mode mode = CMakeOpenProjectWizard::Nothing;
        if (!cbpFileFi.exists())
            mode = CMakeOpenProjectWizard::NeedToCreate;
        else if (cbpFileFi.lastModified() < sourceFileInfo.lastModified())
            mode = CMakeOpenProjectWizard::NeedToUpdate;

        if (mode != CMakeOpenProjectWizard::Nothing) {
            CMakeOpenProjectWizard copw(m_manager, mode,
                                        CMakeOpenProjectWizard::BuildInfo(activeBC));
            if (copw.exec() != QDialog::Accepted)
                return false;
            else
                activeBC->setUseNinja(copw.useNinja());
        }
dt's avatar
dt committed
621
    }
622

623
    m_watcher = new QFileSystemWatcher(this);
624
    connect(m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(fileChanged(QString)));
Tobias Hunger's avatar
Tobias Hunger committed
625

626
    parseCMakeLists();
627

628
    if (!hasUserFile && hasBuildTarget(QLatin1String("all"))) {
629
        MakeStep *makeStep = qobject_cast<MakeStep *>(
Tobias Hunger's avatar
Tobias Hunger committed
630
                    activeTarget()->activeBuildConfiguration()->stepList(ProjectExplorer::Constants::BUILDSTEPS_BUILD)->at(0));
Tobias Hunger's avatar
Tobias Hunger committed
631
        Q_ASSERT(makeStep);
632
        makeStep->setBuildTarget(QLatin1String("all"), true);
Tobias Hunger's avatar
Tobias Hunger committed
633
    }
634

dt's avatar
dt committed
635
636
637
638
639
640
641
642
643
    connect(Core::EditorManager::instance(), SIGNAL(editorAboutToClose(Core::IEditor*)),
            this, SLOT(editorAboutToClose(Core::IEditor*)));

    connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
            this, SLOT(editorChanged(Core::IEditor*)));

    connect(ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
            this, SLOT(buildStateChanged(ProjectExplorer::Project*)));

644
645
646
647
648
649
650
651
    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*)));

dt's avatar
dt committed
652
    return true;
con's avatar
con committed
653
654
}

655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
bool CMakeProject::setupTarget(Target *t)
{
    CMakeBuildConfigurationFactory *factory
            = ExtensionSystem::PluginManager::instance()->getObject<CMakeBuildConfigurationFactory>();
    CMakeBuildConfiguration *bc = factory->create(t, Constants::CMAKE_BC_ID, QLatin1String("all"));
    if (!bc)
        return false;

    t->addBuildConfiguration(bc);

    DeployConfigurationFactory *fac = ExtensionSystem::PluginManager::instance()->getObject<DeployConfigurationFactory>();
    ProjectExplorer::DeployConfiguration *dc = fac->create(t, ProjectExplorer::Constants::DEFAULT_DEPLOYCONFIGURATION_ID);
    t->addDeployConfiguration(dc);
    return true;
}

671
CMakeBuildTarget CMakeProject::buildTargetForTitle(const QString &title)
672
{
tomdeblauwe's avatar
tomdeblauwe committed
673
    foreach (const CMakeBuildTarget &ct, m_buildTargets)
674
675
        if (ct.title == title)
            return ct;
676
    return CMakeBuildTarget();
677
678
}

dt's avatar
dt committed
679
680
QString CMakeProject::uiHeaderFile(const QString &uiFile)
{
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
    QFileInfo fi(uiFile);
    Utils::FileName project = Utils::FileName::fromString(projectDirectory());
    Utils::FileName baseDirectory = Utils::FileName::fromString(fi.absolutePath());

    while (baseDirectory.isChildOf(project)) {
        Utils::FileName cmakeListsTxt = baseDirectory;
        cmakeListsTxt.appendPath(QLatin1String("CMakeLists.txt"));
        if (cmakeListsTxt.toFileInfo().exists())
            break;
        QDir dir(baseDirectory.toString());
        dir.cdUp();
        baseDirectory = Utils::FileName::fromString(dir.absolutePath());
    }

    QDir srcDirRoot = QDir(project.toString());
    QString relativePath = srcDirRoot.relativeFilePath(baseDirectory.toString());
dt's avatar
dt committed
697
698
699
700
701
    QDir buildDir = QDir(activeTarget()->activeBuildConfiguration()->buildDirectory());
    QString uiHeaderFilePath = buildDir.absoluteFilePath(relativePath);
    uiHeaderFilePath += QLatin1String("/ui_");
    uiHeaderFilePath += fi.completeBaseName();
    uiHeaderFilePath += QLatin1String(".h");
702

dt's avatar
dt committed
703
704
705
    return QDir::cleanPath(uiHeaderFilePath);
}

706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
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()) {
        if (ct.library)
            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));
    }
}

dt's avatar
dt committed
769
770
771
void CMakeProject::createUiCodeModelSupport()
{
//    qDebug()<<"creatUiCodeModelSupport()";
772
773
    CppTools::CppModelManagerInterface *modelManager
            = CppTools::CppModelManagerInterface::instance();
dt's avatar
dt committed
774
775

    // First move all to
776
    QMap<QString, QtSupport::UiCodeModelSupport *> oldCodeModelSupport;
dt's avatar
dt committed
777
778
779
780
781
    oldCodeModelSupport = m_uiCodeModelSupport;
    m_uiCodeModelSupport.clear();

    // Find all ui files
    foreach (const QString &uiFile, m_files) {
782
        if (uiFile.endsWith(QLatin1String(".ui"))) {
dt's avatar
dt committed
783
784
            // UI file, not convert to
            QString uiHeaderFilePath = uiHeaderFile(uiFile);
785
            QMap<QString, QtSupport::UiCodeModelSupport *>::iterator it
dt's avatar
dt committed
786
787
788
                    = oldCodeModelSupport.find(uiFile);
            if (it != oldCodeModelSupport.end()) {
                //                qDebug()<<"updated old codemodelsupport";
789
                QtSupport::UiCodeModelSupport *cms = it.value();
dt's avatar
dt committed
790
791
792
793
794
                cms->setFileName(uiHeaderFilePath);
                m_uiCodeModelSupport.insert(it.key(), cms);
                oldCodeModelSupport.erase(it);
            } else {
                //                qDebug()<<"adding new codemodelsupport";
795
                QtSupport::UiCodeModelSupport *cms = new QtSupport::UiCodeModelSupport(modelManager, this, uiFile, uiHeaderFilePath);
dt's avatar
dt committed
796
                m_uiCodeModelSupport.insert(uiFile, cms);
797
                modelManager->addExtraEditorSupport(cms);
dt's avatar
dt committed
798
799
800
801
802
            }
        }
    }

    // Remove old
803
    QMap<QString, QtSupport::UiCodeModelSupport *>::const_iterator it, end;
dt's avatar
dt committed
804
805
    end = oldCodeModelSupport.constEnd();
    for (it = oldCodeModelSupport.constBegin(); it!=end; ++it) {
806
        modelManager->removeExtraEditorSupport(it.value());
dt's avatar
dt committed
807
808
809
810
811
812
813
        delete it.value();
    }
}

void CMakeProject::updateCodeModelSupportFromEditor(const QString &uiFileName,
                                                    const QString &contents)
{
814
    const QMap<QString, QtSupport::UiCodeModelSupport *>::const_iterator it =
dt's avatar
dt committed
815
816
817
818
819
820
821
822
            m_uiCodeModelSupport.constFind(uiFileName);
    if (it != m_uiCodeModelSupport.constEnd())
        it.value()->updateFromEditor(contents);
}

void CMakeProject::editorChanged(Core::IEditor *editor)
{
    // Handle old editor
823
824
    if (m_lastEditor && isFormWindowDocument(m_lastEditor->document())) {
        disconnect(m_lastEditor->document(), SIGNAL(changed()), this, SLOT(uiDocumentContentsChanged()));
dt's avatar
dt committed
825
        if (m_dirtyUic) {
826
            const QString contents =  formWindowEditorContents(m_lastEditor);
827
            updateCodeModelSupportFromEditor(m_lastEditor->document()->filePath(), contents);
dt's avatar
dt committed
828
829
830
831
832
833
834
            m_dirtyUic = false;
        }
    }

    m_lastEditor = editor;

    // Handle new editor
835
836
    if (editor && isFormWindowDocument(editor->document()))
        connect(editor->document(), SIGNAL(changed()), this, SLOT(uiDocumentContentsChanged()));
dt's avatar
dt committed
837
838
839
840
841
842
843
}

void CMakeProject::editorAboutToClose(Core::IEditor *editor)
{
    if (m_lastEditor == editor) {
        // Oh no our editor is going to be closed
        // get the content first
844
845
        if (isFormWindowDocument(m_lastEditor->document())) {
            disconnect(m_lastEditor->document(), SIGNAL(changed()), this, SLOT(uiDocumentContentsChanged()));
dt's avatar
dt committed
846
            if (m_dirtyUic) {
847
                const QString contents = formWindowEditorContents(m_lastEditor);
848
                updateCodeModelSupportFromEditor(m_lastEditor->document()->filePath(), contents);
dt's avatar
dt committed
849
850
851
852
853
854
855
                m_dirtyUic = false;
            }
        }
        m_lastEditor = 0;
    }
}

856
void CMakeProject::uiDocumentContentsChanged()
dt's avatar
dt committed
857
858
{
    // cast sender, get filename
859
    if (!m_dirtyUic && isFormWindowDocument(sender()))
860
        m_dirtyUic = true;
dt's avatar
dt committed
861
862
863
864
865
866
}

void CMakeProject::buildStateChanged(ProjectExplorer::Project *project)
{
    if (project == this) {
        if (!ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager()->isBuilding(this)) {
867
            QMap<QString, QtSupport::UiCodeModelSupport *>::const_iterator it, end;
dt's avatar
dt committed
868
869
870
871
872
873
874
875
            end = m_uiCodeModelSupport.constEnd();
            for (it = m_uiCodeModelSupport.constBegin(); it != end; ++it) {
                it.value()->updateFromBuild();
            }
        }
    }
}

876
877
// CMakeFile

con's avatar
con committed
878
CMakeFile::CMakeFile(CMakeProject *parent, QString fileName)
879
    : Core::IDocument(parent), m_project(parent)
con's avatar
con committed
880
{
881
    setFilePath(fileName);
con's avatar
con committed
882
883
}

884
bool CMakeFile::save(QString *errorString, const QString &fileName, bool autoSave)
con's avatar
con committed
885
886
887
{
    // Once we have an texteditor open for this file, we probably do
    // need to implement this, don't we.
888
    Q_UNUSED(errorString)
889
    Q_UNUSED(fileName)
890
    Q_UNUSED(autoSave)
con's avatar
con committed
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
    return false;
}

QString CMakeFile::defaultPath() const
{
    return QString();
}

QString CMakeFile::suggestedFileName() const
{
    return QString();
}

QString CMakeFile::mimeType() const
{
906
    return QLatin1String(Constants::CMAKEMIMETYPE);
con's avatar
con committed
907
908
909
910
911
912
913
914
915
916
917
918
919
}


bool CMakeFile::isModified() const
{
    return false;
}

bool CMakeFile::isSaveAsAllowed() const
{
    return false;
}

920
Core::IDocument::ReloadBehavior CMakeFile::reloadBehavior(ChangeTrigger state, ChangeType type) const
con's avatar
con committed
921
{
922
923
924
925
926
    Q_UNUSED(state)
    Q_UNUSED(type)
    return BehaviorSilent;
}

927
bool CMakeFile::reload(QString *errorString, ReloadFlag flag, ChangeType type)
928
{
929
    Q_UNUSED(errorString)
930
931
    Q_UNUSED(flag)
    Q_UNUSED(type)
932
    return true;
con's avatar
con committed
933
934
}

935
CMakeBuildSettingsWidget::CMakeBuildSettingsWidget(CMakeBuildConfiguration *bc) : m_buildConfiguration(0)
con's avatar
con committed
936
{
937
    QFormLayout *fl = new QFormLayout(this);
938
    fl->setContentsMargins(20, -1, 0, -1);
939
    fl->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
940
    setLayout(fl);
941

942
    QPushButton *runCmakeButton = new QPushButton(tr("Run cmake"));
943
944
945
946
    connect(runCmakeButton, SIGNAL(clicked()),
            this, SLOT(runCMake()));
    fl->addRow(tr("Reconfigure project:"), runCmakeButton);

947
948
949
950
951
952
953
954
955
956
957
    m_pathLineEdit = new QLineEdit(this);
    m_pathLineEdit->setReadOnly(true);

    QHBoxLayout *hbox = new QHBoxLayout();
    hbox->addWidget(m_pathLineEdit);

    m_changeButton = new QPushButton(this);
    m_changeButton->setText(tr("&Change"));
    connect(m_changeButton, SIGNAL(clicked()), this, SLOT(openChangeBuildDirectoryDialog()));
    hbox->addWidget(m_changeButton);

958
    fl->addRow(tr("Build directory:"), hbox);
con's avatar
con committed
959

960
    m_buildConfiguration = bc;
961
    m_pathLineEdit->setText(m_buildConfiguration->buildDirectory());
Tobias Hunger's avatar
Tobias Hunger committed
962
    if (m_buildConfiguration->buildDirectory() == bc->target()->project()->projectDirectory())
963
964
        m_changeButton->setEnabled(false);
    else
965
        m_changeButton->setEnabled(true);
966

967
    setDisplayName(tr("CMake"));
968
969
}

970
void CMakeBuildSettingsWidget::openChangeBuildDirectoryDialog()
971
{
972
    CMakeProject *project = static_cast<CMakeProject *>(m_buildConfiguration->target()->project());
973
974
    CMakeOpenProjectWizard copw(project->projectManager(), CMakeOpenProjectWizard::ChangeDirectory,
                                CMakeOpenProjectWizard::BuildInfo(m_buildConfiguration));
975
    if (copw.exec() == QDialog::Accepted) {
976
        project->changeBuildDirectory(m_buildConfiguration, copw.buildDirectory());
977
        m_buildConfiguration->setUseNinja(copw.useNinja());
978
        m_pathLineEdit->setText(m_buildConfiguration->buildDirectory());
979