2
0

gdscript_language_protocol.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /*************************************************************************/
  2. /* gdscript_language_protocol.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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_log.h"
  34. #include "editor/editor_node.h"
  35. #include "editor/editor_settings.h"
  36. GDScriptLanguageProtocol *GDScriptLanguageProtocol::singleton = nullptr;
  37. Error GDScriptLanguageProtocol::LSPeer::handle_data() {
  38. int read = 0;
  39. // Read headers
  40. if (!has_header) {
  41. while (true) {
  42. if (req_pos >= LSP_MAX_BUFFER_SIZE) {
  43. req_pos = 0;
  44. ERR_FAIL_COND_V_MSG(true, ERR_OUT_OF_MEMORY, "Response header too big");
  45. }
  46. Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
  47. if (err != OK) {
  48. return FAILED;
  49. } else if (read != 1) { // Busy, wait until next poll
  50. return ERR_BUSY;
  51. }
  52. char *r = (char *)req_buf;
  53. int l = req_pos;
  54. // End of headers
  55. if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
  56. r[l - 3] = '\0'; // Null terminate to read string
  57. String header;
  58. header.parse_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;
  84. msg.parse_utf8((const char *)req_buf, req_pos);
  85. // Reset to read again
  86. req_pos = 0;
  87. has_header = false;
  88. // Response
  89. String output = GDScriptLanguageProtocol::get_singleton()->process_message(msg);
  90. if (!output.is_empty()) {
  91. res_queue.push_back(output.utf8());
  92. }
  93. }
  94. return OK;
  95. }
  96. Error GDScriptLanguageProtocol::LSPeer::send_data() {
  97. int sent = 0;
  98. if (!res_queue.is_empty()) {
  99. CharString c_res = res_queue[0];
  100. if (res_sent < c_res.size()) {
  101. Error err = connection->put_partial_data((const uint8_t *)c_res.get_data() + res_sent, c_res.size() - res_sent - 1, sent);
  102. if (err != OK) {
  103. return err;
  104. }
  105. res_sent += sent;
  106. }
  107. // Response sent
  108. if (res_sent >= c_res.size() - 1) {
  109. res_sent = 0;
  110. res_queue.remove_at(0);
  111. }
  112. }
  113. return OK;
  114. }
  115. Error GDScriptLanguageProtocol::on_client_connected() {
  116. Ref<StreamPeerTCP> tcp_peer = server->take_connection();
  117. ERR_FAIL_COND_V_MSG(clients.size() >= LSP_MAX_CLIENTS, FAILED, "Max client limits reached");
  118. Ref<LSPeer> peer = memnew(LSPeer);
  119. peer->connection = tcp_peer;
  120. clients.insert(next_client_id, peer);
  121. next_client_id++;
  122. EditorNode::get_log()->add_message("[LSP] Connection Taken", EditorLog::MSG_TYPE_EDITOR);
  123. return OK;
  124. }
  125. void GDScriptLanguageProtocol::on_client_disconnected(const int &p_client_id) {
  126. clients.erase(p_client_id);
  127. EditorNode::get_log()->add_message("[LSP] Disconnected", EditorLog::MSG_TYPE_EDITOR);
  128. }
  129. String GDScriptLanguageProtocol::process_message(const String &p_text) {
  130. String ret = process_string(p_text);
  131. if (ret.is_empty()) {
  132. return ret;
  133. } else {
  134. return format_output(ret);
  135. }
  136. }
  137. String GDScriptLanguageProtocol::format_output(const String &p_text) {
  138. String header = "Content-Length: ";
  139. CharString charstr = p_text.utf8();
  140. size_t len = charstr.length();
  141. header += itos(len);
  142. header += "\r\n\r\n";
  143. return header + p_text;
  144. }
  145. void GDScriptLanguageProtocol::_bind_methods() {
  146. ClassDB::bind_method(D_METHOD("initialize", "params"), &GDScriptLanguageProtocol::initialize);
  147. ClassDB::bind_method(D_METHOD("initialized", "params"), &GDScriptLanguageProtocol::initialized);
  148. ClassDB::bind_method(D_METHOD("on_client_connected"), &GDScriptLanguageProtocol::on_client_connected);
  149. ClassDB::bind_method(D_METHOD("on_client_disconnected"), &GDScriptLanguageProtocol::on_client_disconnected);
  150. ClassDB::bind_method(D_METHOD("notify_client", "method", "params", "client_id"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));
  151. ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled);
  152. ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document);
  153. ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace);
  154. ClassDB::bind_method(D_METHOD("is_initialized"), &GDScriptLanguageProtocol::is_initialized);
  155. }
  156. Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
  157. lsp::InitializeResult ret;
  158. String root_uri = p_params["rootUri"];
  159. String root = p_params["rootPath"];
  160. bool is_same_workspace;
  161. #ifndef WINDOWS_ENABLED
  162. is_same_workspace = root.to_lower() == workspace->root.to_lower();
  163. #else
  164. is_same_workspace = root.replace("\\", "/").to_lower() == workspace->root.to_lower();
  165. #endif
  166. if (root_uri.length() && is_same_workspace) {
  167. workspace->root_uri = root_uri;
  168. } else {
  169. workspace->root_uri = "file://" + workspace->root;
  170. Dictionary params;
  171. params["path"] = workspace->root;
  172. Dictionary request = make_notification("gdscript_client/changeWorkspace", params);
  173. ERR_FAIL_COND_V_MSG(!clients.has(latest_client_id), ret.to_json(),
  174. vformat("GDScriptLanguageProtocol: Can't initialize invalid peer '%d'.", latest_client_id));
  175. Ref<LSPeer> peer = clients.get(latest_client_id);
  176. if (peer != nullptr) {
  177. String msg = Variant(request).to_json_string();
  178. msg = format_output(msg);
  179. (*peer)->res_queue.push_back(msg.utf8());
  180. }
  181. }
  182. if (!_initialized) {
  183. workspace->initialize();
  184. text_document->initialize();
  185. _initialized = true;
  186. }
  187. return ret.to_json();
  188. }
  189. void GDScriptLanguageProtocol::initialized(const Variant &p_params) {
  190. lsp::GodotCapabilities capabilities;
  191. DocTools *doc = EditorHelp::get_doc_data();
  192. for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {
  193. lsp::GodotNativeClassInfo gdclass;
  194. gdclass.name = E.value.name;
  195. gdclass.class_doc = &(E.value);
  196. if (ClassDB::ClassInfo *ptr = ClassDB::classes.getptr(StringName(E.value.name))) {
  197. gdclass.class_info = ptr;
  198. }
  199. capabilities.native_classes.push_back(gdclass);
  200. }
  201. notify_client("gdscript/capabilities", capabilities.to_json());
  202. }
  203. void GDScriptLanguageProtocol::poll() {
  204. if (server->is_connection_available()) {
  205. on_client_connected();
  206. }
  207. HashMap<int, Ref<LSPeer>>::Iterator E = clients.begin();
  208. while (E != clients.end()) {
  209. Ref<LSPeer> peer = E->value;
  210. StreamPeerTCP::Status status = peer->connection->get_status();
  211. if (status == StreamPeerTCP::STATUS_NONE || status == StreamPeerTCP::STATUS_ERROR) {
  212. on_client_disconnected(E->key);
  213. E = clients.begin();
  214. continue;
  215. } else {
  216. if (peer->connection->get_available_bytes() > 0) {
  217. latest_client_id = E->key;
  218. Error err = peer->handle_data();
  219. if (err != OK && err != ERR_BUSY) {
  220. on_client_disconnected(E->key);
  221. E = clients.begin();
  222. continue;
  223. }
  224. }
  225. Error err = peer->send_data();
  226. if (err != OK && err != ERR_BUSY) {
  227. on_client_disconnected(E->key);
  228. E = clients.begin();
  229. continue;
  230. }
  231. }
  232. ++E;
  233. }
  234. }
  235. Error GDScriptLanguageProtocol::start(int p_port, const IPAddress &p_bind_ip) {
  236. return server->listen(p_port, p_bind_ip);
  237. }
  238. void GDScriptLanguageProtocol::stop() {
  239. for (const KeyValue<int, Ref<LSPeer>> &E : clients) {
  240. Ref<LSPeer> peer = clients.get(E.key);
  241. peer->connection->disconnect_from_host();
  242. }
  243. server->stop();
  244. }
  245. void GDScriptLanguageProtocol::notify_client(const String &p_method, const Variant &p_params, int p_client_id) {
  246. if (p_client_id == -1) {
  247. ERR_FAIL_COND_MSG(latest_client_id == -1,
  248. "GDScript LSP: Can't notify client as none was connected.");
  249. p_client_id = latest_client_id;
  250. }
  251. ERR_FAIL_COND(!clients.has(p_client_id));
  252. Ref<LSPeer> peer = clients.get(p_client_id);
  253. ERR_FAIL_COND(peer == nullptr);
  254. Dictionary message = make_notification(p_method, p_params);
  255. String msg = Variant(message).to_json_string();
  256. msg = format_output(msg);
  257. peer->res_queue.push_back(msg.utf8());
  258. }
  259. void GDScriptLanguageProtocol::request_client(const String &p_method, const Variant &p_params, int p_client_id) {
  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 == nullptr);
  268. Dictionary message = make_request(p_method, p_params, next_server_id);
  269. next_server_id++;
  270. String msg = Variant(message).to_json_string();
  271. msg = format_output(msg);
  272. peer->res_queue.push_back(msg.utf8());
  273. }
  274. bool GDScriptLanguageProtocol::is_smart_resolve_enabled() const {
  275. return bool(_EDITOR_GET("network/language_server/enable_smart_resolve"));
  276. }
  277. bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const {
  278. return bool(_EDITOR_GET("network/language_server/show_native_symbols_in_editor"));
  279. }
  280. GDScriptLanguageProtocol::GDScriptLanguageProtocol() {
  281. server.instantiate();
  282. singleton = this;
  283. workspace.instantiate();
  284. text_document.instantiate();
  285. set_scope("textDocument", text_document.ptr());
  286. set_scope("completionItem", text_document.ptr());
  287. set_scope("workspace", workspace.ptr());
  288. workspace->root = ProjectSettings::get_singleton()->get_resource_path();
  289. }