aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/nim/project/nimproject.cpp
blob: 7ef868d2b7e3c8e1af85fe18b11cda5b3ef9f37b (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
// Copyright (C) Filippo Cucchetto <filippocucchetto@gmail.com>
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "nimproject.h"

#include "../nimconstants.h"
#include "../nimtr.h"
#include "nimbleproject.h"
#include "nimcompilerbuildstep.h"

#include <coreplugin/icontext.h>

#include <projectexplorer/buildinfo.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectmanager.h>
#include <projectexplorer/target.h>
#include <projectexplorer/toolchain.h>
#include <projectexplorer/toolchainkitaspect.h>

using namespace ProjectExplorer;
using namespace Utils;

namespace Nim {

const char SETTINGS_KEY[] = "Nim.BuildSystem";
const char EXCLUDED_FILES_KEY[] = "ExcludedFiles";

NimProjectScanner::NimProjectScanner(Project *project)
    : m_project(project)
{
    connect(&m_directoryWatcher, &FileSystemWatcher::directoryChanged,
            this, &NimProjectScanner::directoryChanged);
    connect(&m_directoryWatcher, &FileSystemWatcher::fileChanged,
            this, &NimProjectScanner::fileChanged);

    connect(m_project, &Project::settingsLoaded, this, &NimProjectScanner::loadSettings);
    connect(m_project, &Project::aboutToSaveSettings, this, &NimProjectScanner::saveSettings);

    connect(&m_scanner, &TreeScanner::finished, this, [this] {
        // Collect scanned nodes
        std::vector<std::unique_ptr<FileNode>> nodes;
        TreeScanner::Result scanResult = m_scanner.release();
        for (FileNode *node : scanResult.takeAllFiles()) {
            if (!node->path().endsWith(".nim") && !node->path().endsWith(".nimble"))
                node->setEnabled(false); // Disable files that do not end in .nim
            nodes.emplace_back(node);
        }

        // Sync watched dirs
        const QSet<FilePath> fsDirs = Utils::transform<QSet>(nodes,
                                                             [](const std::unique_ptr<FileNode> &fn) { return fn->directory(); });
        const QSet<FilePath> projectDirs = Utils::toSet(m_directoryWatcher.directories());
        m_directoryWatcher.addDirectories(Utils::toList(fsDirs - projectDirs), FileSystemWatcher::WatchAllChanges);
        m_directoryWatcher.removeDirectories(Utils::toList(projectDirs - fsDirs));

        // Sync project files
        const QSet<FilePath> fsFiles = Utils::transform<QSet>(nodes, &FileNode::filePath);
        const QSet<FilePath> projectFiles = Utils::toSet(m_project->files([](const Node *n) { return Project::AllFiles(n); }));

        if (fsFiles != projectFiles) {
            auto projectNode = std::make_unique<ProjectNode>(m_project->projectDirectory());
            projectNode->setDisplayName(m_project->displayName());
            projectNode->addNestedNodes(std::move(nodes));
            m_project->setRootProjectNode(std::move(projectNode));
        }

        emit finished();
    });
}

void NimProjectScanner::loadSettings()
{
    QVariantMap settings = m_project->namedSettings(SETTINGS_KEY).toMap();
    if (settings.contains(EXCLUDED_FILES_KEY))
        setExcludedFiles(FilePaths::fromSettings(settings.value(EXCLUDED_FILES_KEY, excludedFiles().toSettings())));

    emit requestReparse();
}

void NimProjectScanner::saveSettings()
{
    QVariantMap settings;
    settings.insert(EXCLUDED_FILES_KEY, excludedFiles().toSettings());
    m_project->setNamedSettings(SETTINGS_KEY, settings);
}

void NimProjectScanner::startScan()
{
    m_scanner.setFilter(
        [excludedFiles = excludedFiles()](const MimeType &, const FilePath &fp) {
            return excludedFiles.contains(fp) || fp.endsWith(".nimproject")
                   || fp.contains(".nimproject.user") || fp.contains(".nimble.user");
        });

    m_scanner.asyncScanForFiles(m_project->projectDirectory());
}

void NimProjectScanner::watchProjectFilePath()
{
    m_directoryWatcher.addFile(m_project->projectFilePath(), FileSystemWatcher::WatchModifiedDate);
}

void NimProjectScanner::setExcludedFiles(const FilePaths &list)
{
    static_cast<NimbleProject *>(m_project)->setExcludedFiles(list);
}

FilePaths NimProjectScanner::excludedFiles() const
{
    return static_cast<NimbleProject *>(m_project)->excludedFiles();
}

bool NimProjectScanner::addFiles(const FilePaths &filePaths)
{
    setExcludedFiles(Utils::filtered(excludedFiles(), [&](const FilePath & f) {
        return !filePaths.contains(f);
    }));

    emit requestReparse();

    return true;
}

RemovedFilesFromProject NimProjectScanner::removeFiles(const FilePaths &filePaths)
{
    setExcludedFiles(Utils::filteredUnique(excludedFiles() + filePaths));

    emit requestReparse();

    return RemovedFilesFromProject::Ok;
}

bool NimProjectScanner::renameFile(const FilePath &, const FilePath &to)
{
    FilePaths files = excludedFiles();
    files.removeOne(to);
    setExcludedFiles(files);

    emit requestReparse();

    return true;
}

// NimBuildSystem

class NimBuildSystem final : public BuildSystem
{
public:
    explicit NimBuildSystem(BuildConfiguration *bc);
    ~NimBuildSystem();

    bool supportsAction(Node *, ProjectAction action, const Node *node) const final;
    bool addFiles(Node *node, const FilePaths &filePaths, FilePaths *) final;
    RemovedFilesFromProject removeFiles(Node *node,
                                        const FilePaths &filePaths,
                                        FilePaths *) final;
    bool deleteFiles(Node *, const FilePaths &) final;
    bool renameFiles(
        Node *,
        const Utils::FilePairs &filesToRename,
        Utils::FilePaths *notRenamed) final;
    void triggerParsing() final;

protected:
    ParseGuard m_guard;
    NimProjectScanner m_projectScanner;
};

NimBuildSystem::NimBuildSystem(BuildConfiguration *bc)
    : BuildSystem(bc), m_projectScanner(bc->project())
{
    connect(&m_projectScanner, &NimProjectScanner::finished, this, [this] {
        m_guard.markAsSuccess();
        m_guard = {}; // Trigger destructor of previous object, emitting parsingFinished()

        emitBuildSystemUpdated();
    });

    connect(&m_projectScanner, &NimProjectScanner::requestReparse,
            this, &NimBuildSystem::requestDelayedParse);

    connect(&m_projectScanner, &NimProjectScanner::directoryChanged, this, [this] {
        if (!isWaitingForParse())
            requestDelayedParse();
    });

    requestDelayedParse();
}

NimBuildSystem::~NimBuildSystem()
{
    // Trigger any pending parsingFinished signals before destroying any other build system part:
    m_guard = {};
}

void NimBuildSystem::triggerParsing()
{
    m_guard = guardParsingRun();
    m_projectScanner.startScan();
}

FilePath nimPathFromKit(Kit *kit)
{
    auto tc = ToolchainKitAspect::toolchain(kit, Constants::C_NIMLANGUAGE_ID);
    QTC_ASSERT(tc, return {});
    const FilePath command = tc->compilerCommand();
    return command.isEmpty() ? FilePath() : command.absolutePath();
}

FilePath nimblePathFromKit(Kit *kit)
{
    // There's no extra setting for "nimble", derive it from the "nim" path.
    const FilePath nimbleFromPath = FilePath("nimble").searchInPath();
    const FilePath nimPath = nimPathFromKit(kit);
    const FilePath nimbleFromKit = nimPath.pathAppended("nimble").withExecutableSuffix();
    return nimbleFromKit.exists() ? nimbleFromKit.canonicalPath() : nimbleFromPath;
}

bool NimBuildSystem::supportsAction(Node *context, ProjectAction action, const Node *node) const
{
    if (node->asFileNode()) {
        return action == ProjectAction::Rename
               || action == ProjectAction::RemoveFile;
    }
    if (node->isFolderNodeType() || node->isProjectNodeType()) {
        return action == ProjectAction::AddNewFile
               || action == ProjectAction::RemoveFile
               || action == ProjectAction::AddExistingFile;
    }
    return BuildSystem::supportsAction(context, action, node);
}

bool NimBuildSystem::addFiles(Node *, const FilePaths &filePaths, FilePaths *)
{
    return m_projectScanner.addFiles(filePaths);
}

RemovedFilesFromProject NimBuildSystem::removeFiles(Node *,
                                                    const FilePaths &filePaths,
                                                    FilePaths *)
{
    return m_projectScanner.removeFiles(filePaths);
}

bool NimBuildSystem::deleteFiles(Node *, const FilePaths &)
{
    return true;
}

bool NimBuildSystem::renameFiles(Node *, const FilePairs &filesToRename, FilePaths *notRenamed)
{
    bool success = true;
    for (const auto &[oldFilePath, newFilePath] : filesToRename) {
        if (!m_projectScanner.renameFile(oldFilePath, newFilePath)) {
            success = false;
            if (notRenamed)
                *notRenamed << oldFilePath;
        }
    }
    return success;
}

static FilePath defaultBuildDirectory(const Kit *k,
                                      const FilePath &projectFilePath,
                                      const QString &bc,
                                      BuildConfiguration::BuildType buildType)
{
    return BuildConfiguration::buildDirectoryFromTemplate(
        projectFilePath.parentDir(), projectFilePath, projectFilePath.baseName(),
        k, bc, buildType, "nim");
}

NimBuildConfiguration::NimBuildConfiguration(Target *target, Utils::Id id)
    : BuildConfiguration(target, id)
{
    setConfigWidgetDisplayName(Tr::tr("General"));
    setConfigWidgetHasFrame(true);
    setBuildDirectorySettingsKey("Nim.NimBuildConfiguration.BuildDirectory");

    appendInitialBuildStep(Constants::C_NIMCOMPILERBUILDSTEP_ID);
    appendInitialCleanStep(Constants::C_NIMCOMPILERCLEANSTEP_ID);

    setInitializer([this](const BuildInfo &info) {
        // Create the build configuration and initialize it from build info
        setBuildDirectory(defaultBuildDirectory(kit(),
                                                project()->projectFilePath(),
                                                displayName(),
                                                buildType()));

        auto nimCompilerBuildStep = buildSteps()->firstOfType<NimCompilerBuildStep>();
        QTC_ASSERT(nimCompilerBuildStep, return);
        nimCompilerBuildStep->setBuildType(info.buildType);
    });
}

FilePath NimBuildConfiguration::cacheDirectory() const
{
    return buildDirectory().pathAppended("nimcache");
}

FilePath NimBuildConfiguration::outFilePath() const
{
    auto nimCompilerBuildStep = buildSteps()->firstOfType<NimCompilerBuildStep>();
    QTC_ASSERT(nimCompilerBuildStep, return {});
    return nimCompilerBuildStep->outFilePath();
}

// NimBuildConfigurationFactory

class NimBuildConfigurationFactory final : public ProjectExplorer::BuildConfigurationFactory
{
public:
    NimBuildConfigurationFactory()
    {
        registerBuildConfiguration<NimBuildConfiguration>(Constants::C_NIMBUILDCONFIGURATION_ID);
        setSupportedProjectType(Constants::C_NIMPROJECT_ID);
        setSupportedProjectMimeTypeName(Constants::C_NIM_PROJECT_MIMETYPE);

        setBuildGenerator([](const Kit *k, const FilePath &projectPath, bool forSetup) {
            const auto oneBuild = [&](BuildConfiguration::BuildType buildType, const QString &typeName) {
                BuildInfo info;
                info.buildType = buildType;
                info.typeName = typeName;
                if (forSetup) {
                    info.displayName = info.typeName;
                    info.buildDirectory = defaultBuildDirectory(k, projectPath, info.typeName, buildType);
                }
                info.enabledByDefault = buildType == BuildConfiguration::Debug;
                return info;
            };
            return QList<BuildInfo>{
                oneBuild(BuildConfiguration::Debug, Tr::tr("Debug")),
                oneBuild(BuildConfiguration::Release, Tr::tr("Release"))
            };
        });
    }
};


class NimProject final : public Project
{
public:
    explicit NimProject(const FilePath &filePath);

    // Keep for compatibility with Qt Creator 4.10
    void toMap(Store &map) const final;

protected:
    // Keep for compatibility with Qt Creator 4.10
    RestoreResult fromMap(const Store &map, QString *errorMessage) final;

    QStringList m_excludedFiles;
};

NimProject::NimProject(const FilePath &filePath) : Project(Constants::C_NIM_MIMETYPE, filePath)
{
    setType(Constants::C_NIMPROJECT_ID);
    setDisplayName(filePath.completeBaseName());
    // ensure debugging is enabled (Nim plugin translates nim code to C code)
    setProjectLanguages(Core::Context(ProjectExplorer::Constants::CXX_LANGUAGE_ID));
    setBuildSystemCreator<NimBuildSystem>("nim");
}

void NimProject::toMap(Store &map) const
{
    Project::toMap(map);
    map[Constants::C_NIMPROJECT_EXCLUDEDFILES] = m_excludedFiles;
}

Project::RestoreResult NimProject::fromMap(const Store &map, QString *errorMessage)
{
    auto result = Project::fromMap(map, errorMessage);
    m_excludedFiles = map.value(Constants::C_NIMPROJECT_EXCLUDEDFILES).toStringList();
    return result;
}

// Setup

void setupNimProject()
{
    static const NimBuildConfigurationFactory buildConfigFactory;
    const auto issuesGenerator = [](const Kit *k) {
        Tasks result;
        auto tc = ToolchainKitAspect::toolchain(k, Constants::C_NIMLANGUAGE_ID);
        if (!tc) {
            result.append(
                Project::createTask(Task::TaskType::Error, Tr::tr("No Nim compiler set.")));
            return result;
        }
        if (!tc->compilerCommand().exists())
            result.append(
                Project::createTask(Task::TaskType::Error, Tr::tr("Nim compiler does not exist.")));
        return result;
    };
    ProjectManager::registerProjectType<NimProject>(
        Constants::C_NIM_PROJECT_MIMETYPE, issuesGenerator);
}

} // Nim