summaryrefslogtreecommitdiff
path: root/src/plugins/cppeditor/cppcodemodelinspectordialog.cpp
blob: b150788c408f2cee65f0b8518406e4b08b1ea6ef (plain)
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
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "cppcodemodelinspectordialog.h"
#include "ui_cppcodemodelinspectordialog.h"
#include "cppeditor.h"

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <cpptools/cppcodemodelinspectordumper.h>
#include <cpptools/cppmodelmanager.h>
#include <cpptools/cpptoolseditorsupport.h>
#include <projectexplorer/project.h>

#include <cplusplus/CppDocument.h>
#include <cplusplus/Overview.h>
#include <cplusplus/Token.h>
#include <utils/qtcassert.h>

#include <QAbstractTableModel>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSortFilterProxyModel>

using namespace CppTools;
namespace CMI = CppCodeModelInspector;

namespace {

template <class T> void resizeColumns(QTreeView *view)
{
    for (int column = 0; column < T::ColumnCount - 1; ++column)
        view->resizeColumnToContents(column);
}

TextEditor::BaseTextEditor *currentEditor()
{
    return qobject_cast<TextEditor::BaseTextEditor*>(Core::EditorManager::currentEditor());
}

QString fileInCurrentEditor()
{
    if (TextEditor::BaseTextEditor *editor = currentEditor())
        return editor->document()->filePath();
    return QString();
}

class DepthFinder : public CPlusPlus::SymbolVisitor {
public:
    DepthFinder() : m_symbol(0), m_depth(-1), m_foundDepth(-1), m_stop(false) {}

    int operator()(const CPlusPlus::Document::Ptr &document, CPlusPlus::Symbol *symbol)
    {
        m_symbol = symbol;
        accept(document->globalNamespace());
        return m_foundDepth;
    }

    bool preVisit(CPlusPlus::Symbol *symbol)
    {
        if (m_stop)
            return false;

        if (symbol->asScope()) {
            ++m_depth;
            if (symbol == m_symbol) {
                m_foundDepth = m_depth;
                m_stop = true;
            }
            return true;
        }

        return false;
    }

    void postVisit(CPlusPlus::Symbol *symbol)
    {
        if (symbol->asScope())
            --m_depth;
    }

private:
    CPlusPlus::Symbol *m_symbol;
    int m_depth;
    int m_foundDepth;
    bool m_stop;
};

} // anonymous namespace

namespace CppEditor {
namespace Internal {

// --- FilterableView -----------------------------------------------------------------------------

class FilterableView : public QWidget
{
    Q_OBJECT
public:
    FilterableView(QWidget *parent);

    void setModel(QAbstractItemModel *model);
    QItemSelectionModel *selectionModel() const;
    void selectIndex(const QModelIndex &index);
    void resizeColumns(int columnCount);

signals:
    void filterChanged(const QString &filterText);

public slots:
    void clearFilter();

private:
    QTreeView *view;
    QLineEdit *lineEdit;
};

FilterableView::FilterableView(QWidget *parent)
    : QWidget(parent)
{
    view = new QTreeView(this);
    view->setAlternatingRowColors(true);
    view->setTextElideMode(Qt::ElideMiddle);
    view->setSortingEnabled(true);

    lineEdit = new QLineEdit(this);
    lineEdit->setPlaceholderText(QLatin1String("File Path"));
    QObject::connect(lineEdit, SIGNAL(textChanged(QString)), SIGNAL(filterChanged(QString)));

    QLabel *label = new QLabel(QLatin1String("&Filter:"), this);
    label->setBuddy(lineEdit);

    QPushButton *clearButton = new QPushButton(QLatin1String("&Clear"), this);
    QObject::connect(clearButton, SIGNAL(clicked()), SLOT(clearFilter()));

    QHBoxLayout *filterBarLayout = new QHBoxLayout();
    filterBarLayout->addWidget(label);
    filterBarLayout->addWidget(lineEdit);
    filterBarLayout->addWidget(clearButton);

    QVBoxLayout *mainLayout = new QVBoxLayout();
    mainLayout->addWidget(view);
    mainLayout->addLayout(filterBarLayout);

    setLayout(mainLayout);
}

void FilterableView::setModel(QAbstractItemModel *model)
{
    view->setModel(model);
}

QItemSelectionModel *FilterableView::selectionModel() const
{
    return view->selectionModel();
}

void FilterableView::selectIndex(const QModelIndex &index)
{
    if (index.isValid())  {
        view->selectionModel()->setCurrentIndex(index,
            QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
    }
}

void FilterableView::resizeColumns(int columnCount)
{
    for (int column = 0; column < columnCount - 1; ++column)
        view->resizeColumnToContents(column);
}

void FilterableView::clearFilter()
{
    lineEdit->clear();
}

// --- KeyValueModel ------------------------------------------------------------------------------

class KeyValueModel : public QAbstractListModel
{
    Q_OBJECT
public:
    typedef QList<QPair<QString, QString> > Table;

    KeyValueModel(QObject *parent);
    void configure(const Table &table);
    void clear();

    enum Columns { KeyColumn, ValueColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
    Table m_table;
};

KeyValueModel::KeyValueModel(QObject *parent) : QAbstractListModel(parent)
{
}

void KeyValueModel::configure(const Table &table)
{
    emit layoutAboutToBeChanged();
    m_table = table;
    emit layoutChanged();
}

void KeyValueModel::clear()
{
    emit layoutAboutToBeChanged();
    m_table.clear();
    emit layoutChanged();
}

int KeyValueModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_table.size();
}

int KeyValueModel::columnCount(const QModelIndex &/*parent*/) const
{
    return KeyValueModel::ColumnCount;
}

QVariant KeyValueModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DisplayRole) {
        const int row = index.row();
        const int column = index.column();
        if (column == KeyColumn) {
            return m_table.at(row).first;
        } else if (column == ValueColumn) {
            return m_table.at(row).second;
        }
    }
    return QVariant();
}

QVariant KeyValueModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case KeyColumn:
            return QLatin1String("Key");
        case ValueColumn:
            return QLatin1String("Value");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- SnapshotModel ------------------------------------------------------------------------------

class SnapshotModel : public QAbstractListModel
{
    Q_OBJECT
public:
    SnapshotModel(QObject *parent);
    void configure(const CPlusPlus::Snapshot &snapshot);
    void setGlobalSnapshot(const CPlusPlus::Snapshot &snapshot);

    QModelIndex indexForDocument(const QString &filePath);

