callgrindvisualisation.cpp 14.2 KB
Newer Older
Mike McQuaid's avatar
Mike McQuaid committed
1
2
3
4
/**************************************************************************
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
Mike McQuaid's avatar
Mike McQuaid committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
Mike McQuaid's avatar
Mike McQuaid committed
8
9
10
11
**
**
** GNU Lesser General Public License Usage
**
Tobias Hunger's avatar
Tobias Hunger committed
12
13
14
15
16
17
** 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.
Mike McQuaid's avatar
Mike McQuaid committed
18
19
**
** In addition, as a special exception, Nokia gives you certain additional
Tobias Hunger's avatar
Tobias Hunger committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
Mike McQuaid's avatar
Mike McQuaid committed
21
22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
Tobias Hunger's avatar
Tobias Hunger committed
23
24
25
26
27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
Mike McQuaid's avatar
Mike McQuaid committed
28
** If you have questions regarding the use of this file, please contact
29
** Nokia at qt-info@nokia.com.
Mike McQuaid's avatar
Mike McQuaid committed
30
31
32
33
34
35
36
37
38
39
40
41
42
**
**************************************************************************/

#include "callgrindvisualisation.h"

#include "callgrindhelper.h"

#include <valgrind/callgrind/callgrindabstractmodel.h>
#include <valgrind/callgrind/callgrinddatamodel.h>
#include <valgrind/callgrind/callgrindfunction.h>
#include <valgrind/callgrind/callgrindproxymodel.h>
#include <utils/qtcassert.h>

43
44
45
46
47
48
49
50
51
52
53
#include <QtGui/QGraphicsRectItem>
#include <QtGui/QGraphicsScene>
#include <QtGui/QGraphicsSimpleTextItem>
#include <QtGui/QMouseEvent>
#include <QtGui/QStaticText>
#include <QtGui/QStyleOptionGraphicsItem>
#include <QtCore/QPair>
#include <QtCore/QPersistentModelIndex>
#include <QtCore/QLinkedList>
#include <QtCore/QAbstractItemModel>
#include <QtCore/QDebug>
Mike McQuaid's avatar
Mike McQuaid committed
54
55
56
57
58

#define VISUALISATION_DEBUG 0
// Margin from hardcoded value in:
// QGraphicsView::fitInView(const QRectF &rect,
//                          Qt::AspectRatioMode aspectRatioMode)
59
// Bug report here: https://bugreports.qt-project.org/browse/QTBUG-11945
60
static const int FIT_IN_VIEW_MARGIN = 2;
Mike McQuaid's avatar
Mike McQuaid committed
61
62
63

using namespace Valgrind::Callgrind;

64
namespace Valgrind {
Mike McQuaid's avatar
Mike McQuaid committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
namespace Internal {

class FunctionGraphicsTextItem : public QAbstractGraphicsShapeItem
{
public:
    FunctionGraphicsTextItem(const QString &text, QGraphicsItem *parent);

    virtual void paint(QPainter *painter,
                       const QStyleOptionGraphicsItem *option, QWidget *widget);
    virtual QRectF boundingRect() const;

private:
    QString m_text;
    QStaticText m_staticText;
    qreal m_previousViewportDimension;
};

class FunctionGraphicsItem : public QGraphicsRectItem
{
public:
    enum DataKey {
        FunctionCallKey
    };

    FunctionGraphicsItem(const QString &text, qreal x, qreal y,
                         qreal width, qreal height, QGraphicsItem *parent = 0);

