qt4project.cpp 50 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
#include "qt4project.h"
hjk's avatar
hjk committed
31

Tobias Hunger's avatar
Tobias Hunger committed
32
#include "qt4projectmanager.h"
con's avatar
con committed
33
34
#include "makestep.h"
#include "qmakestep.h"
Tobias Hunger's avatar
Tobias Hunger committed
35
#include "qmakerunconfigurationfactory.h"
con's avatar
con committed
36
#include "qt4nodes.h"
37
#include "qt4projectconfigwidget.h"
con's avatar
con committed
38
#include "qt4projectmanagerconstants.h"
dt's avatar
dt committed
39
#include "qt4buildconfiguration.h"
40
#include "findqt4profiles.h"
41
#include "buildconfigurationinfo.h"
42

43
#include <coreplugin/icore.h>
44
#include <coreplugin/idocument.h>
45
#include <coreplugin/icontext.h>
con's avatar
con committed
46
47
#include <coreplugin/messagemanager.h>
#include <coreplugin/coreconstants.h>
dt's avatar
dt committed
48
#include <coreplugin/progressmanager/progressmanager.h>
49
#include <coreplugin/documentmanager.h>
50
#include <coreplugin/variablemanager.h>
51
#include <extensionsystem/pluginmanager.h>
52
#include <cpptools/ModelManagerInterface.h>
53
#include <qmljs/qmljsmodelmanagerinterface.h>
54
#include <qmljstools/qmljsmodelmanager.h>
55
56
#include <projectexplorer/buildtargetinfo.h>
#include <projectexplorer/deploymentdata.h>
57
#include <projectexplorer/toolchain.h>
58
#include <projectexplorer/headerpath.h>
59
#include <projectexplorer/target.h>
Tobias Hunger's avatar
Tobias Hunger committed
60
#include <projectexplorer/kitinformation.h>
61
#include <projectexplorer/projectexplorer.h>
62
#include <projectexplorer/projectexplorerconstants.h>
63
#include <projectexplorer/projectmacroexpander.h>
64
#include <utils/qtcassert.h>
65
#include <qtsupport/customexecutablerunconfiguration.h>
66
67
68
#include <qtsupport/qmldumptool.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/profilereader.h>
Tobias Hunger's avatar
Tobias Hunger committed
69
#include <qtsupport/qtkitinformation.h>
70
#include <qtsupport/qtsupportconstants.h>
71
#include <qtsupport/qtversionmanager.h>
72
#include <utils/QtConcurrentTools>
73
#include <utils/stringutils.h>
con's avatar
con committed
74

75
76
77
78
79
#include <QDebug>
#include <QDir>
#include <QFileSystemWatcher>
#include <QFileDialog>
#include <QInputDialog>
con's avatar
con committed
80
81
82
83
84

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

hjk's avatar
hjk committed
85
enum { debug = 0 };
con's avatar
con committed
86

Tobias Hunger's avatar
Tobias Hunger committed
87
88
89
90
91
92
93
94
95
96
// -----------------------------------------------------------------------
// Helpers:
// -----------------------------------------------------------------------

namespace {

Qt4BuildConfiguration *enableActiveQt4BuildConfiguration(ProjectExplorer::Target *t, bool enabled)
{
    if (!t)
        return 0;
97
    Qt4BuildConfiguration *bc = static_cast<Qt4BuildConfiguration *>(t->activeBuildConfiguration());
Tobias Hunger's avatar
Tobias Hunger committed
98
99
100
101
102
103
104
105
    if (!bc)
        return 0;
    bc->setEnabled(enabled);
    return bc;
}

} // namespace

con's avatar
con committed
106
107
108
namespace Qt4ProjectManager {
namespace Internal {

109
class Qt4ProjectFile : public Core::IDocument
110
111
112
113
{
    Q_OBJECT

public:
Tobias Hunger's avatar
Tobias Hunger committed
114
    Qt4ProjectFile(const QString &filePath, QObject *parent = 0);
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

    bool save(QString *errorString, const QString &fileName, bool autoSave);
    QString fileName() const;
    virtual void rename(const QString &newName);

    QString defaultPath() const;
    QString suggestedFileName() const;
    virtual QString mimeType() const;

    bool isModified() const;
    bool isSaveAsAllowed() const;

    ReloadBehavior reloadBehavior(ChangeTrigger state, ChangeType type) const;
    bool reload(QString *errorString, ReloadFlag flag, ChangeType type);

private:
    const QString m_mimeType;
    QString m_filePath;
};

/// Watches folders for Qt4PriFile nodes
/// use one file system watcher to watch all folders
/// such minimizing system ressouce usage

class CentralizedFolderWatcher : public QObject
{
    Q_OBJECT
public:
    CentralizedFolderWatcher(QObject *parent);
    ~CentralizedFolderWatcher();
145
146
    void watchFolders(const QList<QString> &folders, Qt4ProjectManager::Qt4PriFileNode *node);
    void unwatchFolders(const QList<QString> &folders, Qt4ProjectManager::Qt4PriFileNode *node);
147
148
149
150
151
152
153
154
155

private slots:
    void folderChanged(const QString &folder);
    void onTimer();
    void delayedFolderChanged(const QString &folder);

private:
    QSet<QString> recursiveDirs(const QString &folder);
    QFileSystemWatcher m_watcher;
156
    QMultiMap<QString, Qt4ProjectManager::Qt4PriFileNode *> m_map;
157
158
159
160
161
162

