maemorunconfiguration.cpp 46.8 KB
Newer Older
ck's avatar
ck committed
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
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 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.
**
**************************************************************************/

#include "maemorunconfiguration.h"

ck's avatar
ck committed
32
#include "maemodeviceconfigurations.h"
ck's avatar
ck committed
33
#include "maemomanager.h"
34
#include "maemosettingspage.h"
ck's avatar
ck committed
35
36
37
#include "maemotoolchain.h"
#include "profilereader.h"
#include "qt4project.h"
38
#include "qt4buildconfiguration.h"
ck's avatar
ck committed
39

40
#include <coreplugin/progressmanager/progressmanager.h>
ck's avatar
ck committed
41
42
43
44
45
46
47
48
49
50
51
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <debugger/debuggermanager.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/pathchooser.h>
#include <utils/qtcassert.h>
#include <projectexplorer/persistentsettings.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/session.h>

#include <QtCore/QDebug>
52
#include <QtCore/QFuture>
kh1's avatar
kh1 committed
53
#include <QtCore/QPair>
ck's avatar
ck committed
54
55
56
#include <QtCore/QProcess>
#include <QtCore/QSharedPointer>

ck's avatar
ck committed
57
#include <QtGui/QComboBox>
ck's avatar
ck committed
58
#include <QtGui/QCheckBox>
ck's avatar
ck committed
59
#include <QtGui/QDesktopServices>
ck's avatar
ck committed
60
61
62
63
64
65
#include <QtGui/QFormLayout>
#include <QtGui/QFrame>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QRadioButton>
66
#include <QtGui/QToolButton>
ck's avatar
ck committed
67
68
69

using namespace ProjectExplorer;

dt's avatar
dt committed
70
71
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
ck's avatar
ck committed
72
73
74
75
76

class MaemoRunConfigurationWidget : public QWidget
{
    Q_OBJECT
public:
ck's avatar
ck committed
77
78
    MaemoRunConfigurationWidget(MaemoRunConfiguration *runConfiguration,
                                QWidget *parent = 0);
ck's avatar
ck committed
79
80
81
82

private slots:
    void configNameEdited(const QString &text);
    void argumentsEdited(const QString &args);
ck's avatar
ck committed
83
84
    void deviceConfigurationChanged(const QString &name);
    void resetDeviceConfigurations();
85
    void showSettingsDialog();
ck's avatar
ck committed
86

87
    void updateSimulatorPath();
kh1's avatar
kh1 committed
88
    void updateTargetInformation();
ck's avatar
ck committed
89
90

private:
ck's avatar
ck committed
91
92
    void setSimInfoVisible(const MaemoDeviceConfigurations::DeviceConfig &devConf);

ck's avatar
ck committed
93
94
95
96
    QLineEdit *m_configNameLineEdit;
    QLineEdit *m_argsLineEdit;
    QLabel *m_executableLabel;
    QLabel *m_debuggerLabel;
ck's avatar
ck committed
97
98
99
    QComboBox *m_devConfBox;
    QLabel *m_simPathNameLabel;
    QLabel *m_simPathValueLabel;
ck's avatar
ck committed
100
101
102
103
104
105
106
107
    MaemoRunConfiguration *m_runConfiguration;
};

class AbstractMaemoRunControl : public ProjectExplorer::RunControl
{
    Q_OBJECT

public:
108
    AbstractMaemoRunControl(RunConfiguration *runConfig);
ck's avatar
ck committed
109
110
111
112
    virtual ~AbstractMaemoRunControl() {}

protected:
    void startDeployment(bool forDebugging);
kh1's avatar
kh1 committed
113
    void deploy();
ck's avatar
ck committed
114
115
116
117
118
119
120
    void stopDeployment();
    bool isDeploying() const;
    const QString executableOnHost() const;
    const QString executableOnTarget() const;
    const QString executableFileName() const;
    const QString port() const;
    const QString targetCmdLinePrefix() const;
ck's avatar
ck committed
121
    const QString remoteDir() const;
122
    const QStringList options() const;
123
    void deploymentFinished(bool success);
ck's avatar
ck committed
124
125
126
127
128
129
130
131
    virtual bool setProcessEnvironment(QProcess &process);
private slots:
    void readStandardError();
    void readStandardOutput();
    void deployProcessFinished();

protected:
    ErrorDumper dumper;
dt's avatar
dt committed
132
    MaemoRunConfiguration *runConfig; // TODO this pointer can be invalid
kh1's avatar
kh1 committed
133
    const MaemoDeviceConfigurations::DeviceConfig devConfig;
ck's avatar
ck committed
134
135

private:
136
137
138
    virtual void handleDeploymentFinished(bool success)=0;

    QFutureInterface<void> m_progress;
ck's avatar
ck committed
139
    QProcess deployProcess;
140
141
142
143
144
145
146
147
148
149
    struct Deployable
    {
        typedef void (MaemoRunConfiguration::*updateFunc)();
        Deployable(const QString &f, const QString &d, updateFunc u)
            : fileName(f), dir(d), updateTimestamp(u) {}
        QString fileName;
        QString dir;
        updateFunc updateTimestamp;
    };
    QList<Deployable> deployables;
ck's avatar
ck committed
150
151
152
153
154
155
};

class MaemoRunControl : public AbstractMaemoRunControl
{
    Q_OBJECT
public:
156
    MaemoRunControl(RunConfiguration *runConfiguration);
ck's avatar
ck committed
157
158
159
160
161
162
163
164
165
    ~MaemoRunControl();
    void start();
    void stop();
    bool isRunning() const;

private slots:
    void executionFinished();

private:
166
    virtual void handleDeploymentFinished(bool success);
ck's avatar
ck committed
167
168
169
170
171
172
173
174
175
176
177
    void startExecution();

    QProcess sshProcess;
    QProcess stopProcess;
    bool stoppedByUser;
};

class MaemoDebugRunControl : public AbstractMaemoRunControl
{
    Q_OBJECT
public:
178
    MaemoDebugRunControl(RunConfiguration *runConfiguration);
ck's avatar
ck committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    ~MaemoDebugRunControl();
    void start();
    void stop();
    bool isRunning() const;
    Q_SLOT void debuggingFinished();

signals:
    void stopRequested();

private slots:
    void gdbServerStarted();
    void debuggerOutput(const QString &output);

private:
193
    virtual void handleDeploymentFinished(bool success);
ck's avatar
ck committed
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

    void startGdbServer();
    void gdbServerStartFailed(const QString &reason);
    void startDebugging();

    QProcess gdbServer;
    QProcess stopProcess;
    const QString gdbServerPort;
    Debugger::DebuggerManager *debuggerManager;
    QSharedPointer<Debugger::DebuggerStartParameters> startParams;
    int inferiorPid;
};

void ErrorDumper::printToStream(QProcess::ProcessError error)
{
    QString reason;
    switch (error) {
        case QProcess::FailedToStart:
            reason = "The process failed to start. Either the invoked program is"
                " missing, or you may have insufficient permissions to invoke "
                "the program.";
            break;

        case QProcess::Crashed:
            reason = "The process crashed some time after starting successfully.";
            break;

        case QProcess::Timedout:
            reason = "The last waitFor...() function timed out. The state of "
                "QProcess is unchanged, and you can try calling waitFor...() "
                "again.";
            break;

        case QProcess::WriteError:
            reason = "An error occurred when attempting to write to the process."
                " For example, the process may not be running, or it may have "
                "closed its input channel.";
            break;

        case QProcess::ReadError:
            reason = "An error occurred when attempting to read from the process."
                " For example, the process may not be running.";
            break;

        default:
            reason = "QProcess::UnknownError";
            break;
    }
    qWarning() << "Failed to run emulator. Reason:" << reason;
}


