aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/projectexplorer/projectwindow.cpp
blob: 04fbe2881949a0dd3c00882cf5de856f2a4be142 (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
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "projectwindow.h"

#include "buildinfo.h"
#include "buildmanager.h"
#include "buildsettingspropertiespage.h"
#include "devicesupport/devicekitaspects.h"
#include "devicesupport/idevicefactory.h"
#include "kit.h"
#include "kitmanager.h"
#include "kitoptionspage.h"
#include "project.h"
#include "projectexplorerconstants.h"
#include "projectexplorersettings.h"
#include "projectexplorertr.h"
#include "projectimporter.h"
#include "projectmanager.h"
#include "projectpanelfactory.h"
#include "projectsettingswidget.h"
#include "projectwindow.h"
#include "runsettingspropertiespage.h"
#include "target.h"
#include "targetsetuppage.h"
#include "task.h"

#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/coreicons.h>
#include <coreplugin/find/optionspopup.h>
#include <coreplugin/findplaceholder.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>
#include <coreplugin/modemanager.h>
#include <coreplugin/outputwindow.h>

#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>

#include <utils/algorithm.h>
#include <utils/basetreeview.h>
#include <utils/fileutils.h>
#include <utils/hostosinfo.h>
#include <utils/navigationtreeview.h>
#include <utils/qtcassert.h>
#include <utils/qtcsettings.h>
#include <utils/qtcwidgets.h>
#include <utils/styledbar.h>
#include <utils/stylehelper.h>
#include <utils/treemodel.h>
#include <utils/utilsicons.h>

#include <QApplication>
#include <QCheckBox>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QDockWidget>
#include <QHeaderView>
#include <QLabel>
#include <QMenu>
#include <QMessageBox>
#include <QMetaObject>
#include <QPainter>
#include <QPushButton>
#include <QScrollArea>
#include <QStyledItemDelegate>
#include <QToolButton>
#include <QVBoxLayout>

using namespace Core;
using namespace Utils;

namespace ProjectExplorer::Internal {

const char kBuildSystemOutputContext[] = "ProjectsMode.BuildSystemOutput";
const char kRegExpActionId[] = "OutputFilter.RegularExpressions.BuildSystemOutput";
const char kCaseSensitiveActionId[] = "OutputFilter.CaseSensitive.BuildSystemOutput";
const char kInvertActionId[] = "OutputFilter.Invert.BuildSystemOutput";

const int CONTENTS_MARGIN = 5;
const int BELOW_CONTENTS_MARGIN = 16;
const int PanelVMargin = 14;

class ProjectPanel : public QScrollArea
{
public:
    explicit ProjectPanel(QWidget *inner)
    {
        setWindowTitle(inner->windowTitle());
        setFocusProxy(inner);
        setFrameStyle(QFrame::NoFrame);
        setWidgetResizable(true);
        setFocusPolicy(Qt::NoFocus);

        inner->setContentsMargins(PanelVMargin, CONTENTS_MARGIN, PanelVMargin, BELOW_CONTENTS_MARGIN);

        setWidget(inner);
    }
};

class BuildSystemOutputWindow : public OutputWindow
{
public:
    BuildSystemOutputWindow();

    QWidget *toolBar();

private:
    void updateFilter();

    QPointer<QWidget> m_toolBar;
    QPointer<FancyLineEdit> m_filterOutputLineEdit;
    QAction m_clear;
    QAction m_filterActionRegexp;
    QAction m_filterActionCaseSensitive;
    QAction m_invertFilterAction;
    QAction m_zoomIn;
    QAction m_zoomOut;
};

BuildSystemOutputWindow::BuildSystemOutputWindow()
    : OutputWindow(Context(kBuildSystemOutputContext), "ProjectsMode.BuildSystemOutput.Zoom")
{
    setReadOnly(true);

    Command *clearCommand = ActionManager::command(Core::Constants::OUTPUTPANE_CLEAR);
    m_clear.setIcon(Utils::Icons::CLEAN_TOOLBAR.icon());
    m_clear.setText(clearCommand->action()->text());
    ActionManager::registerAction(&m_clear,
                                  Core::Constants::OUTPUTPANE_CLEAR,
                                  Context(kBuildSystemOutputContext));
    connect(&m_clear, &QAction::triggered, this, &OutputWindow::clear);

    m_filterActionRegexp.setCheckable(true);
    m_filterActionRegexp.setText(Tr::tr("Use Regular Expressions"));
    connect(&m_filterActionRegexp, &QAction::toggled, this, &BuildSystemOutputWindow::updateFilter);
    ActionManager::registerAction(&m_filterActionRegexp,
                                  kRegExpActionId,
                                  Context(Constants::C_PROJECTEXPLORER));

    m_filterActionCaseSensitive.setCheckable(true);
    m_filterActionCaseSensitive.setText(Tr::tr("Case Sensitive"));
    connect(&m_filterActionCaseSensitive,
            &QAction::toggled,
            this,
            &BuildSystemOutputWindow::updateFilter);
    ActionManager::registerAction(&m_filterActionCaseSensitive,
                                  kCaseSensitiveActionId,
                                  Context(Constants::C_PROJECTEXPLORER));

    m_invertFilterAction.setCheckable(true);
    m_invertFilterAction.setText(Tr::tr("Show Non-matching Lines"));
    connect(&m_invertFilterAction, &QAction::toggled, this, &BuildSystemOutputWindow::updateFilter);
    ActionManager::registerAction(&m_invertFilterAction,
                                  kInvertActionId,
                                  Context(Constants::C_PROJECTEXPLORER));

    connect(TextEditor::TextEditorSettings::instance(),
            &TextEditor::TextEditorSettings::fontSettingsChanged,
            this,
            [this] { setBaseFont(TextEditor::TextEditorSettings::fontSettings().font()); });
    setBaseFont(TextEditor::TextEditorSettings::fontSettings().font());

    m_zoomIn.setIcon(Utils::Icons::PLUS_TOOLBAR.icon());
    m_zoomIn.setText(ActionManager::command(Core::Constants::ZOOM_IN)->action()->text());
    connect(&m_zoomIn, &QAction::triggered, this, [this] { zoomIn(); });
    ActionManager::registerAction(&m_zoomIn,
                                  Core::Constants::ZOOM_IN,
                                  Context(kBuildSystemOutputContext));

    m_zoomOut.setIcon(Utils::Icons::MINUS_TOOLBAR.icon());
    m_zoomOut.setText(ActionManager::command(Core::Constants::ZOOM_OUT)->action()->text());
    connect(&m_zoomOut, &QAction::triggered, this, [this] { zoomOut(); });
    ActionManager::registerAction(&m_zoomOut,
                                  Core::Constants::ZOOM_OUT,
                                  Context(kBuildSystemOutputContext));
}

QWidget *BuildSystemOutputWindow::toolBar()
{
    if (!m_toolBar) {
        m_toolBar = new StyledBar(this);
        auto clearButton
            = Command::toolButtonWithAppendedShortcut(&m_clear, Core::Constants::OUTPUTPANE_CLEAR);

        m_filterOutputLineEdit = new FancyLineEdit;
        m_filterOutputLineEdit->setButtonVisible(FancyLineEdit::Left, true);
        m_filterOutputLineEdit->setButtonIcon(FancyLineEdit::Left, Utils::Icons::MAGNIFIER.icon());
        m_filterOutputLineEdit->setFiltering(true);
        m_filterOutputLineEdit->setHistoryCompleter("ProjectsMode.BuildSystemOutput.Filter");
        m_filterOutputLineEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
        connect(m_filterOutputLineEdit,
                &FancyLineEdit::textChanged,
                this,
                &BuildSystemOutputWindow::updateFilter);
        connect(m_filterOutputLineEdit,
                &FancyLineEdit::returnPressed,
                this,
                &BuildSystemOutputWindow::updateFilter);
        connect(m_filterOutputLineEdit, &FancyLineEdit::leftButtonClicked, this, [this] {
            auto popup = new OptionsPopup(m_filterOutputLineEdit,
                                          {kRegExpActionId,
                                           kCaseSensitiveActionId,
                                           kInvertActionId});
            popup->show();
        });

        auto zoomInButton = Command::toolButtonWithAppendedShortcut(&m_zoomIn,
                                                                    Core::Constants::ZOOM_IN);
        auto zoomOutButton = Command::toolButtonWithAppendedShortcut(&m_zoomOut,
                                                                     Core::Constants::ZOOM_OUT);

        auto layout = new QHBoxLayout;
        layout->setContentsMargins(0, 0, 0, 0);
        layout->setSpacing(0);
        m_toolBar->setLayout(layout);
        layout->addWidget(clearButton);
        layout->addWidget(m_filterOutputLineEdit);
        layout->addWidget(zoomInButton);
        layout->addWidget(zoomOutButton);
        layout->addStretch();
    }
    return m_toolBar;
}

void BuildSystemOutputWindow::updateFilter()
{
    if (!m_filterOutputLineEdit)
        return;
    updateFilterProperties(m_filterOutputLineEdit->text(),
                           m_filterActionCaseSensitive.isChecked() ? Qt::CaseSensitive
                                                                    : Qt::CaseInsensitive,
                           m_filterActionRegexp.isChecked(),
                           m_invertFilterAction.isChecked(),
                           0 /* before context */,
                           0 /* after context */);
}

using ProjectPanels = QList<QWidget *>;

// Overall structure:
//
// All items are derived from ProjectItemBase.
// First level are ProjectItems for all projects.
// Second level are the three fixed group items.
// Third level are the individual items in the group.
//
// ProjectModel
//    ProjectModel::rootItem()
//       ProjectItem
//           TargetGroupItem
//               TargetItem
//               ...
//           VanishedTargetsGroupItem
//               VanishedTargetPanelItem
//               ...
//           MiscSettingsGroupItem
//               MiscSettingsPanelItem
//               ...
//       ProjectItem
//           ...
//       ...
//
// The first level is shown in the project selection combobox.
// The second level is nowhere shown.
// The third level items are shown in the three treeviews in the left column.

class ProjectItemBase : public TreeItem
{
public:
    ProjectItemBase() = default;

    ~ProjectItemBase() = default;

    // This item got activated through user interaction and
    // is now responsible for the central widget.
    virtual void itemActivatedDirectly() {}

    // A subitem got activated and gives us the opportunity to adjust.
    virtual void itemActivatedFromBelow(const ProjectItemBase * /*trigger*/) {}

    // A parent item got activated and makes us its active child.
    virtual void itemActivatedFromAbove() {}

    // A subitem got deactivated and gives us the opportunity to adjust.
    virtual void itemDeactivatedFromBelow() {}

    // A subitem got updated, re-expansion is necessary.
    virtual void itemUpdatedFromBelow() {}

    // The index of the currently selected item in the tree view.
    virtual ProjectItemBase *activeItem() { return this; }

    // The kit id in case the item is associated with a kit.
    virtual Id kitId() const { return {}; }

    // This item's widget to be shown as central widget.
    virtual ProjectPanels panelWidgets() const { return {}; }

    // To augment a context menu
    virtual void addToMenu(QMenu * /*menu*/) const {}

    ProjectItemBase *parent() const { return static_cast<ProjectItemBase *>(TreeItem::parent()); }
    ProjectItemBase *childAt(int pos) const { return static_cast<ProjectItemBase *>(TreeItem::childAt(pos)); }
};

// Second level

//
// TargetGroupItem
//

class TargetItem;

class TargetGroupItem final : public ProjectItemBase
{
public:
    explicit TargetGroupItem(Project *project);
    ~TargetGroupItem() final;

    Qt::ItemFlags flags(int) const final { return Qt::NoItemFlags; }

    ProjectPanels panelWidgets() const final;
    ProjectItemBase *activeItem() final;
    void itemActivatedFromBelow(const ProjectItemBase *) final;
    void itemUpdatedFromBelow() final;

    TargetItem *currentTargetItem() const;
    TargetItem *targetItem(Target *target) const;

    void scheduleRebuildContents();
    void rebuildContents();

private:
    const QPointer<Project> m_project;
    bool m_rebuildScheduled = false;

    mutable QPointer<ProjectPanel> m_targetSetupPanel;
    QObject m_guard;
};

class VanishedTargetPanelItem final : public ProjectItemBase
{
public:
    VanishedTargetPanelItem(const Store &store, Project *project)
        : m_store(store)
        , m_project(project)
    {}

    QVariant data(int column, int role) const final;
    Qt::ItemFlags flags(int column) const final;

    void addToMenu(QMenu *menu) const;
    void itemActivatedDirectly();

protected:
    Store m_store;
    const QPointer<Project> m_project;
};

static QString deviceTypeDisplayName(const Store &store)
{
    Id deviceTypeId = Id::fromSetting(store.value(Target::deviceTypeKey()));
    if (!deviceTypeId.isValid())
        deviceTypeId = Constants::DESKTOP_DEVICE_TYPE;

    QString typeDisplayName = Tr::tr("Unknown device type");
    if (deviceTypeId.isValid()) {
        if (IDeviceFactory *factory = IDeviceFactory::find(deviceTypeId))
            typeDisplayName = factory->displayName();
    }
    return typeDisplayName;
}

static QString msgOptionsForRestoringSettings()
{
    return "<html>"
           + Tr::tr("The project was configured for kits that no longer exist. Select one of the "
                    "following options in the context menu to restore the project's settings:")
           + "<ul><li>"
           + Tr::tr("Create a new kit with the same name for the same device type, with the "
                    "original build, deploy, and run steps. Other kit settings are not restored.")
           + "</li><li>" + Tr::tr("Copy the build, deploy, and run steps to another kit.")
           + "</li></ul></html>";
}

QVariant VanishedTargetPanelItem::data(int column, int role) const
{
    Q_UNUSED(column)
    switch (role) {
    case Qt::DisplayRole:
        //: vanished target display role: vanished target name (device type name)
        return Tr::tr("%1 (%2)").arg(m_store.value(Target::displayNameKey()).toString(),
                                     deviceTypeDisplayName(m_store));
    case Qt::ToolTipRole:
        return msgOptionsForRestoringSettings();
    }

    return {};
}

void VanishedTargetPanelItem::addToMenu(QMenu *menu) const
{
    const int index = indexInParent();
    menu->addAction(Tr::tr("Create a New Kit"),
                    m_project.data(),
                    [index, store = m_store, project = m_project] {
        Target *t = project->createKitAndTargetFromStore(store);
        if (t) {
            project->setActiveTarget(t, SetActive::Cascade);
            project->removeVanishedTarget(index);
        }
    });
    QMenu *copyMenu = menu->addMenu(Tr::tr("Copy Steps to Another Kit"));
    const QList<Kit *> kits = KitManager::kits();
    for (Kit *kit : kits) {
        QAction *copyAction = copyMenu->addAction(kit->displayName());
        QObject::connect(copyAction,
                         &QAction::triggered,
                         [index, store = m_store, project = m_project, kit] {
            if (project->copySteps(store, kit))
                project->removeVanishedTarget(index);
        });
    }
    menu->addSeparator();
    menu->addAction(Tr::tr("Remove Vanished Target \"%1\"")
                        .arg(m_store.value(Target::displayNameKey()).toString()),
                    m_project.data(),
                    [index, project = m_project] { project->removeVanishedTarget(index); });
    menu->addAction(Tr::tr("Remove All Vanished Targets"),
                    m_project.data(),
                    [project = m_project] { project->removeAllVanishedTargets(); });
}

void VanishedTargetPanelItem::itemActivatedDirectly()
{
    QMenu menu;
    addToMenu(&menu);
    menu.exec(QCursor::pos());
}

Qt::ItemFlags VanishedTargetPanelItem::flags(int column) const
{
    Q_UNUSED(column)
    return Qt::ItemIsEnabled;
}

// The middle part of the second tree level, i.e. the list of vanished configured kits/targets.
class VanishedTargetsGroupItem : public ProjectItemBase
{
public:
    explicit VanishedTargetsGroupItem(Project *project)
        : m_project(project)
    {
        QTC_ASSERT(m_project, return);
        rebuild();
    }

    void rebuild()
    {
        removeChildren();
        for (const Store &store : m_project->vanishedTargets())
            appendChild(new VanishedTargetPanelItem(store, m_project));
    }

    Qt::ItemFlags flags(int) const final { return Qt::NoItemFlags; }

    QVariant data(int column, int role) const final
    {
        Q_UNUSED(column)
        switch (role) {
        case Qt::ToolTipRole:
            return msgOptionsForRestoringSettings();
        }
        return {};
    }

private:
    const QPointer<Project> m_project;
};

// Standard third level for the generic case: i.e. all except for the Build/Run page

class MiscSettingsPanelItem final : public ProjectItemBase
{
public:
    MiscSettingsPanelItem(ProjectPanelFactory *factory, Project *project)
        : m_factory(factory), m_project(project)
    {}

    ~MiscSettingsPanelItem() final { delete m_widget; }

    QVariant data(int column, int role) const final;
    Qt::ItemFlags flags(int column) const final;
    ProjectPanels panelWidgets() const final;
    ProjectItemBase *activeItem() final;
    void itemActivatedDirectly() final;

    Id panelId() const { return m_factory->id(); }

protected:
    ProjectPanelFactory *m_factory = nullptr;
    const QPointer<Project> m_project;
    mutable QPointer<QWidget> m_widget = nullptr;
};

QVariant MiscSettingsPanelItem::data(int column, int role) const
{
    Q_UNUSED(column)
    if (role == Qt::DisplayRole) {
        if (m_factory)
            return m_factory->displayName();
    }
    return {};
}

ProjectPanels MiscSettingsPanelItem::panelWidgets() const
{
    if (!m_widget) {
        m_widget = new ProjectPanel(m_factory->createWidget(m_project));
        m_widget->setWindowTitle(m_factory->displayName());
    }
    return {m_widget.get()};
}

ProjectItemBase *MiscSettingsPanelItem::activeItem()
{
    return this; // We are the active one.
}

Qt::ItemFlags MiscSettingsPanelItem::flags(int column) const
{
    if (m_factory && m_project) {
        if (!m_factory->supports(m_project))
            return Qt::ItemIsSelectable;
    }
    return TreeItem::flags(column);
}

void MiscSettingsPanelItem::itemActivatedDirectly()
{
    // Bubble up
    return parent()->itemActivatedFromBelow(this);
}

// The lower part of the second tree level, i.e. the project settings list.
// The upper part is the TargetSettingsPanelItem .
class MiscSettingsGroupItem : public ProjectItemBase
{
public:
    explicit MiscSettingsGroupItem(Project *project)
    {
        QTC_ASSERT(project, return);
        const QList<ProjectPanelFactory *> factories = ProjectPanelFactory::factories();
        for (ProjectPanelFactory *factory : factories)
            appendChild(new MiscSettingsPanelItem(factory, project));
    }

    Qt::ItemFlags flags(int) const final
    {
        return Qt::NoItemFlags;
    }

    ProjectItemBase *activeItem() final
    {
        if (0 <= m_currentPanelIndex && m_currentPanelIndex < childCount())
            return childAt(m_currentPanelIndex)->activeItem();
        return nullptr;
    }

    void itemActivatedFromBelow(const ProjectItemBase *trigger) final
    {
        m_currentPanelIndex = indexOf(trigger);
        QTC_ASSERT(m_currentPanelIndex != -1, return);
        parent()->itemActivatedFromBelow(this);
    }

private:
    int m_currentPanelIndex = -1;
};

// The first tree level, i.e. projects.
class ProjectItem : public ProjectItemBase
{
public:
    ProjectItem() = default;

    ProjectItem(Project *project, const std::function<void()> &changeListener)
        : m_project(project), m_changeListener(changeListener)
    {
        QTC_ASSERT(m_project, return);
        appendChild(m_targetsItem = new TargetGroupItem(m_project));
        appendChild(m_vanishedTargetsItem = new VanishedTargetsGroupItem(m_project));
        appendChild(m_miscItem = new MiscSettingsGroupItem(m_project));
        QObject::connect(
            m_project,
            &Project::vanishedTargetsChanged,
            &m_guard,
            [this] { m_vanishedTargetsItem->rebuild(); },
            Qt::QueuedConnection /* this is triggered by a child item, so queue */);

        QObject::connect(project, &Project::removedTarget, &m_guard, [this] {
            announceChange();
        });

        QObject::connect(project, &Project::activeTargetChanged, &m_guard, [this] {
            announceChange();
        });

        QObject::connect(project, &Project::addedTarget, &m_guard, [this] {
            announceChange();
        });
    }

    ~ProjectItem()
    {
        // Actual deletion of the items below happens in the base destructor,
        // this here just removes some later dangling pointers for better debugging.
        m_targetsItem = nullptr;
        m_vanishedTargetsItem = nullptr;
        m_miscItem = nullptr;
    }

    QVariant data(int column, int role) const final
    {
        Q_UNUSED(column);
        switch (role) {
        case Qt::DisplayRole:
            return m_project->displayName();

        case Qt::FontRole: {
            QFont font;
            font.setBold(m_project == ProjectManager::startupProject());
            return font;
        }
        }

        return {};
    }

    ProjectItemBase *activeItem() final
    {
        if (ProjectItemBase *child = childAt(m_currentChildIndex))
            return child->activeItem();
        return nullptr;
    }

    void itemUpdatedFromBelow() final
    {
        announceChange();
    }

    void itemDeactivatedFromBelow() final
    {
        announceChange();
    }

    void itemActivatedFromBelow(const ProjectItemBase *item) final
    {
        QTC_ASSERT(item, return);
        int res = indexOf(item);
        QTC_ASSERT(res >= 0, return);
        m_currentChildIndex = res;
        announceChange();
    }

    void itemActivatedFromAbove() final
    {
        // Someone selected the project using the combobox or similar.
        ProjectManager::setStartupProject(m_project);
        m_currentChildIndex = 0; // Use some Target page by defaults
        m_targetsItem->itemActivatedFromAbove(); // And propagate downwards.
        announceChange();
    }

    void announceChange()
    {
        m_changeListener();
    }

    Project *project() const { return m_project; }

    TreeItem *itemForProjectPanel(Id panelId)
    {
        return m_miscItem->findChildAtLevel(1, [panelId](const TreeItem *item){
            return dynamic_cast<const MiscSettingsPanelItem *>(item)->panelId() == panelId;
        });
    }

    TargetGroupItem *targetsItem() const { return m_targetsItem; }
    VanishedTargetsGroupItem *vanishedTargetsItem() const { return m_vanishedTargetsItem; }
    MiscSettingsGroupItem *miscSettingsItem() const { return m_miscItem; }

private:
    int m_currentChildIndex = 0; // Start with Build & Run.
    Project *m_project = nullptr;
    TargetGroupItem *m_targetsItem = nullptr;
    VanishedTargetsGroupItem *m_vanishedTargetsItem = nullptr;
    MiscSettingsGroupItem *m_miscItem = nullptr;
    const std::function<void ()> m_changeListener;
    QObject m_guard;
};

class TargetSetupPageWrapper final : public QWidget
{
public:
    explicit TargetSetupPageWrapper(Project *project)
        : m_project(project)
    {
        setWindowTitle(Tr::tr("Configure Project"));

        m_configureButton.setText(Tr::tr("&Configure Project"));

        m_targetSetupPage.setProjectAndPath(m_project, m_project->projectFilePath());
        m_targetSetupPage.setTasksGenerator([this](const Kit *k) {
            QTC_ASSERT(m_project.get(), return Tasks());
            return m_project->projectIssues(k);
        });
        m_targetSetupPage.setProjectImporter(m_project->projectImporter());
        m_targetSetupPage.initializePage();
        m_targetSetupPage.setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);

        auto setupPageContainer = new QVBoxLayout;
        setupPageContainer->addWidget(&m_targetSetupPage);

        auto hbox = new QHBoxLayout;
        hbox->addStretch();
        hbox->addWidget(&m_configureButton);

        auto layout = new QVBoxLayout(this);
        layout->setContentsMargins(0, 0, 0, 0);
        layout->addLayout(setupPageContainer);
        layout->addLayout(hbox);

        onCompleteChanged();

        connect(&m_targetSetupPage, &QWizardPage::completeChanged,
                this, &TargetSetupPageWrapper::onCompleteChanged);

        connect(&m_configureButton, &QAbstractButton::clicked,
                this, &TargetSetupPageWrapper::done);
    }

protected:
    void keyReleaseEvent(QKeyEvent *event) final
    {
        if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
            event->accept();
    }

    void keyPressEvent(QKeyEvent *event) final
    {
        if (m_targetSetupPage.importLineEditHasFocus() || !m_configureButton.isEnabled())
            return;

        if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
            event->accept();
            done();
        }
    }

private:
    void done()
    {
        disconnect(&m_targetSetupPage, &QWizardPage::completeChanged,
                   this, &TargetSetupPageWrapper::onCompleteChanged);
        m_targetSetupPage.setupProject(m_project);
        ModeManager::activateMode(Core::Constants::MODE_EDIT);
    }

    void onCompleteChanged()
    {
        m_configureButton.setEnabled(m_targetSetupPage.isComplete());
    }

    QPointer<Project> m_project;
    TargetSetupPage m_targetSetupPage;
    QPushButton m_configureButton;
    QDialogButtonBox m_buttonBox;
};

