androidconfigurations.cpp 19.5 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
32
33
34

#include "androidconfigurations.h"
#include "androidconstants.h"
#include "ui_addnewavddialog.h"

#include <coreplugin/icore.h>
35
#include <utils/hostosinfo.h>
BogDan Vatra's avatar
BogDan Vatra committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <utils/persistentsettings.h>

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

#include <QStringListModel>
#include <QMessageBox>

#if defined(_WIN32)
#include <iostream>
#include <windows.h>
#define sleep(_n) Sleep(1000 * (_n))
Thiago Macieira's avatar
Thiago Macieira committed
53
54
#else
#include <unistd.h>
BogDan Vatra's avatar
BogDan Vatra committed
55
56
#endif

hjk's avatar
hjk committed
57
using namespace ProjectExplorer;
BogDan Vatra's avatar
BogDan Vatra committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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 ArmGdbLocationKey("GdbLocation");
    const QLatin1String ArmGdbserverLocationKey("GdbserverLocation");
    const QLatin1String X86GdbLocationKey("X86GdbLocation");
    const QLatin1String X86GdbserverLocationKey("X86GdbserverLocation");
    const QLatin1String OpenJDKLocationKey("OpenJDKLocation");
    const QLatin1String KeystoreLocationKey("KeystoreLocation");
    const QLatin1String PartitionSizeKey("PartitionSize");
    const QLatin1String ArmToolchainPrefix("arm-linux-androideabi");
    const QLatin1String X86ToolchainPrefix("x86");
    const QLatin1String ArmToolsPrefix("arm-linux-androideabi");
    const QLatin1String X86ToolsPrefix("i686-android-linux");
    const QLatin1String Unknown("unknown");
    const QLatin1String keytoolName("keytool");
    const QLatin1String jarsignerName("jarsigner");
    const QLatin1String changeTimeStamp("ChangeTimeStamp");

85
    static QString sdkSettingsFileName()
BogDan Vatra's avatar
BogDan Vatra committed
86
    {
87
88
        return QString::fromLatin1("%1/android.xml")
                                           .arg(QFileInfo(Core::ICore::settings(QSettings::SystemScope)->fileName()).absolutePath());
BogDan Vatra's avatar
BogDan Vatra committed
89
90
    }

91
    bool androidDevicesLessThan(const AndroidDeviceInfo &dev1, const AndroidDeviceInfo &dev2)
BogDan Vatra's avatar
BogDan Vatra committed
92
93
94
95
96
    {
        return dev1.sdk < dev2.sdk;
    }
}

97
98
99
100
101
102
103
104
105
Abi::Architecture AndroidConfigurations::architectureForToolChainPrefix(const QString& toolchainprefix)
{
    if (toolchainprefix == ArmToolchainPrefix)
        return Abi::ArmArchitecture;
    if (toolchainprefix == X86ToolchainPrefix)
        return Abi::X86Architecture;
    return Abi::UnknownArchitecture;
}

hjk's avatar
hjk committed
106
QLatin1String AndroidConfigurations::toolchainPrefix(Abi::Architecture architecture)
BogDan Vatra's avatar
BogDan Vatra committed
107
108
{
    switch (architecture) {
hjk's avatar
hjk committed
109
    case Abi::ArmArchitecture:
BogDan Vatra's avatar
BogDan Vatra committed
110
        return ArmToolchainPrefix;
hjk's avatar
hjk committed
111
    case Abi::X86Architecture:
BogDan Vatra's avatar
BogDan Vatra committed
112
113
114
115
116
117
        return X86ToolchainPrefix;
    default:
        return Unknown;
    }
}

hjk's avatar
hjk committed
118
QLatin1String AndroidConfigurations::toolsPrefix(Abi::Architecture architecture)
BogDan Vatra's avatar
BogDan Vatra committed
119
120
{
    switch (architecture) {
hjk's avatar
hjk committed
121
    case Abi::ArmArchitecture:
BogDan Vatra's avatar
BogDan Vatra committed
122
        return ArmToolsPrefix;
hjk's avatar
hjk committed
123
    case Abi::X86Architecture:
BogDan Vatra's avatar
BogDan Vatra committed
124
125
126
127
128
129
130
131
132
133
        return X86ToolsPrefix;
    default:
        return Unknown;
    }
}

