qtversionmanager.cpp 29.5 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 "qtversionmanager.h"
hjk's avatar
hjk committed
31

Tobias Hunger's avatar
Tobias Hunger committed
32
#include "qtkitinformation.h"
dt's avatar
dt committed
33
34
#include "qtversionfactory.h"

35
36
#include "qtsupportconstants.h"

dt's avatar
dt committed
37
// only for legay restore
38
#include <projectexplorer/projectexplorerconstants.h>
39
40
#include <projectexplorer/toolchainmanager.h>
#include <projectexplorer/gcctoolchain.h>
41

42
#include <qtsupport/debugginghelper.h>
Jarek Kobus's avatar
Jarek Kobus committed
43

44
#include <coreplugin/icore.h>
kh1's avatar
kh1 committed
45
#include <coreplugin/helpmanager.h>
46

47
#include <extensionsystem/pluginmanager.h>
48

49
#include <utils/filesystemwatcher.h>
50
#include <utils/hostosinfo.h>
Jarek Kobus's avatar
Jarek Kobus committed
51
#include <utils/persistentsettings.h>
52
#include <utils/qtcprocess.h>
dt's avatar
dt committed
53
#include <utils/qtcassert.h>
54
55
56
#ifdef Q_OS_WIN
#    include <utils/winutils.h>
#endif
con's avatar
con committed
57

58
59
#include <QDebug>
#include <QDir>
60
61
62
63
#include <QFile>
#include <QSettings>
#include <QTextStream>
#include <QTimer>
con's avatar
con committed
64

65
66
#include <algorithm>

67
68
using namespace QtSupport;
using namespace QtSupport::Internal;
69

dt's avatar
dt committed
70
71
72
static const char QTVERSION_DATA_KEY[] = "QtVersion.";
static const char QTVERSION_TYPE_KEY[] = "QtVersion.Type";
static const char QTVERSION_FILE_VERSION_KEY[] = "Version";
Tobias Hunger's avatar
Tobias Hunger committed
73
static const char QTVERSION_FILENAME[] = "/qtcreator/qtversion.xml";
74
static const char QTVERSION_LEGACY_FILENAME[] = "/qtversion.xml"; // TODO: pre 2.6, remove later
dt's avatar
dt committed
75
76

// legacy settings
77
static const char QtVersionsSectionName[] = "QtVersions";
con's avatar
con committed
78

79
80
enum { debug = 0 };

81
82
83
84
template<class T>
static T *createToolChain(const QString &id)
{
    QList<ProjectExplorer::ToolChainFactory *> factories =
85
            ExtensionSystem::PluginManager::getObjects<ProjectExplorer::ToolChainFactory>();
86
87
88
89
90
91
92
93
94
    foreach (ProjectExplorer::ToolChainFactory *f, factories) {
       if (f->id() == id) {
           Q_ASSERT(f->canCreate());
           return static_cast<T *>(f->create());
       }
    }
    return 0;
}

95
static Utils::FileName globalSettingsFileName()
96
{
97
    QSettings *globalSettings = ExtensionSystem::PluginManager::globalSettings();
98
    return Utils::FileName::fromString(QFileInfo(globalSettings->fileName()).absolutePath()
99
                                       + QLatin1String(QTVERSION_FILENAME));
100
101
}

102
static Utils::FileName settingsFileName(const QString &path)
dt's avatar
dt committed
103
{
104
105
    QSettings *settings = ExtensionSystem::PluginManager::settings();
    QFileInfo settingsLocation(settings->fileName());
106
    return Utils::FileName::fromString(settingsLocation.absolutePath() + path);
dt's avatar
dt committed
107
108
}

109
110

// prefer newer qts otherwise compare on id
dt's avatar
dt committed
111
bool qtVersionNumberCompare(BaseQtVersion *a, BaseQtVersion *b)
112
113
114
115
{
    return a->qtVersion() > b->qtVersion() || (a->qtVersion() == b->qtVersion() && a->uniqueId() < b->uniqueId());
}

116
117
118
// --------------------------------------------------------------------------
// QtVersionManager
// --------------------------------------------------------------------------
119
QtVersionManager *QtVersionManager::m_self = 0;
120

Tobias Hunger's avatar
Tobias Hunger committed
121
QtVersionManager::QtVersionManager() :
122
    m_configFileWatcher(0),
Tobias Hunger's avatar
Tobias Hunger committed
123
124
    m_fileWatcherTimer(new QTimer(this)),
    m_writer(0)
con's avatar
con committed
125
{
126
    m_self = this;
con's avatar
con committed
127
    m_idcount = 1;
128
129

    qRegisterMetaType<Utils::FileName>();
130
131
132
133

    // Give the file a bit of time to settle before reading it...
    m_fileWatcherTimer->setInterval(2000);
    connect(m_fileWatcherTimer, SIGNAL(timeout()), SLOT(updateFromInstaller()));
dt's avatar
dt committed
134
135
136
137
138
}

void QtVersionManager::extensionsInitialized()
{
    bool success = restoreQtVersions();
139
    updateFromInstaller(false);
dt's avatar
dt committed
140
141
142
    if (!success) {
        // We did neither restore our settings or upgraded
        // in that case figure out if there's a qt in path
Friedemann Kleint's avatar
Friedemann Kleint committed
143
        // and add it to the Qt versions
dt's avatar
dt committed
144
145
146
        findSystemQt();
    }

147
    emit qtVersionsLoaded();
148
    emit qtVersionsChanged(m_versions.keys(), QList<int>(), QList<int>());
dt's avatar
dt committed
149
    saveQtVersions();
150

151
152
    const Utils::FileName configFileName = globalSettingsFileName();
    if (configFileName.toFileInfo().exists()) {
153
154
        m_configFileWatcher = new Utils::FileSystemWatcher(this);
        connect(m_configFileWatcher, SIGNAL(fileChanged(QString)),
155
                m_fileWatcherTimer, SLOT(start()));
156
        m_configFileWatcher->addFile(configFileName.toString(),
157
158
                                     Utils::FileSystemWatcher::WatchModifiedDate);
    } // exists
dt's avatar
dt committed
159
160
}

161
162
163
164
165
166
bool QtVersionManager::delayedInitialize()
{
    updateDocumentation();
    return true;
}

167
168
169
170
171
bool QtVersionManager::isLoaded() const
{
    return m_writer;
}

dt's avatar
dt committed
172
173
QtVersionManager::~QtVersionManager()
{
Tobias Hunger's avatar
Tobias Hunger committed
174
    delete m_writer;
dt's avatar
dt committed
175
176
177
178
179
180
181
182
183
184
185
    qDeleteAll(m_versions);
    m_versions.clear();
}

QtVersionManager *QtVersionManager::instance()
{
    return m_self;
}

bool QtVersionManager::restoreQtVersions()
{
186
187
188
189
    QTC_ASSERT(!m_writer, return false);
    m_writer = new Utils::PersistentSettingsWriter(settingsFileName(QLatin1String(QTVERSION_FILENAME)),
                                                   QLatin1String("QtCreatorQtVersions"));

190
    QList<QtVersionFactory *> factories = ExtensionSystem::PluginManager::getObjects<QtVersionFactory>();
dt's avatar
dt committed
191

Jarek Kobus's avatar
Jarek Kobus committed
192
    Utils::PersistentSettingsReader reader;
193
    Utils::FileName filename = settingsFileName(QLatin1String(QTVERSION_FILENAME));
194

Tobias Hunger's avatar
Tobias Hunger committed
195
    // Read Qt Creator 2.5 qtversions.xml once:
196
    if (!filename.toFileInfo().exists())
197
        filename = settingsFileName(QLatin1String(QTVERSION_LEGACY_FILENAME));
Tobias Hunger's avatar
Tobias Hunger committed
198
    if (!reader.load(filename))
dt's avatar
dt committed
199
200
201
202
203
204
205
206
        return false;
    QVariantMap data = reader.restoreValues();

    // Check version:
    int version = data.value(QLatin1String(QTVERSION_FILE_VERSION_KEY), 0).toInt();
    if (version < 1)
        return false;

207
    const QString keyPrefix = QLatin1String(QTVERSION_DATA_KEY);
208
209
210
    const QVariantMap::ConstIterator dcend = data.constEnd();
    for (QVariantMap::ConstIterator it = data.constBegin(); it != dcend; ++it) {
        const QString &key = it.key();
211
212
213
214
215
216
        if (!key.startsWith(keyPrefix))
            continue;
        bool ok;
        int count = key.mid(keyPrefix.count()).toInt(&ok);
        if (!ok || count < 0)
            continue;
dt's avatar
dt committed
217

218
        const QVariantMap qtversionMap = it.value().toMap();
219
        const QString type = qtversionMap.value(QLatin1String(QTVERSION_TYPE_KEY)).toString();
dt's avatar
dt committed
220
221
222
223

        bool restored = false;
        foreach (QtVersionFactory *f, factories) {
            if (f->canRestore(type)) {
224
                if (BaseQtVersion *qtv = f->restore(type, qtversionMap)) {
dt's avatar
dt committed
225
226
                    if (m_versions.contains(qtv->uniqueId())) {
                        // This shouldn't happen, we are restoring the same id multiple times?
227
                        qWarning() << "A Qt version with id"<<qtv->uniqueId()<<"already exists";
dt's avatar
dt committed
228
229
230
231
232
233
234
235
236
237
238
                        delete qtv;
                    } else {
                        m_versions.insert(qtv->uniqueId(), qtv);
                        m_idcount = qtv->uniqueId() > m_idcount ? qtv->uniqueId() : m_idcount;
                        restored = true;
                        break;
                    }
                }
            }
        }
        if (!restored)
239
            qWarning("Warning: Unable to restore Qt version '%s' stored in %s.",
dt's avatar
dt committed
240
                     qPrintable(type),
241
                     qPrintable(filename.toUserOutput()));
dt's avatar
dt committed
242
243
    }
    ++m_idcount;
244

dt's avatar
dt committed
245
246
247
    return true;
}

248
void QtVersionManager::updateFromInstaller(bool emitSignal)
dt's avatar
dt committed
249
{
250
251
    m_fileWatcherTimer->stop();

252
    const Utils::FileName path = globalSettingsFileName();
Tobias Hunger's avatar
Tobias Hunger committed
253
    // Handle overwritting of data:
254
    if (m_configFileWatcher) {
255
256
        m_configFileWatcher->removeFile(path.toString());
        m_configFileWatcher->addFile(path.toString(), Utils::FileSystemWatcher::WatchModifiedDate);
257
258
    }

259
260
261
262
    QList<int> added;
    QList<int> removed;
    QList<int> changed;

263
    QList<QtVersionFactory *> factories = ExtensionSystem::PluginManager::getObjects<QtVersionFactory>();
Jarek Kobus's avatar
Jarek Kobus committed
264
    Utils::PersistentSettingsReader reader;
265
    QVariantMap data;
266
    if (reader.load(path))
267
        data = reader.restoreValues();
dt's avatar
dt committed
268
269

    if (debug) {
270
        qDebug()<< "======= Existing Qt versions =======";
dt's avatar
dt committed
271
        foreach (BaseQtVersion *version, m_versions) {
272
            qDebug() << version->qmakeCommand().toString() << "id:"<<version->uniqueId();
dt's avatar
dt committed
273
274
275
276
277
            qDebug() << "  autodetection source:"<< version->autodetectionSource();
            qDebug() << "";
        }
        qDebug()<< "======= Adding sdk versions =======";
    }
278

dt's avatar
dt committed
279
    QStringList sdkVersions;
280
281

    const QString keyPrefix = QLatin1String(QTVERSION_DATA_KEY);
282
283
284
    const QVariantMap::ConstIterator dcend = data.constEnd();
    for (QVariantMap::ConstIterator it = data.constBegin(); it != dcend; ++it) {
        const QString &key = it.key();
285
286
287
288
289
290
        if (!key.startsWith(keyPrefix))
            continue;
        bool ok;
        int count = key.mid(keyPrefix.count()).toInt(&ok);
        if (!ok || count < 0)
            continue;
dt's avatar
dt committed
291

292
        QVariantMap qtversionMap = it.value().toMap();
293
        const QString type = qtversionMap.value(QLatin1String(QTVERSION_TYPE_KEY)).toString();
dt's avatar
dt committed
294
295
296
297
298
        const QString autoDetectionSource = qtversionMap.value(QLatin1String("autodetectionSource")).toString();
        sdkVersions << autoDetectionSource;
        int id = -1; // see BaseQtVersion::fromMap()
        QtVersionFactory *factory = 0;
        foreach (QtVersionFactory *f, factories) {
299
            if (f->canRestore(type))
dt's avatar
dt committed
300
301
302
303
304
305
306
                factory = f;
        }
        if (!factory) {
            if (debug)
                qDebug("Warning: Unable to find factory for type '%s'", qPrintable(type));
            continue;
        }
Friedemann Kleint's avatar
Friedemann Kleint committed
307
        // First try to find a existing Qt version to update
dt's avatar
dt committed
308
309
310
311
312
313
        bool restored = false;
        foreach (BaseQtVersion *v, m_versions) {
            if (v->autodetectionSource() == autoDetectionSource) {
                id = v->uniqueId();
                if (debug)
                    qDebug() << " Qt version found with same autodetection source" << autoDetectionSource << " => Migrating id:" << id;
314
                m_versions.remove(id);
dt's avatar
dt committed
315
316
                qtversionMap[QLatin1String("Id")] = id;

317
                if (BaseQtVersion *qtv = factory->restore(type, qtversionMap)) {
dt's avatar
dt committed
318
                    Q_ASSERT(qtv->isAutodetected());
319
                    m_versions.insert(id, qtv);
dt's avatar
dt committed
320
321
                    restored = true;
                }
322
323
324
325
                if (restored)
                    changed << id;
                else
                    removed << id;
dt's avatar
dt committed
326
327
328
329
330
331
            }
        }
        // Create a new qtversion
        if (!restored) { // didn't replace any existing versions
            if (debug)
                qDebug() << " No Qt version found matching" << autoDetectionSource << " => Creating new version";
332
            if (BaseQtVersion *qtv = factory->restore(type, qtversionMap)) {
dt's avatar
dt committed
333
                Q_ASSERT(qtv->isAutodetected());
334
335
                m_versions.insert(qtv->uniqueId(), qtv);
                added << qtv->uniqueId();
dt's avatar
dt committed
336
337
338
339
340
341
342
343
344
345
346
347
                restored = true;
            }
        }
        if (!restored)
            if (debug)
                qDebug("Warning: Unable to update qtversion '%s' from sdk installer.",
                       qPrintable(autoDetectionSource));
    }

    if (debug) {
        qDebug() << "======= Before removing outdated sdk versions =======";
        foreach (BaseQtVersion *version, m_versions) {
348
            qDebug() << version->qmakeCommand().toString() << "id:"<<version->uniqueId();
dt's avatar
dt committed
349
350
351
352
353
            qDebug() << "  autodetection source:"<< version->autodetectionSource();
            qDebug() << "";
        }
    }
    foreach (BaseQtVersion *qtVersion, QtVersionManager::instance()->versions()) {
354
        if (qtVersion->autodetectionSource().startsWith(QLatin1String("SDK."))) {
dt's avatar
dt committed
355
356
357
            if (!sdkVersions.contains(qtVersion->autodetectionSource())) {
                if (debug)
                    qDebug() << "  removing version"<<qtVersion->autodetectionSource();
358
359
                m_versions.remove(qtVersion->uniqueId());
                removed << qtVersion->uniqueId();
dt's avatar
dt committed
360
361
362
363
364
365
366
            }
        }
    }

    if (debug) {
        qDebug()<< "======= End result =======";
        foreach (BaseQtVersion *version, m_versions) {
367
            qDebug() << version->qmakeCommand().toString() << "id:"<<version->uniqueId();
dt's avatar
dt committed
368
369
370
371
            qDebug() << "  autodetection source:"<< version->autodetectionSource();
            qDebug() << "";
        }
    }
372
373
    if (emitSignal)
        emit qtVersionsChanged(added, removed, changed);
374
    saveQtVersions();
dt's avatar
dt committed
375
376
377
378
}

void QtVersionManager::saveQtVersions()
{
Tobias Hunger's avatar
Tobias Hunger committed
379
    if (!m_writer)
380
        return;
381
382
383

    QVariantMap data;
    data.insert(QLatin1String(QTVERSION_FILE_VERSION_KEY), 1);
dt's avatar
dt committed
384
385
386
387
388
389

    int count = 0;
    foreach (BaseQtVersion *qtv, m_versions) {
        QVariantMap tmp = qtv->toMap();
        if (tmp.isEmpty())
            continue;
390
        tmp.insert(QLatin1String(QTVERSION_TYPE_KEY), qtv->type());
391
        data.insert(QString::fromLatin1(QTVERSION_DATA_KEY) + QString::number(count), tmp);
dt's avatar
dt committed
392
393
394
        ++count;

    }
395
    m_writer->save(data, Core::ICore::mainWindow());
dt's avatar
dt committed
396
397
398
399
}

void QtVersionManager::findSystemQt()
{
400
    Utils::FileName systemQMakePath = QtSupport::DebuggingHelperLibrary::findSystemQt(Utils::Environment::systemEnvironment());
dt's avatar
dt committed
401
402
403
404
    if (systemQMakePath.isNull())
        return;

    BaseQtVersion *version = QtVersionFactory::createQtVersionFromQMakePath(systemQMakePath);
405
406
407
408
    if (version) {
        version->setDisplayName(BaseQtVersion::defaultDisplayName(version->qtVersionString(), systemQMakePath, true));
        m_versions.insert(version->uniqueId(), version);
    }
dt's avatar
dt committed
409
410
411
}

void QtVersionManager::addVersion(BaseQtVersion *version)
con's avatar
con committed
412
{
413
    QTC_ASSERT(m_writer, return);
414
    QTC_ASSERT(version != 0, return);
415
    if (m_versions.contains(version->uniqueId()))
416
417
        return;

418
    int uniqueId = version->uniqueId();
419
420
    m_versions.insert(uniqueId, version);

421
    emit qtVersionsChanged(QList<int>() << uniqueId, QList<int>(), QList<int>());
dt's avatar
dt committed
422
    saveQtVersions();
con's avatar
con committed
423
424
}

dt's avatar
dt committed
425
void QtVersionManager::removeVersion(BaseQtVersion *version)
426
{
427
    QTC_ASSERT(version != 0, return);
428
    m_versions.remove(version->uniqueId());
429
    emit qtVersionsChanged(QList<int>(), QList<int>() << version->uniqueId(), QList<int>());
dt's avatar
dt committed
430
    saveQtVersions();
431
432
433
    delete version;
}

con's avatar
con committed
434
435
void QtVersionManager::updateDocumentation()
{
kh1's avatar
kh1 committed
436
    Core::HelpManager *helpManager = Core::HelpManager::instance();
dt's avatar
dt committed
437
    Q_ASSERT(helpManager);
con's avatar
con committed
438
    QStringList files;
dt's avatar
dt committed
439
    foreach (BaseQtVersion *v, m_versions) {
440
441
442
443
444
445
446
447
        const QStringList docPaths = QStringList() << v->documentationPath() + QLatin1Char('/')
                                                   << v->documentationPath() + QLatin1String("/qch/");
        foreach (const QString &docPath, docPaths) {
            const QDir versionHelpDir(docPath);
            foreach (const QString &helpFile,
                     versionHelpDir.entryList(QStringList() << QLatin1String("*.qch"), QDir::Files))
                files << docPath + helpFile;
        }
con's avatar
con committed
448
449
450
451
    }
    helpManager->registerDocumentation(files);
}

452
void QtVersionManager::updateDumpFor(const Utils::FileName &qmakeCommand)
453
454
455
456
457
{
    foreach (BaseQtVersion *v, versions()) {
        if (v->qmakeCommand() == qmakeCommand)
            v->recheckDumper();
    }
458
    emit dumpUpdatedFor(qmakeCommand);
459
460
}

con's avatar
con committed
461
462
463
464
465
int QtVersionManager::getUniqueId()
{
    return m_idcount++;
}

dt's avatar
dt committed
466
QList<BaseQtVersion *> QtVersionManager::versions() const
con's avatar
con committed
467
{
dt's avatar
dt committed
468
    QList<BaseQtVersion *> versions;
469
    QTC_ASSERT(isLoaded(), return versions);
dt's avatar
dt committed
470
    foreach (BaseQtVersion *version, m_versions)
471
472
473
        versions << version;
    qSort(versions.begin(), versions.end(), &qtVersionNumberCompare);
    return versions;
con's avatar
con committed
474
475
}

dt's avatar
dt committed
476
QList<BaseQtVersion *> QtVersionManager::validVersions() const
477
{
dt's avatar
dt committed
478
    QList<BaseQtVersion *> results;
479
    QTC_ASSERT(isLoaded(), return results);
dt's avatar
dt committed
480
    foreach (BaseQtVersion *v, m_versions) {
481
482
483
        if (v->isValid())
            results.append(v);
    }
484
    qSort(results.begin(), results.end(), &qtVersionNumberCompare);
485
486
487
    return results;
}

488
489
bool QtVersionManager::isValidId(int id) const
{
490
    QTC_ASSERT(isLoaded(), return false);
491
    return m_versions.contains(id);
492
493
}

494
Core::FeatureSet QtVersionManager::availableFeatures(const QString &platformName) const
495
496
497
{
    Core::FeatureSet features;
    foreach (BaseQtVersion *const qtVersion, validVersions()) {
498
        if (qtVersion->isValid() && ((qtVersion->platformName() == platformName) || platformName.isEmpty()))
499
500
            features |= qtVersion->availableFeatures();
    }
501

502
503
504
    return features;
}

505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
QStringList QtVersionManager::availablePlatforms() const
{
    QStringList platforms;
    foreach (BaseQtVersion *const qtVersion, validVersions()) {
        if (qtVersion->isValid() && !qtVersion->platformName().isEmpty())
            platforms.append(qtVersion->platformName());
    }
    platforms.removeDuplicates();
    return platforms;
}

QString QtVersionManager::displayNameForPlatform(const QString &string) const
{
    foreach (BaseQtVersion *const qtVersion, validVersions()) {
        if (qtVersion->platformName() == string)
            return qtVersion->platformDisplayName();
    }
    return QString();
}

dt's avatar
dt committed
525
BaseQtVersion *QtVersionManager::version(int id) const
con's avatar
con committed
526
{
527
    QTC_ASSERT(isLoaded(), return 0);
dt's avatar
dt committed
528
    QMap<int, BaseQtVersion *>::const_iterator it = m_versions.find(id);
529
    if (it == m_versions.constEnd())
dt's avatar
dt committed
530
        return 0;
531
    return it.value();
con's avatar
con committed
532
533
}

534
535
536
class SortByUniqueId
{
public:
dt's avatar
dt committed
537
    bool operator()(BaseQtVersion *a, BaseQtVersion *b)
538
539
540
541
542
    {
        return a->uniqueId() < b->uniqueId();
    }
};

dt's avatar
dt committed
543
bool QtVersionManager::equals(BaseQtVersion *a, BaseQtVersion *b)
544
{
dt's avatar
dt committed
545
    return a->equals(b);
546
547
}

dt's avatar
dt committed
548
void QtVersionManager::setNewQtVersions(QList<BaseQtVersion *> newVersions)
549
{
550
551
    // We want to preserve the same order as in the settings dialog
    // so we sort a copy
dt's avatar
dt committed
552
    QList<BaseQtVersion *> sortedNewVersions = newVersions;
553
554
555
    SortByUniqueId sortByUniqueId;
    qSort(sortedNewVersions.begin(), sortedNewVersions.end(), sortByUniqueId);

556
557
    QList<int> addedVersions;
    QList<int> removedVersions;
558
559
560
561
562
    QList<int> changedVersions;
    // So we trying to find the minimal set of changed versions,
    // iterate over both sorted list

    // newVersions and oldVersions iterator
dt's avatar
dt committed
563
564
    QList<BaseQtVersion *>::const_iterator nit, nend;
    QMap<int, BaseQtVersion *>::const_iterator oit, oend;
565
566
567
568
569
570
571
572
573
    nit = sortedNewVersions.constBegin();
    nend = sortedNewVersions.constEnd();
    oit = m_versions.constBegin();
    oend = m_versions.constEnd();

    while (nit != nend && oit != oend) {
        int nid = (*nit)->uniqueId();
        int oid = (*oit)->uniqueId();
        if (nid < oid) {
574
            addedVersions.push_back(nid);
575
576
            ++nit;
        } else if (oid < nid) {
577
            removedVersions.push_back(oid);
578
579
580
581
582
583
            ++oit;
        } else {
            if (!equals(*oit, *nit))
                changedVersions.push_back(oid);
            ++oit;
            ++nit;
584
585
        }
    }
586
587

    while (nit != nend) {
588
        addedVersions.push_back((*nit)->uniqueId());
589
        ++nit;
590
591
592
    }

    while (oit != oend) {
593
        removedVersions.push_back((*oit)->uniqueId());
594
        ++oit;
595
596
    }

597
598
    qDeleteAll(m_versions);
    m_versions.clear();
dt's avatar
dt committed
599
    foreach (BaseQtVersion *v, sortedNewVersions)
600
        m_versions.insert(v->uniqueId(), v);
601

602
    if (!changedVersions.isEmpty() || !addedVersions.isEmpty() || !removedVersions.isEmpty())
603
604
        updateDocumentation();

dt's avatar
dt committed
605
    saveQtVersions();
606

607
608
    if (!changedVersions.isEmpty() || !addedVersions.isEmpty() || !removedVersions.isEmpty())
        emit qtVersionsChanged(addedVersions, removedVersions, changedVersions);
609
610
}

con's avatar
con committed
611
612
// Returns the version that was used to build the project in that directory
// That is returns the directory
Tobias Hunger's avatar
Tobias Hunger committed
613
// To find out whether we already have a qtversion for that directory call
con's avatar
con committed
614
// QtVersion *QtVersionManager::qtVersionForDirectory(const QString directory);
615
Utils::FileName QtVersionManager::findQMakeBinaryFromMakefile(const QString &makefile)
con's avatar
con committed
616
617
{
    bool debugAdding = false;
618
619
620
    QFile fi(makefile);
    if (fi.exists() && fi.open(QFile::ReadOnly)) {
        QTextStream ts(&fi);
621
        QRegExp r1(QLatin1String("QMAKE\\s*=(.*)"));
con's avatar
con committed
622
623
624
625
626
627
        while (!ts.atEnd()) {
            QString line = ts.readLine();
            if (r1.exactMatch(line)) {
                if (debugAdding)
                    qDebug()<<"#~~ QMAKE is:"<<r1.cap(1).trimmed();
                QFileInfo qmake(r1.cap(1).trimmed());
628
                QString qmakePath = qmake.filePath();
629
630
                if (Utils::HostOsInfo::isWindowsHost()
                        && !qmakePath.endsWith(QLatin1String(".exe"))) {
631
                    qmakePath.append(QLatin1String(".exe"));
632
                }
633
                // Is qmake still installed?
634
                QFileInfo fi(qmakePath);
635
                if (fi.exists())
Tobias Hunger's avatar
Tobias Hunger committed
636
                    return Utils::FileName(fi);
con's avatar
con committed
637
638
639
            }
        }
    }
640
    return Utils::FileName();
con's avatar
con committed
641
642
}

643
BaseQtVersion *QtVersionManager::qtVersionForQMakeBinary(const Utils::FileName &qmakePath)
con's avatar
con committed
644
{
Tobias Hunger's avatar
Tobias Hunger committed
645
646
647
648
649
650
651
    foreach (BaseQtVersion *version, versions()) {
        if (version->qmakeCommand() == qmakePath) {
            return version;
            break;
        }
    }
    return 0;
con's avatar
con committed
652
653
}

654
void dumpQMakeAssignments(const QList<QMakeAssignment> &list)
con's avatar
con committed
655
{
656
    foreach (const QMakeAssignment &qa, list) {
657
658
659
660
        qDebug()<<qa.variable<<qa.op<<qa.value;
    }
}

661
QtVersionManager::MakefileCompatible QtVersionManager::makefileIsFor(const QString &makefile, const QString &proFile)
662
663
{
    if (proFile.isEmpty())
664
        return CouldNotParse;
665

666
667
668
669
    // The Makefile.Debug / Makefile.Release lack a # Command: line
    if (findQMakeLine(makefile, QLatin1String("# Command:")).trimmed().isEmpty())
        return CouldNotParse;

670
    QString line = findQMakeLine(makefile, QLatin1String("# Project:")).trimmed();
671
    if (line.isEmpty())
672
        return CouldNotParse;
673

674
    line.remove(0, line.indexOf(QLatin1Char(':')) + 1);
675
676
    line = line.trimmed();

677
    QFileInfo srcFileInfo(QFileInfo(makefile).absoluteDir(), line);
678
    QFileInfo proFileInfo(proFile);
679
    return (srcFileInfo == proFileInfo) ? SameProject : DifferentProject;
680
681
}

dt's avatar
dt committed
682
QPair<BaseQtVersion::QmakeBuildConfigs, QString> QtVersionManager::scanMakeFile(const QString &makefile, BaseQtVersion::QmakeBuildConfigs defaultBuildConfig)
683
{
684
685
    if (debug)
        qDebug()<<"ScanMakeFile, the gory details:";
dt's avatar
dt committed
686
    BaseQtVersion::QmakeBuildConfigs result = defaultBuildConfig;
687
    QString result2;
688

689
    QString line = findQMakeLine(makefile, QLatin1String("# Command:"));
690
    if (!line.isEmpty()) {
691
692
        if (debug)
            qDebug()<<"Found line"<<line;
693
694
695
        line = trimLine(line);
        QList<QMakeAssignment> assignments;
        QList<QMakeAssignment> afterAssignments;
696
        parseArgs(line, &assignments, &afterAssignments, &result2);
697

698
699
700
701
702
703
        if (debug) {
            dumpQMakeAssignments(assignments);
            if (!afterAssignments.isEmpty())
                qDebug()<<"-after";
            dumpQMakeAssignments(afterAssignments);
        }
704
705
706
707
708

        // Search in assignments for CONFIG(+=,-=,=)(debug,release,debug_and_release)
        // Also remove them from the list
        result = qmakeBuildConfigFromCmdArgs(&assignments, defaultBuildConfig);

dt's avatar
dt committed
709
710
        if (debug)
            dumpQMakeAssignments(assignments);
711

712
        foreach (const QMakeAssignment &qa, assignments)
713
            Utils::QtcProcess::addArg(&result2, qa.variable + qa.op + qa.value);
714
        if (!afterAssignments.isEmpty()) {
715
            Utils::QtcProcess::addArg(&result2, QLatin1String("-after"));
716
            foreach (const QMakeAssignment &qa, afterAssignments)
717
                Utils::QtcProcess::addArg(&result2, qa.variable + qa.op + qa.value);
718
719
720
721
        }
    }

    // Dump the gathered information:
722
723
724
    if (debug) {
        qDebug()<<"\n\nDumping information from scanMakeFile";
        qDebug()<<"QMake CONFIG variable parsing";
725
        qDebug()<<"  "<< (result & BaseQtVersion::NoBuild ? QByteArray("No Build") : QByteArray::number(int(result)));
dt's avatar
dt committed
726
727
        qDebug()<<"  "<< (result & BaseQtVersion::DebugBuild ? "debug" : "release");
        qDebug()<<"  "<< (result & BaseQtVersion::BuildAll ? "debug_and_release" : "no debug_and_release");
728
729
730
731
        qDebug()<<"\nAddtional Arguments";
        qDebug()<<result2;
        qDebug()<<"\n\n";
    }
732
733
734
    return qMakePair(result, result2);
}

735
QString QtVersionManager::findQMakeLine(const QString &makefile, const QString &key)
736
{
737
738
739
    QFile fi(makefile);
    if (fi.exists() && fi.open(QFile::ReadOnly)) {
        QTextStream ts(&fi);
con's avatar
con committed
740
        while (!ts.atEnd()) {
741
            const QString line = ts.readLine();
742
            if (line.startsWith(key))
743
744
745
746
747
748
749
750
751
752
753
                return line;
        }
    }
    return QString();
}

/// This function trims the "#Command /path/to/qmake" from the the line
QString QtVersionManager::trimLine(const QString line)
{

    // Actually the first space after #Command: /path/to/qmake
754
    const int firstSpace = line.indexOf(QLatin1Char(' '), 11);
755
756
757
    return line.mid(firstSpace).trimmed();
}

758
void QtVersionManager::parseArgs(const QString &args, QList<QMakeAssignment> *assignments, QList<QMakeAssignment> *afterAssignments, QString *additionalArguments)
759
{
760
    QRegExp regExp(QLatin1String("([^\\s\\+-]*)\\s*(\\+=|=|-=|~=)(.*)"));
761
762
    bool after = false;
    bool ignoreNext = false;
763
764
765
    *additionalArguments = args;
    Utils::QtcProcess::ArgIterator ait(additionalArguments);
    while (ait.next()) {
766
767
768
        if (ignoreNext) {
            // Ignoring
            ignoreNext = false;
769
770
            ait.deleteArg();
        } else if (ait.value() == QLatin1String("-after")) {
771
            after = true;
772
773
774
            ait.deleteArg();
        } else if (ait.value().contains(QLatin1Char('='))) {
            if (regExp.exactMatch(ait.value())) {
775
776
777
778
779
780
781
782
783
784
785
                QMakeAssignment qa;
                qa.variable = regExp.cap(1);
                qa.op = regExp.cap(2);
                qa.value = regExp.cap(3).trimmed();
                if (after)
                    afterAssignments->append(qa);
                else
                    assignments->append(qa);
            } else {
                qDebug()<<"regexp did not match";
            }
786
787
            ait.deleteArg();
        } else if (ait.value() == QLatin1String("-o")) {
788
            ignoreNext = true;
789
            ait.deleteArg();
790
#if defined(Q_OS_WIN32)
791
        } else if (ait.value() == QLatin1String("-win32")) {
792
#elif defined(Q_OS_MAC)
793
        } else if (ait.value() == QLatin1String("-macx")) {
794
#elif defined(Q_OS_QNX6)
795
        } else if (ait.value() == QLatin1String("-qnx6")) {
796
#else
797
        } else if (ait.value() == QLatin1String("-unix")) {
798
#endif
799
800
801
802
            ait.deleteArg();
        }
    }
    ait.deleteArg();  // The .pro file is always the last arg
803
804
805
}

/// This function extracts all the CONFIG+=debug, CONFIG+=release
dt's avatar
dt committed
806
BaseQtVersion::QmakeBuildConfigs QtVersionManager::qmakeBuildConfigFromCmdArgs(QList<QMakeAssignment> *assignments, BaseQtVersion::QmakeBuildConfigs defaultBuildConfig)
807
{
dt's avatar
dt committed
808
    BaseQtVersion::QmakeBuildConfigs result = defaultBuildConfig;
809
810
    QList<QMakeAssignment> oldAssignments = *assignments;
    assignments->clear();
811
    foreach (const QMakeAssignment &qa, oldAssignments) {
812
813
        if (qa.variable == QLatin1String("CONFIG")) {
            QStringList values = qa.value.split(QLatin1Char(' '));
814
            QStringList newValues;
815
            foreach (const QString &value, values) {
816
817
                if (value == QLatin1String("debug")) {
                    if (qa.op == QLatin1String("+="))
dt's avatar
dt committed
818
                        result = result  | BaseQtVersion::DebugBuild;
819
                    else
dt's avatar
dt committed
820
                        result = result  & ~BaseQtVersion::DebugBuild;
821
822
                } else if (value == QLatin1String("release")) {
                    if (qa.op == QLatin1String("+="))
dt's avatar
dt committed
823
                        result = result & ~BaseQtVersion::DebugBuild;
824
                    else
dt's avatar
dt committed
825
                        result = result | BaseQtVersion::DebugBuild;
826
827
                } else if (value == QLatin1String("debug_and_release")) {
                    if (qa.op == QLatin1String("+="))
dt's avatar
dt committed
828
                        result = result | BaseQtVersion::BuildAll;
829
                    else
dt's avatar
dt committed
830
                        result = result & ~BaseQtVersion::BuildAll;
831
832
                } else {
                    newValues.append(value);
con's avatar
con committed
833
                }
834
                QMakeAssignment newQA = qa;
835
                newQA.value = newValues.join(QLatin1String(" "));
836
837
                if (!newValues.isEmpty())
                    assignments->append(newQA);
con's avatar
con committed
838
            }
839
840
        } else {
            assignments->append(qa);
con's avatar
con committed
841
842
843
844
        }
    }
    return result;
}
845

846
847
848
849
850
851
852
853
854
855
856
Core::FeatureSet QtFeatureProvider::availableFeatures(const QString &platformName) const
{
     return QtVersionManager::instance()->availableFeatures(platformName);
}

QStringList QtFeatureProvider::availablePlatforms() const
{
    return QtVersionManager::instance()->availablePlatforms();
}

QString QtFeatureProvider::displayNameForPlatform(const QString &string) const
857
{
858
    return QtVersionManager::instance()->displayNameForPlatform(string);
859
}