qt4project.cpp 33.4 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
#include "qt4project.h"
hjk's avatar
hjk committed
31

con's avatar
con committed
32
33
#include "qt4projectmanager.h"
#include "profilereader.h"
dt's avatar
dt committed
34
#include "prowriter.h"
con's avatar
con committed
35
36
37
38
39
40
#include "makestep.h"
#include "qmakestep.h"
#include "deployhelper.h"
#include "qt4runconfiguration.h"
#include "qtversionmanager.h"
#include "qt4nodes.h"
41
#include "qt4projectconfigwidget.h"
con's avatar
con committed
42
43
44
45
#include "qt4buildenvironmentwidget.h"
#include "qt4projectmanagerconstants.h"
#include "projectloadwizard.h"

46
#include <coreplugin/icore.h>
con's avatar
con committed
47
48
49
#include <coreplugin/messagemanager.h>
#include <coreplugin/coreconstants.h>
#include <cpptools/cppmodelmanagerinterface.h>
50
#include <extensionsystem/pluginmanager.h>
con's avatar
con committed
51
52
53
54
55
#include <projectexplorer/nodesvisitor.h>
#include <projectexplorer/project.h>
#include <projectexplorer/customexecutablerunconfiguration.h>

#include <QtCore/QDebug>
56
57
#include <QtCore/QDir>
#include <QtGui/QFileDialog>
con's avatar
con committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
using namespace ProjectExplorer;

enum { debug = 0 };

namespace Qt4ProjectManager {
namespace Internal {

// Qt4ProjectFiles: Struct for (Cached) lists of files in a project
struct Qt4ProjectFiles {
    void clear();
    bool equals(const Qt4ProjectFiles &f) const;

    QStringList files[ProjectExplorer::FileTypeSize];
    QStringList generatedFiles[ProjectExplorer::FileTypeSize];
    QStringList proFiles;
};

void Qt4ProjectFiles::clear()
{
    for (int i = 0; i < FileTypeSize; ++i) {
        files[i].clear();
        generatedFiles[i].clear();
    }
    proFiles.clear();
}

bool Qt4ProjectFiles::equals(const Qt4ProjectFiles &f) const
{
    for (int i = 0; i < FileTypeSize; ++i)
        if (files[i] != f.files[i] || generatedFiles[i] != f.generatedFiles[i])
            return false;
    if (proFiles != f.proFiles)
        return false;
    return true;
}

inline bool operator==(const Qt4ProjectFiles &f1, const Qt4ProjectFiles &f2)
{       return f1.equals(f2); }

inline bool operator!=(const Qt4ProjectFiles &f1, const Qt4ProjectFiles &f2)
{       return !f1.equals(f2); }

QDebug operator<<(QDebug d, const  Qt4ProjectFiles &f)
{
    QDebug nsp = d.nospace();
    nsp << "Qt4ProjectFiles: proFiles=" <<  f.proFiles << '\n';
    for (int i = 0; i < FileTypeSize; ++i)
        nsp << "Type " << i << " files=" << f.files[i] <<  " generated=" << f.generatedFiles[i] << '\n';
    return d;
}

// A visitor to collect all files of a project in a Qt4ProjectFiles struct
class ProjectFilesVisitor : public ProjectExplorer::NodesVisitor
{
    Q_DISABLE_COPY(ProjectFilesVisitor)
    ProjectFilesVisitor(Qt4ProjectFiles *files);
public:

    static void findProjectFiles(Qt4ProFileNode *rootNode, Qt4ProjectFiles *files);

    void visitProjectNode(ProjectNode *projectNode);
    void visitFolderNode(FolderNode *folderNode);

private:
    Qt4ProjectFiles *m_files;
};

ProjectFilesVisitor::ProjectFilesVisitor(Qt4ProjectFiles *files) :
    m_files(files)
{
}

void ProjectFilesVisitor::findProjectFiles(Qt4ProFileNode *rootNode, Qt4ProjectFiles *files)
{
    files->clear();
    ProjectFilesVisitor visitor(files);
    rootNode->accept(&visitor);
    for (int i = 0; i < FileTypeSize; ++i) {
        qSort(files->files[i]);
        qSort(files->generatedFiles[i]);
    }
    qSort(files->proFiles);
}

void ProjectFilesVisitor::visitProjectNode(ProjectNode *projectNode)
{
    const QString path = projectNode->path();
    if (!m_files->proFiles.contains(path))
        m_files->proFiles.append(path);
    visitFolderNode(projectNode);
}

void ProjectFilesVisitor::visitFolderNode(FolderNode *folderNode)
{
    foreach (FileNode *fileNode, folderNode->fileNodes()) {
        const QString path = fileNode->path();
        const int type = fileNode->fileType();
        QStringList &targetList = fileNode->isGenerated() ? m_files->generatedFiles[type] : m_files->files[type];
        if (!targetList.contains(path))
            targetList.push_back(path);
    }
}

}
}