    enum Columns { SymbolCountColumn, SharedColumn, FilePathColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
    QList<CPlusPlus::Document::Ptr> m_documents;
    CPlusPlus::Snapshot m_globalSnapshot;
};

SnapshotModel::SnapshotModel(QObject *parent) : QAbstractListModel(parent)
{
}

void SnapshotModel::configure(const CPlusPlus::Snapshot &snapshot)
{
    emit layoutAboutToBeChanged();
    m_documents = CMI::Utils::snapshotToList(snapshot);
    emit layoutChanged();
}

void SnapshotModel::setGlobalSnapshot(const CPlusPlus::Snapshot &snapshot)
{
    m_globalSnapshot = snapshot;
}

QModelIndex SnapshotModel::indexForDocument(const QString &filePath)
{
    for (int i = 0, total = m_documents.size(); i < total; ++i) {
        const CPlusPlus::Document::Ptr document = m_documents.at(i);
        if (document->fileName() == filePath)
            return index(i, FilePathColumn);
    }
    return QModelIndex();
}

int SnapshotModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_documents.size();
}

int SnapshotModel::columnCount(const QModelIndex &/*parent*/) const
{
    return SnapshotModel::ColumnCount;
}

QVariant SnapshotModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DisplayRole) {
        const int column = index.column();
        CPlusPlus::Document::Ptr document = m_documents.at(index.row());
        if (column == SymbolCountColumn) {
            return document->control()->symbolCount();
        } else if (column == SharedColumn) {
            CPlusPlus::Document::Ptr globalDocument = m_globalSnapshot.document(document->fileName());
            const bool isShared
                = globalDocument && globalDocument->fingerprint() == document->fingerprint();
            return CMI::Utils::toString(isShared);
        } else if (column == FilePathColumn) {
            return QDir::toNativeSeparators(document->fileName());
        }
    }
    return QVariant();
}

QVariant SnapshotModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case SymbolCountColumn:
            return QLatin1String("Symbols");
        case SharedColumn:
            return QLatin1String("Shared");
        case FilePathColumn:
            return QLatin1String("File Path");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- IncludesModel ------------------------------------------------------------------------------

static bool includesSorter(const CPlusPlus::Document::Include &i1,
                           const CPlusPlus::Document::Include &i2)
{
    return i1.line() < i2.line();
}

class IncludesModel : public QAbstractListModel
{
    Q_OBJECT
public:
    IncludesModel(QObject *parent);
    void configure(const QList<CPlusPlus::Document::Include> &includes);
    void clear();

    enum Columns { ResolvedOrNotColumn, LineNumberColumn, FilePathsColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
    QList<CPlusPlus::Document::Include> m_includes;
};

IncludesModel::IncludesModel(QObject *parent) : QAbstractListModel(parent)
{
}

void IncludesModel::configure(const QList<CPlusPlus::Document::Include> &includes)
{
    emit layoutAboutToBeChanged();
    m_includes = includes;
    qStableSort(m_includes.begin(), m_includes.end(), includesSorter);
    emit layoutChanged();
}

void IncludesModel::clear()
{
    emit layoutAboutToBeChanged();
    m_includes.clear();
    emit layoutChanged();
}

int IncludesModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_includes.size();
}

int IncludesModel::columnCount(const QModelIndex &/*parent*/) const
{
    return IncludesModel::ColumnCount;
}

QVariant IncludesModel::data(const QModelIndex &index, int role) const
{
    if (role != Qt::DisplayRole && role != Qt::ForegroundRole)
        return QVariant();

    static const QBrush greenBrush(QColor(0, 139, 69));
    static const QBrush redBrush(QColor(205, 38, 38));

    const CPlusPlus::Document::Include include = m_includes.at(index.row());
    const QString resolvedFileName = QDir::toNativeSeparators(include.resolvedFileName());
    const bool isResolved = !resolvedFileName.isEmpty();

    if (role == Qt::DisplayRole) {
        const int column = index.column();
        if (column == ResolvedOrNotColumn) {
            return CMI::Utils::toString(isResolved);
        } else if (column == LineNumberColumn) {
            return include.line();
        } else if (column == FilePathsColumn) {
            return QVariant(CMI::Utils::unresolvedFileNameWithDelimiters(include)
                            + QLatin1String(" --> ") + resolvedFileName);
        }
    } else if (role == Qt::ForegroundRole) {
        return isResolved ? greenBrush : redBrush;
    }

    return QVariant();
}

QVariant IncludesModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case ResolvedOrNotColumn:
            return QLatin1String("Resolved");
        case LineNumberColumn:
            return QLatin1String("Line");
        case FilePathsColumn:
            return QLatin1String("File Paths");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- DiagnosticMessagesModel --------------------------------------------------------------------

static bool diagnosticMessagesModelSorter(const CPlusPlus::Document::DiagnosticMessage &m1,
                                          const CPlusPlus::Document::DiagnosticMessage &m2)
{
    return m1.line() < m2.line();
}

class DiagnosticMessagesModel : public QAbstractListModel
{
    Q_OBJECT
public:
    DiagnosticMessagesModel(QObject *parent);
    void configure(const QList<CPlusPlus::Document::DiagnosticMessage> &messages);
    void clear();

    enum Columns { LevelColumn, LineColumnNumberColumn, MessageColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
    QList<CPlusPlus::Document::DiagnosticMessage> m_messages;
};

DiagnosticMessagesModel::DiagnosticMessagesModel(QObject *parent) : QAbstractListModel(parent)
{
}

void DiagnosticMessagesModel::configure(
        const QList<CPlusPlus::Document::DiagnosticMessage> &messages)
{
    emit layoutAboutToBeChanged();
    m_messages = messages;
    qStableSort(m_messages.begin(), m_messages.end(), diagnosticMessagesModelSorter);
    emit layoutChanged();
}

void DiagnosticMessagesModel::clear()
{
    emit layoutAboutToBeChanged();
    m_messages.clear();
    emit layoutChanged();
}

int DiagnosticMessagesModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_messages.size();
}

int DiagnosticMessagesModel::columnCount(const QModelIndex &/*parent*/) const
{
    return DiagnosticMessagesModel::ColumnCount;
}