AndroidConfig::AndroidConfig(const QSettings &settings)
{
    // user settings
    partitionSize = settings.value(PartitionSizeKey, 1024).toInt();
hjk's avatar
hjk committed
134
135
136
137
138
    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());
BogDan Vatra's avatar
BogDan Vatra committed
139
140

    PersistentSettingsReader reader;
141
142
    if (reader.load(FileName::fromString(sdkSettingsFileName()))
            && settings.value(changeTimeStamp).toInt() != QFileInfo(sdkSettingsFileName()).lastModified().toMSecsSinceEpoch() / 1000) {
BogDan Vatra's avatar
BogDan Vatra committed
143
        // persisten settings
hjk's avatar
hjk committed
144
145
146
147
148
        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());
BogDan Vatra's avatar
BogDan Vatra committed
149
150
151
152
153
154
155
156
157
158
159
160
        // persistent settings
    }

}

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

void AndroidConfig::save(QSettings &settings) const
{
161
    QFileInfo fileInfo(sdkSettingsFileName());
BogDan Vatra's avatar
BogDan Vatra committed
162
163
164
165
    if (fileInfo.exists())
        settings.setValue(changeTimeStamp, fileInfo.lastModified().toMSecsSinceEpoch() / 1000);

    // user settings
Tobias Hunger's avatar
Tobias Hunger committed
166
167
168
169
170
    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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
    settings.setValue(PartitionSizeKey, partitionSize);
}

void AndroidConfigurations::setConfig(const AndroidConfig &devConfigs)
{
    m_config = devConfigs;
    save();
    updateAvailablePlatforms();
    emit updated();
}

void AndroidConfigurations::updateAvailablePlatforms()
{
    m_availablePlatforms.clear();
hjk's avatar
hjk committed
185
    FileName path = m_config.ndkLocation;
BogDan Vatra's avatar
BogDan Vatra committed
186
    QDirIterator it(path.appendPath(QLatin1String("platforms")).toString(), QStringList() << QLatin1String("android-*"), QDir::Dirs);
BogDan Vatra's avatar
BogDan Vatra committed
187
188
189
190
191
192
193
194
195
196
197
    while (it.hasNext()) {
        const QString &fileName = it.next();
        m_availablePlatforms.push_back(fileName.mid(fileName.lastIndexOf(QLatin1Char('-')) + 1).toInt());
    }
    qSort(m_availablePlatforms.begin(), m_availablePlatforms.end(), qGreater<int>());
}

QStringList AndroidConfigurations::sdkTargets(int minApiLevel) const
{
    QStringList targets;
    QProcess proc;
Tobias Hunger's avatar
Tobias Hunger committed
198
    proc.start(androidToolPath().toString(), QStringList() << QLatin1String("list") << QLatin1String("target")); // list avaialbe AVDs
BogDan Vatra's avatar
BogDan Vatra committed
199
200
201
202
    if (!proc.waitForFinished(-1)) {
        proc.terminate();
        return targets;
    }
203
    while (proc.canReadLine()) {
204
        const QString line = QString::fromLocal8Bit(proc.readLine().trimmed());
BogDan Vatra's avatar
BogDan Vatra committed
205
206
207
208
209
210
211
212
213
214
        int index = line.indexOf(QLatin1String("\"android-"));
        if (index == -1)
            continue;
        QString apiLevel = line.mid(index + 1, line.length() - index - 2);
        if (apiLevel.mid(apiLevel.lastIndexOf(QLatin1Char('-')) + 1).toInt() >= minApiLevel)
            targets.push_back(apiLevel);
    }
    return targets;
}

hjk's avatar
hjk committed
215
FileName AndroidConfigurations::adbToolPath() const
BogDan Vatra's avatar
BogDan Vatra committed
216
{
hjk's avatar
hjk committed
217
    FileName path = m_config.sdkLocation;
218
    return path.appendPath(QLatin1String("platform-tools/adb" QTC_HOST_EXE_SUFFIX));
BogDan Vatra's avatar
BogDan Vatra committed
219
220
}