    QSet<QString> m_recursiveWatchedFolders;
    QTimer m_compressTimer;
    QSet<QString> m_changedFolders;
};

con's avatar
con committed
163
// Qt4ProjectFiles: Struct for (Cached) lists of files in a project
Tobias Hunger's avatar
Tobias Hunger committed
164
165
class Qt4ProjectFiles {
public:
con's avatar
con committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    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
{
    ProjectFilesVisitor(Qt4ProjectFiles *files);
hjk's avatar
hjk committed
212

con's avatar
con committed
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
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
Friedemann Kleint's avatar
Friedemann Kleint committed
263
namespace Internal {
Tobias Hunger's avatar
Tobias Hunger committed
264
Qt4ProjectFile::Qt4ProjectFile(const QString &filePath, QObject *parent)
265
    : Core::IDocument(parent),
con's avatar
con committed
266
267
268
269
270
      m_mimeType(QLatin1String(Qt4ProjectManager::Constants::PROFILE_MIMETYPE)),
      m_filePath(filePath)
{
}

271
bool Qt4ProjectFile::save(QString *, const QString &, bool)
con's avatar
con committed
272
{
273
274
    // This is never used
    return false;
con's avatar
con committed
275
276
}

dt's avatar
dt committed
277
278
279
280
281
282
283
void Qt4ProjectFile::rename(const QString &newName)
{
    // Can't happen
    Q_UNUSED(newName);
    Q_ASSERT(false);
}

con's avatar
con committed
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
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
{
306
    return false; // we save after changing anyway
con's avatar
con committed
307
308
309
310
311
312
313
}

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

314
Core::IDocument::ReloadBehavior Qt4ProjectFile::reloadBehavior(ChangeTrigger state, ChangeType type) const
con's avatar
con committed
315
{
316
317
318
319
320
    Q_UNUSED(state)
    Q_UNUSED(type)
    return BehaviorSilent;
}

321
bool Qt4ProjectFile::reload(QString *errorString, ReloadFlag flag, ChangeType type)
322
{
323
    Q_UNUSED(errorString)
324
325
    Q_UNUSED(flag)
    Q_UNUSED(type)
326
    return true;
con's avatar
con committed
327
328
}

329
} // namespace Internal
330

con's avatar
con committed
331
/*!
332
  \class Qt4Project
con's avatar
con committed
333
334
335
336
337
338

  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
339
    m_rootProjectNode(0),
con's avatar
con committed
340
    m_nodesWatcher(new Internal::Qt4NodesWatcher(this)),
Tobias Hunger's avatar
Tobias Hunger committed
341
    m_fileInfo(new Qt4ProjectFile(fileName, this)),
342
    m_projectFiles(new Qt4ProjectFiles),
343
    m_qmakeGlobals(0),
dt's avatar
dt committed
344
345
346
    m_asyncUpdateFutureInterface(0),
    m_pendingEvaluateFuturesCount(0),
    m_asyncUpdateState(NoState),
347
    m_cancelEvaluate(false),
348
349
    m_centralizedFolderWatcher(0),
    m_activeTarget(0)
con's avatar
con committed
350
{
351
    setProjectContext(Core::Context(Qt4ProjectManager::Constants::PROJECT_ID));
352
    setProjectLanguages(Core::Context(ProjectExplorer::Constants::LANG_CXX));
353

dt's avatar
dt committed
354
355
356
    m_asyncUpdateTimer.setSingleShot(true);
    m_asyncUpdateTimer.setInterval(3000);
    connect(&m_asyncUpdateTimer, SIGNAL(timeout()), this, SLOT(asyncUpdate()));
con's avatar
con committed
357
358
359
360
}

Qt4Project::~Qt4Project()
{
361
    m_codeModelFuture.cancel();
362
    m_asyncUpdateState = ShuttingDown;
dt's avatar
dt committed
363
    m_manager->unregisterProject(this);
con's avatar
con committed
364
    delete m_projectFiles;
365
    m_cancelEvaluate = true;
366
367
368
369
370
    // Deleting the root node triggers a few things, make sure rootProjectNode
    // returns 0 already
    Qt4ProFileNode *root = m_rootProjectNode;
    m_rootProjectNode = 0;
    delete root;
con's avatar
con committed
371
372
373
374
375
376
377
378
379
380
381
382
383
384
}

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

385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
bool Qt4Project::setupTarget(ProjectExplorer::Target *t)
{
    QList<BuildConfigurationInfo> infoList
            = Qt4BuildConfigurationFactory::availableBuildConfigurations(t->kit(), m_fileInfo->fileName());
    setupTarget(t, infoList);
    return true;
}

void Qt4Project::setupTarget(ProjectExplorer::Target *t, const QList<BuildConfigurationInfo> &infoList)
{
    // Build Configurations:
    foreach (const BuildConfigurationInfo &info, infoList) {
        QString name = info.buildConfig & QtSupport::BaseQtVersion::DebugBuild
                ? tr("Debug") : tr("Release");
        Qt4BuildConfiguration *bc
                = Qt4BuildConfiguration::setup(t, name, name,
                                               info.buildConfig, info.additionalArguments,
                                               info.directory, info.importing);
        t->addBuildConfiguration(bc);
    }

    // Deploy Configurations:
    t->updateDefaultDeployConfigurations();
    // Do not create Run Configurations: Those will be generated later anyway.
}

411
bool Qt4Project::fromMap(const QVariantMap &map)
con's avatar
con committed
412
{
413
414
    if (!Project::fromMap(map))
        return false;
con's avatar
con committed
415

Tobias Hunger's avatar
Tobias Hunger committed
416
417
    // Prune targets without buildconfigurations:
    // This can happen esp. when updating from a old version of Qt Creator
dt's avatar
dt committed
418
    QList<Target *>ts = targets();
Tobias Hunger's avatar
Tobias Hunger committed
419
    foreach (Target *t, ts) {
420
        if (t->buildConfigurations().isEmpty()) {
421
            qWarning() << "Removing" << t->id().name() << "since it has no buildconfigurations!";
Tobias Hunger's avatar
Tobias Hunger committed
422
            removeTarget(t);
423
        }
Tobias Hunger's avatar
Tobias Hunger committed
424
425
    }

dt's avatar
dt committed
426
427
428
429
430
    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
431
432
    update();
    updateFileList();
433
434
    // This might be incorrect, need a full update
    updateCodeModels();
435

Tobias Hunger's avatar
Tobias Hunger committed
436
    // We have the profile nodes now, so we know the runconfigs!
437
438
    connect(m_nodesWatcher, SIGNAL(proFileUpdated(Qt4ProjectManager::Qt4ProFileNode*,bool,bool)),
            this, SIGNAL(proFileUpdated(Qt4ProjectManager::Qt4ProFileNode*,bool,bool)));
439

440
    // Now we emit update once :)
Daniel Teske's avatar
Daniel Teske committed
441
    m_rootProjectNode->emitProFileUpdatedRecursive();
442

443
444
445
446
447
448
    // On active buildconfiguration changes, reevaluate the .pro files
    m_activeTarget = activeTarget();
    if (m_activeTarget)
        connect(m_activeTarget, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
                this, SLOT(scheduleAsyncUpdate()));

Tobias Hunger's avatar
Tobias Hunger committed
449
450
451
    connect(this, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
            this, SLOT(activeTargetWasChanged()));

dt's avatar
dt committed
452
    return true;
con's avatar
con committed
453
454
}

dt's avatar
dt committed
455
456
457
458
459
460
461
462
463
464
465
466
467
/// 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) {
468
        if (*ait == CPlusPlus::CppModelManagerInterface::configurationFileName())
dt's avatar
dt committed
469
            ++ait;
470
        else if (*bit == CPlusPlus::CppModelManagerInterface::configurationFileName())
dt's avatar
dt committed
471
472
473
474
475
476
477
            ++bit;
        else if (*ait == *bit)
            ++ait, ++bit;
        else
           return false;
    }
    return (ait == aend && bit == bend);
Tobias Hunger's avatar
Tobias Hunger committed
478
479
}

480
void Qt4Project::updateCodeModels()
con's avatar
con committed
481
482
483
484
{
    if (debug)
        qDebug()<<"Qt4Project::updateCodeModel()";

485
    if (activeTarget() && !activeTarget()->activeBuildConfiguration())
Tobias Hunger's avatar
Tobias Hunger committed
486
487
        return;

488
489
490
491
492
493
    updateCppCodeModel();
    updateQmlJSCodeModel();
}

void Qt4Project::updateCppCodeModel()
{
494
495
    typedef CPlusPlus::CppModelManagerInterface::ProjectPart ProjectPart;

Tobias Hunger's avatar
Tobias Hunger committed
496
    Kit *k = 0;
497
498
    QtSupport::BaseQtVersion *qtVersion = 0;
    ToolChain *tc = 0;
Tobias Hunger's avatar
Tobias Hunger committed
499
    if (ProjectExplorer::Target *target = activeTarget())
Tobias Hunger's avatar
Tobias Hunger committed
500
        k = target->kit();
Tobias Hunger's avatar
Tobias Hunger committed
501
    else
Tobias Hunger's avatar
Tobias Hunger committed
502
503
504
        k = KitManager::instance()->defaultKit();
    qtVersion = QtSupport::QtKitInformation::qtVersion(k);
    tc = ToolChainKitInformation::toolChain(k);
505

506
    CPlusPlus::CppModelManagerInterface *modelmanager =
507
        CPlusPlus::CppModelManagerInterface::instance();
con's avatar
con committed
508

509
    if (!modelmanager)
con's avatar
con committed
510
511
        return;

512
513
    FindQt4ProFiles findQt4ProFiles;
    QList<Qt4ProFileNode *> proFiles = findQt4ProFiles(rootProjectNode());
con's avatar
con committed
514

515
516
517
518
519
520
521
522
523
    CPlusPlus::CppModelManagerInterface::ProjectInfo pinfo = modelmanager->projectInfo(this);
    pinfo.clearProjectParts();
    ProjectPart::QtVersion qtVersionForPart = ProjectPart::NoQt;
    if (qtVersion) {
        if (qtVersion->qtVersion() < QtSupport::QtVersionNumber(5,0,0))
            qtVersionForPart = ProjectPart::Qt4;
        else
            qtVersionForPart = ProjectPart::Qt5;
    }
524

525
526
527
    QStringList allFiles;
    foreach (Qt4ProFileNode *pro, proFiles) {
        ProjectPart::Ptr part(new ProjectPart);
528
529
530
531
532

        if (pro->variableValue(ConfigVar).contains(QLatin1String("qt")))
            part->qtVersion = qtVersionForPart;
        else
            part->qtVersion = ProjectPart::NoQt;
533

534
        const QStringList cxxflags = pro->variableValue(CppFlagsVar);
535

536
537
        // part->defines
        if (tc)
538
            part->defines = tc->predefinedMacros(cxxflags);
539
540
541
542
543
544
545
        part->defines += pro->cxxDefines();

        // part->includePaths
        part->includePaths.append(pro->variableValue(IncludePathVar));

        QList<HeaderPath> headers;
        if (tc)
546
            headers = tc->systemHeaderPaths(cxxflags, SysRootKitInformation::sysRoot(k));
547
        if (qtVersion)
Tobias Hunger's avatar
Tobias Hunger committed
548
            headers.append(qtVersion->systemHeaderPathes(k));
549

550
        foreach (const HeaderPath &headerPath, headers) {
dt's avatar
dt committed
551
            if (headerPath.kind() == HeaderPath::FrameworkHeaderPath)
552
                part->frameworkPaths.append(headerPath.path());
dt's avatar
dt committed
553
            else
554
                part->includePaths.append(headerPath.path());
con's avatar
con committed
555
556
        }

557
558
559
        if (qtVersion) {
            if (!qtVersion->frameworkInstallPath().isEmpty())
                part->frameworkPaths.append(qtVersion->frameworkInstallPath());
560

561
        }
562
563
        if (Qt4ProFileNode *node = rootQt4ProjectNode())
            part->includePaths.append(node->resolvedMkspecPath());
con's avatar
con committed
564

565
566
        // part->precompiledHeaders
        part->precompiledHeaders.append(pro->variableValue(PrecompiledHeaderVar));
dt's avatar
dt committed
567

568
569
        // part->language
        if (tc)
570
            part->language = tc->compilerFlags(cxxflags) == ToolChain::STD_CXX11 ? ProjectPart::CXX11 : ProjectPart::CXX;
571
        else
572
            part->language = CPlusPlus::CppModelManagerInterface::ProjectPart::CXX11;
573

574
        part->sourceFiles = pro->variableValue(CppSourceVar);
575
576
        part->headerFiles += pro->variableValue(CppHeaderVar);
        part->headerFiles += pro->uiFiles();
577
        part->sourceFiles.prepend(CPlusPlus::CppModelManagerInterface::configurationFileName());
578
        part->objcSourceFiles = pro->variableValue(ObjCSourceVar);
579
        pinfo.appendProjectPart(part);
con's avatar
con committed
580

581
        allFiles += part->headerFiles;
582
        allFiles += part->sourceFiles;
583
        allFiles += part->objcSourceFiles;
con's avatar
con committed
584
    }
585
586
587

    modelmanager->updateProjectInfo(pinfo);
    m_codeModelFuture = modelmanager->updateSourceFiles(allFiles);
588
589
}

590
591
void Qt4Project::updateQmlJSCodeModel()
{
592
    QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
593
594
595
    if (!modelManager)
        return;

596
597
    QmlJS::ModelManagerInterface::ProjectInfo projectInfo =
            QmlJSTools::defaultProjectInfoForProject(this);
598
599
600
601

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

602
    projectInfo.importPaths.clear();
603
604

    bool hasQmlLib = false;
605
606
    foreach (Qt4ProFileNode *node, proFiles) {
        projectInfo.importPaths.append(node->variableValue(QmlImportPathVar));
607
608
609
610
611
        if (!hasQmlLib) {
            QStringList qtLibs = node->variableValue(QtVar);
            hasQmlLib = qtLibs.contains(QLatin1String("declarative")) ||
                    qtLibs.contains(QLatin1String("qml")) ||
                    qtLibs.contains(QLatin1String("quick"));
612
            break;
613
        }
614
    }
615

616
617
618
619
620
    // If the project directory has a pro/pri file that includes a qml or quick or declarative
    // library then chances of the project being a QML project is quite high.
    // This assumption fails when there are no QDeclarativeEngine/QDeclarativeView (QtQuick 1)
    // or QQmlEngine/QQuickView (QtQuick 2) instances.
    Core::Context pl(ProjectExplorer::Constants::LANG_CXX);
621
    if (hasQmlLib)
622
623
624
        pl.add(ProjectExplorer::Constants::LANG_QMLJS);
    setProjectLanguages(pl);

625
626
    projectInfo.importPaths.removeDuplicates();

627
    modelManager->updateProjectInfo(projectInfo);
628
629
}

630
631
632
///*!
//  Updates complete project
//  */
con's avatar
con committed
633
634
void Qt4Project::update()
{
dt's avatar
dt committed
635
636
    if (debug)
        qDebug()<<"Doing sync update";
con's avatar
con committed
637
    m_rootProjectNode->update();
638

dt's avatar
dt committed
639
640
    if (debug)
        qDebug()<<"State is now Base";
dt's avatar
dt committed
641
    m_asyncUpdateState = Base;
Tobias Hunger's avatar
Tobias Hunger committed
642
    enableActiveQt4BuildConfiguration(activeTarget(), true);
643
    updateBuildSystemData();
644
645
646
647
648
649
650
651
    updateRunConfigurations();
    emit proFilesEvaluated();
}

void Qt4Project::updateRunConfigurations()
{
    foreach (Target *t, targets())
        t->updateDefaultRunConfigurations();
dt's avatar
dt committed
652
653
654
655
}

void Qt4Project::scheduleAsyncUpdate(Qt4ProFileNode *node)
{
dt's avatar
dt committed
656
657
    if (m_asyncUpdateState == ShuttingDown)
        return;
658

dt's avatar
dt committed
659
    if (debug)
Daniel Teske's avatar
Daniel Teske committed
660
        qDebug()<<"schduleAsyncUpdate (node)"<<node->path();
dt's avatar
dt committed
661
662
663
    Q_ASSERT(m_asyncUpdateState != NoState);

    if (m_cancelEvaluate) {
dt's avatar
dt committed
664
665
        if (debug)
            qDebug()<<"  Already canceling, nothing to do";
dt's avatar
dt committed
666
667
668
669
670
671
        // 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;
    }

Tobias Hunger's avatar
Tobias Hunger committed
672
    enableActiveQt4BuildConfiguration(activeTarget(), false);
673

dt's avatar
dt committed
674
675
    if (m_asyncUpdateState == AsyncFullUpdatePending) {
        // Just postpone
dt's avatar
dt committed
676
677
        if (debug)
            qDebug()<<"  full update pending, restarting timer";
dt's avatar
dt committed
678
679
680
        m_asyncUpdateTimer.start();
    } else if (m_asyncUpdateState == AsyncPartialUpdatePending
               || m_asyncUpdateState == Base) {
dt's avatar
dt committed
681
682
        if (debug)
            qDebug()<<"  adding node to async update list, setting state to AsyncPartialUpdatePending";
dt's avatar
dt committed
683
684
685
        // Add the node
        m_asyncUpdateState = AsyncPartialUpdatePending;

686
        QList<Qt4ProFileNode *>::iterator it;
dt's avatar
dt committed
687
        bool add = true;
dt's avatar
dt committed
688
689
        if (debug)
            qDebug()<<"scheduleAsyncUpdate();"<<m_partialEvaluate.size()<<"nodes";
dt's avatar
dt committed
690
691
692
693
694
695
        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
Daniel Teske's avatar
Daniel Teske committed
696
697
                it = m_partialEvaluate.erase(it);
            } else if ((*it)->isParent(node)) { // The node is the parent of a child already in the list
dt's avatar
dt committed
698
699
700
701
702
703
704
705
706
707
708
                add = false;
                break;
            } else {
                ++it;
            }
        }

        if (add)
            m_partialEvaluate.append(node);
        // and start the timer anew
        m_asyncUpdateTimer.start();
709
710
711

        // Cancel running code model update
        m_codeModelFuture.cancel();
dt's avatar
dt committed
712
713
714
715
716
717
718
719
    } 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
720
721
        if (debug)
            qDebug()<<"  Async update in progress, scheduling new one afterwards";
dt's avatar
dt committed
722
723
724
725
726
727
        scheduleAsyncUpdate();
    }
}

void Qt4Project::scheduleAsyncUpdate()
{
dt's avatar
dt committed
728
729
    if (debug)
        qDebug()<<"scheduleAsyncUpdate";
dt's avatar
dt committed
730
731
    if (m_asyncUpdateState == ShuttingDown)
        return;
732

dt's avatar
dt committed
733
734
735
    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
736
737
        if (debug)
            qDebug()<<"  canceling is in progress, doing nothing";
dt's avatar
dt committed
738
739
740
        return;
    }
    if (m_asyncUpdateState == AsyncUpdateInProgress) {
dt's avatar
dt committed
741
742
        if (debug)
            qDebug()<<"  update in progress, canceling and setting state to full update pending";
dt's avatar
dt committed
743
744
        m_cancelEvaluate = true;
        m_asyncUpdateState = AsyncFullUpdatePending;
Tobias Hunger's avatar
Tobias Hunger committed
745
        enableActiveQt4BuildConfiguration(activeTarget(), false);
Daniel Teske's avatar
Daniel Teske committed
746
        m_rootProjectNode->setParseInProgressRecursive(true);
dt's avatar
dt committed
747
748
749
        return;
    }

dt's avatar
dt committed
750
751
    if (debug)
        qDebug()<<"  starting timer for full update, setting state to full update pending";
dt's avatar
dt committed
752
    m_partialEvaluate.clear();
Tobias Hunger's avatar
Tobias Hunger committed
753
    enableActiveQt4BuildConfiguration(activeTarget(), false);
Daniel Teske's avatar
Daniel Teske committed
754
    m_rootProjectNode->setParseInProgressRecursive(true);
dt's avatar
dt committed
755
756
    m_asyncUpdateState = AsyncFullUpdatePending;
    m_asyncUpdateTimer.start();
757
758
759

