cmakeproject.cpp 33.6 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
9
** Commercial Usage
10
**
11
12
13
14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18
19
20
21
22
23
** 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.
24
**
25
** If you are unsure which license is appropriate for your use, please
26
** contact the sales department at http://www.qtsoftware.com/contact.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
31
32
#include "cmakeproject.h"
#include "cmakeprojectconstants.h"
#include "cmakeprojectnodes.h"
hjk's avatar
hjk committed
33
#include "cmakerunconfiguration.h"
34
#include "makestep.h"
35
#include "cmakeopenprojectwizard.h"
36
#include "cmakebuildenvironmentwidget.h"
hjk's avatar
hjk committed
37

38
#include <projectexplorer/projectexplorerconstants.h>
con's avatar
con committed
39
#include <cpptools/cppmodelmanagerinterface.h>
dt's avatar
dt committed
40
#include <extensionsystem/pluginmanager.h>
hjk's avatar
hjk committed
41
#include <utils/qtcassert.h>
dt's avatar
dt committed
42
#include <coreplugin/icore.h>
hjk's avatar
hjk committed
43

dt's avatar
dt committed
44
#include <QtCore/QMap>
con's avatar
con committed
45
#include <QtCore/QDebug>
hjk's avatar
hjk committed
46
#include <QtCore/QDir>
dt's avatar
dt committed
47
#include <QtCore/QDateTime>
hjk's avatar
hjk committed
48
#include <QtCore/QProcess>
49
#include <QtGui/QFormLayout>
dt's avatar
dt committed
50
#include <QtGui/QMainWindow>
con's avatar
con committed
51
52
53

using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;
54
55
using ProjectExplorer::Environment;
using ProjectExplorer::EnvironmentItem;
56
57
58
59
60
61
62
63
64
65
66

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


con's avatar
con committed
67
CMakeProject::CMakeProject(CMakeManager *manager, const QString &fileName)
68
69
70
    : m_manager(manager),
      m_fileName(fileName),
      m_rootNode(new CMakeProjectNode(m_fileName)),
71
72
      m_toolChain(0),
      m_insideFileChanged(false)
con's avatar
con committed
73
74
{
    m_file = new CMakeFile(this, fileName);
75
76
77
78
79
}

CMakeProject::~CMakeProject()
{
    delete m_rootNode;
80
    delete m_toolChain;
81
82
}

83
84
85
86
87
88
89
90
91
void CMakeProject::slotActiveBuildConfiguration()
{
    // Pop up a dialog asking the user to rerun cmake
    QFileInfo sourceFileInfo(m_fileName);
    QStringList needToCreate;
    QStringList needToUpdate;

    QString cbpFile = CMakeManager::findCbpFile(QDir(buildDirectory(activeBuildConfiguration())));
    QFileInfo cbpFileFi(cbpFile);
92
    CMakeOpenProjectWizard::Mode mode;
93
    if (!cbpFileFi.exists())
94
        mode = CMakeOpenProjectWizard::NeedToCreate;
95
    else if (cbpFileFi.lastModified() < sourceFileInfo.lastModified())
96
97
98
        mode = CMakeOpenProjectWizard::NeedToUpdate;
    else
        mode = CMakeOpenProjectWizard::Nothing;
99

100
    if (mode != CMakeOpenProjectWizard::Nothing) {
101
102
103
104
105
        CMakeOpenProjectWizard copw(m_manager,
                                    sourceFileInfo.absolutePath(),
                                    buildDirectory(activeBuildConfiguration()),
                                    mode,
                                    environment(activeBuildConfiguration()));
106
        copw.exec();
dt's avatar
dt committed
107
        setValue(activeBuildConfiguration(), "msvcVersion", copw.msvcVersion());
108
109
110
111
112
    }
    // reparse
    parseCMakeLists();
}

113
114
115
116
117
118
119
void CMakeProject::fileChanged(const QString &fileName)
{
    if (m_insideFileChanged== true)
        return;
    m_insideFileChanged = true;
    if (fileName == m_fileName) {
        // Oh we have changed...
120
        slotActiveBuildConfiguration();
121
122
123
124
125
126
127
128
129
    }
    m_insideFileChanged = false;
}

