aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/projectexplorer/applicationlauncher.cpp
blob: 3aef28f09035c6cd4b539c5d6f270c889d62f0de (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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** 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 "applicationlauncher.h"
#ifdef Q_OS_WIN
#include "windebuginterface.h"
#include <qt_windows.h>
#endif

#include <coreplugin/icore.h>

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

#include "devicesupport/deviceprocess.h"
#include "projectexplorer.h"
#include "projectexplorersettings.h"

#include <QTextCodec>
#include <QTimer>

/*!
    \class ProjectExplorer::ApplicationLauncher

    \brief The ApplicationLauncher class is the application launcher of the
    ProjectExplorer plugin.

    Encapsulates processes running in a console or as GUI processes,
    captures debug output of GUI processes on Windows (outputDebugString()).

    \sa Utils::ConsoleProcess
*/

using namespace Utils;

namespace ProjectExplorer {

using namespace Internal;

namespace Internal {


class ApplicationLauncherPrivate : public QObject
{
public:
    enum State { Inactive, Run };
    explicit ApplicationLauncherPrivate(ApplicationLauncher *parent);
    ~ApplicationLauncherPrivate() override { setFinished(); }

    void start(const Runnable &runnable, const IDevice::ConstPtr &device, bool local);
    void stop();

    // Local
    void handleProcessStarted();
    void localGuiProcessError();
    void localConsoleProcessError(const QString &error);
    void readLocalStandardOutput();
    void readLocalStandardError();
    void cannotRetrieveLocalDebugOutput();
    void checkLocalDebugOutput(qint64 pid, const QString &message);
    void localProcessDone(int, QProcess::ExitStatus);
    void bringToForeground();
    qint64 applicationPID() const;
    bool isRunning() const;
    bool isRemoteRunning() const;

    // Remote
    void doReportError(const QString &message);
    void handleRemoteStderr();
    void handleRemoteStdout();
    void handleApplicationFinished();
    void setFinished();
    void handleApplicationError(QProcess::ProcessError error);

public:
    ApplicationLauncher *q;

    bool m_isLocal = true;

    // Local
    QtcProcess m_guiProcess;
    ConsoleProcess m_consoleProcess;
    bool m_useTerminal = false;
    // Keep track whether we need to emit a finished signal
    bool m_processRunning = false;

    QTextCodec *m_outputCodec;
    QTextCodec::ConverterState m_outputCodecState;
    QTextCodec::ConverterState m_errorCodecState;

    qint64 m_listeningPid = 0;

    // Remote
    DeviceProcess *m_deviceProcess = nullptr;
    State m_state = Inactive;
    bool m_stopRequested = false;
    bool m_success = false;
};

} // Internal

ApplicationLauncherPrivate::ApplicationLauncherPrivate(ApplicationLauncher *parent)
    : q(parent), m_outputCodec(QTextCodec::codecForLocale())
{
    if (ProjectExplorerPlugin::projectExplorerSettings().mergeStdErrAndStdOut){
        m_guiProcess.setProcessChannelMode(QProcess::MergedChannels);
    } else {
        m_guiProcess.setProcessChannelMode(QProcess::SeparateChannels);
        connect(&m_guiProcess, &QProcess::readyReadStandardError,
                this, &ApplicationLauncherPrivate::readLocalStandardError);
    }
    connect(&m_guiProcess, &QProcess::readyReadStandardOutput,
            this, &ApplicationLauncherPrivate::readLocalStandardOutput);
    connect(&m_guiProcess, &QProcess::errorOccurred,
            this, &ApplicationLauncherPrivate::localGuiProcessError);
    connect(&m_guiProcess, static_cast<void (QProcess::*)(int,QProcess::ExitStatus)>(&QProcess::finished),
            this, &ApplicationLauncherPrivate::localProcessDone);
    connect(&m_guiProcess, &QProcess::started,
            this, &ApplicationLauncherPrivate::handleProcessStarted);
    connect(&m_guiProcess, &QProcess::errorOccurred,
            q, &ApplicationLauncher::error);

    m_consoleProcess.setSettings(Core::ICore::settings());

    connect(&m_consoleProcess, &ConsoleProcess::processStarted,
            this, &ApplicationLauncherPrivate::handleProcessStarted);
    connect(&m_consoleProcess, &ConsoleProcess::processError,
            this, &ApplicationLauncherPrivate::localConsoleProcessError);
    connect(&m_consoleProcess, &ConsoleProcess::processStopped,
            this, &ApplicationLauncherPrivate::localProcessDone);
    connect(&m_consoleProcess,
            static_cast<void (ConsoleProcess::*)(QProcess::ProcessError)>(&ConsoleProcess::error),
            q, &ApplicationLauncher::error);

#ifdef Q_OS_WIN
    connect(WinDebugInterface::instance(), &WinDebugInterface::cannotRetrieveDebugOutput,
            this, &ApplicationLauncherPrivate::cannotRetrieveLocalDebugOutput);
    connect(WinDebugInterface::instance(), &WinDebugInterface::debugOutput,
            this, &ApplicationLauncherPrivate::checkLocalDebugOutput);
#endif
}

ApplicationLauncher::ApplicationLauncher(QObject *parent) : QObject(parent),
    d(std::make_unique<ApplicationLauncherPrivate>(this))
{ }

ApplicationLauncher::~ApplicationLauncher() = default;

void ApplicationLauncher::setProcessChannelMode(QProcess::ProcessChannelMode mode)
{
    d->m_guiProcess.setProcessChannelMode(mode);
}

void ApplicationLauncher::setUseTerminal(bool on)
{
    d->m_useTerminal = on;
}

void ApplicationLauncher::stop()
{
    d->stop();
}

void ApplicationLauncherPrivate::stop()
{
    if (m_isLocal) {
        if (!isRunning())
            return;
        if (m_useTerminal) {
            m_consoleProcess.stop();
            localProcessDone(0, QProcess::CrashExit);
        } else {
            m_guiProcess.terminate();
            if (!m_guiProcess.waitForFinished(1000) && m_guiProcess.state() == QProcess::Running) { // This is blocking, so be fast.
                m_guiProcess.kill();
                m_guiProcess.waitForFinished();
            }
        }
    } else {
        if (m_stopRequested)
            return;
        m_stopRequested = true;
        m_success = false;
        emit q->reportProgress(ApplicationLauncher::tr("User requested stop. Shutting down..."));
        switch (m_state) {
            case Run:
                m_deviceProcess->terminate();
                break;
            case Inactive:
                break;
        }
    }
}

bool ApplicationLauncher::isRunning() const
{
    return d->isRunning();
}

bool ApplicationLauncher::isRemoteRunning() const
{
    return d->isRemoteRunning();
}

bool ApplicationLauncherPrivate::isRunning() const
{
    if (m_useTerminal)
        return m_consoleProcess.isRunning();
    return m_guiProcess.state() != QProcess::NotRunning;
}

bool ApplicationLauncherPrivate::isRemoteRunning() const
{
    return m_isLocal ? false : m_deviceProcess->state() == QProcess::Running;
}

ProcessHandle ApplicationLauncher::applicationPID() const
{
    return ProcessHandle(d->applicationPID());
}

qint64 ApplicationLauncherPrivate::applicationPID() const
{
    if (!isRunning())
        return 0;

    if (m_useTerminal)
        return m_consoleProcess.applicationPID();

    return m_guiProcess.processId();
}

QString ApplicationLauncher::errorString() const
{
    if (d->m_useTerminal)
        return d->m_consoleProcess.errorString();
    else
        return d->m_guiProcess.errorString();
}

QProcess::ProcessError ApplicationLauncher::processError() const
{
    if (d->m_useTerminal)
        return d->m_consoleProcess.error();
    else
        return d->m_guiProcess.error();
}

void ApplicationLauncherPrivate::localGuiProcessError()
{
    QString error;
    QProcess::ExitStatus status = QProcess::NormalExit;
    switch (m_guiProcess.error()) {
    case QProcess::FailedToStart:
        error = ApplicationLauncher::tr("Failed to start program. Path or permissions wrong?");
        break;
    case QProcess::Crashed:
        error = ApplicationLauncher::tr("The program has unexpectedly finished.");
        status = QProcess::CrashExit;
        break;
    default:
        error = ApplicationLauncher::tr("Some error has occurred while running the program.");
    }
    emit q->appendMessage(error, ErrorMessageFormat);
    if (m_processRunning && !isRunning()) {
        m_processRunning = false;
        emit q->processExited(-1, status);
    }
}

void ApplicationLauncherPrivate::localConsoleProcessError(const QString &error)
{
    emit q->appendMessage(error, ErrorMessageFormat);
    if (m_processRunning && m_consoleProcess.applicationPID() == 0) {
        m_processRunning = false;
        emit q->processExited(-1, QProcess::NormalExit);
    }
}

void ApplicationLauncherPrivate::readLocalStandardOutput()
{
    QByteArray data = m_guiProcess.readAllStandardOutput();
    QString msg = m_outputCodec->toUnicode(
            data.constData(), data.length(), &m_outputCodecState);
    emit q->appendMessage(msg, StdOutFormatSameLine, false);
}

void ApplicationLauncherPrivate::readLocalStandardError()
{
    QByteArray data = m_guiProcess.readAllStandardError();
    QString msg = m_outputCodec->toUnicode(
            data.constData(), data.length(), &m_errorCodecState);
    emit q->appendMessage(msg, StdErrFormatSameLine, false);
}

void ApplicationLauncherPrivate::cannotRetrieveLocalDebugOutput()
{
#ifdef Q_OS_WIN
    disconnect(WinDebugInterface::instance(), nullptr, this, nullptr);
    emit q->appendMessage(ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput(), ErrorMessageFormat);
#endif
}

void ApplicationLauncherPrivate::checkLocalDebugOutput(qint64 pid, const QString &message)
{
    if (m_listeningPid == pid)
        emit q->appendMessage(message, DebugFormat);
}

void ApplicationLauncherPrivate::localProcessDone(int exitCode, QProcess::ExitStatus status)
{
    QTimer::singleShot(100, this, [this, exitCode, status]() {
        m_listeningPid = 0;
        emit q->processExited(exitCode, status);
    });
}

QString ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput()
{
    return tr("Cannot retrieve debugging output.") + QLatin1Char('\n');
}

void ApplicationLauncherPrivate::handleProcessStarted()
{
    m_listeningPid = applicationPID();
    emit q->processStarted();
}

void ApplicationLauncher::start(const Runnable &runnable)
{
    d->start(runnable, IDevice::ConstPtr(), true);
}

void ApplicationLauncher::start(const Runnable &runnable, const IDevice::ConstPtr &device)
{
    d->start(runnable, device, false);
}

void ApplicationLauncherPrivate::start(const Runnable &runnable, const IDevice::ConstPtr &device, bool local)
{
    m_isLocal = local;

    if (m_isLocal) {
        // Work around QTBUG-17529 (QtDeclarative fails with 'File name case mismatch' ...)
        const QString fixedPath = FileUtils::normalizePathName(runnable.workingDirectory);
        m_guiProcess.setWorkingDirectory(fixedPath);
        m_consoleProcess.setWorkingDirectory(fixedPath);
        m_guiProcess.setEnvironment(runnable.environment);
        m_consoleProcess.setEnvironment(runnable.environment);

        m_processRunning = true;
    #ifdef Q_OS_WIN
        if (!WinDebugInterface::instance()->isRunning())
            WinDebugInterface::instance()->start(); // Try to start listener again...
    #endif

        if (!m_useTerminal) {
            m_guiProcess.setCommand(runnable.executable, runnable.commandLineArguments);
            m_guiProcess.closeWriteChannel();
            m_guiProcess.start();
        } else {
            m_consoleProcess.start(runnable.executable, runnable.commandLineArguments);
        }
    } else {
        QTC_ASSERT(m_state == Inactive, return);

        m_state = Run;
        if (!device) {
            doReportError(ApplicationLauncher::tr("Cannot run: No device."));
            setFinished();
            return;
        }

        if (!device->canCreateProcess()) {
            doReportError(ApplicationLauncher::tr("Cannot run: Device is not able to create processes."));
            setFinished();
            return;
        }

        if (runnable.executable.isEmpty()) {
            doReportError(ApplicationLauncher::tr("Cannot run: No command given."));
            setFinished();
            return;
        }

        m_stopRequested = false;
        m_success = true;

        m_deviceProcess = device->createProcess(this);
        m_deviceProcess->setRunInTerminal(m_useTerminal);
        connect(m_deviceProcess, &DeviceProcess::started,
                q, &ApplicationLauncher::remoteProcessStarted);
        connect(m_deviceProcess, &DeviceProcess::readyReadStandardOutput,
                this, &ApplicationLauncherPrivate::handleRemoteStdout);
        connect(m_deviceProcess, &DeviceProcess::readyReadStandardError,
                this, &ApplicationLauncherPrivate::handleRemoteStderr);
        connect(m_deviceProcess, &DeviceProcess::error,
                this, &ApplicationLauncherPrivate::handleApplicationError);
        connect(m_deviceProcess, &DeviceProcess::finished,
                this, &ApplicationLauncherPrivate::handleApplicationFinished);
        m_deviceProcess->start(runnable);
    }
}

void ApplicationLauncherPrivate::handleApplicationError(QProcess::ProcessError error)
{
    if (error == QProcess::FailedToStart) {
        doReportError(ApplicationLauncher::tr("Application failed to start: %1")
                         .arg(m_deviceProcess->errorString()));
        setFinished();
    }
}

void ApplicationLauncherPrivate::setFinished()
{
    if (m_state == Inactive)
        return;

    if (m_deviceProcess) {
        m_deviceProcess->disconnect(this);
        m_deviceProcess->deleteLater();
        m_deviceProcess = nullptr;
    }

    m_state = Inactive;
    emit q->finished(m_success);
}

void ApplicationLauncherPrivate::handleApplicationFinished()
{
    QTC_ASSERT(m_state == Run, return);

    if (m_deviceProcess->exitStatus() == QProcess::CrashExit) {
        doReportError(m_deviceProcess->errorString());
    } else {
        const int exitCode = m_deviceProcess->exitCode();
        if (exitCode != 0) {
            doReportError(ApplicationLauncher::tr("Application finished with exit code %1.").arg(exitCode));
        } else {
            emit q->reportProgress(ApplicationLauncher::tr("Application finished with exit code 0."));
        }
    }
    setFinished();
}

void ApplicationLauncherPrivate::handleRemoteStdout()
{
    QTC_ASSERT(m_state == Run, return);
    const QByteArray output = m_deviceProcess->readAllStandardOutput();
    emit q->remoteStdout(QString::fromUtf8(output));
}

void ApplicationLauncherPrivate::handleRemoteStderr()
{
    QTC_ASSERT(m_state == Run, return);
    const QByteArray output = m_deviceProcess->readAllStandardError();
    emit q->remoteStderr(QString::fromUtf8(output));
}

void ApplicationLauncherPrivate::doReportError(const QString &message)
{
    m_success = false;
    emit q->reportError(message);
}

} // namespace ProjectExplorer