androidconfigurations.cpp 41.7 KB
Newer Older
BogDan Vatra's avatar
BogDan Vatra committed
1 2
/**************************************************************************
**
3
** Copyright (c) 2013 BogDan Vatra <bog_dan_ro@yahoo.com>
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
BogDan Vatra's avatar
BogDan Vatra committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
BogDan Vatra's avatar
BogDan Vatra 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.
BogDan Vatra's avatar
BogDan Vatra committed
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
BogDan Vatra's avatar
BogDan Vatra committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
BogDan Vatra's avatar
BogDan Vatra committed
29 30 31

#include "androidconfigurations.h"
#include "androidconstants.h"
Daniel Teske's avatar
Daniel Teske committed
32 33 34
#include "androidtoolchain.h"
#include "androiddevice.h"
#include "androidgdbserverkitinformation.h"
BogDan Vatra's avatar
BogDan Vatra committed
35
#include "ui_addnewavddialog.h"
36
#include "androidqtversion.h"
37
#include "androiddevicedialog.h"
BogDan Vatra's avatar
BogDan Vatra committed
38 39

#include <coreplugin/icore.h>
40
#include <utils/hostosinfo.h>
BogDan Vatra's avatar
BogDan Vatra committed
41
#include <utils/persistentsettings.h>
Daniel Teske's avatar
Daniel Teske committed
42 43 44 45
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/devicesupport/devicemanager.h>
#include <projectexplorer/toolchainmanager.h>
46
#include <projectexplorer/session.h>
47
#include <debugger/debuggeritemmanager.h>
Daniel Teske's avatar
Daniel Teske committed
48 49 50 51
#include <debugger/debuggerkitinformation.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtversionmanager.h>
Daniel Teske's avatar
Daniel Teske committed
52
#include <utils/environment.h>
Orgad Shaneh's avatar
Orgad Shaneh committed
53
#include <utils/sleep.h>
BogDan Vatra's avatar
BogDan Vatra committed
54 55 56 57 58 59 60 61 62 63 64 65

#include <QDateTime>
#include <QSettings>
#include <QStringList>
#include <QProcess>
#include <QFileInfo>
#include <QDirIterator>
#include <QMetaObject>

#include <QStringListModel>
#include <QMessageBox>

hjk's avatar
hjk committed
66
using namespace ProjectExplorer;
BogDan Vatra's avatar
BogDan Vatra committed
67 68 69 70 71 72 73 74 75 76 77 78 79
using namespace Utils;

namespace Android {
namespace Internal {

namespace {
    const QLatin1String SettingsGroup("AndroidConfigurations");
    const QLatin1String SDKLocationKey("SDKLocation");
    const QLatin1String NDKLocationKey("NDKLocation");
    const QLatin1String NDKToolchainVersionKey("NDKToolchainVersion");
    const QLatin1String AntLocationKey("AntLocation");
    const QLatin1String OpenJDKLocationKey("OpenJDKLocation");
    const QLatin1String KeystoreLocationKey("KeystoreLocation");
Daniel Teske's avatar
Daniel Teske committed
80
    const QLatin1String AutomaticKitCreationKey("AutomatiKitCreation");
81
    const QLatin1String MakeExtraSearchDirectory("MakeExtraSearchDirectory");
82
    const QLatin1String DefaultDevice("DefaultDevice");
BogDan Vatra's avatar
BogDan Vatra committed
83
    const QLatin1String PartitionSizeKey("PartitionSize");
84
    const QLatin1String ToolchainHostKey("ToolchainHost");
BogDan Vatra's avatar
BogDan Vatra committed
85 86
    const QLatin1String ArmToolchainPrefix("arm-linux-androideabi");
    const QLatin1String X86ToolchainPrefix("x86");
BogDan Vatra's avatar
BogDan Vatra committed
87
    const QLatin1String MipsToolchainPrefix("mipsel-linux-android");
BogDan Vatra's avatar
BogDan Vatra committed
88
    const QLatin1String ArmToolsPrefix("arm-linux-androideabi");
BogDan Vatra's avatar
BogDan Vatra committed
89
    const QLatin1String X86ToolsPrefix("i686-linux-android");
BogDan Vatra's avatar
BogDan Vatra committed
90
    const QLatin1String MipsToolsPrefix("mipsel-linux-android");
BogDan Vatra's avatar
BogDan Vatra committed
91 92 93 94 95
    const QLatin1String Unknown("unknown");
    const QLatin1String keytoolName("keytool");
    const QLatin1String jarsignerName("jarsigner");
    const QLatin1String changeTimeStamp("ChangeTimeStamp");

96
    static QString sdkSettingsFileName()
BogDan Vatra's avatar
BogDan Vatra committed
97
    {
98 99
        return QFileInfo(Core::ICore::settings(QSettings::SystemScope)->fileName()).absolutePath()
                + QLatin1String("/qtcreator/android.xml");
BogDan Vatra's avatar
BogDan Vatra committed
100 101
    }

102
    bool androidDevicesLessThan(const AndroidDeviceInfo &dev1, const AndroidDeviceInfo &dev2)
BogDan Vatra's avatar
BogDan Vatra committed
103
    {
Daniel Teske's avatar
Compile  
Daniel Teske committed
104 105
        if (dev1.serialNumber.contains(QLatin1String("????")) == dev2.serialNumber.contains(QLatin1String("????")))
            return !dev1.serialNumber.contains(QLatin1String("????"));
106 107
        if (dev1.type != dev2.type)
            return dev1.type == AndroidDeviceInfo::Hardware;
108 109
        if (dev1.sdk != dev2.sdk)
            return dev1.sdk < dev2.sdk;
110

111
        return dev1.serialNumber < dev2.serialNumber;
BogDan Vatra's avatar
BogDan Vatra committed
112 113 114
    }
}

115 116 117 118 119 120
Abi::Architecture AndroidConfigurations::architectureForToolChainPrefix(const QString& toolchainprefix)
{
    if (toolchainprefix == ArmToolchainPrefix)
        return Abi::ArmArchitecture;
    if (toolchainprefix == X86ToolchainPrefix)
        return Abi::X86Architecture;
BogDan Vatra's avatar
BogDan Vatra committed
121 122
    if (toolchainprefix == MipsToolchainPrefix)
        return Abi::MipsArchitecture;
123 124 125
    return Abi::UnknownArchitecture;
}

hjk's avatar
hjk committed
126
QLatin1String AndroidConfigurations::toolchainPrefix(Abi::Architecture architecture)
BogDan Vatra's avatar
BogDan Vatra committed
127 128
{
    switch (architecture) {
hjk's avatar
hjk committed
129
    case Abi::ArmArchitecture:
BogDan Vatra's avatar
BogDan Vatra committed
130
        return ArmToolchainPrefix;
hjk's avatar
hjk committed
131
    case Abi::X86Architecture:
BogDan Vatra's avatar
BogDan Vatra committed
132
        return X86ToolchainPrefix;
BogDan Vatra's avatar
BogDan Vatra committed
133 134
    case Abi::MipsArchitecture:
        return MipsToolchainPrefix;
BogDan Vatra's avatar
BogDan Vatra committed
135 136 137 138 139
    default:
        return Unknown;
    }
}

hjk's avatar
hjk committed
140
QLatin1String AndroidConfigurations::toolsPrefix(Abi::Architecture architecture)
BogDan Vatra's avatar
BogDan Vatra committed
141 142
{
    switch (architecture) {
hjk's avatar
hjk committed
143
    case Abi::ArmArchitecture:
BogDan Vatra's avatar
BogDan Vatra committed
144
        return ArmToolsPrefix;
hjk's avatar
hjk committed
145
    case Abi::X86Architecture:
BogDan Vatra's avatar
BogDan Vatra committed
146
        return X86ToolsPrefix;
BogDan Vatra's avatar
BogDan Vatra committed
147 148
    case Abi::MipsArchitecture:
        return MipsToolsPrefix;
BogDan Vatra's avatar
BogDan Vatra committed
149 150 151 152 153 154 155 156 157
    default:
        return Unknown;
    }
}

AndroidConfig::AndroidConfig(const QSettings &settings)
{
    // user settings
    partitionSize = settings.value(PartitionSizeKey, 1024).toInt();
hjk's avatar
hjk committed
158 159 160 161 162
    sdkLocation = FileName::fromString(settings.value(SDKLocationKey).toString());
    ndkLocation = FileName::fromString(settings.value(NDKLocationKey).toString());
    antLocation = FileName::fromString(settings.value(AntLocationKey).toString());
    openJDKLocation = FileName::fromString(settings.value(OpenJDKLocationKey).toString());
    keystoreLocation = FileName::fromString(settings.value(KeystoreLocationKey).toString());
163
    toolchainHost = settings.value(ToolchainHostKey).toString();
Daniel Teske's avatar
Daniel Teske committed
164
    automaticKitCreation = settings.value(AutomaticKitCreationKey, true).toBool();
165 166 167 168 169
    QString extraDirectory = settings.value(MakeExtraSearchDirectory).toString();
    if (extraDirectory.isEmpty())
        makeExtraSearchDirectories = QStringList();
    else
        makeExtraSearchDirectories << extraDirectory;
BogDan Vatra's avatar
BogDan Vatra committed
170 171

    PersistentSettingsReader reader;
172 173
    if (reader.load(FileName::fromString(sdkSettingsFileName()))
            && settings.value(changeTimeStamp).toInt() != QFileInfo(sdkSettingsFileName()).lastModified().toMSecsSinceEpoch() / 1000) {
BogDan Vatra's avatar
BogDan Vatra committed
174
        // persisten settings
hjk's avatar
hjk committed
175 176 177 178 179
        sdkLocation = FileName::fromString(reader.restoreValue(SDKLocationKey).toString());
        ndkLocation = FileName::fromString(reader.restoreValue(NDKLocationKey).toString());
        antLocation = FileName::fromString(reader.restoreValue(AntLocationKey).toString());
        openJDKLocation = FileName::fromString(reader.restoreValue(OpenJDKLocationKey).toString());
        keystoreLocation = FileName::fromString(reader.restoreValue(KeystoreLocationKey).toString());
180
        toolchainHost = reader.restoreValue(ToolchainHostKey).toString();
Daniel Teske's avatar
Daniel Teske committed
181 182 183
        QVariant v = reader.restoreValue(AutomaticKitCreationKey);
        if (v.isValid())
            automaticKitCreation = v.toBool();
184 185 186 187 188
        QString extraDirectory = reader.restoreValue(MakeExtraSearchDirectory).toString();
        if (extraDirectory.isEmpty())
            makeExtraSearchDirectories = QStringList();
        else
            makeExtraSearchDirectories << extraDirectory;
BogDan Vatra's avatar
BogDan Vatra committed
189 190 191 192 193 194 195 196 197 198 199 200
        // persistent settings
    }

}

AndroidConfig::AndroidConfig()
{
    partitionSize = 1024;
}

void AndroidConfig::save(QSettings &settings) const
{
201
    QFileInfo fileInfo(sdkSettingsFileName());
BogDan Vatra's avatar
BogDan Vatra committed
202 203 204 205
    if (fileInfo.exists())
        settings.setValue(changeTimeStamp, fileInfo.lastModified().toMSecsSinceEpoch() / 1000);

    // user settings
Tobias Hunger's avatar
Tobias Hunger committed
206 207 208 209 210
    settings.setValue(SDKLocationKey, sdkLocation.toString());
    settings.setValue(NDKLocationKey, ndkLocation.toString());
    settings.setValue(AntLocationKey, antLocation.toString());
    settings.setValue(OpenJDKLocationKey, openJDKLocation.toString());
    settings.setValue(KeystoreLocationKey, keystoreLocation.toString());
BogDan Vatra's avatar
BogDan Vatra committed
211
    settings.setValue(PartitionSizeKey, partitionSize);
Daniel Teske's avatar
Daniel Teske committed
212
    settings.setValue(AutomaticKitCreationKey, automaticKitCreation);
213
    settings.setValue(ToolchainHostKey, toolchainHost);
214 215 216
    settings.setValue(MakeExtraSearchDirectory,
                      makeExtraSearchDirectories.isEmpty() ? QString()
                                                           : makeExtraSearchDirectories.at(0));
BogDan Vatra's avatar
BogDan Vatra committed
217 218 219 220 221
}

void AndroidConfigurations::setConfig(const AndroidConfig &devConfigs)
{
    m_config = devConfigs;
222 223 224 225

    if (m_config.toolchainHost.isEmpty())
        detectToolchainHost();

BogDan Vatra's avatar
BogDan Vatra committed
226
    save();
227
    updateAvailableNdkPlatforms();
228
    updateAvailableSdkPlatforms();
Daniel Teske's avatar
Daniel Teske committed
229
    updateAutomaticKitList();
230
    updateAndroidDevice();
BogDan Vatra's avatar
BogDan Vatra committed
231 232 233
    emit updated();
}

234
void AndroidConfigurations::updateAvailableNdkPlatforms()
BogDan Vatra's avatar
BogDan Vatra committed
235
{
236
    m_availableNdkPlatforms.clear();
hjk's avatar
hjk committed
237
    FileName path = m_config.ndkLocation;
BogDan Vatra's avatar
BogDan Vatra committed
238
    QDirIterator it(path.appendPath(QLatin1String("platforms")).toString(), QStringList() << QLatin1String("android-*"), QDir::Dirs);
BogDan Vatra's avatar
BogDan Vatra committed
239 240
    while (it.hasNext()) {
        const QString &fileName = it.next();
241
        m_availableNdkPlatforms.push_back(fileName.mid(fileName.lastIndexOf(QLatin1Char('-')) + 1).toInt());
BogDan Vatra's avatar
BogDan Vatra committed
242
    }
243
    qSort(m_availableNdkPlatforms.begin(), m_availableNdkPlatforms.end(), qGreater<int>());
BogDan Vatra's avatar
BogDan Vatra committed
244 245
}

246
void AndroidConfigurations::updateAvailableSdkPlatforms()
BogDan Vatra's avatar
BogDan Vatra committed
247
{
248 249
    m_availableSdkPlatforms.clear();

BogDan Vatra's avatar
BogDan Vatra committed
250
    QProcess proc;
251
    proc.setProcessEnvironment(androidToolEnvironment().toProcessEnvironment());
Tobias Hunger's avatar
Tobias Hunger committed
252
    proc.start(androidToolPath().toString(), QStringList() << QLatin1String("list") << QLatin1String("target")); // list avaialbe AVDs
BogDan Vatra's avatar
BogDan Vatra committed
253 254
    if (!proc.waitForFinished(-1)) {
        proc.terminate();
255
        return;
BogDan Vatra's avatar
BogDan Vatra committed
256
    }
257
    while (proc.canReadLine()) {
258
        const QString line = QString::fromLocal8Bit(proc.readLine().trimmed());
BogDan Vatra's avatar
BogDan Vatra committed
259 260 261
        int index = line.indexOf(QLatin1String("\"android-"));
        if (index == -1)
            continue;
262 263 264 265
        QString androidTarget = line.mid(index + 1, line.length() - index - 2);
        int apiLevel = androidTarget.mid(androidTarget.lastIndexOf(QLatin1Char('-')) + 1).toInt();
        QVector<int>::iterator it = qLowerBound(m_availableSdkPlatforms.begin(), m_availableSdkPlatforms.end(), apiLevel, qGreater<int>());
        m_availableSdkPlatforms.insert(it, apiLevel);
BogDan Vatra's avatar
BogDan Vatra committed
266
    }
267 268 269 270 271 272 273 274 275 276 277 278
}

QStringList AndroidConfigurations::sdkTargets(int minApiLevel) const
{
    QStringList result;
    for (int i = 0; i < m_availableSdkPlatforms.size(); ++i) {
        if (m_availableSdkPlatforms.at(i) >= minApiLevel)
            result << QLatin1String("android-") + QString::number(m_availableSdkPlatforms.at(i));
        else
            break;
    }
    return result;
BogDan Vatra's avatar
BogDan Vatra committed
279 280
}

hjk's avatar
hjk committed
281
FileName AndroidConfigurations::adbToolPath() const
BogDan Vatra's avatar
BogDan Vatra committed
282
{
hjk's avatar
hjk committed
283
    FileName path = m_config.sdkLocation;
284
    return path.appendPath(QLatin1String("platform-tools/adb" QTC_HOST_EXE_SUFFIX));
BogDan Vatra's avatar
BogDan Vatra committed
285 286
}

287 288 289 290 291 292 293 294
Utils::Environment AndroidConfigurations::androidToolEnvironment() const
{
    Utils::Environment env = Utils::Environment::systemEnvironment();
    if (!m_config.openJDKLocation.isEmpty())
        env.set(QLatin1String("JAVA_HOME"), m_config.openJDKLocation.toUserOutput());
    return env;
}

hjk's avatar
hjk committed
295
FileName AndroidConfigurations::androidToolPath() const
BogDan Vatra's avatar
BogDan Vatra committed
296
{
297 298 299 300
    if (HostOsInfo::isWindowsHost()) {
        // I want to switch from using android.bat to using an executable. All it really does is call
        // Java and I've made some progress on it. So if android.exe exists, return that instead.
        FileName path = m_config.sdkLocation;
301
        path.appendPath(QLatin1String("tools/android" QTC_HOST_EXE_SUFFIX));
302 303 304
        if (path.toFileInfo().exists())
            return path;
        path = m_config.sdkLocation;
305
        return path.appendPath(QLatin1String("tools/android" ANDROID_BAT_SUFFIX));
306 307 308 309
    } else {
        FileName path = m_config.sdkLocation;
        return path.appendPath(QLatin1String("tools/android"));
    }
BogDan Vatra's avatar
BogDan Vatra committed
310 311
}

hjk's avatar
hjk committed
312
FileName AndroidConfigurations::antToolPath() const
BogDan Vatra's avatar
BogDan Vatra committed
313
{
Tobias Hunger's avatar
Tobias Hunger committed
314
    if (!m_config.antLocation.isEmpty())
BogDan Vatra's avatar
BogDan Vatra committed
315 316
        return m_config.antLocation;
    else
hjk's avatar
hjk committed
317
        return FileName::fromString(QLatin1String("ant"));
BogDan Vatra's avatar
BogDan Vatra committed
318 319
}

hjk's avatar
hjk committed
320
FileName AndroidConfigurations::emulatorToolPath() const
BogDan Vatra's avatar
BogDan Vatra committed
321
{
hjk's avatar
hjk committed
322
    FileName path = m_config.sdkLocation;
323
    return path.appendPath(QLatin1String("tools/emulator" QTC_HOST_EXE_SUFFIX));
BogDan Vatra's avatar
BogDan Vatra committed
324 325
}

326
FileName AndroidConfigurations::toolPath(Abi::Architecture architecture, const QString &ndkToolChainVersion) const
BogDan Vatra's avatar
BogDan Vatra committed
327
{
hjk's avatar
hjk committed
328
    FileName path = m_config.ndkLocation;
Tobias Hunger's avatar
Tobias Hunger committed
329
    return path.appendPath(QString::fromLatin1("toolchains/%1-%2/prebuilt/%3/bin/%4")
BogDan Vatra's avatar
BogDan Vatra committed
330
            .arg(toolchainPrefix(architecture))
331
            .arg(ndkToolChainVersion)
332
            .arg(m_config.toolchainHost)
Tobias Hunger's avatar
Tobias Hunger committed
333
            .arg(toolsPrefix(architecture)));
BogDan Vatra's avatar
BogDan Vatra committed
334 335
}

336
FileName AndroidConfigurations::stripPath(Abi::Architecture architecture, const QString &ndkToolChainVersion) const
BogDan Vatra's avatar
BogDan Vatra committed
337
{
338
    return toolPath(architecture, ndkToolChainVersion).append(QLatin1String("-strip" QTC_HOST_EXE_SUFFIX));
BogDan Vatra's avatar
BogDan Vatra committed
339 340
}

341
FileName AndroidConfigurations::readelfPath(Abi::Architecture architecture, const QString &ndkToolChainVersion) const
BogDan Vatra's avatar
BogDan Vatra committed
342
{
343
    return toolPath(architecture, ndkToolChainVersion).append(QLatin1String("-readelf" QTC_HOST_EXE_SUFFIX));
BogDan Vatra's avatar
BogDan Vatra committed
344 345
}

346 347 348 349 350
FileName AndroidConfigurations::gccPath(Abi::Architecture architecture, const QString &ndkToolChainVersion) const
{
    return toolPath(architecture, ndkToolChainVersion).append(QLatin1String("-gcc" QTC_HOST_EXE_SUFFIX));
}

351
FileName AndroidConfigurations::gdbPath(Abi::Architecture architecture, const QString &ndkToolChainVersion) const
BogDan Vatra's avatar
BogDan Vatra committed
352
{
353
    return toolPath(architecture, ndkToolChainVersion).append(QLatin1String("-gdb" QTC_HOST_EXE_SUFFIX));
BogDan Vatra's avatar
BogDan Vatra committed
354 355
}

hjk's avatar
hjk committed
356
FileName AndroidConfigurations::openJDKPath() const
BogDan Vatra's avatar
BogDan Vatra committed
357 358 359 360
{
    return m_config.openJDKLocation;
}

361 362 363 364
void AndroidConfigurations::detectToolchainHost()
{
    QStringList hostPatterns;
    switch (HostOsInfo::hostOs()) {
365
    case OsTypeLinux:
366 367
        hostPatterns << QLatin1String("linux*");
        break;
368
    case OsTypeWindows:
369 370
        hostPatterns << QLatin1String("windows*");
        break;
371
    case OsTypeMac:
372 373 374 375 376 377 378 379 380 381 382 383 384
        hostPatterns << QLatin1String("darwin*");
        break;
    default: /* unknown host */ return;
    }

    FileName path = m_config.ndkLocation;
    QDirIterator it(path.appendPath(QLatin1String("prebuilt")).toString(), hostPatterns, QDir::Dirs);
    if (it.hasNext()) {
        it.next();
        m_config.toolchainHost = it.fileName();
    }
}