void CMakeProject::updateToolChain(const QString &compiler)
{
    //qDebug()<<"CodeBlocks Compilername"<<compiler
    ProjectExplorer::ToolChain *newToolChain = 0;
    if (compiler == "gcc") {
130
131
132
#ifdef Q_OS_WIN
        newToolChain = ProjectExplorer::ToolChain::createMinGWToolChain("gcc", QString());
#else
133
        newToolChain = ProjectExplorer::ToolChain::createGccToolChain("gcc");
134
#endif
135
    } else if (compiler == "msvc8") {
136
        // TODO MSVC toolchain
dt's avatar
dt committed
137
        newToolChain = ProjectExplorer::ToolChain::createMSVCToolChain(value(activeBuildConfiguration(), "msvcVersion").toString(), false);
138
    } else {
139
        // TODO other toolchains
140
141
142
143
144
145
146
147
148
149
150
151
        qDebug()<<"Not implemented yet!!! Qt Creator doesn't know which toolchain to use for"<<compiler;
    }

    if (ProjectExplorer::ToolChain::equals(newToolChain, m_toolChain)) {
        delete newToolChain;
        newToolChain = 0;
    } else {
        delete m_toolChain;
        m_toolChain = newToolChain;
    }
}

dt's avatar
dt committed
152
153
154
155
156
157
158
ProjectExplorer::ToolChain *CMakeProject::toolChain(const QString &buildConfiguration) const
{
    if (buildConfiguration != activeBuildConfiguration())
        qWarning()<<"CMakeProject asked for toolchain of a not active buildconfiguration";
    return m_toolChain;
}

159
160
161
162
163
164
165
166
167
168
169
void CMakeProject::changeBuildDirectory(const QString &buildConfiguration, const QString &newBuildDirectory)
{
    setValue(buildConfiguration, "buildDirectory", newBuildDirectory);
    parseCMakeLists();
}

QString CMakeProject::sourceDirectory() const
{
    return QFileInfo(m_fileName).absolutePath();
}