//
// Third level: The per-kit entries
//
class TargetItem final : public ProjectItemBase
{
public:
    enum TargetItemDataRole {
        CanEnableRole = Qt::UserRole + 1,
    };

    TargetItem(Project *project, Id kitId, const Tasks &issues)
        : m_project(project), m_kitId(kitId), m_kitIssues(issues)
    {
        m_kitWarningForProject = containsType(m_kitIssues, Task::TaskType::Warning);
        m_kitErrorsForProject = containsType(m_kitIssues, Task::TaskType::Error);

        m_targetRemovedConnection = QObject::connect(
            project,
            &ProjectExplorer::Project::removedTarget,
            [this, t = target()](ProjectExplorer::Target *rt) {
                if (t == rt) {
                    m_buildSettingsWidget.clear();
                    m_deploySettingsWidget.clear();
                    m_runSettingsWidget.clear();
                }
            });
    }

    ~TargetItem()
    {
        m_project->disconnect(m_targetRemovedConnection);
        delete m_buildSettingsWidget;
        delete m_deploySettingsWidget;
        delete m_runSettingsWidget;
    }

    Target *target() const
    {
        return m_project->target(m_kitId);
    }

    Id kitId() const
    {
        return m_kitId;
    }

    Qt::ItemFlags flags(int column) const final
    {
        Q_UNUSED(column)
        return m_kitErrorsForProject ? Qt::ItemFlags({})
                                     : Qt::ItemFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    }