hjk's avatar
hjk committed
385
FileName AndroidConfigurations::openJDKBinPath() const
BogDan Vatra's avatar
BogDan Vatra committed
386
{
hjk's avatar
hjk committed
387
    FileName path = m_config.openJDKLocation;
Tobias Hunger's avatar
Tobias Hunger committed
388 389 390
    if (!path.isEmpty())
        return path.appendPath(QLatin1String("bin"));
    return path;
BogDan Vatra's avatar
BogDan Vatra committed
391 392
}

hjk's avatar
hjk committed
393
FileName AndroidConfigurations::keytoolPath() const
BogDan Vatra's avatar
BogDan Vatra committed
394
{
Tobias Hunger's avatar
Tobias Hunger committed
395
    return openJDKBinPath().appendPath(keytoolName);
BogDan Vatra's avatar
BogDan Vatra committed
396 397
}

hjk's avatar
hjk committed
398
FileName AndroidConfigurations::jarsignerPath() const
BogDan Vatra's avatar
BogDan Vatra committed
399
{
Tobias Hunger's avatar
Tobias Hunger committed
400
    return openJDKBinPath().appendPath(jarsignerName);
BogDan Vatra's avatar
BogDan Vatra committed
401 402
}

hjk's avatar
hjk committed
403
FileName AndroidConfigurations::zipalignPath() const
404
{
405
    FileName path = m_config.sdkLocation;
406
    return path.appendPath(QLatin1String("tools/zipalign" QTC_HOST_EXE_SUFFIX));
407 408
}