dt's avatar
dt committed
170
bool CMakeProject::parseCMakeLists()
171
{
172
    // Find cbp file
173
    QString cbpFile = CMakeManager::findCbpFile(buildDirectory(activeBuildConfiguration()));
174
175

    // setFolderName
176
    m_rootNode->setFolderName(QFileInfo(cbpFile).completeBaseName());
177
    CMakeCbpParser cbpparser;
178
179
180
181
182
    // Parsing
    //qDebug()<<"Parsing file "<<cbpFile;
    if (cbpparser.parseCbpFile(cbpFile)) {        
        // ToolChain
        updateToolChain(cbpparser.compilerName());
183

184
        m_projectName = cbpparser.projectName();
dt's avatar
dt committed
185
        m_rootNode->setFolderName(cbpparser.projectName());
186

187
188
        //qDebug()<<"Building Tree";

dt's avatar
dt committed
189

190
        QList<ProjectExplorer::FileNode *> fileList = cbpparser.fileList();
dt's avatar
dt committed
191
192
193
194
195
196
197

        if (cbpparser.hasCMakeFiles()) {
            fileList.append(cbpparser.cmakeFileList());
        } else {
            // Manually add the CMakeLists.txt file
            fileList.append(new ProjectExplorer::FileNode(sourceDirectory() + "/CMakeLists.txt", ProjectExplorer::ProjectFileType, false));
        }
198

dt's avatar
dt committed
199
        m_files.clear();
200
        foreach (ProjectExplorer::FileNode *fn, fileList)
con's avatar
con committed
201
202
203
            m_files.append(fn->path());
        m_files.sort();

204
205
206
207
        buildTree(m_rootNode, fileList);


        //qDebug()<<"Adding Targets";
dt's avatar
dt committed
208
        m_targets = cbpparser.targets();
dt's avatar
dt committed
209
210
211
212
213
214
215
//        qDebug()<<"Printing targets";
//        foreach(CMakeTarget ct, m_targets) {
//            qDebug()<<ct.title<<" with executable:"<<ct.executable;
//            qDebug()<<"WD:"<<ct.workingDirectory;
//            qDebug()<<ct.makeCommand<<ct.makeCleanCommand;
//            qDebug()<<"";
//        }
dt's avatar
dt committed
216

217
        //qDebug()<<"Updating CodeModel";
218
219
220
221
222
223
224
225
226
227

        QStringList allIncludePaths;
        QStringList allFrameworkPaths;
        QList<ProjectExplorer::HeaderPath> allHeaderPaths = m_toolChain->systemHeaderPaths();
        foreach (ProjectExplorer::HeaderPath headerPath, allHeaderPaths) {
            if (headerPath.kind() == ProjectExplorer::HeaderPath::FrameworkHeaderPath)
                allFrameworkPaths.append(headerPath.path());
            else
                allIncludePaths.append(headerPath.path());
        }
228
        // This explicitly adds -I. to the include paths
229
        allIncludePaths.append(sourceDirectory());
230

231
        allIncludePaths.append(cbpparser.includeFiles());
con's avatar
con committed
232
233
        CppTools::CppModelManagerInterface *modelmanager = ExtensionSystem::PluginManager::instance()->getObject<CppTools::CppModelManagerInterface>();
        if (modelmanager) {
234
            CppTools::CppModelManagerInterface::ProjectInfo pinfo = modelmanager->projectInfo(this);
235
236
237
238
239
240
241
242
243
244
245
246
            if (pinfo.includePaths != allIncludePaths
                || pinfo.sourceFiles != m_files
                || pinfo.defines != m_toolChain->predefinedMacros()
                || pinfo.frameworkPaths != allFrameworkPaths)  {
                pinfo.includePaths = allIncludePaths;
                // TODO we only want C++ files, not all other stuff that might be in the project
                pinfo.sourceFiles = m_files;
                pinfo.defines = m_toolChain->predefinedMacros(); // TODO this is to simplistic
                pinfo.frameworkPaths = allFrameworkPaths;
                modelmanager->updateProjectInfo(pinfo);
                modelmanager->updateSourceFiles(pinfo.sourceFiles);
            }
con's avatar
con committed
247
        }
dt's avatar
dt committed
248
249

        // Create run configurations for m_targets
250
        //qDebug()<<"Create run configurations of m_targets";
251
        QMultiMap<QString, QSharedPointer<CMakeRunConfiguration> > existingRunConfigurations;
dt's avatar
dt committed
252
253
254
255
256
257
        foreach(QSharedPointer<ProjectExplorer::RunConfiguration> cmakeRunConfiguration, runConfigurations()) {
            if (QSharedPointer<CMakeRunConfiguration> rc = cmakeRunConfiguration.dynamicCast<CMakeRunConfiguration>()) {
                existingRunConfigurations.insert(rc->title(), rc);
            }
        }

258
        bool setActive = existingRunConfigurations.isEmpty();
dt's avatar
dt committed
259
260
261
262
263
        foreach(const CMakeTarget &ct, m_targets) {
            if (ct.executable.isEmpty())
                continue;
            if (ct.title.endsWith("/fast"))
                continue;
264
265
            QList<QSharedPointer<CMakeRunConfiguration> > list = existingRunConfigurations.values(ct.title);
            if (!list.isEmpty()) {
dt's avatar
dt committed
266
                // Already exists, so override the settings...
267
268
269
270
271
272
273
274
                foreach (QSharedPointer<CMakeRunConfiguration> rc, list) {
                    //qDebug()<<"Updating Run Configuration with title"<<ct.title;
                    //qDebug()<<"  Executable new:"<<ct.executable<< "old:"<<rc->executable();
                    //qDebug()<<"  WD new:"<<ct.workingDirectory<<"old:"<<rc->workingDirectory();
                    rc->setExecutable(ct.executable);
                    rc->setWorkingDirectory(ct.workingDirectory);
                }
                existingRunConfigurations.remove(ct.title);
dt's avatar
dt committed
275
276
            } else {
                // Does not exist yet
277
278
                //qDebug()<<"Adding new run configuration with title"<<ct.title;
                //qDebug()<<"  Executable:"<<ct.executable<<"WD:"<<ct.workingDirectory;
dt's avatar
dt committed
279
280
281
                QSharedPointer<ProjectExplorer::RunConfiguration> rc(new CMakeRunConfiguration(this, ct.executable, ct.workingDirectory, ct.title));
                addRunConfiguration(rc);
                // The first one gets the honour of beeing the active one
282
                if (setActive) {
dt's avatar
dt committed
283
                    setActiveRunConfiguration(rc);
284
                    setActive = false;
dt's avatar
dt committed
285
286
287
                }
            }
        }
288
        QMultiMap<QString, QSharedPointer<CMakeRunConfiguration> >::const_iterator it =
dt's avatar
dt committed
289
290
291
                existingRunConfigurations.constBegin();
        for( ; it != existingRunConfigurations.constEnd(); ++it) {
            QSharedPointer<CMakeRunConfiguration> rc = it.value();
292
293
            //qDebug()<<"Removing old RunConfiguration with title:"<<rc->title();
            //qDebug()<<"  Executable:"<<rc->executable()<<rc->workingDirectory();
dt's avatar
dt committed
294
295
            removeRunConfiguration(rc);
        }
296
        //qDebug()<<"\n";
con's avatar
con committed
297
298
    } else {
        // TODO report error
dt's avatar
dt committed
299
        qDebug()<<"Parsing failed";
300
301
        delete m_toolChain;
        m_toolChain = 0;
dt's avatar
dt committed
302
        return false;
con's avatar
con committed
303
    }
dt's avatar
dt committed
304
    return true;
con's avatar
con committed
305
306
}

