forked from h4tr3d/cmakeprojectmanager2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuilddirmanager.cpp
1031 lines (867 loc) · 35.9 KB
/
builddirmanager.cpp
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.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "builddirmanager.h"
#include "cmakebuildconfiguration.h"
#include "cmakekitinformation.h"
#include "cmakeparser.h"
#include "cmakeprojectmanager.h"
#include "cmakeprojectnodes.h"
#include "cmaketool.h"
#include <coreplugin/icore.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <cpptools/projectpartbuilder.h>
#include <projectexplorer/headerpath.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectnodes.h>
#include <projectexplorer/target.h>
#include <projectexplorer/taskhub.h>
#include <projectexplorer/toolchain.h>
#include <utils/algorithm.h>
#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <utils/synchronousprocess.h>
#include <QDateTime>
#include <QFile>
#include <QFileInfo>
#include <QMessageBox>
#include <QRegularExpression>
#include <QSet>
#include <QTemporaryDir>
#include <chrono>
using namespace ProjectExplorer;
// --------------------------------------------------------------------
// Helper:
// --------------------------------------------------------------------
namespace CMakeProjectManager {
namespace Internal {
static QStringList toArguments(const CMakeConfig &config, const Kit *k) {
return Utils::transform(config, [k](const CMakeConfigItem &i) -> QString {
return i.toArgument(k->macroExpander());
});
}
// --------------------------------------------------------------------
// Compose source tree:
// --------------------------------------------------------------------
namespace {
bool sortNodesByPath(Node *a, Node *b)
{
return a->filePath() < b->filePath();
}
QList<FileNode*> composeProjectTree(QList<FileNode*> cmakefiles,
QList<FileNode*> treefiles)
{
// Assume: both input lists is sorted
// Step 1: get only added files
QList<ProjectExplorer::FileNode *> added;
QList<ProjectExplorer::FileNode *> deleted;
ProjectExplorer::compareSortedLists(cmakefiles, treefiles, deleted, added, sortNodesByPath);
qDeleteAll(ProjectExplorer::subtractSortedList(treefiles, added, sortNodesByPath));
// Step 2: now add new files to the cmakefiles. Note: using cmakefiles as a base is a good idea!
// also, keep result sorted
auto count = cmakefiles.count();
cmakefiles.append(added);
std::inplace_merge(cmakefiles.begin(), cmakefiles.begin() + count, cmakefiles.end(), sortNodesByPath);
return cmakefiles;
}
} // ::anonymous
// --------------------------------------------------------------------
// BuildDirManager:
// --------------------------------------------------------------------
BuildDirManager::BuildDirManager(CMakeBuildConfiguration *bc) :
m_buildConfiguration(bc)
{
QTC_ASSERT(bc, return);
m_projectName = sourceDirectory().fileName();
m_reparseTimer.setSingleShot(true);
connect(&m_reparseTimer, &QTimer::timeout, this, &BuildDirManager::parse);
connect(Core::EditorManager::instance(), &Core::EditorManager::aboutToSave,
this, &BuildDirManager::handleDocumentSaves);
}
BuildDirManager::~BuildDirManager()
{
stopProcess();
resetData();
delete m_tempDir;
}
const Kit *BuildDirManager::kit() const
{
return m_buildConfiguration->target()->kit();
}
const Utils::FileName BuildDirManager::buildDirectory() const
{
return m_buildConfiguration->buildDirectory();
}
const Utils::FileName BuildDirManager::workDirectory() const
{
const Utils::FileName bdir = buildDirectory();
if (bdir.exists())
return bdir;
if (m_tempDir)
return Utils::FileName::fromString(m_tempDir->path());
return bdir;
}
const Utils::FileName BuildDirManager::sourceDirectory() const
{
return m_buildConfiguration->target()->project()->projectDirectory();
}
const CMakeConfig BuildDirManager::intendedConfiguration() const
{
return m_buildConfiguration->cmakeConfiguration();
}
const CMakeToolchainInfo &BuildDirManager::cmakeToolchainInfo() const
{
return m_buildConfiguration->cmakeToolchainInfo();
}
bool BuildDirManager::isParsing() const
{
if (m_cmakeProcess)
return m_cmakeProcess->state() != QProcess::NotRunning;
return false;
}
void BuildDirManager::cmakeFilesChanged()
{
if (isParsing())
return;
const CMakeTool *tool = CMakeKitInformation::cmakeTool(m_buildConfiguration->target()->kit());
if (!tool->isAutoRun())
return;
m_reparseTimer.start(1000);
}
void BuildDirManager::forceReparse()
{
if (m_buildConfiguration->target()->activeBuildConfiguration() != m_buildConfiguration)
return;
stopProcess();
CMakeTool *tool = CMakeKitInformation::cmakeTool(kit());
QTC_ASSERT(tool, return);
startCMake(tool, CMakeGeneratorKitInformation::generatorArguments(kit()), intendedConfiguration(), cmakeToolchainInfo());
}
void BuildDirManager::resetData()
{
m_hasData = false;
qDeleteAll(m_watchedFiles);
m_watchedFiles.clear();
m_cmakeCache.clear();
m_projectName.clear();
m_buildTargets.clear();
m_files.clear();
}
bool BuildDirManager::updateCMakeStateBeforeBuild()
{
return m_reparseTimer.isActive();
}
bool BuildDirManager::persistCMakeState()
{
if (!m_tempDir)
return false;
QDir dir(buildDirectory().toString());
dir.mkpath(buildDirectory().toString());
delete m_tempDir;
m_tempDir = nullptr;
resetData();
QTimer::singleShot(0, this, &BuildDirManager::parse); // make sure signals only happen afterwards!
return true;
}
void BuildDirManager::generateProjectTree(CMakeProjectNode *root, const QList<FileNodeInfo> &treeFiles)
{
root->setDisplayName(m_projectName);
// Delete no longer necessary file watcher:
const QSet<Utils::FileName> currentWatched
= Utils::transform(m_watchedFiles, [](CMakeFile *cmf) { return cmf->filePath(); });
const QSet<Utils::FileName> toWatch = m_cmakeFiles;
QSet<Utils::FileName> toDelete = currentWatched;
toDelete.subtract(toWatch);
m_watchedFiles = Utils::filtered(m_watchedFiles, [&toDelete](Internal::CMakeFile *cmf) {
if (toDelete.contains(cmf->filePath())) {
delete cmf;
return false;
}
return true;
});
// Add new file watchers:
QSet<Utils::FileName> toAdd = toWatch;
toAdd.subtract(currentWatched);
foreach (const Utils::FileName &fn, toAdd) {
CMakeFile *cm = new CMakeFile(this, fn);
Core::DocumentManager::addDocument(cm);
m_watchedFiles.insert(cm);
}
// Compose lists
auto tm = std::chrono::system_clock::now();
// Create nodes
auto cmakeFileNodes = Utils::transform(m_files, [](const FileNodeInfo& node) {
return new FileNode(node.filePath, node.fileType, node.generated);
});
auto treeFileNodes = Utils::transform(treeFiles, [](const FileNodeInfo& node) {
return new FileNode(node.filePath, node.fileType, node.generated);
});
auto treeFilesCount = treeFiles.count();
auto cmakeFilesCount = m_files.count();
cmakeFileNodes = composeProjectTree(cmakeFileNodes, treeFileNodes);
qDebug() << "Extract data," << "Tree:" << treeFilesCount << "CMake:" << cmakeFilesCount << "Total:" << cmakeFileNodes.count();
auto delta = std::chrono::system_clock::now() - tm;
qDebug() << "Files composing time:" << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count();
tm = std::chrono::system_clock::now();
auto project = static_cast<CMakeProject*>(m_buildConfiguration->target()->project());
project->updateFilesCache(cmakeFileNodes);
root->buildTree(cmakeFileNodes);
delta = std::chrono::system_clock::now() - tm;
qDebug() << "Tree generation time:" << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count();
}
QSet<Core::Id> BuildDirManager::updateCodeModel(CppTools::ProjectPartBuilder &ppBuilder)
{
QSet<Core::Id> languages;
ToolChain *tcCxx = ToolChainKitInformation::toolChain(kit(), ToolChain::Language::Cxx);
ToolChain *tcC = ToolChainKitInformation::toolChain(kit(), ToolChain::Language::C);
const Utils::FileName sysroot = SysRootKitInformation::sysRoot(kit());
QHash<QString, QStringList> targetDataCacheCxx;
QHash<QString, QStringList> targetDataCacheC;
foreach (const CMakeBuildTarget &cbt, buildTargets()) {
if (cbt.targetType == UtilityType)
continue;
// CMake shuffles the include paths that it reports via the CodeBlocks generator
// So remove the toolchain include paths, so that at least those end up in the correct
// place.
auto cxxflags = getFlagsFor(cbt, targetDataCacheCxx, ToolChain::Language::Cxx);
auto cflags = getFlagsFor(cbt, targetDataCacheC, ToolChain::Language::C);
QSet<Utils::FileName> tcIncludes;
if (tcCxx)
foreach (const HeaderPath &hp, tcCxx->systemHeaderPaths(cxxflags, sysroot))
tcIncludes.insert(Utils::FileName::fromString(hp.path()));
if (tcC)
foreach (const HeaderPath &hp, tcC->systemHeaderPaths(cflags, sysroot))
tcIncludes.insert(Utils::FileName::fromString(hp.path()));
QStringList includePaths;
foreach (const Utils::FileName &i, cbt.includeFiles) {
if (!tcIncludes.contains(i))
includePaths.append(i.toString());
}
includePaths += buildDirectory().toString();
ppBuilder.setIncludePaths(includePaths);
ppBuilder.setCFlags(cflags);
ppBuilder.setCxxFlags(cxxflags);
ppBuilder.setDefines(cbt.defines);
ppBuilder.setDisplayName(cbt.title);
const QSet<Core::Id> partLanguages
= QSet<Core::Id>::fromList(ppBuilder.createProjectPartsForFiles(
Utils::transform(cbt.files, [](const Utils::FileName &fn) { return fn.toString(); })));
languages.unite(partLanguages);
}
return languages;
}
void BuildDirManager::parse()
{
checkConfiguration();
CMakeTool *tool = CMakeKitInformation::cmakeTool(kit());
const QStringList generatorArgs = CMakeGeneratorKitInformation::generatorArguments(kit());
QTC_ASSERT(tool, return);
const QString cbpFile = CMakeManager::findCbpFile(QDir(workDirectory().toString()));
const QFileInfo cbpFileFi = cbpFile.isEmpty() ? QFileInfo() : QFileInfo(cbpFile);
if (!cbpFileFi.exists()) {
// Initial create:
startCMake(tool, generatorArgs, intendedConfiguration(), cmakeToolchainInfo());
return;
}
const bool mustUpdate = m_cmakeFiles.isEmpty()
|| Utils::anyOf(m_cmakeFiles, [&cbpFileFi](const Utils::FileName &f) {
return f.toFileInfo().lastModified() > cbpFileFi.lastModified();
});
if (mustUpdate) {
startCMake(tool, generatorArgs, CMakeConfig(), CMakeToolchainInfo());
} else {
completeParsing();
}
}
void BuildDirManager::clearCache()
{
auto cmakeCache = Utils::FileName(workDirectory()).appendPath(QLatin1String("CMakeCache.txt"));
auto cmakeFiles = Utils::FileName(workDirectory()).appendPath(QLatin1String("CMakeFiles"));
const bool mustCleanUp = cmakeCache.exists() || cmakeFiles.exists();
if (!mustCleanUp)
return;
Utils::FileUtils::removeRecursively(cmakeCache);
Utils::FileUtils::removeRecursively(cmakeFiles);
forceReparse();
}
QList<CMakeBuildTarget> BuildDirManager::buildTargets() const
{
return m_buildTargets;
}
CMakeConfig BuildDirManager::parsedConfiguration() const
{
if (m_cmakeCache.isEmpty()) {
Utils::FileName cacheFile = workDirectory();
cacheFile.appendPath(QLatin1String("CMakeCache.txt"));
if (!cacheFile.exists())
return m_cmakeCache;
QString errorMessage;
m_cmakeCache = parseConfiguration(cacheFile, &errorMessage);
if (!errorMessage.isEmpty())
emit errorOccured(errorMessage);
const Utils::FileName sourceOfBuildDir
= Utils::FileName::fromUtf8(CMakeConfigItem::valueOf("CMAKE_HOME_DIRECTORY", m_cmakeCache));
const Utils::FileName canonicalSourceOfBuildDir = Utils::FileUtils::canonicalPath(sourceOfBuildDir);
const Utils::FileName canonicalSourceDirectory = Utils::FileUtils::canonicalPath(sourceDirectory());
if (canonicalSourceOfBuildDir != canonicalSourceDirectory) // Uses case-insensitive compare where appropriate
emit errorOccured(tr("The build directory is not for %1 but for %2")
.arg(canonicalSourceOfBuildDir.toUserOutput(),
canonicalSourceDirectory.toUserOutput()));
}
return m_cmakeCache;
}
void BuildDirManager::stopProcess()
{
if (!m_cmakeProcess)
return;
m_cmakeProcess->disconnect();
if (m_cmakeProcess->state() == QProcess::Running) {
m_cmakeProcess->terminate();
if (!m_cmakeProcess->waitForFinished(500) && m_cmakeProcess->state() == QProcess::Running)
m_cmakeProcess->kill();
}
cleanUpProcess();
if (!m_future)
return;
m_future->reportCanceled();
m_future->reportFinished();
delete m_future;
m_future = nullptr;
}
void BuildDirManager::cleanUpProcess()
{
if (!m_cmakeProcess)
return;
QTC_ASSERT(m_cmakeProcess->state() == QProcess::NotRunning, return);
m_cmakeProcess->disconnect();
if (m_cmakeProcess->state() == QProcess::Running) {
m_cmakeProcess->terminate();
if (!m_cmakeProcess->waitForFinished(500) && m_cmakeProcess->state() == QProcess::Running)
m_cmakeProcess->kill();
}
m_cmakeProcess->waitForFinished();
delete m_cmakeProcess;
m_cmakeProcess = nullptr;
// Delete issue parser:
m_parser->flush();
delete m_parser;
m_parser = nullptr;
}
void BuildDirManager::extractData()
{
const Utils::FileName topCMake
= Utils::FileName::fromString(sourceDirectory().toString() + QLatin1String("/CMakeLists.txt"));
resetData();
QList<ProjectExplorer::FileNode *> files;
auto onScopeExit = [&files, this](void*) {
m_files = Utils::transform(files, [](const ProjectExplorer::FileNode *node) {
return FileNodeInfo(node->filePath(), node->fileType(), node->isGenerated());
});
Utils::sort(m_files);
qDeleteAll(files);
};
auto scopeExitHolder = std::unique_ptr<void,decltype(onScopeExit)>(reinterpret_cast<void*>(1), onScopeExit);
m_projectName = sourceDirectory().fileName();
files.append(new FileNode(topCMake, ProjectFileType, false));
// Do not insert topCMake into m_cmakeFiles: The project already watches that!
// Find cbp file
Utils::FileName cbpFile = Utils::FileName::fromString(CMakeManager::findCbpFile(workDirectory().toString()));
if (cbpFile.isEmpty())
return;
m_cmakeFiles.insert(cbpFile);
// Add CMakeCache.txt file:
Utils::FileName cacheFile = workDirectory();
cacheFile.appendPath(QLatin1String("CMakeCache.txt"));
if (cacheFile.toFileInfo().exists())
m_cmakeFiles.insert(cacheFile);
// setFolderName
CMakeCbpParser cbpparser;
CMakeTool *cmake = CMakeKitInformation::cmakeTool(kit());
// Parsing
if (!cbpparser.parseCbpFile(cmake->pathMapper(), cbpFile, sourceDirectory()))
return;
m_projectName = cbpparser.projectName();
files = cbpparser.fileList();
if (cbpparser.hasCMakeFiles()) {
files.append(cbpparser.cmakeFileList());
foreach (const FileNode *node, cbpparser.cmakeFileList())
m_cmakeFiles.insert(node->filePath());
}
// Make sure the top cmakelists.txt file is always listed:
if (!Utils::contains(files, [topCMake](FileNode *fn) { return fn->filePath() == topCMake; })) {
files.append(new FileNode(topCMake, ProjectFileType, false));
}
m_buildTargets = cbpparser.buildTargets();
}
void BuildDirManager::startCMake(CMakeTool *tool, const QStringList &generatorArgs,
const CMakeConfig &config, const CMakeToolchainInfo &toolchain)
{
QTC_ASSERT(tool && tool->isValid(), return);
QTC_ASSERT(!m_cmakeProcess, return);
QTC_ASSERT(!m_parser, return);
QTC_ASSERT(!m_future, return);
// Find a directory to set up into:
if (!buildDirectory().exists()) {
if (!m_tempDir)
m_tempDir = new QTemporaryDir(QDir::tempPath() + QLatin1String("/qtc-cmake-XXXXXX"));
QTC_ASSERT(m_tempDir->isValid(), return);
}
// Make sure work directory exists:
QTC_ASSERT(workDirectory().exists(), return);
m_parser = new CMakeParser;
QDir source = QDir(sourceDirectory().toString());
connect(m_parser, &IOutputParser::addTask, m_parser,
[source](const Task &task) {
if (task.file.isEmpty() || task.file.toFileInfo().isAbsolute()) {
TaskHub::addTask(task);
} else {
Task t = task;
t.file = Utils::FileName::fromString(source.absoluteFilePath(task.file.toString()));
TaskHub::addTask(t);
}
});
// Always use the sourceDir: If we are triggered because the build directory is getting deleted
// then we are racing against CMakeCache.txt also getting deleted.
const QString srcDir = sourceDirectory().toString();
m_cmakeProcess = new Utils::QtcProcess(this);
m_cmakeProcess->setWorkingDirectory(workDirectory().toString());
m_cmakeProcess->setEnvironment(m_buildConfiguration->environment());
connect(m_cmakeProcess, &QProcess::readyReadStandardOutput,
this, &BuildDirManager::processCMakeOutput);
connect(m_cmakeProcess, &QProcess::readyReadStandardError,
this, &BuildDirManager::processCMakeError);
connect(m_cmakeProcess, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
this, &BuildDirManager::cmakeFinished);
QString args;
Utils::QtcProcess::addArg(&args, srcDir);
Utils::QtcProcess::addArgs(&args, generatorArgs);
Utils::QtcProcess::addArgs(&args, toArguments(config, kit()));
Utils::QtcProcess::addArgs(&args, toolchain.arguments(toArguments(config, kit()), workDirectory().toString()));
TaskHub::clearTasks(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);
Core::MessageManager::write(tr("Running \"%1 %2\" in %3.")
.arg(tool->cmakeExecutable().toUserOutput())
.arg(args)
.arg(workDirectory().toUserOutput()));
m_future = new QFutureInterface<void>();
m_future->setProgressRange(0, 1);
Core::ProgressManager::addTask(m_future->future(),
tr("Configuring \"%1\"").arg(m_buildConfiguration->target()->project()->displayName()),
"CMake.Configure");
m_cmakeProcess->setCommand(tool->cmakeExecutable().toString(), args);
m_cmakeProcess->start();
emit configurationStarted();
}
void BuildDirManager::cmakeFinished(int code, QProcess::ExitStatus status)
{
QTC_ASSERT(m_cmakeProcess, return);
// process rest of the output:
processCMakeOutput();
processCMakeError();
cleanUpProcess();
QString msg;
if (status != QProcess::NormalExit)
msg = tr("*** cmake process crashed!");
else if (code != 0)
msg = tr("*** cmake process exited with exit code %1.").arg(code);
if (!msg.isEmpty()) {
Core::MessageManager::write(msg);
TaskHub::addTask(Task::Error, msg, ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);
m_future->reportCanceled();
} else {
m_future->setProgressValue(1);
}
m_future->reportFinished();
delete m_future;
m_future = nullptr;
completeParsing();
}
static QString lineSplit(const QString &rest, const QByteArray &array, std::function<void(const QString &)> f)
{
QString tmp = rest + Utils::SynchronousProcess::normalizeNewlines(QString::fromLocal8Bit(array));
int start = 0;
int end = tmp.indexOf(QLatin1Char('\n'), start);
while (end >= 0) {
f(tmp.mid(start, end - start));
start = end + 1;
end = tmp.indexOf(QLatin1Char('\n'), start);
}
return tmp.mid(start);
}
void BuildDirManager::processCMakeOutput()
{
static QString rest;
rest = lineSplit(rest, m_cmakeProcess->readAllStandardOutput(), [this](const QString &s) { Core::MessageManager::write(s); });
}
void BuildDirManager::processCMakeError()
{
static QString rest;
rest = lineSplit(rest, m_cmakeProcess->readAllStandardError(), [this](const QString &s) {
m_parser->stdError(s);
Core::MessageManager::write(s);
});
}
void BuildDirManager::completeParsing()
{
extractData(); // try even if cmake failed...
m_hasData = true;
emit dataAvailable();
}
QStringList BuildDirManager::getFlagsFor(const CMakeBuildTarget &buildTarget,
QHash<QString, QStringList> &cache,
ToolChain::Language lang)
{
// check cache:
auto it = cache.constFind(buildTarget.title);
if (it != cache.constEnd())
return *it;
if (extractFlagsFromMake(buildTarget, cache, lang))
return cache.value(buildTarget.title);
if (extractFlagsFromNinja(buildTarget, cache, lang))
return cache.value(buildTarget.title);
cache.insert(buildTarget.title, QStringList());
return QStringList();
}
bool BuildDirManager::extractFlagsFromMake(const CMakeBuildTarget &buildTarget,
QHash<QString, QStringList> &cache,
ToolChain::Language lang)
{
QString makeCommand = buildTarget.makeCommand.toString();
QString flagsPrefix;
switch (lang)
{
case ToolChain::Language::Cxx:
flagsPrefix = QLatin1String("CXX_FLAGS =");
break;
case ToolChain::Language::C:
flagsPrefix = QLatin1String("C_FLAGS =");
break;
default:
return false;
}
int startIndex = makeCommand.indexOf('\"');
int endIndex = makeCommand.indexOf('\"', startIndex + 1);
if (startIndex != -1 && endIndex != -1) {
startIndex += 1;
QString makefile = makeCommand.mid(startIndex, endIndex - startIndex);
int slashIndex = makefile.lastIndexOf('/');
makefile.truncate(slashIndex);
makefile.append("/CMakeFiles/" + buildTarget.title + ".dir/flags.make");
// Remove un-needed shell escaping:
makefile = makefile.remove("\\");
QFile file(makefile);
if (file.exists()) {
file.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream stream(&file);
while (!stream.atEnd()) {
QString line = stream.readLine().trimmed();
if (line.startsWith(flagsPrefix)) {
// Skip past =
auto flags =
Utils::transform(line.mid(flagsPrefix.length()).trimmed().split(' ', QString::SkipEmptyParts), [](QString flag) -> QString {
// Remove \' for function-style macrosses:
// -D'MACRO()'=xxx
// -D'MACRO()=xxx'
// -D'MACRO()'
return flag
.replace(QRegExp("^-D(\\s*)'([0-9a-ZA-Z_\\(\\)]+)'="), "-D\\1\\2=")
.replace(QRegExp("^-D(\\s*)'([0-9a-ZA-Z_\\(\\)]+)=(.+)'$"), "-D\\1\\2=\\3")
.replace(QRegExp("^-D(\\s*)'([0-9a-ZA-Z_\\(\\)]+)'$"), "-D\\1\\2");
});
cache.insert(buildTarget.title, flags);
//qDebug() << "Flags:" << (lang == ToolChain::Language::Cxx ? "C++" : "C") << flags;
return true;
}
}
}
}
return false;
}
bool BuildDirManager::extractFlagsFromNinja(const CMakeBuildTarget &buildTarget,
QHash<QString, QStringList> &cache,
ToolChain::Language lang)
{
Q_UNUSED(buildTarget)
if (!cache.isEmpty()) // We fill the cache in one go!
return false;
QString compilerPrefix;
switch (lang)
{
case ToolChain::Language::Cxx:
compilerPrefix = QLatin1String("CXX_COMPILER");
break;
case ToolChain::Language::C:
compilerPrefix = QLatin1String("C_COMPILER");
break;
default:
return false;
}
// Attempt to find build.ninja file and obtain FLAGS (CXX_FLAGS) from there if no suitable flags.make were
// found
// Get "all" target's working directory
QByteArray ninjaFile;
QString buildNinjaFile = buildTargets().at(0).workingDirectory.toString();
buildNinjaFile += "/build.ninja";
QFile buildNinja(buildNinjaFile);
if (buildNinja.exists()) {
buildNinja.open(QIODevice::ReadOnly | QIODevice::Text);
ninjaFile = buildNinja.readAll();
buildNinja.close();
}
if (ninjaFile.isEmpty())
return false;
QTextStream stream(ninjaFile);
bool cxxFound = false;
const QString targetSignature = "# Object build statements for ";
QString currentTarget;
while (!stream.atEnd()) {
// 1. Look for a block that refers to the current target
// 2. Look for a build rule which invokes CXX_COMPILER
// 3. Return the FLAGS definition
QString line = stream.readLine().trimmed();
if (line.startsWith('#')) {
if (line.startsWith(targetSignature)) {
int pos = line.lastIndexOf(' ');
currentTarget = line.mid(pos + 1);
}
} else if (!currentTarget.isEmpty() && line.startsWith("build")) {
cxxFound = line.indexOf(compilerPrefix) != -1;
} else if (cxxFound && line.startsWith("FLAGS =")) {
// Skip past =
cache.insert(currentTarget, line.mid(7).trimmed().split(' ', QString::SkipEmptyParts));
}
}
return !cache.isEmpty();
}
void BuildDirManager::checkConfiguration()
{
if (m_tempDir) // always throw away changes in the tmpdir!
return;
Kit *k = m_buildConfiguration->target()->kit();
const CMakeConfig cache = parsedConfiguration();
if (cache.isEmpty())
return; // No cache file yet.
CMakeConfig newConfig;
QSet<QString> changedKeys;
QSet<QString> removedKeys;
foreach (const CMakeConfigItem &iBc, intendedConfiguration()) {
const CMakeConfigItem &iCache
= Utils::findOrDefault(cache, [&iBc](const CMakeConfigItem &i) { return i.key == iBc.key; });
if (iCache.isNull()) {
removedKeys << QString::fromUtf8(iBc.key);
} else if (QString::fromUtf8(iCache.value) != iBc.expandedValue(k)) {
changedKeys << QString::fromUtf8(iBc.key);
newConfig.append(iCache);
} else {
newConfig.append(iBc);
}
}
if (!changedKeys.isEmpty() || !removedKeys.isEmpty()) {
QSet<QString> total = removedKeys + changedKeys;
QStringList keyList = total.toList();
Utils::sort(keyList);
QString table = QLatin1String("<table>");
foreach (const QString &k, keyList) {
QString change;
if (removedKeys.contains(k))
change = tr("<removed>");
else
change = QString::fromUtf8(CMakeConfigItem::valueOf(k.toUtf8(), cache)).trimmed();
if (change.isEmpty())
change = tr("<empty>");
table += QString::fromLatin1("\n<tr><td>%1</td><td>%2</td></tr>").arg(k).arg(change.toHtmlEscaped());
}
table += QLatin1String("\n</table>");
QPointer<QMessageBox> box = new QMessageBox(Core::ICore::mainWindow());
box->setText(tr("CMake configuration has changed on disk."));
box->setInformativeText(tr("The CMakeCache.txt file has changed: %1").arg(table));
auto *defaultButton = box->addButton(tr("Overwrite Changes in CMake"), QMessageBox::RejectRole);
box->addButton(tr("Apply Changes to Project"), QMessageBox::AcceptRole);
box->setDefaultButton(defaultButton);
int ret = box->exec();
if (ret == QMessageBox::Apply)
m_buildConfiguration->setCMakeConfiguration(newConfig);
}
}
void BuildDirManager::handleDocumentSaves(Core::IDocument *document)
{
Target *t = m_buildConfiguration->target()->project()->activeTarget();
BuildConfiguration *bc = t ? t->activeBuildConfiguration() : nullptr;
if (!m_cmakeFiles.contains(document->filePath()) ||
m_buildConfiguration->target() != t ||
m_buildConfiguration != bc)
return;
m_reparseTimer.start(100);
}
static QByteArray trimCMakeCacheLine(const QByteArray &in) {
int start = 0;
while (start < in.count() && (in.at(start) == ' ' || in.at(start) == '\t'))
++start;
return in.mid(start, in.count() - start - 1);
}
static QByteArrayList splitCMakeCacheLine(const QByteArray &line) {
const int colonPos = line.indexOf(':');
if (colonPos < 0)
return QByteArrayList();
const int equalPos = line.indexOf('=', colonPos + 1);
if (equalPos < colonPos)
return QByteArrayList();
return QByteArrayList() << line.mid(0, colonPos)
<< line.mid(colonPos + 1, equalPos - colonPos - 1)
<< line.mid(equalPos + 1);
}
static CMakeConfigItem::Type fromByteArray(const QByteArray &type) {
if (type == "BOOL")
return CMakeConfigItem::BOOL;
if (type == "STRING")
return CMakeConfigItem::STRING;
if (type == "FILEPATH")
return CMakeConfigItem::FILEPATH;
if (type == "PATH")
return CMakeConfigItem::PATH;
QTC_CHECK(type == "INTERNAL" || type == "STATIC");
return CMakeConfigItem::INTERNAL;
}
CMakeConfig BuildDirManager::parseConfiguration(const Utils::FileName &cacheFile,
QString *errorMessage)
{
CMakeConfig result;
QFile cache(cacheFile.toString());
if (!cache.open(QIODevice::ReadOnly | QIODevice::Text)) {
if (errorMessage)
*errorMessage = tr("Failed to open %1 for reading.").arg(cacheFile.toUserOutput());
return CMakeConfig();
}
QSet<QByteArray> advancedSet;
QMap<QByteArray, QByteArray> valuesMap;
QByteArray documentation;
while (!cache.atEnd()) {
const QByteArray line = trimCMakeCacheLine(cache.readLine());
if (line.isEmpty() || line.startsWith('#'))
continue;
if (line.startsWith("//")) {
documentation = line.mid(2);
continue;
}
const QByteArrayList pieces = splitCMakeCacheLine(line);
if (pieces.isEmpty())
continue;
QTC_ASSERT(pieces.count() == 3, continue);
const QByteArray key = pieces.at(0);
const QByteArray type = pieces.at(1);
const QByteArray value = pieces.at(2);
if (key.endsWith("-ADVANCED") && value == "1") {
advancedSet.insert(key.left(key.count() - 9 /* "-ADVANCED" */));
} else if (key.endsWith("-STRINGS") && fromByteArray(type) == CMakeConfigItem::INTERNAL) {
valuesMap[key.left(key.count() - 8) /* "-STRINGS" */] = value;
} else {
CMakeConfigItem::Type t = fromByteArray(type);
result << CMakeConfigItem(key, t, documentation, value);
}
}
// Set advanced flags:
for (int i = 0; i < result.count(); ++i) {
CMakeConfigItem &item = result[i];
item.isAdvanced = advancedSet.contains(item.key);
if (valuesMap.contains(item.key)) {
item.values = CMakeConfigItem::cmakeSplitValue(QString::fromUtf8(valuesMap[item.key]));
} else if (item.key == "CMAKE_BUILD_TYPE") {
// WA for known options
item.values << "" << "Debug" << "Release" << "MinSizeRel" << "RelWithDebInfo";
}
}
Utils::sort(result, CMakeConfigItem::sortOperator());
return result;
}
void BuildDirManager::handleCmakeFileChange()
{
Target *t = m_buildConfiguration->target()->project()->activeTarget();
BuildConfiguration *bc = t ? t->activeBuildConfiguration() : nullptr;
if (m_buildConfiguration->target() == t && m_buildConfiguration == bc)
cmakeFilesChanged();
}
void BuildDirManager::maybeForceReparse()
{
checkConfiguration();
const QByteArray GENERATOR_KEY = "CMAKE_GENERATOR";
const QByteArray EXTRA_GENERATOR_KEY = "CMAKE_EXTRA_GENERATOR";
const QByteArray CMAKE_COMMAND_KEY = "CMAKE_COMMAND";
const QByteArrayList criticalKeys
= QByteArrayList() << GENERATOR_KEY << CMAKE_COMMAND_KEY;
if (!m_hasData) {
forceReparse();
return;
}
const CMakeConfig currentConfig = parsedConfiguration();
const CMakeTool *tool = CMakeKitInformation::cmakeTool(kit());
QTC_ASSERT(tool, return); // No cmake... we should not have ended up here in the first place
const QString extraKitGenerator = CMakeGeneratorKitInformation::extraGenerator(kit());
const QString mainKitGenerator = CMakeGeneratorKitInformation::generator(kit());
CMakeConfig targetConfig = m_buildConfiguration->cmakeConfiguration();
targetConfig.append(CMakeConfigItem(GENERATOR_KEY, CMakeConfigItem::INTERNAL,
QByteArray(), mainKitGenerator.toUtf8()));
if (!extraKitGenerator.isEmpty())
targetConfig.append(CMakeConfigItem(EXTRA_GENERATOR_KEY, CMakeConfigItem::INTERNAL,
QByteArray(), extraKitGenerator.toUtf8()));
targetConfig.append(CMakeConfigItem(CMAKE_COMMAND_KEY, CMakeConfigItem::INTERNAL,
QByteArray(), tool->cmakeExecutable().toUserOutput().toUtf8()));
Utils::sort(targetConfig, CMakeConfigItem::sortOperator());
bool mustReparse = false;
auto ccit = currentConfig.constBegin();
auto kcit = targetConfig.constBegin();