watchhandler.cpp 63.4 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
hjk's avatar
hjk committed
3
4
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** 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 Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
** 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.
23
**
hjk's avatar
hjk committed
24
25
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
#include "watchhandler.h"
31
32

#include "breakhandler.h"
33
#include "debuggerinternalconstants.h"
34
#include "debuggeractions.h"
35
#include "debuggercore.h"
36
#include "debuggerengine.h"
37
#include "debuggerdialogs.h"
38
#include "watchutils.h"
con's avatar
con committed
39

hjk's avatar
hjk committed
40
#include <utils/qtcassert.h>
41
#include <utils/savedaction.h>
con's avatar
con committed
42

43
44
#include <cplusplus/CppRewriter.h>

45
46
47
#include <QDebug>
#include <QEvent>
#include <QFile>
hjk's avatar
hjk committed
48
#include <QPointer>
49
50
51
52
53
54
#include <QProcess>
#include <QTextStream>
#include <QtAlgorithms>

#include <QLabel>
#include <QTextEdit>
55
#include <QTabWidget>
con's avatar
con committed
56
57

#include <ctype.h>
58
#include <utils/qtcassert.h>
hjk's avatar
hjk committed
59

hjk's avatar
hjk committed
60
61
62
63
64
65
//#define USE_WATCH_MODEL_TEST 0
//#define USE_EXPENSIVE_CHECKS 0

#if USE_WATCH_MODEL_TEST
#include "modeltest.h"
#endif
con's avatar
con committed
66

