aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/debugger/unstartedappwatcherdialog.cpp
blob: 2ef8c675884f05ed9232fa50102416c349661c83 (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
/****************************************************************************
**
** Copyright (C) 2016 Petar Perisin <petar.perisin@gmail.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "unstartedappwatcherdialog.h"

#include "debuggeritem.h"
#include "debuggerdialogs.h"
#include "debuggerkitinformation.h"

#include <utils/pathchooser.h>

#include <projectexplorer/kit.h>
#include <projectexplorer/target.h>
#include <projectexplorer/project.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/projecttree.h>
#include <projectexplorer/runconfiguration.h>
#include <projectexplorer/buildconfiguration.h>

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QCheckBox>
#include <QDialogButtonBox>
#include <QKeyEvent>
#include <QLabel>
#include <QFormLayout>
#include <QLineEdit>
#include <QFileDialog>

using namespace ProjectExplorer;

namespace Debugger {
namespace Internal {

static bool isLocal(RunConfiguration *runConfiguration)
{
    Target *target = runConfiguration ? runConfiguration->target() : nullptr;
    Kit *kit = target ? target->kit() : nullptr;
    return DeviceTypeKitAspect::deviceTypeId(kit) == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE;
}

/*!
    \class Debugger::Internal::UnstartedAppWatcherDialog

    \brief The UnstartedAppWatcherDialog class provides ability to wait for a certain application
           to be started, after what it will attach to it.

    This dialog can be useful in cases where automated scripts are used in order to execute some
    tests on application. In those cases application will be started from a script. This dialog
    allows user to attach to application in those cases in very short time after they are started.

    In order to attach, user needs to provide appropriate kit (for local debugging) and
    application path.

    After selecting start, dialog will check if selected application is started every
    10 miliseconds. As soon as application is started, QtCreator will attach to it.

    After user attaches, it is possible to keep dialog active and as soon as debugging
    session ends, it will start watching again. This is because sometimes automated test
    scripts can restart application several times during tests.
*/

UnstartedAppWatcherDialog::UnstartedAppWatcherDialog(QWidget *parent)
    : QDialog(parent)
{
    setWindowTitle(tr("Attach to Process Not Yet Started"));

    m_kitChooser = new KitChooser(this);
    m_kitChooser->setKitPredicate([](const Kit *k) {
        return ToolChainKitAspect::targetAbi(k).os() == Abi::hostAbi().os();
    });
    m_kitChooser->setShowIcons(true);
    m_kitChooser->populate();
    m_kitChooser->setVisible(true);

    Project *project = ProjectTree::currentProject();
    Target *activeTarget = project ? project->activeTarget() : nullptr;
    Kit *kit = activeTarget ? activeTarget->kit() : nullptr;

    if (kit)
        m_kitChooser->setCurrentKitId(kit->id());
    else if (KitManager::defaultKit())
        m_kitChooser->setCurrentKitId(KitManager::defaultKit()->id());

    auto pathLayout = new QHBoxLayout;
    m_pathChooser = new Utils::PathChooser(this);
    m_pathChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
    m_pathChooser->setHistoryCompleter("LocalExecutable", true);
    m_pathChooser->setMinimumWidth(400);

    auto resetExecutable = new QPushButton(tr("Reset"));
    resetExecutable->setEnabled(false);
    pathLayout->addWidget(m_pathChooser);
    pathLayout->addWidget(resetExecutable);
    if (activeTarget) {
        if (RunConfiguration *runConfig = activeTarget->activeRunConfiguration()) {
            const Runnable runnable = runConfig->runnable();
            if (isLocal(runConfig)) {
                resetExecutable->setEnabled(true);
                connect(resetExecutable, &QPushButton::clicked, this, [this, runnable] {
                    m_pathChooser->setFilePath(runnable.executable);
                });
            }
        }
    }

    m_hideOnAttachCheckBox = new QCheckBox(tr("Reopen dialog when application finishes"), this);
    m_hideOnAttachCheckBox->setToolTip(tr("Reopens this dialog when application finishes."));

    m_hideOnAttachCheckBox->setChecked(false);
    m_hideOnAttachCheckBox->setVisible(true);

    m_continueOnAttachCheckBox = new QCheckBox(tr("Continue on attach"), this);
    m_continueOnAttachCheckBox->setToolTip(tr("Debugger does not stop the"
                                              " application after attach."));

    m_continueOnAttachCheckBox->setChecked(true);
    m_continueOnAttachCheckBox->setVisible(true);

    m_waitingLabel = new QLabel(QString(), this);
    m_waitingLabel->setAlignment(Qt::AlignCenter);

    auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Close, this);
    m_watchingPushButton = buttonBox->addButton(tr("Start Watching"), QDialogButtonBox::ActionRole);
    m_watchingPushButton->setCheckable(true);
    m_watchingPushButton->setChecked(false);
    m_watchingPushButton->setEnabled(false);
    m_watchingPushButton->setDefault(true);

    auto mainLayout = new QFormLayout(this);
    mainLayout->addRow(new QLabel(tr("Kit: "), this), m_kitChooser);
    mainLayout->addRow(new QLabel(tr("Executable: "), this), pathLayout);
    mainLayout->addRow(m_hideOnAttachCheckBox);
    mainLayout->addRow(m_continueOnAttachCheckBox);
    mainLayout->addRow(m_waitingLabel);
    mainLayout->addItem(new QSpacerItem(20, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));
    mainLayout->addRow(buttonBox);
    setLayout(mainLayout);

    connect(m_pathChooser, &Utils::PathChooser::beforeBrowsing,
            this, &UnstartedAppWatcherDialog::selectExecutable);
    connect(m_watchingPushButton, &QAbstractButton::toggled,
            this, &UnstartedAppWatcherDialog::startStopWatching);
    connect(m_pathChooser, &Utils::PathChooser::pathChanged, this,
            &UnstartedAppWatcherDialog::stopAndCheckExecutable);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
    connect(&m_timer, &QTimer::timeout,
            this, &UnstartedAppWatcherDialog::findProcess);
    connect(m_kitChooser, &KitChooser::currentIndexChanged,
            this, &UnstartedAppWatcherDialog::kitChanged);
    kitChanged();
    m_pathChooser->setFocus();

    setWaitingState(checkExecutableString() ? NotWatchingState : InvalidWacherState);
}

