Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/gdscript/language_server/gdscript_language_protocol.cpp
10278 views
1
/**************************************************************************/
2
/* gdscript_language_protocol.cpp */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10
/* */
11
/* Permission is hereby granted, free of charge, to any person obtaining */
12
/* a copy of this software and associated documentation files (the */
13
/* "Software"), to deal in the Software without restriction, including */
14
/* without limitation the rights to use, copy, modify, merge, publish, */
15
/* distribute, sublicense, and/or sell copies of the Software, and to */
16
/* permit persons to whom the Software is furnished to do so, subject to */
17
/* the following conditions: */
18
/* */
19
/* The above copyright notice and this permission notice shall be */
20
/* included in all copies or substantial portions of the Software. */
21
/* */
22
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29
/**************************************************************************/
30
31
#include "gdscript_language_protocol.h"
32
33
#include "core/config/project_settings.h"
34
#include "editor/doc/doc_tools.h"
35
#include "editor/doc/editor_help.h"
36
#include "editor/editor_log.h"
37
#include "editor/editor_node.h"
38
#include "editor/settings/editor_settings.h"
39
40
GDScriptLanguageProtocol *GDScriptLanguageProtocol::singleton = nullptr;
41
42
Error GDScriptLanguageProtocol::LSPeer::handle_data() {
43
int read = 0;
44
// Read headers
45
if (!has_header) {
46
while (true) {
47
if (req_pos >= LSP_MAX_BUFFER_SIZE) {
48
req_pos = 0;
49
ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Response header too big");
50
}
51
Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
52
if (err != OK) {
53
return FAILED;
54
} else if (read != 1) { // Busy, wait until next poll
55
return ERR_BUSY;
56
}
57
char *r = (char *)req_buf;
58
int l = req_pos;
59
60
// End of headers
61
if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
62
r[l - 3] = '\0'; // Null terminate to read string
63
String header = String::utf8(r);
64
content_length = header.substr(16).to_int();
65
has_header = true;
66
req_pos = 0;
67
break;
68
}
69
req_pos++;
70
}
71
}
72
if (has_header) {
73
while (req_pos < content_length) {
74
if (req_pos >= LSP_MAX_BUFFER_SIZE) {
75
req_pos = 0;
76
has_header = false;
77
ERR_FAIL_COND_V_MSG(req_pos >= LSP_MAX_BUFFER_SIZE, ERR_OUT_OF_MEMORY, "Response content too big");
78
}
79
Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
80
if (err != OK) {
81
return FAILED;
82
} else if (read != 1) {
83
return ERR_BUSY;
84
}
85
req_pos++;
86
}
87
88
// Parse data
89
String msg = String::utf8((const char *)req_buf, req_pos);
90
91
// Reset to read again
92
req_pos = 0;
93
has_header = false;
94
95
// Response
96
String output = GDScriptLanguageProtocol::get_singleton()->process_message(msg);
97
if (!output.is_empty()) {
98
res_queue.push_back(output.utf8());
99
}
100
}
101
return OK;
102
}
103
104
Error GDScriptLanguageProtocol::LSPeer::send_data() {
105
int sent = 0;
106
while (!res_queue.is_empty()) {
107
CharString c_res = res_queue[0];
108
if (res_sent < c_res.size()) {
109
Error err = connection->put_partial_data((const uint8_t *)c_res.get_data() + res_sent, c_res.size() - res_sent - 1, sent);
110
if (err != OK) {
111
return err;
112
}
113
res_sent += sent;
114
}
115
// Response sent
116
if (res_sent >= c_res.size() - 1) {
117
res_sent = 0;
118
res_queue.remove_at(0);
119
}
120
}
121
return OK;
122
}
123
124
Error GDScriptLanguageProtocol::on_client_connected() {
125
Ref<StreamPeerTCP> tcp_peer = server->take_connection();
126
ERR_FAIL_COND_V_MSG(clients.size() >= LSP_MAX_CLIENTS, FAILED, "Max client limits reached");
127
Ref<LSPeer> peer = memnew(LSPeer);
128
peer->connection = tcp_peer;
129
clients.insert(next_client_id, peer);
130
next_client_id++;
131
EditorNode::get_log()->add_message("[LSP] Connection Taken", EditorLog::MSG_TYPE_EDITOR);
132
return OK;
133
}
134
135
void GDScriptLanguageProtocol::on_client_disconnected(const int &p_client_id) {
136
clients.erase(p_client_id);
137
EditorNode::get_log()->add_message("[LSP] Disconnected", EditorLog::MSG_TYPE_EDITOR);
138
}
139
140
String GDScriptLanguageProtocol::process_message(const String &p_text) {
141
String ret = process_string(p_text);
142
if (ret.is_empty()) {
143
return ret;
144
} else {
145
return format_output(ret);
146
}
147
}
148
149
String GDScriptLanguageProtocol::format_output(const String &p_text) {
150
String header = "Content-Length: ";
151
CharString charstr = p_text.utf8();
152
size_t len = charstr.length();
153
header += itos(len);
154
header += "\r\n\r\n";
155
156
return header + p_text;
157
}
158
159
void GDScriptLanguageProtocol::_bind_methods() {
160
ClassDB::bind_method(D_METHOD("initialize", "params"), &GDScriptLanguageProtocol::initialize);
161
ClassDB::bind_method(D_METHOD("initialized", "params"), &GDScriptLanguageProtocol::initialized);
162
ClassDB::bind_method(D_METHOD("on_client_connected"), &GDScriptLanguageProtocol::on_client_connected);
163
ClassDB::bind_method(D_METHOD("on_client_disconnected"), &GDScriptLanguageProtocol::on_client_disconnected);
164
ClassDB::bind_method(D_METHOD("notify_client", "method", "params", "client_id"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));
165
ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled);
166
ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document);
167
ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace);
168
ClassDB::bind_method(D_METHOD("is_initialized"), &GDScriptLanguageProtocol::is_initialized);
169
}
170
171
Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
172
LSP::InitializeResult ret;
173
174
{
175
// Warn if the workspace root does not match with the project that is currently open in Godot,
176
// since it might lead to unexpected behavior, like wrong warnings about duplicate class names.
177
178
String root;
179
Variant root_uri_var = p_params["rootUri"];
180
Variant root_var = p_params["rootPath"];
181
if (root_uri_var.is_string()) {
182
root = get_workspace()->get_file_path(root_uri_var);
183
} else if (root_var.is_string()) {
184
root = root_var;
185
}
186
187
if (ProjectSettings::get_singleton()->localize_path(root) != "res://") {
188
LSP::ShowMessageParams params{
189
LSP::MessageType::Warning,
190
"The GDScript Language Server might not work correctly with other projects than the one opened in Godot."
191
};
192
notify_client("window/showMessage", params.to_json());
193
}
194
}
195
196
String root_uri = p_params["rootUri"];
197
String root = p_params["rootPath"];
198
bool is_same_workspace;
199
#ifndef WINDOWS_ENABLED
200
is_same_workspace = root.to_lower() == workspace->root.to_lower();
201
#else
202
is_same_workspace = root.replace_char('\\', '/').to_lower() == workspace->root.to_lower();
203
#endif
204
205
if (root_uri.length() && is_same_workspace) {
206
workspace->root_uri = root_uri;
207
} else {
208
String r_root = workspace->root;
209
r_root = r_root.lstrip("/");
210
workspace->root_uri = "file:///" + r_root;
211
212
Dictionary params;
213
params["path"] = workspace->root;
214
Dictionary request = make_notification("gdscript_client/changeWorkspace", params);
215
216
ERR_FAIL_COND_V_MSG(!clients.has(latest_client_id), ret.to_json(),
217
vformat("GDScriptLanguageProtocol: Can't initialize invalid peer '%d'.", latest_client_id));
218
Ref<LSPeer> peer = clients.get(latest_client_id);
219
if (peer.is_valid()) {
220
String msg = Variant(request).to_json_string();
221
msg = format_output(msg);
222
(*peer)->res_queue.push_back(msg.utf8());
223
}
224
}
225
226
if (!_initialized) {
227
workspace->initialize();
228
text_document->initialize();
229
_initialized = true;
230
}
231
232
return ret.to_json();
233
}
234
235
void GDScriptLanguageProtocol::initialized(const Variant &p_params) {
236
LSP::GodotCapabilities capabilities;
237
238
DocTools *doc = EditorHelp::get_doc_data();
239
for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {
240
LSP::GodotNativeClassInfo gdclass;
241
gdclass.name = E.value.name;
242
gdclass.class_doc = &(E.value);
243
if (ClassDB::ClassInfo *ptr = ClassDB::classes.getptr(StringName(E.value.name))) {
244
gdclass.class_info = ptr;
245
}
246
capabilities.native_classes.push_back(gdclass);
247
}
248
249
notify_client("gdscript/capabilities", capabilities.to_json());
250
}
251
252
void GDScriptLanguageProtocol::poll(int p_limit_usec) {
253
uint64_t target_ticks = OS::get_singleton()->get_ticks_usec() + p_limit_usec;
254
255
if (server->is_connection_available()) {
256
on_client_connected();
257
}
258
259
HashMap<int, Ref<LSPeer>>::Iterator E = clients.begin();
260
while (E != clients.end()) {
261
Ref<LSPeer> peer = E->value;
262
peer->connection->poll();
263
StreamPeerTCP::Status status = peer->connection->get_status();
264
if (status == StreamPeerTCP::STATUS_NONE || status == StreamPeerTCP::STATUS_ERROR) {
265
on_client_disconnected(E->key);
266
E = clients.begin();
267
continue;
268
} else {
269
Error err = OK;
270
while (peer->connection->get_available_bytes() > 0) {
271
latest_client_id = E->key;
272
err = peer->handle_data();
273
if (err != OK || OS::get_singleton()->get_ticks_usec() >= target_ticks) {
274
break;
275
}
276
}
277
278
if (err != OK && err != ERR_BUSY) {
279
on_client_disconnected(E->key);
280
E = clients.begin();
281
continue;
282
}
283
284
err = peer->send_data();
285
if (err != OK && err != ERR_BUSY) {
286
on_client_disconnected(E->key);
287
E = clients.begin();
288
continue;
289
}
290
}
291
++E;
292
}
293
}
294
295
Error GDScriptLanguageProtocol::start(int p_port, const IPAddress &p_bind_ip) {
296
return server->listen(p_port, p_bind_ip);
297
}
298
299
void GDScriptLanguageProtocol::stop() {
300
for (const KeyValue<int, Ref<LSPeer>> &E : clients) {
301
Ref<LSPeer> peer = clients.get(E.key);
302
peer->connection->disconnect_from_host();
303
}
304
305
server->stop();
306
}
307
308
void GDScriptLanguageProtocol::notify_client(const String &p_method, const Variant &p_params, int p_client_id) {
309
#ifdef TESTS_ENABLED
310
if (clients.is_empty()) {
311
return;
312
}
313
#endif
314
if (p_client_id == -1) {
315
ERR_FAIL_COND_MSG(latest_client_id == -1,
316
"GDScript LSP: Can't notify client as none was connected.");
317
p_client_id = latest_client_id;
318
}
319
ERR_FAIL_COND(!clients.has(p_client_id));
320
Ref<LSPeer> peer = clients.get(p_client_id);
321
ERR_FAIL_COND(peer.is_null());
322
323
Dictionary message = make_notification(p_method, p_params);
324
String msg = Variant(message).to_json_string();
325
msg = format_output(msg);
326
peer->res_queue.push_back(msg.utf8());
327
}
328
329
void GDScriptLanguageProtocol::request_client(const String &p_method, const Variant &p_params, int p_client_id) {
330
#ifdef TESTS_ENABLED
331
if (clients.is_empty()) {
332
return;
333
}
334
#endif
335
if (p_client_id == -1) {
336
ERR_FAIL_COND_MSG(latest_client_id == -1,
337
"GDScript LSP: Can't notify client as none was connected.");
338
p_client_id = latest_client_id;
339
}
340
ERR_FAIL_COND(!clients.has(p_client_id));
341
Ref<LSPeer> peer = clients.get(p_client_id);
342
ERR_FAIL_COND(peer.is_null());
343
344
Dictionary message = make_request(p_method, p_params, next_server_id);
345
next_server_id++;
346
String msg = Variant(message).to_json_string();
347
msg = format_output(msg);
348
peer->res_queue.push_back(msg.utf8());
349
}
350
351
bool GDScriptLanguageProtocol::is_smart_resolve_enabled() const {
352
return bool(_EDITOR_GET("network/language_server/enable_smart_resolve"));
353
}
354
355
bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const {
356
return bool(_EDITOR_GET("network/language_server/show_native_symbols_in_editor"));
357
}
358
359
// clang-format off
360
#define SET_DOCUMENT_METHOD(m_method) set_method(_STR(textDocument/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))
361
#define SET_COMPLETION_METHOD(m_method) set_method(_STR(completionItem/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))
362
#define SET_WORKSPACE_METHOD(m_method) set_method(_STR(workspace/m_method), callable_mp(workspace.ptr(), &GDScriptWorkspace::m_method))
363
// clang-format on
364
365
GDScriptLanguageProtocol::GDScriptLanguageProtocol() {
366
server.instantiate();
367
singleton = this;
368
workspace.instantiate();
369
text_document.instantiate();
370
371
SET_DOCUMENT_METHOD(didOpen);
372
SET_DOCUMENT_METHOD(didClose);
373
SET_DOCUMENT_METHOD(didChange);
374
SET_DOCUMENT_METHOD(willSaveWaitUntil);
375
SET_DOCUMENT_METHOD(didSave);
376
377
SET_DOCUMENT_METHOD(documentSymbol);
378
SET_DOCUMENT_METHOD(completion);
379
SET_DOCUMENT_METHOD(rename);
380
SET_DOCUMENT_METHOD(prepareRename);
381
SET_DOCUMENT_METHOD(references);
382
SET_DOCUMENT_METHOD(foldingRange);
383
SET_DOCUMENT_METHOD(codeLens);
384
SET_DOCUMENT_METHOD(documentLink);
385
SET_DOCUMENT_METHOD(colorPresentation);
386
SET_DOCUMENT_METHOD(hover);
387
SET_DOCUMENT_METHOD(definition);
388
SET_DOCUMENT_METHOD(declaration);
389
SET_DOCUMENT_METHOD(signatureHelp);
390
391
SET_DOCUMENT_METHOD(nativeSymbol); // Custom method.
392
393
SET_COMPLETION_METHOD(resolve);
394
395
SET_WORKSPACE_METHOD(didDeleteFiles);
396
397
set_method("initialize", callable_mp(this, &GDScriptLanguageProtocol::initialize));
398
set_method("initialized", callable_mp(this, &GDScriptLanguageProtocol::initialized));
399
400
workspace->root = ProjectSettings::get_singleton()->get_resource_path();
401
}
402
403
#undef SET_DOCUMENT_METHOD
404
#undef SET_COMPLETION_METHOD
405
#undef SET_WORKSPACE_METHOD
406
407