rui_orig/webBridge.go

502 lines
12 KiB
Go
Raw Normal View History

2022-11-02 21:05:55 +03:00
//go:build !wasm
package rui
import (
"fmt"
"net/http"
"strconv"
"strings"
"sync"
"github.com/gorilla/websocket"
)
2024-03-12 19:32:22 +03:00
type webBridge struct {
answer map[int]chan DataObject
answerID int
answerMutex sync.Mutex
writeMutex sync.Mutex
closed bool
canvasBuffer strings.Builder
canvasVarNumber int
updateScripts map[string]*strings.Builder
writeMessage func(string) bool
callFuncImmediately func(funcName string, args ...any) bool
}
2022-11-02 21:05:55 +03:00
type wsBridge struct {
2024-03-12 19:32:22 +03:00
webBridge
conn *websocket.Conn
}
type httpBridge struct {
webBridge
responseBuffer strings.Builder
response chan string
remoteAddress string
2022-11-02 21:05:55 +03:00
}
type canvasVar struct {
name string
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 8096,
}
2024-03-12 19:32:22 +03:00
func createSocketBridge(w http.ResponseWriter, req *http.Request) *wsBridge {
2024-06-13 09:37:48 +03:00
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
2022-11-02 21:05:55 +03:00
conn, err := upgrader.Upgrade(w, req, nil)
if err != nil {
ErrorLog(err.Error())
return nil
}
bridge := new(wsBridge)
2024-03-12 19:32:22 +03:00
bridge.initBridge()
2022-11-02 21:05:55 +03:00
bridge.conn = conn
2024-03-12 19:32:22 +03:00
bridge.writeMessage = func(script string) bool {
if ProtocolInDebugLog {
2026-05-29 16:07:48 +03:00
DebugLog("🖥️ ← " + script)
2024-03-12 19:32:22 +03:00
}
if bridge.conn == nil {
ErrorLog("No connection")
return false
}
bridge.writeMutex.Lock()
err := bridge.conn.WriteMessage(websocket.TextMessage, []byte(script))
bridge.writeMutex.Unlock()
if err != nil {
ErrorLog(err.Error())
return false
}
return true
}
bridge.callFuncImmediately = bridge.callFunc
2022-11-02 21:05:55 +03:00
return bridge
}
2024-03-12 19:32:22 +03:00
func createHttpBridge(req *http.Request) *httpBridge {
bridge := new(httpBridge)
bridge.initBridge()
2026-08-06 16:52:19 +03:00
bridge.response = make(chan string, 100)
2024-03-12 19:32:22 +03:00
bridge.writeMessage = func(script string) bool {
if script != "" {
if ProtocolInDebugLog {
DebugLog(script)
}
if bridge.responseBuffer.Len() > 0 {
bridge.responseBuffer.WriteRune('\n')
}
bridge.responseBuffer.WriteString(script)
}
return true
}
bridge.callFuncImmediately = bridge.callImmediately
bridge.remoteAddress = req.RemoteAddr
return bridge
}
func (bridge *webBridge) initBridge() {
bridge.answerID = 1
bridge.answer = make(map[int]chan DataObject)
bridge.closed = false
bridge.updateScripts = map[string]*strings.Builder{}
2022-11-02 21:05:55 +03:00
}
2026-07-28 12:26:03 +03:00
func (bridge *webBridge) writeScript(script string) {
bridge.writeMessage(script)
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) startUpdateScript(htmlID string) bool {
2022-11-02 21:05:55 +03:00
if _, ok := bridge.updateScripts[htmlID]; ok {
return false
}
buffer := allocStringBuilder()
bridge.updateScripts[htmlID] = buffer
2026-09-03 12:39:07 +03:00
writeStrings(buffer, "{\nlet element = document.getElementById('", htmlID, "');\nif (element) {\n")
2022-11-02 21:05:55 +03:00
return true
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) finishUpdateScript(htmlID string) {
2022-11-02 21:05:55 +03:00
if buffer, ok := bridge.updateScripts[htmlID]; ok {
2024-03-12 19:32:22 +03:00
buffer.WriteString("scanElementsSize();\n}\n}\n")
2022-11-02 21:05:55 +03:00
bridge.writeMessage(buffer.String())
2024-03-12 19:32:22 +03:00
2022-11-02 21:05:55 +03:00
freeStringBuilder(buffer)
delete(bridge.updateScripts, htmlID)
}
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) argToString(arg any) (string, bool) {
2022-11-02 21:05:55 +03:00
switch arg := arg.(type) {
case string:
2026-08-06 16:52:19 +03:00
escChars := []struct{ esc, repl string }{
{esc: "\\", repl: `\\`},
{esc: "'", repl: `\'`},
{esc: "\b", repl: `\b`},
{esc: "\t", repl: `\t`},
{esc: "\n", repl: `\n`},
{esc: "\v", repl: `\v`},
{esc: "\r", repl: `\r`},
{esc: "\f", repl: `\f`},
}
for _, s := range escChars {
if strings.Contains(arg, s.esc) {
arg = strings.ReplaceAll(arg, s.esc, s.repl)
}
}
for n := range 0x20 {
esc := string([]rune{rune(n)})
if strings.Contains(arg, esc) {
repl := fmt.Sprintf(`\x%02d`, n)
arg = strings.ReplaceAll(arg, esc, repl)
}
}
2022-11-02 21:05:55 +03:00
return `'` + arg + `'`, true
case rune:
switch arg {
case '\t':
return `'\t'`, true
case '\r':
return `'\r'`, true
case '\n':
return `'\n'`, true
case '\b':
return `'\b'`, true
case '\f':
return `'\f'`, true
case '\v':
return `'\v'`, true
case '\'':
return `'\''`, true
case '\\':
return `'\\'`, true
}
if arg < ' ' {
return fmt.Sprintf(`'\x%02d'`, int(arg)), true
}
return `'` + string(arg) + `'`, true
case bool:
if arg {
return "true", true
} else {
return "false", true
}
case float32:
return fmt.Sprintf("%g", float64(arg)), true
case float64:
return fmt.Sprintf("%g", arg), true
case []float64:
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
lead := '['
for _, val := range arg {
buffer.WriteRune(lead)
lead = ','
2025-06-23 16:59:24 +03:00
fmt.Fprintf(buffer, "%g", val)
2022-11-02 21:05:55 +03:00
}
buffer.WriteRune(']')
return buffer.String(), true
case canvasVar:
return arg.name, true
default:
if n, ok := isInt(arg); ok {
return fmt.Sprintf("%d", n), true
}
}
2022-11-23 15:10:29 +03:00
ErrorLog("Unsupported argument type")
2022-11-02 21:05:55 +03:00
return "", false
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) callFuncScript(funcName string, args ...any) (string, bool) {
buffer := allocStringBuilder()
defer freeStringBuilder(buffer)
buffer.WriteString(funcName)
buffer.WriteRune('(')
2022-11-02 21:05:55 +03:00
for i, arg := range args {
argText, ok := bridge.argToString(arg)
if !ok {
2024-03-12 19:32:22 +03:00
return "", false
2022-11-02 21:05:55 +03:00
}
if i > 0 {
2024-03-12 19:32:22 +03:00
buffer.WriteString(", ")
2022-11-02 21:05:55 +03:00
}
2024-03-12 19:32:22 +03:00
buffer.WriteString(argText)
2022-11-02 21:05:55 +03:00
}
2024-03-12 19:32:22 +03:00
buffer.WriteString(");")
2022-11-02 21:05:55 +03:00
2024-03-12 19:32:22 +03:00
return buffer.String(), true
}
2024-02-10 12:25:01 +03:00
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) callFunc(funcName string, args ...any) bool {
if funcText, ok := bridge.callFuncScript(funcName, args...); ok {
return bridge.writeMessage(funcText)
2022-11-02 21:05:55 +03:00
}
2024-03-12 19:32:22 +03:00
return false
2022-11-02 21:05:55 +03:00
}
2026-07-11 19:21:20 +03:00
func (bridge *webBridge) localStorageRequest(funcName string, args ...any) {
bridge.callFuncImmediately(funcName, args...)
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) updateInnerHTML(htmlID, html string) {
2022-11-02 21:05:55 +03:00
bridge.callFunc("updateInnerHTML", htmlID, html)
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) updateCSSProperty(htmlID, property, value string) {
2022-11-02 21:05:55 +03:00
if buffer, ok := bridge.updateScripts[htmlID]; ok {
2026-09-03 12:39:07 +03:00
writeStrings(buffer, `element.style['`, property, `'] = '`, value, "';\n")
2022-11-02 21:05:55 +03:00
} else {
bridge.callFunc("updateCSSProperty", htmlID, property, value)
}
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) updateProperty(htmlID, property string, value any) {
2022-11-02 21:05:55 +03:00
if buffer, ok := bridge.updateScripts[htmlID]; ok {
if val, ok := bridge.argToString(value); ok {
2026-09-03 12:39:07 +03:00
writeStrings(buffer, `element.setAttribute('`, property, `', `, val, ");\n")
2022-11-02 21:05:55 +03:00
}
} else {
bridge.callFunc("updateProperty", htmlID, property, value)
}
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) removeProperty(htmlID, property string) {
2022-11-02 21:05:55 +03:00
if buffer, ok := bridge.updateScripts[htmlID]; ok {
2026-09-03 12:39:07 +03:00
writeStrings(buffer, `if (element.hasAttribute('`, property, `')) { element.removeAttribute('`, property, "');}\n")
2022-11-02 21:05:55 +03:00
} else {
bridge.callFunc("removeProperty", htmlID, property)
}
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) appendAnimationCSS(css string) {
bridge.writeMessage(`{
let styles = document.getElementById('ruiAnimations');
if (styles) {
styles.textContent += '` + css + `';
}
2022-11-08 16:31:21 +03:00
}`)
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) setAnimationCSS(css string) {
bridge.writeMessage(`{
let styles = document.getElementById('ruiAnimations');
if (styles) {
styles.textContent = '` + css + `';
}
2022-11-08 16:31:21 +03:00
}`)
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) canvasStart(htmlID string) {
2022-11-02 21:05:55 +03:00
bridge.canvasBuffer.Reset()
2026-09-03 12:39:07 +03:00
writeStrings(&bridge.canvasBuffer, "{\nconst ctx = getCanvasContext('", htmlID, `');`)
2022-11-02 21:05:55 +03:00
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) callCanvasFunc(funcName string, args ...any) {
2026-09-03 12:39:07 +03:00
writeStrings(&bridge.canvasBuffer, "\nctx.", funcName, `(`)
2022-11-02 21:05:55 +03:00
for i, arg := range args {
if i > 0 {
bridge.canvasBuffer.WriteString(", ")
}
argText, _ := bridge.argToString(arg)
bridge.canvasBuffer.WriteString(argText)
}
bridge.canvasBuffer.WriteString(");")
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) updateCanvasProperty(property string, value any) {
2022-11-02 21:05:55 +03:00
argText, _ := bridge.argToString(value)
2026-09-03 12:39:07 +03:00
writeStrings(&bridge.canvasBuffer, "\nctx.", property, " = ", argText, ";")
2022-11-02 21:05:55 +03:00
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) createCanvasVar(funcName string, args ...any) any {
2022-11-02 21:05:55 +03:00
bridge.canvasVarNumber++
result := canvasVar{name: fmt.Sprintf("v%d", bridge.canvasVarNumber)}
2026-09-03 12:39:07 +03:00
writeStrings(&bridge.canvasBuffer, "\nlet ", result.name, " = ctx.", funcName, "(")
2022-11-02 21:05:55 +03:00
for i, arg := range args {
if i > 0 {
bridge.canvasBuffer.WriteString(", ")
}
argText, _ := bridge.argToString(arg)
bridge.canvasBuffer.WriteString(argText)
}
bridge.canvasBuffer.WriteString(");")
return result
}
func (bridge *webBridge) createPath2D(arg string) any {
bridge.canvasVarNumber++
result := canvasVar{name: fmt.Sprintf("v%d", bridge.canvasVarNumber)}
2026-09-03 12:39:07 +03:00
writeStrings(&bridge.canvasBuffer, "\nlet ", result.name, ` = new Path2D(`)
if arg != "" {
argText, _ := bridge.argToString(arg)
bridge.canvasBuffer.WriteString(argText)
}
bridge.canvasBuffer.WriteString(`);`)
return result
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) callCanvasVarFunc(v any, funcName string, args ...any) {
2022-11-02 21:05:55 +03:00
varName, ok := v.(canvasVar)
if !ok {
return
}
2026-09-03 12:39:07 +03:00
writeStrings(&bridge.canvasBuffer, "\n", varName.name, ".", funcName, "(")
2022-11-02 21:05:55 +03:00
for i, arg := range args {
if i > 0 {
bridge.canvasBuffer.WriteString(", ")
}
argText, _ := bridge.argToString(arg)
bridge.canvasBuffer.WriteString(argText)
}
bridge.canvasBuffer.WriteString(");")
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) callCanvasImageFunc(url string, property string, funcName string, args ...any) {
2022-11-02 21:05:55 +03:00
2026-09-03 12:39:07 +03:00
writeStrings(&bridge.canvasBuffer, "\nimg = images.get('", url, "');\nif (img) {\n")
2022-11-02 21:05:55 +03:00
if property != "" {
2026-09-03 12:39:07 +03:00
writeStrings(&bridge.canvasBuffer, "ctx.", property, " = ")
2022-11-02 21:05:55 +03:00
}
2026-09-03 12:39:07 +03:00
writeStrings(&bridge.canvasBuffer, "ctx.", funcName, "(img")
2022-11-02 21:05:55 +03:00
for _, arg := range args {
bridge.canvasBuffer.WriteString(", ")
argText, _ := bridge.argToString(arg)
bridge.canvasBuffer.WriteString(argText)
}
bridge.canvasBuffer.WriteString(");\n}")
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) canvasFinish() {
bridge.canvasBuffer.WriteString("\n}\n")
bridge.writeMessage(bridge.canvasBuffer.String())
2022-11-02 21:05:55 +03:00
}
func (bridge *webBridge) remoteValue(funcName string, args ...any) (DataObject, bool) {
2022-11-02 21:05:55 +03:00
bridge.answerMutex.Lock()
answerID := bridge.answerID
bridge.answerID++
bridge.answerMutex.Unlock()
answer := make(chan DataObject)
bridge.answer[answerID] = answer
funcArgs := append([]any{answerID}, args...)
2024-03-12 19:32:22 +03:00
var result DataObject = nil
2024-12-10 18:23:04 +03:00
if bridge.callFuncImmediately(funcName, funcArgs...) {
2024-03-12 19:32:22 +03:00
result = <-answer
}
close(answer)
2022-11-02 21:05:55 +03:00
delete(bridge.answer, answerID)
2024-03-12 19:32:22 +03:00
return result, true
2022-11-02 21:05:55 +03:00
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) canvasTextMetrics(htmlID, font, text string) TextMetrics {
result := TextMetrics{}
if data, ok := bridge.remoteValue("canvasTextMetrics", htmlID, font, text); ok {
2024-03-12 19:32:22 +03:00
result.Width = dataFloatProperty(data, "width")
}
return result
}
2022-11-02 21:05:55 +03:00
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) htmlPropertyValue(htmlID, name string) string {
if data, ok := bridge.remoteValue("getPropertyValue", htmlID, name); ok {
2022-11-02 21:05:55 +03:00
if value, ok := data.PropertyValue("value"); ok {
return value
}
}
return ""
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) answerReceived(answer DataObject) {
2022-11-02 21:05:55 +03:00
if text, ok := answer.PropertyValue("answerID"); ok {
if id, err := strconv.Atoi(text); err == nil {
if chanel, ok := bridge.answer[id]; ok {
chanel <- answer
delete(bridge.answer, id)
} else {
ErrorLog("Bad answerID = " + text + " (chan not found)")
}
} else {
ErrorLog("Invalid answerID = " + text)
}
} else {
ErrorLog("answerID not found")
}
}
2024-03-12 19:32:22 +03:00
func (bridge *wsBridge) close() {
bridge.closed = true
defer bridge.conn.Close()
bridge.conn = nil
}
func (bridge *wsBridge) readMessage() (string, bool) {
_, p, err := bridge.conn.ReadMessage()
if err != nil {
if !bridge.closed {
ErrorLog(err.Error())
}
return "", false
}
return string(p), true
}
func (bridge *wsBridge) sendResponse() {
}
2022-11-02 21:05:55 +03:00
func (bridge *wsBridge) remoteAddr() string {
return bridge.conn.RemoteAddr().String()
}
2024-03-12 19:32:22 +03:00
func (bridge *httpBridge) close() {
bridge.closed = true
// TODO
}
func (bridge *httpBridge) callImmediately(funcName string, args ...any) bool {
if funcText, ok := bridge.callFuncScript(funcName, args...); ok {
if ProtocolInDebugLog {
DebugLog("Run func: " + funcText)
}
bridge.response <- funcText
return true
}
return false
}
func (bridge *httpBridge) sendResponse() {
bridge.writeMutex.Lock()
text := bridge.responseBuffer.String()
bridge.responseBuffer.Reset()
bridge.writeMutex.Unlock()
bridge.response <- text
}
func (bridge *httpBridge) remoteAddr() string {
return bridge.remoteAddress
}