Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft: LSP Implementation #17

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions addons/pronto/helpers/EditorIcon.gd
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ class_name EditorIcon
@export var name: String:
set(n):
name = n
_tex = Engine.get_main_loop().get_root().get_theme_icon(name, &"EditorIcons")
emit_changed()
if Engine.get_main_loop() != null:
_tex = Engine.get_main_loop().get_root().get_theme_icon(name, &"EditorIcons")
emit_changed()

var _tex: ImageTexture

Expand Down
106 changes: 106 additions & 0 deletions addons/pronto/helpers/LanguageClient.gd
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
@tool
extends Node
class_name LanguageClient

signal on_notification(data: Dictionary)
signal on_response(data: Dictionary)

func _ready():
socket = StreamPeerTCP.new()
socket.connect_to_host('127.0.0.1', 6005)
socket.poll()
socket.set_no_delay(true)

send_request('initialize', {
'processId': null,
'clientInfo': {'name': 'pronto'},
'rootUri': 'file://' + ProjectSettings.globalize_path("res://"),
'capabilities': {
'textDocument': {'hover': {}, 'synchronization': {'dynamicRegistration': true}},
'workspace': {'applyEdit': true, 'workspaceEdit': {'documentChanges': true}},
},
}, func (r): pass)

func script_path(script: Script):
return "file://" + ProjectSettings.globalize_path(script.resource_path)

func _exit_tree():
socket.disconnect_from_host()

func _process(delta):
if Engine.is_editor_hint():
return
socket.poll()
var m = receive_message()
if m != null:
if "id" in m:
_waiting_handlers[int(m["id"])].call(m["result"])
_waiting_handlers.erase(int(m["id"]))
else:
on_notification.emit(m)

func completion(script: Script, line: int, character: int, cb: Callable):
send_request('textDocument/completion', {
'textDocument': {'uri': script_path(script)}, 'position': {'line': line, 'character': character}
}, cb)

var _waiting_handlers = {}
var _document_versions = {}

func did_change(script: Script):
if not script.resource_path in _document_versions:
_document_versions[script.resource_path] = 1
else:
_document_versions[script.resource_path] += 1
send_notification("textDocument/didChange", {
"textDocument": {"uri": script_path(script), "version": _document_versions[script.resource_path]},
"contentChanges": {"text": script.source_code}
})

func did_open(script: Script):
send_notification("textDocument/didOpen", {'textDocument': {
'uri': script_path(script),
'text': script.source_code
}})

func send_notification(notification: String, params: Dictionary):
send({'jsonrpc': '2.0', 'method': notification, 'params': params})

func send_request(request: String, params: Dictionary, cb: Callable):
var my_id = current_id
current_id = current_id + 1
_waiting_handlers[my_id] = cb
send({'jsonrpc': '2.0', 'id': my_id, 'method': request, 'params': params})

func send(obj: Dictionary):
print("> " + str(obj))
var data = JSON.stringify(obj).to_utf8_buffer()
socket.put_data('Content-Length: {0}\r\n\r\n'.format([data.size()]).to_utf8_buffer())
socket.put_data(data)

var current_id = 1
var socket: StreamPeerTCP
var buffer = ""

func receive_message():
var available = socket.get_available_bytes()
buffer += socket.get_string(available)

var header_end = buffer.find("\r\n\r\n")
if header_end >= 0:
var headers = {}
for pair in Array(buffer.substr(0, header_end).split("\r\n")).map(func (header): return header.split(': ')):
assert(pair.size() == 2)
headers[pair[0].to_lower()] = pair[1]
assert("content-length" in headers)

var json_length = int(headers["content-length"])
var total_length = header_end + 4 + json_length
if buffer.length() < total_length:
return null
var json = buffer.substr(header_end + 4, json_length)
var data = JSON.parse_string(json)
buffer = buffer.substr(total_length)
return data
else:
return null
2 changes: 2 additions & 0 deletions addons/pronto/helpers/Utils.gd
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,8 @@ static func global_rect_of(node: Node):
return Rect2(node.global_position, Vector2.ZERO)

static func fix_minimum_size(n: Control):
if G.at("_pronto_editor_plugin") == null:
return
n.custom_minimum_size *= G.at("_pronto_editor_plugin").get_editor_interface().get_editor_scale()

static func log(s):
Expand Down
2 changes: 2 additions & 0 deletions addons/pronto/pronto.gd
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ func _edit(object):
if _is_editing_behavior():
edited_object.deselected()

# get_editor_interface().edit_script(load("res://examples/platformer.tscn::GDScript_tb7ap"))

edited_object = object
if _is_editing_behavior() and edited_object is Node:
show_signals(edited_object)
Expand Down
23 changes: 23 additions & 0 deletions addons/pronto/signal_connecting/expression_edit.gd
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ signal text_changed()
@export var min_width = 80
@export var max_width = 260

var edited_script

var _LanguageClient: LanguageClient

func _input(event):
if not $Expression.has_focus():
return
Expand All @@ -37,8 +41,27 @@ func _ready():
if owner != self:
fake_a_godot_highlighter()
resize()
add_child(LanguageClient.new())

edited_script = GDScript.new()
edited_script.source_code = 'extends Object'
edited_script.reload()
edited_script.resource_path = "res://test-script.gd"
ResourceSaver.save(edited_script)

