androiddeployqtstep.cpp 16.2 KB
Newer Older
1 2
/**************************************************************************
**
3 4
** Copyright (c) 2014 BogDan Vatra <bog_dan_ro@yahoo.com>
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
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
** Contact: http://www.qt-project.org/legal
**
** 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 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.
**
** GNU Lesser General Public License Usage
** 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
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "androiddeployqtstep.h"
#include "androiddeployqtwidget.h"
33
#include "androidqtsupport.h"
34 35 36 37
#include "certificatesmodel.h"

#include "javaparser.h"
#include "androidmanager.h"
38
#include "androidconstants.h"
39
#include "androidglobal.h"
40 41 42 43

#include <coreplugin/fileutils.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
44 45

#include <projectexplorer/buildconfiguration.h>
46 47 48
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/project.h>
49 50
#include <projectexplorer/target.h>

51
#include <qtsupport/qtkitinformation.h>
52 53 54 55

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

56 57 58
#include <QInputDialog>
#include <QMessageBox>

59

60 61 62
using namespace Android;
using namespace Android::Internal;

63
const QLatin1String UninstallPreviousPackageKey("UninstallPreviousPackage");
64 65 66 67 68
const QLatin1String KeystoreLocationKey("KeystoreLocation");
const QLatin1String SignPackageKey("SignPackage");
const QLatin1String BuildTargetSdkKey("BuildTargetSdk");
const QLatin1String VerboseOutputKey("VerboseOutput");
const QLatin1String InputFile("InputFile");
69
const QLatin1String ProFilePathForInputFile("ProFilePathForInputFile");
70
const QLatin1String InstallFailedInconsistentCertificatesString("INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES");
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
const Core::Id AndroidDeployQtStep::Id("Qt4ProjectManager.AndroidDeployQtStep");

//////////////////
// AndroidDeployQtStepFactory
/////////////////

AndroidDeployQtStepFactory::AndroidDeployQtStepFactory(QObject *parent)
    : IBuildStepFactory(parent)
{
}

QList<Core::Id> AndroidDeployQtStepFactory::availableCreationIds(ProjectExplorer::BuildStepList *parent) const
{
    if (parent->id() != ProjectExplorer::Constants::BUILDSTEPS_DEPLOY)
        return QList<Core::Id>();
    if (!AndroidManager::supportsAndroid(parent->target()))
        return QList<Core::Id>();
    if (parent->contains(AndroidDeployQtStep::Id))
        return QList<Core::Id>();
    return QList<Core::Id>() << AndroidDeployQtStep::Id;
}

93
QString AndroidDeployQtStepFactory::displayNameForId(Core::Id id) const
94 95 96 97 98 99
{
    if (id == AndroidDeployQtStep::Id)
        return tr("Deploy to Android device or emulator");
    return QString();
}

100
bool AndroidDeployQtStepFactory::canCreate(ProjectExplorer::BuildStepList *parent, Core::Id id) const
101 102 103 104
{
    return availableCreationIds(parent).contains(id);
}

105
ProjectExplorer::BuildStep *AndroidDeployQtStepFactory::create(ProjectExplorer::BuildStepList *parent, Core::Id id)
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
{
    Q_ASSERT(canCreate(parent, id));
    Q_UNUSED(id);
    return new AndroidDeployQtStep(parent);
}

bool AndroidDeployQtStepFactory::canRestore(ProjectExplorer::BuildStepList *parent, const QVariantMap &map) const
{
    return canCreate(parent, ProjectExplorer::idFromMap(map));
}

ProjectExplorer::BuildStep *AndroidDeployQtStepFactory::restore(ProjectExplorer::BuildStepList *parent, const QVariantMap &map)
{
    Q_ASSERT(canRestore(parent, map));
    AndroidDeployQtStep * const step = new AndroidDeployQtStep(parent);
    if (!step->fromMap(map)) {
        delete step;
        return 0;
    }
    return step;
}

bool AndroidDeployQtStepFactory::canClone(ProjectExplorer::BuildStepList *parent, ProjectExplorer::BuildStep *product) const
{
    return canCreate(parent, product->id());
}

ProjectExplorer::BuildStep *AndroidDeployQtStepFactory::clone(ProjectExplorer::BuildStepList *parent, ProjectExplorer::BuildStep *product)
{
    Q_ASSERT(canClone(parent, product));
    return new AndroidDeployQtStep(parent, static_cast<AndroidDeployQtStep *>(product));
}

//////////////////
// AndroidDeployQtStep
/////////////////

AndroidDeployQtStep::AndroidDeployQtStep(ProjectExplorer::BuildStepList *parent)
    : ProjectExplorer::AbstractProcessStep(parent, Id)
{
    ctor();
}

AndroidDeployQtStep::AndroidDeployQtStep(ProjectExplorer::BuildStepList *parent,
    AndroidDeployQtStep *other)
    : ProjectExplorer::AbstractProcessStep(parent, other)
{
    ctor();
}

void AndroidDeployQtStep::ctor()
{
158 159 160 161
    m_uninstallPreviousPackage = false;
    m_uninstallPreviousPackageTemp = false;
    m_uninstallPreviousPackageRun = false;

162 163 164 165 166 167
    //: AndroidDeployQtStep default display name
    setDefaultDisplayName(tr("Deploy to Android device"));
}

bool AndroidDeployQtStep::init()
{
168
    if (AndroidManager::checkForQt51Files(project()->projectDirectory()))
169
        emit addOutput(tr("Found old folder \"android\" in source directory. Qt 5.2 does not use that folder by default."), ErrorOutput);
170 171

    m_targetArch = AndroidManager::targetArch(target());
172 173 174 175
    if (m_targetArch.isEmpty()) {
        emit addOutput(tr("No Android arch set by the .pro file."), ErrorOutput);
        return false;
    }
176
    m_deviceAPILevel = AndroidManager::minimumSDK(target());
Daniel Teske's avatar
Daniel Teske committed
177
    AndroidDeviceInfo info = AndroidConfigurations::showDeviceDialog(project(), m_deviceAPILevel, m_targetArch);
178 179 180 181 182 183 184 185 186 187 188
    if (info.serialNumber.isEmpty()) // aborted
        return false;

    if (info.type == AndroidDeviceInfo::Emulator) {
        m_avdName = info.serialNumber;
        m_serialNumber.clear();
        m_deviceAPILevel = info.sdk;
    } else {
        m_avdName.clear();
        m_serialNumber = info.serialNumber;
    }
189
    AndroidManager::setDeviceSerialNumber(target(), m_serialNumber);
190

191
    ProjectExplorer::BuildConfiguration *bc = target()->activeBuildConfiguration();
192 193 194 195 196

    QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
    if (!version)
        return false;

197 198 199 200 201 202 203 204
    m_uninstallPreviousPackageRun = m_uninstallPreviousPackage || m_uninstallPreviousPackageTemp;
    m_uninstallPreviousPackageTemp = false;
    if (m_uninstallPreviousPackageRun) {
        m_packageName = AndroidManager::packageName(target());
        if (m_packageName.isEmpty()){
            emit addOutput(tr("Cannot find the package name."), ErrorOutput);
            return false;
        }
205 206
    }
    ProjectExplorer::ProcessParameters *pp = processParameters();
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
    m_useAndroiddeployqt = version->qtVersion() >= QtSupport::QtVersionNumber(5, 4, 0);
    if (m_useAndroiddeployqt) {
        AndroidBuildApkStep *androidBuildApkStep
            = AndroidGlobal::buildStep<AndroidBuildApkStep>(target()->activeBuildConfiguration());
        if (!androidBuildApkStep) {
            emit addOutput(tr("Cannot find the android build step."), ErrorOutput);
            return false;
        }
        Utils::FileName tmp = AndroidManager::androidQtSupport(target())->androiddeployqtPath(target());
        if (tmp.isEmpty()) {
            emit addOutput(tr("Cannot find the androiddeployqt tool."), ErrorOutput);
            return false;
        }


        pp->setCommand(tmp.toString());
        const QString output(bc->buildDirectory().appendPath(QLatin1String(Constants::ANDROID_BUILDDIRECTORY)).toString());
        pp->setWorkingDirectory(output);

        Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--verbose"));
        Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--output"));
        Utils::QtcProcess::addArg(&m_androiddeployqtArgs, output);
        Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--no-build"));
        Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--input"));
        tmp = AndroidManager::androidQtSupport(target())->androiddeployJsonPath(target());
        if (tmp.isEmpty()) {
            emit addOutput(tr("Cannot find the androiddeploy Json file."), ErrorOutput);
            return false;
        }
        Utils::QtcProcess::addArg(&m_androiddeployqtArgs, tmp.toString());

        if (m_uninstallPreviousPackageRun)
            Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--install"));
        else
            Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--reinstall"));

        Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--deployment"));
        switch (androidBuildApkStep->deployAction()) {
            case AndroidBuildApkStep::MinistroDeployment:
                Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("ministro"));
                break;
            case AndroidBuildApkStep::DebugDeployment:
                Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("debug"));
                break;
            case AndroidBuildApkStep::BundleLibrariesDeployment:
                Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("bundled"));
                break;
        }
    } else {
        pp->setCommand(AndroidConfigurations::currentConfig().adbToolPath().toString());
        m_apkPath = AndroidManager::androidQtSupport(target())->apkPath(target(), AndroidManager::signPackage(target())
                                                                        ? AndroidQtSupport::ReleaseBuildSigned
                                                                        : AndroidQtSupport::DebugBuild).toString();
        pp->setWorkingDirectory(bc->buildDirectory().toString());
    }
262 263 264 265 266 267 268 269
    pp->setMacroExpander(bc->macroExpander());
    Utils::Environment env = bc->environment();
    pp->setEnvironment(env);
    m_buildDirectory = bc->buildDirectory().toString();
    bool result = AbstractProcessStep::init();
    if (!result)
        return false;

Daniel Teske's avatar
Daniel Teske committed
270 271
    if (AndroidConfigurations::currentConfig().findAvd(m_deviceAPILevel, m_targetArch).isEmpty())
        AndroidConfigurations::currentConfig().startAVDAsync(m_avdName);
272 273 274 275 276
    return true;
}

void AndroidDeployQtStep::run(QFutureInterface<bool> &fi)
{
277
    m_installOk = true;
278
    if (!m_avdName.isEmpty()) {
Daniel Teske's avatar
Daniel Teske committed
279
        QString serialNumber = AndroidConfigurations::currentConfig().waitForAvd(m_deviceAPILevel, m_targetArch, fi);
280 281
        if (serialNumber.isEmpty()) {
            fi.reportResult(false);
Daniel Teske's avatar
Daniel Teske committed
282
            emit finished();
283 284 285
            return;
        }
        m_serialNumber = serialNumber;
286 287 288 289
        AndroidManager::setDeviceSerialNumber(target(), serialNumber);
    }

    ProjectExplorer::ProcessParameters *pp = processParameters();
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    if (m_useAndroiddeployqt) {
        if (!m_serialNumber.isEmpty() && !m_serialNumber.startsWith(QLatin1String("????"))) {
            Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--device"));
            Utils::QtcProcess::addArg(&m_androiddeployqtArgs, m_serialNumber);
        }
        pp->setArguments(m_androiddeployqtArgs);
    } else {
        if (m_uninstallPreviousPackageRun) {
            emit addOutput(tr("Uninstall previous package %1.").arg(m_packageName), MessageOutput);
            runCommand(AndroidConfigurations::currentConfig().adbToolPath().toString(),
                       AndroidDeviceInfo::adbSelector(m_serialNumber)
                       << QLatin1String("uninstall") << m_packageName);
        }

        QString args;
        foreach (const QString &arg, AndroidDeviceInfo::adbSelector(m_serialNumber))
            Utils::QtcProcess::addArg(&args, arg);

        Utils::QtcProcess::addArg(&args, QLatin1String("install"));
        Utils::QtcProcess::addArg(&args, QLatin1String("-r"));
        Utils::QtcProcess::addArg(&args, m_apkPath);
        pp->setArguments(args);
    }
313 314
    pp->resolveAll();

315 316 317
    AbstractProcessStep::run(fi);

    emit addOutput(tr("Pulling files necessary for debugging."), MessageOutput);
Daniel Teske's avatar
Daniel Teske committed
318
    runCommand(AndroidConfigurations::currentConfig().adbToolPath().toString(),
319 320 321
               AndroidDeviceInfo::adbSelector(m_serialNumber)
               << QLatin1String("pull") << QLatin1String("/system/bin/app_process")
               << QString::fromLatin1("%1/app_process").arg(m_buildDirectory));
Daniel Teske's avatar
Daniel Teske committed
322
    runCommand(AndroidConfigurations::currentConfig().adbToolPath().toString(),
323 324 325 326 327 328 329 330
               AndroidDeviceInfo::adbSelector(m_serialNumber) << QLatin1String("pull")
               << QLatin1String("/system/lib/libc.so")
               << QString::fromLatin1("%1/libc.so").arg(m_buildDirectory));
}

void AndroidDeployQtStep::runCommand(const QString &program, const QStringList &arguments)
{
    QProcess buildProc;
hjk's avatar
hjk committed
331
    emit addOutput(tr("Package deploy: Running command \"%1 %2\".").arg(program).arg(arguments.join(QLatin1Char(' '))), BuildStep::MessageOutput);
332 333
    buildProc.start(program, arguments);
    if (!buildProc.waitForStarted()) {
334
        emit addOutput(tr("Packaging error: Could not start command \"%1 %2\". Reason: %3")
hjk's avatar
hjk committed
335
            .arg(program).arg(arguments.join(QLatin1Char(' '))).arg(buildProc.errorString()), BuildStep::ErrorMessageOutput);
336 337 338 339 340
        return;
    }
    if (!buildProc.waitForFinished(2 * 60 * 1000)
            || buildProc.error() != QProcess::UnknownError
            || buildProc.exitCode() != 0) {
341
        QString mainMessage = tr("Packaging Error: Command \"%1 %2\" failed.")
hjk's avatar
hjk committed
342
                .arg(program).arg(arguments.join(QLatin1Char(' ')));
343
        if (buildProc.error() != QProcess::UnknownError)
344
            mainMessage += QLatin1Char(' ') + tr("Reason: %1").arg(buildProc.errorString());
345 346 347 348 349 350
        else
            mainMessage += tr("Exit code: %1").arg(buildProc.exitCode());
        emit addOutput(mainMessage, BuildStep::ErrorMessageOutput);
    }
}

351
ProjectExplorer::BuildStepConfigWidget *AndroidDeployQtStep::createConfigWidget()
352
{
353
    return new AndroidDeployQtWidget(this);
354 355
}

356
void AndroidDeployQtStep::stdOutput(const QString &line)
357
{
358 359 360
    if (line.contains(InstallFailedInconsistentCertificatesString))
        m_installOk = false;
    AbstractProcessStep::stdOutput(line);
361 362
}

363
void AndroidDeployQtStep::stdError(const QString &line)
364
{
365 366 367
    if (line.contains(InstallFailedInconsistentCertificatesString))
        m_installOk = false;
    AbstractProcessStep::stdError(line);
368 369
}

370
bool AndroidDeployQtStep::processSucceeded(int exitCode, QProcess::ExitStatus status)
371
{
372 373 374 375
    if (!m_installOk && !m_uninstallPreviousPackageRun &&
            QMessageBox::critical(0, tr("Install failed"),
                                  tr("Another application with the same package id but signed with "
                                     "different ceritificate already exists.\n"
BogDan Vatra's avatar
BogDan Vatra committed
376
                                     "Do you want to uninstall the existing package next time?"),
377 378 379 380 381
                                  QMessageBox::Yes, QMessageBox::No)
            == QMessageBox::Yes)  {
        m_uninstallPreviousPackageTemp = true;
    }
    return m_installOk && AbstractProcessStep::processSucceeded(exitCode, status);
382 383 384 385
}

bool AndroidDeployQtStep::fromMap(const QVariantMap &map)
{
386
    m_uninstallPreviousPackage = map.value(UninstallPreviousPackageKey, false).toBool();
387 388 389 390 391 392
    return ProjectExplorer::BuildStep::fromMap(map);
}

QVariantMap AndroidDeployQtStep::toMap() const
{
    QVariantMap map = ProjectExplorer::BuildStep::toMap();
393
    map.insert(UninstallPreviousPackageKey, m_uninstallPreviousPackage);
394 395 396
    return map;
}

397
void AndroidDeployQtStep::setUninstallPreviousPackage(bool uninstall)
398
{
399
    m_uninstallPreviousPackage = uninstall;
400 401
}

402 403
bool AndroidDeployQtStep::runInGuiThread() const
{
Daniel Teske's avatar
Daniel Teske committed
404
    return true;
405 406
}

407
bool AndroidDeployQtStep::uninstallPreviousPackage()
408
{
409
    return m_uninstallPreviousPackage;
410
}