aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/android/androidavdmanager.cpp
blob: e537911fc69cc44ee008e1b3c57149b0958351d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "androidavdmanager.h"
#include "androidtr.h"
#include "avdmanageroutputparser.h"

#include <coreplugin/icore.h>

#include <projectexplorer/projectexplorerconstants.h>

#include <utils/algorithm.h>
#include <utils/async.h>
#include <utils/qtcprocess.h>
#include <utils/qtcassert.h>

#include <QLoggingCategory>
#include <QMainWindow>
#include <QMessageBox>

#include <chrono>

using namespace Utils;
using namespace std;
using namespace std::chrono_literals;

namespace Android::Internal {

const int avdCreateTimeoutMs = 30000;

static Q_LOGGING_CATEGORY(avdManagerLog, "qtc.android.avdManager", QtWarningMsg)

/*!
    Runs the \c avdmanager tool specific to configuration \a config with arguments \a args. Returns
    \c true if the command is successfully executed. Output is copied into \a output. The function
    blocks the calling thread.
 */
bool AndroidAvdManager::avdManagerCommand(const QStringList &args, QString *output)
{
    CommandLine cmd(androidConfig().avdManagerToolPath(), args);
    Process proc;
    proc.setEnvironment(androidConfig().toolsEnvironment());
    qCDebug(avdManagerLog).noquote() << "Running AVD Manager command:" << cmd.toUserOutput();
    proc.setCommand(cmd);
    proc.runBlocking();
    if (proc.result() == ProcessResult::FinishedWithSuccess) {
        if (output)
            *output = proc.allOutput();
        return true;
    }
    return false;
}

static bool checkForTimeout(const chrono::steady_clock::time_point &start,
                            int msecs = 3000)
{
    bool timedOut = false;
    auto end = chrono::steady_clock::now();
    if (chrono::duration_cast<chrono::milliseconds>(end-start).count() > msecs)
        timedOut = true;
    return timedOut;
}

static CreateAvdInfo createAvdCommand(const CreateAvdInfo &info)
{
    CreateAvdInfo result = info;

    if (!result.isValid()) {
        qCDebug(avdManagerLog) << "AVD Create failed. Invalid CreateAvdInfo" << result.name
                               << result.systemImage->displayText() << result.systemImage->apiLevel();
        result.error = Tr::tr("Cannot create AVD. Invalid input.");
        return result;
    }

    CommandLine avdManager(androidConfig().avdManagerToolPath(), {"create", "avd", "-n", result.name});
    avdManager.addArgs({"-k", result.systemImage->sdkStylePath()});

    if (result.sdcardSize > 0)
        avdManager.addArgs({"-c", QString("%1M").arg(result.sdcardSize)});

    if (!result.deviceDefinition.isEmpty() && result.deviceDefinition != "Custom")
        avdManager.addArgs({"-d", QString("%1").arg(result.deviceDefinition)});

    if (result.overwrite)
        avdManager.addArg("-f");

    qCDebug(avdManagerLog).noquote() << "Running AVD Manager command:" << avdManager.toUserOutput();
    Process proc;
    proc.setProcessMode(ProcessMode::Writer);
    proc.setEnvironment(androidConfig().toolsEnvironment());
    proc.setCommand(avdManager);
    proc.start();
    if (!proc.waitForStarted()) {
        result.error = Tr::tr("Could not start process \"%1\".").arg(avdManager.toUserOutput());
        return result;
    }
    QTC_CHECK(proc.isRunning());
    proc.write("yes\n"); // yes to "Do you wish to create a custom hardware profile"

    auto start = chrono::steady_clock::now();
    QString errorOutput;
    QByteArray question;
    while (errorOutput.isEmpty()) {
        proc.waitForReadyRead(500ms);
        question += proc.readAllRawStandardOutput();
        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("yes\n");
            else
                proc.write("\n");
            question.clear();
        }
        // The exit code is always 0, so we need to check stderr
        // For now assume that any output at all indicates a error
        errorOutput = QString::fromLocal8Bit(proc.readAllRawStandardError());
        if (!proc.isRunning())
            break;

        // For a sane input and command, process should finish before timeout.
        if (checkForTimeout(start, avdCreateTimeoutMs))
            result.error = Tr::tr("Cannot create AVD. Command timed out.");
    }