    // Cancel running code model update
    m_codeModelFuture.cancel();
dt's avatar
dt committed
760
761
762
763
764
765
}


void Qt4Project::incrementPendingEvaluateFutures()
{
    ++m_pendingEvaluateFuturesCount;
dt's avatar
dt committed
766
767
    if (debug)
        qDebug()<<"incrementPendingEvaluateFutures to"<<m_pendingEvaluateFuturesCount;
dt's avatar
dt committed
768
769
770
771
772
773
774
775
776

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

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

dt's avatar
dt committed
777
778
    if (debug)
        qDebug()<<"decrementPendingEvaluateFutures to"<<m_pendingEvaluateFuturesCount;
dt's avatar
dt committed
779
780
781

    m_asyncUpdateFutureInterface->setProgressValue(m_asyncUpdateFutureInterface->progressValue() + 1);
    if (m_pendingEvaluateFuturesCount == 0) {
dt's avatar
dt committed
782
783
        if (debug)
            qDebug()<<"  WOHOO, no pending futures, cleaning up";
dt's avatar
dt committed
784
        // We are done!
dt's avatar
dt committed
785
786
        if (debug)
            qDebug()<<"  reporting finished";
787

dt's avatar
dt committed
788
789
790
791
792
793
794
        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
795
796
            if (debug)
                qDebug()<<"  Oh update is pending start the timer";
dt's avatar
dt committed
797
            m_asyncUpdateTimer.start();
798
        } else  if (m_asyncUpdateState != ShuttingDown){
Tobias Hunger's avatar
Tobias Hunger committed
799
            // After being done, we need to call:
800
            m_asyncUpdateState = Base;
Tobias Hunger's avatar
Tobias Hunger committed
801
            enableActiveQt4BuildConfiguration(activeTarget(), true);
802
            updateFileList();
803
            updateCodeModels();
804
            updateBuildSystemData();
805
806
            updateRunConfigurations();
            emit proFilesEvaluated();
dt's avatar
dt committed
807
808
            if (debug)
                qDebug()<<"  Setting state to Base";
dt's avatar
dt committed
809
810
811
812
813
814
815
816
817
818
819
        }
    }
}

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