    QVariant data(int column, int role) const final
    {
        switch (role) {
        case Qt::DisplayRole: {
            if (Kit *kit = KitManager::kit(m_kitId))
                return kit->displayName();
            break;
        }

        case Qt::DecorationRole: {
            const Kit *k = KitManager::kit(m_kitId);
            if (!k)
                break;
            if (m_kitErrorsForProject)
                return kitIconWithOverlay(*k, IconOverlay::Error);
            if (!isEnabled())
                return kitIconWithOverlay(*k, IconOverlay::Add);
            if (m_kitWarningForProject)
                return kitIconWithOverlay(*k, IconOverlay::Warning);
            return k->icon();
        }

        case Qt::ForegroundRole: {
            if (!isEnabled())
                return Utils::creatorColor(Theme::TextColorDisabled);
            break;
        }

        case Qt::FontRole: {
            QFont font = parent()->data(column, role).value<QFont>();
            if (TargetItem *targetItem = dynamic_cast<TargetGroupItem *>(parent())->currentTargetItem()) {
                Target *t = targetItem->target();
                if (t && t->id() == m_kitId && m_project == ProjectManager::startupProject())
                    font.setBold(true);
            }
            return font;
        }

        case Qt::ToolTipRole: {
            Kit *k = KitManager::kit(m_kitId);
            if (!k)
                break;
            const QString extraText = [this] {
                if (m_kitErrorsForProject)
                    return QString("<h3>" + Tr::tr("Kit is unsuited for project") + "</h3>");
                if (isEnabled())
                    return QString();
                return QString("<h3>"
                    + Tr::tr("Click to enable target, click again to make active") + "</h3>");
            }();
            return k->toHtml(m_kitIssues, extraText);
        }

        case CanEnableRole: {
            const Kit *k = KitManager::kit(m_kitId);
            return k && !m_kitErrorsForProject && !isEnabled();
        }

        default:
            break;
        }
        return {};
    }

