Path: blob/master/modules/gdscript/language_server/gdscript_language_protocol.cpp
10278 views
/**************************************************************************/1/* gdscript_language_protocol.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "gdscript_language_protocol.h"3132#include "core/config/project_settings.h"33#include "editor/doc/doc_tools.h"34#include "editor/doc/editor_help.h"35#include "editor/editor_log.h"36#include "editor/editor_node.h"37#include "editor/settings/editor_settings.h"3839GDScriptLanguageProtocol *GDScriptLanguageProtocol::singleton = nullptr;4041Error GDScriptLanguageProtocol::LSPeer::handle_data() {42int read = 0;43// Read headers44if (!has_header) {45while (true) {46if (req_pos >= LSP_MAX_BUFFER_SIZE) {47req_pos = 0;48ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Response header too big");49}50Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);51if (err != OK) {52return FAILED;53} else if (read != 1) { // Busy, wait until next poll54return ERR_BUSY;55}56char *r = (char *)req_buf;57int l = req_pos;5859// End of headers60if (l > 3 && r[l] == '\n' && r[l - 1] == '\r' && r[l - 2] == '\n' && r[l - 3] == '\r') {61r[l - 3] = '\0'; // Null terminate to read string62String header = String::utf8(r);63content_length = header.substr(16).to_int();64has_header = true;65req_pos = 0;66break;67}68req_pos++;69}70}71if (has_header) {72while (req_pos < content_length) {73if (req_pos >= LSP_MAX_BUFFER_SIZE) {74req_pos = 0;75has_header = false;76ERR_FAIL_COND_V_MSG(req_pos >= LSP_MAX_BUFFER_SIZE, ERR_OUT_OF_MEMORY, "Response content too big");77}78Error err = connection->get_partial_data(&req_buf[req_pos], 1, read);79if (err != OK) {80return FAILED;81} else if (read != 1) {82return ERR_BUSY;83}84req_pos++;85}8687// Parse data88String msg = String::utf8((const char *)req_buf, req_pos);8990// Reset to read again91req_pos = 0;92has_header = false;9394// Response95String output = GDScriptLanguageProtocol::get_singleton()->process_message(msg);96if (!output.is_empty()) {97res_queue.push_back(output.utf8());98}99}100return OK;101}102103Error GDScriptLanguageProtocol::LSPeer::send_data() {104int sent = 0;105while (!res_queue.is_empty()) {106CharString c_res = res_queue[0];107if (res_sent < c_res.size()) {108Error err = connection->put_partial_data((const uint8_t *)c_res.get_data() + res_sent, c_res.size() - res_sent - 1, sent);109if (err != OK) {110return err;111}112res_sent += sent;113}114// Response sent115if (res_sent >= c_res.size() - 1) {116res_sent = 0;117res_queue.remove_at(0);118}119}120return OK;121}122123Error GDScriptLanguageProtocol::on_client_connected() {124Ref<StreamPeerTCP> tcp_peer = server->take_connection();125ERR_FAIL_COND_V_MSG(clients.size() >= LSP_MAX_CLIENTS, FAILED, "Max client limits reached");126Ref<LSPeer> peer = memnew(LSPeer);127peer->connection = tcp_peer;128clients.insert(next_client_id, peer);129next_client_id++;130EditorNode::get_log()->add_message("[LSP] Connection Taken", EditorLog::MSG_TYPE_EDITOR);131return OK;132}133134void GDScriptLanguageProtocol::on_client_disconnected(const int &p_client_id) {135clients.erase(p_client_id);136EditorNode::get_log()->add_message("[LSP] Disconnected", EditorLog::MSG_TYPE_EDITOR);137}138139String GDScriptLanguageProtocol::process_message(const String &p_text) {140String ret = process_string(p_text);141if (ret.is_empty()) {142return ret;143} else {144return format_output(ret);145}146}147148String GDScriptLanguageProtocol::format_output(const String &p_text) {149String header = "Content-Length: ";150CharString charstr = p_text.utf8();151size_t len = charstr.length();152header += itos(len);153header += "\r\n\r\n";154155return header + p_text;156}157158void GDScriptLanguageProtocol::_bind_methods() {159ClassDB::bind_method(D_METHOD("initialize", "params"), &GDScriptLanguageProtocol::initialize);160ClassDB::bind_method(D_METHOD("initialized", "params"), &GDScriptLanguageProtocol::initialized);161ClassDB::bind_method(D_METHOD("on_client_connected"), &GDScriptLanguageProtocol::on_client_connected);162ClassDB::bind_method(D_METHOD("on_client_disconnected"), &GDScriptLanguageProtocol::on_client_disconnected);163ClassDB::bind_method(D_METHOD("notify_client", "method", "params", "client_id"), &GDScriptLanguageProtocol::notify_client, DEFVAL(Variant()), DEFVAL(-1));164ClassDB::bind_method(D_METHOD("is_smart_resolve_enabled"), &GDScriptLanguageProtocol::is_smart_resolve_enabled);165ClassDB::bind_method(D_METHOD("get_text_document"), &GDScriptLanguageProtocol::get_text_document);166ClassDB::bind_method(D_METHOD("get_workspace"), &GDScriptLanguageProtocol::get_workspace);167ClassDB::bind_method(D_METHOD("is_initialized"), &GDScriptLanguageProtocol::is_initialized);168}169170Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) {171LSP::InitializeResult ret;172173{174// Warn if the workspace root does not match with the project that is currently open in Godot,175// since it might lead to unexpected behavior, like wrong warnings about duplicate class names.176177String root;178Variant root_uri_var = p_params["rootUri"];179Variant root_var = p_params["rootPath"];180if (root_uri_var.is_string()) {181root = get_workspace()->get_file_path(root_uri_var);182} else if (root_var.is_string()) {183root = root_var;184}185186if (ProjectSettings::get_singleton()->localize_path(root) != "res://") {187LSP::ShowMessageParams params{188LSP::MessageType::Warning,189"The GDScript Language Server might not work correctly with other projects than the one opened in Godot."190};191notify_client("window/showMessage", params.to_json());192}193}194195String root_uri = p_params["rootUri"];196String root = p_params["rootPath"];197bool is_same_workspace;198#ifndef WINDOWS_ENABLED199is_same_workspace = root.to_lower() == workspace->root.to_lower();200#else201is_same_workspace = root.replace_char('\\', '/').to_lower() == workspace->root.to_lower();202#endif203204if (root_uri.length() && is_same_workspace) {205workspace->root_uri = root_uri;206} else {207String r_root = workspace->root;208r_root = r_root.lstrip("/");209workspace->root_uri = "file:///" + r_root;210211Dictionary params;212params["path"] = workspace->root;213Dictionary request = make_notification("gdscript_client/changeWorkspace", params);214215ERR_FAIL_COND_V_MSG(!clients.has(latest_client_id), ret.to_json(),216vformat("GDScriptLanguageProtocol: Can't initialize invalid peer '%d'.", latest_client_id));217Ref<LSPeer> peer = clients.get(latest_client_id);218if (peer.is_valid()) {219String msg = Variant(request).to_json_string();220msg = format_output(msg);221(*peer)->res_queue.push_back(msg.utf8());222}223}224225if (!_initialized) {226workspace->initialize();227text_document->initialize();228_initialized = true;229}230231return ret.to_json();232}233234void GDScriptLanguageProtocol::initialized(const Variant &p_params) {235LSP::GodotCapabilities capabilities;236237DocTools *doc = EditorHelp::get_doc_data();238for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {239LSP::GodotNativeClassInfo gdclass;240gdclass.name = E.value.name;241gdclass.class_doc = &(E.value);242if (ClassDB::ClassInfo *ptr = ClassDB::classes.getptr(StringName(E.value.name))) {243gdclass.class_info = ptr;244}245capabilities.native_classes.push_back(gdclass);246}247248notify_client("gdscript/capabilities", capabilities.to_json());249}250251void GDScriptLanguageProtocol::poll(int p_limit_usec) {252uint64_t target_ticks = OS::get_singleton()->get_ticks_usec() + p_limit_usec;253254if (server->is_connection_available()) {255on_client_connected();256}257258HashMap<int, Ref<LSPeer>>::Iterator E = clients.begin();259while (E != clients.end()) {260Ref<LSPeer> peer = E->value;261peer->connection->poll();262StreamPeerTCP::Status status = peer->connection->get_status();263if (status == StreamPeerTCP::STATUS_NONE || status == StreamPeerTCP::STATUS_ERROR) {264on_client_disconnected(E->key);265E = clients.begin();266continue;267} else {268Error err = OK;269while (peer->connection->get_available_bytes() > 0) {270latest_client_id = E->key;271err = peer->handle_data();272if (err != OK || OS::get_singleton()->get_ticks_usec() >= target_ticks) {273break;274}275}276277if (err != OK && err != ERR_BUSY) {278on_client_disconnected(E->key);279E = clients.begin();280continue;281}282283err = peer->send_data();284if (err != OK && err != ERR_BUSY) {285on_client_disconnected(E->key);286E = clients.begin();287continue;288}289}290++E;291}292}293294Error GDScriptLanguageProtocol::start(int p_port, const IPAddress &p_bind_ip) {295return server->listen(p_port, p_bind_ip);296}297298void GDScriptLanguageProtocol::stop() {299for (const KeyValue<int, Ref<LSPeer>> &E : clients) {300Ref<LSPeer> peer = clients.get(E.key);301peer->connection->disconnect_from_host();302}303304server->stop();305}306307void GDScriptLanguageProtocol::notify_client(const String &p_method, const Variant &p_params, int p_client_id) {308#ifdef TESTS_ENABLED309if (clients.is_empty()) {310return;311}312#endif313if (p_client_id == -1) {314ERR_FAIL_COND_MSG(latest_client_id == -1,315"GDScript LSP: Can't notify client as none was connected.");316p_client_id = latest_client_id;317}318ERR_FAIL_COND(!clients.has(p_client_id));319Ref<LSPeer> peer = clients.get(p_client_id);320ERR_FAIL_COND(peer.is_null());321322Dictionary message = make_notification(p_method, p_params);323String msg = Variant(message).to_json_string();324msg = format_output(msg);325peer->res_queue.push_back(msg.utf8());326}327328void GDScriptLanguageProtocol::request_client(const String &p_method, const Variant &p_params, int p_client_id) {329#ifdef TESTS_ENABLED330if (clients.is_empty()) {331return;332}333#endif334if (p_client_id == -1) {335ERR_FAIL_COND_MSG(latest_client_id == -1,336"GDScript LSP: Can't notify client as none was connected.");337p_client_id = latest_client_id;338}339ERR_FAIL_COND(!clients.has(p_client_id));340Ref<LSPeer> peer = clients.get(p_client_id);341ERR_FAIL_COND(peer.is_null());342343Dictionary message = make_request(p_method, p_params, next_server_id);344next_server_id++;345String msg = Variant(message).to_json_string();346msg = format_output(msg);347peer->res_queue.push_back(msg.utf8());348}349350bool GDScriptLanguageProtocol::is_smart_resolve_enabled() const {351return bool(_EDITOR_GET("network/language_server/enable_smart_resolve"));352}353354bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const {355return bool(_EDITOR_GET("network/language_server/show_native_symbols_in_editor"));356}357358// clang-format off359#define SET_DOCUMENT_METHOD(m_method) set_method(_STR(textDocument/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))360#define SET_COMPLETION_METHOD(m_method) set_method(_STR(completionItem/m_method), callable_mp(text_document.ptr(), &GDScriptTextDocument::m_method))361#define SET_WORKSPACE_METHOD(m_method) set_method(_STR(workspace/m_method), callable_mp(workspace.ptr(), &GDScriptWorkspace::m_method))362// clang-format on363364GDScriptLanguageProtocol::GDScriptLanguageProtocol() {365server.instantiate();366singleton = this;367workspace.instantiate();368text_document.instantiate();369370SET_DOCUMENT_METHOD(didOpen);371SET_DOCUMENT_METHOD(didClose);372SET_DOCUMENT_METHOD(didChange);373SET_DOCUMENT_METHOD(willSaveWaitUntil);374SET_DOCUMENT_METHOD(didSave);375376SET_DOCUMENT_METHOD(documentSymbol);377SET_DOCUMENT_METHOD(completion);378SET_DOCUMENT_METHOD(rename);379SET_DOCUMENT_METHOD(prepareRename);380SET_DOCUMENT_METHOD(references);381SET_DOCUMENT_METHOD(foldingRange);382SET_DOCUMENT_METHOD(codeLens);383SET_DOCUMENT_METHOD(documentLink);384SET_DOCUMENT_METHOD(colorPresentation);385SET_DOCUMENT_METHOD(hover);386SET_DOCUMENT_METHOD(definition);387SET_DOCUMENT_METHOD(declaration);388SET_DOCUMENT_METHOD(signatureHelp);389390SET_DOCUMENT_METHOD(nativeSymbol); // Custom method.391392SET_COMPLETION_METHOD(resolve);393394SET_WORKSPACE_METHOD(didDeleteFiles);395396set_method("initialize", callable_mp(this, &GDScriptLanguageProtocol::initialize));397set_method("initialized", callable_mp(this, &GDScriptLanguageProtocol::initialized));398399workspace->root = ProjectSettings::get_singleton()->get_resource_path();400}401402#undef SET_DOCUMENT_METHOD403#undef SET_COMPLETION_METHOD404#undef SET_WORKSPACE_METHOD405406407