feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
//go:build js
package web
import "github.com/egoist/mygo/internal/platform"
func (app) ListCookies(_ platform.DataStore, _ string, done func([]platform.Cookie, error)) {
done(nil, platform.ErrUnsupported)
}
func (app) SetCookie(_ platform.DataStore, _ platform.Cookie, done func(error)) {
done(platform.ErrUnsupported)
}
func (app) DeleteCookie(_ platform.DataStore, _ platform.CookieKey, done func(error)) {
done(platform.ErrUnsupported)
}
func (app) ClearCookies(_ platform.DataStore, done func(error)) { done(platform.ErrUnsupported) }
func (app) CompileContentRules(_, _, _ string, done func(any, error)) {
done(nil, platform.ErrUnsupported)
}
+270
View File
@@ -0,0 +1,270 @@
//go:build js
package web
import (
"path"
"slices"
"strconv"
"strings"
"syscall/js"
"time"
)
// Files dropped on a window have no paths in browsers: the backend reads
// them as they drop and keeps them at paths of its own, as
// /mygo-drop/3/photo.png, which FileDrop gives, and which os.Open,
// os.ReadFile, os.Stat and os.ReadDir read, through the fs object that Go's
// syscall package calls in browsers (wasm_exec.js's, whose functions fail
// there): the backend answers for its paths and passes the others on.
// dropRoot is the directory of the files dropped, one directory for each
// drop.
const dropRoot = "/mygo-drop"
// keptDrops is how many drops the backend keeps the files of: the oldest
// go, with their memory.
const keptDrops = 16
// dropped are the files dropped, by path.
type dropped struct {
files map[string]*droppedFile
drops []string // the directories of the drops kept, oldest first
n int
fds map[int]*openFile
fd int
}
type droppedFile struct {
data []byte
time time.Time
}
type openFile struct {
path string
f *droppedFile // nil for a directory
at int
}
var drops = dropped{files: map[string]*droppedFile{}, fds: map[int]*openFile{}, fd: 1 << 20}
// add keeps the files of a drop, by name, and returns their paths.
func (d *dropped) add(names []string, data [][]byte) []string {
d.n++
dir := dropRoot + "/" + strconv.Itoa(d.n)
d.drops = append(d.drops, dir)
if len(d.drops) > keptDrops {
old := d.drops[0]
d.drops = d.drops[1:]
for p := range d.files {
if strings.HasPrefix(p, old+"/") {
delete(d.files, p)
}
}
}
now := time.Now()
paths := make([]string, 0, len(names))
for i, name := range names {
// A name is a file's, never a path: browsers give no folders.
name = strings.ReplaceAll(name, "/", "_")
p := dir + "/" + name
for k := 2; d.files[p] != nil; k++ {
p = dir + "/" + strconv.Itoa(k) + "-" + name
}
d.files[p] = &droppedFile{data: data[i], time: now}
paths = append(paths, p)
}
return paths
}
// isDir reports whether p is the root of the drops or a drop's directory.
func (d *dropped) isDir(p string) bool {
return p == dropRoot || slices.Contains(d.drops, p)
}
// list returns the names in directory p.
func (d *dropped) list(p string) []string {
var names []string
if p == dropRoot {
for _, dir := range d.drops {
names = append(names, path.Base(dir))
}
return names
}
for f := range d.files {
if path.Dir(f) == p {
names = append(names, path.Base(f))
}
}
slices.Sort(names)
return names
}
// installFiles has the fs object answer for the paths of the files
// dropped.
func installFiles() {
fs := js.Global().Get("fs")
if fs.IsUndefined() {
return
}
ours := func(p js.Value) (string, bool) {
if p.Type() != js.TypeString {
return "", false
}
s := path.Clean(p.String())
return s, s == dropRoot || strings.HasPrefix(s, dropRoot+"/")
}
// The flags of opening to write, as the fs object numbers them (-1 in
// browsers, where it writes nothing).
writes := 0
for _, flag := range []string{"O_WRONLY", "O_RDWR", "O_CREAT", "O_TRUNC", "O_APPEND"} {
if v := fs.Get("constants").Get(flag); v.Type() == js.TypeNumber {
writes |= v.Int()
}
}
wrap := func(name string, fn func(args []js.Value, cb js.Value) bool) {
orig := fs.Get(name)
fs.Set(name, js.FuncOf(func(this js.Value, args []js.Value) any {
if len(args) > 0 && fn(args[:len(args)-1], args[len(args)-1]) {
return nil
}
return orig.Call("apply", this, js.ValueOf(toAny(args)))
}))
}
stat := func(args []js.Value, cb js.Value) bool {
p, ok := ours(args[0])
if !ok {
return false
}
if drops.isDir(p) {
cb.Invoke(js.Null(), statOf(nil, time.Now()))
} else if f := drops.files[p]; f != nil {
cb.Invoke(js.Null(), statOf(f, f.time))
} else {
cb.Invoke(fsError("ENOENT"))
}
return true
}
wrap("stat", stat)
wrap("lstat", stat)
wrap("open", func(args []js.Value, cb js.Value) bool {
p, ok := ours(args[0])
if !ok {
return false
}
f := drops.files[p]
switch {
case f == nil && !drops.isDir(p):
cb.Invoke(fsError("ENOENT"))
case len(args) > 1 && args[1].Type() == js.TypeNumber && args[1].Int()&writes != 0:
cb.Invoke(fsError("EROFS"))
default:
drops.fd++
drops.fds[drops.fd] = &openFile{path: p, f: f}
cb.Invoke(js.Null(), drops.fd)
}
return true
})
fd := func(v js.Value) *openFile {
if v.Type() != js.TypeNumber {
return nil
}
return drops.fds[v.Int()]
}
wrap("fstat", func(args []js.Value, cb js.Value) bool {
o := fd(args[0])
if o == nil {
return false
}
if o.f == nil {
cb.Invoke(js.Null(), statOf(nil, time.Now()))
} else {
cb.Invoke(js.Null(), statOf(o.f, o.f.time))
}
return true
})
wrap("read", func(args []js.Value, cb js.Value) bool {
o := fd(args[0])
if o == nil {
return false
}
if o.f == nil {
cb.Invoke(fsError("EISDIR"))
return true
}
buf, offset, length := args[1], args[2].Int(), args[3].Int()
at := o.at
if len(args) > 4 && args[4].Type() == js.TypeNumber {
at = args[4].Int() // pread
} else {
defer func() { o.at = at }()
}
n := min(length, max(len(o.f.data)-at, 0))
if n > 0 {
js.CopyBytesToJS(buf.Call("subarray", offset, offset+n), o.f.data[at:at+n])
at += n
}
cb.Invoke(js.Null(), n)
return true
})
wrap("close", func(args []js.Value, cb js.Value) bool {
if fd(args[0]) == nil {
return false
}
delete(drops.fds, args[0].Int())
cb.Invoke(js.Null())
return true
})
wrap("readdir", func(args []js.Value, cb js.Value) bool {
p, ok := ours(args[0])
if !ok {
return false
}
if !drops.isDir(p) {
cb.Invoke(fsError("ENOTDIR"))
return true
}
cb.Invoke(js.Null(), js.ValueOf(toAny(drops.list(p))))
return true
})
}
// statOf returns the stat of a file dropped, or of a directory for nil, as
// Node's fs gives it.
func statOf(f *droppedFile, t time.Time) js.Value {
mode, size := 0o40555, 0 // a directory, read only
if f != nil {
mode, size = 0o100444, len(f.data)
}
ms := float64(t.UnixMilli())
st := js.ValueOf(map[string]any{
"dev": 0, "ino": 0, "mode": mode, "nlink": 1, "uid": 0, "gid": 0, "rdev": 0,
"size": size, "blksize": 4096, "blocks": (size + 511) / 512,
"atimeMs": ms, "mtimeMs": ms, "ctimeMs": ms,
})
st.Set("isDirectory", isDirectory[f == nil])
return st
}
// isDirectory are the isDirectory methods of stats: of files and of
// directories.
var isDirectory = map[bool]js.Func{
false: js.FuncOf(func(js.Value, []js.Value) any { return false }),
true: js.FuncOf(func(js.Value, []js.Value) any { return true }),
}
// fsError returns an error of Node's fs, which Go's syscall package reads
// the code of.
func fsError(code string) js.Value {
e := js.Global().Get("Error").New(code)
e.Set("code", code)
return e
}
func toAny[T any](s []T) []any {
out := make([]any, len(s))
for i, v := range s {
out[i] = v
}
return out
}
+308
View File
@@ -0,0 +1,308 @@
//go:build js
package web
import (
"strings"
"syscall/js"
"github.com/egoist/mygo/internal/platform"
)
// menuCSS styles context menus, which the page draws with HTML: browsers
// show no menus of a page's own.
const menuCSS = `
.mygo-menu{position:fixed;z-index:2147483647;min-width:180px;padding:5px;box-sizing:border-box;border-radius:8px;
font:13px system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:#1d1d1f;background:rgba(246,246,246,.96);
-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);box-shadow:0 0 0 .5px rgba(0,0,0,.2),0 8px 24px rgba(0,0,0,.18);
user-select:none;-webkit-user-select:none;cursor:default;outline:none}
.mygo-menu-item{display:flex;align-items:center;gap:16px;height:22px;padding:0 10px 0 22px;border-radius:4px;position:relative;white-space:nowrap}
.mygo-menu-item[data-checked]::before{content:"✓";position:absolute;left:7px;font-size:11px}
.mygo-menu-item>.label{flex:1}
.mygo-menu-item>.accel{opacity:.5}
.mygo-menu-item .subtitle{display:block;margin-bottom:3px;font-size:11px;opacity:.6}
.mygo-menu-item.on{background:#0a64d6;color:#fff}
.mygo-menu-item.on>.accel{opacity:.8}
.mygo-menu-item[aria-disabled=true]{opacity:.35}
.mygo-menu-separator{height:1px;margin:5px 10px;background:rgba(0,0,0,.12)}
@media (prefers-color-scheme:dark){.mygo-menu{color:#f5f5f7;background:rgba(40,40,42,.96);box-shadow:0 0 0 .5px rgba(255,255,255,.18),0 8px 24px rgba(0,0,0,.4)}
.mygo-menu-separator{background:rgba(255,255,255,.14)}}
`
var menuStyled bool
// popup is a context menu shown on the page.
type popup struct {
b *Backend
w *window
menus []js.Value // the menu and its submenus open
funcs []js.Func
// removers remove the listeners of the page's events.
removers []func()
done bool
// rtl lays the menus out right to left (Menu.RightToLeft).
rtl bool
}
// PopupMenu shows m at pos in w's content, or where the pointer last
// pressed, and waits until the user chooses an item or dismisses it,
// handling events meanwhile.
func (b *Backend) PopupMenu(m *platform.Menu, pw platform.Window, pos *platform.Point) {
w, _ := pw.(*window)
if w == nil {
b.mu.Lock()
if n := len(b.windows); n > 0 {
w = b.windows[n-1]
}
b.mu.Unlock()
}
if w == nil || w.closed || m == nil || len(m.Items) == 0 {
return
}
doc := js.Global().Get("document")
if !menuStyled {
menuStyled = true
style := doc.Call("createElement", "style")
style.Set("textContent", menuCSS)
doc.Get("head").Call("appendChild", style)
}
x, y := w.s.downX, w.s.downY
if pos != nil {
x, y = float64(pos.X), float64(pos.Y)
}
r := w.s.canvas.Call("getBoundingClientRect")
x += r.Get("left").Float()
y += r.Get("top").Float()
p := &popup{b: b, w: w, rtl: m.RightToLeft}
chosen := 0
p.open(m, x, y, 0, func(id int) { chosen = id })
// Dismissed by a press elsewhere, Escape, or the page losing focus.
p.listen(doc, "pointerdown", func(e js.Value) {
if p.inside(e.Get("target")) {
// The window keeps the keyboard.
e.Call("preventDefault")
return
}
p.done = true
})
p.listen(doc, "keydown", func(e js.Value) {
if e.Get("key").String() == "Escape" {
e.Call("preventDefault")
e.Call("stopPropagation")
p.done = true
}
})
p.listen(js.Global(), "blur", func(e js.Value) {
// The page's, not an element's, which capturing sees too.
if e.Get("target").Equal(js.Global()) {
p.done = true
}
})
for !p.done && !w.closed {
b.Step()
}
for _, el := range p.menus {
el.Call("remove")
}
for _, remove := range p.removers {
remove()
}
for _, l := range p.funcs {
l.Release()
}
w.s.focus()
if chosen != 0 {
w.h.MenuItemClicked(chosen)
}
}
// listen adds a listener for the life of the menu, capturing, so that the
// window's own listeners do not see what the menu takes.
func (p *popup) listen(target js.Value, event string, fn func(e js.Value)) {
f := js.FuncOf(func(_ js.Value, args []js.Value) any {
p.b.sync(func() { fn(args[0]) })
return nil
})
p.funcs = append(p.funcs, f)
target.Call("addEventListener", event, f, true)
p.removers = append(p.removers, func() { target.Call("removeEventListener", event, f, true) })
}
func (p *popup) inside(el js.Value) bool {
for _, m := range p.menus {
if m.Call("contains", el).Bool() {
return true
}
}
return false
}
// open shows menu m with its top left at (x, y), page pixels, as the menu
// of depth level, closing deeper ones.
func (p *popup) open(m *platform.Menu, x, y float64, level int, choose func(int)) {
for len(p.menus) > level {
p.menus[len(p.menus)-1].Call("remove")
p.menus = p.menus[:len(p.menus)-1]
}
doc := js.Global().Get("document")
el := doc.Call("createElement", "div")
el.Set("className", "mygo-menu")
el.Call("setAttribute", "role", "menu")
if p.rtl {
el.Call("setAttribute", "dir", "rtl")
}
for _, it := range m.Items {
if !it.Visible {
continue
}
if it.Type == platform.MenuItemSeparator {
sep := doc.Call("createElement", "div")
sep.Set("className", "mygo-menu-separator")
sep.Call("setAttribute", "role", "separator")
el.Call("appendChild", sep)
continue
}
row := doc.Call("createElement", "div")
row.Set("className", "mygo-menu-item")
row.Call("setAttribute", "role", "menuitem")
row.Call("setAttribute", "aria-disabled", !it.Enabled)
if it.Checked && (it.Type == platform.MenuItemCheckbox || it.Type == platform.MenuItemRadio) {
row.Call("setAttribute", "data-checked", "")
}
label := doc.Call("createElement", "span")
label.Set("className", "label")
label.Set("textContent", strings.ReplaceAll(it.LabelWithBadge(), "&", ""))
if it.Subtitle != "" {
row.Get("style").Set("height", "auto")
sub := doc.Call("createElement", "span")
sub.Set("className", "subtitle")
sub.Set("textContent", it.Subtitle)
label.Call("appendChild", sub)
}
row.Call("appendChild", label)
accel := doc.Call("createElement", "span")
accel.Set("className", "accel")
if it.Type == platform.MenuItemSubmenu {
if p.rtl {
accel.Set("textContent", "‹")
} else {
accel.Set("textContent", "›")
}
} else {
accel.Set("textContent", accelText(it.Accelerator, p.b.mac))
}
row.Call("appendChild", accel)
el.Call("appendChild", row)
p.on(row, "pointerenter", func(js.Value) {
for k := range el.Get("children").Length() {
el.Get("children").Index(k).Get("classList").Call("remove", "on")
}
if !it.Enabled {
return
}
row.Get("classList").Call("add", "on")
if it.Type == platform.MenuItemSubmenu && it.Submenu != nil {
r := row.Call("getBoundingClientRect")
x := r.Get("right").Float() + 2
if p.rtl {
x = r.Get("left").Float() - 2
}
p.open(it.Submenu, x, r.Get("top").Float()-5, level+1, choose)
} else {
p.open(&platform.Menu{}, 0, 0, level+1, choose)
}
})
p.on(row, "pointerup", func(js.Value) {
if it.Enabled && it.Type != platform.MenuItemSubmenu {
choose(it.ID)
p.done = true
}
})
}
if el.Get("children").Length() == 0 {
return
}
doc.Get("body").Call("appendChild", el)
// Kept on the page.
vw, vh := js.Global().Get("innerWidth").Float(), js.Global().Get("innerHeight").Float()
r := el.Call("getBoundingClientRect")
if p.rtl {
// Its top right corner at x.
x = max(x-r.Get("width").Float(), 4)
}
if x+r.Get("width").Float() > vw {
x = max(vw-r.Get("width").Float()-4, 0)
}
if y+r.Get("height").Float() > vh {
y = max(vh-r.Get("height").Float()-4, 0)
}
st := el.Get("style")
st.Set("left", ftoa(x)+"px")
st.Set("top", ftoa(y)+"px")
p.menus = append(p.menus, el)
}
// on adds a listener to an element of the menu.
func (p *popup) on(el js.Value, event string, fn func(e js.Value)) {
f := js.FuncOf(func(_ js.Value, args []js.Value) any {
p.b.sync(func() {
if !p.done {
fn(args[0])
}
})
return nil
})
p.funcs = append(p.funcs, f)
el.Call("addEventListener", event, f)
}
// accelText writes an accelerator as menus show it: with the symbols of
// macOS on a Mac.
func accelText(a string, mac bool) string {
if a == "" {
return ""
}
parts := strings.Split(a, "+")
var b strings.Builder
for i, part := range parts {
last := i == len(parts)-1
switch strings.ToLower(part) {
case "cmdorctrl", "commandorcontrol":
if mac {
b.WriteString("⌘")
} else {
b.WriteString("Ctrl+")
}
case "cmd", "command", "super", "meta":
if mac {
b.WriteString("⌘")
} else {
b.WriteString("Win+")
}
case "ctrl", "control":
if mac {
b.WriteString("⌃")
} else {
b.WriteString("Ctrl+")
}
case "alt", "option":
if mac {
b.WriteString("⌥")
} else {
b.WriteString("Alt+")
}
case "shift":
if mac {
b.WriteString("⇧")
} else {
b.WriteString("Shift+")
}
default:
if last {
b.WriteString(strings.ToUpper(part[:1]) + part[1:])
}
}
}
return b.String()
}
+29
View File
@@ -0,0 +1,29 @@
//go:build js
package web
import (
"syscall/js"
"github.com/egoist/mygo/internal/platform"
)
func (b *Backend) Network() platform.Network { return network{b} }
// network is the browser's navigator.onLine, which tells no cost.
type network struct{ b *Backend }
func (network) Status() platform.NetworkStatus {
return platform.NetworkStatus{Online: js.Global().Get("navigator").Get("onLine").Bool()}
}
// Watch listens to the window's online and offline events.
func (n network) Watch() {
changed := n.b.funcOf(func(js.Value, []js.Value) any {
n.b.sync(func() { n.b.h.NetworkChanged(n.Status()) })
return nil
})
for _, event := range []string{"online", "offline"} {
js.Global().Call("addEventListener", event, changed)
}
}
+115
View File
@@ -0,0 +1,115 @@
//go:build js
package web
import (
"bytes"
"syscall/js"
"time"
"github.com/egoist/mygo/internal/platform"
)
func (b *Backend) NowPlaying() platform.NowPlaying { return nowPlaying{b} }
// nowPlaying is the page's Media Session (navigator.mediaSession), which
// browsers show in their media controls and answer the media keys with.
type nowPlaying struct{ b *Backend }
var (
// mediaActions are the session's actions, by the command each sends,
// and their handlers, made once.
mediaActions = []struct {
name string
cmd platform.MediaCommand
}{
{"play", platform.MediaPlay},
{"pause", platform.MediaPause},
{"stop", platform.MediaStop},
{"nexttrack", platform.MediaNext},
{"previoustrack", platform.MediaPrevious},
{"seekto", platform.MediaSeek},
}
mediaHandlers []js.Func
artworkURL string // the object URL of the artwork shown
)
func (n nowPlaying) Set(info *platform.NowPlayingInfo) {
session := js.Global().Get("navigator").Get("mediaSession")
if session.IsUndefined() {
return
}
if mediaHandlers == nil {
for _, a := range mediaActions {
cmd := a.cmd
mediaHandlers = append(mediaHandlers, n.b.funcOf(func(_ js.Value, args []js.Value) any {
var pos time.Duration
if cmd == platform.MediaSeek && len(args) > 0 {
pos = time.Duration(args[0].Get("seekTime").Float() * float64(time.Second))
}
n.b.sync(func() { n.b.h.MediaCommand(cmd, pos) })
return nil
}))
}
}
if artworkURL != "" {
js.Global().Get("URL").Call("revokeObjectURL", artworkURL)
artworkURL = ""
}
if info == nil {
session.Set("metadata", js.Null())
session.Set("playbackState", "none")
for _, a := range mediaActions {
setActionHandler(session, a.name, js.Null())
}
return
}
meta := map[string]any{"title": info.Title, "artist": info.Artist, "album": info.Album}
if len(info.Artwork) > 0 {
typ := "image/jpeg"
if bytes.HasPrefix(info.Artwork, []byte("\x89PNG")) {
typ = "image/png"
}
data := js.Global().Get("Uint8Array").New(len(info.Artwork))
js.CopyBytesToJS(data, info.Artwork)
blob := js.Global().Get("Blob").New([]any{data}, map[string]any{"type": typ})
artworkURL = js.Global().Get("URL").Call("createObjectURL", blob).String()
meta["artwork"] = []any{map[string]any{"src": artworkURL, "type": typ}}
}
session.Set("metadata", js.Global().Get("MediaMetadata").New(meta))
state := info.State
if state == "stopped" {
state = "none"
}
session.Set("playbackState", state)
for i, a := range mediaActions {
h := js.Null()
if info.Commands&a.cmd != 0 {
h = mediaHandlers[i].Value
}
setActionHandler(session, a.name, h)
}
if session.Get("setPositionState").Type() == js.TypeFunction {
if info.Duration > 0 {
call(session, "setPositionState", map[string]any{
"duration": info.Duration.Seconds(),
"position": min(info.Position, info.Duration).Seconds(),
"playbackRate": info.Rate,
})
} else {
call(session, "setPositionState")
}
}
}
// setActionHandler sets the handler of an action, which browsers that do
// not know the action reject.
func setActionHandler(session js.Value, action string, h js.Value) {
call(session, "setActionHandler", action, h)
}
// call calls a method, ignoring what it throws.
func call(v js.Value, method string, args ...any) {
defer func() { _ = recover() }()
v.Call(method, args...)
}
+9
View File
@@ -0,0 +1,9 @@
//go:build js
package web
import "github.com/egoist/mygo/internal/platform"
func (app) AddRecentDocument(string) error { return errUnsupported }
func (app) ClearRecentDocuments() error { return errUnsupported }
func (app) SetJumpList(platform.JumpList) error { return errUnsupported }
+13
View File
@@ -0,0 +1,13 @@
//go:build js
package web
import "github.com/egoist/mygo/internal/platform"
func (*Backend) Secrets() platform.Secrets { return secrets{} }
type secrets struct{}
func (secrets) SetSecret(string, string, []byte) error { return platform.ErrUnsupported }
func (secrets) Secret(string, string) ([]byte, error) { return nil, platform.ErrUnsupported }
func (secrets) DeleteSecret(string, string) error { return platform.ErrUnsupported }
+882
View File
@@ -0,0 +1,882 @@
//go:build js
package web
import (
"log"
"math"
"strconv"
"syscall/js"
"unicode/utf8"
"github.com/egoist/mygo/internal/gpu/gl"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/transfer"
)
// surface is the canvas of a window, drawn with WebGL 2, or in memory and
// shown with a 2D context where the browser has no WebGL 2. A textarea out
// of sight has the keyboard while the window has: input methods compose
// in it, at the caret of the content, and its clipboard events carry the
// clipboard. Its inputmode is "none" while nothing in the content takes
// text, so that touch devices, which show their keyboard for a focused
// textarea, show it only for a text input.
type surface struct {
w *window
canvas, input js.Value
gl *gl.Context
presenter gl.Presenter
ctx2d js.Value
image js.Value // ImageData of the frames drawn in memory
rgba []byte
// width and height are the canvas's size in DIPs, CSS pixels, and
// scale the device pixels of one.
width, height, scale float64
pending bool
request js.Value // the requestAnimationFrame pending
frame js.Func
funcs []js.Func
global []listener
observer js.Value
closed bool
composing bool
text platform.TextInputState
// copied tells that a key copying went to the content, which the copy
// event that follows does not repeat.
copied bool
// held are the keys the content got pressed and not yet released,
// whose key ups an input method or Command may keep (key).
held platform.HeldKeys
// downX and downY place the last press, where a context menu opens.
downX, downY float64
clicks platform.ClickCounter
}
func newSurface(w *window) (*surface, error) {
doc := js.Global().Get("document")
s := &surface{w: w, scale: 1}
s.canvas = doc.Call("createElement", "canvas")
s.canvas.Set("tabIndex", -1)
s.input = doc.Call("createElement", "textarea")
for k, v := range map[string]string{"autocomplete": "off", "autocorrect": "off", "autocapitalize": "off", "spellcheck": "false", "tabindex": "-1", "inputmode": "none"} {
s.input.Call("setAttribute", k, v)
}
w.el.Call("appendChild", s.canvas)
w.el.Call("appendChild", s.input)
ctx, err := gl.NewContext(s.canvas)
if err != nil {
log.Printf("mygo: drawing in memory: %v", err)
s.ctx2d = s.canvas.Call("getContext", "2d")
} else {
s.gl = ctx
}
s.frame = js.FuncOf(func(js.Value, []js.Value) any {
w.b.sync(s.drawFrame)
return nil
})
s.listen()
return s, nil
}
// on adds a listener of the browser's events to target, which handles them
// on the main goroutine.
func (s *surface) on(target js.Value, event string, passive bool, fn func(e js.Value)) {
f := js.FuncOf(func(_ js.Value, args []js.Value) any {
s.w.b.sync(func() {
if !s.closed {
fn(args[0])
}
})
return nil
})
s.funcs = append(s.funcs, f)
target.Call("addEventListener", event, f, map[string]any{"passive": passive})
// Listeners on window and document go with the surface.
if target.Equal(js.Global()) || target.Equal(js.Global().Get("document")) {
s.global = append(s.global, listener{target, event, f})
}
}
type listener struct {
target js.Value
event string
fn js.Func
}
func (s *surface) send(ev platform.SurfaceEvent) bool {
if !s.held.Track(ev) {
return false
}
return s.w.h.SurfaceEvent(ev)
}
func (s *surface) listen() {
c, in := s.canvas, s.input
ro := js.Global().Get("ResizeObserver")
if !ro.IsUndefined() {
f := js.FuncOf(func(js.Value, []js.Value) any {
s.w.b.sync(func() {
if !s.closed && s.measure() {
s.RequestFrame()
}
})
return nil
})
s.funcs = append(s.funcs, f)
s.observer = ro.New(f)
s.observer.Call("observe", c)
}
s.on(js.Global(), "resize", true, func(js.Value) {
if s.measure() {
s.RequestFrame()
}
})
s.on(js.Global().Get("document"), "visibilitychange", true, func(js.Value) {
if s.Occluded() {
s.send(platform.SurfaceEvent{Kind: platform.SurfaceHidden})
} else {
s.send(platform.SurfaceEvent{Kind: platform.SurfaceShown})
s.RequestFrame()
}
})
if s.gl != nil {
s.on(c, "webglcontextlost", false, func(e js.Value) { e.Call("preventDefault") })
s.on(c, "webglcontextrestored", true, func(js.Value) {
s.gl.Renew()
s.presenter = gl.Presenter{}
s.send(platform.SurfaceEvent{Kind: platform.SurfaceRenew})
})
}
// The pointer is the primary one of its kind (isPrimary): the mouse,
// or the first finger or pen down. The others, as a second finger on
// a touchscreen, neither press nor move it, as on Windows and Linux,
// where a second finger presses nothing either: it would take the
// press of the first, and end it as it lifts. Every finger comes as a
// touch of its own besides (touch).
s.on(c, "pointermove", true, func(e js.Value) {
s.touch(e, platform.TouchMove)
if !primary(e) {
return
}
x, y := s.point(e)
pointer, pressure := device(e)
s.send(platform.SurfaceEvent{Kind: platform.PointerMove, X: x, Y: y, Mods: s.mods(e), Pointer: pointer, Pressure: pressure})
// A button pressed or released while another is held comes as a
// move, which pointerdown and pointerup leave out; the desktop's
// windows hear each button.
if kind, b, ok := chord(e.Get("button").Int(), e.Get("buttons").Int()); ok {
ev := platform.SurfaceEvent{Kind: kind, X: x, Y: y, Button: b, Mods: s.mods(e), Pointer: pointer, Pressure: pressure}
if kind == platform.PointerDown {
s.downX, s.downY = x, y
ev.Clicks = s.clicks.Press(b, x, y, uint32(e.Get("timeStamp").Float()), platform.DefaultDoubleClick)
}
s.send(ev)
}
})
s.on(c, "pointerdown", false, func(e js.Value) {
e.Call("preventDefault")
s.touch(e, platform.TouchDown)
if !primary(e) {
return
}
s.focus()
x, y := s.point(e)
button := e.Get("button").Int()
switch button {
case 3, 4:
k := platform.KeyBack
if button == 4 {
k = platform.KeyForward
}
s.send(platform.SurfaceEvent{Kind: platform.KeyPressed, Key: k, Mods: s.mods(e)})
s.send(platform.SurfaceEvent{Kind: platform.KeyReleased, Key: k, Mods: s.mods(e)})
return
}
c.Call("setPointerCapture", e.Get("pointerId"))
b := buttonOf(button)
s.downX, s.downY = x, y
clicks := s.clicks.Press(b, x, y, uint32(e.Get("timeStamp").Float()), platform.DefaultDoubleClick) // browsers tell no double-click settings
pointer, pressure := device(e)
s.send(platform.SurfaceEvent{Kind: platform.PointerDown, X: x, Y: y, Button: b, Clicks: clicks, Mods: s.mods(e), Pointer: pointer, Pressure: pressure})
})
s.on(c, "pointerup", true, func(e js.Value) {
s.touch(e, platform.TouchUp)
if !primary(e) {
return
}
button := e.Get("button").Int()
if button == 3 || button == 4 {
return
}
x, y := s.point(e)
pointer, _ := device(e)
s.send(platform.SurfaceEvent{Kind: platform.PointerUp, X: x, Y: y, Button: buttonOf(button), Mods: s.mods(e), Pointer: pointer})
})
// The browser took the pointer, as a touch it scrolls or zooms the
// page with, or one the system took: its buttons go up with no
// release, and the press commits nothing.
s.on(c, "pointercancel", true, func(e js.Value) {
s.touch(e, platform.TouchCancel)
if !primary(e) {
return
}
x, y := s.point(e)
pointer, _ := device(e)
s.send(platform.SurfaceEvent{Kind: platform.PointerCancel, X: x, Y: y, Mods: s.mods(e), Pointer: pointer})
})
s.on(c, "pointerleave", true, func(e js.Value) {
if !primary(e) {
return
}
s.send(platform.SurfaceEvent{Kind: platform.PointerLeave})
})
// iOS sends a tap's mouse events even though its pointerdown was
// canceled: the mousedown would move the focus to the canvas, and the
// touch keyboard would hide as soon as it showed.
s.on(c, "mousedown", false, func(e js.Value) { e.Call("preventDefault") })
s.on(c, "contextmenu", false, func(e js.Value) { e.Call("preventDefault") })
s.on(c, "wheel", false, func(e js.Value) {
e.Call("preventDefault")
x, y := s.point(e)
dx, dy := e.Get("deltaX").Float(), e.Get("deltaY").Float()
precise := true
switch e.Get("deltaMode").Int() {
case 1: // lines
dx, dy, precise = dx*lineHeight, dy*lineHeight, false
case 2: // pages
dx, dy, precise = dx*s.width, dy*s.height, false
default:
// A wheel's notches, which browsers give as pixels too.
if w := e.Get("wheelDeltaY"); w.Type() == js.TypeNumber && w.Int() != 0 && w.Int()%120 == 0 {
precise = false
}
}
if precise && e.Get("ctrlKey").Bool() {
// A touchpad's pinch, which Chrome and Firefox send as
// scrolling with Control held, as they do Control and two
// fingers: Chrome scrolls 100 pixels by the natural log of
// the scale.
s.send(platform.SurfaceEvent{Kind: platform.PointerZoom, X: x, Y: y, Scale: math.Exp(-dy / 100), Mods: s.mods(e)})
return
}
s.send(platform.SurfaceEvent{Kind: platform.PointerScroll, X: x, Y: y, DX: dx, DY: dy, Precise: precise, Mods: s.mods(e)})
})
// Safari sends pinches as gesture events instead, whose scale is from
// 1 as the pinch began; without preventDefault it zooms the page.
pinch := 1.0
gesture := func(e js.Value) {
e.Call("preventDefault")
scale := e.Get("scale").Float()
if e.Get("type").String() == "gesturestart" {
pinch = 1
}
if scale > 0 && pinch > 0 && scale != pinch {
x, y := s.point(e)
s.send(platform.SurfaceEvent{Kind: platform.PointerZoom, X: x, Y: y, Scale: scale / pinch, Mods: s.mods(e)})
}
pinch = scale
}
s.on(c, "gesturestart", false, gesture)
s.on(c, "gesturechange", false, gesture)
// Files dragged over the canvas, and dropped: their bytes are read, as
// browsers give them, before the drop goes to the content (files.go).
// The browser opens no file dropped on the window, which would leave
// the app, whether the content takes it or not.
files := func(e js.Value) bool {
types := e.Get("dataTransfer").Get("types")
return !types.IsNull() && !types.IsUndefined() && types.Call("includes", "Files").Bool()
}
over := func(e js.Value) {
if !files(e) {
return
}
e.Call("preventDefault")
x, y := s.point(e)
effect := "none"
if s.send(platform.SurfaceEvent{Kind: platform.FileDragOver, X: x, Y: y}) {
effect = "copy"
}
e.Get("dataTransfer").Set("dropEffect", effect)
}
s.on(c, "dragenter", false, over)
s.on(c, "dragover", false, over)
s.on(c, "dragleave", true, func(e js.Value) {
if files(e) {
s.send(platform.SurfaceEvent{Kind: platform.FileDragLeave})
}
})
s.on(c, "drop", false, func(e js.Value) {
if !files(e) {
return
}
e.Call("preventDefault")
x, y := s.point(e)
list := e.Get("dataTransfer").Get("files")
names := make([]string, list.Length())
reads := make([]any, list.Length())
for i := range names {
f := list.Index(i)
names[i] = f.Get("name").String()
reads[i] = f.Call("arrayBuffer")
}
var done js.Func
done = js.FuncOf(func(_ js.Value, args []js.Value) any {
done.Release()
results := args[0]
s.w.b.sync(func() {
// Folders have no bytes to read: they are left out.
var kept []string
var data [][]byte
for i, name := range names {
r := results.Index(i)
if r.Get("status").String() != "fulfilled" {
continue
}
buf := js.Global().Get("Uint8Array").New(r.Get("value"))
b := make([]byte, buf.Length())
js.CopyBytesToGo(b, buf)
kept, data = append(kept, name), append(data, b)
}
if s.closed {
return
}
if len(kept) == 0 {
s.send(platform.SurfaceEvent{Kind: platform.FileDragLeave})
return
}
s.send(platform.SurfaceEvent{Kind: platform.FileDrop, X: x, Y: y, Files: drops.add(kept, data)})
})
return nil
})
js.Global().Get("Promise").Call("allSettled", reads).Call("then", done)
})
s.on(in, "focus", true, func(js.Value) {
s.w.focused = true
s.w.h.Focused()
s.send(platform.SurfaceEvent{Kind: platform.SurfaceFocus})
})
s.on(in, "blur", true, func(js.Value) {
s.w.focused = false
s.send(platform.SurfaceEvent{Kind: platform.SurfaceBlur})
s.w.h.Blurred()
})
s.on(in, "keydown", false, func(e js.Value) { s.key(e, true) })
s.on(in, "keyup", false, func(e js.Value) { s.key(e, false) })
s.on(in, "beforeinput", false, func(e js.Value) {
switch e.Get("inputType").String() {
case "insertText":
if !e.Get("isComposing").Bool() && !s.composing {
e.Call("preventDefault")
if t := e.Get("data"); t.Type() == js.TypeString && t.String() != "" {
s.send(platform.SurfaceEvent{Kind: platform.TextInput, Text: t.String()})
}
}
case "insertCompositionText", "deleteCompositionText", "insertFromComposition":
default:
// Keys did what the rest do (Enter, Backspace, …); a paste
// comes as its own event.
e.Call("preventDefault")
}
})
s.on(in, "compositionstart", true, func(js.Value) { s.composing = true })
s.on(in, "compositionupdate", true, func(e js.Value) {
t := e.Get("data").String()
s.send(platform.SurfaceEvent{Kind: platform.TextComposition, Text: t, Caret: utf8.RuneCountInString(t)})
})
s.on(in, "compositionend", true, func(e js.Value) {
s.composing = false
s.send(platform.SurfaceEvent{Kind: platform.TextComposition})
if t := e.Get("data"); t.Type() == js.TypeString && t.String() != "" {
s.send(platform.SurfaceEvent{Kind: platform.TextInput, Text: t.String()})
}
in.Set("value", "")
})
s.on(in, "copy", false, func(e js.Value) { s.copy(e, "copy") })
s.on(in, "cut", false, func(e js.Value) { s.copy(e, "cut") })
s.on(in, "paste", false, func(e js.Value) {
e.Call("preventDefault")
data := e.Get("clipboardData")
if data.IsNull() || data.IsUndefined() {
return
}
// The text formats pasted: plain text, HTML, and those of apps.
var reps []transfer.Representation
types := data.Get("types")
for i := range types.Length() {
f := types.Index(i).String()
if f == "Files" {
continue
}
if v := data.Call("getData", f).String(); v != "" {
reps = append(reps, transfer.Bytes(transfer.Format(f), []byte(v)))
}
}
s.w.b.mu.Lock()
s.w.b.clip = data.Call("getData", "text/plain").String()
s.w.b.clipData = transfer.Data{}
if len(reps) > 0 {
s.w.b.clipData = transfer.New(transfer.NewItem(reps...))
}
s.w.b.mu.Unlock()
s.send(platform.SurfaceEvent{Kind: platform.SurfaceCommand, Text: "paste"})
})
}
// lineHeight is how many DIPs a line of a wheel scrolls.
const lineHeight = 16
// copy has the content copy, or cut, its selection, and gives the browser
// the text, which the clipboard event carries to the system's clipboard.
func (s *surface) copy(e js.Value, cmd string) {
e.Call("preventDefault")
if !s.copied {
s.send(platform.SurfaceEvent{Kind: platform.SurfaceCommand, Text: cmd})
}
s.copied = false
s.w.b.mu.Lock()
text, all := s.w.b.clip, s.w.b.clipData
s.w.b.mu.Unlock()
if data := e.Get("clipboardData"); !data.IsNull() && !data.IsUndefined() && text != "" {
data.Call("setData", "text/plain", text)
// The other text formats copied, as a rich text's HTML.
for _, f := range all.Formats() {
if f == transfer.Text || f == transfer.FileList || f == transfer.PNG {
continue
}
if b, err := all.Read(f); err == nil {
data.Call("setData", string(f), string(b))
}
}
}
}
func buttonOf(b int) int {
switch b {
case 1:
return 2
case 2:
return 1
}
return 0
}
// primary reports whether a pointer event is the primary pointer's, as
// the mouse is; browsers without isPrimary have the mouse alone.
func primary(e js.Value) bool {
p := e.Get("isPrimary")
return p.Type() != js.TypeBoolean || p.Bool()
}
// touch sends a finger's pointer event as a touch of kind, by its
// pointerId, with the size of its contact, for the views that follow each
// finger (platform.TouchDown): the primary finger is the pointer as well.
func (s *surface) touch(e js.Value, kind platform.SurfaceEventKind) {
if t := e.Get("pointerType"); t.Type() != js.TypeString || t.String() != "touch" {
return
}
x, y := s.point(e)
_, pressure := device(e)
w, h := contact(e)
s.send(platform.SurfaceEvent{Kind: kind, ID: uint64(e.Get("pointerId").Int()), X: x, Y: y, Mods: s.mods(e), Pressure: pressure, Width: w, Height: h})
}
// contact returns the size of a finger's contact of a pointer event, in
// CSS pixels (width and height), or 0 where the browser does not tell it:
// it reports 1 by 1 then, as for a mouse.
func contact(e js.Value) (w, h float64) {
wv, hv := e.Get("width"), e.Get("height")
if wv.Type() != js.TypeNumber || hv.Type() != js.TypeNumber {
return 0, 0
}
if w, h = wv.Float(), hv.Float(); w <= 1 && h <= 1 {
return 0, 0
}
return w, h
}
// device returns the device of a pointer event (pointerType) and its
// pressure, which browsers give a mouse too: 0.5 while a button is down.
func device(e js.Value) (platform.PointerKind, float64) {
k := platform.PointerMouse
if t := e.Get("pointerType"); t.Type() == js.TypeString {
switch t.String() {
case "pen":
k = platform.PointerPen
case "touch":
k = platform.PointerTouch
}
}
if p := e.Get("pressure"); p.Type() == js.TypeNumber {
return k, p.Float()
}
return k, 0
}
// chord returns the press or release of button, a DOM pointermove's, with
// buttons the DOM's buttons held after it: a button going down or up while
// another is held. ok is false for a move that changed no button (button
// -1), or changed a side button's.
func chord(button, buttons int) (kind platform.SurfaceEventKind, b int, ok bool) {
if button < 0 || button > 2 {
return 0, 0, false
}
b = buttonOf(button)
// buttons has a bit per button: 1 the primary, 2 the secondary, 4 the
// middle, as MyGo numbers them.
if buttons&(1<<b) != 0 {
return platform.PointerDown, b, true
}
return platform.PointerUp, b, true
}
// point returns where a pointer event happened in the canvas, in DIPs.
func (s *surface) point(e js.Value) (float64, float64) {
r := s.canvas.Call("getBoundingClientRect")
return e.Get("clientX").Float() - r.Get("left").Float(), e.Get("clientY").Float() - r.Get("top").Float()
}
// mods returns the modifiers of an event. Command is Control on a Mac, as
// the shortcuts of package ui, which take a browser for another system
// than macOS, expect Control where Macs have Command.
func (s *surface) mods(e js.Value) platform.Modifiers {
var m platform.Modifiers
if e.Get("shiftKey").Bool() {
m |= platform.ModShift
}
if e.Get("altKey").Bool() {
m |= platform.ModAlt
}
ctrl, meta := e.Get("ctrlKey").Bool(), e.Get("metaKey").Bool()
if s.w.b.mac {
ctrl, meta = meta, ctrl
}
if ctrl {
m |= platform.ModCtrl
}
if meta {
m |= platform.ModSuper
}
return m
}
// key handles a key going down or up in the textarea. Keys that type text
// come as text from beforeinput, after this, and keys an input method
// takes are its own. The browser does nothing of its own with keys but
// those typing text, copying and pasting, and those of its own (F5, F11,
// F12, …).
func (s *surface) key(e js.Value, down bool) {
if down {
s.copied = false
}
name, code := e.Get("key").String(), e.Get("code").String()
mods := s.mods(e)
if e.Get("isComposing").Bool() || e.Get("keyCode").Int() == 229 {
if !down {
// The input method took the key up of a key the content got
// pressed, as it began composing while the key was held: the
// key goes up all the same.
s.held.Lift(keyOf(name, code), codeKey(code), mods, s.send)
}
return
}
switch name {
case "Shift", "Control", "Alt", "Meta", "CapsLock", "AltGraph":
s.send(platform.SurfaceEvent{Kind: platform.ModifiersChanged, Mods: mods})
if name == "Meta" && !down && s.w.b.mac {
// A Mac's browsers send no key up for the keys let go of
// while Command is held: they go up with it.
s.held.LiftAll(mods, s.send)
}
s.rawKey(e, code, codeKey(code), mods, down)
return
case "Dead", "Process", "Unidentified", "Compose":
if !down {
s.held.Lift(keyOf(name, code), codeKey(code), mods, s.send)
}
if name != "Process" {
s.rawKey(e, code, codeKey(code), mods, down)
}
return
}
k, physical, keyCode := keyOf(name, code), codeKey(code), platform.KeyCodeForDOM(code)
primary := mods&platform.ModCtrl != 0
if down && primary && mods&(platform.ModAlt|platform.ModShift) == 0 {
switch k {
case platform.KeyV:
// The paste event brings the clipboard's text.
return
case platform.KeyC, platform.KeyX:
// The content copies now, and the copy event that follows
// gives the browser the text.
s.send(platform.SurfaceEvent{Kind: platform.KeyPressed, Key: k, PhysicalKey: physical, Code: keyCode, Mods: mods, Repeat: e.Get("repeat").Bool()})
s.copied = true
return
}
}
kind := platform.KeyReleased
if down {
kind = platform.KeyPressed
}
s.send(platform.SurfaceEvent{Kind: kind, Key: k, PhysicalKey: physical, Code: keyCode, Mods: mods, Repeat: e.Get("repeat").Bool()})
if !down {
return
}
switch {
case name == "F5" || name == "F11" || name == "F12":
case utf8.RuneCountInString(name) > 1 || primary:
e.Call("preventDefault")
}
}
// rawKey sends a key shortcuts have no name for by its position, code being
// the KeyboardEvent's; what the content takes the browser does nothing with.
func (s *surface) rawKey(e js.Value, code string, physical platform.Key, mods platform.Modifiers, down bool) {
keyCode := platform.KeyCodeForDOM(code)
if keyCode == platform.CodeUnknown {
return
}
kind := platform.RawKeyReleased
if down {
kind = platform.RawKeyPressed
}
if s.send(platform.SurfaceEvent{Kind: kind, PhysicalKey: physical, Code: keyCode, Mods: mods, Repeat: e.Get("repeat").Bool()}) {
e.Call("preventDefault")
}
}
// keyOf returns the key of a KeyboardEvent's key and code: letters and
// digits by what they type, as other systems tell them.
func keyOf(name, code string) platform.Key {
if utf8.RuneCountInString(name) == 1 {
r, _ := utf8.DecodeRuneInString(name)
if k := platform.KeyForRune(r); k != platform.KeyUnknown {
return k
}
}
if k, ok := named[name]; ok {
return k
}
return codeKey(code)
}
// codeKey returns the key at a KeyboardEvent's code: its position on an
// ANSI US keyboard (SurfaceEvent.PhysicalKey).
func codeKey(code string) platform.Key {
switch {
case len(code) == 4 && code[:3] == "Key":
return platform.KeyA + platform.Key(code[3]-'A')
case len(code) == 6 && code[:5] == "Digit":
return platform.Key0 + platform.Key(code[5]-'0')
}
if k, ok := codes[code]; ok {
return k
}
return platform.KeyUnknown
}
var named = map[string]platform.Key{
"Enter": platform.KeyEnter, "Escape": platform.KeyEscape, "Backspace": platform.KeyBackspace, "Tab": platform.KeyTab,
" ": platform.KeySpace, "Delete": platform.KeyDelete, "Insert": platform.KeyInsert, "Home": platform.KeyHome, "End": platform.KeyEnd,
"PageUp": platform.KeyPageUp, "PageDown": platform.KeyPageDown, "ArrowLeft": platform.KeyLeft, "ArrowRight": platform.KeyRight,
"ArrowUp": platform.KeyUp, "ArrowDown": platform.KeyDown, "ContextMenu": platform.KeyContextMenu,
"BrowserBack": platform.KeyBack, "BrowserForward": platform.KeyForward,
"F1": platform.KeyF1, "F2": platform.KeyF2, "F3": platform.KeyF3, "F4": platform.KeyF4, "F5": platform.KeyF5, "F6": platform.KeyF6,
"F7": platform.KeyF7, "F8": platform.KeyF8, "F9": platform.KeyF9, "F10": platform.KeyF10, "F11": platform.KeyF11, "F12": platform.KeyF12,
}
var codes = map[string]platform.Key{
"Minus": platform.KeyMinus, "Equal": platform.KeyEqual, "Comma": platform.KeyComma, "Period": platform.KeyPeriod,
"Slash": platform.KeySlash, "Semicolon": platform.KeySemicolon, "Quote": platform.KeyQuote, "BracketLeft": platform.KeyBracketLeft,
"BracketRight": platform.KeyBracketRight, "Backslash": platform.KeyBackslash, "Backquote": platform.KeyBackquote, "Space": platform.KeySpace,
}
// focus gives the window the keyboard: its textarea.
func (s *surface) focus() {
s.input.Call("focus", map[string]any{"preventScroll": true})
}
// measure takes the canvas's size and the device pixel ratio, and tells the
// content when they changed.
func (s *surface) measure() bool {
r := s.canvas.Call("getBoundingClientRect")
w, h, scale := r.Get("width").Float(), r.Get("height").Float(), devicePixelRatio()
if w == s.width && h == s.height && scale == s.scale {
return false
}
s.width, s.height, s.scale = w, h, scale
s.send(platform.SurfaceEvent{Kind: platform.SurfaceResize})
return true
}
// pixels returns the size of frames, as package ui computes it.
func (s *surface) pixels() (int, int) {
return int(math.Ceil(float64(float32(s.width) * float32(s.scale)))), int(math.Ceil(float64(float32(s.height) * float32(s.scale))))
}
// drawFrame handles a frame of the browser's, when the content asked for
// one, with the canvas as large as the frame and WebGL's context current.
func (s *surface) drawFrame() {
s.pending = false
if s.closed || !s.w.visible {
return
}
s.measure()
pw, ph := s.pixels()
if s.canvas.Get("width").Int() != pw || s.canvas.Get("height").Int() != ph {
s.canvas.Set("width", pw)
s.canvas.Set("height", ph)
}
if s.gl != nil {
s.gl.MakeCurrent()
}
s.send(platform.SurfaceEvent{Kind: platform.SurfaceFrame})
}
func (s *surface) Native() platform.SurfaceNative {
if s.gl == nil {
return platform.SurfaceNative{}
}
return platform.SurfaceNative{Canvas: s.gl.ID()}
}
func (s *surface) Size() (float64, float64, float64) { return s.width, s.height, s.scale }
func (s *surface) RequestFrame() {
if s.pending || s.closed {
return
}
s.pending = true
s.request = js.Global().Call("requestAnimationFrame", s.frame)
}
// RefreshRate is unknown: browsers do not tell it.
func (s *surface) RefreshRate() float64 { return 0 }
// Occluded reports whether the page is hidden, as in a tab in the
// background, where browsers give no frames.
func (s *surface) Occluded() bool { return js.Global().Get("document").Get("hidden").Bool() }
func (s *surface) PresentPixels(pix []byte, stride, width, height int) {
if s.gl != nil {
if err := s.presenter.Present(pix, stride, width, height); err != nil {
log.Print("mygo: ", err)
}
return
}
if s.ctx2d.IsUndefined() || s.ctx2d.IsNull() || width <= 0 || height <= 0 {
return
}
// ImageData holds straight RGBA; frames are premultiplied BGRA.
n := 4 * width * height
if cap(s.rgba) < n {
s.rgba = make([]byte, n)
}
rgba := s.rgba[:n]
for y := range height {
src, dst := pix[y*stride:][:4*width], rgba[4*width*y:][:4*width]
for x := 0; x < 4*width; x += 4 {
b, g, r, a := src[x], src[x+1], src[x+2], src[x+3]
if a != 0 && a != 255 {
r, g, b = unpremul(r, a), unpremul(g, a), unpremul(b, a)
}
dst[x], dst[x+1], dst[x+2], dst[x+3] = r, g, b, a
}
}
if s.image.IsUndefined() || s.image.Get("width").Int() != width || s.image.Get("height").Int() != height {
s.image = s.ctx2d.Call("createImageData", width, height)
}
js.CopyBytesToJS(s.image.Get("data"), rgba)
s.ctx2d.Call("putImageData", s.image, 0, 0)
}
func unpremul(c, a byte) byte { return byte(min(255, (int(c)*255+int(a)/2)/int(a))) }
var cursors = [...]string{
platform.CursorDefault: "default", platform.CursorPointer: "pointer", platform.CursorText: "text", platform.CursorMove: "move",
platform.CursorResizeEW: "ew-resize", platform.CursorResizeNS: "ns-resize", platform.CursorResizeNWSE: "nwse-resize",
platform.CursorResizeNESW: "nesw-resize", platform.CursorNotAllowed: "not-allowed", platform.CursorCrosshair: "crosshair",
platform.CursorGrab: "grab", platform.CursorGrabbing: "grabbing", platform.CursorResizeN: "n-resize", platform.CursorResizeE: "e-resize",
platform.CursorResizeS: "s-resize", platform.CursorResizeW: "w-resize", platform.CursorResizeColumn: "col-resize",
platform.CursorResizeRow: "row-resize", platform.CursorVerticalText: "vertical-text", platform.CursorCopy: "copy",
platform.CursorAlias: "alias", platform.CursorContextMenu: "context-menu", platform.CursorNone: "none",
platform.CursorProgress: "progress", platform.CursorWait: "wait", platform.CursorHelp: "help", platform.CursorCell: "cell",
platform.CursorZoomIn: "zoom-in", platform.CursorZoomOut: "zoom-out", platform.CursorAllScroll: "all-scroll",
platform.CursorNoDrop: "no-drop",
}
func (s *surface) SetCursor(c platform.Cursor) {
name := "default"
if int(c) < len(cursors) && cursors[c] != "" {
name = cursors[c]
}
s.canvas.Get("style").Set("cursor", name)
}
// SetTextInput moves the textarea to the caret, where input methods show
// their candidates, and lets touch devices show their keyboard while an
// element takes text: browsers show it, or hide it, as the inputmode of
// the focused textarea changes. Keys of a hardware keyboard come either
// way.
func (s *surface) SetTextInput(t platform.TextInputState) {
if t.Active != s.text.Active {
mode := "none"
if t.Active {
mode = "text"
}
s.input.Call("setAttribute", "inputmode", mode)
}
s.text = t
st := s.input.Get("style")
if !t.Active {
st.Set("left", "0")
st.Set("top", "0")
return
}
st.Set("left", ftoa(t.Caret.X)+"px")
st.Set("top", ftoa(t.Caret.Y)+"px")
st.Set("height", ftoa(max(t.Caret.H, 1))+"px")
}
func (s *surface) UpdateAccessibility(*platform.AccessTree) {}
func (s *surface) StartDataDrag(platform.DragRequest) {}
func (s *surface) CancelDataDrag() {}
func (s *surface) SetDropFormats([]transfer.Format) {}
func (s *surface) PlaceWebViews([]platform.WebViewPlacement) {}
func (s *surface) NewWebView(*platform.WindowOptions, platform.WindowHandler) (platform.WebView, error) {
return nil, errUnsupported
}
func (s *surface) close() {
s.closed = true
if s.pending {
js.Global().Call("cancelAnimationFrame", s.request)
}
if !s.observer.IsUndefined() {
s.observer.Call("disconnect")
}
for _, l := range s.global {
l.target.Call("removeEventListener", l.event, l.fn)
}
// The functions may still be called back once: they find the surface
// closed. They are released after the frame.
funcs, frame := s.funcs, s.frame
var release js.Func
release = js.FuncOf(func(js.Value, []js.Value) any {
for _, f := range funcs {
f.Release()
}
frame.Release()
release.Release()
return nil
})
js.Global().Call("setTimeout", release, 1000)
}
func itoa(n int) string { return strconv.Itoa(n) }
func ftoa(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) }
+11
View File
@@ -0,0 +1,11 @@
//go:build js
package web
import "github.com/egoist/mygo/internal/platform"
func (*Backend) NewFileWatch(func(platform.FileWatchNotice)) (platform.FileWatch, error) {
return nil, platform.ErrUnsupported
}
func (*Backend) ReplaceFile(target, replacement string) error { return platform.ErrUnsupported }
+632
View File
@@ -0,0 +1,632 @@
//go:build js
// Package web is the backend for browsers (GOOS=js, GOARCH=wasm): windows
// showing content MyGo draws itself (package ui) on canvases of the page,
// drawn with WebGL 2 by the GL renderer (package gl), or in memory where
// the browser has no WebGL 2. A window fills the page's element with the
// ID "mygo", or else the page; windows opened later cover earlier ones.
// Windows of web pages, menus, trays and the like have nothing in a
// browser to stand for them, and report so.
//
// Go's main goroutine, which runs the event loop (Run), is the main thread.
// JavaScript calls Go's functions (js.FuncOf) on goroutines of their own:
// the backend has the main goroutine handle their events and waits for
// it, so that they can still prevent the browser's defaults.
package web
import (
"bytes"
"errors"
"runtime"
"strconv"
"sync"
"syscall/js"
"time"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/transfer"
)
var errUnsupported = errors.New("mygo: browsers do not support this")
// Backend is the browser backend.
type Backend struct {
h platform.AppHandler
mainID uint64
tasks chan func()
signal chan struct{}
wake chan struct{}
quit chan struct{}
mu sync.Mutex
windows []*window
// clip is the text copied, which pastes read: browsers give the
// clipboard's text only to paste events (see surface.paste). clipData
// is all that was copied or pasted, in its text formats, as HTML and
// a rich text's own format.
clip string
clipData transfer.Data
// source is the appearance the app asked for: "light", "dark" or
// "system".
source string
mac bool
funcs []js.Func
}
// New returns the browser backend.
func New() *Backend {
return &Backend{
tasks: make(chan func()),
signal: make(chan struct{}, 1),
wake: make(chan struct{}, 1),
quit: make(chan struct{}),
}
}
func goroutineID() uint64 {
var buf [64]byte
n := runtime.Stack(buf[:], false)
b := bytes.TrimPrefix(buf[:n], []byte("goroutine "))
b = b[:max(bytes.IndexByte(b, ' '), 0)]
id, _ := strconv.ParseUint(string(b), 10, 64)
return id
}
func (b *Backend) Name() string { return "js/webgl2" }
func (b *Backend) Init(h platform.AppHandler, _ platform.AppOptions) error {
if js.Global().Get("document").IsUndefined() {
return errors.New("mygo: no document to draw in (a worker?)")
}
b.h = h
b.mainID = goroutineID()
installFiles()
nav := js.Global().Get("navigator")
platformName := nav.Get("platform")
b.mac = !platformName.IsUndefined() && len(platformName.String()) >= 3 && platformName.String()[:3] == "Mac"
changed := b.funcOf(func(js.Value, []js.Value) any {
b.sync(func() { b.h.ThemeChanged() })
return nil
})
for _, q := range []string{"(prefers-color-scheme: dark)", "(prefers-reduced-motion: reduce)", "(prefers-reduced-transparency: reduce)", "(prefers-contrast: more)",
"(pointer: fine)", "(pointer: coarse)", "(any-pointer: fine)", "(any-pointer: coarse)", "(hover: none)", "(any-hover: none)"} {
js.Global().Call("matchMedia", q).Call("addEventListener", "change", changed)
}
// The languages the user reads: the browser's.
js.Global().Call("addEventListener", "languagechange", b.funcOf(func(js.Value, []js.Value) any {
b.sync(func() { b.h.LocaleChanged() })
return nil
}))
// The page's own choice of appearance (themeAttr), as a page framing
// the app sets it, since frames take the media's.
js.Global().Get("MutationObserver").New(changed).Call("observe", js.Global().Get("document").Get("documentElement"),
map[string]any{"attributes": true, "attributeFilter": []any{themeAttr}})
return nil
}
// funcOf wraps fn for JavaScript, for the life of the app.
func (b *Backend) funcOf(fn func(this js.Value, args []js.Value) any) js.Func {
f := js.FuncOf(fn)
b.funcs = append(b.funcs, f)
return f
}
func (b *Backend) Run() error {
b.h.Ready()
for {
select {
case <-b.quit:
b.h.Terminating()
return nil
case <-b.signal:
b.h.Dispatch()
case t := <-b.tasks:
t()
case <-b.wake:
}
}
}
func (b *Backend) Quit() {
select {
case <-b.quit:
default:
close(b.quit)
}
}
func (b *Backend) IsMainThread() bool { return b.mainID == 0 || goroutineID() == b.mainID }
func (b *Backend) Signal() {
select {
case b.signal <- struct{}{}:
default:
}
}
func (b *Backend) Step() {
select {
case <-b.signal:
b.h.Dispatch()
case t := <-b.tasks:
t()
case <-b.wake:
case <-time.After(50 * time.Millisecond):
}
}
func (b *Backend) Wake() {
select {
case b.wake <- struct{}{}:
default:
}
}
// sync runs fn on the main goroutine and waits for it: JavaScript's
// callbacks handle their events through it.
func (b *Backend) sync(fn func()) {
if b.IsMainThread() {
fn()
return
}
done := make(chan struct{})
select {
case b.tasks <- func() { defer close(done); fn() }:
<-done
case <-b.quit:
}
}
func (b *Backend) NewWindow(o *platform.WindowOptions, h platform.WindowHandler) (platform.Window, error) {
if !o.Surface {
return nil, errors.New("mygo: browsers show windows of native UI (WindowOptions.Content) only")
}
w, err := newWindow(b, o, h)
if err != nil {
return nil, err
}
b.mu.Lock()
b.windows = append(b.windows, w)
b.mu.Unlock()
return w, nil
}
func (b *Backend) removeWindow(w *window) {
b.mu.Lock()
defer b.mu.Unlock()
for i, x := range b.windows {
if x == w {
b.windows = append(b.windows[:i], b.windows[i+1:]...)
return
}
}
}
func (*Backend) SetApplicationMenu(*platform.Menu) {}
func (*Backend) UpdateMenuItem(*platform.MenuItem) {}
func (b *Backend) App() platform.AppController { return app{} }
func (b *Backend) Dialogs() platform.Dialogs { return dialogs{} }
func (b *Backend) Clipboard() platform.Clipboard { return clipboard{b} }
func (b *Backend) Shell() platform.Shell { return shell{} }
func (b *Backend) Screen() platform.Screen { return screen{} }
func (b *Backend) Theme() platform.Theme { return theme{b} }
func (b *Backend) Power() platform.Power { return power{} }
func (*Backend) NewTray(string, platform.TrayHandler) (platform.Tray, error) {
return nil, errUnsupported
}
func (*Backend) RegisterHotkey(int, string, string) error { return errUnsupported }
func (*Backend) UnregisterHotkey(int) {}
func (*Backend) NotificationsSupported() bool { return false }
func (*Backend) WebViewAvailable() bool { return false }
func (*Backend) RemoveNotification(string) {}
func (*Backend) RemoveAllNotifications() {}
func (*Backend) ShowNotification(_ *platform.Notification, done func(error)) {
done(errUnsupported)
}
type app struct{}
func (app) SetActivationPolicy(string) {}
func (app) Activate() {}
func (app) AllowForeground() {}
func (app) WithActivationToken(_ string, fn func()) { fn() }
func (app) Hide() {}
func (app) Unhide() {}
func (app) IsHidden() bool { return js.Global().Get("document").Get("hidden").Bool() }
func (app) IsActive() bool { return js.Global().Get("document").Call("hasFocus").Bool() }
func (app) SetBadge(string) {}
func (app) Badge() string { return "" }
func (app) Bounce(bool) int { return 0 }
func (app) CancelBounce(int) {}
func (app) SetDockIcon([]byte) error { return errUnsupported }
func (app) ShowAboutPanel(platform.AboutPanelOptions) {}
func (app) Package() (platform.PackageInfo, bool) { return platform.PackageInfo{}, false }
func (app) RegisterURLScheme(string, string, string) error { return errUnsupported }
func (app) UnregisterURLScheme(string, string, string) error { return errUnsupported }
func (app) IsURLSchemeRegistered(string, string, string) bool { return false }
func (app) SetOpenAtLogin(bool, string, string, string) error { return errUnsupported }
func (app) OpenAtLogin(string, string, string) bool { return false }
func (app) OpenedAtLogin() bool { return false }
func (app) SetDockMenu(*platform.Menu) {}
func (app) ClearBrowsingData(_ platform.DataStore, _ platform.SiteData, done func(error)) {
done(errUnsupported)
}
func (app) NewDataStore(platform.DataStoreOptions) (platform.DataStore, error) {
return nil, errUnsupported
}
// PreferredLanguages returns the browser's languages, navigator.languages.
func (app) PreferredLanguages() []string {
nav := js.Global().Get("navigator")
var out []string
if list := nav.Get("languages"); list.Type() == js.TypeObject {
for i := range list.Length() {
if l := list.Index(i); l.Type() == js.TypeString {
out = append(out, l.String())
}
}
}
if len(out) == 0 {
if l := nav.Get("language"); l.Type() == js.TypeString {
out = append(out, l.String())
}
}
return out
}
// Region returns the formats of the browser's locale, as Intl resolves
// it: its first day of the week where the browser tells it
// (Intl.Locale's getWeekInfo, or weekInfo before), and its hour cycle.
func (app) Region() platform.Region {
r := platform.Region{FirstWeekday: -1}
intl := js.Global().Get("Intl")
if intl.Type() != js.TypeObject {
return r
}
opts := intl.Get("DateTimeFormat").New(js.Undefined(), map[string]any{"hour": "numeric"}).Call("resolvedOptions")
if l := opts.Get("locale"); l.Type() == js.TypeString {
r.Locale = l.String()
}
switch opts.Get("hourCycle").String() {
case "h11", "h12":
r.HourCycle = 12
case "h23", "h24":
r.HourCycle = 24
}
if r.Locale == "" || intl.Get("Locale").Type() != js.TypeFunction {
return r
}
func() {
defer func() { recover() }() // a browser that throws on either
locale := intl.Get("Locale").New(r.Locale)
info := js.Undefined()
if locale.Get("getWeekInfo").Type() == js.TypeFunction {
info = locale.Call("getWeekInfo")
} else {
info = locale.Get("weekInfo")
}
if info.Type() == js.TypeObject && info.Get("firstDay").Type() == js.TypeNumber {
r.FirstWeekday = info.Get("firstDay").Int() % 7 // 7 is Sunday
}
}()
return r
}
// localeKey is the key of localStorage the app's language is kept under.
const localeKey = "mygo:locale"
// SavedLocale reads the app's language from the page's localStorage.
func (app) SavedLocale() (tag string, kept bool) {
defer func() { recover() }() // storage the page may not use
if v := js.Global().Get("localStorage").Call("getItem", localeKey); v.Type() == js.TypeString {
tag = v.String()
}
return tag, true
}
// SaveLocale keeps the app's language in the page's localStorage.
func (app) SaveLocale(tag string) bool {
defer func() { recover() }()
storage := js.Global().Get("localStorage")
if tag == "" {
storage.Call("removeItem", localeKey)
} else {
storage.Call("setItem", localeKey, tag)
}
return true
}
// SetLanguages makes the app's language the page's (<html lang>), which
// browsers draw the text of canvases and read the page aloud in, and its
// direction the page's (<html dir>).
func (app) SetLanguages(tags []string, rtl bool) {
root := js.Global().Get("document").Get("documentElement")
if len(tags) > 0 {
root.Set("lang", tags[0])
}
dir := "ltr"
if rtl {
dir = "rtl"
}
root.Set("dir", dir)
}
type dialogs struct{}
func (dialogs) ShowOpenDialog(_ platform.Window, _ *platform.OpenDialogOptions, cb func([]string, error)) {
cb(nil, errUnsupported)
}
func (dialogs) ShowSaveDialog(_ platform.Window, _ *platform.SaveDialogOptions, cb func(string, error)) {
cb("", errUnsupported)
}
// ShowMessageBox asks with the browser's own dialogs: an alert for one
// button, a confirm for more, whose OK is the first button and Cancel the
// cancel button.
func (dialogs) ShowMessageBox(_ platform.Window, o *platform.MessageBoxOptions, cb func(platform.MessageBoxResult, error)) {
text := o.Message
if o.Detail != "" {
text += "\n\n" + o.Detail
}
if len(o.Buttons) <= 1 {
js.Global().Call("alert", text)
cb(platform.MessageBoxResult{}, nil)
return
}
res := o.CancelID
if js.Global().Call("confirm", text).Bool() {
res = 0
if res == o.CancelID {
res = 1
}
}
cb(platform.MessageBoxResult{Response: res, CheckboxChecked: o.CheckboxChecked}, nil)
}
// clipboard keeps the text copied, and writes it to the system's
// clipboard as well, which browsers allow while the user acts (a key
// copying). Reading the system's clipboard takes a paste event, which
// gives the surface its text (surface.paste).
type clipboard struct{ b *Backend }
func (clipboard) WatchChanges(func()) (func(), error) {
return nil, platform.ErrUnsupported
}
func (c clipboard) ReadText() string {
c.b.mu.Lock()
defer c.b.mu.Unlock()
return c.b.clip
}
func (c clipboard) WriteText(text string) {
c.b.mu.Lock()
c.b.clip = text
c.b.clipData = transfer.TextData(text)
c.b.mu.Unlock()
if cb := js.Global().Get("navigator").Get("clipboard"); !cb.IsUndefined() {
p := cb.Call("writeText", text)
p.Call("catch", js.Global().Get("Function").New("")) // without the user acting
}
}
// WriteTextThen writes text as WriteText does, and gives done what the
// browser's clipboard answers: an error where it refuses, as without the
// user acting, or in a page of no secure context, which has no clipboard
// API. The text is copied in the page either way, which pastes it.
func (c clipboard) WriteTextThen(text string, done func(error)) {
c.b.mu.Lock()
c.b.clip = text
c.b.clipData = transfer.TextData(text)
c.b.mu.Unlock()
var p js.Value
if cb := js.Global().Get("navigator").Get("clipboard"); cb.IsUndefined() || cb.IsNull() {
p = js.Global().Get("Promise").Call("reject", js.Global().Get("Error").New("no clipboard API outside secure contexts"))
} else {
p = cb.Call("writeText", text)
}
var ok, failed js.Func
answer := func(err error) {
ok.Release()
failed.Release()
c.b.sync(func() { done(err) })
}
ok = js.FuncOf(func(js.Value, []js.Value) any {
answer(nil)
return nil
})
failed = js.FuncOf(func(_ js.Value, args []js.Value) any {
msg := "refused"
if len(args) > 0 && args[0].Type() == js.TypeObject {
if m := args[0].Get("message"); m.Type() == js.TypeString && m.String() != "" {
msg = m.String()
}
}
answer(errors.New("mygo: the browser did not write the clipboard: " + msg))
return nil
})
p.Call("then", ok, failed)
}
func (c clipboard) ReadData(formats []transfer.Format) (transfer.Data, error) {
c.b.mu.Lock()
d := c.b.clipData
c.b.mu.Unlock()
var reps []transfer.Representation
for _, f := range formats {
if b, err := d.Read(f); err == nil {
reps = append(reps, transfer.Bytes(f, b))
}
}
if formats == nil {
return d, nil
}
if len(reps) == 0 {
return transfer.Data{}, nil
}
return transfer.New(transfer.NewItem(reps...)), nil
}
// WriteData keeps data's text formats, which the copy event under way
// gives the browser (surface.copy), and writes its plain text to the
// system's clipboard, which browsers allow while the user acts. Browsers
// have no mark of concealed content.
func (c clipboard) WriteData(d transfer.Data, _ bool, released func()) error {
t, err := d.Read(transfer.Text)
if err != nil {
return errUnsupported
}
d, err = d.Materialize(d.Formats())
if err != nil {
return err
}
c.WriteText(string(t))
c.b.mu.Lock()
c.b.clipData = d
c.b.mu.Unlock()
if released != nil {
released()
}
return nil
}
func (c clipboard) Formats() []transfer.Format {
c.b.mu.Lock()
defer c.b.mu.Unlock()
if c.b.clip == "" && len(c.b.clipData.Items()) == 0 {
return nil
}
return c.b.clipData.Formats()
}
func (clipboard) Flush() error { return nil }
func (clipboard) Close() {}
func (clipboard) ReadHTML() string { return "" }
func (clipboard) WriteHTML(string) {}
func (clipboard) ReadImage() []byte { return nil }
func (clipboard) WriteImage([]byte) error { return errUnsupported }
func (c clipboard) Clear() { c.WriteText("") }
func (c clipboard) AvailableFormats() []string { return []string{"text/plain"} }
type shell struct{}
func (shell) OpenExternal(url string) error {
js.Global().Call("open", url, "_blank", "noopener")
return nil
}
func (shell) OpenPath(string) error { return errUnsupported }
func (shell) ShowItemInFolder(string) {}
func (shell) TrashItem(string) error { return errUnsupported }
func (shell) TrashItemResult(string) (string, error) { return "", platform.ErrUnsupported }
func (shell) PreviewItem(string) error { return errUnsupported }
func (shell) Beep() {}
func (shell) FileIcon(string, int) ([]byte, error) { return nil, errUnsupported }
func (shell) TypeIcon(string, int) ([]byte, error) { return nil, errUnsupported }
func (shell) OpenApplication(string) error { return errUnsupported }
func (shell) DefaultApp(string) (platform.Application, error) {
return platform.Application{}, errUnsupported
}
func (*Backend) Applications() ([]platform.Application, error) { return nil, errUnsupported }
type screen struct{}
func (screen) Displays() []platform.Display {
s := js.Global().Get("screen")
return []platform.Display{{
ID: 1,
Bounds: platform.Rect{Width: s.Get("width").Int(), Height: s.Get("height").Int()},
WorkArea: platform.Rect{Width: s.Get("availWidth").Int(), Height: s.Get("availHeight").Int()},
ScaleFactor: devicePixelRatio(),
Primary: true,
}}
}
func (screen) CursorPoint() platform.Point { return platform.Point{} }
func devicePixelRatio() float64 {
if r := js.Global().Get("devicePixelRatio"); r.Type() == js.TypeNumber && r.Float() > 0 {
return r.Float()
}
return 1
}
func matches(query string) bool {
return js.Global().Call("matchMedia", query).Get("matches").Bool()
}
type theme struct{ b *Backend }
// themeAttr is the attribute of the page's root element that chooses the
// appearance, "dark" or "light", over the browser's: a page framing the
// app sets it to its own, which the frame's prefers-color-scheme does not
// follow in Chrome.
const themeAttr = "data-mygo-theme"
func (t theme) IsDark() bool {
t.b.mu.Lock()
source := t.b.source
t.b.mu.Unlock()
switch source {
case "dark":
return true
case "light":
return false
}
switch js.Global().Get("document").Get("documentElement").Call("getAttribute", themeAttr).String() {
case "dark":
return true
case "light":
return false
}
return matches("(prefers-color-scheme: dark)")
}
func (t theme) SetSource(source string) {
t.b.mu.Lock()
t.b.source = source
t.b.mu.Unlock()
t.b.h.ThemeChanged()
}
func (theme) UIFont() string { return "" }
func (theme) FontRendering() platform.FontRendering { return platform.FontRendering{} }
func (theme) Preferences() platform.Preferences {
return platform.Preferences{
ReduceMotion: matches("(prefers-reduced-motion: reduce)"),
ReduceTransparency: matches("(prefers-reduced-transparency: reduce)"),
HighContrast: matches("(prefers-contrast: more)"),
TextScale: 1,
Pointer: pointer("pointer"),
AnyPointer: pointer("any-pointer"),
NoHover: matches("(hover: none)"),
NoAnyHover: matches("(any-hover: none)"),
}
}
// pointer returns the accuracy the media feature (pointer or any-pointer)
// matches: the finest of any-pointer's.
func pointer(feature string) platform.PointerAccuracy {
switch {
case matches("(" + feature + ": fine)"):
return platform.PointerFine
case matches("(" + feature + ": coarse)"):
return platform.PointerCoarse
case matches("(" + feature + ": none)"):
return platform.PointerNone
}
return platform.PointerFine // a browser without the feature
}
type power struct{}
func (power) Watch() {}
func (power) KeepAwake(bool, string) func() { return func() {} }
func (power) OnBattery() bool { return false }
func (power) IdleTime() time.Duration { return 0 }
// KeepRunning does nothing: a page's timers are the browser's to throttle.
func (power) KeepRunning(string) func() { return func() {} }
+240
View File
@@ -0,0 +1,240 @@
//go:build js
package web
import (
"errors"
"io/fs"
"os"
"path"
"path/filepath"
"slices"
"syscall/js"
"testing"
"github.com/egoist/mygo/internal/platform"
)
func TestKeyOf(t *testing.T) {
for _, tc := range []struct {
key, code string
want platform.Key
}{
{"a", "KeyA", platform.KeyA},
{"A", "KeyA", platform.KeyA},
// Letters follow the layout: the key typing a z on a German
// keyboard is Z, where QWERTY has Y.
{"z", "KeyY", platform.KeyZ},
// Shifted and composed characters go by the key.
{"!", "Digit1", platform.Key1},
{"å", "KeyA", platform.KeyA},
{"ß", "Minus", platform.KeyMinus},
{" ", "Space", platform.KeySpace},
{"Enter", "Enter", platform.KeyEnter},
{"ArrowLeft", "ArrowLeft", platform.KeyLeft},
{"F12", "F12", platform.KeyF12},
{"BrowserBack", "BrowserBack", platform.KeyBack},
{"Unidentified", "", platform.KeyUnknown},
} {
if got := keyOf(tc.key, tc.code); got != tc.want {
t.Errorf("keyOf(%q, %q) = %v, want %v", tc.key, tc.code, got, tc.want)
}
}
}
func TestCodeKey(t *testing.T) {
// The key by position, whatever the layout types: ы is on S.
for code, want := range map[string]platform.Key{
"KeyS": platform.KeyS, "Digit1": platform.Key1, "Semicolon": platform.KeySemicolon,
"IntlBackslash": platform.KeyUnknown, "": platform.KeyUnknown,
} {
if got := codeKey(code); got != want {
t.Errorf("codeKey(%q) = %v, want %v", code, got, want)
}
}
}
func TestAccelText(t *testing.T) {
for _, tc := range []struct {
accel string
mac bool
want string
}{
{"CmdOrCtrl+C", true, "⌘C"},
{"CmdOrCtrl+C", false, "Ctrl+C"},
{"CmdOrCtrl+Shift+z", true, "⌘⇧Z"},
{"Alt+F4", false, "Alt+F4"},
{"", true, ""},
} {
if got := accelText(tc.accel, tc.mac); got != tc.want {
t.Errorf("accelText(%q, %v) = %q, want %q", tc.accel, tc.mac, got, tc.want)
}
}
}
func TestButtonOf(t *testing.T) {
// DOM: 0 primary, 1 middle, 2 secondary; MyGo: 0 primary, 1
// secondary, 2 middle.
for dom, want := range []int{0, 2, 1} {
if got := buttonOf(dom); got != want {
t.Errorf("buttonOf(%d) = %d, want %d", dom, got, want)
}
}
}
func TestUnpremul(t *testing.T) {
for _, tc := range []struct{ c, a, want byte }{{128, 128, 255}, {64, 128, 128}, {0, 10, 0}, {200, 255, 200}} {
if got := unpremul(tc.c, tc.a); got != tc.want {
t.Errorf("unpremul(%d, %d) = %d, want %d", tc.c, tc.a, got, tc.want)
}
}
}
// TestDroppedFiles reads files dropped through os, as apps do with the
// paths of FileDrop, and leaves other paths to the fs object (Node's, in
// tests).
func TestDroppedFiles(t *testing.T) {
installFiles()
paths := drops.add([]string{"notes.txt", "notes.txt", "a/b.png"}, [][]byte{[]byte("hello"), []byte("again"), {1, 2, 3}})
dir := path.Dir(paths[0])
want := []string{dir + "/notes.txt", dir + "/2-notes.txt", dir + "/a_b.png"}
if !slices.Equal(paths, want) {
t.Fatalf("paths %v, want %v", paths, want)
}
for i, p := range paths {
b, err := os.ReadFile(p)
if err != nil || len(b) == 0 {
t.Fatalf("ReadFile(%s) = %q, %v", p, b, err)
}
if i == 0 && string(b) != "hello" {
t.Errorf("ReadFile(%s) = %q", p, b)
}
}
if st, err := os.Stat(paths[2]); err != nil || st.Size() != 3 || st.IsDir() {
t.Errorf("Stat(%s) = %v, %v", paths[2], st, err)
}
entries, err := os.ReadDir(dir)
if err != nil || len(entries) != 3 {
t.Fatalf("ReadDir(%s) = %v, %v", dir, entries, err)
}
f, err := os.Open(paths[0])
if err != nil {
t.Fatal(err)
}
buf := make([]byte, 3)
if n, err := f.ReadAt(buf, 2); err != nil || string(buf[:n]) != "llo" {
t.Errorf("ReadAt = %q, %v", buf[:n], err)
}
f.Close()
if err := os.WriteFile(paths[0], []byte("x"), 0o644); err == nil {
t.Error("a file dropped was written")
}
if _, err := os.ReadFile(dir + "/missing"); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("a missing file: %v", err)
}
// Other paths are the fs object's.
other := filepath.Join(t.TempDir(), "x")
if err := os.WriteFile(other, []byte("node"), 0o644); err != nil {
t.Fatal(err)
}
if b, err := os.ReadFile(other); err != nil || string(b) != "node" {
t.Errorf("ReadFile(%s) = %q, %v", other, b, err)
}
// The oldest drops go.
for range keptDrops {
drops.add([]string{"x"}, [][]byte{{0}})
}
if _, err := os.Stat(paths[0]); err == nil {
t.Error("the files of the oldest drop stay")
}
}
// TestWebViewAvailable: browsers have no system webview, so the call says
// so, and an app opens a window of native UI instead of one showing a page
// it could not show.
func TestWebViewAvailable(t *testing.T) {
if New().WebViewAvailable() {
t.Error("WebViewAvailable = true in a browser, which has no webview")
}
}
func TestChord(t *testing.T) {
// A DOM pointermove with button (DOM numbering) going down or up while
// another is held, and buttons held after it.
for _, tc := range []struct {
button, buttons int
kind platform.SurfaceEventKind
want int
ok bool
}{
{-1, 1, 0, 0, false}, // a move
{2, 1 | 2, platform.PointerDown, 1, true}, // the secondary goes down while the primary is held
{2, 1, platform.PointerUp, 1, true}, // and up
{1, 2 | 4, platform.PointerDown, 2, true}, // the middle while the secondary is held
{0, 4, platform.PointerUp, 0, true}, // the primary up while the middle is held
{3, 1 | 8, 0, 0, false}, // a side button
} {
kind, b, ok := chord(tc.button, tc.buttons)
if ok != tc.ok || ok && (kind != tc.kind || b != tc.want) {
t.Errorf("chord(%d, %d) = %v, %d, %v; want %v, %d, %v", tc.button, tc.buttons, kind, b, ok, tc.kind, tc.want, tc.ok)
}
}
}
func TestDevice(t *testing.T) {
// A PointerEvent's pointerType and pressure, which browsers give a
// mouse too, and an event of a browser without them.
for _, tc := range []struct {
props map[string]any
want platform.PointerKind
pressure float64
}{
{map[string]any{"pointerType": "mouse", "pressure": 0.5}, platform.PointerMouse, 0.5},
{map[string]any{"pointerType": "pen", "pressure": 0.75}, platform.PointerPen, 0.75},
{map[string]any{"pointerType": "touch", "pressure": 0}, platform.PointerTouch, 0},
{map[string]any{}, platform.PointerMouse, 0},
} {
e := js.Global().Get("Object").New()
for k, v := range tc.props {
e.Set(k, v)
}
if k, p := device(e); k != tc.want || p != tc.pressure {
t.Errorf("device(%v) = %d, %v; want %d, %v", tc.props, k, p, tc.want, tc.pressure)
}
}
}
func TestContact(t *testing.T) {
// A PointerEvent's width and height, in CSS pixels: 1 by 1 where the
// browser does not tell the contact, as for a mouse, and an event of a
// browser without them (#1879).
for _, tc := range []struct {
props map[string]any
w, h float64
}{
{map[string]any{"width": 24.5, "height": 30}, 24.5, 30},
{map[string]any{"width": 1, "height": 1}, 0, 0},
{map[string]any{"width": 1, "height": 12}, 1, 12},
{map[string]any{}, 0, 0},
} {
e := js.Global().Get("Object").New()
for k, v := range tc.props {
e.Set(k, v)
}
if w, h := contact(e); w != tc.w || h != tc.h {
t.Errorf("contact(%v) = %v, %v; want %v, %v", tc.props, w, h, tc.w, tc.h)
}
}
}
func TestCursorNames(t *testing.T) {
// Every cursor has its CSS name.
for c := platform.CursorDefault; c <= platform.CursorNoDrop; c++ {
if int(c) >= len(cursors) || cursors[c] == "" {
t.Errorf("cursor %d has no CSS name", c)
}
}
if cursors[platform.CursorProgress] != "progress" || cursors[platform.CursorNoDrop] != "no-drop" {
t.Errorf("progress is %q, no-drop %q", cursors[platform.CursorProgress], cursors[platform.CursorNoDrop])
}
}
+259
View File
@@ -0,0 +1,259 @@
//go:build js
package web
import (
"syscall/js"
"github.com/egoist/mygo/internal/platform"
)
// window is a window of the page: an element filling the page's element
// with the ID "mygo", or else the page, holding the canvas its surface
// draws on. The page's title is the title of the window opened last.
type window struct {
b *Backend
h platform.WindowHandler
opts *platform.WindowOptions
el js.Value
s *surface
title string
visible bool
focused bool
closed bool
full bool
}
// css is the style sheet of windows, added to the page once.
const css = `
.mygo-window{position:absolute;inset:0;overflow:hidden;contain:strict}
body>.mygo-window{position:fixed}
.mygo-window>canvas{display:block;width:100%;height:100%;touch-action:none;outline:none;user-select:none;-webkit-user-select:none}
.mygo-window>textarea{position:absolute;left:0;top:0;width:1px;height:1em;padding:0;margin:0;border:0;outline:none;resize:none;overflow:hidden;opacity:0;color:transparent;background:transparent;caret-color:transparent;white-space:pre;font-size:16px;z-index:-1}
`
var styled bool
func newWindow(b *Backend, o *platform.WindowOptions, h platform.WindowHandler) (*window, error) {
doc := js.Global().Get("document")
if !styled {
styled = true
style := doc.Call("createElement", "style")
style.Set("textContent", css)
doc.Get("head").Call("appendChild", style)
}
parent := doc.Call("getElementById", "mygo")
if parent.IsNull() {
parent = doc.Get("body")
} else if js.Global().Call("getComputedStyle", parent).Get("position").String() == "static" {
parent.Get("style").Set("position", "relative")
}
w := &window{b: b, h: h, opts: o, title: o.Title, full: o.FullScreen}
w.el = doc.Call("createElement", "div")
w.el.Set("className", "mygo-window")
w.el.Get("style").Set("display", "none")
if c := o.BackgroundColor; c != nil {
w.SetBackgroundColor(*c)
}
parent.Call("appendChild", w.el)
s, err := newSurface(w)
if err != nil {
w.el.Call("remove")
return nil, err
}
w.s = s
w.SetTitle(o.Title)
return w, nil
}
func (w *window) Handle() uintptr { return 0 }
func (w *window) Surface() platform.Surface { return w.s }
func (w *window) SetTitle(t string) {
w.title = t
if t != "" {
js.Global().Get("document").Set("title", t)
}
}
func (w *window) Title() string { return w.title }
func (w *window) SetRepresentedFile(string) {}
func (w *window) SetDocumentEdited(bool) {}
// bounds returns the window's element's rectangle in the page.
func (w *window) bounds() platform.Rect {
r := w.el.Call("getBoundingClientRect")
return platform.Rect{X: r.Get("x").Int(), Y: r.Get("y").Int(), Width: r.Get("width").Int(), Height: r.Get("height").Int()}
}
// The page sets where windows are and how large: the methods setting it do
// nothing.
func (w *window) SetBounds(platform.Rect) {}
func (w *window) Bounds() platform.Rect { return w.bounds() }
func (w *window) SetContentBounds(platform.Rect) {}
func (w *window) ContentBounds() platform.Rect { return w.bounds() }
func (w *window) SetMinimumSize(platform.Size) {}
func (w *window) SetMaximumSize(platform.Size) {}
func (w *window) SetResizable(bool) {}
func (w *window) IsResizable() bool { return false }
func (w *window) SetMovable(bool) {}
func (w *window) IsMovable() bool { return false }
func (w *window) SetMinimizable(bool) {}
func (w *window) IsMinimizable() bool { return false }
func (w *window) SetMaximizable(bool) {}
func (w *window) IsMaximizable() bool { return false }
func (w *window) SetClosable(bool) {}
func (w *window) IsClosable() bool { return w.opts.Closable }
func (w *window) SetAlwaysOnTop(bool) {}
func (w *window) IsAlwaysOnTop() bool { return false }
func (w *window) Minimize() {}
func (w *window) IsMinimized() bool { return false }
func (w *window) Maximize() {}
func (w *window) Unmaximize() {}
func (w *window) IsMaximized() bool { return false }
func (w *window) Restore() {}
func (w *window) Center() {}
func (w *window) SetOpacity(float64) {}
func (w *window) Opacity() float64 { return 1 }
func (w *window) SetHasShadow(bool) {}
func (w *window) HasShadow() bool { return false }
func (w *window) SetIgnoreMouseEvents(bool) {}
func (w *window) IgnoresMouseEvents() bool { return false }
func (w *window) SetContentProtection(bool) {}
func (w *window) SetVibrancy(string) {}
func (w *window) SetVibrancyTint(*platform.Color) {}
func (w *window) SetActiveAppearance(bool) {}
func (w *window) SetWindowButtonsTheme(string) {}
func (w *window) SetProgressBar(string, float64) {}
func (w *window) FlashFrame(bool) {}
func (w *window) SetSkipTaskbar(bool) {}
func (w *window) SetVisibleOnAllWorkspaces(bool) {}
func (w *window) SetIcon([]byte) error { return errUnsupported }
func (w *window) SetMenu(*platform.Menu) {}
func (w *window) SetAutoHideMenu(bool) {}
func (w *window) TitleBar() platform.TitleBar { return platform.TitleBar{} }
func (w *window) StartDrag() {}
func (w *window) TitleBarDoubleClicked() {}
func (w *window) PlaceFlyout(platform.Flyout, platform.Size) {}
// Show shows the window and gives it the keyboard, unless the app is in a
// frame of another page: that page keeps the keyboard until the window is
// clicked, as frames loading do not take it from the page scrolling them.
func (w *window) Show() {
w.ShowInactive()
if js.Global().Get("top").Equal(js.Global().Get("self")) {
w.Focus()
}
}
func (w *window) ShowInactive() {
if w.closed || w.visible {
return
}
w.visible = true
w.el.Get("style").Set("display", "")
w.s.measure()
w.s.RequestFrame()
}
func (w *window) Hide() {
if !w.visible {
return
}
w.visible = false
w.el.Get("style").Set("display", "none")
}
func (w *window) IsVisible() bool { return w.visible }
func (w *window) Focus() { w.s.focus() }
func (w *window) Blur() { w.s.input.Call("blur") }
func (w *window) IsFocused() bool { return w.focused }
// CornerRadius is 0: the window is an element of the page, square.
func (w *window) CornerRadius() float64 { return 0 }
// SetFullScreen asks the browser to show the window's element on the whole
// screen, which it allows while the user acts.
func (w *window) SetFullScreen(v bool) {
if v == w.full {
return
}
w.full = v
doc := js.Global().Get("document")
if v {
if fn := w.el.Get("requestFullscreen"); fn.Type() == js.TypeFunction {
w.el.Call("requestFullscreen").Call("catch", js.Global().Get("Function").New(""))
}
w.h.EnteredFullScreen()
} else {
if !doc.Get("fullscreenElement").IsNull() {
doc.Call("exitFullscreen").Call("catch", js.Global().Get("Function").New(""))
}
w.h.LeftFullScreen()
}
}
func (w *window) IsFullScreen() bool { return w.full }
func (w *window) SetBackgroundColor(c platform.Color) {
w.el.Get("style").Set("background", "rgba("+itoa(int(c.R))+","+itoa(int(c.G))+","+itoa(int(c.B))+","+ftoa(float64(c.A)/255)+")")
}
func (w *window) Close() {
if w.closed {
return
}
w.closed = true
w.s.close()
w.el.Call("remove")
w.b.removeWindow(w)
w.h.Closed()
}
// The page of a window is native UI's: none to load.
func (w *window) WebViewHandle() uintptr { return 0 }
func (w *window) LoadURL(string) {}
func (w *window) LoadHTML(string, string) {}
func (w *window) LoadFile(string, string) {}
func (w *window) Reload(bool) {}
func (w *window) StopLoading() {}
func (w *window) GoBack() {}
func (w *window) GoForward() {}
func (w *window) CanGoBack() bool { return false }
func (w *window) CanGoForward() bool { return false }
func (w *window) URL() string { return "" }
func (w *window) IsLoading() bool { return false }
func (w *window) Eval(string) {}
func (w *window) SetUserScripts([]platform.UserScript) {}
func (w *window) SetContentRules([]any) {}
func (w *window) SetZoom(float64) {}
func (w *window) Zoom() float64 { return 1 }
func (w *window) SetUserAgent(string) {}
func (w *window) UserAgent() string { return js.Global().Get("navigator").Get("userAgent").String() }
func (w *window) OpenDevTools() {}
func (w *window) CloseDevTools() {}
func (w *window) IsDevToolsOpened() bool { return false }
func (w *window) ProcessID() int { return 0 }
func (w *window) GPUProcessID() int { return 0 }
func (w *window) IsAudible() bool { return false }
func (w *window) SetAudioMuted(bool) {}
func (w *window) IsAudioMuted() bool { return false }
func (w *window) TogglePictureInPicture() {}
func (w *window) PictureInPictureActive(cb func(bool)) { cb(false) }
func (w *window) SessionState() []byte { return nil }
func (w *window) RestoreSessionState([]byte) bool { return false }
func (w *window) DroppedFiles() []string { return nil }
func (w *window) Print() {}
func (w *window) CapturePage(cb func([]byte, error)) { cb(nil, errUnsupported) }
func (w *window) PrintToPDF(_ platform.PDFOptions, cb func([]byte, error)) { cb(nil, errUnsupported) }
func (w *window) CallAsyncFunction(_ string, cb func(string, error)) {
cb("", errUnsupported)
}
func (w *window) CaptureState(platform.CaptureKind) platform.CaptureState {
return platform.CaptureNone
}
func (w *window) SetCaptureState(platform.CaptureKind, platform.CaptureState) {}