memcheckerrorview.cpp 12.9 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
5 6
** Author: Andreas Hartmetz, KDAB (andreas.hartmetz@kdab.com)
**
hjk's avatar
hjk committed
7
** This file is part of Qt Creator.
8
**
hjk's avatar
hjk committed
9 10 11 12 13
** 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
Eike Ziller's avatar
Eike Ziller committed
14 15
** conditions see http://www.qt.io/licensing.  For further information
** use the contact form at http://www.qt.io/contact-us.
16 17
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
18
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
19 20 21 22 23 24
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25
**
hjk's avatar
hjk committed
26 27
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
28 29
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
30
****************************************************************************/
31 32 33 34

#include "memcheckerrorview.h"

#include "suppressiondialog.h"
35
#include "valgrindsettings.h"
36

hjk's avatar
hjk committed
37 38 39 40 41 42
#include "xmlprotocol/error.h"
#include "xmlprotocol/errorlistmodel.h"
#include "xmlprotocol/frame.h"
#include "xmlprotocol/stack.h"
#include "xmlprotocol/modelhelpers.h"
#include "xmlprotocol/suppression.h"
43

hjk's avatar
hjk committed
44
#include <coreplugin/coreconstants.h>
45
#include <coreplugin/editormanager/editormanager.h>
46
#include <projectexplorer/project.h>
47
#include <projectexplorer/projectexplorer.h>
hjk's avatar
hjk committed
48
#include <projectexplorer/session.h>
49 50
#include <utils/qtcassert.h>

51 52
#include <QDir>
#include <QDebug>
Friedemann Kleint's avatar
Friedemann Kleint committed
53

54 55 56
#include <QAction>
#include <QApplication>
#include <QClipboard>
57
#include <QContextMenuEvent>
58 59 60 61 62 63 64
#include <QLabel>
#include <QListView>
#include <QMenu>
#include <QPainter>
#include <QScrollBar>
#include <QSortFilterProxyModel>
#include <QStyledItemDelegate>
Christian Stenger's avatar
Christian Stenger committed
65
#include <QTextDocument>
66
#include <QVBoxLayout>
67 68 69

using namespace Valgrind::XmlProtocol;

