qt4project.cpp 38.9 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
con's avatar
con committed
8
**
9
**
10
** GNU Lesser General Public License Usage
11
**
hjk's avatar
hjk committed
12
13
14
15
16
17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21
22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23
24
25
26
27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28
** If you have questions regarding the use of this file, please contact
Tobias Hunger's avatar
Tobias Hunger committed
29
** Nokia at info@qt.nokia.com.
con's avatar
con committed
30
**
31
**************************************************************************/
hjk's avatar
hjk committed
32

con's avatar
con committed
33
#include "qt4project.h"
hjk's avatar
hjk committed
34

con's avatar
con committed
35
#include "profilereader.h"
Tobias Hunger's avatar
Tobias Hunger committed
36
#include "qt4projectmanager.h"
con's avatar
con committed
37
38
39
#include "makestep.h"
#include "qmakestep.h"
#include "qt4nodes.h"
40
#include "qt4projectconfigwidget.h"
con's avatar
con committed
41
42
#include "qt4projectmanagerconstants.h"
#include "projectloadwizard.h"
dt's avatar
dt committed
43
#include "qt4buildconfiguration.h"
44
#include "findqt4profiles.h"
45
#include "qmldumptool.h"
dt's avatar
dt committed
46
#include "baseqtversion.h"
47

48
#include <coreplugin/icore.h>
49
#include <coreplugin/icontext.h>
con's avatar
con committed
50
51
#include <coreplugin/messagemanager.h>
#include <coreplugin/coreconstants.h>
dt's avatar
dt committed
52
#include <coreplugin/progressmanager/progressmanager.h>
53
#include <extensionsystem/pluginmanager.h>
54
#include <cplusplus/ModelManagerInterface.h>
55
#include <qmljs/qmljsmodelmanagerinterface.h>
56
#include <projectexplorer/toolchain.h>
57
#include <projectexplorer/headerpath.h>
58
#include <projectexplorer/buildenvironmentwidget.h>
Tobias Hunger's avatar
Tobias Hunger committed
59
#include <projectexplorer/customexecutablerunconfiguration.h>
60
#include <projectexplorer/projectexplorer.h>
61
#include <projectexplorer/projectexplorerconstants.h>
62
#include <utils/qtcassert.h>
con's avatar
con committed
63
64

#include <QtCore/QDebug>
65
66
#include <QtCore/QDir>
#include <QtGui/QFileDialog>
67
#include <QtGui/QInputDialog>
con's avatar
con committed
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
178
179
180
181
182
183
184
185

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)
{
}

186
bool Qt4ProjectFile::save(QString *, const QString &)
con's avatar
con committed
187
{
188
189
    // This is never used
    return false;
con's avatar
con committed
190
191
}

dt's avatar
dt committed
192
193
194
195
196
197
198
void Qt4ProjectFile::rename(const QString &newName)
{
    // Can't happen
    Q_UNUSED(newName);
    Q_ASSERT(false);
}

con's avatar
con committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
{
221
    return false; // we save after changing anyway
con's avatar
con committed
222
223
224
225
}

bool Qt4ProjectFile::isReadOnly() const
{
dt's avatar
dt committed
226
227
    QFileInfo fi(m_filePath);
    return !fi.isWritable();
con's avatar
con committed
228
229
230
231
232
233
234
}

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

235
Core::IFile::ReloadBehavior Qt4ProjectFile::reloadBehavior(ChangeTrigger state, ChangeType type) const
con's avatar
con committed
236
{
237
238
239
240
241
    Q_UNUSED(state)
    Q_UNUSED(type)
    return BehaviorSilent;
}

242
bool Qt4ProjectFile::reload(QString *errorString, ReloadFlag flag, ChangeType type)
243
{
244
    Q_UNUSED(errorString)
245
246
    Q_UNUSED(flag)
    Q_UNUSED(type)
247
    return true;
con's avatar
con committed
248
249
250
}