    virtual void paint(QPainter *painter,
                       const QStyleOptionGraphicsItem *option, QWidget *widget);
    FunctionGraphicsTextItem *textItem() const;

private:
    FunctionGraphicsTextItem *m_text;
};

FunctionGraphicsTextItem::FunctionGraphicsTextItem(const QString &text,
                                                   QGraphicsItem *parent)
    : QAbstractGraphicsShapeItem(parent)
    , m_text(text)
    , m_previousViewportDimension(0)
{
    setFlag(QGraphicsItem::ItemIgnoresTransformations);
    setAcceptedMouseButtons(0); // do not steal focus from parent item
    setToolTip(text);
}

void FunctionGraphicsTextItem::paint(QPainter *painter,
                                     const QStyleOptionGraphicsItem *,
                                     QWidget *widget)
{
    const qreal textHeight = painter->fontMetrics().height();
    // Magic number based on what looked best.
    const int margin = 2 + FIT_IN_VIEW_MARGIN;
    const QRectF viewportRect =
            widget->rect().adjusted(margin, margin, -margin, -margin);

    const qreal maxWidth = viewportRect.width()
            * parentItem()->boundingRect().width()
            / scene()->sceneRect().width();
    const qreal maxHeight = viewportRect.height()
            * parentItem()->boundingRect().height()
            / scene()->sceneRect().height();

128
    if (textHeight > maxHeight)
Mike McQuaid's avatar
Mike McQuaid committed
129
130
        return;

131
    if (viewportRect.width() != m_previousViewportDimension) {
Mike McQuaid's avatar
Mike McQuaid committed
132
133
        const QString &elidedText =
                painter->fontMetrics().elidedText(m_text, Qt::ElideRight,
134
                                                  maxWidth);
Mike McQuaid's avatar
Mike McQuaid committed
135
136
137
        m_staticText.setText(elidedText);
        m_staticText.prepare();

138
        m_previousViewportDimension = viewportRect.width();
Mike McQuaid's avatar
Mike McQuaid committed
139
140
141
142
143
144
145
146
147
148
    }

#if VISUALISATION_DEBUG
    painter->setPen(Qt::red);
    painter->drawRect(boundingRect());
#endif

    painter->save();
    int textLeft = 0;
    int textTop = 0;
149
150
151
    const int textWidth = painter->fontMetrics().width(m_staticText.text());
    textLeft = -textWidth/2;
    textTop = (maxHeight - textHeight)/2;
Mike McQuaid's avatar
Mike McQuaid committed
152
153
154
155
156
157
158
159
160
161
162
    painter->drawStaticText(textLeft, textTop, m_staticText);

    painter->restore();
}

QRectF FunctionGraphicsTextItem::boundingRect() const
{
    return mapRectFromParent(parentItem()->boundingRect());
}

FunctionGraphicsItem::FunctionGraphicsItem(const QString &text,
hjk's avatar
hjk committed
163
        qreal x, qreal y, qreal width, qreal height, QGraphicsItem *parent)
Mike McQuaid's avatar
Mike McQuaid committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    : QGraphicsRectItem(x, y, width, height, parent)
    , m_text(0)
{
    setFlag(QGraphicsItem::ItemIsSelectable);
    setFlag(QGraphicsItem::ItemClipsToShape);
    setFlag(QGraphicsItem::ItemClipsChildrenToShape);
    setToolTip(text);

    m_text = new FunctionGraphicsTextItem(text, this);
    m_text->setPos(rect().center().x(), y);
}

FunctionGraphicsTextItem *FunctionGraphicsItem::textItem() const
{
    return m_text;
}

void FunctionGraphicsItem::paint(QPainter *painter,
hjk's avatar
hjk committed
182
    const QStyleOptionGraphicsItem *option, QWidget *)
Mike McQuaid's avatar
Mike McQuaid committed
183
184
185
186
187
188
{
    painter->save();

    QRectF rect = this->rect();
    const QColor &color = brush().color();
    if (option->state & QStyle::State_Selected) {
189
190
191
192
        QLinearGradient gradient(0, 0, rect.width(), 0);
        gradient.setColorAt(0, color.darker(100));
        gradient.setColorAt(0.5, color.lighter(200));
        gradient.setColorAt(1, color.darker(100));
Mike McQuaid's avatar
Mike McQuaid committed
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
        painter->setBrush(gradient);
    }
    else {
        painter->setBrush(color);
    }

#if VISUALISATION_DEBUG
    painter->setPen(Qt::blue);
    painter->drawRect(boundingRect());
#endif

    QPen pen = painter->pen();
    pen.setColor(color.darker());
    pen.setWidthF(0.5);
    painter->setPen(pen);
    qreal halfPenWidth = pen.widthF()/2.0;
    rect.adjust(halfPenWidth, halfPenWidth, -halfPenWidth, -halfPenWidth);
    painter->drawRect(rect);

    painter->restore();
}

class Visualisation::Private
{
public:
    Private(Visualisation *qq);

    void handleMousePressEvent(QMouseEvent *event, bool doubleClicked);
    qreal sceneHeight() const;
    qreal sceneWidth() const;

