debuggertooltipmanager.cpp 50.3 KB
Newer Older
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
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "debuggertooltipmanager.h"
#include "watchutils.h"
#include "debuggerengine.h"
37
#include "debuggeractions.h"
38
#include "watchhandler.h"
39
#include "watchutils.h"
40
41
42
43
44
45
#include "stackhandler.h"
#include "debuggercore.h"

#include <coreplugin/icore.h>
#include <coreplugin/modemanager.h>
#include <coreplugin/imode.h>
46
#include <coreplugin/coreconstants.h>
47
48
#include <coreplugin/editormanager/editormanager.h>
#include <texteditor/itexteditor.h>
49
#include <texteditor/basetexteditor.h>
50
#include <texteditor/tooltip/tooltip.h>
51
#include <texteditor/tooltip/tipcontents.h>
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

#include <utils/qtcassert.h>

#include <QtGui/QToolButton>
#include <QtGui/QToolBar>
#include <QtGui/QVBoxLayout>
#include <QtGui/QStyle>
#include <QtGui/QIcon>
#include <QtGui/QApplication>
#include <QtGui/QMainWindow>
#include <QtGui/QMoveEvent>
#include <QtGui/QDesktopWidget>
#include <QtGui/QScrollBar>
#include <QtGui/QSortFilterProxyModel>
#include <QtGui/QStandardItemModel>
#include <QtGui/QStandardItem>
#include <QtGui/QPlainTextEdit>
#include <QtGui/QTextCursor>
#include <QtGui/QTextDocument>
#include <QtGui/QLabel>
72
#include <QtGui/QClipboard>
73
74
75
76
77
78

#include <QtCore/QVariant>
#include <QtCore/QStack>
#include <QtCore/QDebug>
#include <QtCore/QTimer>

hjk's avatar
hjk committed
79
80
81
using namespace Core;
using namespace TextEditor;

82
enum { debugToolTips = 0 };
83
enum { debugToolTipPositioning = 0 };
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

// Expire tooltips after n days on (no longer load them) in order
// to avoid them piling up.
enum { toolTipsExpiryDays = 6 };

static const char sessionSettingsKeyC[] = "DebuggerToolTips";
static const char sessionDocumentC[] = "DebuggerToolTips";
static const char sessionVersionAttributeC[] = "version";
static const char toolTipElementC[] = "DebuggerToolTip";
static const char toolTipClassAttributeC[] = "class";
static const char fileNameAttributeC[] = "name";
static const char functionAttributeC[] = "function";
static const char textPositionAttributeC[] = "position";
static const char textLineAttributeC[] = "line";
static const char textColumnAttributeC[] = "column";
99
100
static const char offsetXAttributeC[] = "offset_x";
static const char offsetYAttributeC[] = "offset_y";
101
102
103
104
105
106
107
108
109
110
111
112
static const char engineTypeAttributeC[] = "engine";
static const char dateAttributeC[] = "date";
static const char treeElementC[] = "tree";
static const char treeModelAttributeC[] = "model"; // Locals/Watches
static const char treeExpressionAttributeC[] = "expression"; // Locals/Watches
static const char modelElementC[] = "model";
static const char modelColumnCountAttributeC[] = "columncount";
static const char modelRowElementC[] = "row";
static const char modelItemElementC[] = "item";

// Forward a stream reader across end elements looking for the
// next start element of a desired type.
hjk's avatar
hjk committed
113
static bool readStartElement(QXmlStreamReader &r, const char *name)
114
115
116
117
{
    if (debugToolTips > 1)
        qDebug("readStartElement: looking for '%s', currently at: %s/%s",
               name, qPrintable(r.tokenString()), qPrintable(r.name().toString()));
hjk's avatar
hjk committed
118
119
    while (r.tokenType() != QXmlStreamReader::StartElement
            || r.name() != QLatin1String(name))
120
121
122
123
124
125
        switch (r.readNext()) {
        case QXmlStreamReader::EndDocument:
            return false;
        case QXmlStreamReader::NoToken:
        case QXmlStreamReader::Invalid:
            qWarning("'%s'/'%s' encountered while looking for start element '%s'.",
hjk's avatar
hjk committed
126
127
                    qPrintable(r.tokenString()),
                    qPrintable(r.name().toString()), name);
128
129
130
131
132
133
134
            return false;
        default:
            break;
        }
    return true;
}

hjk's avatar
hjk committed
135
static void debugMode(const QAbstractItemModel *model)
136
137
138
139
140
141
142
{
    QDebug nospace = qDebug().nospace();
    nospace << model << '\n';
    for (int r = 0; r < model->rowCount(); r++)
        nospace << '#' << r << ' ' << model->data(model->index(r, 0)).toString() << '\n';
}

143
144
145
146
147
namespace Debugger {
namespace Internal {

// A convenience struct to pass around all tooltip-relevant editor members
// (TextEditor, Widget, File, etc), constructing from a Core::IEditor.
hjk's avatar
hjk committed
148

149
class DebuggerToolTipEditor
150
{
151
public:
hjk's avatar
hjk committed
152
153
154
    explicit DebuggerToolTipEditor(IEditor *ie = 0);
    bool isValid() const { return textEditor && baseTextEditor && file; }
    operator bool() const { return isValid(); }
155
156
157
158
    QString fileName() const { return file ? file->fileName() : QString(); }

    static DebuggerToolTipEditor currentToolTipEditor();

hjk's avatar
hjk committed
159
160
161
    ITextEditor *textEditor;
    BaseTextEditorWidget *baseTextEditor;
    IFile *file;
162
163
};

hjk's avatar
hjk committed
164
DebuggerToolTipEditor::DebuggerToolTipEditor(IEditor *ie) :
165
    textEditor(0), baseTextEditor(0), file(0)
166
{
167
    if (ie && ie->file() && isEditorDebuggable(ie)) {
hjk's avatar
hjk committed
168
169
        if (ITextEditor *te = qobject_cast<ITextEditor *>(ie)) {
            if (BaseTextEditorWidget *pe = qobject_cast<BaseTextEditorWidget *>(ie->widget())) {
170
                textEditor = te;
171
                baseTextEditor = pe;
172
                file = ie->file();
173
            }
174
175
        }
    }
176
177
}

178
DebuggerToolTipEditor DebuggerToolTipEditor::currentToolTipEditor()
179
{
hjk's avatar
hjk committed
180
    if (IEditor *ie = EditorManager::instance()->currentEditor())
181
182
        return DebuggerToolTipEditor(ie);
    return DebuggerToolTipEditor();
183
184
185
186
187
188
189
190
191
}

/* Helper for building a QStandardItemModel of a tree form (see TreeModelVisitor).
 * The recursion/building is based on the scheme: \code
<row><item1><item2>
    <row><item11><item12></row>
</row>
\endcode */

hjk's avatar
hjk committed
192
193
class StandardItemTreeModelBuilder
{
194
195
196
197
198
public:
    typedef QList<QStandardItem *> StandardItemRow;

    explicit StandardItemTreeModelBuilder(QStandardItemModel *m, Qt::ItemFlags f = Qt::ItemIsSelectable);

hjk's avatar
hjk committed
199
200
201
    void addItem(const QString &);
    void startRow();
    void endRow();
202
203

private:
hjk's avatar
hjk committed
204
    void pushRow();
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

