File: resultsview.cpp

package info (click to toggle)
cppcheck 2.18.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,132 kB
  • sloc: cpp: 268,935; python: 20,890; ansic: 8,090; sh: 1,045; makefile: 1,008; xml: 1,005; cs: 291
file content (591 lines) | stat: -rw-r--r-- 17,871 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
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
250
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
/*
 * Cppcheck - A tool for static C/C++ code analysis
 * Copyright (C) 2007-2025 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 "resultsview.h"

#include "checkstatistics.h"
#include "checkersreport.h"
#include "codeeditor.h"
#include "codeeditorstyle.h"
#include "common.h"
#include "csvreport.h"
#include "erroritem.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "path.h"
#include "printablereport.h"
#include "resultstree.h"
#include "settings.h"
#include "txtreport.h"
#include "xmlreport.h"
#include "xmlreportv2.h"

#include "ui_resultsview.h"

#include <set>
#include <string>

#include <QAbstractItemModel>
#include <QApplication>
#include <QByteArray>
#include <QClipboard>
#include <QDate>
#include <QDateTime>
#include <QDialog>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QIODevice>
#include <QLabel>
#include <QList>
#include <QListWidget>
#include <QListWidgetItem>
#include <QMenu>
#include <QMessageBox>
#include <QPoint>
#include <QPrintDialog>
#include <QPrintPreviewDialog>
#include <QPrinter>
#include <QProgressBar>
#include <QSettings>
#include <QSplitter>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QTextDocument>
#include <QTextEdit>
#include <QTextStream>
#include <QVariant>
#include <QVariantMap>
#include <Qt>

enum class ReportType : std::uint8_t;

ResultsView::ResultsView(QWidget * parent) :
    QWidget(parent),
    mUI(new Ui::ResultsView),
    mStatistics(new CheckStatistics(this))
{
    mUI->setupUi(this);

    connect(mUI->mTree, &ResultsTree::resultsHidden, this, &ResultsView::resultsHidden);
    connect(mUI->mTree, &ResultsTree::checkSelected, this, &ResultsView::checkSelected);
    connect(mUI->mTree, &ResultsTree::treeSelectionChanged, this, &ResultsView::updateDetails);
    connect(mUI->mTree, &ResultsTree::suppressIds, this, &ResultsView::suppressIds);
    connect(this, &ResultsView::showResults, mUI->mTree, &ResultsTree::showResults);
    connect(this, &ResultsView::showCppcheckResults, mUI->mTree, &ResultsTree::showCppcheckResults);
    connect(this, &ResultsView::showClangResults, mUI->mTree, &ResultsTree::showClangResults);
    connect(this, &ResultsView::collapseAllResults, mUI->mTree, &ResultsTree::collapseAll);
    connect(this, &ResultsView::expandAllResults, mUI->mTree, &ResultsTree::expandAll);
    connect(this, &ResultsView::showHiddenResults, mUI->mTree, &ResultsTree::showHiddenResults);

    mUI->mListLog->setContextMenuPolicy(Qt::CustomContextMenu);
}

void ResultsView::initialize(QSettings *settings, ApplicationList *list, ThreadHandler *checkThreadHandler)
{
    mUI->mProgress->setMinimum(0);
    mUI->mProgress->setVisible(false);
    mUI->mLabelCriticalErrors->setVisible(false);

    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();

    mUI->mTree->initialize(settings, list, checkThreadHandler);
}

ResultsView::~ResultsView()
{
    delete mUI;
    delete mCheckSettings;
}

void ResultsView::clear(bool results)
{
    if (results) {
        mUI->mTree->clear();
    }

    mUI->mDetails->setText(QString());

    mStatistics->clear();
    delete mCheckSettings;
    mCheckSettings = nullptr;

    //Clear the progressbar
    mUI->mProgress->setMaximum(PROGRESS_MAX);
    mUI->mProgress->setValue(0);
    mUI->mProgress->setFormat("%p%");

    mUI->mLabelCriticalErrors->setVisible(false);

    mSuccess = false;
}

void ResultsView::clear(const QString &filename)
{
    mUI->mTree->clear(filename);
}

void ResultsView::clearRecheckFile(const QString &filename)
{
    mUI->mTree->clearRecheckFile(filename);
}

const ShowTypes & ResultsView::getShowTypes() const
{
    return mUI->mTree->mShowSeverities;
}

void ResultsView::setReportType(ReportType reportType) {
    mUI->mTree->setReportType(reportType);
}

void ResultsView::progress(int value, const QString& description)
{
    mUI->mProgress->setValue(value);
    mUI->mProgress->setFormat(QString("%p% (%1)").arg(description));
}

void ResultsView::error(const ErrorItem &item)
{
    if (item.severity == Severity::internal && (item.errorId == "logChecker" || item.errorId.endsWith("-logChecker"))) {
        mStatistics->addChecker(item.message);
        return;
    }

    handleCriticalError(item);

    if (item.severity == Severity::internal)
        return;

    if (mUI->mTree->addErrorItem(item)) {
        emit gotResults();
        mStatistics->addItem(item.tool(), ShowTypes::SeverityToShowType(item.severity));
    }
}

void ResultsView::filterResults(const QString& filter)
{
    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);
    ts <<  '[' << QDate::currentDate().toString("dd.MM.yyyy") << "]\n";
    ts << QDateTime::currentMSecsSinceEpoch() << '\n';
    for (const 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);
}

void ResultsView::save(const QString &filename, Report::Type type, const QString& productName) const
{
    Report *report = nullptr;

    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, productName);
        break;
    }

    if (report) {
        if (report->create())
            mUI->mTree->saveResults(report);
        else {
            QMessageBox msgBox;
            msgBox.setText(tr("Failed to save the report."));
            msgBox.setIcon(QMessageBox::Critical);
            msgBox.exec();
        }
        delete report;
        report = nullptr;
    } else {
        QMessageBox msgBox;
        msgBox.setText(tr("Failed to save the report."));
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.exec();
    }
}

void ResultsView::print()
{
    QPrinter printer;
    QPrintDialog dialog(&printer, this);
    dialog.setWindowTitle(tr("Print Report"));
    if (dialog.exec() != QDialog::Accepted)
        return;

    print(&printer);
}

void ResultsView::printPreview()
{
    QPrinter printer;
    QPrintPreviewDialog dialog(&printer, this);
    connect(&dialog, SIGNAL(paintRequested(QPrinter*)), SLOT(print(QPrinter*)));
    dialog.exec();
}

void ResultsView::print(QPrinter* printer) const
{
    if (!hasResults()) {
        QMessageBox msgBox;
        msgBox.setText(tr("No errors found, nothing to print."));
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.exec();
        return;
    }

    PrintableReport report;
    mUI->mTree->saveResults(&report);
    QTextDocument doc(report.getFormattedReportText());
    doc.print(printer);
}

void ResultsView::updateSettings(bool showFullPath,
                                 bool saveFullPath,
                                 bool saveAllErrors,
                                 bool showNoErrorsMessage,
                                 bool showErrorId,
                                 bool showInconclusive)
{
    mUI->mTree->updateSettings(showFullPath, saveFullPath, saveAllErrors, showErrorId, showInconclusive);
    mShowNoErrorsMessage = showNoErrorsMessage;
}

void ResultsView::updateStyleSetting(QSettings *settings)
{
    CodeEditorStyle theStyle(CodeEditorStyle::loadSettings(settings));
    mUI->mCode->setStyle(theStyle);
}

void ResultsView::setCheckDirectory(const QString &dir)
{
    mUI->mTree->setCheckDirectory(dir);
}

QString ResultsView::getCheckDirectory() const
{
    return mUI->mTree->getCheckDirectory();
}

void ResultsView::setCheckSettings(const Settings &settings)
{
    delete mCheckSettings;
    mCheckSettings = new Settings;
    *mCheckSettings = settings;
}

void ResultsView::checkingStarted(int count)
{
    mSuccess = true;
    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));
}

void ResultsView::checkingFinished()
{
    mUI->mProgress->setVisible(false);
    mUI->mProgress->setFormat("%p%");

    {
        Settings checkSettings;
        const std::set<std::string> activeCheckers = mStatistics->getActiveCheckers();
        CheckersReport checkersReport(mCheckSettings ? *mCheckSettings : checkSettings, activeCheckers);
        mStatistics->setCheckersReport(QString::fromStdString(checkersReport.getReport(mCriticalErrors.toStdString())));
    }

    // 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?
    if (mShowNoErrorsMessage) {
        //Tell user that we found no errors
        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
        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();
        }
    }
}

bool ResultsView::hasVisibleResults() const
{
    return mUI->mTree->hasVisibleResults();
}

bool ResultsView::hasResults() const
{
    return mUI->mTree->hasResults();
}

void ResultsView::saveSettings(QSettings *settings)
{
    mUI->mTree->saveSettings();
    QByteArray state = mUI->mVerticalSplitter->saveState();
    settings->setValue(SETTINGS_MAINWND_SPLITTER_STATE, state);
    mUI->mVerticalSplitter->restoreState(state);
}

void ResultsView::translate()
{
    mUI->retranslateUi(this);
    mUI->mTree->translate();
}

void ResultsView::disableProgressbar()
{
    mUI->mProgress->setEnabled(false);
}

void ResultsView::readErrorsXml(const QString &filename)
{
    mSuccess = false; // Don't know if results come from an aborted analysis

    const int version = XmlReport::determineVersion(filename);
    if (version == 0) {
        QMessageBox msgBox;
        msgBox.setText(tr("Failed to read the report."));
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.exec();
        return;
    }
    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, QString());
    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();
    }

    for (const ErrorItem& item : errors) {
        handleCriticalError(item);
        mUI->mTree->addErrorItem(item);
    }

    QString dir;
    if (!errors.isEmpty() && !errors[0].errorPath.isEmpty()) {
        QString relativePath = QFileInfo(filename).canonicalPath();
        if (QFileInfo::exists(relativePath + '/' + errors[0].errorPath[0].file))
            dir = relativePath;
    }

    mUI->mTree->setCheckDirectory(dir);
}

void ResultsView::updateDetails(const QModelIndex &index)
{
    const auto *model = qobject_cast<const QStandardItemModel*>(mUI->mTree->model());
    QStandardItem *item = model->itemFromIndex(index);

    if (!item) {
        mUI->mCode->clear();
        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 itemdata = item->data().toMap();

    // If there is no severity data then it is a parent item without summary and message
    if (!itemdata.contains("severity")) {
        mUI->mCode->clear();
        mUI->mDetails->setText(QString());
        return;
    }

    const QString message = itemdata["message"].toString();
    QString formattedMsg = message;

    const QString file0 = itemdata["file0"].toString();
    if (!file0.isEmpty() && Path::isHeader(itemdata["file"].toString().toStdString()))
        formattedMsg += QString("\n\n%1: %2").arg(tr("First included by")).arg(QDir::toNativeSeparators(file0));

    if (itemdata["cwe"].toInt() > 0)
        formattedMsg.prepend("CWE: " + QString::number(itemdata["cwe"].toInt()) + "\n");
    if (mUI->mTree->showIdColumn())
        formattedMsg.prepend(tr("Id") + ": " + itemdata["id"].toString() + "\n");
    if (itemdata["incomplete"].toBool())
        formattedMsg += "\n" + tr("Bug hunting analysis is incomplete");
    mUI->mDetails->setText(formattedMsg);

    const int lineNumber = itemdata["line"].toInt();

    QString filepath = itemdata["file"].toString();
    if (!QFileInfo::exists(filepath) && QFileInfo::exists(mUI->mTree->getCheckDirectory() + '/' + filepath))
        filepath = mUI->mTree->getCheckDirectory() + '/' + filepath;

    QStringList symbols;
    if (itemdata.contains("symbolNames"))
        symbols = itemdata["symbolNames"].toString().split("\n");

    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)
{
    mUI->mListLog->addItem(item.toString());
}

void ResultsView::logClear()
{
    mUI->mListLog->clear();
}

void ResultsView::logCopyEntry()
{
    const QListWidgetItem * item = mUI->mListLog->currentItem();
    if (nullptr != item) {
        QClipboard *clipboard = QApplication::clipboard();
        clipboard->setText(item->text());
    }
}

void ResultsView::logCopyComplete()
{
    QString logText;
    for (int i=0; i < mUI->mListLog->count(); ++i) {
        const QListWidgetItem * item = mUI->mListLog->item(i);
        if (nullptr != item) {
            logText += item->text();
        }
    }
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(logText);
}

void ResultsView::on_mListLog_customContextMenuRequested(const QPoint &pos)
{
    if (mUI->mListLog->count() <= 0)
        return;

    const QPoint globalPos = mUI->mListLog->mapToGlobal(pos);

    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);
}

void ResultsView::stopAnalysis()
{
    mSuccess = false;
    mUI->mLabelCriticalErrors->setText(tr("Analysis was stopped"));
    mUI->mLabelCriticalErrors->setVisible(true);
}

void ResultsView::handleCriticalError(const ErrorItem &item)
{
    if (ErrorLogger::isCriticalErrorId(item.errorId.toStdString())) {
        if (!mCriticalErrors.contains(item.errorId)) {
            if (!mCriticalErrors.isEmpty())
                mCriticalErrors += ",";
            mCriticalErrors += item.errorId;
            if (item.severity == Severity::internal)
                mCriticalErrors += " (suppressed)";
        }
        QString msg = tr("There was a critical error with id '%1'").arg(item.errorId);
        if (!item.file0.isEmpty())
            msg += ", " + tr("when checking %1").arg(item.file0);
        else
            msg += ", " + tr("when checking a file");
        msg += ". " + tr("Analysis was aborted.");
        mUI->mLabelCriticalErrors->setText(msg);
        mUI->mLabelCriticalErrors->setVisible(true);
        mSuccess = false;
    }
}

bool ResultsView::isSuccess() const {
    return mSuccess;
}