cmakeproject.cpp 30.8 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
8
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
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
26
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
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
    m_watcher = new ProjectExplorer::FileWatcher(this);
    connect(m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(fileChanged(QString)));
    m_watcher->addFile(fileName);
78
79
80

    connect(this, SIGNAL(activeBuildConfigurationChanged()),
            this, SLOT(slotActiveBuildConfiguration()));
81
82
83
84
85
}

CMakeProject::~CMakeProject()
{
    delete m_rootNode;
86
    delete m_toolChain;
87
88
}

89
90
91
92
93
94
95
96
97
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);
98
    CMakeOpenProjectWizard::Mode mode;
99
    if (!cbpFileFi.exists())
100
        mode = CMakeOpenProjectWizard::NeedToCreate;
101
    else if (cbpFileFi.lastModified() < sourceFileInfo.lastModified())
102
103
104
        mode = CMakeOpenProjectWizard::NeedToUpdate;
    else
        mode = CMakeOpenProjectWizard::Nothing;
105

106
    if (mode != CMakeOpenProjectWizard::Nothing) {
107
108
109
110
111
        CMakeOpenProjectWizard copw(m_manager,
                                    sourceFileInfo.absolutePath(),
                                    buildDirectory(activeBuildConfiguration()),
                                    mode,
                                    environment(activeBuildConfiguration()));
112
113
114
115
116
117
        copw.exec();
    }
    // reparse
    parseCMakeLists();
}

118
119
120
121
122
123
124
void CMakeProject::fileChanged(const QString &fileName)
{
    if (m_insideFileChanged== true)
        return;
    m_insideFileChanged = true;
    if (fileName == m_fileName) {
        // Oh we have changed...
125
        slotActiveBuildConfiguration();
126
127
128
129
130
131
132
133
134
135
136
    }
    m_insideFileChanged = false;
}

void CMakeProject::updateToolChain(const QString &compiler)
{
    //qDebug()<<"CodeBlocks Compilername"<<compiler
    ProjectExplorer::ToolChain *newToolChain = 0;
    if (compiler == "gcc") {
        newToolChain = ProjectExplorer::ToolChain::createGccToolChain("gcc");
    } else if (compiler == "msvc8") {
137
        // TODO MSVC toolchain
138
139
140
        //newToolChain = ProjectExplorer::ToolChain::createMSVCToolChain("//TODO");
        Q_ASSERT(false);
    } else {
141
        // TODO other toolchains
142
143
144
145
146
147
148
149
150
151
152
153
        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;
    }
}

154
155
156
157
158
159
160
161
162
163
164
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
165
void CMakeProject::parseCMakeLists()
166
{
167
    // Find cbp file
168
    QString cbpFile = CMakeManager::findCbpFile(buildDirectory(activeBuildConfiguration()));
169
170

    // setFolderName
171
    m_rootNode->setFolderName(QFileInfo(cbpFile).completeBaseName());
172
    CMakeCbpParser cbpparser;
173
174
175
176
177
    // Parsing
    //qDebug()<<"Parsing file "<<cbpFile;
    if (cbpparser.parseCbpFile(cbpFile)) {        
        // ToolChain
        updateToolChain(cbpparser.compilerName());
178

179
        m_projectName = cbpparser.projectName();
dt's avatar
dt committed
180
        m_rootNode->setFolderName(cbpparser.projectName());
181

182
183
        //qDebug()<<"Building Tree";

184
185
        QList<ProjectExplorer::FileNode *> fileList = cbpparser.fileList();
        // Manually add the CMakeLists.txt file
186
        fileList.append(new ProjectExplorer::FileNode(sourceDirectory() + "/CMakeLists.txt", ProjectExplorer::ProjectFileType, false));
187

dt's avatar
dt committed
188
        m_files.clear();
189
        foreach (ProjectExplorer::FileNode *fn, fileList)
con's avatar
con committed
190
191
192
            m_files.append(fn->path());
        m_files.sort();

193
194
195
196
        buildTree(m_rootNode, fileList);


        //qDebug()<<"Adding Targets";
dt's avatar
dt committed
197
        m_targets = cbpparser.targets();
dt's avatar
dt committed
198
199
200
201
202
203
204
//        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
205

206
        //qDebug()<<"Updating CodeModel";
207
208
209
210
211
212
213
214
215
216

        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());
        }