307
308
QString CMakeProject::buildParser(const QString &buildConfiguration) const
{
309
    Q_UNUSED(buildConfiguration)
310
311
    // TODO this is actually slightly wrong, but do i care?
    // this should call toolchain(buildConfiguration)
312
313
314
315
316
317
318
319
320
321
322
323
324
    if (!m_toolChain)
        return QString::null;
    if (m_toolChain->type() == ProjectExplorer::ToolChain::GCC
        || m_toolChain->type() == ProjectExplorer::ToolChain::LinuxICC
        || m_toolChain->type() == ProjectExplorer::ToolChain::MinGW) {
        return ProjectExplorer::Constants::BUILD_PARSER_GCC;
    } else if (m_toolChain->type() == ProjectExplorer::ToolChain::MSVC
               || m_toolChain->type() == ProjectExplorer::ToolChain::WINCE) {
        return ProjectExplorer::Constants::BUILD_PARSER_MSVC;
    }
    return QString::null;
}

325
QStringList CMakeProject::targets() const
con's avatar
con committed
326
{
327
    QStringList results;
328
329
330
331
332
    foreach (const CMakeTarget &ct, m_targets) {
        if (ct.executable.isEmpty())
            continue;
        if (ct.title.endsWith("/fast"))
            continue;
333
        results << ct.title;
334
    }
335
    return results;
con's avatar
con committed
336
337
}

338
void CMakeProject::gatherFileNodes(ProjectExplorer::FolderNode *parent, QList<ProjectExplorer::FileNode *> &list)
con's avatar
con committed
339
{
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
    foreach(ProjectExplorer::FolderNode *folder, parent->subFolderNodes())
        gatherFileNodes(folder, list);
    foreach(ProjectExplorer::FileNode *file, parent->fileNodes())
        list.append(file);
}

void CMakeProject::buildTree(CMakeProjectNode *rootNode, QList<ProjectExplorer::FileNode *> newList)
{
    // Gather old list
    QList<ProjectExplorer::FileNode *> oldList;
    gatherFileNodes(rootNode, oldList);
    qSort(oldList.begin(), oldList.end(), ProjectExplorer::ProjectNode::sortNodesByPath);
    qSort(newList.begin(), newList.end(), ProjectExplorer::ProjectNode::sortNodesByPath);

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


    while(oldIt != oldEnd && newIt != newEnd) {
        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
391
392
393
394
395
        // Get relative path to rootNode
        QString parentDir = QFileInfo(fn->path()).absolutePath();
        ProjectExplorer::FolderNode *folder = findOrCreateFolder(rootNode, parentDir);
        rootNode->addFileNodes(QList<ProjectExplorer::FileNode *>()<< fn, folder);
    }
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410

    // remove old file nodes and check wheter folder nodes can be removed
    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
411
412
413
414
415
}

ProjectExplorer::FolderNode *CMakeProject::findOrCreateFolder(CMakeProjectNode *rootNode, QString directory)
{
    QString relativePath = QDir(QFileInfo(rootNode->path()).path()).relativeFilePath(directory);
416
    QStringList parts = relativePath.split("/", QString::SkipEmptyParts);
con's avatar
con committed
417
    ProjectExplorer::FolderNode *parent = rootNode;
hjk's avatar
hjk committed
418
    foreach (const QString &part, parts) {
con's avatar
con committed
419
420
        // Find folder in subFolders
        bool found = false;
hjk's avatar
hjk committed
421
        foreach (ProjectExplorer::FolderNode *folder, parent->subFolderNodes()) {
con's avatar
con committed
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
            if (QFileInfo(folder->path()).fileName() == part) {
                // yeah found something :)
                parent = folder;
                found = true;
                break;
            }
        }
        if (!found) {
            // No FolderNode yet, so create it
            ProjectExplorer::FolderNode *tmp = new ProjectExplorer::FolderNode(part);
            rootNode->addFolderNodes(QList<ProjectExplorer::FolderNode *>() << tmp, parent);
            parent = tmp;
        }
    }
    return parent;
}

QString CMakeProject::name() const
{
441
    return m_projectName;
con's avatar
con committed
442
443
}

444
445


con's avatar
con committed
446
447
448
449
450
Core::IFile *CMakeProject::file() const
{
    return m_file;
}

451
CMakeManager *CMakeProject::projectManager() const
con's avatar
con committed
452
453
454
455
456
457
458
459
460
461
462
463
464
465
{
    return m_manager;
}

QList<ProjectExplorer::Project *> CMakeProject::dependsOn()
{
    return QList<Project *>();
}

bool CMakeProject::isApplication() const
{
    return true;
}

466
467
468
469
470
471
ProjectExplorer::Environment CMakeProject::baseEnvironment(const QString &buildConfiguration) const
{
    Environment env = useSystemEnvironment(buildConfiguration) ? Environment(QProcess::systemEnvironment()) : Environment();
    return env;
}

con's avatar
con committed
472
473
ProjectExplorer::Environment CMakeProject::environment(const QString &buildConfiguration) const
{
474
475
476
477
478
479
480
    Environment env = baseEnvironment(buildConfiguration);
    env.modify(userEnvironmentChanges(buildConfiguration));
    return env;
}

