-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcmakebuildsystem.cpp
More file actions
2311 lines (1931 loc) · 88.7 KB
/
cmakebuildsystem.cpp
File metadata and controls
2311 lines (1931 loc) · 88.7 KB
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
// 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 "cmakekitaspect.h"
#include "cmakeprocess.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 <projectexplorer/extracompiler.h>
#include <projectexplorer/kitaspects.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectupdater.h>
#include <projectexplorer/target.h>
#include <projectexplorer/taskhub.h>
#include <texteditor/texteditor.h>
#include <texteditor/textdocument.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
#include <qtsupport/qtcppkitinfo.h>
#include <qtsupport/qtsupportconstants.h>
#include <utils/algorithm.h>
#include <utils/checkablemessagebox.h>
#include <utils/macroexpander.h>
#include <utils/mimeconstants.h>
#include <utils/process.h>
#include <utils/qtcassert.h>
#include <QClipboard>
#include <QGuiApplication>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLoggingCategory>
#include <QTimer>
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(ProjectUpdaterFactory::createCppProjectUpdater())
{
// 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 = fn.toString().startsWith(projectFilePath().toString() + ".user")
|| 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 == Utils::Constants::CMAKE_PROJECT_MIMETYPE
|| mt == Utils::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);
connect(&m_reader, &FileApiReader::debuggingStarted, this, &BuildSystem::debuggingStarted);
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);
qDeleteAll(m_allFiles.allFiles);
}
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.";
if (m_allFiles.allFiles.isEmpty()) {
qCDebug(cmakeBuildSystemLog)
<< "No treescanner information available, forcing treescanner run.";
updateReparseParameters(REPARSE_SCAN);
}
int reparseParameters = takeReparseParameters();
m_waitingForScan = (reparseParameters & REPARSE_SCAN) != 0;
m_waitingForParse = true;
m_combinedScanAndParseResult = true;
if (m_waitingForScan) {
qCDebug(cmakeBuildSystemLog) << "Starting TreeScanner";
QTC_CHECK(m_treeScanner.isFinished());
if (m_treeScanner.asyncScanForFiles(projectDirectory()))
Core::ProgressManager::addTask(m_treeScanner.future(),
tr("Scan \"%1\" project tree")
.arg(project()->displayName()),
"CMake.Scan.Tree");
}
QTC_ASSERT(m_parameters.isValid(), return );
TaskHub::clearTasks(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);
qCDebug(cmakeBuildSystemLog) << "Parse called with flags:"
<< reparseParametersString(reparseParameters);
const FilePath cache = m_parameters.buildDirectory.pathAppended("CMakeCache.txt");
if (!cache.exists()) {
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();
const CMakeTool *tool = m_parameters.cmakeTool();
CMakeTool::Version version = tool ? tool->version() : CMakeTool::Version();
const bool isDebuggable = (version.major == 3 && version.minor >= 27) || version.major > 3;
qCDebug(cmakeBuildSystemLog) << "Asking reader to parse";
m_reader.parse(reparseParameters & REPARSE_FORCE_CMAKE_RUN,
reparseParameters & REPARSE_FORCE_INITIAL_CONFIGURATION,
reparseParameters & REPARSE_FORCE_EXTRA_CONFIGURATION,
(reparseParameters & REPARSE_DEBUG) && isDebuggable,
reparseParameters & REPARSE_PROFILING);
}
void CMakeBuildSystem::requestDebugging()
{
qCDebug(cmakeBuildSystemLog) << "Requesting parse due to \"Rescan Project\" command";
reparse(REPARSE_FORCE_CMAKE_RUN | REPARSE_FORCE_EXTRA_CONFIGURATION | REPARSE_URGENT
| REPARSE_DEBUG);
}
bool CMakeBuildSystem::supportsAction(Node *context, ProjectAction action, const Node *node) const
{
#if 0
if (dynamic_cast<CMakeTargetNode *>(context))
return action == ProjectAction::AddNewFile || action == ProjectAction::AddExistingFile
|| action == ProjectAction::AddExistingDirectory || action == ProjectAction::Rename
|| action == ProjectAction::RemoveFile;
#else
switch (action) {
case ProjectExplorer::AddNewFile:
case ProjectExplorer::EraseFile:
case ProjectExplorer::Rename:
return true;
default:
break;
}
#endif
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) {
using namespace Utils::Constants;
const auto mimeType = Utils::mimeTypeForFile(file);
if (mimeType.matchesName(CPP_SOURCE_MIMETYPE)
|| mimeType.matchesName(CPP_HEADER_MIMETYPE)
|| mimeType.matchesName(OBJECTIVE_C_SOURCE_MIMETYPE)
|| mimeType.matchesName(OBJECTIVE_CPP_SOURCE_MIMETYPE)) {
sourceFiles << file;
} else if (mimeType.matchesName(QML_MIMETYPE)
|| mimeType.matchesName(QMLUI_MIMETYPE)
|| mimeType.matchesName(QMLPROJECT_MIMETYPE)
|| mimeType.matchesName(JS_MIMETYPE)
|| mimeType.matchesName(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 0
if (notAdded)
*notAdded = filePaths;
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()) {
qCCritical(cmakeBuildSystemLog) << "target.backtrace for" << targetName << "is empty. "
<< "The location where to add the files is unknown.";
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
Core::DocumentManager::saveModifiedDocumentSilently(
Core::DocumentModel::documentForFilePath(targetCMakeFile));
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)) {
qCCritical(cmakeBuildSystemLog).noquote()
<< targetCMakeFile.path() << "failed to parse! Error:"
<< QString::fromStdString(errorString);
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()) {
qCCritical(cmakeBuildSystemLog) << "Function that defined the target" << targetName
<< "could not be found at" << targetDefinitionLine;
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;
int extraChars = 0;
QString snippet;
auto afterFunctionLastArgument =
[&line, &column, &snippet, &extraChars, 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);
// Take into consideration the quotes
if (lastArgument.Delim == cmListFileArgument::Quoted)
extraChars = 2;
};
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 + extraChars},
Constants::CMAKE_EDITOR_ID,
Core::EditorManager::DoNotMakeVisible));
if (!editor) {
qCCritical(cmakeBuildSystemLog).noquote()
<< "BaseTextEditor cannot be obtained for" << targetCMakeFile.path() << line
<< int(column + extraChars);
return false;
}
editor->insert(snippet);
editor->editorWidget()->autoIndent();
if (!Core::DocumentManager::saveDocument(editor->document())) {
qCCritical(cmakeBuildSystemLog).noquote()
<< "Changes to" << targetCMakeFile.path() << "could not be saved.";
return false;
}
if (notAdded)
notAdded->clear();
return true;
}
#else
bool handled = false;
if (auto n = dynamic_cast<CMakeProjectNode *>(context)) {
noAutoAdditionNotify(filePaths, n);
handled = true;
} else if (auto n = dynamic_cast<CMakeTargetNode *>(context)) {
noAutoAdditionNotify(filePaths, n);
handled = true;
}
if (addFilesPriv(filePaths))
handled = true;
if (handled)
return true;
#endif
return BuildSystem::addFiles(context, filePaths, notAdded);
}
#if 1
bool CMakeBuildSystem::deleteFiles(Node *context, const Utils::FilePaths &filePaths)
{
if (eraseFilesPriv(filePaths))
return true;
return BuildSystem::deleteFiles(context, filePaths);
}
bool CMakeBuildSystem::canRenameFile(Node *context, const FilePath &filePath, const FilePath &newFilePath)
{
// TBD: filter out rename ability
return true;
}
bool CMakeBuildSystem::renameFile(Node *context, const FilePath &filePath, const FilePath &newFilePath)
{
if (renameFilePriv(filePath, newFilePath))
return true;
return BuildSystem::renameFile(context, filePath, newFilePath);
}
#else
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
Core::DocumentManager::saveModifiedDocumentSilently(
Core::DocumentModel::documentForFilePath(targetCMakeFile));
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.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);
});
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()) {
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.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;
qCCritical(cmakeBuildSystemLog).noquote()
<< "File" << filePos.value().cmakeFile.path() << "does not exist.";
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;
qCCritical(cmakeBuildSystemLog).noquote()
<< "BaseTextEditor cannot be obtained for"
<< filePos.value().cmakeFile.path() << filePos.value().argumentPosition.Line
<< int(filePos.value().argumentPosition.Column - 1);
continue;
}
// If quotes were used for the source file, remove the quotes too
int extraChars = 0;
if (filePos->argumentPosition.Delim == cmListFileArgument::Quoted)
extraChars = 2;
if (!filePos.value().fromGlobbing)
editor->replace(filePos.value().relativeFileName.length() + extraChars, "");
editor->editorWidget()->autoIndent();
if (!Core::DocumentManager::saveDocument(editor->document())) {
badFiles << file;
qCCritical(cmakeBuildSystemLog).noquote()
<< "Changes to" << filePos.value().cmakeFile.path()
<< "could not be saved.";
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()) {
qCCritical(cmakeBuildSystemLog).noquote()
<< "File" << fileToRename.cmakeFile.path() << "does not exist.";
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) {
qCCritical(cmakeBuildSystemLog).noquote()
<< "BaseTextEditor cannot be obtained for" << fileToRename.cmakeFile.path()
<< fileToRename.argumentPosition.Line << int(fileToRename.argumentPosition.Column);
return false;
}
// If quotes were used for the source file, skip the starting quote
if (fileToRename.argumentPosition.Delim == cmListFileArgument::Quoted)
editor->setCursorPosition(editor->position() + 1);
if (!fileToRename.fromGlobbing)
editor->replace(fileToRename.relativeFileName.length(), newRelPathName);
editor->editorWidget()->autoIndent();
if (!Core::DocumentManager::saveDocument(editor->document())) {
qCCritical(cmakeBuildSystemLog).noquote()
<< "Changes to" << fileToRename.cmakeFile.path() << "could not be saved.";
return false;
}
return true;
}
return false;
}
#endif // #if 1
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") {
const QString generatedFileName = "ui_" + sourceFile.completeBaseName() + ".h";
auto targetNode = this->project()->nodeForFilePath(sourceFile);
while (targetNode && !dynamic_cast<const CMakeTargetNode *>(targetNode))
targetNode = targetNode->parentFolderNode();
FilePaths generatedFilePaths;
if (targetNode) {
const QString autogenSignature = targetNode->buildKey() + "_autogen/include";
// If AUTOUIC reports the generated header file name, use that path
generatedFilePaths = this->project()->files(
[autogenSignature, generatedFileName](const Node *n) {
const FilePath filePath = n->filePath();
if (!filePath.contains(autogenSignature))
return false;
return Project::GeneratedFiles(n) && filePath.endsWith(generatedFileName);
});
}
if (generatedFilePaths.empty())
generatedFilePaths = {generatedFilePath.pathAppended(generatedFileName)};
return generatedFilePaths;
}
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";
if (reparseFlags & REPARSE_SCAN)
result += " SCAN";
}
return result.trimmed();
}
void CMakeBuildSystem::reparse(int reparseParameters)
{
setParametersAndRequestParse(BuildDirParameters(this), reparseParameters);
}
void CMakeBuildSystem::setParametersAndRequestParse(const BuildDirParameters ¶meters,
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 ¶meters) 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 | REPARSE_SCAN);
}
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::runCMakeWithProfiling()
{
qCDebug(cmakeBuildSystemLog) << "Requesting parse due \"CMake Profiler\" command";
reparse(REPARSE_FORCE_CMAKE_RUN | REPARSE_URGENT | REPARSE_FORCE_EXTRA_CONFIGURATION
| REPARSE_PROFILING);
}
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::addFilesPriv(const Utils::FilePaths &filePaths)
{
QList<FileNode *> nodes; // nodes to store in persistent tree
for (auto &filePath : filePaths) {
const auto mimeType = Utils::mimeTypeForFile(filePath);
auto type = TreeScanner::genericFileType(mimeType, filePath);
auto node = new FileNode(filePath, type);
node->setEnabled(false);
node->setIsGenerated(false);
nodes << node;
}
if (nodes.empty())
return true;
// Update tree without full rescan run
sort(nodes, Node::sortByPath);
auto oldSize = m_allFiles.allFiles.size();
m_allFiles.allFiles.append(nodes);
std::inplace_merge(m_allFiles.allFiles.begin(),
m_allFiles.allFiles.begin() + oldSize,
m_allFiles.allFiles.end(),
Node::sortByPath);
// TBD: fix allFiles.folderNode
// Real adding occurs after function exit.
updateProjectDataPriv();
return true;
}
bool CMakeBuildSystem::eraseFilesPriv(const Utils::FilePaths &filePaths)
{
QList<const FileNode *> removed;
for (auto& filePath : filePaths) {
const auto mimeType = Utils::mimeTypeForFile(filePath);
auto type = TreeScanner::genericFileType(mimeType, filePath);
auto toRemove = new FileNode(filePath, type);
toRemove->setIsGenerated(false);
// To update list
removed << toRemove;
}
// Update tree without full rescan run
sort(removed, Node::sortByPath);
// Inplace change m_allFiles in one pass
auto it = std::lower_bound(m_allFiles.allFiles.begin(),
m_allFiles.allFiles.end(), removed[0], Node::sortByPath);
QTC_ASSERT(it != m_allFiles.allFiles.end(), return false);
int allIdx = static_cast<int>(std::distance(m_allFiles.allFiles.begin(), it));
int remIdx = 0;