/*!
251
  \class Qt4Project
con's avatar
con committed
252
253
254
255
256
257

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

Qt4Project::Qt4Project(Qt4Manager *manager, const QString& fileName) :
    m_manager(manager),
dt's avatar
dt committed
258
    m_rootProjectNode(0),
con's avatar
con committed
259
260
    m_nodesWatcher(new Internal::Qt4NodesWatcher(this)),
    m_fileInfo(new Qt4ProjectFile(this, fileName, this)),
261
    m_projectFiles(new Qt4ProjectFiles),
dt's avatar
dt committed
262
263
264
265
266
    m_proFileOption(0),
    m_asyncUpdateFutureInterface(0),
    m_pendingEvaluateFuturesCount(0),
    m_asyncUpdateState(NoState),
    m_cancelEvaluate(false)
con's avatar
con committed
267
{
268
269
270
    setProjectContext(Core::Context(Qt4ProjectManager::Constants::PROJECT_ID));
    setProjectLanguage(Core::Context(ProjectExplorer::Constants::LANG_CXX));

dt's avatar
dt committed
271
272
273
    m_asyncUpdateTimer.setSingleShot(true);
    m_asyncUpdateTimer.setInterval(3000);
    connect(&m_asyncUpdateTimer, SIGNAL(timeout()), this, SLOT(asyncUpdate()));
con's avatar
con committed
274
275
276
277
}

Qt4Project::~Qt4Project()
{
278
    m_codeModelFuture.cancel();
279
    m_asyncUpdateState = ShuttingDown;
dt's avatar
dt committed
280
    m_manager->unregisterProject(this);
con's avatar
con committed
281
    delete m_projectFiles;
282
283
    m_cancelEvaluate = true;
    delete m_rootProjectNode;
con's avatar
con committed
284
285
286
287
288
289
290
291
292
293
294
295
296
297
}

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

298
bool Qt4Project::fromMap(const QVariantMap &map)
con's avatar
con committed
299
{
300
301
    if (!Project::fromMap(map))
        return false;
con's avatar
con committed
302

Tobias Hunger's avatar
Tobias Hunger committed
303
304
    // Prune targets without buildconfigurations:
    // This can happen esp. when updating from a old version of Qt Creator
dt's avatar
dt committed
305
    QList<Target *>ts = targets();
Tobias Hunger's avatar
Tobias Hunger committed
306
    foreach (Target *t, ts) {
307
308
        if (t->buildConfigurations().isEmpty()) {
            qWarning() << "Removing" << t->id() << "since it has no buildconfigurations!";
Tobias Hunger's avatar
Tobias Hunger committed
309
            removeTarget(t);
310
        }
Tobias Hunger's avatar
Tobias Hunger committed
311
312
313
314
    }

    // Add buildconfigurations so we can parse the pro-files.
    if (targets().isEmpty())
315
        addDefaultBuild();
con's avatar
con committed
316

317
318
319
320
321
    if (targets().isEmpty()) {
        qWarning() << "Unable to create targets!";
        return false;
    }

Tobias Hunger's avatar
Tobias Hunger committed
322
323
    Q_ASSERT(activeTarget());
    Q_ASSERT(activeTarget()->activeBuildConfiguration());
324

dt's avatar
dt committed
325
326
327
328
329
    m_manager->registerProject(this);

    m_rootProjectNode = new Qt4ProFileNode(this, m_fileInfo->fileName(), this);
    m_rootProjectNode->registerWatcher(m_nodesWatcher);

Tobias Hunger's avatar
Tobias Hunger committed
330
331
332
    update();
    updateFileList();
    // This might be incorrect, need a full update
333
    updateCodeModels();
334

335
336
    foreach (Target *t, targets())
        static_cast<Qt4BaseTarget *>(t)->createApplicationProFiles();
dt's avatar
dt committed
337

dt's avatar
dt committed
338
339
    foreach (Target *t, targets())
        onAddedTarget(t);
con's avatar
con committed
340

341
342
343
344
345
    connect(m_nodesWatcher, SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool)),
            this, SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode *,bool)));

    connect(m_nodesWatcher, SIGNAL(proFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode*)),
            this, SIGNAL(proFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode*)));
346

347
348
349
350
351
352
353
354
    // Now we emit update once :)
    m_rootProjectNode->emitProFileUpdated();


    // Setup Qt versions supported (== possible targets).
    connect(this, SIGNAL(addedTarget(ProjectExplorer::Target*)),
            this, SLOT(onAddedTarget(ProjectExplorer::Target*)));

Tobias Hunger's avatar
Tobias Hunger committed
355
356
357
    connect(this, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
            this, SLOT(activeTargetWasChanged()));

358
359
    emit fromMapFinished();

dt's avatar
dt committed
360
    return true;
con's avatar
con committed
361
362
}

363
Qt4BaseTarget *Qt4Project::activeTarget() const
364
{
365
    return static_cast<Qt4BaseTarget *>(Project::activeTarget());
366
367
}

Tobias Hunger's avatar
Tobias Hunger committed
368
369
370
void Qt4Project::onAddedTarget(ProjectExplorer::Target *t)
{
    Q_ASSERT(t);
371
    Qt4BaseTarget *qt4target = qobject_cast<Qt4BaseTarget *>(t);
372
373
374
    Q_ASSERT(qt4target);
    connect(qt4target, SIGNAL(buildDirectoryInitialized()),
            this, SIGNAL(buildDirectoryInitialized()));
375
376
    connect(qt4target, SIGNAL(proFileEvaluateNeeded(Qt4ProjectManager::Qt4BaseTarget*)),
            this, SLOT(proFileEvaluateNeeded(Qt4ProjectManager::Qt4BaseTarget*)));
dt's avatar
dt committed
377
378
}

379
void Qt4Project::proFileEvaluateNeeded(Qt4ProjectManager::Qt4BaseTarget *target)
dt's avatar
dt committed
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
{
    if (activeTarget() == target)
        scheduleAsyncUpdate();
}

/// equalFileList compares two file lists ignoring
/// <configuration> without generating temporary lists

bool Qt4Project::equalFileList(const QStringList &a, const QStringList &b)
{
    if (abs(a.length() - b.length()) > 1)
        return false;
    QStringList::const_iterator ait = a.constBegin();
    QStringList::const_iterator bit = b.constBegin();
    QStringList::const_iterator aend = a.constEnd();
    QStringList::const_iterator bend = b.constEnd();

    while (ait != aend && bit != bend) {
        if (*ait == QLatin1String("<configuration>"))
            ++ait;
        else if (*bit == QLatin1String("<configuration>"))
            ++bit;
        else if (*ait == *bit)
            ++ait, ++bit;
        else
           return false;
    }
    return (ait == aend && bit == bend);
Tobias Hunger's avatar
Tobias Hunger committed
408
409
}

410
void Qt4Project::updateCodeModels()
con's avatar
con committed
411
412
413
414
{
    if (debug)
        qDebug()<<"Qt4Project::updateCodeModel()";

Tobias Hunger's avatar
Tobias Hunger committed
415
416
417
    if (!activeTarget() || !activeTarget()->activeBuildConfiguration())
        return;

418
419
420
421
422
423
    updateCppCodeModel();
    updateQmlJSCodeModel();
}

void Qt4Project::updateCppCodeModel()
{
Tobias Hunger's avatar
Tobias Hunger committed
424
    Qt4BuildConfiguration *activeBC = activeTarget()->activeBuildConfiguration();
425

426
    CPlusPlus::CppModelManagerInterface *modelmanager =
427
        CPlusPlus::CppModelManagerInterface::instance();
con's avatar
con committed
428

429
    if (!modelmanager)
con's avatar
con committed
430
431
        return;

432
    // Collect global headers/defines
433
434
435
    QStringList predefinedIncludePaths;
    QStringList predefinedFrameworkPaths;
    QByteArray predefinedMacros;
con's avatar
con committed
436

dt's avatar
dt committed
437
438
439
    QString qtFrameworkPath;
    if (activeBC->qtVersion())
        qtFrameworkPath = activeBC->qtVersion()->frameworkInstallPath();
440
441
442
    if (!qtFrameworkPath.isEmpty())
        predefinedFrameworkPaths.append(qtFrameworkPath);

dt's avatar
dt committed
443
    ToolChain *tc = activeBC->toolChain();
444
445
    if (tc) {
        predefinedMacros = tc->predefinedMacros();
446
447

        QList<HeaderPath> headers = tc->systemHeaderPaths();
dt's avatar
dt committed
448
        if (activeBC->qtVersion())
dt's avatar
dt committed
449
            headers.append(activeBC->qtVersion()->systemHeaderPathes());
450
        foreach (const HeaderPath &headerPath, headers) {
dt's avatar
dt committed
451
452
453
454
455
            if (headerPath.kind() == HeaderPath::FrameworkHeaderPath)
                predefinedFrameworkPaths.append(headerPath.path());
            else
                predefinedIncludePaths.append(headerPath.path());
        }
con's avatar
con committed
456
457
    }

Roberto Raggi's avatar
Compile    
Roberto Raggi committed
458
459
    FindQt4ProFiles findQt4ProFiles;
    QList<Qt4ProFileNode *> proFiles = findQt4ProFiles(rootProjectNode());
dt's avatar
dt committed
460
461
    QByteArray allDefinedMacros = predefinedMacros;
    QStringList allIncludePaths;
Roberto Raggi's avatar
Compile    
Roberto Raggi committed
462
    QStringList allFrameworkPaths = predefinedFrameworkPaths;
463
    QStringList allPrecompileHeaders;
Roberto Raggi's avatar
Compile    
Roberto Raggi committed
464

465
    // Collect per .pro file information
con's avatar
con committed
466
    foreach (Qt4ProFileNode *pro, proFiles) {
dt's avatar
dt committed
467
        allPrecompileHeaders.append(pro->variableValue(PrecompiledHeaderVar));
468

469
        // Add custom defines
dt's avatar
dt committed
470

471
        foreach (const QString &def, pro->variableValue(DefinesVar)) {
dt's avatar
dt committed
472
            allDefinedMacros += "#define ";
con's avatar
con committed
473
474
            const int index = def.indexOf(QLatin1Char('='));
            if (index == -1) {
dt's avatar
dt committed
475
476
                allDefinedMacros += def.toLatin1();
                allDefinedMacros += " 1\n";
con's avatar
con committed
477
478
479
            } else {
                const QString name = def.left(index);
                const QString value = def.mid(index + 1);
dt's avatar
dt committed
480
481
482
483
                allDefinedMacros += name.toLatin1();
                allDefinedMacros += ' ';
                allDefinedMacros += value.toLocal8Bit();
                allDefinedMacros += '\n';
con's avatar
con committed
484
485
486
487
            }
        }

        const QStringList proIncludePaths = pro->variableValue(IncludePathVar);
488
        foreach (const QString &includePath, proIncludePaths) {
489
            if (!allIncludePaths.contains(includePath))
490
                allIncludePaths.append(includePath);
491
        }
con's avatar
con committed
492
493
    }

dt's avatar
dt committed
494
    // Add mkspec directory
dt's avatar
dt committed
495
496
    if (activeBC->qtVersion())
        allIncludePaths.append(activeBC->qtVersion()->mkspecPath());
dt's avatar
dt committed
497

dt's avatar
dt committed
498
    allIncludePaths.append(predefinedIncludePaths);
499

con's avatar
con committed
500
501
502
503
504
505
    QStringList files;
    files += m_projectFiles->files[HeaderType];
    files += m_projectFiles->generatedFiles[HeaderType];
    files += m_projectFiles->files[SourceType];
    files += m_projectFiles->generatedFiles[SourceType];

506
    CPlusPlus::CppModelManagerInterface::ProjectInfo pinfo = modelmanager->projectInfo(this);
con's avatar
con committed
507

508
509
    //qDebug()<<"Using precompiled header"<<allPrecompileHeaders;

dt's avatar
dt committed
510
511
512
    bool fileList = equalFileList(pinfo.sourceFiles, files);

    if (pinfo.defines == allDefinedMacros
513
514
        && pinfo.includePaths == allIncludePaths
        && pinfo.frameworkPaths == allFrameworkPaths
dt's avatar
dt committed
515
        && fileList
516
        && pinfo.precompiledHeaders == allPrecompileHeaders) {
517
        // Nothing to update...
con's avatar
con committed
518
    } else {
dt's avatar
dt committed
519
520
521
522
523
524
        pinfo.sourceFiles.clear();
        if (pinfo.defines != allDefinedMacros
            || pinfo.includePaths != allIncludePaths
            || pinfo.frameworkPaths != allFrameworkPaths
            || pinfo.precompiledHeaders != allPrecompileHeaders)
        {
525
526
527
            pinfo.sourceFiles.append(QLatin1String("<configuration>"));
        }

dt's avatar
dt committed
528
529
        //pinfo.defines = predefinedMacros;
        pinfo.defines = allDefinedMacros;
530
531
        pinfo.includePaths = allIncludePaths;
        pinfo.frameworkPaths = allFrameworkPaths;
dt's avatar
dt committed
532
        pinfo.sourceFiles += files;
533
        pinfo.precompiledHeaders = allPrecompileHeaders;
534
535

        modelmanager->updateProjectInfo(pinfo);
dt's avatar
dt committed
536
        m_codeModelFuture = modelmanager->updateSourceFiles(pinfo.sourceFiles);
con's avatar
con committed
537
    }
538
539
}

540
541
void Qt4Project::updateQmlJSCodeModel()
{
542
    QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
543
544
545
    if (!modelManager)
        return;

546
    QmlJS::ModelManagerInterface::ProjectInfo projectInfo = modelManager->projectInfo(this);
547
    projectInfo.sourceFiles = m_projectFiles->files[QMLType];
548
549
550
551
552
553
554

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

    foreach (Qt4ProFileNode *node, proFiles) {
        projectInfo.importPaths.append(node->variableValue(QmlImportPathVar));
    }
555
    bool preferDebugDump = false;
556
    if (activeTarget() && activeTarget()->activeBuildConfiguration()) {
dt's avatar
dt committed
557
558
559
        preferDebugDump = activeTarget()->activeBuildConfiguration()->qmakeBuildConfiguration() & BaseQtVersion::DebugBuild;
        BaseQtVersion *qtVersion = activeTarget()->activeBuildConfiguration()->qtVersion();
        if (qtVersion && qtVersion->isValid()) {
560
561
562
563
564
            const QString qtVersionImportPath = qtVersion->versionInfo().value("QT_INSTALL_IMPORTS");
            if (!qtVersionImportPath.isEmpty())
                projectInfo.importPaths += qtVersionImportPath;
        }
    }
565
    QmlDumpTool::pathAndEnvironment(this, preferDebugDump, &projectInfo.qmlDumpPath, &projectInfo.qmlDumpEnvironment);
566
567
    projectInfo.importPaths.removeDuplicates();

568
    modelManager->updateProjectInfo(projectInfo);
569
570
}

571
572
573
///*!
//  Updates complete project
//  */
con's avatar
con committed
574
575
void Qt4Project::update()
{
dt's avatar
dt committed
576
577
    if (debug)
        qDebug()<<"Doing sync update";
con's avatar
con committed
578
    m_rootProjectNode->update();
579

dt's avatar
dt committed
580
581
    if (debug)
        qDebug()<<"State is now Base";
dt's avatar
dt committed
582
    m_asyncUpdateState = Base;
583
    activeTarget()->activeBuildConfiguration()->setEnabled(true);
dt's avatar
dt committed
584
585
586
587
}

