summaryrefslogtreecommitdiff
path: root/src/plugins/android/androidsettingswidget.cpp
blob: 5cdf42cdf3c593b2708725194934d4fe8c58c695 (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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
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
/****************************************************************************
**
** Copyright (C) 2016 BogDan Vatra <bog_dan_ro@yahoo.com>
** 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 "androidsettingswidget.h"

#include "ui_androidsettingswidget.h"

#include "androidconfigurations.h"
#include "androidconstants.h"
#include "androidtoolchain.h"

#include <utils/environment.h>
#include <utils/hostosinfo.h>
#include <utils/pathchooser.h>
#include <utils/runextensions.h>
#include <utils/utilsicons.h>
#include <projectexplorer/toolchainmanager.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtversionmanager.h>

#include <QFile>
#include <QTextStream>
#include <QProcess>
#include <QTimer>
#include <QTime>

#include <QDesktopServices>
#include <QFileDialog>
#include <QMessageBox>
#include <QModelIndex>
#include <QtCore/QUrl>

namespace Android {
namespace Internal {

void AvdModel::setAvdList(const QVector<AndroidDeviceInfo> &list)
{
    beginResetModel();
    m_list = list;
    endResetModel();
}

QModelIndex AvdModel::indexForAvdName(const QString &avdName) const
{
    for (int i = 0; i < m_list.size(); ++i) {
        if (m_list.at(i).serialNumber == avdName)
            return index(i, 0);
    }
    return QModelIndex();
}

QString AvdModel::avdName(const QModelIndex &index) const
{
    return m_list.at(index.row()).avdname;
}

QVariant AvdModel::data(const QModelIndex &index, int role) const
{
    if (role != Qt::DisplayRole || !index.isValid())
        return QVariant();
    switch (index.column()) {
        case 0:
            return m_list[index.row()].avdname;
        case 1:
            return QString::fromLatin1("API %1").arg(m_list[index.row()].sdk);
        case 2: {
            QStringList cpuAbis = m_list[index.row()].cpuAbi;
            return cpuAbis.isEmpty() ? QVariant() : QVariant(cpuAbis.first());
        }
    }
    return QVariant();
}

QVariant AvdModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
            case 0:
                //: AVD - Android Virtual Device
                return tr("AVD Name");
            case 1:
                return tr("AVD Target");
            case 2:
                return tr("CPU/ABI");
        }
    }
    return QAbstractItemModel::headerData(section, orientation, role );
}

int AvdModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_list.size();
}

int AvdModel::columnCount(const QModelIndex &/*parent*/) const
{
    return 3;
}