// ----------- Qt4ProjectFile
Qt4ProjectFile::Qt4ProjectFile(Qt4Project *project, const QString &filePath, QObject *parent)
    : Core::IFile(parent),
      m_mimeType(QLatin1String(Qt4ProjectManager::Constants::PROFILE_MIMETYPE)),
      m_project(project),
      m_filePath(filePath)
{
}

bool Qt4ProjectFile::save(const QString &)
{
178
179
    // This is never used
    return false;
con's avatar
con committed
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
}

QString Qt4ProjectFile::fileName() const
{
    return m_filePath;
}

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

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

QString Qt4ProjectFile::mimeType() const
{
    return m_mimeType;
}

bool Qt4ProjectFile::isModified() const
{
204
    return false; // we save after changing anyway
con's avatar
con committed
205
206
207
208
}

bool Qt4ProjectFile::isReadOnly() const
{
dt's avatar
dt committed
209
210
    QFileInfo fi(m_filePath);
    return !fi.isWritable();
con's avatar
con committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
}

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

void Qt4ProjectFile::modified(Core::IFile::ReloadBehavior *)
{
}

/*!
  /class Qt4Project

  Qt4Project manages information about an individual Qt 4 (.pro) project file.
  */

Qt4Project::Qt4Project(Qt4Manager *manager, const QString& fileName) :
dt's avatar
dt committed
229
    m_toolChain(0),
con's avatar
con committed
230
    m_manager(manager),
dt's avatar
dt committed
231
    m_rootProjectNode(0),
con's avatar
con committed
232
233
234
235
236
    m_nodesWatcher(new Internal::Qt4NodesWatcher(this)),
    m_fileInfo(new Qt4ProjectFile(this, fileName, this)),
    m_isApplication(true),
    m_projectFiles(new Qt4ProjectFiles)
{
dt's avatar
dt committed
237
    m_manager->registerProject(this);
con's avatar
con committed
238
239
240
241
242
243
244
245
246

    connect(qt4ProjectManager()->versionManager(), SIGNAL(defaultQtVersionChanged()),
            this, SLOT(defaultQtVersionChanged()));
    connect(qt4ProjectManager()->versionManager(), SIGNAL(qtVersionsChanged()),
            this, SLOT(qtVersionsChanged()));

    m_updateCodeModelTimer.setSingleShot(true);
    m_updateCodeModelTimer.setInterval(20);
    connect(&m_updateCodeModelTimer, SIGNAL(timeout()), this, SLOT(updateCodeModel()));
247
248
249
250

    m_addUiFilesTimer.setSingleShot(true);
    m_addUiFilesTimer.setInterval(20);
    connect(&m_addUiFilesTimer, SIGNAL(timeout()), this, SLOT(addUiFiles()));
con's avatar
con committed
251
252
253
254
}

Qt4Project::~Qt4Project()
{
dt's avatar
dt committed
255
    m_manager->unregisterProject(this);
con's avatar
con committed
256
    delete m_projectFiles;
dt's avatar
dt committed
257
    delete m_toolChain;
dt's avatar
dt committed
258
    m_toolChain = 0;
con's avatar
con committed
259
260
261
262
263
}

void Qt4Project::defaultQtVersionChanged()
{
    if (qtVersionId(activeBuildConfiguration()) == 0)
264
        m_rootProjectNode->update();
con's avatar
con committed
265
266
267
268
269
270
271
}

void Qt4Project::qtVersionsChanged()
{
    foreach (QString bc, buildConfigurations()) {
        if (!qt4ProjectManager()->versionManager()->version(qtVersionId(bc))->isValid()) {
            setQtVersion(bc, 0);
hjk's avatar
hjk committed
272
            if (bc == activeBuildConfiguration())
273
                m_rootProjectNode->update();
con's avatar
con committed
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
        }
    }
}

void Qt4Project::updateFileList()
{
    Qt4ProjectFiles newFiles;
    ProjectFilesVisitor::findProjectFiles(m_rootProjectNode, &newFiles);
    if (newFiles != *m_projectFiles) {
        *m_projectFiles = newFiles;
        emit fileListChanged();
        if (debug)
            qDebug() << Q_FUNC_INFO << *m_projectFiles;
    }
}

void Qt4Project::restoreSettingsImpl(PersistentSettingsReader &settingsReader)
{
    Project::restoreSettingsImpl(settingsReader);

    addDefaultBuild();

    // Ensure that the qt version in each build configuration is valid
    // or if not, is reset to the default
    foreach (const QString &bc, buildConfigurations())
        qtVersionId(bc);

dt's avatar
dt committed
301
302
303
304
305
306
307
308
309
    m_rootProjectNode = new Qt4ProFileNode(this, m_fileInfo->fileName(), this);
    m_rootProjectNode->registerWatcher(m_nodesWatcher);
    connect(m_nodesWatcher, SIGNAL(foldersAdded()), this, SLOT(updateFileList()));
    connect(m_nodesWatcher, SIGNAL(foldersRemoved()), this, SLOT(updateFileList()));
    connect(m_nodesWatcher, SIGNAL(filesAdded()), this, SLOT(updateFileList()));
    connect(m_nodesWatcher, SIGNAL(filesRemoved()), this, SLOT(updateFileList()));
    connect(m_nodesWatcher, SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode *)),
            this, SLOT(scheduleUpdateCodeModel()));