void CMakeProject::setUseSystemEnvironment(const QString &buildConfiguration, bool b)
{
481
482
    if (b == useSystemEnvironment(buildConfiguration))
        return;
483
    setValue(buildConfiguration, "clearSystemEnvironment", !b);
484
    emit environmentChanged(buildConfiguration);
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
}

bool CMakeProject::useSystemEnvironment(const QString &buildConfiguration) const
{
    bool b = !(value(buildConfiguration, "clearSystemEnvironment").isValid() && value(buildConfiguration, "clearSystemEnvironment").toBool());
    return b;
}

QList<ProjectExplorer::EnvironmentItem> CMakeProject::userEnvironmentChanges(const QString &buildConfig) const
{
    return EnvironmentItem::fromStringList(value(buildConfig, "userEnvironmentChanges").toStringList());
}

void CMakeProject::setUserEnvironmentChanges(const QString &buildConfig, const QList<ProjectExplorer::EnvironmentItem> &diff)
{
500
501
502
    QStringList list = EnvironmentItem::toStringList(diff);
    if (list == value(buildConfig, "userEnvironmentChanges"))
        return;
503
    setValue(buildConfig, "userEnvironmentChanges", EnvironmentItem::toStringList(diff));
504
    emit environmentChanged(buildConfig);
con's avatar
con committed
505
506
507
508
}

QString CMakeProject::buildDirectory(const QString &buildConfiguration) const
{
509
510
    QString buildDirectory = value(buildConfiguration, "buildDirectory").toString();
    if (buildDirectory.isEmpty())
511
        buildDirectory = sourceDirectory() + "/qtcreator-build";
512
    return buildDirectory;
con's avatar
con committed
513
514
515
516
}

ProjectExplorer::BuildStepConfigWidget *CMakeProject::createConfigWidget()
{
517
    return new CMakeBuildSettingsWidget(this);
con's avatar
con committed
518
519
520
521
}

QList<ProjectExplorer::BuildStepConfigWidget*> CMakeProject::subConfigWidgets()
{
522
523
524
    QList<ProjectExplorer::BuildStepConfigWidget*> list;
    list <<  new CMakeBuildEnvironmentWidget(this);
    return list;
con's avatar
con committed
525
526
527
528
529
530
}

// This method is called for new build configurations
// You should probably set some default values in this method
 void CMakeProject::newBuildConfiguration(const QString &buildConfiguration)
 {
531
532
     // Default to all
     makeStep()->setBuildTarget(buildConfiguration, "all", true);
533

534
    CMakeOpenProjectWizard copw(projectManager(), sourceDirectory(), buildDirectory(buildConfiguration), environment(buildConfiguration));
535
536
    if (copw.exec() == QDialog::Accepted) {
        setValue(buildConfiguration, "buildDirectory", copw.buildDirectory());
dt's avatar
dt committed
537
        setValue(buildConfiguration, "msvcVersion", copw.msvcVersion());
538
539
        parseCMakeLists();
    }
con's avatar
con committed
540
541
542
543
544
545
546
547
548
549
 }

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


QStringList CMakeProject::files(FilesMode fileMode) const
{
550
    Q_UNUSED(fileMode)
con's avatar
con committed
551
552
553
554
555
    return m_files;
}

void CMakeProject::saveSettingsImpl(ProjectExplorer::PersistentSettingsWriter &writer)
{
dt's avatar
dt committed
556
    Project::saveSettingsImpl(writer);
con's avatar
con committed
557
558
}

559
560
561
562
563
564
565
566
567
568
MakeStep *CMakeProject::makeStep() const
{
    foreach (ProjectExplorer::BuildStep *bs, buildSteps()) {
        MakeStep *ms = qobject_cast<MakeStep *>(bs);
        if (ms)
            return ms;
    }
    return 0;
}

569