AndroidSettingsWidget::AndroidSettingsWidget(QWidget *parent)
    : QWidget(parent),
      m_sdkState(NotSet),
      m_ndkState(NotSet),
      m_javaState(NotSet),
      m_ui(new Ui_AndroidSettingsWidget),
      m_androidConfig(AndroidConfigurations::currentConfig())
{
    m_ui->setupUi(this);

    connect(&m_checkGdbWatcher, &QFutureWatcherBase::finished,
            this, &AndroidSettingsWidget::checkGdbFinished);

    m_ui->SDKLocationPathChooser->setFileName(m_androidConfig.sdkLocation());
    m_ui->SDKLocationPathChooser->setPromptDialogTitle(tr("Select Android SDK folder"));
    m_ui->NDKLocationPathChooser->setFileName(m_androidConfig.ndkLocation());
    m_ui->NDKLocationPathChooser->setPromptDialogTitle(tr("Select Android NDK folder"));

    QString dir;
    QString filter;
    if (Utils::HostOsInfo::isWindowsHost()) {
        dir = QDir::homePath() + QLatin1String("/ant.bat");
        filter = QLatin1String("ant (ant.bat)");
    } else if (Utils::HostOsInfo::isMacHost()) {
        // work around QTBUG-7739 that prohibits filters that don't start with *
        dir = QLatin1String("/usr/bin/ant");
        filter = QLatin1String("ant (*ant)");
    } else {
        dir = QLatin1String("/usr/bin/ant");
        filter = QLatin1String("ant (ant)");
    }
    m_ui->AntLocationPathChooser->setFileName(m_androidConfig.antLocation());
    m_ui->AntLocationPathChooser->setExpectedKind(Utils::PathChooser::Command);
    m_ui->AntLocationPathChooser->setPromptDialogTitle(tr("Select ant Script"));
    m_ui->AntLocationPathChooser->setInitialBrowsePathBackup(dir);
    m_ui->AntLocationPathChooser->setPromptDialogFilter(filter);
    m_ui->UseGradleCheckBox->setChecked(m_androidConfig.useGrandle());

    m_ui->OpenJDKLocationPathChooser->setFileName(m_androidConfig.openJDKLocation());
    m_ui->OpenJDKLocationPathChooser->setPromptDialogTitle(tr("Select JDK Path"));
    m_ui->DataPartitionSizeSpinBox->setValue(m_androidConfig.partitionSize());
    m_ui->CreateKitCheckBox->setChecked(m_androidConfig.automaticKitCreation());
    m_ui->AVDTableView->setModel(&m_AVDModel);
    m_ui->AVDTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    m_ui->AVDTableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);

    m_ui->downloadAntToolButton->setVisible(!Utils::HostOsInfo::isLinuxHost());
    m_ui->downloadOpenJDKToolButton->setVisible(!Utils::HostOsInfo::isLinuxHost());

    const QPixmap warningPixmap = Utils::Icons::WARNING.pixmap();
    m_ui->jdkWarningIconLabel->setPixmap(warningPixmap);
    m_ui->kitWarningIconLabel->setPixmap(warningPixmap);

    const QPixmap errorPixmap = Utils::Icons::CRITICAL.pixmap();
    m_ui->sdkWarningIconLabel->setPixmap(errorPixmap);
    m_ui->gdbWarningIconLabel->setPixmap(errorPixmap);
    m_ui->ndkWarningIconLabel->setPixmap(errorPixmap);

    connect(m_ui->gdbWarningLabel, &QLabel::linkActivated,
            this, &AndroidSettingsWidget::showGdbWarningDialog);

    connect(&m_virtualDevicesWatcher, &QFutureWatcherBase::finished,
            this, &AndroidSettingsWidget::updateAvds);

    check(All);
    applyToUi(All);

    connect(&m_futureWatcher, &QFutureWatcherBase::finished,
            this, &AndroidSettingsWidget::avdAdded);

    connect(m_ui->NDKLocationPathChooser, &Utils::PathChooser::rawPathChanged,
            this, &AndroidSettingsWidget::ndkLocationEditingFinished);
    connect(m_ui->SDKLocationPathChooser, &Utils::PathChooser::rawPathChanged,
            this, &AndroidSettingsWidget::sdkLocationEditingFinished);
    connect(m_ui->AntLocationPathChooser, &Utils::PathChooser::rawPathChanged,
            this, &AndroidSettingsWidget::antLocationEditingFinished);
    connect(m_ui->OpenJDKLocationPathChooser, &Utils::PathChooser::rawPathChanged,
            this, &AndroidSettingsWidget::openJDKLocationEditingFinished);
    connect(m_ui->AVDAddPushButton, &QAbstractButton::clicked,
            this, &AndroidSettingsWidget::addAVD);
    connect(m_ui->AVDRemovePushButton, &QAbstractButton::clicked,
            this, &AndroidSettingsWidget::removeAVD);
    connect(m_ui->AVDStartPushButton, &QAbstractButton::clicked,
            this, &AndroidSettingsWidget::startAVD);
    connect(m_ui->AVDTableView, &QAbstractItemView::activated,
            this, &AndroidSettingsWidget::avdActivated);
    connect(m_ui->AVDTableView, &QAbstractItemView::clicked,
            this, &AndroidSettingsWidget::avdActivated);
    connect(m_ui->DataPartitionSizeSpinBox, &QAbstractSpinBox::editingFinished,
            this, &AndroidSettingsWidget::dataPartitionSizeEditingFinished);
    connect(m_ui->manageAVDPushButton, &QAbstractButton::clicked,
            this, &AndroidSettingsWidget::manageAVD);
    connect(m_ui->CreateKitCheckBox, &QAbstractButton::toggled,
            this, &AndroidSettingsWidget::createKitToggled);
    connect(m_ui->downloadSDKToolButton, &QAbstractButton::clicked,
            this, &AndroidSettingsWidget::openSDKDownloadUrl);
    connect(m_ui->downloadNDKToolButton, &QAbstractButton::clicked,
            this, &AndroidSettingsWidget::openNDKDownloadUrl);
    connect(m_ui->downloadAntToolButton, &QAbstractButton::clicked,
            this, &AndroidSettingsWidget::openAntDownloadUrl);
    connect(m_ui->downloadOpenJDKToolButton, &QAbstractButton::clicked,
            this, &AndroidSettingsWidget::openOpenJDKDownloadUrl);
    connect(m_ui->UseGradleCheckBox, &QAbstractButton::toggled,
            this, &AndroidSettingsWidget::useGradleToggled);

}