70
namespace Valgrind {
hjk's avatar
hjk committed
71 72
namespace Internal {

73
class MemcheckErrorDelegate : public Analyzer::DetailedErrorDelegate
hjk's avatar
hjk committed
74 75 76 77 78 79 80 81
{
    Q_OBJECT

public:
    explicit MemcheckErrorDelegate(QListView *parent);

    void copy();

82
    SummaryLineInfo summaryInfo(const QModelIndex &index) const;
hjk's avatar
hjk committed
83 84

private:
85 86
    QWidget *createDetailsWidget(const QFont &font, const QModelIndex &errorIndex,
                                 QWidget *parent) const;
hjk's avatar
hjk committed
87 88
};

89 90 91 92 93 94
static QString makeFrameName(const Frame &frame, const QString &relativeTo,
                             bool link = true, const QString &linkAttr = QString())
{
    const QString d = frame.directory();
    const QString f = frame.file();
    const QString fn = frame.functionName();
95
    const QString fullPath = d + QLatin1Char('/') + f;
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

    QString path;
    if (!d.isEmpty() && !f.isEmpty())
        path = fullPath;
    else
        path = frame.object();

    if (QFile::exists(path))
        path = QFileInfo(path).canonicalFilePath();

    if (path.startsWith(relativeTo))
        path.remove(0, relativeTo.length());

    if (frame.line() != -1)
        path += QLatin1Char(':') + QString::number(frame.line());

112 113 114
    // Since valgrind only runs on POSIX systems, converting path separators
    // will ruin the paths on Windows. Leave it untouched.
    path = path.toHtmlEscaped();
115 116 117

    if (link && !f.isEmpty() && QFile::exists(fullPath)) {
        // make a hyperlink label
118
        path = QString::fromLatin1("<a href=\"file://%1:%2\" %4>%3</a>")
119
                .arg(fullPath).arg(frame.line()).arg(path).arg(linkAttr);
120 121 122
    }

    if (!fn.isEmpty())
123
        return QCoreApplication::translate("Valgrind::Internal", "%1 in %2").arg(fn.toHtmlEscaped(), path);
hjk's avatar
hjk committed
124
    if (!path.isEmpty())
125
        return path;
126
    return QString::fromLatin1("0x%1").arg(frame.instructionPointer(), 0, 16);
127 128
}

hjk's avatar
hjk committed
129
static QString relativeToPath()
130
{
hjk's avatar
hjk committed
131
    // The project for which we insert the snippet.
hjk's avatar
hjk committed
132
    const ProjectExplorer::Project *project = ProjectExplorer::SessionManager::startupProject();
133

134
    QString relativeTo(project ? project->projectDirectory().toString() : QDir::homePath());
135 136 137
    const QChar slash = QLatin1Char('/');
    if (!relativeTo.endsWith(slash))
        relativeTo.append(slash);
138 139 140 141

    return relativeTo;
}

hjk's avatar
hjk committed
142
static QString errorLocation(const QModelIndex &index, const Error &error,
143 144
                             bool link = false, bool absolutePath = false,
                             const QString &linkAttr = QString())
145
{
146 147
    if (!index.isValid())
        return QString();
148
    const ErrorListModel *model = 0;
149
    const QAbstractProxyModel *proxy = qobject_cast<const QAbstractProxyModel *>(index.model());
150
    while (!model && proxy) {
151 152
        model = qobject_cast<const ErrorListModel *>(proxy->sourceModel());
        proxy = qobject_cast<const QAbstractProxyModel *>(proxy->sourceModel());
hjk's avatar
hjk committed
153
    }
154 155
    QTC_ASSERT(model, return QString());

156
    const QString relativePath = absolutePath ? QString() : relativeToPath();
157
    return QCoreApplication::translate("Valgrind::Internal", "in %1").
158
            arg(makeFrameName(model->findRelevantFrame(error), relativePath,
Friedemann Kleint's avatar
Friedemann Kleint committed
159
                              link, linkAttr));
160 161
}

162 163 164
QWidget *MemcheckErrorDelegate::createDetailsWidget(const QFont & font,
                                                    const QModelIndex &errorIndex,
                                                    QWidget *parent) const
165 166
{
    QWidget *widget = new QWidget(parent);
167 168
    QTC_ASSERT(errorIndex.isValid(), return widget);

169 170 171 172
    QVBoxLayout *layout = new QVBoxLayout;
    // code + white-space:pre so the padding (see below) works properly
    // don't include frameName here as it should wrap if required and pre-line is not supported
    // by Qt yet it seems
173
    const QString displayTextTemplate = QString::fromLatin1("<code style='white-space:pre'>%1:</code> %2");
hjk's avatar
hjk committed
174
    const QString relativeTo = relativeToPath();
175 176 177 178 179 180 181 182 183
    const Error error = errorIndex.data(ErrorListModel::ErrorRole).value<Error>();

    QLabel *errorLabel = new QLabel();
    errorLabel->setWordWrap(true);
    errorLabel->setContentsMargins(0, 0, 0, 0);
    errorLabel->setMargin(0);
    errorLabel->setIndent(0);
    QPalette p = errorLabel->palette();
    QColor lc = p.color(QPalette::Text);
184
    QString linkStyle = QString::fromLatin1("style=\"color:rgba(%1, %2, %3, %4);\"")
185 186 187
                            .arg(lc.red()).arg(lc.green()).arg(lc.blue()).arg(int(0.7 * 255));
    p.setBrush(QPalette::Text, p.highlightedText());
    errorLabel->setPalette(p);
188
    errorLabel->setText(QString::fromLatin1("%1&nbsp;&nbsp;<span %4>%2</span>")
189 190 191
                            .arg(error.what(),
                                 errorLocation(errorIndex, error, /*link=*/ true,
                                               /*absolutePath=*/ false, linkStyle),
192
                                 linkStyle));
Montel Laurent's avatar
Montel Laurent committed
193
    connect(errorLabel, &QLabel::linkActivated, this, &MemcheckErrorDelegate::openLinkInEditor);
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    layout->addWidget(errorLabel);

    const QVector<Stack> stacks = error.stacks();
    for (int i = 0; i < stacks.count(); ++i) {
        const Stack &stack = stacks.at(i);
        // auxwhat for additional stacks
        if (i > 0) {
            QLabel *stackLabel = new QLabel(stack.auxWhat());
            stackLabel->setWordWrap(true);
            stackLabel->setContentsMargins(0, 0, 0, 0);
            stackLabel->setMargin(0);
            stackLabel->setIndent(0);
            QPalette p = stackLabel->palette();
            p.setBrush(QPalette::Text, p.highlightedText());
            stackLabel->setPalette(p);
            layout->addWidget(stackLabel);
        }
        int frameNr = 1;
        foreach (const Frame &frame, stack.frames()) {
            QString frameName = makeFrameName(frame, relativeTo);
hjk's avatar
hjk committed
214
            QTC_ASSERT(!frameName.isEmpty(), /**/);
215 216 217 218 219 220 221 222 223

            QLabel *frameLabel = new QLabel(widget);
            frameLabel->setAutoFillBackground(true);
            if (frameNr % 2 == 0) {
                // alternating rows
                QPalette p = frameLabel->palette();
                p.setBrush(QPalette::Base, p.alternateBase());
                frameLabel->setPalette(p);
            }
224 225 226 227

            QFont fixedPitchFont = font;
            fixedPitchFont.setFixedPitch(true);
            frameLabel->setFont(fixedPitchFont);
Montel Laurent's avatar
Montel Laurent committed
228
            connect(frameLabel, &QLabel::linkActivated, this, &MemcheckErrorDelegate::openLinkInEditor);
229 230 231 232 233
            // pad frameNr to 2 chars since only 50 frames max are supported by valgrind
            const QString displayText = displayTextTemplate
                                            .arg(frameNr++, 2).arg(frameName);
            frameLabel->setText(displayText);

hjk's avatar
hjk committed
234
            frameLabel->setToolTip(toolTipForFrame(frame));
235 236 237 238 239 240 241 242 243 244 245 246 247 248
            frameLabel->setWordWrap(true);
            frameLabel->setContentsMargins(0, 0, 0, 0);
            frameLabel->setMargin(0);
            frameLabel->setIndent(10);
            layout->addWidget(frameLabel);
        }
    }

    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    widget->setLayout(layout);
    return widget;
}

249 250
MemcheckErrorDelegate::MemcheckErrorDelegate(QListView *parent)
    : Analyzer::DetailedErrorDelegate(parent)
251 252 253
{
}

254 255
Analyzer::DetailedErrorDelegate::SummaryLineInfo MemcheckErrorDelegate::summaryInfo(
        const QModelIndex &index) const
256
{
257 258 259 260 261
    const Error error = index.data(ErrorListModel::ErrorRole).value<Error>();
    SummaryLineInfo info;
    info.errorText = error.what();
    info.errorLocation = errorLocation(index, error);
    return info;
262 263 264 265 266 267 268 269 270 271 272
}

void MemcheckErrorDelegate::copy()
{
    QTC_ASSERT(m_detailsIndex.isValid(), return);

    QString content;
    QTextStream stream(&content);
    const Error error = m_detailsIndex.data(ErrorListModel::ErrorRole).value<Error>();

    stream << error.what() << "\n";
273 274 275
    stream << "  "
           << errorLocation(m_detailsIndex, error, /*link=*/ false, /*absolutePath=*/ true)
           << "\n";
276

277
    foreach (const Stack &stack, error.stacks()) {
278
        if (!stack.auxWhat().isEmpty())
279 280
            stream << stack.auxWhat();
        int i = 1;
281 282
        foreach (const Frame &frame, stack.frames())
            stream << "  " << i++ << ": " << makeFrameName(frame, QString(), false) << "\n";
283 284 285 286 287 288 289
    }

    stream.flush();
    QApplication::clipboard()->setText(content);
}

MemcheckErrorView::MemcheckErrorView(QWidget *parent)
290
    : Analyzer::DetailedErrorView(parent),
291 292
      m_settings(0)
{
293 294
    MemcheckErrorDelegate *delegate = new MemcheckErrorDelegate(this);
    setItemDelegate(delegate);
295 296

    m_copyAction = new QAction(this);
297
    m_copyAction->setText(tr("Copy"));
298
    m_copyAction->setIcon(QIcon(QLatin1String(Core::Constants::ICON_COPY)));
299 300
    m_copyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_C));
    m_copyAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
301
    connect(m_copyAction, &QAction::triggered, delegate, &MemcheckErrorDelegate::copy);
302
    addAction(m_copyAction);
303 304 305 306 307 308

