aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/cmakeprojectmanager/cmakebuildsystem.cpp
blob: 146c2f853c4f25d7919a324b965bba2c20394cf9 (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
// 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 "cmakebuildsystem.h"

#include "builddirparameters.h"
#include "cmakebuildconfiguration.h"
#include "cmakebuildstep.h"
#include "cmakebuildtarget.h"
#include "cmakekitinformation.h"
#include "cmakeproject.h"
#include "cmakeprojectconstants.h"
#include "cmakeprojectmanagertr.h"
#include "cmakespecificsettings.h"
#include "projecttreehelper.h"

#include <android/androidconstants.h>

#include <coreplugin/icore.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/progressmanager/progressmanager.h>

#include <cppeditor/cppeditorconstants.h>
#include <cppeditor/cppprojectupdater.h>

#include <projectexplorer/extracompiler.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>
#include <projectexplorer/taskhub.h>

#include <texteditor/texteditor.h>
#include <texteditor/textdocument.h>

#include <qmljs/qmljsmodelmanagerinterface.h>
#include <qmljstools/qmljstoolsconstants.h>
#include <qtsupport/qtcppkitinfo.h>
#include <qtsupport/qtkitinformation.h>

#include <app/app_version.h>

#include <utils/algorithm.h>
#include <utils/checkablemessagebox.h>
#include <utils/fileutils.h>
#include <utils/macroexpander.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>

#include <QClipboard>
#include <QGuiApplication>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLoggingCategory>

using namespace ProjectExplorer;
using namespace TextEditor;
using namespace Utils;

namespace CMakeProjectManager::Internal {

static Q_LOGGING_CATEGORY(cmakeBuildSystemLog, "qtc.cmake.buildsystem", QtWarningMsg);

// --------------------------------------------------------------------
// CMakeBuildSystem:
// --------------------------------------------------------------------

CMakeBuildSystem::CMakeBuildSystem(CMakeBuildConfiguration *bc)
    : BuildSystem(bc)
    , m_cppCodeModelUpdater(new CppEditor::CppProjectUpdater)
{
    // TreeScanner:
    connect(&m_treeScanner, &TreeScanner::finished,
            this, &CMakeBuildSystem::handleTreeScanningFinished);

    m_treeScanner.setFilter([this](const MimeType &mimeType, const FilePath &fn) {
        // Mime checks requires more resources, so keep it last in check list
        auto isIgnored = TreeScanner::isWellKnownBinary(mimeType, fn);

        // Cache mime check result for speed up
        if (!isIgnored) {
            auto it = m_mimeBinaryCache.find(mimeType.name());
            if (it != m_mimeBinaryCache.end()) {
                isIgnored = *it;
            } else {
                isIgnored = TreeScanner::isMimeBinary(mimeType, fn);
                m_mimeBinaryCache[mimeType.name()] = isIgnored;
            }
        }

        return isIgnored;
    });

    m_treeScanner.setTypeFactory([](const MimeType &mimeType, const FilePath &fn) {
        auto type = TreeScanner::genericFileType(mimeType, fn);
        if (type == FileType::Unknown) {
            if (mimeType.isValid()) {
                const QString mt = mimeType.name();
                if (mt == CMakeProjectManager::Constants::CMAKE_PROJECT_MIMETYPE
                    || mt == CMakeProjectManager::Constants::CMAKE_MIMETYPE)
                    type = FileType::Project;
            }
        }
        return type;
    });

    connect(&m_reader, &FileApiReader::configurationStarted, this, [this] {
        clearError(ForceEnabledChanged::True);
    });

    connect(&m_reader,
            &FileApiReader::dataAvailable,
            this,
            &CMakeBuildSystem::handleParsingSucceeded);
    connect(&m_reader, &FileApiReader::errorOccurred, this, &CMakeBuildSystem::handleParsingFailed);
    connect(&m_reader, &FileApiReader::dirty, this, &CMakeBuildSystem::becameDirty);

    wireUpConnections();

    m_isMultiConfig = CMakeGeneratorKitAspect::isMultiConfigGenerator(bc->kit());
}

CMakeBuildSystem::~CMakeBuildSystem()
{
    if (!m_treeScanner.isFinished()) {
        auto future = m_treeScanner.future();
        future.cancel();
        future.waitForFinished();
    }

    delete m_cppCodeModelUpdater;
    qDeleteAll(m_extraCompilers);
}

void CMakeBuildSystem::triggerParsing()
{
    qCDebug(cmakeBuildSystemLog) << buildConfiguration()->displayName() << "Parsing has been triggered";

    if (!buildConfiguration()->isActive()) {
        qCDebug(cmakeBuildSystemLog)
            << "Parsing has been triggered: SKIPPING since BC is not active -- clearing state.";
        stopParsingAndClearState();
        return; // ignore request, this build configuration is not active!
    }

    auto guard = guardParsingRun();

    if (!guard.guardsProject()) {
        // This can legitimately trigger if e.g. Build->Run CMake
        // is selected while this here is already running.

        // Stop old parse run and keep that ParseGuard!
        qCDebug(cmakeBuildSystemLog) << "Stopping current parsing run!";
        stopParsingAndClearState();
    } else {
        // Use new ParseGuard
        m_currentGuard = std::move(guard);
    }
    QTC_ASSERT(!m_reader.isParsing(), return );

    qCDebug(cmakeBuildSystemLog) << "ParseGuard acquired.";

    int reparseParameters = takeReparseParameters();

    m_waitingForParse = true;
    m_combinedScanAndParseResult = true;

    QTC_ASSERT(m_parameters.isValid(), return );

    TaskHub::clearTasks(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);

    qCDebug(cmakeBuildSystemLog) << "Parse called with flags:"
                                 << reparseParametersString(reparseParameters);

    const QString cache = m_parameters.buildDirectory.pathAppended("CMakeCache.txt").toString();
    if (!QFileInfo::exists(cache)) {
        reparseParameters |= REPARSE_FORCE_INITIAL_CONFIGURATION | REPARSE_FORCE_CMAKE_RUN;
        qCDebug(cmakeBuildSystemLog)
            << "No" << cache
            << "file found, new flags:" << reparseParametersString(reparseParameters);
    }

    if ((0 == (reparseParameters & REPARSE_FORCE_EXTRA_CONFIGURATION))
        && mustApplyConfigurationChangesArguments(m_parameters)) {
        reparseParameters |= REPARSE_FORCE_CMAKE_RUN | REPARSE_FORCE_EXTRA_CONFIGURATION;
    }

    // The code model will be updated after the CMake run. There is no need to have an
    // active code model updater when the next one will be triggered.
    m_cppCodeModelUpdater->cancel();

    qCDebug(cmakeBuildSystemLog) << "Asking reader to parse";
    m_reader.parse(reparseParameters & REPARSE_FORCE_CMAKE_RUN,
                   reparseParameters & REPARSE_FORCE_INITIAL_CONFIGURATION,
                   reparseParameters & REPARSE_FORCE_EXTRA_CONFIGURATION);
}

bool CMakeBuildSystem::supportsAction(Node *context, ProjectAction action, const Node *node) const
{
    if (dynamic_cast<CMakeTargetNode *>(context))
        return action == ProjectAction::AddNewFile || action == ProjectAction::AddExistingFile
               || action == ProjectAction::AddExistingDirectory || action == ProjectAction::Rename
               || action == ProjectAction::RemoveFile;

    return BuildSystem::supportsAction(context, action, node);
}

static QString newFilesForFunction(const std::string &cmakeFunction,
                                   const FilePaths &filePaths,
                                   const FilePath &projDir)
{
    auto relativeFilePaths = [projDir](const FilePaths &filePaths) {
        return Utils::transform(filePaths, [projDir](const FilePath &path) {
            return path.canonicalPath().relativePathFrom(projDir).cleanPath().toString();
        });
    };

    if (cmakeFunction == "qt_add_qml_module" || cmakeFunction == "qt6_add_qml_module") {
        FilePaths sourceFiles;
        FilePaths resourceFiles;
        FilePaths qmlFiles;

        for (const auto &file : filePaths) {
            const auto mimeType = Utils::mimeTypeForFile(file);
            if (mimeType.matchesName(CppEditor::Constants::CPP_SOURCE_MIMETYPE)
                || mimeType.matchesName(CppEditor::Constants::CPP_HEADER_MIMETYPE)
                || mimeType.matchesName(CppEditor::Constants::OBJECTIVE_C_SOURCE_MIMETYPE)
                || mimeType.matchesName(CppEditor::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)) {
                sourceFiles << file;
            } else if (mimeType.matchesName(QmlJSTools::Constants::QML_MIMETYPE)
                       || mimeType.matchesName(QmlJSTools::Constants::QMLUI_MIMETYPE)
                       || mimeType.matchesName(QmlJSTools::Constants::QMLPROJECT_MIMETYPE)
                       || mimeType.matchesName(QmlJSTools::Constants::JS_MIMETYPE)
                       || mimeType.matchesName(QmlJSTools::Constants::JSON_MIMETYPE)) {
                qmlFiles << file;
            } else {
                resourceFiles << file;
            }
        }

        QStringList result;
        if (!sourceFiles.isEmpty())
            result << QString("SOURCES %1").arg(relativeFilePaths(sourceFiles).join(" "));
        if (!resourceFiles.isEmpty())
            result << QString("RESOURCES %1").arg(relativeFilePaths(resourceFiles).join(" "));
        if (!qmlFiles.isEmpty())
            result << QString("QML_FILES %1").arg(relativeFilePaths(qmlFiles).join(" "));

        return result.join("\n");
    }

    return relativeFilePaths(filePaths).join(" ");
}

bool CMakeBuildSystem::addFiles(Node *context, const FilePaths &filePaths, FilePaths *notAdded)
{
    if (auto n = dynamic_cast<CMakeTargetNode *>(context)) {
        const QString targetName = n->buildKey();
        auto target = Utils::findOrDefault(buildTargets(),
                                           [targetName](const CMakeBuildTarget &target) {
                                               return target.title == targetName;
                                           });

        if (target.backtrace.isEmpty()) {
            *notAdded = filePaths;
            return false;
        }
        const FilePath targetCMakeFile = target.backtrace.last().path;
        const int targetDefinitionLine = target.backtrace.last().line;

        // Have a fresh look at the CMake file, not relying on a cached value
        expected_str<QByteArray> fileContent = targetCMakeFile.fileContents();
        cmListFile cmakeListFile;
        std::string errorString;
        if (fileContent) {
            fileContent = fileContent->replace("\r\n", "\n");
            if (!cmakeListFile.ParseString(fileContent->toStdString(),
                                           targetCMakeFile.fileName().toStdString(),
                                           errorString)) {
                *notAdded = filePaths;
                return false;
            }
        }

        auto function = std::find_if(cmakeListFile.Functions.begin(),
                                     cmakeListFile.Functions.end(),
                                     [targetDefinitionLine](const auto &func) {
                                         return func.Line() == targetDefinitionLine;
                                     });

        if (function == cmakeListFile.Functions.end()) {
            *notAdded = filePaths;
            return false;
        }

        // Special case: when qt_add_executable and qt_add_qml_module use the same target name
        // then qt_add_qml_module function should be used
        const std::string target_name = targetName.toStdString();
        auto add_qml_module_func
            = std::find_if(cmakeListFile.Functions.begin(),
                           cmakeListFile.Functions.end(),
                           [target_name](const auto &func) {
                               return (func.LowerCaseName() == "qt_add_qml_module"
                                       || func.LowerCaseName() == "qt6_add_qml_module")
                                      && func.Arguments().front().Value == target_name;
                           });
        if (add_qml_module_func != cmakeListFile.Functions.end())
            function = add_qml_module_func;

        const QString newSourceFiles = newFilesForFunction(function->LowerCaseName(),
                                                           filePaths,
                                                           n->filePath().canonicalPath());

        static QSet<std::string> knownFunctions{"add_executable",
                                                "add_library",
                                                "qt_add_executable",
                                                "qt_add_library",
                                                "qt6_add_executable",
                                                "qt6_add_library",
                                                "qt_add_qml_module",
                                                "qt6_add_qml_module"};

        int line = 0;
        int column = 0;
        QString snippet;

        auto afterFunctionLastArgument = [&line, &column, &snippet, newSourceFiles](const auto &f) {
            auto lastArgument = f->Arguments().back();

            line = lastArgument.Line;
            column = lastArgument.Column + static_cast<int>(lastArgument.Value.size()) - 1;
            snippet = QString("\n%1").arg(newSourceFiles);
        };

        if (knownFunctions.contains(function->LowerCaseName())) {
            afterFunctionLastArgument(function);
        } else {
            auto targetSourcesFunc = std::find_if(cmakeListFile.Functions.begin(),
                                                  cmakeListFile.Functions.end(),
                                                  [target_name](const auto &func) {
                                                      return func.LowerCaseName()
                                                                 == "target_sources"
                                                             && func.Arguments().front().Value
                                                                    == target_name;
                                                  });

            if (targetSourcesFunc == cmakeListFile.Functions.end()) {
                line = function->LineEnd() + 1;
                column = 0;
                snippet = QString("\ntarget_sources(%1\n  PRIVATE\n    %2\n)\n")
                              .arg(targetName)
                              .arg(newSourceFiles);
            } else {
                afterFunctionLastArgument(targetSourcesFunc);
            }
        }

        BaseTextEditor *editor = qobject_cast<BaseTextEditor *>(
            Core::EditorManager::openEditorAt({targetCMakeFile, line, column},
                                              Constants::CMAKE_EDITOR_ID,
                                              Core::EditorManager::DoNotMakeVisible));
        if (!editor) {
            *notAdded = filePaths;
            return false;
        }

        editor->insert(snippet);
        editor->editorWidget()->autoIndent();
        if (!Core::DocumentManager::saveDocument(editor->document()))
            return false;

        return true;
    }

    return BuildSystem::addFiles(context, filePaths, notAdded);
}

std::optional<CMakeBuildSystem::ProjectFileArgumentPosition>
CMakeBuildSystem::projectFileArgumentPosition(const QString &targetName, const QString &fileName)
{
    auto target = Utils::findOrDefault(buildTargets(), [targetName](const CMakeBuildTarget &target) {
        return target.title == targetName;
    });

    if (target.backtrace.isEmpty())
        return std::nullopt;

    const FilePath targetCMakeFile = target.backtrace.last().path;

    // Have a fresh look at the CMake file, not relying on a cached value
    expected_str<QByteArray> fileContent = targetCMakeFile.fileContents();
    cmListFile cmakeListFile;
    std::string errorString;
    if (fileContent) {
        fileContent = fileContent->replace("\r\n", "\n");
        if (!cmakeListFile.ParseString(fileContent->toStdString(),
                                       targetCMakeFile.fileName().toStdString(),
                                       errorString))
            return std::nullopt;
    }

    const int targetDefinitionLine = target.backtrace.last().line;

    auto function = std::find_if(cmakeListFile.Functions.begin(),
                                 cmakeListFile.Functions.end(),
                                 [targetDefinitionLine](const auto &func) {
                                     return func.Line() == targetDefinitionLine;
                                 });

    const std::string target_name = targetName.toStdString();
    auto targetSourcesFunc = std::find_if(cmakeListFile.Functions.begin(),
                                          cmakeListFile.Functions.end(),
                                          [target_name](const auto &func) {
                                              return func.LowerCaseName() == "target_sources"
                                                     && func.Arguments().size() > 1
                                                     && func.Arguments().front().Value
                                                            == target_name;
                                          });
    auto addQmlModuleFunc = std::find_if(cmakeListFile.Functions.begin(),
                                         cmakeListFile.Functions.end(),
                                         [target_name](const auto &func) {
                                             return (func.LowerCaseName() == "qt_add_qml_module"
                                                     || func.LowerCaseName() == "qt6_add_qml_module")
                                                    && func.Arguments().size() > 1
                                                    && func.Arguments().front().Value
                                                           == target_name;
                                         });

    for (const auto &func : {function, targetSourcesFunc, addQmlModuleFunc}) {
        if (func == cmakeListFile.Functions.end())
            continue;
        auto filePathArgument
            = Utils::findOrDefault(func->Arguments(),
                                   [file_name = fileName.toStdString()](const auto &arg) {
                                       return arg.Delim != cmListFileArgument::Comment
                                              && arg.Value == file_name;
                                   });

        if (!filePathArgument.Value.empty()) {
            return ProjectFileArgumentPosition{filePathArgument, targetCMakeFile, fileName};
        } else {
            // Check if the filename is part of globbing variable result
            const auto globFunctions = std::get<0>(
                Utils::partition(cmakeListFile.Functions, [](const auto &f) {
                    return f.LowerCaseName() == "file" && f.Arguments().size() > 2
                           && (f.Arguments().front().Value == "GLOB"
                               || f.Arguments().front().Value == "GLOB_RECURSE");
                }));

            const auto globVariables = Utils::transform<QSet>(globFunctions, [](const auto &func) {
                return std::string("${") + func.Arguments()[1].Value + "}";
            });

            const auto haveGlobbing = Utils::anyOf(func->Arguments(),
                                                   [globVariables](const auto &arg) {
                                                       return globVariables.contains(arg.Value)
                                                              && arg.Delim
                                                                     != cmListFileArgument::Comment;
                                                   });

            if (haveGlobbing) {
                return ProjectFileArgumentPosition{filePathArgument,
                                                   targetCMakeFile,
                                                   fileName,
                                                   true};
            }

            // Check if the filename is part of a variable set by the user
            const auto setFunctions = std::get<0>(
                Utils::partition(cmakeListFile.Functions, [](const auto &f) {
                    return f.LowerCaseName() == "set" && f.Arguments().size() > 1;
                }));

            for (const auto &arg : func->Arguments()) {
                if (arg.Delim == cmListFileArgument::Comment)
                    continue;

                auto matchedFunctions = Utils::filtered(setFunctions, [arg](const auto &f) {
                    return arg.Value == std::string("${") + f.Arguments()[0].Value + "}";
                });

                for (const auto &f : matchedFunctions) {
                    filePathArgument
                        = Utils::findOrDefault(f.Arguments(),
                                               [file_name = fileName.toStdString()](
                                                   const auto &arg) {
                                                   return arg.Delim != cmListFileArgument::Comment
                                                          && arg.Value == file_name;
                                               });

                    if (!filePathArgument.Value.empty()) {
                        return ProjectFileArgumentPosition{filePathArgument,
                                                           targetCMakeFile,
                                                           fileName};
                    }
                }
            }
        }
    }

    return std::nullopt;
}

RemovedFilesFromProject CMakeBuildSystem::removeFiles(Node *context,
                                                      const FilePaths &filePaths,
                                                      FilePaths *notRemoved)
{
    FilePaths badFiles;
    if (auto n = dynamic_cast<CMakeTargetNode *>(context)) {
        const FilePath projDir = n->filePath().canonicalPath();
        const QString targetName = n->buildKey();

        for (const auto &file : filePaths) {
            const QString fileName
                = file.canonicalPath().relativePathFrom(projDir).cleanPath().toString();

            auto filePos = projectFileArgumentPosition(targetName, fileName);
            if (filePos) {
                if (!filePos.value().cmakeFile.exists()) {
                    badFiles << file;
                    continue;
                }

                BaseTextEditor *editor = qobject_cast<BaseTextEditor *>(
                    Core::EditorManager::openEditorAt({filePos.value().cmakeFile,
                                                       static_cast<int>(filePos.value().argumentPosition.Line),
                                                       static_cast<int>(filePos.value().argumentPosition.Column
                                                                        - 1)},
                                                      Constants::CMAKE_EDITOR_ID,
                                                      Core::EditorManager::DoNotMakeVisible));
                if (!editor) {
                    badFiles << file;
                    continue;
                }

                if (!filePos.value().fromGlobbing)
                    editor->replace(filePos.value().relativeFileName.length(), "");

                editor->editorWidget()->autoIndent();
                if (!Core::DocumentManager::saveDocument(editor->document())) {
                    badFiles << file;
                    continue;
                }
            } else {
                badFiles << file;
            }
        }

        if (notRemoved && !badFiles.isEmpty())
            *notRemoved = badFiles;

        return badFiles.isEmpty() ? RemovedFilesFromProject::Ok : RemovedFilesFromProject::Error;
    }

    return RemovedFilesFromProject::Error;
}

bool CMakeBuildSystem::canRenameFile(Node *context,
                                     const FilePath &oldFilePath,
                                     const FilePath &newFilePath)
{
    // "canRenameFile" will cause an actual rename after the function call.
    // This will make the a sequence like
    //    canonicalPath().relativePathFrom(projDir).cleanPath().toString()
    // to fail if the file doesn't exist on disk
    // therefore cache the results for the subsequent "renameFile" call
    // where oldFilePath has already been renamed as newFilePath.

    if (auto n = dynamic_cast<CMakeTargetNode *>(context)) {
        const FilePath projDir = n->filePath().canonicalPath();
        const QString oldRelPathName
            = oldFilePath.canonicalPath().relativePathFrom(projDir).cleanPath().toString();

        const QString targetName = n->buildKey();

        const QString key
            = QStringList{projDir.path(), targetName, oldFilePath.path(), newFilePath.path()}
                  .join(";");

        auto filePos = projectFileArgumentPosition(targetName, oldRelPathName);
        if (!filePos)
            return false;

        m_filesToBeRenamed.insert(key, filePos.value());
        return true;
    }
    return false;
}

bool CMakeBuildSystem::renameFile(Node *context,
                                  const FilePath &oldFilePath,
                                  const FilePath &newFilePath)
{
    if (auto n = dynamic_cast<CMakeTargetNode *>(context)) {
        const FilePath projDir = n->filePath().canonicalPath();
        const QString newRelPathName
            = newFilePath.canonicalPath().relativePathFrom(projDir).cleanPath().toString();

        const QString targetName = n->buildKey();
        const QString key
            = QStringList{projDir.path(), targetName, oldFilePath.path(), newFilePath.path()}.join(
                ";");

        auto fileToRename = m_filesToBeRenamed.take(key);
        if (!fileToRename.cmakeFile.exists())
            return false;

        BaseTextEditor *editor = qobject_cast<BaseTextEditor *>(
            Core::EditorManager::openEditorAt({fileToRename.cmakeFile,
                                               static_cast<int>(fileToRename.argumentPosition.Line),
                                               static_cast<int>(fileToRename.argumentPosition.Column
                                                                - 1)},
                                              Constants::CMAKE_EDITOR_ID,
                                              Core::EditorManager::DoNotMakeVisible));
        if (!editor)
            return false;

        if (!fileToRename.fromGlobbing)
            editor->replace(fileToRename.relativeFileName.length(), newRelPathName);

        editor->editorWidget()->autoIndent();
        if (!Core::DocumentManager::saveDocument(editor->document()))
            return false;

        return true;
    }

    return false;
}

FilePaths CMakeBuildSystem::filesGeneratedFrom(const FilePath &sourceFile) const
{
    FilePath project = projectDirectory();
    FilePath baseDirectory = sourceFile.parentDir();

    while (baseDirectory.isChildOf(project)) {
        const FilePath cmakeListsTxt = baseDirectory.pathAppended("CMakeLists.txt");
        if (cmakeListsTxt.exists())
            break;
        baseDirectory = baseDirectory.parentDir();
    }

    const FilePath relativePath = baseDirectory.relativePathFrom(project);
    FilePath generatedFilePath = buildConfiguration()->buildDirectory().resolvePath(relativePath);

    if (sourceFile.suffix() == "ui") {
        generatedFilePath = generatedFilePath
                                .pathAppended("ui_" + sourceFile.completeBaseName() + ".h");
        return {generatedFilePath};
    }
    if (sourceFile.suffix() == "scxml") {
        generatedFilePath = generatedFilePath.pathAppended(sourceFile.completeBaseName());
        return {generatedFilePath.stringAppended(".h"), generatedFilePath.stringAppended(".cpp")};
    }

    // TODO: Other types will be added when adapters for their compilers become available.
    return {};
}

QString CMakeBuildSystem::reparseParametersString(int reparseFlags)
{
    QString result;
    if (reparseFlags == REPARSE_DEFAULT) {
        result = "<NONE>";
    } else {
        if (reparseFlags & REPARSE_URGENT)
            result += " URGENT";
        if (reparseFlags & REPARSE_FORCE_CMAKE_RUN)
            result += " FORCE_CMAKE_RUN";
        if (reparseFlags & REPARSE_FORCE_INITIAL_CONFIGURATION)
            result += " FORCE_CONFIG";
    }
    return result.trimmed();
}

void CMakeBuildSystem::reparse(int reparseParameters)
{
    setParametersAndRequestParse(BuildDirParameters(this), reparseParameters);
}

void CMakeBuildSystem::setParametersAndRequestParse(const BuildDirParameters &parameters,
                                                    const int reparseParameters)
{
    project()->clearIssues();

    qCDebug(cmakeBuildSystemLog) << buildConfiguration()->displayName()
                                 << "setting parameters and requesting reparse"
                                 << reparseParametersString(reparseParameters);

    if (!buildConfiguration()->isActive()) {
        qCDebug(cmakeBuildSystemLog) << "setting parameters and requesting reparse: SKIPPING since BC is not active -- clearing state.";
        stopParsingAndClearState();
        return; // ignore request, this build configuration is not active!
    }

    const CMakeTool *tool = parameters.cmakeTool();
    if (!tool || !tool->isValid()) {
        TaskHub::addTask(
            BuildSystemTask(Task::Error,
                            Tr::tr("The kit needs to define a CMake tool to parse this project.")));
        return;
    }
    if (!tool->hasFileApi()) {
        TaskHub::addTask(
            BuildSystemTask(Task::Error,
                            CMakeKitAspect::msgUnsupportedVersion(tool->version().fullVersion)));
        return;
    }
    QTC_ASSERT(parameters.isValid(), return );

    m_parameters = parameters;
    ensureBuildDirectory(parameters);
    updateReparseParameters(reparseParameters);

    m_reader.setParameters(m_parameters);

    if (reparseParameters & REPARSE_URGENT) {
        qCDebug(cmakeBuildSystemLog) << "calling requestReparse";
        requestParse();
    } else {
        qCDebug(cmakeBuildSystemLog) << "calling requestDelayedReparse";
        requestDelayedParse();
    }
}

bool CMakeBuildSystem::mustApplyConfigurationChangesArguments(const BuildDirParameters &parameters) const
{
    if (parameters.configurationChangesArguments.isEmpty())
        return false;

    int answer = QMessageBox::question(Core::ICore::dialogParent(),
                                       Tr::tr("Apply configuration changes?"),
                                       "<p>" + Tr::tr("Run CMake with configuration changes?")
                                       + "</p><pre>"
                                       + parameters.configurationChangesArguments.join("\n")
                                       + "</pre>",
                                       QMessageBox::Apply | QMessageBox::Discard,
                                       QMessageBox::Apply);
    return answer == QMessageBox::Apply;
}

void CMakeBuildSystem::runCMake()
{
    qCDebug(cmakeBuildSystemLog) << "Requesting parse due \"Run CMake\" command";
    reparse(REPARSE_FORCE_CMAKE_RUN | REPARSE_URGENT);
}

void CMakeBuildSystem::runCMakeAndScanProjectTree()
{
    qCDebug(cmakeBuildSystemLog) << "Requesting parse due to \"Rescan Project\" command";
    reparse(REPARSE_FORCE_CMAKE_RUN | REPARSE_URGENT);
}

void CMakeBuildSystem::runCMakeWithExtraArguments()
{
    qCDebug(cmakeBuildSystemLog) << "Requesting parse due to \"Rescan Project\" command";
    reparse(REPARSE_FORCE_CMAKE_RUN | REPARSE_FORCE_EXTRA_CONFIGURATION | REPARSE_URGENT);
}

void CMakeBuildSystem::stopCMakeRun()
{
    qCDebug(cmakeBuildSystemLog) << buildConfiguration()->displayName()
                                 << "stopping CMake's run";
    m_reader.stopCMakeRun();
}

void CMakeBuildSystem::buildCMakeTarget(const QString &buildTarget)
{
    QTC_ASSERT(!buildTarget.isEmpty(), return);
    if (ProjectExplorerPlugin::saveModifiedFiles())
        cmakeBuildConfiguration()->buildTarget(buildTarget);
}

bool CMakeBuildSystem::persistCMakeState()
{
    BuildDirParameters parameters(this);
    QTC_ASSERT(parameters.isValid(), return false);

    const bool hadBuildDirectory = parameters.buildDirectory.exists();
    ensureBuildDirectory(parameters);

    int reparseFlags = REPARSE_DEFAULT;
    qCDebug(cmakeBuildSystemLog) << "Checking whether build system needs to be persisted:"
                                 << "buildDir:" << parameters.buildDirectory
                                 << "Has extraargs:" << !parameters.configurationChangesArguments.isEmpty();

    if (mustApplyConfigurationChangesArguments(parameters)) {
        reparseFlags = REPARSE_FORCE_EXTRA_CONFIGURATION;
        qCDebug(cmakeBuildSystemLog) << "   -> must run CMake with extra arguments.";
    }
    if (!hadBuildDirectory) {
        reparseFlags = REPARSE_FORCE_INITIAL_CONFIGURATION;
        qCDebug(cmakeBuildSystemLog) << "   -> must run CMake with initial arguments.";
    }

    if (reparseFlags == REPARSE_DEFAULT)
        return false;

    qCDebug(cmakeBuildSystemLog) << "Requesting parse to persist CMake State";
    setParametersAndRequestParse(parameters,
                                 REPARSE_URGENT | REPARSE_FORCE_CMAKE_RUN | reparseFlags);
    return true;
}

void CMakeBuildSystem::clearCMakeCache()
{
    QTC_ASSERT(m_parameters.isValid(), return );
    QTC_ASSERT(!m_isHandlingError, return );

    stopParsingAndClearState();

    const FilePath pathsToDelete[] = {
        m_parameters.buildDirectory / "CMakeCache.txt",
        m_parameters.buildDirectory / "CMakeCache.txt.prev",
        m_parameters.buildDirectory / "CMakeFiles",
        m_parameters.buildDirectory / ".cmake/api/v1/reply",
        m_parameters.buildDirectory / ".cmake/api/v1/reply.prev",
        m_parameters.buildDirectory / Constants::PACKAGE_MANAGER_DIR
    };

    for (const FilePath &path : pathsToDelete)
        path.removeRecursively();

    emit configurationCleared();
}

void CMakeBuildSystem::combineScanAndParse(bool restoredFromBackup)
{
    if (buildConfiguration()->isActive()) {
        if (m_waitingForParse)
            return;

        if (m_combinedScanAndParseResult) {
            updateProjectData();
            m_currentGuard.markAsSuccess();

            if (restoredFromBackup)
                project()->addIssue(
                    CMakeProject::IssueType::Warning,
                    Tr::tr("<b>CMake configuration failed<b>"
                           "<p>The backup of the previous configuration has been restored.</p>"
                           "<p>Issues and \"Projects > Build\" settings "
                           "show more information about the failure.</p>"));

            m_reader.resetData();

            m_currentGuard = {};
            m_testNames.clear();

            emitBuildSystemUpdated();

            runCTest();
        } else {
            updateFallbackProjectData();

            project()->addIssue(CMakeProject::IssueType::Warning,
                                Tr::tr("<b>Failed to load project<b>"
                                       "<p>Issues and \"Projects > Build\" settings "
                                       "show more information about the failure.</p>"));
        }
    }
}

void CMakeBuildSystem::checkAndReportError(QString &errorMessage)
{
    if (!errorMessage.isEmpty()) {
        setError(errorMessage);
        errorMessage.clear();
    }
}

void CMakeBuildSystem::updateProjectData()
{
    qCDebug(cmakeBuildSystemLog) << "Updating CMake project data";

    QTC_ASSERT(m_treeScanner.isFinished() && !m_reader.isParsing(), return );

    buildConfiguration()->project()->setExtraProjectFiles(m_reader.projectFilesToWatch());

    CMakeConfig patchedConfig = configurationFromCMake();
    {
        QSet<QString> res;
        QStringList apps;
        for (const auto &target : std::as_const(m_buildTargets)) {
            if (target.targetType == DynamicLibraryType) {
                res.insert(target.executable.parentDir().toString());
                apps.push_back(target.executable.toUserOutput());
            }
            // ### shall we add also the ExecutableType ?
        }
        {
            CMakeConfigItem paths;
            paths.key = Android::Constants::ANDROID_SO_LIBS_PATHS;
            paths.values = Utils::toList(res);
            patchedConfig.append(paths);
        }

        apps.sort();
        {
            CMakeConfigItem appsPaths;
            appsPaths.key = "TARGETS_BUILD_PATH";
            appsPaths.values = apps;
            patchedConfig.append(appsPaths);
        }
    }

    Project *p = project();
    {
        auto newRoot = m_reader.rootProjectNode();
        if (newRoot) {
            setRootProjectNode(std::move(newRoot));

            if (QTC_GUARD(p->rootProjectNode())) {
                const QString nodeName = p->rootProjectNode()->displayName();
                p->setDisplayName(nodeName);

                // set config on target nodes
                const QSet<QString> buildKeys = Utils::transform<QSet>(m_buildTargets,
                                                                       &CMakeBuildTarget::title);
                p->rootProjectNode()->forEachProjectNode(
                    [patchedConfig, buildKeys](const ProjectNode *node) {
                        if (buildKeys.contains(node->buildKey())) {
                            auto targetNode = const_cast<CMakeTargetNode *>(
                                dynamic_cast<const CMakeTargetNode *>(node));
                            if (QTC_GUARD(targetNode))
                                targetNode->setConfig(patchedConfig);
                        }
                    });
            }
        }
    }

    {
        qDeleteAll(m_extraCompilers);
        m_extraCompilers = findExtraCompilers();
        qCDebug(cmakeBuildSystemLog) << "Extra compilers created.";
    }

    QtSupport::CppKitInfo kitInfo(kit());
    QTC_ASSERT(kitInfo.isValid(), return );

    QString errorMessage;
    RawProjectParts rpps = m_reader.createRawProjectParts(errorMessage);
    if (!errorMessage.isEmpty())
        setError(errorMessage);
    qCDebug(cmakeBuildSystemLog) << "Raw project parts created." << errorMessage;

    for (RawProjectPart &rpp : rpps) {
        rpp.setQtVersion(
                    kitInfo.projectPartQtVersion); // TODO: Check if project actually uses Qt.
        const FilePath includeFileBaseDir = buildConfiguration()->buildDirectory();
        QStringList cxxFlags = rpp.flagsForCxx.commandLineFlags;
        QStringList cFlags = rpp.flagsForC.commandLineFlags;
        addTargetFlagForIos(cxxFlags, cFlags, this, [this] {
            return m_configurationFromCMake.stringValueOf("CMAKE_OSX_DEPLOYMENT_TARGET");
        });
        if (kitInfo.cxxToolChain)
            rpp.setFlagsForCxx({kitInfo.cxxToolChain, cxxFlags, includeFileBaseDir});
        if (kitInfo.cToolChain)
            rpp.setFlagsForC({kitInfo.cToolChain, cFlags, includeFileBaseDir});
    }

    m_cppCodeModelUpdater->update({p, kitInfo, buildConfiguration()->environment(), rpps},
                                  m_extraCompilers);

    {
        const bool mergedHeaderPathsAndQmlImportPaths = kit()->value(
                    QtSupport::KitHasMergedHeaderPathsWithQmlImportPaths::id(), false).toBool();
        QStringList extraHeaderPaths;
        QList<QByteArray> moduleMappings;
        for (const RawProjectPart &rpp : std::as_const(rpps)) {
            FilePath moduleMapFile = buildConfiguration()->buildDirectory()
                    .pathAppended("qml_module_mappings/" + rpp.buildSystemTarget);
            if (expected_str<QByteArray> content = moduleMapFile.fileContents()) {
                auto lines = content->split('\n');
                for (const QByteArray &line : lines) {
                    if (!line.isEmpty())
                        moduleMappings.append(line.simplified());
                }
            }

            if (mergedHeaderPathsAndQmlImportPaths) {
                for (const auto &headerPath : rpp.headerPaths) {
                    if (headerPath.type == HeaderPathType::User || headerPath.type == HeaderPathType::System)
                        extraHeaderPaths.append(headerPath.path);
                }
            }
        }
        updateQmlJSCodeModel(extraHeaderPaths, moduleMappings);
    }
    updateInitialCMakeExpandableVars();

    emit buildConfiguration()->buildTypeChanged();

    qCDebug(cmakeBuildSystemLog) << "All CMake project data up to date.";
}

void CMakeBuildSystem::handleTreeScanningFinished()
{
    TreeScanner::Result result = m_treeScanner.release();
    m_allFiles = result.folderNode;
    qDeleteAll(result.allFiles);

    updateFileSystemNodes();
}

void CMakeBuildSystem::updateFileSystemNodes()
{
    auto newRoot = std::make_unique<CMakeProjectNode>(m_parameters.sourceDirectory);
    newRoot->setDisplayName(m_parameters.sourceDirectory.fileName());

    if (!m_reader.topCmakeFile().isEmpty()) {
        auto node = std::make_unique<FileNode>(m_reader.topCmakeFile(), FileType::Project);
        node->setIsGenerated(false);

        std::vector<std::unique_ptr<FileNode>> fileNodes;
        fileNodes.emplace_back(std::move(node));

        addCMakeLists(newRoot.get(), std::move(fileNodes));
    }

    if (m_allFiles)
        addFileSystemNodes(newRoot.get(), m_allFiles);
    setRootProjectNode(std::move(newRoot));

    m_reader.resetData();

    m_currentGuard = {};
    emitBuildSystemUpdated();

    qCDebug(cmakeBuildSystemLog) << "All fallback CMake project data up to date.";
}

void CMakeBuildSystem::updateFallbackProjectData()
{
    qCDebug(cmakeBuildSystemLog) << "Updating fallback CMake project data";
    qCDebug(cmakeBuildSystemLog) << "Starting TreeScanner";
    QTC_CHECK(m_treeScanner.isFinished());
    if (m_treeScanner.asyncScanForFiles(projectDirectory()))
        Core::ProgressManager::addTask(m_treeScanner.future(),
                                       Tr::tr("Scan \"%1\" project tree")
                                           .arg(project()->displayName()),
                                       "CMake.Scan.Tree");
}

void CMakeBuildSystem::updateCMakeConfiguration(QString &errorMessage)
{
    CMakeConfig cmakeConfig = m_reader.takeParsedConfiguration(errorMessage);
    for (auto &ci : cmakeConfig)
        ci.inCMakeCache = true;
    if (!errorMessage.isEmpty()) {
        const CMakeConfig changes = configurationChanges();
        for (const auto &ci : changes) {
            if (ci.isInitial)
                continue;
            const bool haveConfigItem = Utils::contains(cmakeConfig, [ci](const CMakeConfigItem& i) {
                return i.key == ci.key;
            });
            if (!haveConfigItem)
                cmakeConfig.append(ci);
        }
    }
    setConfigurationFromCMake(cmakeConfig);
}

void CMakeBuildSystem::handleParsingSucceeded(bool restoredFromBackup)
{
    if (!buildConfiguration()->isActive()) {
        stopParsingAndClearState();
        return;
    }

    clearError();

    QString errorMessage;
    {
        m_buildTargets = Utils::transform(CMakeBuildStep::specialTargets(m_reader.usesAllCapsTargets()), [this](const QString &t) {
            CMakeBuildTarget result;
            result.title = t;
            result.workingDirectory = m_parameters.buildDirectory;
            result.sourceDirectory = m_parameters.sourceDirectory;
            return result;
        });
        m_buildTargets += m_reader.takeBuildTargets(errorMessage);
        m_cmakeFiles = m_reader.takeCMakeFileInfos(errorMessage);

        checkAndReportError(errorMessage);
    }

    {
        updateCMakeConfiguration(errorMessage);
        checkAndReportError(errorMessage);
    }

    if (const CMakeTool *tool = m_parameters.cmakeTool())
        m_ctestPath = tool->cmakeExecutable().withNewPath(m_reader.ctestPath());

    setApplicationTargets(appTargets());

    // Note: This is practically always wrong and resulting in an empty view.
    // Setting the real data is triggered from a successful run of a
    // MakeInstallStep.
    setDeploymentData(deploymentDataFromFile());

    QTC_ASSERT(m_waitingForParse, return );
    m_waitingForParse = false;

    combineScanAndParse(restoredFromBackup);
}

void CMakeBuildSystem::handleParsingFailed(const QString &msg)
{
    setError(msg);

    QString errorMessage;
    updateCMakeConfiguration(errorMessage);
    // ignore errorMessage here, we already got one.

    m_ctestPath.clear();

    QTC_CHECK(m_waitingForParse);
    m_waitingForParse = false;
    m_combinedScanAndParseResult = false;

    combineScanAndParse(false);
}

void CMakeBuildSystem::wireUpConnections()
{
    // At this point the entire project will be fully configured, so let's connect everything and
    // trigger an initial parser run

    // Became active/inactive:
    connect(target(), &Target::activeBuildConfigurationChanged, this, [this] {
        // Build configuration has changed:
        qCDebug(cmakeBuildSystemLog) << "Requesting parse due to active BC changed";
        reparse(CMakeBuildSystem::REPARSE_DEFAULT);
    });
    connect(project(), &Project::activeTargetChanged, this, [this] {
        // Build configuration has changed:
        qCDebug(cmakeBuildSystemLog) << "Requesting parse due to active target changed";
        reparse(CMakeBuildSystem::REPARSE_DEFAULT);
    });

    // BuildConfiguration changed:
    connect(buildConfiguration(), &BuildConfiguration::environmentChanged, this, [this] {
        // The environment on our BC has changed, force CMake run to catch up with possible changes
        qCDebug(cmakeBuildSystemLog) << "Requesting parse due to environment change";
        reparse(CMakeBuildSystem::REPARSE_FORCE_CMAKE_RUN);
    });
    connect(buildConfiguration(), &BuildConfiguration::buildDirectoryChanged, this, [this] {
        // The build directory of our BC has changed:
        // Does the directory contain a CMakeCache ? Existing build, just parse
        // No CMakeCache? Run with initial arguments!
        qCDebug(cmakeBuildSystemLog) << "Requesting parse due to build directory change";
        const BuildDirParameters parameters(this);
        const FilePath cmakeCacheTxt = parameters.buildDirectory.pathAppended("CMakeCache.txt");
        const bool hasCMakeCache = cmakeCacheTxt.exists();
        const auto options = ReparseParameters(
                    hasCMakeCache
                    ? REPARSE_DEFAULT
                    : (REPARSE_FORCE_INITIAL_CONFIGURATION | REPARSE_FORCE_CMAKE_RUN));
        if (hasCMakeCache) {
            QString errorMessage;
            const CMakeConfig config = CMakeConfig::fromFile(cmakeCacheTxt, &errorMessage);
            if (!config.isEmpty() && errorMessage.isEmpty()) {
                QString cmakeBuildTypeName = config.stringValueOf("CMAKE_BUILD_TYPE");
                setCMakeBuildType(cmakeBuildTypeName, true);
            }
        }
        reparse(options);
    });

    connect(project(), &Project::projectFileIsDirty, this, [this] {
        if (buildConfiguration()->isActive() && !isParsing()) {
            auto settings = CMakeSpecificSettings::instance();
            if (settings->autorunCMake.value()) {
                qCDebug(cmakeBuildSystemLog) << "Requesting parse due to dirty project file";
                reparse(CMakeBuildSystem::REPARSE_FORCE_CMAKE_RUN);
            }
        }
    });

    // Force initial parsing run:
    if (buildConfiguration()->isActive()) {
        qCDebug(cmakeBuildSystemLog) << "Initial run:";
        reparse(CMakeBuildSystem::REPARSE_DEFAULT);
    }
}

void CMakeBuildSystem::ensureBuildDirectory(const BuildDirParameters &parameters)
{
    const FilePath bdir = parameters.buildDirectory;

    if (!buildConfiguration()->createBuildDirectory()) {
        handleParsingFailed(Tr::tr("Failed to create build directory \"%1\".").arg(bdir.toUserOutput()));
        return;
    }

    const CMakeTool *tool = parameters.cmakeTool();
    if (!tool) {
        handleParsingFailed(Tr::tr("No CMake tool set up in kit."));
        return;
    }

    if (tool->cmakeExecutable().needsDevice()) {
        if (!tool->cmakeExecutable().ensureReachable(bdir)) {
            // Make sure that the build directory is available on the device.
            handleParsingFailed(
                Tr::tr("The remote CMake executable cannot write to the local build directory."));
        }
    }
}

void CMakeBuildSystem::stopParsingAndClearState()
{
    qCDebug(cmakeBuildSystemLog) << buildConfiguration()->displayName()
                                 << "stopping parsing run!";
    m_reader.stop();
    m_reader.resetData();
}

void CMakeBuildSystem::becameDirty()
{
    qCDebug(cmakeBuildSystemLog) << "CMakeBuildSystem: becameDirty was triggered.";
    if (isParsing())
        return;

    reparse(REPARSE_DEFAULT);
}

void CMakeBuildSystem::updateReparseParameters(const int parameters)
{
    m_reparseParameters |= parameters;
}

int CMakeBuildSystem::takeReparseParameters()
{
    int result = m_reparseParameters;
    m_reparseParameters = REPARSE_DEFAULT;
    return result;
}

void CMakeBuildSystem::runCTest()
{
    if (!m_error.isEmpty() || m_ctestPath.isEmpty()) {
        qCDebug(cmakeBuildSystemLog) << "Cancel ctest run after failed cmake run";
        emit testInformationUpdated();
        return;
    }
    qCDebug(cmakeBuildSystemLog) << "Requesting ctest run after cmake run";

    const BuildDirParameters parameters(this);
    QTC_ASSERT(parameters.isValid(), return);

    ensureBuildDirectory(parameters);
    m_ctestProcess.reset(new Process);
    m_ctestProcess->setEnvironment(buildConfiguration()->environment());
    m_ctestProcess->setWorkingDirectory(parameters.buildDirectory);
    m_ctestProcess->setCommand({m_ctestPath, { "-N", "--show-only=json-v1"}});
    connect(m_ctestProcess.get(), &Process::done, this, [this] {
        if (m_ctestProcess->result() == ProcessResult::FinishedWithSuccess) {
            const QJsonDocument json
                = QJsonDocument::fromJson(m_ctestProcess->readAllRawStandardOutput());
            if (!json.isEmpty() && json.isObject()) {
                const QJsonObject jsonObj = json.object();
                const QJsonObject btGraph = jsonObj.value("backtraceGraph").toObject();
                const QJsonArray cmakelists = btGraph.value("files").toArray();
                const QJsonArray nodes = btGraph.value("nodes").toArray();
                const QJsonArray tests = jsonObj.value("tests").toArray();
                int counter = 0;
                for (const QJsonValue &testVal : tests) {
                    ++counter;
                    const QJsonObject test = testVal.toObject();
                    QTC_ASSERT(!test.isEmpty(), continue);
                    int file = -1;
                    int line = -1;
                    const int bt = test.value("backtrace").toInt(-1);
                    // we may have no real backtrace due to different registering
                    if (bt != -1) {
                        QSet<int> seen;
                        std::function<QJsonObject(int)> findAncestor = [&](int index){
                            const QJsonObject node = nodes.at(index).toObject();
                            const int parent = node.value("parent").toInt(-1);
                            if (seen.contains(parent) || parent < 0)
                                return node;
                            seen << parent;
                            return findAncestor(parent);
                        };
                        const QJsonObject btRef = findAncestor(bt);
                        file = btRef.value("file").toInt(-1);
                        line = btRef.value("line").toInt(-1);
                    }
                    // we may have no CMakeLists.txt file reference due to different registering
                    const FilePath cmakeFile = file != -1
                            ? FilePath::fromString(cmakelists.at(file).toString()) : FilePath();
                    m_testNames.append({ test.value("name").toString(), counter, cmakeFile, line });
                }
            }
        }
        emit testInformationUpdated();
    });
    m_ctestProcess->start();
}

CMakeBuildConfiguration *CMakeBuildSystem::cmakeBuildConfiguration() const
{
    return static_cast<CMakeBuildConfiguration *>(BuildSystem::buildConfiguration());
}

static FilePaths librarySearchPaths(const CMakeBuildSystem *bs, const QString &buildKey)
{
    const CMakeBuildTarget cmakeBuildTarget
        = Utils::findOrDefault(bs->buildTargets(), Utils::equal(&CMakeBuildTarget::title, buildKey));

    return cmakeBuildTarget.libraryDirectories;
}

const QList<BuildTargetInfo> CMakeBuildSystem::appTargets() const
{
    QList<BuildTargetInfo> appTargetList;
    const bool forAndroid = DeviceTypeKitAspect::deviceTypeId(kit())
                            == Android::Constants::ANDROID_DEVICE_TYPE;
    for (const CMakeBuildTarget &ct : m_buildTargets) {
        if (CMakeBuildSystem::filteredOutTarget(ct))
            continue;

        if (ct.targetType == ExecutableType || (forAndroid && ct.targetType == DynamicLibraryType)) {
            const QString buildKey = ct.title;

            BuildTargetInfo bti;
            bti.displayName = ct.title;
            bti.targetFilePath = ct.executable;
            bti.projectFilePath = ct.sourceDirectory.cleanPath();
            bti.workingDirectory = ct.workingDirectory;
            bti.buildKey = buildKey;
            bti.usesTerminal = !ct.linksToQtGui;
            bti.isQtcRunnable = ct.qtcRunnable;

            // Workaround for QTCREATORBUG-19354:
            bti.runEnvModifier = [this, buildKey](Environment &env, bool enabled) {
                if (enabled)
                    env.prependOrSetLibrarySearchPaths(librarySearchPaths(this, buildKey));
            };

            appTargetList.append(bti);
        }
    }

    return appTargetList;
}

QStringList CMakeBuildSystem::buildTargetTitles() const
{
    auto nonAutogenTargets = filtered(m_buildTargets, [](const CMakeBuildTarget &target){
        return !CMakeBuildSystem::filteredOutTarget(target);
    });
    return transform(nonAutogenTargets, &CMakeBuildTarget::title);
}

const QList<CMakeBuildTarget> &CMakeBuildSystem::buildTargets() const
{
    return m_buildTargets;
}

bool CMakeBuildSystem::filteredOutTarget(const CMakeBuildTarget &target)
{
    return target.title.endsWith("_autogen") ||
           target.title.endsWith("_autogen_timestamp_deps");
}

bool CMakeBuildSystem::isMultiConfig() const
{
    return m_isMultiConfig;
}

void CMakeBuildSystem::setIsMultiConfig(bool isMultiConfig)
{
    m_isMultiConfig = isMultiConfig;
}

bool CMakeBuildSystem::isMultiConfigReader() const
{
    return m_reader.isMultiConfig();
}

bool CMakeBuildSystem::usesAllCapsTargets() const
{
    return m_reader.usesAllCapsTargets();
}

CMakeProject *CMakeBuildSystem::project() const
{
    return static_cast<CMakeProject *>(ProjectExplorer::BuildSystem::project());
}

const QList<TestCaseInfo> CMakeBuildSystem::testcasesInfo() const
{
    return m_testNames;
}

CommandLine CMakeBuildSystem::commandLineForTests(const QList<QString> &tests,
                                                  const QStringList &options) const
{
    QStringList args = options;
    const QSet<QString> testsSet = Utils::toSet(tests);
    auto current = Utils::transform<QSet<QString>>(m_testNames, &TestCaseInfo::name);
    if (tests.isEmpty() || current == testsSet)
        return {m_ctestPath, args};

    QString testNumbers("0,0,0"); // start, end, stride
    for (const TestCaseInfo &info : m_testNames) {
        if (testsSet.contains(info.name))
            testNumbers += QString(",%1").arg(info.number);
    }
    args << "-I" << testNumbers;
    return {m_ctestPath, args};
}

DeploymentData CMakeBuildSystem::deploymentDataFromFile() const
{
    DeploymentData result;

    FilePath sourceDir = project()->projectDirectory();
    FilePath buildDir = buildConfiguration()->buildDirectory();

    QString deploymentPrefix;
    FilePath deploymentFilePath = sourceDir.pathAppended("QtCreatorDeployment.txt");

    bool hasDeploymentFile = deploymentFilePath.exists();
    if (!hasDeploymentFile) {
        deploymentFilePath = buildDir.pathAppended("QtCreatorDeployment.txt");
        hasDeploymentFile = deploymentFilePath.exists();
    }
    if (!hasDeploymentFile)
        return result;

    deploymentPrefix = result.addFilesFromDeploymentFile(deploymentFilePath, sourceDir);
    for (const CMakeBuildTarget &ct : m_buildTargets) {
        if (ct.targetType == ExecutableType || ct.targetType == DynamicLibraryType) {
            if (!ct.executable.isEmpty()
                    && result.deployableForLocalFile(ct.executable).localFilePath() != ct.executable) {
                result.addFile(ct.executable,
                               deploymentPrefix + buildDir.relativeChildPath(ct.executable).toString(),
                               DeployableFile::TypeExecutable);
            }
        }
    }

    return result;
}

QList<ExtraCompiler *> CMakeBuildSystem::findExtraCompilers()
{
    qCDebug(cmakeBuildSystemLog) << "Finding Extra Compilers: start.";

    QList<ExtraCompiler *> extraCompilers;
    const QList<ExtraCompilerFactory *> factories = ExtraCompilerFactory::extraCompilerFactories();

    qCDebug(cmakeBuildSystemLog) << "Finding Extra Compilers: Got factories.";

    const QSet<QString> fileExtensions = Utils::transform<QSet>(factories,
                                                                &ExtraCompilerFactory::sourceTag);

    qCDebug(cmakeBuildSystemLog) << "Finding Extra Compilers: Got file extensions:"
                                 << fileExtensions;

    // Find all files generated by any of the extra compilers, in a rather crude way.
    Project *p = project();
    const FilePaths fileList = p->files([&fileExtensions](const Node *n) {
        if (!Project::SourceFiles(n) || !n->isEnabled()) // isEnabled excludes nodes from the file system tree
            return false;
        const QString suffix = n->filePath().suffix();
        return !suffix.isEmpty() && fileExtensions.contains(suffix);
    });

    qCDebug(cmakeBuildSystemLog) << "Finding Extra Compilers: Got list of files to check.";

    // Generate the necessary information:
    for (const FilePath &file : fileList) {
        qCDebug(cmakeBuildSystemLog)
            << "Finding Extra Compilers: Processing" << file.toUserOutput();
        ExtraCompilerFactory *factory = Utils::findOrDefault(factories,
                                                             [&file](const ExtraCompilerFactory *f) {
                                                                 return file.endsWith(
                                                                     '.' + f->sourceTag());
                                                             });
        QTC_ASSERT(factory, continue);

        FilePaths generated = filesGeneratedFrom(file);
        qCDebug(cmakeBuildSystemLog)
            << "Finding Extra Compilers:     generated files:" << generated;
        if (generated.isEmpty())
            continue;

        extraCompilers.append(factory->create(p, file, generated));
        qCDebug(cmakeBuildSystemLog)
            << "Finding Extra Compilers:     done with" << file.toUserOutput();
    }

    qCDebug(cmakeBuildSystemLog) << "Finding Extra Compilers: done.";

    return extraCompilers;
}

void CMakeBuildSystem::updateQmlJSCodeModel(const QStringList &extraHeaderPaths,
                                            const QList<QByteArray> &moduleMappings)
{
    QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();

    if (!modelManager)
        return;

    Project *p = project();
    QmlJS::ModelManagerInterface::ProjectInfo projectInfo
        = modelManager->defaultProjectInfoForProject(p, p->files(Project::HiddenRccFolders));

    projectInfo.importPaths.clear();

    auto addImports = [&projectInfo](const QString &imports) {
        const QStringList importList = CMakeConfigItem::cmakeSplitValue(imports);
        for (const QString &import : importList)
            projectInfo.importPaths.maybeInsert(FilePath::fromString(import), QmlJS::Dialect::Qml);
    };

    const CMakeConfig &cm = configurationFromCMake();
    addImports(cm.stringValueOf("QML_IMPORT_PATH"));
    addImports(kit()->value(QtSupport::KitQmlImportPath::id()).toString());

    for (const QString &extraHeaderPath : extraHeaderPaths)
        projectInfo.importPaths.maybeInsert(FilePath::fromString(extraHeaderPath),
                                            QmlJS::Dialect::Qml);

    for (const QByteArray &mm : moduleMappings) {
        auto kvPair = mm.split('=');
        if (kvPair.size() != 2)
            continue;
        QString from = QString::fromUtf8(kvPair.at(0).trimmed());
        QString to = QString::fromUtf8(kvPair.at(1).trimmed());
        if (!from.isEmpty() && !to.isEmpty() && from != to) {
            // The QML code-model does not support sub-projects, so if there are multiple mappings for a single module,
            // choose the shortest one.
            if (projectInfo.moduleMappings.contains(from)) {
                if (to.size() < projectInfo.moduleMappings.value(from).size())
                    projectInfo.moduleMappings.insert(from, to);
            } else {
                projectInfo.moduleMappings.insert(from, to);
            }
        }
    }

    project()->setProjectLanguage(ProjectExplorer::Constants::QMLJS_LANGUAGE_ID,
                                  !projectInfo.sourceFiles.isEmpty());
    modelManager->updateProjectInfo(projectInfo, p);
}

void CMakeBuildSystem::updateInitialCMakeExpandableVars()
{
    const CMakeConfig &cm = configurationFromCMake();
    const CMakeConfig &initialConfig = initialCMakeConfiguration();

    CMakeConfig config;

    const FilePath projectDirectory = project()->projectDirectory();
    const auto samePath = [projectDirectory](const FilePath &first, const FilePath &second) {
        // if a path is relative, resolve it relative to the project directory
        // this is not 100% correct since CMake resolve them to CMAKE_CURRENT_SOURCE_DIR
        // depending on context, but we cannot do better here
        return first == second
               || projectDirectory.resolvePath(first)
                      == projectDirectory.resolvePath(second)
               || projectDirectory.resolvePath(first).canonicalPath()
                      == projectDirectory.resolvePath(second).canonicalPath();
    };

    // Replace path values that do not  exist on file system
    const QByteArrayList singlePathList = {
        "CMAKE_C_COMPILER",
        "CMAKE_CXX_COMPILER",
        "QT_QMAKE_EXECUTABLE",
        "QT_HOST_PATH",
        "CMAKE_TOOLCHAIN_FILE"
    };
    for (const auto &var : singlePathList) {
        auto it = std::find_if(cm.cbegin(), cm.cend(), [var](const CMakeConfigItem &item) {
            return item.key == var && !item.isInitial;
        });

        if (it != cm.cend()) {
            const QByteArray initialValue = initialConfig.expandedValueOf(kit(), var).toUtf8();
            const FilePath initialPath = FilePath::fromUserInput(QString::fromUtf8(initialValue));
            const FilePath path = FilePath::fromUserInput(QString::fromUtf8(it->value));

            if (!initialValue.isEmpty() && !samePath(path, initialPath) && !path.exists()) {
                CMakeConfigItem item(*it);
                item.value = initialValue;

                config << item;
            }
        }
    }

    // Prepend new values to existing path lists
    const QByteArrayList multiplePathList = {
        "CMAKE_PREFIX_PATH",
        "CMAKE_FIND_ROOT_PATH"
    };
    for (const auto &var : multiplePathList) {
        auto it = std::find_if(cm.cbegin(), cm.cend(), [var](const CMakeConfigItem &item) {
            return item.key == var && !item.isInitial;
        });

        if (it != cm.cend()) {
            const QByteArrayList initialValueList = initialConfig.expandedValueOf(kit(), var).toUtf8().split(';');

            for (const auto &initialValue: initialValueList) {
                const FilePath initialPath = FilePath::fromUserInput(QString::fromUtf8(initialValue));

                const bool pathIsContained
                    = Utils::contains(it->value.split(';'), [samePath, initialPath](const QByteArray &p) {
                          return samePath(FilePath::fromUserInput(QString::fromUtf8(p)), initialPath);
                      });
                if (!initialValue.isEmpty() && !pathIsContained) {
                    CMakeConfigItem item(*it);
                    item.value = initialValue;
                    item.value.append(";");
                    item.value.append(it->value);

                    config << item;
                }
            }
        }
    }

    if (!config.isEmpty())
        emit configurationChanged(config);
}

MakeInstallCommand CMakeBuildSystem::makeInstallCommand(const FilePath &installRoot) const
{
    MakeInstallCommand cmd;
    if (CMakeTool *tool = CMakeKitAspect::cmakeTool(target()->kit()))
        cmd.command.setExecutable(tool->cmakeExecutable());

    QString installTarget = "install";
    if (usesAllCapsTargets())
        installTarget = "INSTALL";

    FilePath buildDirectory = ".";
    if (auto bc = buildConfiguration())
        buildDirectory = bc->buildDirectory();

    cmd.command.addArg("--build");
    cmd.command.addArg(buildDirectory.path());
    cmd.command.addArg("--target");
    cmd.command.addArg(installTarget);

    if (isMultiConfigReader())
        cmd.command.addArgs({"--config", cmakeBuildType()});

    cmd.environment.set("DESTDIR", installRoot.nativePath());
    return cmd;
}

QList<QPair<Id, QString>> CMakeBuildSystem::generators() const
{
    if (!buildConfiguration())
        return {};
    const CMakeTool * const cmakeTool
            = CMakeKitAspect::cmakeTool(buildConfiguration()->target()->kit());
    if (!cmakeTool)
        return {};
    QList<QPair<Id, QString>> result;
    const QList<CMakeTool::Generator> &generators = cmakeTool->supportedGenerators();
    for (const CMakeTool::Generator &generator : generators) {
        result << qMakePair(Id::fromSetting(generator.name),
                            Tr::tr("%1 (via cmake)").arg(generator.name));
        for (const QString &extraGenerator : generator.extraGenerators) {
            const QString displayName = extraGenerator + " - " + generator.name;
            result << qMakePair(Id::fromSetting(displayName),
                                Tr::tr("%1 (via cmake)").arg(displayName));
        }
    }
    return result;
}

void CMakeBuildSystem::runGenerator(Id id)
{
    QTC_ASSERT(cmakeBuildConfiguration(), return);
    const auto showError = [](const QString &detail) {
        Core::MessageManager::writeDisrupting(Tr::tr("cmake generator failed: %1.").arg(detail));
    };
    const CMakeTool * const cmakeTool
            = CMakeKitAspect::cmakeTool(buildConfiguration()->target()->kit());
    if (!cmakeTool) {
        showError(Tr::tr("Kit does not have a cmake binary set"));
        return;
    }
    const QString generator = id.toSetting().toString();
    const FilePath outDir = buildConfiguration()->buildDirectory()
            / ("qtc_" + FileUtils::fileSystemFriendlyName(generator));
    if (!outDir.ensureWritableDir()) {
        showError(Tr::tr("Cannot create output directory \"%1\"").arg(outDir.toString()));
        return;
    }
    CommandLine cmdLine(cmakeTool->cmakeExecutable(), {"-S", buildConfiguration()->target()
                        ->project()->projectDirectory().toUserOutput(), "-G", generator});
    if (!cmdLine.executable().isExecutableFile()) {
        showError(Tr::tr("No valid cmake executable"));
        return;
    }
    const auto itemFilter = [](const CMakeConfigItem &item) {
        return !item.isNull()
                && item.type != CMakeConfigItem::STATIC
                && item.type != CMakeConfigItem::INTERNAL
                && !item.key.contains("GENERATOR");
    };
    QList<CMakeConfigItem> configItems = Utils::filtered(m_configurationChanges.toList(),
                                                         itemFilter);
    const QList<CMakeConfigItem> initialConfigItems
            = Utils::filtered(initialCMakeConfiguration().toList(), itemFilter);
    for (const CMakeConfigItem &item : std::as_const(initialConfigItems)) {
        if (!Utils::contains(configItems, [&item](const CMakeConfigItem &existingItem) {
            return existingItem.key == item.key;
        })) {
            configItems << item;
        }
    }
    for (const CMakeConfigItem &item : std::as_const(configItems))
        cmdLine.addArg(item.toArgument(buildConfiguration()->macroExpander()));
    if (const auto optionsAspect = buildConfiguration()->aspect<AdditionalCMakeOptionsAspect>();
            optionsAspect && !optionsAspect->value().isEmpty()) {
        cmdLine.addArgs(optionsAspect->value(), CommandLine::Raw);
    }
    const auto proc = new Process(this);
    connect(proc, &Process::done, proc, &Process::deleteLater);
    connect(proc, &Process::readyReadStandardOutput, this, [proc] {
        Core::MessageManager::writeFlashing(QString::fromLocal8Bit(proc->readAllRawStandardOutput()));
    });
    connect(proc, &Process::readyReadStandardError, this, [proc] {
        Core::MessageManager::writeDisrupting(QString::fromLocal8Bit(proc->readAllRawStandardError()));
    });
    proc->setWorkingDirectory(outDir);
    proc->setEnvironment(buildConfiguration()->environment());
    proc->setCommand(cmdLine);
    Core::MessageManager::writeFlashing(Tr::tr("Running in %1: %2")
                                        .arg(outDir.toUserOutput(), cmdLine.toUserOutput()));
    proc->start();
}

ExtraCompiler *CMakeBuildSystem::findExtraCompiler(const ExtraCompilerFilter &filter) const
{
    return Utils::findOrDefault(m_extraCompilers, filter);
}

} // CMakeProjectManager::Internal