409
AndroidDeviceInfo AndroidConfigurations::showDeviceDialog(ProjectExplorer::Project *project, int apiLevel, const QString &abi)
BogDan Vatra's avatar
BogDan Vatra committed
410
{
411 412 413 414 415 416 417
    QString serialNumber = defaultDevice(project, abi);
    if (!serialNumber.isEmpty()) {
        // search for that device
        foreach (const AndroidDeviceInfo &info, AndroidConfigurations::instance().connectedDevices())
            if (info.serialNumber == serialNumber
                    && info.sdk >= apiLevel)
                return info;
BogDan Vatra's avatar
BogDan Vatra committed
418

419 420 421 422 423 424
        foreach (const AndroidDeviceInfo &info, AndroidConfigurations::instance().androidVirtualDevices())
            if (info.serialNumber == serialNumber
                    && info.sdk >= apiLevel)
                return info;
    }

425
    AndroidDeviceDialog dialog(apiLevel, abi, Core::ICore::mainWindow());
426 427 428 429 430
    if (dialog.exec() == QDialog::Accepted) {
        AndroidDeviceInfo info = dialog.device();
        if (dialog.saveDeviceSelection()) {
            if (!info.serialNumber.isEmpty())
                AndroidConfigurations::instance().setDefaultDevice(project, abi, info.serialNumber);
BogDan Vatra's avatar
BogDan Vatra committed
431
        }
432
        return info;
Tobias Hunger's avatar
Tobias Hunger committed
433
    }
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    return AndroidDeviceInfo();
}

