qtversionmanager.cpp 52.9 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
7
8
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
9
** Commercial Usage
10
**
11
12
13
14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18
19
20
21
22
23
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
**
25
26
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

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

con's avatar
con committed
32
#include "qt4projectmanagerconstants.h"
33
#include "ui_showbuildlog.h"
con's avatar
con committed
34

35
#include <coreplugin/icore.h>
con's avatar
con committed
36
#include <coreplugin/coreconstants.h>
37
#include <extensionsystem/pluginmanager.h>
dt's avatar
dt committed
38
39
#include <projectexplorer/cesdkhandler.h>
#include <projectexplorer/toolchain.h>
con's avatar
con committed
40
#include <help/helpplugin.h>
hjk's avatar
hjk committed
41
#include <utils/qtcassert.h>
con's avatar
con committed
42

hjk's avatar
hjk committed
43
44
#include <QtCore/QDebug>
#include <QtCore/QProcess>
con's avatar
con committed
45
46
47
#include <QtCore/QSettings>
#include <QtCore/QStringRef>
#include <QtCore/QTime>
hjk's avatar
hjk committed
48

con's avatar
con committed
49
#include <QtGui/QFileDialog>
hjk's avatar
hjk committed
50
#include <QtGui/QHeaderView>
con's avatar
con committed
51
#include <QtGui/QMessageBox>
52
53
54
55
56
57
#include <QtGui/QPushButton>
#include <QtGui/QToolButton>
#include <QtGui/QApplication>
#include <QtGui/QDesktopServices>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
con's avatar
con committed
58
59
60
61
62
63
64
65
66

using namespace Qt4ProjectManager::Internal;

using ProjectExplorer::Environment;

static const char *QtVersionsSectionName = "QtVersions";
static const char *defaultQtVersionKey = "DefaultQtVersion";
static const char *newQtVersionsKey = "NewQtVersions";

67
68


con's avatar
con committed
69
70
71
QtVersionManager::QtVersionManager()
    : m_emptyVersion(new QtVersion)
{
72
    QSettings *s = Core::ICore::instance()->settings();
con's avatar
con committed
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
    m_defaultVersion = s->value(defaultQtVersionKey, 0).toInt();

    m_idcount = 1;
    int size = s->beginReadArray(QtVersionsSectionName);
    for (int i = 0; i < size; ++i) {
        s->setArrayIndex(i);
        // Find the right id
        // Either something saved or something generated
        // Note: This code assumes that either all ids are read from the settings
        // or generated on the fly.
        int id = s->value("Id", -1).toInt();
        if (id == -1)
            id = getUniqueId();
        else if (id > m_idcount)
            m_idcount = id;
        QtVersion *version = new QtVersion(s->value("Name").toString(),
                                           s->value("Path").toString(),
                                           id,
                                           s->value("IsSystemVersion", false).toBool());
        version->setMingwDirectory(s->value("MingwDirectory").toString());
        version->setPrependPath(s->value("PrependPath").toString());
        version->setMsvcVersion(s->value("msvcVersion").toString());
        m_versions.append(version);
    }
    s->endArray();
    updateUniqueIdToIndexMap();

    ++m_idcount;
    addNewVersionsFromInstaller();
    updateSystemVersion();

    writeVersionsIntoSettings();
    updateDocumentation();
}

QtVersionManager::~QtVersionManager()
{
    qDeleteAll(m_versions);
    m_versions.clear();
    delete m_emptyVersion;
    m_emptyVersion = 0;
}

void QtVersionManager::addVersion(QtVersion *version)
{
    m_versions.append(version);
    emit qtVersionsChanged();
120
    writeVersionsIntoSettings();
con's avatar
con committed
121
122
123
124
}

void QtVersionManager::updateDocumentation()
{
125
126
    Help::HelpManager *helpManager
        = ExtensionSystem::PluginManager::instance()->getObject<Help::HelpManager>();
dt's avatar
dt committed
127
    Q_ASSERT(helpManager);
con's avatar
con committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
    QStringList fileEndings = QStringList() << "/qch/qt.qch" << "/qch/qmake.qch" << "/qch/designer.qch";
    QStringList files;
    foreach (QtVersion *version, m_versions) {
        QString docPath = version->versionInfo().value("QT_INSTALL_DOCS");
        foreach (const QString &fileEnding, fileEndings)
            files << docPath+fileEnding;
    }
    helpManager->registerDocumentation(files);
}

int QtVersionManager::getUniqueId()
{
    return m_idcount++;
}

143
144
145
146
147
148
QString QtVersionManager::id() const
{
    return QLatin1String(Constants::QTVERSION_PAGE);
}

QString QtVersionManager::trName() const
con's avatar
con committed
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
{
    return tr(Constants::QTVERSION_PAGE);
}

QString QtVersionManager::category() const
{
    return Constants::QT_CATEGORY;
}

QString QtVersionManager::trCategory() const
{
    return tr(Constants::QT_CATEGORY);
}

QWidget *QtVersionManager::createPage(QWidget *parent)
{
    if (m_widget)
        delete m_widget;
    m_widget = new QtDirWidget(parent, m_versions, m_defaultVersion);
    return m_widget;
}

void QtVersionManager::updateUniqueIdToIndexMap()
{
    m_uniqueIdToIndex.clear();
hjk's avatar
hjk committed
174
    for (int i = 0; i < m_versions.size(); ++i)
con's avatar
con committed
175
176
177
        m_uniqueIdToIndex.insert(m_versions.at(i)->uniqueId(), i);
}

178
void QtVersionManager::apply()
con's avatar
con committed
179
180
181
182
183
184
185
186
187
188
189
190
{
    m_widget->finish();
    QList<QtVersion*> newVersions = m_widget->versions();
    bool versionPathsChanged = m_versions.size() != newVersions.size();
    if (!versionPathsChanged) {
        for (int i = 0; i < m_versions.size(); ++i) {
            if (m_versions.at(i)->path() != newVersions.at(i)->path()) {
                versionPathsChanged = true;
                break;
            }
        }
    }
191
192
193
194
    qDeleteAll(m_versions);
    m_versions.clear();
    foreach(QtVersion *version, m_widget->versions())
        m_versions.append(new QtVersion(*version));
con's avatar
con committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    if (versionPathsChanged)
        updateDocumentation();
    updateUniqueIdToIndexMap();

    bool emitDefaultChanged = false;
    if (m_defaultVersion != m_widget->defaultVersion()) {
        m_defaultVersion = m_widget->defaultVersion();
        emitDefaultChanged = true;
    }

    emit qtVersionsChanged();
    if (emitDefaultChanged)
        emit defaultQtVersionChanged();

    writeVersionsIntoSettings();
}

void QtVersionManager::writeVersionsIntoSettings()
{
214
    QSettings *s = Core::ICore::instance()->settings();
con's avatar
con committed
215
    s->setValue(defaultQtVersionKey, m_defaultVersion);
216
    s->beginWriteArray(QtVersionsSectionName);
con's avatar
con committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
    for (int i = 0; i < m_versions.size(); ++i) {
        s->setArrayIndex(i);
        s->setValue("Name", m_versions.at(i)->name());
        s->setValue("Path", m_versions.at(i)->path());
        s->setValue("Id", m_versions.at(i)->uniqueId());
        s->setValue("MingwDirectory", m_versions.at(i)->mingwDirectory());
        s->setValue("PrependPath", m_versions.at(i)->prependPath());
        s->setValue("msvcVersion", m_versions.at(i)->msvcVersion());
        s->setValue("IsSystemVersion", m_versions.at(i)->isSystemVersion());
    }
    s->endArray();
}

QList<QtVersion* > QtVersionManager::versions() const
{
    return m_versions;
}

