-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathmuon.go
353 lines (266 loc) · 7.68 KB
/
muon.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package muon
import (
"encoding/json"
"errors"
"net"
"net/http"
"reflect"
"unsafe"
. "github.com/ImVexed/muon/ultralight"
)
// Window represents a single Ultralight instance
type Window struct {
wnd ULWindow
ov ULOverlay
view ULView
app ULApp
handler http.Handler
cfg *Config
callbacks map[string]*ipf
}
type ipf struct {
Function reflect.Value
ParamTypes []reflect.Type
}
// Config contains configurable controls for the Ultralight engine
type Config struct {
Title string
Height uint32
Width uint32
X int32
Y int32
Resizeable bool
Borderless bool
Titled bool
Maximizable bool
}
// New creates a Ultralight Window
func New(cfg *Config, handler http.Handler) *Window {
w := &Window{
cfg: cfg,
handler: handler,
callbacks: make(map[string]*ipf),
}
ufg := UlCreateConfig()
std := UlCreateSettings()
w.app = UlCreateApp(std, ufg)
mm := UlAppGetMainMonitor(w.app)
var hint uint32
if cfg.Resizeable {
hint |= 4
}
if cfg.Borderless {
hint |= 1
}
if cfg.Titled {
hint |= 2
} else {
w.cfg.Title = ""
}
if cfg.Maximizable {
hint |= 8
}
w.wnd = UlCreateWindow(mm, w.cfg.Width, w.cfg.Height, false, hint)
UlWindowSetTitle(w.wnd, w.cfg.Title)
UlAppSetWindow(w.app, w.wnd)
w.ov = UlCreateOverlay(w.wnd, w.cfg.Width, w.cfg.Height, w.cfg.X, w.cfg.Y)
UlWindowSetResizeCallback(w.wnd, resizeCallback(w.ov), nil)
w.view = UlOverlayGetView(w.ov)
return w
}
// Start sets up the Ultralight runtime and begins showing the Window
func (w *Window) Start() error {
addr, err := serveHandler(w.handler)
if err != nil {
return err
}
url := UlCreateString(addr)
defer UlDestroyString(url)
UlViewLoadURL(w.view, url)
UlAppRun(w.app)
return nil
}
var registerCount int
// Bind registers the given function to the given name in the Window's JS global object
func (w *Window) Bind(name string, function interface{}) {
f := &ipf{
Function: reflect.ValueOf(function),
}
t := f.Function.Type()
f.ParamTypes = make([]reflect.Type, t.NumIn())
for i := 0; i < t.NumIn(); i++ {
f.ParamTypes[i] = t.In(i)
}
if t.NumOut() > 1 {
panic("Too many return values!")
}
w.callbacks[name] = f
w.addFunction(name)
}
// Eval evaluates a given JavaScript string in the given Window view. `ret` is necessary for JSON serialization if an object is returned.
func (w *Window) Eval(js string, ret reflect.Type) (interface{}, error) {
us := UlCreateString(js)
defer UlDestroyString(us)
ref := UlViewEvaluateScript(w.view, us)
ctx := UlViewGetJSContext(w.view)
val, err := fromJSValue(ctx, ref, ret)
if err != nil {
return nil, err
}
return val.Interface(), nil
}
// Resize changes the given Window's size
func (w *Window) Resize(width int, height int) {
UlOverlayResize(w.ov, uint32(width), uint32(height))
}
// Move sets the Window's position to the given coordinates
func (w *Window) Move(x int, y int) {
UlOverlayMoveTo(w.ov, int32(x), int32(y))
}
func (w *Window) ipcCallback(ctx JSContextRef, functin JSObjectRef, thisObject JSObjectRef, argumentCount uint, arguments []JSValueRef, exception []JSValueRef) JSValueRef {
jsName := JSStringCreateWithUTF8CString("name")
defer JSStringRelease(jsName)
prop := JSObjectGetProperty(ctx, functin, jsName, nil)
jsProp := JSValueToStringCopy(ctx, prop, nil)
defer JSStringRelease(jsProp)
name := fromJSString(jsProp)
f, ok := w.callbacks[name]
if !ok {
return JSValueMakeNull(ctx)
}
params := make([]reflect.Value, argumentCount)
for i := uint(0); i < argumentCount; i++ {
val, err := fromJSValue(ctx, arguments[i], f.ParamTypes[i])
if err != nil {
panic(err)
}
params[i] = val
}
val := f.Function.Call(params)
if len(val) > 1 {
panic("Javascript does not support more than 1 return value!")
}
if len(val) == 0 {
return JSValueMakeNull(ctx)
}
return toJSValue(ctx, val[0])
}
func fromJSValue(ctx JSContextRef, value JSValueRef, rtype reflect.Type) (reflect.Value, error) {
if rtype == nil {
rtype = reflect.TypeOf(struct{}{})
}
var rv reflect.Value
var err error
if JSValueIsArray(ctx, value) {
l := JSStringCreateWithUTF8CString("length")
defer JSStringRelease(l)
obj := *(*JSObjectRef)(unsafe.Pointer(&value))
prop := JSObjectGetProperty(ctx, obj, l, nil)
length := int(JSValueToNumber(ctx, prop, nil))
if rtype.Kind() != reflect.Slice {
return reflect.Zero(rtype), errors.New("JS return is of type Array while Go type target is not")
}
values := reflect.MakeSlice(rtype, length, length)
for i := 0; i < length; i++ {
ref := JSObjectGetPropertyAtIndex(ctx, obj, uint32(i), nil)
val, err := fromJSValue(ctx, ref, rtype.Elem())
if err != nil {
return reflect.Zero(rtype), err
}
values.Index(i).Set(val)
}
return values, nil
}
switch JSValueGetType(ctx, value) {
case KJSTypeBoolean:
rv = reflect.ValueOf(JSValueToBoolean(ctx, value))
case KJSTypeNumber:
rv = reflect.ValueOf(JSValueToNumber(ctx, value, nil))
case KJSTypeString:
ref := JSValueToStringCopy(ctx, value, nil)
rv = reflect.ValueOf(fromJSString(ref))
JSStringRelease(ref)
case KJSTypeObject:
ref := JSValueCreateJSONString(ctx, value, 0, nil)
obj := reflect.New(rtype).Interface()
if err = json.Unmarshal([]byte(fromJSString(ref)), &obj); err == nil {
rv = reflect.Indirect(reflect.ValueOf(obj))
}
JSStringRelease(ref)
case KJSTypeUndefined, KJSTypeNull:
rv = reflect.Zero(rtype)
}
return rv, err
}
func fromJSString(str JSStringRef) string {
len := JSStringGetMaximumUTF8CStringSize(str)
data := make([]byte, len)
written := JSStringGetUTF8CString(str, data, len)
return string(data[:written-1])
}
func toJSValue(ctx JSContextRef, value reflect.Value) JSValueRef {
var jsv JSValueRef
var err error
switch value.Kind() {
case reflect.Float64:
jsv = JSValueMakeNumber(ctx, value.Float())
case reflect.Bool:
jsv = JSValueMakeBoolean(ctx, value.Bool())
case reflect.String:
str := JSStringCreateWithUTF8CString(value.String())
jsv = JSValueMakeString(ctx, str)
JSStringRelease(str)
case reflect.Ptr:
return toJSValue(ctx, reflect.Indirect(value))
case reflect.Struct:
if json, err := json.Marshal(value.Interface()); err == nil {
str := JSStringCreateWithUTF8CString(string(json))
jsv = JSValueMakeFromJSONString(ctx, str)
JSStringRelease(str)
}
case reflect.Slice, reflect.Array:
rets := make([]JSValueRef, value.Len())
for i := 0; i < value.Len(); i++ {
rets[i] = toJSValue(ctx, value.Index(i))
}
arr := JSObjectMakeArray(ctx, uint(len(rets)), rets, nil)
jsv = *(*JSValueRef)(unsafe.Pointer(&arr))
default:
panic("Not implemented!")
}
if err != nil {
return JSValueMakeNull(ctx)
}
return jsv
}
func (w *Window) addFunction(name string) {
ctx := UlViewGetJSContext(w.view)
gobj := JSContextGetGlobalObject(ctx)
fn := JSStringCreateWithUTF8CString(name)
defer JSStringRelease(fn)
fname := JSStringCreateWithUTF8CString("name")
defer JSStringRelease(fname)
fob := JSObjectMakeFunctionWithCallback(ctx, fn, w.ipcCallback)
JSObjectSetProperty(ctx, fob, fname, JSValueMakeString(ctx, fname), KJSPropertyAttributeNone, []JSValueRef{})
val := *(*JSValueRef)(unsafe.Pointer(&fob))
JSObjectSetProperty(ctx, gobj, fn, val, KJSPropertyAttributeNone, []JSValueRef{})
}
func resizeCallback(ov ULOverlay) func(userData unsafe.Pointer, width uint32, height uint32) {
return func(userData unsafe.Pointer, width uint32, height uint32) {
if height > 0 && width > 0 {
UlOverlayResize(ov, width, height)
}
}
}
func serveHandler(handler http.Handler) (string, error) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return "", err
}
go func() {
if err := http.Serve(ln, handler); err != nil {
panic(err)
}
}()
return "http://" + ln.Addr().String(), nil
}