    ProjectPanels panelWidgets() const final
    {
        if (!m_buildSettingsWidget)
            m_buildSettingsWidget = new ProjectPanel(createBuildSettingsWidget(target()));
        if (!m_deploySettingsWidget)
            m_deploySettingsWidget = new ProjectPanel(createDeploySettingsWidget(target()));
        if (!m_runSettingsWidget)
            m_runSettingsWidget = new ProjectPanel(createRunSettingsWidget(target()));

        return {
            m_buildSettingsWidget.get(),
            m_deploySettingsWidget.get(),
            m_runSettingsWidget.get()
        };
    }

    void addToMenu(QMenu *menu) const final
    {
        addToContextMenu(menu, flags(/*column = */ 0) & Qt::ItemIsSelectable);
    }

    void itemActivatedDirectly() final
    {
        if (!isEnabled()) {
            m_project->addTargetForKit(KitManager::kit(m_kitId));
        } else {
            // Go to Run page, when on Run previously etc.
            m_project->setActiveTarget(target(), SetActive::Cascade);
            parent()->itemActivatedFromBelow(this);
        }
    }

    void itemActivatedFromAbove() final
    {
        // Usually programmatic activation, e.g. after opening the Project mode.
        m_project->setActiveTarget(target(), SetActive::Cascade);
    }