void Qt4Project::scheduleAsyncUpdate(Qt4ProFileNode *node)
{
dt's avatar
dt committed
588
589
    if (m_asyncUpdateState == ShuttingDown)
        return;
590

dt's avatar
dt committed
591
592
    if (debug)
        qDebug()<<"schduleAsyncUpdate (node)";
dt's avatar
dt committed
593
594
595
    Q_ASSERT(m_asyncUpdateState != NoState);

    if (m_cancelEvaluate) {
dt's avatar
dt committed
596
597
        if (debug)
            qDebug()<<"  Already canceling, nothing to do";
dt's avatar
dt committed
598
599
600
601
602
603
        // A cancel is in progress
        // That implies that a full update is going to happen afterwards
        // So we don't need to do anything
        return;
    }

604
605
    activeTarget()->activeBuildConfiguration()->setEnabled(false);

dt's avatar
dt committed
606
607
    if (m_asyncUpdateState == AsyncFullUpdatePending) {
        // Just postpone
dt's avatar
dt committed
608
609
        if (debug)
            qDebug()<<"  full update pending, restarting timer";
dt's avatar
dt committed
610
611
612
        m_asyncUpdateTimer.start();
    } else if (m_asyncUpdateState == AsyncPartialUpdatePending
               || m_asyncUpdateState == Base) {
dt's avatar
dt committed
613
614
        if (debug)
            qDebug()<<"  adding node to async update list, setting state to AsyncPartialUpdatePending";
dt's avatar
dt committed
615
616
617
618
619
        // Add the node
        m_asyncUpdateState = AsyncPartialUpdatePending;

        QList<Internal::Qt4ProFileNode *>::iterator it;
        bool add = true;
dt's avatar
dt committed
620
621
        if (debug)
            qDebug()<<"scheduleAsyncUpdate();"<<m_partialEvaluate.size()<<"nodes";
dt's avatar
dt committed
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
        it = m_partialEvaluate.begin();
        while (it != m_partialEvaluate.end()) {
            if (*it == node) {
                add = false;
                break;
            } else if (node->isParent(*it)) { // We already have the parent in the list, nothing to do
                add = false;
                break;
            } else if ((*it)->isParent(node)) { // The node is the parent of a child already in the list
                it = m_partialEvaluate.erase(it);
            } else {
                ++it;
            }
        }

        if (add)
            m_partialEvaluate.append(node);
        // and start the timer anew
        m_asyncUpdateTimer.start();
    } else if (m_asyncUpdateState == AsyncUpdateInProgress) {
        // A update is in progress
        // And this slot only gets called if a file changed on disc
        // So we'll play it safe and schedule a complete evaluate
        // This might trigger if due to version control a few files
        // change a partial update gets in progress and then another
        // batch of changes come in, which triggers a full update
        // even if that's not really needed
dt's avatar
dt committed
649
650
        if (debug)
            qDebug()<<"  Async update in progress, scheduling new one afterwards";
dt's avatar
dt committed
651
652
653
654
655
656
        scheduleAsyncUpdate();
    }
}