// #pragma mark -- MaemoRunConfiguration


ck's avatar
ck committed
249
250
251
static const QLatin1String ArgumentsKey("Arguments");
static const QLatin1String SimulatorPathKey("Simulator");
static const QLatin1String DeviceIdKey("DeviceId");
252
253
254
static const QLatin1String LastDeployedKey("LastDeployed");
static const QLatin1String DebuggingHelpersLastDeployedKey(
    "DebuggingHelpersLastDeployed");
ck's avatar
ck committed
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270

MaemoRunConfiguration::MaemoRunConfiguration(Project *project,
        const QString &proFilePath)
    : RunConfiguration(project)
    , m_proFilePath(proFilePath)
    , m_cachedTargetInformationValid(false)
    , m_cachedSimulatorInformationValid(false)
    , qemu(0)
{
    if (!m_proFilePath.isEmpty()) {
        setName(tr("%1 on Maemo device").arg(QFileInfo(m_proFilePath)
            .completeBaseName()));
    } else {
        setName(tr("MaemoRunConfiguration"));
    }

ck's avatar
ck committed
271
272
273
    connect(&MaemoDeviceConfigurations::instance(), SIGNAL(updated()),
            this, SLOT(updateDeviceConfigurations()));

274
275
276
277
278
279
280
281
    connect(project, SIGNAL(targetInformationChanged()),
            this, SLOT(invalidateCachedTargetInformation()));

    connect(project, SIGNAL(targetInformationChanged()),
            this, SLOT(enabledStateChanged()));

    connect(project, SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode*)),
            this, SLOT(proFileUpdate(Qt4ProjectManager::Internal::Qt4ProFileNode*)));
ck's avatar
ck committed
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

    qemu = new QProcess(this);
    connect(qemu, SIGNAL(error(QProcess::ProcessError)), &dumper,
        SLOT(printToStream(QProcess::ProcessError)));
    connect(qemu, SIGNAL(finished(int, QProcess::ExitStatus)), this,
        SLOT(qemuProcessFinished()));
}

MaemoRunConfiguration::~MaemoRunConfiguration()
{
    if (qemu && qemu->state() != QProcess::NotRunning) {
        qemu->terminate();
        qemu->kill();
    }
    delete qemu;
    qemu = NULL;
}

QString MaemoRunConfiguration::type() const
{
    return QLatin1String("Qt4ProjectManager.MaemoRunConfiguration");
}

Qt4Project *MaemoRunConfiguration::project() const
{
    Qt4Project *pro = qobject_cast<Qt4Project *>(RunConfiguration::project());
    Q_ASSERT(pro != 0);
    return pro;
}

312
bool MaemoRunConfiguration::isEnabled(ProjectExplorer::BuildConfiguration *config) const
ck's avatar
ck committed
313
{
314
    Qt4BuildConfiguration *qt4bc = qobject_cast<Qt4BuildConfiguration*>(config);
315
316
    QTC_ASSERT(qt4bc, return false);
    ToolChain::ToolChainType type = qt4bc->toolChainType();
ck's avatar
ck committed
317
318
319
320
321
322
323
324
    return type == ToolChain::GCC_MAEMO;
}

QWidget *MaemoRunConfiguration::configurationWidget()
{
    return new MaemoRunConfigurationWidget(this);
}

325
326
327
328
329
330
331
void MaemoRunConfiguration::proFileUpdate(Qt4ProjectManager::Internal::Qt4ProFileNode *pro)
{
    if (m_proFilePath == pro->path())
        invalidateCachedTargetInformation();
}


ck's avatar
ck committed
332
333
void MaemoRunConfiguration::save(PersistentSettingsWriter &writer) const
{
ck's avatar
ck committed
334
335
    writer.saveValue(DeviceIdKey, m_devConfig.internalId);
    writer.saveValue(ArgumentsKey, m_arguments);
336

ck's avatar
ck committed
337
338
339
340
    writer.saveValue(LastDeployedKey, m_lastDeployed);
    writer.saveValue(DebuggingHelpersLastDeployedKey,
        m_debuggingHelpersLastDeployed);

ck's avatar
ck committed
341
    writer.saveValue(SimulatorPathKey, m_simulatorPath);
342

ck's avatar
ck committed
343
344
345
346
347
348
349
350
351
352
    const QDir &dir = QFileInfo(project()->file()->fileName()).absoluteDir();
    writer.saveValue("ProFile", dir.relativeFilePath(m_proFilePath));

    RunConfiguration::save(writer);
}

void MaemoRunConfiguration::restore(const PersistentSettingsReader &reader)
{
    RunConfiguration::restore(reader);

ck's avatar
ck committed
353
354
355
    setDeviceConfig(MaemoDeviceConfigurations::instance().
        find(reader.restoreValue(DeviceIdKey).toInt()));
    m_arguments = reader.restoreValue(ArgumentsKey).toStringList();
356

ck's avatar
ck committed
357
358
359
360
    m_lastDeployed = reader.restoreValue(LastDeployedKey).toDateTime();
    m_debuggingHelpersLastDeployed =
        reader.restoreValue(DebuggingHelpersLastDeployedKey).toDateTime();

ck's avatar
ck committed
361
    m_simulatorPath = reader.restoreValue(SimulatorPathKey).toString();
362

ck's avatar
ck committed
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
    const QDir &dir = QFileInfo(project()->file()->fileName()).absoluteDir();
    m_proFilePath = dir.filePath(reader.restoreValue("ProFile").toString());
}

bool MaemoRunConfiguration::currentlyNeedsDeployment() const
{
    return fileNeedsDeployment(executable(), m_lastDeployed);
}

void MaemoRunConfiguration::wasDeployed()
{
    m_lastDeployed = QDateTime::currentDateTime();
}

bool MaemoRunConfiguration::hasDebuggingHelpers() const
{
dt's avatar
dt committed
379
    Qt4BuildConfiguration *qt4bc = project()->activeQt4BuildConfiguration();
380
    return qt4bc->qtVersion()->hasDebuggingHelper();
ck's avatar
ck committed
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
}

bool MaemoRunConfiguration::debuggingHelpersNeedDeployment() const
{
    if (hasDebuggingHelpers())
        return fileNeedsDeployment(dumperLib(), m_debuggingHelpersLastDeployed);
    return false;
}

void MaemoRunConfiguration::debuggingHelpersDeployed()
{
    m_debuggingHelpersLastDeployed = QDateTime::currentDateTime();
}

bool MaemoRunConfiguration::fileNeedsDeployment(const QString &path,
    const QDateTime &lastDeployed) const
{
    return !lastDeployed.isValid()
        || QFileInfo(path).lastModified() > lastDeployed;
}

ck's avatar
ck committed
402
403
void MaemoRunConfiguration::setDeviceConfig(
    const MaemoDeviceConfigurations::DeviceConfig &devConf)
404
{
ck's avatar
ck committed
405
    m_devConfig = devConf;
406
407
}

ck's avatar
ck committed
408
MaemoDeviceConfigurations::DeviceConfig MaemoRunConfiguration::deviceConfig() const
409
{
ck's avatar
ck committed
410
    return m_devConfig;
ck's avatar
ck committed
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
}

const QString MaemoRunConfiguration::sshCmd() const
{
    return cmd(QString::fromLocal8Bit("ssh"));
}

