androidmanager.cpp 44.1 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

Tobias Hunger's avatar
Tobias Hunger committed
30
#include "androidmanager.h"
BogDan Vatra's avatar
BogDan Vatra committed
31 32 33 34 35 36
#include "androiddeployconfiguration.h"
#include "androidconfigurations.h"
#include "androidrunconfiguration.h"
#include "androiddeploystep.h"
#include "androidglobal.h"
#include "androidpackagecreationstep.h"
37
#include "androidtoolchain.h"
BogDan Vatra's avatar
BogDan Vatra committed
38

39
#include <coreplugin/documentmanager.h>
Tobias Hunger's avatar
Tobias Hunger committed
40 41 42
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
BogDan Vatra's avatar
BogDan Vatra committed
43 44 45 46
#include <qt4projectmanager/qt4nodes.h>
#include <qt4projectmanager/qt4project.h>
#include <qt4projectmanager/qt4projectmanagerconstants.h>
#include <qt4projectmanager/qt4buildconfiguration.h>
47
#include <qtsupport/customexecutablerunconfiguration.h>
Tobias Hunger's avatar
Tobias Hunger committed
48
#include <qtsupport/qtkitinformation.h>
Tobias Hunger's avatar
Tobias Hunger committed
49
#include <qtsupport/qtsupportconstants.h>
BogDan Vatra's avatar
BogDan Vatra committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

#include <QDir>
#include <QFileSystemWatcher>
#include <QList>
#include <QProcess>
#include <QMessageBox>
#include <QApplication>
#include <QDomDocument>

namespace {
    const QLatin1String AndroidDirName("android");
    const QLatin1String AndroidManifestName("AndroidManifest.xml");
    const QLatin1String AndroidLibsFileName("/res/values/libs.xml");
    const QLatin1String AndroidStringsFileName("/res/values/strings.xml");
    const QLatin1String AndroidDefaultPropertiesName("project.properties");
65
    const QLatin1String AndroidLibraryPrefix("--Managed_by_Qt_Creator--");
BogDan Vatra's avatar
BogDan Vatra committed
66 67 68

    QString cleanPackageName(QString packageName)
    {
69
        QRegExp legalChars(QLatin1String("[a-zA-Z0-9_\\.]"));
BogDan Vatra's avatar
BogDan Vatra committed
70 71 72 73 74

        for (int i = 0; i < packageName.length(); ++i)
            if (!legalChars.exactMatch(packageName.mid(i, 1)))
                packageName[i] = QLatin1Char('_');

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
        static QStringList keywords;
        if (keywords.isEmpty())
            keywords << QLatin1String("abstract") << QLatin1String("continue") << QLatin1String("for")
                     << QLatin1String("new") << QLatin1String("switch") << QLatin1String("assert")
                     << QLatin1String("default") << QLatin1String("if") << QLatin1String("package")
                     << QLatin1String("synchronized") << QLatin1String("boolean") << QLatin1String("do")
                     << QLatin1String("goto") << QLatin1String("private") << QLatin1String("this")
                     << QLatin1String("break") << QLatin1String("double") << QLatin1String("implements")
                     << QLatin1String("protected") << QLatin1String("throw") << QLatin1String("byte")
                     << QLatin1String("else") << QLatin1String("import") << QLatin1String("public")
                     << QLatin1String("throws") << QLatin1String("case") << QLatin1String("enum")
                     << QLatin1String("instanceof") << QLatin1String("return") << QLatin1String("transient")
                     << QLatin1String("catch") << QLatin1String("extends") << QLatin1String("int")
                     << QLatin1String("short") << QLatin1String("try") << QLatin1String("char")
                     << QLatin1String("final") << QLatin1String("interface") << QLatin1String("static")
                     << QLatin1String("void") << QLatin1String("class") << QLatin1String("finally")
                     << QLatin1String("long") << QLatin1String("strictfp") << QLatin1String("volatile")
                     << QLatin1String("const") << QLatin1String("float") << QLatin1String("native")
                     << QLatin1String("super") << QLatin1String("while");

        // No keywords
        int index = -1;
        while (index != packageName.length()) {
            int next = packageName.indexOf(QLatin1Char('.'), index + 1);
            if (next == -1)
                next = packageName.length();
            QString word = packageName.mid(index + 1, next - index - 1);
            if (!word.isEmpty()) {
                QChar c = word[0];
                if (c >= QChar(QLatin1Char('0')) && c<= QChar(QLatin1Char('9'))) {
                    packageName.insert(index + 1, QLatin1Char('_'));
                    index = next + 1;
                    continue;
                }
            }
            if (keywords.contains(word)) {
                packageName.insert(next, QLatin1String("_"));
                index = next + 1;
            } else {
                index = next;
            }
        }


BogDan Vatra's avatar
BogDan Vatra committed
119 120 121 122 123 124 125
        return packageName;
    }
} // anonymous namespace