bool UnstartedAppWatcherDialog::event(QEvent *e)
{
    if (e->type() == QEvent::ShortcutOverride) {
        auto ke = static_cast<QKeyEvent *>(e);
        if (ke->key() == Qt::Key_Escape && !ke->modifiers()) {
            ke->accept();
            return true;
        }
    }
    return QDialog::event(e);
}

void UnstartedAppWatcherDialog::selectExecutable()
{
    QString path;

    Project *project = ProjectTree::currentProject();
    Target *activeTarget = project ? project->activeTarget() : nullptr;

    if (activeTarget) {
        if (RunConfiguration *runConfig = activeTarget->activeRunConfiguration()) {
            const Runnable runnable = runConfig->runnable();
            if (isLocal(runConfig))
                path = runnable.executable.toFileInfo().path();
        }
    }

    if (path.isEmpty()) {
        if (activeTarget && activeTarget->activeBuildConfiguration()) {
            path = activeTarget->activeBuildConfiguration()->buildDirectory().toString();
        } else if (project) {
            path = project->projectDirectory().toString();
        }
    }
    m_pathChooser->setInitialBrowsePathBackup(path);
}

void UnstartedAppWatcherDialog::startWatching()
{
    show();
    if (checkExecutableString()) {
        setWaitingState(WatchingState);
        startStopTimer(true);
    } else {
        setWaitingState(InvalidWacherState);
    }
}

void UnstartedAppWatcherDialog::pidFound(const DeviceProcessItem &p)
{
    setWaitingState(FoundState);
    startStopTimer(false);
    m_process = p;

    if (hideOnAttach())
        hide();
    else
        accept();

    emit processFound();
}