const QString MaemoRunConfiguration::scpCmd() const
{
    return cmd(QString::fromLocal8Bit("scp"));
}

const QString MaemoRunConfiguration::cmd(const QString &cmdName) const
{
    QString command(cmdName);
#ifdef Q_OS_WIN
    command = maddeRoot() + QLatin1String("/bin/") + command
          + QLatin1String(".exe");
#endif
    return command;
}

const MaemoToolChain *MaemoRunConfiguration::toolchain() const
{
kh1's avatar
kh1 committed
435
436
    Qt4BuildConfiguration *qt4bc = qobject_cast<Qt4BuildConfiguration *>
        (project()->activeBuildConfiguration());
437
    QTC_ASSERT(qt4bc, return 0);
ck's avatar
ck committed
438
    MaemoToolChain *tc = dynamic_cast<MaemoToolChain *>(
439
        qt4bc->toolChain() );
ck's avatar
ck committed
440
441
442
443
444
445
    QTC_ASSERT(tc != 0, return 0);
    return tc;
}

const QString MaemoRunConfiguration::gdbCmd() const
{
446
447
448
    if (const MaemoToolChain *tc = toolchain())
        return tc->targetRoot() + "/bin/gdb";
    return QString();
ck's avatar
ck committed
449
450
451
452
}

QString MaemoRunConfiguration::maddeRoot() const
{
453
    if (const MaemoToolChain *tc = toolchain())
kh1's avatar
kh1 committed
454
        return tc->maddeRoot();
455
    return QString();
ck's avatar
ck committed
456
457
458
459
}

const QString MaemoRunConfiguration::sysRoot() const
{
460
    if (const MaemoToolChain *tc = toolchain())
ck's avatar
ck committed
461
        return tc->sysrootRoot();
462
    return QString();
ck's avatar
ck committed
463
464
}

465
466
const QStringList MaemoRunConfiguration::arguments() const
{
ck's avatar
ck committed
467
    return m_arguments;
468
469
}

ck's avatar
ck committed
470
471
const QString MaemoRunConfiguration::dumperLib() const
{
dt's avatar
dt committed
472
    Qt4BuildConfiguration *qt4bc = project()->activeQt4BuildConfiguration();
473
    return qt4bc->qtVersion()->debuggingHelperLibrary();
ck's avatar
ck committed
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
}

QString MaemoRunConfiguration::executable() const
{
    const_cast<MaemoRunConfiguration*> (this)->updateTarget();
    return m_executable;
}

QString MaemoRunConfiguration::simulatorPath() const
{
    qDebug("MaemoRunConfiguration::simulatorPath() called, %s",
        qPrintable(m_simulatorPath));

    const_cast<MaemoRunConfiguration*> (this)->updateSimulatorInformation();
    return m_simulatorPath;
}

QString MaemoRunConfiguration::visibleSimulatorParameter() const
{
    qDebug("MaemoRunConfiguration::visibleSimulatorParameter() called");

    const_cast<MaemoRunConfiguration*> (this)->updateSimulatorInformation();
    return m_visibleSimulatorParameter;
}

QString MaemoRunConfiguration::simulator() const
{
    const_cast<MaemoRunConfiguration*> (this)->updateSimulatorInformation();
    return m_simulator;
}

QString MaemoRunConfiguration::simulatorArgs() const
{
    const_cast<MaemoRunConfiguration*> (this)->updateSimulatorInformation();
    return m_simulatorArgs;
}

void MaemoRunConfiguration::setArguments(const QStringList &args)
{
ck's avatar
ck committed
513
    m_arguments = args;
ck's avatar
ck committed
514
515
516
517
518
519
520
521
522
523
524
525
526
527
}


bool MaemoRunConfiguration::isQemuRunning() const
{
    return (qemu && qemu->state() != QProcess::NotRunning);
}

void MaemoRunConfiguration::invalidateCachedTargetInformation()
{
    m_cachedTargetInformationValid = false;
    emit targetInformationChanged();
}

528
void MaemoRunConfiguration::setUserSimulatorPath(const QString &path)
ck's avatar
ck committed
529
{
530
    qDebug("MaemoRunConfiguration::setUserSimulatorPath() called, "
ck's avatar
ck committed
531
532
533
        "m_simulatorPath: %s, new path: %s", qPrintable(m_simulatorPath),
        qPrintable(path));

534
535
    m_isUserSetSimulator = true;
    if (m_userSimulatorPath != path)
ck's avatar
ck committed
536
537
        m_cachedSimulatorInformationValid = false;

538
    m_userSimulatorPath = path;
ck's avatar
ck committed
539
540
541
542
543
544
545
546
547
548
549
550
    emit cachedSimulatorInformationChanged();
}

void MaemoRunConfiguration::invalidateCachedSimulatorInformation()
{
    qDebug("MaemoRunConfiguration::invalidateCachedSimulatorInformation() "
        "called");

    m_cachedSimulatorInformationValid = false;
    emit cachedSimulatorInformationChanged();
}

551
552
553
554
555
556
557
558
559
void MaemoRunConfiguration::resetCachedSimulatorInformation()
{
    m_userSimulatorPath.clear();
    m_isUserSetSimulator = false;

    m_cachedSimulatorInformationValid = false;
    emit cachedSimulatorInformationChanged();
}

ck's avatar
ck committed
560
561
562
563
564
565
566
567
void MaemoRunConfiguration::updateTarget()
{
    if (m_cachedTargetInformationValid)
        return;

    m_executable = QString::null;
    m_cachedTargetInformationValid = true;

dt's avatar
dt committed
568
569
    if (Qt4Project *qt4Project = project()) {
        Qt4BuildConfiguration *qt4bc = qt4Project->activeQt4BuildConfiguration();
570
571
        Qt4ProFileNode *proFileNode = qt4Project->rootProjectNode()->findProFileFor(m_proFilePath);
        if (!proFileNode) {
ck's avatar
ck committed
572
573
574
575
            emit targetInformationChanged();
            return;
        }

576
        ProFileReader *reader = qt4Project->createProFileReader(proFileNode);
ck's avatar
ck committed
577
578
        reader->setCumulative(false);

579
        // Find out what flags we pass on to qmake
ck's avatar
ck committed
580
581
        QStringList addedUserConfigArguments;
        QStringList removedUserConfigArguments;
582
583
        qt4bc->getConfigCommandLineArguments(&addedUserConfigArguments, &removedUserConfigArguments);
        reader->setConfigCommandLineArguments(addedUserConfigArguments, removedUserConfigArguments);
ck's avatar
ck committed
584
585

        if (!reader->readProFile(m_proFilePath)) {
586
            qt4Project->destroyProFileReader(reader);
ck's avatar
ck committed
587
588
589
590
591
592
593
594
595
596
597
598
            Core::ICore::instance()->messageManager()->printToOutputPane(tr(
                "Could not parse %1. The Maemo run configuration %2 "
                "can not be started.").arg(m_proFilePath).arg(name()));
            emit targetInformationChanged();
            return;
        }

        // Extract data
        QDir baseProjectDirectory =
            QFileInfo(project()->file()->fileName()).absoluteDir();
        QString relSubDir =
            baseProjectDirectory.relativeFilePath(QFileInfo(m_proFilePath).path());
599
        QDir baseBuildDirectory = qt4bc->buildDirectory();
ck's avatar
ck committed
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
        QString baseDir = baseBuildDirectory.absoluteFilePath(relSubDir);

        if (!reader->contains("DESTDIR")) {
#if 0   // TODO: fix this, seems to be wrong on windows
            if (reader->values("CONFIG").contains("debug_and_release_target")) {
                QString qmakeBuildConfig = "release";
                if (projectBuildConfiguration & QtVersion::DebugBuild)
                    qmakeBuildConfig = "debug";
                baseDir += QLatin1Char('/') + qmakeBuildConfig;
            }
#endif
        } else {
            const QString &destDir = reader->value("DESTDIR");
            if (QDir::isRelativePath(destDir))
                baseDir += QLatin1Char('/') + destDir;
            else
                baseDir = destDir;
        }

        QString target = reader->value("TARGET");
        if (target.isEmpty())
            target = QFileInfo(m_proFilePath).baseName();

        m_executable = QDir::cleanPath(baseDir + QLatin1Char('/') + target);
624
        qt4Project->destroyProFileReader(reader);
ck's avatar
ck committed
625
626
627
628
629
630
631
632
633
634
635
636
637
    }

    emit targetInformationChanged();
}

