gdscript_language_protocol.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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;
  59. header.parse_utf8(r);
  60. content_length = header.substr(16).to_int();
  61. has_header = true;
  62. req_pos = 0;
  63. break;
  64. }
  65. req_pos++;
  66. }
  67. }
  68. if (has_header) {
  69. while (req_pos < content_length) {
  70. if (req_pos >= LSP_MAX_BUFFER_SIZE) {
  71. req_pos = 0;
  72. has_header = false;
  73. ERR_FAIL_COND_V_MSG(req_pos >= LSP_MAX_BUFFER_SIZE, ERR_OUT_OF_MEMORY, "Response content too big");
  74. }
  75. Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
  76. if (err != OK) {
  77. return FAILED;
  78. } else if (read != 1) {
  79. return ERR_BUSY;
  80. }
  81. req_pos++;
  82. }
  83. // Parse data
  84. String msg;
  85. msg.parse_utf8((const char *)req_buf, req_pos);
  86. // Reset to read again
  87. req_pos = 0;
  88. has_header = false;
  89. // Response
  90. String output = GDScriptLanguageProtocol::get_singleton()->process_message(msg);
  91. if (!output.is_empty()) {
  92. res_queue.push_back(output.utf8());
  93. }
  94. }
  95. return OK;
  96. }
  97. Error GDScriptLanguageProtocol::LSPeer::send_data() {
  98. int sent = 0;
  99. while (!res_queue.is_empty()) {
  100. CharString c_res = res_queue[0];
  101. if (res_sent < c_res.size()) {
  102. Error err = connection->put_partial_data((const uint8_t *)c_res.get_data() + res_sent, c_res.size() - res_sent - 1, sent);
  103. if (err != OK) {
  104. return err;
  105. }
  106. res_sent += sent;
  107. }
  108. // Response sent
  109. if (res_sent >= c_res.size() - 1) {
  110. res_sent = 0;
  111. res_queue.remove_at(0);
  112. }
  113. }
  114. return OK;
  115. }
  116. Error GDScriptLanguageProtocol::on_client_connected() {
  117. Ref<StreamPeerTCP> tcp_peer = server->take_connection();
  118. ERR_FAIL_COND_V_MSG(clients.size() >= LSP_MAX_CLIENTS, FAILED, "Max client limits reached");
  119. Ref<LSPeer> peer = memnew(LSPeer);
  120. peer->connection = tcp_peer;
  121. clients.insert(next_client_id, peer);
  122. next_client_id++;
  123. EditorNode::get_log()->add_message("[LSP] Connection Taken", EditorLog::MSG_TYPE_EDITOR);
  124. return OK;
  125. }
  126. void GDScriptLanguageProtocol::on_client_disconnected(const int &p_client_id) {
  127. clients.erase(p_client_id);
  128. EditorNode::get_log()->add_message("[LSP] Disconnected", EditorLog::MSG_TYPE_EDITOR);
  129. }
  130. String GDScriptLanguageProtocol::process_message(const String &p_text) {
  131. String ret = process_string(p_text);
  132. if (ret.is_empty()) {
  133. return ret;
  134. } else {
  135. return format_output(ret);
  136. }
  137. }
  138. String GDScriptLanguageProtocol::format_output(const String &p_text) {
  139. String header = "Content-Length: ";
  140. CharString charstr = p_text.utf8();
  141. size_t len = charstr.length();
  142. header += itos(len);
  143. header += "\r\n\r\n";
  144. return header + p_text;
  145. }
  146. void GDScriptLanguageProtocol::_bind_methods() {
  147. ClassDB::bind_method(D_METHOD("initialize", "params"), &GDScriptLanguageProtocol::initialize);
  148. ClassDB::bind_method(D_METHOD("initialized", "params"), &GDScriptLanguageProtocol::initialized);
  149. ClassDB::bind_method(D_METHOD("on_client_connected"), &GDScriptLanguageProtocol::on_client_connected);
  150. ClassDB::bind_method(D_METHOD("on_client_disconnected"), &GDScriptLanguageProtocol::on_client_disconnected);
  151. ClassDB::bind_method(D_METHOD("notify_client", "method", "params", "client_id"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));
  152. ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled);
  153. ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document);
  154. ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace);
  155. ClassDB::bind_method(D_METHOD("is_initialized"), &GDScriptLanguageProtocol::is_initialized);
  156. }
  157. Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
  158. lsp::InitializeResult ret;
  159. String root_uri = p_params["rootUri"];
  160. String root = p_params["rootPath"];
  161. bool is_same_workspace;
  162. #ifndef WINDOWS_ENABLED
  163. is_same_workspace = root.to_lower() == workspace->root.to_lower();
  164. #else
  165. is_same_workspace = root.replace("\\", "/").to_lower() == workspace->root.to_lower();
  166. #endif
  167. if (root_uri.length() && is_same_workspace) {
  168. workspace->root_uri = root_uri;
  169. } else {
  170. String r_root = workspace->root;
  171. r_root = r_root.lstrip("/");
  172. workspace->root_uri = "file:///" + r_root;
  173. Dictionary params;
  174. params["path"] = workspace->root;
  175. Dictionary request = make_notification("gdscript_client/changeWorkspace", params);
  176. ERR_FAIL_COND_V_MSG(!clients.has(latest_client_id), ret.to_json(),
  177. vformat("GDScriptLanguageProtocol: Can't initialize invalid peer '%d'.", latest_client_id));
  178. Ref<LSPeer> peer = clients.get(latest_client_id);
  179. if (peer.is_valid()) {
  180. String msg = Variant(request).to_json_string();
  181. msg = format_output(msg);
  182. (*peer)->res_queue.push_back(msg.utf8());
  183. }
  184. }
  185. if (!_initialized) {
  186. workspace->initialize();
  187. text_document->initialize();
  188. _initialized = true;
  189. }
  190. return ret.to_json();
  191. }
  192. void GDScriptLanguageProtocol::initialized(const Variant &p_params) {
  193. lsp::GodotCapabilities capabilities;
  194. DocTools *doc = EditorHelp::get_doc_data();
  195. for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {
  196. lsp::GodotNativeClassInfo gdclass;
  197. gdclass.name = E.value.name;
  198. gdclass.class_doc = &(E.value);
  199. if (ClassDB::ClassInfo *ptr = ClassDB::classes.getptr(StringName(E.value.name))) {
  200. gdclass.class_info = ptr;
  201. }
  202. capabilities.native_classes.push_back(gdclass);
  203. }
  204. notify_client("gdscript/capabilities", capabilities.to_json());
  205. }
  206. void GDScriptLanguageProtocol::poll(int p_limit_usec) {
  207. uint64_t target_ticks = OS::get_singleton()->get_ticks_usec() + p_limit_usec;
  208. if (server->is_connection_available()) {
  209. on_client_connected();
  210. }
  211. HashMap<int, Ref<LSPeer>>::Iterator E = clients.begin();
  212. while (E != clients.end()) {
  213. Ref<LSPeer> peer = E->value;
  214. peer->connection->poll();
  215. StreamPeerTCP::Status status = peer->connection->get_status();
  216. if (status == StreamPeerTCP::STATUS_NONE || status == StreamPeerTCP::STATUS_ERROR) {
  217. on_client_disconnected(E->key);
  218. E = clients.begin();
  219. continue;
  220. } else {
  221. Error err = OK;
  222. while (peer->connection->get_available_bytes() > 0) {
  223. latest_client_id = E->key;
  224. err = peer->handle_data();
  225. if (err != OK || OS::get_singleton()->get_ticks_usec() >= target_ticks) {
  226. break;
  227. }
  228. }
  229. if (err != OK && err != ERR_BUSY) {
  230. on_client_disconnected(E->key);
  231. E = clients.begin();
  232. continue;
  233. }
  234. err = peer->send_data();
  235. if (err != OK && err != ERR_BUSY) {
  236. on_client_disconnected(E->key);
  237. E = clients.begin();
  238. continue;
  239. }
  240. }
  241. ++E;
  242. }
  243. }
  244. Error GDScriptLanguageProtocol::start(int p_port, const IPAddress &p_bind_ip) {
  245. return server->listen(p_port, p_bind_ip);
  246. }
  247. void GDScriptLanguageProtocol::stop() {
  248. for (const KeyValue<int, Ref<LSPeer>> &E : clients) {
  249. Ref<LSPeer> peer = clients.get(E.key);
  250. peer->connection->disconnect_from_host();
  251. }
  252. server->stop();
  253. }
  254. void GDScriptLanguageProtocol::notify_client(const String &p_method, const Variant &p_params, int p_client_id) {
  255. #ifdef TESTS_ENABLED
  256. if (clients.is_empty()) {
  257. return;
  258. }
  259. #endif
  260. if (p_client_id == -1) {
  261. ERR_FAIL_COND_MSG(latest_client_id == -1,
  262. "GDScript LSP: Can't notify client as none was connected.");
  263. p_client_id = latest_client_id;
  264. }
  265. ERR_FAIL_COND(!clients.has(p_client_id));
  266. Ref<LSPeer> peer = clients.get(p_client_id);
  267. ERR_FAIL_COND(peer.is_null());
  268. Dictionary message = make_notification(p_method, p_params);
  269. String msg = Variant(message).to_json_string();
  270. msg = format_output(msg);
  271. peer->res_queue.push_back(msg.utf8());
  272. }
  273. void GDScriptLanguageProtocol::request_client(const String &p_method, const Variant &p_params, int p_client_id) {
  274. #ifdef TESTS_ENABLED
  275. if (clients.is_empty()) {
  276. return;
  277. }
  278. #endif
  279. if (p_client_id == -1) {
  280. ERR_FAIL_COND_MSG(latest_client_id == -1,
  281. "GDScript LSP: Can't notify client as none was connected.");
  282. p_client_id = latest_client_id;
  283. }
  284. ERR_FAIL_COND(!clients.has(p_client_id));
  285. Ref<LSPeer> peer = clients.get(p_client_id);
  286. ERR_FAIL_COND(peer.is_null());
  287. Dictionary message = make_request(p_method, p_params, next_server_id);
  288. next_server_id++;
  289. String msg = Variant(message).to_json_string();
  290. msg = format_output(msg);
  291. peer->res_queue.push_back(msg.utf8());
  292. }
  293. bool GDScriptLanguageProtocol::is_smart_resolve_enabled() const {
  294. return bool(_EDITOR_GET("network/language_server/enable_smart_resolve"));
  295. }
  296. bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const {
  297. return bool(_EDITOR_GET("network/language_server/show_native_symbols_in_editor"));
  298. }
  299. GDScriptLanguageProtocol::GDScriptLanguageProtocol() {
  300. server.instantiate();
  301. singleton = this;
  302. workspace.instantiate();
  303. text_document.instantiate();
  304. set_scope("textDocument", text_document.ptr());
  305. set_scope("completionItem", text_document.ptr());
  306. set_scope("workspace", workspace.ptr());
  307. workspace->root = ProjectSettings::get_singleton()->get_resource_path();
  308. }