File: resultstree.cpp

package info (click to toggle)
cppcheck 2.17.1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 25,384 kB
  • sloc: cpp: 263,341; python: 19,737; ansic: 7,953; sh: 1,018; makefile: 996; xml: 994; cs: 291
file content (1542 lines) | stat: -rw-r--r-- 52,071 bytes parent folder | download
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
/*
 * 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 "resultstree.h"

#include "application.h"
#include "applicationlist.h"
#include "checkers.h"
#include "common.h"
#include "erroritem.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "path.h"
#include "projectfile.h"
#include "report.h"
#include "showtypes.h"
#include "suppressions.h"
#include "threadhandler.h"
#include "xmlreportv2.h"

#include <algorithm>
#include <utility>

#include <QAction>
#include <QApplication>
#include <QClipboard>
#include <QContextMenuEvent>
#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QFileInfo>
#include <QFileDialog>
#include <QIcon>
#include <QItemSelectionModel>
#include <QKeyEvent>
#include <QList>
#include <QLocale>
#include <QMap>
#include <QMenu>
#include <QMessageBox>
#include <QModelIndex>
#include <QObject>
#include <QProcess>
#include <QSet>
#include <QSettings>
#include <QSignalMapper>
#include <QStandardItem>
#include <QUrl>
#include <QVariant>
#include <QVariantMap>
#include <Qt>

static constexpr char COLUMN[] = "column";
static constexpr char CWE[] = "cwe";
static constexpr char ERRORID[] = "id";
static constexpr char FILENAME[] = "file";
static constexpr char FILE0[] = "file0";
static constexpr char HASH[] = "hash";
static constexpr char HIDE[] = "hide";
static constexpr char INCONCLUSIVE[] = "inconclusive";
static constexpr char LINE[] = "line";
static constexpr char MESSAGE[] = "message";
static constexpr char REMARK[] = "remark";
static constexpr char SEVERITY[] = "severity";
static constexpr char SINCEDATE[] = "sinceDate";
static constexpr char SYMBOLNAMES[] = "symbolNames";
static constexpr char SUMMARY[] = "summary";
static constexpr char TAGS[] = "tags";

// These must match column headers given in ResultsTree::translate()
static constexpr int COLUMN_FILE                  = 0;
static constexpr int COLUMN_LINE                  = 1;
static constexpr int COLUMN_SEVERITY              = 2;
static constexpr int COLUMN_MISRA_CLASSIFICATION  = 3;
static constexpr int COLUMN_CERT_LEVEL            = 4;
static constexpr int COLUMN_INCONCLUSIVE          = 5;
static constexpr int COLUMN_SUMMARY               = 6;
static constexpr int COLUMN_ID                    = 7;
static constexpr int COLUMN_MISRA_GUIDELINE       = 8;
static constexpr int COLUMN_CERT_RULE             = 9;
static constexpr int COLUMN_SINCE_DATE            = 10;
static constexpr int COLUMN_TAGS                  = 11;
static constexpr int COLUMN_CWE                   = 12;

static QString getGuideline(ReportType reportType, const std::map<std::string, std::string> &guidelineMapping,
                            const QString& errorId, Severity severity) {
    return QString::fromStdString(getGuideline(errorId.toStdString(),
                                               reportType, guidelineMapping,
                                               severity));
}

static QString getClassification(ReportType reportType, const QString& guideline) {
    return QString::fromStdString(getClassification(guideline.toStdString(), reportType));
}

static Severity getSeverityFromClassification(const QString &c) {
    if (c == checkers::Man)
        return Severity::error;
    if (c == checkers::Req)
        return Severity::warning;
    if (c == checkers::Adv)
        return Severity::style;
    if (c == checkers::Doc)
        return Severity::information;
    if (c == "L1")
        return Severity::error;
    if (c == "L2")
        return Severity::warning;
    if (c == "L3")
        return Severity::style;
    return Severity::none;
}

static QStringList getLabels() {
    return QStringList{
        QObject::tr("File"),
        QObject::tr("Line"),
        QObject::tr("Severity"),
        QObject::tr("Classification"),
        QObject::tr("Level"),
        QObject::tr("Inconclusive"),
        QObject::tr("Summary"),
        QObject::tr("Id"),
        QObject::tr("Guideline"),
        QObject::tr("Rule"),
        QObject::tr("Since date"),
        QObject::tr("Tags"),
        QObject::tr("CWE")};
}

ResultsTree::ResultsTree(QWidget * parent) :
    QTreeView(parent)
{
    setModel(&mModel);
    translate(); // Adds columns to grid
    clear();
    setExpandsOnDoubleClick(false);
    setSortingEnabled(true);

    connect(this, &ResultsTree::doubleClicked, this, &ResultsTree::quickStartApplication);
}

void ResultsTree::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
        quickStartApplication(this->currentIndex());
    }
    QTreeView::keyPressEvent(event);
}

void ResultsTree::setReportType(ReportType reportType) {
    mReportType = reportType;

    mGuideline = createGuidelineMapping(reportType);

    for (int i = 0; i < mModel.rowCount(); ++i) {
        const QStandardItem *fileItem = mModel.item(i, COLUMN_FILE);
        if (!fileItem)
            continue;
        for (int j = 0; j < fileItem->rowCount(); ++j) {
            const auto& childdata = fileItem->child(j,0)->data().toMap();
            const QString& errorId = childdata[ERRORID].toString();
            Severity severity = ShowTypes::ShowTypeToSeverity(ShowTypes::VariantToShowType(childdata[SEVERITY]));
            const QString& guideline = getGuideline(mReportType, mGuideline, errorId, severity);
            const QString& classification = getClassification(mReportType, guideline);
            fileItem->child(j, COLUMN_CERT_LEVEL)->setText(classification);
            fileItem->child(j, COLUMN_CERT_RULE)->setText(guideline);
            fileItem->child(j, COLUMN_MISRA_CLASSIFICATION)->setText(classification);
            fileItem->child(j, COLUMN_MISRA_GUIDELINE)->setText(guideline);
        }
    }

    if (isAutosarMisraReport()) {
        showColumn(COLUMN_MISRA_CLASSIFICATION);
        showColumn(COLUMN_MISRA_GUIDELINE);
    } else {
        hideColumn(COLUMN_MISRA_CLASSIFICATION);
        hideColumn(COLUMN_MISRA_GUIDELINE);
    }

    if (isCertReport()) {
        showColumn(COLUMN_CERT_LEVEL);
        showColumn(COLUMN_CERT_RULE);
    } else {
        hideColumn(COLUMN_CERT_LEVEL);
        hideColumn(COLUMN_CERT_RULE);
    }

    if (mReportType == ReportType::normal) {
        showColumn(COLUMN_SEVERITY);
    } else {
        hideColumn(COLUMN_SEVERITY);
    }

    refreshTree();
}

void ResultsTree::initialize(QSettings *settings, ApplicationList *list, ThreadHandler *checkThreadHandler)
{
    mSettings = settings;
    mApplications = list;
    mThread = checkThreadHandler;
    loadSettings();
}


QStandardItem *ResultsTree::createNormalItem(const QString &name)
{
    auto *item = new QStandardItem(name);
    item->setData(name, Qt::ToolTipRole);
    item->setEditable(false);
    return item;
}

QStandardItem *ResultsTree::createCheckboxItem(bool checked)
{
    auto *item = new QStandardItem;
    item->setCheckable(true);
    item->setCheckState(checked ? Qt::Checked : Qt::Unchecked);
    item->setEnabled(false);
    return item;
}

QStandardItem *ResultsTree::createLineNumberItem(const QString &linenumber)
{
    auto *item = new QStandardItem();
    item->setData(QVariant(linenumber.toInt()), Qt::DisplayRole);
    item->setToolTip(linenumber);
    item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
    item->setEditable(false);
    return item;
}

bool ResultsTree::addErrorItem(const ErrorItem &item)
{
    if (item.errorPath.isEmpty()) {
        return false;
    }

    const QErrorPathItem &loc = item.errorId.startsWith("clang") ? item.errorPath.front() : item.errorPath.back();
    QString realfile = stripPath(loc.file, false);

    if (realfile.isEmpty()) {
        realfile = tr("Undefined file");
    }

    bool showItem = true;

    // Ids that are temporarily hidden..
    if (mHiddenMessageId.contains(item.errorId))
        showItem = false;

    //If specified, filter on summary, message, filename, and id
    if (showItem && !mFilter.isEmpty()) {
        if (!item.summary.contains(mFilter, Qt::CaseInsensitive) &&
            !item.message.contains(mFilter, Qt::CaseInsensitive) &&
            !item.errorPath.back().file.contains(mFilter, Qt::CaseInsensitive) &&
            !item.errorId.contains(mFilter, Qt::CaseInsensitive)) {
            showItem = false;
        }
    }

    if (showItem) {
        if (mReportType == ReportType::normal)
            showItem = mShowSeverities.isShown(item.severity);
        else {
            const QString& guideline = getGuideline(mReportType, mGuideline, item.errorId, item.severity);
            const QString& classification = getClassification(mReportType, guideline);
            showItem = !classification.isEmpty() && mShowSeverities.isShown(getSeverityFromClassification(classification));
        }
    }

    // if there is at least one error that is not hidden, we have a visible error
    mVisibleErrors |= showItem;

    ErrorLine line;
    line.file = realfile;
    line.line = loc.line;
    line.errorId = item.errorId;
    line.cwe = item.cwe;
    line.hash = item.hash;
    line.inconclusive = item.inconclusive;
    line.summary = item.summary;
    line.message = item.message;
    line.severity = item.severity;
    line.sinceDate = item.sinceDate;
    if (const ProjectFile *activeProject = ProjectFile::getActiveProject()) {
        line.tags = activeProject->getWarningTags(item.hash);
    }
    line.remark = item.remark;
    //Create the base item for the error and ensure it has a proper
    //file item as a parent
    QStandardItem* fileItem = ensureFileItem(loc.file, item.file0, !showItem);
    QStandardItem* stditem = addBacktraceFiles(fileItem,
                                               line,
                                               !showItem,
                                               severityToIcon(line.severity),
                                               false);

    if (!stditem)
        return false;

    //Add user data to that item
    QMap<QString, QVariant> itemdata;
    itemdata[SEVERITY]  = ShowTypes::SeverityToShowType(item.severity);
    itemdata[SUMMARY] = item.summary;
    itemdata[MESSAGE]  = item.message;
    itemdata[FILENAME]  = loc.file;
    itemdata[LINE]  = loc.line;
    itemdata[COLUMN] = loc.column;
    itemdata[ERRORID]  = item.errorId;
    itemdata[CWE] = item.cwe;
    itemdata[HASH] = item.hash;
    itemdata[INCONCLUSIVE] = item.inconclusive;
    itemdata[FILE0] = stripPath(item.file0, true);
    itemdata[SINCEDATE] = item.sinceDate;
    itemdata[SYMBOLNAMES] = item.symbolNames;
    itemdata[TAGS] = line.tags;
    itemdata[REMARK] = line.remark;
    itemdata[HIDE] = false;
    stditem->setData(QVariant(itemdata));

    //Add backtrace files as children
    if (item.errorPath.size() > 1) {
        for (int i = 0; i < item.errorPath.size(); i++) {
            const QErrorPathItem &e = item.errorPath[i];
            line.file = e.file;
            line.line = e.line;
            line.message = line.summary = e.info;
            QStandardItem *child_item = addBacktraceFiles(stditem,
                                                          line,
                                                          false,
                                                          ":images/go-down.png",
                                                          true);
            if (!child_item)
                continue;

            // Add user data to that item
            QMap<QString, QVariant> child_data;
            child_data[SEVERITY]  = ShowTypes::SeverityToShowType(line.severity);
            child_data[SUMMARY] = line.summary;
            child_data[MESSAGE]  = line.message;
            child_data[FILENAME]  = e.file;
            child_data[LINE]  = e.line;
            child_data[COLUMN] = e.column;
            child_data[ERRORID]  = line.errorId;
            child_data[CWE] = line.cwe;
            child_data[HASH] = line.hash;
            child_data[INCONCLUSIVE] = line.inconclusive;
            child_data[SYMBOLNAMES] = item.symbolNames;
            child_item->setData(QVariant(child_data));
        }
    }

    return true;
}

QStandardItem *ResultsTree::addBacktraceFiles(QStandardItem *parent,
                                              const ErrorLine &item,
                                              const bool hide,
                                              const QString &icon,
                                              bool childOfMessage)
{
    if (!parent)
        return nullptr;

    //TODO message has parameter names so we'll need changes to the core
    //cppcheck so we can get proper translations

    const QString itemSeverity = childOfMessage ? tr("note") : severityToTranslatedString(item.severity);

    // Check for duplicate rows and don't add them if found
    for (int i = 0; i < parent->rowCount(); i++) {
        // The first column is the file name and is always the same

        // the third column is the line number so check it first
        if (parent->child(i, COLUMN_LINE)->text() == QString::number(item.line)) {
            // the second column is the severity so check it next
            if (parent->child(i, COLUMN_SEVERITY)->text() == itemSeverity) {
                // the sixth column is the summary so check it last
                if (parent->child(i, COLUMN_SUMMARY)->text() == item.summary) {
                    // this row matches so don't add it
                    return nullptr;
                }
            }
        }
    }

    QMap<int, QStandardItem*> columns;
    const QString guideline = getGuideline(mReportType, mGuideline, item.errorId, item.severity);
    const QString classification = getClassification(mReportType, guideline);
    columns[COLUMN_CERT_LEVEL] = createNormalItem(classification);
    columns[COLUMN_CERT_RULE] = createNormalItem(guideline);
    columns[COLUMN_CWE] = createNormalItem(QString::number(item.cwe));
    columns[COLUMN_FILE] = createNormalItem(QDir::toNativeSeparators(item.file));
    columns[COLUMN_ID] = createNormalItem(childOfMessage ? QString() : item.errorId);
    columns[COLUMN_INCONCLUSIVE] = childOfMessage ? createNormalItem(QString()) : createCheckboxItem(item.inconclusive);
    columns[COLUMN_LINE] = createLineNumberItem(QString::number(item.line));
    columns[COLUMN_MISRA_CLASSIFICATION] = createNormalItem(classification);
    columns[COLUMN_MISRA_GUIDELINE] = createNormalItem(guideline);
    columns[COLUMN_SEVERITY] = createNormalItem(itemSeverity);
    columns[COLUMN_SINCE_DATE] = createNormalItem(item.sinceDate);
    columns[COLUMN_SUMMARY] = createNormalItem(item.summary);
    columns[COLUMN_TAGS] = createNormalItem(item.tags);

    const int numberOfColumns = getLabels().size();
    QList<QStandardItem*> list;
    for (int i = 0; i < numberOfColumns; ++i)
        list << columns[i];

    parent->appendRow(list);

    setRowHidden(parent->rowCount() - 1, parent->index(), hide);

    if (!icon.isEmpty()) {
        list[0]->setIcon(QIcon(icon));
    }

    return list[0];
}

QString ResultsTree::severityToTranslatedString(Severity severity)
{
    switch (severity) {
    case Severity::style:
        return tr("style");

    case Severity::error:
        return tr("error");

    case Severity::warning:
        return tr("warning");

    case Severity::performance:
        return tr("performance");

    case Severity::portability:
        return tr("portability");

    case Severity::information:
        return tr("information");

    case Severity::debug:
        return tr("debug");

    case Severity::internal:
        return tr("internal");

    case Severity::none:
    default:
        return QString();
    }
}

QStandardItem *ResultsTree::findFileItem(const QString &name) const
{
    // The first column contains the file name. In Windows we can get filenames
    // "header.h" and "Header.h" and must compare them as identical.

    for (int i = 0; i < mModel.rowCount(); i++) {
#ifdef _WIN32
        if (QString::compare(mModel.item(i, COLUMN_FILE)->text(), name, Qt::CaseInsensitive) == 0)
#else
        if (mModel.item(i, COLUMN_FILE)->text() == name)
#endif
            return mModel.item(i, COLUMN_FILE);
    }
    return nullptr;
}

void ResultsTree::clear()
{
    mModel.removeRows(0, mModel.rowCount());

    if (const ProjectFile *activeProject = ProjectFile::getActiveProject()) {
        hideColumn(COLUMN_SINCE_DATE);
        if (activeProject->getTags().isEmpty())
            hideColumn(COLUMN_TAGS);
        else
            showColumn(COLUMN_TAGS);
    } else {
        hideColumn(COLUMN_SINCE_DATE);
        hideColumn(COLUMN_TAGS);
    }
}

void ResultsTree::clear(const QString &filename)
{
    const QString stripped = stripPath(filename, false);

    for (int i = 0; i < mModel.rowCount(); ++i) {
        const QStandardItem *fileItem = mModel.item(i, COLUMN_FILE);
        if (!fileItem)
            continue;

        QVariantMap fitemdata = fileItem->data().toMap();
        if (stripped == fitemdata[FILENAME].toString() ||
            filename == fitemdata[FILE0].toString()) {
            mModel.removeRow(i);
            break;
        }
    }
}

void ResultsTree::clearRecheckFile(const QString &filename)
{
    for (int i = 0; i < mModel.rowCount(); ++i) {
        const QStandardItem *fileItem = mModel.item(i, COLUMN_FILE);
        if (!fileItem)
            continue;

        QString actualfile((!mCheckPath.isEmpty() && filename.startsWith(mCheckPath)) ? filename.mid(mCheckPath.length() + 1) : filename);
        QVariantMap fitemdata = fileItem->data().toMap();
        QString storedfile = fitemdata[FILENAME].toString();
        storedfile = ((!mCheckPath.isEmpty() && storedfile.startsWith(mCheckPath)) ? storedfile.mid(mCheckPath.length() + 1) : storedfile);
        if (actualfile == storedfile) {
            mModel.removeRow(i);
            break;
        }
    }
}


void ResultsTree::loadSettings()
{
    for (int i = 0; i < mModel.columnCount(); i++) {
        QString temp = QString(SETTINGS_RESULT_COLUMN_WIDTH).arg(i);
        setColumnWidth(i, qMax(20, mSettings->value(temp, 800 / mModel.columnCount()).toInt()));
    }

    mSaveFullPath = mSettings->value(SETTINGS_SAVE_FULL_PATH, false).toBool();
    mSaveAllErrors = mSettings->value(SETTINGS_SAVE_ALL_ERRORS, false).toBool();
    mShowFullPath = mSettings->value(SETTINGS_SHOW_FULL_PATH, false).toBool();

    showIdColumn(mSettings->value(SETTINGS_SHOW_ERROR_ID, true).toBool());
    showInconclusiveColumn(mSettings->value(SETTINGS_INCONCLUSIVE_ERRORS, false).toBool());
}

void ResultsTree::saveSettings() const
{
    for (int i = 0; i < mModel.columnCount(); i++) {
        QString temp = QString(SETTINGS_RESULT_COLUMN_WIDTH).arg(i);
        mSettings->setValue(temp, columnWidth(i));
    }
}

void ResultsTree::showResults(ShowTypes::ShowType type, bool show)
{
    if (type != ShowTypes::ShowNone && mShowSeverities.isShown(type) != show) {
        mShowSeverities.show(type, show);
        refreshTree();
    }
}

void ResultsTree::showCppcheckResults(bool show)
{
    mShowCppcheck = show;
    refreshTree();
}

void ResultsTree::showClangResults(bool show)
{
    mShowClang = show;
    refreshTree();
}

void ResultsTree::filterResults(const QString& filter)
{
    mFilter = filter;
    refreshTree();
}

void ResultsTree::showHiddenResults()
{
    //Clear the "hide" flag for each item
    mHiddenMessageId.clear();
    refreshTree();
    emit resultsHidden(false);
}


void ResultsTree::refreshTree()
{
    mVisibleErrors = false;
    //Get the amount of files in the tree
    const int filecount = mModel.rowCount();

    for (int i = 0; i < filecount; i++) {
        //Get file i
        QStandardItem *fileItem = mModel.item(i, 0);
        if (!fileItem) {
            continue;
        }

        //Get the amount of errors this file contains
        const int errorcount = fileItem->rowCount();

        //By default it shouldn't be visible
        bool showFile = false;

        for (int j = 0; j < errorcount; j++) {
            //Get the error itself
            QStandardItem *child = fileItem->child(j, 0);
            if (!child) {
                continue;
            }

            //Get error's user data and convert it to QVariantMap
            QVariantMap userdata = child->data().toMap();

            //Check if this error should be hidden
            bool hide = userdata[HIDE].toBool() || mHiddenMessageId.contains(userdata[ERRORID].toString());

            if (!hide) {
                if (mReportType == ReportType::normal)
                    hide = !mShowSeverities.isShown(ShowTypes::VariantToShowType(userdata[SEVERITY]));
                else {
                    const QString& classification = fileItem->child(j, COLUMN_MISRA_CLASSIFICATION)->text();
                    hide = classification.isEmpty() || !mShowSeverities.isShown(getSeverityFromClassification(classification));
                }
            }

            // If specified, filter on summary, message, filename, and id
            if (!hide && !mFilter.isEmpty()) {
                if (!userdata[SUMMARY].toString().contains(mFilter, Qt::CaseInsensitive) &&
                    !userdata[MESSAGE].toString().contains(mFilter, Qt::CaseInsensitive) &&
                    !userdata[FILENAME].toString().contains(mFilter, Qt::CaseInsensitive) &&
                    !userdata[ERRORID].toString().contains(mFilter, Qt::CaseInsensitive) &&
                    !fileItem->child(j, COLUMN_MISRA_CLASSIFICATION)->text().contains(mFilter, Qt::CaseInsensitive)) {
                    hide = true;
                }
            }

            // Tool filter
            if (!hide) {
                if (userdata[ERRORID].toString().startsWith("clang"))
                    hide = !mShowClang;
                else
                    hide = !mShowCppcheck;
            }

            if (!hide) {
                showFile = true;
                mVisibleErrors = true;
            }

            //Hide/show accordingly
            setRowHidden(j, fileItem->index(), hide);
        }

        // Show the file if any of it's errors are visible
        setRowHidden(i, QModelIndex(), !showFile);
    }
}

QStandardItem *ResultsTree::ensureFileItem(const QString &fullpath, const QString &file0, bool hide)
{
    QString name = stripPath(fullpath, false);
    // Since item has path with native separators we must use path with
    // native separators to find it.
    QStandardItem *item = findFileItem(QDir::toNativeSeparators(name));

    if (item) {
        if (!hide)
            setRowHidden(item->row(), QModelIndex(), hide);
        return item;
    }

    // Ensure shown path is with native separators
    name = QDir::toNativeSeparators(name);
    item = createNormalItem(name);
    item->setIcon(QIcon(":images/text-x-generic.png"));

    //Add user data to that item
    QMap<QString, QVariant> itemdata;
    itemdata[FILENAME] = fullpath;
    itemdata[FILE0] = file0;
    item->setData(QVariant(itemdata));
    mModel.appendRow(item);

    setRowHidden(item->row(), QModelIndex(), hide);

    return item;
}

void ResultsTree::contextMenuEvent(QContextMenuEvent * e)
{
    QModelIndex index = indexAt(e->pos());
    if (index.isValid()) {
        bool multipleSelection = false;

        mSelectionModel = selectionModel();
        if (mSelectionModel->selectedRows().count() > 1)
            multipleSelection = true;

        mContextItem = mModel.itemFromIndex(index);

        //Create a new context menu
        QMenu menu(this);

        //Create a signal mapper so we don't have to store data to class
        //member variables
        QSignalMapper signalMapper;

        if (mContextItem && mApplications->getApplicationCount() > 0 && mContextItem->parent()) {
            //Create an action for the application
            int defaultApplicationIndex = mApplications->getDefaultApplication();
            defaultApplicationIndex = std::max(defaultApplicationIndex, 0);
            const Application& app = mApplications->getApplication(defaultApplicationIndex);
            auto *start = new QAction(app.getName(), &menu);
            if (multipleSelection)
                start->setDisabled(true);

            //Add it to context menu
            menu.addAction(start);

            //Connect the signal to signal mapper
            connect(start, &QAction::triggered, &signalMapper, QOverload<>::of(&QSignalMapper::map));

            //Add a new mapping
            signalMapper.setMapping(start, defaultApplicationIndex);

            connect(&signalMapper, SIGNAL(mapped(int)),
                    this, SLOT(context(int)));
        }

        // Add popup menuitems
        if (mContextItem) {
            if (mApplications->getApplicationCount() > 0) {
                menu.addSeparator();
            }

            //Create an action for the application
            auto *recheckAction          = new QAction(tr("Recheck"), &menu);
            auto *copyAction             = new QAction(tr("Copy"), &menu);
            auto *hide                   = new QAction(tr("Hide"), &menu);
            auto *hideallid              = new QAction(tr("Hide all with id"), &menu);
            auto *opencontainingfolder   = new QAction(tr("Open containing folder"), &menu);

            if (multipleSelection) {
                hideallid->setDisabled(true);
                opencontainingfolder->setDisabled(true);
            }
            if (mThread->isChecking())
                recheckAction->setDisabled(true);
            else
                recheckAction->setDisabled(false);

            menu.addAction(recheckAction);
            menu.addSeparator();
            menu.addAction(copyAction);
            menu.addSeparator();
            menu.addAction(hide);
            menu.addAction(hideallid);

            auto *suppress = new QAction(tr("Suppress selected id(s)"), &menu);
            {
                QVariantMap itemdata = mContextItem->data().toMap();
                const QString messageId = itemdata[ERRORID].toString();
                suppress->setEnabled(!ErrorLogger::isCriticalErrorId(messageId.toStdString()));
            }
            menu.addAction(suppress);
            connect(suppress, &QAction::triggered, this, &ResultsTree::suppressSelectedIds);

            menu.addSeparator();
            menu.addAction(opencontainingfolder);

            connect(recheckAction, &QAction::triggered, this, &ResultsTree::recheckSelectedFiles);
            connect(copyAction, &QAction::triggered, this, &ResultsTree::copy);
            connect(hide, &QAction::triggered, this, &ResultsTree::hideResult);
            connect(hideallid, &QAction::triggered, this, &ResultsTree::hideAllIdResult);
            connect(opencontainingfolder, &QAction::triggered, this, &ResultsTree::openContainingFolder);

            const ProjectFile *currentProject = ProjectFile::getActiveProject();
            if (currentProject && !currentProject->getTags().isEmpty()) {
                menu.addSeparator();
                QMenu *tagMenu = menu.addMenu(tr("Tag"));
                {
                    auto *action = new QAction(tr("No tag"), tagMenu);
                    tagMenu->addAction(action);
                    connect(action, &QAction::triggered, [=]() {
                        tagSelectedItems(QString());
                    });
                }

                for (const QString& tagstr : currentProject->getTags()) {
                    auto *action = new QAction(tagstr, tagMenu);
                    tagMenu->addAction(action);
                    connect(action, &QAction::triggered, [=]() {
                        tagSelectedItems(tagstr);
                    });
                }
            }
        }

        //Start the menu
        menu.exec(e->globalPos());
        index = indexAt(e->pos());
        if (index.isValid()) {
            mContextItem = mModel.itemFromIndex(index);
        }
    }
}

void ResultsTree::startApplication(const QStandardItem *target, int application)
{
    //If there are no applications specified, tell the user about it
    if (mApplications->getApplicationCount() == 0) {
        QMessageBox msg(QMessageBox::Critical,
                        tr("Cppcheck"),
                        tr("No editor application configured.\n\n"
                           "Configure the editor application for Cppcheck in preferences/Applications."),
                        QMessageBox::Ok,
                        this);
        msg.exec();
        return;
    }

    if (application == -1)
        application = mApplications->getDefaultApplication();

    if (application == -1) {
        QMessageBox msg(QMessageBox::Critical,
                        tr("Cppcheck"),
                        tr("No default editor application selected.\n\n"
                           "Please select the default editor application in preferences/Applications."),
                        QMessageBox::Ok,
                        this);
        msg.exec();
        return;

    }

    if (target && application >= 0 && application < mApplications->getApplicationCount() && target->parent()) {
        // Make sure we are working with the first column
        if (target->column() != 0)
            target = target->parent()->child(target->row(), 0);

        QVariantMap targetdata = target->data().toMap();

        //Replace (file) with filename
        QString file = targetdata[FILENAME].toString();
        file = QDir::toNativeSeparators(file);
        qDebug() << "Opening file: " << file;

        QFileInfo info(file);
        if (!info.exists()) {
            if (info.isAbsolute()) {
                QMessageBox msgbox(this);
                msgbox.setWindowTitle("Cppcheck");
                msgbox.setText(tr("Could not find the file!"));
                msgbox.setIcon(QMessageBox::Critical);
                msgbox.exec();
            } else {
                QDir checkdir(mCheckPath);
                if (checkdir.isAbsolute() && checkdir.exists()) {
                    file = mCheckPath + "/" + file;
                } else {
                    QString dir = askFileDir(file);
                    dir += '/';
                    file = dir + file;
                }
            }
        }

        if (file.indexOf(" ") > -1) {
            file.insert(0, "\"");
            file.append("\"");
        }

        const Application& app = mApplications->getApplication(application);
        QString params = app.getParameters();
        params.replace("(file)", file, Qt::CaseInsensitive);

        QVariant line = targetdata[LINE];
        params.replace("(line)", QString("%1").arg(line.toInt()), Qt::CaseInsensitive);

        params.replace("(message)", targetdata[MESSAGE].toString(), Qt::CaseInsensitive);
        params.replace("(severity)", targetdata[SEVERITY].toString(), Qt::CaseInsensitive);

        QString program = app.getPath();

        // In Windows we must surround paths including spaces with quotation marks.
#ifdef Q_OS_WIN
        if (program.indexOf(" ") > -1) {
            if (!program.startsWith('"') && !program.endsWith('"')) {
                program.insert(0, "\"");
                program.append("\"");
            }
        }
#endif // Q_OS_WIN

#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
        const QString cmdLine = QString("%1 %2").arg(program).arg(params);
#endif

        // this is reported as deprecated in Qt 5.15.2 but no longer in Qt 6
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
        SUPPRESS_WARNING_CLANG_PUSH("-Wdeprecated")
        SUPPRESS_WARNING_GCC_PUSH("-Wdeprecated-declarations")
#endif

#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
        const bool success = QProcess::startDetached(cmdLine);
#else
        const bool success = QProcess::startDetached(program, QProcess::splitCommand(params));
#endif

#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
        SUPPRESS_WARNING_GCC_POP
            SUPPRESS_WARNING_CLANG_POP
#endif
        if (!success) {
            QString text = tr("Could not start %1\n\nPlease check the application path and parameters are correct.").arg(program);

            QMessageBox msgbox(this);
            msgbox.setWindowTitle("Cppcheck");
            msgbox.setText(text);
            msgbox.setIcon(QMessageBox::Critical);

            msgbox.exec();
        }
    }
}

QString ResultsTree::askFileDir(const QString &file)
{
    QString text = tr("Could not find file:") + '\n' + file + '\n';
    QString title;
    if (file.indexOf('/')) {
        QString folderName = file.mid(0, file.indexOf('/'));
        text += tr("Please select the folder '%1'").arg(folderName);
        title = tr("Select Directory '%1'").arg(folderName);
    } else {
        text += tr("Please select the directory where file is located.");
        title = tr("Select Directory");
    }

    QMessageBox msgbox(this);
    msgbox.setWindowTitle("Cppcheck");
    msgbox.setText(text);
    msgbox.setIcon(QMessageBox::Warning);
    msgbox.exec();

    QString dir = QFileDialog::getExistingDirectory(this, title,
                                                    getPath(SETTINGS_LAST_SOURCE_PATH),
                                                    QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

    if (dir.isEmpty())
        return QString();

    // User selected root path
    if (QFileInfo::exists(dir + '/' + file))
        mCheckPath = dir;

    // user selected checked folder
    else if (file.indexOf('/') > 0) {
        dir += '/';
        QString folderName = file.mid(0, file.indexOf('/'));
        if (dir.indexOf('/' + folderName + '/'))
            dir = dir.mid(0, dir.lastIndexOf('/' + folderName + '/'));
        if (QFileInfo::exists(dir + '/' + file))
            mCheckPath = dir;
    }

    // Otherwise; return
    else
        return QString();

    setPath(SETTINGS_LAST_SOURCE_PATH, mCheckPath);
    return mCheckPath;
}

void ResultsTree::copy()
{
    if (!mSelectionModel)
        return;

    QString text;
    for (const QModelIndex& index : mSelectionModel->selectedRows()) {
        const QStandardItem *item = mModel.itemFromIndex(index);
        if (!item->parent()) {
            text += item->text() + '\n';
            continue;
        }
        if (item->parent()->parent())
            item = item->parent();
        QVariantMap itemdata = item->data().toMap();
        if (!itemdata.contains("id"))
            continue;
        QString inconclusive = itemdata[INCONCLUSIVE].toBool() ? ",inconclusive" : "";
        text += itemdata[FILENAME].toString() + ':' + QString::number(itemdata[LINE].toInt()) + ':' + QString::number(itemdata[COLUMN].toInt())
                + ": "
                + QString::fromStdString(severityToString(ShowTypes::ShowTypeToSeverity((ShowTypes::ShowType)itemdata[SEVERITY].toInt()))) + inconclusive
                + ": "
                + itemdata[MESSAGE].toString()
                + " ["
                + itemdata[ERRORID].toString()
                + "]\n";
    }

    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(text);
}

void ResultsTree::hideResult()
{
    if (!mSelectionModel)
        return;

    for (QModelIndex index : mSelectionModel->selectedRows()) {
        QStandardItem *item = mModel.itemFromIndex(index);
        //Set the "hide" flag for this item
        QVariantMap itemdata = item->data().toMap();
        itemdata[HIDE] = true;
        item->setData(QVariant(itemdata));

        refreshTree();
        emit resultsHidden(true);
    }
}

void ResultsTree::recheckSelectedFiles()
{
    if (!mSelectionModel)
        return;

    QStringList selectedItems;
    for (QModelIndex index : mSelectionModel->selectedRows()) {
        QStandardItem *item = mModel.itemFromIndex(index);
        while (item->parent())
            item = item->parent();
        QVariantMap itemdata = item->data().toMap();
        QString currentFile = itemdata[FILENAME].toString();
        if (!currentFile.isEmpty()) {
            QString fileNameWithCheckPath;
            QFileInfo curfileInfo(currentFile);
            if (!curfileInfo.exists() && !mCheckPath.isEmpty() && currentFile.indexOf(mCheckPath) != 0)
                fileNameWithCheckPath = mCheckPath + "/" + currentFile;
            else
                fileNameWithCheckPath = currentFile;
            const QFileInfo fileInfo(fileNameWithCheckPath);
            if (!fileInfo.exists()) {
                askFileDir(currentFile);
                return;
            }
            if (Path::isHeader(currentFile.toStdString())) {
                if (!itemdata[FILE0].toString().isEmpty() && !selectedItems.contains(itemdata[FILE0].toString())) {
                    selectedItems<<((!mCheckPath.isEmpty() && (itemdata[FILE0].toString().indexOf(mCheckPath) != 0)) ? (mCheckPath + "/" + itemdata[FILE0].toString()) : itemdata[FILE0].toString());
                    if (!selectedItems.contains(fileNameWithCheckPath))
                        selectedItems<<fileNameWithCheckPath;
                }
            } else if (!selectedItems.contains(fileNameWithCheckPath))
                selectedItems<<fileNameWithCheckPath;
        }
    }
    emit checkSelected(std::move(selectedItems));
}

void ResultsTree::hideAllIdResult()
{
    if (!mContextItem || !mContextItem->parent())
        return;

    // Make sure we are working with the first column
    if (mContextItem->column() != 0)
        mContextItem = mContextItem->parent()->child(mContextItem->row(), 0);
    QVariantMap itemdata = mContextItem->data().toMap();

    QString messageId = itemdata[ERRORID].toString();

    mHiddenMessageId.append(messageId);

    refreshTree();
    emit resultsHidden(true);
}

void ResultsTree::suppressSelectedIds()
{
    if (!mSelectionModel)
        return;

    QSet<QString> selectedIds;
    for (QModelIndex index : mSelectionModel->selectedRows()) {
        QStandardItem *item = mModel.itemFromIndex(index);
        if (!item->parent())
            continue;
        if (item->parent()->parent())
            item = item->parent();
        QVariantMap itemdata = item->data().toMap();
        if (!itemdata.contains("id"))
            continue;
        selectedIds << itemdata[ERRORID].toString();
    }

    // delete all errors with selected message Ids
    for (int i = 0; i < mModel.rowCount(); i++) {
        QStandardItem * const file = mModel.item(i, 0);
        for (int j = 0; j < file->rowCount();) {
            QStandardItem *errorItem = file->child(j, 0);
            QVariantMap userdata = errorItem->data().toMap();
            if (selectedIds.contains(userdata[ERRORID].toString())) {
                file->removeRow(j);
            } else {
                j++;
            }
        }
        if (file->rowCount() == 0)
            mModel.removeRow(file->row());
    }


    emit suppressIds(selectedIds.values());
}

void ResultsTree::suppressHash()
{
    if (!mSelectionModel)
        return;

    // Extract selected warnings
    QSet<QStandardItem *> selectedWarnings;
    for (QModelIndex index : mSelectionModel->selectedRows()) {
        QStandardItem *item = mModel.itemFromIndex(index);
        if (!item->parent())
            continue;
        while (item->parent()->parent())
            item = item->parent();
        selectedWarnings.insert(item);
    }

    bool changed = false;
    ProjectFile *projectFile = ProjectFile::getActiveProject();
    for (QStandardItem *item: selectedWarnings) {
        QStandardItem *fileItem = item->parent();
        const QVariantMap itemdata = item->data().toMap();
        if (projectFile && itemdata.contains(HASH)) {
            SuppressionList::Suppression suppression;
            suppression.hash = itemdata[HASH].toULongLong();
            suppression.errorId = itemdata[ERRORID].toString().toStdString();
            suppression.fileName = itemdata[FILENAME].toString().toStdString();
            suppression.lineNumber = itemdata[LINE].toInt();
            projectFile->addSuppression(suppression);
            changed = true;
        }
        fileItem->removeRow(item->row());
        if (fileItem->rowCount() == 0)
            mModel.removeRow(fileItem->row());
    }

    if (changed)
        projectFile->write();
}

void ResultsTree::openContainingFolder()
{
    QString filePath = getFilePath(mContextItem, true);
    if (!filePath.isEmpty()) {
        filePath = QFileInfo(filePath).absolutePath();
        QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
    }
}

void ResultsTree::tagSelectedItems(const QString &tag)
{
    if (!mSelectionModel)
        return;
    bool isTagged = false;
    ProjectFile *currentProject = ProjectFile::getActiveProject();
    for (QModelIndex index : mSelectionModel->selectedRows()) {
        QStandardItem *item = mModel.itemFromIndex(index);
        QVariantMap itemdata = item->data().toMap();
        if (itemdata.contains("tags")) {
            itemdata[TAGS] = tag;
            item->setData(QVariant(itemdata));
            item->parent()->child(index.row(), COLUMN_TAGS)->setText(tag);
            if (currentProject && itemdata.contains(HASH)) {
                isTagged = true;
                currentProject->setWarningTags(itemdata[HASH].toULongLong(), tag);
            }
        }
    }
    if (isTagged)
        currentProject->write();
}

void ResultsTree::context(int application)
{
    startApplication(mContextItem, application);
}

void ResultsTree::quickStartApplication(const QModelIndex &index)
{
    startApplication(mModel.itemFromIndex(index));
}

QString ResultsTree::getFilePath(const QStandardItem *target, bool fullPath)
{
    if (target) {
        // Make sure we are working with the first column
        if (target->column() != 0)
            target = target->parent()->child(target->row(), 0);

        QVariantMap targetdata = target->data().toMap();

        //Replace (file) with filename
        QString file = targetdata[FILENAME].toString();
        QString pathStr = QDir::toNativeSeparators(file);
        if (!fullPath) {
            QFileInfo fi(pathStr);
            pathStr = fi.fileName();
        }

        return pathStr;
    }

    return QString();
}

QString ResultsTree::severityToIcon(Severity severity)
{
    switch (severity) {
    case Severity::error:
        return ":images/dialog-error.png";
    case Severity::style:
        return ":images/applications-development.png";
    case Severity::warning:
        return ":images/dialog-warning.png";
    case Severity::portability:
        return ":images/applications-system.png";
    case Severity::performance:
        return ":images/utilities-system-monitor.png";
    case Severity::information:
        return ":images/dialog-information.png";
    default:
        return QString();
    }
}

void ResultsTree::saveResults(Report *report) const
{
    report->writeHeader();

    for (int i = 0; i < mModel.rowCount(); i++) {
        if (mSaveAllErrors || !isRowHidden(i, QModelIndex()))
            saveErrors(report, mModel.item(i, 0));
    }

    report->writeFooter();
}

void ResultsTree::saveErrors(Report *report, const QStandardItem *fileItem) const
{
    if (!fileItem) {
        return;
    }

    for (int i = 0; i < fileItem->rowCount(); i++) {
        const QStandardItem *error = fileItem->child(i, 0);

        if (!error) {
            continue;
        }

        if (isRowHidden(i, fileItem->index()) && !mSaveAllErrors) {
            continue;
        }

        ErrorItem item;
        readErrorItem(error, &item);

        report->writeError(item);
    }
}

static int indexOf(const QList<ErrorItem> &list, const ErrorItem &item)
{
    for (int i = 0; i < list.size(); i++) {
        if (ErrorItem::sameCID(item, list[i])) {
            return i;
        }
    }
    return -1;
}

void ResultsTree::updateFromOldReport(const QString &filename)
{
    showColumn(COLUMN_SINCE_DATE);

    QList<ErrorItem> oldErrors;
    XmlReportV2 oldReport(filename, QString());
    if (oldReport.open()) {
        oldErrors = oldReport.read();
        oldReport.close();
    }

    // Read current results..
    for (int i = 0; i < mModel.rowCount(); i++) {
        QStandardItem *fileItem = mModel.item(i,0);
        for (int j = 0; j < fileItem->rowCount(); j++) {
            QStandardItem *error = fileItem->child(j,0);
            ErrorItem errorItem;
            readErrorItem(error, &errorItem);
            const int oldErrorIndex = indexOf(oldErrors, errorItem);
            QVariantMap errordata = error->data().toMap();

            // New error .. set the "sinceDate" property
            if (oldErrorIndex >= 0 && !oldErrors[oldErrorIndex].sinceDate.isEmpty()) {
                errordata[SINCEDATE] = oldErrors[oldErrorIndex].sinceDate;
                error->setData(errordata);
                fileItem->child(j, COLUMN_SINCE_DATE)->setText(oldErrors[oldErrorIndex].sinceDate);
            } else if (oldErrorIndex < 0 || errordata[SINCEDATE].toString().isEmpty()) {
                const QString sinceDate = QLocale::system().toString(QDate::currentDate(), QLocale::ShortFormat);
                errordata[SINCEDATE] = sinceDate;
                error->setData(errordata);
                fileItem->child(j, COLUMN_SINCE_DATE)->setText(sinceDate);
                if (oldErrorIndex < 0)
                    continue;
            }

            if (!errorItem.tags.isEmpty())
                continue;

            const ErrorItem &oldErrorItem = oldErrors[oldErrorIndex];
            errordata[TAGS] = oldErrorItem.tags;
            error->setData(errordata);
        }
    }
}

void ResultsTree::readErrorItem(const QStandardItem *error, ErrorItem *item) const
{
    // Get error's user data
    QVariantMap errordata = error->data().toMap();

    item->severity = ShowTypes::ShowTypeToSeverity(ShowTypes::VariantToShowType(errordata[SEVERITY]));
    item->summary = errordata[SUMMARY].toString();
    item->message = errordata[MESSAGE].toString();
    item->errorId = errordata[ERRORID].toString();
    item->cwe = errordata[CWE].toInt();
    item->hash = errordata[HASH].toULongLong();
    item->inconclusive = errordata[INCONCLUSIVE].toBool();
    item->file0 = errordata[FILE0].toString();
    item->sinceDate = errordata[SINCEDATE].toString();
    item->tags = errordata[TAGS].toString();
    item->remark = errordata[REMARK].toString();
    item->classification = error->parent()->child(error->row(), COLUMN_MISRA_CLASSIFICATION)->text();
    item->guideline = error->parent()->child(error->row(), COLUMN_MISRA_GUIDELINE)->text();

    if (error->rowCount() == 0) {
        QErrorPathItem e;
        e.file = stripPath(errordata[FILENAME].toString(), true);
        e.line = errordata[LINE].toInt();
        e.info = errordata[MESSAGE].toString();
        item->errorPath << e;
    }

    for (int j = 0; j < error->rowCount(); j++) {
        const QStandardItem *child_error = error->child(j, 0);
        //Get error's user data
        QVariant child_userdata = child_error->data();
        //Convert it to QVariantMap
        QVariantMap child_data = child_userdata.toMap();

        QErrorPathItem e;
        e.file = stripPath(child_data[FILENAME].toString(), true);
        e.line = child_data[LINE].toInt();
        e.info = child_data[MESSAGE].toString();
        item->errorPath << e;
    }
}

void ResultsTree::updateSettings(bool showFullPath,
                                 bool saveFullPath,
                                 bool saveAllErrors,
                                 bool showErrorId,
                                 bool showInconclusive)
{
    if (mShowFullPath != showFullPath) {
        mShowFullPath = showFullPath;
        refreshFilePaths();
    }

    mSaveFullPath = saveFullPath;
    mSaveAllErrors = saveAllErrors;

    showIdColumn(showErrorId);
    showInconclusiveColumn(showInconclusive);
}

void ResultsTree::setCheckDirectory(const QString &dir)
{
    mCheckPath = dir;
}


const QString& ResultsTree::getCheckDirectory() const
{
    return mCheckPath;
}

QString ResultsTree::stripPath(const QString &path, bool saving) const
{
    if ((!saving && mShowFullPath) || (saving && mSaveFullPath)) {
        return QString(path);
    }

    QDir dir(mCheckPath);
    return dir.relativeFilePath(path);
}

void ResultsTree::refreshFilePaths(QStandardItem *item)
{
    if (!item) {
        return;
    }

    //Mark that this file's path hasn't been updated yet
    bool updated = false;

    //Loop through all errors within this file
    for (int i = 0; i < item->rowCount(); i++) {
        //Get error i
        QStandardItem *error = item->child(i, 0);

        if (!error) {
            continue;
        }

        //Get error's user data and convert it to QVariantMap
        QVariantMap userdata = error->data().toMap();

        //Get list of files
        QString file = userdata[FILENAME].toString();

        //Update this error's text
        error->setText(stripPath(file, false));

        //If this error has backtraces make sure the files list has enough filenames
        if (error->hasChildren()) {
            //Loop through all files within the error
            for (int j = 0; j < error->rowCount(); j++) {
                //Get file
                QStandardItem *child = error->child(j, 0);
                if (!child) {
                    continue;
                }
                //Get child's user data
                QVariant child_userdata = child->data();
                //Convert it to QVariantMap
                QVariantMap child_data = child_userdata.toMap();

                //Get list of files
                QString child_files = child_data[FILENAME].toString();
                //Update file's path
                child->setText(stripPath(child_files, false));
            }
        }

        //if the main file hasn't been updated yet, update it now
        if (!updated) {
            updated = true;
            item->setText(error->text());
        }

    }
}

void ResultsTree::refreshFilePaths()
{
    qDebug("Refreshing file paths");

    //Go through all file items (these are parent items that contain the errors)
    for (int i = 0; i < mModel.rowCount(); i++) {
        refreshFilePaths(mModel.item(i, 0));
    }
}

bool ResultsTree::hasVisibleResults() const
{
    return mVisibleErrors;
}

bool ResultsTree::hasResults() const
{
    return mModel.rowCount() > 0;
}

void ResultsTree::translate()
{
    mModel.setHorizontalHeaderLabels(getLabels());
    //TODO go through all the errors in the tree and translate severity and message
}

void ResultsTree::showIdColumn(bool show)
{
    mShowErrorId = show;
    if (show)
        showColumn(COLUMN_ID);
    else
        hideColumn(COLUMN_ID);
}

void ResultsTree::showInconclusiveColumn(bool show)
{
    if (show)
        showColumn(COLUMN_INCONCLUSIVE);
    else
        hideColumn(COLUMN_INCONCLUSIVE);
}

void ResultsTree::currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
    QTreeView::currentChanged(current, previous);
    emit treeSelectionChanged(current);
}

bool ResultsTree::isCertReport() const {
    return mReportType == ReportType::certC || mReportType == ReportType::certCpp;
}

bool ResultsTree::isAutosarMisraReport() const {
    return mReportType == ReportType::autosar ||
           mReportType == ReportType::misraC ||
           mReportType == ReportType::misraCpp2008 ||
           mReportType == ReportType::misraCpp2023;
}