void MaemoRunConfiguration::updateSimulatorInformation()
{
    if (m_cachedSimulatorInformationValid)
        return;

    m_simulator = QString::null;
    m_simulatorArgs == QString::null;
    m_cachedSimulatorInformationValid = true;
638
639
640
641
    m_simulatorPath = QDir::toNativeSeparators(m_userSimulatorPath);
    m_visibleSimulatorParameter = tr("Could not autodetect target simulator, "
        "please choose one on your own.");

642
643
644
645
    if (!m_isUserSetSimulator) {
        if (const MaemoToolChain *tc = toolchain())
            m_simulatorPath = QDir::toNativeSeparators(tc->simulatorRoot());
    }
ck's avatar
ck committed
646
647
648
649
650
651

    if (!m_simulatorPath.isEmpty()) {
        m_visibleSimulatorParameter = tr("'%1' is not a valid Maemo simulator.")
            .arg(m_simulatorPath);
    }

652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
    QDir dir(m_simulatorPath);
    if (dir.exists(m_simulatorPath)) {
        const QStringList &files = dir.entryList(QDir::Files | QDir::NoSymLinks
            | QDir::NoDotAndDotDot);
        if (files.count() >= 2) {
            const QLatin1String info("information");
            if (files.contains(info)) {
                QFile file(m_simulatorPath + QLatin1Char('/') + info);
                if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                    QMap<QString, QString> map;
                    QTextStream stream(&file);
                    while (!stream.atEnd()) {
                        const QString &line = stream.readLine().trimmed();
                        const int index = line.indexOf(QLatin1Char('='));
                        map.insert(line.mid(0, index).remove(QLatin1Char('\'')),
                            line.mid(index + 1).remove(QLatin1Char('\'')));
                    }

                    m_simulator = map.value(QLatin1String("runcommand"));
                    m_simulatorArgs = map.value(QLatin1String("runcommand_args"));

                    m_visibleSimulatorParameter = m_simulator
ck's avatar
ck committed
674
#ifdef Q_OS_WIN
675
                        + QLatin1String(".exe")
ck's avatar
ck committed
676
#endif
677
678
                        + QLatin1Char(' ') + m_simulatorArgs;
                }
ck's avatar
ck committed
679
680
            }
        }
681
682
683
    } else {
        m_visibleSimulatorParameter = tr("'%1' could not be found. Please "
            "choose a simulator on your own.").arg(m_simulatorPath);
ck's avatar
ck committed
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
    }

    emit cachedSimulatorInformationChanged();
}

void MaemoRunConfiguration::startStopQemu()
{
    if (qemu->state() != QProcess::NotRunning) {
        if (qemu->state() == QProcess::Running) {
            qemu->terminate();
            qemu->kill();
            emit qemuProcessStatus(false);
        }
        return;
    }

    QString root = maddeRoot();
    if (root.isEmpty() || simulator().isEmpty())
        return;

    const QLatin1Char colon(';');
    const QString path = QDir::toNativeSeparators(root + QLatin1Char('/'));

    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    env.insert("PATH", env.value("Path") + colon + path + QLatin1String("bin"));
    env.insert("PATH", env.value("Path") + colon + path + QLatin1String("madlib"));

    qemu->setProcessEnvironment(env);
    qemu->setWorkingDirectory(simulatorPath());

    QString app = root + QLatin1String("/madlib/") + simulator()
#ifdef Q_OS_WIN
        + QLatin1String(".exe")
#endif
    ;   // keep

    qemu->start(app + QLatin1Char(' ') + simulatorArgs(), QIODevice::ReadWrite);
    emit qemuProcessStatus(qemu->waitForStarted());
}

void MaemoRunConfiguration::qemuProcessFinished()
{
    emit qemuProcessStatus(false);
}

void MaemoRunConfiguration::enabledStateChanged()
{
    MaemoManager::instance()->setQemuSimulatorStarterEnabled(isEnabled());
}

ck's avatar
ck committed
734
735
736
737
738
739
740
741
742
void MaemoRunConfiguration::updateDeviceConfigurations()
{
    qDebug("%s: Current devid = %llu", Q_FUNC_INFO, m_devConfig.internalId);
    m_devConfig =
        MaemoDeviceConfigurations::instance().find(m_devConfig.internalId);
    qDebug("%s: new devid = %llu", Q_FUNC_INFO, m_devConfig.internalId);
    emit deviceConfigurationsUpdated();
}

ck's avatar
ck committed
743
744
745
746
747
748
749
750
751
752

// #pragma mark -- MaemoRunConfigurationWidget

MaemoRunConfigurationWidget::MaemoRunConfigurationWidget(
        MaemoRunConfiguration *runConfiguration, QWidget *parent)
    : QWidget(parent)
    , m_runConfiguration(runConfiguration)
{
    QFormLayout *mainLayout = new QFormLayout;
    setLayout(mainLayout);
dt's avatar
dt committed
753

ck's avatar
ck committed
754
755
756
    mainLayout->setFormAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    m_configNameLineEdit = new QLineEdit(m_runConfiguration->name());
    mainLayout->addRow(tr("Run configuration name:"), m_configNameLineEdit);
757
758
    QWidget *devConfWidget = new QWidget;
    QHBoxLayout *devConfLayout = new QHBoxLayout(devConfWidget);
ck's avatar
ck committed
759
    m_devConfBox = new QComboBox;
760
    m_devConfBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
761
762
763
764
765
    devConfLayout->addWidget(m_devConfBox);
    QLabel *addDevConfLabel
        = new QLabel(tr("<a href=\"#\">Manage device configurations</a>"));
    devConfLayout->addWidget(addDevConfLabel);
    mainLayout->addRow(new QLabel(tr("Device Configuration:")), devConfWidget);
ck's avatar
ck committed
766
767
768
769
770
771
    m_executableLabel = new QLabel(m_runConfiguration->executable());
    mainLayout->addRow(tr("Executable:"), m_executableLabel);
    m_argsLineEdit = new QLineEdit(m_runConfiguration->arguments().join(" "));
    mainLayout->addRow(tr("Arguments:"), m_argsLineEdit);
    m_debuggerLabel = new QLabel(m_runConfiguration->gdbCmd());
    mainLayout->addRow(tr("Debugger:"), m_debuggerLabel);
772
    mainLayout->addItem(new QSpacerItem(10, 10));
ck's avatar
ck committed
773
774
775
776
    m_simPathNameLabel = new QLabel(tr("Simulator Path:"));
    m_simPathValueLabel = new QLabel(m_runConfiguration->simulatorPath());
    mainLayout->addRow(m_simPathNameLabel, m_simPathValueLabel);
    resetDeviceConfigurations();
ck's avatar
ck committed
777

778
779
    connect(m_runConfiguration, SIGNAL(cachedSimulatorInformationChanged()),
        this, SLOT(updateSimulatorPath()));
ck's avatar
ck committed
780
781
    connect(m_runConfiguration, SIGNAL(deviceConfigurationsUpdated()),
            this, SLOT(resetDeviceConfigurations()));
ck's avatar
ck committed
782
783
784
785
786

    connect(m_configNameLineEdit, SIGNAL(textEdited(QString)), this,
        SLOT(configNameEdited(QString)));
    connect(m_argsLineEdit, SIGNAL(textEdited(QString)), this,
        SLOT(argumentsEdited(QString)));
ck's avatar
ck committed
787
788
    connect(m_devConfBox, SIGNAL(activated(QString)), this,
            SLOT(deviceConfigurationChanged(QString)));
ck's avatar
ck committed
789
790
    connect(m_runConfiguration, SIGNAL(targetInformationChanged()), this,
        SLOT(updateTargetInformation()));
791
792
    connect(addDevConfLabel, SIGNAL(linkActivated(QString)), this,
        SLOT(showSettingsDialog()));
ck's avatar
ck committed
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
}