QtVersion *QtVersionManager::version(int id) const
{
    int pos = m_uniqueIdToIndex.value(id, -1);
    if (pos != -1)
        return m_versions.at(pos);

hjk's avatar
hjk committed
241
    if (m_defaultVersion < m_versions.count())
con's avatar
con committed
242
243
244
245
246
247
248
249
250
251
252
        return m_versions.at(m_defaultVersion);
    else
        return m_emptyVersion;
}

void QtVersionManager::addNewVersionsFromInstaller()
{
    // Add new versions which may have been installed by the WB installer in the form:
    // NewQtVersions="qt 4.3.2=c:\\qt\\qt432;qt embedded=c:\\qtembedded;"
    // or NewQtVersions="qt 4.3.2=c:\\qt\\qt432=c:\\qtcreator\\mingw\\=prependToPath;
    // Duplicate entries are not added, the first new version is set as default.
253
    QSettings *settings = Core::ICore::instance()->settings();
254
255
256

    if (!settings->contains(newQtVersionsKey) &&
        !settings->contains(QLatin1String("Installer/")+newQtVersionsKey))
con's avatar
con committed
257
258
259
260
261
        return;

//    qDebug()<<"QtVersionManager::addNewVersionsFromInstaller()";

    QString newVersionsValue = settings->value(newQtVersionsKey).toString();
262
263
264
    if (newVersionsValue.isEmpty())
        newVersionsValue = settings->value(QLatin1String("Installer/")+newQtVersionsKey).toString();

con's avatar
con committed
265
266
267
268
    QStringList newVersionsList = newVersionsValue.split(';', QString::SkipEmptyParts);
    bool defaultVersionWasReset = false;
    foreach (QString newVersion, newVersionsList) {
        QStringList newVersionData = newVersion.split('=');
hjk's avatar
hjk committed
269
        if (newVersionData.count()>=2) {
con's avatar
con committed
270
271
            if (QDir(newVersionData[1]).exists()) {
                QtVersion *version = new QtVersion(newVersionData[0], newVersionData[1], m_idcount++ );
hjk's avatar
hjk committed
272
                if (newVersionData.count() >= 3)
con's avatar
con committed
273
                    version->setMingwDirectory(newVersionData[2]);
hjk's avatar
hjk committed
274
                if (newVersionData.count() >= 4)
con's avatar
con committed
275
276
277
278
                    version->setPrependPath(newVersionData[3]);

                bool versionWasAlreadyInList = false;
                foreach(const QtVersion * const it, m_versions) {
hjk's avatar
hjk committed
279
                    if (QDir(version->path()).canonicalPath() == QDir(it->path()).canonicalPath()) {
con's avatar
con committed
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
                        versionWasAlreadyInList = true;
                        break;
                    }
                }

                if (!versionWasAlreadyInList) {
                    m_versions.append(version);
                } else {
                    // clean up
                    delete version;
                }
                if (!defaultVersionWasReset) {
                    m_defaultVersion = versionWasAlreadyInList? m_defaultVersion : m_versions.count() - 1;
                    defaultVersionWasReset = true;
                }
            }
        }
    }
    settings->remove(newQtVersionsKey);
299
    settings->remove(QLatin1String("Installer/")+newQtVersionsKey);
con's avatar
con committed
300
301
302
303
304
305
306
307
308
    updateUniqueIdToIndexMap();
}

void QtVersionManager::updateSystemVersion()
{
    bool haveSystemVersion = false;
    foreach (QtVersion *version, m_versions) {
        if (version->isSystemVersion()) {
            version->setPath(findSystemQt());
309
            version->setName(tr("Auto-detected Qt"));
con's avatar
con committed
310
311
312
313
314
            haveSystemVersion = true;
        }
    }
    if (haveSystemVersion)
        return;
315
    QtVersion *version = new QtVersion(tr("Auto-detected Qt"),
con's avatar
con committed
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
                                       findSystemQt(),
                                       getUniqueId(),
                                       true);
    m_versions.prepend(version);
    updateUniqueIdToIndexMap();
    if (m_versions.size() > 1) // we had other versions before adding system version
        ++m_defaultVersion;
}

QStringList QtVersionManager::possibleQMakeCommands()
{
    // On windows noone has renamed qmake, right?
#ifdef Q_OS_WIN
    return QStringList() << "qmake.exe";
#endif
    // On unix some distributions renamed qmake to avoid clashes
    QStringList result;
    result << "qmake-qt4" << "qmake4" << "qmake";
    return result;
}

337
QString QtVersionManager::qtVersionForQMake(const QString &qmakePath)
con's avatar
con committed
338
339
340
341
342
343
344
345
{
    QProcess qmake;
    qmake.start(qmakePath, QStringList()<<"--version");
    if (!qmake.waitForFinished())
        return false;
    QString output = qmake.readAllStandardOutput();
    QRegExp regexp("(QMake version|Qmake version:)[\\s]*([\\d.]*)");
    regexp.indexIn(output);
346
347
348
349
350
351
    if (regexp.cap(2).startsWith("2.")) {
        QRegExp regexp2("Using Qt version[\\s]*([\\d\\.]*)");
        regexp2.indexIn(output);
        return regexp2.cap(1);
    }
    return QString();
con's avatar
con committed
352
353
354
355
356
357
358
359
360
361
}

QString QtVersionManager::findSystemQt() const
{
    Environment env = Environment::systemEnvironment();
    QStringList paths = env.path();
    foreach (const QString &path, paths) {
        foreach (const QString &possibleCommand, possibleQMakeCommands()) {
            QFileInfo qmake(path + "/" + possibleCommand);
            if (qmake.exists()) {
362
                if (!qtVersionForQMake(qmake.absoluteFilePath()).isNull()) {
con's avatar
con committed
363
364
365
366
367
368
369
370
371
372
373
374
                    QDir dir(qmake.absoluteDir());
                    dir.cdUp();
                    return dir.absolutePath();
                }
            }
        }
    }
    return tr("<not found>");
}

QtVersion *QtVersionManager::currentQtVersion() const
{
hjk's avatar
hjk committed
375
    if (m_defaultVersion < m_versions.count())
con's avatar
con committed
376
377
378
379
380
381
382
383
384
385
386
387
        return m_versions.at(m_defaultVersion);
    else
        return m_emptyVersion;
}

//-----------------------------------------------------
QtDirWidget::QtDirWidget(QWidget *parent, QList<QtVersion *> versions, int defaultVersion)
    : QWidget(parent)
    , m_defaultVersion(defaultVersion)
    , m_specifyNameString(tr("<specify a name>"))
    , m_specifyPathString(tr("<specify a path>"))
{
388
389
390
391
392
393
    // Initialize m_versions
    foreach(QtVersion *version, versions) {
        m_versions.append(new QtVersion(*version));
    }


con's avatar
con committed
394
    m_ui.setupUi(this);
395
396
397
    m_ui.qtPath->setExpectedKind(Core::Utils::PathChooser::Directory);
    m_ui.qtPath->setPromptDialogTitle(tr("Select QTDIR"));
    m_ui.mingwPath->setExpectedKind(Core::Utils::PathChooser::Directory);
398
    m_ui.qtPath->setPromptDialogTitle(tr("Select the Qt Directory"));
con's avatar
con committed
399
400
401
402
403
404
405
406
407
408

    m_ui.addButton->setIcon(QIcon(Core::Constants::ICON_PLUS));
    m_ui.delButton->setIcon(QIcon(Core::Constants::ICON_MINUS));

    for (int i = 0; i < m_versions.count(); ++i) {
        const QtVersion * const version = m_versions.at(i);
        QTreeWidgetItem *item = new QTreeWidgetItem(m_ui.qtdirList);
        item->setText(0, version->name());
        item->setText(1, version->path());
        item->setData(0, Qt::UserRole, version->uniqueId());
409

410
411
        if (version->isValid()) {
            if (version->hasDebuggingHelper())
412
                item->setData(2, Qt::DecorationRole, QIcon(":/extensionsystem/images/ok.png"));
413
            else
414
                item->setData(2, Qt::DecorationRole, QIcon(":/extensionsystem/images/error.png"));
415
        } else {
416
            item->setData(2, Qt::DecorationRole, QIcon());
417
        }
418

con's avatar
con committed
419
420
421
422
423
424
425
        m_ui.defaultCombo->addItem(version->name());
        if (i == m_defaultVersion)
            m_ui.defaultCombo->setCurrentIndex(i);
    }

    connect(m_ui.nameEdit, SIGNAL(textEdited(const QString &)),
            this, SLOT(updateCurrentQtName()));
426
427
428


    connect(m_ui.qtPath, SIGNAL(changed()),
con's avatar
con committed
429
            this, SLOT(updateCurrentQtPath()));
430
    connect(m_ui.mingwPath, SIGNAL(changed()),
con's avatar
con committed
431
432
433
434
435
436
            this, SLOT(updateCurrentMingwDirectory()));

    connect(m_ui.addButton, SIGNAL(clicked()),
            this, SLOT(addQtDir()));
    connect(m_ui.delButton, SIGNAL(clicked()),
            this, SLOT(removeQtDir()));
437
438
439
440
441

    connect(m_ui.qtPath, SIGNAL(browsingFinished()),
            this, SLOT(onQtBrowsed()));
    connect(m_ui.mingwPath, SIGNAL(browsingFinished()),
            this, SLOT(onMingwBrowsed()));
con's avatar
con committed
442
443
444
445
446
447
448
449
450

    connect(m_ui.qtdirList, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),
            this, SLOT(versionChanged(QTreeWidgetItem *, QTreeWidgetItem *)));
    connect(m_ui.defaultCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(defaultChanged(int)));

    connect(m_ui.msvcComboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(msvcVersionChanged()));