    QStandardItemModel *m_model;
    const Qt::ItemFlags m_flags;
    StandardItemRow m_row;
    QStack<QStandardItem *> m_rowParents;
};

StandardItemTreeModelBuilder::StandardItemTreeModelBuilder(QStandardItemModel *m, Qt::ItemFlags f) :
    m_model(m), m_flags(f)
{
    m_model->removeRows(0, m_model->rowCount());
}

void StandardItemTreeModelBuilder::addItem(const QString &s)
{
    QStandardItem *item = new QStandardItem(s);
    item->setFlags(m_flags);
    m_row.push_back(item);
}

void StandardItemTreeModelBuilder::pushRow()
{
    if (m_rowParents.isEmpty()) {
        m_model->appendRow(m_row);
    } else {
        m_rowParents.top()->appendRow(m_row);
    }
    m_rowParents.push(m_row.front());
    m_row.clear();
}

void StandardItemTreeModelBuilder::startRow()
{
    // Push parent in case rows are nested. This is a Noop for the very first row.
    if (!m_row.isEmpty())
        pushRow();
}

void StandardItemTreeModelBuilder::endRow()
{
    if (!m_row.isEmpty()) // Push row if no child rows have been encountered
        pushRow();
    m_rowParents.pop();
}

/* Helper visitor base class for recursing over a tree model
 * (see StandardItemTreeModelBuilder for the scheme). */
hjk's avatar
hjk committed
252
253
class TreeModelVisitor
{
254
public:
hjk's avatar
hjk committed
255
    virtual void run() { run(QModelIndex()); }
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

protected:
    TreeModelVisitor(const QAbstractItemModel *model) : m_model(model) {}

    virtual void rowStarted() {}
    virtual void handleItem(const QModelIndex &m) = 0;
    virtual void rowEnded() {}

    const QAbstractItemModel *model() const { return m_model; }

private:
    void run(const QModelIndex &parent);

    const QAbstractItemModel *m_model;
};

void TreeModelVisitor::run(const QModelIndex &parent)
{
    const int columnCount = m_model->columnCount(parent);
    const int rowCount = m_model->rowCount(parent);
    for (int r = 0; r < rowCount; r++) {
        rowStarted();
        QModelIndex left;
        for (int c = 0; c < columnCount; c++) {
            const QModelIndex index = m_model->index(r, c, parent);
            handleItem(index);
            if (!c)
                left = index;
        }
        if (left.isValid())
            run(left);
        rowEnded();
    }
}

// Visitor writing out a tree model in XML format.
hjk's avatar
hjk committed
292
293
class XmlWriterTreeModelVisitor : public TreeModelVisitor
{
294
public:
hjk's avatar
hjk committed
295
    XmlWriterTreeModelVisitor(const QAbstractItemModel *model, QXmlStreamWriter &w);
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

    virtual void run();

protected:
    virtual void rowStarted() { m_writer.writeStartElement(QLatin1String(modelRowElementC)); }
    virtual void handleItem(const QModelIndex &m);
    virtual void rowEnded() { m_writer.writeEndElement(); }

private:
    const QString m_modelItemElement;
    QXmlStreamWriter &m_writer;
};

XmlWriterTreeModelVisitor::XmlWriterTreeModelVisitor(const QAbstractItemModel *model, QXmlStreamWriter &w) :
    TreeModelVisitor(model), m_modelItemElement(QLatin1String(modelItemElementC)), m_writer(w)
{
}

void XmlWriterTreeModelVisitor::run()
{
    m_writer.writeStartElement(QLatin1String(modelElementC));
    const int columnCount = model()->columnCount();
    m_writer.writeAttribute(QLatin1String(modelColumnCountAttributeC), QString::number(columnCount));
   TreeModelVisitor::run();
    m_writer.writeEndElement();
}

void XmlWriterTreeModelVisitor::handleItem(const QModelIndex &m)
{
    const QString value = m.data(Qt::DisplayRole).toString();
    if (value.isEmpty()) {
        m_writer.writeEmptyElement(m_modelItemElement);
    } else {
        m_writer.writeTextElement(m_modelItemElement, value);
    }
}

333
// TreeModelVisitor for debugging/copying models
hjk's avatar
hjk committed
334
335
class DumpTreeModelVisitor : public TreeModelVisitor
{
336
public:
337
338
339
340
341
342
    enum Mode
    {
        DebugMode,      // For debugging, "|'data'|"
        ClipboardMode   // Tab-delimited "\tdata" for clipboard (see stack window)
    };
    explicit DumpTreeModelVisitor(const QAbstractItemModel *model, Mode m, QTextStream &s);
343
344
345
346
347
348
349

protected:
    virtual void rowStarted();
    virtual void handleItem(const QModelIndex &m);
    virtual void rowEnded();

private:
350
351
    const Mode m_mode;

352
353
    QTextStream &m_stream;
    int m_level;
354
    unsigned m_itemsInRow;
355
356
};

357
358
DumpTreeModelVisitor::DumpTreeModelVisitor(const QAbstractItemModel *model, Mode m, QTextStream &s) :
    TreeModelVisitor(model), m_mode(m), m_stream(s), m_level(0), m_itemsInRow(0)
359
{
360
361
    if (m_mode == DebugMode)
        m_stream << model->metaObject()->className() << '/' << model->objectName();
362
363
364
365
366
}

void DumpTreeModelVisitor::rowStarted()
{
    m_level++;
367
368
369
370
371
372
373
374
375
376
377
378
    if (m_itemsInRow) { // Nested row.
        m_stream << '\n';
        m_itemsInRow = 0;
    }
    switch (m_mode) {
    case DebugMode:
        m_stream << QString(2 * m_level, QLatin1Char(' '));
        break;
    case ClipboardMode:
        m_stream << QString(m_level, QLatin1Char('\t'));
        break;
    }
379
380
381
382
}

void DumpTreeModelVisitor::handleItem(const QModelIndex &m)
{
383
384
385
386
387
388
389
390
391
392
393
394
395
396
    const QString data = m.data().toString();
    switch (m_mode) {
    case DebugMode:
        if (m.column())
            m_stream << '|';
        m_stream << '\'' << data << '\'';
        break;
    case ClipboardMode:
        if (m.column())
            m_stream << '\t';
        m_stream << data;
        break;
    }
    m_itemsInRow++;
397
398
399
400
}

void DumpTreeModelVisitor::rowEnded()
{
401
402
403
404
    if (m_itemsInRow) {
        m_stream << '\n';
        m_itemsInRow = 0;
    }
405
406
407
408
409
410
    m_level--;
}

} // namespace Internal
} // namespace Debugger

hjk's avatar
hjk committed
411
412
/*
static QDebug operator<<(QDebug d, const QAbstractItemModel &model)
413
414
415
{
    QString s;
    QTextStream str(&s);
416
    Debugger::Internal::DumpTreeModelVisitor v(&model, Debugger::Internal::DumpTreeModelVisitor::DebugMode, str);
417
418
419
420
    v.run();
    qDebug().nospace() << s;
    return d;
}
hjk's avatar
hjk committed
421
*/
422
423
424
425
426

