1 /**************************************************************************
3 ** This file is part of Qt Creator
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
7 ** Author: Andreas Hartmetz, KDAB (andreas.hartmetz@kdab.com)
9 ** Contact: Nokia Corporation (info@qt.nokia.com)
12 ** GNU Lesser General Public License Usage
14 ** This file may be used under the terms of the GNU Lesser General Public
15 ** License version 2.1 as published by the Free Software Foundation and
16 ** appearing in the file LICENSE.LGPL included in the packaging of this file.
17 ** Please review the following information to ensure the GNU Lesser General
18 ** Public License version 2.1 requirements will be met:
19 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
21 ** In addition, as a special exception, Nokia gives you certain additional
22 ** rights. These rights are described in the Nokia Qt LGPL Exception
23 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27 ** Alternatively, this file may be used in accordance with the terms and
28 ** conditions contained in a signed written agreement between you and Nokia.
30 ** If you have questions regarding the use of this file, please contact
31 ** Nokia at qt-info@nokia.com.
33 **************************************************************************/
35 #include "memcheckerrorview.h"
37 #include "suppressiondialog.h"
39 #include <valgrind/xmlprotocol/error.h>
40 #include <valgrind/xmlprotocol/errorlistmodel.h>
41 #include <valgrind/xmlprotocol/frame.h>
42 #include <valgrind/xmlprotocol/stack.h>
43 #include <valgrind/xmlprotocol/modelhelpers.h>
44 #include <valgrind/xmlprotocol/suppression.h>
46 #include <valgrindtoolbase/valgrindsettings.h>
48 #include <texteditor/basetexteditor.h>
50 #include <projectexplorer/projectexplorer.h>
51 #include <projectexplorer/project.h>
52 #include <coreplugin/coreconstants.h>
54 #include <utils/qtcassert.h>
56 #include <QtCore/QDir>
57 #include <QtCore/QDebug>
59 #include <QtGui/QLabel>
60 #include <QtGui/QListView>
61 #include <QtGui/QPainter>
62 #include <QtGui/QScrollBar>
63 #include <QtGui/QSortFilterProxyModel>
64 #include <QtGui/QVBoxLayout>
65 #include <QtGui/QAction>
66 #include <QtGui/QClipboard>
67 #include <QtGui/QApplication>
68 #include <QtGui/QMenu>
70 using namespace Analyzer;
71 using namespace Analyzer::Internal;
72 using namespace Valgrind::XmlProtocol;
74 MemcheckErrorDelegate::MemcheckErrorDelegate(QListView *parent)
75 : QStyledItemDelegate(parent),
78 connect(parent->verticalScrollBar(), SIGNAL(valueChanged(int)),
79 SLOT(verticalScrolled()));
82 MemcheckErrorDelegate::~MemcheckErrorDelegate()
86 QSize MemcheckErrorDelegate::sizeHint(const QStyleOptionViewItem &opt, const QModelIndex &index) const
88 const QListView *view = qobject_cast<const QListView *>(parent());
89 const int viewportWidth = view->viewport()->width();
90 const bool isSelected = view->selectionModel()->currentIndex() == index;
92 int dy = 2 * s_itemMargin;
95 QFontMetrics fm(opt.font);
96 return QSize(viewportWidth, fm.height() + dy);
99 if (m_detailsWidget && m_detailsIndex != index) {
100 m_detailsWidget->deleteLater();
104 if (!m_detailsWidget) {
105 m_detailsWidget = createDetailsWidget(index, view->viewport());
106 QTC_ASSERT(m_detailsWidget->parent() == view->viewport(),
107 m_detailsWidget->setParent(view->viewport()));
108 m_detailsIndex = index;
110 QTC_ASSERT(m_detailsIndex == index, qt_noop());
112 const int widthExcludingMargins = viewportWidth - 2 * s_itemMargin;
113 m_detailsWidget->setFixedWidth(widthExcludingMargins);
115 m_detailsWidgetHeight = m_detailsWidget->heightForWidth(widthExcludingMargins);
116 // HACK: it's a bug in QLabel(?) that we have to force the widget to have the size it said
118 m_detailsWidget->setFixedHeight(m_detailsWidgetHeight);
119 return QSize(viewportWidth, dy + m_detailsWidget->heightForWidth(widthExcludingMargins));
122 static QString makeFrameName(const Frame &frame, const QString &relativeTo,
123 bool link = true, const QString &linkAttr = QString())
125 const QString d = frame.directory();
126 const QString f = frame.file();
127 const QString fn = frame.functionName();
128 const QString fullPath = d + QDir::separator() + f;
131 if (!d.isEmpty() && !f.isEmpty())
134 path = frame.object();
136 if (QFile::exists(path))
137 path = QFileInfo(path).canonicalFilePath();
139 if (path.startsWith(relativeTo))
140 path.remove(0, relativeTo.length());
142 if (frame.line() != -1)
143 path += QLatin1Char(':') + QString::number(frame.line());
145 path = Qt::escape(path);
147 if (link && !f.isEmpty() && QFile::exists(fullPath)) {
148 // make a hyperlink label
149 path = QString("<a href=\"file://%1:%2\" %4>%3</a>")
150 .arg(fullPath, QString::number(frame.line()), path, linkAttr);
154 return QCoreApplication::translate("Analyzer::Internal", "%1 in %2").arg(Qt::escape(fn), path);
155 else if (!path.isEmpty())
158 return QString("0x%1").arg(frame.instructionPointer(), 0, 16);
161 QString relativeToPath()
163 // project for which we insert the snippet
164 const ProjectExplorer::Project *project =
165 ProjectExplorer::ProjectExplorerPlugin::instance()->startupProject();
167 QString relativeTo( project ? project->projectDirectory() : QDir::homePath() );
168 if (!relativeTo.endsWith(QDir::separator()))
169 relativeTo.append(QDir::separator());
174 QString errorLocation(const QModelIndex &index, const Error &error,
175 bool link = false, const QString &linkAttr = QString())
177 const ErrorListModel *model = 0;
178 const QAbstractProxyModel *proxy = qobject_cast<const QAbstractProxyModel*>(index.model());
179 while(!model && proxy) {
180 model = qobject_cast<const ErrorListModel*>(proxy->sourceModel());
181 proxy = qobject_cast<const QAbstractProxyModel*>(proxy->sourceModel());
183 QTC_ASSERT(model, return QString());
185 return QCoreApplication::translate("Analyzer::Internal", "in %1").
186 arg(makeFrameName(model->findRelevantFrame(error), relativeToPath(),
190 QWidget *MemcheckErrorDelegate::createDetailsWidget(const QModelIndex &errorIndex, QWidget *parent) const
192 QWidget *widget = new QWidget(parent);
193 QVBoxLayout *layout = new QVBoxLayout;
194 // code + white-space:pre so the padding (see below) works properly
195 // don't include frameName here as it should wrap if required and pre-line is not supported
196 // by Qt yet it seems
197 const QString displayTextTemplate = QString("<code style='white-space:pre'>%1:</code> %2");
199 QString relativeTo = relativeToPath();
201 const Error error = errorIndex.data(ErrorListModel::ErrorRole).value<Error>();
203 QLabel *errorLabel = new QLabel();
204 errorLabel->setWordWrap(true);
205 errorLabel->setContentsMargins(0, 0, 0, 0);
206 errorLabel->setMargin(0);
207 errorLabel->setIndent(0);
208 QPalette p = errorLabel->palette();
209 QColor lc = p.color(QPalette::Text);
210 QString linkStyle = QString("style=\"color:rgba(%1, %2, %3, %4);\"")
211 .arg(lc.red()).arg(lc.green()).arg(lc.blue()).arg(int(0.7 * 255));
212 p.setBrush(QPalette::Text, p.highlightedText());
213 errorLabel->setPalette(p);
214 errorLabel->setText(QString("%1 <span %4>%2</span>")
215 .arg(error.what(), errorLocation(errorIndex, error, true, linkStyle),
217 connect(errorLabel, SIGNAL(linkActivated(QString)), SLOT(openLinkInEditor(QString)));
218 layout->addWidget(errorLabel);
220 const QVector<Stack> stacks = error.stacks();
221 for (int i = 0; i < stacks.count(); ++i) {
222 const Stack &stack = stacks.at(i);
223 // auxwhat for additional stacks
225 QLabel *stackLabel = new QLabel(stack.auxWhat());
226 stackLabel->setWordWrap(true);
227 stackLabel->setContentsMargins(0, 0, 0, 0);
228 stackLabel->setMargin(0);
229 stackLabel->setIndent(0);
230 QPalette p = stackLabel->palette();
231 p.setBrush(QPalette::Text, p.highlightedText());
232 stackLabel->setPalette(p);
233 layout->addWidget(stackLabel);
236 foreach (const Frame &frame, stack.frames()) {
237 QString frameName = makeFrameName(frame, relativeTo);
238 QTC_ASSERT(!frameName.isEmpty(), qt_noop());
240 QLabel *frameLabel = new QLabel(widget);
241 frameLabel->setAutoFillBackground(true);
242 if (frameNr % 2 == 0) {
244 QPalette p = frameLabel->palette();
245 p.setBrush(QPalette::Base, p.alternateBase());
246 frameLabel->setPalette(p);
248 frameLabel->setFont(QFont("monospace"));
249 connect(frameLabel, SIGNAL(linkActivated(QString)), SLOT(openLinkInEditor(QString)));
250 // pad frameNr to 2 chars since only 50 frames max are supported by valgrind
251 const QString displayText = displayTextTemplate
252 .arg(frameNr++, 2).arg(frameName);
253 frameLabel->setText(displayText);
255 frameLabel->setToolTip(Valgrind::XmlProtocol::toolTipForFrame(frame));
256 frameLabel->setWordWrap(true);
257 frameLabel->setContentsMargins(0, 0, 0, 0);
258 frameLabel->setMargin(0);
259 frameLabel->setIndent(10);
260 layout->addWidget(frameLabel);
264 layout->setContentsMargins(0, 0, 0, 0);
265 layout->setSpacing(0);
266 widget->setLayout(layout);
270 void MemcheckErrorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &basicOption,
271 const QModelIndex &index) const
273 QStyleOptionViewItemV4 opt(basicOption);
274 initStyleOption(&opt, index);
276 const QListView *const view = qobject_cast<const QListView *>(parent());
277 const bool isSelected = view->selectionModel()->currentIndex() == index;
279 QFontMetrics fm(opt.font);
280 QPoint pos = opt.rect.topLeft();
284 const QColor bgColor = isSelected ? opt.palette.highlight().color() : opt.palette.background().color();
285 painter->setBrush(bgColor);
288 painter->setPen(Qt::NoPen);
289 painter->drawRect(opt.rect);
291 pos.rx() += s_itemMargin;
292 pos.ry() += s_itemMargin;
294 const Error error = index.data(ErrorListModel::ErrorRole).value<Error>();
297 // only show detailed widget and let it handle everything
298 QTC_ASSERT(m_detailsIndex == index, qt_noop());
299 QTC_ASSERT(m_detailsWidget, return); // should have been set in sizeHint()
300 m_detailsWidget->move(pos);
301 // when scrolling quickly, the widget can get stuck in a visible part of the scroll area
302 // even though it should not be visible. therefore we hide it every time the scroll value
303 // changes and un-hide it when the item with details widget is paint()ed, i.e. visible.
304 m_detailsWidget->show();
306 const int viewportWidth = view->viewport()->width();
307 const int widthExcludingMargins = viewportWidth - 2 * s_itemMargin;
308 QTC_ASSERT(m_detailsWidget->width() == widthExcludingMargins, qt_noop());
309 QTC_ASSERT(m_detailsWidgetHeight == m_detailsWidget->height(), qt_noop());
311 // the reference coordinate for text drawing is the text baseline; move it inside the view rect.
312 pos.ry() += fm.ascent();
314 const QColor textColor = opt.palette.text().color();
315 painter->setPen(textColor);
316 // draw only text + location
317 const QString what = error.what();
318 painter->drawText(pos, what);
320 const QString name = errorLocation(index, error);
321 const int whatWidth = QFontMetrics(opt.font).width(what);
322 const int space = 10;
323 const int widthLeft = opt.rect.width() - (pos.x() + whatWidth + space + s_itemMargin);
325 QFont monospace = opt.font;
326 monospace.setFamily("monospace");
327 QFontMetrics metrics(monospace);
328 QColor nameColor = textColor;
329 nameColor.setAlphaF(0.7);
331 painter->setFont(monospace);
332 painter->setPen(nameColor);
334 QPoint namePos = pos;
335 namePos.rx() += whatWidth + space;
336 painter->drawText(namePos, metrics.elidedText(name, Qt::ElideLeft, widthLeft));
340 // Separator lines (like build issues pane)
341 painter->setPen(QColor::fromRgb(150,150,150));
342 painter->drawLine(0, opt.rect.bottom(), opt.rect.right(), opt.rect.bottom());
347 void MemcheckErrorDelegate::currentChanged(const QModelIndex &now, const QModelIndex &previous)
349 if (m_detailsWidget) {
350 m_detailsWidget->deleteLater();
354 m_detailsIndex = QModelIndex();
356 emit sizeHintChanged(now);
357 if (previous.isValid())
358 emit sizeHintChanged(previous);
361 void MemcheckErrorDelegate::layoutChanged()
363 if (m_detailsWidget) {
364 m_detailsWidget->deleteLater();
366 m_detailsIndex = QModelIndex();
370 void MemcheckErrorDelegate::viewResized()
372 const QListView *view = qobject_cast<const QListView *>(parent());
374 emit sizeHintChanged(view->selectionModel()->currentIndex());
377 void MemcheckErrorDelegate::verticalScrolled()
380 m_detailsWidget->hide();
383 void MemcheckErrorDelegate::copy()
385 QTC_ASSERT(m_detailsIndex.isValid(), return);
388 QTextStream stream(&content);
389 const Error error = m_detailsIndex.data(ErrorListModel::ErrorRole).value<Error>();
391 stream << error.what() << "\n";
392 stream << " " << errorLocation(m_detailsIndex, error) << "\n";
394 const QString relativeTo = relativeToPath();
396 foreach(const Stack &stack, error.stacks()) {
397 if (!stack.auxWhat().isEmpty()) {
398 stream << stack.auxWhat();
401 foreach(const Frame &frame, stack.frames()) {
402 stream << " " << i++ << ": " << makeFrameName(frame, relativeTo) << "\n";
407 QApplication::clipboard()->setText(content);
410 void MemcheckErrorDelegate::openLinkInEditor(const QString &link)
412 const int pathStart = strlen("file://");
413 const int pathEnd = link.lastIndexOf(':');
414 const QString path = link.mid(pathStart, pathEnd - pathStart);
415 const int line = link.mid(pathEnd + 1).toInt(0);
416 TextEditor::BaseTextEditorWidget::openEditorAt(path, qMax(line, 0));
419 MemcheckErrorView::MemcheckErrorView(QWidget *parent)
423 setItemDelegate(new MemcheckErrorDelegate(this));
424 connect(this, SIGNAL(resized()), itemDelegate(), SLOT(viewResized()));
426 m_copyAction = new QAction(this);
427 m_copyAction->setText(tr("Copy Selection"));
428 m_copyAction->setIcon(QIcon(Core::Constants::ICON_COPY));
429 m_copyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_C));
430 m_copyAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
431 connect(m_copyAction, SIGNAL(triggered()), itemDelegate(), SLOT(copy()));
432 addAction(m_copyAction);
434 m_suppressAction = new QAction(this);
435 m_suppressAction->setText(tr("Suppress Error"));
436 m_suppressAction->setIcon(QIcon(QLatin1String(":/qmldesigner/images/eye_crossed.png")));
437 m_suppressAction->setShortcut(QKeySequence(Qt::Key_Delete));
438 m_suppressAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
439 connect(m_suppressAction, SIGNAL(triggered()), this, SLOT(suppressError()));
440 addAction(m_suppressAction);
443 MemcheckErrorView::~MemcheckErrorView()
445 itemDelegate()->deleteLater();
448 void MemcheckErrorView::setModel(QAbstractItemModel *model)
450 QListView::setModel(model);
451 connect(selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)),
452 itemDelegate(), SLOT(currentChanged(QModelIndex, QModelIndex)));
454 connect(model, SIGNAL(layoutChanged()),
455 itemDelegate(), SLOT(layoutChanged()));
458 void MemcheckErrorView::resizeEvent(QResizeEvent *e)
461 QListView::resizeEvent(e);
464 void MemcheckErrorView::setDefaultSuppressionFile(const QString &suppFile)
466 m_defaultSuppFile = suppFile;
469 QString MemcheckErrorView::defaultSuppressionFile() const
471 return m_defaultSuppFile;
474 // slot, can (for now) be invoked either when the settings were modified *or* when the active
475 // settings object has changed.
476 void MemcheckErrorView::settingsChanged(AnalyzerSettings *settings)
478 QTC_ASSERT(settings, return);
480 m_settings = settings;
483 void MemcheckErrorView::contextMenuEvent(QContextMenuEvent *e)
485 const QModelIndexList indizes = selectionModel()->selectedRows();
486 if (indizes.isEmpty())
491 foreach(const QModelIndex &index, indizes) {
492 Error error = model()->data(index, ErrorListModel::ErrorRole).value<Error>();
493 if (!error.suppression().isNull())
498 menu.addAction(m_copyAction);
500 menu.addAction(m_suppressAction);
501 m_suppressAction->setEnabled(!errors.isEmpty());
502 menu.exec(e->globalPos());
505 void MemcheckErrorView::suppressError()
507 SuppressionDialog *dialog = new SuppressionDialog(this);
508 if (dialog->shouldShow()) {
509 dialog->setModal(true);
511 dialog->setAttribute(Qt::WA_DeleteOnClose, true);