    result.error = errorOutput;
    return result;
}

AndroidAvdManager::AndroidAvdManager() = default;

AndroidAvdManager::~AndroidAvdManager() = default;

QFuture<CreateAvdInfo> AndroidAvdManager::createAvd(CreateAvdInfo info) const
{
    return Utils::asyncRun(&createAvdCommand, info);
}

static void avdConfigEditManufacturerTag(const FilePath &avdPath, bool recoverMode = false)
{
    if (!avdPath.exists())
        return;

    const FilePath configFilePath = avdPath / "config.ini";
    FileReader reader;
    if (!reader.fetch(configFilePath, QIODevice::ReadOnly | QIODevice::Text))
        return;

    FileSaver saver(configFilePath);
    QTextStream textStream(reader.data());
    while (!textStream.atEnd()) {
        QString line = textStream.readLine();
        if (line.contains("hw.device.manufacturer")) {
            if (recoverMode)
                line.replace("#", "");
            else
                line.prepend("#");
        }
        line.append("\n");
        saver.write(line.toUtf8());
    }
    saver.finalize();
}

static AndroidDeviceInfoList listVirtualDevices()
{
    QString output;
    AndroidDeviceInfoList avdList;
    /*
        Currenly avdmanager tool fails to parse some AVDs because the correct
        device definitions at devices.xml does not have some of the newest devices.
        Particularly, failing because of tag "hw.device.manufacturer", thus removing
        it would make paring successful. However, it has to be returned afterwards,
        otherwise, Android Studio would give an error during parsing also. So this fix
        aim to keep support for Qt Creator and Android Studio.
    */
    FilePaths allAvdErrorPaths;
    FilePaths avdErrorPaths;

    do {
        if (!AndroidAvdManager::avdManagerCommand({"list", "avd"}, &output)) {
            qCDebug(avdManagerLog)
                << "Avd list command failed" << output << androidConfig().sdkToolsVersion();
            return {};
        }

        avdErrorPaths.clear();
        avdList = parseAvdList(output, &avdErrorPaths);
        allAvdErrorPaths << avdErrorPaths;
        for (const FilePath &avdPath : std::as_const(avdErrorPaths))
            avdConfigEditManufacturerTag(avdPath); // comment out manufacturer tag
    } while (!avdErrorPaths.isEmpty());            // try again

    for (const FilePath &avdPath : std::as_const(allAvdErrorPaths))
        avdConfigEditManufacturerTag(avdPath, true); // re-add manufacturer tag

    return avdList;
}

QFuture<AndroidDeviceInfoList> AndroidAvdManager::avdList() const
{
    return Utils::asyncRun(listVirtualDevices);
}

QString AndroidAvdManager::startAvd(const QString &name) const
{
    if (!findAvd(name).isEmpty() || startAvdAsync(name))
        return waitForAvd(name);
    return {};
}

static bool is32BitUserSpace()
{
    // Do a similar check as android's emulator is doing:
    if (HostOsInfo::isLinuxHost()) {
        if (QSysInfo::WordSize == 32) {
            Process proc;
            proc.setCommand({"getconf", {"LONG_BIT"}});
            proc.runBlocking(3s);
            if (proc.result() != ProcessResult::FinishedWithSuccess)
                return true;
            return proc.allOutput().trimmed() == "32";
        }
    }
    return false;
}