217
        // This explicitly adds -I. to the include paths
218
        allIncludePaths.append(sourceDirectory());
219

220
        allIncludePaths.append(cbpparser.includeFiles());
con's avatar
con committed
221
222
        CppTools::CppModelManagerInterface *modelmanager = ExtensionSystem::PluginManager::instance()->getObject<CppTools::CppModelManagerInterface>();
        if (modelmanager) {
223
            CppTools::CppModelManagerInterface::ProjectInfo pinfo = modelmanager->projectInfo(this);
224
            pinfo.includePaths = allIncludePaths;
225
            // TODO we only want C++ files, not all other stuff that might be in the project
226
            pinfo.sourceFiles = m_files;
dt's avatar
dt committed
227
            pinfo.defines = m_toolChain->predefinedMacros(); // TODO this is to simplistic
228
            pinfo.frameworkPaths = allFrameworkPaths;
229
            modelmanager->updateProjectInfo(pinfo);
con's avatar
con committed
230
        }
dt's avatar
dt committed
231
232

        // Create run configurations for m_targets
233
        //qDebug()<<"Create run configurations of m_targets";
234
        QMultiMap<QString, QSharedPointer<CMakeRunConfiguration> > existingRunConfigurations;
dt's avatar
dt committed
235
236
237
238
239
240
        foreach(QSharedPointer<ProjectExplorer::RunConfiguration> cmakeRunConfiguration, runConfigurations()) {
            if (QSharedPointer<CMakeRunConfiguration> rc = cmakeRunConfiguration.dynamicCast<CMakeRunConfiguration>()) {
                existingRunConfigurations.insert(rc->title(), rc);
            }
        }

241
        bool setActive = existingRunConfigurations.isEmpty();
dt's avatar
dt committed
242
243
244
245
246
        foreach(const CMakeTarget &ct, m_targets) {
            if (ct.executable.isEmpty())
                continue;
            if (ct.title.endsWith("/fast"))
                continue;
247
248
            QList<QSharedPointer<CMakeRunConfiguration> > list = existingRunConfigurations.values(ct.title);
            if (!list.isEmpty()) {
dt's avatar
dt committed
249
                // Already exists, so override the settings...
250
251
252
253
254
255
256
257
                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
258
259
            } else {
                // Does not exist yet
260
261
                //qDebug()<<"Adding new run configuration with title"<<ct.title;
                //qDebug()<<"  Executable:"<<ct.executable<<"WD:"<<ct.workingDirectory;
dt's avatar
dt committed
262
263
264
                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
265
                if (setActive) {
dt's avatar
dt committed
266
                    setActiveRunConfiguration(rc);
267
                    setActive = false;
dt's avatar
dt committed
268
269
270
                }
            }
        }
271
        QMultiMap<QString, QSharedPointer<CMakeRunConfiguration> >::const_iterator it =
dt's avatar
dt committed
272
273
274
                existingRunConfigurations.constBegin();
        for( ; it != existingRunConfigurations.constEnd(); ++it) {
            QSharedPointer<CMakeRunConfiguration> rc = it.value();
275
276
            //qDebug()<<"Removing old RunConfiguration with title:"<<rc->title();
            //qDebug()<<"  Executable:"<<rc->executable()<<rc->workingDirectory();
dt's avatar
dt committed
277
278
            removeRunConfiguration(rc);
        }
279
        //qDebug()<<"\n";
