cppcheck/gui/resultsview.cpp

604 lines
19 KiB
C++
Raw Normal View History

/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QMessageBox>
2010-11-22 23:37:29 +01:00
#include <QStandardItemModel>
#include <QStandardItem>
#include <QVariant>
#include <QString>
#include <QModelIndex>
#include <QPrinter>
#include <QPrintDialog>
#include <QPrintPreviewDialog>
#include <QSettings>
#include <QDir>
#include <QDate>
#include <QMenu>
#include <QClipboard>
#include "resultsview.h"
#include "common.h"
#include "erroritem.h"
#include "txtreport.h"
#include "xmlreport.h"
#include "xmlreportv2.h"
#include "csvreport.h"
#include "printablereport.h"
2010-11-24 16:39:53 +01:00
#include "applicationlist.h"
#include "checkstatistics.h"
#include "path.h"
#include "codeeditorstyle.h"
ResultsView::ResultsView(QWidget * parent) :
2010-04-15 20:08:51 +02:00
QWidget(parent),
mShowNoErrorsMessage(true),
mStatistics(new CheckStatistics(this))
{
mUI.setupUi(this);
2017-07-31 08:17:13 +02:00
connect(mUI.mTree, &ResultsTree::resultsHidden, this, &ResultsView::resultsHidden);
connect(mUI.mTree, &ResultsTree::checkSelected, this, &ResultsView::checkSelected);
connect(mUI.mTree, &ResultsTree::treeSelectionChanged, this, &ResultsView::updateDetails);
2017-08-11 07:45:29 +02:00
connect(mUI.mTree, &ResultsTree::suppressIds, this, &ResultsView::suppressIds);
connect(mUI.mTree, &ResultsTree::editFunctionContract, this, &ResultsView::editFunctionContract);
connect(this, &ResultsView::showResults, mUI.mTree, &ResultsTree::showResults);
connect(this, &ResultsView::showCppcheckResults, mUI.mTree, &ResultsTree::showCppcheckResults);
connect(this, &ResultsView::showClangResults, mUI.mTree, &ResultsTree::showClangResults);
2017-08-20 15:08:53 +02:00
connect(this, &ResultsView::collapseAllResults, mUI.mTree, &ResultsTree::collapseAll);
connect(this, &ResultsView::expandAllResults, mUI.mTree, &ResultsTree::expandAll);
connect(this, &ResultsView::showHiddenResults, mUI.mTree, &ResultsTree::showHiddenResults);
2020-08-22 11:37:44 +02:00
// Function contracts
connect(mUI.mListAddedContracts, &QListWidget::itemDoubleClicked, this, &ResultsView::contractDoubleClicked);
connect(mUI.mListMissingContracts, &QListWidget::itemDoubleClicked, this, &ResultsView::contractDoubleClicked);
2020-08-22 11:37:44 +02:00
mUI.mListAddedContracts->installEventFilter(this);
// Variable contracts
connect(mUI.mListAddedVariables, &QListWidget::itemDoubleClicked, this, &ResultsView::variableDoubleClicked);
connect(mUI.mListMissingVariables, &QListWidget::itemDoubleClicked, this, &ResultsView::variableDoubleClicked);
connect(mUI.mEditVariablesFilter, &QLineEdit::textChanged, this, &ResultsView::editVariablesFilter);
mUI.mListAddedVariables->installEventFilter(this);
mUI.mListLog->setContextMenuPolicy(Qt::CustomContextMenu);
mUI.mListAddedContracts->setSortingEnabled(true);
mUI.mListMissingContracts->setSortingEnabled(true);
}
2017-07-28 12:10:10 +02:00
void ResultsView::initialize(QSettings *settings, ApplicationList *list, ThreadHandler *checkThreadHandler)
{
mUI.mProgress->setMinimum(0);
mUI.mProgress->setVisible(false);
2019-06-25 15:29:15 +02:00
CodeEditorStyle theStyle(CodeEditorStyle::loadSettings(settings));
mUI.mCode->setStyle(theStyle);
QByteArray state = settings->value(SETTINGS_MAINWND_SPLITTER_STATE).toByteArray();
mUI.mVerticalSplitter->restoreState(state);
mShowNoErrorsMessage = settings->value(SETTINGS_SHOW_NO_ERRORS, true).toBool();
2017-07-28 11:54:20 +02:00
mUI.mTree->initialize(settings, list, checkThreadHandler);
}
ResultsView::~ResultsView()
{
//dtor
}
2020-08-22 11:37:44 +02:00
void ResultsView::setAddedFunctionContracts(const QStringList &addedContracts)
{
mUI.mListAddedContracts->clear();
mUI.mListAddedContracts->addItems(addedContracts);
for (const QString& f: addedContracts) {
auto res = mUI.mListMissingContracts->findItems(f, Qt::MatchExactly);
if (!res.empty())
delete res.front();
}
}
2020-08-22 11:37:44 +02:00
void ResultsView::setAddedVariableContracts(const QStringList &added)
{
mUI.mListAddedVariables->clear();
mUI.mListAddedVariables->addItems(added);
for (const QString& var: added) {
for (auto *item: mUI.mListMissingVariables->findItems(var, Qt::MatchExactly))
2020-08-22 11:37:44 +02:00
delete item;
mVariableContracts.insert(var);
}
}
2017-07-28 12:10:10 +02:00
void ResultsView::clear(bool results)
{
if (results) {
2017-07-28 11:54:20 +02:00
mUI.mTree->clear();
}
2017-08-03 12:39:31 +02:00
mUI.mDetails->setText(QString());
2017-07-28 05:23:25 +02:00
mStatistics->clear();
//Clear the progressbar
mUI.mProgress->setMaximum(PROGRESS_MAX);
mUI.mProgress->setValue(0);
mUI.mProgress->setFormat("%p%");
}
2017-07-28 12:10:10 +02:00
void ResultsView::clear(const QString &filename)
{
2017-07-28 11:54:20 +02:00
mUI.mTree->clear(filename);
}
2017-07-28 12:10:10 +02:00
void ResultsView::clearRecheckFile(const QString &filename)
{
2017-07-28 11:54:20 +02:00
mUI.mTree->clearRecheckFile(filename);
}
2020-08-22 11:37:44 +02:00
void ResultsView::clearContracts()
{
mUI.mListAddedContracts->clear();
mUI.mListAddedVariables->clear();
mUI.mListMissingContracts->clear();
mUI.mListMissingVariables->clear();
mFunctionContracts.clear();
mVariableContracts.clear();
}
void ResultsView::showContracts(bool visible)
{
mUI.mTabFunctionContracts->setVisible(visible);
mUI.mTabVariableContracts->setVisible(visible);
}
2017-07-28 12:10:10 +02:00
void ResultsView::progress(int value, const QString& description)
{
mUI.mProgress->setValue(value);
mUI.mProgress->setFormat(QString("%p% (%1)").arg(description));
}
2017-07-28 12:10:10 +02:00
void ResultsView::error(const ErrorItem &item)
{
2017-07-28 11:54:20 +02:00
if (mUI.mTree->addErrorItem(item)) {
2017-07-28 12:10:10 +02:00
emit gotResults();
2017-08-09 20:53:17 +02:00
mStatistics->addItem(item.tool(), ShowTypes::SeverityToShowType(item.severity));
}
}
2009-03-22 18:39:44 +01:00
2017-07-28 12:10:10 +02:00
void ResultsView::filterResults(const QString& filter)
{
2017-07-28 11:54:20 +02:00
mUI.mTree->filterResults(filter);
}
void ResultsView::saveStatistics(const QString &filename) const
{
QFile f(filename);
if (!f.open(QIODevice::Text | QIODevice::Append))
return;
QTextStream ts(&f);
2017-08-09 20:53:17 +02:00
ts << '[' << QDate::currentDate().toString("dd.MM.yyyy") << "]\n";
2017-08-11 08:08:30 +02:00
ts << QDateTime::currentMSecsSinceEpoch() << '\n';
2017-08-09 20:53:17 +02:00
foreach (QString tool, mStatistics->getTools()) {
ts << tool << "-error:" << mStatistics->getCount(tool, ShowTypes::ShowErrors) << '\n';
ts << tool << "-warning:" << mStatistics->getCount(tool, ShowTypes::ShowWarnings) << '\n';
ts << tool << "-style:" << mStatistics->getCount(tool, ShowTypes::ShowStyle) << '\n';
ts << tool << "-performance:" << mStatistics->getCount(tool, ShowTypes::ShowPerformance) << '\n';
ts << tool << "-portability:" << mStatistics->getCount(tool, ShowTypes::ShowPortability) << '\n';
}
}
void ResultsView::updateFromOldReport(const QString &filename) const
{
mUI.mTree->updateFromOldReport(filename);
}
2017-07-28 12:10:10 +02:00
void ResultsView::save(const QString &filename, Report::Type type) const
{
Report *report = nullptr;
2011-10-13 20:53:06 +02:00
switch (type) {
case Report::CSV:
report = new CsvReport(filename);
break;
case Report::TXT:
report = new TxtReport(filename);
break;
case Report::XMLV2:
report = new XmlReportV2(filename);
break;
}
2011-10-13 20:53:06 +02:00
if (report) {
2017-07-28 11:12:05 +02:00
if (report->create())
2017-07-28 11:54:20 +02:00
mUI.mTree->saveResults(report);
2011-10-13 20:53:06 +02:00
else {
QMessageBox msgBox;
msgBox.setText(tr("Failed to save the report."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
}
delete report;
report = nullptr;
2011-10-13 20:53:06 +02:00
} else {
QMessageBox msgBox;
msgBox.setText(tr("Failed to save the report."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
}
}
2017-07-28 12:10:10 +02:00
void ResultsView::print()
{
QPrinter printer;
QPrintDialog dialog(&printer, this);
dialog.setWindowTitle(tr("Print Report"));
if (dialog.exec() != QDialog::Accepted)
return;
2017-07-28 12:10:10 +02:00
print(&printer);
}
2017-07-28 12:10:10 +02:00
void ResultsView::printPreview()
{
QPrinter printer;
QPrintPreviewDialog dialog(&printer, this);
2017-07-28 13:43:49 +02:00
connect(&dialog, SIGNAL(paintRequested(QPrinter*)), SLOT(print(QPrinter*)));
dialog.exec();
}
2017-07-28 12:10:10 +02:00
void ResultsView::print(QPrinter* printer)
{
2017-07-28 12:10:10 +02:00
if (!hasResults()) {
QMessageBox msgBox;
msgBox.setText(tr("No errors found, nothing to print."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
return;
}
PrintableReport report;
2017-07-28 11:54:20 +02:00
mUI.mTree->saveResults(&report);
2017-07-28 11:12:05 +02:00
QTextDocument doc(report.getFormattedReportText());
doc.print(printer);
}
2017-07-28 12:10:10 +02:00
void ResultsView::updateSettings(bool showFullPath,
bool saveFullPath,
bool saveAllErrors,
bool showNoErrorsMessage,
bool showErrorId,
bool showInconclusive)
{
2017-07-28 11:54:20 +02:00
mUI.mTree->updateSettings(showFullPath, saveFullPath, saveAllErrors, showErrorId, showInconclusive);
mShowNoErrorsMessage = showNoErrorsMessage;
}
2019-06-25 15:29:15 +02:00
void ResultsView::updateStyleSetting(QSettings *settings)
{
2019-06-25 15:29:15 +02:00
CodeEditorStyle theStyle(CodeEditorStyle::loadSettings(settings));
mUI.mCode->setStyle(theStyle);
}
2017-07-28 12:10:10 +02:00
void ResultsView::setCheckDirectory(const QString &dir)
{
2017-07-28 11:54:20 +02:00
mUI.mTree->setCheckDirectory(dir);
}
QString ResultsView::getCheckDirectory()
{
2017-07-28 11:54:20 +02:00
return mUI.mTree->getCheckDirectory();
}
2017-07-28 12:10:10 +02:00
void ResultsView::checkingStarted(int count)
{
mUI.mProgress->setVisible(true);
mUI.mProgress->setMaximum(PROGRESS_MAX);
mUI.mProgress->setValue(0);
mUI.mProgress->setFormat(tr("%p% (%1 of %2 files checked)").arg(0).arg(count));
}
2017-07-28 12:10:10 +02:00
void ResultsView::checkingFinished()
{
mUI.mProgress->setVisible(false);
mUI.mProgress->setFormat("%p%");
// TODO: Items can be mysteriously hidden when checking is finished, this function
// call should be redundant but it "unhides" the wrongly hidden items.
mUI.mTree->refreshTree();
//Should we inform user of non visible/not found errors?
2011-10-13 20:53:06 +02:00
if (mShowNoErrorsMessage) {
//Tell user that we found no errors
2017-07-28 12:10:10 +02:00
if (!hasResults()) {
QMessageBox msg(QMessageBox::Information,
tr("Cppcheck"),
tr("No errors found."),
QMessageBox::Ok,
this);
msg.exec();
} //If we have errors but they aren't visible, tell user about it
2017-07-28 11:54:20 +02:00
else if (!mUI.mTree->hasVisibleResults()) {
QString text = tr("Errors were found, but they are configured to be hidden.\n"\
"To toggle what kind of errors are shown, open view menu.");
QMessageBox msg(QMessageBox::Information,
tr("Cppcheck"),
text,
QMessageBox::Ok,
this);
msg.exec();
}
}
}
2017-07-28 12:10:10 +02:00
bool ResultsView::hasVisibleResults() const
{
2017-07-28 11:54:20 +02:00
return mUI.mTree->hasVisibleResults();
}
2017-07-28 12:10:10 +02:00
bool ResultsView::hasResults() const
{
2017-07-28 11:54:20 +02:00
return mUI.mTree->hasResults();
}
2017-07-28 12:10:10 +02:00
void ResultsView::saveSettings(QSettings *settings)
{
2017-07-28 11:54:20 +02:00
mUI.mTree->saveSettings();
QByteArray state = mUI.mVerticalSplitter->saveState();
settings->setValue(SETTINGS_MAINWND_SPLITTER_STATE, state);
mUI.mVerticalSplitter->restoreState(state);
}
2017-07-28 12:10:10 +02:00
void ResultsView::translate()
{
mUI.retranslateUi(this);
2017-07-28 11:54:20 +02:00
mUI.mTree->translate();
}
2017-07-28 12:10:10 +02:00
void ResultsView::disableProgressbar()
{
mUI.mProgress->setEnabled(false);
}
2017-07-28 12:10:10 +02:00
void ResultsView::readErrorsXml(const QString &filename)
{
const int version = XmlReport::determineVersion(filename);
2011-10-13 20:53:06 +02:00
if (version == 0) {
QMessageBox msgBox;
msgBox.setText(tr("Failed to read the report."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
return;
}
2017-07-29 19:36:01 +02:00
if (version == 1) {
QMessageBox msgBox;
msgBox.setText(tr("XML format version 1 is no longer supported."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
return;
}
XmlReportV2 report(filename);
QList<ErrorItem> errors;
if (report.open()) {
errors = report.read();
} else {
QMessageBox msgBox;
msgBox.setText(tr("Failed to read the report."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
}
ErrorItem item;
foreach (item, errors) {
2017-07-28 11:54:20 +02:00
mUI.mTree->addErrorItem(item);
}
QString dir;
if (!errors.isEmpty() && !errors[0].errorPath.isEmpty()) {
QString relativePath = QFileInfo(filename).canonicalPath();
if (QFileInfo(relativePath + '/' + errors[0].errorPath[0].file).exists())
dir = relativePath;
}
mUI.mTree->setCheckDirectory(dir);
}
2017-07-28 12:10:10 +02:00
void ResultsView::updateDetails(const QModelIndex &index)
{
QStandardItemModel *model = qobject_cast<QStandardItemModel*>(mUI.mTree->model());
QStandardItem *item = model->itemFromIndex(index);
2011-10-13 20:53:06 +02:00
if (!item) {
mUI.mCode->clear();
2017-08-03 12:39:31 +02:00
mUI.mDetails->setText(QString());
return;
}
// Make sure we are working with the first column
if (item->parent() && item->column() != 0)
item = item->parent()->child(item->row(), 0);
QVariantMap data = item->data().toMap();
// If there is no severity data then it is a parent item without summary and message
2011-10-13 20:53:06 +02:00
if (!data.contains("severity")) {
mUI.mCode->clear();
2017-08-03 12:39:31 +02:00
mUI.mDetails->setText(QString());
return;
}
const QString message = data["message"].toString();
2018-08-07 10:44:25 +02:00
QString formattedMsg = message;
const QString file0 = data["file0"].toString();
2017-08-03 12:39:31 +02:00
if (!file0.isEmpty() && Path::isHeader(data["file"].toString().toStdString()))
formattedMsg += QString("\n\n%1: %2").arg(tr("First included by")).arg(QDir::toNativeSeparators(file0));
if (data["cwe"].toInt() > 0)
formattedMsg.prepend("CWE: " + QString::number(data["cwe"].toInt()) + "\n");
2017-07-28 11:54:20 +02:00
if (mUI.mTree->showIdColumn())
formattedMsg.prepend(tr("Id") + ": " + data["id"].toString() + "\n");
if (data["incomplete"].toBool())
formattedMsg += "\n" + tr("Bug hunting analysis is incomplete");
mUI.mDetails->setText(formattedMsg);
const int lineNumber = data["line"].toInt();
QString filepath = data["file"].toString();
if (!QFileInfo(filepath).exists() && QFileInfo(mUI.mTree->getCheckDirectory() + '/' + filepath).exists())
filepath = mUI.mTree->getCheckDirectory() + '/' + filepath;
QStringList symbols;
if (data.contains("symbolNames"))
symbols = data["symbolNames"].toString().split("\n");
2018-02-18 12:06:54 +01:00
2020-07-19 11:10:53 +02:00
if (filepath == mUI.mCode->getFileName()) {
mUI.mCode->setError(lineNumber, symbols);
return;
}
QFile file(filepath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
mUI.mCode->clear();
return;
}
QTextStream in(&file);
mUI.mCode->setError(in.readAll(), lineNumber, symbols);
mUI.mCode->setFileName(filepath);
}
void ResultsView::log(const QString &str)
{
mUI.mListLog->addItem(str);
}
void ResultsView::debugError(const ErrorItem &item)
{
2020-07-15 07:59:05 +02:00
mUI.mListLog->addItem(item.toString());
}
void ResultsView::bughuntingReportLine(const QString& line)
2020-02-10 20:24:36 +01:00
{
for (const QString& s: line.split("\n")) {
2020-08-22 11:37:44 +02:00
if (s.startsWith("[intvar] ")) {
const QString varname = s.mid(9);
if (!mVariableContracts.contains(varname)) {
mVariableContracts.insert(varname);
mUI.mListMissingVariables->addItem(varname);
}
} else if (s.startsWith("[missing contract] ")) {
const QString functionName = s.mid(19);
2020-08-22 11:37:44 +02:00
if (!mFunctionContracts.contains(functionName)) {
mFunctionContracts.insert(functionName);
mUI.mListMissingContracts->addItem(functionName);
}
}
2020-02-10 21:07:14 +01:00
}
2020-02-10 20:24:36 +01:00
}
void ResultsView::logClear()
{
mUI.mListLog->clear();
}
void ResultsView::logCopyEntry()
{
const QListWidgetItem * item = mUI.mListLog->currentItem();
2017-12-08 09:16:34 +01:00
if (nullptr != item) {
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(item->text());
}
}
void ResultsView::logCopyComplete()
{
QString logText;
2017-12-08 09:16:34 +01:00
for (int i=0; i < mUI.mListLog->count(); ++i) {
const QListWidgetItem * item = mUI.mListLog->item(i);
2017-12-08 09:16:34 +01:00
if (nullptr != item) {
logText += item->text();
}
}
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(logText);
}
void ResultsView::contractDoubleClicked(QListWidgetItem* item)
{
emit editFunctionContract(item->text());
}
2020-08-22 11:37:44 +02:00
void ResultsView::variableDoubleClicked(QListWidgetItem* item)
{
emit editVariableContract(item->text());
}
void ResultsView::editVariablesFilter(const QString &text)
{
for (auto *item: mUI.mListAddedVariables->findItems(".*", Qt::MatchRegExp)) {
2020-08-22 11:37:44 +02:00
QString varname = item->text().mid(0, item->text().indexOf(" "));
item->setHidden(!varname.contains(text));
}
for (auto *item: mUI.mListMissingVariables->findItems(".*", Qt::MatchRegExp))
2020-08-26 10:15:09 +02:00
item->setHidden(!item->text().contains(text));
2020-08-22 11:37:44 +02:00
}
void ResultsView::on_mListLog_customContextMenuRequested(const QPoint &pos)
{
2018-02-20 14:32:07 +01:00
if (mUI.mListLog->count() <= 0)
return;
2018-02-20 14:32:07 +01:00
const QPoint globalPos = mUI.mListLog->mapToGlobal(pos);
2018-02-20 14:32:07 +01:00
QMenu contextMenu;
contextMenu.addAction(tr("Clear Log"), this, SLOT(logClear()));
contextMenu.addAction(tr("Copy this Log entry"), this, SLOT(logCopyEntry()));
contextMenu.addAction(tr("Copy complete Log"), this, SLOT(logCopyComplete()));
contextMenu.exec(globalPos);
}
2020-08-22 11:37:44 +02:00
bool ResultsView::eventFilter(QObject *target, QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
if (target == mUI.mListAddedVariables) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Delete) {
for (auto *i: mUI.mListAddedVariables->selectedItems()) {
2020-08-22 11:37:44 +02:00
emit deleteVariableContract(i->text().mid(0, i->text().indexOf(" ")));
delete i;
}
return true;
}
}
if (target == mUI.mListAddedContracts) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Delete) {
for (auto *i: mUI.mListAddedContracts->selectedItems()) {
2020-08-22 11:37:44 +02:00
emit deleteFunctionContract(i->text());
delete i;
}
return true;
}
}
}
return QObject::eventFilter(target, event);
}