    Visualisation *q;
    DataProxyModel *m_model;
    QGraphicsScene m_scene;
};

Visualisation::Private::Private(Visualisation *qq)
    : q(qq)
    , m_model(new DataProxyModel(qq))
{
    // setup scene
    m_scene.setObjectName("Visualisation Scene");
    ///NOTE: with size 100x100 the Qt-internal mouse selection fails...
    m_scene.setSceneRect(0, 0, 1024, 1024);

    // setup model
    m_model->setMinimumInclusiveCostRatio(0.1);
    connect(m_model,
            SIGNAL(filterFunctionChanged(const Function*,const Function*)),
            qq, SLOT(populateScene()));
}

void Visualisation::Private::handleMousePressEvent(QMouseEvent *event,
                                                   bool doubleClicked)
{
    // find the first item that accepts mouse presses under the cursor position
    QGraphicsItem *itemAtPos = 0;
250
    foreach (QGraphicsItem *item, q->items(event->pos())) {
Mike McQuaid's avatar
Mike McQuaid 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
        if (!(item->acceptedMouseButtons() & event->button()))
            continue;

        itemAtPos = item;
        break;
    }

    // if there is an item, select it
    if (itemAtPos) {
        const Function *func = q->functionForItem(itemAtPos);

        if (doubleClicked) {
            q->functionActivated(func);
        }
        else {
            q->scene()->clearSelection();
            itemAtPos->setSelected(true);
            q->functionSelected(func);
        }
    }

}

qreal Visualisation::Private::sceneHeight() const
{
    return m_scene.height() - FIT_IN_VIEW_MARGIN;
}

qreal Visualisation::Private::sceneWidth() const
{
    // Magic number to improve margins appearance
    return m_scene.width() + 1;
}

Visualisation::Visualisation(QWidget *parent)
    : QGraphicsView(parent)
    , d(new Private(this))
{
    setObjectName("Visualisation View");
    setScene(&d->m_scene);
    setRenderHint(QPainter::Antialiasing);
}

Visualisation::~Visualisation()
{
    delete d;
}

const Function *Visualisation::functionForItem(QGraphicsItem *item) const
{
    return item->data(FunctionGraphicsItem::FunctionCallKey).value<const Function *>();
}

QGraphicsItem *Visualisation::itemForFunction(const Function *function) const
{
306
    foreach (QGraphicsItem *item, items()) {
Mike McQuaid's avatar
Mike McQuaid committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
        if (functionForItem(item) == function)
            return item;
    }
    return 0;
}

void Visualisation::setFunction(const Function *function)
{
    d->m_model->setFilterFunction(function);
}

const Function *Visualisation::function() const
{
    return d->m_model->filterFunction();
}

323
324
325
326
327
void Visualisation::setMinimumInclusiveCostRatio(double ratio)
{
    d->m_model->setMinimumInclusiveCostRatio(ratio);
}

hjk's avatar
hjk committed
328
void Visualisation::setModel(QAbstractItemModel *model)
Mike McQuaid's avatar
Mike McQuaid committed
329
330
331
332
333
{
    QTC_ASSERT(!d->m_model->sourceModel() && model, return); // only set once!
    d->m_model->setSourceModel(model);

    connect(model,
hjk's avatar
hjk committed
334
            SIGNAL(columnsInserted(QModelIndex,int,int)),
Mike McQuaid's avatar
Mike McQuaid committed
335
336
            SLOT(populateScene()));
    connect(model,
hjk's avatar
hjk committed
337
            SIGNAL(columnsMoved(QModelIndex,int,int,QModelIndex,int)),
Mike McQuaid's avatar
Mike McQuaid committed
338
339
            SLOT(populateScene()));
    connect(model,
hjk's avatar
hjk committed
340
            SIGNAL(columnsRemoved(QModelIndex,int,int)),
Mike McQuaid's avatar
Mike McQuaid committed
341
342
            SLOT(populateScene()));
    connect(model,
hjk's avatar
hjk committed
343
            SIGNAL(dataChanged(QModelIndex,QModelIndex)),
Mike McQuaid's avatar
Mike McQuaid committed
344
345
            SLOT(populateScene()));
    connect(model,
hjk's avatar
hjk committed
346
            SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
Mike McQuaid's avatar
Mike McQuaid committed
347
348
349
350
            SLOT(populateScene()));
    connect(model, SIGNAL(layoutChanged()), SLOT(populateScene()));
    connect(model, SIGNAL(modelReset()), SLOT(populateScene()));
    connect(model,
hjk's avatar
hjk committed
351
            SIGNAL(rowsInserted(QModelIndex,int,int)),
Mike McQuaid's avatar
Mike McQuaid committed
352
353
            SLOT(populateScene()));
    connect(model,
hjk's avatar
hjk committed
354
            SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)),
Mike McQuaid's avatar
Mike McQuaid committed
355
356
            SLOT(populateScene()));
    connect(model,
hjk's avatar
hjk committed
357
            SIGNAL(rowsRemoved(QModelIndex,int,int)),
Mike McQuaid's avatar
Mike McQuaid committed
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
            SLOT(populateScene()));

    populateScene();
}