con's avatar
con committed
280
281
    } else {
        // TODO report error
dt's avatar
dt committed
282
        qDebug()<<"Parsing failed";
283
284
        delete m_toolChain;
        m_toolChain = 0;
con's avatar
con committed
285
286
287
    }
}

288
289
QString CMakeProject::buildParser(const QString &buildConfiguration) const
{
mae's avatar
mae committed
290
    Q_UNUSED(buildConfiguration);
291
292
    // TODO this is actually slightly wrong, but do i care?
    // this should call toolchain(buildConfiguration)
293
294
295
296
297
298
299
300
301
302
303
304
305
    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;
}

306
QStringList CMakeProject::targets() const
con's avatar
con committed
307
{
308
    QStringList results;
309
310
311
312
313
    foreach (const CMakeTarget &ct, m_targets) {
        if (ct.executable.isEmpty())
            continue;
        if (ct.title.endsWith("/fast"))
            continue;
314
        results << ct.title;
315
    }
316
    return results;
con's avatar
con committed
317
318
}

319
void CMakeProject::gatherFileNodes(ProjectExplorer::FolderNode *parent, QList<ProjectExplorer::FileNode *> &list)
con's avatar
con committed
320
{
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
    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
372
373
374
375
376
        // Get relative path to rootNode
        QString parentDir = QFileInfo(fn->path()).absolutePath();
        ProjectExplorer::FolderNode *folder = findOrCreateFolder(rootNode, parentDir);
        rootNode->addFileNodes(QList<ProjectExplorer::FileNode *>()<< fn, folder);
    }
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391

    // 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
392
393
394
395
396
}