void MaemoRunConfigurationWidget::configNameEdited(const QString &text)
{
    m_runConfiguration->setName(text);
}

void MaemoRunConfigurationWidget::argumentsEdited(const QString &text)
{
    m_runConfiguration->setArguments(text.split(' ', QString::SkipEmptyParts));
}

void MaemoRunConfigurationWidget::updateTargetInformation()
{
    m_executableLabel->setText(m_runConfiguration->executable());
}

810
811
void MaemoRunConfigurationWidget::updateSimulatorPath()
{
ck's avatar
ck committed
812
    m_simPathValueLabel->setText(m_runConfiguration->simulatorPath());
813
814
}

ck's avatar
ck committed
815
void MaemoRunConfigurationWidget::deviceConfigurationChanged(const QString &name)
ck's avatar
ck committed
816
{
ck's avatar
ck committed
817
818
819
820
    const MaemoDeviceConfigurations::DeviceConfig &devConfig =
            MaemoDeviceConfigurations::instance().find(name);
    setSimInfoVisible(devConfig);
    m_runConfiguration->setDeviceConfig(devConfig);
ck's avatar
ck committed
821
822
}

ck's avatar
ck committed
823
824
void MaemoRunConfigurationWidget::setSimInfoVisible(
    const MaemoDeviceConfigurations::DeviceConfig &devConf)
ck's avatar
ck committed
825
{
ck's avatar
ck committed
826
827
828
829
    const bool isSimulator =
        devConf.type == MaemoDeviceConfigurations::DeviceConfig::Simulator;
    m_simPathNameLabel->setVisible(isSimulator);
    m_simPathValueLabel->setVisible(isSimulator);
ck's avatar
ck committed
830
831
}

ck's avatar
ck committed
832
void MaemoRunConfigurationWidget::resetDeviceConfigurations()
ck's avatar
ck committed
833
{
ck's avatar
ck committed
834
835
836
837
838
839
840
841
842
843
    m_devConfBox->clear();
    const QList<MaemoDeviceConfigurations::DeviceConfig> &devConfs =
        MaemoDeviceConfigurations::instance().devConfigs();
    foreach (const MaemoDeviceConfigurations::DeviceConfig &devConf, devConfs)
        m_devConfBox->addItem(devConf.name);
    m_devConfBox->addItem(MaemoDeviceConfigurations::DeviceConfig().name);
    const MaemoDeviceConfigurations::DeviceConfig &devConf =
        m_runConfiguration->deviceConfig();
    m_devConfBox->setCurrentIndex(m_devConfBox->findText(devConf.name));
    setSimInfoVisible(devConf);
ck's avatar
ck committed
844
845
}

846
847
848
849
850
851
852
void MaemoRunConfigurationWidget::showSettingsDialog()
{
    MaemoSettingsPage *settingsPage = MaemoManager::instance()->settingsPage();
    Core::ICore::instance()->showOptionsDialog(settingsPage->category(),
                                               settingsPage->id());
}

ck's avatar
ck committed
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
// #pragma mark -- MaemoRunConfigurationFactory


MaemoRunConfigurationFactory::MaemoRunConfigurationFactory(QObject* parent)
    : IRunConfigurationFactory(parent)
{
}

MaemoRunConfigurationFactory::~MaemoRunConfigurationFactory()
{
}

bool MaemoRunConfigurationFactory::canRestore(const QString &type) const
{
    return type == "Qt4ProjectManager.MaemoRunConfiguration";
}

QStringList MaemoRunConfigurationFactory::availableCreationTypes(
    Project *pro) const
{
    Qt4Project *qt4project = qobject_cast<Qt4Project *>(pro);
    if (qt4project) {
        QStringList applicationProFiles;
        QList<Qt4ProFileNode *> list = qt4project->applicationProFiles();
        foreach (Qt4ProFileNode * node, list) {
            applicationProFiles.append("MaemoRunConfiguration." + node->path());
        }
        return applicationProFiles;
    }
    return QStringList();
}

QString MaemoRunConfigurationFactory::displayNameForType(
    const QString &type) const
{
    const int size = QString::fromLocal8Bit("MaemoRunConfiguration.").size();
889
    return tr("%1 on Maemo Device").arg(QFileInfo(type.mid(size))
ck's avatar
ck committed
890
891
892
        .completeBaseName());
}

893
RunConfiguration *MaemoRunConfigurationFactory::create(Project *project,
ck's avatar
ck committed
894
895
896
897
898
899
900
901
902
903
    const QString &type)
{
    Qt4Project *qt4project = qobject_cast<Qt4Project *>(project);
    Q_ASSERT(qt4project);

    connect(project, SIGNAL(addedRunConfiguration(ProjectExplorer::Project*,
        QString)), this, SLOT(addedRunConfiguration(ProjectExplorer::Project*)));
    connect(project, SIGNAL(removedRunConfiguration(ProjectExplorer::Project*,
        QString)), this, SLOT(removedRunConfiguration(ProjectExplorer::Project*)));

904
    RunConfiguration *rc = 0;
ck's avatar
ck committed
905
906
    const QLatin1String prefix("MaemoRunConfiguration.");
    if (type.startsWith(prefix)) {
907
        rc = new MaemoRunConfiguration(qt4project, type.mid(QString(prefix).size()));
ck's avatar
ck committed
908
909
    } else {
        Q_ASSERT(type == "Qt4ProjectManager.MaemoRunConfiguration");
910
        rc = new MaemoRunConfiguration(qt4project, QString::null);
ck's avatar
ck committed
911
912
    }

913
    if (rc) {
ck's avatar
ck committed
914
        connect(project, SIGNAL(runConfigurationsEnabledStateChanged()),
915
916
            rc, SLOT(enabledStateChanged()));
        connect(MaemoManager::instance(), SIGNAL(startStopQemu()), rc,
ck's avatar
ck committed
917
            SLOT(startStopQemu()));
918
        connect(rc, SIGNAL(qemuProcessStatus(bool)),
ck's avatar
ck committed
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
            MaemoManager::instance(), SLOT(updateQemuSimulatorStarter(bool)));
    }

    ProjectExplorerPlugin *explorer = ProjectExplorerPlugin::instance();
    connect(explorer->session(), SIGNAL(projectAdded(ProjectExplorer::Project*)),
        this, SLOT(projectAdded(ProjectExplorer::Project*)));
    connect(explorer->session(), SIGNAL(projectRemoved(ProjectExplorer::Project*)),
        this, SLOT(projectRemoved(ProjectExplorer::Project*)));
    connect(explorer, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
        this, SLOT(currentProjectChanged(ProjectExplorer::Project*)));

    return rc;
}