451
452
453
454
455
    connect(m_ui.rebuildButton, SIGNAL(clicked()),
            this, SLOT(buildDebuggingHelper()));
    connect(m_ui.showLogButton, SIGNAL(clicked()),
            this, SLOT(showDebuggingBuildLog()));

con's avatar
con committed
456
457
458
459
    showEnvironmentPage(0);
    updateState();
}

460
461
462
void QtDirWidget::buildDebuggingHelper()
{
    // Find the qt version for this button..
463
464
    QTreeWidgetItem *currentItem = m_ui.qtdirList->currentItem();
    if (!currentItem)
465
466
        return;

467
468
    int currentItemIndex = m_ui.qtdirList->indexOfTopLevelItem(currentItem);
    QtVersion *version = m_versions[currentItemIndex];
469

470
471
    QString result = m_versions.at(currentItemIndex)->buildDebuggingHelperLibrary();
    currentItem->setData(2, Qt::UserRole, result);
472

473
474
475
476
477
478
    if (version->hasDebuggingHelper()) {
        m_ui.debuggingHelperStateLabel->setPixmap(QPixmap(":/extensionsystem/images/ok.png"));
        currentItem->setData(2, Qt::DecorationRole, QIcon(":/extensionsystem/images/ok.png"));
    } else {        
        m_ui.debuggingHelperStateLabel->setPixmap(QPixmap(":/extensionsystem/images/error.png"));
        currentItem->setData(2, Qt::DecorationRole, QIcon(":/extensionsystem/images/error.png"));
479
    }
480
    m_ui.showLogButton->setEnabled(true);
481
482
483
484
}

void QtDirWidget::showDebuggingBuildLog()
{
485
486
    QTreeWidgetItem *currentItem = m_ui.qtdirList->currentItem();
    if (!currentItem)
487
488
        return;

489
    int currentItemIndex = m_ui.qtdirList->indexOfTopLevelItem(currentItem);
490
    QDialog dlg;
hjk's avatar
hjk committed
491
    Ui_ShowBuildLog ui;
492
    ui.setupUi(&dlg);
493
    ui.log->setPlainText(m_ui.qtdirList->topLevelItem(currentItemIndex)->data(2, Qt::UserRole).toString());
494
495
496
    dlg.exec();
}

497
498
499
500
501
QtDirWidget::~QtDirWidget()
{
    qDeleteAll(m_versions);
}

con's avatar
con committed
502
503
504
505
506
507
508
509
510
void QtDirWidget::addQtDir()
{
    QtVersion *newVersion = new QtVersion(m_specifyNameString, m_specifyPathString);
    m_versions.append(newVersion);

    QTreeWidgetItem *item = new QTreeWidgetItem(m_ui.qtdirList);
    item->setText(0, newVersion->name());
    item->setText(1, newVersion->path());
    item->setData(0, Qt::UserRole, newVersion->uniqueId());
511
    item->setData(2, Qt::DecorationRole, QIcon());
512

513
    m_ui.qtdirList->setCurrentItem(item);
con's avatar
con committed
514

515
516
    m_ui.nameEdit->setText(newVersion->name());
    m_ui.qtPath->setPath(newVersion->path());
con's avatar
con committed
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
    m_ui.defaultCombo->addItem(newVersion->name());
    m_ui.nameEdit->setFocus();
    m_ui.nameEdit->selectAll();
}

void QtDirWidget::removeQtDir()
{
    QTreeWidgetItem *item = m_ui.qtdirList->currentItem();
    int index = m_ui.qtdirList->indexOfTopLevelItem(item);
    if (index < 0)
        return;

    for (int i = 0; i < m_ui.defaultCombo->count(); ++i) {
        if (m_ui.defaultCombo->itemText(i) == item->text(0)) {
            m_ui.defaultCombo->removeItem(i);
            break;
        }
    }

    delete item;

    delete m_versions.takeAt(index);
    updateState();
}

void QtDirWidget::updateState()
{
    bool enabled = (m_ui.qtdirList->currentItem() != 0);
    bool isSystemVersion = (enabled 
        && m_versions.at(m_ui.qtdirList->indexOfTopLevelItem(m_ui.qtdirList->currentItem()))->isSystemVersion());
    m_ui.delButton->setEnabled(enabled && !isSystemVersion);
    m_ui.nameEdit->setEnabled(enabled && !isSystemVersion);
549
550
551
    m_ui.qtPath->setEnabled(enabled && !isSystemVersion);
    m_ui.mingwPath->setEnabled(enabled);

552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
    bool hasLog = enabled && !m_ui.qtdirList->currentItem()->data(2, Qt::UserRole).toString().isEmpty();
    m_ui.showLogButton->setEnabled(hasLog);

    QtVersion *version = 0;
    if (enabled)
        version = m_versions.at(m_ui.qtdirList->indexOfTopLevelItem(m_ui.qtdirList->currentItem()));
    if (version) {
        m_ui.rebuildButton->setEnabled(version->isValid());
        if (version->hasDebuggingHelper())
            m_ui.debuggingHelperStateLabel->setPixmap(QPixmap(":/extensionsystem/images/ok.png"));
        else
            m_ui.debuggingHelperStateLabel->setPixmap(QPixmap(":/extensionsystem/images/error.png"));
    } else {
        m_ui.rebuildButton->setEnabled(false);
        m_ui.debuggingHelperStateLabel->setPixmap(QPixmap());
    }
}
569
570
571
572
void QtDirWidget::makeMingwVisible(bool visible)
{
    m_ui.mingwLabel->setVisible(visible);
    m_ui.mingwPath->setVisible(visible);
con's avatar
con committed
573
574
575
576
577
}