    m_suppressAction = new QAction(this);
    m_suppressAction->setText(tr("Suppress Error"));
    m_suppressAction->setIcon(QIcon(QLatin1String(":/qmldesigner/images/eye_crossed.png")));
    m_suppressAction->setShortcut(QKeySequence(Qt::Key_Delete));
    m_suppressAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
309
    connect(m_suppressAction, &QAction::triggered, this, &MemcheckErrorView::suppressError);
310
    addAction(m_suppressAction);
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
}

MemcheckErrorView::~MemcheckErrorView()
{
}

void MemcheckErrorView::setDefaultSuppressionFile(const QString &suppFile)
{
    m_defaultSuppFile = suppFile;
}

QString MemcheckErrorView::defaultSuppressionFile() const
{
    return m_defaultSuppFile;
}

// slot, can (for now) be invoked either when the settings were modified *or* when the active
// settings object has changed.
hjk's avatar
hjk committed
329
void MemcheckErrorView::settingsChanged(ValgrindBaseSettings *settings)
330 331 332 333 334 335 336 337
{
    QTC_ASSERT(settings, return);
    m_settings = settings;
}

void MemcheckErrorView::contextMenuEvent(QContextMenuEvent *e)
{
    const QModelIndexList indizes = selectionModel()->selectedRows();
338
    if (indizes.isEmpty())
339
        return;
340

341
    QList<Error> errors;
342
    foreach (const QModelIndex &index, indizes) {
343 344 345 346 347 348 349 350
        Error error = model()->data(index, ErrorListModel::ErrorRole).value<Error>();
        if (!error.suppression().isNull())
            errors << error;
    }

    QMenu menu;
    menu.addAction(m_copyAction);
    menu.addSeparator();
351 352 353 354 355 356 357
    menu.addAction(m_suppressAction);
    m_suppressAction->setEnabled(!errors.isEmpty());
    menu.exec(e->globalPos());
}

void MemcheckErrorView::suppressError()
{
hjk's avatar
hjk committed
358
    SuppressionDialog::maybeShow(this);
359
}
hjk's avatar
hjk committed
360 361

} // namespace Internal
362
} // namespace Valgrind
hjk's avatar
hjk committed
363 364

#include "memcheckerrorview.moc"