ProjectExplorer::FolderNode *CMakeProject::findOrCreateFolder(CMakeProjectNode *rootNode, QString directory)
{
    QString relativePath = QDir(QFileInfo(rootNode->path()).path()).relativeFilePath(directory);
397
    QStringList parts = relativePath.split("/", QString::SkipEmptyParts);
con's avatar
con committed
398
    ProjectExplorer::FolderNode *parent = rootNode;
hjk's avatar
hjk committed
399
    foreach (const QString &part, parts) {
con's avatar
con committed
400
401
        // Find folder in subFolders
        bool found = false;
hjk's avatar
hjk committed
402
        foreach (ProjectExplorer::FolderNode *folder, parent->subFolderNodes()) {
con's avatar
con committed
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
            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
{
422
    return m_projectName;
con's avatar
con committed
423
424
}

425
426


con's avatar
con committed
427
428
429
430
431
Core::IFile *CMakeProject::file() const
{
    return m_file;
}

432
CMakeManager *CMakeProject::projectManager() const
con's avatar
con committed
433
434
435
436
437
438
439
440
441
442
443
444
445
446
{
    return m_manager;
}

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

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

447
448
449
450
451
452
ProjectExplorer::Environment CMakeProject::baseEnvironment(const QString &buildConfiguration) const
{
    Environment env = useSystemEnvironment(buildConfiguration) ? Environment(QProcess::systemEnvironment()) : Environment();
    return env;
}

con's avatar
con committed
453
454
ProjectExplorer::Environment CMakeProject::environment(const QString &buildConfiguration) const
{
455
456
457
458
459
460
461
    Environment env = baseEnvironment(buildConfiguration);
    env.modify(userEnvironmentChanges(buildConfiguration));
    return env;
}

void CMakeProject::setUseSystemEnvironment(const QString &buildConfiguration, bool b)
{
462
463
    if (b == useSystemEnvironment(buildConfiguration))
        return;
464
    setValue(buildConfiguration, "clearSystemEnvironment", !b);
465
    emit environmentChanged(buildConfiguration);
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
}

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)
{
481
482
483
    QStringList list = EnvironmentItem::toStringList(diff);
    if (list == value(buildConfig, "userEnvironmentChanges"))
        return;
484
    setValue(buildConfig, "userEnvironmentChanges", EnvironmentItem::toStringList(diff));
485
    emit environmentChanged(buildConfig);
con's avatar
con committed
486
487
488
489
}

QString CMakeProject::buildDirectory(const QString &buildConfiguration) const
{
490
491
    QString buildDirectory = value(buildConfiguration, "buildDirectory").toString();
    if (buildDirectory.isEmpty())
492
        buildDirectory = sourceDirectory() + "/qtcreator-build";
493
    return buildDirectory;
con's avatar
con committed
494
495
496
497
}

ProjectExplorer::BuildStepConfigWidget *CMakeProject::createConfigWidget()
{
498
    return new CMakeBuildSettingsWidget(this);
con's avatar
con committed
499
500
501
502
}

QList<ProjectExplorer::BuildStepConfigWidget*> CMakeProject::subConfigWidgets()
{
503
504
505
    QList<ProjectExplorer::BuildStepConfigWidget*> list;
    list <<  new CMakeBuildEnvironmentWidget(this);
    return list;
con's avatar
con committed
506
507
508
509
510
511
}

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

515
    CMakeOpenProjectWizard copw(projectManager(), sourceDirectory(), buildDirectory(buildConfiguration), environment(buildConfiguration));
516
517
518
519
    if (copw.exec() == QDialog::Accepted) {
        setValue(buildConfiguration, "buildDirectory", copw.buildDirectory());
        parseCMakeLists();
    }
con's avatar
con committed
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
 }

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


QStringList CMakeProject::files(FilesMode fileMode) const
{
    Q_UNUSED(fileMode);
    return m_files;
}

void CMakeProject::saveSettingsImpl(ProjectExplorer::PersistentSettingsWriter &writer)
{
dt's avatar
dt committed
536
    Project::saveSettingsImpl(writer);
con's avatar
con committed
537
538
}

539
540
541
542
543
544
545
546
547
548
MakeStep *CMakeProject::makeStep() const
{
    foreach (ProjectExplorer::BuildStep *bs, buildSteps()) {
        MakeStep *ms = qobject_cast<MakeStep *>(bs);
        if (ms)
            return ms;
    }
    return 0;
}

549

con's avatar
con committed
550
551
void CMakeProject::restoreSettingsImpl(ProjectExplorer::PersistentSettingsReader &reader)
{
dt's avatar
dt committed
552
    Project::restoreSettingsImpl(reader);
dt's avatar
dt committed
553
554
555
556
557
    bool hasUserFile = !buildConfigurations().isEmpty();
    if (!hasUserFile) {
        // Ask the user for where he wants to build it
        // and the cmake command line

558
        CMakeOpenProjectWizard copw(m_manager, sourceDirectory(), ProjectExplorer::Environment::systemEnvironment());
559
560
        copw.exec();
        // TODO handle cancel....
dt's avatar
dt committed
561

562
        qDebug()<<"ccd.buildDirectory()"<<copw.buildDirectory();
dt's avatar
dt committed
563
564

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

567
        insertBuildStep(0, makeStep);
568

569
570
571
        addBuildConfiguration("all");
        setActiveBuildConfiguration("all");
        makeStep->setBuildTarget("all", "all", true);
572
573
574
        if (!copw.buildDirectory().isEmpty())
            setValue("all", "buildDirectory", copw.buildDirectory());
        //TODO save arguments somewhere copw.arguments()
dt's avatar
dt committed
575
576
577
578

        MakeStep *cleanMakeStep = new MakeStep(this);
        insertCleanStep(0, cleanMakeStep);
        cleanMakeStep->setValue("clean", true);
579
580
581
    } 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
582
583
584
        QFileInfo sourceFileInfo(m_fileName);
        QStringList needToCreate;
        QStringList needToUpdate;
585
586
        QString cbpFile = CMakeManager::findCbpFile(QDir(buildDirectory(activeBuildConfiguration())));
        QFileInfo cbpFileFi(cbpFile);
587
588

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

594
        if (mode != CMakeOpenProjectWizard::Nothing) {
595
596
597
598
599
            CMakeOpenProjectWizard copw(m_manager,
                                        sourceFileInfo.absolutePath(),
                                        buildDirectory(activeBuildConfiguration()),
                                        mode,
                                        environment(activeBuildConfiguration()));
dt's avatar
dt committed
600
601
            copw.exec();
        }
dt's avatar
dt committed
602
603
604
    }

    parseCMakeLists(); // Gets the directory from the active buildconfiguration
con's avatar
con committed
605
606
}

