summaryrefslogtreecommitdiff
path: root/src/plugins/debugger/threadshandler.cpp
blob: 286b58258f1d43381924dd46773734e5227b37e9 (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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0

#include "threadshandler.h"

#include "debuggeractions.h"
#include "debuggerengine.h"
#include "debuggericons.h"
#include "debuggerprotocol.h"
#include "debuggertr.h"
#include "watchutils.h"

#include <utils/algorithm.h>
#include <utils/basetreeview.h>
#include <utils/qtcassert.h>

#include <QCoreApplication>
#include <QDebug>
#include <QIcon>
#include <QMenu>

using namespace Utils;

namespace Debugger::Internal {

// ThreadItem

ThreadItem::ThreadItem(const ThreadData &data)
    : threadData(data)
{}

QVariant ThreadItem::data(int column, int role) const
{
    switch (role) {
    case Qt::DisplayRole:
        if (column == 0)
            return QString("#%1 %2").arg(threadData.id).arg(threadData.name);
        return threadPart(column);
    case Qt::ToolTipRole:
        return threadToolTip();
    default:
        break;
    }
    return QVariant();
}

Qt::ItemFlags ThreadItem::flags(int column) const
{
    return threadData.stopped ? TreeItem::flags(column) : Qt::ItemFlags({});
}

QString ThreadItem::threadToolTip() const
{
    const char start[] = "<tr><td>";
    const char sep[] = "</td><td>";
    const char end[] = "</td>";
    QString rc;
    QTextStream str(&rc);
    str << "<html><head/><body><table>"
        << start << Tr::tr("Thread&nbsp;id:")
        << sep << threadData.id << end;
    if (!threadData.targetId.isEmpty())
        str << start << Tr::tr("Target&nbsp;id:")
            << sep << threadData.targetId << end;
    if (!threadData.groupId.isEmpty())
        str << start << Tr::tr("Group&nbsp;id:")
            << sep << threadData.groupId << end;
    if (!threadData.name.isEmpty())
        str << start << Tr::tr("Name:")
            << sep << threadData.name << end;
    if (!threadData.state.isEmpty())
        str << start << Tr::tr("State:")
            << sep << threadData.state << end;
    if (!threadData.core.isEmpty())
        str << start << Tr::tr("Core:")
            << sep << threadData.core << end;
    if (threadData.address) {
        str << start << Tr::tr("Stopped&nbsp;at:") << sep;
        if (!threadData.function.isEmpty())
            str << threadData.function << "<br>";
        if (!threadData.fileName.isEmpty())
            str << threadData.fileName << ':' << threadData.lineNumber << "<br>";
        str << formatToolTipAddress(threadData.address);
    }
    str << "</table></body></html>";
    return rc;
}

QVariant ThreadItem::threadPart(int column) const
{
    switch (column) {
    case ThreadData::IdColumn:
        return threadData.id;
    case ThreadData::FunctionColumn:
        return threadData.function;
    case ThreadData::FileColumn:
        return threadData.fileName.isEmpty() ? threadData.module : threadData.fileName;
    case ThreadData::LineColumn:
        return threadData.lineNumber >= 0
                ? QString::number(threadData.lineNumber) : QString();
    case ThreadData::AddressColumn:
        return threadData.address > 0
                ? "0x" + QString::number(threadData.address, 16)
                : QString();
    case ThreadData::CoreColumn:
        return threadData.core;
    case ThreadData::StateColumn:
        return threadData.state;
    case ThreadData::TargetIdColumn:
        if (threadData.targetId.startsWith("Thread "))
            return threadData.targetId.mid(7);
        return threadData.targetId;
    case ThreadData::NameColumn:
        return threadData.name;
    case ThreadData::DetailsColumn:
        return threadData.details;
    case ThreadData::ComboNameColumn:
        return QString::fromLatin1("#%1 %2").arg(threadData.id).arg(threadData.name);
    }
    return QVariant();
}

void ThreadItem::notifyRunning() // Clear state information.
{
    threadData.address = 0;
    threadData.function.clear();
    threadData.fileName.clear();
    threadData.frameLevel = -1;
    threadData.state.clear();
    threadData.lineNumber = -1;
    threadData.stopped = false;
    update();
}

void ThreadItem::notifyStopped()
{
    threadData.stopped = true;
    update();
}

void ThreadItem::mergeThreadData(const ThreadData &other)
{
    if (!other.core.isEmpty())
        threadData.core = other.core;
    if (!other.fileName.isEmpty())
        threadData.fileName = other.fileName;
    if (!other.targetId.isEmpty())
        threadData.targetId = other.targetId;
    if (!other.name.isEmpty())
        threadData.name = other.name;
    if (other.frameLevel != -1)
        threadData.frameLevel = other.frameLevel;
    if (!other.function.isEmpty())
        threadData.function = other.function;
    if (other.address)
        threadData.address = other.address;
    if (!other.module.isEmpty())
        threadData.module = other.module;
    if (!other.details.isEmpty())
        threadData.details = other.details;
    if (!other.state.isEmpty())
        threadData.state = other.state;
    if (other.lineNumber != -1)
        threadData.lineNumber = other.lineNumber;
    update();
}


// ThreadsHandler

/*!
    \class Debugger::Internal::ThreadData
    \internal
    \brief  The ThreadData class contains information
            about a single thread.
*/

/*!
    \class Debugger::Internal::ThreadsHandler
    \internal
    \brief  The ThreadsHandler class provides a model to
            represent the running threads in a QTreeView or ComboBox.
*/

ThreadsHandler::ThreadsHandler(DebuggerEngine *engine)
    : m_engine(engine)
{
    setObjectName("ThreadsModel");
    setHeader({"  " + Tr::tr("ID") + "  ",
               Tr::tr("Address"), Tr::tr("Function"), Tr::tr("File"), Tr::tr("Line"), Tr::tr("State"),
               Tr::tr("Name"), Tr::tr("Target ID"), Tr::tr("Details"), Tr::tr("Core"),
              });
}

ThreadsHandler::~ThreadsHandler()
{
    delete m_comboBox;
}

QVariant ThreadsHandler::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DecorationRole && index.column() == 0) {
        // Return icon that indicates whether this is the active thread.
        TreeItem *item = itemForIndex(index);
        if (item && item == m_currentThread)
            return Icons::LOCATION.icon();
        return Icons::EMPTY.icon();
    }

    return ThreadsHandlerModel::data(index, role);
}