QVariant DiagnosticMessagesModel::data(const QModelIndex &index, int role) const
{
    if (role != Qt::DisplayRole && role != Qt::ForegroundRole)
        return QVariant();

    static const QBrush yellowOrangeBrush(QColor(237, 145, 33));
    static const QBrush redBrush(QColor(205, 38, 38));
    static const QBrush darkRedBrushQColor(QColor(139, 0, 0));

    const CPlusPlus::Document::DiagnosticMessage message = m_messages.at(index.row());
    const CPlusPlus::Document::DiagnosticMessage::Level level
        = static_cast<CPlusPlus::Document::DiagnosticMessage::Level>(message.level());

    if (role == Qt::DisplayRole) {
        const int column = index.column();
        if (column == LevelColumn) {
            return CMI::Utils::toString(level);
        } else if (column == LineColumnNumberColumn) {
            return QVariant(QString::number(message.line()) + QLatin1Char(':')
                            + QString::number(message.column()));
        } else if (column == MessageColumn) {
            return message.text();
        }
    } else if (role == Qt::ForegroundRole) {
        switch (level) {
        case CPlusPlus::Document::DiagnosticMessage::Warning:
            return yellowOrangeBrush;
        case CPlusPlus::Document::DiagnosticMessage::Error:
            return redBrush;
        case CPlusPlus::Document::DiagnosticMessage::Fatal:
            return darkRedBrushQColor;
        default:
            return QVariant();
        }
    }

    return QVariant();
}

QVariant DiagnosticMessagesModel::headerData(int section, Qt::Orientation orientation, int role)
    const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case LevelColumn:
            return QLatin1String("Level");
        case LineColumnNumberColumn:
            return QLatin1String("Line:Column");
        case MessageColumn:
            return QLatin1String("Message");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- MacrosModel --------------------------------------------------------------------------------

class MacrosModel : public QAbstractListModel
{
    Q_OBJECT
public:
    MacrosModel(QObject *parent);
    void configure(const QList<CPlusPlus::Macro> &macros);
    void clear();

    enum Columns { LineNumberColumn, MacroColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
    QList<CPlusPlus::Macro> m_macros;
};

MacrosModel::MacrosModel(QObject *parent) : QAbstractListModel(parent)
{
}

void MacrosModel::configure(const QList<CPlusPlus::Macro> &macros)
{
    emit layoutAboutToBeChanged();
    m_macros = macros;
    emit layoutChanged();
}

void MacrosModel::clear()
{
    emit layoutAboutToBeChanged();
    m_macros.clear();
    emit layoutChanged();
}

int MacrosModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_macros.size();
}

int MacrosModel::columnCount(const QModelIndex &/*parent*/) const
{
    return MacrosModel::ColumnCount;
}

QVariant MacrosModel::data(const QModelIndex &index, int role) const
{
    const int column = index.column();
    if (role == Qt::DisplayRole || (role == Qt::ToolTipRole && column == MacroColumn)) {
        const CPlusPlus::Macro macro = m_macros.at(index.row());
        if (column == LineNumberColumn)
            return macro.line();
        else if (column == MacroColumn)
            return macro.toString();
    } else if (role == Qt::TextAlignmentRole) {
        return Qt::AlignTop + Qt::AlignLeft;
    }
    return QVariant();
}

QVariant MacrosModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case LineNumberColumn:
            return QLatin1String("Line");
        case MacroColumn:
            return QLatin1String("Macro");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- SymbolsModel -------------------------------------------------------------------------------

class SymbolsModel : public QAbstractItemModel
{
    Q_OBJECT
public:
    SymbolsModel(QObject *parent);
    void configure(const CPlusPlus::Document::Ptr &document);
    void clear();

    enum Columns { SymbolColumn, LineNumberColumn, ColumnCount };

    QModelIndex index(int row, int column, const QModelIndex &parent) const;
    QModelIndex parent(const QModelIndex &child) const;
    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
    CPlusPlus::Document::Ptr m_document;
};

SymbolsModel::SymbolsModel(QObject *parent) : QAbstractItemModel(parent)
{
}

void SymbolsModel::configure(const CPlusPlus::Document::Ptr &document)
{
    QTC_CHECK(document);
    emit layoutAboutToBeChanged();
    m_document = document;
    emit layoutChanged();
}

void SymbolsModel::clear()
{
    emit layoutAboutToBeChanged();
    m_document.clear();
    emit layoutChanged();
}

static CPlusPlus::Symbol *indexToSymbol(const QModelIndex &index)
{
    if (CPlusPlus::Symbol *symbol = static_cast<CPlusPlus::Symbol*>(index.internalPointer()))
        return symbol;
    return 0;
}

static CPlusPlus::Scope *indexToScope(const QModelIndex &index)
{
    if (CPlusPlus::Symbol *symbol = indexToSymbol(index))
        return symbol->asScope();
    return 0;
}

QModelIndex SymbolsModel::index(int row, int column, const QModelIndex &parent) const
{
    CPlusPlus::Scope *scope = 0;
    if (parent.isValid())
        scope = indexToScope(parent);
    else if (m_document)
        scope = m_document->globalNamespace();

    if (scope) {
        if ((unsigned)row < scope->memberCount())
            return createIndex(row, column, scope->memberAt(row));
    }

    return QModelIndex();
}

QModelIndex SymbolsModel::parent(const QModelIndex &child) const
{
    if (!child.isValid())
        return QModelIndex();

    if (CPlusPlus::Symbol *symbol = indexToSymbol(child)) {
        if (CPlusPlus::Scope *scope = symbol->enclosingScope()) {
            const int row = DepthFinder()(m_document, scope);
            return createIndex(row, 0, scope);
        }
    }

    return QModelIndex();
}

int SymbolsModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        if (CPlusPlus::Scope *scope = indexToScope(parent))
            return scope->memberCount();
    } else {
        if (m_document)
            return m_document->globalNamespace()->memberCount();
    }
    return 0;
}

int SymbolsModel::columnCount(const QModelIndex &) const
{
    return ColumnCount;
}

QVariant SymbolsModel::data(const QModelIndex &index, int role) const
{
    const int column = index.column();
    if (role == Qt::DisplayRole) {
        CPlusPlus::Symbol *symbol = indexToSymbol(index);
        if (!symbol)
            return QVariant();
        if (column == LineNumberColumn) {
            return symbol->line();
        } else if (column == SymbolColumn) {
            QString name = CPlusPlus::Overview().prettyName(symbol->name());
            if (name.isEmpty())
                name = QLatin1String("<no name>");
            return name;
        }
    }
    return QVariant();
}

QVariant SymbolsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case SymbolColumn:
            return QLatin1String("Symbol");
        case LineNumberColumn:
            return QLatin1String("Line");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- TokensModel --------------------------------------------------------------------------------

class TokensModel : public QAbstractListModel
{
    Q_OBJECT
public:
    TokensModel(QObject *parent);
    void configure(CPlusPlus::TranslationUnit *translationUnit);
    void clear();