bool hasMaemoRunConfig(ProjectExplorer::Project* project)
{
    if (Qt4Project *qt4Project = qobject_cast<Qt4Project *>(project)) {
936
937
938
        QList<RunConfiguration *> list = qt4Project->runConfigurations();
        foreach (RunConfiguration *rc, list) {
            if (qobject_cast<MaemoRunConfiguration *>(rc))
ck's avatar
ck committed
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
                return true;
        }
    }
    return false;
}

void MaemoRunConfigurationFactory::addedRunConfiguration(
    ProjectExplorer::Project* project)
{
    if (hasMaemoRunConfig(project))
        MaemoManager::instance()->addQemuSimulatorStarter(project);
}

void MaemoRunConfigurationFactory::removedRunConfiguration(
    ProjectExplorer::Project* project)
{
    if (!hasMaemoRunConfig(project))
        MaemoManager::instance()->removeQemuSimulatorStarter(project);
}

void MaemoRunConfigurationFactory::projectAdded(
    ProjectExplorer::Project* project)
{
    if (hasMaemoRunConfig(project))
        MaemoManager::instance()->addQemuSimulatorStarter(project);
}

void MaemoRunConfigurationFactory::projectRemoved(
    ProjectExplorer::Project* project)
{
    if (hasMaemoRunConfig(project))
        MaemoManager::instance()->removeQemuSimulatorStarter(project);
}

void MaemoRunConfigurationFactory::currentProjectChanged(
    ProjectExplorer::Project* project)
{
    bool hasRunConfig = hasMaemoRunConfig(project);
    MaemoManager::instance()->setQemuSimulatorStarterEnabled(hasRunConfig);

    bool isRunning = false;
    if (Qt4Project *qt4Project = qobject_cast<Qt4Project *>(project)) {
981
982
983
        RunConfiguration *rc = qt4Project->activeRunConfiguration();
        if (MaemoRunConfiguration *mrc = qobject_cast<MaemoRunConfiguration *>(rc))
            isRunning = mrc->isQemuRunning();
ck's avatar
ck committed
984
985
986
987
988
989
990
991
992
993
994
995
996
    }
    MaemoManager::instance()->updateQemuSimulatorStarter(isRunning);
}


// #pragma mark -- MaemoRunControlFactory


MaemoRunControlFactory::MaemoRunControlFactory(QObject *parent)
    : IRunControlFactory(parent)
{
}

997
bool MaemoRunControlFactory::canRun(RunConfiguration *runConfiguration,
ck's avatar
ck committed
998
999
    const QString &mode) const
{
1000
    return qobject_cast<MaemoRunConfiguration *>(runConfiguration)
ck's avatar
ck committed
1001
1002
1003
1004
        && (mode == ProjectExplorer::Constants::RUNMODE
        || mode == ProjectExplorer::Constants::DEBUGMODE);
}

1005
RunControl* MaemoRunControlFactory::create(RunConfiguration *runConfig,
ck's avatar
ck committed
1006
1007
    const QString &mode)
{
dt's avatar
dt committed
1008
    MaemoRunConfiguration *rc = qobject_cast<MaemoRunConfiguration *>(runConfig);
1009
    Q_ASSERT(rc);
ck's avatar
ck committed
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
    Q_ASSERT(mode == ProjectExplorer::Constants::RUNMODE
        || mode == ProjectExplorer::Constants::DEBUGMODE);
    if (mode == ProjectExplorer::Constants::RUNMODE)
        return new MaemoRunControl(rc);
    return new MaemoDebugRunControl(rc);
}

QString MaemoRunControlFactory::displayName() const
{
    return tr("Run on device");
}

1022
QWidget* MaemoRunControlFactory::configurationWidget(RunConfiguration *config)
ck's avatar
ck committed
1023
1024
1025
1026
1027
1028
1029
1030
1031
{
    Q_UNUSED(config)
    return 0;
}


// #pragma mark -- AbstractMaemoRunControl


1032
AbstractMaemoRunControl::AbstractMaemoRunControl(RunConfiguration *rc)
ck's avatar
ck committed
1033
    : RunControl(rc)
1034
    , runConfig(qobject_cast<MaemoRunConfiguration *>(rc))
ck's avatar
ck committed
1035
1036
    , devConfig(runConfig ? runConfig->deviceConfig()
                          : MaemoDeviceConfigurations::DeviceConfig())
ck's avatar
ck committed
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
{
    setProcessEnvironment(deployProcess);

    connect(&deployProcess, SIGNAL(readyReadStandardError()), this,
        SLOT(readStandardError()));
    connect(&deployProcess, SIGNAL(readyReadStandardOutput()), this,
        SLOT(readStandardOutput()));
    connect(&deployProcess, SIGNAL(error(QProcess::ProcessError)), &dumper,
        SLOT(printToStream(QProcess::ProcessError)));
    connect(&deployProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this,
        SLOT(deployProcessFinished()));
}

void AbstractMaemoRunControl::startDeployment(bool forDebugging)
{
dt's avatar
dt committed
1052
    QTC_ASSERT(runConfig, return);
kh1's avatar
kh1 committed
1053

1054
1055
    Core::ICore::instance()->progressManager()->addTask(m_progress.future(),
        tr("Deploying"), QLatin1String("Maemo.Deploy"));
kh1's avatar
kh1 committed
1056
1057
1058
    if (devConfig.isValid()) {
        deployables.clear();
        if (runConfig->currentlyNeedsDeployment()) {
1059
1060
1061
            deployables.append(Deployable(executableFileName(),
                QFileInfo(executableOnHost()).canonicalPath(),
                &MaemoRunConfiguration::wasDeployed));
kh1's avatar
kh1 committed
1062
1063
1064
        }
        if (forDebugging && runConfig->debuggingHelpersNeedDeployment()) {
            const QFileInfo &info(runConfig->dumperLib());
1065
1066
            deployables.append(Deployable(info.fileName(), info.canonicalPath(),
                &MaemoRunConfiguration::debuggingHelpersDeployed));
kh1's avatar
kh1 committed
1067
1068
        }

1069
1070
1071
        m_progress.setProgressRange(0, deployables.count());
        m_progress.setProgressValue(0);
        m_progress.reportStarted();
kh1's avatar
kh1 committed
1072
        deploy();
ck's avatar
ck committed
1073
    } else {
kh1's avatar
kh1 committed
1074
        deploymentFinished(false);
ck's avatar
ck committed
1075
    }
kh1's avatar
kh1 committed
1076
1077
1078
1079
}

void AbstractMaemoRunControl::deploy()
{
ck's avatar
ck committed
1080
    if (!deployables.isEmpty()) {
1081
1082
        const Deployable &deployable = deployables.first();
        emit addToOutputWindow(this, tr("File to deploy: %1.").arg(deployable.fileName));
kh1's avatar
kh1 committed
1083

ck's avatar
ck committed
1084
        QStringList cmdArgs;
1085
1086
1087
        cmdArgs << "-P" << port() << options() << deployable.fileName
            << (devConfig.uname + "@" + devConfig.host + ":" + remoteDir());
        deployProcess.setWorkingDirectory(deployable.dir);
kh1's avatar
kh1 committed
1088

ck's avatar
ck committed
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
        deployProcess.start(runConfig->scpCmd(), cmdArgs);
        if (!deployProcess.waitForStarted()) {
            emit error(this, tr("Could not start scp. Deployment failed."));
            deployProcess.kill();
        } else {
            emit started();
        }
    } else {
        deploymentFinished(true);
    }
}