void QtDirWidget::showEnvironmentPage(QTreeWidgetItem *item)
{
    m_ui.msvcComboBox->setVisible(false);
hjk's avatar
hjk committed
578
    if (item) {
con's avatar
con committed
579
580
        int index = m_ui.qtdirList->indexOfTopLevelItem(item);
        m_ui.errorLabel->setText("");
dt's avatar
dt committed
581
582
        ProjectExplorer::ToolChain::ToolChainType t = m_versions.at(index)->toolchainType();
        if (t == ProjectExplorer::ToolChain::MinGW) {
con's avatar
con committed
583
            m_ui.msvcComboBox->setVisible(false);
584
585
            makeMingwVisible(true);
            m_ui.mingwPath->setPath(m_versions.at(index)->mingwDirectory());
dt's avatar
dt committed
586
        } else if (t == ProjectExplorer::ToolChain::MSVC || t == ProjectExplorer::ToolChain::WINCE){
con's avatar
con committed
587
            m_ui.msvcComboBox->setVisible(false);
588
            makeMingwVisible(false);
dt's avatar
dt committed
589
590
591
            QStringList msvcEnvironments = ProjectExplorer::ToolChain::availableMSVCVersions();
            if (msvcEnvironments.count() == 0) {
            } else if (msvcEnvironments.count() == 1) {
con's avatar
con committed
592
593
594
            } else {
                 m_ui.msvcComboBox->setVisible(true);
                 bool block = m_ui.msvcComboBox->blockSignals(true);
595
                 m_ui.msvcComboBox->clear();
dt's avatar
dt committed
596
597
598
                 foreach(const QString &msvcenv, msvcEnvironments) {
                     m_ui.msvcComboBox->addItem(msvcenv);
                     if (msvcenv == m_versions.at(index)->msvcVersion()) {
con's avatar
con committed
599
600
601
602
603
                         m_ui.msvcComboBox->setCurrentIndex(m_ui.msvcComboBox->count() - 1);
                     }
                 }
                 m_ui.msvcComboBox->blockSignals(block);
            }
dt's avatar
dt committed
604
        } else if (t == ProjectExplorer::ToolChain::INVALID) {
con's avatar
con committed
605
            m_ui.msvcComboBox->setVisible(false);
606
            makeMingwVisible(false);
con's avatar
con committed
607
            if (!m_versions.at(index)->isInstalled())
608
609
                m_ui.errorLabel->setText(tr("The Qt Version %1 is not installed. Run make install")
                                           .arg(QDir::toNativeSeparators(m_versions.at(index)->path())));
con's avatar
con committed
610
611
            else
                m_ui.errorLabel->setText(tr("%1 is not a valid qt directory").arg(m_versions.at(index)->path()));
dt's avatar
dt committed
612
        } else { //ProjectExplorer::ToolChain::GCC
con's avatar
con committed
613
            m_ui.msvcComboBox->setVisible(false);
614
            makeMingwVisible(false);
615
616
617
618
            m_ui.errorLabel->setText("Found Qt version "
                                     + m_versions.at(index)->qtVersionString()
                                     + " using mkspec "
                                     + m_versions.at(index)->mkspec());
con's avatar
con committed
619
620
621
        }
    } else {
        m_ui.msvcComboBox->setVisible(false);
622
        makeMingwVisible(false);
con's avatar
con committed
623
624
625
626
627
    }
}

void QtDirWidget::versionChanged(QTreeWidgetItem *item, QTreeWidgetItem *old)
{
hjk's avatar
hjk committed
628
    if (old) {
con's avatar
con committed
629
630
631
632
        fixQtVersionName(m_ui.qtdirList->indexOfTopLevelItem(old));
    }
    if (item) {
        m_ui.nameEdit->setText(item->text(0));
633
        m_ui.qtPath->setPath(item->text(1));
con's avatar
con committed
634
635
    } else {
        m_ui.nameEdit->clear();
636
        m_ui.qtPath->setPath(""); // clear()
con's avatar
con committed
637
638
639
640
641
    }
    showEnvironmentPage(item);
    updateState();
}

642
void QtDirWidget::onQtBrowsed()
con's avatar
con committed
643
{
644
    const QString dir = m_ui.qtPath->path();
con's avatar
con committed
645
646
647
648
649
650
651
652
653
654
655
656
657
    if (dir.isEmpty())
        return;

    updateCurrentQtPath();
    if (m_ui.nameEdit->text().isEmpty() || m_ui.nameEdit->text() == m_specifyNameString) {
        QStringList dirSegments = dir.split(QDir::separator(), QString::SkipEmptyParts);
        if (!dirSegments.isEmpty())
            m_ui.nameEdit->setText(dirSegments.last());
        updateCurrentQtName();
    }
    updateState();
}

658
void QtDirWidget::onMingwBrowsed()
con's avatar
con committed
659
{
660
    const QString dir = m_ui.mingwPath->path();
con's avatar
con committed
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
    if (dir.isEmpty())
        return;

    updateCurrentMingwDirectory();
    updateState();
}

void QtDirWidget::defaultChanged(int)
{
    for (int i=0; i<m_ui.defaultCombo->count(); ++i) {
        if (m_versions.at(i)->name() == m_ui.defaultCombo->currentText()) {
            m_defaultVersion = i;
            return;
        }
    }

    m_defaultVersion = 0;
}

void QtDirWidget::updateCurrentQtName()
{
    QTreeWidgetItem *currentItem = m_ui.qtdirList->currentItem();
dt's avatar
dt committed
683
    Q_ASSERT(currentItem);
con's avatar
con committed
684
685
686
687
688
689
690
691
692
693
    int currentItemIndex = m_ui.qtdirList->indexOfTopLevelItem(currentItem);
    m_versions[currentItemIndex]->setName(m_ui.nameEdit->text());
    currentItem->setText(0, m_versions[currentItemIndex]->name());

    m_ui.defaultCombo->setItemText(currentItemIndex, m_versions[currentItemIndex]->name());
}


void QtDirWidget::finish()
{
hjk's avatar
hjk committed
694
    if (QTreeWidgetItem *item = m_ui.qtdirList->currentItem())
con's avatar
con committed
695
696
697
698
699
700
701
702
703
704
        fixQtVersionName(m_ui.qtdirList->indexOfTopLevelItem(item));
}

/* Checks that the qt version name is unique
 * and otherwise changes the name
 *
 */
void QtDirWidget::fixQtVersionName(int index)
{
    int count = m_versions.count();
hjk's avatar
hjk committed
705
706
707
    for (int i = 0; i < count; ++i) {
        if (i != index) {
            if (m_versions.at(i)->name() == m_versions.at(index)->name()) {
con's avatar
con committed
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
                // Same name, find new name
                QString name = m_versions.at(index)->name();
                QRegExp regexp("^(.*)\\((\\d)\\)$");
                if (regexp.exactMatch(name)) {
                    // Alreay in Name (#) format
                    name = regexp.cap(1) + "(" + QString().setNum(regexp.cap(2).toInt() + 1) + ")";
                } else {
                    name = name + " (2)";
                }
                // set new name
                m_versions[index]->setName(name);
                m_ui.qtdirList->topLevelItem(index)->setText(0, name);
                m_ui.defaultCombo->setItemText(index, name);

                // Now check again...
                fixQtVersionName(index);
            }
        }
    }
}

void QtDirWidget::updateCurrentQtPath()
{
    QTreeWidgetItem *currentItem = m_ui.qtdirList->currentItem();
dt's avatar
dt committed
732
    Q_ASSERT(currentItem);
con's avatar
con committed
733
    int currentItemIndex = m_ui.qtdirList->indexOfTopLevelItem(currentItem);
734
735
    if (m_versions[currentItemIndex]->path() == m_ui.qtPath->path())
        return;
736
    m_versions[currentItemIndex]->setPath(m_ui.qtPath->path());
con's avatar
con committed
737
738
739
    currentItem->setText(1, m_versions[currentItemIndex]->path());

    showEnvironmentPage(currentItem);
740
741

    if (m_versions[currentItemIndex]->isValid()) {
742
743
744
745
746
747
748
749
750
751
        bool hasLog = !currentItem->data(2, Qt::UserRole).toString().isEmpty();
        bool hasHelper = m_versions[currentItemIndex]->hasDebuggingHelper();
        if (hasHelper) {
            currentItem->setData(2, Qt::DecorationRole, QIcon(":/extensionsystem/images/ok.png"));
            m_ui.debuggingHelperStateLabel->setPixmap(QPixmap(":/extensionsystem/images/ok.png"));
        } else {
            currentItem->setData(2, Qt::DecorationRole, QIcon(":/extensionsystem/images/error.png"));
            m_ui.debuggingHelperStateLabel->setPixmap(QPixmap(":/extensionsystem/images/error.png"));
        }
        m_ui.showLogButton->setEnabled(hasLog);
752
    } else {
753
754
        currentItem->setData(2, Qt::DecorationRole, QIcon());
        m_ui.debuggingHelperStateLabel->setPixmap(QPixmap());
755
    }
con's avatar
con committed
756
757
758
759
760
}