void Qt4Project::scheduleAsyncUpdate()
{
dt's avatar
dt committed
657
658
    if (debug)
        qDebug()<<"scheduleAsyncUpdate";
dt's avatar
dt committed
659
660
    if (m_asyncUpdateState == ShuttingDown)
        return;
661

dt's avatar
dt committed
662
663
664
    Q_ASSERT(m_asyncUpdateState != NoState);
    if (m_cancelEvaluate) { // we are in progress of canceling
                            // and will start the evaluation after that
dt's avatar
dt committed
665
666
        if (debug)
            qDebug()<<"  canceling is in progress, doing nothing";
dt's avatar
dt committed
667
668
669
        return;
    }
    if (m_asyncUpdateState == AsyncUpdateInProgress) {
dt's avatar
dt committed
670
671
        if (debug)
            qDebug()<<"  update in progress, canceling and setting state to full update pending";
dt's avatar
dt committed
672
673
        m_cancelEvaluate = true;
        m_asyncUpdateState = AsyncFullUpdatePending;
674
        activeTarget()->activeBuildConfiguration()->setEnabled(false);
675
        m_rootProjectNode->emitProFileInvalidated();
dt's avatar
dt committed
676
677
678
        return;
    }

dt's avatar
dt committed
679
680
    if (debug)
        qDebug()<<"  starting timer for full update, setting state to full update pending";
dt's avatar
dt committed
681
    m_partialEvaluate.clear();
682
    activeTarget()->activeBuildConfiguration()->setEnabled(false);
683
    m_rootProjectNode->emitProFileInvalidated();
dt's avatar
dt committed
684
685
    m_asyncUpdateState = AsyncFullUpdatePending;
    m_asyncUpdateTimer.start();
686
687
688

    // Cancel running code model update
    m_codeModelFuture.cancel();
dt's avatar
dt committed
689
690
691
692
693
694
}


