File: cmakeserver.cpp

package info (click to toggle)
kdevelop 4%3A5.6.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 57,892 kB
  • sloc: cpp: 278,773; javascript: 3,558; python: 3,385; sh: 1,317; ansic: 689; xml: 273; php: 95; makefile: 40; lisp: 13; sed: 12
file content (227 lines) | stat: -rw-r--r-- 8,542 bytes parent folder | download
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
/* KDevelop CMake Support
 *
 * Copyright 2017 Aleix Pol <aleixpol@kde.org>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#include "cmakeserver.h"
#include "cmakeprojectdata.h"
#include "cmakeutils.h"

#include <interfaces/iruntime.h>
#include <interfaces/iruntimecontroller.h>
#include <interfaces/icore.h>
#include <interfaces/iproject.h>

#include <QDir>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QTimer>
#include <QTemporaryFile>
#include "debug.h"

CMakeServer::CMakeServer(KDevelop::IProject* project)
    : QObject()
    , m_localSocket(new QLocalSocket(this))
{
    QString path;
    {
        const auto cacheLocation = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
        QDir::temp().mkpath(cacheLocation);

        QTemporaryFile file(cacheLocation + QLatin1String("/kdevelopcmake"));
        file.open();
        file.close();
        path = file.fileName();
        Q_ASSERT(!path.isEmpty());
    }

    m_process.setProcessChannelMode(QProcess::ForwardedChannels);

    connect(&m_process, &QProcess::errorOccurred,
            this, [this, path](QProcess::ProcessError error) {
        qCWarning(CMAKE) << "cmake server error:" << error << path << m_process.readAllStandardError() << m_process.readAllStandardOutput();
    });
    connect(&m_process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, [](int code){
        qCDebug(CMAKE) << "cmake server finished with code" << code;
    });
    connect(&m_process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &CMakeServer::finished);

    connect(m_localSocket, &QIODevice::readyRead, this, &CMakeServer::processOutput);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
    connect(m_localSocket, &QLocalSocket::errorOccurred,
#else
    connect(m_localSocket, QOverload<QLocalSocket::LocalSocketError>::of(&QLocalSocket::error),
#endif
            this, [this, path](QLocalSocket::LocalSocketError socketError) {
        qCWarning(CMAKE) << "cmake server socket error:" << socketError << path;
        setConnected(false);
    });
    connect(m_localSocket, &QLocalSocket::connected, this, [this]() { setConnected(true); });

    connect(&m_process, &QProcess::started, this, [this, path](){
        //Once the process has started, wait for the file to be created, then connect to it
        QTimer::singleShot(1000, this, [this, path]() {
            m_localSocket->connectToServer(path, QIODevice::ReadWrite);
        });
    });
    // we're called with the importing project as our parent, so we can fetch configured
    // cmake executable (project-specific or kdevelop-wide) rather than the system version.
    m_process.setProgram(CMake::currentCMakeExecutable(project).toLocalFile());
    m_process.setArguments({QStringLiteral("-E"), QStringLiteral("server"), QStringLiteral("--experimental"), QLatin1String("--pipe=") + path});
    KDevelop::ICore::self()->runtimeController()->currentRuntime()->startProcess(&m_process);
}

CMakeServer::~CMakeServer()
{
    m_process.disconnect();
    m_process.kill();
    m_process.waitForFinished();
}

void CMakeServer::setConnected(bool conn)
{
    if (conn == m_connected)
        return;

    m_connected = conn;
    if (m_connected)
        Q_EMIT connected();
    else
        Q_EMIT disconnected();
}

bool CMakeServer::isServerAvailable()
{
    return m_localSocket->isOpen();
}

static QByteArray openTag() { return QByteArrayLiteral("\n[== \"CMake Server\" ==[\n"); }
static QByteArray closeTag() { return QByteArrayLiteral("\n]== \"CMake Server\" ==]\n"); }

void CMakeServer::sendCommand(const QJsonObject& object)
{
    Q_ASSERT(isServerAvailable());

    const QByteArray data = openTag() + QJsonDocument(object).toJson(QJsonDocument::Compact) + closeTag();
    auto len = m_localSocket->write(data);
//     qCDebug(CMAKE) << "writing...\n" << QJsonDocument(object).toJson();
    Q_ASSERT(len > 0);
}

void CMakeServer::processOutput()
{
    Q_ASSERT(m_localSocket);

    const auto openTag = ::openTag();
    const auto closeTag = ::closeTag();

    m_buffer += m_localSocket->readAll();
    for(; m_buffer.size() > openTag.size(); ) {

        Q_ASSERT(m_buffer.startsWith(openTag));
        const int idx = m_buffer.indexOf(closeTag, openTag.size());
        if (idx >= 0) {
            emitResponse(m_buffer.mid(openTag.size(), idx - openTag.size()));
            m_buffer.remove(0, idx + closeTag.size());
        } else {
            break;
        }
    }
}

void CMakeServer::emitResponse(const QByteArray& data)
{
    QJsonParseError error;
    auto doc = QJsonDocument::fromJson(data, &error);
    if (error.error) {
        qCWarning(CMAKE) << "error processing" << error.errorString() << data;
    }
    Q_ASSERT(doc.isObject());
    Q_EMIT response(doc.object());
}

void CMakeServer::handshake(const KDevelop::Path& source, const KDevelop::Path& build)
{
    Q_ASSERT(!source.isEmpty());

    const QString generatorVariable = QStringLiteral("CMAKE_GENERATOR");
    const QString homeDirectoryVariable = QStringLiteral("CMAKE_HOME_DIRECTORY");
    const QString cacheFileDirectoryVariable = QStringLiteral("CMAKE_CACHEFILE_DIR");
    const auto cacheValues = CMake::readCacheValues(KDevelop::Path(build, QStringLiteral("CMakeCache.txt")),
                                                    {generatorVariable, homeDirectoryVariable, cacheFileDirectoryVariable});

    QString generator = cacheValues.value(generatorVariable);
    if (generator.isEmpty()) {
        generator = CMake::defaultGenerator();
    }

    // prefer pre-existing source directory, see also: https://gitlab.kitware.com/cmake/cmake/issues/16736
    QString sourceDirectory = cacheValues.value(homeDirectoryVariable);
    if (sourceDirectory.isEmpty()) {
        sourceDirectory = source.toLocalFile();
    } else if (QFileInfo(sourceDirectory).canonicalFilePath() != QFileInfo(source.toLocalFile()).canonicalFilePath()) {
        qCWarning(CMAKE) << "Build directory is configured for another source directory:"
                   << homeDirectoryVariable << sourceDirectory
                   << "wanted to open" << source << "in" << build;
    }

    // prefer to reuse the exact same build dir path to prevent useless recompilation
    // when we open a symlinked project path
    QString buildDirectory = cacheValues.value(cacheFileDirectoryVariable);
    if (buildDirectory.isEmpty()) {
        buildDirectory = build.toLocalFile();
    } else if (QFileInfo(buildDirectory).canonicalFilePath() != QFileInfo(build.toLocalFile()).canonicalFilePath()) {
        qCWarning(CMAKE) << "Build directory mismatch:"
                   << cacheFileDirectoryVariable << buildDirectory
                   << "wanted to open" << build;
        buildDirectory = build.toLocalFile();
    }

    qCDebug(CMAKE) << "Using generator" << generator << "for project"
                   << sourceDirectory << "aka" << source
                   << "in" << buildDirectory << "aka" << build;

    sendCommand({
        {QStringLiteral("cookie"), {}},
        {QStringLiteral("type"), QStringLiteral("handshake")},
        {QStringLiteral("major"), 1},
        {QStringLiteral("protocolVersion"), QJsonObject{{QStringLiteral("major"), 1}} },
        {QStringLiteral("sourceDirectory"), sourceDirectory},
        {QStringLiteral("buildDirectory"), buildDirectory},
        {QStringLiteral("generator"), generator}
    });
}

void CMakeServer::configure(const QStringList& args)
{
    sendCommand({
        {QStringLiteral("type"), QStringLiteral("configure")},
        {QStringLiteral("cacheArguments"), QJsonArray::fromStringList(args)}
    });
}

void CMakeServer::compute()
{
    sendCommand({ {QStringLiteral("type"), QStringLiteral("compute")} });
}

void CMakeServer::codemodel()
{
    sendCommand({ {QStringLiteral("type"), QStringLiteral("codemodel")} });
}