# TODO
if not Engine.is_editor_hint():
# TODO move to autoload
_LanguageClient = LanguageClient.new()
add_child(_LanguageClient)
$Expression.code_completion_enabled = true
$Expression.code_completion_prefixes = ['.', '/'] # TODO
$Expression.language_client = _LanguageClient
$Expression.edited_script = edited_script

func fake_a_godot_highlighter():
if G.at("_pronto_editor_plugin") == null:
return
var s = G.at("_pronto_editor_plugin").get_editor_interface().get_editor_settings()
var h = CodeHighlighter.new()
h.number_color = s.get("text_editor/theme/highlighting/number_color")
Expand Down
14 changes: 10 additions & 4 deletions addons/pronto/signal_connecting/expression_edit.tscn
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
[gd_scene load_steps=6 format=3 uid="uid://d1jujxfamsekk"]
[gd_scene load_steps=7 format=3 uid="uid://d1jujxfamsekk"]

[ext_resource type="Script" path="res://addons/pronto/signal_connecting/expression_edit.gd" id="1_lndi8"]
[ext_resource type="Script" path="res://addons/pronto/helpers/EditorIcon.gd" id="2_au0w8"]
[ext_resource type="Script" path="res://addons/pronto/signal_connecting/lsp_edit.gd" id="2_lla62"]

[sub_resource type="SystemFont" id="SystemFont_xd5ge"]
font_names = PackedStringArray("Monospace")

[sub_resource type="CodeHighlighter" id="CodeHighlighter_yn0mp"]
[sub_resource type="CodeHighlighter" id="CodeHighlighter_tp1bn"]
number_color = Color(0, 0.55, 0.28, 1)
symbol_color = Color(0, 0, 0.61, 1)
function_color = Color(0, 0.225, 0.9, 1)
Expand Down Expand Up @@ -63,10 +64,12 @@ script = ExtResource("2_au0w8")
name = "DebugStep"

[node name="expression_edit" type="HBoxContainer"]
custom_minimum_size = Vector2(0, 43)
custom_minimum_size = Vector2(180, 32)
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
offset_right = -972.0
offset_bottom = -614.0
grow_horizontal = 2
grow_vertical = 2
size_flags_horizontal = 0
Expand All @@ -80,10 +83,13 @@ size_flags_horizontal = 3
theme_override_fonts/font = SubResource("SystemFont_xd5ge")
placeholder_text = "Expression..."
draw_tabs = true
syntax_highlighter = SubResource("CodeHighlighter_yn0mp")
syntax_highlighter = SubResource("CodeHighlighter_tp1bn")
scroll_fit_content_height = true
code_completion_enabled = true
code_completion_prefixes = Array[String]([".", "/"])
indent_automatic = true
auto_brace_completion_enabled = true
script = ExtResource("2_lla62")

[node name="OpenFile" type="Button" parent="."]
layout_mode = 2
Expand Down
24 changes: 24 additions & 0 deletions addons/pronto/signal_connecting/lsp_edit.gd
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
@tool
extends CodeEdit

var language_client: LanguageClient
var edited_script: Script:
set(s):
edited_script = s
language_client.did_open(s)

func _ready():
text_changed.connect(on_text_changed)

func on_text_changed():
edited_script.source_code = text
language_client.did_change(edited_script)

func _request_code_completion(force):
print([get_caret_line(), get_caret_column()])
language_client.completion(edited_script, get_caret_line(), get_caret_column(), func (entries):
for entry in entries:
# print(entry)
pass
# add_code_completion_option(CodeEdit.KIND_MEMBER)
)
10 changes: 9 additions & 1 deletion examples/platformer/platformer.tscn
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
[gd_scene load_steps=14 format=3 uid="uid://88vl7ypda1n1"]
[gd_scene load_steps=15 format=3 uid="uid://88vl7ypda1n1"]

[ext_resource type="Script" path="res://addons/pronto/behaviors/Placeholder.gd" id="1_rpa0n"]
[ext_resource type="Script" path="res://addons/pronto/behaviors/Move.gd" id="2_pahj6"]
Expand Down Expand Up @@ -54,6 +54,13 @@ arguments = ["dir"]
only_if = ""
expression = ""

[sub_resource type="GDScript" id="GDScript_tb7ap"]
script/source = "extends Object

func
2 + 3
"

[node name="platformer" type="Node2D"]

[node name="CharacterBody2D" type="CharacterBody2D" parent="."]
Expand Down Expand Up @@ -141,3 +148,4 @@ position = Vector2(231, 530)
position = Vector2(1, 0)
script = ExtResource("1_rpa0n")
placeholder_size = Vector2(227, 25)
metadata/s = SubResource("GDScript_tb7ap")
14 changes: 14 additions & 0 deletions language_client_test.tscn
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[gd_scene load_steps=2 format=3 uid="uid://dthrl53okqjb"]

[ext_resource type="PackedScene" uid="uid://d1jujxfamsekk" path="res://addons/pronto/signal_connecting/expression_edit.tscn" id="2_5guic"]

[node name="Node" type="Control"]
layout_mode = 3
anchors_preset = 0

[node name="expression_edit" parent="." instance=ExtResource("2_5guic")]
layout_mode = 1
offset_left = 37.0
offset_top = 40.0
offset_right = 217.0
offset_bottom = 74.0