void UnstartedAppWatcherDialog::startStopWatching(bool start)
{
    setWaitingState(start ? WatchingState : NotWatchingState);
    m_watchingPushButton->setText(start ? tr("Stop Watching") : tr("Start Watching"));
    startStopTimer(start);
}

void UnstartedAppWatcherDialog::startStopTimer(bool start)
{
    if (start)
        m_timer.start(10);
    else
        m_timer.stop();
}

void UnstartedAppWatcherDialog::findProcess()
{
    const QString &appName = Utils::FileUtils::normalizePathName(m_pathChooser->filePath().toString());
    DeviceProcessItem fallback;
    foreach (const DeviceProcessItem &p, DeviceProcessList::localProcesses()) {
        if (Utils::FileUtils::normalizePathName(p.exe) == appName) {
            pidFound(p);
            return;
        }
        if (p.cmdLine.startsWith(appName))
            fallback = p;
    }
    if (fallback.pid != 0)
        pidFound(fallback);
}

void UnstartedAppWatcherDialog::stopAndCheckExecutable()
{
    startStopTimer(false);
    setWaitingState(checkExecutableString() ? NotWatchingState : InvalidWacherState);
}

void UnstartedAppWatcherDialog::kitChanged()
{
    const DebuggerItem *debugger = DebuggerKitAspect::debugger(m_kitChooser->currentKit());
    if (!debugger)
        return;
    if (debugger->engineType() == Debugger::CdbEngineType) {
        m_continueOnAttachCheckBox->setEnabled(false);
        m_continueOnAttachCheckBox->setChecked(true);
    } else {
        m_continueOnAttachCheckBox->setEnabled(true);
    }
}

bool UnstartedAppWatcherDialog::checkExecutableString() const
{
    if (!m_pathChooser->filePath().toString().isEmpty()) {
        QFileInfo fileInfo(m_pathChooser->filePath().toString());
        return (fileInfo.exists() && fileInfo.isFile());
    }
    return false;
}

Kit *UnstartedAppWatcherDialog::currentKit() const
{
    return m_kitChooser->currentKit();
}

DeviceProcessItem UnstartedAppWatcherDialog::currentProcess() const
{
    return m_process;
}

bool UnstartedAppWatcherDialog::hideOnAttach() const
{
    return m_hideOnAttachCheckBox->isChecked();
}

bool UnstartedAppWatcherDialog::continueOnAttach() const
{
    return m_continueOnAttachCheckBox->isEnabled() && m_continueOnAttachCheckBox->isChecked();
}

void UnstartedAppWatcherDialog::setWaitingState(UnstartedAppWacherState state)
{
    switch (state) {
    case InvalidWacherState:
        m_waitingLabel->setText(tr("Select valid executable."));
        m_watchingPushButton->setEnabled(false);
        m_watchingPushButton->setChecked(false);
        m_pathChooser->setEnabled(true);
        m_kitChooser->setEnabled(true);
        break;

    case NotWatchingState:
        m_waitingLabel->setText(tr("Not watching."));
        m_watchingPushButton->setEnabled(true);
        m_watchingPushButton->setChecked(false);
        m_pathChooser->setEnabled(true);
        m_kitChooser->setEnabled(true);
        break;

    case WatchingState:
        m_waitingLabel->setText(tr("Waiting for process to start..."));
        m_watchingPushButton->setEnabled(true);
        m_watchingPushButton->setChecked(true);
        m_pathChooser->setEnabled(false);
        m_kitChooser->setEnabled(false);
        break;

    case FoundState:
        m_waitingLabel->setText(tr("Attach"));
        m_watchingPushButton->setEnabled(false);
        m_watchingPushButton->setChecked(true);
        m_pathChooser->setEnabled(false);
        m_kitChooser->setEnabled(true);
        break;
    }
}

} // namespace Internal
} // namespace Debugger