void AndroidConfigurations::clearDefaultDevices(ProjectExplorer::Project *project)
{
    if (m_defaultDeviceForAbi.contains(project))
        m_defaultDeviceForAbi.remove(project);
}

void AndroidConfigurations::setDefaultDevice(ProjectExplorer::Project *project, const QString &abi, const QString &serialNumber)
{
    m_defaultDeviceForAbi[project][abi] = serialNumber;
}

QString AndroidConfigurations::defaultDevice(Project *project, const QString &abi) const
{
    if (!m_defaultDeviceForAbi.contains(project))
        return QString();
    const QMap<QString, QString> &map = m_defaultDeviceForAbi.value(project);
    if (!map.contains(abi))
        return QString();
    return map.value(abi);
BogDan Vatra's avatar
BogDan Vatra committed
456 457
}

458
QVector<AndroidDeviceInfo> AndroidConfigurations::connectedDevices(QString *error) const
BogDan Vatra's avatar
BogDan Vatra committed
459
{
460
    QVector<AndroidDeviceInfo> devices;
BogDan Vatra's avatar
BogDan Vatra committed
461
    QProcess adbProc;
Tobias Hunger's avatar
Tobias Hunger committed
462
    adbProc.start(adbToolPath().toString(), QStringList() << QLatin1String("devices"));
BogDan Vatra's avatar
BogDan Vatra committed
463
    if (!adbProc.waitForFinished(-1)) {
464
        adbProc.kill();
465 466
        if (error)
            *error = tr("Could not run: %1").arg(adbToolPath().toString() + QLatin1String(" devices"));
BogDan Vatra's avatar
BogDan Vatra committed
467 468 469
        return devices;
    }
    QList<QByteArray> adbDevs = adbProc.readAll().trimmed().split('\n');
BogDan Vatra's avatar
BogDan Vatra committed
470 471 472 473 474 475
    if (adbDevs.empty())
        return devices;

    while (adbDevs.first().startsWith("* daemon"))
        adbDevs.removeFirst(); // remove the daemon logs
    adbDevs.removeFirst(); // remove "List of devices attached" header line
476 477 478

    // workaround for '????????????' serial numbers:
    // can use "adb -d" when only one usb device attached
BogDan Vatra's avatar
BogDan Vatra committed
479
    foreach (const QByteArray &device, adbDevs) {
480 481
        const QString serialNo = QString::fromLatin1(device.left(device.indexOf('\t')).trimmed());
        const QString deviceType = QString::fromLatin1(device.mid(device.indexOf('\t'))).trimmed();
482 483
        if (isBootToQt(serialNo))
            continue;
484
        AndroidDeviceInfo dev;
485
        dev.serialNumber = serialNo;
486
        dev.type = serialNo.startsWith(QLatin1String("emulator")) ? AndroidDeviceInfo::Emulator : AndroidDeviceInfo::Hardware;
BogDan Vatra's avatar
BogDan Vatra committed
487
        dev.sdk = getSDKVersion(dev.serialNumber);
488
        dev.cpuAbi = getAbis(dev.serialNumber);
489
        dev.unauthorized = (deviceType == QLatin1String("unauthorized"));
BogDan Vatra's avatar
BogDan Vatra committed
490 491
        devices.push_back(dev);
    }
492

BogDan Vatra's avatar
BogDan Vatra committed
493
    qSort(devices.begin(), devices.end(), androidDevicesLessThan);
494 495
    if (devices.isEmpty() && error)
        *error = tr("No devices found in output of: %1").arg(adbToolPath().toString() + QLatin1String(" devices"));
BogDan Vatra's avatar
BogDan Vatra committed
496 497 498
    return devices;
}

