rui_orig/webBridge.go

520 lines
13 KiB
Go
Raw Permalink 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
//conn *websocket.Conn
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 {
DebugLog("🖥️ <- " + script)
}
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()
bridge.response = make(chan string, 10)
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
}
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
2024-03-12 19:32:22 +03:00
buffer.WriteString("{\nlet element = document.getElementById('")
2022-11-02 21:05:55 +03:00
buffer.WriteString(htmlID)
buffer.WriteString("');\nif (element) {\n")
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:
arg = strings.ReplaceAll(arg, "\\", `\\`)
arg = strings.ReplaceAll(arg, "'", `\'`)
arg = strings.ReplaceAll(arg, "\n", `\n`)
arg = strings.ReplaceAll(arg, "\r", `\r`)
arg = strings.ReplaceAll(arg, "\t", `\t`)
arg = strings.ReplaceAll(arg, "\b", `\b`)
arg = strings.ReplaceAll(arg, "\f", `\f`)
arg = strings.ReplaceAll(arg, "\v", `\v`)
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 = ','
buffer.WriteString(fmt.Sprintf("%g", val))
}
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
}
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) appendToInnerHTML(htmlID, html string) {
2022-11-02 21:05:55 +03:00
bridge.callFunc("appendToInnerHTML", 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 {
buffer.WriteString(`element.style['`)
buffer.WriteString(property)
buffer.WriteString(`'] = '`)
buffer.WriteString(value)
buffer.WriteString("';\n")
} 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 {
buffer.WriteString(`element.setAttribute('`)
buffer.WriteString(property)
buffer.WriteString(`', `)
buffer.WriteString(val)
buffer.WriteString(");\n")
}
} 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 {
buffer.WriteString(`if (element.hasAttribute('`)
buffer.WriteString(property)
buffer.WriteString(`')) { element.removeAttribute('`)
buffer.WriteString(property)
buffer.WriteString("');}\n")
} 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()
2024-03-12 19:32:22 +03:00
bridge.canvasBuffer.WriteString("{\nconst ctx = getCanvasContext('")
2022-11-02 21:05:55 +03:00
bridge.canvasBuffer.WriteString(htmlID)
bridge.canvasBuffer.WriteString(`');`)
}
2024-03-12 19:32:22 +03:00
func (bridge *webBridge) callCanvasFunc(funcName string, args ...any) {
2022-11-02 21:05:55 +03:00
bridge.canvasBuffer.WriteString("\nctx.")
bridge.canvasBuffer.WriteString(funcName)
bridge.canvasBuffer.WriteRune('(')
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
bridge.canvasBuffer.WriteString("\nctx.")
bridge.canvasBuffer.WriteString(property)
bridge.canvasBuffer.WriteString(" = ")
argText, _ := bridge.argToString(value)
bridge.canvasBuffer.WriteString(argText)
bridge.canvasBuffer.WriteString(";")
}
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)}
2024-02-10 12:25:01 +03:00
bridge.canvasBuffer.WriteString("\nlet ")
2022-11-02 21:05:55 +03:00
bridge.canvasBuffer.WriteString(result.name)
bridge.canvasBuffer.WriteString(" = ctx.")
bridge.canvasBuffer.WriteString(funcName)
bridge.canvasBuffer.WriteRune('(')
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)}
bridge.canvasBuffer.WriteString("\nlet ")
bridge.canvasBuffer.WriteString(result.name)
bridge.canvasBuffer.WriteString(` = 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
}
bridge.canvasBuffer.WriteString("\n")
bridge.canvasBuffer.WriteString(varName.name)
bridge.canvasBuffer.WriteRune('.')
bridge.canvasBuffer.WriteString(funcName)
bridge.canvasBuffer.WriteRune('(')
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
bridge.canvasBuffer.WriteString("\nimg = images.get('")
bridge.canvasBuffer.WriteString(url)
bridge.canvasBuffer.WriteString("');\nif (img) {\n")
if property != "" {
bridge.canvasBuffer.WriteString("ctx.")
bridge.canvasBuffer.WriteString(property)
bridge.canvasBuffer.WriteString(" = ")
}
bridge.canvasBuffer.WriteString("ctx.")
bridge.canvasBuffer.WriteString(funcName)
bridge.canvasBuffer.WriteString("(img")
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
ok := bridge.callFuncImmediately(funcName, funcArgs...)
if ok {
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
}