AndroidSettingsWidget::~AndroidSettingsWidget()
{
    delete m_ui;
    m_futureWatcher.waitForFinished();
}

// NOTE: Will be run via QFuture
static QPair<QStringList, bool> checkGdbForBrokenPython(const QStringList &paths)
{
    foreach (const QString &path, paths) {
        QTime timer;
        timer.start();
        QProcess proc;
        proc.setProcessChannelMode(QProcess::MergedChannels);
        proc.start(path);
        proc.waitForStarted();

        QByteArray output;
        while (proc.waitForReadyRead(300)) {
            output += proc.readAll();
            if (output.contains("(gdb)"))
                break;
            if (timer.elapsed() > 7 * 1000)
                return qMakePair(paths, true); // Took too long, abort
        }

        output.clear();

        proc.write("python import string\n");
        proc.write("python print(string.ascii_uppercase)\n");
        proc.write("python import struct\n");
        proc.write("quit\n");
        while (proc.waitForFinished(300)) {
            if (timer.elapsed() > 9 * 1000)
                return qMakePair(paths, true); // Took too long, abort
        }
        proc.waitForFinished();

        output = proc.readAll();

        bool error = output.contains("_PyObject_Free")
                || output.contains("_PyExc_IOError")
                || output.contains("_sysconfigdata_nd ")
                || !output.contains("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
        if (error)
            return qMakePair(paths, error);
    }
    return qMakePair(paths, false);
}

void AndroidSettingsWidget::check(AndroidSettingsWidget::Mode mode)
{
    if (mode & Sdk) {
        m_sdkState = Okay;
        if (m_androidConfig.sdkLocation().isEmpty())
            m_sdkState = NotSet;
        else if (!(sdkLocationIsValid() && sdkPlatformToolsInstalled()))
            m_sdkState = Error;
    }

    if (mode & Ndk) {
        m_ndkState = Okay;
        Utils::FileName platformPath = m_androidConfig.ndkLocation();
        Utils::FileName toolChainPath = m_androidConfig.ndkLocation();
        Utils::FileName sourcesPath = m_androidConfig.ndkLocation();
        m_ui->gdbWarningIconLabel->setVisible(false);
        m_ui->gdbWarningLabel->setVisible(false);
        if (m_androidConfig.ndkLocation().isEmpty()) {
            m_ndkState = NotSet;
        } else if (!platformPath.appendPath(QLatin1String("platforms")).exists()
                || !toolChainPath.appendPath(QLatin1String("toolchains")).exists()
                || !sourcesPath.appendPath(QLatin1String("sources/cxx-stl")).exists()) {
            m_ndkState = Error;
            m_ndkErrorMessage = tr("\"%1\" does not seem to be an Android NDK top folder.")
                    .arg(m_androidConfig.ndkLocation().toUserOutput());
        } else if (platformPath.toString().contains(QLatin1Char(' '))) {
            m_ndkState = Error;
            m_ndkErrorMessage = tr("The Android NDK cannot be installed into a path with spaces.");
        } else {
            QList<AndroidToolChainFactory::AndroidToolChainInformation> compilerPaths
                    = AndroidToolChainFactory::toolchainPathsForNdk(m_androidConfig.ndkLocation());
            m_ndkCompilerCount = compilerPaths.count();

            // Check for a gdb with a broken python
            QStringList gdbPaths;
            foreach (const AndroidToolChainFactory::AndroidToolChainInformation &ati, compilerPaths) {
                if (ati.language == Core::Id(ProjectExplorer::Constants::C_LANGUAGE_ID))
                    continue;
                // we only check the arm gdbs, that's indicative enough
                if (ati.abi.architecture() != ProjectExplorer::Abi::ArmArchitecture)
                    continue;
                Utils::FileName gdbPath = m_androidConfig.gdbPath(ati.abi, ati.version);
                if (gdbPath.exists())
                    gdbPaths << gdbPath.toString();
            }

            if (!gdbPaths.isEmpty()) {
                m_checkGdbWatcher.setFuture(Utils::runAsync(&checkGdbForBrokenPython, gdbPaths));
                m_gdbCheckPaths = gdbPaths;
            }

            // See if we have qt versions for those toolchains
            QSet<ProjectExplorer::Abi> toolchainsForAbi;
            foreach (const AndroidToolChainFactory::AndroidToolChainInformation &ati, compilerPaths) {
                if (ati.language == Core::Id(ProjectExplorer::Constants::CXX_LANGUAGE_ID))
                    toolchainsForAbi.insert(ati.abi);
            }

            const QList<QtSupport::BaseQtVersion *> androidQts
                    = QtSupport::QtVersionManager::versions([](const QtSupport::BaseQtVersion *v) {
                return v->type() == QLatin1String(Constants::ANDROIDQT) && !v->qtAbis().isEmpty();
            });
            QSet<ProjectExplorer::Abi> qtVersionsForAbi;
            foreach (QtSupport::BaseQtVersion *qtVersion, androidQts)
                qtVersionsForAbi.insert(qtVersion->qtAbis().first());

            QSet<ProjectExplorer::Abi> missingQtArchs = toolchainsForAbi.subtract(qtVersionsForAbi);
            if (missingQtArchs.isEmpty()) {
                m_ndkMissingQtArchs.clear();
            } else {
                if (missingQtArchs.count() == 1) {
                    m_ndkMissingQtArchs = tr("Qt version for architecture %1 is missing.\n"
                                             "To add the Qt version, select Options > Build & Run > Qt Versions.")
                            .arg((*missingQtArchs.constBegin()).toString());
                } else {
                    m_ndkMissingQtArchs = tr("Qt versions for %n architectures are missing.\n"
                                             "To add the Qt versions, select Options > Build & Run > Qt Versions.",
                                             nullptr, missingQtArchs.size());
                }
            }
        }
    }

    if (mode & Java) {
        m_javaState = Okay;
        if (m_androidConfig.openJDKLocation().isEmpty()) {
            m_javaState = NotSet;
        } else {
            Utils::FileName bin = m_androidConfig.openJDKLocation();
            bin.appendPath(QLatin1String("bin/javac" QTC_HOST_EXE_SUFFIX));
            if (!m_androidConfig.openJDKLocation().exists() || !bin.exists())
                m_javaState = Error;
        }
    }
}

void AndroidSettingsWidget::applyToUi(AndroidSettingsWidget::Mode mode)
{
    if (mode & Sdk) {
        if (m_sdkState == Error) {
            m_ui->sdkWarningIconLabel->setVisible(true);
            m_ui->sdkWarningLabel->setVisible(true);
            Utils::FileName location = Utils::FileName::fromUserInput(m_ui->SDKLocationPathChooser->rawPath());
            if (sdkLocationIsValid())
                m_ui->sdkWarningLabel->setText(tr("The Platform tools are missing. Please use the Android SDK Manager to install them."));
            else
                m_ui->sdkWarningLabel->setText(tr("\"%1\" does not seem to be an Android SDK top folder.").arg(location.toUserOutput()));
        } else {
            m_ui->sdkWarningIconLabel->setVisible(false);
            m_ui->sdkWarningLabel->setVisible(false);
        }
    }

    if (mode & Ndk) {
        if (m_ndkState == NotSet) {
            m_ui->ndkWarningIconLabel->setVisible(false);
            m_ui->toolchainFoundLabel->setVisible(false);
            m_ui->kitWarningIconLabel->setVisible(false);
            m_ui->kitWarningLabel->setVisible(false);
        } else if (m_ndkState == Error) {
            m_ui->toolchainFoundLabel->setText(m_ndkErrorMessage);
            m_ui->toolchainFoundLabel->setVisible(true);
            m_ui->ndkWarningIconLabel->setVisible(true);
            m_ui->kitWarningIconLabel->setVisible(false);
            m_ui->kitWarningLabel->setVisible(false);
        } else {
            if (m_ndkCompilerCount > 0) {
                m_ui->ndkWarningIconLabel->setVisible(false);
                m_ui->toolchainFoundLabel->setText(tr("Found %n toolchains for this NDK.", 0, m_ndkCompilerCount));
                m_ui->toolchainFoundLabel->setVisible(true);
            } else {
                m_ui->ndkWarningIconLabel->setVisible(false);
                m_ui->toolchainFoundLabel->setVisible(false);
            }

            if (m_ndkMissingQtArchs.isEmpty()) {
                m_ui->kitWarningIconLabel->setVisible(false);
                m_ui->kitWarningLabel->setVisible(false);
            } else {
                m_ui->kitWarningIconLabel->setVisible(true);
                m_ui->kitWarningLabel->setVisible(true);
                m_ui->kitWarningLabel->setText(m_ndkMissingQtArchs);
            }
        }
    }

    if (mode & Java) {
        Utils::FileName location = m_androidConfig.openJDKLocation();
        bool error = m_javaState == Error;
        m_ui->jdkWarningIconLabel->setVisible(error);
        m_ui->jdkWarningLabel->setVisible(error);
        if (error)
            m_ui->jdkWarningLabel->setText(tr("\"%1\" does not seem to be a JDK folder.").arg(location.toUserOutput()));
    }

    if (mode & Sdk || mode & Java) {
        if (m_sdkState == Okay && m_javaState == Okay) {
            m_ui->AVDManagerFrame->setEnabled(true);
        } else {
            m_ui->AVDManagerFrame->setEnabled(false);
        }

        startUpdateAvd();
    }
}

void AndroidSettingsWidget::disableAvdControls()
{
    m_ui->AVDAddPushButton->setEnabled(false);
    m_ui->AVDTableView->setEnabled(false);
    m_ui->AVDRemovePushButton->setEnabled(false);
    m_ui->AVDStartPushButton->setEnabled(false);
}

void AndroidSettingsWidget::enableAvdControls()
{
    m_ui->AVDTableView->setEnabled(true);
    m_ui->AVDAddPushButton->setEnabled(true);
    avdActivated(m_ui->AVDTableView->currentIndex());
}

void AndroidSettingsWidget::startUpdateAvd()
{
    disableAvdControls();
    m_virtualDevicesWatcher.setFuture(m_androidConfig.androidVirtualDevicesFuture());
}

void AndroidSettingsWidget::updateAvds()
{
    m_AVDModel.setAvdList(m_virtualDevicesWatcher.result());
    if (!m_lastAddedAvd.isEmpty()) {
        m_ui->AVDTableView->setCurrentIndex(m_AVDModel.indexForAvdName(m_lastAddedAvd));
        m_lastAddedAvd.clear();
    }
    enableAvdControls();
}

bool AndroidSettingsWidget::sdkLocationIsValid() const
{
    Utils::FileName androidExe = m_androidConfig.sdkLocation();
    Utils::FileName androidBat = m_androidConfig.sdkLocation();
    Utils::FileName emulator = m_androidConfig.sdkLocation();
    return (androidExe.appendPath(QLatin1String("/tools/android" QTC_HOST_EXE_SUFFIX)).exists()
            || androidBat.appendPath(QLatin1String("/tools/android" ANDROID_BAT_SUFFIX)).exists())
            && emulator.appendPath(QLatin1String("/tools/emulator" QTC_HOST_EXE_SUFFIX)).exists();
}

bool AndroidSettingsWidget::sdkPlatformToolsInstalled() const
{
    Utils::FileName adb = m_androidConfig.sdkLocation();
    return adb.appendPath(QLatin1String("platform-tools/adb" QTC_HOST_EXE_SUFFIX)).exists();
}

void AndroidSettingsWidget::saveSettings()
{
    sdkLocationEditingFinished();
    ndkLocationEditingFinished();
    antLocationEditingFinished();
    openJDKLocationEditingFinished();
    dataPartitionSizeEditingFinished();
    AndroidConfigurations::setConfig(m_androidConfig);
}

void AndroidSettingsWidget::sdkLocationEditingFinished()
{
    m_androidConfig.setSdkLocation(Utils::FileName::fromUserInput(m_ui->SDKLocationPathChooser->rawPath()));

    check(Sdk);

    if (m_sdkState == Okay)
        searchForAnt(m_androidConfig.sdkLocation());

    applyToUi(Sdk);
}

void AndroidSettingsWidget::ndkLocationEditingFinished()
{
    m_androidConfig.setNdkLocation(Utils::FileName::fromUserInput(m_ui->NDKLocationPathChooser->rawPath()));

    check(Ndk);

    if (m_ndkState == Okay)
        searchForAnt(m_androidConfig.ndkLocation());

    applyToUi(Ndk);
}

void AndroidSettingsWidget::searchForAnt(const Utils::FileName &location)
{
    if (!m_androidConfig.antLocation().isEmpty())
            return;
    if (location.isEmpty())
        return;
    QDir parentFolder = location.toFileInfo().absoluteDir();
    foreach (const QString &file, parentFolder.entryList()) {
        if (file.startsWith(QLatin1String("apache-ant"))) {
            Utils::FileName ant = Utils::FileName::fromString(parentFolder.absolutePath());
            ant.appendPath(file).appendPath(QLatin1String("bin"));
            if (Utils::HostOsInfo::isWindowsHost())
                ant.appendPath(QLatin1String("ant.bat"));
            else
                ant.appendPath(QLatin1String("ant"));
            if (ant.exists()) {
                m_androidConfig.setAntLocation(ant);
                m_ui->AntLocationPathChooser->setFileName(ant);
            }
        }
    }
}

void AndroidSettingsWidget::antLocationEditingFinished()
{
    m_androidConfig.setAntLocation(Utils::FileName::fromUserInput(m_ui->AntLocationPathChooser->rawPath()));
}

void AndroidSettingsWidget::openJDKLocationEditingFinished()
{
    m_androidConfig.setOpenJDKLocation(Utils::FileName::fromUserInput(m_ui->OpenJDKLocationPathChooser->rawPath()));

    check(Java);
    applyToUi(Java);
}

void AndroidSettingsWidget::openSDKDownloadUrl()
{
    QDesktopServices::openUrl(QUrl::fromUserInput("https://developer.android.com/studio/"));
}

void AndroidSettingsWidget::openNDKDownloadUrl()
{
    QDesktopServices::openUrl(QUrl::fromUserInput("https://developer.android.com/ndk/downloads/"));
}

void AndroidSettingsWidget::openAntDownloadUrl()
{
    QDesktopServices::openUrl(QUrl::fromUserInput("http://ant.apache.org/bindownload.cgi"));
}

void AndroidSettingsWidget::openOpenJDKDownloadUrl()
{
    QDesktopServices::openUrl(QUrl::fromUserInput("http://www.oracle.com/technetwork/java/javase/downloads/"));
}

void AndroidSettingsWidget::addAVD()
{
    disableAvdControls();
    AndroidConfig::CreateAvdInfo info = m_androidConfig.gatherCreateAVDInfo(this);

    if (info.target.isEmpty()) {
        enableAvdControls();
        return;
    }

    m_futureWatcher.setFuture(m_androidConfig.createAVD(info));
}

void AndroidSettingsWidget::avdAdded()
{
    AndroidConfig::CreateAvdInfo info = m_futureWatcher.result();
    if (!info.error.isEmpty()) {
        enableAvdControls();
        QMessageBox::critical(this, QApplication::translate("AndroidConfig", "Error Creating AVD"), info.error);
        return;
    }

    startUpdateAvd();
    m_lastAddedAvd = info.name;
}

void AndroidSettingsWidget::removeAVD()
{
    disableAvdControls();
    QString avdName = m_AVDModel.avdName(m_ui->AVDTableView->currentIndex());
    if (QMessageBox::question(this, tr("Remove Android Virtual Device"),
                              tr("Remove device \"%1\"? This cannot be undone.").arg(avdName),
                              QMessageBox::Yes | QMessageBox::No)
            == QMessageBox::No) {
        enableAvdControls();
        return;
    }

    m_androidConfig.removeAVD(avdName);
    startUpdateAvd();
}

void AndroidSettingsWidget::startAVD()
{
    m_androidConfig.startAVDAsync(m_AVDModel.avdName(m_ui->AVDTableView->currentIndex()));
}

void AndroidSettingsWidget::avdActivated(const QModelIndex &index)
{
    m_ui->AVDRemovePushButton->setEnabled(index.isValid());
    m_ui->AVDStartPushButton->setEnabled(index.isValid());
}

void AndroidSettingsWidget::dataPartitionSizeEditingFinished()
{
    m_androidConfig.setPartitionSize(m_ui->DataPartitionSizeSpinBox->value());
}

void AndroidSettingsWidget::createKitToggled()
{
    m_androidConfig.setAutomaticKitCreation(m_ui->CreateKitCheckBox->isChecked());
}

void AndroidSettingsWidget::useGradleToggled()
{
    m_androidConfig.setUseGradle(m_ui->UseGradleCheckBox->isChecked());
}

void AndroidSettingsWidget::checkGdbFinished()
{
    QPair<QStringList, bool> result = m_checkGdbWatcher.future().result();
    if (result.first != m_gdbCheckPaths) // no longer relevant
        return;
    m_ui->gdbWarningIconLabel->setVisible(result.second);
    m_ui->gdbWarningLabel->setVisible(result.second);
}

void AndroidSettingsWidget::showGdbWarningDialog()
{
    QMessageBox::warning(this,
                         tr("Unsupported GDB"),
                         tr("The GDB inside this NDK seems to not support Python. "
                            "The Qt Project offers fixed GDB builds at: "
                            "<a href=\"http://download.qt.io/official_releases/gdb/\">"
                            "http://download.qt.io/official_releases/gdb/</a>"));
}

void AndroidSettingsWidget::manageAVD()
{
    QProcess *avdProcess = new QProcess();
    connect(this, &QObject::destroyed, avdProcess, &QObject::deleteLater);
    connect(avdProcess, static_cast<void (QProcess::*)(int)>(&QProcess::finished),
            avdProcess, &QObject::deleteLater);

    avdProcess->setProcessEnvironment(m_androidConfig.androidToolEnvironment().toProcessEnvironment());
    QString executable = m_androidConfig.androidToolPath().toString();
    QStringList arguments = QStringList("avd");

    avdProcess->start(executable, arguments);
}


} // namespace Internal
} // namespace Android