    enum Columns { SpelledColumn, KindColumn, IndexColumn, OffsetColumn, LineColumnNumberColumn,
                   BytesAndCodePointsColumn, GeneratedColumn, ExpandedColumn, WhiteSpaceColumn,
                   NewlineColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
    struct TokenInfo {
        CPlusPlus::Token token;
        unsigned line;
        unsigned column;
    };
    QList<TokenInfo> m_tokenInfos;
};

TokensModel::TokensModel(QObject *parent) : QAbstractListModel(parent)
{
}

void TokensModel::configure(CPlusPlus::TranslationUnit *translationUnit)
{
    if (!translationUnit)
        return;

    emit layoutAboutToBeChanged();
    m_tokenInfos.clear();
    for (int i = 0, total = translationUnit->tokenCount(); i < total; ++i) {
        TokenInfo info;
        info.token = translationUnit->tokenAt(i);
        translationUnit->getPosition(info.token.utf16charsBegin(), &info.line, &info.column);
        m_tokenInfos.append(info);
    }
    emit layoutChanged();
}

void TokensModel::clear()
{
    emit layoutAboutToBeChanged();
    m_tokenInfos.clear();
    emit layoutChanged();
}

int TokensModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_tokenInfos.size();
}

int TokensModel::columnCount(const QModelIndex &/*parent*/) const
{
    return TokensModel::ColumnCount;
}

QVariant TokensModel::data(const QModelIndex &index, int role) const
{
    const int column = index.column();
    if (role == Qt::DisplayRole) {
        const TokenInfo info = m_tokenInfos.at(index.row());
        const CPlusPlus::Token token = info.token;
        if (column == SpelledColumn)
            return QString::fromUtf8(token.spell());
        else if (column == KindColumn)
            return CMI::Utils::toString(static_cast<CPlusPlus::Kind>(token.kind()));
        else if (column == IndexColumn)
            return index.row();
        else if (column == OffsetColumn)
            return token.bytesBegin();
        else if (column == LineColumnNumberColumn)
            return QString::fromLatin1("%1:%2").arg(CMI::Utils::toString(info.line),
                                                    CMI::Utils::toString(info.column));
        else if (column == BytesAndCodePointsColumn)
            return QString::fromLatin1("%1/%2").arg(CMI::Utils::toString(token.bytes()),
                                                    CMI::Utils::toString(token.utf16chars()));
        else if (column == GeneratedColumn)
            return CMI::Utils::toString(token.generated());
        else if (column == ExpandedColumn)
            return CMI::Utils::toString(token.expanded());
        else if (column == WhiteSpaceColumn)
            return CMI::Utils::toString(token.whitespace());
        else if (column == NewlineColumn)
            return CMI::Utils::toString(token.newline());
    } else if (role == Qt::TextAlignmentRole) {
        return Qt::AlignTop + Qt::AlignLeft;
    }
    return QVariant();
}

QVariant TokensModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case SpelledColumn:
            return QLatin1String("Spelled");
        case KindColumn:
            return QLatin1String("Kind");
        case IndexColumn:
            return QLatin1String("Index");
        case OffsetColumn:
            return QLatin1String("Offset");
        case LineColumnNumberColumn:
            return QLatin1String("Line:Column");
        case BytesAndCodePointsColumn:
            return QLatin1String("Bytes/Codepoints");
        case GeneratedColumn:
            return QLatin1String("Generated");
        case ExpandedColumn:
            return QLatin1String("Expanded");
        case WhiteSpaceColumn:
            return QLatin1String("Whitespace");
        case NewlineColumn:
            return QLatin1String("Newline");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- ProjectPartsModel --------------------------------------------------------------------------

class ProjectPartsModel : public QAbstractListModel
{
    Q_OBJECT
public:
    ProjectPartsModel(QObject *parent);

    void configure(const QList<CppModelManagerInterface::ProjectInfo> &projectInfos,
                   const ProjectPart::Ptr &currentEditorsProjectPart);

    QModelIndex indexForCurrentEditorsProjectPart() const;
    ProjectPart::Ptr projectPartForProjectFile(const QString &projectFilePath) const;

    enum Columns { PartNameColumn, PartFilePathColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
    QList<ProjectPart::Ptr> m_projectPartsList;
    int m_currentEditorsProjectPartIndex;
};

ProjectPartsModel::ProjectPartsModel(QObject *parent)
    : QAbstractListModel(parent), m_currentEditorsProjectPartIndex(-1)
{
}

void ProjectPartsModel::configure(const QList<CppModelManagerInterface::ProjectInfo> &projectInfos,
                                  const ProjectPart::Ptr &currentEditorsProjectPart)
{
    emit layoutAboutToBeChanged();
    m_projectPartsList.clear();
    foreach (const CppModelManagerInterface::ProjectInfo &info, projectInfos) {
        foreach (const ProjectPart::Ptr &projectPart, info.projectParts()) {
            if (!m_projectPartsList.contains(projectPart)) {
                m_projectPartsList << projectPart;
                if (projectPart == currentEditorsProjectPart)
                    m_currentEditorsProjectPartIndex = m_projectPartsList.size() - 1;
            }
        }
    }
    emit layoutChanged();
}

QModelIndex ProjectPartsModel::indexForCurrentEditorsProjectPart() const
{
    if (m_currentEditorsProjectPartIndex == -1)
        return QModelIndex();
    return createIndex(m_currentEditorsProjectPartIndex, PartFilePathColumn);
}

ProjectPart::Ptr ProjectPartsModel::projectPartForProjectFile(const QString &projectFilePath) const
{
    foreach (const ProjectPart::Ptr &part, m_projectPartsList) {
        if (part->projectFile == projectFilePath)
            return part;
    }
    return ProjectPart::Ptr();
}

int ProjectPartsModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_projectPartsList.size();
}

int ProjectPartsModel::columnCount(const QModelIndex &/*parent*/) const
{
    return ProjectPartsModel::ColumnCount;
}

QVariant ProjectPartsModel::data(const QModelIndex &index, int role) const
{
    const int row = index.row();
    if (role == Qt::DisplayRole) {
        const int column = index.column();
        if (column == PartNameColumn)
            return m_projectPartsList.at(row)->displayName;
        else if (column == PartFilePathColumn)
            return QDir::toNativeSeparators(m_projectPartsList.at(row)->projectFile);
    }
    return QVariant();
}

QVariant ProjectPartsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case PartNameColumn:
            return QLatin1String("Name");
        case PartFilePathColumn:
            return QLatin1String("Project File Path");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- WorkingCopyModel ---------------------------------------------------------------------------

class WorkingCopyModel : public QAbstractListModel
{
    Q_OBJECT
public:
    WorkingCopyModel(QObject *parent);

    void configure(const CppModelManagerInterface::WorkingCopy &workingCopy);
    QModelIndex indexForFile(const QString &filePath);

    enum Columns { RevisionColumn, FilePathColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
    struct WorkingCopyEntry {
        WorkingCopyEntry(const QString &filePath, const QByteArray &source, unsigned revision)
            : filePath(filePath), source(source), revision(revision)
        {}