void AbstractMaemoRunControl::stopDeployment()
{
    deployProcess.kill();
}

bool AbstractMaemoRunControl::isDeploying() const
{
    return deployProcess.state() != QProcess::NotRunning;
}

void AbstractMaemoRunControl::deployProcessFinished()
{
    bool success;
    if (deployProcess.exitCode() == 0) {
        emit addToOutputWindow(this, tr("Target deployed."));
        success = true;
1117
1118
1119
        Deployable deployable = deployables.takeFirst();
        (runConfig->*deployable.updateTimestamp)();
        m_progress.setProgressValue(m_progress.progressValue() + 1);
ck's avatar
ck committed
1120
1121
1122
1123
    } else {
        emit error(this, tr("Deployment failed."));
        success = false;
    }
kh1's avatar
kh1 committed
1124
1125
1126
1127
    if (deployables.isEmpty() || !success)
        deploymentFinished(success);
    else
        deploy();
ck's avatar
ck committed
1128
1129
}

1130
1131
1132
1133
1134
1135
void AbstractMaemoRunControl::deploymentFinished(bool success)
{
    m_progress.reportFinished();
    handleDeploymentFinished(success);
}

ck's avatar
ck committed
1136
1137
1138
1139
1140
1141
1142
const QString AbstractMaemoRunControl::executableOnHost() const
{
    return runConfig->executable();
}

const QString AbstractMaemoRunControl::port() const
{
ck's avatar
ck committed
1143
    return QString::number(devConfig.port);
ck's avatar
ck committed
1144
1145
1146
1147
1148
1149
1150
}

const QString AbstractMaemoRunControl::executableFileName() const
{
    return QFileInfo(executableOnHost()).fileName();
}

ck's avatar
ck committed
1151
1152
1153
1154
1155
1156
1157
const QString AbstractMaemoRunControl::remoteDir() const
{
    return devConfig.uname == QString::fromLocal8Bit("root")
        ? QString::fromLocal8Bit("/root")
        : QString::fromLocal8Bit("/home/") + devConfig.uname;
}

1158
1159
1160
1161
1162
const QStringList AbstractMaemoRunControl::options() const
{
    const bool usePassword =
        devConfig.authentication == MaemoDeviceConfigurations::DeviceConfig::Password;
    const QLatin1String opt("-o");
1163
1164
1165
1166
    QStringList optionList;
    if (!usePassword)
        optionList << QLatin1String("-i") << devConfig.keyFile;
    return optionList << opt
1167
1168
1169
1170
        << QString::fromLatin1("PasswordAuthentication=%1").
            arg(usePassword ? "yes" : "no") << opt
        << QString::fromLatin1("PubkeyAuthentication=%1").
            arg(usePassword ? "no" : "yes") << opt
ck's avatar
ck committed
1171
1172
1173
        << QString::fromLatin1("ConnectTimeout=%1").arg(devConfig.timeout)
        << opt << QLatin1String("CheckHostIP=no")
        << opt << QLatin1String("StrictHostKeyChecking=no");
1174
1175
}

ck's avatar
ck committed
1176
1177
const QString AbstractMaemoRunControl::executableOnTarget() const
{
ck's avatar
ck committed
1178
    return QString::fromLocal8Bit("%1/%2").arg(remoteDir()).
ck's avatar
ck committed
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
        arg(executableFileName());
}

const QString AbstractMaemoRunControl::targetCmdLinePrefix() const
{
    return QString::fromLocal8Bit("chmod u+x %1; source /etc/profile; ").
        arg(executableOnTarget());
}

bool AbstractMaemoRunControl::setProcessEnvironment(QProcess &process)
{
    QTC_ASSERT(runConfig, return false);
kh1's avatar
kh1 committed
1191
1192
    Qt4BuildConfiguration *qt4bc = qobject_cast<Qt4BuildConfiguration*>
        (runConfig->project()->activeBuildConfiguration());
1193
    QTC_ASSERT(qt4bc, return false);
ck's avatar
ck committed
1194
    Environment env = Environment::systemEnvironment();
1195
    qt4bc->toolChain()->addToEnvironment(env);
ck's avatar
ck committed
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
    process.setEnvironment(env.toStringList());

    return true;
}

void AbstractMaemoRunControl::readStandardError()
{
    QProcess *process = static_cast<QProcess *>(sender());
    const QByteArray &data = process->readAllStandardError();
    emit addToOutputWindow(this, QString::fromLocal8Bit(data.constData(),
        data.length()));
}

void AbstractMaemoRunControl::readStandardOutput()
{
    QProcess *process = static_cast<QProcess *>(sender());
    const QByteArray &data = process->readAllStandardOutput();
    emit addToOutputWindow(this, QString::fromLocal8Bit(data.constData(),
        data.length()));
}


// #pragma mark -- MaemoRunControl


1221
MaemoRunControl::MaemoRunControl(RunConfiguration *runConfiguration)
ck's avatar
ck committed
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
    : AbstractMaemoRunControl(runConfiguration)
{
    setProcessEnvironment(sshProcess);
    setProcessEnvironment(stopProcess);

    connect(&sshProcess, SIGNAL(readyReadStandardError()), this,
        SLOT(readStandardError()));
    connect(&sshProcess, SIGNAL(readyReadStandardOutput()), this,
        SLOT(readStandardOutput()));
    connect(&sshProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this,
        SLOT(executionFinished()));
    connect(&sshProcess, SIGNAL(error(QProcess::ProcessError)), &dumper,
        SLOT(printToStream(QProcess::ProcessError)));
}

MaemoRunControl::~MaemoRunControl()
{
    stop();
    stopProcess.waitForFinished(5000);
}

void MaemoRunControl::start()
{
    stoppedByUser = false;
    startDeployment(false);
}

1249
void MaemoRunControl::handleDeploymentFinished(bool success)
ck's avatar
ck committed
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
{
    if (success)
        startExecution();
    else
        emit finished();
}

void MaemoRunControl::startExecution()
{
    const QString remoteCall = QString::fromLocal8Bit("%1 %2 %3")
        .arg(targetCmdLinePrefix()).arg(executableOnTarget())
        .arg(runConfig->arguments().join(" "));

    QStringList cmdArgs;
ck's avatar
ck committed
1264
    cmdArgs << "-n" << "-p" << port() << "-l" << devConfig.uname
1265
        << options() << devConfig.host << remoteCall;
ck's avatar
ck committed
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
    sshProcess.start(runConfig->sshCmd(), cmdArgs);

    sshProcess.start(runConfig->sshCmd(), cmdArgs);
    emit addToOutputWindow(this, tr("Starting remote application."));
    if (sshProcess.waitForStarted()) {
        emit started();
    } else {
        emit error(this, tr("Could not start ssh!"));
        sshProcess.kill();
    }
}

void MaemoRunControl::executionFinished()
{
    if (stoppedByUser)
        emit addToOutputWindow(this, tr("Remote process stopped by user."));
    else if (sshProcess.exitCode() != 0)
        emit addToOutputWindow(this, tr("Remote process exited with error."));
    else
        emit addToOutputWindow(this, tr("Remote process finished successfully."));
    emit finished();
}