dt's avatar
dt committed
570
bool CMakeProject::restoreSettingsImpl(ProjectExplorer::PersistentSettingsReader &reader)
con's avatar
con committed
571
{
dt's avatar
dt committed
572
    Project::restoreSettingsImpl(reader);
dt's avatar
dt committed
573
574
575
576
577
    bool hasUserFile = !buildConfigurations().isEmpty();
    if (!hasUserFile) {
        // Ask the user for where he wants to build it
        // and the cmake command line

578
        CMakeOpenProjectWizard copw(m_manager, sourceDirectory(), ProjectExplorer::Environment::systemEnvironment());
579
580
        copw.exec();
        // TODO handle cancel....
dt's avatar
dt committed
581

582
        qDebug()<<"ccd.buildDirectory()"<<copw.buildDirectory();
dt's avatar
dt committed
583
584

        // Now create a standard build configuration
585
586
        MakeStep *makeStep = new MakeStep(this);

587
        insertBuildStep(0, makeStep);
588

589
        addBuildConfiguration("all");
dt's avatar
dt committed
590
        setValue("all", "msvcVersion", copw.msvcVersion());
591
        makeStep->setBuildTarget("all", "all", true);
592
593
594
        if (!copw.buildDirectory().isEmpty())
            setValue("all", "buildDirectory", copw.buildDirectory());
        //TODO save arguments somewhere copw.arguments()
dt's avatar
dt committed
595
596
597
598

        MakeStep *cleanMakeStep = new MakeStep(this);
        insertCleanStep(0, cleanMakeStep);
        cleanMakeStep->setValue("clean", true);
599
600
        setActiveBuildConfiguration("all");

dt's avatar
dt committed
601

602
603
604
    } else {
        // We have a user file, but we could still be missing the cbp file
        // or simply run createXml with the saved settings
dt's avatar
dt committed
605
606
607
        QFileInfo sourceFileInfo(m_fileName);
        QStringList needToCreate;
        QStringList needToUpdate;
608
609
        QString cbpFile = CMakeManager::findCbpFile(QDir(buildDirectory(activeBuildConfiguration())));
        QFileInfo cbpFileFi(cbpFile);
610
611

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

617
        if (mode != CMakeOpenProjectWizard::Nothing) {
618
619
620
621
622
            CMakeOpenProjectWizard copw(m_manager,
                                        sourceFileInfo.absolutePath(),
                                        buildDirectory(activeBuildConfiguration()),
                                        mode,
                                        environment(activeBuildConfiguration()));
dt's avatar
dt committed
623
            copw.exec();
dt's avatar
dt committed
624
            setValue(activeBuildConfiguration(), "msvcVersion", copw.msvcVersion());
dt's avatar
dt committed
625
        }
dt's avatar
dt committed
626
    }
dt's avatar
dt committed
627
628
629
    bool result = parseCMakeLists(); // Gets the directory from the active buildconfiguration
    if (!result)
        return false;
630
631
632
633
634
635
636

    m_watcher = new ProjectExplorer::FileWatcher(this);
    connect(m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(fileChanged(QString)));
    m_watcher->addFile(m_fileName);

    connect(this, SIGNAL(activeBuildConfigurationChanged()),
            this, SLOT(slotActiveBuildConfiguration()));
dt's avatar
dt committed
637
    return true;
con's avatar
con committed
638
639
}

640
641
642
643
644
645
646
647
CMakeTarget CMakeProject::targetForTitle(const QString &title)
{
    foreach(const CMakeTarget &ct, m_targets)
        if (ct.title == title)
            return ct;
    return CMakeTarget();
}

648
649
650
651
652
653
654
655
656
ProjectExplorer::ToolChain::ToolChainType CMakeProject::toolChainType() const
{
    if (m_toolChain)
        return m_toolChain->type();
    return ProjectExplorer::ToolChain::UNKNOWN;
}

// CMakeFile

con's avatar
con committed
657
658
659
660
661
662
663
664
665
666
CMakeFile::CMakeFile(CMakeProject *parent, QString fileName)
    : Core::IFile(parent), m_project(parent), m_fileName(fileName)
{

}

bool CMakeFile::save(const QString &fileName)
{
    // Once we have an texteditor open for this file, we probably do
    // need to implement this, don't we.
667
    Q_UNUSED(fileName)
con's avatar
con committed
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
703
704
705
706
707
708
    return false;
}

QString CMakeFile::fileName() const
{
    return m_fileName;
}

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

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

QString CMakeFile::mimeType() const
{
    return Constants::CMAKEMIMETYPE;
}


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

bool CMakeFile::isReadOnly() const
{
    return true;
}

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

void CMakeFile::modified(ReloadBehavior *behavior)
{
709
    Q_UNUSED(behavior)
con's avatar
con committed
710
711
}

712
713
CMakeBuildSettingsWidget::CMakeBuildSettingsWidget(CMakeProject *project)
    : m_project(project)
con's avatar
con committed
714
{
715
    QFormLayout *fl = new QFormLayout(this);
716
717
    fl->setContentsMargins(0, -1, 0, -1);
    fl->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
718
    setLayout(fl);
719
720
    m_pathLineEdit = new QLineEdit(this);
    m_pathLineEdit->setReadOnly(true);
721
722
723
724
    // TODO currently doesn't work
    // since creating the cbp file also creates makefiles
    // and then cmake builds in that directory instead of shadow building
    // We need our own generator for that to work
725
726
727
728
729
730
731
732
733
734

    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);

    fl->addRow("Build directory:", hbox);
con's avatar
con committed
735
736
737
738
739
740
741
742
743
}

QString CMakeBuildSettingsWidget::displayName() const
{
    return "CMake";
}