    void addToContextMenu(QMenu *menu, bool isSelectable) const
    {
        Kit *kit = KitManager::kit(m_kitId);
        QTC_ASSERT(kit, return);
        const QString projectName = m_project->displayName();

        QAction *enableAction = menu->addAction(Tr::tr("Enable Kit for Project \"%1\"").arg(projectName));
        enableAction->setEnabled(isSelectable && m_kitId.isValid() && !isEnabled());
        QObject::connect(enableAction, &QAction::triggered, [this, kit] {
            m_project->addTargetForKit(kit);
        });

        QAction * const enableForAllAction
                = menu->addAction(Tr::tr("Enable Kit for All Projects"));
        enableForAllAction->setEnabled(isSelectable);
        QObject::connect(enableForAllAction, &QAction::triggered, [kit] {
            for (Project * const p : ProjectManager::projects()) {
                if (!p->target(kit))
                    p->addTargetForKit(kit);
            }
        });

        QAction *disableAction = menu->addAction(Tr::tr("Disable Kit for Project \"%1\"").arg(projectName));
        disableAction->setEnabled(isSelectable && m_kitId.isValid() && isEnabled());
        QObject::connect(disableAction, &QAction::triggered, m_project, [this] {
            Target *t = target();
            QTC_ASSERT(t, return);
            QString kitName = t->displayName();
            if (BuildManager::isBuilding(t)) {
                QMessageBox box;
                QPushButton *closeAnyway = box.addButton(Tr::tr("Cancel Build and Disable Kit in This Project"), QMessageBox::AcceptRole);
                QPushButton *cancelClose = box.addButton(Tr::tr("Do Not Remove"), QMessageBox::RejectRole);
                box.setDefaultButton(cancelClose);
                box.setWindowTitle(Tr::tr("Disable Kit \"%1\" in This Project?").arg(kitName));
                box.setText(Tr::tr("The kit <b>%1</b> is currently being built.").arg(kitName));
                box.setInformativeText(Tr::tr("Do you want to cancel the build process and remove the kit anyway?"));
                box.exec();
                if (box.clickedButton() != closeAnyway)
                    return;
                BuildManager::cancel();
            }

            QCoreApplication::processEvents();

            m_project->removeTarget(t);
        });

        QAction *disableForAllAction = menu->addAction(Tr::tr("Disable Kit for All Projects"));
        disableForAllAction->setEnabled(isSelectable);
        QObject::connect(disableForAllAction, &QAction::triggered, [kit] {
            for (Project * const p : ProjectManager::projects()) {
                Target * const t = p->target(kit);
                if (!t)
                    continue;
                if (BuildManager::isBuilding(t))
                    BuildManager::cancel();
                p->removeTarget(t);
            }
        });

        QMenu *copyMenu = menu->addMenu(Tr::tr("Copy Steps From Another Kit..."));
        if (m_kitId.isValid()) {
            const QList<Kit *> kits = KitManager::kits();
            for (Kit *kit : kits) {
                QAction *copyAction = copyMenu->addAction(kit->displayName());
                if (kit->id() == m_kitId || !m_project->target(kit->id())) {
                    copyAction->setEnabled(false);
                } else {
                    QObject::connect(copyAction, &QAction::triggered, [this, kit] {
                        Target *sourceTarget = m_project->target(kit->id());
                        m_project->copySteps(sourceTarget, KitManager::kit(m_kitId));
                    });
                }
            }
        } else {
            copyMenu->setEnabled(false);
        }
    }

private:
    enum class IconOverlay {
        Add,
        Warning,
        Error
    };

    static QIcon kitIconWithOverlay(const Kit &kit, IconOverlay overlayType)
    {
        QIcon overlayIcon;
        switch (overlayType) {
        case IconOverlay::Add:
            break;
        case IconOverlay::Warning: {
            static const QIcon warning = Utils::Icons::OVERLAY_WARNING.icon();
            overlayIcon = warning;
            break;
        }
        case IconOverlay::Error: {
            static const QIcon err = Utils::Icons::OVERLAY_ERROR.icon();
            overlayIcon = err;
            break;
        }
        }
        const QSize iconSize(16, 16);
        const QRect iconRect(QPoint(), iconSize);
        QPixmap result(iconSize * qApp->devicePixelRatio());
        result.fill(Qt::transparent);
        result.setDevicePixelRatio(qApp->devicePixelRatio());
        QPainter p(&result);
        kit.icon().paint(&p, iconRect, Qt::AlignCenter,
                         overlayType == IconOverlay::Add ? QIcon::Disabled : QIcon::Normal);
        overlayIcon.paint(&p, iconRect);
        return result;
    }

    bool isEnabled() const { return target() != nullptr; }

public:
    QPointer<Project> m_project; // Not owned.

    Id m_kitId;
    bool m_kitErrorsForProject = false;
    bool m_kitWarningForProject = false;
    Tasks m_kitIssues;

    mutable QPointer<QWidget> m_buildSettingsWidget;
    mutable QPointer<QWidget> m_deploySettingsWidget;
    mutable QPointer<QWidget> m_runSettingsWidget;
    QMetaObject::Connection m_targetRemovedConnection;
};

//
// Also third level:
//

TargetGroupItem::TargetGroupItem(Project *project)
    : m_project(project)
{
    QObject::connect(project, &Project::addedTarget, &m_guard, [this] { update(); });

    QObject::connect(KitManager::instance(), &KitManager::kitAdded, &m_guard, [this] {
        scheduleRebuildContents();
    });

    QObject::connect(KitManager::instance(), &KitManager::kitRemoved, &m_guard, [this] {
         scheduleRebuildContents();
    });
    QObject::connect(KitManager::instance(), &KitManager::kitUpdated, &m_guard, [this] {
         scheduleRebuildContents();
    });
    QObject::connect(KitManager::instance(), &KitManager::kitsLoaded, &m_guard, [this] {
         scheduleRebuildContents();
    });

    globalProjectExplorerSettings().kitFilter.addOnChanged(&m_guard, [this] {
        scheduleRebuildContents();
    });

    rebuildContents();
}

TargetGroupItem::~TargetGroupItem()
{
    delete m_targetSetupPanel;
}

ProjectItemBase *TargetGroupItem::activeItem()
{
    if (TargetItem *item = currentTargetItem())
        return item->activeItem();
    return this;
}

ProjectPanels TargetGroupItem::panelWidgets() const
{
    if (!m_targetSetupPanel)
        m_targetSetupPanel = new ProjectPanel(new TargetSetupPageWrapper(m_project));

    return {m_targetSetupPanel.get()};
}

void TargetGroupItem::itemActivatedFromBelow(const ProjectItemBase *)
{
    parent()->itemActivatedFromBelow(this);
}

void TargetGroupItem::itemUpdatedFromBelow()
{
    // Bubble up to trigger setting the active project.
    QTC_ASSERT(parent(), return);
    parent()->itemUpdatedFromBelow();
}

TargetItem *TargetGroupItem::currentTargetItem() const
{
    return targetItem(m_project->activeTarget());
}

TargetItem *TargetGroupItem::targetItem(Target *target) const
{
    if (target) {
        const Id needle = target->id(); // Unconfigured project have no active target.
        for (int i = 0, n = childCount(); i != n; ++i) {
            ProjectItemBase *child = childAt(i);
            if (child->kitId() == needle) {
                auto targetItem = dynamic_cast<TargetItem *>(child);
                QTC_CHECK(targetItem);
                return targetItem;
            }
        }
    }
    return nullptr;
}

void TargetGroupItem::scheduleRebuildContents()
{
    if (m_rebuildScheduled)
        return;
    m_rebuildScheduled = true;
    QMetaObject::invokeMethod(&m_guard, [this] { rebuildContents(); }, Qt::QueuedConnection);
}

void TargetGroupItem::rebuildContents()
{
    m_rebuildScheduled = false;
    QGuiApplication::setOverrideCursor(Qt::WaitCursor);
    const auto sortedKits = KitManager::sortedKits();
    removeChildren();

    const KitFilter kitFilter = globalProjectExplorerSettings().kitFilter();

    for (Kit *kit : sortedKits) {
        const auto appendItem = [&] {
            appendChild(new TargetItem(m_project, kit->id(), m_project->projectIssues(kit)));
        };

        if (kitFilter == KitFilter::ShowAll) {
            appendItem();
            continue;
        }

        if (kitFilter == KitFilter::ShowOnlyMatching) {
            if (m_project->projectIssues(kit).isEmpty())
                appendItem();
            continue;
        }

        if (m_project->target(kit->id()) != nullptr) {
            appendItem();
            continue;
        }
    }

    if (parent())
        parent()->itemUpdatedFromBelow();

    QGuiApplication::restoreOverrideCursor();
}

//
// SelectorTree
//

class SelectorDelegate : public QStyledItemDelegate
{
public:
    SelectorDelegate() = default;