namespace Debugger {
namespace Internal {

// Visitor building a QStandardItem from a tree model (copy).
hjk's avatar
hjk committed
427
428
class TreeModelCopyVisitor : public TreeModelVisitor
{
429
public:
hjk's avatar
hjk committed
430
431
432
    TreeModelCopyVisitor(const QAbstractItemModel *source, QStandardItemModel *target) :
        TreeModelVisitor(source), m_builder(target)
    {}
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455

protected:
    virtual void rowStarted() { m_builder.startRow(); }
    virtual void handleItem(const QModelIndex &m) { m_builder.addItem(m.data().toString()); }
    virtual void rowEnded() { m_builder.endRow(); }

private:
    StandardItemTreeModelBuilder m_builder;
};

/*!
    \class PinnableToolTipWidget

    A pinnable tooltip that goes from State 'Unpinned' (button showing
    'Pin') to 'Pinned' (button showing 'Close').
    It consists of a title toolbar and a vertical main layout.
*/

PinnableToolTipWidget::PinnableToolTipWidget(QWidget *parent) :
    QWidget(parent),
    m_pinState(Unpinned),
    m_mainVBoxLayout(new QVBoxLayout),
    m_toolBar(new QToolBar),
456
    m_toolButton(new QToolButton)
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
491
492
{
    m_mainVBoxLayout->setSizeConstraint(QLayout::SetFixedSize);
    m_mainVBoxLayout->setContentsMargins(0, 0, 0, 0);

    const QIcon pinIcon(QLatin1String(":/debugger/images/pin.xpm"));
    const QList<QSize> pinIconSizes = pinIcon.availableSizes();

    m_toolButton->setIcon(pinIcon);
    connect(m_toolButton, SIGNAL(clicked()), this, SLOT(toolButtonClicked()));

    m_toolBar->setProperty("_q_custom_style_disabled", QVariant(true));
    if (!pinIconSizes.isEmpty())
        m_toolBar->setIconSize(pinIconSizes.front());
    m_toolBar->addWidget(m_toolButton);

    m_mainVBoxLayout->addWidget(m_toolBar);

    setLayout(m_mainVBoxLayout);
}

void PinnableToolTipWidget::addWidget(QWidget *w)
{
    w->setFocusPolicy(Qt::NoFocus);
    m_mainVBoxLayout->addWidget(w);
}

void PinnableToolTipWidget::addToolBarWidget(QWidget *w)
{
    m_toolBar->addWidget(w);
}

void PinnableToolTipWidget::pin()
{
    if (m_pinState == Unpinned) {
        m_pinState = Pinned;
        m_toolButton->setIcon(style()->standardIcon(QStyle::SP_DockWidgetCloseButton));
493
494
        doPin();
        emit pinned();
495
496
497
    }
}

498
499
500
501
void PinnableToolTipWidget::doPin()
{
}

502
503
504
505
506
507
508
509
510
511
512
513
void PinnableToolTipWidget::toolButtonClicked()
{
    switch (m_pinState) {
    case Unpinned:
        pin();
        break;
    case Pinned:
        close();
        break;
    }
}

514
515
516
517
518
519
520
521
/* A Label that emits a signal when the user drags for moving the parent
 * widget around. */
class DraggableLabel : public QLabel
{
    Q_OBJECT
public:
    explicit DraggableLabel(QWidget *parent = 0);

522
523
524
    bool isActive() const { return m_active; }
    void setActive(bool v) { m_active = v; }

525
526
527
528
529
530
531
532
533
534
signals:
    void dragged(const QPoint &d);

protected:
    virtual void mousePressEvent(QMouseEvent * event);
    virtual void mouseReleaseEvent(QMouseEvent * event);
    virtual void mouseMoveEvent(QMouseEvent * event);

private:
    QPoint m_moveStartPos;
535
    bool m_active;
536
537
538
};

DraggableLabel::DraggableLabel(QWidget *parent) :
539
    QLabel(parent), m_moveStartPos(-1, -1), m_active(false)
540
541
542
543
544
{
}

void DraggableLabel::mousePressEvent(QMouseEvent * event)
{
545
    if (m_active && event->button() ==  Qt::LeftButton) {
546
547
548
549
550
551
552
553
        m_moveStartPos = event->globalPos();
        event->accept();
    }
    QLabel::mousePressEvent(event);
}

void DraggableLabel::mouseReleaseEvent(QMouseEvent * event)
{
554
    if (m_active && event->button() ==  Qt::LeftButton)
555
556
557
558
559
560
        m_moveStartPos = QPoint(-1, -1);
    QLabel::mouseReleaseEvent(event);
}

void DraggableLabel::mouseMoveEvent(QMouseEvent * event)
{
561
    if (m_active && (event->buttons() & Qt::LeftButton)) {
562
563
564
565
566
567
568
        if (m_moveStartPos != QPoint(-1, -1)) {
            const QPoint newPos = event->globalPos();
            emit dragged(event->globalPos() - m_moveStartPos);
            m_moveStartPos = newPos;
        }
        event->accept();
    }
569
    QLabel::mouseMoveEvent(event);
570
571
}

572
573
574
575
576
577
578
579
580
581
582
583
/*!
    \class DebuggerToolTipContext

    File name and position where the tooltip is anchored. Redundant position/line column
    information is used to detect if the underlying file has been changed
    on restoring.
*/

DebuggerToolTipContext::DebuggerToolTipContext() : position(0), line(0), column(0)
{
}

hjk's avatar
hjk committed
584
DebuggerToolTipContext DebuggerToolTipContext::fromEditor(IEditor *ie, int pos)
585
586
{
    DebuggerToolTipContext rc;
hjk's avatar
hjk committed
587
588
    if (const IFile *file = ie->file()) {
        if (const ITextEditor *te = qobject_cast<const ITextEditor *>(ie)) {
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
            rc.fileName = file->fileName();
            rc.position = pos;
            te->convertPosition(pos, &rc.line, &rc.column);
        }
    }
    return rc;
}

QDebug operator<<(QDebug d, const DebuggerToolTipContext &c)
{
    QDebug nsp = d.nospace();
    nsp << c.fileName << '@' << c.line << ',' << c.column << " (" << c.position << ')';
    if (!c.function.isEmpty())
        nsp << ' ' << c.function << "()";
    return d;
}

/*!
    \class AbstractDebuggerToolTipWidget

    Base class for a tool tip widget associated with file name
    and position with functionality to
    \list
    \o Save and restore values (session data) in XML form
    \o Acquire and release the engine: When the debugger stops at a file, all
       matching tooltips acquire the engine, that is, display the engine data.
       When continuing or switching away from the frame, the tooltips release the
       engine, that is, store the data internally and keep displaying them
       marked as 'previous'.
    \endlist
    When restoring the data from a session, all tooltips start in 'released' mode.

    Stored tooltips expire after toolTipsExpiryDays while loading to prevent
    them accumulating.

    In addition, if the stored line number diverges too much from the current line
    number in positionShow(), the tooltip is also closed/discarded.
626
627
628
629
630
631
632

    The widget is that is first shown by the TextEditor's tooltip
    class and typically closed by it unless the user pins it.
    In that case, it is removed from the tip's layout, added to the DebuggerToolTipManager's
    list of pinned tooltips and re-shown as a global tooltip widget.
    As the debugger stop and continues, it shows the debugger values or a copy
    of them. On closing or session changes, the contents it saved.
633
634
*/

hjk's avatar
hjk committed
635
static QString msgReleasedText() { return AbstractDebuggerToolTipWidget::tr("Previous"); }
636
637
638

AbstractDebuggerToolTipWidget::AbstractDebuggerToolTipWidget(QWidget *parent) :
    PinnableToolTipWidget(parent),
639
    m_titleLabel(new DraggableLabel), m_engineAcquired(false),
640
641
    m_creationDate(QDate::currentDate())
{
642
643
644
645
646
    QToolButton *copyButton = new QToolButton;
    copyButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_COPY)));
    connect(copyButton, SIGNAL(clicked()), this, SLOT(copy()));
    addToolBarWidget(copyButton);