607
608
609
610
611
612
613
614
CMakeTarget CMakeProject::targetForTitle(const QString &title)
{
    foreach(const CMakeTarget &ct, m_targets)
        if (ct.title == title)
            return ct;
    return CMakeTarget();
}

con's avatar
con committed
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
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.
    Q_UNUSED(fileName);
    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)
{
    Q_UNUSED(behavior);
}

670
671
CMakeBuildSettingsWidget::CMakeBuildSettingsWidget(CMakeProject *project)
    : m_project(project)
con's avatar
con committed
672
{
673
674
    QFormLayout *fl = new QFormLayout(this);
    setLayout(fl);
675
676
    m_pathLineEdit = new QLineEdit(this);
    m_pathLineEdit->setReadOnly(true);
677
678
679
680
    // 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
681
682
683
684
685
686
687
688
689
690

    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
691
692
693
694
695
696
697
698
699
}

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

void CMakeBuildSettingsWidget::init(const QString &buildConfiguration)
{
700
    m_buildConfiguration = buildConfiguration;
701
702
703
704
    m_pathLineEdit->setText(m_project->buildDirectory(buildConfiguration));
    if (m_project->buildDirectory(buildConfiguration) == m_project->sourceDirectory())
        m_changeButton->setEnabled(false);
    else
705
        m_changeButton->setEnabled(true);
con's avatar
con committed
706
}
707

708
void CMakeBuildSettingsWidget::openChangeBuildDirectoryDialog()
709
{
710
711
712
713
    CMakeOpenProjectWizard copw(m_project->projectManager(),
                                m_project->sourceDirectory(),
                                m_project->buildDirectory(m_buildConfiguration),
                                m_project->environment(m_buildConfiguration));
714
715
716
717
    if (copw.exec() == QDialog::Accepted) {
        m_project->changeBuildDirectory(m_buildConfiguration, copw.buildDirectory());
        m_pathLineEdit->setText(m_project->buildDirectory(m_buildConfiguration));
    }
718
719
720
721
722
723
}

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