void Qt4Project::incrementPendingEvaluateFutures()
{
    ++m_pendingEvaluateFuturesCount;
dt's avatar
dt committed
695
696
    if (debug)
        qDebug()<<"incrementPendingEvaluateFutures to"<<m_pendingEvaluateFuturesCount;
dt's avatar
dt committed
697
698
699
700
701
702
703
704
705

    m_asyncUpdateFutureInterface->setProgressRange(m_asyncUpdateFutureInterface->progressMinimum(),
                                                  m_asyncUpdateFutureInterface->progressMaximum() + 1);
}

void Qt4Project::decrementPendingEvaluateFutures()
{
    --m_pendingEvaluateFuturesCount;

dt's avatar
dt committed
706
707
    if (debug)
        qDebug()<<"decrementPendingEvaluateFutures to"<<m_pendingEvaluateFuturesCount;
dt's avatar
dt committed
708
709
710

    m_asyncUpdateFutureInterface->setProgressValue(m_asyncUpdateFutureInterface->progressValue() + 1);
    if (m_pendingEvaluateFuturesCount == 0) {
dt's avatar
dt committed
711
712
        if (debug)
            qDebug()<<"  WOHOO, no pending futures, cleaning up";
dt's avatar
dt committed
713
        // We are done!
dt's avatar
dt committed
714
715
        if (debug)
            qDebug()<<"  reporting finished";
dt's avatar
dt committed
716
717
718
719
720
721
722
        m_asyncUpdateFutureInterface->reportFinished();
        delete m_asyncUpdateFutureInterface;
        m_asyncUpdateFutureInterface = 0;
        m_cancelEvaluate = false;

        // TODO clear the profile cache ?
        if (m_asyncUpdateState == AsyncFullUpdatePending || m_asyncUpdateState == AsyncPartialUpdatePending) {
dt's avatar
dt committed
723
724
            if (debug)
                qDebug()<<"  Oh update is pending start the timer";
dt's avatar
dt committed
725
            m_asyncUpdateTimer.start();
726
        } else  if (m_asyncUpdateState != ShuttingDown){
Tobias Hunger's avatar
Tobias Hunger committed
727
            // After being done, we need to call:
728
            activeTarget()->activeBuildConfiguration()->setEnabled(true);
729
730
            foreach (Target *t, targets())
                static_cast<Qt4BaseTarget *>(t)->createApplicationProFiles();
731
            updateFileList();
732
            updateCodeModels();
dt's avatar
dt committed
733
734
            if (debug)
                qDebug()<<"  Setting state to Base";
dt's avatar
dt committed
735
736
737
738
739
740
741
742
743
744
745
746
            m_asyncUpdateState = Base;
        }
    }
}

bool Qt4Project::wasEvaluateCanceled()
{
    return m_cancelEvaluate;
}