647
    m_titleLabel->setText(msgReleasedText());
648
649
    m_titleLabel->setMinimumWidth(40); // Ensure a draggable area even if text is empty.
    connect(m_titleLabel, SIGNAL(dragged(QPoint)), this, SLOT(slotDragged(QPoint)));
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
    addToolBarWidget(m_titleLabel);
}

bool AbstractDebuggerToolTipWidget::matches(const QString &fileName,
                                            const QString &engineType,
                                            const QString &function) const
{
    if (fileName.isEmpty() || m_context.fileName != fileName)
        return false;
    // Optional.
    if (!engineType.isEmpty() && engineType != m_engineType)
        return false;
    if (function.isEmpty() || m_context.function.isEmpty())
        return true;
    return function == m_context.function;
}

void AbstractDebuggerToolTipWidget::acquireEngine(Debugger::DebuggerEngine *engine)
{
hjk's avatar
hjk committed
669
    QTC_ASSERT(engine, return);
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693


    if (debugToolTips)
        qDebug() << this << " acquiring" << engine << m_engineAcquired;
    if (m_engineAcquired)
        return;
    doAcquireEngine(engine);
    m_engineType = engine->objectName();
    m_engineAcquired = true;
    m_titleLabel->setText(QString());
}

void AbstractDebuggerToolTipWidget::releaseEngine()
{
    // Release engine of same type
    if (!m_engineAcquired)
        return;
    if (debugToolTips)
        qDebug() << "releaseEngine" << this;
    doReleaseEngine();
    m_titleLabel->setText(msgReleasedText());
    m_engineAcquired = false;
}

694
695
696
697
698
699
700
701
702
703
void AbstractDebuggerToolTipWidget::copy()
{
    const QString clipboardText = clipboardContents();
    QClipboard *clipboard = QApplication::clipboard();
#ifdef Q_WS_X11
    clipboard->setText(clipboardText, QClipboard::Selection);
#endif
    clipboard->setText(clipboardText, QClipboard::Clipboard);
}

704
705
706
707
708
709
void AbstractDebuggerToolTipWidget::slotDragged(const QPoint &p)
{
    move(pos() + p);
    m_offset += p;
}

710
bool AbstractDebuggerToolTipWidget::positionShow(const DebuggerToolTipEditor &te)
711
712
713
{
    // Figure out new position of tooltip using the text edit.
    // If the line changed too much, close this tip.
hjk's avatar
hjk committed
714
    QTC_ASSERT(te, return false);
715
    QTextCursor cursor(te.baseTextEditor->document());
716
717
    cursor.setPosition(m_context.position);
    const int line = cursor.blockNumber();
718
    const int column = cursor.columnNumber();
719
720
721
722
723
724
725
    if (qAbs(m_context.line - line) > 2) {
        if (debugToolTips)
            qDebug() << "Closing " << this << " in positionShow() lines "
                     << line << m_context.line;
        close();
        return false;
    }
726
727
728
729
730
731
732
    if (debugToolTipPositioning)
        qDebug() << "positionShow" << this << line << column;

    const QPoint screenPos = te.baseTextEditor->toolTipPosition(cursor) + m_offset;
    const QRect toolTipArea = QRect(screenPos, QSize(sizeHint()));
    const QRect plainTextArea = QRect(te.baseTextEditor->mapToGlobal(QPoint(0, 0)), te.baseTextEditor->size());
    const bool visible = plainTextArea.contains(toolTipArea);
733
    if (debugToolTips)
734
        qDebug() << "DebuggerToolTipWidget::positionShow() " << this << m_context
735
                 << " line: " << line << " plainTextPos " << toolTipArea
736
                 << " offset: " << m_offset
737
                 << " Area: " << plainTextArea << " Screen pos: "
738
                 << screenPos << te.baseTextEditor << " visible=" << visible;
739

740
741
742
743
744
745
746
747
748
749
    if (!visible) {
        hide();
        return false;
    }

    move(screenPos);
    show();
    return true;
}

750
751
752
753
754
void AbstractDebuggerToolTipWidget::doPin()
{
    if (parentWidget()) {
        // We are currently within a text editor tooltip:
        // Rip out of parent widget and re-show as a tooltip
hjk's avatar
hjk committed
755
        WidgetContent::pinToolTip(this);
756
757
758
759
760
761
762
    } else {
        // We have just be restored from session data.
        setWindowFlags(Qt::ToolTip);
    }
    m_titleLabel->setActive(true); // User can now drag
}

763
 // Parse a 'yyyyMMdd' date
hjk's avatar
hjk committed
764
static QDate dateFromString(const QString &date)
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
{
    return date.size() == 8 ?
        QDate(date.left(4).toInt(), date.mid(4, 2).toInt(), date.mid(6, 2).toInt()) :
        QDate();
}

AbstractDebuggerToolTipWidget *AbstractDebuggerToolTipWidget::loadSessionData(QXmlStreamReader &r)
{
    if (debugToolTips)
        qDebug() << ">DebuggerToolTipWidget::loadSessionData" << r.tokenString() << r.name();
    AbstractDebuggerToolTipWidget *rc = AbstractDebuggerToolTipWidget::loadSessionDataI(r);
    if (debugToolTips)
        qDebug() << "<DebuggerToolTipWidget::loadSessionData" << r.tokenString() << r.name() << " returns  " << rc;
    return rc;
}

