This commit is contained in:
STARAI\Star 2024-10-13 23:12:55 +08:00
commit 35c2a0f3cf
16 changed files with 755 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.*
!.gitignore
go.sum
node_modules
package.json

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2024 apigo
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

70
README.md Normal file
View File

@ -0,0 +1,70 @@
# util for GoJS
## usage
```go
import (
"apigo.cc/gojs"
_ "apigo.cc/gojs/util"
)
func main() {
r, err := gojs.Run(`
import util from 'apigo.cc/gojs/util'
function main(args){
return util.sha512('hello 123')
}
`, "test.js")
fmt.Println(r, err, r == "27d0d415a3b14bdeb5ab5b2298ed3aed272361688927250eaef201603b84dd8bebb57cae089d6b5f1e9aee122a67917ccdf8a9ba5e499c64b35e133c7f6b007a")
}
```
## module.exports
```ts
function json(data:any)
function jsonP(data:any)
function unJson(data:string)
function yaml(data:any)
function unYaml(data:string)
function load(filename:string)
function save(filename:string, data:any)
function base64(data:any)
function unBase64(data:string)
function urlBase64(data:any)
function unUrlBase64(data:string)
function hex(data:any)
function unHex(data:string)
function aes(data:any, key:string, iv:string)
function unAes(data:string, key:string, iv:string)
function gzip(data:any)
function gunzip(data:string)
function id()
function uniqueId()
function token(size:number)
function md5(data:any)
function sha1(data:any)
function sha256(data:any)
function sha512(data:any)
function tpl(text:string, data:any, functions?:Object)
function sleep(ms:number)
function setTimeout(callback:()=>void, ms?:number, ...args:any)
function shell(cmd:string, ...args:string[])
function toDatetime(timestamp:number)
function fromDatetime(datetimeStr:string)
function toDate(timestamp:number)
function fromDate(dateStr:string)
function os()
function arch()
function joinPath(...paths:string[])
function getPathDir(path:string)
function getPathBase(path:string)
function getPathVolume(path:string)
function absPath(path:string)
function cleanPath(path:string)
function isLocalPath(path:string)
```
## full api see [util.ts](https://apigo.cc/gojs/util/util.ts)

67
app.js Normal file
View File