con's avatar
con committed
310
311
312
313
314
315
316
317
318
319
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
372
373
374
375
376
    update();

    // restored old runconfigurations
    if (runConfigurations().isEmpty()) {
        // Oha no runConfigurations, add some
        QList<Qt4ProFileNode *> list;
        collectApplicationProFiles(list, m_rootProjectNode);

        if (!list.isEmpty()) {
            foreach (Qt4ProFileNode *node, list) {
                QSharedPointer<RunConfiguration> rc(new Qt4RunConfiguration(this, node->path()));
                addRunConfiguration(rc);
            }
            setActiveRunConfiguration(runConfigurations().first());
        } else {
            QSharedPointer<RunConfiguration> rc(new ProjectExplorer::CustomExecutableRunConfiguration(this));
            addRunConfiguration(rc);
            setActiveRunConfiguration(rc);
            m_isApplication = false;
        }
    }

    // Now connect
    connect(m_nodesWatcher, SIGNAL(foldersAboutToBeAdded(FolderNode *, const QList<FolderNode*> &)),
            this, SLOT(foldersAboutToBeAdded(FolderNode *, const QList<FolderNode*> &)));
    connect(m_nodesWatcher, SIGNAL(foldersAdded()), this, SLOT(checkForNewApplicationProjects()));

    connect(m_nodesWatcher, SIGNAL(foldersRemoved()), this, SLOT(checkForDeletedApplicationProjects()));

    connect(m_nodesWatcher, SIGNAL(projectTypeChanged(Qt4ProjectManager::Internal::Qt4ProFileNode *,
                                                      const Qt4ProjectManager::Internal::Qt4ProjectType,
                                                      const Qt4ProjectManager::Internal::Qt4ProjectType)),
            this, SLOT(projectTypeChanged(Qt4ProjectManager::Internal::Qt4ProFileNode *,
                                          const Qt4ProjectManager::Internal::Qt4ProjectType,
                                          const Qt4ProjectManager::Internal::Qt4ProjectType)));

    connect(m_nodesWatcher, SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode *)),
            this, SLOT(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode *)));

}

void Qt4Project::saveSettingsImpl(ProjectExplorer::PersistentSettingsWriter &writer)
{
    Project::saveSettingsImpl(writer);
}

namespace {
    class FindQt4ProFiles: protected ProjectExplorer::NodesVisitor {
        QList<Qt4ProFileNode *> m_proFiles;

    public:
        QList<Qt4ProFileNode *> operator()(ProjectNode *root)
        {
            m_proFiles.clear();
            root->accept(this);
            return m_proFiles;
        }

    protected:
        virtual void visitProjectNode(ProjectNode *projectNode)
        {
            if (Qt4ProFileNode *pro = qobject_cast<Qt4ProFileNode *>(projectNode))
                m_proFiles.append(pro);
        }
    };
}

377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
void Qt4Project::addUiFilesToCodeModel(const QStringList &files)
{
    // if we already have a full updateCodeModel() scheduled
    // then we don't need to this seperately
    // since that one will add also all the ui files
    if (m_updateCodeModelTimer.isActive())
        return;
    m_addUiFilesTimer.start();
    m_uiFilesToAdd << files;
}

void Qt4Project::addUiFiles()
{
    if (m_updateCodeModelTimer.isActive())
        return;
    CppTools::CppModelManagerInterface *modelManager =
        ExtensionSystem::PluginManager::instance()->getObject<CppTools::CppModelManagerInterface>();
    modelManager->updateSourceFiles(m_uiFilesToAdd);
    m_uiFilesToAdd.clear();
}

con's avatar
con committed
398
399
400
401
402
void Qt4Project::scheduleUpdateCodeModel()
{
    m_updateCodeModelTimer.start();
}

403
404
405
406
407
QString Qt4Project::makeCommand(const QString &buildConfiguration) const
{
    return toolChain(buildConfiguration)->makeCommand();
}