499
QString AndroidConfigurations::createAVD(QWidget *parent, int minApiLevel, QString targetArch) const
BogDan Vatra's avatar
BogDan Vatra committed
500
{
501
    QDialog d(parent);
BogDan Vatra's avatar
BogDan Vatra committed
502 503
    Ui::AddNewAVDDialog avdDialog;
    avdDialog.setupUi(&d);
504 505
    // NOTE: adb list targets does actually include information on which abis are supported per apilevel
    // we aren't using that information here
506
    avdDialog.targetComboBox->addItems(sdkTargets(minApiLevel));
507 508 509 510 511 512 513 514 515 516

    if (targetArch.isEmpty())
        avdDialog.abiComboBox->addItems(QStringList()
                                        << QLatin1String("armeabi-v7a")
                                        << QLatin1String("armeabi")
                                        << QLatin1String("x86")
                                        << QLatin1String("mips"));
    else
        avdDialog.abiComboBox->addItems(QStringList(targetArch));

517
    if (!avdDialog.targetComboBox->count()) {
Friedemann Kleint's avatar
Friedemann Kleint committed
518
        QMessageBox::critical(0, tr("Error Creating AVD"),
519
                              tr("Cannot create a new AVD. No sufficiently recent Android SDK available.\n"
Friedemann Kleint's avatar
Friedemann Kleint committed
520
                                 "Please install an SDK of at least API version %1.").
Friedemann Kleint's avatar
Friedemann Kleint committed
521
                              arg(minApiLevel));
522
        return QString();
BogDan Vatra's avatar
BogDan Vatra committed
523 524 525 526 527 528
    }

    QRegExp rx(QLatin1String("\\S+"));
    QRegExpValidator v(rx, 0);
    avdDialog.nameLineEdit->setValidator(&v);
    if (d.exec() != QDialog::Accepted)
529 530
        return QString();
    return createAVD(avdDialog.targetComboBox->currentText(), avdDialog.nameLineEdit->text(), avdDialog.abiComboBox->currentText(), avdDialog.sizeSpinBox->value());
BogDan Vatra's avatar
BogDan Vatra committed
531 532
}

533
QString AndroidConfigurations::createAVD(const QString &target, const QString &name, const QString &abi, int sdcardSize ) const
BogDan Vatra's avatar
BogDan Vatra committed
534 535
{
    QProcess proc;
536
    proc.setProcessEnvironment(androidToolEnvironment().toProcessEnvironment());
Tobias Hunger's avatar
Tobias Hunger committed
537
    proc.start(androidToolPath().toString(),
BogDan Vatra's avatar
BogDan Vatra committed
538
               QStringList() << QLatin1String("create") << QLatin1String("avd")
539
               << QLatin1String("-t") << target
BogDan Vatra's avatar
BogDan Vatra committed
540
               << QLatin1String("-n") << name
541
               << QLatin1String("-b") << abi
BogDan Vatra's avatar
BogDan Vatra committed
542 543
               << QLatin1String("-c") << QString::fromLatin1("%1M").arg(sdcardSize));
    if (!proc.waitForStarted())
544
        return QString();
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565

    proc.write(QByteArray("yes\n")); // yes to "Do you wish to create a custom hardware profile"

    QByteArray question;
    while (true) {
        proc.waitForReadyRead(500);
        question += proc.readAllStandardOutput();
        if (question.endsWith(QByteArray("]:"))) {
            // truncate to last line
            int index = question.lastIndexOf(QByteArray("\n"));
            if (index != -1)
                question = question.mid(index);
            if (question.contains("hw.gpu.enabled"))
                proc.write(QByteArray("yes\n"));
            else
                proc.write(QByteArray("\n"));
            question.clear();
        }

        if (proc.state() != QProcess::Running)
            break;
BogDan Vatra's avatar
BogDan Vatra committed
566
    }
567 568 569

    proc.waitForFinished();

570 571 572
    if (proc.exitCode()) // error!
        return QString();
    return name;
BogDan Vatra's avatar
BogDan Vatra committed
573 574 575 576 577
}

