androidtoolmanager.cpp 12.6 KB
Newer Older
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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** 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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "androidtoolmanager.h"

#include "androidmanager.h"

#include "utils/algorithm.h"
#include "utils/environment.h"
#include "utils/qtcassert.h"
#include "utils/runextensions.h"
#include "utils/synchronousprocess.h"

#include <QLoggingCategory>

namespace {
Q_LOGGING_CATEGORY(androidToolLog, "qtc.android.sdkManager")
}

namespace Android {
namespace Internal {

using namespace Utils;

class AndroidToolOutputParser
{
public:
    void parseTargetListing(const QString &output, const FileName &sdkLocation,
                            SdkPlatformList *platformList);

    QList<SdkPlatform> m_installedPlatforms;
};

/*!
    Runs the \c android tool located at \a toolPath with arguments \a args and environment \a
    environment. Returns \c true for successful execution. Command's output is copied to \a
    output.
 */
static bool androidToolCommand(Utils::FileName toolPath, const QStringList &args,
                               const Environment &environment, QString *output)
{
    QString androidToolPath = toolPath.toString();
    SynchronousProcess proc;
    proc.setProcessEnvironment(environment.toProcessEnvironment());
    SynchronousProcessResponse response = proc.runBlocking(androidToolPath, args);
    if (response.result == SynchronousProcessResponse::Finished) {
        if (output)
            *output = response.allOutput();
        return true;
    }
    return false;
}

static QStringList cleanAndroidABIs(const QStringList &abis)
{
    QStringList res;
    foreach (const QString &abi, abis) {
        int index = abi.lastIndexOf(QLatin1Char('/'));
        if (index == -1)
            res << abi;
        else
            res << abi.mid(index + 1);
    }
    return res;
}

AndroidToolManager::AndroidToolManager(const AndroidConfig &config) :
    m_config(config),
    m_parser(new AndroidToolOutputParser)
{

}

AndroidToolManager::~AndroidToolManager()
{

}

100
SdkPlatformList AndroidToolManager::availableSdkPlatforms(bool *ok) const
101
{
102
    bool success = false;
103 104 105 106 107
    SdkPlatformList list;
    QString targetListing;
    if (androidToolCommand(m_config.androidToolPath(), QStringList({"list",  "target"}),
                           androidToolEnvironment(), &targetListing)) {
        m_parser->parseTargetListing(targetListing, m_config.sdkLocation(), &list);
108
        success = true;
109 110 111
    } else {
        qCDebug(androidToolLog) << "Android tool target listing failed";
    }
112 113 114 115

    if (ok)
        *ok = success;

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
    return list;
}

void AndroidToolManager::launchAvdManager() const
{
    QProcess::startDetached(m_config.androidToolPath().toString(), QStringList("avd"));
}

QFuture<AndroidConfig::CreateAvdInfo>
AndroidToolManager::createAvd(AndroidConfig::CreateAvdInfo info) const
{
    return Utils::runAsync(&AndroidToolManager::createAvdImpl, info,
                           m_config.androidToolPath(), androidToolEnvironment());
}

bool AndroidToolManager::removeAvd(const QString &name) const
{
    SynchronousProcess proc;
    proc.setTimeoutS(5);
    proc.setProcessEnvironment(androidToolEnvironment().toProcessEnvironment());
    SynchronousProcessResponse response
            = proc.runBlocking(m_config.androidToolPath().toString(),
                               QStringList({"delete", "avd", "-n", name}));
    return response.result == SynchronousProcessResponse::Finished && response.exitCode == 0;
}

Vikas Pachdha's avatar
Vikas Pachdha committed
142
QFuture<AndroidDeviceInfoList> AndroidToolManager::androidVirtualDevicesFuture() const
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
{
    return Utils::runAsync(&AndroidToolManager::androidVirtualDevices,
                           m_config.androidToolPath(), m_config.sdkLocation(),
                           androidToolEnvironment());
}

Environment AndroidToolManager::androidToolEnvironment() const
{
    Environment env = Environment::systemEnvironment();
    Utils::FileName jdkLocation = m_config.openJDKLocation();
    if (!jdkLocation.isEmpty()) {
        env.set(QLatin1String("JAVA_HOME"), jdkLocation.toUserOutput());
        Utils::FileName binPath = jdkLocation;
        binPath.appendPath(QLatin1String("bin"));
        env.prependOrSetPath(binPath.toUserOutput());
    }
    return env;
}

AndroidConfig::CreateAvdInfo AndroidToolManager::createAvdImpl(AndroidConfig::CreateAvdInfo info,
                                                               FileName androidToolPath,
                                                               Environment env)
{
    QProcess proc;
    proc.setProcessEnvironment(env.toProcessEnvironment());
    QStringList arguments;
    arguments << QLatin1String("create") << QLatin1String("avd")
Vikas Pachdha's avatar
Vikas Pachdha committed
170
              << QLatin1String("-t") << AndroidConfig::apiLevelNameFor(info.target)
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
              << QLatin1String("-n") << info.name
              << QLatin1String("-b") << info.abi;
    if (info.sdcardSize > 0)
        arguments << QLatin1String("-c") << QString::fromLatin1("%1M").arg(info.sdcardSize);
    proc.start(androidToolPath.toString(), arguments);
    if (!proc.waitForStarted()) {
        info.error = tr("Could not start process \"%1 %2\"")
                .arg(androidToolPath.toString(), arguments.join(QLatin1Char(' ')));
        return info;
    }
    QTC_CHECK(proc.state() == QProcess::Running);
    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;
    }
    QTC_CHECK(proc.state() == QProcess::NotRunning);