    void paint(QPainter *painter, const QStyleOptionViewItem &option,
               const QModelIndex &index) const override
    {
        painter->save();
        painter->translate(addIconWidth, 0);
        QStyledItemDelegate::paint(painter, option, index);
        painter->restore();
        if (index.data(TargetItem::CanEnableRole).toBool()) {
            QRect iconRect = option.rect;
            iconRect.setWidth(addIconWidth);
            painter->save();
            painter->setPen(creatorColor(Theme::Token_Notification_Success_Default));
            painter->drawText(iconRect, "+", QTextOption(Qt::AlignLeft | Qt::AlignVCenter));
            painter->restore();
        }
    }

    QSize sizeHint(const QStyleOptionViewItem &option,
                   const QModelIndex &index) const final
    {
        QSize s = QStyledItemDelegate::sizeHint(option, index);
        return QSize(s.width() + addIconWidth, s.height() * 1.2);
    }

private:
    static const int addIconWidth = 8;
};

class SelectorTree : public TreeView
{
public:
    SelectorTree()
    {
        setSizeAdjustPolicy(QAbstractItemView::SizeAdjustPolicy::AdjustToContents);
        setFrameStyle(QFrame::NoFrame);
        setItemDelegate(&m_selectorDelegate);
        setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        setExpandsOnDoubleClick(false);
        setHeaderHidden(true);
        setItemsExpandable(false); // No user interaction.
        setRootIsDecorated(false);
        setSelectionMode(QAbstractItemView::SingleSelection);
        setSelectionBehavior(QAbstractItemView::SelectRows);
        setEditTriggers(QAbstractItemView::NoEditTriggers);
        setActivationMode(SingleClickActivation);
        setObjectName("ProjectNavigation");
        setContextMenuPolicy(Qt::CustomContextMenu);
    }

    QSize minimumSizeHint() const final
    {
        return {10, 10};
    }

    void updateSize()
    {
        resizeColumnToContents(0);
        updateGeometry();
    }

private:
    // remove branch indicators
    void drawBranches(QPainter *, const QRect &, const QModelIndex &) const final
    {
        return;
    }

    bool userWantsContextMenu(const QMouseEvent *e) const final
    {
        // On Windows, we get additional mouse events for the item view when right-clicking,
        // causing unwanted kit activation (QTCREATORBUG-24156). Let's suppress these.
        return HostOsInfo::isWindowsHost() && e->button() == Qt::RightButton;
    }

    SelectorDelegate m_selectorDelegate;
};

using ProjectsModel = TreeModel<TypedTreeItem<ProjectItem>, ProjectItem>;

//
// ProjectWindowPrivate
//

class ProjectWindowTabWidget : public QTabWidget
{
public:
    ProjectWindowTabWidget(QWidget *parent = nullptr)
        : QTabWidget(parent)
    {
        auto tabBar = new QtcTabBar;
        setTabBar(tabBar); // Must be the first called setter!
        tabBar->setObjectName("ProjectConfigurationTabBar"); // used by Squish
        setDocumentMode(true);
    }
};

class CentralWidget : public QWidget
{
public:
    explicit CentralWidget(QWidget *parent)
        : QWidget(parent)
    {
        m_tabWidget = new ProjectWindowTabWidget(this);

        auto layout = new QVBoxLayout(this);
        layout->setContentsMargins(0, 0, 0, 0);
        layout->setSpacing(0);
        layout->addWidget(new StyledBar(this));
        layout->addWidget(m_tabWidget);
    }

    void setCurrentIndex(int index)
    {
        m_tabWidget->setCurrentIndex(index);
    }

    void setPanels(const ProjectPanels &panels, bool setFocus)
    {
        const int oldIndex = m_tabWidget->currentIndex();

        while (m_tabWidget->count()) {
            const int pos = m_tabWidget->count() - 1;
            m_tabWidget->removeTab(pos);
        }

        for (QWidget *panel : panels) {
            QTC_ASSERT(panel, continue);
            m_tabWidget->addTab(panel, panel->windowTitle());
        }

        m_tabWidget->setCurrentIndex(oldIndex);

        if (QWidget *widget = m_tabWidget->currentWidget()) {
            if (setFocus)
                widget->setFocus();
        }
    }

private:
    QTabWidget *m_tabWidget = nullptr;
};

class ShowAllKitsComboBox final : public QComboBox
{
public:
    ShowAllKitsComboBox(ProjectsModel *projectsModel, QWidget *parent)
        : QComboBox(parent)
    {
        TypedSelectionAspect<KitFilter> &kitFilter = globalProjectExplorerSettings().kitFilter;
        for (int i = 0; i < 3; ++i)
            addItem(kitFilter.displayForIndex(i), i);

        setCurrentIndex(int(kitFilter()));

        connect(this, &QComboBox::currentIndexChanged, projectsModel, [projectsModel](int index) {
            globalProjectExplorerSettings().kitFilter.setValue(KitFilter(index));
            globalProjectExplorerSettings().writeSettings();
            projectsModel->rootItem()->forFirstLevelChildren([](ProjectItem *item) {
                item->targetsItem()->scheduleRebuildContents();
            });
        });
    }
};

