-
Notifications
You must be signed in to change notification settings - Fork 3
/
ui.go
122 lines (101 loc) · 2.49 KB
/
ui.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
package glass
import (
"bytes"
_ "embed"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"github.com/hamba/logger/v2"
"github.com/vincent-petithory/dataurl"
"github.com/zserge/lorca"
)
var (
//go:embed webui/index.html
page []byte
//go:embed webui/wasm_exec.js
wasmExec []byte
//go:embed webui/fonts.css
fonts []byte
)
// newFunc is used for testing.
var newFunc = lorca.New
// UIConfig contains configuration for the UI.
type UIConfig struct {
Width int `yaml:"width"`
Height int `yaml:"height"`
Fullscreen bool `yaml:"fullscreen"`
CustomCSS []string `yaml:"customCss"`
}
// Validate validates the ui configuration.
func (c UIConfig) Validate() error {
if c.Width <= 0 || c.Height <= 0 {
return errors.New("config: ui width and height muse be greater than zero")
}
return nil
}
// UI implements a ui manager.
type UI struct {
win lorca.UI
}
// NewUI returns a new UI.
func NewUI(cfg UIConfig, log *logger.Logger) (*UI, error) {
// Add wasmExec to html page.
page = bytes.Replace(page, []byte("{{ .WASMExec }}"), wasmExec, 1)
args := []string{
"--disable-web-security",
"--test-type",
}
if cfg.Fullscreen {
args = append(args, "--start-fullscreen")
}
url := dataurl.New(page, "text/html")
win, err := newFunc(url.String(), "", cfg.Width, cfg.Height, args...)
if err != nil {
return nil, fmt.Errorf("could not create window: %w", err)
}
val := win.Eval("loadCSS(`fonts`, `" + string(fonts) + "`);")
if val.Err() != nil {
return nil, fmt.Errorf("could not load fonts: %w", err)
}
for i, cssPath := range cfg.CustomCSS {
b, err := os.ReadFile(filepath.Clean(cssPath))
if err != nil {
return nil, fmt.Errorf("could not read custom css %q: %w", cssPath, err)
}
name := "customCSS" + strconv.Itoa(i+1)
val := win.Eval("loadCSS(`" + name + "`, `" + string(b) + "`);")
if val.Err() != nil {
return nil, fmt.Errorf("could not load custom css %q: %w", cssPath, err)
}
}
ui := &UI{
win: win,
}
if err = ui.bindFuncs(log); err != nil {
return nil, err
}
return ui, nil
}
// Eval evaluates a javascript expression.
func (ui *UI) Eval(js string) (any, error) {
v := ui.win.Eval(js)
if v.Err() != nil {
return nil, v.Err()
}
if len(v.Bytes()) == 0 {
return nil, nil //nolint:nilnil
}
var i any
err := v.To(&i)
return i, err
}
// Done returns a channel signalling the UI being closed.
func (ui *UI) Done() <-chan struct{} {
return ui.win.Done()
}
// Close closes the ui.
func (ui *UI) Close() error {
return ui.win.Close()
}