@ -0,0 +1,67 @@
window._dialogTexts = { 'zh': { 'Close': '关闭', 'Cancel': '取消', 'Confirm': '确定' } }
function _getDialogDefaultText(text) { return (window._dialogTexts[navigator.language] && window._dialogTexts[navigator.language][text]) || (window._dialogTexts[navigator.language.split('-')[0]] && window._dialogTexts[navigator.language.split('-')[0]][text]) || text }
window.alert = function (msg, buttonText) { return showDialog(msg, [buttonText || _getDialogDefaultText('Close')]) }
window.confirm = function (msg, confirmButtonText, cancelButtonText) { return showDialog(msg, [cancelButtonText || _getDialogDefaultText('Cancel'), cancelButtonText || _getDialogDefaultText('Confirm')]) }
window.prompt = function (msg, defaultValue, confirmButtonText, cancelButtonText) { return showDialog(msg, [cancelButtonText || _getDialogDefaultText('Cancel'), cancelButtonText || _getDialogDefaultText('Confirm')], [{ value: defaultValue || '' }]) }
window.showDialog = function (msg, buttons, inputs) {
if (!document.querySelector('#_dialogStyle')) {
let sDom = document.createElement('style')
sDom.id = '_dialogStyle'
sDom.textContent = '._dialogMask {position:fixed;left:0;right:0;top:0;bottom:0;background:rgba(128,128,128,0.7);display:flex;justify-content:center;align-items:center}\n' +
'._dialogPanel {background:#eee;padding:16px;min-width:300px;max-width:80%;max-height:80%;margin:auto;border-radius:10px;display:flex;flex-flow:column;overflow:auto}\n' +
'._dialogMessage {font-size:0.875rem;flex:1;overflow:auto;white-space:pre-wrap}\n' +
'._dialogInputs {display:flex;flex-flow:column;margin-top:8px}\n' +
'._dialogInputs input {flex:1;border:1px solid #aaa;border-radius:4px;min-height:28px;padding:0 8px}\n' +
'._dialogLine {text-align:end;padding:4px 0}\n' +
'._dialogButtons {text-align:end}\n' +
'._dialogButtons button {background:none;border:none;color:#999;min-height:28px;cursor:pointer;font-size:1rem;margin-left:10px}\n' +
'._dialogButtons button:hover {color:#999}\n' +
'._dialogButtons button:last-child {color:#06f}'
document.head.append(sDom)
}
return new Promise(resolve => {
let a = ['<div class="_dialogPanel">']
if (msg) a.push('<div class="_dialogMessage">__MSG__</div>'.replace(/__MSG__/, msg))
if (inputs && inputs.length) {
let a1 = ['<div class="_dialogInputs">']
for (let i = 0; i < inputs.length; i++) {
a1.push('<input id="_dialogInput__ID_____INPUT_INDEX__" placeholder="__INPUT_HINT__" value="__INPUT_VALUE__"/>'.replace(/__INPUT_INDEX__/, i + '').replace(/__INPUT_HINT__/, inputs[i].hint || '').replace(/__INPUT_VALUE__/, inputs[i].value || ''))
}
a1.push('</div>')
a.push(a1.join(''))
}
a.push('<div class="_dialogLine"><hr/></div>')
let a2 = ['<div class="_dialogButtons">']
for (let i = 0; i < buttons.length; i++) a2.push('<button class="_dialogButton" onclick="_dialogAction__ID__(__BUTTON_INDEX__)">__BUTTON_LABEL__</button>'.replace(/__BUTTON_INDEX__/, i + '').replace(/__BUTTON_LABEL__/, buttons[i]))
a2.push('</div>')
a.push(a2.join(''))
let dialogId = Math.ceil(Math.random() * 10000000000).toString(36)
let w = document.createElement('div')
w.id = '_dialogWindow' + dialogId
w.className = '_dialogMask'
window['_dialogAction' + dialogId] = function (index) {
let isOK = index === buttons.length - 1
if (inputs && inputs.length) {
if (isOK) {
let inputValues = []
for (let i = 0; i < inputs.length; i++) inputValues.push(document.querySelector('#_dialogInput' + dialogId + '_' + i).value)
resolve(inputs.length === 1 ? inputValues[0] : inputValues)
} else {
resolve(false)
}
} else {
resolve(isOK ? true : index)
}
document.body.removeChild(document.querySelector('#_dialogWindow' + dialogId))
}
w.innerHTML = a.join('').replace(/__ID__/g, dialogId)
document.body.append(w)
})
}
let app = {
close: __closeWindow,
setTitle: __setTitle,
setSize: __setSize,
eval: __eval,
}

3
cgo.yml Normal file
View File

@ -0,0 +1,3 @@
CGO_ENABLED: true
CGO_CPPFLAGS:
- -I%PROJECT%/include

334
client.go Normal file
View File