void Visualisation::setText(const QString &message)
{
    d->m_scene.clear();

    QGraphicsSimpleTextItem *textItem = d->m_scene.addSimpleText(message);
    textItem->setBrush(palette().foreground());
    textItem->setPos((d->sceneWidth() - textItem->boundingRect().width()) / 2,
                     (d->sceneHeight() - textItem->boundingRect().height()) / 2);
    textItem->setFlag(QGraphicsItem::ItemIgnoresTransformations);
}

void Visualisation::populateScene()
{
    // reset scene first
    d->m_scene.clear();

    const qreal sceneWidth = d->sceneWidth();
    const qreal sceneHeight = d->sceneHeight();

    // cache costs of each element, calculate total costs
    qreal total = 0;

    typedef QPair<QModelIndex, qreal> Pair;
    QLinkedList<Pair> costs;
hjk's avatar
hjk committed
387
    for (int row = 0; row < d->m_model->rowCount(); ++row) {
Mike McQuaid's avatar
Mike McQuaid committed
388
389
390
391
392
393
394
395
396
397
398
399
400
        const QModelIndex index = d->m_model->index(row, DataModel::InclusiveCostColumn);

        bool ok = false;
        const qreal cost = index.data().toReal(&ok);
        QTC_ASSERT(ok, continue);
        costs << QPair<QModelIndex, qreal>(d->m_model->index(row, 0), cost);
        total += cost;
    }

    if (!costs.isEmpty() || d->m_model->filterFunction()) {
        // item showing the current filter function

        QString text;
hjk's avatar
hjk committed
401
        if (d->m_model->filterFunction()) {
Mike McQuaid's avatar
Mike McQuaid committed
402
            text = d->m_model->filterFunction()->name();
hjk's avatar
hjk committed
403
        } else {
Mike McQuaid's avatar
Mike McQuaid committed
404
405
406
407
408
409
410
411
412
            const float ratioPercent = d->m_model->minimumInclusiveCostRatio() * 100;
            QString ratioPercentString = QString::number(ratioPercent);
            ratioPercentString.append(QLocale::system().percent());
            const int hiddenFunctions = d->m_model->sourceModel()->rowCount() - d->m_model->rowCount();
            text = tr("All functions with an inclusive cost ratio higher than %1 (%2 are hidden)")
                    .arg(ratioPercentString)
                    .arg(hiddenFunctions);
        }

hjk's avatar
hjk committed
413
        const qreal height = sceneHeight * (costs.isEmpty() ? 1.0 : 0.1);
Mike McQuaid's avatar
Mike McQuaid committed
414
415
416
417
418
419
420
421
422
423
        FunctionGraphicsItem *item = new FunctionGraphicsItem(text, 0, 0, sceneWidth, height);
        const QColor background = CallgrindHelper::colorForString(text);
        item->setBrush(background);
        item->setData(FunctionGraphicsItem::FunctionCallKey, QVariant::fromValue(d->m_model->filterFunction()));
        // NOTE: workaround wrong tooltip being show, no idea why...
        item->setZValue(-1);
        d->m_scene.addItem(item);
    }

    // add the canvas elements to the scene
424
    qreal used = sceneHeight * 0.1;
hjk's avatar
hjk committed
425
    foreach (const Pair &cost, costs) {
Mike McQuaid's avatar
Mike McQuaid committed
426
427
428
        const QModelIndex &index = cost.first;
        const QString text = index.data().toString();

429
        const qreal height = (sceneHeight * 0.9 * cost.second) / total;
Mike McQuaid's avatar
Mike McQuaid committed
430

431
        FunctionGraphicsItem *item = new FunctionGraphicsItem(text, 0, used, sceneWidth, height);
Mike McQuaid's avatar
Mike McQuaid committed
432
433
434
435
        const QColor background = CallgrindHelper::colorForString(text);
        item->setBrush(background);
        item->setData(FunctionGraphicsItem::FunctionCallKey, index.data(DataModel::FunctionRole));
        d->m_scene.addItem(item);
436
        used += height;
Mike McQuaid's avatar
Mike McQuaid committed
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
    }
}

void Visualisation::mousePressEvent(QMouseEvent *event)
{
    d->handleMousePressEvent(event, false);

    QGraphicsView::mousePressEvent(event);
}

void Visualisation::mouseDoubleClickEvent(QMouseEvent *event)
{
    d->handleMousePressEvent(event, true);

    QGraphicsView::mouseDoubleClickEvent(event);
}

void Visualisation::resizeEvent(QResizeEvent *event)
{
    fitInView(sceneRect());

    QGraphicsView::resizeEvent(event);
}

461
} // namespace Internal
462
} // namespace Valgrind