bool AndroidAvdManager::startAvdAsync(const QString &avdName) const
{
    const FilePath emulator = androidConfig().emulatorToolPath();
    if (!emulator.exists()) {
        QMetaObject::invokeMethod(Core::ICore::mainWindow(), [emulator] {
            QMessageBox::critical(Core::ICore::dialogParent(),
                                  Tr::tr("Emulator Tool Is Missing"),
                                  Tr::tr("Install the missing emulator tool (%1) to the"
                                         " installed Android SDK.")
                                  .arg(emulator.displayName()));
        });
        return false;
    }

    // TODO: Here we are potentially leaking Process instance in case when shutdown happens
    // after the avdProcess has started and before it has finished. Giving a parent object here
    // should solve the issue. However, AndroidAvdManager is not a QObject, so no clue what parent
    // would be the most appropriate. Preferably some object taken form android plugin...
    Process *avdProcess = new Process;
    avdProcess->setProcessChannelMode(QProcess::MergedChannels);
    QObject::connect(avdProcess, &Process::done, avdProcess, [avdProcess] {
        if (avdProcess->exitCode()) {
            const QString errorOutput = QString::fromLatin1(avdProcess->rawStdOut());
            QMetaObject::invokeMethod(Core::ICore::mainWindow(), [errorOutput] {
                const QString title = Tr::tr("AVD Start Error");
                QMessageBox::critical(Core::ICore::dialogParent(), title, errorOutput);
            });
        }
        avdProcess->deleteLater();
    });

    // start the emulator
    CommandLine cmd(androidConfig().emulatorToolPath());
    if (is32BitUserSpace())
        cmd.addArg("-force-32bit");

    cmd.addArgs(androidConfig().emulatorArgs(), CommandLine::Raw);
    cmd.addArgs({"-avd", avdName});
    qCDebug(avdManagerLog).noquote() << "Running command (startAvdAsync):" << cmd.toUserOutput();
    avdProcess->setCommand(cmd);
    avdProcess->start();
    return avdProcess->waitForStarted(QDeadlineTimer::Forever);
}

QString AndroidAvdManager::findAvd(const QString &avdName) const
{
    const QList<AndroidDeviceInfo> devices = androidConfig().connectedDevices();
    for (const AndroidDeviceInfo &device : devices) {
        if (device.type != ProjectExplorer::IDevice::Emulator)
            continue;
        if (device.avdName == avdName)
            return device.serialNumber;
    }
    return {};
}

QString AndroidAvdManager::waitForAvd(const QString &avdName,
                                      const std::optional<QFuture<void>> &future) 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
    QString serialNumber;
    for (int i = 0; i < 60; ++i) {
        if (future && future->isCanceled())
            return {};
        serialNumber = findAvd(avdName);
        if (!serialNumber.isEmpty())
            return waitForBooted(serialNumber, future) ? serialNumber : QString();
        QThread::sleep(2);
    }
    return {};
}

bool AndroidAvdManager::isAvdBooted(const QString &device) const
{
    QStringList arguments = AndroidDeviceInfo::adbSelector(device);
    arguments << "shell" << "getprop" << "init.svc.bootanim";

    const CommandLine command({androidConfig().adbToolPath(), arguments});
    qCDebug(avdManagerLog).noquote() << "Running command (isAvdBooted):" << command.toUserOutput();
    Process adbProc;
    adbProc.setCommand(command);
    adbProc.runBlocking();
    if (adbProc.result() != ProcessResult::FinishedWithSuccess)
        return false;
    QString value = adbProc.allOutput().trimmed();
    return value == "stopped";
}

bool AndroidAvdManager::waitForBooted(const QString &serialNumber,
                                      const std::optional<QFuture<void>> &future) const
{
    // found a serial number, now wait until it's done booting...
    for (int i = 0; i < 60; ++i) {
        if (future && future->isCanceled())
            return false;
        if (isAvdBooted(serialNumber))
            return true;
        QThread::sleep(2);
        if (!androidConfig().isConnected(serialNumber)) // device was disconnected
            return false;
    }
    return false;
}

} // Android::Internal