dt's avatar
dt committed
408
409
ProjectExplorer::ToolChain *Qt4Project::toolChain(const QString &buildConfiguration) const
{
Roberto Raggi's avatar
--debug    
Roberto Raggi committed
410
411
    if (debug)
        qDebug()<<"Qt4Project::toolChain() for buildconfiguration:"<<buildConfiguration;
dt's avatar
dt committed
412
    Q_UNUSED(buildConfiguration);
dt's avatar
dt committed
413
    ToolChain *m_test= 0;
dt's avatar
dt committed
414
415
416
417
418
419
420
421
422
    QtVersion *version = qtVersion(activeBuildConfiguration());
    ToolChain::ToolChainType t = version->toolchainType();
    if (t == ToolChain::MinGW) {
        QStringList list = rootProjectNode()->variableValue(Internal::CxxCompilerVar);
        QString qmake_cxx = list.isEmpty() ? QString::null : list.first();
        Environment env = Environment::systemEnvironment();
        qtVersion(activeBuildConfiguration())->addToEnvironment(env);
        qmake_cxx = env.searchInPath(qmake_cxx);
        m_test = ToolChain::createMinGWToolChain(qmake_cxx, version->mingwDirectory());
423
        //qDebug()<<"Mingw ToolChain";
dt's avatar
dt committed
424
425
    } else if(t == ToolChain::MSVC) {
        m_test = ToolChain::createMSVCToolChain(version->msvcVersion());
426
        //qDebug()<<"MSVC ToolChain ("<<version->msvcVersion()<<")";
dt's avatar
dt committed
427
428
    } else if(t == ToolChain::WINCE) {
        m_test = ToolChain::createWinCEToolChain(version->msvcVersion(), version->wincePlatform());
429
        //qDebug()<<"WinCE ToolChain ("<<version->msvcVersion()<<","<<version->wincePlatform()<<")";
430
    } else if(t == ToolChain::GCC || t == ToolChain::LinuxICC) {
dt's avatar
dt committed
431
432
433
434
435
        QStringList list = rootProjectNode()->variableValue(Internal::CxxCompilerVar);
        QString qmake_cxx = list.isEmpty() ? QString::null : list.first();
        Environment env = Environment::systemEnvironment();
        qtVersion(activeBuildConfiguration())->addToEnvironment(env);
        qmake_cxx = env.searchInPath(qmake_cxx);
436
437
438
439
440
        if (qmake_cxx.isEmpty()) {
            // macx-xcode mkspec resets the value of QMAKE_CXX.
            // Unfortunately, we need a valid QMAKE_CXX to configure the parser.
            qmake_cxx = QLatin1String("cc");
        }
dt's avatar
dt committed
441
        m_test = ToolChain::createGccToolChain(qmake_cxx);
442
443
444
445
        //qDebug()<<"GCC ToolChain ("<<qmake_cxx<<")";
    } else {
        qDebug()<<"Could not detect ToolChain for"<<version->mkspec();
        qDebug()<<"Qt Creator doesn't know about the system includes, nor the systems defines.";
dt's avatar
dt committed
446
447
    }

dt's avatar
dt committed
448
    if (ToolChain::equals(m_test, m_toolChain)) {
dt's avatar
dt committed
449
450
451
452
453
454
455
456
        delete m_test;
    } else {
        delete m_toolChain;
        m_toolChain = m_test;
    }
    return m_toolChain;
}