class ProjectWindowPrivate : public QObject
{
public:
    ProjectWindowPrivate(ProjectWindow *parent)
        : q(parent), m_centralWidget(new CentralWidget(q))
    {
        q->setCentralWidget(m_centralWidget);

        m_projectsModel.setHeader({Tr::tr("Projects")});

        m_targetsView = new SelectorTree;
        m_targetsView->setModel(&m_projectsModel);
        m_targetsView->setContextMenuPolicy(Qt::CustomContextMenu);
        connect(m_targetsView, &QAbstractItemView::activated, this, [this](const QModelIndex &idx) {
            m_vanishedTargetsView->clearSelection();
            m_projectSettingsView->clearSelection();
            itemActivated(idx);
        });
        connect(m_targetsView, &QWidget::customContextMenuRequested,
                this, &ProjectWindowPrivate::openContextMenu);

        m_vanishedTargetsView = new SelectorTree;
        m_vanishedTargetsView->setModel(&m_projectsModel);
        m_vanishedTargetsView->setContextMenuPolicy(Qt::CustomContextMenu);
        connect(m_vanishedTargetsView, &QAbstractItemView::activated, this, [this](const QModelIndex &idx) {
            m_targetsView->clearSelection();
            m_projectSettingsView->clearSelection();
            itemActivated(idx);
        });
        connect(m_vanishedTargetsView, &QWidget::customContextMenuRequested,
                this, &ProjectWindowPrivate::openContextMenu);

        m_projectSettingsView = new SelectorTree;
        m_projectSettingsView->setModel(&m_projectsModel);
        m_projectSettingsView->setContextMenuPolicy(Qt::CustomContextMenu);
        connect(m_projectSettingsView, &QAbstractItemView::activated, this, [this](const QModelIndex &idx) {
            m_targetsView->clearSelection();
            m_vanishedTargetsView->clearSelection();
            itemActivated(idx);
        });
        connect(m_projectSettingsView, &QWidget::customContextMenuRequested,
                this, &ProjectWindowPrivate::openContextMenu);

        const QFont labelFont = StyleHelper::uiFont(StyleHelper::UiElementH4);

        auto targetsLabel = new QLabel(Tr::tr("Build & Run"));
        targetsLabel->setFont(labelFont);

        m_vanishedTargetsLabel = new QLabel(Tr::tr("Vanished Targets"));
        m_vanishedTargetsLabel->setFont(labelFont);

        auto projectSettingsLabel = new QLabel(Tr::tr("Project Settings"));
        projectSettingsLabel->setFont(labelFont);

        const int space = 18;
        auto scrolledWidget = new QWidget;
        auto scrolledLayout = new QVBoxLayout(scrolledWidget);
        auto kitsFilterLayout = new QHBoxLayout;
        auto kitsFilter = new ShowAllKitsComboBox(&m_projectsModel, scrolledWidget);

        kitsFilterLayout->addWidget(kitsFilter);
        kitsFilterLayout->addStretch();
        scrolledLayout->setSizeConstraint(QLayout::SetFixedSize);
        scrolledLayout->setContentsMargins(0, 0, 0, 0);
        scrolledLayout->setSpacing(0);
        scrolledLayout->addWidget(targetsLabel);
        scrolledLayout->addSpacing(space);
        scrolledLayout->addWidget(m_targetsView);
        scrolledLayout->addSpacing(6);
        scrolledLayout->addItem(kitsFilterLayout);
        scrolledLayout->addSpacing(space);
        scrolledLayout->addWidget(m_vanishedTargetsLabel);
        scrolledLayout->addSpacing(space);
        scrolledLayout->addWidget(m_vanishedTargetsView);
        scrolledLayout->addSpacing(space);
        scrolledLayout->addWidget(projectSettingsLabel);
        scrolledLayout->addSpacing(space);
        scrolledLayout->addWidget(m_projectSettingsView);

        m_scrollArea = new QScrollArea;
        m_scrollArea->setFrameStyle(QFrame::NoFrame);
        m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        m_scrollArea->setWidgetResizable(true);
        m_scrollArea->setWidget(scrolledWidget);

        m_projectSelection = new QComboBox;
        m_projectSelection->setObjectName("ProjectSelection"); // used by Squish
        m_projectSelection->setModel(&m_projectsModel);
        connect(m_projectSelection, &QComboBox::activated,
                this, &ProjectWindowPrivate::projectSelected, Qt::QueuedConnection);

        const auto switchProjectAction = new QAction(this);
        ActionManager::registerAction(switchProjectAction, Core::Constants::GOTOPREVINHISTORY,
                                      Context(Constants::C_PROJECTEXPLORER));
        connect(switchProjectAction, &QAction::triggered, this, [this] {
            if (m_projectSelection->count() > 1)
                m_projectSelection->showPopup();
        });

        ProjectManager *sessionManager = ProjectManager::instance();
        connect(sessionManager, &ProjectManager::projectAdded,
                this, &ProjectWindowPrivate::registerProject);
        connect(sessionManager, &ProjectManager::aboutToRemoveProject,
                this, &ProjectWindowPrivate::deregisterProject);
        connect(sessionManager, &ProjectManager::startupProjectChanged,
                this, &ProjectWindowPrivate::startupProjectChanged);

        m_importBuild = new QPushButton(Tr::tr("Import Existing Build..."));
        connect(m_importBuild, &QPushButton::clicked,
                this, &ProjectWindowPrivate::handleImportBuild);
        connect(sessionManager, &ProjectManager::startupProjectChanged, this, [this](Project *project) {
            m_importBuild->setEnabled(project && project->projectImporter());
        });

        auto styledBar = new StyledBar; // The black blob on top of the side bar
        styledBar->setObjectName("ProjectModeStyledBar");

        auto selectorView = new QWidget; // Black blob + Combobox + Project tree below.
        selectorView->setObjectName("ProjectSelector"); // Needed for dock widget state saving
        selectorView->setWindowTitle(Tr::tr("Project Selector"));
        selectorView->setAutoFillBackground(true);

        auto activeLabel = new QLabel(Tr::tr("Active Project"));
        activeLabel->setFont(StyleHelper::uiFont(StyleHelper::UiElementH4));

        auto innerLayout = new QVBoxLayout;
        innerLayout->setSpacing(10);
        innerLayout->setContentsMargins(PanelVMargin, innerLayout->spacing(), PanelVMargin, 0);
#ifdef QT_NO_DEBUG
        const QStringList list = ICore::settings()->value("HideOptionCategories").toStringList();
#else
        const QStringList list;
#endif
        if (!list.contains("Kits")) {
            auto manageKits = new QPushButton(Tr::tr("Manage Kits..."));
            connect(manageKits, &QPushButton::clicked,
                    this, &ProjectWindowPrivate::handleManageKits);

            innerLayout->addWidget(manageKits);
            innerLayout->addSpacerItem(new QSpacerItem(10, 30, QSizePolicy::Maximum, QSizePolicy::Maximum));
        }
        innerLayout->addWidget(activeLabel);
        innerLayout->addWidget(m_projectSelection);
        innerLayout->addWidget(m_importBuild);
        innerLayout->addWidget(m_scrollArea);

        auto selectorLayout = new QVBoxLayout(selectorView);
        selectorLayout->setContentsMargins(0, 0, 0, 0);
        selectorLayout->addWidget(styledBar);
        selectorLayout->addLayout(innerLayout);

        auto selectorDock = q->addDockForWidget(selectorView, true);
        q->addDockWidget(Qt::LeftDockWidgetArea, selectorDock);

        m_buildSystemOutput = new BuildSystemOutputWindow;
        auto output = new QWidget;
        // ProjectWindow sets background role to Base which is wrong for the output window,
        // especially the find tool bar (resulting in wrong label color)
        output->setBackgroundRole(QPalette::Window);
        output->setObjectName("BuildSystemOutput");
        output->setWindowTitle(Tr::tr("Build System Output"));
        auto outputLayout = new QVBoxLayout;
        output->setLayout(outputLayout);
        outputLayout->setContentsMargins(0, 0, 0, 0);
        outputLayout->setSpacing(0);
        outputLayout->addWidget(m_buildSystemOutput->toolBar());
        outputLayout->addWidget(m_buildSystemOutput);
        outputLayout->addWidget(new FindToolBarPlaceHolder(m_buildSystemOutput));
        m_outputDock = q->addDockForWidget(output, true);
        q->addDockWidget(Qt::RightDockWidgetArea, m_outputDock);

        m_toggleRightSidebarAction.setCheckable(true);
        m_toggleRightSidebarAction.setChecked(true);
        const auto toolTipText = [](bool checked) {
            return checked ? msgHideRightSideBar() : msgShowRightSideBar();
        };
        m_toggleRightSidebarAction.setText(toolTipText(false)); // always "Show Right Sidebar"
        m_toggleRightSidebarAction.setToolTip(toolTipText(m_toggleRightSidebarAction.isChecked()));
        ActionManager::registerAction(&m_toggleRightSidebarAction,
                                      Core::Constants::TOGGLE_RIGHT_SIDEBAR,
                                      Context(Constants::C_PROJECTEXPLORER));
        connect(&m_toggleRightSidebarAction,
                &QAction::toggled,
                this,
                [this, toolTipText](bool checked) {
                    m_toggleRightSidebarAction.setToolTip(toolTipText(checked));
                    m_outputDock->setVisible(checked);
                });

        connect(m_projectSelection, &QComboBox::currentIndexChanged, this, [this] {
            updateProjectBase();
        });
    }

    ProjectItem *currentProjectItem() const
    {
        const QModelIndex index = m_projectsModel.index(m_projectSelection->currentIndex(), 0, QModelIndex());
        if (!index.isValid())
            return nullptr;
        auto projectItem = dynamic_cast<ProjectItem *>(m_projectsModel.itemForIndex(index));
        QTC_CHECK(projectItem);
        return projectItem;
    }

    void updatePanel()
    {
        ProjectItem *projectItem = currentProjectItem();
        if (!projectItem)
            return;

        ProjectPanels panels;
        if (ProjectItemBase *active = projectItem->activeItem())
            panels = active->panelWidgets();
        setPanels(panels);

        m_targetsView->updateSize();
        m_vanishedTargetsView->updateSize();
        m_projectSettingsView->updateSize();
    }

    void registerProject(Project *project)
    {
        QTC_ASSERT(itemForProject(project) == nullptr, return);
        auto projectItem = new ProjectItem(project, [this] { updatePanel(); });
        m_projectsModel.rootItem()->appendChild(projectItem);
    }

    void deregisterProject(Project *project)
    {
        ProjectItem *item = itemForProject(project);
        QTC_ASSERT(item, return);
        m_projectsModel.destroyItem(item);
    }

    void projectSelected(int index)
    {
        Project *project = m_projectsModel.rootItem()->childAt(index)->project();
        ProjectManager::setStartupProject(project);
    }