        QString filePath;
        QByteArray source;
        unsigned revision;
    };

    QList<WorkingCopyEntry> m_workingCopyList;
};

WorkingCopyModel::WorkingCopyModel(QObject *parent) : QAbstractListModel(parent)
{
}

void WorkingCopyModel::configure(const CppModelManagerInterface::WorkingCopy &workingCopy)
{
    emit layoutAboutToBeChanged();
    m_workingCopyList.clear();
    QHashIterator<QString, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
    while (it.hasNext()) {
        it.next();
        m_workingCopyList << WorkingCopyEntry(it.key(), it.value().first, it.value().second);
    }
    emit layoutChanged();
}

QModelIndex WorkingCopyModel::indexForFile(const QString &filePath)
{
    for (int i = 0, total = m_workingCopyList.size(); i < total; ++i) {
        const WorkingCopyEntry entry = m_workingCopyList.at(i);
        if (entry.filePath == filePath)
            return index(i, FilePathColumn);
    }
    return QModelIndex();
}

int WorkingCopyModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_workingCopyList.size();
}

int WorkingCopyModel::columnCount(const QModelIndex &/*parent*/) const
{
    return WorkingCopyModel::ColumnCount;
}

QVariant WorkingCopyModel::data(const QModelIndex &index, int role) const
{
    const int row = index.row();
    if (role == Qt::DisplayRole) {
        const int column = index.column();
        if (column == RevisionColumn)
            return m_workingCopyList.at(row).revision;
        else if (column == FilePathColumn)
            return m_workingCopyList.at(row).filePath;
    } else if (role == Qt::UserRole) {
        return m_workingCopyList.at(row).source;
    }
    return QVariant();
}

QVariant WorkingCopyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case RevisionColumn:
            return QLatin1String("Revision");
        case FilePathColumn:
            return QLatin1String("File Path");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- SnapshotInfo -------------------------------------------------------------------------------

class SnapshotInfo
{
public:
    enum Type { GlobalSnapshot, EditorSnapshot };
    SnapshotInfo(const CPlusPlus::Snapshot &snapshot, Type type)
        : snapshot(snapshot), type(type) {}

    CPlusPlus::Snapshot snapshot;
    Type type;
};

// --- CppCodeModelInspectorDialog ----------------------------------------------------------------

CppCodeModelInspectorDialog::CppCodeModelInspectorDialog(QWidget *parent)
    : QDialog(parent)
    , m_ui(new Ui::CppCodeModelInspectorDialog)
    , m_snapshotInfos(new QList<SnapshotInfo>())
    , m_snapshotView(new FilterableView(this))
    , m_snapshotModel(new SnapshotModel(this))
    , m_proxySnapshotModel(new QSortFilterProxyModel(this))
    , m_docGenericInfoModel(new KeyValueModel(this))
    , m_docIncludesModel(new IncludesModel(this))
    , m_docDiagnosticMessagesModel(new DiagnosticMessagesModel(this))
    , m_docMacrosModel(new MacrosModel(this))
    , m_docSymbolsModel(new SymbolsModel(this))
    , m_docTokensModel(new TokensModel(this))
    , m_projectPartsView(new FilterableView(this))
    , m_projectPartsModel(new ProjectPartsModel(this))
    , m_proxyProjectPartsModel(new QSortFilterProxyModel(this))
    , m_partGenericInfoModel(new KeyValueModel(this))
    , m_workingCopyView(new FilterableView(this))
    , m_workingCopyModel(new WorkingCopyModel(this))
    , m_proxyWorkingCopyModel(new QSortFilterProxyModel(this))
{
    m_ui->setupUi(this);
    m_ui->snapshotSelectorAndViewLayout->addWidget(m_snapshotView);
    m_ui->projectPartsSplitter->insertWidget(0, m_projectPartsView);
    m_ui->workingCopySplitter->insertWidget(0, m_workingCopyView);

    setAttribute(Qt::WA_DeleteOnClose);
    connect(Core::ICore::instance(), SIGNAL(coreAboutToClose()), SLOT(close()));

    m_proxySnapshotModel->setSourceModel(m_snapshotModel);
    m_proxySnapshotModel->setFilterKeyColumn(SnapshotModel::FilePathColumn);
    m_snapshotView->setModel(m_proxySnapshotModel);
    m_ui->docGeneralView->setModel(m_docGenericInfoModel);
    m_ui->docIncludesView->setModel(m_docIncludesModel);
    m_ui->docDiagnosticMessagesView->setModel(m_docDiagnosticMessagesModel);
    m_ui->docDefinedMacrosView->setModel(m_docMacrosModel);
    m_ui->docSymbolsView->setModel(m_docSymbolsModel);
    m_ui->docTokensView->setModel(m_docTokensModel);

    m_proxyProjectPartsModel->setSourceModel(m_projectPartsModel);
    m_proxyProjectPartsModel->setFilterKeyColumn(ProjectPartsModel::PartFilePathColumn);
    m_projectPartsView->setModel(m_proxyProjectPartsModel);
    m_ui->partGeneralView->setModel(m_partGenericInfoModel);

    m_proxyWorkingCopyModel->setSourceModel(m_workingCopyModel);
    m_proxyWorkingCopyModel->setFilterKeyColumn(WorkingCopyModel::FilePathColumn);
    m_workingCopyView->setModel(m_proxyWorkingCopyModel);

    connect(m_snapshotView->selectionModel(),
            SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            SLOT(onDocumentSelected(QModelIndex,QModelIndex)));
    connect(m_snapshotView, SIGNAL(filterChanged(QString)),
            SLOT(onSnapshotFilterChanged(QString)));
    connect(m_ui->snapshotSelector, SIGNAL(currentIndexChanged(int)),
            SLOT(onSnapshotSelected(int)));
    connect(m_ui->docSymbolsView, SIGNAL(expanded(QModelIndex)),
            SLOT(onSymbolsViewExpandedOrCollapsed(QModelIndex)));
    connect(m_ui->docSymbolsView, SIGNAL(collapsed(QModelIndex)),
            SLOT(onSymbolsViewExpandedOrCollapsed(QModelIndex)));

    connect(m_projectPartsView->selectionModel(),
            SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            SLOT(onProjectPartSelected(QModelIndex,QModelIndex)));
    connect(m_projectPartsView, SIGNAL(filterChanged(QString)),
            SLOT(onProjectPartFilterChanged(QString)));

    connect(m_workingCopyView->selectionModel(),
            SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            SLOT(onWorkingCopyDocumentSelected(QModelIndex,QModelIndex)));
    connect(m_workingCopyView, SIGNAL(filterChanged(QString)),
            SLOT(onWorkingCopyFilterChanged(QString)));

    connect(m_ui->refreshButton, SIGNAL(clicked()), SLOT(onRefreshRequested()));
    connect(m_ui->closeButton, SIGNAL(clicked()), SLOT(close()));

    refresh();
}