hjk's avatar
hjk committed
221
FileName AndroidConfigurations::androidToolPath() const
BogDan Vatra's avatar
BogDan Vatra committed
222
{
223
224
225
226
    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;
227
        path.appendPath(QLatin1String("tools/android" QTC_HOST_EXE_SUFFIX));
228
229
230
        if (path.toFileInfo().exists())
            return path;
        path = m_config.sdkLocation;
231
        return path.appendPath(QLatin1String("tools/android" ANDROID_BAT_SUFFIX));
232
233
234
235
    } else {
        FileName path = m_config.sdkLocation;
        return path.appendPath(QLatin1String("tools/android"));
    }
BogDan Vatra's avatar
BogDan Vatra committed
236
237
}

hjk's avatar
hjk committed
238
FileName AndroidConfigurations::antToolPath() const
BogDan Vatra's avatar
BogDan Vatra committed
239
{
Tobias Hunger's avatar
Tobias Hunger committed
240
    if (!m_config.antLocation.isEmpty())
BogDan Vatra's avatar
BogDan Vatra committed
241
242
        return m_config.antLocation;
    else
hjk's avatar
hjk committed
243
        return FileName::fromString(QLatin1String("ant"));
BogDan Vatra's avatar
BogDan Vatra committed
244
245
}

hjk's avatar
hjk committed
246
FileName AndroidConfigurations::emulatorToolPath() const
BogDan Vatra's avatar
BogDan Vatra committed
247
{
hjk's avatar
hjk committed
248
    FileName path = m_config.sdkLocation;
249
    return path.appendPath(QLatin1String("tools/emulator" QTC_HOST_EXE_SUFFIX));
BogDan Vatra's avatar
BogDan Vatra committed
250
251
}

252
FileName AndroidConfigurations::toolPath(Abi::Architecture architecture, const QString &ndkToolChainVersion) const
BogDan Vatra's avatar
BogDan Vatra committed
253
{
hjk's avatar
hjk committed
254
    FileName path = m_config.ndkLocation;
Tobias Hunger's avatar
Tobias Hunger committed
255
    return path.appendPath(QString::fromLatin1("toolchains/%1-%2/prebuilt/%3/bin/%4")
BogDan Vatra's avatar
BogDan Vatra committed
256
            .arg(toolchainPrefix(architecture))
257
            .arg(ndkToolChainVersion)
BogDan Vatra's avatar
BogDan Vatra committed
258
            .arg(ToolchainHost)
Tobias Hunger's avatar
Tobias Hunger committed
259
            .arg(toolsPrefix(architecture)));
BogDan Vatra's avatar
BogDan Vatra committed
260
261
}

262
FileName AndroidConfigurations::stripPath(Abi::Architecture architecture, const QString &ndkToolChainVersion) const
BogDan Vatra's avatar
BogDan Vatra committed
263
{
264
    return toolPath(architecture, ndkToolChainVersion).append(QLatin1String("-strip" QTC_HOST_EXE_SUFFIX));
BogDan Vatra's avatar
BogDan Vatra committed
265
266
}

267
FileName AndroidConfigurations::readelfPath(Abi::Architecture architecture, const QString &ndkToolChainVersion) const
BogDan Vatra's avatar
BogDan Vatra committed
268
{
269
    return toolPath(architecture, ndkToolChainVersion).append(QLatin1String("-readelf" QTC_HOST_EXE_SUFFIX));
BogDan Vatra's avatar
BogDan Vatra committed
270
271
}

272
FileName AndroidConfigurations::gdbPath(Abi::Architecture architecture, const QString &ndkToolChainVersion) const
BogDan Vatra's avatar
BogDan Vatra committed
273
{
274
    return toolPath(architecture, ndkToolChainVersion).append(QLatin1String("-gdb" QTC_HOST_EXE_SUFFIX));
BogDan Vatra's avatar
BogDan Vatra committed
275
276
}

hjk's avatar
hjk committed
277
FileName AndroidConfigurations::openJDKPath() const
BogDan Vatra's avatar
BogDan Vatra committed
278
279
280
281
{
    return m_config.openJDKLocation;
}

hjk's avatar
hjk committed
282
FileName AndroidConfigurations::openJDKBinPath() const
BogDan Vatra's avatar
BogDan Vatra committed
283
{
hjk's avatar
hjk committed
284
    FileName path = m_config.openJDKLocation;
Tobias Hunger's avatar
Tobias Hunger committed
285
286
287
    if (!path.isEmpty())
        return path.appendPath(QLatin1String("bin"));
    return path;
BogDan Vatra's avatar
BogDan Vatra committed
288
289
}

