gdscript_language_protocol.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. #include "gdscript_language_protocol.h"
  31. #include "core/config/project_settings.h"
  32. #include "editor/doc_tools.h"
  33. #include "editor/editor_help.h"
  34. #include "editor/editor_log.h"
  35. #include "editor/editor_node.h"
  36. #include "editor/editor_settings.h"
  37. GDScriptLanguageProtocol *GDScriptLanguageProtocol::singleton = nullptr;
  38. Error GDScriptLanguageProtocol::LSPeer::handle_data() {
  39. int read = 0;
  40. // Read headers
  41. if (!has_header) {
  42. while (true) {
  43. if (req_pos >= LSP_MAX_BUFFER_SIZE) {
  44. req_pos = 0;
  45. ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Response header too big");
  46. }
  47. Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
  48. if (err != OK) {
  49. return FAILED;
  50. } else if (read != 1) { // Busy, wait until next poll
  51. return ERR_BUSY;
  52. }
  53. char *r = (char *)req_buf;
  54. int l = req_pos;
  55. // End of headers
  56. if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
  57. r[l - 3] = '\0'; // Null terminate to read string
  58. String header = String::utf8(r);
  59. content_length = header.substr(16).to_int();
  60. has_header = true;
  61. req_pos = 0;
  62. break;
  63. }
  64. req_pos++;
  65. }
  66. }
  67. if (has_header) {
  68. while (req_pos < content_length) {
  69. if (req_pos >= LSP_MAX_BUFFER_SIZE) {
  70. req_pos = 0;
  71. has_header = false;
  72. ERR_FAIL_COND_V_MSG(req_pos >= LSP_MAX_BUFFER_SIZE, ERR_OUT_OF_MEMORY, "Response content too big");
  73. }
  74. Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
  75. if (err != OK) {
  76. return FAILED;
  77. } else if (read != 1) {
  78. return ERR_BUSY;
  79. }
  80. req_pos++;
  81. }
  82. // Parse data
  83. String msg = String::utf8((const char *)req_buf, req_pos);
  84. // Reset to read again
  85. req_pos = 0;
  86. has_header = false;
  87. // Response
  88. String output = GDScriptLanguageProtocol::get_singleton()->process_message(msg);
  89. if (!output.is_empty()) {
  90. res_queue.push_back(output.utf8());
  91. }
  92. }
  93. return OK;
  94. }
  95. Error GDScriptLanguageProtocol::LSPeer::send_data() {
  96. int sent = 0;
  97. while (!res_queue.is_empty()) {
  98. CharString c_res = res_queue[0];
  99. if (res_sent < c_res.size()) {
  100. Error err = connection->put_partial_data((const uint8_t *)c_res.get_data() + res_sent, c_res.size() - res_sent - 1, sent);
  101. if (err != OK) {
  102. return err;
  103. }
  104. res_sent += sent;
  105. }
  106. // Response sent
  107. if (res_sent >= c_res.size() - 1) {
  108. res_sent = 0;
  109. res_queue.remove_at(0);
  110. }
  111. }
  112. return OK;
  113. }
  114. Error GDScriptLanguageProtocol::on_client_connected() {
  115. Ref<StreamPeerTCP> tcp_peer = server->take_connection();
  116. ERR_FAIL_COND_V_MSG(clients.size() >= LSP_MAX_CLIENTS, FAILED, "Max client limits reached");
  117. Ref<LSPeer> peer = memnew(LSPeer);
  118. peer->connection = tcp_peer;
  119. clients.insert(next_client_id, peer);
  120. next_client_id++;
  121. EditorNode::get_log()->add_message("[LSP] Connection Taken", EditorLog::MSG_TYPE_EDITOR);
  122. return OK;
  123. }
  124. void GDScriptLanguageProtocol::on_client_disconnected(const int &p_client_id) {
  125. clients.erase(p_client_id);
  126. EditorNode::get_log()->add_message("[LSP] Disconnected", EditorLog::MSG_TYPE_EDITOR);
  127. }
  128. String GDScriptLanguageProtocol::process_message(const String &p_text) {
  129. String ret = process_string(p_text);
  130. if (ret.is_empty()) {
  131. return ret;
  132. } else {
  133. return format_output(ret);
  134. }
  135. }
  136. String GDScriptLanguageProtocol::format_output(const String &p_text) {
  137. String header = "Content-Length: ";
  138. CharString charstr = p_text.utf8();
  139. size_t len = charstr.length();
  140. header += itos(len);
  141. header += "\r\n\r\n";
  142. return header + p_text;
  143. }
  144. void GDScriptLanguageProtocol::_bind_methods() {
  145. ClassDB::bind_method(D_METHOD("initialize", "params"), &GDScriptLanguageProtocol::initialize);
  146. ClassDB::bind_method(D_METHOD("initialized", "params"), &GDScriptLanguageProtocol::initialized);
  147. ClassDB::bind_method(D_METHOD("on_client_connected"), &GDScriptLanguageProtocol::on_client_connected);
  148. ClassDB::bind_method(D_METHOD("on_client_disconnected"), &GDScriptLanguageProtocol::on_client_disconnected);
  149. ClassDB::bind_method(D_METHOD("notify_client", "method", "params", "client_id"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));
  150. ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled);
  151. ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document);
  152. ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace);
  153. ClassDB::bind_method(D_METHOD("is_initialized"), &GDScriptLanguageProtocol::is_initialized);
  154. }
  155. Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
  156. LSP::InitializeResult ret;
  157. {
  158. // Warn if the workspace root does not match with the project that is currently open in Godot,
  159. // since it might lead to unexpected behavior, like wrong warnings about duplicate class names.
  160. String root;
  161. Variant root_uri_var = p_params["rootUri"];
  162. Variant root_var = p_params["rootPath"];
  163. if (root_uri_var.is_string()) {
  164. root = get_workspace()->get_file_path(root_uri_var);
  165. } else if (root_var.is_string()) {
  166. root = root_var;
  167. }
  168. if (ProjectSettings::get_singleton()->localize_path(root) != "res://") {
  169. LSP::ShowMessageParams params{
  170. LSP::MessageType::Warning,
  171. "The GDScript Language Server might not work correctly with other projects than the one opened in Godot."
  172. };
  173. notify_client("window/showMessage", params.to_json());
  174. }
  175. }
  176. String root_uri = p_params["rootUri"];
  177. String root = p_params["rootPath"];
  178. bool is_same_workspace;
  179. #ifndef WINDOWS_ENABLED
  180. is_same_workspace = root.to_lower() == workspace->root.to_lower();
  181. #else
  182. is_same_workspace = root.replace_char('\\', '/').to_lower() == workspace->root.to_lower();
  183. #endif
  184. if (root_uri.length() && is_same_workspace) {
  185. workspace->root_uri = root_uri;
  186. } else {
  187. String r_root = workspace->root;
  188. r_root = r_root.lstrip("/");
  189. workspace->root_uri = "file:///" + r_root;
  190. Dictionary params;
  191. params["path"] = workspace->root;
  192. Dictionary request = make_notification("gdscript_client/changeWorkspace", params);
  193. ERR_FAIL_COND_V_MSG(!clients.has(latest_client_id), ret.to_json(),
  194. vformat("GDScriptLanguageProtocol: Can't initialize invalid peer '%d'.", latest_client_id));
  195. Ref<LSPeer> peer = clients.get(latest_client_id);
  196. if (peer.is_valid()) {
  197. String msg = Variant(request).to_json_string();
  198. msg = format_output(msg);
  199. (*peer)->res_queue.push_back(msg.utf8());
  200. }
  201. }
  202. if (!_initialized) {
  203. workspace->initialize();
  204. text_document->initialize();
  205. _initialized = true;
  206. }
  207. return ret.to_json();
  208. }
  209. void GDScriptLanguageProtocol::initialized(const Variant &p_params) {
  210. LSP::GodotCapabilities capabilities;
  211. DocTools *doc = EditorHelp::get_doc_data();
  212. for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {
  213. LSP::GodotNativeClassInfo gdclass;
  214. gdclass.name = E.value.name;
  215. gdclass.class_doc = &(E.value);
  216. if (ClassDB::ClassInfo *ptr = ClassDB::classes.getptr(StringName(E.value.name))) {
  217. gdclass.class_info = ptr;
  218. }
  219. capabilities.native_classes.push_back(gdclass);
  220. }
  221. notify_client("gdscript/capabilities", capabilities.to_json());
  222. }
  223. void GDScriptLanguageProtocol::poll(int p_limit_usec) {
  224. uint64_t target_ticks = OS::get_singleton()->get_ticks_usec() + p_limit_usec;
  225. if (server->is_connection_available()) {
  226. on_client_connected();
  227. }
  228. HashMap<int, Ref<LSPeer>>::Iterator E = clients.begin();
  229. while (E != clients.end()) {
  230. Ref<LSPeer> peer = E->value;
  231. peer->connection->poll();
  232. StreamPeerTCP::Status status = peer->connection->get_status();
  233. if (status == StreamPeerTCP::STATUS_NONE || status == StreamPeerTCP::STATUS_ERROR) {
  234. on_client_disconnected(E->key);
  235. E = clients.begin();
  236. continue;
  237. } else {
  238. Error err = OK;
  239. while (peer->connection->get_available_bytes() > 0) {
  240. latest_client_id = E->key;
  241. err = peer->handle_data();
  242. if (err != OK || OS::get_singleton()->get_ticks_usec() >= target_ticks) {
  243. break;
  244. }
  245. }
  246. if (err != OK && err != ERR_BUSY) {
  247. on_client_disconnected(E->key);
  248. E = clients.begin();
  249. continue;
  250. }
  251. err = peer->send_data();
  252. if (err != OK && err != ERR_BUSY) {
  253. on_client_disconnected(E->key);
  254. E = clients.begin();
  255. continue;
  256. }
  257. }
  258. ++E;
  259. }
  260. }
  261. Error GDScriptLanguageProtocol::start(int p_port, const IPAddress &p_bind_ip) {
  262. return server->listen(p_port, p_bind_ip);
  263. }
  264. void GDScriptLanguageProtocol::stop() {
  265. for (const KeyValue<int, Ref<LSPeer>> &E : clients) {
  266. Ref<LSPeer> peer = clients.get(E.key);
  267. peer->connection->disconnect_from_host();
  268. }
  269. server->stop();
  270. }
  271. void GDScriptLanguageProtocol::notify_client(const String &p_method, const Variant &p_params, int p_client_id) {
  272. #ifdef TESTS_ENABLED
  273. if (clients.is_empty()) {
  274. return;
  275. }
  276. #endif
  277. if (p_client_id == -1) {
  278. ERR_FAIL_COND_MSG(latest_client_id == -1,
  279. "GDScript LSP: Can't notify client as none was connected.");
  280. p_client_id = latest_client_id;
  281. }
  282. ERR_FAIL_COND(!clients.has(p_client_id));
  283. Ref<LSPeer> peer = clients.get(p_client_id);
  284. ERR_FAIL_COND(peer.is_null());
  285. Dictionary message = make_notification(p_method, p_params);
  286. String msg = Variant(message).to_json_string();
  287. msg = format_output(msg);
  288. peer->res_queue.push_back(msg.utf8());
  289. }
  290. void GDScriptLanguageProtocol::request_client(const String &p_method, const Variant &p_params, int p_client_id) {
  291. #ifdef TESTS_ENABLED
  292. if (clients.is_empty()) {
  293. return;
  294. }
  295. #endif
  296. if (p_client_id == -1) {
  297. ERR_FAIL_COND_MSG(latest_client_id == -1,
  298. "GDScript LSP: Can't notify client as none was connected.");
  299. p_client_id = latest_client_id;
  300. }
  301. ERR_FAIL_COND(!clients.has(p_client_id));
  302. Ref<LSPeer> peer = clients.get(p_client_id);
  303. ERR_FAIL_COND(peer.is_null());
  304. Dictionary message = make_request(p_method, p_params, next_server_id);
  305. next_server_id++;
  306. String msg = Variant(message).to_json_string();
  307. msg = format_output(msg);
  308. peer->res_queue.push_back(msg.utf8());
  309. }
  310. bool GDScriptLanguageProtocol::is_smart_resolve_enabled() const {
  311. return bool(_EDITOR_GET("network/language_server/enable_smart_resolve"));
  312. }
  313. bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const {
  314. return bool(_EDITOR_GET("network/language_server/show_native_symbols_in_editor"));
  315. }
  316. // clang-format off
  317. #define SET_DOCUMENT_METHOD(m_method) set_method(_STR(textDocument/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))
  318. #define SET_COMPLETION_METHOD(m_method) set_method(_STR(completionItem/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))
  319. #define SET_WORKSPACE_METHOD(m_method) set_method(_STR(workspace/m_method), callable_mp(workspace.ptr(), &GDScriptWorkspace::m_method))
  320. // clang-format on
  321. GDScriptLanguageProtocol::GDScriptLanguageProtocol() {
  322. server.instantiate();
  323. singleton = this;
  324. workspace.instantiate();
  325. text_document.instantiate();
  326. SET_DOCUMENT_METHOD(didOpen);
  327. SET_DOCUMENT_METHOD(didClose);
  328. SET_DOCUMENT_METHOD(didChange);
  329. SET_DOCUMENT_METHOD(willSaveWaitUntil);
  330. SET_DOCUMENT_METHOD(didSave);
  331. SET_DOCUMENT_METHOD(documentSymbol);
  332. SET_DOCUMENT_METHOD(completion);
  333. SET_DOCUMENT_METHOD(rename);
  334. SET_DOCUMENT_METHOD(prepareRename);
  335. SET_DOCUMENT_METHOD(references);
  336. SET_DOCUMENT_METHOD(foldingRange);
  337. SET_DOCUMENT_METHOD(codeLens);
  338. SET_DOCUMENT_METHOD(documentLink);
  339. SET_DOCUMENT_METHOD(colorPresentation);
  340. SET_DOCUMENT_METHOD(hover);
  341. SET_DOCUMENT_METHOD(definition);
  342. SET_DOCUMENT_METHOD(declaration);
  343. SET_DOCUMENT_METHOD(signatureHelp);
  344. SET_DOCUMENT_METHOD(nativeSymbol); // Custom method.
  345. SET_COMPLETION_METHOD(resolve);
  346. SET_WORKSPACE_METHOD(didDeleteFiles);
  347. set_method("initialize", callable_mp(this, &GDScriptLanguageProtocol::initialize));
  348. set_method("initialized", callable_mp(this, &GDScriptLanguageProtocol::initialized));
  349. workspace->root = ProjectSettings::get_singleton()->get_resource_path();
  350. }
  351. #undef SET_DOCUMENT_METHOD
  352. #undef SET_COMPLETION_METHOD
  353. #undef SET_WORKSPACE_METHOD