AbstractDebuggerToolTipWidget *AbstractDebuggerToolTipWidget::loadSessionDataI(QXmlStreamReader &r)
{
    if (!readStartElement(r, toolTipElementC))
        return 0;
    const QXmlStreamAttributes attributes = r.attributes();
    DebuggerToolTipContext context;
    context.fileName = attributes.value(QLatin1String(fileNameAttributeC)).toString();
    context.position = attributes.value(QLatin1String(textPositionAttributeC)).toString().toInt();
    context.line = attributes.value(QLatin1String(textLineAttributeC)).toString().toInt();
    context.column = attributes.value(QLatin1String(textColumnAttributeC)).toString().toInt();
    context.function = attributes.value(QLatin1String(functionAttributeC)).toString();
792
793
794
795
796
797
798
799
    QPoint offset;
    const QString offsetXAttribute = QLatin1String(offsetXAttributeC);
    const QString offsetYAttribute = QLatin1String(offsetYAttributeC);
    if (attributes.hasAttribute(offsetXAttribute))
        offset.setX(attributes.value(offsetXAttribute).toString().toInt());
    if (attributes.hasAttribute(offsetYAttribute))
        offset.setY(attributes.value(offsetYAttribute).toString().toInt());

800
801
802
803
804
805
806
807
808
809
    const QString className = attributes.value(QLatin1String(toolTipClassAttributeC)).toString();
    const QString engineType = attributes.value(QLatin1String(engineTypeAttributeC)).toString();
    const QDate creationDate = dateFromString(attributes.value(QLatin1String(dateAttributeC)).toString());
    if (!creationDate.isValid() || creationDate.daysTo(QDate::currentDate()) >  toolTipsExpiryDays) {
        if (debugToolTips)
            qDebug() << "Expiring tooltip " << context.fileName << '@' << context.position << " from " << creationDate;
        r.readElementText(QXmlStreamReader::SkipChildElements); // Skip
        return 0;
    }
    if (debugToolTips)
810
        qDebug() << "Creating tooltip " << context <<  " from " << creationDate << offset;
811
812
813
814
815
    AbstractDebuggerToolTipWidget *rc = 0;
    if (className == "Debugger::Internal::DebuggerTreeViewToolTipWidget")
        rc = new DebuggerTreeViewToolTipWidget;
    if (rc) {
        rc->setContext(context);
816
        rc->setAttribute(Qt::WA_DeleteOnClose);
817
818
819
        rc->setEngineType(engineType);
        rc->doLoadSessionData(r);
        rc->setCreationDate(creationDate);
820
821
        if (!offset.isNull())
            rc->setOffset(offset);
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
        rc->pin();
    } else {
        qWarning("Unable to create debugger tool tip widget of class %s", qPrintable(className));
        r.readElementText(QXmlStreamReader::SkipChildElements); // Skip
    }
    return rc;
}

void AbstractDebuggerToolTipWidget::saveSessionData(QXmlStreamWriter &w) const
{
    w.writeStartElement(QLatin1String(toolTipElementC));
    QXmlStreamAttributes attributes;
    attributes.append(QLatin1String(toolTipClassAttributeC), QString::fromAscii(metaObject()->className()));
    attributes.append(QLatin1String(fileNameAttributeC), m_context.fileName);
    if (!m_context.function.isEmpty())
        attributes.append(QLatin1String(functionAttributeC), m_context.function);
    attributes.append(QLatin1String(textPositionAttributeC), QString::number(m_context.position));
    attributes.append(QLatin1String(textLineAttributeC), QString::number(m_context.line));
    attributes.append(QLatin1String(textColumnAttributeC), QString::number(m_context.column));
    attributes.append(QLatin1String(dateAttributeC), m_creationDate.toString(QLatin1String("yyyyMMdd")));
842
843
844
845
    if (m_offset.x())
        attributes.append(QLatin1String(offsetXAttributeC), QString::number(m_offset.x()));
    if (m_offset.y())
        attributes.append(QLatin1String(offsetYAttributeC), QString::number(m_offset.y()));
846
847
848
849
850
851
852
853
    if (!m_engineType.isEmpty())
        attributes.append(QLatin1String(engineTypeAttributeC), m_engineType);
    w.writeAttributes(attributes);
    doSaveSessionData(w);
    w.writeEndElement();
}

// Model for tooltips filtering a local variable using the locals model,
854
// taking the expression. Suppress the tooltip data.
855
856
857
858
859
860
class DebuggerToolTipExpressionFilterModel : public QSortFilterProxyModel
{
public:
    explicit DebuggerToolTipExpressionFilterModel(QAbstractItemModel *model, const QString &exp, QObject *parent = 0);
    virtual bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;

861
862
    virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;

863
864
865
866
867
868
869
870
871
872
873
874
private:
    const QString m_expression;
};

DebuggerToolTipExpressionFilterModel::DebuggerToolTipExpressionFilterModel(QAbstractItemModel *model,
                                                                           const QString &exp,
                                                                           QObject *parent) :
    QSortFilterProxyModel(parent), m_expression(exp)
{
    setSourceModel(model);
}

875
876
877
878
879
880
QVariant DebuggerToolTipExpressionFilterModel::data(const QModelIndex &index, int role) const
{
    return role != Qt::ToolTipRole ?
        QSortFilterProxyModel::data(index, role) : QVariant();
}

881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
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
930
931
932
933
934
935
936
937
938
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
bool DebuggerToolTipExpressionFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
    // Match on expression for top level, else pass through.
    if (sourceParent.isValid())
        return true;
    const QModelIndex expIndex = sourceModel()->index(sourceRow, 0, sourceParent);
    return expIndex.data().toString() == m_expression;
}

/*!
    \class DebuggerToolTipTreeView

    A treeview that adapts its size to the model contents (also while expanding)
    to be used within DebuggerTreeViewToolTipWidget.

*/

DebuggerToolTipTreeView::DebuggerToolTipTreeView(QWidget *parent) :
    QTreeView(parent)
{
    setHeaderHidden(true);

    setUniformRowHeights(true);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    connect(this, SIGNAL(collapsed(QModelIndex)), this, SLOT(computeSize()),
        Qt::QueuedConnection);
    connect(this, SIGNAL(expanded(QModelIndex)), this, SLOT(computeSize()),
        Qt::QueuedConnection);
}

QAbstractItemModel *DebuggerToolTipTreeView::swapModel(QAbstractItemModel *newModel)
{
    QAbstractItemModel *previousModel = model();
    if (previousModel != newModel) {
        if (previousModel)
            previousModel->disconnect(SIGNAL(rowsInserted(QModelIndex,int,int)), this);
        setModel(newModel);
        connect(newModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
                this, SLOT(computeSize()), Qt::QueuedConnection);
        computeSize();
    }
    return previousModel;
}

int DebuggerToolTipTreeView::computeHeight(const QModelIndex &index) const
{
    int s = rowHeight(index);
    const int rowCount = model()->rowCount(index);
    for (int i = 0; i < rowCount; ++i)
        s += computeHeight(model()->index(i, 0, index));
    return s;
}

void DebuggerToolTipTreeView::computeSize()
{
    int columns = 30; // Decoration
    int rows = 0;
    bool rootDecorated = false;

    if (model()) {
        const int columnCount = model()->columnCount();
        rootDecorated = model()->rowCount() > 0;
        if (rootDecorated)
        for (int i = 0; i < columnCount; ++i) {
            resizeColumnToContents(i);
            columns += sizeHintForColumn(i);
        }
        if (columns < 100)
            columns = 100; // Prevent toolbar from shrinking when displaying 'Previous'
        rows += computeHeight(QModelIndex());

        // Fit tooltip to screen, showing/hiding scrollbars as needed.
        // Add a bit of space to account for tooltip border, and not
        // touch the border of the screen.
        QPoint pos(x(), y());
        QRect desktopRect = QApplication::desktop()->availableGeometry(pos);
        const int maxWidth = desktopRect.right() - pos.x() - 5 - 5;
        const int maxHeight = desktopRect.bottom() - pos.y() - 5 - 5;

        if (columns > maxWidth)
            rows += horizontalScrollBar()->height();

        if (rows > maxHeight) {
            setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
            rows = maxHeight;
            columns += verticalScrollBar()->width();
        } else {
            setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        }

        if (columns > maxWidth) {
            setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
            columns = maxWidth;
        } else {
            setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        }
    }

    m_size = QSize(columns + 5, rows + 5);
    setMinimumSize(m_size);
    setMaximumSize(m_size);
    setRootIsDecorated(rootDecorated);
}