hjk's avatar
hjk committed
290
FileName AndroidConfigurations::keytoolPath() const
BogDan Vatra's avatar
BogDan Vatra committed
291
{
Tobias Hunger's avatar
Tobias Hunger committed
292
    return openJDKBinPath().appendPath(keytoolName);
BogDan Vatra's avatar
BogDan Vatra committed
293
294
}

hjk's avatar
hjk committed
295
FileName AndroidConfigurations::jarsignerPath() const
BogDan Vatra's avatar
BogDan Vatra committed
296
{
Tobias Hunger's avatar
Tobias Hunger committed
297
    return openJDKBinPath().appendPath(jarsignerName);
BogDan Vatra's avatar
BogDan Vatra committed
298
299
}

hjk's avatar
hjk committed
300
FileName AndroidConfigurations::zipalignPath() const
301
302
{
    Utils::FileName path = m_config.sdkLocation;
303
    return path.appendPath(QLatin1String("tools/zipalign" QTC_HOST_EXE_SUFFIX));
304
305
}

BogDan Vatra's avatar
BogDan Vatra committed
306
307
QString AndroidConfigurations::getDeployDeviceSerialNumber(int *apiLevel) const
{
308
    QVector<AndroidDeviceInfo> devices = connectedDevices();
BogDan Vatra's avatar
BogDan Vatra committed
309

310
    foreach (AndroidDeviceInfo device, devices) {
BogDan Vatra's avatar
BogDan Vatra committed
311
312
313
314
        if (device.sdk >= *apiLevel) {
            *apiLevel = device.sdk;
            return device.serialNumber;
        }
Tobias Hunger's avatar
Tobias Hunger committed
315
    }
BogDan Vatra's avatar
BogDan Vatra committed
316
317
318
    return startAVD(apiLevel);
}

319
QVector<AndroidDeviceInfo> AndroidConfigurations::connectedDevices(int apiLevel) const
BogDan Vatra's avatar
BogDan Vatra committed
320
{
321
    QVector<AndroidDeviceInfo> devices;
BogDan Vatra's avatar
BogDan Vatra committed
322
    QProcess adbProc;
Tobias Hunger's avatar
Tobias Hunger committed
323
    adbProc.start(adbToolPath().toString(), QStringList() << QLatin1String("devices"));
BogDan Vatra's avatar
BogDan Vatra committed
324
    if (!adbProc.waitForFinished(-1)) {
325
        adbProc.kill();
BogDan Vatra's avatar
BogDan Vatra committed
326
327
328
329
        return devices;
    }
    QList<QByteArray> adbDevs = adbProc.readAll().trimmed().split('\n');
    adbDevs.removeFirst();
330
    AndroidDeviceInfo dev;
BogDan Vatra's avatar
BogDan Vatra committed
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
    foreach (const QByteArray &device, adbDevs) {
        dev.serialNumber = QString::fromLatin1(device.left(device.indexOf('\t')).trimmed());
        dev.sdk = getSDKVersion(dev.serialNumber);
        if (apiLevel != -1 && dev.sdk != apiLevel)
            continue;
        devices.push_back(dev);
    }
    qSort(devices.begin(), devices.end(), androidDevicesLessThan);
    return devices;
}

bool AndroidConfigurations::createAVD(int minApiLevel) const
{
    QDialog d;
    Ui::AddNewAVDDialog avdDialog;
    avdDialog.setupUi(&d);
    QStringListModel model(sdkTargets(minApiLevel));
    avdDialog.targetComboBox->setModel(&model);
    if (!model.rowCount()) {
Friedemann Kleint's avatar
Friedemann Kleint committed
350
        QMessageBox::critical(0, tr("Error Creating AVD"),
351
                              tr("Cannot create a new AVD. No sufficiently recent Android SDK available.\n"
Friedemann Kleint's avatar
Friedemann Kleint committed
352
                                 "Please install an SDK of at least API version %1.").
Friedemann Kleint's avatar
Friedemann Kleint committed
353
                              arg(minApiLevel));
BogDan Vatra's avatar
BogDan Vatra committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367
        return false;
    }

    QRegExp rx(QLatin1String("\\S+"));
    QRegExpValidator v(rx, 0);
    avdDialog.nameLineEdit->setValidator(&v);
    if (d.exec() != QDialog::Accepted)
        return false;
    return createAVD(avdDialog.targetComboBox->currentText(), avdDialog.nameLineEdit->text(), avdDialog.sizeSpinBox->value());
}

