gdscript_language_protocol.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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/io/json.h"
  32. #include "core/project_settings.h"
  33. #include "editor/editor_log.h"
  34. #include "editor/editor_node.h"
  35. GDScriptLanguageProtocol *GDScriptLanguageProtocol::singleton = NULL;
  36. Error GDScriptLanguageProtocol::LSPeer::handle_data() {
  37. int read = 0;
  38. // Read headers
  39. if (!has_header) {
  40. while (true) {
  41. if (req_pos >= LSP_MAX_BUFFER_SIZE) {
  42. req_pos = 0;
  43. ERR_FAIL_COND_V_MSG(true, ERR_OUT_OF_MEMORY, "Response header too big");
  44. }
  45. Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
  46. if (err != OK)
  47. return FAILED;
  48. else if (read != 1) // Busy, wait until next poll
  49. return ERR_BUSY;
  50. char *r = (char *)req_buf;
  51. int l = req_pos;
  52. // End of headers
  53. if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {
  54. r[l - 3] = '\0'; // Null terminate to read string
  55. String header;
  56. header.parse_utf8(r);
  57. content_length = header.substr(16).to_int();
  58. has_header = true;
  59. req_pos = 0;
  60. break;
  61. }
  62. req_pos++;
  63. }
  64. }
  65. if (has_header) {
  66. while (req_pos < content_length) {
  67. if (req_pos >= LSP_MAX_BUFFER_SIZE) {
  68. req_pos = 0;
  69. has_header = false;
  70. ERR_FAIL_COND_V_MSG(req_pos >= LSP_MAX_BUFFER_SIZE, ERR_OUT_OF_MEMORY, "Response content too big");
  71. }
  72. Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);
  73. if (err != OK)
  74. return FAILED;
  75. else if (read != 1)
  76. return ERR_BUSY;
  77. req_pos++;
  78. }
  79. // Parse data
  80. String msg;
  81. msg.parse_utf8((const char *)req_buf, req_pos);
  82. // Reset to read again
  83. req_pos = 0;
  84. has_header = false;
  85. // Response
  86. String output = GDScriptLanguageProtocol::get_singleton()->process_message(msg);
  87. if (!output.empty()) {
  88. res_queue.push_back(output.utf8());
  89. }
  90. }
  91. return OK;
  92. }
  93. Error GDScriptLanguageProtocol::LSPeer::send_data() {
  94. int sent = 0;
  95. if (!res_queue.empty()) {
  96. CharString c_res = res_queue[0];
  97. if (res_sent < c_res.size()) {
  98. Error err = connection->put_partial_data((const uint8_t *)c_res.get_data() + res_sent, c_res.size() - res_sent - 1, sent);
  99. if (err != OK) {
  100. return err;
  101. }
  102. res_sent += sent;
  103. }
  104. // Response sent
  105. if (res_sent >= c_res.size() - 1) {
  106. res_sent = 0;
  107. res_queue.remove(0);
  108. }
  109. }
  110. return OK;
  111. }
  112. Error GDScriptLanguageProtocol::on_client_connected() {
  113. Ref<StreamPeerTCP> tcp_peer = server->take_connection();
  114. ERR_FAIL_COND_V_MSG(clients.size() >= LSP_MAX_CLIENTS, FAILED, "Max client limits reached");
  115. Ref<LSPeer> peer = memnew(LSPeer);
  116. peer->connection = tcp_peer;
  117. clients.set(next_client_id, peer);
  118. next_client_id++;
  119. EditorNode::get_log()->add_message("Connection Taken", EditorLog::MSG_TYPE_EDITOR);
  120. return OK;
  121. }
  122. void GDScriptLanguageProtocol::on_client_disconnected(const int &p_client_id) {
  123. clients.erase(p_client_id);
  124. EditorNode::get_log()->add_message("Disconnected", EditorLog::MSG_TYPE_EDITOR);
  125. }
  126. String GDScriptLanguageProtocol::process_message(const String &p_text) {
  127. String ret = process_string(p_text);
  128. if (ret.empty()) {
  129. return ret;
  130. } else {
  131. return format_output(ret);
  132. }
  133. }
  134. String GDScriptLanguageProtocol::format_output(const String &p_text) {
  135. String header = "Content-Length: ";
  136. CharString charstr = p_text.utf8();
  137. size_t len = charstr.length();
  138. header += itos(len);
  139. header += "\r\n\r\n";
  140. return header + p_text;
  141. }
  142. void GDScriptLanguageProtocol::_bind_methods() {
  143. ClassDB::bind_method(D_METHOD("initialize", "params"), &GDScriptLanguageProtocol::initialize);
  144. ClassDB::bind_method(D_METHOD("initialized", "params"), &GDScriptLanguageProtocol::initialized);
  145. ClassDB::bind_method(D_METHOD("on_client_connected"), &GDScriptLanguageProtocol::on_client_connected);
  146. ClassDB::bind_method(D_METHOD("on_client_disconnected"), &GDScriptLanguageProtocol::on_client_disconnected);
  147. ClassDB::bind_method(D_METHOD("notify_client", "method", "params", "client_id"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));
  148. ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled);
  149. ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document);
  150. ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace);
  151. ClassDB::bind_method(D_METHOD("is_initialized"), &GDScriptLanguageProtocol::is_initialized);
  152. }
  153. Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {
  154. lsp::InitializeResult ret;
  155. String root_uri = p_params["rootUri"];
  156. String root = p_params["rootPath"];
  157. bool is_same_workspace;
  158. #ifndef WINDOWS_ENABLED
  159. is_same_workspace = root.to_lower() == workspace->root.to_lower();
  160. #else
  161. is_same_workspace = root.replace("\\", "/").to_lower() == workspace->root.to_lower();
  162. #endif
  163. if (root_uri.length() && is_same_workspace) {
  164. workspace->root_uri = root_uri;
  165. } else {
  166. workspace->root_uri = "file://" + workspace->root;
  167. Dictionary params;
  168. params["path"] = workspace->root;
  169. Dictionary request = make_notification("gdscript_client/changeWorkspace", params);
  170. ERR_FAIL_COND_V_MSG(!clients.has(latest_client_id), ret.to_json(),
  171. vformat("GDScriptLanguageProtocol: Can't initialize invalid peer '%d'.", latest_client_id));
  172. Ref<LSPeer> peer = clients.get(latest_client_id);
  173. if (peer != NULL) {
  174. String msg = JSON::print(request);
  175. msg = format_output(msg);
  176. (*peer)->res_queue.push_back(msg.utf8());
  177. }
  178. }
  179. if (!_initialized) {
  180. workspace->initialize();
  181. text_document->initialize();
  182. _initialized = true;
  183. }
  184. return ret.to_json();
  185. }
  186. void GDScriptLanguageProtocol::initialized(const Variant &p_params) {
  187. lsp::GodotCapabilities capabilities;
  188. DocData *doc = EditorHelp::get_doc_data();
  189. for (Map<String, DocData::ClassDoc>::Element *E = doc->class_list.front(); E; E = E->next()) {
  190. lsp::GodotNativeClassInfo gdclass;
  191. gdclass.name = E->get().name;
  192. gdclass.class_doc = &(E->get());
  193. if (ClassDB::ClassInfo *ptr = ClassDB::classes.getptr(StringName(E->get().name))) {
  194. gdclass.class_info = ptr;
  195. }
  196. capabilities.native_classes.push_back(gdclass);
  197. }
  198. notify_client("gdscript/capabilities", capabilities.to_json());
  199. }
  200. void GDScriptLanguageProtocol::poll() {
  201. if (server->is_connection_available()) {
  202. on_client_connected();
  203. }
  204. const int *id = NULL;
  205. while ((id = clients.next(id))) {
  206. Ref<LSPeer> peer = clients.get(*id);
  207. StreamPeerTCP::Status status = peer->connection->get_status();
  208. if (status == StreamPeerTCP::STATUS_NONE || status == StreamPeerTCP::STATUS_ERROR) {
  209. on_client_disconnected(*id);
  210. id = NULL;
  211. } else {
  212. if (peer->connection->get_available_bytes() > 0) {
  213. latest_client_id = *id;
  214. Error err = peer->handle_data();
  215. if (err != OK && err != ERR_BUSY) {
  216. on_client_disconnected(*id);
  217. id = NULL;
  218. }
  219. }
  220. Error err = peer->send_data();
  221. if (err != OK && err != ERR_BUSY) {
  222. on_client_disconnected(*id);
  223. id = NULL;
  224. }
  225. }
  226. }
  227. }
  228. Error GDScriptLanguageProtocol::start(int p_port, const IP_Address &p_bind_ip) {
  229. return server->listen(p_port, p_bind_ip);
  230. }
  231. void GDScriptLanguageProtocol::stop() {
  232. const int *id = NULL;
  233. while ((id = clients.next(id))) {
  234. Ref<LSPeer> peer = clients.get(*id);
  235. peer->connection->disconnect_from_host();
  236. }
  237. server->stop();
  238. }
  239. void GDScriptLanguageProtocol::notify_client(const String &p_method, const Variant &p_params, int p_client_id) {
  240. if (p_client_id == -1) {
  241. ERR_FAIL_COND_MSG(latest_client_id == -1,
  242. "GDScript LSP: Can't notify client as none was connected.");
  243. p_client_id = latest_client_id;
  244. }
  245. ERR_FAIL_COND(!clients.has(p_client_id));
  246. Ref<LSPeer> peer = clients.get(p_client_id);
  247. ERR_FAIL_COND(peer == NULL);
  248. Dictionary message = make_notification(p_method, p_params);
  249. String msg = JSON::print(message);
  250. msg = format_output(msg);
  251. peer->res_queue.push_back(msg.utf8());
  252. }
  253. bool GDScriptLanguageProtocol::is_smart_resolve_enabled() const {
  254. return bool(_EDITOR_GET("network/language_server/enable_smart_resolve"));
  255. }
  256. bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const {
  257. return bool(_EDITOR_GET("network/language_server/show_native_symbols_in_editor"));
  258. }
  259. GDScriptLanguageProtocol::GDScriptLanguageProtocol() {
  260. server.instance();
  261. singleton = this;
  262. workspace.instance();
  263. text_document.instance();
  264. set_scope("textDocument", text_document.ptr());
  265. set_scope("completionItem", text_document.ptr());
  266. set_scope("workspace", workspace.ptr());
  267. workspace->root = ProjectSettings::get_singleton()->get_resource_path();
  268. }