/*!
    \class DebuggerTreeViewToolTipWidget

    Tool tip widget for tree views with functionality to save/restore tree
    model contents to XML.
    With the engine acquired, it sets a filter model (by expression) on
    one of the engine's models (debuggerModel).
    On release, it serializes and restores the data to a QStandardItemModel
    (defaultModel) and displays that.

*/

DebuggerTreeViewToolTipWidget::DebuggerTreeViewToolTipWidget(QWidget *parent) :
    AbstractDebuggerToolTipWidget(parent),
    m_debuggerModel(TooltipsWatch),
    m_treeView(new DebuggerToolTipTreeView),
    m_defaultModel(new QStandardItemModel(this))
{
    addWidget(m_treeView);
}

void DebuggerTreeViewToolTipWidget::doAcquireEngine(Debugger::DebuggerEngine *engine)
{
    // Create a filter model on the debugger's model and switch to it.
    QAbstractItemModel *model = 0;
    switch (m_debuggerModel) {
    case LocalsWatch:
        model = engine->localsModel();
        break;
    case WatchersWatch:
        model = engine->watchersModel();
        break;
    case TooltipsWatch:
        model = engine->toolTipsModel();
        break;
    }
hjk's avatar
hjk committed
1023
    QTC_ASSERT(model, return);
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
    DebuggerToolTipExpressionFilterModel *filterModel =
            new DebuggerToolTipExpressionFilterModel(model, m_expression);
    m_treeView->swapModel(filterModel);
}

void DebuggerTreeViewToolTipWidget::doReleaseEngine()
{
    // Save data to stream and restore to the  m_defaultModel (QStandardItemModel)
    m_defaultModel->removeRows(0, m_defaultModel->rowCount());
    if (const QAbstractItemModel *model = m_treeView->model()) {
        TreeModelCopyVisitor v(model, m_defaultModel);
        v.run();
    }
    delete m_treeView->swapModel(m_defaultModel);
}

void DebuggerTreeViewToolTipWidget::restoreTreeModel(QXmlStreamReader &r, QStandardItemModel *m)
{
    StandardItemTreeModelBuilder builder(m);
    int columnCount = 1;
    bool withinModel = true;
    while (withinModel && !r.atEnd()) {
        const QXmlStreamReader::TokenType token = r.readNext();
        switch (token) {
        case QXmlStreamReader::StartElement: {
            const QStringRef element = r.name();
            // Root model element with column count.
            if (element == QLatin1String(modelElementC)) {
                if (const int cc = r.attributes().value(QLatin1String(modelColumnCountAttributeC)).toString().toInt())
                    columnCount = cc;
                m->setColumnCount(columnCount);
            } else if (element == QLatin1String(modelRowElementC)) {
                builder.startRow();
            } else if (element == QLatin1String(modelItemElementC)) {
                builder.addItem(r.readElementText());
            }
        }
            break; // StartElement
        case QXmlStreamReader::EndElement: {
            const QStringRef element = r.name();
            // Row closing: pop off parent.
            if (element == QLatin1String(modelRowElementC)) {
                builder.endRow();
            } else if (element == QLatin1String(modelElementC)) {
                withinModel = false;
            }
        }
            break; // EndElement
        default:
            break;
        } // switch
    } // while
}

void DebuggerTreeViewToolTipWidget::doSaveSessionData(QXmlStreamWriter &w) const
{
    w.writeStartElement(QLatin1String(treeElementC));
    QXmlStreamAttributes attributes;
    attributes.append(QLatin1String(treeModelAttributeC), QString::number(m_debuggerModel));
    attributes.append(QLatin1String(treeExpressionAttributeC), m_expression);
    w.writeAttributes(attributes);
    if (QAbstractItemModel *model = m_treeView->model()) {
        XmlWriterTreeModelVisitor v(model, w);
        v.run();
    }
    w.writeEndElement();
}

void DebuggerTreeViewToolTipWidget::doLoadSessionData(QXmlStreamReader &r)
{
    if (!readStartElement(r, treeElementC))
        return;
    // Restore data to default model and show that.
    const QXmlStreamAttributes attributes = r.attributes();
    m_debuggerModel = attributes.value(QLatin1String(treeModelAttributeC)).toString().toInt();
    m_expression = attributes.value(QLatin1String(treeExpressionAttributeC)).toString();
    if (debugToolTips)
        qDebug() << "DebuggerTreeViewToolTipWidget::doLoadSessionData() " << m_debuggerModel << m_expression;
    setObjectName(QLatin1String("DebuggerTreeViewToolTipWidget: ") + m_expression);
    restoreTreeModel(r, m_defaultModel);
    r.readNext(); // Skip </tree>
    m_treeView->swapModel(m_defaultModel);
}

1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
QString DebuggerTreeViewToolTipWidget::treeModelClipboardContents(const QAbstractItemModel *m)
{
    QString rc;
    QTextStream str(&rc);
    DumpTreeModelVisitor v(m, DumpTreeModelVisitor::ClipboardMode, str);
    v.run();
    return rc;
}

QString DebuggerTreeViewToolTipWidget::clipboardContents() const
{
    if (const QAbstractItemModel *model = m_treeView->model())
        return DebuggerTreeViewToolTipWidget::treeModelClipboardContents(model);
    return QString();
}

1124
1125
1126
/*!
    \class DebuggerToolTipManager

1127
    Manages the pinned tooltip widgets, listens on editor scroll and main window move
1128
1129
1130
1131
1132
    events and takes care of repositioning the tooltips.

    Listens to editor change and mode change. In debug mode, if there tooltips
    for the current editor (by file name), position and show them.

1133
1134
1135
    In addition, listens on state change and stack frame completed signals
    of the engine. If a stack frame is completed, have all matching tooltips
    (by file name and function) acquire the engine, others release.
1136
1137
1138
1139
1140
*/

DebuggerToolTipManager *DebuggerToolTipManager::m_instance = 0;

DebuggerToolTipManager::DebuggerToolTipManager(QObject *parent) :
1141
    QObject(parent), m_debugModeActive(false),
1142
    m_lastToolTipPoint(-1, -1), m_lastToolTipEditor(0)
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
{
    DebuggerToolTipManager::m_instance = this;
}

DebuggerToolTipManager::~DebuggerToolTipManager()
{
    DebuggerToolTipManager::m_instance = 0;
}

void DebuggerToolTipManager::registerEngine(DebuggerEngine *engine)
{
    connect(engine, SIGNAL(stateChanged(Debugger::DebuggerState)),
            this, SLOT(slotDebuggerStateChanged(Debugger::DebuggerState)));
    connect(engine, SIGNAL(stackFrameCompleted()), this, SLOT(slotStackFrameCompleted()));
}

hjk's avatar
hjk committed
1159
void DebuggerToolTipManager::showToolTip(const QPoint &p, IEditor *editor,
1160
                                         AbstractDebuggerToolTipWidget *toolTipWidget)
1161
{
1162
1163
1164
    QWidget *widget = editor->widget();
    if (debugToolTipPositioning)
        qDebug() << "DebuggerToolTipManager::showToolTip" << p << " Mouse at " << QCursor::pos();
hjk's avatar
hjk committed
1165
1166
    const WidgetContent widgetContent(toolTipWidget, true);
    ToolTip::instance()->show(p, widgetContent, widget);
1167
    registerToolTip(toolTipWidget);
1168
1169
}