void MaemoRunControl::stop()
{
kh1's avatar
kh1 committed
1291
    if (!isRunning())
kh1's avatar
kh1 committed
1292
1293
        return;

ck's avatar
ck committed
1294
1295
1296
1297
1298
1299
    stoppedByUser = true;
    if (isDeploying()) {
        stopDeployment();
    } else {
        stopProcess.kill();
        QStringList cmdArgs;
ck's avatar
ck committed
1300
1301
        const QString remoteCall = QString::fromLocal8Bit("pkill -x %1; "
            "sleep 1; pkill -x -9 %1").arg(executableFileName());
ck's avatar
ck committed
1302
        cmdArgs << "-n" << "-p" << port() << "-l" << devConfig.uname
1303
            << options() << devConfig.host << remoteCall;
ck's avatar
ck committed
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
        stopProcess.start(runConfig->sshCmd(), cmdArgs);
    }
}

bool MaemoRunControl::isRunning() const
{
    return isDeploying() || sshProcess.state() != QProcess::NotRunning;
}


// #pragma mark -- MaemoDebugRunControl


1317
MaemoDebugRunControl::MaemoDebugRunControl(RunConfiguration *runConfiguration)
ck's avatar
ck committed
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
    : AbstractMaemoRunControl(runConfiguration)
    , gdbServerPort("10000"), debuggerManager(0)
    , startParams(new Debugger::DebuggerStartParameters)
{
    setProcessEnvironment(gdbServer);
    setProcessEnvironment(stopProcess);

    qDebug("Maemo Debug run controls started");
    debuggerManager = ExtensionSystem::PluginManager::instance()
        ->getObject<Debugger::DebuggerManager>();

    QTC_ASSERT(debuggerManager != 0, return);
    startParams->startMode = Debugger::StartRemote;
    startParams->executable = executableOnHost();
ck's avatar
ck committed
1332
    startParams->remoteChannel = devConfig.host + ":" + gdbServerPort;
ck's avatar
ck committed
1333
1334
1335
1336
1337
1338
    startParams->remoteArchitecture = "arm";
    startParams->sysRoot = runConfig->sysRoot();
    startParams->toolChainType = ToolChain::GCC_MAEMO;
    startParams->debuggerCommand = runConfig->gdbCmd();
    startParams->dumperLibrary = runConfig->dumperLib();
    startParams->remoteDumperLib = QString::fromLocal8Bit("%1/%2")
ck's avatar
ck committed
1339
        .arg(remoteDir()).arg(QFileInfo(runConfig->dumperLib()).fileName());
ck's avatar
ck committed
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360

    connect(this, SIGNAL(stopRequested()), debuggerManager, SLOT(exitDebugger()));
    connect(debuggerManager, SIGNAL(debuggingFinished()), this,
        SLOT(debuggingFinished()), Qt::QueuedConnection);
    connect(debuggerManager, SIGNAL(applicationOutputAvailable(QString)),
        this, SLOT(debuggerOutput(QString)), Qt::QueuedConnection);
}

MaemoDebugRunControl::~MaemoDebugRunControl()
{
    disconnect(SIGNAL(addToOutputWindow(RunControl*,QString)));
    disconnect(SIGNAL(addToOutputWindowInline(RunControl*,QString)));
    stop();
    debuggingFinished();
}

void MaemoDebugRunControl::start()
{
    startDeployment(true);
}

1361
void MaemoDebugRunControl::handleDeploymentFinished(bool success)
ck's avatar
ck committed
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
{
    if (success) {
        startGdbServer();
    } else {
        emit finished();
    }
}

void MaemoDebugRunControl::startGdbServer()
{
    const QString remoteCall(QString::fromLocal8Bit("%1 gdbserver :%2 %3 %4").
        arg(targetCmdLinePrefix()).arg(gdbServerPort). arg(executableOnTarget())
        .arg(runConfig->arguments().join(" ")));
    QStringList sshArgs;
ck's avatar
ck committed
1376
    sshArgs << "-t" << "-n" << "-l" << devConfig.uname << "-p"
1377
        << port() << options() << devConfig.host << remoteCall;
ck's avatar
ck committed
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
    inferiorPid = -1;
    disconnect(&gdbServer, SIGNAL(readyReadStandardError()), 0, 0);
    connect(&gdbServer, SIGNAL(readyReadStandardError()), this,
        SLOT(gdbServerStarted()));
    gdbServer.start(runConfig->sshCmd(), sshArgs);
    qDebug("Maemo: started gdb server, ssh arguments were %s", qPrintable(sshArgs.join(" ")));
}

void MaemoDebugRunControl::gdbServerStartFailed(const QString &reason)
{
    emit addToOutputWindow(this, tr("Debugging failed: %1").arg(reason));
    emit stopRequested();
    emit finished();
}

void MaemoDebugRunControl::gdbServerStarted()
{
    const QByteArray output = gdbServer.readAllStandardError();
    qDebug("gdbserver's stderr output: %s", output.data());

    const QByteArray searchString("pid = ");
    const int searchStringLength = searchString.length();

    int pidStartPos = output.indexOf(searchString);
    const int pidEndPos = output.indexOf("\n", pidStartPos + searchStringLength);
    if (pidStartPos == -1 || pidEndPos == -1) {
        gdbServerStartFailed(output.data());
        return;
    }

    pidStartPos += searchStringLength;
    QByteArray pidString = output.mid(pidStartPos, pidEndPos - pidStartPos);
    qDebug("pidString = %s", pidString.data());

    bool ok;
    const int pid = pidString.toInt(&ok);
    if (!ok) {
        gdbServerStartFailed(tr("Debugging failed, could not parse gdb "
            "server pid!"));
        return;
    }

    inferiorPid = pid;
    qDebug("inferiorPid = %d", inferiorPid);

    disconnect(&gdbServer, SIGNAL(readyReadStandardError()), 0, 0);
    connect(&gdbServer, SIGNAL(readyReadStandardError()), this,
        SLOT(readStandardError()));
    startDebugging();
}

void MaemoDebugRunControl::startDebugging()
{
    debuggerManager->startNewDebugger(startParams);
}

void MaemoDebugRunControl::stop()
{
    if (!isRunning())
        return;
    emit addToOutputWindow(this, tr("Stopping debugging operation ..."));
    if (isDeploying()) {
        stopDeployment();
    } else {
        emit stopRequested();
    }
}

bool MaemoDebugRunControl::isRunning() const
{
    return isDeploying() || gdbServer.state() != QProcess::NotRunning
        || debuggerManager->state() != Debugger::DebuggerNotReady;
}

void MaemoDebugRunControl::debuggingFinished()
{
    if (gdbServer.state() != QProcess::NotRunning) {
        stopProcess.kill();
        const QString remoteCall = QString::fromLocal8Bit("kill %1; sleep 1; "
ck's avatar
ck committed
1457
            "kill -9 %1; pkill -x -9 gdbserver").arg(inferiorPid);
ck's avatar
ck committed
1458
        QStringList sshArgs;
ck's avatar
ck committed
1459
        sshArgs << "-n" << "-l" << devConfig.uname << "-p" << port()
1460
            << options() << devConfig.host << remoteCall;
ck's avatar
ck committed
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
        stopProcess.start(runConfig->sshCmd(), sshArgs);
    }
    qDebug("ssh return code is %d", gdbServer.exitCode());
    emit addToOutputWindow(this, tr("Debugging finished."));