    QString errorOutput = QString::fromLocal8Bit(proc.readAllStandardError());
    // The exit code is always 0, so we need to check stderr
    // For now assume that any output at all indicates a error
    if (!errorOutput.isEmpty()) {
        info.error = errorOutput;
    }

    return info;
}

Vikas Pachdha's avatar
Vikas Pachdha committed
215 216 217
AndroidDeviceInfoList AndroidToolManager::androidVirtualDevices(const Utils::FileName &androidTool,
                                                                const FileName &sdkLocationPath,
                                                                const Environment &environment)
218
{
Vikas Pachdha's avatar
Vikas Pachdha committed
219
    AndroidDeviceInfoList devices;
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
    QString output;
    if (!androidToolCommand(androidTool, QStringList({"list", "avd"}), environment, &output))
        return devices;

    QStringList avds = output.split('\n');
    if (avds.empty())
        return devices;

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

    bool nextLineIsTargetLine = false;

    AndroidDeviceInfo dev;
    for (int i = 0; i < avds.size(); i++) {
        QString line = avds.at(i);
        if (!line.contains(QLatin1String("Name:")))
            continue;

        int index = line.indexOf(QLatin1Char(':')) + 2;
        if (index >= line.size())
            break;
        dev.avdname = line.mid(index).trimmed();
        dev.sdk = -1;
        dev.cpuAbi.clear();
        ++i;
        for (; i < avds.size(); ++i) {
            line = avds.at(i);
            if (line.contains(QLatin1String("---------")))
                break;

            if (line.contains(QLatin1String("Target:")) || nextLineIsTargetLine) {
                if (line.contains(QLatin1String("Google APIs"))) {
                    nextLineIsTargetLine = true;
                    continue;
                }

                nextLineIsTargetLine = false;

                int lastIndex = line.lastIndexOf(QLatin1Char(' '));
                if (lastIndex == -1) // skip line
                    break;
                QString tmp = line.mid(lastIndex).remove(QLatin1Char(')')).trimmed();
                Utils::FileName platformPath = sdkLocationPath;
                platformPath.appendPath(QString("/platforms/android-%1").arg(tmp));
                dev.sdk = AndroidManager::findApiLevel(platformPath);
            }
            if (line.contains(QLatin1String("Tag/ABI:"))) {
                int lastIndex = line.lastIndexOf(QLatin1Char('/')) + 1;
                if (lastIndex >= line.size())
                    break;
                dev.cpuAbi = QStringList(line.mid(lastIndex));
            } else if (line.contains(QLatin1String("ABI:"))) {
                int lastIndex = line.lastIndexOf(QLatin1Char(' ')) + 1;
                if (lastIndex >= line.size())
                    break;
                dev.cpuAbi = QStringList(line.mid(lastIndex).trimmed());
            }
        }
        // armeabi-v7a devices can also run armeabi code
        if (dev.cpuAbi == QStringList("armeabi-v7a"))
            dev.cpuAbi << QLatin1String("armeabi");
        dev.state = AndroidDeviceInfo::OkState;
        dev.type = AndroidDeviceInfo::Emulator;
        if (dev.cpuAbi.isEmpty() || dev.sdk == -1)
            continue;
        devices.push_back(dev);
    }
    Utils::sort(devices);

    return devices;
}

void AndroidToolOutputParser::parseTargetListing(const QString &output,
                                                 const Utils::FileName &sdkLocation,
                                                 SdkPlatformList *platformList)
{
    if (!platformList)
        return;

301 302 303 304 305 306 307 308 309
    auto addSystemImage = [](const QStringList& abiList, SdkPlatform &platform) {
        foreach (auto imageAbi, abiList) {
            SystemImage image;
            image.abiName = imageAbi;
            image.apiLevel = platform.apiLevel;
            platform.systemImages.append(image);
        }
    };

310
    SdkPlatform platform;
311
    QStringList abiList;
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    foreach (const QString &l, output.split('\n')) {
        const QString line = l.trimmed();
        if (line.startsWith(QLatin1String("id:")) && line.contains(QLatin1String("android-"))) {
            int index = line.indexOf(QLatin1String("\"android-"));
            if (index == -1)
                continue;
            QString androidTarget = line.mid(index + 1, line.length() - index - 2);
            const QString tmp = androidTarget.mid(androidTarget.lastIndexOf(QLatin1Char('-')) + 1);
            Utils::FileName platformPath = sdkLocation;
            platformPath.appendPath(QString("/platforms/android-%1").arg(tmp));
            platform.installedLocation = platformPath;
            platform.apiLevel = AndroidManager::findApiLevel(platformPath);
        } else if (line.startsWith(QLatin1String("Name:"))) {
            platform.name = line.mid(6);
        } else if (line.startsWith(QLatin1String("Tag/ABIs :"))) {
327
            abiList = cleanAndroidABIs(line.mid(10).trimmed().split(QLatin1String(", ")));
328
        } else if (line.startsWith(QLatin1String("ABIs"))) {
329
            abiList = cleanAndroidABIs(line.mid(6).trimmed().split(QLatin1String(", ")));
330 331 332
        } else if (line.startsWith(QLatin1String("---")) || line.startsWith(QLatin1String("==="))) {
            if (platform.apiLevel == -1)
                continue;
333 334

            addSystemImage(abiList, platform);
335
            *platformList << platform;
336

337
            platform = SdkPlatform();
338
            abiList.clear();
339 340 341 342
        }
    }

    // The last parsed Platform.
343 344
    if (platform.apiLevel != -1) {
        addSystemImage(abiList, platform);
345
        *platformList << platform;
346
    }
Vikas Pachdha's avatar
Vikas Pachdha committed
347 348

    Utils::sort(*platformList);
349 350 351 352
}

} // namespace Internal
} // namespace Android