OSDN Git Service

Update license.
[qt-creator-jp/qt-creator-jp.git] / src / plugins / memcheck / memcheckerrorview.cpp
1 /**************************************************************************
2 **
3 ** This file is part of Qt Creator
4 **
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6 **
7 ** Author: Andreas Hartmetz, KDAB (andreas.hartmetz@kdab.com)
8 **
9 ** Contact: Nokia Corporation (info@qt.nokia.com)
10 **
11 **
12 ** GNU Lesser General Public License Usage
13 **
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.
20 **
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.
24 **
25 ** Other Usage
26 **
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.
29 **
30 ** If you have questions regarding the use of this file, please contact
31 ** Nokia at qt-info@nokia.com.
32 **
33 **************************************************************************/
34
35 #include "memcheckerrorview.h"
36
37 #include "suppressiondialog.h"
38
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>
45
46 #include <valgrindtoolbase/valgrindsettings.h>
47
48 #include <texteditor/basetexteditor.h>
49
50 #include <projectexplorer/projectexplorer.h>
51 #include <projectexplorer/project.h>
52 #include <coreplugin/coreconstants.h>
53
54 #include <utils/qtcassert.h>
55
56 #include <QtCore/QDir>
57 #include <QtCore/QDebug>
58
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>
69
70 using namespace Analyzer;
71 using namespace Analyzer::Internal;
72 using namespace Valgrind::XmlProtocol;
73
74 MemcheckErrorDelegate::MemcheckErrorDelegate(QListView *parent)
75     : QStyledItemDelegate(parent),
76       m_detailsWidget(0)
77 {
78     connect(parent->verticalScrollBar(), SIGNAL(valueChanged(int)),
79             SLOT(verticalScrolled()));
80 }
81
82 MemcheckErrorDelegate::~MemcheckErrorDelegate()
83 {
84 }
85
86 QSize MemcheckErrorDelegate::sizeHint(const QStyleOptionViewItem &opt, const QModelIndex &index) const
87 {
88     const QListView *view = qobject_cast<const QListView *>(parent());
89     const int viewportWidth = view->viewport()->width();
90     const bool isSelected = view->selectionModel()->currentIndex() == index;
91
92     int dy = 2 * s_itemMargin;
93
94     if (!isSelected) {
95         QFontMetrics fm(opt.font);
96         return QSize(viewportWidth, fm.height() + dy);
97     }
98
99     if (m_detailsWidget && m_detailsIndex != index) {
100         m_detailsWidget->deleteLater();
101         m_detailsWidget = 0;
102     }
103
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;
109     } else {
110         QTC_ASSERT(m_detailsIndex == index, qt_noop());
111     }
112     const int widthExcludingMargins = viewportWidth - 2 * s_itemMargin;
113     m_detailsWidget->setFixedWidth(widthExcludingMargins);
114
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
117     //       it would have.
118     m_detailsWidget->setFixedHeight(m_detailsWidgetHeight);
119     return QSize(viewportWidth, dy + m_detailsWidget->heightForWidth(widthExcludingMargins));
120 }
121
122 static QString makeFrameName(const Frame &frame, const QString &relativeTo,
123                              bool link = true, const QString &linkAttr = QString())
124 {
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;
129
130     QString path;
131     if (!d.isEmpty() && !f.isEmpty())
132         path = fullPath;
133     else
134         path = frame.object();
135
136     if (QFile::exists(path))
137         path = QFileInfo(path).canonicalFilePath();
138
139     if (path.startsWith(relativeTo))
140         path.remove(0, relativeTo.length());
141
142     if (frame.line() != -1)
143         path += QLatin1Char(':') + QString::number(frame.line());
144
145     path = Qt::escape(path);
146
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);
151     }
152
153     if (!fn.isEmpty())
154         return QCoreApplication::translate("Analyzer::Internal", "%1 in %2").arg(Qt::escape(fn), path);
155     else if (!path.isEmpty())
156         return path;
157     else
158         return QString("0x%1").arg(frame.instructionPointer(), 0, 16);
159 }
160
161 QString relativeToPath()
162 {
163     // project for which we insert the snippet
164     const ProjectExplorer::Project *project =
165             ProjectExplorer::ProjectExplorerPlugin::instance()->startupProject();
166
167     QString relativeTo( project ? project->projectDirectory() : QDir::homePath() );
168     if (!relativeTo.endsWith(QDir::separator()))
169         relativeTo.append(QDir::separator());
170
171     return relativeTo;
172 }
173
174 QString errorLocation(const QModelIndex &index, const Error &error,
175                       bool link = false, const QString &linkAttr = QString())
176 {
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());
182     };
183     QTC_ASSERT(model, return QString());
184
185     return QCoreApplication::translate("Analyzer::Internal", "in %1").
186             arg(makeFrameName(model->findRelevantFrame(error), relativeToPath(),
187                               link, linkAttr));
188 }
189
190 QWidget *MemcheckErrorDelegate::createDetailsWidget(const QModelIndex &errorIndex, QWidget *parent) const
191 {
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");
198
199     QString relativeTo = relativeToPath();
200
201     const Error error = errorIndex.data(ErrorListModel::ErrorRole).value<Error>();
202
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&nbsp;&nbsp;<span %4>%2</span>")
215                             .arg(error.what(), errorLocation(errorIndex, error, true, linkStyle),
216                                  linkStyle));
217     connect(errorLabel, SIGNAL(linkActivated(QString)), SLOT(openLinkInEditor(QString)));
218     layout->addWidget(errorLabel);
219
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
224         if (i > 0) {
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);
234         }
235         int frameNr = 1;
236         foreach (const Frame &frame, stack.frames()) {
237             QString frameName = makeFrameName(frame, relativeTo);
238             QTC_ASSERT(!frameName.isEmpty(), qt_noop());
239
240             QLabel *frameLabel = new QLabel(widget);
241             frameLabel->setAutoFillBackground(true);
242             if (frameNr % 2 == 0) {
243                 // alternating rows
244                 QPalette p = frameLabel->palette();
245                 p.setBrush(QPalette::Base, p.alternateBase());
246                 frameLabel->setPalette(p);
247             }
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);
254
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);
261         }
262     }
263
264     layout->setContentsMargins(0, 0, 0, 0);
265     layout->setSpacing(0);
266     widget->setLayout(layout);
267     return widget;
268 }
269
270 void MemcheckErrorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &basicOption,
271                                   const QModelIndex &index) const
272 {
273     QStyleOptionViewItemV4 opt(basicOption);
274     initStyleOption(&opt, index);
275
276     const QListView *const view = qobject_cast<const QListView *>(parent());
277     const bool isSelected = view->selectionModel()->currentIndex() == index;
278
279     QFontMetrics fm(opt.font);
280     QPoint pos = opt.rect.topLeft();
281
282     painter->save();
283
284     const QColor bgColor = isSelected ? opt.palette.highlight().color() : opt.palette.background().color();
285     painter->setBrush(bgColor);
286
287     // clear background
288     painter->setPen(Qt::NoPen);
289     painter->drawRect(opt.rect);
290
291     pos.rx() += s_itemMargin;
292     pos.ry() += s_itemMargin;
293
294     const Error error = index.data(ErrorListModel::ErrorRole).value<Error>();
295
296     if (isSelected) {
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();
305
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());
310     } else {
311         // the reference coordinate for text drawing is the text baseline; move it inside the view rect.
312         pos.ry() += fm.ascent();
313
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);
319
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);
324         if (widthLeft > 0) {
325             QFont monospace = opt.font;
326             monospace.setFamily("monospace");
327             QFontMetrics metrics(monospace);
328             QColor nameColor = textColor;
329             nameColor.setAlphaF(0.7);
330
331             painter->setFont(monospace);
332             painter->setPen(nameColor);
333
334             QPoint namePos = pos;
335             namePos.rx() += whatWidth + space;
336             painter->drawText(namePos, metrics.elidedText(name, Qt::ElideLeft, widthLeft));
337         }
338     }
339
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());
343
344     painter->restore();
345 }
346
347 void MemcheckErrorDelegate::currentChanged(const QModelIndex &now, const QModelIndex &previous)
348 {
349     if (m_detailsWidget) {
350         m_detailsWidget->deleteLater();
351         m_detailsWidget = 0;
352     }
353
354     m_detailsIndex = QModelIndex();
355     if (now.isValid())
356         emit sizeHintChanged(now);
357     if (previous.isValid())
358         emit sizeHintChanged(previous);
359 }
360
361 void MemcheckErrorDelegate::layoutChanged()
362 {
363     if (m_detailsWidget) {
364         m_detailsWidget->deleteLater();
365         m_detailsWidget = 0;
366         m_detailsIndex = QModelIndex();
367     }
368 }
369
370 void MemcheckErrorDelegate::viewResized()
371 {
372     const QListView *view = qobject_cast<const QListView *>(parent());
373     if (m_detailsWidget)
374         emit sizeHintChanged(view->selectionModel()->currentIndex());
375 }
376
377 void MemcheckErrorDelegate::verticalScrolled()
378 {
379     if (m_detailsWidget)
380         m_detailsWidget->hide();
381 }
382
383 void MemcheckErrorDelegate::copy()
384 {
385     QTC_ASSERT(m_detailsIndex.isValid(), return);
386
387     QString content;
388     QTextStream stream(&content);
389     const Error error = m_detailsIndex.data(ErrorListModel::ErrorRole).value<Error>();
390
391     stream << error.what() << "\n";
392     stream << "  " << errorLocation(m_detailsIndex, error) << "\n";
393
394     const QString relativeTo = relativeToPath();
395
396     foreach(const Stack &stack, error.stacks()) {
397         if (!stack.auxWhat().isEmpty()) {
398             stream << stack.auxWhat();
399         }
400         int i = 1;
401         foreach(const Frame &frame, stack.frames()) {
402             stream << "  " << i++ << ": " << makeFrameName(frame, relativeTo) << "\n";
403         }
404     }
405
406     stream.flush();
407     QApplication::clipboard()->setText(content);
408 }
409
410 void MemcheckErrorDelegate::openLinkInEditor(const QString &link)
411 {
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));
417 }
418
419 MemcheckErrorView::MemcheckErrorView(QWidget *parent)
420     : QListView(parent),
421       m_settings(0)
422 {
423     setItemDelegate(new MemcheckErrorDelegate(this));
424     connect(this, SIGNAL(resized()), itemDelegate(), SLOT(viewResized()));
425
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);
433
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);
441 }
442
443 MemcheckErrorView::~MemcheckErrorView()
444 {
445     itemDelegate()->deleteLater();
446 }
447
448 void MemcheckErrorView::setModel(QAbstractItemModel *model)
449 {
450     QListView::setModel(model);
451     connect(selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)),
452             itemDelegate(), SLOT(currentChanged(QModelIndex, QModelIndex)));
453
454     connect(model, SIGNAL(layoutChanged()),
455             itemDelegate(), SLOT(layoutChanged()));
456 }
457
458 void MemcheckErrorView::resizeEvent(QResizeEvent *e)
459 {
460     emit resized();
461     QListView::resizeEvent(e);
462 }
463
464 void MemcheckErrorView::setDefaultSuppressionFile(const QString &suppFile)
465 {
466     m_defaultSuppFile = suppFile;
467 }
468
469 QString MemcheckErrorView::defaultSuppressionFile() const
470 {
471     return m_defaultSuppFile;
472 }
473
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)
477 {
478     QTC_ASSERT(settings, return);
479
480     m_settings = settings;
481 }
482
483 void MemcheckErrorView::contextMenuEvent(QContextMenuEvent *e)
484 {
485     const QModelIndexList indizes = selectionModel()->selectedRows();
486     if (indizes.isEmpty())
487         return;
488
489
490     QList<Error> errors;
491     foreach(const QModelIndex &index, indizes) {
492         Error error = model()->data(index, ErrorListModel::ErrorRole).value<Error>();
493         if (!error.suppression().isNull())
494             errors << error;
495     }
496
497     QMenu menu;
498     menu.addAction(m_copyAction);
499     menu.addSeparator();
500     menu.addAction(m_suppressAction);
501     m_suppressAction->setEnabled(!errors.isEmpty());
502     menu.exec(e->globalPos());
503 }
504
505 void MemcheckErrorView::suppressError()
506 {
507     SuppressionDialog *dialog = new SuppressionDialog(this);
508     if (dialog->shouldShow()) {
509         dialog->setModal(true);
510         dialog->show();
511         dialog->setAttribute(Qt::WA_DeleteOnClose, true);
512     } else {
513         delete dialog;
514     }
515 }