bool ThreadsHandler::setData(const QModelIndex &idx, const QVariant &data, int role)
{
    if (role == BaseTreeView::ItemActivatedRole) {
        const Thread thread = itemForIndexAtLevel<1>(idx);
        if (thread != m_currentThread) {
            m_currentThread = thread;
            threadSwitcher()->setCurrentIndex(idx.row());
            m_engine->selectThread(thread);
        }
        return true;
    }

    if (role == BaseTreeView::ItemViewEventRole) {
        ItemViewEvent ev = data.value<ItemViewEvent>();

        if (ev.as<QContextMenuEvent>()) {
            auto menu = new QMenu;
            menu->addAction(debuggerSettings()->settingsDialog.action());
            menu->popup(ev.globalPos());
            return true;
        }
    }

    return false;
}

void ThreadsHandler::sort(int column, Qt::SortOrder order)
{
    rootItem()->sortChildren([order, column](const ThreadItem *item1, const ThreadItem *item2) -> bool {
        const QVariant v1 = item1->threadPart(column);
        const QVariant v2 = item2->threadPart(column);
        if (v1 == v2)
            return false;
        if (column == 0)
            return (v1.toInt() < v2.toInt()) != (order == Qt::DescendingOrder);
        // FIXME: Use correct toXXX();
        return (v1.toString() < v2.toString()) != (order == Qt::DescendingOrder);
    });
}

Thread ThreadsHandler::currentThread() const
{
    return m_currentThread;
}