void Qt4Project::asyncUpdate()
{
dt's avatar
dt committed
820
821
    if (debug)
        qDebug()<<"async update, timer expired, doing now";
dt's avatar
dt committed
822
823
824
    Q_ASSERT(!m_asyncUpdateFutureInterface);
    m_asyncUpdateFutureInterface = new QFutureInterface<void>();

hjk's avatar
hjk committed
825
    Core::ProgressManager *progressManager = Core::ICore::progressManager();
dt's avatar
dt committed
826

con's avatar
con committed
827
    m_asyncUpdateFutureInterface->setProgressRange(0, 0);
828
829
    progressManager->addTask(m_asyncUpdateFutureInterface->future(), tr("Evaluating"),
                             QLatin1String(Constants::PROFILE_EVALUATE));
dt's avatar
dt committed
830
831
    if (debug)
        qDebug()<<"  adding task";
dt's avatar
dt committed
832
833
834
835

    m_asyncUpdateFutureInterface->reportStarted();

    if (m_asyncUpdateState == AsyncFullUpdatePending) {
dt's avatar
dt committed
836
837
        if (debug)
            qDebug()<<"  full update, starting with root node";
dt's avatar
dt committed
838
839
        m_rootProjectNode->asyncUpdate();
    } else {
dt's avatar
dt committed
840
841
        if (debug)
            qDebug()<<"  partial update,"<<m_partialEvaluate.size()<<"nodes to update";
842
        foreach (Qt4ProFileNode *node, m_partialEvaluate)
dt's avatar
dt committed
843
844
845
846
            node->asyncUpdate();
    }

    m_partialEvaluate.clear();
dt's avatar
dt committed
847
848
    if (debug)
        qDebug()<<"  Setting state to AsyncUpdateInProgress";
dt's avatar
dt committed
849
    m_asyncUpdateState = AsyncUpdateInProgress;
con's avatar
con committed
850
851
852
853
854
855
856
857
858
859
860
861
}

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

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