CppCodeModelInspectorDialog::~CppCodeModelInspectorDialog()
{
    delete m_snapshotInfos;
    delete m_ui;
}

void CppCodeModelInspectorDialog::onRefreshRequested()
{
    refresh();
}

void CppCodeModelInspectorDialog::onSnapshotFilterChanged(const QString &pattern)
{
    m_proxySnapshotModel->setFilterWildcard(pattern);
}

void CppCodeModelInspectorDialog::onSnapshotSelected(int row)
{
    if (row < 0 || row >= m_snapshotInfos->size())
        return;

    m_snapshotView->clearFilter();
    const SnapshotInfo info = m_snapshotInfos->at(row);
    m_snapshotModel->configure(info.snapshot);
    m_snapshotView->resizeColumns(SnapshotModel::ColumnCount);

    if (info.type == SnapshotInfo::GlobalSnapshot) {
        // Select first document
        const QModelIndex index = m_proxySnapshotModel->index(0, SnapshotModel::FilePathColumn);
        m_snapshotView->selectIndex(index);
    } else if (info.type == SnapshotInfo::EditorSnapshot) {
        // Select first document, unless we can find the editor document
        QModelIndex index = m_snapshotModel->indexForDocument(fileInCurrentEditor());
        index = m_proxySnapshotModel->mapFromSource(index);
        if (!index.isValid())
            index = m_proxySnapshotModel->index(0, SnapshotModel::FilePathColumn);
        m_snapshotView->selectIndex(index);
    }
}

void CppCodeModelInspectorDialog::onDocumentSelected(const QModelIndex &current,
                                                     const QModelIndex &)
{
    if (current.isValid()) {
        const QModelIndex index = m_proxySnapshotModel->index(current.row(),
                                                              SnapshotModel::FilePathColumn);
        const QString filePath = QDir::fromNativeSeparators(
            m_proxySnapshotModel->data(index, Qt::DisplayRole).toString());
        const SnapshotInfo info = m_snapshotInfos->at(m_ui->snapshotSelector->currentIndex());
        updateDocumentData(info.snapshot.document(filePath));
    } else {
        clearDocumentData();
    }
}

void CppCodeModelInspectorDialog::onSymbolsViewExpandedOrCollapsed(const QModelIndex &)
{
    resizeColumns<SymbolsModel>(m_ui->docSymbolsView);
}

void CppCodeModelInspectorDialog::onProjectPartFilterChanged(const QString &pattern)
{
    m_proxyProjectPartsModel->setFilterWildcard(pattern);
}

void CppCodeModelInspectorDialog::onProjectPartSelected(const QModelIndex &current,
                                                        const QModelIndex &)
{
    if (current.isValid()) {
        QModelIndex index = m_proxyProjectPartsModel->mapToSource(current);
        if (index.isValid()) {
            index = m_projectPartsModel->index(index.row(), ProjectPartsModel::PartFilePathColumn);
            const QString projectFilePath = QDir::fromNativeSeparators(
                m_projectPartsModel->data(index, Qt::DisplayRole).toString());
            updateProjectPartData(m_projectPartsModel->projectPartForProjectFile(projectFilePath));
        }
    } else {
        clearProjectPartData();
    }
}

void CppCodeModelInspectorDialog::onWorkingCopyFilterChanged(const QString &pattern)
{
    m_proxyWorkingCopyModel->setFilterWildcard(pattern);
}

void CppCodeModelInspectorDialog::onWorkingCopyDocumentSelected(const QModelIndex &current,
                                                                const QModelIndex &)
{
    if (current.isValid()) {
        const QModelIndex index = m_proxyWorkingCopyModel->mapToSource(current);
        if (index.isValid()) {
            const QString source
                = QString::fromUtf8(m_workingCopyModel->data(index, Qt::UserRole).toByteArray());
            m_ui->workingCopySourceEdit->setPlainText(source);
        }
    } else {
        m_ui->workingCopySourceEdit->setPlainText(QString());
    }
}