hjk's avatar
hjk committed
67
68
namespace Debugger {
namespace Internal {
con's avatar
con committed
69

70
71
72
73
// Creates debug output for accesses to the model.
enum { debugModel = 0 };

#define MODEL_DEBUG(s) do { if (debugModel) qDebug() << s; } while (0)
hjk's avatar
hjk committed
74
75
76
77
78
79
80

#if USE_EXPENSIVE_CHECKS
#define CHECK(s) s
#else
#define CHECK(s)
#endif

81

82
83
84
85
86
static QHash<QByteArray, int> theWatcherNames;
static QHash<QByteArray, int> theTypeFormats;
static QHash<QByteArray, int> theIndividualFormats;
static int theUnprintableBase = -1;

hjk's avatar
hjk committed
87

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
static QByteArray stripForFormat(const QByteArray &ba)
{
    QByteArray res;
    res.reserve(ba.size());
    int inArray = 0;
    for (int i = 0; i != ba.size(); ++i) {
        const char c = ba.at(i);
        if (c == '<')
            break;
        if (c == '[')
            ++inArray;
        if (c == ']')
            --inArray;
        if (c == ' ')
            continue;
103
104
        if (c == '&') // Treat references like the referenced type.
            continue;
105
106
107
108
109
        if (inArray && c >= '0' && c <= '9')
            continue;
        res.append(c);
    }
    return res;
110
111
}

con's avatar
con committed
112
113
////////////////////////////////////////////////////////////////////
//
114
// WatchItem
con's avatar
con committed
115
116
//
////////////////////////////////////////////////////////////////////
117

hjk's avatar
hjk committed
118
119
120
121
// Used to make sure the item cache is notified of construction and
// destruction of items.

class WatchItem;
122
123
typedef QList<WatchItem *> WatchItems;

hjk's avatar
hjk committed
124
125
126
WatchItem *itemConstructor(WatchModel *model, const QByteArray &iname);
void itemDestructor(WatchModel *model, WatchItem *item);

127
128
129
class WatchItem : public WatchData
{
public:
130
131
    WatchItem *parent; // Not owned.
    WatchItems children; // Not owned. Handled via itemDestructor().
132

hjk's avatar
hjk committed
133
134
135
private:
    friend WatchItem *itemConstructor(WatchModel *model, const QByteArray &iname);
    friend void itemDestructor(WatchModel *model, WatchItem *item);
136

hjk's avatar
hjk committed
137
    WatchItem() { parent = 0; }
hjk's avatar
hjk committed
138
139
    ~WatchItem() {}
    WatchItem(const WatchItem &); // Not implemented.
140
141
142
};

///////////////////////////////////////////////////////////////////////
hjk's avatar
hjk committed
143
//
144
// WatchModel
hjk's avatar
hjk committed
145
//
146
///////////////////////////////////////////////////////////////////////
hjk's avatar
hjk committed
147

hjk's avatar
hjk committed
148
class WatchModel : public QAbstractItemModel
hjk's avatar
hjk committed
149
{
hjk's avatar
hjk committed
150
    Q_OBJECT
hjk's avatar
hjk committed
151

hjk's avatar
hjk committed
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
private:
    explicit WatchModel(WatchHandler *handler);
    ~WatchModel();

    friend WatchItem *itemConstructor(WatchModel *model, const QByteArray &iname);
    friend void itemDestructor(WatchModel *model, WatchItem *item);

public:
    int rowCount(const QModelIndex &idx = QModelIndex()) const;
    int columnCount(const QModelIndex &idx) const;

signals:
    void currentIndexRequested(const QModelIndex &idx);
    void itemIsExpanded(const QModelIndex &idx);

private:
    QVariant data(const QModelIndex &idx, int role) const;
    bool setData(const QModelIndex &idx, const QVariant &value, int role);
    QModelIndex index(int, int, const QModelIndex &idx) const;
    QModelIndex parent(const QModelIndex &idx) const;
    bool hasChildren(const QModelIndex &idx) const;
    Qt::ItemFlags flags(const QModelIndex &idx) const;
    QVariant headerData(int section, Qt::Orientation orientation,
        int role = Qt::DisplayRole) const;
    bool canFetchMore(const QModelIndex &parent) const;
    void fetchMore(const QModelIndex &parent);

    void invalidateAll(const QModelIndex &parentIndex = QModelIndex());
180
    void resetValueCacheRecursively(WatchItem *item);
181

hjk's avatar
hjk committed
182
183
184
185
186
187
188
189
190
    WatchItem *createItem(const QByteArray &iname, const QString &name, WatchItem *parent);

    friend class WatchHandler;

    WatchItem *watchItem(const QModelIndex &) const;
    QModelIndex watchIndex(const WatchItem *needle) const;
    QModelIndex watchIndexHelper(const WatchItem *needle,
        const WatchItem *parentItem, const QModelIndex &parentIndex) const;

191
    void insertDataItem(const WatchData &data, bool destructive);
hjk's avatar
hjk committed
192
193
    Q_SLOT void reinsertAllData();
    void reinsertAllDataHelper(WatchItem *item, QList<WatchData> *data);
hjk's avatar
hjk committed
194
    bool ancestorChanged(const QSet<QByteArray> &parentINames, WatchItem *item) const;
hjk's avatar
hjk committed
195
196
    void insertBulkData(const QList<WatchData> &data);
    QString displayForAutoTest(const QByteArray &iname) const;
197
    void reinitialize(bool includeInspectData = false);
hjk's avatar
hjk committed
198
199
    void destroyItem(WatchItem *item); // With model notification.
    void destroyChildren(WatchItem *item); // With model notification.
200
    void destroyHelper(const WatchItems &items); // Without model notification.
hjk's avatar
hjk committed
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
    void emitDataChanged(int column,
        const QModelIndex &parentIndex = QModelIndex());

    friend QDebug operator<<(QDebug d, const WatchModel &m);

    void dump();
    void dumpHelper(WatchItem *item);
    Q_SLOT void emitAllChanged();

    void showInEditorHelper(QString *contents, WatchItem *item, int level);
    void setCurrentItem(const QByteArray &iname);

    QString displayType(const WatchData &typeIn) const;
    QString formattedValue(const WatchData &data) const;
    QString removeInitialNamespace(QString str) const;
    QString removeNamespaces(QString str) const;
    void formatRequests(QByteArray *out, const WatchItem *item) const;
    DebuggerEngine *engine() const;
    QString display(const WatchItem *item, int col) const;
    int itemFormat(const WatchData &data) const;
    bool contentIsValid() const;

    WatchHandler *m_handler; // Not owned.

    WatchItem *m_root; // Owned.
    WatchItem *m_localsRoot; // Not owned.
    WatchItem *m_inspectorRoot; // Not owned.
    WatchItem *m_watchRoot; // Not owned.
    WatchItem *m_returnRoot; // Not owned.
    WatchItem *m_tooltipRoot; // Not owned.

    QSet<QByteArray> m_expandedINames;
    QSet<QByteArray> m_fetchTriggered;

    QStringList typeFormatList(const WatchData &data) const;
    TypeFormats m_reportedTypeFormats;

    // QWidgets and QProcesses taking care of special displays.
    typedef QMap<QByteArray, QPointer<QObject> > EditHandlers;
    EditHandlers m_editHandlers;

    WatchItem *createItem(const QByteArray &iname);
    WatchItem *createItem(const WatchData &data);
    void assignData(WatchItem *item, const WatchData &data);
    WatchItem *findItem(const QByteArray &iname) const;
    friend class WatchItem;
hjk's avatar
hjk committed
247
248
    typedef QHash<QByteArray, WatchItem *> Cache;
    Cache m_cache;
249
250
    typedef QHash<QByteArray, QString> ValueCache;
    ValueCache m_valueCache;
hjk's avatar
hjk committed
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

    #if USE_EXPENSIVE_CHECKS
    QHash<const WatchItem *, QByteArray> m_cache2;
    void checkTree();
    void checkItem(const WatchItem *item) const;
    void checkTree(WatchItem *item, QSet<QByteArray> *inames);
    #endif
};

WatchModel::WatchModel(WatchHandler *handler)
    : m_handler(handler)
{
    m_root = createItem(QByteArray(), tr("Root"), 0);
    // Note: Needs to stay
    m_localsRoot = createItem("local", tr("Locals"), m_root);
    m_inspectorRoot = createItem("inspect", tr("Inspector"), m_root);
    m_watchRoot = createItem("watch", tr("Expressions"), m_root);
    m_returnRoot = createItem("return", tr("Return Value"), m_root);
    m_tooltipRoot = createItem("tooltip", tr("Tooltip"), m_root);

    connect(debuggerCore()->action(SortStructMembers), SIGNAL(valueChanged(QVariant)),
        SLOT(reinsertAllData()));
    connect(debuggerCore()->action(ShowStdNamespace), SIGNAL(valueChanged(QVariant)),
        SLOT(reinsertAllData()));
    connect(debuggerCore()->action(ShowQtNamespace), SIGNAL(valueChanged(QVariant)),
        SLOT(reinsertAllData()));
hjk's avatar
hjk committed
277
278
}

279
280
WatchModel::~WatchModel()
{
hjk's avatar
hjk committed
281
282
283
284
    CHECK(checkItem(m_root));
    destroyChildren(m_root);
    itemDestructor(this, m_root);
    QTC_CHECK(m_cache.isEmpty());
285
286
}

hjk's avatar
hjk committed
287
WatchItem *itemConstructor(WatchModel *model, const QByteArray &iname)
hjk's avatar
hjk committed
288
{
hjk's avatar
hjk committed
289
290
291
292
293
294
295
    QTC_CHECK(!model->m_cache.contains(iname));
    WatchItem *item = new WatchItem();
    item->iname = iname;
    model->m_cache[iname] = item;
    CHECK(model->m_cache2[item] = iname);
    CHECK(model->checkItem(item));
    return item;
hjk's avatar
hjk committed
296
297
}

hjk's avatar
hjk committed
298
void itemDestructor(WatchModel *model, WatchItem *item)
hjk's avatar
hjk committed
299
{
hjk's avatar
hjk committed
300
301
302
303
304
    QTC_ASSERT(model->m_cache.value(item->iname) == item, return);
    CHECK(model->checkItem(item));
    CHECK(model->m_cache2.remove(item));
    model->m_cache.remove(item->iname);
    delete item;
hjk's avatar
hjk committed
305
306
}

hjk's avatar
hjk committed
307
WatchItem *WatchModel::createItem(const QByteArray &iname, const QString &name, WatchItem *parent)
308
{
hjk's avatar
hjk committed
309
310
311
312
313
314
315
316
    WatchItem *item = itemConstructor(this, iname);
    item->name = name;
    item->hasChildren = true; // parent == 0;
    item->state = 0;
    item->parent = parent;
    if (parent)
        parent->children.append(item);
    return item;
317
318
}

319
void WatchModel::reinitialize(bool includeInspectData)
320
{
hjk's avatar
hjk committed
321
322
323
324
325
326
327
    CHECK(checkTree());
    //MODEL_DEBUG("REMOVING " << n << " CHILDREN OF " << m_root->iname);
    QTC_CHECK(m_root->children.size() == 5);
    destroyChildren(m_localsRoot);
    destroyChildren(m_watchRoot);
    destroyChildren(m_returnRoot);
    destroyChildren(m_tooltipRoot);
328
329
330
331
    if (includeInspectData) {
        destroyChildren(m_inspectorRoot);
        QTC_CHECK(m_cache.size() == 6);
    }
hjk's avatar
hjk committed
332
    CHECK(checkTree());
333
334
}

hjk's avatar
hjk committed
335
void WatchModel::emitAllChanged()
336
{
hjk's avatar
hjk committed
337
    emit layoutChanged();
338
}
339

340
341
342
343
DebuggerEngine *WatchModel::engine() const
{
    return m_handler->m_engine;
}
344
345
346
347
348
349
350
351
352
353
354

void WatchModel::dump()
{
    qDebug() << "\n";
    foreach (WatchItem *child, m_root->children)
        dumpHelper(child);
}

void WatchModel::dumpHelper(WatchItem *item)
{
    qDebug() << "ITEM: " << item->iname
hjk's avatar
hjk committed
355
        << (item->parent ? item->parent->iname : "<none>");
356
357
358
359
    foreach (WatchItem *child, item->children)
        dumpHelper(child);
}

360
void WatchModel::destroyHelper(const WatchItems &items)
hjk's avatar
hjk committed
361
{
hjk's avatar
hjk committed
362
363
364
365
    for (int i = items.size(); --i >= 0; ) {
        WatchItem *item = items.at(i);
        destroyHelper(item->children);
        itemDestructor(this, item);
366
    }
hjk's avatar
hjk committed
367
368
}

369
void WatchModel::destroyItem(WatchItem *item)
con's avatar
con committed
370
{
hjk's avatar
hjk committed
371
372
373
374
375
376
    const QByteArray iname = item->iname;
    CHECK(checkTree());
    QTC_ASSERT(m_cache.contains(iname), return);

    // Deregister from model and parent.
    // It's sufficient to do this non-recursively.
377
    WatchItem *parent = item->parent;
hjk's avatar
hjk committed
378
379
380
    QTC_ASSERT(parent, return);
    QModelIndex parentIndex = watchIndex(parent);
    const int i = parent->children.indexOf(item);
381
    //MODEL_DEBUG("NEED TO REMOVE: " << item->iname << "AT" << n);
hjk's avatar
hjk committed
382
383
    beginRemoveRows(parentIndex, i, i);
    parent->children.removeAt(i);
384
    endRemoveRows();
hjk's avatar
hjk committed
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399

    // Destroy contents.
    destroyHelper(item->children);
    itemDestructor(this, item);
    QTC_ASSERT(!m_cache.contains(iname), return);
    CHECK(checkTree());
}

void WatchModel::destroyChildren(WatchItem *item)
{
    CHECK(checkTree());
    QTC_ASSERT(m_cache.contains(item->iname), return);
    if (item->children.isEmpty())
        return;

400
    WatchItems items = item->children;
hjk's avatar
hjk committed
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

    // Deregister from model and parent.
    // It's sufficient to do this non-recursively.
    QModelIndex idx = watchIndex(item);
    beginRemoveRows(idx, 0, items.size() - 1);
    item->children.clear();
    endRemoveRows();

    // Destroy contents.
    destroyHelper(items);
    CHECK(checkTree());
}

WatchItem *WatchModel::findItem(const QByteArray &iname) const
{
    return m_cache.value(iname, 0);
}

WatchItem *WatchModel::createItem(const WatchData &data)
{
    WatchItem *item = itemConstructor(this, data.iname);
    static_cast<WatchData &>(*item) = data;
    return item;
}

void WatchModel::assignData(WatchItem *item, const WatchData &data)
{
    CHECK(checkItem(item));
    QTC_ASSERT(data.iname == item->iname,
        m_cache.remove(item->iname);
        m_cache[data.iname] = item);
    static_cast<WatchData &>(*item) = data;
    CHECK(checkItem(item));
434
435
}

436
437
438
439
void WatchModel::reinsertAllData()
{
    QList<WatchData> list;
    reinsertAllDataHelper(m_root, &list);
440
    reinitialize(true);
hjk's avatar
hjk committed
441
    insertBulkData(list);
442
443
444
445
446
}

void WatchModel::reinsertAllDataHelper(WatchItem *item, QList<WatchData> *data)
{
    data->append(*item);
hjk's avatar
hjk committed
447
    data->back().setAllUnneeded();
448
449
450
451
    foreach (WatchItem *child, item->children)
        reinsertAllDataHelper(child, data);
}

452
static QByteArray parentName(const QByteArray &iname)
453
{
hjk's avatar
hjk committed
454
455
    const int pos = iname.lastIndexOf('.');
    return pos == -1 ? QByteArray() : iname.left(pos);
con's avatar
con committed
456
457
}

458
static QString niceTypeHelper(const QByteArray &typeIn)
459
{
460
461
462
    typedef QMap<QByteArray, QString> Cache;
    static Cache cache;
    const Cache::const_iterator it = cache.constFind(typeIn);
463
    if (it != cache.constEnd())
464
        return it.value();
465
    const QString simplified = CPlusPlus::simplifySTLType(QLatin1String(typeIn));
466
467
    cache.insert(typeIn, simplified); // For simplicity, also cache unmodified types
    return simplified;
con's avatar
con committed
468
469
}

470
QString WatchModel::removeNamespaces(QString str) const
471
{
hjk's avatar
hjk committed
472
    if (!debuggerCore()->boolSetting(ShowStdNamespace))
473
        str.remove(QLatin1String("std::"));
hjk's avatar
hjk committed
474
    if (!debuggerCore()->boolSetting(ShowQtNamespace)) {
475
        const QString qtNamespace = QString::fromLatin1(engine()->qtNamespace());
476
        if (!qtNamespace.isEmpty())
477
478
479
480
481
            str.remove(qtNamespace);
    }
    return str;
}

482
QString WatchModel::removeInitialNamespace(QString str) const
483
484
485
486
487
{
    if (str.startsWith(QLatin1String("std::"))
            && debuggerCore()->boolSetting(ShowStdNamespace))
        str = str.mid(5);
    if (!debuggerCore()->boolSetting(ShowQtNamespace)) {
488
        const QByteArray qtNamespace = engine()->qtNamespace();
489
        if (!qtNamespace.isEmpty() && str.startsWith(QLatin1String(qtNamespace)))
490
            str = str.mid(qtNamespace.size());
491
    }
492
493
494
495
496
    return str;
}

QString WatchModel::displayType(const WatchData &data) const
{
497
    QString base = data.displayedType.isEmpty()
498
499
        ? niceTypeHelper(data.type)
        : data.displayedType;
500
    if (data.bitsize)
501
502
        base += QString::fromLatin1(":%1").arg(data.bitsize);
    base.remove(QLatin1Char('\''));
503
    return base;
504
505
}

hjk's avatar
hjk committed
506
static int formatToIntegerBase(int format)
507
508
{
    switch (format) {
hjk's avatar
hjk committed
509
510
511
512
513
514
        case HexadecimalFormat:
            return 16;
        case BinaryFormat:
            return 2;
        case OctalFormat:
            return 8;
515
516
517
518
    }
    return 10;
}

519
520
521
template <class IntType> QString reformatInteger(IntType value, int format)
{
    switch (format) {
hjk's avatar
hjk committed
522
        case HexadecimalFormat:
523
            return QLatin1String("(hex) ") + QString::number(value, 16);
hjk's avatar
hjk committed
524
        case BinaryFormat:
525
            return QLatin1String("(bin) ") + QString::number(value, 2);
hjk's avatar
hjk committed
526
        case OctalFormat:
527
            return QLatin1String("(oct) ") + QString::number(value, 8);
528
529
530
531
    }
    return QString::number(value); // not reached
}

532
// Format printable (char-type) characters
533
static QString reformatCharacter(int code, int format)
534
535
536
537
{
    const QString codeS = reformatInteger(code, format);
    if (code < 0) // Append unsigned value.
        return codeS + QLatin1String(" / ") + reformatInteger(256 + code, format);
538
539
540
    const QChar c = QLatin1Char(code);
    if (c.isPrint())
        return codeS + QLatin1String(" '") + c + QLatin1Char('\'');
541
542
543
544
545
546
547
548
549
550
551
552
553
    switch (code) {
    case 0:
        return codeS + QLatin1String(" '\\0'");
    case '\r':
        return codeS + QLatin1String(" '\\r'");
    case '\t':
        return codeS + QLatin1String(" '\\t'");
    case '\n':
        return codeS + QLatin1String(" '\\n'");
    }
    return codeS;
}

554
555
556
557
static QString quoteUnprintable(const QString &str)
{
    if (WatchHandler::unprintableBase() == 0)
        return str;
558

559
    QString encoded;
560
561
562
    if (WatchHandler::unprintableBase() == -1) {
        foreach (const QChar c, str) {
            int u = c.unicode();
563
            if (c.isPrint())
564
565
                encoded += c;
            else if (u == '\r')
566
                encoded += QLatin1String("\\r");
567
            else if (u == '\t')
568
                encoded += QLatin1String("\\t");
569
            else if (u == '\n')
570
                encoded += QLatin1String("\\n");
571
            else
572
                encoded += QString::fromLatin1("\\%1")
573
574
575
576
577
                    .arg(c.unicode(), 3, 8, QLatin1Char('0'));
        }
        return encoded;
    }

578
579
580
581
    foreach (const QChar c, str) {
        if (c.isPrint()) {
            encoded += c;
        } else if (WatchHandler::unprintableBase() == 8) {
582
            encoded += QString::fromLatin1("\\%1")
583
584
                .arg(c.unicode(), 3, 8, QLatin1Char('0'));
        } else {
585
            encoded += QString::fromLatin1("\\u%1")
586
587
588
589
590
591
                .arg(c.unicode(), 4, 16, QLatin1Char('0'));
        }
    }
    return encoded;
}

592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
static QString translate(const QString &str)
{
    if (str.startsWith(QLatin1Char('<'))) {
        if (str == QLatin1String("<Edit>"))
            return WatchHandler::tr("<Edit>");
        if (str == QLatin1String("<empty>"))
            return WatchHandler::tr("<empty>");
        if (str == QLatin1String("<uninitialized>"))
            return WatchHandler::tr("<uninitialized>");
        if (str == QLatin1String("<invalid>"))
            return WatchHandler::tr("<invalid>");
        if (str == QLatin1String("<not accessible>"))
            return WatchHandler::tr("<not accessible>");
        if (str.endsWith(QLatin1String(" items>"))) {
            // '<10 items>' or '<>10 items>' (more than)
            bool ok;
            const bool moreThan = str.at(1) == QLatin1Char('>');
            const int numberPos = moreThan ? 2 : 1;
            const int len = str.indexOf(QLatin1Char(' ')) - numberPos;
            const int size = str.mid(numberPos, len).toInt(&ok);
            QTC_ASSERT(ok, qWarning("WatchHandler: Invalid item count '%s'",
613
                qPrintable(str)));
614
615
616
617
618
619
620
621
            return moreThan ?
                     WatchHandler::tr("<more than %n items>", 0, size) :
                     WatchHandler::tr("<%n items>", 0, size);
        }
    }
    return quoteUnprintable(str);
}

622
QString WatchModel::formattedValue(const WatchData &data) const
623
{
624
625
    const QString &value = data.value;

626
627
628
629
630
631
632
633
    if (data.type == "bool") {
        if (value == QLatin1String("0"))
            return QLatin1String("false");
        if (value == QLatin1String("1"))
            return QLatin1String("true");
        return value;
    }

634
    if (isIntType(data.type)) {
635
636
        if (value.isEmpty())
            return value;
637
        // Do not reformat booleans (reported as 'true, false').
638
        const QChar firstChar = value.at(0);
639
        if (!firstChar.isDigit() && firstChar != QLatin1Char('-'))
640
            return value;
641

642
        // Append quoted, printable character also for decimal.
643
        const int format = itemFormat(data);
644
        if (data.type.endsWith("char")) {
645
            bool ok;
646
647
            const int code = value.toInt(&ok);
            return ok ? reformatCharacter(code, format) : value;
648
649
        }
        // Rest: Leave decimal as is
650
        if (format <= 0)
651
            return value;
652
        // Evil hack, covers 'unsigned' as well as quint64.
653
        if (data.type.contains('u'))
654
655
            return reformatInteger(value.toULongLong(0, 0), format);
        return reformatInteger(value.toLongLong(), format);
656
    }
657

hjk's avatar
hjk committed
658
    if (data.type == "va_list")
659
        return value;
hjk's avatar
hjk committed
660

661
    if (!isPointerType(data.type) && !data.isVTablePointer()) {
662
        bool ok = false;
663
        qulonglong integer = value.toULongLong(&ok, 0);
664
665
666
667
        if (ok) {
            const int format = itemFormat(data);
            return reformatInteger(integer, format);
        }
668
    }
669

670
    return translate(value);
671
672
}

673
674
675
676
677
678
679
680
681
// Get a pointer address from pointer values reported by the debugger.
// Fix CDB formatting of pointers "0x00000000`000003fd class foo *", or
// "0x00000000`000003fd "Hallo"", or check gdb formatting of characters.
static inline quint64 pointerValue(QString data)
{
    const int blankPos = data.indexOf(QLatin1Char(' '));
    if (blankPos != -1)
        data.truncate(blankPos);
    data.remove(QLatin1Char('`'));
682
    return data.toULongLong(0, 0);
683
684
}

685
686
687
688
689
690
691
692
693
// Return the type used for editing
static inline int editType(const WatchData &d)
{
    if (d.type == "bool")
        return QVariant::Bool;
    if (isIntType(d.type))
        return d.type.contains('u') ? QVariant::ULongLong : QVariant::LongLong;
    if (isFloatType(d.type))
        return QVariant::Double;
694
695
696
    // Check for pointers using hex values (0xAD00 "Hallo")
    if (isPointerType(d.type) && d.value.startsWith(QLatin1String("0x")))
        return QVariant::ULongLong;
697
698
699
700
701
702
703
704
705
706
   return QVariant::String;
}

// Convert to editable (see above)
static inline QVariant editValue(const WatchData &d)
{
    switch (editType(d)) {
    case QVariant::Bool:
        return d.value != QLatin1String("0") && d.value != QLatin1String("false");
    case QVariant::ULongLong:
707
708
        if (isPointerType(d.type)) // Fix pointer values (0xAD00 "Hallo" -> 0xAD00)
            return QVariant(pointerValue(d.value));
709
710
711
712
713
714
715
716
        return QVariant(d.value.toULongLong());
    case QVariant::LongLong:
        return QVariant(d.value.toLongLong());
    case QVariant::Double:
        return QVariant(d.value.toDouble());
    default:
        break;
    }
717
718
    // Some string value: '0x434 "Hallo"':
    // Remove quotes and replace newlines, which will cause line edit troubles.
hjk's avatar
hjk committed
719
    QString stringValue = d.value;
720
721
722
723
724
725
726
727
    if (stringValue.endsWith(QLatin1Char('"'))) {
        const int leadingDoubleQuote = stringValue.indexOf(QLatin1Char('"'));
        if (leadingDoubleQuote != stringValue.size() - 1) {
            stringValue.truncate(stringValue.size() - 1);
            stringValue.remove(0, leadingDoubleQuote + 1);
            stringValue.replace(QLatin1String("\n"), QLatin1String("\\n"));
        }
    }
728
    return QVariant(translate(stringValue));
729
730
}

hjk's avatar
hjk committed
731
bool WatchModel::canFetchMore(const QModelIndex &idx) const
hjk's avatar
hjk committed
732
{
hjk's avatar
hjk committed
733
734
735
    if (!idx.isValid())
        return false;
    WatchItem *item = watchItem(idx);
736
    QTC_ASSERT(item, return false);
737
738
    if (!contentIsValid() && !item->isInspect())
        return false;
hjk's avatar
hjk committed
739
740
741
    if (!item->iname.contains('.'))
        return false;
    return !m_fetchTriggered.contains(item->iname);
742
743
}

hjk's avatar
hjk committed
744
void WatchModel::fetchMore(const QModelIndex &idx)
745
{
hjk's avatar
hjk committed
746
747
748
    if (!idx.isValid())
        return; // Triggered by ModelTester.
    WatchItem *item = watchItem(idx);
749
750
    QTC_ASSERT(item, return);
    QTC_ASSERT(!m_fetchTriggered.contains(item->iname), return);
hjk's avatar
hjk committed
751
    m_expandedINames.insert(item->iname);
752
753
754
755
    m_fetchTriggered.insert(item->iname);
    if (item->children.isEmpty()) {
        WatchData data = *item;
        data.setChildrenNeeded();
756
757
758
        WatchUpdateFlags flags;
        flags.tryIncremental = true;
        engine()->updateWatchData(data, flags);
759
760
761
762
763
764
765
766
767
768
    }
}

QModelIndex WatchModel::index(int row, int column, const QModelIndex &parent) const
{
    if (!hasIndex(row, column, parent))
        return QModelIndex();

    const WatchItem *item = watchItem(parent);
    QTC_ASSERT(item, return QModelIndex());
769
770
    if (row >= item->children.size())
        return QModelIndex();
771
772
773
774
775
776
777
778
779
    return createIndex(row, column, (void*)(item->children.at(row)));
}

QModelIndex WatchModel::parent(const QModelIndex &idx) const
{
    if (!idx.isValid())
        return QModelIndex();

    const WatchItem *item = watchItem(idx);
hjk's avatar
hjk committed
780
781
    const WatchItem *parent = item->parent;
    if (!parent || parent == m_root)
782
783
        return QModelIndex();

hjk's avatar
hjk committed
784
    const WatchItem *grandparent = parent->parent;
785
786
787
    if (!grandparent)
        return QModelIndex();

788
789
    const WatchItems &uncles = grandparent->children;
    for (int i = 0, n = uncles.size(); i < n; ++i)
hjk's avatar
hjk committed
790
791
        if (uncles.at(i) == parent)
            return createIndex(i, 0, (void*) parent);
792
793

    return QModelIndex();
hjk's avatar
hjk committed
794
795
796
797
}

int WatchModel::rowCount(const QModelIndex &idx) const
{
hjk's avatar
hjk committed
798
799
    if (!idx.isValid())
        return m_root->children.size();
hjk's avatar
hjk committed
800
801
802
803
804
    if (idx.column() > 0)
        return 0;
    return watchItem(idx)->children.size();
}

805
int WatchModel::columnCount(const QModelIndex &idx) const
hjk's avatar
hjk committed
806
{
807
    Q_UNUSED(idx)
808
809
810
811
812
813
814
815
816
817
818
    return 3;
}

bool WatchModel::hasChildren(const QModelIndex &parent) const
{
    WatchItem *item = watchItem(parent);
    return !item || item->hasChildren;
}

WatchItem *WatchModel::watchItem(const QModelIndex &idx) const
{
hjk's avatar
hjk committed
819
    WatchItem *item = idx.isValid()
820
        ? static_cast<WatchItem*>(idx.internalPointer()) : m_root;
hjk's avatar
hjk committed
821
822
    CHECK(checkItem(item));
    return item;
823
824
825
826
}

QModelIndex WatchModel::watchIndex(const WatchItem *item) const
{
hjk's avatar
hjk committed
827
    CHECK(checkItem(item));
828
829
830
    return watchIndexHelper(item, m_root, QModelIndex());
}

831
QModelIndex WatchModel::watchIndexHelper(const WatchItem *needle,
832
833
834
835
836
837
838
839
840
841
    const WatchItem *parentItem, const QModelIndex &parentIndex) const
{
    if (needle == parentItem)
        return parentIndex;
    for (int i = parentItem->children.size(); --i >= 0; ) {
        const WatchItem *childItem = parentItem->children.at(i);
        QModelIndex childIndex = index(i, 0, parentIndex);
        QModelIndex idx = watchIndexHelper(needle, childItem, childIndex);
        if (idx.isValid())
            return idx;
hjk's avatar
hjk committed
842
    }
843
    return QModelIndex();
hjk's avatar
hjk committed
844
845
}

846
void WatchModel::emitDataChanged(int column, const QModelIndex &parentIndex)
847
848
849
850
851
852
853
854
855
856
857
{
    QModelIndex idx1 = index(0, column, parentIndex);
    QModelIndex idx2 = index(rowCount(parentIndex) - 1, column, parentIndex);
    if (idx1.isValid() && idx2.isValid())
        emit dataChanged(idx1, idx2);
    //qDebug() << "CHANGING:\n" << idx1 << "\n" << idx2 << "\n"
    //    << data(parentIndex, INameRole).toString();
    for (int i = rowCount(parentIndex); --i >= 0; )
        emitDataChanged(column, index(i, 0, parentIndex));
}

858
859
860
861
862
863
864
865
void WatchModel::invalidateAll(const QModelIndex &parentIndex)
{
    QModelIndex idx1 = index(0, 0, parentIndex);
    QModelIndex idx2 = index(rowCount(parentIndex) - 1, columnCount(parentIndex) - 1, parentIndex);
    if (idx1.isValid() && idx2.isValid())
        emit dataChanged(idx1, idx2);
}

866
void WatchModel::resetValueCacheRecursively(WatchItem *item)
867
{
868
    m_valueCache[item->iname] = item->value;
869
870
    const WatchItems &items = item->children;
    for (int i = items.size(); --i >= 0; )
871
        resetValueCacheRecursively(items.at(i));
872
873
}

874
875
// Truncate value for item view, maintaining quotes.
static QString truncateValue(QString v)
876
877
878
879
880
881
882
883
884
885
{
    enum { maxLength = 512 };
    if (v.size() < maxLength)
        return v;
    const bool isQuoted = v.endsWith(QLatin1Char('"')); // check for 'char* "Hallo"'
    v.truncate(maxLength);
    v += isQuoted ? QLatin1String("...\"") : QLatin1String("...");
    return v;
}

886
887
int WatchModel::itemFormat(const WatchData &data) const
{
888
    const int individualFormat = theIndividualFormats.value(data.iname, -1);
889
890
    if (individualFormat != -1)
        return individualFormat;
891
    return theTypeFormats.value(stripForFormat(data.type), -1);
892
893
}

894
895
bool WatchModel::contentIsValid() const
{
hjk's avatar
hjk committed
896
    // FIXME:
897
    // inspector doesn't follow normal beginCycle()/endCycle()
hjk's avatar
hjk committed
898
899
    //if (m_type == InspectWatch)
    //    return true;
900
901
902
    return m_handler->m_contentsValid;
}

hjk's avatar
hjk committed
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
#if USE_EXPENSIVE_CHECKS
void WatchModel::checkTree()
{
    QSet<QByteArray> inames;
    checkTree(m_root, &inames);
    QSet<QByteArray> current = m_cache.keys().toSet();
    Q_ASSERT(inames == current);
}

void WatchModel::checkTree(WatchItem *item, QSet<QByteArray> *inames)
{
    checkItem(item);
    inames->insert(item->iname);
    for (int i = 0, n = item->children.size(); i != n; ++i)
        checkTree(item->children.at(i), inames);
}

void WatchModel::checkItem(const WatchItem *item) const
{
    Q_ASSERT(item->children.size() < 1000 * 1000);
    Q_ASSERT(m_cache2.contains(item));
    Q_ASSERT(m_cache2.value(item) == item->iname);
    Q_ASSERT(m_cache.value(item->iname) == item);
}
#endif

static QString expression(const WatchItem *item)
930
931
{
    if (!item->exp.isEmpty())
932
         return QString::fromLatin1(item->exp);
hjk's avatar
hjk committed
933
    if (item->address && !item->type.isEmpty()) {
934
        return QString::fromLatin1("*(%1*)%2").
hjk's avatar
hjk committed
935
936
937
938
                arg(QLatin1String(item->type), QLatin1String(item->hexAddress()));
    }
    if (const WatchItem *parent = item->parent) {
        if (!parent->exp.isEmpty())
939
           return QString::fromLatin1("(%1).%2")
hjk's avatar
hjk committed
940
941
942
            .arg(QString::fromLatin1(parent->exp), item->name);
    }
    return QString();
943
944
}

945
946
947
948
949
QString WatchModel::display(const WatchItem *item, int col) const
{
    QString result;
    switch (col) {
        case 0:
hjk's avatar
hjk committed
950
            if (item->parent == m_watchRoot && item->name.isEmpty())
951
                result = tr("<Edit>");
hjk's avatar
hjk committed
952
            else if (item->parent == m_returnRoot)
953
                result = tr("returned value");
hjk's avatar
hjk committed
954
            else if (item->name == QLatin1String("*"))
955
956
957
958
959
960
961
                result = QLatin1Char('*') + item->parent->name;
            else
                result = removeInitialNamespace(item->name);
            break;
        case 1:
            result = removeInitialNamespace(
                truncateValue(formattedValue(*item)));
962
            // Append referencing address unless the value contains it.
963
            if (item->referencingAddress) {
964
965
966
967
968
969
                if (result.startsWith(QLatin1String("0x"))) {
                    result.prepend(QLatin1Char('@'));
                } else {
                    result += QLatin1String(" @");
                    result += QString::fromLatin1(item->hexReferencingAddress());
                }
970
971
972
973
974
975
976
977
978
979
980
981
982
            }
            break;
        case 2:
            result = removeNamespaces(displayType(*item));
            break;
        default:
            break;
    }
    return result;
}

QString WatchModel::displayForAutoTest(const QByteArray &iname) const
{
hjk's avatar
hjk committed
983
    WatchItem *item = findItem(iname);
984
985
986
987
988
    if (item)
        return display(item, 1) + QLatin1Char(' ') + display(item, 2);
    return QString();
}

hjk's avatar
hjk committed
989
990
QVariant WatchModel::data(const QModelIndex &idx, int role) const
{
hjk's avatar
hjk committed
991
992
993
    if (!idx.isValid())
        return QVariant(); // Triggered by ModelTester.

994
995
    const WatchItem *item = watchItem(idx);
    const WatchItem &data = *item;
con's avatar
con committed
996
997

    switch (role) {
hjk's avatar
hjk committed
998
        case LocalsEditTypeRole:
999
            return QVariant(editType(data));
hjk's avatar
hjk committed
1000

1001
1002
1003
        case LocalsNameRole:
            return QVariant(data.name);

hjk's avatar
hjk committed
1004
        case LocalsIntegerBaseRole:
1005
1006
            if (isPointerType(data.type)) // Pointers using 0x-convention
                return QVariant(16);
1007
            return QVariant(formatToIntegerBase(itemFormat(data)));
hjk's avatar
hjk committed
1008
1009

        case Qt::EditRole: {
1010
            switch (idx.column()) {
hjk's avatar
hjk committed
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
                case 0:
                    return QVariant(expression(item));
                case 1:
                    return editValue(data);
                case 2:
                    // FIXME:: To be tested: Can debuggers handle those?
                    if (!data.displayedType.isEmpty())
                        return data.displayedType;
                    return QString::fromUtf8(data.type);
                default:
                    break;
            }
        }

1025
1026
        case Qt::DisplayRole:
            return display(item, idx.column());
hjk's avatar
hjk committed
1027

1028
        case Qt::ToolTipRole:
hjk's avatar
hjk committed
1029
            return debuggerCore()->boolSetting(UseToolTipsInLocalsView)
1030
                ? data.toToolTip() : QVariant();
con's avatar
con committed
1031
1032
1033
1034

        case Qt::ForegroundRole: {
            static const QVariant red(QColor(200, 0, 0));
            static const QVariant gray(QColor(140, 140, 140));
1035
            if (idx.column() == 1) {
1036
                if (!data.valueEnabled || (!contentIsValid() && !data.isInspect()))
1037
1038
1039
                    return gray;
                if (data.value != m_valueCache.value(data.iname))
                    return red;
con's avatar
con committed
1040
1041
1042
1043
            }
            break;
        }

1044
1045
        case LocalsExpressionRole:
            return QVariant(expression(item));
hjk's avatar
hjk committed
1046

1047
1048
1049
        case LocalsRawExpressionRole:
            return data.exp;

1050
        case LocalsINameRole:
con's avatar
con committed
1051
1052
            return data.iname;

1053
        case LocalsExpandedRole:
hjk's avatar
hjk committed
1054
            return m_expandedINames.contains(data.iname);
1055

1056
        case LocalsTypeFormatListRole:
hjk's avatar
hjk committed
1057
            return typeFormatList(data);
1058

1059
        case LocalsTypeRole:
1060
1061
            return removeNamespaces(displayType(data));

1062
        case LocalsRawTypeRole:
1063
1064
            return QString::fromLatin1(data.type);

1065
        case LocalsTypeFormatRole:
1066
            return theTypeFormats.value(stripForFormat(data.type), -1);
1067

1068
        case LocalsIndividualFormatRole:
1069
            return theIndividualFormats.value(data.iname, -1);
1070

1071
        case LocalsRawValueRole:
1072
            return data.value;
1073

1074
        case LocalsPointerValueRole:
1075
            return data.referencingAddress;
1076

hjk's avatar
hjk committed
1077
        case LocalsIsWatchpointAtAddressRole: {
1078
            BreakpointParameters bp(WatchpointAtAddress);
hjk's avatar
hjk committed
1079
1080
1081
            bp.address = data.coreAddress();
            return engine()->breakHandler()->findWatchpoint(bp) != 0;
        }
1082
1083

        case LocalsAddressRole:
1084
            return QVariant(data.coreAddress());
1085
1086
        case LocalsReferencingAddressRole:
            return QVariant(data.referencingAddress);
1087
1088
        case LocalsSizeRole:
            return QVariant(data.size);
1089
1090

        case LocalsIsWatchpointAtPointerValueRole:
hjk's avatar
hjk committed
1091
            if (isPointerType(data.type)) {