void CMakeBuildSettingsWidget::init(const QString &buildConfiguration)
{
744
    m_buildConfiguration = buildConfiguration;
745
746
747
748
    m_pathLineEdit->setText(m_project->buildDirectory(buildConfiguration));
    if (m_project->buildDirectory(buildConfiguration) == m_project->sourceDirectory())
        m_changeButton->setEnabled(false);
    else
749
        m_changeButton->setEnabled(true);
con's avatar
con committed
750
}
751

752
void CMakeBuildSettingsWidget::openChangeBuildDirectoryDialog()
753
{
754
755
756
757
    CMakeOpenProjectWizard copw(m_project->projectManager(),
                                m_project->sourceDirectory(),
                                m_project->buildDirectory(m_buildConfiguration),
                                m_project->environment(m_buildConfiguration));
758
759
760
761
    if (copw.exec() == QDialog::Accepted) {
        m_project->changeBuildDirectory(m_buildConfiguration, copw.buildDirectory());
        m_pathLineEdit->setText(m_project->buildDirectory(m_buildConfiguration));
    }
762
763
764
765
766
767
}

/////
// CMakeCbpParser
////

768
769
770
771
772
773
bool CMakeCbpParser::parseCbpFile(const QString &fileName)
{
    QFile fi(fileName);
    if (fi.exists() && fi.open(QFile::ReadOnly)) {
        setDevice(&fi);

hjk's avatar
hjk committed
774
        while (!atEnd()) {
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
            readNext();
            if (name() == "CodeBlocks_project_file") {
                parseCodeBlocks_project_file();
            } else if (isStartElement()) {
                parseUnknownElement();
            }
        }
        fi.close();
        m_includeFiles.sort();
        m_includeFiles.removeDuplicates();
        return true;
    }
    return false;
}