void CppCodeModelInspectorDialog::refresh()
{
    CppTools::CppModelManagerInterface *cmmi = CppTools::CppModelManagerInterface::instance();

    const int oldSnapshotIndex = m_ui->snapshotSelector->currentIndex();
    const bool selectEditorRelevant
        = m_ui->selectEditorRelevantEntriesAfterRefreshCheckBox->isChecked();

    // Snapshots and Documents
    m_snapshotInfos->clear();
    m_ui->snapshotSelector->clear();

    const CPlusPlus::Snapshot globalSnapshot = cmmi->snapshot();
    CppCodeModelInspector::Dumper dumper(globalSnapshot);
    m_snapshotModel->setGlobalSnapshot(globalSnapshot);

    m_snapshotInfos->append(SnapshotInfo(globalSnapshot, SnapshotInfo::GlobalSnapshot));
    const QString globalSnapshotTitle
        = QString::fromLatin1("Global/Indexing Snapshot (%1 Documents)").arg(globalSnapshot.size());
    m_ui->snapshotSelector->addItem(globalSnapshotTitle);
    dumper.dumpSnapshot(globalSnapshot, globalSnapshotTitle, /*isGlobalSnapshot=*/ true);

    TextEditor::BaseTextEditor *editor = currentEditor();
    CppEditorSupport *editorSupport = 0;
    if (editor) {
        editorSupport = cmmi->cppEditorSupport(editor);
        if (editorSupport) {
            const CPlusPlus::Snapshot editorSnapshot = editorSupport->snapshotUpdater()->snapshot();
            m_snapshotInfos->append(SnapshotInfo(editorSnapshot, SnapshotInfo::EditorSnapshot));
            const QString editorSnapshotTitle
                = QString::fromLatin1("Current Editor's Snapshot (%1 Documents)")
                    .arg(editorSnapshot.size());
            dumper.dumpSnapshot(editorSnapshot, editorSnapshotTitle);
            m_ui->snapshotSelector->addItem(editorSnapshotTitle);
        }
        CppEditor::Internal::CPPEditorWidget *cppEditorWidget
            = qobject_cast<CppEditor::Internal::CPPEditorWidget *>(editor->editorWidget());
        if (cppEditorWidget) {
            SemanticInfo semanticInfo = cppEditorWidget->semanticInfo();
            CPlusPlus::Snapshot snapshot;

            // Add semantic info snapshot
            snapshot = semanticInfo.snapshot;
            m_snapshotInfos->append(SnapshotInfo(snapshot, SnapshotInfo::EditorSnapshot));
            m_ui->snapshotSelector->addItem(
                QString::fromLatin1("Current Editor's Semantic Info Snapshot (%1 Documents)")
                    .arg(snapshot.size()));

            // Add a pseudo snapshot containing only the semantic info document since this document
            // is not part of the semantic snapshot.
            snapshot = CPlusPlus::Snapshot();
            snapshot.insert(cppEditorWidget->semanticInfo().doc);
            m_snapshotInfos->append(SnapshotInfo(snapshot, SnapshotInfo::EditorSnapshot));
            const QString snapshotTitle
                = QString::fromLatin1("Current Editor's Pseudo Snapshot with Semantic Info Document (%1 Documents)")
                    .arg(snapshot.size());
            dumper.dumpSnapshot(snapshot, snapshotTitle);
            m_ui->snapshotSelector->addItem(snapshotTitle);
        }
    }

    int snapshotIndex = 0;
    if (selectEditorRelevant) {
        for (int i = 0, total = m_snapshotInfos->size(); i < total; ++i) {
            const SnapshotInfo info = m_snapshotInfos->at(i);
            if (info.type == SnapshotInfo::EditorSnapshot) {
                snapshotIndex = i;
                break;
            }
        }
    } else if (oldSnapshotIndex < m_snapshotInfos->size()) {
        snapshotIndex = oldSnapshotIndex;
    }
    m_ui->snapshotSelector->setCurrentIndex(snapshotIndex);
    onSnapshotSelected(snapshotIndex);

    // Project Parts
    const ProjectPart::Ptr editorsProjectPart = editorSupport
        ? editorSupport->snapshotUpdater()->currentProjectPart()
        : ProjectPart::Ptr();

    const QList<CppModelManagerInterface::ProjectInfo> projectInfos = cmmi->projectInfos();
    dumper.dumpProjectInfos(projectInfos);
    m_projectPartsModel->configure(projectInfos, editorsProjectPart);
    m_projectPartsView->resizeColumns(ProjectPartsModel::ColumnCount);
    QModelIndex index = m_proxyProjectPartsModel->index(0, ProjectPartsModel::PartFilePathColumn);
    if (index.isValid()) {
        if (selectEditorRelevant && editorsProjectPart) {
            QModelIndex editorPartIndex = m_projectPartsModel->indexForCurrentEditorsProjectPart();
            editorPartIndex = m_proxyProjectPartsModel->mapFromSource(editorPartIndex);
            if (editorPartIndex.isValid())
                index = editorPartIndex;
        }
        m_projectPartsView->selectIndex(index);
    }

    // Working Copy
    const CppModelManagerInterface::WorkingCopy workingCopy = cmmi->workingCopy();
    dumper.dumpWorkingCopy(workingCopy);
    m_workingCopyModel->configure(workingCopy);
    m_workingCopyView->resizeColumns(WorkingCopyModel::ColumnCount);
    if (workingCopy.size() > 0) {
        QModelIndex index = m_proxyWorkingCopyModel->index(0, WorkingCopyModel::FilePathColumn);
        if (selectEditorRelevant) {
            const QModelIndex eindex = m_workingCopyModel->indexForFile(fileInCurrentEditor());
            if (eindex.isValid())
                index = m_proxyWorkingCopyModel->mapFromSource(eindex);
        }
        m_workingCopyView->selectIndex(index);
    }

    // Merged entities
    dumper.dumpMergedEntities(cmmi->headerPaths(), cmmi->definedMacros());
}

enum DocumentTabs {
    DocumentGeneralTab,
    DocumentIncludesTab,
    DocumentDiagnosticsTab,
    DocumentDefinedMacrosTab,
    DocumentPreprocessedSourceTab,
    DocumentSymbolsTab,
    DocumentTokensTab
};

static QString docTabName(int tabIndex, int numberOfEntries = -1)
{
    const char *names[] = {
        "&General",
        "&Includes",
        "&Diagnostic Messages",
        "(Un)Defined &Macros",
        "P&reprocessed Source",
        "&Symbols",
        "&Tokens"
    };
    QString result = QLatin1String(names[tabIndex]);
    if (numberOfEntries != -1)
        result += QString::fromLatin1(" (%1)").arg(numberOfEntries);
    return result;
}

void CppCodeModelInspectorDialog::clearDocumentData()
{
    m_docGenericInfoModel->clear();

    m_ui->docTab->setTabText(DocumentIncludesTab, docTabName(DocumentIncludesTab));
    m_docIncludesModel->clear();

    m_ui->docTab->setTabText(DocumentDiagnosticsTab, docTabName(DocumentDiagnosticsTab));
    m_docDiagnosticMessagesModel->clear();

    m_ui->docTab->setTabText(DocumentDefinedMacrosTab, docTabName(DocumentDefinedMacrosTab));
    m_docMacrosModel->clear();

    m_ui->docPreprocessedSourceEdit->setPlainText(QString());

    m_docSymbolsModel->clear();

    m_ui->docTab->setTabText(DocumentTokensTab, docTabName(DocumentTokensTab));
    m_docTokensModel->clear();
}

void CppCodeModelInspectorDialog::updateDocumentData(const CPlusPlus::Document::Ptr &document)
{
    QTC_ASSERT(document, return);

    // General
    KeyValueModel::Table table = KeyValueModel::Table()
        << qMakePair(QString::fromLatin1("File Path"),
                     QDir::toNativeSeparators(document->fileName()))
        << qMakePair(QString::fromLatin1("Last Modified"),
                     CMI::Utils::toString(document->lastModified()))
        << qMakePair(QString::fromLatin1("Revision"),
                     CMI::Utils::toString(document->revision()))
        << qMakePair(QString::fromLatin1("Editor Revision"),
                     CMI::Utils::toString(document->editorRevision()))
        << qMakePair(QString::fromLatin1("Check Mode"),
                     CMI::Utils::toString(document->checkMode()))
        << qMakePair(QString::fromLatin1("Tokenized"),
                     CMI::Utils::toString(document->isTokenized()))
        << qMakePair(QString::fromLatin1("Parsed"),
                     CMI::Utils::toString(document->isParsed()))
        << qMakePair(QString::fromLatin1("Project Parts"),
                     CMI::Utils::partsForFile(document->fileName()))
        ;
    m_docGenericInfoModel->configure(table);
    resizeColumns<KeyValueModel>(m_ui->docGeneralView);

    // Includes
    m_docIncludesModel->configure(document->resolvedIncludes() + document->unresolvedIncludes());
    resizeColumns<IncludesModel>(m_ui->docIncludesView);
    m_ui->docTab->setTabText(DocumentIncludesTab,
        docTabName(DocumentIncludesTab, m_docIncludesModel->rowCount()));

    // Diagnostic Messages
    m_docDiagnosticMessagesModel->configure(document->diagnosticMessages());
    resizeColumns<DiagnosticMessagesModel>(m_ui->docDiagnosticMessagesView);
    m_ui->docTab->setTabText(DocumentDiagnosticsTab,
        docTabName(DocumentDiagnosticsTab, m_docDiagnosticMessagesModel->rowCount()));

    // Macros
    m_docMacrosModel->configure(document->definedMacros());
    resizeColumns<MacrosModel>(m_ui->docDefinedMacrosView);
    m_ui->docTab->setTabText(DocumentDefinedMacrosTab,
        docTabName(DocumentDefinedMacrosTab, m_docMacrosModel->rowCount()));

    // Source
    m_ui->docPreprocessedSourceEdit->setPlainText(QString::fromUtf8(document->utf8Source()));

    // Symbols
    m_docSymbolsModel->configure(document);
    resizeColumns<SymbolsModel>(m_ui->docSymbolsView);

    // Tokens
    m_docTokensModel->configure(document->translationUnit());
    resizeColumns<TokensModel>(m_ui->docTokensView);
    m_ui->docTab->setTabText(DocumentTokensTab,
        docTabName(DocumentTokensTab, m_docTokensModel->rowCount()));
}