bool AndroidConfigurations::createAVD(const QString &target, const QString &name, int sdcardSize ) const
{
    QProcess proc;
Tobias Hunger's avatar
Tobias Hunger committed
368
    proc.start(androidToolPath().toString(),
BogDan Vatra's avatar
BogDan Vatra committed
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
               QStringList() << QLatin1String("create") << QLatin1String("avd")
               << QLatin1String("-a") << QLatin1String("-t") << target
               << QLatin1String("-n") << name
               << QLatin1String("-c") << QString::fromLatin1("%1M").arg(sdcardSize));
    if (!proc.waitForStarted())
        return false;
    proc.write(QByteArray("no\n"));
    if (!proc.waitForFinished(-1)) {
        proc.terminate();
        return false;
    }
    return !proc.exitCode();
}

bool AndroidConfigurations::removeAVD(const QString &name) const
{
    QProcess proc;
Tobias Hunger's avatar
Tobias Hunger committed
386
    proc.start(androidToolPath().toString(),
BogDan Vatra's avatar
BogDan Vatra committed
387
388
389
390
391
392
393
394
395
               QStringList() << QLatin1String("delete") << QLatin1String("avd")
               << QLatin1String("-n") << name);
    if (!proc.waitForFinished(-1)) {
        proc.terminate();
        return false;
    }
    return !proc.exitCode();
}

396
QVector<AndroidDeviceInfo> AndroidConfigurations::androidVirtualDevices() const
BogDan Vatra's avatar
BogDan Vatra committed
397
{
398
    QVector<AndroidDeviceInfo> devices;
BogDan Vatra's avatar
BogDan Vatra committed
399
    QProcess proc;
Tobias Hunger's avatar
Tobias Hunger committed
400
    proc.start(androidToolPath().toString(),
BogDan Vatra's avatar
BogDan Vatra committed
401
402
403
404
405
406
407
               QStringList() << QLatin1String("list") << QLatin1String("avd")); // list available AVDs
    if (!proc.waitForFinished(-1)) {
        proc.terminate();
        return devices;
    }
    QList<QByteArray> avds = proc.readAll().trimmed().split('\n');
    avds.removeFirst();
408
    AndroidDeviceInfo dev;
BogDan Vatra's avatar
BogDan Vatra committed
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
    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:")))
                dev.cpuABI = line.mid(line.lastIndexOf(QLatin1Char(' '))).trimmed();
        }
        devices.push_back(dev);
    }
    qSort(devices.begin(), devices.end(), androidDevicesLessThan);

    return devices;
}