bool AndroidConfigurations::removeAVD(const QString &name) const
{
    QProcess proc;
578
    proc.setProcessEnvironment(androidToolEnvironment().toProcessEnvironment());
Tobias Hunger's avatar
Tobias Hunger committed
579
    proc.start(androidToolPath().toString(),
BogDan Vatra's avatar
BogDan Vatra committed
580 581 582 583 584 585 586 587 588
               QStringList() << QLatin1String("delete") << QLatin1String("avd")
               << QLatin1String("-n") << name);
    if (!proc.waitForFinished(-1)) {
        proc.terminate();
        return false;
    }
    return !proc.exitCode();
}

589
QVector<AndroidDeviceInfo> AndroidConfigurations::androidVirtualDevices() const
BogDan Vatra's avatar
BogDan Vatra committed
590
{
591
    QVector<AndroidDeviceInfo> devices;
BogDan Vatra's avatar
BogDan Vatra committed
592
    QProcess proc;
593
    proc.setProcessEnvironment(androidToolEnvironment().toProcessEnvironment());
Tobias Hunger's avatar
Tobias Hunger committed
594
    proc.start(androidToolPath().toString(),
BogDan Vatra's avatar
BogDan Vatra committed
595 596 597 598 599 600
               QStringList() << QLatin1String("list") << QLatin1String("avd")); // list available AVDs
    if (!proc.waitForFinished(-1)) {
        proc.terminate();
        return devices;
    }
    QList<QByteArray> avds = proc.readAll().trimmed().split('\n');
BogDan Vatra's avatar
BogDan Vatra committed
601 602 603 604 605 606 607
    if (avds.empty())
        return devices;

    while (avds.first().startsWith("* daemon"))
        avds.removeFirst(); // remove the daemon logs
    avds.removeFirst(); // remove "List of devices attached" header line

608
    AndroidDeviceInfo dev;
BogDan Vatra's avatar
BogDan Vatra committed
609 610 611 612 613 614 615 616 617 618 619 620 621 622
    for (int i = 0; i < avds.size(); i++) {
        QString line = QLatin1String(avds[i]);
        if (!line.contains(QLatin1String("Name:")))
            continue;

        dev.serialNumber = line.mid(line.indexOf(QLatin1Char(':')) + 2).trimmed();
        ++i;
        for (; i < avds.size(); ++i) {
            line = QLatin1String(avds[i]);
            if (line.contains(QLatin1String("---------")))
                break;
            if (line.contains(QLatin1String("Target:")))
                dev.sdk = line.mid(line.lastIndexOf(QLatin1Char(' '))).remove(QLatin1Char(')')).toInt();
            if (line.contains(QLatin1String("ABI:")))
623
                dev.cpuAbi = QStringList() << line.mid(line.lastIndexOf(QLatin1Char(' '))).trimmed();
BogDan Vatra's avatar
BogDan Vatra committed
624
        }
625 626 627
        // armeabi-v7a devices can also run armeabi code
        if (dev.cpuAbi == QStringList(QLatin1String("armeabi-v7a")))
            dev.cpuAbi << QLatin1String("armeabi");
628
        dev.unauthorized = false;
629
        dev.type = AndroidDeviceInfo::Emulator;
BogDan Vatra's avatar
BogDan Vatra committed
630 631 632 633 634 635 636
        devices.push_back(dev);
    }
    qSort(devices.begin(), devices.end(), androidDevicesLessThan);

    return devices;
}

637 638
QString AndroidConfigurations::startAVD(const QString &name, int apiLevel, QString cpuAbi) const
{
639
    if (!findAvd(apiLevel, cpuAbi).isEmpty() || startAVDAsync(name))
640 641 642
        return waitForAvd(apiLevel, cpuAbi);
    return QString();
}
BogDan Vatra's avatar
BogDan Vatra committed
643

644 645 646 647 648
bool AndroidConfigurations::startAVDAsync(const QString &avdName) const
{
    QProcess *avdProcess = new QProcess();
    connect(this, SIGNAL(destroyed()), avdProcess, SLOT(deleteLater()));
    connect(avdProcess, SIGNAL(finished(int)), avdProcess, SLOT(deleteLater()));
BogDan Vatra's avatar
BogDan Vatra committed
649 650

    // start the emulator
Orgad Shaneh's avatar
Orgad Shaneh committed
651
    avdProcess->start(emulatorToolPath().toString(),
BogDan Vatra's avatar
BogDan Vatra committed
652 653
                        QStringList() << QLatin1String("-partition-size") << QString::number(config().partitionSize)
                        << QLatin1String("-avd") << avdName);
Orgad Shaneh's avatar
Orgad Shaneh committed
654 655
    if (!avdProcess->waitForStarted(-1)) {
        delete avdProcess;
656
        return false;
BogDan Vatra's avatar
BogDan Vatra committed
657
    }
658 659 660
    return true;
}

661
QString AndroidConfigurations::findAvd(int apiLevel, const QString &cpuAbi) const
662 663 664 665 666 667 668 669 670
{
    QVector<AndroidDeviceInfo> devices = connectedDevices();
    foreach (AndroidDeviceInfo device, devices) {
        if (!device.serialNumber.startsWith(QLatin1String("emulator")))
            continue;
        if (!device.cpuAbi.contains(cpuAbi))
            continue;
        if (device.sdk != apiLevel)
            continue;
671
        return device.serialNumber;
672
    }
673
    return QString();
674 675
}

Daniel Teske's avatar
Daniel Teske committed
676
bool AndroidConfigurations::isConnected(const QString &serialNumber) const
677
{
Daniel Teske's avatar
Daniel Teske committed
678 679 680 681 682 683 684
    QVector<AndroidDeviceInfo> devices = connectedDevices();
    foreach (AndroidDeviceInfo device, devices) {
        if (device.serialNumber == serialNumber)
            return true;
    }
    return false;
}
685

Daniel Teske's avatar
Daniel Teske committed
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
bool AndroidConfigurations::waitForBooted(const QString &serialNumber, const QFutureInterface<bool> &fi) const
{
    // found a serial number, now wait until it's done booting...
    for (int i = 0; i < 60; ++i) {
        if (fi.isCanceled())
            return false;
        if (hasFinishedBooting(serialNumber)) {
            return true;
        } else {
            Utils::sleep(2000);
            if (!isConnected(serialNumber)) // device was disconnected
                return false;
        }
    }
    return false;
}

