godot-xterm/examples/web_console/web_console.gd

79 lines
1.9 KiB
GDScript
Raw Normal View History

2021-06-07 08:53:43 +02:00
extends Node
const TPut := preload("res://addons/godot_xterm/util/tput.gd")
2021-06-07 08:53:43 +02:00
signal exited(status)
var line := ""
var _tput
2021-06-07 08:53:43 +02:00
2022-11-09 21:57:46 +01:00
@onready var terminal = $Terminal
2024-03-30 03:24:32 +01:00
@onready var _has_js: bool = OS.has_feature("web")
2021-06-07 08:53:43 +02:00
func prompt(prompt: String):
_tput.setaf(TPut.ANSIColor.bright_green)
terminal.write(prompt)
_tput.sgr0()
func _ready():
_tput = TPut.new(terminal)
_tput.setaf(TPut.ANSIColor.bright_cyan)
terminal.write("*** Web Console ***\r\n\r\n")
_tput.setaf(TPut.ANSIColor.yellow)
terminal.write("Input will be passed to Godot's JavaScript.eval() function.\r\n")
terminal.write("Some things you could try:\r\n\r\n")
terminal.write(">> 1 + 1\r\n")
terminal.write(">> window.location\r\n")
terminal.write(">> alert('Hello')\r\n\r\n")
_tput.setaf(TPut.ANSIColor.bright_cyan)
terminal.write("Enter 'q', 'quit', or 'exit' to return to the previous menu.\r\n\r\n")
_tput.sgr0()
prompt(">> ")
terminal.grab_focus()
func grab_focus():
terminal.grab_focus()
func _on_Terminal_key_pressed(_data, event: InputEventKey):
if not event:
return
2024-03-30 03:24:32 +01:00
# For some reason, data String is malformed on Web, so only use event.unicode.
2021-06-07 08:53:43 +02:00
var data = char(event.unicode)
2024-03-30 03:24:32 +01:00
match event.keycode:
2021-06-07 08:53:43 +02:00
KEY_ENTER:
terminal.write("\r\n")
2021-06-07 08:53:43 +02:00
if line == "q" or line == "quit" or line == "exit":
return emit_signal("exited", 0)
2021-06-07 08:53:43 +02:00
if not _has_js:
2024-03-30 03:24:32 +01:00
var msg := "WebConsole only available in Web build."
2021-06-07 08:53:43 +02:00
push_error(msg)
_tput.setaf(TPut.ANSIColor.red)
terminal.write(msg)
_tput.sgr0()
prompt("\r\n>> ")
else:
2024-03-30 03:24:32 +01:00
var json = JavaScriptBridge.eval("JSON.stringify(%s)" % line, true)
_tput.setaf(TPut.ANSIColor.magenta)
terminal.write(str(json))
_tput.sgr0()
2021-06-07 08:53:43 +02:00
line = ""
2024-03-30 03:24:32 +01:00
_tput.sgr0()
2021-06-07 08:53:43 +02:00
prompt("\r\n>> ")
2021-06-07 08:53:43 +02:00
KEY_BACKSPACE:
if line.length() > 0:
terminal.write("\b \b")
line = line.substr(0, line.length() - 1)
_:
line += data
terminal.write(data)