con's avatar
con committed
457
458
459
460
461
462
void Qt4Project::updateCodeModel()
{
    if (debug)
        qDebug()<<"Qt4Project::updateCodeModel()";

    CppTools::CppModelManagerInterface *modelmanager =
463
464
        ExtensionSystem::PluginManager::instance()
            ->getObject<CppTools::CppModelManagerInterface>();
con's avatar
con committed
465

466
    if (!modelmanager)
con's avatar
con committed
467
468
469
470
471
472
473
474
475
        return;

    QStringList allIncludePaths;
    QStringList allFrameworkPaths;

    const QHash<QString, QString> versionInfo = qtVersion(activeBuildConfiguration())->versionInfo();
    const QString newQtIncludePath = versionInfo.value(QLatin1String("QT_INSTALL_HEADERS"));
    const QString newQtLibsPath = versionInfo.value(QLatin1String("QT_INSTALL_LIBS"));

dt's avatar
dt committed
476
    ToolChain *tc = toolChain(activeBuildConfiguration());
477
478
479
480
481
    QByteArray predefinedMacros;
    QList<HeaderPath> allHeaderPaths;
    if (tc) {
        predefinedMacros = tc->predefinedMacros();
        allHeaderPaths = tc->systemHeaderPaths();
482
483
484
485
486
487
        //qDebug()<<"Predifined Macros";
        //qDebug()<<tc->predefinedMacros();
        //qDebug()<<"";
        //qDebug()<<"System Header Paths";
        //foreach(const HeaderPath &hp, tc->systemHeaderPaths())
        //    qDebug()<<hp.path();
488
    }
dt's avatar
dt committed
489
490
491
492
493
    foreach (HeaderPath headerPath, allHeaderPaths) {
        if (headerPath.kind() == HeaderPath::FrameworkHeaderPath)
            allFrameworkPaths.append(headerPath.path());
        else
            allIncludePaths.append(headerPath.path());
con's avatar
con committed
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
    }

    allIncludePaths.append(newQtIncludePath);
    QDir dir(newQtIncludePath);
    foreach (QFileInfo info, dir.entryInfoList(QDir::Dirs)) {
        if (! info.fileName().startsWith(QLatin1String("Qt")))
            continue;
        allIncludePaths.append(info.absoluteFilePath());
    }

#ifdef Q_OS_MAC
    allFrameworkPaths.append(newQtLibsPath);
    // put QtXXX.framework/Headers directories in include path since that qmake's behavior
    QDir frameworkDir(newQtLibsPath);
    foreach (QFileInfo info, frameworkDir.entryInfoList(QDir::Dirs)) {
        if (! info.fileName().startsWith(QLatin1String("Qt")))
            continue;
        allIncludePaths.append(info.absoluteFilePath()+"/Headers");
    }
#endif

    FindQt4ProFiles findQt4ProFiles;
    QList<Qt4ProFileNode *> proFiles = findQt4ProFiles(rootProjectNode());
    QByteArray definedMacros;

    foreach (Qt4ProFileNode *pro, proFiles) {
        foreach (const QString def, pro->variableValue(DefinesVar)) {
            definedMacros += "#define ";
            const int index = def.indexOf(QLatin1Char('='));
            if (index == -1) {
                definedMacros += def.toLatin1();
                definedMacros += " 1\n";
            } else {
                const QString name = def.left(index);
                const QString value = def.mid(index + 1);
                definedMacros += name.toLatin1();
                definedMacros += ' ';
                definedMacros += value.toLocal8Bit();
                definedMacros += '\n';
            }
        }

        const QStringList proIncludePaths = pro->variableValue(IncludePathVar);
        foreach (QString includePath, proIncludePaths) {
            if (allIncludePaths.contains(includePath))
                continue;

            allIncludePaths.append(includePath);
        }
    }

dt's avatar
dt committed
545
546
547
    // Add mkspec directory
    allIncludePaths.append(qtVersion(activeBuildConfiguration())->mkspecPath());

con's avatar
con committed
548
549
550
551
552
553
    QStringList files;
    files += m_projectFiles->files[HeaderType];
    files += m_projectFiles->generatedFiles[HeaderType];
    files += m_projectFiles->files[SourceType];
    files += m_projectFiles->generatedFiles[SourceType];

554
    CppTools::CppModelManagerInterface::ProjectInfo pinfo = modelmanager->projectInfo(this);
con's avatar
con committed
555

556
557
558
559
560
    if (pinfo.defines == predefinedMacros             &&
            pinfo.includePaths == allIncludePaths     &&
            pinfo.frameworkPaths == allFrameworkPaths &&
            pinfo.sourceFiles == files) {
        modelmanager->updateProjectInfo(pinfo);
con's avatar
con committed
561
    } else {
562
        pinfo.defines = predefinedMacros;
con's avatar
con committed
563
        // pinfo->defines += definedMacros;   // ### FIXME: me
564
565
566
567
568
569
        pinfo.includePaths = allIncludePaths;
        pinfo.frameworkPaths = allFrameworkPaths;
        pinfo.sourceFiles = files;

        modelmanager->updateProjectInfo(pinfo);
        modelmanager->updateSourceFiles(pinfo.sourceFiles);
con's avatar
con committed
570
571
572
573
    }
}


574
575
576
///*!
//  Updates complete project
//  */
con's avatar
con committed
577
578
579
580
581
582
583
584
585
void Qt4Project::update()
{
    // TODO Maybe remove this method completely?
    m_rootProjectNode->update();
    //updateCodeModel();
}

ProFileReader *Qt4Project::createProFileReader() const
{
dt's avatar
dt committed
586
    ProFileReader *reader = new ProFileReader();
con's avatar
con committed
587
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
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
    connect(reader, SIGNAL(errorFound(const QString&)),
            this, SLOT(proFileParseError(const QString&)));
    QtVersion *version = qtVersion(activeBuildConfiguration());
    if (version->isValid()) {
        reader->setQtVersion(version);
    }
    return reader;
}

/*!
  Returns whether the project is an application, or has an application as a subproject.
 */
bool Qt4Project::isApplication() const
{
    return m_isApplication;
}

ProjectExplorer::ProjectExplorerPlugin *Qt4Project::projectExplorer() const
{
    return m_manager->projectExplorer();
}

ProjectExplorer::IProjectManager *Qt4Project::projectManager() const
{
    return m_manager;
}

Qt4Manager *Qt4Project::qt4ProjectManager() const
{
    return m_manager;
}

QString Qt4Project::name() const
{
    return QFileInfo(file()->fileName()).completeBaseName();
}

Core::IFile *Qt4Project::file() const
{
    return m_fileInfo;
}

QStringList Qt4Project::files(FilesMode fileMode) const
{
    QStringList files;
    for (int i = 0; i < FileTypeSize; ++i) {
        files += m_projectFiles->files[i];
        if (fileMode == AllFiles)
            files += m_projectFiles->generatedFiles[i];
    }
    return files;
}

QList<ProjectExplorer::Project*> Qt4Project::dependsOn()
{
    // NBS implement dependsOn
    return QList<Project *>();
}