QString AndroidConfigurations::waitForAvd(int apiLevel, const QString &cpuAbi, const QFutureInterface<bool> &fi) const
{
    // we cannot use adb -e wait-for-device, since that doesn't work if a emulator is already running
    // 60 rounds of 2s sleeping, two minutes for the avd to start
707
    QString serialNumber;
Daniel Teske's avatar
Daniel Teske committed
708 709
    for (int i = 0; i < 60; ++i) {
        if (fi.isCanceled())
Orgad Shaneh's avatar
Orgad Shaneh committed
710
            return QString();
Daniel Teske's avatar
Daniel Teske committed
711 712 713 714
        serialNumber = findAvd(apiLevel, cpuAbi);
        if (!serialNumber.isEmpty())
            return waitForBooted(serialNumber, fi) ?  serialNumber : QString();
        Utils::sleep(2000);
BogDan Vatra's avatar
BogDan Vatra committed
715 716 717 718
    }
    return QString();
}

719 720 721 722 723 724 725 726 727 728 729
bool AndroidConfigurations::isBootToQt(const QString &device) const
{
    // workaround for '????????????' serial numbers
    QStringList arguments = AndroidDeviceInfo::adbSelector(device);
    arguments << QLatin1String("shell")
              << QLatin1String("ls -l /system/bin/appcontroller || ls -l /usr/bin/appcontroller && echo Boot2Qt");

    QProcess adbProc;
    adbProc.start(adbToolPath().toString(), arguments);
    if (!adbProc.waitForFinished(-1)) {
        adbProc.kill();
730
        return false;
731 732 733 734
    }
    return adbProc.readAll().contains("Boot2Qt");
}

BogDan Vatra's avatar
BogDan Vatra committed
735 736
int AndroidConfigurations::getSDKVersion(const QString &device) const
{
737 738 739 740
    // workaround for '????????????' serial numbers
    QStringList arguments = AndroidDeviceInfo::adbSelector(device);
    arguments << QLatin1String("shell") << QLatin1String("getprop")
              << QLatin1String("ro.build.version.sdk");
BogDan Vatra's avatar
BogDan Vatra committed
741 742

    QProcess adbProc;
743
    adbProc.start(adbToolPath().toString(), arguments);
BogDan Vatra's avatar
BogDan Vatra committed
744
    if (!adbProc.waitForFinished(-1)) {
745
        adbProc.kill();
BogDan Vatra's avatar
BogDan Vatra committed
746 747 748 749 750
        return -1;
    }
    return adbProc.readAll().trimmed().toInt();
}

751 752 753 754 755 756 757
//!
//! \brief AndroidConfigurations::getProductModel
//! \param device serial number
//! \return the produce model of the device or if that cannot be read the serial number
//!
QString AndroidConfigurations::getProductModel(const QString &device) const
{
758 759
    if (m_serialNumberToDeviceName.contains(device))
        return m_serialNumberToDeviceName.value(device);
760 761 762 763 764 765 766 767 768 769 770 771 772 773
    // workaround for '????????????' serial numbers
    QStringList arguments = AndroidDeviceInfo::adbSelector(device);
    arguments << QLatin1String("shell") << QLatin1String("getprop")
              << QLatin1String("ro.product.model");

    QProcess adbProc;
    adbProc.start(adbToolPath().toString(), arguments);
    if (!adbProc.waitForFinished(-1)) {
        adbProc.kill();
        return device;
    }
    QString model = QString::fromLocal8Bit(adbProc.readAll().trimmed());
    if (model.isEmpty())
        return device;
774 775
    if (!device.startsWith(QLatin1String("????")))
        m_serialNumberToDeviceName.insert(device, model);
776 777 778
    return model;
}

779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
bool AndroidConfigurations::hasFinishedBooting(const QString &device) const
{
    QStringList arguments = AndroidDeviceInfo::adbSelector(device);
    arguments << QLatin1String("shell") << QLatin1String("getprop")
              << QLatin1String("init.svc.bootanim");

    QProcess adbProc;
    adbProc.start(adbToolPath().toString(), arguments);
    if (!adbProc.waitForFinished(-1)) {
        adbProc.kill();
        return false;
    }
    QString value = QString::fromLocal8Bit(adbProc.readAll().trimmed());
    if (value == QLatin1String("stopped"))
        return true;
    return false;
}

797 798 799
QStringList AndroidConfigurations::getAbis(const QString &device) const
{
    QStringList result;
800
    for (int i = 1; i < 6; ++i) {
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
        QStringList arguments = AndroidDeviceInfo::adbSelector(device);
        arguments << QLatin1String("shell") << QLatin1String("getprop");
        if (i == 1)
            arguments << QLatin1String("ro.product.cpu.abi");
        else
            arguments << QString::fromLatin1("ro.product.cpu.abi%1").arg(i);

        QProcess adbProc;
        adbProc.start(adbToolPath().toString(), arguments);
        if (!adbProc.waitForFinished(-1)) {
            adbProc.kill();
            return result;
        }
        QString abi = QString::fromLocal8Bit(adbProc.readAll().trimmed());
        if (abi.isEmpty())
            break;
        result << abi;
    }
    return result;
}

822
QString AndroidConfigurations::highestAndroidSdk() const
823
{
824
    if (m_availableSdkPlatforms.isEmpty())
825
        return QString();
826
    return QLatin1String("android-") + QString::number(m_availableSdkPlatforms.first());
827 828
}

829
QString AndroidConfigurations::bestNdkPlatformMatch(const QString &targetAPI) const
BogDan Vatra's avatar
BogDan Vatra committed
830 831
{
    int target = targetAPI.mid(targetAPI.lastIndexOf(QLatin1Char('-')) + 1).toInt();
832
    foreach (int apiLevel, m_availableNdkPlatforms) {
BogDan Vatra's avatar
BogDan Vatra committed
833 834 835 836 837 838
        if (apiLevel <= target)
            return QString::fromLatin1("android-%1").arg(apiLevel);
    }
    return QLatin1String("android-8");
}

839 840 841 842 843
QStringList AndroidConfigurations::makeExtraSearchDirectories() const
{
    return m_config.makeExtraSearchDirectories;
}

844
static bool equalKits(Kit *a, Kit *b)
Daniel Teske's avatar
Daniel Teske committed
845 846 847 848 849 850 851 852 853 854 855
{
    return ToolChainKitInformation::toolChain(a) == ToolChainKitInformation::toolChain(b)
            && QtSupport::QtKitInformation::qtVersion(a) == QtSupport::QtKitInformation::qtVersion(b);
}