void ThreadsHandler::setCurrentThread(const Thread &thread)
{
    QTC_ASSERT(thread, return);
    if (thread == m_currentThread)
        return;

    if (!threadForId(thread->id())) {
        qWarning("ThreadsHandler::setCurrentThreadId: No such thread %s.", qPrintable(thread->id()));
        return;
    }

    m_currentThread = thread;
    thread->update();
    threadSwitcher()->setCurrentIndex(thread->index().row());
}

void ThreadsHandler::notifyGroupCreated(const QString &groupId, const QString &pid)
{
    m_pidForGroupId[groupId] = pid;
}

void ThreadsHandler::updateThread(const ThreadData &threadData)
{
    if (Thread thread = threadForId(threadData.id))
        thread->mergeThreadData(threadData);
    else
        rootItem()->appendChild(new ThreadItem(threadData));
}

void ThreadsHandler::removeThread(const QString &id)
{
    if (Thread thread = threadForId(id))
        destroyItem(thread);
}

void ThreadsHandler::removeAll()
{
    rootItem()->removeChildren();
}

bool ThreadsHandler::notifyGroupExited(const QString &groupId)
{
    QList<ThreadItem *> list;
    forItemsAtLevel<1>([&list, groupId](ThreadItem *item) {
        if (item->threadData.groupId == groupId)
            list.append(item);
    });
    for (ThreadItem *item : std::as_const(list))
        destroyItem(item);

    m_pidForGroupId.remove(groupId);
    return m_pidForGroupId.isEmpty();
}

Thread ThreadsHandler::threadForId(const QString &id) const
{
    return findItemAtLevel<1>([id](const Thread &item) {
        return item->threadData.id == id;
    });
}

void ThreadsHandler::notifyRunning(const QString &id)
{
    if (id.isEmpty() || id == "all")
        forItemsAtLevel<1>([](const Thread &thread) { thread->notifyRunning(); });
    else if (Thread thread = threadForId(id))
        thread->notifyRunning();
}

void ThreadsHandler::notifyStopped(const QString &id)
{
    if (id.isEmpty() || id == "all")
        forItemsAtLevel<1>([](const Thread &thread) { thread->notifyStopped(); });
    else if (Thread thread = threadForId(id))
        thread->notifyStopped();
}

QPointer<QComboBox> ThreadsHandler::threadSwitcher()
{
    if (!m_comboBox) {
        m_comboBox = new QComboBox;
        m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
        m_comboBox->setModel(this);
        connect(m_comboBox, &QComboBox::activated, this, [this](int row) {
            setData(index(row, 0), {}, BaseTreeView::ItemActivatedRole);
        });
    }
    return m_comboBox;
}

void ThreadsHandler::setThreads(const GdbMi &data)
{
    rootItem()->removeChildren();

    // ^done,threads=[{id="1",target-id="Thread 0xb7fdc710 (LWP 4264)",
    // frame={level="0",addr="0x080530bf",func="testQString",args=[],
    // file="/.../app.cpp",fullname="/../app.cpp",line="1175"},
    // state="stopped",core="0"}],current-thread-id="1"

    const GdbMi &threads = data["threads"];
    for (const GdbMi &item : threads) {
        const GdbMi &frame = item["frame"];
        ThreadData thread;
        thread.id = item["id"].data();
        thread.targetId = item["target-id"].data();
        thread.details = item["details"].data();
        thread.core = item["core"].data();
        thread.state = item["state"].data();
        thread.address = frame["addr"].toAddress();
        thread.function = frame["func"].data();
        thread.fileName = frame["fullname"].data();
        thread.lineNumber = frame["line"].toInt();
        thread.module = frame["from"].data();
        thread.name = item["name"].data();
        thread.stopped = thread.state != "running";
        updateThread(thread);
    }

    const QString &currentId = data["current-thread-id"].data();
    m_currentThread = threadForId(currentId);

    if (!m_currentThread && threads.childCount() > 0)
        m_currentThread = rootItem()->childAt(0);

    if (m_currentThread) {
        const QModelIndex currentThreadIndex = m_currentThread->index();
        threadSwitcher()->setCurrentIndex(currentThreadIndex.row());
    }
}

QAbstractItemModel *ThreadsHandler::model()
{
    return this;
}

} // Debugger::Internal