namespace Android {
namespace Internal {

Tobias Hunger's avatar
Tobias Hunger committed
126
bool AndroidManager::supportsAndroid(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
127
{
Tobias Hunger's avatar
Tobias Hunger committed
128 129
    if (!qobject_cast<Qt4ProjectManager::Qt4Project *>(target->project()))
        return false;
Tobias Hunger's avatar
Tobias Hunger committed
130
    QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target->kit());
131
    return version && version->platformName() == QLatin1String(QtSupport::Constants::ANDROID_PLATFORM);
Tobias Hunger's avatar
Tobias Hunger committed
132
}
BogDan Vatra's avatar
BogDan Vatra committed
133

Tobias Hunger's avatar
Tobias Hunger committed
134 135 136 137 138 139 140
QString AndroidManager::packageName(ProjectExplorer::Target *target)
{
    QDomDocument doc;
    if (!openManifest(target, doc))
        return QString();
    QDomElement manifestElem = doc.documentElement();
    return manifestElem.attribute(QLatin1String("package"));
BogDan Vatra's avatar
BogDan Vatra committed
141 142
}

Tobias Hunger's avatar
Tobias Hunger committed
143
bool AndroidManager::setPackageName(ProjectExplorer::Target *target, const QString &name)
BogDan Vatra's avatar
BogDan Vatra committed
144
{
Tobias Hunger's avatar
Tobias Hunger committed
145 146 147 148 149 150
    QDomDocument doc;
    if (!openManifest(target, doc))
        return false;
    QDomElement manifestElem = doc.documentElement();
    manifestElem.setAttribute(QLatin1String("package"), cleanPackageName(name));
    return saveManifest(target, doc);
BogDan Vatra's avatar
BogDan Vatra committed
151 152
}

Tobias Hunger's avatar
Tobias Hunger committed
153
QString AndroidManager::applicationName(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
154
{
Tobias Hunger's avatar
Tobias Hunger committed
155
    QDomDocument doc;
156
    if (!openXmlFile(doc, stringsPath(target)))
Tobias Hunger's avatar
Tobias Hunger committed
157 158 159 160 161 162 163 164 165
        return QString();
    QDomElement metadataElem = doc.documentElement().firstChildElement(QLatin1String("string"));
    while (!metadataElem.isNull()) {
        if (metadataElem.attribute(QLatin1String("name")) == QLatin1String("app_name"))
            return metadataElem.text();
        metadataElem = metadataElem.nextSiblingElement(QLatin1String("string"));
    }
    return QString();
}
BogDan Vatra's avatar
BogDan Vatra committed
166

Tobias Hunger's avatar
Tobias Hunger committed
167 168 169 170
bool AndroidManager::setApplicationName(ProjectExplorer::Target *target, const QString &name)
{
    QDomDocument doc;
    Utils::FileName path = stringsPath(target);
171
    if (!openXmlFile(doc, path))
Tobias Hunger's avatar
Tobias Hunger committed
172 173 174 175 176 177 178 179 180 181 182 183
        return false;
    QDomElement metadataElem = doc.documentElement().firstChildElement(QLatin1String("string"));
    while (!metadataElem.isNull()) {
        if (metadataElem.attribute(QLatin1String("name")) == QLatin1String("app_name")) {
            metadataElem.removeChild(metadataElem.firstChild());
            metadataElem.appendChild(doc.createTextNode(name));
            break;
        }
        metadataElem = metadataElem.nextSiblingElement(QLatin1String("string"));
    }
    return saveXmlFile(target, doc, path);
}
BogDan Vatra's avatar
BogDan Vatra committed
184

Tobias Hunger's avatar
Tobias Hunger committed
185
QString AndroidManager::intentName(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
186
{
Tobias Hunger's avatar
Tobias Hunger committed
187
    return packageName(target) + QLatin1Char('/') + activityName(target);
BogDan Vatra's avatar
BogDan Vatra committed
188 189
}

Tobias Hunger's avatar
Tobias Hunger committed
190
QString AndroidManager::activityName(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
191
{
Tobias Hunger's avatar
Tobias Hunger committed
192 193 194 195 196
    QDomDocument doc;
    if (!openManifest(target, doc))
        return QString();
    QDomElement activityElem = doc.documentElement().firstChildElement(QLatin1String("application")).firstChildElement(QLatin1String("activity"));
    return activityElem.attribute(QLatin1String("android:name"));
BogDan Vatra's avatar
BogDan Vatra committed
197 198
}

199
QString AndroidManager::buildTargetSDK(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
200
{
201 202 203 204
    QVariant v = target->namedSettings(QLatin1String("AndroidManager.TargetSdk"));
    if (v.isValid())
        return v.toString();

205 206 207 208 209
    QString fallback = QLatin1String("android-8");
    if (QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(target->kit()))
        if (qt->qtVersion() >= QtSupport::QtVersionNumber(5, 0, 0))
            fallback = QLatin1String("android-9");

Tobias Hunger's avatar
Tobias Hunger committed
210
    if (!createAndroidTemplatesIfNecessary(target))
211
        return AndroidConfigurations::instance().bestMatch(fallback);
212

Tobias Hunger's avatar
Tobias Hunger committed
213 214
    QFile file(defaultPropertiesPath(target).toString());
    if (!file.open(QIODevice::ReadOnly))
215
        return AndroidConfigurations::instance().bestMatch(fallback);
Tobias Hunger's avatar
Tobias Hunger committed
216 217 218 219 220
    while (!file.atEnd()) {
        QByteArray line = file.readLine();
        if (line.startsWith("target="))
            return QString::fromLatin1(line.trimmed().mid(7));
    }
221
    return AndroidConfigurations::instance().bestMatch(fallback);
Tobias Hunger's avatar
Tobias Hunger committed
222
}
BogDan Vatra's avatar
BogDan Vatra committed
223

224
bool AndroidManager::setBuildTargetSDK(ProjectExplorer::Target *target, const QString &sdk)
Tobias Hunger's avatar
Tobias Hunger committed
225 226
{
    updateTarget(target, sdk, applicationName(target));
227
    target->setNamedSettings(QLatin1String("AndroidManager.TargetSdk"), sdk);
Tobias Hunger's avatar
Tobias Hunger committed
228 229
    return true;
}
BogDan Vatra's avatar
BogDan Vatra committed
230

231 232 233 234 235 236 237 238 239 240 241
QString AndroidManager::targetArch(ProjectExplorer::Target *target)
{
    Qt4ProjectManager::Qt4Project *pro = qobject_cast<Qt4ProjectManager::Qt4Project *>(target->project());
    if (!pro)
        return QString();
    Qt4ProjectManager::Qt4ProFileNode *node = pro->rootQt4ProjectNode();
    if (!node)
        return QString();
    return node->singleVariableValue(Qt4ProjectManager::AndroidArchVar);
}

Tobias Hunger's avatar
Tobias Hunger committed
242
Utils::FileName AndroidManager::dirPath(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
243
{
Tobias Hunger's avatar
Tobias Hunger committed
244
    return Utils::FileName::fromString(target->project()->projectDirectory()).appendPath(AndroidDirName);
BogDan Vatra's avatar
BogDan Vatra committed
245 246
}

Tobias Hunger's avatar
Tobias Hunger committed
247
Utils::FileName AndroidManager::manifestPath(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
248
{
Tobias Hunger's avatar
Tobias Hunger committed
249
    return dirPath(target).appendPath(AndroidManifestName);
BogDan Vatra's avatar
BogDan Vatra committed
250 251
}

Tobias Hunger's avatar
Tobias Hunger committed
252
Utils::FileName AndroidManager::libsPath(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
253
{
Tobias Hunger's avatar
Tobias Hunger committed
254 255
    return dirPath(target).appendPath(AndroidLibsFileName);
}
BogDan Vatra's avatar
BogDan Vatra committed
256

Tobias Hunger's avatar
Tobias Hunger committed
257 258 259
Utils::FileName AndroidManager::stringsPath(ProjectExplorer::Target *target)
{
    return dirPath(target).append(AndroidStringsFileName);
BogDan Vatra's avatar
BogDan Vatra committed
260 261
}

Tobias Hunger's avatar
Tobias Hunger committed
262
Utils::FileName AndroidManager::defaultPropertiesPath(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
263
{
Tobias Hunger's avatar
Tobias Hunger committed
264 265
    return dirPath(target).appendPath(AndroidDefaultPropertiesName);
}
BogDan Vatra's avatar
BogDan Vatra committed
266

Tobias Hunger's avatar
Tobias Hunger committed
267 268 269 270
Utils::FileName AndroidManager::srcPath(ProjectExplorer::Target *target)
{
    return dirPath(target).appendPath(QLatin1String("/src"));
}
BogDan Vatra's avatar
BogDan Vatra committed
271

Tobias Hunger's avatar
Tobias Hunger committed
272 273 274 275 276 277 278 279 280 281 282 283
Utils::FileName AndroidManager::apkPath(ProjectExplorer::Target *target, BuildType buildType)
{
    return dirPath(target)
            .appendPath(QLatin1String("bin"))
            .appendPath(QString::fromLatin1("%1-%2.apk")
                        .arg(applicationName(target))
                        .arg(buildType == DebugBuild
                             ? QLatin1String("debug")
                             : (buildType == ReleaseBuildUnsigned)
                               ? QLatin1String("release-unsigned")
                               : QLatin1String("signed")));
}
BogDan Vatra's avatar
BogDan Vatra committed
284

Tobias Hunger's avatar
Tobias Hunger committed
285 286 287 288 289 290 291 292 293 294 295
QStringList AndroidManager::availableTargetApplications(ProjectExplorer::Target *target)
{
    QStringList apps;
    Qt4ProjectManager::Qt4Project *qt4Project = qobject_cast<Qt4ProjectManager::Qt4Project *>(target->project());
    foreach (Qt4ProjectManager::Qt4ProFileNode *proFile, qt4Project->applicationProFiles()) {
        if (proFile->projectType() == Qt4ProjectManager::ApplicationTemplate) {
            if (proFile->targetInformation().target.startsWith(QLatin1String("lib"))
                    && proFile->targetInformation().target.endsWith(QLatin1String(".so")))
                apps << proFile->targetInformation().target.mid(3, proFile->targetInformation().target.lastIndexOf(QLatin1Char('.')) - 3);
            else
                apps << proFile->targetInformation().target;
BogDan Vatra's avatar
BogDan Vatra committed
296 297
        }
    }
Tobias Hunger's avatar
Tobias Hunger committed
298 299 300
    apps.sort();
    return apps;
}
BogDan Vatra's avatar
BogDan Vatra committed
301

Tobias Hunger's avatar
Tobias Hunger committed
302 303 304 305 306 307 308 309 310 311 312 313 314
QString AndroidManager::targetApplication(ProjectExplorer::Target *target)
{
    QDomDocument doc;
    if (!openManifest(target, doc))
        return QString();
    QDomElement metadataElem = doc.documentElement().firstChildElement(QLatin1String("application")).firstChildElement(QLatin1String("activity")).firstChildElement(QLatin1String("meta-data"));
    while (!metadataElem.isNull()) {
        if (metadataElem.attribute(QLatin1String("android:name")) == QLatin1String("android.app.lib_name"))
            return metadataElem.attribute(QLatin1String("android:value"));
        metadataElem = metadataElem.nextSiblingElement(QLatin1String("meta-data"));
    }
    return QString();
}
BogDan Vatra's avatar
BogDan Vatra committed
315

316 317 318 319 320 321
bool AndroidManager::bundleQt(ProjectExplorer::Target *target)
{
    ProjectExplorer::RunConfiguration *runConfiguration = target->activeRunConfiguration();
    AndroidRunConfiguration *androidRunConfiguration = qobject_cast<AndroidRunConfiguration *>(runConfiguration);
    if (androidRunConfiguration != 0) {
        AndroidDeployStep *deployStep = androidRunConfiguration->deployStep();
322
        return deployStep->deployAction() == AndroidDeployStep::BundleLibraries;
323 324 325 326 327 328
    }

    return false;
}

bool AndroidManager::updateDeploymentSettings(ProjectExplorer::Target *target)
329 330 331 332 333 334 335
{
    // For Qt 4, the "use local libs" options is handled by passing command line arguments to the
    // app, so no need to alter the AndroidManifest.xml
    QtSupport::BaseQtVersion *baseQtVersion = QtSupport::QtKitInformation::qtVersion(target->kit());
    if (baseQtVersion == 0 || baseQtVersion->qtVersion() < QtSupport::QtVersionNumber(5,0,0))
        return true;

336 337 338 339 340 341
    ProjectExplorer::RunConfiguration *runConfiguration = target->activeRunConfiguration();
    AndroidRunConfiguration *androidRunConfiguration = qobject_cast<AndroidRunConfiguration *>(runConfiguration);
    if (androidRunConfiguration == 0)
        return false;

    AndroidDeployStep *deployStep = androidRunConfiguration->deployStep();
342 343 344 345
    AndroidDeployStep::AndroidDeployAction deployAction = deployStep->deployAction();
    bool useLocalLibs = deployAction == AndroidDeployStep::DeployLocal
            || deployAction == AndroidDeployStep::BundleLibraries;
    bool bundleQtLibs = deployAction == AndroidDeployStep::BundleLibraries;
346

347 348 349 350 351 352
    QDomDocument doc;
    if (!openManifest(target, doc))
        return false;

    QDomElement metadataElem = doc.documentElement().firstChildElement(QLatin1String("application")).firstChildElement(QLatin1String("activity")).firstChildElement(QLatin1String("meta-data"));

353 354 355
    // ### Passes -1 for API level, which means it won't work with setups that require
    // library selection based on API level. Use the old approach (command line argument)
    // in these cases. Hence the Qt version > 4 condition at the beginning of this function.
356 357 358 359
    QString localLibs;
    QString localJars;
    QString staticInitClasses;
    if (useLocalLibs) {
360 361 362
        localLibs = loadLocalLibs(target, -1);
        localJars = loadLocalJars(target, -1);
        staticInitClasses = loadLocalJarsInitClasses(target, -1);
363 364 365 366 367
    }

    bool changedManifest = false;
    while (!metadataElem.isNull()) {
        if (metadataElem.attribute(QLatin1String("android:name")) == QLatin1String("android.app.use_local_qt_libs")) {
Orgad Shaneh's avatar
Orgad Shaneh committed
368
            if (metadataElem.attribute(QLatin1String("android:value")).toInt() != int(useLocalLibs)) {
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
                metadataElem.setAttribute(QLatin1String("android:value"), int(useLocalLibs));
                changedManifest = true;
            }
        } else if (metadataElem.attribute(QLatin1String("android:name")) == QLatin1String("android.app.load_local_libs")) {
            if (metadataElem.attribute(QLatin1String("android:value")) != localLibs) {
                metadataElem.setAttribute(QLatin1String("android:value"), localLibs);
                changedManifest = true;
            }
        } else if (metadataElem.attribute(QLatin1String("android:name")) == QLatin1String("android.app.load_local_jars")) {
            if (metadataElem.attribute(QLatin1String("android:value")) != localJars) {
                metadataElem.setAttribute(QLatin1String("android:value"), localJars);
                changedManifest = true;
            }
        } else if (metadataElem.attribute(QLatin1String("android:name")) == QLatin1String("android.app.static_init_classes")) {
            if (metadataElem.attribute(QLatin1String("android:value")) != staticInitClasses) {
                metadataElem.setAttribute(QLatin1String("android:value"), staticInitClasses);
                changedManifest = true;
            }
387
        } else if (metadataElem.attribute(QLatin1String("android:name")) == QLatin1String("android.app.bundle_local_qt_libs")) {
Orgad Shaneh's avatar
Orgad Shaneh committed
388
            if (metadataElem.attribute(QLatin1String("android:value")).toInt() != int(bundleQtLibs)) {
389 390 391
                metadataElem.setAttribute(QLatin1String("android:value"), int(bundleQtLibs));
                changedManifest = true;
            }
392 393 394 395 396 397 398 399 400 401 402
        }

        metadataElem = metadataElem.nextSiblingElement(QLatin1String("meta-data"));
    }

    if (changedManifest)
        return saveManifest(target, doc);
    else
        return true;
}

Tobias Hunger's avatar
Tobias Hunger committed
403 404 405 406 407 408 409 410 411 412
bool AndroidManager::setTargetApplication(ProjectExplorer::Target *target, const QString &name)
{
    QDomDocument doc;
    if (!openManifest(target, doc))
        return false;
    QDomElement metadataElem = doc.documentElement().firstChildElement(QLatin1String("application")).firstChildElement(QLatin1String("activity")).firstChildElement(QLatin1String("meta-data"));
    while (!metadataElem.isNull()) {
        if (metadataElem.attribute(QLatin1String("android:name")) == QLatin1String("android.app.lib_name")) {
            metadataElem.setAttribute(QLatin1String("android:value"), name);
            return saveManifest(target, doc);
BogDan Vatra's avatar
BogDan Vatra committed
413
        }
Tobias Hunger's avatar
Tobias Hunger committed
414
        metadataElem = metadataElem.nextSiblingElement(QLatin1String("meta-data"));
BogDan Vatra's avatar
BogDan Vatra committed
415
    }
Tobias Hunger's avatar
Tobias Hunger committed
416
    return false;
BogDan Vatra's avatar
BogDan Vatra committed
417 418
}

Tobias Hunger's avatar
Tobias Hunger committed
419
QString AndroidManager::targetApplicationPath(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
420
{
Tobias Hunger's avatar
Tobias Hunger committed
421 422 423 424 425 426 427 428 429 430
    QString selectedApp = targetApplication(target);
    if (selectedApp.isEmpty())
        return QString();
    Qt4ProjectManager::Qt4Project *qt4Project = qobject_cast<Qt4ProjectManager::Qt4Project *>(target->project());
    foreach (Qt4ProjectManager::Qt4ProFileNode *proFile, qt4Project->applicationProFiles()) {
        if (proFile->projectType() == Qt4ProjectManager::ApplicationTemplate) {
            if (proFile->targetInformation().target.startsWith(QLatin1String("lib"))
                    && proFile->targetInformation().target.endsWith(QLatin1String(".so"))) {
                if (proFile->targetInformation().target.mid(3, proFile->targetInformation().target.lastIndexOf(QLatin1Char('.')) - 3)
                        == selectedApp)
431
                    return proFile->targetInformation().buildDir + QLatin1Char('/') + proFile->targetInformation().target;
Tobias Hunger's avatar
Tobias Hunger committed
432 433 434 435 436 437 438
            } else {
                if (proFile->targetInformation().target == selectedApp)
                    return proFile->targetInformation().buildDir + QLatin1String("/lib") + proFile->targetInformation().target + QLatin1String(".so");
            }
        }
    }
    return QString();
BogDan Vatra's avatar
BogDan Vatra committed
439 440
}

Tobias Hunger's avatar
Tobias Hunger committed
441
bool AndroidManager::createAndroidTemplatesIfNecessary(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
442
{
Tobias Hunger's avatar
Tobias Hunger committed
443
    QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target->kit());
Tobias Hunger's avatar
Tobias Hunger committed
444 445 446 447 448
    Qt4ProjectManager::Qt4Project *qt4Project = qobject_cast<Qt4ProjectManager::Qt4Project*>(target->project());
    if (!qt4Project || !qt4Project->rootProjectNode() || !version)
        return false;

    Utils::FileName javaSrcPath
449
            = Utils::FileName::fromString(version->qmakeProperty("QT_INSTALL_PREFIX"))
450
            .appendPath(QLatin1String("src/android/java"));
Tobias Hunger's avatar
Tobias Hunger committed
451 452 453 454 455 456
    QDir projectDir(qt4Project->projectDirectory());
    Utils::FileName androidPath = dirPath(target);

    QStringList m_ignoreFiles;
    bool forceUpdate = false;
    QDomDocument srcVersionDoc;
457 458
    Utils::FileName srcVersionPath = javaSrcPath;
    srcVersionPath.appendPath(QLatin1String("version.xml"));
459
    if (openXmlFile(srcVersionDoc, srcVersionPath)) {
Tobias Hunger's avatar
Tobias Hunger committed
460
        QDomDocument dstVersionDoc;
461 462
        Utils::FileName dstVersionPath=androidPath;
        dstVersionPath.appendPath(QLatin1String("version.xml"));
463
        if (openXmlFile(dstVersionDoc, dstVersionPath))
Tobias Hunger's avatar
Tobias Hunger committed
464 465 466 467 468 469 470 471 472 473 474 475 476 477
            forceUpdate = (srcVersionDoc.documentElement().attribute(QLatin1String("value")).toDouble()
                           > dstVersionDoc.documentElement().attribute(QLatin1String("value")).toDouble());
        else
            forceUpdate = true;

        if (forceUpdate && androidPath.toFileInfo().exists()) {
            QDomElement ignoreFile = srcVersionDoc.documentElement().firstChildElement(QLatin1String("ignore")).firstChildElement(QLatin1String("file"));
            while (!ignoreFile.isNull()) {
                m_ignoreFiles << ignoreFile.text();
                ignoreFile = ignoreFile.nextSiblingElement();
            }
        }
    }

BogDan Vatra's avatar
BogDan Vatra committed
478
    Utils::FileName src = androidPath;
479
    src.appendPath(QLatin1String("src"));
BogDan Vatra's avatar
BogDan Vatra committed
480
    Utils::FileName res = androidPath;
481
    res.appendPath(QLatin1String("res"));
BogDan Vatra's avatar
BogDan Vatra committed
482

Tobias Hunger's avatar
Tobias Hunger committed
483 484
    if (!forceUpdate && androidPath.toFileInfo().exists()
            && manifestPath(target).toFileInfo().exists()
BogDan Vatra's avatar
BogDan Vatra committed
485 486
            && src.toFileInfo().exists()
            && res.toFileInfo().exists())
Tobias Hunger's avatar
Tobias Hunger committed
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
        return true;

    forceUpdate &= androidPath.toFileInfo().exists();

    if (!dirPath(target).toFileInfo().exists() && !projectDir.mkdir(AndroidDirName)) {
        raiseError(tr("Error creating Android directory '%1'.").arg(AndroidDirName));
        return false;
    }

    QStringList androidFiles;
    QDirIterator it(javaSrcPath.toString(), QDirIterator::Subdirectories);
    int pos = it.path().size();
    while (it.hasNext()) {
        it.next();
        if (it.fileInfo().isDir()) {
            projectDir.mkpath(AndroidDirName + it.filePath().mid(pos));
        } else {
504 505
            Utils::FileName dstFile = androidPath;
            dstFile.appendPath(it.filePath().mid(pos));
Tobias Hunger's avatar
Tobias Hunger committed
506 507 508 509 510 511 512 513 514 515 516 517
            if (m_ignoreFiles.contains(it.fileName())) {
                continue;
            } else {
                if (dstFile.toFileInfo().exists())
                    QFile::remove(dstFile.toString());
                else
                    androidFiles << dstFile.toString();
            }
            QFile::copy(it.filePath(), dstFile.toString());
        }
    }
    if (!androidFiles.isEmpty())
518
        qt4Project->rootProjectNode()->addFiles(androidFiles);
Tobias Hunger's avatar
Tobias Hunger committed
519

520 521 522 523 524 525
    int minApiLevel = 4;
    if (QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(target->kit()))
        if (qt->qtVersion() >= QtSupport::QtVersionNumber(5, 0, 0))
            minApiLevel = 9;

    QStringList sdks = AndroidConfigurations::instance().sdkTargets(minApiLevel);
Tobias Hunger's avatar
Tobias Hunger committed
526 527 528 529
    if (sdks.isEmpty()) {
        raiseError(tr("No Qt for Android SDKs were found.\nPlease install at least one SDK."));
        return false;
    }
530 531

    updateTarget(target, AndroidConfigurations::instance().sdkTargets(minApiLevel).at(0));
Tobias Hunger's avatar
Tobias Hunger committed
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
    QStringList apps = availableTargetApplications(target);
    if (!apps.isEmpty())
        setTargetApplication(target, apps.at(0));

    QString applicationName = target->project()->displayName();
    if (!applicationName.isEmpty()) {
        setPackageName(target, packageName(target) + QLatin1Char('.') + applicationName);
        applicationName[0] = applicationName[0].toUpper();
        setApplicationName(target, applicationName);
    }

    if (forceUpdate)
        QMessageBox::warning(0, tr("Warning"), tr("Android files have been updated automatically"));

    return true;
BogDan Vatra's avatar
BogDan Vatra committed
547 548
}

Tobias Hunger's avatar
Tobias Hunger committed
549
void AndroidManager::updateTarget(ProjectExplorer::Target *target, const QString &targetSDK, const QString &name)
BogDan Vatra's avatar
BogDan Vatra committed
550
{
Tobias Hunger's avatar
Tobias Hunger committed
551
    QString androidDir = dirPath(target).toString();
BogDan Vatra's avatar
BogDan Vatra committed
552

553 554 555 556
    Utils::Environment env = Utils::Environment::systemEnvironment();
    QString javaHome = AndroidConfigurations::instance().config().openJDKLocation.toString();
    if (!javaHome.isEmpty())
        env.set(QLatin1String("JAVA_HOME"), javaHome);
BogDan Vatra's avatar
BogDan Vatra committed
557 558 559
    // clean previous build
    QProcess androidProc;
    androidProc.setWorkingDirectory(androidDir);
560
    androidProc.setProcessEnvironment(env.toProcessEnvironment());
Tobias Hunger's avatar
Tobias Hunger committed
561 562
    androidProc.start(AndroidConfigurations::instance().antToolPath().toString(),
                      QStringList() << QLatin1String("clean"));
BogDan Vatra's avatar
BogDan Vatra committed
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
    if (!androidProc.waitForFinished(-1))
        androidProc.terminate();
    // clean previous build

    int targetSDKNumber = targetSDK.mid(targetSDK.lastIndexOf(QLatin1Char('-')) + 1).toInt();
    bool commentLines = false;
    QDirIterator it(androidDir, QStringList() << QLatin1String("*.java"), QDir::Files, QDirIterator::Subdirectories);
    while (it.hasNext()) {
        it.next();
        QFile file(it.filePath());
        if (!file.open(QIODevice::ReadWrite))
            continue;
        QList<QByteArray> lines = file.readAll().trimmed().split('\n');

        bool modified = false;
        bool comment = false;
        for (int i = 0; i < lines.size(); i++) {
580 581 582
            QByteArray trimmed = lines[i].trimmed();
            if (trimmed.contains("@ANDROID-")) {
                commentLines = targetSDKNumber < trimmed.mid(trimmed.lastIndexOf('-') + 1).toInt();
BogDan Vatra's avatar
BogDan Vatra committed
583 584 585 586 587 588
                comment = !comment;
                continue;
            }
            if (!comment)
                continue;
            if (commentLines) {
589
                if (!trimmed.startsWith("//QtCreator")) {
BogDan Vatra's avatar
BogDan Vatra committed
590 591 592
                    lines[i] = "//QtCreator " + lines[i];
                    modified = true;
                }
593
            } else { if (trimmed.startsWith("//QtCreator")) {
BogDan Vatra's avatar
BogDan Vatra committed
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
                    lines[i] = lines[i].mid(12);
                    modified = true;
                }
            }
        }
        if (modified) {
            file.resize(0);
            foreach (const QByteArray &line, lines) {
                file.write(line);
                file.write("\n");
            }
        }
        file.close();
    }

    QStringList params;
    params << QLatin1String("update") << QLatin1String("project") << QLatin1String("-p") << androidDir;
    if (!targetSDK.isEmpty())
        params << QLatin1String("-t") << targetSDK;
    if (!name.isEmpty())
        params << QLatin1String("-n") << name;
Tobias Hunger's avatar
Tobias Hunger committed
615
    androidProc.start(AndroidConfigurations::instance().androidToolPath().toString(), params);
BogDan Vatra's avatar
BogDan Vatra committed
616 617 618 619
    if (!androidProc.waitForFinished(-1))
        androidProc.terminate();
}

Tobias Hunger's avatar
Tobias Hunger committed
620
Utils::FileName AndroidManager::localLibsRulesFilePath(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
621
{
Tobias Hunger's avatar
Tobias Hunger committed
622
    QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target->kit());
Tobias Hunger's avatar
Tobias Hunger committed
623 624
    if (!version)
        return Utils::FileName();
625
    return Utils::FileName::fromString(version->qmakeProperty("QT_INSTALL_LIBS"));
Tobias Hunger's avatar
Tobias Hunger committed
626
}
BogDan Vatra's avatar
BogDan Vatra committed
627

Tobias Hunger's avatar
Tobias Hunger committed
628 629 630 631
QString AndroidManager::loadLocalLibs(ProjectExplorer::Target *target, int apiLevel)
{
    return loadLocal(target, apiLevel, Lib);
}
BogDan Vatra's avatar
BogDan Vatra committed
632

633 634 635 636 637
QString AndroidManager::loadLocalBundledFiles(ProjectExplorer::Target *target, int apiLevel)
{
    return loadLocal(target, apiLevel, BundledFile);
}

Tobias Hunger's avatar
Tobias Hunger committed
638 639
QString AndroidManager::loadLocalJars(ProjectExplorer::Target *target, int apiLevel)
{
640 641
    ItemType type = bundleQt(target) ? BundledJar : Jar;
    return loadLocal(target, apiLevel, type);
Tobias Hunger's avatar
Tobias Hunger committed
642
}
BogDan Vatra's avatar
BogDan Vatra committed
643

644 645
QString AndroidManager::loadLocalJarsInitClasses(ProjectExplorer::Target *target, int apiLevel)
{
646 647
    ItemType type = bundleQt(target) ? BundledJar : Jar;
    return loadLocal(target, apiLevel, type, QLatin1String("initClass"));
648 649
}

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
QPair<int, int> AndroidManager::apiLevelRange(ProjectExplorer::Target *target)
{
    // 4 is the minimum version on which qt is supported
    // 19 and 20 are not yet released, but allow the user
    // to set them
    int minApiLevel = 4;
    QtSupport::BaseQtVersion *qt;
    if (target && (qt = QtSupport::QtKitInformation::qtVersion(target->kit())))
        if (qt->qtVersion() >= QtSupport::QtVersionNumber(5, 0, 0))
            minApiLevel = 9;
    return qMakePair(minApiLevel, 20);
}

QString AndroidManager::androidNameForApiLevel(int x)
{
    switch (x) {
    case 4:
        return QLatin1String("Android 1.6");
    case 5:
        return QLatin1String("Android 2.0");
    case 6:
        return QLatin1String("Android 2.0.1");
    case 7:
        return QLatin1String("Android 2.1.x");
    case 8:
        return QLatin1String("Android 2.2.x");
    case 9:
        return QLatin1String("Android 2.3, 2.3.1, 2.3.2");
    case 10:
        return QLatin1String("Android 2.3.3, 2.3.4");
    case 11:
        return QLatin1String("Android 3.0.x");
    case 12:
        return QLatin1String("Android 3.1.x");
    case 13:
        return QLatin1String("Android 3.2");
    case 14:
        return QLatin1String("Android 4.0, 4.0.1, 4.0.2");
    case 15:
        return QLatin1String("Android 4.0.3, 4.0.4");
    case 16:
        return QLatin1String("Android 4.1, 4.1.1");
    case 17:
        return QLatin1String("Android 4.2, 4.2.2");
    case 18:
        return QLatin1String("Android 4.3");
    default:
        return QLatin1String("Unknown Android version.");
    }
}

701
QVector<AndroidManager::Library> AndroidManager::availableQtLibsWithDependencies(ProjectExplorer::Target *target)
Tobias Hunger's avatar
Tobias Hunger committed
702
{
Tobias Hunger's avatar
Tobias Hunger committed
703
    QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target->kit());
Tobias Hunger's avatar
Tobias Hunger committed
704
    if (!target->activeRunConfiguration())
705
        return QVector<AndroidManager::Library>();
Tobias Hunger's avatar
Tobias Hunger committed
706

707 708
    ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(target->kit());
    if (tc->type() != QLatin1String(Constants::ANDROID_TOOLCHAIN_TYPE))
709
        return QVector<AndroidManager::Library>();
710 711 712 713

    Qt4ProjectManager::Qt4Project *project = static_cast<Qt4ProjectManager::Qt4Project *>(target->project());
    QString arch = project->rootQt4ProjectNode()->singleVariableValue(Qt4ProjectManager::AndroidArchVar);

714
    AndroidToolChain *atc = static_cast<AndroidToolChain *>(tc);
715
    QString libgnustl = libGnuStl(arch, atc->ndkToolChainVersion());
716 717 718

    Utils::FileName readelfPath = AndroidConfigurations::instance().readelfPath(target->activeRunConfiguration()->abi().architecture(),
                                                                                atc->ndkToolChainVersion());
Tobias Hunger's avatar
Tobias Hunger committed
719 720 721
    const Qt4ProjectManager::Qt4Project *const qt4Project
            = qobject_cast<const Qt4ProjectManager::Qt4Project *>(target->project());
    if (!qt4Project || !version)
722
        return QVector<AndroidManager::Library>();
723
    QString qtLibsPath = version->qmakeProperty("QT_INSTALL_LIBS");
Tobias Hunger's avatar
Tobias Hunger committed
724
    if (!readelfPath.toFileInfo().exists()) {
725
        return QVector<AndroidManager::Library>();
BogDan Vatra's avatar
BogDan Vatra committed
726
    }
Tobias Hunger's avatar
Tobias Hunger committed
727 728 729 730 731 732 733
    LibrariesMap mapLibs;
    QDir libPath;
    QDirIterator it(qtLibsPath, QStringList() << QLatin1String("*.so"), QDir::Files, QDirIterator::Subdirectories);
    while (it.hasNext()) {
        libPath = it.next();
        const QString library = libPath.absolutePath().mid(libPath.absolutePath().lastIndexOf(QLatin1Char('/')) + 1);
        mapLibs[library].dependencies = dependencies(readelfPath, libPath.absolutePath());
BogDan Vatra's avatar
BogDan Vatra committed
734 735
    }

736 737 738
    const QString library = libgnustl.mid(libgnustl.lastIndexOf(QLatin1Char('/')) + 1);
    mapLibs[library] = Library();;

Tobias Hunger's avatar
Tobias Hunger committed
739
    // clean dependencies
740 741 742
    const LibrariesMap::Iterator lend = mapLibs.end();
    for (LibrariesMap::Iterator lit = mapLibs.begin(); lit != lend; ++lit) {
        Library &library = lit.value();
Tobias Hunger's avatar
Tobias Hunger committed
743
        int it = 0;
744 745 746 747
        while (it < library.dependencies.size()) {
            const QString &dependName = library.dependencies[it];
            if (!mapLibs.contains(dependName) && dependName.startsWith(QLatin1String("lib")) && dependName.endsWith(QLatin1String(".so")))
                library.dependencies.removeAt(it);
748
            else
Tobias Hunger's avatar
Tobias Hunger committed
749
                ++it;
BogDan Vatra's avatar
BogDan Vatra committed
750
        }
751 752
        if (library.dependencies.isEmpty())
            library.level = 0;
BogDan Vatra's avatar
BogDan Vatra committed
753 754
    }

Tobias Hunger's avatar
Tobias Hunger committed
755 756
    QVector<Library> qtLibraries;
    // calculate the level for every library
757 758 759 760
    for (LibrariesMap::Iterator lit = mapLibs.begin(); lit != lend; ++lit) {
        Library &library = lit.value();
        const QString &key = lit.key();
        if (library.level < 0)
Tobias Hunger's avatar
Tobias Hunger committed
761
           setLibraryLevel(key, mapLibs);
BogDan Vatra's avatar
BogDan Vatra committed
762

763 764
        if (library.name.isEmpty() && key.startsWith(QLatin1String("lib")) && key.endsWith(QLatin1String(".so")))
            library.name = key.mid(3, key.length() - 6);
BogDan Vatra's avatar
BogDan Vatra committed
765

766 767
        for (int it = 0; it < library.dependencies.size(); it++) {
            const QString &libName = library.dependencies[it];
Tobias Hunger's avatar
Tobias Hunger committed
768
            if (libName.startsWith(QLatin1String("lib")) && libName.endsWith(QLatin1String(".so")))
769
                library.dependencies[it] = libName.mid(3, libName.length() - 6);
Tobias Hunger's avatar
Tobias Hunger committed
770
        }
771
        qtLibraries.push_back(library);
BogDan Vatra's avatar
BogDan Vatra committed
772
    }
Tobias Hunger's avatar
Tobias Hunger committed
773
    qSort(qtLibraries.begin(), qtLibraries.end(), qtLibrariesLessThan);
774 775 776 777 778 779 780 781 782 783

    return qtLibraries;

}

QStringList AndroidManager::availableQtLibs(ProjectExplorer::Target *target)
{
    QStringList libs;
    QVector<Library> qtLibraries = availableQtLibsWithDependencies(target);
    foreach (Library lib, qtLibraries)
Tobias Hunger's avatar
Tobias Hunger committed
784 785
        libs.push_back(lib.name);
    return libs;
BogDan Vatra's avatar
BogDan Vatra committed
786 787
}

Tobias Hunger's avatar
Tobias Hunger committed
788
QStringList AndroidManager::qtLibs(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
789
{
Tobias Hunger's avatar
Tobias Hunger committed
790
    return libsXml(target, QLatin1String("qt_libs"));
BogDan Vatra's avatar
BogDan Vatra committed
791 792
}

Tobias Hunger's avatar
Tobias Hunger committed
793
bool AndroidManager::setQtLibs(ProjectExplorer::Target *target, const QStringList &libs)
BogDan Vatra's avatar
BogDan Vatra committed
794
{
Tobias Hunger's avatar
Tobias Hunger committed
795
    return setLibsXml(target, libs, QLatin1String("qt_libs"));
BogDan Vatra's avatar
BogDan Vatra committed
796 797
}

798 799 800 801 802 803 804 805 806 807
bool AndroidManager::setBundledInAssets(ProjectExplorer::Target *target, const QStringList &fileList)
{
    return setLibsXml(target, fileList, QLatin1String("bundled_in_assets"));
}

bool AndroidManager::setBundledInLib(ProjectExplorer::Target *target, const QStringList &fileList)
{
    return setLibsXml(target, fileList, QLatin1String("bundled_in_lib"));
}

Tobias Hunger's avatar
Tobias Hunger committed
808
QStringList AndroidManager::availablePrebundledLibs(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
809
{
Tobias Hunger's avatar
Tobias Hunger committed
810 811 812 813
    QStringList libs;
    Qt4ProjectManager::Qt4Project *qt4Project = qobject_cast<Qt4ProjectManager::Qt4Project *>(target->project());
    if (!qt4Project)
        return libs;
BogDan Vatra's avatar
BogDan Vatra committed
814

Tobias Hunger's avatar
Tobias Hunger committed
815 816
    foreach (Qt4ProjectManager::Qt4ProFileNode *node, qt4Project->allProFiles())
        if (node->projectType() == Qt4ProjectManager::LibraryTemplate)
817
            libs << node->targetInformation().target;
Tobias Hunger's avatar
Tobias Hunger committed
818
    return libs;
BogDan Vatra's avatar
BogDan Vatra committed
819 820
}

Tobias Hunger's avatar
Tobias Hunger committed
821
QStringList AndroidManager::prebundledLibs(ProjectExplorer::Target *target)
BogDan Vatra's avatar
BogDan Vatra committed
822
{
Tobias Hunger's avatar
Tobias Hunger committed
823
    return libsXml(target, QLatin1String("bundled_libs"));
BogDan Vatra's avatar
BogDan Vatra committed
824 825
}

Tobias Hunger's avatar
Tobias Hunger committed
826
bool AndroidManager::setPrebundledLibs(ProjectExplorer::Target *target, const QStringList &libs)
BogDan Vatra's avatar
BogDan Vatra committed
827
{
Tobias Hunger's avatar
Tobias Hunger committed
828
    return setLibsXml(target, libs, QLatin1String("bundled_libs"));
BogDan Vatra's avatar
BogDan Vatra committed
829 830
}

Tobias Hunger's avatar
Tobias Hunger committed
831
bool AndroidManager::openLibsXml(ProjectExplorer::Target *target, QDomDocument &doc)
BogDan Vatra's avatar
BogDan Vatra committed
832
{
833
    return openXmlFile(doc, libsPath(target));
BogDan Vatra's avatar
BogDan Vatra committed
834 835
}

Tobias Hunger's avatar
Tobias Hunger committed
836
bool AndroidManager::saveLibsXml(ProjectExplorer::Target *target, QDomDocument &doc)
BogDan Vatra's avatar
BogDan Vatra committed
837
{
Tobias Hunger's avatar
Tobias Hunger committed
838
    return saveXmlFile(target, doc, libsPath(target));
BogDan Vatra's avatar
BogDan Vatra committed
839 840
}

Tobias Hunger's avatar
Tobias Hunger committed
841
void AndroidManager::raiseError(const QString &reason)
BogDan Vatra's avatar
BogDan Vatra committed
842
{
Tobias Hunger's avatar
Tobias Hunger committed
843
    QMessageBox::critical(0, tr("Error creating Android templates"), reason);
BogDan Vatra's avatar
BogDan Vatra committed
844 845
}

846
QString AndroidManager::loadLocal(ProjectExplorer::Target *target, int apiLevel, ItemType item, const QString &attribute)
BogDan Vatra's avatar
BogDan Vatra committed
847
{
Tobias Hunger's avatar
Tobias Hunger committed
848 849 850
    QString itemType;
    if (item == Lib)
        itemType = QLatin1String("lib");
851 852 853
    else if (item == BundledFile)
        itemType = QLatin1String("bundled");
    else // Jar or BundledJar
Tobias Hunger's avatar
Tobias Hunger committed
854 855 856
        itemType = QLatin1String("jar");

    QString localLibs;
BogDan Vatra's avatar
BogDan Vatra committed
857

858 859
    QDir rulesFilesDir(localLibsRulesFilePath(target).toString());
    if (!rulesFilesDir.exists())
Tobias Hunger's avatar
Tobias Hunger committed
860 861 862 863
        return localLibs;

    QStringList libs;
    libs << qtLibs(target) << prebundledLibs(target);
864 865 866 867 868 869 870 871 872 873

    QFileInfoList rulesFiles = rulesFilesDir.entryInfoList(QStringList() << QLatin1String("*.xml"),
                                                           QDir::Files | QDir::Readable);

    QStringList dependencyLibs;
    QStringList replacedLibs;
    foreach (QFileInfo rulesFile, rulesFiles) {
        if (rulesFile.baseName() != QLatin1String("rules")
                && !rulesFile.baseName().endsWith(QLatin1String("-android-dependencies"))) {
            continue;
BogDan Vatra's avatar
BogDan Vatra committed
874 875
        }

876 877 878 879 880 881 882 883 884 885
        QDomDocument doc;
        if (!openXmlFile(doc, Utils::FileName::fromString(rulesFile.absoluteFilePath())))
            return localLibs;

        QDomElement element = doc.documentElement().firstChildElement(QLatin1String("platforms")).firstChildElement(itemType + QLatin1Char('s')).firstChildElement(QLatin1String("version"));
        while (!element.isNull()) {
            if (element.attribute(QLatin1String("value")).toInt() == apiLevel) {
                if (element.hasAttribute(QLatin1String("symlink")))
                    apiLevel = element.attribute(QLatin1String("symlink")).toInt();
                break;
Tobias Hunger's avatar
Tobias Hunger committed
886
            }
887 888 889 890 891 892 893 894
            element = element.nextSiblingElement(QLatin1String("version"));
        }

        element = doc.documentElement().firstChildElement(QLatin1String("dependencies")).firstChildElement(QLatin1String("lib"));
        while (!element.isNull()) {
            if (libs.contains(element.attribute(QLatin1String("name")))) {
                QDomElement libElement = element.firstChildElement(QLatin1String("depends")).firstChildElement(itemType);
                while (!libElement.isNull()) {
895 896 897
                    if (libElement.attribute(QLatin1String("bundling")).toInt() == (item == BundledJar ? 1 : 0)) {
                        if (libElement.hasAttribute(attribute)) {
                            QString dependencyLib = libElement.attribute(attribute).arg(apiLevel);
898 899 900 901 902 903
                            if (libElement.hasAttribute(QLatin1String("extends"))) {
                                const QString extends = libElement.attribute(QLatin1String("extends"));
                                if (libs.contains(extends)) {
                                    dependencyLibs << dependencyLib;
                                }
                            } else if (!dependencyLibs.contains(dependencyLib)) {
904
                                dependencyLibs << dependencyLib;
905
                            }
906 907 908 909 910 911 912
                        }

                        if (libElement.hasAttribute(QLatin1String("replaces"))) {
                            QString replacedLib = libElement.attribute(QLatin1String("replaces")).arg(apiLevel);
                            if (!replacedLibs.contains(replacedLib))
                                replacedLibs << replacedLib;
                        }
913 914 915 916 917 918 919 920 921 922 923 924
                    }

                    libElement = libElement.nextSiblingElement(itemType);
                }

                libElement = element.firstChildElement(QLatin1String("replaces")).firstChildElement(itemType);
                while (!libElement.isNull()) {
                    if (libElement.hasAttribute(attribute)) {
                        QString replacedLib = libElement.attribute(attribute).arg(apiLevel);
                        if (!replacedLibs.contains(replacedLib))
                            replacedLibs << replacedLib;
                    }
Tobias Hunger's avatar
Tobias Hunger committed
925

926 927
                    libElement = libElement.nextSiblingElement(itemType);
                }
BogDan Vatra's avatar
BogDan Vatra committed
928
            }
929
            element = element.nextSiblingElement(QLatin1String("lib"));
BogDan Vatra's avatar
BogDan Vatra committed
930 931
        }
    }
932 933 934

    // The next loop requires all library names to end with a ":" so we append one
    // to the end after joining.
Robert Loehning's avatar
Robert Loehning committed
935
    localLibs = dependencyLibs.join(QLatin1String(":")) + QLatin1Char(':');
936 937 938
    foreach (QString replacedLib, replacedLibs)
        localLibs.remove(replacedLib + QLatin1Char(':'));

Tobias Hunger's avatar
Tobias Hunger committed
939
    return localLibs;
BogDan Vatra's avatar
BogDan Vatra committed
940 941
}

942
bool AndroidManager::openXmlFile(QDomDocument &doc, const Utils::FileName &fileName)
BogDan Vatra's avatar
BogDan Vatra committed
943
{
Tobias Hunger's avatar
Tobias Hunger committed
944 945
    QFile f(fileName.toString());
    if (!f.open(QIODevice::ReadOnly))
BogDan Vatra's avatar
BogDan Vatra committed
946 947
        return false;

Tobias Hunger's avatar
Tobias Hunger committed
948 949
    if (!doc.setContent(f.readAll())) {
        raiseError(tr("Can't parse '%1'").arg(fileName.toUserOutput()));
BogDan Vatra's avatar
BogDan Vatra committed
950 951
        return false;
    }
Tobias Hunger's avatar
Tobias Hunger committed
952
    return true;
BogDan Vatra's avatar
BogDan Vatra committed
953 954
}

Tobias Hunger's avatar
Tobias Hunger committed
955
bool AndroidManager::saveXmlFile(ProjectExplorer::Target *target, QDomDocument &doc, const Utils::FileName &fileName)
BogDan Vatra's avatar
BogDan Vatra committed
956
{
Tobias Hunger's avatar
Tobias Hunger committed
957 958
    if (!createAndroidTemplatesIfNecessary(target))
        return false;
BogDan Vatra's avatar
BogDan Vatra committed
959

Tobias Hunger's avatar
Tobias Hunger committed
960 961 962 963
    QFile f(fileName.toString());
    if (!f.open(QIODevice::WriteOnly)) {
        raiseError(tr("Can't open '%1'").arg(fileName.toUserOutput()));
        return false;
BogDan Vatra's avatar
BogDan Vatra committed
964
    }
Tobias Hunger's avatar
Tobias Hunger committed
965
    return f.write(doc.toByteArray(4)) >= 0;
BogDan Vatra's avatar
BogDan Vatra committed
966 967
}

Tobias Hunger's avatar
Tobias Hunger committed
968
bool AndroidManager::openManifest(ProjectExplorer::Target *target, QDomDocument &doc)
BogDan Vatra's avatar
BogDan Vatra committed
969
{
970
    return openXmlFile(doc, manifestPath(target));
BogDan Vatra's avatar
BogDan Vatra committed
971 972
}

Tobias Hunger's avatar
Tobias Hunger committed
973
bool AndroidManager::saveManifest(ProjectExplorer::Target *target, QDomDocument &doc)
BogDan Vatra's avatar
BogDan Vatra committed
974
{
975
    Core::FileChangeBlocker blocker(manifestPath(target).toString());
Tobias Hunger's avatar
Tobias Hunger committed
976
    return saveXmlFile(target, doc, manifestPath(target));
BogDan Vatra's avatar
BogDan Vatra committed
977 978
}

Tobias Hunger's avatar
Tobias Hunger committed
979
QStringList AndroidManager::libsXml(ProjectExplorer::Target *target, const QString &tag)
BogDan Vatra's avatar
BogDan Vatra committed
980 981 982
{
    QStringList libs;
    QDomDocument doc;
Tobias Hunger's avatar
Tobias Hunger committed
983
    if (!openLibsXml(target, doc))
BogDan Vatra's avatar
BogDan Vatra committed
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
        return libs;
    QDomElement arrayElem = doc.documentElement().firstChildElement(QLatin1String("array"));
    while (!arrayElem.isNull()) {
        if (arrayElem.attribute(QLatin1String("name")) == tag) {
            arrayElem = arrayElem.firstChildElement(QLatin1String("item"));
            while (!arrayElem.isNull()) {
                libs << arrayElem.text();
                arrayElem = arrayElem.nextSiblingElement(QLatin1String("item"));
            }
            return libs;
        }
        arrayElem = arrayElem.nextSiblingElement(QLatin1String("array"));
    }
    return libs;
}

Tobias Hunger's avatar
Tobias Hunger committed
1000
bool AndroidManager::setLibsXml(ProjectExplorer::Target *target, const QStringList &libs, const QString &tag)
BogDan Vatra's avatar
BogDan Vatra committed
1001 1002
{
    QDomDocument doc;
Tobias Hunger's avatar
Tobias Hunger committed
1003
    if (!openLibsXml(target, doc))
BogDan Vatra's avatar
BogDan Vatra committed
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
        return false;
    QDomElement arrayElem = doc.documentElement().firstChildElement(QLatin1String("array"));
    while (!arrayElem.isNull()) {
        if (arrayElem.attribute(QLatin1String("name")) == tag) {
            doc.documentElement().removeChild(arrayElem);
            arrayElem = doc.createElement(QLatin1String("array"));
            arrayElem.setAttribute(QLatin1String("name"), tag);
            foreach (const QString &lib, libs) {
                QDomElement item = doc.createElement(QLatin1String("item"));
                item.appendChild(doc.createTextNode(lib));
                arrayElem.appendChild(item);
            }
            doc.documentElement().appendChild(arrayElem);
Tobias Hunger's avatar
Tobias Hunger committed
1017
            return saveLibsXml(target, doc);
BogDan Vatra's avatar
BogDan Vatra committed
1018 1019 1020 1021