summaryrefslogtreecommitdiff
path: root/src/plugins/cmakeprojectmanager/servermodereader.cpp
blob: 04c69af89fcbd256cbb7be2faa758aee7ed1104f (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
/****************************************************************************
**
** 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 "servermodereader.h"

#include "cmakebuildconfiguration.h"
#include "cmakeprojectconstants.h"
#include "cmakeprojectmanager.h"
#include "cmakeprojectnodes.h"
#include "servermode.h"

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/toolchain.h>
#include <projectexplorer/task.h>
#include <projectexplorer/taskhub.h>

#include <utils/algorithm.h>
#include <utils/asconst.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>

using namespace ProjectExplorer;
using namespace Utils;

namespace CMakeProjectManager {
namespace Internal {

const char CACHE_TYPE[] = "cache";
const char CODEMODEL_TYPE[] = "codemodel";
const char CONFIGURE_TYPE[] = "configure";
const char CMAKE_INPUTS_TYPE[] = "cmakeInputs";
const char COMPUTE_TYPE[] = "compute";

const char NAME_KEY[] = "name";
const char SOURCE_DIRECTORY_KEY[] = "sourceDirectory";
const char SOURCES_KEY[] = "sources";

const int MAX_PROGRESS = 1400;

// --------------------------------------------------------------------
// ServerModeReader:
// --------------------------------------------------------------------

ServerModeReader::ServerModeReader()
{
    connect(Core::EditorManager::instance(), &Core::EditorManager::aboutToSave,
            this, [this](const Core::IDocument *document) {
        if (m_cmakeFiles.contains(document->filePath()))
            emit dirty();
    });

    connect(&m_parser, &CMakeParser::addOutput,
            this, [](const QString &m) { Core::MessageManager::write(m); });
    connect(&m_parser, &CMakeParser::addTask, this, [this](const Task &t) {
        Task editable(t);
        if (!editable.file.isEmpty()) {
            QDir srcDir(m_parameters.sourceDirectory.toString());
            editable.file = FileName::fromString(srcDir.absoluteFilePath(editable.file.toString()));
        }
        TaskHub::addTask(editable);
    });
}

ServerModeReader::~ServerModeReader()
{
    stop();
}

void ServerModeReader::setParameters(const BuildDirReader::Parameters &p)
{
    BuildDirReader::setParameters(p);
    if (!m_cmakeServer) {
        m_cmakeServer.reset(new ServerMode(p.environment,
                                           p.sourceDirectory, p.buildDirectory, p.cmakeExecutable,
                                           p.generator, p.extraGenerator, p.platform, p.toolset,
                                           true, 1));
        connect(m_cmakeServer.get(), &ServerMode::errorOccured,
                this, &ServerModeReader::errorOccured);
        connect(m_cmakeServer.get(), &ServerMode::cmakeReply,
                this, &ServerModeReader::handleReply);
        connect(m_cmakeServer.get(), &ServerMode::cmakeError,
                this, &ServerModeReader::handleError);
        connect(m_cmakeServer.get(), &ServerMode::cmakeProgress,
                this, &ServerModeReader::handleProgress);
        connect(m_cmakeServer.get(), &ServerMode::cmakeSignal,
                this, &ServerModeReader::handleSignal);
        connect(m_cmakeServer.get(), &ServerMode::cmakeMessage, [this](const QString &m) {
            const QStringList lines = m.split('\n');
            for (const QString &l : lines) {
                m_parser.stdError(l);
                Core::MessageManager::write(l);
            }
        });
        connect(m_cmakeServer.get(), &ServerMode::message,
                this, [](const QString &m) { Core::MessageManager::write(m); });
        connect(m_cmakeServer.get(), &ServerMode::connected,
                this, &ServerModeReader::isReadyNow, Qt::QueuedConnection); // Delay
        connect(m_cmakeServer.get(), &ServerMode::disconnected,
                this, [this]() {
            stop();
            Core::MessageManager::write(tr("Parsing of CMake project failed: Connection to CMake server lost."));
            m_cmakeServer.reset();
        }, Qt::QueuedConnection); // Delay
    }
}

bool ServerModeReader::isCompatible(const BuildDirReader::Parameters &p)
{
    // Server mode connection got lost, reset...
    if (!m_parameters.cmakeExecutable.isEmpty() && !m_cmakeServer)
        return false;

    return p.cmakeHasServerMode
            && p.cmakeExecutable == m_parameters.cmakeExecutable
            && p.environment == m_parameters.environment
            && p.generator == m_parameters.generator
            && p.extraGenerator == m_parameters.extraGenerator
            && p.platform == m_parameters.platform
            && p.toolset == m_parameters.toolset
            && p.sourceDirectory == m_parameters.sourceDirectory
            && p.buildDirectory == m_parameters.buildDirectory;
}

void ServerModeReader::resetData()
{
    m_hasData = false;
}

void ServerModeReader::parse(bool force)
{
    emit configurationStarted();
    Core::MessageManager::write(tr("Starting to parse CMake project for Qt Creator."));

    QTC_ASSERT(m_cmakeServer, return);
    QVariantMap extra;
    if (force || !QDir(m_parameters.buildDirectory.toString()).exists("CMakeCache.txt")) {
        QStringList cacheArguments = transform(m_parameters.configuration,
                                               [this](const CMakeConfigItem &i) {
            return i.toArgument(m_parameters.expander);
        });
        cacheArguments.prepend(QString()); // Work around a bug in CMake 3.7.0 and 3.7.1 where
                                           // the first argument gets lost!
        extra.insert("cacheArguments", QVariant(cacheArguments));
    }

    m_future.reset(new QFutureInterface<void>());
    m_future->setProgressRange(0, MAX_PROGRESS);
    m_progressStepMinimum = 0;
    m_progressStepMaximum = 1000;
    Core::ProgressManager::addTask(m_future->future(),
                                   tr("Configuring \"%1\"").arg(m_parameters.projectName),
                                   "CMake.Configure");

    m_cmakeServer->sendRequest(CONFIGURE_TYPE, extra);
}

void ServerModeReader::stop()
{
    if (m_future) {
        m_future->reportCanceled();
        m_future->reportFinished();
        m_future.reset();
    }
    m_parser.flush();
}

bool ServerModeReader::isReady() const
{
    return m_cmakeServer->isConnected();
}

bool ServerModeReader::isParsing() const
{
    return static_cast<bool>(m_future);
}

bool ServerModeReader::hasData() const
{
    return m_hasData;
}

QList<CMakeBuildTarget> ServerModeReader::buildTargets() const
{
    const QList<CMakeBuildTarget> result = transform(m_targets, [](const Target *t) -> CMakeBuildTarget {
        CMakeBuildTarget ct;
        ct.title = t->name;
        ct.executable = t->artifacts.isEmpty() ? FileName() : t->artifacts.at(0);
        TargetType type = UtilityType;
        if (t->type == "EXECUTABLE")
            type = ExecutableType;
        else if (t->type == "STATIC_LIBRARY")
            type = StaticLibraryType;
        else if (t->type == "MODULE_LIBRARY"
                 || t->type == "SHARED_LIBRARY"
                 || t->type == "INTERFACE_LIBRARY"
                 || t->type == "OBJECT_LIBRARY")
            type = DynamicLibraryType;
        else
            type = UtilityType;
        ct.targetType = type;
        if (t->artifacts.isEmpty()) {
            ct.workingDirectory = t->buildDirectory;
        } else {
            ct.workingDirectory = Utils::FileName::fromString(t->artifacts.at(0).toFileInfo().absolutePath());
        }
        ct.sourceDirectory = t->sourceDirectory;
        return ct;
    });
    m_targets.clear();
    return result;
}

CMakeConfig ServerModeReader::takeParsedConfiguration()
{
    CMakeConfig config = m_cmakeCache;
    m_cmakeCache.clear();
    return config;
}

static void addCMakeVFolder(FolderNode *base, const Utils::FileName &basePath, int priority,
                     const QString &displayName, const QList<FileNode *> &files)
{
    if (files.isEmpty())
        return;
    FolderNode *folder = base;
    if (!displayName.isEmpty()) {
        folder = new VirtualFolderNode(basePath, priority);
        folder->setDisplayName(displayName);
        base->addNode(folder);
    }
    folder->addNestedNodes(files);
    for (FolderNode *fn : folder->folderNodes())
        fn->compress();
}

static QList<FileNode *> removeKnownNodes(const QSet<Utils::FileName> &knownFiles, const QList<FileNode *> &files)
{
    return Utils::filtered(files, [&knownFiles](const FileNode *n) {
        if (knownFiles.contains(n->filePath())) {
            delete n;
            return false;
        }
        return true;
    });
}

static void addCMakeInputs(FolderNode *root,
                           const Utils::FileName &sourceDir,
                           const Utils::FileName &buildDir,
                           QList<FileNode *> &sourceInputs,
                           QList<FileNode *> &buildInputs,
                           QList<FileNode *> &rootInputs)
{
    ProjectNode *cmakeVFolder = new CMakeInputsNode(root->filePath());
    root->addNode(cmakeVFolder);

    QSet<Utils::FileName> knownFiles;
    root->forEachGenericNode([&knownFiles](const Node *n) {
        if (n->listInProject())
            knownFiles.insert(n->filePath());
    });

    addCMakeVFolder(cmakeVFolder, sourceDir, 1000, QString(), removeKnownNodes(knownFiles, sourceInputs));
    addCMakeVFolder(cmakeVFolder, buildDir, 100,
                    QCoreApplication::translate("CMakeProjectManager::Internal::ServerModeReader", "<Build Directory>"),
                    removeKnownNodes(knownFiles, buildInputs));
    addCMakeVFolder(cmakeVFolder, Utils::FileName(), 10,
                    QCoreApplication::translate("CMakeProjectManager::Internal::ServerModeReader", "<Other Locations>"),
                    removeKnownNodes(knownFiles, rootInputs));
}

void ServerModeReader::generateProjectTree(CMakeProjectNode *root,
                                           const QList<const FileNode *> &allFiles)
{
    // Split up cmake inputs into useful chunks:
    QList<FileNode *> cmakeFilesSource;
    QList<FileNode *> cmakeFilesBuild;
    QList<FileNode *> cmakeFilesOther;
    QList<FileNode *> cmakeLists;

    foreach (FileNode *fn, m_cmakeInputsFileNodes) {
        const FileName path = fn->filePath();
        if (path.fileName().compare("CMakeLists.txt", HostOsInfo::fileNameCaseSensitivity()) == 0)
            cmakeLists.append(fn);
        else if (path.isChildOf(m_parameters.sourceDirectory))
            cmakeFilesSource.append(fn);
        else if (path.isChildOf(m_parameters.buildDirectory))
            cmakeFilesBuild.append(fn);
        else
            cmakeFilesOther.append(fn);
    }
    m_cmakeInputsFileNodes.clear(); // Clean out, they are not going to be used anymore!

    const Project *topLevel = Utils::findOrDefault(m_projects, [this](const Project *p) {
        return m_parameters.sourceDirectory == p->sourceDirectory;
    });
    if (topLevel)
        root->setDisplayName(topLevel->name);

    QHash<Utils::FileName, ProjectNode *> cmakeListsNodes = addCMakeLists(root, cmakeLists);
    QList<FileNode *> knownHeaders;
    addProjects(cmakeListsNodes, m_projects, knownHeaders);

    addHeaderNodes(root, knownHeaders, allFiles);

    if (!cmakeFilesSource.isEmpty() || !cmakeFilesBuild.isEmpty() || !cmakeFilesOther.isEmpty())
        addCMakeInputs(root, m_parameters.sourceDirectory, m_parameters.buildDirectory,
                       cmakeFilesSource, cmakeFilesBuild, cmakeFilesOther);
}

void ServerModeReader::updateCodeModel(CppTools::RawProjectParts &rpps)
{
    int counter = 0;
    for (const FileGroup *fg : Utils::asConst(m_fileGroups)) {
        ++counter;
        const QString defineArg
                = transform(fg->defines, [](const QString &s) -> QString {
                    QString result = QString::fromLatin1("#define ") + s;
                    int assignIndex = result.indexOf('=');
                    if (assignIndex != -1)
                        result[assignIndex] = ' ';
                    return result;
                }).join('\n');
        const QStringList flags = QtcProcess::splitArgs(fg->compileFlags);
        const QStringList includes = transform(fg->includePaths, [](const IncludePath *ip)  { return ip->path.toString(); });

        CppTools::RawProjectPart rpp;
        rpp.setProjectFileLocation(fg->target->sourceDirectory.toString() + "/CMakeLists.txt");
        rpp.setBuildSystemTarget(fg->target->name);
        rpp.setDisplayName(fg->target->name + QString::number(counter));
        rpp.setDefines(defineArg.toUtf8());
        rpp.setIncludePaths(includes);

        CppTools::RawProjectPartFlags cProjectFlags;
        cProjectFlags.commandLineFlags = flags;
        rpp.setFlagsForC(cProjectFlags);

        CppTools::RawProjectPartFlags cxxProjectFlags;
        cxxProjectFlags.commandLineFlags = flags;
        rpp.setFlagsForCxx(cxxProjectFlags);

        rpp.setFiles(transform(fg->sources, &FileName::toString));

        rpps.append(rpp);
    }

    qDeleteAll(m_projects); // Not used anymore!
    m_projects.clear();
    m_targets.clear();
    m_fileGroups.clear();
}

void ServerModeReader::handleReply(const QVariantMap &data, const QString &inReplyTo)
{
    Q_UNUSED(data);
    if (inReplyTo == CONFIGURE_TYPE) {
        m_cmakeServer->sendRequest(COMPUTE_TYPE);
        if (m_future)
            m_future->setProgressValue(1000);
        m_progressStepMinimum = m_progressStepMaximum;
        m_progressStepMaximum = 1100;
    } else if (inReplyTo == COMPUTE_TYPE) {
        m_cmakeServer->sendRequest(CODEMODEL_TYPE);
        if (m_future)
            m_future->setProgressValue(1100);
        m_progressStepMinimum = m_progressStepMaximum;
        m_progressStepMaximum = 1200;
    } else if (inReplyTo == CODEMODEL_TYPE) {
        extractCodeModelData(data);
        m_cmakeServer->sendRequest(CMAKE_INPUTS_TYPE);
        if (m_future)
            m_future->setProgressValue(1200);
        m_progressStepMinimum = m_progressStepMaximum;
        m_progressStepMaximum = 1300;
    } else if (inReplyTo == CMAKE_INPUTS_TYPE) {
        extractCMakeInputsData(data);
        m_cmakeServer->sendRequest(CACHE_TYPE);
        if (m_future)
            m_future->setProgressValue(1300);
        m_progressStepMinimum = m_progressStepMaximum;
        m_progressStepMaximum = 1400;
    } else if (inReplyTo == CACHE_TYPE) {
        extractCacheData(data);
        if (m_future) {
            m_future->setProgressValue(MAX_PROGRESS);
            m_future->reportFinished();
            m_future.reset();
        }
        m_hasData = true;
        Core::MessageManager::write(tr("CMake Project was parsed successfully."));
        emit dataAvailable();
    }
}

void ServerModeReader::handleError(const QString &message)
{
    TaskHub::addTask(Task::Error, message, ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM,
                     Utils::FileName(), -1);
    stop();
    Core::MessageManager::write(tr("CMake Project parsing failed."));
    emit errorOccured(message);
}

void ServerModeReader::handleProgress(int min, int cur, int max, const QString &inReplyTo)
{
    Q_UNUSED(inReplyTo);

    if (!m_future)
        return;
    const int progress = calculateProgress(m_progressStepMinimum, min, cur, max, m_progressStepMaximum);
    m_future->setProgressValue(progress);
}

void ServerModeReader::handleSignal(const QString &signal, const QVariantMap &data)
{
    Q_UNUSED(data);
    // CMake on Windows sends false dirty signals on each edit (QTCREATORBUG-17944)
    if (!HostOsInfo::isWindowsHost() && signal == "dirty")
        emit dirty();
}

int ServerModeReader::calculateProgress(const int minRange, const int min, const int cur, const int max, const int maxRange)
{
    if (minRange == maxRange || min == max)
        return minRange;
    const int clampedCur = std::min(std::max(cur, min), max);
    return minRange + ((clampedCur - min) / (max - min)) * (maxRange - minRange);
}

void ServerModeReader::extractCodeModelData(const QVariantMap &data)
{
    const QVariantList configs = data.value("configurations").toList();
    QTC_CHECK(configs.count() == 1); // FIXME: Support several configurations!
    for (const QVariant &c : configs) {
        const QVariantMap &cData = c.toMap();
        extractConfigurationData(cData);
    }
}

void ServerModeReader::extractConfigurationData(const QVariantMap &data)
{
    const QString name = data.value(NAME_KEY).toString();
    Q_UNUSED(name);
    QSet<QString> knownTargets; // To filter duplicate target names:-/
    const QVariantList projects = data.value("projects").toList();
    for (const QVariant &p : projects) {
        const QVariantMap pData = p.toMap();
        m_projects.append(extractProjectData(pData, knownTargets));
    }
}

ServerModeReader::Project *ServerModeReader::extractProjectData(const QVariantMap &data,
                                                                QSet<QString> &knownTargets)
{
    auto project = new Project;
    project->name = data.value(NAME_KEY).toString();
    project->sourceDirectory = FileName::fromString(data.value(SOURCE_DIRECTORY_KEY).toString());

    const QVariantList targets = data.value("targets").toList();
    for (const QVariant &t : targets) {
        const QVariantMap tData = t.toMap();
        Target *tp = extractTargetData(tData, project, knownTargets);
        if (tp)
            project->targets.append(tp);
    }
    return project;
}

ServerModeReader::Target *ServerModeReader::extractTargetData(const QVariantMap &data, Project *p,
                                                              QSet<QString> &knownTargets)
{
    const QString targetName = data.value(NAME_KEY).toString();

    // Remove duplicate targets: CMake unfortunately does duplicate targets for all projects that
    // contain them. Keep at least till cmake 3.9 is deprecated.
    const int count = knownTargets.count();
    knownTargets.insert(targetName);
    if (knownTargets.count() == count)
        return nullptr;

    auto target = new Target;
    target->project = p;
    target->name = targetName;
    target->sourceDirectory = FileName::fromString(data.value(SOURCE_DIRECTORY_KEY).toString());
    target->buildDirectory = FileName::fromString(data.value("buildDirectory").toString());

    QDir srcDir(target->sourceDirectory.toString());

    target->type = data.value("type").toString();
    const QStringList artifacts = data.value("artifacts").toStringList();
    target->artifacts = transform(artifacts, [&srcDir](const QString &a) { return FileName::fromString(srcDir.absoluteFilePath(a)); });

    const QVariantList fileGroups = data.value("fileGroups").toList();
    for (const QVariant &fg : fileGroups) {
        const QVariantMap fgData = fg.toMap();
        target->fileGroups.append(extractFileGroupData(fgData, srcDir, target));
    }

    fixTarget(target);

    m_targets.append(target);
    return target;
}

ServerModeReader::FileGroup *ServerModeReader::extractFileGroupData(const QVariantMap &data,
                                                                    const QDir &srcDir,
                                                                    Target *t)
{
    auto fileGroup = new FileGroup;
    fileGroup->target = t;
    fileGroup->compileFlags = data.value("compileFlags").toString();
    fileGroup->defines = data.value("defines").toStringList();
    fileGroup->includePaths = transform(data.value("includePath").toList(),
                                        [](const QVariant &i) -> IncludePath* {
        const QVariantMap iData = i.toMap();
        auto result = new IncludePath;
        result->path = FileName::fromString(iData.value("path").toString());
        result->isSystem = iData.value("isSystem", false).toBool();
        return result;
    });
    fileGroup->isGenerated = data.value("isGenerated", false).toBool();
    fileGroup->sources = transform(data.value(SOURCES_KEY).toStringList(),
                                   [&srcDir](const QString &s) {
        return FileName::fromString(QDir::cleanPath(srcDir.absoluteFilePath(s)));
    });

    m_fileGroups.append(fileGroup);
    return fileGroup;
}

void ServerModeReader::extractCMakeInputsData(const QVariantMap &data)
{
    const FileName src = FileName::fromString(data.value(SOURCE_DIRECTORY_KEY).toString());
    QTC_ASSERT(src == m_parameters.sourceDirectory, return);
    QDir srcDir(src.toString());

    m_cmakeFiles.clear();

    const QVariantList buildFiles = data.value("buildFiles").toList();
    for (const QVariant &bf : buildFiles) {
        const QVariantMap &section = bf.toMap();
        const QStringList sources = section.value(SOURCES_KEY).toStringList();

        const bool isTemporary = section.value("isTemporary").toBool();
        const bool isCMake = section.value("isCMake").toBool();

        for (const QString &s : sources) {
            const FileName sfn = FileName::fromString(QDir::cleanPath(srcDir.absoluteFilePath(s)));
            const int oldCount = m_cmakeFiles.count();
            m_cmakeFiles.insert(sfn);
            if (oldCount < m_cmakeFiles.count() && (!isCMake || sfn.toString().endsWith("/CMakeLists.txt"))) {
                // Always include CMakeLists.txt files, even when cmake things these are part of its
                // stuff. This unbreaks cmake binaries running from their own build directory.
                m_cmakeInputsFileNodes.append(new FileNode(sfn, FileType::Project, isTemporary));
            }
        }
    }
}

void ServerModeReader::extractCacheData(const QVariantMap &data)
{
    CMakeConfig config;
    const QVariantList entries = data.value("cache").toList();
    for (const QVariant &e : entries) {
        const QVariantMap eData = e.toMap();
        CMakeConfigItem item;
        item.key = eData.value("key").toByteArray();
        item.value = eData.value("value").toByteArray();
        item.type = CMakeConfigItem::typeStringToType(eData.value("type").toByteArray());
        const QVariantMap properties = eData.value("properties").toMap();
        item.isAdvanced = properties.value("ADVANCED", false).toBool();
        item.documentation = properties.value("HELPSTRING").toByteArray();
        item.values = CMakeConfigItem::cmakeSplitValue(properties.value("STRINGS").toString(), true);
        config.append(item);
    }
    m_cmakeCache = config;
}

void ServerModeReader::fixTarget(ServerModeReader::Target *target) const
{
    QHash<QString, const FileGroup *> languageFallbacks;

    for (const FileGroup *group : Utils::asConst(target->fileGroups)) {
        if (group->includePaths.isEmpty() && group->compileFlags.isEmpty()
                && group->defines.isEmpty())
            continue;

        const FileGroup *fallback = languageFallbacks.value(group->language);
        if (!fallback || fallback->sources.count() < group->sources.count())
            languageFallbacks.insert(group->language, group);
    }

    if (!languageFallbacks.value(""))
        return; // No empty language groups found, no need to proceed.

    const FileGroup *fallback = languageFallbacks.value("CXX");
    if (!fallback)
        fallback = languageFallbacks.value("C");
    if (!fallback)
        fallback = languageFallbacks.value("");

    if (!fallback)
        return;

    for (auto it = target->fileGroups.begin(); it != target->fileGroups.end(); ++it) {
        if (!(*it)->language.isEmpty())
            continue;
        (*it)->language = fallback->language.isEmpty() ? "CXX" : fallback->language;

        if (*it == fallback
                || !(*it)->includePaths.isEmpty() || !(*it)->defines.isEmpty()
                || !(*it)->compileFlags.isEmpty())
            continue;

        for (const IncludePath *ip : fallback->includePaths)
            (*it)->includePaths.append(new IncludePath(*ip));
        (*it)->defines = fallback->defines;
        (*it)->compileFlags = fallback->compileFlags;
    }
}

QHash<Utils::FileName, ProjectNode *>
ServerModeReader::addCMakeLists(CMakeProjectNode *root, const QList<FileNode *> &cmakeLists)
{
    QHash<Utils::FileName, ProjectNode *> cmakeListsNodes;
    cmakeListsNodes.insert(root->filePath(), root);

    const QSet<Utils::FileName> cmakeDirs
            = Utils::transform<QSet>(cmakeLists, [](const Node *n) { return n->filePath().parentDir(); });
    root->addNestedNodes(cmakeLists, Utils::FileName(),
                         [&cmakeDirs, &cmakeListsNodes](const Utils::FileName &fp)
                         -> ProjectExplorer::FolderNode * {
        FolderNode *fn = nullptr;
        if (cmakeDirs.contains(fp)) {
            CMakeListsNode *n = new CMakeListsNode(fp);
            cmakeListsNodes.insert(fp, n);
            fn = n;
        } else {
            fn = new FolderNode(fp);
        }
        return fn;
    });
    root->compress();
    return cmakeListsNodes;
}

static ProjectNode *createProjectNode(const QHash<Utils::FileName, ProjectNode *> &cmakeListsNodes,
                                      const Utils::FileName &dir, const QString &displayName)
{
    ProjectNode *cmln = cmakeListsNodes.value(dir);
    QTC_ASSERT(cmln, qDebug() << dir.toUserOutput() ; return nullptr);

    Utils::FileName projectName = dir;
    projectName.appendPath(".project::" + displayName);

    CMakeProjectNode *pn = static_cast<CMakeProjectNode *>(cmln->projectNode(projectName));
    if (!pn) {
        pn = new CMakeProjectNode(projectName);
        cmln->addNode(pn);
    }
    pn->setDisplayName(displayName);
    return pn;
}

void ServerModeReader::addProjects(const QHash<Utils::FileName, ProjectNode *> &cmakeListsNodes,
                                   const QList<Project *> &projects,
                                   QList<FileNode *> &knownHeaderNodes)
{
    for (const Project *p : projects) {
        ProjectNode *pNode = createProjectNode(cmakeListsNodes, p->sourceDirectory, p->name);
        QTC_ASSERT(pNode, qDebug() << p->sourceDirectory.toUserOutput() ; continue);
        addTargets(cmakeListsNodes, p->targets, knownHeaderNodes);
    }
}

static CMakeTargetNode *createTargetNode(const QHash<Utils::FileName, ProjectNode *> &cmakeListsNodes,
                                         const Utils::FileName &dir, const QString &displayName)
{
    ProjectNode *cmln = cmakeListsNodes.value(dir);
    QTC_ASSERT(cmln, return nullptr);

    QByteArray targetId = CMakeTargetNode::generateId(dir, displayName);

    CMakeTargetNode *tn = static_cast<CMakeTargetNode *>(cmln->findNode([&targetId](const Node *n) {
        return n->id() == targetId;
    }));
    if (!tn) {
        tn = new CMakeTargetNode(dir, displayName);
        cmln->addNode(tn);
    }
    tn->setDisplayName(displayName);
    return tn;
}

void ServerModeReader::addTargets(const QHash<Utils::FileName, ProjectExplorer::ProjectNode *> &cmakeListsNodes,
                                  const QList<Target *> &targets,
                                  QList<ProjectExplorer::FileNode *> &knownHeaderNodes)
{
    for (const Target *t : targets) {
        CMakeTargetNode *tNode = createTargetNode(cmakeListsNodes, t->sourceDirectory, t->name);
        QTC_ASSERT(tNode, qDebug() << "No target node for" << t->sourceDirectory << t->name; continue);
        tNode->setTargetInformation(t->artifacts, t->type);
        addFileGroups(tNode, t->sourceDirectory, t->buildDirectory, t->fileGroups, knownHeaderNodes);
    }
}

void ServerModeReader::addFileGroups(ProjectNode *targetRoot,
                                     const Utils::FileName &sourceDirectory,
                                     const Utils::FileName &buildDirectory,
                                     const QList<ServerModeReader::FileGroup *> &fileGroups,
                                     QList<FileNode *> &knownHeaderNodes)
{
    QList<FileNode *> toList;
    QSet<Utils::FileName> alreadyListed;
    for (const FileGroup *f : fileGroups) {
        const QList<FileName> newSources = Utils::filtered(f->sources, [&alreadyListed](const Utils::FileName &fn) {
            const int count = alreadyListed.count();
            alreadyListed.insert(fn);
            return count != alreadyListed.count();
        });
        const QList<FileNode *> newFileNodes
                = Utils::transform(newSources, [f, &knownHeaderNodes](const Utils::FileName &fn) {
            auto node = new FileNode(fn, Node::fileTypeForFileName(fn), f->isGenerated);
            if (node->fileType() == FileType::Header)
                knownHeaderNodes.append(node);
            return node;
        });
        toList.append(newFileNodes);
    }

    // Split up files in groups (based on location):
    const bool inSourceBuild = (m_parameters.buildDirectory == m_parameters.sourceDirectory);
    QList<FileNode *> sourceFileNodes;
    QList<FileNode *> buildFileNodes;
    QList<FileNode *> otherFileNodes;
    foreach (FileNode *fn, toList) {
        if (fn->filePath().isChildOf(m_parameters.buildDirectory) && !inSourceBuild)
            buildFileNodes.append(fn);
        else if (fn->filePath().isChildOf(m_parameters.sourceDirectory))
            sourceFileNodes.append(fn);
        else
            otherFileNodes.append(fn);
    }

    addCMakeVFolder(targetRoot, sourceDirectory, 1000,  QString(), sourceFileNodes);
    addCMakeVFolder(targetRoot, buildDirectory, 100, tr("<Build Directory>"), buildFileNodes);
    addCMakeVFolder(targetRoot, Utils::FileName(), 10, tr("<Other Locations>"), otherFileNodes);
}

void ServerModeReader::addHeaderNodes(ProjectNode *root, const QList<FileNode *> knownHeaders,
                                      const QList<const FileNode *> &allFiles)
{
    if (root->isEmpty())
        return;

    auto headerNode = new VirtualFolderNode(root->filePath(), Node::DefaultPriority - 5);
    headerNode->setDisplayName(tr("<Headers>"));

    // knownHeaders are already listed in their targets:
    QSet<Utils::FileName> seenHeaders = Utils::transform<QSet>(knownHeaders, &FileNode::filePath);

    // Add scanned headers:
    for (const FileNode *fn : allFiles) {
        if (fn->fileType() != FileType::Header || !fn->filePath().isChildOf(root->filePath()))
            continue;
        const int count = seenHeaders.count();
        seenHeaders.insert(fn->filePath());
        if (seenHeaders.count() != count) {
            auto node = fn->clone();
            node->setEnabled(false);
            headerNode->addNestedNode(node);
        }
    }

    if (headerNode->nodes().isEmpty())
        delete headerNode; // No Headers, do not show this Folder.
    else
        root->addNode(headerNode);
}

} // namespace Internal
} // namespace CMakeProjectManager

#if defined(WITH_TESTS)

#include "cmakeprojectplugin.h"
#include <QTest>

namespace CMakeProjectManager {
namespace Internal {

void CMakeProjectPlugin::testServerModeReaderProgress_data()
{
    QTest::addColumn<int>("minRange");
    QTest::addColumn<int>("min");
    QTest::addColumn<int>("cur");
    QTest::addColumn<int>("max");
    QTest::addColumn<int>("maxRange");
    QTest::addColumn<int>("expected");

    QTest::newRow("empty range") << 100 << 10 << 11 << 20 << 100 << 100;
    QTest::newRow("one range (low)") << 0 << 10 << 11 << 20 << 1 << 0;
    QTest::newRow("one range (high)") << 20 << 10 << 19 << 20 << 20 << 20;
    QTest::newRow("large range") << 30 << 10 << 11 << 20 << 100000 << 30;

    QTest::newRow("empty progress") << -5 << 10 << 10 << 10 << 99995 << -5;
    QTest::newRow("one progress (low)") << 42 << 10 << 10 << 11 << 100042 << 42;
    QTest::newRow("one progress (high)") << 0 << 10 << 11 << 11 << 100000 << 100000;
    QTest::newRow("large progress") << 0 << 10 << 10 << 11 << 100000 << 0;

    QTest::newRow("cur too low") << 0 << 10 << 9 << 100 << 100000 << 0;
    QTest::newRow("cur too high") << 0 << 10 << 101 << 100 << 100000 << 100000;
    QTest::newRow("cur much too low") << 0 << 10 << -1000 << 100 << 100000 << 0;
    QTest::newRow("cur much too high") << 0 << 10 << 1110000 << 100 << 100000 << 100000;
}

void CMakeProjectPlugin::testServerModeReaderProgress()
{
    QFETCH(int, minRange);
    QFETCH(int, min);
    QFETCH(int, cur);
    QFETCH(int, max);
    QFETCH(int, maxRange);
    QFETCH(int, expected);

    ServerModeReader reader;
    const int r = reader.calculateProgress(minRange, min, cur, max, maxRange);

    QCOMPARE(r, expected);

    QVERIFY(r <= maxRange);
    QVERIFY(r >= minRange);
}

} // namespace Internal
} // namespace CMakeProjectManager

#endif