QString AndroidConfigurations::startAVD(int *apiLevel, const QString &name) const
{
Orgad Shaneh's avatar
Orgad Shaneh committed
434
435
436
    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
437
438

    QString avdName = name;
439
    QVector<AndroidDeviceInfo> devices;
BogDan Vatra's avatar
BogDan Vatra committed
440
441
442
443
    bool createAVDOnce = false;
    while (true) {
        if (avdName.isEmpty()) {
            devices = androidVirtualDevices();
Orgad Shaneh's avatar
Orgad Shaneh committed
444
            foreach (const AndroidDeviceInfo &device, devices)
BogDan Vatra's avatar
BogDan Vatra committed
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
                if (device.sdk >= *apiLevel) { // take first emulator how supports this package
                    *apiLevel = device.sdk;
                    avdName = device.serialNumber;
                    break;
                }
        }
        // if no emulators found try to create one once
        if (avdName.isEmpty() && !createAVDOnce) {
            createAVDOnce = true;
            QMetaObject::invokeMethod(const_cast<QObject*>(static_cast<const QObject*>(this)), "createAVD", Qt::AutoConnection,
                                      Q_ARG(int, *apiLevel));
        } else {
            break;
        }
    }

    if (avdName.isEmpty())// stop here if no emulators found
        return avdName;

    // start the emulator
Orgad Shaneh's avatar
Orgad Shaneh committed
465
    avdProcess->start(emulatorToolPath().toString(),
BogDan Vatra's avatar
BogDan Vatra committed
466
467
                        QStringList() << QLatin1String("-partition-size") << QString::number(config().partitionSize)
                        << QLatin1String("-avd") << avdName);
Orgad Shaneh's avatar
Orgad Shaneh committed
468
469
    if (!avdProcess->waitForStarted(-1)) {
        delete avdProcess;
BogDan Vatra's avatar
BogDan Vatra committed
470
471
472
473
474
        return QString();
    }

    // wait until the emulator is online
    QProcess proc;
Tobias Hunger's avatar
Tobias Hunger committed
475
    proc.start(adbToolPath().toString(), QStringList() << QLatin1String("-e") << QLatin1String("wait-for-device"));
Orgad Shaneh's avatar
Orgad Shaneh committed
476
477
    while (!proc.waitForFinished(500)) {
        if (avdProcess->waitForFinished(0)) {
478
            proc.kill();
Orgad Shaneh's avatar
Orgad Shaneh committed
479
480
481
            proc.waitForFinished(-1);
            return QString();
        }
BogDan Vatra's avatar
BogDan Vatra committed
482
483
484
485
    }
    sleep(5);// wait for pm to start

    // workaround for stupid adb bug
Tobias Hunger's avatar
Tobias Hunger committed
486
    proc.start(adbToolPath().toString(), QStringList() << QLatin1String("devices"));
BogDan Vatra's avatar
BogDan Vatra committed
487
    if (!proc.waitForFinished(-1)) {
488
        proc.kill();
BogDan Vatra's avatar
BogDan Vatra committed
489
490
491
492
493
        return QString();
    }

    // get connected devices
    devices = connectedDevices(*apiLevel);
494
    foreach (AndroidDeviceInfo device, devices)
BogDan Vatra's avatar
BogDan Vatra committed
495
496
497
498
499
500
501
502
503
504
        if (device.sdk == *apiLevel)
            return device.serialNumber;
    // this should not happen, but ...
    return QString();
}

int AndroidConfigurations::getSDKVersion(const QString &device) const
{

    QProcess adbProc;
Tobias Hunger's avatar
Tobias Hunger committed
505
    adbProc.start(adbToolPath().toString(),
BogDan Vatra's avatar
BogDan Vatra committed
506
507
508
509
                  QStringList() << QLatin1String("-s") << device
                  << QLatin1String("shell") << QLatin1String("getprop")
                  << QLatin1String("ro.build.version.sdk"));
    if (!adbProc.waitForFinished(-1)) {
510
        adbProc.kill();
BogDan Vatra's avatar
BogDan Vatra committed
511
512
513
514
515
516
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
549
550
551
552
553
554
555
556
557
558
559
        return -1;
    }
    return adbProc.readAll().trimmed().toInt();
}

QString AndroidConfigurations::bestMatch(const QString &targetAPI) const
{
    int target = targetAPI.mid(targetAPI.lastIndexOf(QLatin1Char('-')) + 1).toInt();
    foreach (int apiLevel, m_availablePlatforms) {
        if (apiLevel <= target)
            return QString::fromLatin1("android-%1").arg(apiLevel);
    }
    return QLatin1String("android-8");
}

AndroidConfigurations &AndroidConfigurations::instance(QObject *parent)
{
    if (m_instance == 0)
        m_instance = new AndroidConfigurations(parent);
    return *m_instance;
}

void AndroidConfigurations::save()
{
    QSettings *settings = Core::ICore::instance()->settings();
    settings->beginGroup(SettingsGroup);
    m_config.save(*settings);
    settings->endGroup();
}

AndroidConfigurations::AndroidConfigurations(QObject *parent)
    : QObject(parent)
{
    load();
    updateAvailablePlatforms();
}

void AndroidConfigurations::load()
{
    QSettings *settings = Core::ICore::instance()->settings();
    settings->beginGroup(SettingsGroup);
    m_config = AndroidConfig(*settings);
    settings->endGroup();
}

AndroidConfigurations *AndroidConfigurations::m_instance = 0;

} // namespace Internal
} // namespace Android