void Qt4Project::addDefaultBuild()
{
    if (buildConfigurations().isEmpty()) {
        // We don't have any buildconfigurations, so this is a new project
        // The Project Load Wizard is a work of art
        // It will ask the user what kind of build setup he want
        // It will add missing Qt Versions
        // And get the project into a buildable state

        //TODO have a better check wheter there is already a configuration?
        QMakeStep *qmakeStep = 0;
        MakeStep *makeStep = 0;

        qmakeStep = new QMakeStep(this);
        qmakeStep->setValue("mkspec", "");
        insertBuildStep(1, qmakeStep);

        makeStep = new MakeStep(this);
        insertBuildStep(2, makeStep);

        MakeStep* cleanStep = new MakeStep(this);
        cleanStep->setValue("clean", true);
668
        insertCleanStep(1, cleanStep);
con's avatar
con committed
669
670
671
672
673

        ProjectLoadWizard wizard(this);
        wizard.execDialog();
    } else {
        // Restoring configuration
674
675
676
        foreach(const QString &bc, buildConfigurations()) {
            setValue(bc, "addQDumper", QVariant());
        }
con's avatar
con committed
677
678
679
680
681
682
683
684
685
686
    }
}

void Qt4Project::newBuildConfiguration(const QString &buildConfiguration)
{
    Q_UNUSED(buildConfiguration);
}

void Qt4Project::proFileParseError(const QString &errorMessage)
{
687
    Core::ICore::instance()->messageManager()->printToOutputPane(errorMessage);
con's avatar
con committed
688
689
690
691
692
693
694
695
696
697
}

Qt4ProFileNode *Qt4Project::rootProjectNode() const
{
    return m_rootProjectNode;
}

ProjectExplorer::Environment Qt4Project::baseEnvironment(const QString &buildConfiguration) const
{
    Environment env = useSystemEnvironment(buildConfiguration) ? Environment(QProcess::systemEnvironment()) : Environment();
dt's avatar
dt committed
698
    qtVersion(buildConfiguration)->addToEnvironment(env);
dt's avatar
dt committed
699
700
701
    ToolChain *tc = toolChain(buildConfiguration);
    if (tc)
        tc->addToEnvironment(env);
con's avatar
con committed
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
    return env;
}

ProjectExplorer::Environment Qt4Project::environment(const QString &buildConfiguration) const
{
    Environment env = baseEnvironment(buildConfiguration);
    env.modify(userEnvironmentChanges(buildConfiguration));
    return env;
}

QString Qt4Project::buildDirectory(const QString &buildConfiguration) const
{
    QString workingDirectory;
    if (value(buildConfiguration, "useShadowBuild").toBool())
        workingDirectory = value(buildConfiguration, "buildDirectory").toString();
hjk's avatar
hjk committed
717
    if (workingDirectory.isEmpty())
con's avatar
con committed
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
        workingDirectory = QFileInfo(file()->fileName()).absolutePath();
    return workingDirectory;
}

void Qt4Project::setUseSystemEnvironment(const QString &buildConfiguration, bool b)
{
    setValue(buildConfiguration, "clearSystemEnvironment", !b);
}

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

QString Qt4Project::qtDir(const QString &buildConfiguration) const
{
    QtVersion *version = qtVersion(buildConfiguration);
    if (version)
        return version->path();
    return QString::null;
}

QtVersion *Qt4Project::qtVersion(const QString &buildConfiguration) const
{
    return m_manager->versionManager()->version(qtVersionId(buildConfiguration));
}

int Qt4Project::qtVersionId(const QString &buildConfiguration) const
{
    if (debug)
        qDebug()<<"Looking for qtVersion ID of "<<buildConfiguration;
    int id = 0;
    QVariant vid = value(buildConfiguration, "QtVersionId");
hjk's avatar
hjk committed
752
    if (vid.isValid()) {
con's avatar
con committed
753
754
755
756
757
758
759
760
761
762
763
764
        id = vid.toInt();
        if (m_manager->versionManager()->version(id)->isValid()) {
            return id;
        } else {
            const_cast<Qt4Project *>(this)->setValue(buildConfiguration, "QtVersionId", 0);
            return 0;
        }
    } else {
        // Backward compatibilty, we might have just the name:
        QString vname = value(buildConfiguration, "QtVersion").toString();
        if (debug)
            qDebug()<<"  Backward compatibility reading QtVersion"<<vname;
hjk's avatar
hjk committed
765
        if (!vname.isEmpty()) {
con's avatar
con committed
766
767
            const QList<QtVersion *> &versions = m_manager->versionManager()->versions();
            foreach (const QtVersion * const version, versions) {
hjk's avatar
hjk committed
768
                if (version->name() == vname) {
con's avatar
con committed
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
                    if (debug)
                        qDebug()<<"found name in versions";
                    const_cast<Qt4Project *>(this)->setValue(buildConfiguration, "QtVersionId", version->uniqueId());
                    return version->uniqueId();
                }
            }
        }
    }
    if (debug)
        qDebug()<<"  using qtversion with id ="<<id;
    // Nothing found, reset to default
    const_cast<Qt4Project *>(this)->setValue(buildConfiguration, "QtVersionId", id);
    return id;
}