@ -0,0 +1,334 @@
package client
import (
_ "embed"
"os"
"path/filepath"
"strings"
"sync"
"time"
"apigo.cc/gojs"
"apigo.cc/gojs/goja"
"github.com/ssgo/tool/watcher"
webview "github.com/webview/webview_go"
)
//go:embed client.ts
var clientTS string
//go:embed README.md
var clientMD string
//go:embed app.js
var appCode string
var binds = map[string]any{}
var bindsLock = sync.RWMutex{}
var windowsId uint64
var windows = map[uint64]*Webview{}
var windowsLock = sync.RWMutex{}
var waitChan chan bool
func Bind(name string, fn any) {
bindsLock.Lock()
binds[name] = fn
bindsLock.Unlock()
}
func Unbind(name string) {
bindsLock.Lock()
delete(binds, name)
bindsLock.Unlock()
}
type Webview struct {
id uint64
w webview.WebView
isRunning bool
isAsync bool
isDebug bool
webRoot string
watcher *watcher.Watcher
html string
url string
closeChan chan bool
}
func Wait() {
// 如果有窗口在运行,等待窗口关闭
windowsLock.RLock()
if len(windows) > 0 {
waitChan = make(chan bool, 1)
}
windowsLock.RUnlock()
// fmt.Println("====== wait start")
if waitChan != nil {
<-waitChan
waitChan = nil
}
// fmt.Println("====== wait end")
}
func CloseAll() {
windows1 := map[uint64]*Webview{}
windowsLock.Lock()
for id, w := range windows {
windows1[id] = w
}
windowsLock.Unlock()
for _, w := range windows1 {
w.close()
}
}
func (w *Webview) close() {
// fmt.Println("====== w.Close()")
if w.isRunning {
w.isRunning = false
// w.closeChan = make(chan bool, 1)
// fmt.Println("====== w.w.Terminate()")
w.w.Terminate()
// fmt.Println("====== w.w.Terminate() ok")
// <-w.closeChan
// w.closeChan = nil
}
}
func (w *Webview) doClose() {
// fmt.Println("====== w.doClose()")
if w.watcher != nil {
w.watcher.Stop()
w.watcher = nil
}
windowsLock.Lock()
delete(windows, w.id)
n := len(windows)
windowsLock.Unlock()
// fmt.Println("====== w.w.Destroy()")
w.w.Destroy()
// fmt.Println("====== w.w.Destroy() ok")
// 解除 w.Close 的等待
if w.closeChan != nil {
w.closeChan <- true
}
// 解除 gojs.WaitAll 的等待
if waitChan != nil && n == 0 {
waitChan <- true
}
}
func (w *Webview) loadHtml(html string) {
w.w.SetHtml(html)
}
func (w *Webview) loadURL(url string) {
if url != "" {
if strings.Contains(url, "://") {
w.w.Navigate(url)
} else {
if !filepath.IsAbs(url) {
curPath, _ := os.Getwd()
url = filepath.Join(curPath, url)
}
w.webRoot = filepath.Dir(url)
url = "file://" + url
w.w.Navigate(url)
}
}
w.w.Navigate(url)
}
func (w *Webview) reload() {
if w.html != "" {
w.loadHtml(w.html)
} else {
w.loadURL(w.url)
}
}
func (w *Webview) setTitle(title string) {
w.w.SetTitle(title)
}
func (w *Webview) setSize(width int, height int, sizeMode string) {
w.w.SetSize(width, height, getSizeMode(sizeMode))
}
func (w *Webview) eval(code string) {
w.w.Eval(code)
}
func (w *Webview) Close(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
w.close()
return nil
}
func (w *Webview) LoadHtml(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
w.loadHtml(args.Str(0))
return nil
}
func (w *Webview) LoadURL(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
w.loadURL(args.Str(0))
return nil
}
func (w *Webview) Dispatch(f func()) {
w.w.Dispatch(f)
}
func (w *Webview) SetTitle(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
w.setTitle(args.Str(0))
return nil
}
func (w *Webview) SetSize(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2)
w.setSize(args.Int(0), args.Int(1), args.Str(2))
return nil
}
func (w *Webview) Eval(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
w.eval(args.Str(0))
return nil
}
func (w *Webview) binds() {
tmpBinds := map[string]any{}
bindsLock.RLock()
for k, v := range binds {
tmpBinds[k] = v
}
bindsLock.RUnlock()
for k, v := range tmpBinds {
_ = w.w.Bind(k, v)
}
_ = w.w.Bind("__closeWindow", w.close)
_ = w.w.Bind("__setTitle", w.setTitle)
_ = w.w.Bind("__setSize", w.setSize)
_ = w.w.Bind("__eval", w.eval)
w.w.Init(appCode)
}
func getSizeMode(sizeMode string) webview.Hint {
switch sizeMode {
case "none":
return webview.HintNone
case "fixed":
return webview.HintFixed
case "min":
return webview.HintMin
case "max":
return webview.HintMax
default:
return webview.HintNone
}
}
func init() {
obj := map[string]any{
"open": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm)
title := ""
width := 800
height := 600
sizeMode := "none"
isDebug := false
html := ""
url := ""
if opt := args.Obj(0); opt != nil {
if titleV := opt.Str("title"); titleV != "" {
title = titleV
}
if widthV := opt.Int("width"); widthV != 0 {
width = widthV
}
if heightV := opt.Int("height"); heightV != 0 {
height = heightV
}
if sizeModeV := opt.Str("sizeMode"); sizeModeV != "" {
sizeMode = sizeModeV
}
if isDebugV := opt.Bool("isDebug"); isDebugV {
isDebug = isDebugV
}
if htmlV := opt.Str("html"); htmlV != "" {
html = htmlV
}
if urlV := opt.Str("url"); urlV != "" {
url = urlV
if strings.HasPrefix(url, "file://") {
url = url[7:]
}
}
}
w := &Webview{isDebug: isDebug, html: html, url: url}
startChan := make(chan bool, 1)
go func() {
windowsLock.Lock()
w.id = windowsId
windowsId++
windows[w.id] = w
windowsLock.Unlock()
w.w = webview.New(isDebug)
w.w.SetTitle(title)
w.w.SetSize(width, height, getSizeMode(sizeMode))
w.binds()
if w.isDebug {
var isWaitingRun = false
if w.webRoot == "" && w.html != "" {
w.webRoot = "."
}
if w.webRoot != "" {
w.watcher, _ = watcher.Start([]string{w.webRoot}, []string{"html", "js", "css"}, func(filename string, event string) {
if !isWaitingRun {
isWaitingRun = true
go func() {
time.Sleep(time.Millisecond * 10)
isWaitingRun = false
w.w.Eval("location.reload()")
}()
}
})
}
}
w.isRunning = true
w.reload()
startChan <- true
w.w.Run()
// fmt.Println("====== w.w.Run() end")
w.doClose()
}()
<-startChan
return vm.ToValue(gojs.MakeMap(w))
},
"closeAll": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
CloseAll()
return nil
},
}
gojs.Register("apigo.cc/gojs/client", gojs.Module{
Object: obj,
Desc: "web client framework by github.com/webview/webview",
TsCode: clientTS,
Example: clientMD,
WaitForStop: Wait,
})
}