void QtDirWidget::updateCurrentMingwDirectory()
{
    QTreeWidgetItem *currentItem = m_ui.qtdirList->currentItem();
dt's avatar
dt committed
761
    Q_ASSERT(currentItem);
con's avatar
con committed
762
    int currentItemIndex = m_ui.qtdirList->indexOfTopLevelItem(currentItem);
763
    m_versions[currentItemIndex]->setMingwDirectory(m_ui.mingwPath->path());
con's avatar
con committed
764
765
766
767
768
769
}

void QtDirWidget::msvcVersionChanged()
{
    const QString &msvcVersion = m_ui.msvcComboBox->currentText();
    QTreeWidgetItem *currentItem = m_ui.qtdirList->currentItem();
dt's avatar
dt committed
770
    Q_ASSERT(currentItem);
con's avatar
con committed
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
    int currentItemIndex = m_ui.qtdirList->indexOfTopLevelItem(currentItem);
    m_versions[currentItemIndex]->setMsvcVersion(msvcVersion);
}

QList<QtVersion *> QtDirWidget::versions() const
{
    return m_versions;
}

int QtDirWidget::defaultVersion() const
{
    return m_defaultVersion;
}

///
/// QtVersion
///

QtVersion::QtVersion(const QString &name, const QString &path, int id, bool isSystemVersion)
790
791
792
793
794
795
    : m_name(name),
    m_isSystemVersion(isSystemVersion),
    m_notInstalled(false),
    m_defaultConfigIsDebug(true),
    m_defaultConfigIsDebugAndRelease(true),
    m_hasDebuggingHelper(false)
con's avatar
con committed
796
797
{
    setPath(path);
hjk's avatar
hjk committed
798
    if (id == -1)
con's avatar
con committed
799
800
801
802
803
804
805
806
807
        m_id = getUniqueId();
    else
        m_id = id;
}

QtVersion::QtVersion(const QString &name, const QString &path)
    : m_name(name),
    m_versionInfoUpToDate(false),
    m_mkspecUpToDate(false),
808
809
    m_isSystemVersion(false),
    m_hasDebuggingHelper(false)
con's avatar
con committed
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
{
    setPath(path);
    m_id = getUniqueId();
}

QString QtVersion::name() const
{
    return m_name;
}

QString QtVersion::path() const
{
    return m_path;
}

QString QtVersion::sourcePath() const
{
    return m_sourcePath;
}

QString QtVersion::mkspec() const
{
    updateMkSpec();
    return m_mkspec;
}

dt's avatar
dt committed
836
837
838
839
840
841
QString QtVersion::mkspecPath() const
{
    updateMkSpec();
    return m_mkspecFullPath;
}

842
843
844
845
846
847
QString QtVersion::qtVersionString() const
{
    qmakeCommand();
    return m_qtVersionString;
}

con's avatar
con committed
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
QHash<QString,QString> QtVersion::versionInfo() const
{
    updateVersionInfo();
    return m_versionInfo;
}

void QtVersion::setName(const QString &name)
{
    m_name = name;
}

void QtVersion::setPath(const QString &path)
{
    m_path = QDir::cleanPath(path);
    updateSourcePath();
    m_versionInfoUpToDate = false;
    m_mkspecUpToDate = false;
    m_qmakeCommand = QString::null;
866
867
868
869
870
871
872
// TODO do i need to optimize this?
    m_hasDebuggingHelper = !dumperLibrary().isEmpty();
}

QString QtVersion::dumperLibrary() const
{
    uint hash = qHash(path());
873
874
875
    QString qtInstallData = versionInfo().value("QT_INSTALL_DATA");
    if (qtInstallData.isEmpty())
        qtInstallData = path();
876
877
    QStringList directories;
    directories
878
            << (qtInstallData + "/qtc-debugging-helper/")
879
880
            << (QApplication::applicationDirPath() + "/../qtc-debugging-helper/" + QString::number(hash)) + "/"
            << (QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/qtc-debugging-helper/" + QString::number(hash)) + "/";
881
882
    foreach(const QString &directory, directories) {
#if defined(Q_OS_WIN)
883
        QFileInfo fi(directory + "debug/gdbmacros.dll");
884
#elif defined(Q_OS_MAC)
885
        QFileInfo fi(directory + "libgdbmacros.dylib");
886
#else // generic UNIX
887
        QFileInfo fi(directory + "libgdbmacros.so");
888
889
890
891
892
#endif
        if (fi.exists())
            return fi.filePath();
    }
    return QString();
con's avatar
con committed
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
}

void QtVersion::updateSourcePath()
{
    m_sourcePath = m_path;
    QFile qmakeCache(m_path + QLatin1String("/.qmake.cache"));
    if (qmakeCache.exists()) {
        qmakeCache.open(QIODevice::ReadOnly | QIODevice::Text);
        QTextStream stream(&qmakeCache);
        while (!stream.atEnd()) {
            QString line = stream.readLine().trimmed();
            if (line.startsWith(QLatin1String("QT_SOURCE_TREE"))) {
                m_sourcePath = line.split(QLatin1Char('=')).at(1).trimmed();
                if (m_sourcePath.startsWith(QLatin1String("$$quote("))) {
                    m_sourcePath.remove(0, 8);
                    m_sourcePath.chop(1);
                }
                break;
            }
        }
    }
}

// Returns the version that was used to build the project in that directory
// That is returns the directory
// To find out wheter we already have a qtversion for that directory call
// QtVersion *QtVersionManager::qtVersionForDirectory(const QString directory);
QString QtVersionManager::findQtVersionFromMakefile(const QString &directory)
{
    QString result = QString::null;
    bool debugAdding = false;
    QFile makefile(directory + "/Makefile" );
    if (makefile.exists() && makefile.open(QFile::ReadOnly)) {
        QTextStream ts(&makefile);
        while (!ts.atEnd()) {
            QString line = ts.readLine();
            QRegExp r1("QMAKE\\s*=(.*)");
            if (r1.exactMatch(line)) {
                if (debugAdding)
                    qDebug()<<"#~~ QMAKE is:"<<r1.cap(1).trimmed();
                QFileInfo qmake(r1.cap(1).trimmed());
                QFileInfo binDir(qmake.absolutePath());
                QString qtDir = binDir.absolutePath();
                if (debugAdding)
                    qDebug() << "#~~ QtDir:"<<qtDir;
                // Now we have the qtDir
                // look through the qtversions wheter we already have that qt version setup
                return qtDir;
            }
        }
        makefile.close();
    }
    return result;
}

QtVersion *QtVersionManager::qtVersionForDirectory(const QString &directory)
{
   foreach(QtVersion *v, versions()) {
        if (v->path() == directory) {
            return v;
            break;
        }
    }
   return 0;
}

QtVersion::QmakeBuildConfig QtVersionManager::scanMakefileForQmakeConfig(const QString &directory, QtVersion::QmakeBuildConfig defaultBuildConfig)
{
    bool debugScan = false;
    QtVersion::QmakeBuildConfig result = QtVersion::NoBuild;
    QFile makefile(directory + "/Makefile" );
    if (makefile.exists() && makefile.open(QFile::ReadOnly)) {
        QTextStream ts(&makefile);
        while (!ts.atEnd()) {
            QString line = ts.readLine();
            if (line.startsWith("# Command:")) {
                // if nothing is specified
                result = defaultBuildConfig;

                // Actually parsing that line is not trivial in the general case
                // There might things like this
                // # Command: /home/dteske/git/bqt-45/bin/qmake -unix CONFIG+=debug\ release CONFIG\ +=\ debug_and_release\ debug -o Makefile test.pro
                // which sets debug_and_release and debug
                // or something like this:
                //[...] CONFIG+=debug\ release CONFIG\ +=\ debug_and_release\ debug CONFIG\ -=\ debug_and_release CONFIG\ -=\ debug -o Makefile test.pro
                // which sets -build_all and release

                // To parse that, we search for the first CONFIG, then look for " " which is not after a "\" or the end
                // And then look at each config individually
                // we then remove all "\ " with just " "
                // += sets adding flags
                // -= sets removing flags
                // and then split the string after the =
                // and go over each item separetly
                // debug sets/removes the flag DebugBuild
                // release removes/sets the flag DebugBuild
                // debug_and_release sets/removes the flag BuildAll
                int pos = line.indexOf("CONFIG");
                if (pos != -1) {
                    // Chopped of anything that is not interesting
                    line = line.mid(pos);
                    line = line.trimmed();
                    if (debugScan)
                        qDebug()<<"chopping line :"<<line;

                    //Now chop into parts that are intresting
                    QStringList parts;
                    int lastpos = 0;
hjk's avatar
hjk committed
1001
                    for (int i = 1; i < line.size(); ++i) {
con's avatar
con committed
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
                        if (line.at(i) == QLatin1Char(' ') && line.at(i-1) != QLatin1Char('\\')) {
                            // found a part
                            parts.append(line.mid(lastpos, i-lastpos));
                            if (debugScan)
                                qDebug()<<"part appended:"<<line.mid(lastpos, i-lastpos);
                            lastpos = i + 1; // Nex one starts after the space
                        }
                    }
                    parts.append(line.mid(lastpos));
                    if (debugScan)
                        qDebug()<<"part appended:"<<line.mid(lastpos);

                    foreach(const QString &part, parts) {
hjk's avatar
hjk committed
1015
                        if (debugScan)
con's avatar
con committed
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
                            qDebug()<<"now interpreting part"<<part;
                        bool setFlags;
                        // Now try to understand each part for that we do a rather stupid approach, optimize it if you care
                        if (part.startsWith("CONFIG")) {
                            // Yep something interesting
                            if (part.indexOf("+=") != -1) {
                                setFlags = true;
                            } else if (part.indexOf("-=") != -1) {
                                setFlags = false;
                            } else {
                                setFlags = true;
                                if (debugScan)
                                    qDebug()<<"This can never happen, except if we can't parse Makefiles...";
                            }
                            if (debugScan)
                                qDebug()<<"part has setFlags:"<<setFlags;
                            // now loop forward, looking for something that looks like debug, release or debug_and_release

hjk's avatar
hjk committed
1034
                            for (int i = 0; i < part.size(); ++i) {
con's avatar
con committed
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
                                int left = part.size() - i;
                                if (left >= 17  && QStringRef(&part, i, 17) == "debug_and_release") {
                                        if (setFlags)
                                            result = QtVersion::QmakeBuildConfig(result | QtVersion::BuildAll);
                                        else
                                            result = QtVersion::QmakeBuildConfig(result & ~QtVersion::BuildAll);
                                        if (debugScan)
                                            qDebug()<<"found debug_and_release new value"<<result;
                                        i += 17;
                                } else if (left >=7 && QStringRef(&part, i, 7) ==  "release") {
                                        if (setFlags)
                                            result = QtVersion::QmakeBuildConfig(result & ~QtVersion::DebugBuild);
                                        else
                                            result = QtVersion::QmakeBuildConfig(result | QtVersion::DebugBuild);
                                        if (debugScan)
                                            qDebug()<<"found release new value"<<result;
hjk's avatar
hjk committed
1051
                                        i += 7;
con's avatar
con committed
1052
1053
1054
1055
1056
1057
1058
                                } else if (left >= 5 && QStringRef(&part, i, 5) == "debug") {
                                        if (setFlags)
                                            result = QtVersion::QmakeBuildConfig(result  | QtVersion::DebugBuild);
                                        else
                                            result = QtVersion::QmakeBuildConfig(result  & ~QtVersion::DebugBuild);
                                        if (debugScan)
                                            qDebug()<<"found debug new value"<<result;
hjk's avatar
hjk committed
1059
                                        i += 5;
con's avatar
con committed
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
                                }
                            }
                        }
                    }
                }
                if (debugScan)
                    qDebug()<<"returning: "<<result;
                if (debugScan)
                    qDebug()<<"buildall = "<<bool(result & QtVersion::BuildAll);
                if (debugScan)
                    qDebug()<<"debug ="<<bool(result & QtVersion::DebugBuild);
            }
        }
        makefile.close();
    }
    return result;
}

void QtVersion::updateVersionInfo() const
{
    if (m_versionInfoUpToDate)
        return;
    // extract data from qmake executable
    m_versionInfo.clear();
    m_notInstalled = false;
    QFileInfo qmake(qmakeCommand());
    if (qmake.exists()) {
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
        static const char * const variables[] = {
             "QT_INSTALL_DATA",
             "QT_INSTALL_LIBS",
             "QT_INSTALL_HEADERS",
             "QT_INSTALL_DEMOS",
             "QT_INSTALL_EXAMPLES",
             "QT_INSTALL_CONFIGURATION",
             "QT_INSTALL_TRANSLATIONS",
             "QT_INSTALL_PLUGINS",
             "QT_INSTALL_BINS",
             "QT_INSTALL_DOCS",
             "QT_INSTALL_PREFIX"
        };
        QStringList args;
        for (uint i = 0; i < sizeof variables / sizeof variables[0]; ++i)
            args << "-query" << variables[i];
con's avatar
con committed
1103
1104
1105
1106
1107
1108
1109
1110
1111
        QProcess process;
        process.start(qmake.absoluteFilePath(), args, QIODevice::ReadOnly);
        if (process.waitForFinished(2000)) {
            QByteArray output = process.readAllStandardOutput();
            QTextStream stream(&output);
            while (!stream.atEnd()) {
                QString line = stream.readLine();
                int index = line.indexOf(":");
                if (index != -1)
Joerg Bornemann's avatar
Joerg Bornemann committed
1112
                    m_versionInfo.insert(line.left(index), QDir::fromNativeSeparators(line.mid(index+1)));
con's avatar
con committed
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
            }
        }

        if (m_versionInfo.contains("QT_INSTALL_DATA"))
            m_versionInfo.insert("QMAKE_MKSPECS", QDir::cleanPath(m_versionInfo.value("QT_INSTALL_DATA")+"/mkspecs"));

        // Now check for a qt that is configured with a prefix but not installed
        if (m_versionInfo.contains("QT_INSTALL_BINS")) {
            QFileInfo fi(m_versionInfo.value("QT_INSTALL_BINS"));
            if (!fi.exists())
                m_notInstalled = true;
        }
        if (m_versionInfo.contains("QT_INSTALL_HEADERS")){
            QFileInfo fi(m_versionInfo.value("QT_INSTALL_HEADERS"));
            if (!fi.exists())
                m_notInstalled = true;
        }

        // Parse qconfigpri
        QString baseDir = m_versionInfo.contains("QT_INSTALL_DATA") ?
                           m_versionInfo.value("QT_INSTALL_DATA") :
                           m_path;
        QFile qconfigpri(baseDir + QLatin1String("/mkspecs/qconfig.pri"));
        if (qconfigpri.exists()) {
            qconfigpri.open(QIODevice::ReadOnly | QIODevice::Text);
            QTextStream stream(&qconfigpri);
            while (!stream.atEnd()) {
                QString line = stream.readLine().trimmed();
                if (line.startsWith(QLatin1String("CONFIG"))) {
                    m_defaultConfigIsDebugAndRelease = false;
                    QStringList values = line.split(QLatin1Char('=')).at(1).trimmed().split(" ");
                    foreach(const QString &value, values) {
                        if (value == "debug")
                            m_defaultConfigIsDebug = true;
hjk's avatar
hjk committed
1147
                        else if (value == "release")
con's avatar
con committed
1148
                            m_defaultConfigIsDebug = false;
hjk's avatar
hjk committed
1149
                        else if (value == "build_all")
con's avatar
con committed
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
                            m_defaultConfigIsDebugAndRelease = true;
                    }
                }
            }
        }
    }
    m_versionInfoUpToDate = true;
}

bool QtVersion::isInstalled() const
{
    updateVersionInfo();
    return !m_notInstalled;
}

void QtVersion::updateMkSpec() const
{
    if (m_mkspecUpToDate)
        return;
    //qDebug()<<"Finding mkspec for"<<path();

    QString mkspec;
dt's avatar
dt committed
1172
1173
//    QFile f(path() + "/.qmake.cache");
//    if (f.exists() && f.open(QIODevice::ReadOnly)) {
hjk's avatar
hjk committed
1174
//        while (!f.atEnd()) {
dt's avatar
dt committed
1175
//            QByteArray line = f.readLine();
hjk's avatar
hjk committed
1176
//            if (line.startsWith("QMAKESPEC")) {
dt's avatar
dt committed
1177
//                const QList<QByteArray> &temp = line.split('=');
hjk's avatar
hjk committed
1178
//                if (temp.size() == 2) {
dt's avatar
dt committed
1179
1180
1181
1182
1183
//                    mkspec = temp.at(1).trimmed();
//                    if (mkspec.startsWith("$$QT_BUILD_TREE/mkspecs/"))
//                        mkspec = mkspec.mid(QString("$$QT_BUILD_TREE/mkspecs/").length());
//                    else if (mkspec.startsWith("$$QT_BUILD_TREE\\mkspecs\\"))
//                        mkspec = mkspec.mid(QString("$$QT_BUILD_TREE\\mkspecs\\").length());
1184
//                    mkspec = QDir::fromNativeSeparators(mkspec);
dt's avatar
dt committed
1185
1186
1187
1188
1189
1190
//                }
//                break;
//            }
//        }
//        f.close();
//    } else {
con's avatar
con committed
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
        // no .qmake.cache so look at the default mkspec
        QString mkspecPath = versionInfo().value("QMAKE_MKSPECS");
        if (mkspecPath.isEmpty())
            mkspecPath = path() + "/mkspecs/default";
        else
            mkspecPath = mkspecPath + "/default";
//        qDebug() << "default mkspec is located at" << mkspecPath;
#ifdef Q_OS_WIN
        QFile f2(mkspecPath + "/qmake.conf");
        if (f2.exists() && f2.open(QIODevice::ReadOnly)) {
hjk's avatar
hjk committed
1201
            while (!f2.atEnd()) {
con's avatar
con committed
1202
                QByteArray line = f2.readLine();
hjk's avatar
hjk committed
1203
                if (line.startsWith("QMAKESPEC_ORIGINAL")) {
con's avatar
con committed
1204
1205
                    const QList<QByteArray> &temp = line.split('=');
                    if (temp.size() == 2) {
lowinu's avatar
lowinu committed
1206
                        mkspec = temp.at(1).trimmed();
con's avatar
con committed
1207
1208
1209
1210
1211
1212
1213
1214
1215
                    }
                    break;
                }
            }
            f2.close();
        }
#elif defined(Q_OS_MAC)
        QFile f2(mkspecPath + "/qmake.conf");
        if (f2.exists() && f2.open(QIODevice::ReadOnly)) {
hjk's avatar
hjk committed
1216
            while (!f2.atEnd()) {
con's avatar
con committed
1217
                QByteArray line = f2.readLine();
hjk's avatar
hjk committed
1218
                if (line.startsWith("MAKEFILE_GENERATOR")) {
con's avatar
con committed
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
                    const QList<QByteArray> &temp = line.split('=');
                    if (temp.size() == 2) {
                        const QByteArray &value = temp.at(1);
                        if (value.contains("XCODE")) {
                            // we don't want to generate xcode projects...
//                            qDebug() << "default mkspec is xcode, falling back to g++";
                            mkspec = "macx-g++";
                        } else {
                            //resolve mkspec link
                            QFileInfo f3(mkspecPath);
                            if (f3.isSymLink()) {
                                mkspec = f3.symLinkTarget();
                            }
                        }
                    }
                    break;
                }
            }
            f2.close();
        }
#else
        QFileInfo f2(mkspecPath);
        if (f2.isSymLink()) {
            mkspec = f2.symLinkTarget();
        }
#endif
dt's avatar
dt committed
1245
//    }
con's avatar
con committed
1246

dt's avatar
dt committed
1247
1248
    m_mkspecFullPath = mkspec;
    int index = mkspec.lastIndexOf('/');
hjk's avatar
hjk committed
1249
    if (index == -1)
con's avatar
con committed
1250
        index = mkspec.lastIndexOf('\\');
Joerg Bornemann's avatar
Joerg Bornemann committed
1251
1252
    QString mkspecDir = QDir(m_path + "/mkspecs/").canonicalPath();
    if (index >= 0 && QDir(mkspec.left(index)).canonicalPath() == mkspecDir)
con's avatar
con committed
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
        mkspec = mkspec.mid(index+1).trimmed();

    m_mkspec = mkspec;
    m_mkspecUpToDate = true;
//    qDebug()<<"mkspec for "<<m_path<<" is "<<mkspec;
}

QString QtVersion::qmakeCommand() const
{
    // We can't use versionInfo QT_INSTALL_BINS here
    // because that functions calls us to find out the values for versionInfo
    if (!m_qmakeCommand.isNull())
        return m_qmakeCommand;

    QDir qtDir = path() + "/bin/";
hjk's avatar
hjk committed
1268
    foreach (const QString &possibleCommand, QtVersionManager::possibleQMakeCommands()) {
con's avatar
con committed
1269
1270
1271
        QString s = qtDir.absoluteFilePath(possibleCommand);
        QFileInfo qmake(s);
        if (qmake.exists() && qmake.isExecutable()) {
1272
1273
1274
            QString qtVersion = QtVersionManager::qtVersionForQMake(qmake.absoluteFilePath());
            if (!qtVersion.isNull()) {
                m_qtVersionString = qtVersion;
con's avatar
con committed
1275
1276
1277
1278
1279
1280
1281
1282
                m_qmakeCommand = qmake.absoluteFilePath();
                return qmake.absoluteFilePath();
            }
        }
    }
    return QString::null;
}

dt's avatar
dt committed
1283
ProjectExplorer::ToolChain::ToolChainType QtVersion::toolchainType() const
con's avatar
con committed
1284
1285
{
    if (!isValid())
dt's avatar
dt committed
1286
        return ProjectExplorer::ToolChain::INVALID;
con's avatar
con committed
1287
    const QString &spec = mkspec();
1288
//    qDebug()<<"spec="<<spec;
hjk's avatar
hjk committed
1289
    if (spec.contains("win32-msvc") || spec.contains(QLatin1String("win32-icc")))
dt's avatar
dt committed
1290
        return ProjectExplorer::ToolChain::MSVC;
1291
    else if (spec.contains("win32-g++"))
dt's avatar
dt committed
1292
        return ProjectExplorer::ToolChain::MinGW;
hjk's avatar
hjk committed
1293
    else if (spec == QString::null)
dt's avatar
dt committed
1294
        return ProjectExplorer::ToolChain::INVALID;
1295
    else if (spec.contains("wince"))
dt's avatar
dt committed
1296
        return ProjectExplorer::ToolChain::WINCE;
1297
    else if (spec.contains("linux-icc"))
1298
        return ProjectExplorer::ToolChain::LinuxICC;
con's avatar
con committed
1299
    else
dt's avatar
dt committed
1300
        return ProjectExplorer::ToolChain::GCC;
con's avatar
con committed
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
}

QString QtVersion::mingwDirectory() const
{
    return m_mingwDirectory;
}

void QtVersion::setMingwDirectory(const QString &directory)
{
    m_mingwDirectory = directory;
}

QString QtVersion::prependPath() const
{
    return m_prependPath;
}

void QtVersion::setPrependPath(const QString &directory)
{
    m_prependPath = directory;
}

QString QtVersion::msvcVersion() const
{
    return m_msvcVersion;
}

dt's avatar
dt committed
1328
1329
QString QtVersion::wincePlatform() const
{
1330
//    qDebug()<<"QtVersion::wincePlatform returning"<<ProjectExplorer::CeSdkHandler::platformName(mkspecPath() + "/qmake.conf");
dt's avatar
dt committed
1331
1332
1333
    return ProjectExplorer::CeSdkHandler::platformName(mkspecPath() + "/qmake.conf");
}

con's avatar
con committed
1334
1335
1336
1337
1338
void QtVersion::setMsvcVersion(const QString &version)
{
    m_msvcVersion = version;
}

dt's avatar
dt committed
1339
void QtVersion::addToEnvironment(Environment &env)
con's avatar
con committed
1340
{
dt's avatar
dt committed
1341
    env.set("QTDIR", m_path);
con's avatar
con committed
1342
    QString qtdirbin = versionInfo().value("QT_INSTALL_BINS");
dt's avatar
dt committed
1343
    env.prependOrSetPath(qtdirbin);
con's avatar
con committed
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
    // add libdir, includedir and bindir
    // or add Mingw dirs
    // or do nothing on other
}

int QtVersion::uniqueId() const
{
    return m_id;
}

int QtVersion::getUniqueId()
{
    QtVersionManager *vm = ExtensionSystem::PluginManager::instance()->getObject<QtVersionManager>();
    return vm->getUniqueId();
}

bool QtVersion::isValid() const
{
    return (!(m_id == -1 || m_path == QString::null || m_name == QString::null || mkspec() == QString::null) && !m_notInstalled);
}

QtVersion::QmakeBuildConfig QtVersion::defaultBuildConfig() const
{
    updateVersionInfo();
    QtVersion::QmakeBuildConfig result = QtVersion::QmakeBuildConfig(0);
    if (m_defaultConfigIsDebugAndRelease)
        result = QtVersion::BuildAll;
    if (m_defaultConfigIsDebug)
        result = QtVersion::QmakeBuildConfig(result | QtVersion::DebugBuild);
    return result;
}
1375
1376
1377
1378
1379
1380

bool QtVersion::hasDebuggingHelper() const
{
    return m_hasDebuggingHelper;
}

1381
1382
1383
1384
1385
1386

// TODO buildDebuggingHelperLibrary needs to be accessible outside of the
// qt4versionmanager
// That probably means moving qt4version management into either the projectexplorer
// (The Projectexplorer plugin probably needs some splitting up, most of the stuff
// could be in a plugin shared by qt4projectmanager, cmakemanager and debugger.)
1387
1388
1389
1390
1391
1392
1393
1394
1395
QString QtVersion::buildDebuggingHelperLibrary()
{
// Locations to try:
//    $QTDIR/qtc-debugging-helper
//    $APPLICATION-DIR/qtc-debugging-helper/$hash
//    $USERDIR/qtc-debugging-helper/$hash

    QString output;
    uint hash = qHash(path());
1396
1397
1398
    QString qtInstallData = versionInfo().value("QT_INSTALL_DATA");
    if (qtInstallData.isEmpty())
        qtInstallData = path();
1399
1400
    QStringList directories;
    directories
1401
            << qtInstallData + "/qtc-debugging-helper/"
1402
1403
            << QApplication::applicationDirPath() + "/../qtc-debugging-helper/" + QString::number(hash) +"/"
            << QDesktopServices::storageLocation (QDesktopServices::DataLocation) + "/qtc-debugging-helper/" + QString::number(hash) +"/";
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426

    QStringList files;
    files << "gdbmacros.cpp" << "gdbmacros.pro"
          << "LICENSE.LGPL" << "LGPL_EXCEPTION.TXT";

    foreach(const QString &directory, directories) {
        QString dumperPath = Core::ICore::instance()->resourcePath() + "/gdbmacros/";
        bool success = true;
        QDir().mkpath(directory);
        foreach (const QString &file, files) {
            QString source = dumperPath + file;
            QString dest = directory + file;
            QFileInfo destInfo(dest);
            if (destInfo.exists()) {
                if (destInfo.lastModified() >= QFileInfo(source).lastModified())
                    continue;
                success &= QFile::remove(dest);
            }
            success &= QFile::copy(source, dest);
        }
        if (!success)
            continue;

1427
1428
        // Setup process
        QProcess proc;
1429
1430
1431

        ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment();
        addToEnvironment(env);
1432
        // TODO this is a hack to get, to be removed and rewritten for 1.2
1433
        // For MSVC and MINGW, we need a toolchain to get the right environment
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
        ProjectExplorer::ToolChain *toolChain = 0;
        ProjectExplorer::ToolChain::ToolChainType t = toolchainType();
        if (t == ProjectExplorer::ToolChain::MinGW)
            toolChain = ProjectExplorer::ToolChain::createMinGWToolChain("g++", mingwDirectory());
        else if(t == ProjectExplorer::ToolChain::MSVC)
            toolChain = ProjectExplorer::ToolChain::createMSVCToolChain(msvcVersion());
        if (toolChain) {
            toolChain->addToEnvironment(env);
            delete toolChain;
            toolChain = 0;
        }

1446
1447
1448
        proc.setEnvironment(env.toStringList());
        proc.setWorkingDirectory(directory);
        proc.setProcessChannelMode(QProcess::MergedChannels);
1449

1450
1451
        output += QString("Building debugging helper library in %1\n").arg(directory);
        output += "\n";
1452

1453
        QString make;
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
        // TODO this is butt ugly
        // only qt4projects have a toolchain() method. (Reason mostly, that in order to create
        // the toolchain, we need to have the path to gcc
        // which might depend on environment settings of the project
        // so we hardcode the toolchainType to make conversation here
        // and think about how to fix that later
        if (t == ProjectExplorer::ToolChain::MinGW)
            make = "mingw32-make.exe";
        else if(t == ProjectExplorer::ToolChain::MSVC || t == ProjectExplorer::ToolChain::WINCE)
            make = "nmake.exe";
        else if (t == ProjectExplorer::ToolChain::GCC || t == ProjectExplorer::ToolChain::LinuxICC)
            make = "make";

        QString makeFullPath = env.searchInPath(make);
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
        if (!makeFullPath.isEmpty()) {
            output += QString("Running %1 clean...\n").arg(makeFullPath);
            proc.start(makeFullPath, QStringList() << "clean");
            proc.waitForFinished();
            output += proc.readAll();
        } else {
            output += QString("%1 not found in PATH\n").arg(make);
            break;
        }

        output += QString("\nRuninng %1 ...\n").arg(qmakeCommand());

        proc.start(qmakeCommand(), QStringList()<<"-spec"<< mkspec() <<"gdbmacros.pro");
        proc.waitForFinished();

        output += proc.readAll();

1485
1486
        output += "\n";
        if (!makeFullPath.isEmpty()) {
1487
            output += QString("Running %1 ...\n").arg(makeFullPath);
1488
1489
1490
            proc.start(makeFullPath, QStringList());
            proc.waitForFinished();
            output += proc.readAll();
1491
1492
1493
1494
1495
1496
1497
1498
        } else {
            output += QString("%1 not found in PATH\n").arg(make);
        }
        break;
    }
    m_hasDebuggingHelper = !dumperLibrary().isEmpty();
    return output;
}