void Qt4Project::setQtVersion(const QString &buildConfiguration, int id)
{
    setValue(buildConfiguration, "QtVersionId", id);
}

BuildStepConfigWidget *Qt4Project::createConfigWidget()
{
791
    return new Qt4ProjectConfigWidget(this);
con's avatar
con committed
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
}

QList<BuildStepConfigWidget*> Qt4Project::subConfigWidgets()
{
    QList<BuildStepConfigWidget*> subWidgets;
    subWidgets << new Qt4BuildEnvironmentWidget(this);
    return subWidgets;
}

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

void Qt4Project::setUserEnvironmentChanges(const QString &buildConfig, const QList<ProjectExplorer::EnvironmentItem> &diff)
{
    setValue(buildConfig, "userEnvironmentChanges", EnvironmentItem::toStringList(diff));
}

/// **************************
/// Qt4ProjectBuildConfigWidget
/// **************************


void Qt4Project::collectApplicationProFiles(QList<Qt4ProFileNode *> &list, Qt4ProFileNode *node)
{
    if (node->projectType() == Internal::ApplicationTemplate
        || node->projectType() == Internal::ScriptTemplate) {
        list.append(node);
    }
    foreach (ProjectNode *n, node->subProjectNodes()) {
        Qt4ProFileNode *qt4ProFileNode = qobject_cast<Qt4ProFileNode *>(n);
        if (qt4ProFileNode)
            collectApplicationProFiles(list, qt4ProFileNode);
    }
}

void Qt4Project::foldersAboutToBeAdded(FolderNode *, const QList<FolderNode*> &nodes)
{
    QList<Qt4ProFileNode *> list;
    foreach (FolderNode *node, nodes) {
        Qt4ProFileNode *qt4ProFileNode = qobject_cast<Qt4ProFileNode *>(node);
        if (qt4ProFileNode)
            collectApplicationProFiles(list, qt4ProFileNode);
    }
    m_applicationProFileChange = list;
}

void Qt4Project::checkForNewApplicationProjects()
{
    // Check all new project nodes
    // against all runConfigurations

    foreach (Qt4ProFileNode *qt4proFile, m_applicationProFileChange) {
        bool found = false;
        foreach (QSharedPointer<RunConfiguration> rc, runConfigurations()) {
            QSharedPointer<Qt4RunConfiguration> qtrc = rc.dynamicCast<Qt4RunConfiguration>();
            if (qtrc && qtrc->proFilePath() == qt4proFile->path()) {
                found = true;
                break;
            }
        }
        if (!found) {
            QSharedPointer<Qt4RunConfiguration> newRc(new Qt4RunConfiguration(this, qt4proFile->path()));
            addRunConfiguration(newRc);
            m_isApplication = true;
        }
    }
}

void Qt4Project::checkForDeletedApplicationProjects()
{
    QStringList paths;
    foreach (Qt4ProFileNode * node, applicationProFiles())
        paths.append(node->path());

868
//    qDebug()<<"Still existing paths :"<<paths;
con's avatar
con committed
869
870
871
872
873
874

    QList<QSharedPointer<Qt4RunConfiguration> > removeList;
    foreach (QSharedPointer<RunConfiguration> rc, runConfigurations()) {
        if (QSharedPointer<Qt4RunConfiguration> qt4rc = rc.dynamicCast<Qt4RunConfiguration>()) {
            if (!paths.contains(qt4rc->proFilePath())) {
                removeList.append(qt4rc);
875
//                qDebug()<<"Removing runConfiguration for "<<qt4rc->proFilePath();
con's avatar
con committed
876
877
878
879
880
881
            }
        }
    }

    bool resetActiveRunConfiguration = false;
    QSharedPointer<RunConfiguration> rc(new ProjectExplorer::CustomExecutableRunConfiguration(this));
hjk's avatar
hjk committed
882
    foreach (QSharedPointer<Qt4RunConfiguration> qt4rc, removeList) {
con's avatar
con committed
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
        removeRunConfiguration(qt4rc);
        if (activeRunConfiguration() == qt4rc)
            resetActiveRunConfiguration = true;
    }

    if (runConfigurations().isEmpty()) {
        QSharedPointer<RunConfiguration> rc(new ProjectExplorer::CustomExecutableRunConfiguration(this));
        addRunConfiguration(rc);
        setActiveRunConfiguration(rc);
        m_isApplication = false;
    } else if (resetActiveRunConfiguration) {
        setActiveRunConfiguration(runConfigurations().first());
    }
}

QList<Qt4ProFileNode *> Qt4Project::applicationProFiles() const
{
    QList<Qt4ProFileNode *> list;
    collectApplicationProFiles(list, rootProjectNode());
    return list;
}