void AndroidConfigurations::updateAutomaticKitList()
{
    QList<AndroidToolChain *> toolchains;
    if (AndroidConfigurations::instance().config().automaticKitCreation) {
        // having a empty toolchains list will remove all autodetected kits for android
        // exactly what we want in that case
hjk's avatar
hjk committed
856
        foreach (ToolChain *tc, ToolChainManager::toolChains()) {
Daniel Teske's avatar
Daniel Teske committed
857 858 859 860 861 862 863 864 865 866
            if (!tc->isAutoDetected())
                continue;
            if (tc->type() != QLatin1String(Constants::ANDROID_TOOLCHAIN_TYPE))
                continue;
            toolchains << static_cast<AndroidToolChain *>(tc);
        }
    }

    QList<Kit *> existingKits;

867 868
    foreach (Kit *k, KitManager::kits()) {
        if (DeviceKitInformation::deviceId(k) != Core::Id(Constants::ANDROID_DEVICE_ID))
Daniel Teske's avatar
Daniel Teske committed
869 870 871
            continue;
        if (!k->isAutoDetected())
            continue;
Daniel Teske's avatar
Daniel Teske committed
872 873
        if (k->isSdkProvided())
            continue;
Daniel Teske's avatar
Daniel Teske committed
874

875 876 877 878 879 880 881 882 883 884 885 886
        // Update code for 3.0 beta, which shipped with a bug for the debugger settings
        ProjectExplorer::ToolChain *tc =ToolChainKitInformation::toolChain(k);
        if (tc && Debugger::DebuggerKitInformation::debuggerCommand(k) != tc->suggestedDebugger()) {
            Debugger::DebuggerItem debugger;
            debugger.setCommand(tc->suggestedDebugger());
            debugger.setEngineType(Debugger::GdbEngineType);
            debugger.setDisplayName(tr("Android Debugger for %1").arg(tc->displayName()));
            debugger.setAutoDetected(true);
            debugger.setAbi(tc->targetAbi());
            QVariant id = Debugger::DebuggerItemManager::registerDebugger(debugger);
            Debugger::DebuggerKitInformation::setDebugger(k, id);
        }
Daniel Teske's avatar
Daniel Teske committed
887 888 889
        existingKits << k;
    }

890
    QMap<Abi::Architecture, QList<QtSupport::BaseQtVersion *> > qtVersionsForArch;
hjk's avatar
hjk committed
891
    foreach (QtSupport::BaseQtVersion *qtVersion, QtSupport::QtVersionManager::versions()) {
Daniel Teske's avatar
Daniel Teske committed
892 893
        if (qtVersion->type() != QLatin1String(Constants::ANDROIDQT))
            continue;
894
        QList<Abi> qtAbis = qtVersion->qtAbis();
895 896 897
        if (qtAbis.empty())
            continue;
        qtVersionsForArch[qtAbis.first().architecture()].append(qtVersion);
Daniel Teske's avatar
Daniel Teske committed
898 899
    }

900
    DeviceManager *dm = DeviceManager::instance();
901 902 903 904 905 906 907
    IDevice::ConstPtr device = dm->find(Core::Id(Constants::ANDROID_DEVICE_ID));
    if (device.isNull()) {
        // no device, means no sdk path
        foreach (Kit *k, existingKits)
            KitManager::deregisterKit(k);
        return;
    }
Daniel Teske's avatar
Daniel Teske committed
908 909 910 911

    // register new kits
    QList<Kit *> newKits;
    foreach (AndroidToolChain *tc, toolchains) {
912
        if (tc->isSecondaryToolChain())
913
            continue;
Daniel Teske's avatar
Daniel Teske committed
914 915 916 917
        QList<QtSupport::BaseQtVersion *> qtVersions = qtVersionsForArch.value(tc->targetAbi().architecture());
        foreach (QtSupport::BaseQtVersion *qt, qtVersions) {
            Kit *newKit = new Kit;
            newKit->setAutoDetected(true);
918
            newKit->setIconPath(Utils::FileName::fromString(QLatin1String(Constants::ANDROID_SETTINGS_CATEGORY_ICON)));
Daniel Teske's avatar
Daniel Teske committed
919 920 921 922
            DeviceTypeKitInformation::setDeviceTypeId(newKit, Core::Id(Constants::ANDROID_DEVICE_TYPE));
            ToolChainKitInformation::setToolChain(newKit, tc);
            QtSupport::QtKitInformation::setQtVersion(newKit, qt);
            DeviceKitInformation::setDevice(newKit, device);
hjk's avatar
hjk committed
923 924 925 926 927 928 929

            Debugger::DebuggerItem debugger;
            debugger.setCommand(tc->suggestedDebugger());
            debugger.setEngineType(Debugger::GdbEngineType);
            debugger.setDisplayName(tr("Android Debugger for %1").arg(tc->displayName()));
            debugger.setAutoDetected(true);
            debugger.setAbi(tc->targetAbi());
930 931
            QVariant id = Debugger::DebuggerItemManager::registerDebugger(debugger);
            Debugger::DebuggerKitInformation::setDebugger(newKit, id);
hjk's avatar
hjk committed
932

Daniel Teske's avatar
Daniel Teske committed
933
            AndroidGdbServerKitInformation::setGdbSever(newKit, tc->suggestedGdbServer());
934
            newKit->makeSticky();
Daniel Teske's avatar
Daniel Teske committed
935 936 937 938 939 940 941 942 943 944 945
            newKits << newKit;
        }
    }

    for (int i = existingKits.count() - 1; i >= 0; --i) {
        Kit *existingKit = existingKits.at(i);
        for (int j = 0; j < newKits.count(); ++j) {
            Kit *newKit = newKits.at(j);
            if (equalKits(existingKit, newKit)) {
                // Kit is already registered, nothing to do
                newKits.removeAt(j);
946
                existingKits.at(i)->makeSticky();
Daniel Teske's avatar
Daniel Teske committed
947 948 949 950 951 952 953
                existingKits.removeAt(i);
                KitManager::deleteKit(newKit);
                j = newKits.count();
            }
        }
    }

954 955
    foreach (Kit *k, existingKits) {
        ProjectExplorer::ToolChain *tc = ToolChainKitInformation::toolChain(k);
956 957 958
        QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(k);
        if (tc && tc->type() == QLatin1String(Constants::ANDROID_TOOLCHAIN_TYPE)
                && qtVersion && qtVersion->type() == QLatin1String(Constants::ANDROIDQT)) {
959 960 961 962 963 964
            k->makeUnSticky();
            k->setAutoDetected(false);
        } else {
            KitManager::deregisterKit(k);
        }
    }
Daniel Teske's avatar
Daniel Teske committed
965