void Qt4Project::asyncUpdate()
{
dt's avatar
dt committed
747
748
    if (debug)
        qDebug()<<"async update, timer expired, doing now";
dt's avatar
dt committed
749
750
751
752
753
    Q_ASSERT(!m_asyncUpdateFutureInterface);
    m_asyncUpdateFutureInterface = new QFutureInterface<void>();

    Core::ProgressManager *progressManager = Core::ICore::instance()->progressManager();

con's avatar
con committed
754
755
    m_asyncUpdateFutureInterface->setProgressRange(0, 0);
    progressManager->addTask(m_asyncUpdateFutureInterface->future(), tr("Evaluating"), Constants::PROFILE_EVALUATE);
dt's avatar
dt committed
756
757
    if (debug)
        qDebug()<<"  adding task";
dt's avatar
dt committed
758
759
760
761

    m_asyncUpdateFutureInterface->reportStarted();

    if (m_asyncUpdateState == AsyncFullUpdatePending) {
dt's avatar
dt committed
762
763
        if (debug)
            qDebug()<<"  full update, starting with root node";
dt's avatar
dt committed
764
765
        m_rootProjectNode->asyncUpdate();
    } else {
dt's avatar
dt committed
766
767
        if (debug)
            qDebug()<<"  partial update,"<<m_partialEvaluate.size()<<"nodes to update";
dt's avatar
dt committed
768
769
770
771
772
        foreach(Qt4ProFileNode *node, m_partialEvaluate)
            node->asyncUpdate();
    }

    m_partialEvaluate.clear();
dt's avatar
dt committed
773
774
    if (debug)
        qDebug()<<"  Setting state to AsyncUpdateInProgress";
dt's avatar
dt committed
775
    m_asyncUpdateState = AsyncUpdateInProgress;
con's avatar
con committed
776
777
778
779
780
781
782
783
784
785
786
787
}

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

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

788
QString Qt4Project::displayName() const
con's avatar
con committed
789
790
791
792
{
    return QFileInfo(file()->fileName()).completeBaseName();
}

Tobias Hunger's avatar
Tobias Hunger committed
793
794
QString Qt4Project::id() const
{
Tobias Hunger's avatar
Tobias Hunger committed
795
    return QLatin1String(Constants::QT4PROJECT_ID);
Tobias Hunger's avatar
Tobias Hunger committed
796
797
}

con's avatar
con committed
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
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;
}

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
// Find the folder that contains a file a certain type (recurse down)
static FolderNode *folderOf(FolderNode *in, FileType fileType, const QString &fileName)
{
    foreach(FileNode *fn, in->fileNodes())
        if (fn->fileType() == fileType && fn->path() == fileName)
            return in;
    foreach(FolderNode *folder, in->subFolderNodes())
        if (FolderNode *pn = folderOf(folder, fileType, fileName))
            return pn;
    return 0;
}

// Find the Qt4ProFileNode that contains a file of a certain type.
// First recurse down to folder, then find the pro-file.
static Qt4ProFileNode *proFileNodeOf(Qt4ProFileNode *in, FileType fileType, const QString &fileName)
{
    for (FolderNode *folder =  folderOf(in, fileType, fileName); folder; folder = folder->parentFolderNode())
        if (Qt4ProFileNode *proFile = qobject_cast<Qt4ProFileNode *>(folder))
            return proFile;
    return 0;
}

QString Qt4Project::generatedUiHeader(const QString &formFile) const
{
    // Look in sub-profiles as SessionManager::projectForFile returns
    // the top-level project only.
    if (m_rootProjectNode)
        if (const Qt4ProFileNode *pro = proFileNodeOf(m_rootProjectNode, FormType, formFile))
            return Qt4ProFileNode::uiHeaderFile(pro->uiDirectory(), formFile);
    return QString();
}

con's avatar
con committed
846
847
848
849
850
851
852
853
QList<ProjectExplorer::Project*> Qt4Project::dependsOn()
{
    // NBS implement dependsOn
    return QList<Project *>();
}

void Qt4Project::addDefaultBuild()
{
854
855
856
857
858
859
    // TODO this could probably refactored
    // That is the ProjectLoadWizard divided into useful bits
    // and this code then called here, instead of that strange forwarding
    // to a wizard, which doesn't even show up
    ProjectLoadWizard wizard(this);
    wizard.execDialog();
con's avatar
con committed
860
861
862
863
}

void Qt4Project::proFileParseError(const QString &errorMessage)
{
864
    Core::ICore::instance()->messageManager()->printToOutputPanePopup(errorMessage);
con's avatar
con committed
865
866
}

867
ProFileReader *Qt4Project::createProFileReader(Qt4ProFileNode *qt4ProFileNode, Qt4BuildConfiguration *bc)
868
869
870
871
872
{
    if (!m_proFileOption) {
        m_proFileOption = new ProFileOption;
        m_proFileOptionRefCnt = 0;

873
        if (!bc && activeTarget())
874
875
876
            bc = activeTarget()->activeBuildConfiguration();

        if (bc) {
dt's avatar
dt committed
877
878
            BaseQtVersion *version = bc->qtVersion();
            if (version && version->isValid()) {
879
                m_proFileOption->properties = version->versionInfo();
880
881
                if (bc->toolChain())
                    m_proFileOption->sysroot = bc->qtVersion()->systemRoot();
882
            }
883

884
885
886
887
888
            Utils::Environment env = bc->environment();
            Utils::Environment::const_iterator eit = env.constBegin(), eend = env.constEnd();
            for (; eit != eend; ++eit)
                m_proFileOption->environment.insert(env.key(eit), env.value(eit));

889
890
891
892
893
894
            QStringList args;
            if (QMakeStep *qs = bc->qmakeStep())
                args = qs->parserArguments();
            else
                args = bc->configCommandLineArguments();
            m_proFileOption->setCommandLineArguments(args);
895
        }
896

dt's avatar
dt committed
897
        ProFileCacheManager::instance()->incRefCount();
898
899
900
901
902
903
904
905
906
907
908
909
910
911
    }
    ++m_proFileOptionRefCnt;

    ProFileReader *reader = new ProFileReader(m_proFileOption);

    reader->setOutputDir(qt4ProFileNode->buildDir());

    return reader;
}

void Qt4Project::destroyProFileReader(ProFileReader *reader)
{
    delete reader;
    if (!--m_proFileOptionRefCnt) {
912
913
914
        QString dir = QFileInfo(m_fileInfo->fileName()).absolutePath();
        if (!dir.endsWith(QLatin1Char('/')))
            dir += QLatin1Char('/');
915
916
        ProFileCacheManager::instance()->discardFiles(dir);
        ProFileCacheManager::instance()->decRefCount();
917

918
919
920
921
922
        delete m_proFileOption;
        m_proFileOption = 0;
    }
}

con's avatar
con committed
923
924
925
926
927
Qt4ProFileNode *Qt4Project::rootProjectNode() const
{
    return m_rootProjectNode;
}

928
929
bool Qt4Project::validParse(const QString &proFilePath) const
{
dt's avatar
dt committed
930
931
    if (!m_rootProjectNode)
        return false;
932
933
934
935
    const Qt4ProFileNode *node = m_rootProjectNode->findProFileFor(proFilePath);
    return node && node->validParse();
}

dt's avatar
dt committed
936
QList<BuildConfigWidget*> Qt4Project::subConfigWidgets()
con's avatar
con committed
937
{
dt's avatar
dt committed
938
    QList<BuildConfigWidget*> subWidgets;
939
    subWidgets << new BuildEnvironmentWidget;
con's avatar
con committed
940
941
942
    return subWidgets;
}

943
void Qt4Project::collectAllfProFiles(QList<Qt4ProFileNode *> &list, Qt4ProFileNode *node)
dt's avatar
dt committed
944
{
945
    list.append(node);
dt's avatar
dt committed
946
947
948
    foreach (ProjectNode *n, node->subProjectNodes()) {
        Qt4ProFileNode *qt4ProFileNode = qobject_cast<Qt4ProFileNode *>(n);
        if (qt4ProFileNode)
949
            collectAllfProFiles(list, qt4ProFileNode);
dt's avatar
dt committed
950
951
952
953
    }
}


con's avatar
con committed
954
955
956
957
958
959
960
961
962
963
964
965
966
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);
    }
}

967
QList<Qt4ProFileNode *> Qt4Project::allProFiles() const
dt's avatar
dt committed
968
969
970
971
{
    QList<Qt4ProFileNode *> list;
    if (!rootProjectNode())
        return list;
972
    collectAllfProFiles(list, rootProjectNode());
dt's avatar
dt committed
973
974
975
    return list;
}

con's avatar
con committed
976
977
978
QList<Qt4ProFileNode *> Qt4Project::applicationProFiles() const
{
    QList<Qt4ProFileNode *> list;
Tobias Hunger's avatar
Tobias Hunger committed
979
980
    if (!rootProjectNode())
        return list;
con's avatar
con committed
981
982
983
984
    collectApplicationProFiles(list, rootProjectNode());
    return list;
}

985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
bool Qt4Project::hasApplicationProFile(const QString &path) const
{
    if (path.isEmpty())
        return false;

    QList<Qt4ProFileNode *> list = applicationProFiles();
    foreach (Qt4ProFileNode * node, list)
        if (node->path() == path)
            return true;
    return false;
}

QStringList Qt4Project::applicationProFilePathes(const QString &prepend) const
{
    QStringList proFiles;
    foreach (Qt4ProFileNode *node, applicationProFiles())
        proFiles.append(prepend + node->path());
    return proFiles;
}

Tobias Hunger's avatar
Tobias Hunger committed
1005
1006
1007
1008
1009
void Qt4Project::activeTargetWasChanged()
{
    if (!activeTarget())
        return;

dt's avatar
dt committed
1010
    scheduleAsyncUpdate();
Tobias Hunger's avatar
Tobias Hunger committed
1011
1012
}

1013
bool Qt4Project::hasSubNode(Qt4PriFileNode *root, const QString &path)
dt's avatar
dt committed
1014
{
1015
1016
1017
1018
1019
    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
1020
        } else if (Qt4PriFileNode *qt4prifilenode = qobject_cast<Qt4PriFileNode *>(fn)) {
1021
1022
1023
1024
1025
            if (hasSubNode(qt4prifilenode, path))
                return true;
        }
    }
    return false;
dt's avatar
dt committed
1026
1027
1028
1029
}

void Qt4Project::findProFile(const QString& fileName, Qt4ProFileNode *root, QList<Qt4ProFileNode *> &list)
{
1030
    if (hasSubNode(root, fileName))
dt's avatar
dt committed
1031
1032
1033
1034
1035
1036
1037
1038
1039
        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)
{
1040
1041
1042
    if (files(Qt4Project::ExcludeGeneratedFiles).contains(name)) {
        QList<Qt4ProFileNode *> list;
        findProFile(name, rootProjectNode(), list);
1043
1044
        foreach(Qt4ProFileNode *node, list) {
            ProFileCacheManager::instance()->discardFile(name);
1045
            node->update();
1046
        }
1047
    }
dt's avatar
dt committed
1048
}
1049

1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
CentralizedFolderWatcher *Qt4Project::centralizedFolderWatcher()
{
    return &m_centralizedFolderWatcher;
}

/////////////
/// Centralized Folder Watcher
////////////

// All the folder have a trailing slash!

namespace {
   bool debugCFW = false;
}

CentralizedFolderWatcher::CentralizedFolderWatcher()
{
1067
1068
1069
1070
    m_compressTimer.setSingleShot(true);
    m_compressTimer.setInterval(200);
    connect(&m_compressTimer, SIGNAL(timeout()),
            this, SLOT(onTimer()));
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
    connect (&m_watcher, SIGNAL(directoryChanged(QString)),
             this, SLOT(folderChanged(QString)));
}