1170
void DebuggerToolTipManager::registerToolTip(AbstractDebuggerToolTipWidget *toolTipWidget)
1171
{
hjk's avatar
hjk committed
1172
    QTC_ASSERT(toolTipWidget->context().isValid(), return);
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
    switch (toolTipWidget->pinState()) {
    case PinnableToolTipWidget::Pinned:
        m_pinnedTooltips.push_back(toolTipWidget);
        break;
    case PinnableToolTipWidget::Unpinned:
        // Catch the widget once it is pinned.
        connect(toolTipWidget, SIGNAL(pinned()), this, SLOT(slotPinnedFirstTime()));
        break;
    }
}

void DebuggerToolTipManager::slotPinnedFirstTime()
{
    if (AbstractDebuggerToolTipWidget *tw = qobject_cast<AbstractDebuggerToolTipWidget *>(sender()))
        m_pinnedTooltips.push_back(tw);
1188
1189
1190
1191
}

DebuggerToolTipManager::DebuggerToolTipWidgetList &DebuggerToolTipManager::purgeClosedToolTips()
{
1192
1193
    if (!m_pinnedTooltips.isEmpty()) {
        for (DebuggerToolTipWidgetList::iterator it = m_pinnedTooltips.begin(); it != m_pinnedTooltips.end() ; ) {
1194
            if (it->isNull()) {
1195
                it = m_pinnedTooltips.erase(it);
1196
1197
1198
1199
1200
            } else {
                ++it;
            }
        }
    }
1201
    return m_pinnedTooltips;
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
}

void DebuggerToolTipManager::moveToolTipsBy(const QPoint &distance)
{
    foreach (const QPointer<AbstractDebuggerToolTipWidget> &tw, purgeClosedToolTips())
        if (tw->isVisible())
            tw->move (tw->pos() + distance);
}

bool DebuggerToolTipManager::eventFilter(QObject *, QEvent *e)
{
    // Move along with parent (toplevel)
1214
    if (e->type() == QEvent::Move && hasToolTips()) {
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
        const QMoveEvent *me = static_cast<const QMoveEvent *>(e);
        moveToolTipsBy(me->pos() - me->oldPos());
    }
    return false;
}

void DebuggerToolTipManager::sessionAboutToChange()
{
    closeAllToolTips();
}

void DebuggerToolTipManager::loadSessionData()
{
    const QString data = debuggerCore()->sessionValue(QLatin1String(sessionSettingsKeyC)).toString();
    if (data.isEmpty())
        return;
    QXmlStreamReader r(data);
    r.readNextStartElement();
    if (r.tokenType() != QXmlStreamReader::StartElement || r.name() != QLatin1String(sessionDocumentC))
        return;
    const double version = r.attributes().value(QLatin1String(sessionVersionAttributeC)).toString().toDouble();
    while (!r.atEnd())
        if (AbstractDebuggerToolTipWidget *tw = AbstractDebuggerToolTipWidget::loadSessionData(r))
1238
            registerToolTip(tw);
1239
1240

    if (debugToolTips)
1241
        qDebug() << "DebuggerToolTipManager::loadSessionData version " << version << " restored " << m_pinnedTooltips.size();
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
    slotUpdateVisibleToolTips();
}

void DebuggerToolTipManager::saveSessionData()
{
    QString data;
    if (!purgeClosedToolTips().isEmpty()) {
        QXmlStreamWriter w(&data);
        w.writeStartDocument();
        w.writeStartElement(QLatin1String(sessionDocumentC));
        w.writeAttribute(QLatin1String(sessionVersionAttributeC), QLatin1String("1.0"));
1253
        foreach (const QPointer<AbstractDebuggerToolTipWidget> &tw, m_pinnedTooltips)
1254
1255
1256
1257
            tw->saveSessionData(w);
        w.writeEndDocument();
    }
    if (debugToolTips)
1258
        qDebug() << "DebuggerToolTipManager::saveSessionData" << m_pinnedTooltips.size() << data ;
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
    debuggerCore()->setSessionValue(QLatin1String(sessionSettingsKeyC), QVariant(data));
}

void DebuggerToolTipManager::closeAllToolTips()
{
    if (debugToolTips)
        qDebug() << "DebuggerToolTipManager::closeAllToolTips";

    foreach (const QPointer<AbstractDebuggerToolTipWidget> &tw, purgeClosedToolTips())
        tw->close();
1269
    m_pinnedTooltips.clear();
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
}

void DebuggerToolTipManager::hide()
{
    foreach (const QPointer<AbstractDebuggerToolTipWidget> &tw, purgeClosedToolTips())
        tw->hide();
}

void DebuggerToolTipManager::slotUpdateVisibleToolTips()
{
    if (purgeClosedToolTips().isEmpty())
        return;
    if (!m_debugModeActive) {
        hide();
        return;
    }

1287
    DebuggerToolTipEditor toolTipEditor = DebuggerToolTipEditor::currentToolTipEditor();
1288
1289

    if (debugToolTips)
1290
        qDebug() << "DebuggerToolTipManager::slotUpdateVisibleToolTips() " << sender();
1291

1292
    if (!toolTipEditor.isValid() || toolTipEditor.fileName().isEmpty()) {
1293
1294
1295
1296
1297
        hide();
        return;
    }

    // Reposition and show all tooltips of that file.
1298
    const QString fileName = toolTipEditor.fileName();
1299
    foreach (const QPointer<AbstractDebuggerToolTipWidget> &tw, m_pinnedTooltips) {
1300
        if (tw->fileName() == fileName) {
1301
            tw->positionShow(toolTipEditor);
1302
1303
1304
1305
1306
1307
1308
1309
1310
        } else {
            tw->hide();
        }
    }
}

void DebuggerToolTipManager::slotDebuggerStateChanged(Debugger::DebuggerState state)
{
    const QObject *engine = sender();
hjk's avatar
hjk committed
1311
    QTC_ASSERT(engine, return);
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339

    const QString name = engine->objectName();
    if (debugToolTips)
        qDebug() << "DebuggerToolTipWidget::debuggerStateChanged"
                 << engine << Debugger::DebuggerEngine::stateName(state);

    // Release at earliest possible convenience.
    switch (state) {
    case InferiorRunRequested:
    case DebuggerNotReady:
    case InferiorShutdownRequested:
    case EngineShutdownRequested:
    case DebuggerFinished:
    case EngineShutdownOk:
        foreach (const QPointer<AbstractDebuggerToolTipWidget> &tw, purgeClosedToolTips())
            if (tw->engineType() == name)
                tw->releaseEngine();
        break;
    default:
        break;
    }
}