724
725
726
727
728
729
bool CMakeCbpParser::parseCbpFile(const QString &fileName)
{
    QFile fi(fileName);
    if (fi.exists() && fi.open(QFile::ReadOnly)) {
        setDevice(&fi);

hjk's avatar
hjk committed
730
        while (!atEnd()) {
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
            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
748
    while (!atEnd()) {
749
750
751
752
753
754
755
756
757
758
759
760
761
        readNext();
        if (isEndElement()) {
            return;
        } else if (name() == "Project") {
            parseProject();
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseProject()
{
hjk's avatar
hjk committed
762
    while (!atEnd()) {
763
764
765
        readNext();
        if (isEndElement()) {
            return;
766
767
        } else if (name() == "Option") {
            parseOption();
768
769
770
771
772
773
774
775
776
777
778
779
        } else if (name() == "Unit") {
            parseUnit();
        } else if (name() == "Build") {
            parseBuild();
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseBuild()
{
hjk's avatar
hjk committed
780
    while (!atEnd()) {
781
782
783
784
785
786
787
788
789
790
791
792
793
        readNext();
        if (isEndElement()) {
            return;
        } else if (name() == "Target") {
            parseTarget();
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseTarget()
{
dt's avatar
dt committed
794
    m_targetType = false;
dt's avatar
dt committed
795
796
797
798
    m_target.clear();

    if (attributes().hasAttribute("title"))
        m_target.title = attributes().value("title").toString();
dt's avatar
dt committed
799
    while (!atEnd()) {
800
801
        readNext();
        if (isEndElement()) {
802
            if (m_targetType || m_target.title == "all" || m_target.title == "install") {
dt's avatar
dt committed
803
                m_targets.append(m_target);
dt's avatar
dt committed
804
            }
805
806
807
            return;
        } else if (name() == "Compiler") {
            parseCompiler();
dt's avatar
dt committed
808
809
810
811
812
813
814
815
816
817
818
        } else if (name() == "Option") {
            parseTargetOption();
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseTargetOption()
{
    if (attributes().hasAttribute("output"))
dt's avatar
dt committed
819
        m_target.executable = attributes().value("output").toString();
820
    else if (attributes().hasAttribute("type") && (attributes().value("type") == "1" || attributes().value("type") == "0"))
dt's avatar
dt committed
821
        m_targetType = true;
dt's avatar
dt committed
822
823
    else if (attributes().hasAttribute("working_dir"))
        m_target.workingDirectory = attributes().value("working_dir").toString();
dt's avatar
dt committed
824
    while (!atEnd()) {
dt's avatar
dt committed
825
826
827
828
829
830
831
832
833
834
835
        readNext();
        if (isEndElement()) {
            return;
        } else if (name() == "MakeCommand") {
            parseMakeCommand();
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

836
837
838
839
840
841
842
843
844
QString CMakeCbpParser::projectName() const
{
    return m_projectName;
}

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

846
847
848
    if (attributes().hasAttribute("compiler"))
        m_compiler = attributes().value("compiler").toString();

849
850
851
852
853
854
855
856
    while (!atEnd()) {
        readNext();
        if (isEndElement()) {
            return;
        } else if(isStartElement()) {
            parseUnknownElement();
        }
    }
857
858
}

dt's avatar
dt committed
859
860
void CMakeCbpParser::parseMakeCommand()
{
dt's avatar
dt committed
861
    while (!atEnd()) {
dt's avatar
dt committed
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
        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
879
    while (!atEnd()) {
dt's avatar
dt committed
880
881
882
883
884
885
886
887
888
889
890
891
892
        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
893
    while (!atEnd()) {
dt's avatar
dt committed
894
895
896
        readNext();
        if (isEndElement()) {
            return;
897
898
899
900
901
902
903
904
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseCompiler()
{
hjk's avatar
hjk committed
905
    while (!atEnd()) {
906
907
908
909
910
911
912
913
914
915
916
917
918
919
        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
920
    while (!atEnd()) {
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
        readNext();
        if (isEndElement()) {
            return;
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseUnit()
{
    //qDebug()<<stream.attributes().value("filename");
    QString fileName = attributes().value("filename").toString();
    if (!fileName.endsWith(".rule"))
        m_fileList.append( new ProjectExplorer::FileNode(fileName, ProjectExplorer::SourceType, false));
hjk's avatar
hjk committed
936
    while (!atEnd()) {
937
938
939
940
941
942
943
944
945
946
947
        readNext();
        if (isEndElement()) {
            return;
        } else if (isStartElement()) {
            parseUnknownElement();
        }
    }
}

void CMakeCbpParser::parseUnknownElement()
{
dt's avatar
dt committed
948
    Q_ASSERT(isStartElement());
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969

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

        if (isEndElement())
            break;

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

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

QStringList CMakeCbpParser::includeFiles()
{
    return m_includeFiles;
}
dt's avatar
dt committed
970
971
972
973
974
975

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

976
977
978
979
980
QString CMakeCbpParser::compilerName() const
{
    return m_compiler;
}

dt's avatar
dt committed
981
982
983
984
985
986
987
988
989
void CMakeTarget::clear()
{
    executable = QString::null;
    makeCommand = QString::null;
    makeCleanCommand = QString::null;
    workingDirectory = QString::null;
    title = QString::null;
}