enum ProjectPartTabs {
    ProjectPartGeneralTab,
    ProjectPartFilesTab,
    ProjectPartDefinesTab,
    ProjectPartHeaderPathsTab,
    ProjectPartPrecompiledHeadersTab
};

static QString partTabName(int tabIndex, int numberOfEntries = -1)
{
    const char *names[] = {
        "&General",
        "Project &Files",
        "&Defines",
        "&Header Paths",
        "Pre&compiled Headers"
    };
    QString result = QLatin1String(names[tabIndex]);
    if (numberOfEntries != -1)
        result += QString::fromLatin1(" (%1)").arg(numberOfEntries);
    return result;
}

void CppCodeModelInspectorDialog::clearProjectPartData()
{
    m_partGenericInfoModel->clear();

    m_ui->partProjectFilesEdit->setPlainText(QString());
    m_ui->projectPartTab->setTabText(ProjectPartFilesTab, partTabName(ProjectPartFilesTab));

    m_ui->partToolchainDefinesEdit->setPlainText(QString());
    m_ui->partProjectDefinesEdit->setPlainText(QString());
    m_ui->projectPartTab->setTabText(ProjectPartDefinesTab, partTabName(ProjectPartDefinesTab));

    m_ui->partHeaderPathsEdit->setPlainText(QString());
    m_ui->projectPartTab->setTabText(ProjectPartHeaderPathsTab,
                                     partTabName(ProjectPartHeaderPathsTab));

    m_ui->partPrecompiledHeadersEdit->setPlainText(QString());
    m_ui->projectPartTab->setTabText(ProjectPartPrecompiledHeadersTab,
                                     partTabName(ProjectPartPrecompiledHeadersTab));
}

void CppCodeModelInspectorDialog::updateProjectPartData(const ProjectPart::Ptr &part)
{
    QTC_ASSERT(part, return);

    // General
    QString projectName = QLatin1String("<None>");
    QString projectFilePath = QLatin1String("<None>");
    if (ProjectExplorer::Project *project = part->project) {
        projectName = project->displayName();
        projectFilePath = project->projectFilePath().toUserOutput();
    }
    KeyValueModel::Table table = KeyValueModel::Table()
        << qMakePair(QString::fromLatin1("Project Part Name"), part->displayName)
        << qMakePair(QString::fromLatin1("Project Part File"),
                     QDir::toNativeSeparators(part->projectFile))
        << qMakePair(QString::fromLatin1("Project Name"), projectName)
        << qMakePair(QString::fromLatin1("Project File"), projectFilePath)
        << qMakePair(QString::fromLatin1("C Version"),
                     CMI::Utils::toString(part->cVersion))
        << qMakePair(QString::fromLatin1("CXX Version"),
                     CMI::Utils::toString(part->cxxVersion))
        << qMakePair(QString::fromLatin1("CXX Extensions"),
                     CMI::Utils::toString(part->cxxExtensions))
        << qMakePair(QString::fromLatin1("Qt Version"),
                     CMI::Utils::toString(part->qtVersion))
        ;
    if (!part->projectConfigFile.isEmpty())
        table.prepend(qMakePair(QString::fromLatin1("Project Config File"),
                                part->projectConfigFile));
    m_partGenericInfoModel->configure(table);
    resizeColumns<KeyValueModel>(m_ui->partGeneralView);

    // Project Files
    m_ui->partProjectFilesEdit->setPlainText(CMI::Utils::toString(part->files));
    m_ui->projectPartTab->setTabText(ProjectPartFilesTab,
        partTabName(ProjectPartFilesTab, part->files.size()));

    // Defines
    const QList<QByteArray> defineLines = part->toolchainDefines.split('\n')
        + part->projectDefines.split('\n');
    int numberOfDefines = 0;
    foreach (const QByteArray &line, defineLines) {
        if (line.startsWith("#define "))
            ++numberOfDefines;
    }
    m_ui->partToolchainDefinesEdit->setPlainText(QString::fromUtf8(part->toolchainDefines));
    m_ui->partProjectDefinesEdit->setPlainText(QString::fromUtf8(part->projectDefines));
    m_ui->projectPartTab->setTabText(ProjectPartDefinesTab,
        partTabName(ProjectPartDefinesTab, numberOfDefines));

    // Header Paths
    m_ui->partHeaderPathsEdit->setPlainText(CMI::Utils::pathListToString(part->headerPaths));
    m_ui->projectPartTab->setTabText(ProjectPartHeaderPathsTab,
        partTabName(ProjectPartHeaderPathsTab, part->headerPaths.size()));

    // Precompiled Headers
    m_ui->partPrecompiledHeadersEdit->setPlainText(
                CMI::Utils::pathListToString(part->precompiledHeaders));
    m_ui->projectPartTab->setTabText(ProjectPartPrecompiledHeadersTab,
        partTabName(ProjectPartPrecompiledHeadersTab, part->precompiledHeaders.size()));
}

bool CppCodeModelInspectorDialog::event(QEvent *e)
{
    if (e->type() == QEvent::ShortcutOverride) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(e);
        if (ke->key() == Qt::Key_Escape && !ke->modifiers()) {
            ke->accept();
            close();
            return false;
        }
    }
    return QDialog::event(e);
}

} // namespace Internal
} // namespace CppEditor

#include "cppcodemodelinspectordialog.moc"