void DebuggerToolTipManager::slotStackFrameCompleted()
{
    if (purgeClosedToolTips().isEmpty())
        return;
    DebuggerEngine *engine = qobject_cast<DebuggerEngine *>(sender());
hjk's avatar
hjk committed
1340
    QTC_ASSERT(engine, return);
1341
1342
1343
1344
1345

    // Stack frame changed: All tooltips of that file acquire the engine,
    // all others release (arguable, this could be more precise?)
    QString fileName;
    int lineNumber = 0;
hjk's avatar
hjk committed
1346
    // Get the current frame.
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
    const QString engineName = engine->objectName();
    QString function;
    const int index = engine->stackHandler()->currentIndex();
    if (index >= 0) {
        const StackFrame frame = engine->stackHandler()->currentFrame();
        if (frame.usable) {
            fileName = frame.file;
            lineNumber = frame.line;
            function = frame.function;
        }
    }
    if (debugToolTips)
        qDebug("DebuggerToolTipWidget::slotStackFrameCompleted(%s, %s@%d, %s())",
               qPrintable(engineName), qPrintable(fileName), lineNumber,
               qPrintable(function));
    unsigned acquiredCount = 0;
1363
    foreach (const QPointer<AbstractDebuggerToolTipWidget> &tw, m_pinnedTooltips) {
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
        if (tw->matches(fileName, engineName, function)) {
            tw->acquireEngine(engine);
            acquiredCount++;
        } else {
            tw->releaseEngine();
        }
    }
    slotUpdateVisibleToolTips(); // Move out when stepping in same file.
    if (debugToolTips)
        qDebug() << "DebuggerToolTipWidget::slotStackFrameCompleted()"
                 << engineName << fileName << lineNumber << " acquired " << acquiredCount;
}

bool DebuggerToolTipManager::debug()
{
    return debugToolTips;
}

hjk's avatar
hjk committed
1382
void DebuggerToolTipManager::slotEditorOpened(IEditor *e)
1383
1384
{
    // Move tooltip along when scrolled.
1385
    if (DebuggerToolTipEditor toolTipEditor = DebuggerToolTipEditor(e)) {
1386
        connect(toolTipEditor.baseTextEditor->verticalScrollBar(), SIGNAL(valueChanged(int)),
1387
                this, SLOT(slotUpdateVisibleToolTips()));
1388
1389
1390
        connect(toolTipEditor.textEditor,
            SIGNAL(tooltipOverrideRequested(TextEditor::ITextEditor*,QPoint,int,bool*)),
            SLOT(slotTooltipOverrideRequested(TextEditor::ITextEditor*,QPoint,int,bool*)));
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
    }
}

void DebuggerToolTipManager::debugModeEntered()
{
    if (debugToolTips)
        qDebug("DebuggerToolTipManager::debugModeEntered");

    // Hook up all signals in debug mode.
    if (!m_debugModeActive) {
        m_debugModeActive = true;
hjk's avatar
hjk committed
1402
        QWidget *topLevel = ICore::instance()->mainWindow()->topLevelWidget();
1403
        topLevel->installEventFilter(this);
hjk's avatar
hjk committed
1404
        EditorManager *em = EditorManager::instance();
1405
1406
1407
1408
        connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)),
                this, SLOT(slotUpdateVisibleToolTips()));
        connect(em, SIGNAL(editorOpened(Core::IEditor*)),
                this, SLOT(slotEditorOpened(Core::IEditor*)));
hjk's avatar
hjk committed
1409
        foreach (IEditor *e, em->openedEditors())
1410
1411
            slotEditorOpened(e);
        // Position tooltips delayed once all the editor placeholder layouting is done.
1412
        if (!m_pinnedTooltips.isEmpty())
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
            QTimer::singleShot(0, this, SLOT(slotUpdateVisibleToolTips()));
    }
}

void DebuggerToolTipManager::leavingDebugMode()
{
    if (debugToolTips)
            qDebug("DebuggerToolTipManager::leavingDebugMode");

    // Remove all signals in debug mode.
    if (m_debugModeActive) {
        m_debugModeActive = false;
        hide();
hjk's avatar
hjk committed
1426
        if (QWidget *topLevel = ICore::instance()->mainWindow()->topLevelWidget())
1427
            topLevel->removeEventFilter(this);
hjk's avatar
hjk committed
1428
1429
        if (EditorManager *em = EditorManager::instance()) {
            foreach (IEditor *e, em->openedEditors()) {
1430
                if (DebuggerToolTipEditor toolTipEditor = DebuggerToolTipEditor(e)) {
1431
                    toolTipEditor.baseTextEditor->verticalScrollBar()->disconnect(this);
1432
1433
1434
1435
1436
1437
                    toolTipEditor.textEditor->disconnect(this);
                }
            }
            em->disconnect(this);
        }
        m_lastToolTipEditor = 0;
1438
        m_lastToolTipPoint = QPoint(-1, -1);
1439
1440
1441
    }
}

hjk's avatar
hjk committed
1442
void DebuggerToolTipManager::slotTooltipOverrideRequested(ITextEditor *editor,
1443
1444
1445
1446
                                                          const QPoint &point,
                                                          int pos, bool *handled)
{
    QTC_ASSERT(handled, return);
1447
1448
1449
1450
1451
1452
1453
1454

    const int movedDistance = (point - m_lastToolTipPoint).manhattanLength();
    const bool samePosition = m_lastToolTipEditor == editor && movedDistance < 25;
    if (debugToolTipPositioning)
        qDebug() << ">slotTooltipOverrideRequested() " << editor << point
                 << "from " << m_lastToolTipPoint << ") pos: "
                 << pos << *handled
                 << " Same position=" << samePosition << " d=" << movedDistance;
1455
1456
1457

    DebuggerEngine *currentEngine = 0;
    do {
1458
        if (*handled || samePosition)
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
            break; // Avoid flicker.

        DebuggerCore  *core = debuggerCore();
        if (!isEditorDebuggable(editor) || !core->boolSetting(UseToolTipsInMainEditor))
            break;

        currentEngine = core->currentEngine();
        if (!currentEngine || !currentEngine->canDisplayTooltip())
            break;

        const DebuggerToolTipContext context = DebuggerToolTipContext::fromEditor(editor, pos);
        if (context.isValid() && currentEngine->setToolTipExpression(point, editor, context)) {
            *handled = true;
            m_lastToolTipEditor = editor;
1473
            m_lastToolTipPoint = point;
1474
1475
1476
1477
1478
1479
1480
1481
        }

    } while (false);

    // Other tooltip, close all in case mouse never entered the tooltip
    // and no leave was triggered.
    if (!*handled) {
        m_lastToolTipEditor = 0;
1482
        m_lastToolTipPoint = QPoint(-1, -1);
1483
    }
1484
    if (debugToolTipPositioning)
1485
1486
1487
        qDebug() << "<slotTooltipOverrideRequested() " << currentEngine << *handled;
}

1488
1489
1490
1491
1492
QStringList DebuggerToolTipManager::treeWidgetExpressions(const QString &fileName,
                                                          const QString &engineType,
                                                          const QString &function) const
{
    QStringList rc;
1493
    foreach (const QPointer<AbstractDebuggerToolTipWidget> &tw, m_pinnedTooltips)
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
        if (!tw.isNull() && tw->matches(fileName, engineType, function))
            if (const DebuggerTreeViewToolTipWidget *ttw = qobject_cast<const DebuggerTreeViewToolTipWidget *>(tw.data()))
                rc.push_back(ttw->expression());
    if (debugToolTips)
        qDebug() << "DebuggerToolTipManager::treeWidgetExpressions"
                 << fileName << engineType << function << rc;
    return rc;
}

} // namespace Internal
} // namespace Debugger
1505
1506

#include "debuggertooltipmanager.moc"