void CMakeCbpParser::parseCodeBlocks_project_file()
{
hjk's avatar
hjk committed
792
    while (!atEnd()) {
793
794
795
796
797
798
799
800
801
802
803
804
805
        readNext();
        if (isEndElement()) {
            return;
        } else if (name() == "Project") {
            parseProject();
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseProject()
{
hjk's avatar
hjk committed
806
    while (!atEnd()) {
807
808
809
        readNext();
        if (isEndElement()) {
            return;
810
811
        } else if (name() == "Option") {
            parseOption();
812
813
814
815
816
817
818
819
820
821
822
823
        } else if (name() == "Unit") {
            parseUnit();
        } else if (name() == "Build") {
            parseBuild();
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseBuild()
{
hjk's avatar
hjk committed
824
    while (!atEnd()) {
825
826
827
828
829
830
831
832
833
834
835
836
837
        readNext();
        if (isEndElement()) {
            return;
        } else if (name() == "Target") {
            parseTarget();
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseTarget()
{
dt's avatar
dt committed
838
    m_targetType = false;
dt's avatar
dt committed
839
840
841
842
    m_target.clear();

    if (attributes().hasAttribute("title"))
        m_target.title = attributes().value("title").toString();
dt's avatar
dt committed
843
    while (!atEnd()) {
844
845
        readNext();
        if (isEndElement()) {
846
            if (m_targetType || m_target.title == "all" || m_target.title == "install") {
dt's avatar
dt committed
847
                m_targets.append(m_target);
dt's avatar
dt committed
848
            }
849
850
851
            return;
        } else if (name() == "Compiler") {
            parseCompiler();
dt's avatar
dt committed
852
853
854
855
856
857
858
859
860
861
862
        } else if (name() == "Option") {
            parseTargetOption();
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseTargetOption()
{
    if (attributes().hasAttribute("output"))
dt's avatar
dt committed
863
        m_target.executable = attributes().value("output").toString();
864
    else if (attributes().hasAttribute("type") && (attributes().value("type") == "1" || attributes().value("type") == "0"))
dt's avatar
dt committed
865
        m_targetType = true;
dt's avatar
dt committed
866
867
    else if (attributes().hasAttribute("working_dir"))
        m_target.workingDirectory = attributes().value("working_dir").toString();
dt's avatar
dt committed
868
    while (!atEnd()) {
dt's avatar
dt committed
869
870
871
872
873
874
875
876
877
878
879
        readNext();
        if (isEndElement()) {
            return;
        } else if (name() == "MakeCommand") {
            parseMakeCommand();
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

880
881
882
883
884
885
886
887
888
QString CMakeCbpParser::projectName() const
{
    return m_projectName;
}

void CMakeCbpParser::parseOption()
{
    if (attributes().hasAttribute("title"))
        m_projectName = attributes().value("title").toString();
889

890
891
892
    if (attributes().hasAttribute("compiler"))
        m_compiler = attributes().value("compiler").toString();

893
894
895
896
897
898
899
900
    while (!atEnd()) {
        readNext();
        if (isEndElement()) {
            return;
        } else if(isStartElement()) {
            parseUnknownElement();
        }
    }
901
902
}

dt's avatar
dt committed
903
904
void CMakeCbpParser::parseMakeCommand()
{
dt's avatar
dt committed
905
    while (!atEnd()) {
dt's avatar
dt committed
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
        readNext();
        if (isEndElement()) {
            return;
        } else if (name() == "Build") {
            parseTargetBuild();
        } else if (name() == "Clean") {
            parseTargetClean();
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseTargetBuild()
{
    if (attributes().hasAttribute("command"))
        m_target.makeCommand = attributes().value("command").toString();
dt's avatar
dt committed
923
    while (!atEnd()) {
dt's avatar
dt committed
924
925
926
927
928
929
930
931
932
933
934
935
936
        readNext();
        if (isEndElement()) {
            return;
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseTargetClean()
{
    if (attributes().hasAttribute("command"))
        m_target.makeCleanCommand = attributes().value("command").toString();
dt's avatar
dt committed
937
    while (!atEnd()) {
dt's avatar
dt committed
938
939
940
        readNext();
        if (isEndElement()) {
            return;
941
942
943
944
945
946
947
948
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseCompiler()
{
hjk's avatar
hjk committed
949
    while (!atEnd()) {
950
951
952
953
954
955
956
957
958
959
960
961
962
963
        readNext();
        if (isEndElement()) {
            return;
        } else if (name() == "Add") {
            parseAdd();
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseAdd()
{
    m_includeFiles.append(attributes().value("directory").toString());
hjk's avatar
hjk committed
964
    while (!atEnd()) {
965
966
967
968
969
970
971
972
973
974
975
976
977
        readNext();
        if (isEndElement()) {
            return;
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseUnit()
{
    //qDebug()<<stream.attributes().value("filename");
    QString fileName = attributes().value("filename").toString();
dt's avatar
dt committed
978
    m_parsingCmakeUnit = false;
hjk's avatar
hjk committed
979
    while (!atEnd()) {
980
981
        readNext();
        if (isEndElement()) {
dt's avatar
dt committed
982
983
            if (!fileName.endsWith(".rule") && !m_processedUnits.contains(fileName)) {
                // Now check whether we found a virtual element beneath
984
                if (m_parsingCmakeUnit) {
dt's avatar
dt committed
985
                    m_cmakeFileList.append( new ProjectExplorer::FileNode(fileName, ProjectExplorer::ProjectFileType, false));
986
987
988
989
990
991
                } else {
                    if (fileName.endsWith(".qrc"))
                        m_fileList.append( new ProjectExplorer::FileNode(fileName, ProjectExplorer::ResourceType, false));
                    else
                        m_fileList.append( new ProjectExplorer::FileNode(fileName, ProjectExplorer::SourceType, false));
                }
dt's avatar
dt committed
992
993
                m_processedUnits.insert(fileName);
            }
994
            return;
dt's avatar
dt committed
995
996
        } else if (name() == "Option") {
            parseUnitOption();
997
998
999
1000
1001
1002
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

dt's avatar
dt committed
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
void CMakeCbpParser::parseUnitOption()
{
    if (attributes().hasAttribute("virtualFolder"))
        m_parsingCmakeUnit = true;

    while (!atEnd()) {
        readNext();

        if (isEndElement())
            break;

        if (isStartElement())
            parseUnknownElement();
    }
}

1019
1020
void CMakeCbpParser::parseUnknownElement()
{
dt's avatar
dt committed
1021
    Q_ASSERT(isStartElement());
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038

    while (!atEnd()) {
        readNext();

        if (isEndElement())
            break;

        if (isStartElement())
            parseUnknownElement();
    }
}

QList<ProjectExplorer::FileNode *> CMakeCbpParser::fileList()
{
    return m_fileList;
}

dt's avatar
dt committed
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
QList<ProjectExplorer::FileNode *> CMakeCbpParser::cmakeFileList()
{
    return m_cmakeFileList;
}

bool CMakeCbpParser::hasCMakeFiles()
{
    return !m_cmakeFileList.isEmpty();
}

1049
1050
1051
1052
QStringList CMakeCbpParser::includeFiles()
{
    return m_includeFiles;
}
dt's avatar
dt committed
1053
1054
1055
1056
1057
1058

QList<CMakeTarget> CMakeCbpParser::targets()
{
    return m_targets;
}

1059
1060
1061
1062
1063
QString CMakeCbpParser::compilerName() const
{
    return m_compiler;
}

dt's avatar
dt committed
1064
1065
1066
1067
1068
1069
1070
1071
1072
void CMakeTarget::clear()
{
    executable = QString::null;
    makeCommand = QString::null;
    makeCleanCommand = QString::null;
    workingDirectory = QString::null;
    title = QString::null;
}