    ProjectItem *itemForProject(Project *project) const
    {
        return m_projectsModel.findItemAtLevel<1>([project](ProjectItem *item) {
            return item->project() == project;
        });
    }

    ProjectItemBase *projectItemForIndex(const QModelIndex &index)
    {
        return dynamic_cast<ProjectItemBase *>(m_projectsModel.itemForIndex(index));
    }

    void startupProjectChanged(Project *project)
    {
        if (!project) // Shutting down.
            return;
        ProjectItem *projectItem = itemForProject(project);
        QTC_ASSERT(projectItem, return);
        m_projectSelection->setCurrentIndex(projectItem->indexInParent());
    }

    void updateProjectBase()
    {
        if (ProjectItem *projectItem = currentProjectItem()) {
            m_targetsView->setRootIndex(m_projectsModel.indexForItem(projectItem->targetsItem()));
            m_vanishedTargetsView->setRootIndex(m_projectsModel.indexForItem(projectItem->vanishedTargetsItem()));
            m_projectSettingsView->setRootIndex(m_projectsModel.indexForItem(projectItem->miscSettingsItem()));

            const bool hasVanishedTargets = projectItem->vanishedTargetsItem()->hasChildren();
            m_vanishedTargetsLabel->setVisible(hasVanishedTargets);
            m_vanishedTargetsView->setVisible(hasVanishedTargets);
        } else {
            m_targetsView->setRootIndex(QModelIndex());
            m_vanishedTargetsView->setRootIndex(QModelIndex());
            m_projectSettingsView->setRootIndex(QModelIndex());
        }

        updatePanel();
    }

    void itemActivated(const QModelIndex &index)
    {
        if (ProjectItemBase *item = projectItemForIndex(index))
            item->itemActivatedDirectly();
    }

    void activateProjectPanel(Id panelId)
    {
        if (ProjectItem *projectItem = currentProjectItem()) {
            if (TreeItem *item = projectItem->itemForProjectPanel(panelId)) {
                itemActivated(item->index());
                m_projectSettingsView->selectionModel()->select(item->index(),
                    QItemSelectionModel::ClearAndSelect);
            }
        }
    }

    void activateTargetTab(int index)
    {
        if (ProjectItem *projectItem = currentProjectItem()) {
            if (TargetItem *targetItem = projectItem->targetsItem()->currentTargetItem()) {
                targetItem->itemActivatedDirectly();
                m_centralWidget->setCurrentIndex(index);
            }
        }
    }

    void openContextMenu(const QPoint &pos)
    {
        QMenu menu;

        ProjectItem *projectItem = currentProjectItem();
        Project *project = projectItem ? projectItem->project() : nullptr;

        QAbstractItemView *view = qobject_cast<QAbstractItemView *>(sender());
        QTC_ASSERT(view, return);

        QModelIndex index = view->indexAt(pos);
        if (ProjectItemBase *item = projectItemForIndex(index))
            item->addToMenu(&menu);

        if (!menu.actions().isEmpty())
            menu.addSeparator();

        QAction *importBuild = menu.addAction(Tr::tr("Import Existing Build..."));
        importBuild->setEnabled(project && project->projectImporter());
        QAction *manageKits = menu.addAction(Tr::tr("Manage Kits..."));

        QAction *act = menu.exec(view->mapToGlobal(pos));

        if (act == importBuild)
            handleImportBuild();
        else if (act == manageKits)
            handleManageKits();
    }

    void handleManageKits()
    {
        const QModelIndexList selected = m_targetsView->selectionModel()->selectedIndexes();
        if (!selected.isEmpty()) {
            ProjectItemBase *treeItem = projectItemForIndex(selected.front());
            while (treeItem) {
                if (const Id kitId = treeItem->kitId(); kitId.isValid()) {
                    Core::setPreselectedOptionsPageItem(Constants::KITS_SETTINGS_PAGE_ID, kitId);
                    break;
                }
                treeItem = treeItem->parent();
            }
        }
        ICore::showOptionsDialog(Constants::KITS_SETTINGS_PAGE_ID);
    }

    void handleImportBuild()
    {
        ProjectItem *projectItem = currentProjectItem();
        Project *project = projectItem ? projectItem->project() : nullptr;
        ProjectImporter *projectImporter = project ? project->projectImporter() : nullptr;
        QTC_ASSERT(projectImporter, return);

        FilePath importDir =
                FileUtils::getExistingDirectory(Tr::tr("Import Directory"),
                                                project->projectDirectory());

        Target *lastTarget = nullptr;
        BuildConfiguration *lastBc = nullptr;
        for (const BuildInfo &info : projectImporter->import(importDir, false)) {
            Target *target = project->target(info.kitId);
            if (!target)
                target = project->addTargetForKit(KitManager::kit(info.kitId));
            if (target) {
                projectImporter->makePersistent(target->kit());
                BuildConfiguration *bc = info.factory->create(target, info);
                QTC_ASSERT(bc, continue);
                target->addBuildConfiguration(bc);

                lastTarget = target;
                lastBc = bc;
            }
        }
        if (lastTarget && lastBc) {
            lastTarget->setActiveBuildConfiguration(lastBc, SetActive::Cascade);
            project->setActiveTarget(lastTarget, SetActive::Cascade);
        }
    }

    void setPanels(const ProjectPanels &panels)
    {
         q->savePersistentSettings();
         m_centralWidget->setPanels(panels, q->hasFocus());
         q->loadPersistentSettings();
    }

    ProjectWindow *q;
    ProjectsModel m_projectsModel;
    QComboBox *m_projectSelection;
    QLabel *m_vanishedTargetsLabel;
    SelectorTree *m_targetsView;
    SelectorTree *m_vanishedTargetsView;
    SelectorTree *m_projectSettingsView;
    QScrollArea *m_scrollArea;
    QPushButton *m_importBuild;
    QAction m_toggleRightSidebarAction;
    QDockWidget *m_outputDock;
    BuildSystemOutputWindow *m_buildSystemOutput;
    CentralWidget *m_centralWidget;
};

//
// ProjectWindow
//

ProjectWindow::ProjectWindow()
    : d(std::make_unique<ProjectWindowPrivate>(this))
{
    setBackgroundRole(QPalette::Base);

    // Request custom context menu but do not provide any to avoid
    // the creation of the dock window selection menu.
    setContextMenuPolicy(Qt::CustomContextMenu);
}

void ProjectWindow::activateProjectPanel(Id panelId)
{
    d->activateProjectPanel(panelId);
}

void ProjectWindow::activateBuildSettings()
{
    d->activateTargetTab(0);
}

void ProjectWindow::activateRunSettings()
{
    d->activateTargetTab(2);
}

OutputWindow *ProjectWindow::buildSystemOutput() const
{
    return d->m_buildSystemOutput;
}

void ProjectWindow::hideEvent(QHideEvent *event)
{
    savePersistentSettings();
    FancyMainWindow::hideEvent(event);
}

void ProjectWindow::showEvent(QShowEvent *event)
{
    FancyMainWindow::showEvent(event);
    loadPersistentSettings();
}

ProjectWindow::~ProjectWindow() = default;

const char PROJECT_WINDOW_KEY[] = "ProjectExplorer.ProjectWindow";

void ProjectWindow::savePersistentSettings() const
{
    if (!centralWidget())
        return;
    QtcSettings * const settings = ICore::settings();
    settings->beginGroup(PROJECT_WINDOW_KEY);
    saveSettings(settings);
    settings->endGroup();
}

void ProjectWindow::loadPersistentSettings()
{
    if (!centralWidget())
        return;
    QtcSettings * const settings = ICore::settings();
    settings->beginGroup(PROJECT_WINDOW_KEY);
    restoreSettings(settings);
    settings->endGroup();
    d->m_toggleRightSidebarAction.setChecked(d->m_outputDock->isVisible());
}

} // namespace ProjectExplorer::Internal