maemodeploystep.cpp 25.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

30
31
#include "maemodeploystep.h"

32
#include "maemoconstants.h"
33
#include "maemodeploystepwidget.h"
34
#include "maemodeviceconfiglistmodel.h"
35
#include "maemoglobal.h"
36
#include "maemopackagecreationstep.h"
ck's avatar
ck committed
37
#include "maemoremotemounter.h"
38
#include "maemorunconfiguration.h"
ck's avatar
ck committed
39
#include "maemotoolchain.h"
40
#include "maemousedportsgatherer.h"
41

42
43
44
45
46
47
48
49
#include <coreplugin/ssh/sftpchannel.h>
#include <coreplugin/ssh/sshconnection.h>
#include <coreplugin/ssh/sshremoteprocess.h>

#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>

ck's avatar
ck committed
50
51
#include <qt4projectmanager/qt4buildconfiguration.h>

52
#include <QtCore/QCoreApplication>
ck's avatar
ck committed
53
#include <QtCore/QDir>
54
55
56
57
58
#include <QtCore/QEventLoop>
#include <QtCore/QFileInfo>
#include <QtCore/QTimer>

using namespace Core;
59
60
61
62
using namespace ProjectExplorer;

namespace Qt4ProjectManager {
namespace Internal {
63
namespace { const int DefaultMountPort = 1050; }
64
65
66

const QLatin1String MaemoDeployStep::Id("Qt4ProjectManager.MaemoDeployStep");

Tobias Hunger's avatar
Tobias Hunger committed
67
MaemoDeployStep::MaemoDeployStep(ProjectExplorer::BuildStepList *parent)
68
    : BuildStep(parent, Id)
69
{
70
    ctor();
71
72
}

Tobias Hunger's avatar
Tobias Hunger committed
73
MaemoDeployStep::MaemoDeployStep(ProjectExplorer::BuildStepList *parent,
74
    MaemoDeployStep *other)
75
    : BuildStep(parent, other), m_lastDeployed(other->m_lastDeployed)
76
77
78
79
{
    ctor();
}

80
MaemoDeployStep::~MaemoDeployStep() { }
81
82

void MaemoDeployStep::ctor()
83
{
84
85
    //: MaemoDeployStep default display name
    setDefaultDisplayName(tr("Deploy to Maemo device"));
86

87
88
89
90
91
92
93
94
95
96
97
98
99
    // A MaemoDeployables object is only dependent on the active build
    // configuration and therefore can (and should) be shared among all
    // deploy steps.
    const QList<DeployConfiguration *> &deployConfigs
        = target()->deployConfigurations();
    if (deployConfigs.isEmpty()) {
        m_deployables = QSharedPointer<MaemoDeployables>(new MaemoDeployables(this));
    } else {
        const MaemoDeployStep *const other
            = MaemoGlobal::buildStep<MaemoDeployStep>(deployConfigs.first());
        m_deployables = other->deployables();
    }

ck's avatar
ck committed
100
101
102
    m_connecting = false;
    m_needsInstall = false;
    m_stopped = false;
103
    m_deviceConfigModel = new MaemoDeviceConfigListModel(this);
ck's avatar
ck committed
104
    m_canStart = true;
Christian Kandeler's avatar
Christian Kandeler committed
105
106
107
108
109
110
111
    m_sysrootInstaller = new QProcess(this);
    connect(m_sysrootInstaller, SIGNAL(finished(int,QProcess::ExitStatus)),
        this, SLOT(handleSysrootInstallerFinished()));
    connect(m_sysrootInstaller, SIGNAL(readyReadStandardOutput()), this,
        SLOT(handleSysrootInstallerOutput()));
    connect(m_sysrootInstaller, SIGNAL(readyReadStandardError()), this,
        SLOT(handleSysrootInstallerErrorOutput()));
ck's avatar
ck committed
112
113
114
    m_cleanupTimer = new QTimer(this);
    connect(m_cleanupTimer, SIGNAL(timeout()), this,
        SLOT(handleCleanupTimeout()));
115
    m_mounter = new MaemoRemoteMounter(this);
ck's avatar
ck committed
116
117
118
119
120
121
    connect(m_mounter, SIGNAL(mounted()), this, SLOT(handleMounted()));
    connect(m_mounter, SIGNAL(unmounted()), this, SLOT(handleUnmounted()));
    connect(m_mounter, SIGNAL(error(QString)), this,
        SLOT(handleMountError(QString)));
    connect(m_mounter, SIGNAL(reportProgress(QString)), this,
        SLOT(handleProgressReport(QString)));
122
123
    connect(m_mounter, SIGNAL(debugOutput(QString)), this,
        SLOT(handleMountDebugOutput(QString)));
124
125
126
127
128
    m_portsGatherer = new MaemoUsedPortsGatherer(this);
    connect(m_portsGatherer, SIGNAL(error(QString)), this,
        SLOT(handlePortsGathererError(QString)));
    connect(m_portsGatherer, SIGNAL(portListReady()), this,
        SLOT(handlePortListReady()));
129
130
131
132
133
134
135
136
137
}

bool MaemoDeployStep::init()
{
    return true;
}

void MaemoDeployStep::run(QFutureInterface<bool> &fi)
{
138
139
140
141
    // Move to GUI thread for connection sharing with run control.
    QTimer::singleShot(0, this, SLOT(start()));

    MaemoDeployEventHandler eventHandler(this, fi);
142
    connect (&eventHandler, SIGNAL(destroyed()), this, SLOT(stop()));
143
144
145
146
}

BuildStepConfigWidget *MaemoDeployStep::createConfigWidget()
{
147
148
149
150
151
152
153
    return new MaemoDeployStepWidget(this);
}

QVariantMap MaemoDeployStep::toMap() const
{
    QVariantMap map(BuildStep::toMap());
    addDeployTimesToMap(map);
Christian Kandeler's avatar
Christian Kandeler committed
154
    map.insert(DeployToSysrootKey, m_deployToSysroot);
155
    map.unite(m_deviceConfigModel->toMap());
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
    return map;
}

void MaemoDeployStep::addDeployTimesToMap(QVariantMap &map) const
{
    QVariantList hostList;
    QVariantList fileList;
    QVariantList remotePathList;
    QVariantList timeList;
    typedef QHash<DeployablePerHost, QDateTime>::ConstIterator DepIt;
    for (DepIt it = m_lastDeployed.begin(); it != m_lastDeployed.end(); ++it) {
        fileList << it.key().first.localFilePath;
        remotePathList << it.key().first.remoteDir;
        hostList << it.key().second;
        timeList << it.value();
    }
    map.insert(LastDeployedHostsKey, hostList);
    map.insert(LastDeployedFilesKey, fileList);
    map.insert(LastDeployedRemotePathsKey, remotePathList);
    map.insert(LastDeployedTimesKey, timeList);
}

bool MaemoDeployStep::fromMap(const QVariantMap &map)
{
    if (!BuildStep::fromMap(map))
        return false;
    getDeployTimesFromMap(map);
183
    m_deviceConfigModel->fromMap(map);
Christian Kandeler's avatar
Christian Kandeler committed
184
    m_deployToSysroot = map.value(DeployToSysrootKey, true).toBool();
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
    return true;
}

void MaemoDeployStep::getDeployTimesFromMap(const QVariantMap &map)
{
    const QVariantList &hostList = map.value(LastDeployedHostsKey).toList();
    const QVariantList &fileList = map.value(LastDeployedFilesKey).toList();
    const QVariantList &remotePathList
        = map.value(LastDeployedRemotePathsKey).toList();
    const QVariantList &timeList = map.value(LastDeployedTimesKey).toList();
    const int elemCount
        = qMin(qMin(hostList.size(), fileList.size()),
            qMin(remotePathList.size(), timeList.size()));
    for (int i = 0; i < elemCount; ++i) {
        const MaemoDeployable d(fileList.at(i).toString(),
            remotePathList.at(i).toString());
        m_lastDeployed.insert(DeployablePerHost(d, hostList.at(i).toString()),
            timeList.at(i).toDateTime());
    }
}

const MaemoPackageCreationStep *MaemoDeployStep::packagingStep() const
{
ck's avatar
ck committed
208
    const MaemoPackageCreationStep * const step
209
        = MaemoGlobal::buildStep<MaemoPackageCreationStep>(target()->activeDeployConfiguration());
210
211
    Q_ASSERT_X(step, Q_FUNC_INFO,
        "Impossible: Maemo build configuration without packaging step.");
ck's avatar
ck committed
212
    return step;
213
214
215
216
}

void MaemoDeployStep::raiseError(const QString &errorString)
{
217
    disconnect(m_connection.data(), 0, this, 0);
218
219
220
221
222
    emit addTask(Task(Task::Error, errorString, QString(), -1,
        Constants::TASK_CATEGORY_BUILDSYSTEM));
    emit error();
}

Christian Kandeler's avatar
Christian Kandeler committed
223
void MaemoDeployStep::writeOutput(const QString &text, OutputFormat format)
224
225
226
227
228
229
{
    emit addOutput(text, format);
}

void MaemoDeployStep::stop()
{
ck's avatar
ck committed
230
231
232
    if (m_stopped)
        return;

233
234
235
236
237
238
239
240
241
    const bool remoteProcessRunning
        = (m_deviceInstaller && m_deviceInstaller->isRunning())
              || m_currentDeviceDeployAction;
    const bool isActive = remoteProcessRunning || m_connecting
        || m_needsInstall || !m_filesToCopy.isEmpty();
    if (!isActive) {
        if (m_connection)
            disconnect(m_connection.data(), 0, this, 0);
        return;
ck's avatar
ck committed
242
    }
243
244
245

    if (remoteProcessRunning) {
        const QByteArray programToKill
246
247
248
            = m_currentDeviceDeployAction ? "/bin/cp" : "/usr/bin/dpkg";
        const QByteArray cmdLine = "pkill " + programToKill
            + "; sleep 1; pkill -9 " + programToKill;
249
250
251
        SshRemoteProcess::Ptr killProc
            = m_connection->createRemoteProcess(cmdLine);
        killProc->start();
252
    }
253
254
255
256
257
258
259
260
261
262
263
    m_stopped = true;
    m_unmountState = CurrentMountsUnmount;
    m_canStart = false;
    m_needsInstall = false;
    m_filesToCopy.clear();
    m_connecting = false;
    m_sysrootInstaller->terminate();
    m_sysrootInstaller->waitForFinished(500);
    m_sysrootInstaller->kill();
    m_cleanupTimer->start(5000);
    m_mounter->stop();
264
265
266
267
}

QString MaemoDeployStep::uploadDir() const
{
268
    return MaemoGlobal::homeDirOnDevice(m_connection->connectionParameters().uname);
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
}

bool MaemoDeployStep::currentlyNeedsDeployment(const QString &host,
    const MaemoDeployable &deployable) const
{
    const QDateTime &lastDeployed
        = m_lastDeployed.value(DeployablePerHost(deployable, host));
    return !lastDeployed.isValid()
        || QFileInfo(deployable.localFilePath).lastModified() > lastDeployed;
}

void MaemoDeployStep::setDeployed(const QString &host,
    const MaemoDeployable &deployable)
{
    m_lastDeployed.insert(DeployablePerHost(deployable, host),
        QDateTime::currentDateTime());
}

MaemoDeviceConfig MaemoDeployStep::deviceConfig() const
{
289
290
291
    return deviceConfigModel()->current();
}

292
293
void MaemoDeployStep::start()
{
ck's avatar
ck committed
294
    if (!m_canStart) {
Christian Kandeler's avatar
Christian Kandeler committed
295
        raiseError(tr("Cannot start deployment, as the clean-up from the last time has not finished yet."));
296
        return;
ck's avatar
ck committed
297
298
299
    }
    m_cleanupTimer->stop();
    m_stopped = false;
300

301
    if (!deviceConfig().isValid()) {
302
303
304
        raiseError(tr("Deployment failed: No valid device set."));
        return;
    }
305

306
    Q_ASSERT(!m_currentDeviceDeployAction);
ck's avatar
ck committed
307
308
309
    Q_ASSERT(!m_needsInstall);
    Q_ASSERT(m_filesToCopy.isEmpty());
    const MaemoPackageCreationStep * const pStep = packagingStep();
310
    const QString hostName = deviceConfig().server.host;
ck's avatar
ck committed
311
312
313
314
315
316
317
318
319
320
321
322
    if (pStep->isPackagingEnabled()) {
        const MaemoDeployable d(pStep->packageFilePath(), QString());
        if (currentlyNeedsDeployment(hostName, d))
            m_needsInstall = true;
    } else {
        const int deployableCount = m_deployables->deployableCount();
        for (int i = 0; i < deployableCount; ++i) {
            const MaemoDeployable &d = m_deployables->deployableAt(i);
            if (currentlyNeedsDeployment(hostName, d))
                m_filesToCopy << d;
        }
    }
323

ck's avatar
ck committed
324
    if (m_needsInstall || !m_filesToCopy.isEmpty()) {
325
326
327
328
        if (m_deployToSysroot)
            installToSysroot();
        else
            connectToDevice();
ck's avatar
ck committed
329
330
331
332
    } else {
        writeOutput(tr("All files up to date, no installation necessary."));
        emit done();
    }
333
334
335
336
}

void MaemoDeployStep::handleConnectionFailure()
{
ck's avatar
ck committed
337
338
339
    m_connecting = false;
    if (m_stopped) {
        m_canStart = true;
340
        return;
ck's avatar
ck committed
341
    }
342
343
344
345
346
347
    raiseError(tr("Could not connect to host: %1")
        .arg(m_connection->errorString()));
}

void MaemoDeployStep::handleSftpChannelInitialized()
{
348
349
    if (m_stopped) {
        m_canStart = true;
350
351
352
        return;
    }

353
354
355
356
357
358
    const QString filePath = packagingStep()->packageFilePath();
    const QString filePathNative = QDir::toNativeSeparators(filePath);
    const QString fileName = QFileInfo(filePath).fileName();
    const QString remoteFilePath = uploadDir() + QLatin1Char('/') + fileName;
    const SftpJobId job = m_uploader->uploadFile(filePath,
        remoteFilePath, SftpOverwriteExisting);
359
360
    if (job == SftpInvalidJob) {
        raiseError(tr("Upload failed: Could not open file '%1'")
361
362
363
            .arg(filePathNative));
    } else {
        writeOutput(tr("Started uploading file '%1'.").arg(filePathNative));
364
365
366
367
368
    }
}

void MaemoDeployStep::handleSftpChannelInitializationFailed(const QString &error)
{
369
370
    if (m_stopped) {
        m_canStart = true;
371
        return;
372
    }
373
374
375
    raiseError(tr("Could not set up SFTP connection: %1").arg(error));
}

376
void MaemoDeployStep::handleSftpJobFinished(Core::SftpJobId,
377
378
    const QString &error)
{
379
380
    if (m_stopped) {
        m_canStart = true;
381
382
383
        return;
    }

384
385
    const QString filePathNative
        = QDir::toNativeSeparators(packagingStep()->packageFilePath());
386
387
    if (!error.isEmpty()) {
        raiseError(tr("Failed to upload file %1: %2")
388
            .arg(filePathNative, error));
389
390
391
392
        return;
    }

    writeOutput(tr("Successfully uploaded file '%1'.")
393
394
395
        .arg(filePathNative));
    const QString remoteFilePath
        = uploadDir() + QLatin1Char('/') + QFileInfo(filePathNative).fileName();
396
    runDpkg(remoteFilePath, true);
397
}
ck's avatar
ck committed
398
399
400
401
402
403
404
405
406

void MaemoDeployStep::handleMounted()
{
    if (m_stopped) {
        m_mounter->unmount();
        return;
    }

    if (m_needsInstall) {
407
408
        const QString remoteFilePath = deployMountPoint() + QLatin1Char('/')
            + QFileInfo(packagingStep()->packageFilePath()).fileName();
409
        runDpkg(remoteFilePath, false);
ck's avatar
ck committed
410
    } else {
411
        copyNextFileToDevice();
ck's avatar
ck committed
412
413
414
415
416
417
    }
}

void MaemoDeployStep::handleUnmounted()
{
    if (m_stopped) {
Christian Kandeler's avatar
Christian Kandeler committed
418
        m_mounter->resetMountSpecifications();
ck's avatar
ck committed
419
420
421
422
        m_canStart = true;
        return;
    }

423
424
425
426
427
428
429
430
    switch (m_unmountState) {
    case OldDirsUnmount:
        if (toolChain()->allowsRemoteMounts())
            setupMount();
        else
            prepareSftpConnection();
        break;
    case CurrentDirsUnmount:
431
        m_portsGatherer->start(m_connection, deviceConfig().freePorts());
432
433
        break;
    case CurrentMountsUnmount:
Christian Kandeler's avatar
Christian Kandeler committed
434
435
        writeOutput(tr("Deployment finished."));
        emit done();
436
        break;
Christian Kandeler's avatar
Christian Kandeler committed
437
    }
438
439
440
441
442
443
444
445
446
}

void MaemoDeployStep::handleMountError(const QString &errorMsg)
{
    if (m_stopped)
        m_canStart = true;
    else
        raiseError(errorMsg);
}
Christian Kandeler's avatar
Christian Kandeler committed
447

448
449
450
451
452
453
void MaemoDeployStep::handleMountDebugOutput(const QString &output)
{
    if (!m_stopped)
        writeOutput(output, ErrorOutput);
}

454
455
void MaemoDeployStep::setupMount()
{
Christian Kandeler's avatar
Christian Kandeler committed
456
457
    Q_ASSERT(m_needsInstall || !m_filesToCopy.isEmpty());
    m_mounter->resetMountSpecifications();
458
    m_mounter->setToolchain(toolChain());
Christian Kandeler's avatar
Christian Kandeler committed
459
460
461
462
    if (m_needsInstall) {
        const QString localDir
            = QFileInfo(packagingStep()->packageFilePath()).absolutePath();
        const MaemoMountSpecification mountSpec(localDir, deployMountPoint());
463
        m_mounter->addMountSpecification(mountSpec, true);
Christian Kandeler's avatar
Christian Kandeler committed
464
    } else {
ck's avatar
ck committed
465
#ifdef Q_OS_WIN
Christian Kandeler's avatar
Christian Kandeler committed
466
        bool drivesToMount[26];
467
        qFill(drivesToMount, drivesToMount + sizeof drivesToMount / sizeof drivesToMount[0], false);
Christian Kandeler's avatar
Christian Kandeler committed
468
469
470
471
472
473
474
        for (int i = 0; i < m_filesToCopy.count(); ++i) {
            const QString localDir
                = QFileInfo(m_filesToCopy.at(i).localFilePath).canonicalPath();
            const char driveLetter = localDir.at(0).toLower().toLatin1();
            if (driveLetter < 'a' || driveLetter > 'z') {
                qWarning("Weird: drive letter is '%c'.", driveLetter);
                continue;
ck's avatar
ck committed
475
            }
Christian Kandeler's avatar
Christian Kandeler committed
476
477
478
479
480
481
482
483
484

            const int index = driveLetter - 'a';
            if (drivesToMount[index])
                continue;

            const QString mountPoint = deployMountPoint() + QLatin1Char('/')
                + QLatin1Char(driveLetter);
            const MaemoMountSpecification mountSpec(localDir.left(3),
                mountPoint);
485
            m_mounter->addMountSpecification(mountSpec, true);
Christian Kandeler's avatar
Christian Kandeler committed
486
            drivesToMount[index] = true;
ck's avatar
ck committed
487
        }
Christian Kandeler's avatar
Christian Kandeler committed
488
#else
489
490
        m_mounter->addMountSpecification(MaemoMountSpecification(QLatin1String("/"),
            deployMountPoint()), true);
Christian Kandeler's avatar
Christian Kandeler committed
491
#endif
ck's avatar
ck committed
492
    }
Christian Kandeler's avatar
Christian Kandeler committed
493
494
    m_unmountState = CurrentDirsUnmount;
    m_mounter->unmount();
ck's avatar
ck committed
495
496
}

497
void MaemoDeployStep::prepareSftpConnection()
ck's avatar
ck committed
498
{
499
500
501
502
503
        // TODO: Close channel when upload has finished/failed/etc.
    if (m_uploader) {
        disconnect(m_uploader.data(), 0, this, 0);
        m_uploader->closeChannel();
    }
504
505
506
507
508
509
510
511
    m_uploader = m_connection->createSftpChannel();
    connect(m_uploader.data(), SIGNAL(initialized()), this,
        SLOT(handleSftpChannelInitialized()));
    connect(m_uploader.data(), SIGNAL(initializationFailed(QString)), this,
        SLOT(handleSftpChannelInitializationFailed(QString)));
    connect(m_uploader.data(), SIGNAL(finished(Core::SftpJobId, QString)),
        this, SLOT(handleSftpJobFinished(Core::SftpJobId, QString)));
    m_uploader->initialize();
ck's avatar
ck committed
512
513
}

Christian Kandeler's avatar
Christian Kandeler committed
514
515
void MaemoDeployStep::installToSysroot()
{
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
    if (m_needsInstall) {
        writeOutput(tr("Installing package to sysroot ..."));
        const MaemoToolChain * const tc = toolChain();
        const QStringList args = QStringList() << QLatin1String("-t")
            << tc->targetName() << QLatin1String("xdpkg") << QLatin1String("-i")
            << packagingStep()->packageFilePath();
        m_sysrootInstaller->start(tc->madAdminCommand(), args);
        if (!m_sysrootInstaller->waitForStarted()) {
            writeOutput(tr("Installation to sysroot failed, continuing anyway."),
                ErrorMessageOutput);
            connectToDevice();
        }
    } else {
        writeOutput(tr("Copying files to sysroot ..."));
        Q_ASSERT(!m_filesToCopy.isEmpty());
        QDir sysRootDir(toolChain()->sysrootRoot());
        foreach (const MaemoDeployable &d, m_filesToCopy) {
            const QLatin1Char sep('/');
            const QString targetFilePath = toolChain()->sysrootRoot() + sep
                + d.remoteDir + sep + QFileInfo(d.localFilePath).fileName();
536
537
538
            sysRootDir.mkpath(d.remoteDir.mid(1));
            QFile::remove(targetFilePath);
            if (!QFile::copy(d.localFilePath, targetFilePath)) {
539
540
541
542
543
544
545
546
547
548
549
550
551
                writeOutput(tr("Sysroot installation failed: "
                    "Could not copy '%1' to '%2'. Continuing anyway.")
                    .arg(QDir::toNativeSeparators(d.localFilePath),
                         QDir::toNativeSeparators(targetFilePath)),
                    ErrorMessageOutput);
            }
            QCoreApplication::processEvents();
            if (m_stopped) {
                m_canStart = true;
                return;
            }
        }
        connectToDevice();
Christian Kandeler's avatar
Christian Kandeler committed
552
553
554
555
556
    }
}

void MaemoDeployStep::handleSysrootInstallerFinished()
{
557
558
559
560
561
    if (m_stopped) {
        m_canStart = true;
        return;
    }

Christian Kandeler's avatar
Christian Kandeler committed
562
563
564
565
566
    if (m_sysrootInstaller->error() != QProcess::UnknownError
        || m_sysrootInstaller->exitCode() != 0) {
        writeOutput(tr("Installation to sysroot failed, continuing anyway."),
            ErrorMessageOutput);
    }
567
    connectToDevice();
Christian Kandeler's avatar
Christian Kandeler committed
568
569
}

570
571
572
573
574
575
576
577
578
579
void MaemoDeployStep::connectToDevice()
{
    m_connecting = false;
    const bool canReUse = m_connection
        && m_connection->state() == SshConnection::Connected
        && m_connection->connectionParameters() == deviceConfig().server;
    if (!canReUse)
        m_connection = SshConnection::create();
    connect(m_connection.data(), SIGNAL(connected()), this,
        SLOT(handleConnected()));
580
    connect(m_connection.data(), SIGNAL(error(Core::SshError)), this,
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
        SLOT(handleConnectionFailure()));
    if (canReUse) {
        unmountOldDirs();
    } else {
        writeOutput(tr("Connecting to device..."));
        m_connecting = true;
        m_connection->connectToHost(deviceConfig().server);
    }
}

void MaemoDeployStep::handleConnected()
{
    if (m_stopped) {
        m_canStart = true;
        return;
    }

    unmountOldDirs();
}

void MaemoDeployStep::unmountOldDirs()
{
    m_unmountState = OldDirsUnmount;
    m_mounter->setConnection(m_connection);
    m_mounter->unmount();
}

608
609
void MaemoDeployStep::runDpkg(const QString &packageFilePath,
    bool removeAfterInstall)
Christian Kandeler's avatar
Christian Kandeler committed
610
611
{
    writeOutput(tr("Installing package to device..."));
612
    QByteArray cmd = MaemoGlobal::remoteSudo().toUtf8() + " dpkg -i "
613
        + packageFilePath.toUtf8();
614
615
    if (removeAfterInstall)
        cmd += " && rm " + packageFilePath.toUtf8() + " || :";
Christian Kandeler's avatar
Christian Kandeler committed
616
617
618
619
620
621
622
623
624
625
626
    m_deviceInstaller = m_connection->createRemoteProcess(cmd);
    connect(m_deviceInstaller.data(), SIGNAL(closed(int)), this,
        SLOT(handleInstallationFinished(int)));
    connect(m_deviceInstaller.data(), SIGNAL(outputAvailable(QByteArray)),
        this, SLOT(handleDeviceInstallerOutput(QByteArray)));
    connect(m_deviceInstaller.data(),
        SIGNAL(errorOutputAvailable(QByteArray)), this,
        SLOT(handleDeviceInstallerErrorOutput(QByteArray)));
    m_deviceInstaller->start();
}

ck's avatar
ck committed
627
628
629
630
631
void MaemoDeployStep::handleProgressReport(const QString &progressMsg)
{
    writeOutput(progressMsg);
}

632
void MaemoDeployStep::copyNextFileToDevice()
ck's avatar
ck committed
633
634
{
    Q_ASSERT(!m_filesToCopy.isEmpty());
635
    Q_ASSERT(!m_currentDeviceDeployAction);
ck's avatar
ck committed
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
    const MaemoDeployable d = m_filesToCopy.takeFirst();
    QString sourceFilePath = deployMountPoint();
#ifdef Q_OS_WIN
    const QString localFilePath = QDir::fromNativeSeparators(d.localFilePath);
    sourceFilePath += QLatin1Char('/') + localFilePath.at(0).toLower()
        + localFilePath.mid(2);
#else
    sourceFilePath += d.localFilePath;
#endif

    QString command = QString::fromLatin1("%1 cp -r %2 %3")
        .arg(MaemoGlobal::remoteSudo(), sourceFilePath,
            d.remoteDir + QLatin1Char('/'));
    SshRemoteProcess::Ptr copyProcess
        = m_connection->createRemoteProcess(command.toUtf8());
    connect(copyProcess.data(), SIGNAL(errorOutputAvailable(QByteArray)),
Christian Kandeler's avatar
Christian Kandeler committed
652
        this, SLOT(handleDeviceInstallerErrorOutput(QByteArray)));
ck's avatar
ck committed
653
654
    connect(copyProcess.data(), SIGNAL(closed(int)), this,
        SLOT(handleCopyProcessFinished(int)));
655
    m_currentDeviceDeployAction.reset(new DeviceDeployAction(d, copyProcess));
ck's avatar
ck committed
656
657
658
659
660
661
662
663
664
665
666
667
    writeOutput(tr("Copying file '%1' to path '%2' on the device...")
        .arg(d.localFilePath, d.remoteDir));
    copyProcess->start();
}

void MaemoDeployStep::handleCopyProcessFinished(int exitStatus)
{
    if (m_stopped) {
        m_mounter->unmount();
        return;
    }

668
669
    Q_ASSERT(m_currentDeviceDeployAction);
    const QString localFilePath = m_currentDeviceDeployAction->first.localFilePath;
ck's avatar
ck committed
670
    if (exitStatus != SshRemoteProcess::ExitedNormally
671
        || m_currentDeviceDeployAction->second->exitCode() != 0) {
ck's avatar
ck committed
672
673
        raiseError(tr("Copying file '%1' failed.").arg(localFilePath));
        m_mounter->unmount();
674
        m_currentDeviceDeployAction.reset(0);
ck's avatar
ck committed
675
676
677
    } else {
        writeOutput(tr("Successfully copied file '%1'.").arg(localFilePath));
        setDeployed(m_connection->connectionParameters().host,
678
679
            m_currentDeviceDeployAction->first);
        m_currentDeviceDeployAction.reset(0);
ck's avatar
ck committed
680
681
        if (m_filesToCopy.isEmpty()) {
            writeOutput(tr("All files copied."));
Christian Kandeler's avatar
Christian Kandeler committed
682
            m_unmountState = CurrentMountsUnmount;
ck's avatar
ck committed
683
684
            m_mounter->unmount();
        } else {
685
            copyNextFileToDevice();
ck's avatar
ck committed
686
687
688
689
690
691
        }
    }
}

void MaemoDeployStep::handleCleanupTimeout()
{
692
    m_cleanupTimer->stop();
ck's avatar
ck committed
693
694
695
    if (!m_canStart) {
        m_canStart = true;
        disconnect(m_connection.data(), 0, this, 0);
Christian Kandeler's avatar
Christian Kandeler committed
696
697
        if (m_deviceInstaller)
            disconnect(m_deviceInstaller.data(), 0, this, 0);
698
699
700
701
        if (m_currentDeviceDeployAction) {
            disconnect(m_currentDeviceDeployAction->second.data(), 0, this, 0);
            m_currentDeviceDeployAction.reset(0);
        }
ck's avatar
ck committed
702
703
704
705
706
707
708
709
    }
}

QString MaemoDeployStep::deployMountPoint() const
{
    return MaemoGlobal::homeDirOnDevice(deviceConfig().server.uname)
        + QLatin1String("/deployMountPoint");
}
Christian Kandeler's avatar
Christian Kandeler committed
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732

const MaemoToolChain *MaemoDeployStep::toolChain() const
{
    const Qt4BuildConfiguration * const bc
        = static_cast<Qt4BuildConfiguration *>(buildConfiguration());
    return static_cast<MaemoToolChain *>(bc->toolChain());
}

void MaemoDeployStep::handleSysrootInstallerOutput()
{
    if (!m_stopped) {
        writeOutput(QString::fromLocal8Bit(m_sysrootInstaller->readAllStandardOutput()),
            NormalOutput);
    }
}

void MaemoDeployStep::handleSysrootInstallerErrorOutput()
{
    if (!m_stopped) {
        writeOutput(QString::fromLocal8Bit(m_sysrootInstaller->readAllStandardError()),
            BuildStep::ErrorOutput);
    }
}
733
734
735

void MaemoDeployStep::handleInstallationFinished(int exitStatus)
{
ck's avatar
ck committed
736
737
738
739
740
741
    if (m_stopped) {
        m_mounter->unmount();
        return;
    }

    if (exitStatus != SshRemoteProcess::ExitedNormally
Christian Kandeler's avatar
Christian Kandeler committed
742
        || m_deviceInstaller->exitCode() != 0) {
ck's avatar
ck committed
743
744
745
746
747
748
749
        raiseError(tr("Installing package failed."));
    } else {
        m_needsInstall = false;
        setDeployed(m_connection->connectionParameters().host,
            MaemoDeployable(packagingStep()->packageFilePath(), QString()));
        writeOutput(tr("Package installed."));
    }
Christian Kandeler's avatar
Christian Kandeler committed
750
    m_unmountState = CurrentMountsUnmount;
ck's avatar
ck committed
751
    m_mounter->unmount();
752
753
}

754
755
756
757
758
759
760
761
762
763
764
void MaemoDeployStep::handlePortsGathererError(const QString &errorMsg)
{
    raiseError(errorMsg);
}

void MaemoDeployStep::handlePortListReady()
{
    m_freePorts = deviceConfig().freePorts();
    m_mounter->mount(&m_freePorts, m_portsGatherer);
}

Christian Kandeler's avatar
Christian Kandeler committed
765
void MaemoDeployStep::handleDeviceInstallerOutput(const QByteArray &output)
766
{
Christian Kandeler's avatar
Christian Kandeler committed
767
    writeOutput(QString::fromUtf8(output), NormalOutput);
768
769
}

Christian Kandeler's avatar
Christian Kandeler committed
770
void MaemoDeployStep::handleDeviceInstallerErrorOutput(const QByteArray &output)
771
{
Christian Kandeler's avatar
Christian Kandeler committed
772
    writeOutput(QString::fromUtf8(output), ErrorOutput);
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
}

MaemoDeployEventHandler::MaemoDeployEventHandler(MaemoDeployStep *deployStep,
    QFutureInterface<bool> &future)
    : m_deployStep(deployStep), m_future(future), m_eventLoop(new QEventLoop)
{
    connect(m_deployStep, SIGNAL(done()), this, SLOT(handleDeployingDone()));
    connect(m_deployStep, SIGNAL(error()), this, SLOT(handleDeployingFailed()));
    QTimer cancelChecker;
    connect(&cancelChecker, SIGNAL(timeout()), this, SLOT(checkForCanceled()));
    cancelChecker.start(500);
    future.reportResult(m_eventLoop->exec() == 0);
}

void MaemoDeployEventHandler::handleDeployingDone()
{
    m_eventLoop->exit(0);
}

void MaemoDeployEventHandler::handleDeployingFailed()
{
    m_eventLoop->exit(1);
}

void MaemoDeployEventHandler::checkForCanceled()
{
    if (m_future.isCanceled())
        handleDeployingFailed();
801
802
803
804
}

} // namespace Internal
} // namespace Qt4ProjectManager