28
client.ts Normal file
View File

@ -0,0 +1,28 @@
// just for develop
export default {
open,
closeAll
}
function open(config: Config): View { return null as any }
function closeAll(): void { }
interface Config {
title: string
width: number
height: number
sizeMode: string
isDebug: boolean
html: string
url: string
}
interface View {
close(): void
setTitle(title: string): void
setSize(width: number, height: number, sizeMode?: string): void
loadUrl(url: string): void
loadHtml(html: string): void
eval(code: string): void
}

25
go.mod Normal file
View File

@ -0,0 +1,25 @@
module apigo.cc/gojs/client
go 1.18
require (
apigo.cc/gojs v0.0.1
github.com/ssgo/tool v0.4.27
github.com/ssgo/u v1.7.9
github.com/webview/webview_go v0.0.0-20240831120633-6173450d4dd6
)
require (
github.com/dlclark/regexp2 v1.11.4 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect
github.com/ssgo/config v1.7.7 // indirect
github.com/ssgo/log v1.7.7 // indirect
github.com/ssgo/standard v1.7.7 // indirect
golang.org/x/sys v0.26.0 // indirect
golang.org/x/text v0.19.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
replace apigo.cc/gojs v0.0.1 => ../gojs

25
include/EventToken.h Normal file
View File

@ -0,0 +1,25 @@
#ifndef WEBVIEW_COMPAT_EVENTTOKEN_H
#define WEBVIEW_COMPAT_EVENTTOKEN_H
#ifdef _WIN32
// This compatibility header provides types used by MS WebView2. This header can
// be used as an alternative to the "EventToken.h" header normally provided by
// the Windows SDK. Depending on the MinGW distribution, this header may not be
// present, or it may be present with the name "eventtoken.h". The letter casing
// matters when cross-compiling on a system with case-sensitive file names.
#ifndef __eventtoken_h__
#ifdef __cplusplus
#include <cstdint>
#else
#include <stdint.h>
#endif
typedef struct EventRegistrationToken {
int64_t value;
} EventRegistrationToken;
#endif // __eventtoken_h__
#endif // _WIN32
#endif // WEBVIEW_COMPAT_EVENTTOKEN_H

31
plugin_run.go Normal file
View File

@ -0,0 +1,31 @@
package client
// import (
// "apigo.cc/apigo/gojs"
// "current-plugin"
// "fmt"
// "github.com/ssgo/u"
// "os"
// "strings"
// )
// func main() {
// testOK := false
// client.Bind("setTestOK", func(testIsOK bool) {
// testOK = testIsOK
// })
// if files, err := os.ReadDir("."); err == nil {
// for _, f := range files {
// if !f.IsDir() && strings.HasSuffix(f.Name(), "_test.js") {
// testName := f.Name()[0 : len(f.Name())-8]
// r, err := gojs.RunFile(f.Name(), nil)
// if err != nil || r != true || !testOK {
// fmt.Println(u.BRed("test "+testName+" failed"), r, err)
// } else {
// fmt.Println(u.Green("test "+testName), u.BGreen("OK"))
// }
// }
// }
// }
// }

3
runTest.bat Normal file
View File

@ -0,0 +1,3 @@
set CGO_CPPFLAGS="-I%cd%\include"
cd tests
go test -v -count=1 -ldflags="-H windowsgui" .

86
tests/build Normal file
View File

@ -0,0 +1,86 @@
#!/bin/bash
# 设置默认值
OS=${1:-linux}
ARCH=${2:-amd64}
EXT=""
LDFLAGS=""
# 根据目标操作系统和架构设置编译参数
case "$OS" in
windows)
GOOS=windows
;;
mac)
GOOS=darwin
;;
darwin)
GOOS=darwin
;;
linux)
GOOS=linux
;;
*)
echo "Unsupported OS: $OS"
exit 1
;;
esac
case "$ARCH" in
x64)
GOARCH=amd64
;;
amd64)
GOARCH=amd64
;;
x86)
GOARCH=386
;;
386)
GOARCH=386
;;
arm64)
GOARCH=arm64
;;
arm)
GOARCH=arm
;;
*)
echo "Unsupported ARCH: $ARCH"
exit 1
;;
esac
# 启用 CGO
export CGO_ENABLED=1
# 设置交叉编译工具链(如果需要)
if [ "$GOOS" = "windows" ]; then
EXT=.exe
CC=x86_64-w64-mingw32-gcc
CXX=x86_64-w64-mingw32-g++
LDFLAGS="-H windowsgui"
PWD=`pwd`
CGO_CPPFLAGS="-I${PWD}/include"
elif [ "$GOOS" = "darwin" ]; then
CC=o64-clang
CXX=o64-clang++
else
CC=gcc
CXX=g++
fi
export CC
# 编译
echo "Building for $GOOS/$GOARCH..."
# mkdir -p build
GOOS="${GOOS}" GOARCH="${GOARCH}" CC="${CC}" CXX="${CXX}" CGO_CPPFLAGS="${CGO_CPPFLAGS}" go build -o "dist/${GOOS}_${GOARCH}${EXT}" -ldflags="${LDFLAGS}" .
if [ $? -eq 0 ]; then
echo "Build successful: dist/${GOOS}_${GOARCH}${EXT}"
else
echo "Build failed"
exit 1
fi