CentralizedFolderWatcher::~CentralizedFolderWatcher()
{

}

QSet<QString> CentralizedFolderWatcher::recursiveDirs(const QString &folder)
{
    QSet<QString> result;
    QDir dir(folder);
    QStringList list = dir.entryList(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
    foreach (const QString &f, list) {
1086
1087
1088
        const QString a = folder + f + '/';
        result.insert(a);
        result += recursiveDirs(a);
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
    }
    return result;
}

void CentralizedFolderWatcher::watchFolders(const QList<QString> &folders, Qt4PriFileNode *node)
{
    if (debugCFW)
        qDebug()<<"CFW::watchFolders()"<<folders<<"for node"<<node->path();
    m_watcher.addPaths(folders);

    foreach (const QString &f, folders) {
        QString folder = f;
        if (!folder.endsWith('/'))
            folder.append('/');
        m_map.insert(folder, node);

        // Support for recursive watching
        // we add the recursive directories we find
        QSet<QString> tmp = recursiveDirs(folder);
1108
1109
        if (!tmp.isEmpty())
            m_watcher.addPaths(tmp.toList());
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
        m_recursiveWatchedFolders += tmp;

        if (debugCFW)
            qDebug()<<"adding recursive dirs for"<< folder<<":"<<tmp;
    }
}

void CentralizedFolderWatcher::unwatchFolders(const QList<QString> &folders, Qt4PriFileNode *node)
{
    if (debugCFW)
        qDebug()<<"CFW::unwatchFolders()"<<folders<<"for node"<<node->path();
    foreach (const QString &f, folders) {
        QString folder = f;
        if (!folder.endsWith('/'))
            folder.append('/');
        m_map.remove(folder, node);
        if (!m_map.contains(folder)) {
            m_watcher.removePath(folder);
        }

        // Figure out which recursive directories we can remove
        // TODO this might not scale. I'm pretty sure it doesn't
        // A scaling implementation would need to save more information
        // where a given directory watcher actual comes from...

        QStringList toRemove;
        foreach (const QString &rwf, m_recursiveWatchedFolders) {
            if (rwf.startsWith(folder)) {
                // So the rwf is a subdirectory of a folder we aren't watching
                // but maybe someone else wants us to watch
                bool needToWatch = false;
                QMultiMap<QString, Qt4PriFileNode *>::const_iterator it, end;
                end = m_map.constEnd();
                for (it = m_map.constEnd(); it != end; ++it) {
                    if (rwf.startsWith(it.key())) {
                        needToWatch = true;
                        break;
                    }
                }
                if (!needToWatch) {
                    m_watcher.removePath(rwf);
                    toRemove << rwf;
                }
            }
        }

        if (debugCFW)
            qDebug()<<"removing recursive dirs for"<<folder<<":"<<toRemove;

        foreach (const QString &tr, toRemove) {
            m_recursiveWatchedFolders.remove(tr);
        }
    }
}

void CentralizedFolderWatcher::folderChanged(const QString &folder)
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
{
    m_changedFolders.insert(folder);
    m_compressTimer.start();
}

void CentralizedFolderWatcher::onTimer()
{
    foreach(const QString &folder, m_changedFolders)
        delayedFolderChanged(folder);
    m_changedFolders.clear();
}

void CentralizedFolderWatcher::delayedFolderChanged(const QString &folder)
1179
1180
1181
1182
1183
{
    if (debugCFW)
        qDebug()<<"CFW::folderChanged"<<folder;
    // Figure out whom to inform

1184
    QString dir = folder;
1185
    while (true) {
1186
1187
1188
        if (!dir.endsWith('/'))
            dir.append('/');
        QList<Qt4PriFileNode *> nodes = m_map.values(dir);
1189
1190
1191
1192
        foreach (Qt4PriFileNode *node, nodes) {
            node->folderChanged(folder);
        }

1193
1194
1195
        // Chop off last part, and break if there's nothing to chop off
        //
        if (dir.length() < 2)
1196
            break;
1197
1198
1199
1200
1201
1202

        // We start before the last slash
        int index = dir.lastIndexOf('/', dir.length() - 2);
        if (index == -1)
            break;
        dir = dir.left(index + 1);
1203
1204
    }

1205

dt's avatar
dt committed
1206
1207
1208
1209
    QString folderWithSlash = folder;
    if (!folder.endsWith('/'))
        folderWithSlash.append('/');

1210
    // If a subdirectory was added, watch it too
dt's avatar
dt committed
1211
    QSet<QString> tmp = recursiveDirs(folderWithSlash);
1212
1213
1214
    if (!tmp.isEmpty()) {
        if (debugCFW)
            qDebug()<<"found new recursive dirs"<<tmp;
1215
1216
1217
1218
1219

        QSet<QString> alreadyAdded = m_watcher.directories().toSet();
        tmp.subtract(alreadyAdded);
        if (!tmp.isEmpty())
            m_watcher.addPaths(tmp.toList());
1220
1221
1222
1223
        m_recursiveWatchedFolders += tmp;
    }
}

1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
/*!
  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);
1244
//        QString buildDir = project()->projectDirectory();
1245
1246
1247
1248
1249
1250
1251
//        buildDir.replace(qtSourceDir, currentQtDir);
//        project()->setValue(buildConfiguration, "buildDirectory", buildDir);
//        project()->setValue(buildConfiguration, "autoShadowBuild", true);
//    }
//}