void Qt4Project::projectTypeChanged(Qt4ProFileNode *node, const Qt4ProjectType oldType, const Qt4ProjectType newType)
{
    if (oldType == Internal::ApplicationTemplate
        || oldType == Internal::ScriptTemplate) {
        // check wheter we need to delete a Run Configuration
        checkForDeletedApplicationProjects();
    }

    if (newType == Internal::ApplicationTemplate
        || newType == Internal::ScriptTemplate) {
        // add a new Run Configuration
        m_applicationProFileChange.clear();
        m_applicationProFileChange.append(node);
        checkForNewApplicationProjects();
    }
}

void Qt4Project::proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode *node)
{
    foreach (QSharedPointer<RunConfiguration> rc, runConfigurations()) {
        if (QSharedPointer<Qt4RunConfiguration> qt4rc = rc.dynamicCast<Qt4RunConfiguration>()) {
            if (qt4rc->proFilePath() == node->path()) {
927
                qt4rc->invalidateCachedTargetInformation();
con's avatar
con committed
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
            }
        }
    }
}


QMakeStep *Qt4Project::qmakeStep() const
{
    QMakeStep *qs = 0;
    foreach(BuildStep *bs, buildSteps())
        if ( (qs = qobject_cast<QMakeStep *>(bs)) != 0)
            return qs;
    return 0;
}

MakeStep *Qt4Project::makeStep() const
{
    MakeStep *qs = 0;
    foreach(BuildStep *bs, buildSteps())
        if ((qs = qobject_cast<MakeStep *>(bs)) != 0)
            return qs;
    return 0;
}
dt's avatar
dt committed
951

952
bool Qt4Project::hasSubNode(Qt4PriFileNode *root, const QString &path)
dt's avatar
dt committed
953
{
954
955
956
957
958
    if (root->path() == path)
        return true;
    foreach (FolderNode *fn, root->subFolderNodes()) {
        if (qobject_cast<Qt4ProFileNode *>(fn)) {
            // we aren't interested in pro file nodes
hjk's avatar
hjk committed
959
        } else if (Qt4PriFileNode *qt4prifilenode = qobject_cast<Qt4PriFileNode *>(fn)) {
960
961
962
963
964
            if (hasSubNode(qt4prifilenode, path))
                return true;
        }
    }
    return false;
dt's avatar
dt committed
965
966
967
968
}

void Qt4Project::findProFile(const QString& fileName, Qt4ProFileNode *root, QList<Qt4ProFileNode *> &list)
{
969
    if (hasSubNode(root, fileName))
dt's avatar
dt committed
970
971
972
973
974
975
976
977
978
        list.append(root);

    foreach (FolderNode *fn, root->subFolderNodes())
        if (Qt4ProFileNode *qt4proFileNode =  qobject_cast<Qt4ProFileNode *>(fn))
            findProFile(fileName, qt4proFileNode, list);
}

void Qt4Project::notifyChanged(const QString &name)
{
979
980
981
982
983
984
    if (files(Qt4Project::ExcludeGeneratedFiles).contains(name)) {
        QList<Qt4ProFileNode *> list;
        findProFile(name, rootProjectNode(), list);
        foreach(Qt4ProFileNode *node, list)
            node->update();
    }
dt's avatar
dt committed
985
}
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025

void Qt4Project::invalidateCachedTargetInformation()
{
    foreach(QSharedPointer<RunConfiguration> rc, runConfigurations()) {
        QSharedPointer<Qt4RunConfiguration> qt4rc = rc.dynamicCast<Qt4RunConfiguration>();
        if (qt4rc) {
            qt4rc->invalidateCachedTargetInformation();
        }
    }
}


/*!
  Handle special case were a subproject of the qt directory is opened, and
  qt was configured to be built as a shadow build -> also build in the sub-
  project in the correct shadow build directory.
  */

// TODO this function should be called on project first load
// and it should check against all configured qt versions ?
//void Qt4Project::detectQtShadowBuild(const QString &buildConfiguration) const
//{
//    if (project()->activeBuildConfiguration() == buildConfiguration)
//        return;
//
//    const QString currentQtDir = static_cast<Qt4Project *>(project())->qtDir(buildConfiguration);
//    const QString qtSourceDir = static_cast<Qt4Project *>(project())->qtVersion(buildConfiguration)->sourcePath();
//
//    // if the project is a sub-project of Qt and Qt was shadow-built then automatically
//    // adjust the build directory of the sub-project.
//    if (project()->file()->fileName().startsWith(qtSourceDir) && qtSourceDir != currentQtDir) {
//        project()->setValue(buildConfiguration, "useShadowBuild", true);
//        QString buildDir = QFileInfo(project()->file()->fileName()).absolutePath();
//        buildDir.replace(qtSourceDir, currentQtDir);
//        project()->setValue(buildConfiguration, "buildDirectory", buildDir);
//        project()->setValue(buildConfiguration, "autoShadowBuild", true);
//    }
//}