862
bool Qt4Project::supportsKit(Kit *k, QString *errorMessage) const
Tobias Hunger's avatar
Tobias Hunger committed
863
{
864
    QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
865
866
    if (!version && errorMessage)
        *errorMessage = tr("No Qt version set in kit.");
Tobias Hunger's avatar
Tobias Hunger committed
867
868
869
    return version;
}

870
QString Qt4Project::displayName() const
con's avatar
con committed
871
{
872
    return QFileInfo(document()->fileName()).completeBaseName();
con's avatar
con committed
873
874
}

875
Core::Id Qt4Project::id() const
Tobias Hunger's avatar
Tobias Hunger committed
876
{
877
    return Core::Id(Constants::QT4PROJECT_ID);
Tobias Hunger's avatar
Tobias Hunger committed
878
879
}

880
Core::IDocument *Qt4Project::document() const
con's avatar
con committed
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
{
    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;
}

896
897
898
// Find the folder that contains a file a certain type (recurse down)
static FolderNode *folderOf(FolderNode *in, FileType fileType, const QString &fileName)
{
899
    foreach (FileNode *fn, in->fileNodes())
900
901
        if (fn->fileType() == fileType && fn->path() == fileName)
            return in;
902
    foreach (FolderNode *folder, in->subFolderNodes())
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
        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
928
929
void Qt4Project::proFileParseError(const QString &errorMessage)
{
hjk's avatar
hjk committed
930
    Core::ICore::messageManager()->printToOutputPanePopup(errorMessage);
con's avatar
con committed
931
932
}

933
QtSupport::ProFileReader *Qt4Project::createProFileReader(const Qt4ProFileNode *qt4ProFileNode, Qt4BuildConfiguration *bc)
934
{
935
    if (!m_qmakeGlobals) {
936
        m_qmakeGlobals = new ProFileGlobals;
937
        m_qmakeGlobalsRefCnt = 0;
938

Tobias Hunger's avatar
Tobias Hunger committed
939
        Kit *k;
940
941
        Utils::Environment env = Utils::Environment::systemEnvironment();
        QStringList qmakeArgs;
Orgad Shaneh's avatar
Orgad Shaneh committed
942
        if (!bc)
943
            bc = activeTarget() ? static_cast<Qt4BuildConfiguration *>(activeTarget()->activeBuildConfiguration()) : 0;
Orgad Shaneh's avatar
Orgad Shaneh committed
944
945

        if (bc) {
Tobias Hunger's avatar
Tobias Hunger committed
946
            k = bc->target()->kit();
Orgad Shaneh's avatar
Orgad Shaneh committed
947
            env = bc->environment();
948
            if (bc->qmakeStep())
Orgad Shaneh's avatar
Orgad Shaneh committed
949
                qmakeArgs = bc->qmakeStep()->parserArguments();
950
            else
951
952
                qmakeArgs = bc->configCommandLineArguments();
        } else {
Tobias Hunger's avatar
Tobias Hunger committed
953
            k = KitManager::instance()->defaultKit();
954
        }
955

Tobias Hunger's avatar
Tobias Hunger committed
956
957
958
        QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(k);
        QString systemRoot = SysRootKitInformation::hasSysRoot(k)
                ? SysRootKitInformation::sysRoot(k).toString() : QString();
Tobias Hunger's avatar
Tobias Hunger committed
959

960
961
        if (qtVersion && qtVersion->isValid()) {
            m_qmakeGlobals->qmake_abslocation = QDir::cleanPath(qtVersion->qmakeCommand().toString());
962
            m_qmakeGlobals->setProperties(qtVersion->versionInfo());
963
        }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
964
        m_qmakeGlobals->setDirectories(m_rootProjectNode->sourceDir(), m_rootProjectNode->buildDir());
965
        m_qmakeGlobals->sysroot = systemRoot;
966
967
968

        Utils::Environment::const_iterator eit = env.constBegin(), eend = env.constEnd();
        for (; eit != eend; ++eit)
969
            m_qmakeGlobals->environment.insert(env.key(eit), env.value(eit));
970

971
        m_qmakeGlobals->setCommandLineArguments(m_rootProjectNode->buildDir(), qmakeArgs);
972

973
        QtSupport::ProFileCacheManager::instance()->incRefCount();
974
    }
975
    ++m_qmakeGlobalsRefCnt;
976

977
    QtSupport::ProFileReader *reader = new QtSupport::ProFileReader(m_qmakeGlobals);
978
979
980
981
982
983

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

    return reader;
}

984
ProFileGlobals *Qt4Project::qmakeGlobals()
985
{
986
    return m_qmakeGlobals;
987
988
}

989
void Qt4Project::destroyProFileReader(QtSupport::ProFileReader *reader)
990
991
{
    delete reader;
992
    if (!--m_qmakeGlobalsRefCnt) {
993
994
995
        QString dir = QFileInfo(m_fileInfo->fileName()).absolutePath();
        if (!dir.endsWith(QLatin1Char('/')))
            dir += QLatin1Char('/');
996
997
        QtSupport::ProFileCacheManager::instance()->discardFiles(dir);
        QtSupport::ProFileCacheManager::instance()->decRefCount();
998

999
1000
        delete m_qmakeGlobals;
        m_qmakeGlobals = 0;
1001
1002
1003
    }
}

1004
1005
1006
1007
1008
1009
ProjectExplorer::ProjectNode *Qt4Project::rootProjectNode() const
{
    return m_rootProjectNode;
}

Qt4ProFileNode *Qt4Project::rootQt4ProjectNode() const
con's avatar
con committed
1010
1011
1012
1013
{
    return m_rootProjectNode;
}

1014
1015
bool Qt4Project::validParse(const QString &proFilePath) const
{
dt's avatar
dt committed
1016
1017
    if (!m_rootProjectNode)
        return false;
1018
1019
1020
1021
    const Qt4ProFileNode *node = m_rootProjectNode->findProFileFor(proFilePath);
    return node && node->validParse();
}

1022
1023
1024
1025
1026
1027
1028
1029
bool Qt4Project::parseInProgress(const QString &proFilePath) const
{
    if (!m_rootProjectNode)
        return false;
    const Qt4ProFileNode *node = m_rootProjectNode->findProFileFor(proFilePath);
    return node && node->parseInProgress();
}

1030
void Qt4Project::collectAllfProFiles(QList<Qt4ProFileNode *> &list, Qt4ProFileNode *node)
dt's avatar
dt committed
1031
{
1032
    list.append(node);
dt's avatar
dt committed
1033
1034
1035
    foreach (ProjectNode *n, node->subProjectNodes()) {
        Qt4ProFileNode *qt4ProFileNode = qobject_cast<Qt4ProFileNode *>(n);
        if (qt4ProFileNode)
1036
            collectAllfProFiles(list, qt4ProFileNode);
dt's avatar
dt committed
1037
1038
1039
    }
}

con's avatar
con committed
1040
1041
void Qt4Project::collectApplicationProFiles(QList<Qt4ProFileNode *> &list, Qt4ProFileNode *node)
{
1042
1043
    if (node->projectType() == ApplicationTemplate
        || node->projectType() == ScriptTemplate) {
con's avatar
con committed
1044
1045
1046
1047
1048
1049
1050
1051
1052
        list.append(node);
    }
    foreach (ProjectNode *n, node->subProjectNodes()) {
        Qt4ProFileNode *qt4ProFileNode = qobject_cast<Qt4ProFileNode *>(n);
        if (qt4ProFileNode)
            collectApplicationProFiles(list, qt4ProFileNode);
    }
}

1053
QList<Qt4ProFileNode *> Qt4Project::allProFiles() const
dt's avatar
dt committed
1054
1055
1056
1057
{
    QList<Qt4ProFileNode *> list;
    if (!rootProjectNode())
        return list;
1058
    collectAllfProFiles(list, rootQt4ProjectNode());
dt's avatar
dt committed
1059
1060
1061
    return list;
}

con's avatar
con committed
1062