32
tests/client.html Normal file
View File

@ -0,0 +1,32 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<script>
window.addEventListener('load', () => {
setTimeout(() => {
app.setTitle('测试标题')
alert('test')
app.setSize(1200, 400, "fixed")
setTimeout(() => {
setTestOK(true)
app.close()
}, 1000)
}, 1000)
})
</script>
</head>
<body>
<img src="logo.png" width="20"
onclick="showDialog('', ['No', 'Yes'], [{hint:'aaa',value:111},{hint:'bbb',value:222}]).then(v=>{console.info(v)})" />
<h1>Hello, world!</h1>
<br />
<button onclick="app.close()">关闭</button>
</div>
</body>
</html>

8
tests/client.js Normal file
View File

@ -0,0 +1,8 @@
import client from 'apigo.cc/gojs/client'
client.open({
width: 800,
height: 600,
title: 'Hello',
url: 'client.html',
})

29
tests/client_test.go Normal file
View File

@ -0,0 +1,29 @@
package client_test
import (
"fmt"
"testing"
"apigo.cc/gojs"
"apigo.cc/gojs/client"
)
func TestClient(t *testing.T) {
gojs.ExportForDev()
testOK := false
client.Bind("setTestOK", func(testIsOK bool) {
testOK = testIsOK
})
r, err := gojs.RunFile("client.js")
if err != nil {
t.Fatal(err)
}
gojs.WaitAll()
if !testOK {
t.Fatal("test failed")
} else {
fmt.Println("test OK", r)
}
}

BIN
tests/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB