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:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+35
@@ -0,0 +1,35 @@
|
||||
# automation
|
||||
|
||||
Drive a running [MyGo](https://github.com/egoist/mygo) app from another
|
||||
process, as end-to-end test runners and agents do: list its windows, read
|
||||
the elements of their native UI with the app's keys, act on them, send
|
||||
pointer, wheel, key and text input, choose menu items, evaluate scripts in
|
||||
pages, capture windows, and wait for them to settle. One protocol on
|
||||
macOS, Linux and Windows: newline-delimited JSON over a Unix domain
|
||||
socket that only the user can open.
|
||||
|
||||
```go
|
||||
//go:build e2e
|
||||
|
||||
package main
|
||||
|
||||
import _ "github.com/egoist/mygo/plugins/automation"
|
||||
```
|
||||
|
||||
```sh
|
||||
MYGO_AUTOMATION=/tmp/app.sock ./app
|
||||
echo '{"id": 1, "method": "windows"}' | socat - UNIX-CONNECT:/tmp/app.sock
|
||||
```
|
||||
|
||||
Agents drive it with `mygo-automation`, a command line client with
|
||||
compact snapshots, short refs and diffs once the UI settled, whose guide
|
||||
it prints:
|
||||
|
||||
```sh
|
||||
go install github.com/egoist/mygo/plugins/automation/cmd/mygo-automation
|
||||
mygo-automation skills
|
||||
```
|
||||
|
||||
It listens only when `MYGO_AUTOMATION` is set, and builds without the
|
||||
inspector (`-tags mygo_noinspector`, the release builds of `mygo build`)
|
||||
leave it out. See [the documentation](../../docs/plugins/automation.md).
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
//go:build !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
"github.com/egoist/mygo/internal/surface"
|
||||
)
|
||||
|
||||
// init listens on the socket MYGO_AUTOMATION names, if any, before any
|
||||
// window opens, so that the content of every window of native UI comes to
|
||||
// the plugin as it attaches.
|
||||
func init() {
|
||||
if runtime.GOOS == "android" {
|
||||
// Android's host sets the environment after this package's init, as
|
||||
// the library has to load to run anything: the variable shows by the
|
||||
// time the app is ready, before any window opens.
|
||||
a := newApp()
|
||||
surface.Automate = a.attached
|
||||
mygo.App.WhenReady(func() {
|
||||
close(a.ready)
|
||||
if path := os.Getenv("MYGO_AUTOMATION"); path != "" {
|
||||
a.listen(path)
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
path := os.Getenv("MYGO_AUTOMATION")
|
||||
if path == "" {
|
||||
return
|
||||
}
|
||||
a := newApp()
|
||||
if !a.listen(path) {
|
||||
return
|
||||
}
|
||||
surface.Automate = a.attached
|
||||
mygo.App.WhenReady(func() { close(a.ready) })
|
||||
}
|
||||
|
||||
func newApp() *app {
|
||||
return &app{ready: make(chan struct{}), targets: map[*mygo.Window]target{}}
|
||||
}
|
||||
|
||||
// listen serves requests on the socket at path, and reports whether it can.
|
||||
func (a *app) listen(path string) bool {
|
||||
l, err := listen(path)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "mygo: automation:", err)
|
||||
return false
|
||||
}
|
||||
mygo.App.OnQuit(func() { l.Close() })
|
||||
go serve(l, a)
|
||||
return true
|
||||
}
|
||||
|
||||
// app drives the running app's windows.
|
||||
type app struct {
|
||||
// ready is closed once the app has launched: requests wait for it.
|
||||
ready chan struct{}
|
||||
// targets are the windows of native UI, by window. Main thread only.
|
||||
targets map[*mygo.Window]target
|
||||
}
|
||||
|
||||
// target is a window of native UI: its connection to its content, and
|
||||
// the content.
|
||||
type target struct {
|
||||
conn *surface.Conn
|
||||
content surface.Automated
|
||||
}
|
||||
|
||||
// attached takes a window's content as it attaches (surface.Automate).
|
||||
// Main thread only.
|
||||
func (a *app) attached(conn *surface.Conn, content surface.Automated) {
|
||||
for w := range a.targets {
|
||||
if w.IsDestroyed() {
|
||||
delete(a.targets, w)
|
||||
}
|
||||
}
|
||||
if w, ok := conn.Window.(*mygo.Window); ok {
|
||||
a.targets[w] = target{conn, content}
|
||||
// A closed window's content goes, with what it showed (#1281).
|
||||
w.OnClosed(func() { delete(a.targets, w) })
|
||||
}
|
||||
}
|
||||
|
||||
var errQuit = errors.New("the app quit")
|
||||
|
||||
// onMain runs fn on the main thread, once the app has launched.
|
||||
func (a *app) onMain(fn func()) error {
|
||||
<-a.ready
|
||||
ran := false
|
||||
mygo.RunOnMain(func() {
|
||||
fn()
|
||||
ran = true
|
||||
})
|
||||
if !ran {
|
||||
return errQuit
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// window returns the window of the ID, or for 0 the focused window, else
|
||||
// the first.
|
||||
func (a *app) window(id int) (*mygo.Window, error) {
|
||||
<-a.ready
|
||||
if id != 0 {
|
||||
if w := mygo.WindowByID(id); w != nil && !w.IsDestroyed() {
|
||||
return w, nil
|
||||
}
|
||||
return nil, errorf(codeNoWindow, "no window %d", id)
|
||||
}
|
||||
if w := mygo.FocusedWindow(); w != nil {
|
||||
return w, nil
|
||||
}
|
||||
if ws := mygo.Windows(); len(ws) > 0 {
|
||||
return ws[0], nil
|
||||
}
|
||||
return nil, errorf(codeNoWindow, "the app has no window")
|
||||
}
|
||||
|
||||
// content runs fn on the main thread with the target of a window of
|
||||
// native UI.
|
||||
func (a *app) content(id int, fn func(w *mygo.Window, t target) error) error {
|
||||
w, err := a.window(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var ferr error
|
||||
if err := a.onMain(func() {
|
||||
t, ok := a.targets[w]
|
||||
switch {
|
||||
case w.IsDestroyed():
|
||||
ferr = errorf(codeNoWindow, "window %d closed", w.ID())
|
||||
case !ok:
|
||||
ferr = errorf(codeUnsupported, "window %d shows a web page: use eval", w.ID())
|
||||
default:
|
||||
ferr = fn(w, t)
|
||||
}
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return ferr
|
||||
}
|
||||
|
||||
func (a *app) windows() ([]windowInfo, error) {
|
||||
var out []windowInfo
|
||||
err := a.onMain(func() {
|
||||
for _, w := range mygo.Windows() {
|
||||
if w.IsDestroyed() {
|
||||
continue
|
||||
}
|
||||
info := windowInfo{
|
||||
ID: w.ID(), Title: w.Title(), Kind: "page",
|
||||
Bounds: rectOf(w.Bounds()), ContentBounds: rectOf(w.ContentBounds()),
|
||||
Focused: w.IsFocused(), Visible: w.IsVisible(),
|
||||
}
|
||||
if _, ok := a.targets[w]; ok {
|
||||
info.Kind = "content"
|
||||
} else if p := w.Page(); p != nil {
|
||||
info.URL = p.URL()
|
||||
}
|
||||
out = append(out, info)
|
||||
}
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
func rectOf(r mygo.Rectangle) rect {
|
||||
return rect{float64(r.X), float64(r.Y), float64(r.Width), float64(r.Height)}
|
||||
}
|
||||
|
||||
// tree reads the elements the window shows: in a window out of sight, of
|
||||
// the frame waiting to build (Automated.Settle), built first.
|
||||
func (a *app) tree(id int) (window int, tree *platform.AccessTree, keys map[uint64]any, err error) {
|
||||
err = a.content(id, func(w *mygo.Window, t target) error {
|
||||
window = w.ID()
|
||||
t.content.Settle()
|
||||
tree, keys = t.content.AutomationTree()
|
||||
return nil
|
||||
})
|
||||
return window, tree, keys, err
|
||||
}
|
||||
|
||||
// act gives the content an action of assistive technology, as the
|
||||
// backend gives it those of the system's. In a window out of sight, the
|
||||
// frame that takes it builds at once (Automated.Settle).
|
||||
func (a *app) act(id int, ev platform.SurfaceEvent) error {
|
||||
return a.content(id, func(w *mygo.Window, t target) error {
|
||||
t.content.Settle()
|
||||
tree, _ := t.content.AutomationTree()
|
||||
for _, n := range tree.Nodes {
|
||||
if n.ID == ev.ID {
|
||||
t.conn.Event(ev)
|
||||
t.content.Settle()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errorf(codeNoElement, "window %d shows no element %d", w.ID(), ev.ID)
|
||||
})
|
||||
}
|
||||
|
||||
// input gives the content events, as the backend gives it the system's,
|
||||
// and in a window out of sight builds the frame that takes them.
|
||||
func (a *app) input(id int, evs []platform.SurfaceEvent) error {
|
||||
return a.content(id, func(w *mygo.Window, t target) error {
|
||||
for _, ev := range evs {
|
||||
t.conn.Event(ev)
|
||||
}
|
||||
t.content.Settle()
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (a *app) menu(id int, path []string) error {
|
||||
w, err := a.window(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var merr error
|
||||
if err := a.onMain(func() { merr = chooseMenuItem(w, path) }); err != nil {
|
||||
return err
|
||||
}
|
||||
if merr != nil {
|
||||
var e *Error
|
||||
if !errors.As(merr, &e) {
|
||||
merr = errorf(codeFailed, "%v", merr)
|
||||
}
|
||||
}
|
||||
return merr
|
||||
}
|
||||
|
||||
func (a *app) capture(id int) ([]byte, error) {
|
||||
w, err := a.window(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := w.CapturePage()
|
||||
if err != nil {
|
||||
return nil, errorf(codeFailed, "%v", err)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (a *app) eval(id int, script string) (any, error) {
|
||||
w, err := a.window(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p := w.Page()
|
||||
if p == nil {
|
||||
return nil, errorf(codeUnsupported, "window %d shows native UI, not a web page: use tree", w.ID())
|
||||
}
|
||||
v, err := p.Eval(script)
|
||||
if err != nil {
|
||||
return nil, errorf(codeFailed, "%v", err)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// pollEvery is how often idle asks whether the window settled.
|
||||
const pollEvery = 5 * time.Millisecond
|
||||
|
||||
// idle returns once the window has drawn the frames it asked for: for a
|
||||
// window of native UI, once its content asks for no frame (as
|
||||
// ui.Tester.FramePending tells); for a page, once it has loaded and
|
||||
// answered a script.
|
||||
func (a *app) idle(id int, timeout time.Duration) error {
|
||||
w, err := a.window(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var deadline time.Time
|
||||
if timeout > 0 {
|
||||
deadline = time.Now().Add(timeout)
|
||||
}
|
||||
for {
|
||||
pending := false
|
||||
err := a.content(id, func(_ *mygo.Window, t target) error {
|
||||
t.content.Settle()
|
||||
pending = t.content.FramePending()
|
||||
return nil
|
||||
})
|
||||
var e *Error
|
||||
if errors.As(err, &e) && e.Code == codeUnsupported {
|
||||
// A page.
|
||||
p := w.Page()
|
||||
if p == nil {
|
||||
return errorf(codeNoWindow, "window %d closed", w.ID())
|
||||
}
|
||||
pending = p.IsLoading()
|
||||
if !pending {
|
||||
if _, err := p.Eval("true"); err != nil {
|
||||
return errorf(codeFailed, "%v", err)
|
||||
}
|
||||
}
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
if !pending {
|
||||
return nil
|
||||
}
|
||||
if !deadline.IsZero() && time.Now().After(deadline) {
|
||||
return errorf(codeTimeout, "window %d still draws after %v", w.ID(), timeout)
|
||||
}
|
||||
time.Sleep(pollEvery)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
---
|
||||
name: mygo-automation
|
||||
description: Drive a running MyGo app from the shell. Read the elements of its native UI as compact text with short refs, press, fill, click, type, send keys and wheel events, choose application menu items, evaluate scripts in windows showing a web page, wait for the UI to settle and read what changed, save screenshots.
|
||||
---
|
||||
|
||||
# mygo-automation
|
||||
|
||||
`mygo-automation` drives a running MyGo app through the socket of its
|
||||
automation plugin (`github.com/egoist/mygo/plugins/automation`). It is
|
||||
the guide of the version you run, as `mygo-automation version` tells. If
|
||||
the app's MyGo is another version, install the matching one (see
|
||||
"Installing").
|
||||
|
||||
The loop is: **snapshot → act with `--settle` → read the diff → act
|
||||
again**. Diffs carry the refs you act on next, so a new snapshot is
|
||||
seldom needed.
|
||||
|
||||
```sh
|
||||
mygo-automation open --socket /tmp/app.sock
|
||||
mygo-automation snapshot -i
|
||||
# @e2 [button] "Add" key=add
|
||||
# @e3 [textField] "Name" key=name
|
||||
mygo-automation press @e2 --settle
|
||||
# - @e1 [text] "Count: 0"
|
||||
# + @e1 [text] "Count: 1"
|
||||
# = @e2 [button] "Add" key=add
|
||||
mygo-automation fill @e3 "Ada" --settle
|
||||
mygo-automation screenshot /tmp/app.png
|
||||
mygo-automation close
|
||||
```
|
||||
|
||||
## The app
|
||||
|
||||
The app must link the plugin and be started with `MYGO_AUTOMATION`, the
|
||||
path of the socket it listens on. A file of the app's, kept out of its
|
||||
release by a build tag:
|
||||
|
||||
```go
|
||||
//go:build e2e
|
||||
|
||||
package main
|
||||
|
||||
import _ "github.com/egoist/mygo/plugins/automation"
|
||||
```
|
||||
|
||||
```sh
|
||||
go build -tags e2e -o /tmp/app . && MYGO_AUTOMATION=/tmp/app.sock /tmp/app &
|
||||
```
|
||||
|
||||
Any way of starting it works if the variable reaches it; `mygo dev`
|
||||
passes its environment to the app. Builds without the inspector
|
||||
(`-tags mygo_noinspector`, release builds of `mygo build` without
|
||||
`-debug`) leave the plugin out: they say so on standard error and never
|
||||
listen. The socket is the user's alone. Pick a path in a directory only
|
||||
the user can write to; nothing else is needed to connect, and there is
|
||||
no discovery: the path is the one you gave `MYGO_AUTOMATION`.
|
||||
|
||||
## Sessions
|
||||
|
||||
- `open [--socket <path>]` attaches a session to the app and lists its
|
||||
windows. Without `--socket` it takes `$MYGO_AUTOMATION`. Opening again
|
||||
keeps the session's name but forgets what it saw: every ref given
|
||||
before goes stale.
|
||||
- `close` ends the session and forgets its refs. **The app keeps
|
||||
running.** To quit it, choose its menu item (`menu <App> Quit`, when
|
||||
it has one) or end its process yourself.
|
||||
- Every command takes `--session <name>` (default:
|
||||
`$MYGO_AUTOMATION_SESSION`, else `default`), letters, digits, `.`,
|
||||
`_` and `-`. Sessions keep their socket, chosen window and refs apart,
|
||||
in files of their own in the user's cache directory
|
||||
(`mygo/automation/<name>.json`). Give each agent, or each app, a session
|
||||
of its own; run one command at a time in a session.
|
||||
|
||||
## Reading the UI
|
||||
|
||||
`snapshot` prints the elements of a window of native UI, one per line, a
|
||||
child indented under the element shown above it, in tree order:
|
||||
|
||||
```
|
||||
@e1 [dialog] "Settings"
|
||||
@e2 [checkBox] "Dark mode" key=dark checked focused
|
||||
@e3 [textField] "Name" value="Ada" key=name
|
||||
@e4 [slider] "Volume" value=0.25
|
||||
@e5 [button] "Save" disabled
|
||||
announced "Saved"
|
||||
```
|
||||
|
||||
A line is the element's ref, `[role]`, its label in quotes, then what
|
||||
it has of `value=`, `placeholder=` (when it has no label), `key=` (the
|
||||
app's own name for it), its states, `current=` (what it is the current
|
||||
one of, as the last crumb of a breadcrumb trail is the `page`),
|
||||
`autocomplete=` (what a field's suggestions complete as you type: `list`
|
||||
for a popup of them, `inline` for the text completed in place, or
|
||||
`both`), `haspopup=`, `roledescription=` and `focused`. Empty fields are left
|
||||
out, and so is `focusable`, which every control is. `webview` marks a web
|
||||
view inside native UI: its page has no elements here. `announced` lines
|
||||
are what the app announced to screen readers. Labels and values longer
|
||||
than 120 characters are cut, ending in `…" (N more)`.
|
||||
`keyshortcuts=` (after `key=`) is the keys the app says press or focus
|
||||
the element, as screen readers read them (`aria-keyshortcuts`): `"⌘K"`
|
||||
on macOS, `"Ctrl+K"` elsewhere, several separated by spaces.
|
||||
|
||||
- `-i` (`--interactive`) keeps controls and elements with actions:
|
||||
buttons, fields, check boxes, links, list items you can press, and so
|
||||
on. Elements left out still get refs, and diffs show them.
|
||||
- `--full` adds placeholders, descriptions, ranges (`range=0..1
|
||||
step=0.1`), text selections (`selection=3,3`, in characters), levels,
|
||||
positions in sets (`item=2/5`), the size of a table or a grid and
|
||||
the place of a row or a cell in it as the app gave them
|
||||
(`rowcount=10001 colcount=5`, `rowindex=4122 colindex=2`), the rows
|
||||
and columns a cell covers (`colspan=2`), actions, `bounds=x,y,wxh` and the full
|
||||
element ID (`id=…`), and writes long text whole.
|
||||
- `--json` prints the plugin's answer as it is (IDs, keys, bounds, all
|
||||
fields) on one line. It still takes the window's elements for later
|
||||
diffs and gives refs, which it does not print.
|
||||
- `--window <w>` reads another window (see "Windows and pages").
|
||||
|
||||
Roles are `group`, `text`, `heading`, `button`, `link`, `checkBox`,
|
||||
`radio`, `switch`, `slider`, `progress`, `meter`, `stepper`,
|
||||
`textField`, `comboBox`, `popUpButton`, `menuButton`, `toggleButton`,
|
||||
`image`, `list`, `listItem`, `table`, `grid`, `treeGrid`, `row`, `cell`, `columnHeader`,
|
||||
`tree`, `treeItem`, `tabList`, `tab`, `scroll`, `dialog`, `alertDialog`,
|
||||
`popup`, `tooltip`, `splitter`, `status`, `toolbar`, `radioGroup`,
|
||||
`disclosure`, `colorWell`, `menu`, `menuBar`, `menuItem`,
|
||||
`menuItemCheckBox`, `menuItemRadio`, `region`, `log`, `timer`, `alert`,
|
||||
`separator`, `rowHeader`, `search`, `article`, `navigation`, `deletion`,
|
||||
`insertion`, `tabPanel`, `main`, `banner`, `contentInfo` and
|
||||
`complementary`. States are `disabled`, `checked`,
|
||||
`mixed`, `selected`, `expanded`, `expandable`, `multiline`, `password`,
|
||||
`readOnly`, `selectable`, `multiselectable`, `offscreen`, `segment`,
|
||||
`search`, `invalid`, `sortAscending`, `sortDescending`, `sortOther`,
|
||||
`vertical`, `horizontal` and `busy`. `current=` is `true`, `page`, `step`, `location`,
|
||||
`date` or `time`; `haspopup=` the kind of popup the element opens
|
||||
(`menu`, `listbox`, `tree`, `grid` or `dialog`), and `roledescription=`
|
||||
what the app calls its role.
|
||||
Only what assistive technology reads is there: rows and columns that
|
||||
only lay out others have no line.
|
||||
|
||||
## Selectors
|
||||
|
||||
Commands that act on an element take one of:
|
||||
|
||||
| Selector | Names |
|
||||
| --- | --- |
|
||||
| `@e7` (or `e7`) | the element a snapshot or diff gave that ref, in its window |
|
||||
| `key=<key>` | the one element of the window whose key the app set (`Element.Key`, `Context.Key`) |
|
||||
| `id=<digits>` | the element with that ID, as `--full` and `--json` show |
|
||||
|
||||
Write keys as lines show them: `key=add`, `key=7` (a number), `key=true`
|
||||
(a boolean), `key='"7"'` or `key='"two words"'` (strings that need JSON's
|
||||
quotes, quoted again for the shell). A key two elements share is refused:
|
||||
use a ref. Prefer keys when the app gives them; they last across runs.
|
||||
|
||||
## Refs
|
||||
|
||||
- Refs come from `snapshot`, `diff` and `--settle`. Use the refs of the
|
||||
latest output for a window.
|
||||
- An element keeps its ref while the window shows it: after `press @e2
|
||||
--settle`, `@e2` still names the same button, printed or not.
|
||||
- New elements get new numbers. A ref is never given twice in a session,
|
||||
so it can't come to name another element.
|
||||
- A ref goes **stale** once a snapshot or diff of its window shows its
|
||||
element gone, or the app answers that it is gone. A stale ref is
|
||||
refused, never retargeted:
|
||||
`error: stale ref @e4: its element is gone; use a ref from the latest snapshot or diff (run snapshot)`.
|
||||
An element that comes back gets a new ref.
|
||||
- A ref carries its window: commands on it go there, whatever `window`
|
||||
or `--window` says.
|
||||
- `open` again, or `close`, ends every ref of the session.
|
||||
|
||||
## Acting
|
||||
|
||||
| Command | Does |
|
||||
| --- | --- |
|
||||
| `press <sel>` | presses, as assistive technology does: clicks a button, toggles a check box, opens a menu button |
|
||||
| `focus <sel>` | gives the element the keyboard focus |
|
||||
| `fill <sel> <text>` | replaces a text field's text (`""` empties it) |
|
||||
| `act <sel> <action> [args]` | any action: `press`, `focus`, `increment`, `decrement`, `setValue <text>`, `insertText <text>` (at the caret), `selectText <from> <to>` (characters), `scrollIntoView`, `expand`, `collapse` |
|
||||
| `click <sel>` or `click <x> <y>` | a pointer click at the element's center, or at a point; `--button left\|right\|middle`, `--clicks 2` for a double click, `--mods shift,ctrl,alt,super,cmdOrCtrl` |
|
||||
| `pointer move\|down\|up <sel>\|<x> <y>` | one pointer event, with the same flags, for drags and hovers |
|
||||
| `wheel <sel>\|<x> <y> <dx> <dy>` | scrolls by `dx`, `dy` DIPs (negative `dy` scrolls up); `--precise` as a touchpad, `--mods` |
|
||||
| `type <text>` | types text into the focused element, as the keyboard does |
|
||||
| `key <key>...` | presses and releases keys in order, written as menu accelerators: `Enter`, `Escape`, `Tab`, `Shift+Tab`, `Backspace`, `Delete`, `Up`, `PageDown`, `Home`, `F2`, `a`, `CmdOrCtrl+A`, `CmdOrCtrl+Shift+Z`; `--down` or `--up` sends only the press or the release |
|
||||
| `menu <label>...` | chooses an item of the application menu by the labels along its path: `menu File "New Window"` |
|
||||
|
||||
Points are in DIPs, from the top left corner of the window's content, as
|
||||
`bounds=` shows. Prefer `press` and `fill` to `click` and `type`: they
|
||||
need no coordinates and no focus. A key types no text: send text with
|
||||
`type`. A modifier alone (`key Shift`) is no key. Without `--settle`, an
|
||||
action prints `ok` once the app took it, which may be before it drew.
|
||||
|
||||
`press`, `focus`, `fill`, `act`, `click`, `pointer`, `wheel`, `type`,
|
||||
`key`, `menu` and `wait` take `--window <w>` (for coordinates, keys,
|
||||
text and menus), `--settle` and `--timeout <d>`.
|
||||
|
||||
## Settle and diff
|
||||
|
||||
`--settle` waits until the window has drawn every frame it asked for (the
|
||||
plugin's `idle`), for `--timeout` (default `10s`; `500ms`, a number of
|
||||
milliseconds, or `0` to wait as long as it takes), then prints what
|
||||
changed since the last snapshot or diff of that window, and takes what it
|
||||
shows now for the next diff:
|
||||
|
||||
```
|
||||
= @e2 [button] "Add" key=add
|
||||
- @e3 [textField] "Name" key=name
|
||||
+ @e3 [textField] "Name" value="Ada" key=name focused
|
||||
+ @e4 [text] "Hello, Ada"
|
||||
- @e9 [dialog] "Unsaved changes"
|
||||
```
|
||||
|
||||
- `+` an element that came, with its new ref, or an element as it is now.
|
||||
- `-` an element that went, with its now stale ref, or an element as it
|
||||
was before: a changed element shows as `-` then `+`, with one ref.
|
||||
- `=` an unchanged element next to a change, for context, with its ref.
|
||||
- `(no changes)` when nothing changed. Moves and bounds are not changes.
|
||||
|
||||
A window that never settles, as one with a spinner, warns on standard
|
||||
error after `--timeout` and prints the diff anyway. `diff` prints the
|
||||
same without acting or waiting. An action on a ref diffs the ref's
|
||||
window. One that names no window (`type`, `key`, `menu`, points) while
|
||||
the session targets the focused window diffs the window focused once it
|
||||
settled: a window it opened comes as `+` lines.
|
||||
|
||||
## Waiting
|
||||
|
||||
- `wait` waits for the window to settle (`--timeout`, as above).
|
||||
- `wait <sel>` waits until the window shows the element; `wait --text
|
||||
<s>` until an element's label or value contains `s` (case sensitive).
|
||||
These check the condition while the window keeps drawing; `--settle`
|
||||
waits for it to settle after the condition is met.
|
||||
- `--gone` waits until it no longer shows it, as a dialog closing.
|
||||
- It prints `ok`, or with `--settle` the diff. After `--timeout` it fails
|
||||
with `timeout`. Never sleep: wait for what you expect.
|
||||
|
||||
## Windows and pages
|
||||
|
||||
- `windows` lists the windows: `w1 [content] "Title" focused`; `[content]`
|
||||
shows native UI, `[page]` a web page, with its `url=`; `hidden` and
|
||||
`selected` mark windows not shown and the one the session targets.
|
||||
`--json` prints the plugin's answer.
|
||||
- `window <w>` makes commands target window `w` (`w2` or `2`) unless they
|
||||
name one with `--window`; `window auto` goes back to the focused window,
|
||||
the default, else the first.
|
||||
- Native UI windows have elements: `snapshot`, selectors, `press`, input.
|
||||
- Page windows have none: `snapshot` and input fail with `unsupported`.
|
||||
Read and drive them with `eval <script>`, which prints a string as it
|
||||
is and other values as JSON (`--json`: always JSON); `eval -` reads the
|
||||
script from standard input. An expression's value is printed, promises
|
||||
awaited, or what statements `return`.
|
||||
- A web view inside native UI is one `webview` element: neither
|
||||
`snapshot` nor `eval` reaches its page.
|
||||
|
||||
## Screenshots
|
||||
|
||||
`screenshot <file.png> [--window <w>]` saves the window as a PNG file and
|
||||
prints `<file> <width>x<height>` in device pixels. It never prints the
|
||||
image. Take one only when text does not tell you enough.
|
||||
|
||||
## Output and errors
|
||||
|
||||
Output goes to standard output; errors go to standard error as
|
||||
`error: <message>`, with exit status 1, or 2 for a command line used
|
||||
wrong. Errors from the app start with its code:
|
||||
|
||||
| Error | Means | Do |
|
||||
| --- | --- | --- |
|
||||
| `no session "<name>"` | no `open` for this session | `open --socket <path>` |
|
||||
| `cannot reach the app at <path>` | nothing listens: the app quit, never set `MYGO_AUTOMATION`, or lacks the plugin | start the app, then `open` |
|
||||
| `stale ref @eN` | the ref's element or window is gone | `snapshot`, use a ref it gives |
|
||||
| `no_window` | no window has that ID, or the app has none | `windows` |
|
||||
| `no_element` | the window shows no such element or key | `snapshot` |
|
||||
| `unsupported` | the window cannot do it, as `snapshot` of a page or `eval` in native UI | use the other one |
|
||||
| `timeout` | `wait` did not see what it waited for, or the window never settled | look at a `snapshot`; raise `--timeout` |
|
||||
| `invalid_request` | a value the app can't use, as an unknown key name | fix the command |
|
||||
| `failed` | the app could not do it, as a script that threw, or a menu item it lacks | read the message |
|
||||
|
||||
## Limits
|
||||
|
||||
- Context menus, and the menus of the Dock and of tray icons, can't be
|
||||
chosen: don't open a context menu with `click --button right`.
|
||||
- Settling waits for frames asked for, not for timers the app set
|
||||
(`Context.After`) or work it does in the background: use `wait <sel>`
|
||||
or `wait --text` for those.
|
||||
- On Linux and Windows, `menu` chooses from the window's menu bar, which
|
||||
shows the application menu.
|
||||
- The command does not start or quit the app.
|
||||
|
||||
## Installing
|
||||
|
||||
```sh
|
||||
# In the app's module directory: the version of MyGo its go.mod requires.
|
||||
go install github.com/egoist/mygo/plugins/automation/cmd/mygo-automation
|
||||
# Anywhere else: name that version, which this prints in the app's module.
|
||||
go list -m github.com/egoist/mygo
|
||||
go install github.com/egoist/mygo/plugins/automation/cmd/mygo-automation@vX.Y.Z
|
||||
```
|
||||
|
||||
`version` prints the version of MyGo the command was built from (as
|
||||
`v0.8.0`; `(devel)` or a pseudo-version for a build from a checkout), and
|
||||
`skills` prints this guide. `go install` puts `mygo-automation` in
|
||||
`$(go env GOBIN)`, else
|
||||
`$(go env GOPATH)/bin`. Upgrading the app's MyGo does not upgrade the
|
||||
installed command: install it again, and this guide comes with it.
|
||||
@@ -0,0 +1,26 @@
|
||||
// Command mygo-automation drives a running MyGo app through
|
||||
// plugins/automation's socket, made for AI coding agents: compact text
|
||||
// snapshots of a window's elements with short refs (@e1), actions on
|
||||
// them, and diffs of what the window shows once it settled.
|
||||
//
|
||||
// go install github.com/egoist/mygo/plugins/automation/cmd/mygo-automation
|
||||
// mygo-automation skills
|
||||
//
|
||||
// skills prints the guide, SKILL.md, embedded in the command so that it
|
||||
// matches the commands of the version installed. See
|
||||
// docs/plugins/automation.md.
|
||||
package main
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"os"
|
||||
|
||||
"github.com/egoist/mygo/internal/automationcli"
|
||||
)
|
||||
|
||||
//go:embed SKILL.md
|
||||
var skill []byte
|
||||
|
||||
func main() {
|
||||
os.Exit(automationcli.Run(os.Args[1:], os.Stdin, os.Stdout, os.Stderr, automationcli.Options{Skill: skill}))
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/automationcli"
|
||||
)
|
||||
|
||||
// TestSkills checks that skills prints SKILL.md as it is, and that the
|
||||
// guide tells of every command.
|
||||
func TestSkills(t *testing.T) {
|
||||
var out, errs bytes.Buffer
|
||||
if code := automationcli.Run([]string{"skills"}, nil, &out, &errs, automationcli.Options{Skill: skill}); code != 0 || errs.Len() > 0 {
|
||||
t.Fatalf("skills: exit %d: %s", code, errs.String())
|
||||
}
|
||||
file, err := os.ReadFile("SKILL.md")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(out.Bytes(), file) {
|
||||
t.Error("skills does not print SKILL.md as it is")
|
||||
}
|
||||
if !bytes.HasPrefix(file, []byte("---\nname: mygo-automation\ndescription: ")) {
|
||||
t.Error("SKILL.md lacks its front matter")
|
||||
}
|
||||
for _, name := range automationcli.Commands() {
|
||||
if !strings.Contains(string(file), "`"+name+" ") && !strings.Contains(string(file), "`"+name+"`") {
|
||||
t.Errorf("SKILL.md does not tell of %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
// Package automation lets another process drive a running app, as an
|
||||
// end-to-end test runner or an agent does: list its windows, read what
|
||||
// their native UI shows as elements, act on them, send pointer, wheel,
|
||||
// key and text input, choose items of the application menu, evaluate
|
||||
// scripts in pages, capture windows as PNG images, and wait for them to
|
||||
// settle.
|
||||
//
|
||||
// An app opts in by importing the package, as a file built for tests
|
||||
// does:
|
||||
//
|
||||
// //go:build e2e
|
||||
//
|
||||
// package main
|
||||
//
|
||||
// import _ "github.com/egoist/mygo/plugins/automation"
|
||||
//
|
||||
// Then it listens only when the environment variable MYGO_AUTOMATION names
|
||||
// the path of a Unix domain socket, which only the user can open, and
|
||||
// answers JSON requests on it, one per line:
|
||||
//
|
||||
// MYGO_AUTOMATION=/tmp/app.sock ./app
|
||||
//
|
||||
// Builds without the inspector of native UI (-tags mygo_noinspector, as
|
||||
// mygo build makes for release) leave the plugin out: it never listens
|
||||
// there. See docs/plugins/automation.md for the protocol, and for
|
||||
// mygo-automation (cmd/mygo-automation), its command line client for
|
||||
// agents.
|
||||
package automation
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
//go:build !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// listen listens on the Unix domain socket at path, which only the user
|
||||
// can open. A socket left there by an app that ended without closing it
|
||||
// is removed; one that an app listens on, or a file that is no socket, is
|
||||
// left alone.
|
||||
//
|
||||
// A path that starts with @ is in Android's abstract namespace, where an
|
||||
// app's files are out of adb's reach:
|
||||
//
|
||||
// adb forward tcp:9000 localabstract:mygo
|
||||
func listen(path string) (net.Listener, error) {
|
||||
if strings.HasPrefix(path, "@") {
|
||||
return net.Listen("unix", path)
|
||||
}
|
||||
// A phone on a cable, whose files no socket of this computer reaches: anyone
|
||||
// on its networks can reach the port too, so use it where you trust those,
|
||||
// with a build that isn't a release, which has no plugin.
|
||||
if addr, ok := strings.CutPrefix(path, "tcp:"); ok {
|
||||
return net.Listen("tcp", addr)
|
||||
}
|
||||
if fi, err := os.Lstat(path); err == nil {
|
||||
if fi.Mode().Type() != os.ModeSocket {
|
||||
return nil, fmt.Errorf("%s exists and is not a socket", path)
|
||||
}
|
||||
if c, err := net.Dial("unix", path); err == nil {
|
||||
c.Close()
|
||||
return nil, fmt.Errorf("another app listens on %s", path)
|
||||
}
|
||||
if err := os.Remove(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return listenPrivate(path)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//go:build !unix && !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import "net"
|
||||
|
||||
// listenPrivate listens on the socket. On Windows, a socket's file has no
|
||||
// mode: it takes the access control list of its directory, which is the
|
||||
// user's alone in the user's profile and temporary directory.
|
||||
func listenPrivate(path string) (net.Listener, error) { return net.Listen("unix", path) }
|
||||
@@ -0,0 +1,27 @@
|
||||
//go:build unix && !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// listenPrivate makes the socket readable and writable by the user alone,
|
||||
// from the start: with the umask that leaves the others out while the
|
||||
// socket is made, which runs in init, before goroutines of the app make
|
||||
// files, and with its mode after.
|
||||
func listenPrivate(path string) (net.Listener, error) {
|
||||
old := syscall.Umask(0o177)
|
||||
l, err := net.Listen("unix", path)
|
||||
syscall.Umask(old)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
l.Close()
|
||||
return nil, err
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build darwin && !ios && !mygo_noinspector && !ios
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/internal/darwin"
|
||||
)
|
||||
|
||||
// chooseMenuItem chooses an item of the application menu by the titles
|
||||
// along its path, as the menu bar does. Main thread only.
|
||||
func chooseMenuItem(_ *mygo.Window, path []string) error {
|
||||
return darwin.TestPerformMenuItem(path...)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build linux && !android && (amd64 || arm64) && !mygo_noinspector && !android
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/internal/linux"
|
||||
)
|
||||
|
||||
// chooseMenuItem chooses an item of the window's menu bar, which shows
|
||||
// the application menu, by the labels along its path. Main thread only.
|
||||
func chooseMenuItem(w *mygo.Window, path []string) error {
|
||||
return linux.TestActivateMenuItem(w.NativeHandle(), path...)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//go:build !(darwin && !ios) && !(linux && !android && (amd64 || arm64)) && !(windows && (amd64 || arm64)) && !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import "github.com/egoist/mygo"
|
||||
|
||||
// chooseMenuItem has no menus to choose from on other platforms.
|
||||
func chooseMenuItem(*mygo.Window, []string) error {
|
||||
return errorf(codeUnsupported, "this platform has no menus to choose from")
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build windows && (amd64 || arm64) && !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/internal/windows"
|
||||
)
|
||||
|
||||
// chooseMenuItem chooses an item of the window's menu bar, which shows
|
||||
// the application menu, by the labels along its path. Main thread only.
|
||||
func chooseMenuItem(w *mygo.Window, path []string) error {
|
||||
return windows.TestActivateMenuItem(w.NativeHandle(), path...)
|
||||
}
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
//go:build !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/egoist/mygo/internal/accelerator"
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// roleNames are the names of platform.AccessRole's roles, in their order.
|
||||
var roleNames = [...]string{
|
||||
"group", "text", "button", "link", "checkBox", "radio", "switch", "slider",
|
||||
"progress", "textField", "image", "list", "scroll", "dialog", "popup",
|
||||
"tooltip", "popUpButton", "tabList", "tab", "splitter", "status", "table",
|
||||
"row", "cell", "columnHeader", "tree", "treeItem", "listItem", "menuButton",
|
||||
"toolbar", "radioGroup", "toggleButton", "comboBox", "disclosure", "meter",
|
||||
"stepper", "colorWell", "alertDialog", "menu", "menuBar", "menuItem",
|
||||
"menuItemCheckBox", "menuItemRadio", "heading", "region", "log", "timer",
|
||||
"alert", "separator", "rowHeader", "search", "article",
|
||||
"navigation", "grid", "treeGrid", "deletion", "insertion", "tabPanel",
|
||||
"main", "banner", "contentInfo", "complementary",
|
||||
}
|
||||
|
||||
func roleName(r platform.AccessRole) string {
|
||||
if int(r) < len(roleNames) {
|
||||
return roleNames[r]
|
||||
}
|
||||
return "role" + strconv.Itoa(int(r))
|
||||
}
|
||||
|
||||
// stateNames are the names of platform.AccessStates' bits, from the
|
||||
// lowest.
|
||||
var stateNames = [...]string{
|
||||
"focusable", "disabled", "checked", "mixed", "selected", "expanded",
|
||||
"multiline", "password", "readOnly", "selectable", "offscreen",
|
||||
"multiselectable", "segment", "search", "invalid", "sortAscending",
|
||||
"sortDescending", "expandable", "vertical", "busy", "sortOther",
|
||||
"horizontal",
|
||||
}
|
||||
|
||||
// actionNames are the names of platform.AccessActions' bits, from the
|
||||
// lowest.
|
||||
var actionNames = [...]string{
|
||||
"press", "focus", "increment", "decrement", "setValue", "scrollIntoView", "expand",
|
||||
}
|
||||
|
||||
// names returns the names of the bits set in bits.
|
||||
func names(bits uint64, of []string) []string {
|
||||
var out []string
|
||||
for i, name := range of {
|
||||
if bits&(1<<i) != 0 {
|
||||
out = append(out, name)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// actionKinds are the actions act takes, by name.
|
||||
var actionKinds = map[string]platform.AccessActionKind{
|
||||
"press": platform.AccessPress,
|
||||
"focus": platform.AccessFocus,
|
||||
"increment": platform.AccessIncrement,
|
||||
"decrement": platform.AccessDecrement,
|
||||
"setValue": platform.AccessSetValue,
|
||||
"scrollIntoView": platform.AccessScrollIntoView,
|
||||
"expand": platform.AccessExpand,
|
||||
"collapse": platform.AccessCollapse,
|
||||
"selectText": platform.AccessSelectText,
|
||||
"insertText": platform.AccessInsertText,
|
||||
}
|
||||
|
||||
// inputEvent is an event of an input request.
|
||||
type inputEvent struct {
|
||||
// Type is pointerMove, pointerDown, pointerUp, click, wheel, keyDown,
|
||||
// keyUp, key or text.
|
||||
Type string `json:"type"`
|
||||
X float64 `json:"x"`
|
||||
Y float64 `json:"y"`
|
||||
// Button is left (the default), right or middle; Clicks counts quick
|
||||
// successive presses, 1 unless set.
|
||||
Button string `json:"button"`
|
||||
Clicks int `json:"clicks"`
|
||||
// DX and DY are a wheel's distances in DIPs, Precise marks a
|
||||
// touchpad's.
|
||||
DX float64 `json:"dx"`
|
||||
DY float64 `json:"dy"`
|
||||
Precise bool `json:"precise"`
|
||||
// Key is a key with its modifiers as menus' accelerators write them,
|
||||
// as "Enter" or "CmdOrCtrl+Shift+Z".
|
||||
Key string `json:"key"`
|
||||
// Mods are the modifiers held during a pointer or wheel event: shift,
|
||||
// ctrl, alt, super or cmdOrCtrl.
|
||||
Mods []string `json:"mods"`
|
||||
Text string `json:"text"`
|
||||
// Touch marks pointer events as a finger's, on a phone: they pan and fling
|
||||
// what scrolls, rather than press as a mouse's.
|
||||
Touch bool `json:"touch"`
|
||||
}
|
||||
|
||||
// surfaceEvents returns the events of the surface that evs make, as the
|
||||
// backend's would.
|
||||
func surfaceEvents(evs []inputEvent) ([]platform.SurfaceEvent, error) {
|
||||
var out []platform.SurfaceEvent
|
||||
for i, e := range evs {
|
||||
mods, err := modifiers(e.Mods)
|
||||
if err != nil {
|
||||
return nil, errorf(codeInvalid, "event %d: %v", i, err)
|
||||
}
|
||||
button := 0
|
||||
switch e.Button {
|
||||
case "", "left":
|
||||
case "right":
|
||||
button = 1
|
||||
case "middle":
|
||||
button = 2
|
||||
default:
|
||||
return nil, errorf(codeInvalid, "event %d: no button %q: left, right or middle", i, e.Button)
|
||||
}
|
||||
clicks := max(e.Clicks, 1)
|
||||
at := platform.SurfaceEvent{X: e.X, Y: e.Y, Mods: mods, Touch: e.Touch}
|
||||
pointer := func(kind platform.SurfaceEventKind, clicks int) platform.SurfaceEvent {
|
||||
ev := at
|
||||
ev.Kind, ev.Button, ev.Clicks = kind, button, clicks
|
||||
return ev
|
||||
}
|
||||
switch e.Type {
|
||||
case "pointerMove":
|
||||
out = append(out, pointer(platform.PointerMove, 0))
|
||||
case "pointerDown":
|
||||
out = append(out, pointer(platform.PointerDown, clicks))
|
||||
case "pointerUp":
|
||||
out = append(out, pointer(platform.PointerUp, clicks))
|
||||
if e.Touch {
|
||||
// A finger is gone as it lifts, as phones tell.
|
||||
out = append(out, platform.SurfaceEvent{Kind: platform.PointerLeave, Touch: true})
|
||||
}
|
||||
case "click":
|
||||
// A double click is two presses, the second counting 2.
|
||||
out = append(out, pointer(platform.PointerMove, 0))
|
||||
for n := 1; n <= clicks; n++ {
|
||||
out = append(out, pointer(platform.PointerDown, n), pointer(platform.PointerUp, n))
|
||||
}
|
||||
case "wheel":
|
||||
ev := pointer(platform.PointerScroll, 0)
|
||||
ev.DX, ev.DY, ev.Precise = e.DX, e.DY, e.Precise
|
||||
out = append(out, ev)
|
||||
case "keyDown", "keyUp", "key":
|
||||
k, mods, err := parseKey(e.Key)
|
||||
if err != nil {
|
||||
return nil, errorf(codeInvalid, "event %d: %v", i, err)
|
||||
}
|
||||
ev := platform.SurfaceEvent{Key: k, PhysicalKey: k, Mods: mods}
|
||||
if e.Type != "keyUp" {
|
||||
ev.Kind = platform.KeyPressed
|
||||
out = append(out, ev)
|
||||
}
|
||||
if e.Type != "keyDown" {
|
||||
ev.Kind = platform.KeyReleased
|
||||
out = append(out, ev)
|
||||
}
|
||||
case "text":
|
||||
if e.Text == "" {
|
||||
return nil, errorf(codeInvalid, "event %d: text has no text", i)
|
||||
}
|
||||
out = append(out, platform.SurfaceEvent{Kind: platform.TextInput, Text: e.Text})
|
||||
default:
|
||||
return nil, errorf(codeInvalid, "event %d: no event type %q", i, e.Type)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// modifiers returns the modifiers of names.
|
||||
func modifiers(list []string) (platform.Modifiers, error) {
|
||||
var mods platform.Modifiers
|
||||
for _, name := range list {
|
||||
switch strings.ToLower(name) {
|
||||
case "shift":
|
||||
mods |= platform.ModShift
|
||||
case "ctrl", "control":
|
||||
mods |= platform.ModCtrl
|
||||
case "alt", "option":
|
||||
mods |= platform.ModAlt
|
||||
case "super", "cmd", "command", "meta":
|
||||
mods |= platform.ModSuper
|
||||
case "cmdorctrl":
|
||||
if runtime.GOOS == "darwin" {
|
||||
mods |= platform.ModSuper
|
||||
} else {
|
||||
mods |= platform.ModCtrl
|
||||
}
|
||||
default:
|
||||
return 0, fmt.Errorf("no modifier %q", name)
|
||||
}
|
||||
}
|
||||
return mods, nil
|
||||
}
|
||||
|
||||
// namedKeys are the keys of accelerators that have a key of native UI,
|
||||
// by accelerator.Accelerator's names.
|
||||
var namedKeys = map[string]platform.Key{
|
||||
"Enter": platform.KeyEnter, "Escape": platform.KeyEscape, "Backspace": platform.KeyBackspace,
|
||||
"Tab": platform.KeyTab, "Space": platform.KeySpace, "Delete": platform.KeyDelete,
|
||||
"Insert": platform.KeyInsert, "Home": platform.KeyHome, "End": platform.KeyEnd,
|
||||
"PageUp": platform.KeyPageUp, "PageDown": platform.KeyPageDown, "Left": platform.KeyLeft,
|
||||
"Right": platform.KeyRight, "Up": platform.KeyUp, "Down": platform.KeyDown,
|
||||
}
|
||||
|
||||
// parseKey returns the key and the modifiers of an accelerator.
|
||||
func parseKey(s string) (platform.Key, platform.Modifiers, error) {
|
||||
a, err := accelerator.Parse(s, runtime.GOOS)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
var mods platform.Modifiers
|
||||
for _, m := range []struct {
|
||||
a accelerator.Modifiers
|
||||
p platform.Modifiers
|
||||
}{{accelerator.Super, platform.ModSuper}, {accelerator.Ctrl, platform.ModCtrl}, {accelerator.Alt, platform.ModAlt}, {accelerator.Shift, platform.ModShift}} {
|
||||
if a.Has(m.a) {
|
||||
mods |= m.p
|
||||
}
|
||||
}
|
||||
k := namedKeys[a.Key]
|
||||
if r := []rune(a.Key); len(r) == 1 {
|
||||
k = platform.KeyForRune(r[0])
|
||||
} else if n, err := strconv.Atoi(strings.TrimPrefix(a.Key, "F")); err == nil && a.Key[0] == 'F' && n >= 1 && n <= 12 {
|
||||
k = platform.KeyF1 + platform.Key(n-1)
|
||||
}
|
||||
if k == platform.KeyUnknown {
|
||||
return 0, 0, fmt.Errorf("native UI has no key %q", a.Key)
|
||||
}
|
||||
return k, mods, nil
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
//go:build mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import "os"
|
||||
|
||||
// Builds without the inspector leave the plugin out, as they are the
|
||||
// app's release: it says so rather than leave a test runner waiting.
|
||||
func init() {
|
||||
if os.Getenv("MYGO_AUTOMATION") != "" {
|
||||
os.Stderr.WriteString("mygo: MYGO_AUTOMATION is ignored: this build leaves automation out (mygo_noinspector)\n")
|
||||
}
|
||||
}
|
||||
+515
@@ -0,0 +1,515 @@
|
||||
//go:build !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image/png"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// maxLine is the longest request a line may hold, as a script to
|
||||
// evaluate.
|
||||
const maxLine = 16 << 20
|
||||
|
||||
// request is a line a client sends.
|
||||
type request struct {
|
||||
// ID is any JSON value, which the response repeats.
|
||||
ID json.RawMessage `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params"`
|
||||
}
|
||||
|
||||
// response is the line that answers a request: its Result, or its Error.
|
||||
type response struct {
|
||||
ID json.RawMessage `json:"id"`
|
||||
Result any `json:"result,omitempty"`
|
||||
Error *Error `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Error is a request's failure, with a code clients test and a message
|
||||
// people read.
|
||||
type Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (e *Error) Error() string { return e.Code + ": " + e.Message }
|
||||
|
||||
// The codes of Error.
|
||||
const (
|
||||
// codeParse: the line is not a JSON object.
|
||||
codeParse = "parse_error"
|
||||
// codeInvalid: the request lacks a method, or its params are not the
|
||||
// method's.
|
||||
codeInvalid = "invalid_request"
|
||||
// codeUnknownMethod: no such method.
|
||||
codeUnknownMethod = "unknown_method"
|
||||
// codeNoWindow: no window has the ID, or the app has none.
|
||||
codeNoWindow = "no_window"
|
||||
// codeNoElement: no element of the window's last frame has the ID or
|
||||
// the key.
|
||||
codeNoElement = "no_element"
|
||||
// codeUnsupported: the window or the platform cannot do it, as
|
||||
// reading the elements of a page.
|
||||
codeUnsupported = "unsupported"
|
||||
// codeTimeout: the window did not settle in the time idle allowed.
|
||||
codeTimeout = "timeout"
|
||||
// codeFailed: the app could not do it, as a script that threw.
|
||||
codeFailed = "failed"
|
||||
)
|
||||
|
||||
func errorf(code, format string, args ...any) *Error {
|
||||
return &Error{Code: code, Message: fmt.Sprintf(format, args...)}
|
||||
}
|
||||
|
||||
// driver is what requests do in the app. Window 0 is the default window:
|
||||
// the focused one, else the first. Methods are called from the goroutines
|
||||
// of connections, and hop to the main thread for what they touch.
|
||||
type driver interface {
|
||||
windows() ([]windowInfo, error)
|
||||
tree(window int) (int, *platform.AccessTree, map[uint64]any, error)
|
||||
act(window int, ev platform.SurfaceEvent) error
|
||||
input(window int, evs []platform.SurfaceEvent) error
|
||||
menu(window int, path []string) error
|
||||
capture(window int) ([]byte, error)
|
||||
eval(window int, script string) (any, error)
|
||||
idle(window int, timeout time.Duration) error
|
||||
}
|
||||
|
||||
// serve answers the connections of l until it closes.
|
||||
func serve(l net.Listener, d driver) {
|
||||
for {
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go serveConn(c, d)
|
||||
}
|
||||
}
|
||||
|
||||
// serveConn answers the requests of a connection in order, each once the
|
||||
// one before it is answered, until the client closes it.
|
||||
func serveConn(c io.ReadWriteCloser, d driver) {
|
||||
defer c.Close()
|
||||
sc := bufio.NewScanner(c)
|
||||
sc.Buffer(make([]byte, 0, 64<<10), maxLine)
|
||||
enc := json.NewEncoder(c)
|
||||
enc.SetEscapeHTML(false)
|
||||
for sc.Scan() {
|
||||
line := bytes.TrimSpace(sc.Bytes())
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
if enc.Encode(handle(d, line)) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if errors.Is(sc.Err(), bufio.ErrTooLong) {
|
||||
enc.Encode(response{Error: errorf(codeParse, "a request is longer than %d bytes", maxLine)})
|
||||
}
|
||||
}
|
||||
|
||||
// handle answers a line.
|
||||
func handle(d driver, line []byte) response {
|
||||
var req request
|
||||
if err := json.Unmarshal(line, &req); err != nil {
|
||||
return response{Error: errorf(codeParse, "%v", err)}
|
||||
}
|
||||
res := response{ID: req.ID}
|
||||
v, err := call(d, req)
|
||||
if err != nil {
|
||||
var e *Error
|
||||
if !errors.As(err, &e) {
|
||||
e = &Error{Code: codeFailed, Message: err.Error()}
|
||||
}
|
||||
res.Error = e
|
||||
return res
|
||||
}
|
||||
res.Result = v
|
||||
return res
|
||||
}
|
||||
|
||||
// done is the result of requests that answer nothing but success.
|
||||
type done struct{}
|
||||
|
||||
// call performs a request.
|
||||
func call(d driver, req request) (any, error) {
|
||||
switch req.Method {
|
||||
case "":
|
||||
return nil, errorf(codeInvalid, "the request has no method")
|
||||
case "windows":
|
||||
if err := params(req, &struct{}{}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ws, err := d.windows()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return windowsResult{Windows: ws}, nil
|
||||
case "tree":
|
||||
var p windowParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w, t, keys, err := d.tree(p.Window)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return treeJSON(w, t, keys), nil
|
||||
case "act":
|
||||
var p actParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return act(d, p)
|
||||
case "input":
|
||||
var p inputParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
evs, err := surfaceEvents(p.Events)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return done{}, d.input(p.Window, evs)
|
||||
case "menu":
|
||||
var p menuParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(p.Path) == 0 {
|
||||
return nil, errorf(codeInvalid, "menu needs the path of the item, as [\"File\", \"New\"]")
|
||||
}
|
||||
return done{}, d.menu(p.Window, p.Path)
|
||||
case "capture":
|
||||
var p windowParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := d.capture(p.Window)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r := captureResult{PNG: b}
|
||||
if c, err := png.DecodeConfig(bytes.NewReader(b)); err == nil {
|
||||
r.Width, r.Height = c.Width, c.Height
|
||||
}
|
||||
return r, nil
|
||||
case "eval":
|
||||
var p evalParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := d.eval(p.Window, p.Script)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return evalResult{Value: v}, nil
|
||||
case "idle":
|
||||
var p idleParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p.Timeout < 0 {
|
||||
return nil, errorf(codeInvalid, "timeout is negative")
|
||||
}
|
||||
return done{}, d.idle(p.Window, time.Duration(p.Timeout)*time.Millisecond)
|
||||
}
|
||||
return nil, errorf(codeUnknownMethod, "no method %q", req.Method)
|
||||
}
|
||||
|
||||
// params decodes the params of a request into p, refusing fields the
|
||||
// method does not take.
|
||||
func params(req request, p any) error {
|
||||
raw := bytes.TrimSpace(req.Params)
|
||||
if len(raw) == 0 || bytes.Equal(raw, []byte("null")) {
|
||||
return nil
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(p); err != nil {
|
||||
return errorf(codeInvalid, "params of %s: %v", req.Method, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type windowParams struct {
|
||||
Window int `json:"window"`
|
||||
}
|
||||
|
||||
type actParams struct {
|
||||
Window int `json:"window"`
|
||||
ID nodeID `json:"id"`
|
||||
// Key finds the element by its key instead of ID.
|
||||
Key json.RawMessage `json:"key"`
|
||||
Action string `json:"action"`
|
||||
// Text is setValue's and insertText's; From and To are selectText's.
|
||||
Text string `json:"text"`
|
||||
From int `json:"from"`
|
||||
To int `json:"to"`
|
||||
}
|
||||
|
||||
type inputParams struct {
|
||||
Window int `json:"window"`
|
||||
Events []inputEvent `json:"events"`
|
||||
}
|
||||
|
||||
type menuParams struct {
|
||||
Window int `json:"window"`
|
||||
Path []string `json:"path"`
|
||||
}
|
||||
|
||||
type evalParams struct {
|
||||
Window int `json:"window"`
|
||||
Script string `json:"script"`
|
||||
}
|
||||
|
||||
type idleParams struct {
|
||||
Window int `json:"window"`
|
||||
// Timeout is in milliseconds, 0 for none.
|
||||
Timeout int `json:"timeout"`
|
||||
}
|
||||
|
||||
type windowsResult struct {
|
||||
Windows []windowInfo `json:"windows"`
|
||||
}
|
||||
|
||||
// windowInfo describes a window.
|
||||
type windowInfo struct {
|
||||
ID int `json:"id"`
|
||||
Title string `json:"title"`
|
||||
// Kind is "content" for a window of native UI, "page" for a web page.
|
||||
Kind string `json:"kind"`
|
||||
// URL is a page's.
|
||||
URL string `json:"url,omitempty"`
|
||||
Bounds rect `json:"bounds"`
|
||||
ContentBounds rect `json:"contentBounds"`
|
||||
Focused bool `json:"focused"`
|
||||
Visible bool `json:"visible"`
|
||||
}
|
||||
|
||||
type rect struct {
|
||||
X float64 `json:"x"`
|
||||
Y float64 `json:"y"`
|
||||
Width float64 `json:"width"`
|
||||
Height float64 `json:"height"`
|
||||
}
|
||||
|
||||
type captureResult struct {
|
||||
// PNG is encoded in base64, as encoding/json does []byte; Width and
|
||||
// Height are its size in pixels.
|
||||
PNG []byte `json:"png"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
}
|
||||
|
||||
type evalResult struct {
|
||||
Value any `json:"value"`
|
||||
}
|
||||
|
||||
// nodeID is the ID of an element. It goes as a string of its decimal
|
||||
// digits, which JavaScript's numbers would round, and comes as one or as
|
||||
// a number.
|
||||
type nodeID uint64
|
||||
|
||||
func (id nodeID) MarshalJSON() ([]byte, error) {
|
||||
return strconv.AppendQuote(nil, strconv.FormatUint(uint64(id), 10)), nil
|
||||
}
|
||||
|
||||
func (id *nodeID) UnmarshalJSON(b []byte) error {
|
||||
s := string(b)
|
||||
if u, err := strconv.Unquote(s); err == nil {
|
||||
s = u
|
||||
}
|
||||
n, err := strconv.ParseUint(s, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("an element ID is a string of digits, not %s", b)
|
||||
}
|
||||
*id = nodeID(n)
|
||||
return nil
|
||||
}
|
||||
|
||||
// act performs an action of assistive technology on the element of the
|
||||
// ID or the key.
|
||||
func act(d driver, p actParams) (any, error) {
|
||||
kind, ok := actionKinds[p.Action]
|
||||
if !ok {
|
||||
return nil, errorf(codeInvalid, "no action %q", p.Action)
|
||||
}
|
||||
hasKey := len(bytes.TrimSpace(p.Key)) > 0
|
||||
switch {
|
||||
case p.ID == 0 && !hasKey:
|
||||
return nil, errorf(codeInvalid, "act needs the id or the key of an element")
|
||||
case p.ID != 0 && hasKey:
|
||||
return nil, errorf(codeInvalid, "act takes an id or a key, not both")
|
||||
}
|
||||
id := uint64(p.ID)
|
||||
if hasKey {
|
||||
var want bytes.Buffer
|
||||
if err := json.Compact(&want, p.Key); err != nil {
|
||||
return nil, errorf(codeInvalid, "key: %v", err)
|
||||
}
|
||||
_, t, keys, err := d.tree(p.Window)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n := 0
|
||||
for _, node := range t.Nodes {
|
||||
k, ok := keys[node.ID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if b, err := json.Marshal(keyJSON(k)); err == nil && bytes.Equal(b, want.Bytes()) {
|
||||
id = node.ID
|
||||
n++
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case n == 0:
|
||||
return nil, errorf(codeNoElement, "no element has the key %s", want.Bytes())
|
||||
case n > 1:
|
||||
return nil, errorf(codeInvalid, "%d elements have the key %s: act on one by its id", n, want.Bytes())
|
||||
}
|
||||
}
|
||||
ev := platform.SurfaceEvent{Kind: platform.AccessAction, ID: id, Action: kind, Text: p.Text, From: p.From, To: p.To}
|
||||
return done{}, d.act(p.Window, ev)
|
||||
}
|
||||
|
||||
// treeJSON is the tree request's answer: the elements of window's last
|
||||
// frame.
|
||||
func treeJSON(window int, t *platform.AccessTree, keys map[uint64]any) treeResult {
|
||||
r := treeResult{Window: window, Focus: nodeID(t.Focus), Nodes: make([]nodeJSON, 0, len(t.Nodes)), Announcements: t.Announcements}
|
||||
for _, n := range t.Nodes {
|
||||
j := nodeJSON{
|
||||
ID: nodeID(n.ID), Role: roleName(n.Role), Label: n.Label, Value: n.Value,
|
||||
Placeholder: n.Placeholder, Description: n.Description, KeyShortcuts: n.KeyShortcuts,
|
||||
Bounds: rect{n.Bounds.X, n.Bounds.Y, n.Bounds.W, n.Bounds.H},
|
||||
States: names(uint64(n.States), stateNames[:]),
|
||||
Actions: names(uint64(n.Actions), actionNames[:]),
|
||||
Level: n.Level, PosInSet: n.PosInSet, SetSize: n.SetSize,
|
||||
RowCount: n.RowCount, ColCount: n.ColCount, RowIndex: n.RowIndex, ColIndex: n.ColIndex,
|
||||
RowSpan: n.RowSpan, ColSpan: n.ColSpan,
|
||||
Current: n.Current.String(), AutoComplete: n.AutoComplete.String(), WebView: n.WebView != nil,
|
||||
RoleDescription: n.RoleDescription, HasPopup: n.HasPopup.String(),
|
||||
}
|
||||
for _, c := range n.Controls {
|
||||
j.Controls = append(j.Controls, nodeID(c))
|
||||
}
|
||||
for _, d := range n.DescribedBy {
|
||||
j.DescribedBy = append(j.DescribedBy, nodeID(d))
|
||||
}
|
||||
if n.States&platform.AccessInvalid != 0 {
|
||||
for _, m := range n.ErrorMessage {
|
||||
j.ErrorMessage = append(j.ErrorMessage, nodeID(m))
|
||||
}
|
||||
}
|
||||
if n.Parent >= 0 && n.Parent < len(t.Nodes) {
|
||||
j.Parent = nodeID(t.Nodes[n.Parent].ID)
|
||||
}
|
||||
if k, ok := keys[n.ID]; ok {
|
||||
j.Key = keyJSON(k)
|
||||
}
|
||||
if n.Role.Ranged() {
|
||||
j.Min, j.Max, j.Now, j.Step = &n.Min, &n.Max, &n.Now, &n.Step
|
||||
}
|
||||
if n.Role == platform.RoleTextField || n.Role == platform.RoleComboBox {
|
||||
j.Selection = &[2]int{n.SelStart, n.SelEnd}
|
||||
}
|
||||
r.Nodes = append(r.Nodes, j)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
type treeResult struct {
|
||||
Window int `json:"window"`
|
||||
// Focus is the element with the keyboard focus.
|
||||
Focus nodeID `json:"focus,omitempty"`
|
||||
Nodes []nodeJSON `json:"nodes"`
|
||||
Announcements []string `json:"announcements,omitempty"`
|
||||
}
|
||||
|
||||
// nodeJSON is an element, as assistive technology reads it.
|
||||
type nodeJSON struct {
|
||||
ID nodeID `json:"id"`
|
||||
// Parent is omitted for the elements at the top.
|
||||
Parent nodeID `json:"parent,omitempty"`
|
||||
Role string `json:"role"`
|
||||
// Key is the key the app gave the element (ui's Key).
|
||||
Key any `json:"key,omitempty"`
|
||||
Label string `json:"label,omitempty"`
|
||||
Value string `json:"value,omitempty"`
|
||||
Placeholder string `json:"placeholder,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Bounds rect `json:"bounds"`
|
||||
States []string `json:"states,omitempty"`
|
||||
Actions []string `json:"actions,omitempty"`
|
||||
// Min, Max, Now and Step are those of a slider, a progress bar, a
|
||||
// meter or a stepper.
|
||||
Min *float64 `json:"min,omitempty"`
|
||||
Max *float64 `json:"max,omitempty"`
|
||||
Now *float64 `json:"now,omitempty"`
|
||||
Step *float64 `json:"step,omitempty"`
|
||||
// KeyShortcuts are the keys that press or focus the element, as
|
||||
// ARIA's aria-keyshortcuts, as the platform's menus write them
|
||||
// ("⌘K" on macOS, "Ctrl+K" elsewhere), separated by spaces.
|
||||
KeyShortcuts string `json:"keyShortcuts,omitempty"`
|
||||
// Selection is a text field's, in runes.
|
||||
Selection *[2]int `json:"selection,omitempty"`
|
||||
Level int `json:"level,omitempty"`
|
||||
PosInSet int `json:"posInSet,omitempty"`
|
||||
SetSize int `json:"setSize,omitempty"`
|
||||
// RowCount and ColCount are how many rows and columns a table or a
|
||||
// grid has, and RowIndex and ColIndex the place of a row or a cell
|
||||
// among them, from 1, as the app gave them (aria-rowcount,
|
||||
// aria-colcount, aria-rowindex, aria-colindex).
|
||||
RowCount int `json:"rowCount,omitempty"`
|
||||
ColCount int `json:"colCount,omitempty"`
|
||||
RowIndex int `json:"rowIndex,omitempty"`
|
||||
ColIndex int `json:"colIndex,omitempty"`
|
||||
// RowSpan and ColSpan are how many rows and columns a cell covers,
|
||||
// when more than one (aria-rowspan, aria-colspan).
|
||||
RowSpan int `json:"rowSpan,omitempty"`
|
||||
ColSpan int `json:"colSpan,omitempty"`
|
||||
// Current is the item the element is the current one of, as ARIA's
|
||||
// aria-current: true, page, step, location, date or time.
|
||||
Current string `json:"current,omitempty"`
|
||||
// AutoComplete is what the suggestions of a text field or a combo
|
||||
// box complete as the user types, as ARIA's aria-autocomplete:
|
||||
// inline, list or both.
|
||||
AutoComplete string `json:"autoComplete,omitempty"`
|
||||
// RoleDescription is what the app calls the element's role, as
|
||||
// ARIA's aria-roledescription; HasPopup the kind of popup it opens,
|
||||
// as aria-haspopup: menu, listbox, tree, grid or dialog; Controls the
|
||||
// elements it controls, as aria-controls.
|
||||
RoleDescription string `json:"roleDescription,omitempty"`
|
||||
HasPopup string `json:"hasPopup,omitempty"`
|
||||
Controls []nodeID `json:"controls,omitempty"`
|
||||
// DescribedBy are the elements whose text describes the element, as
|
||||
// ARIA's aria-describedby, and ErrorMessage those holding its error
|
||||
// while it is invalid, as aria-errormessage.
|
||||
DescribedBy []nodeID `json:"describedBy,omitempty"`
|
||||
ErrorMessage []nodeID `json:"errorMessage,omitempty"`
|
||||
// WebView marks the node of a web view's page, whose elements the
|
||||
// tree leaves out.
|
||||
WebView bool `json:"webView,omitempty"`
|
||||
}
|
||||
|
||||
// keyJSON is how a key goes in JSON: strings, booleans and integers as
|
||||
// themselves, other keys as fmt prints them.
|
||||
func keyJSON(k any) any {
|
||||
switch k := k.(type) {
|
||||
case string, bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr:
|
||||
return k
|
||||
}
|
||||
return fmt.Sprint(k)
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
//go:build !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"image"
|
||||
"image/png"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// fakeDriver records what requests ask of the app.
|
||||
type fakeDriver struct {
|
||||
access *platform.AccessTree
|
||||
keys map[uint64]any
|
||||
acted []platform.SurfaceEvent
|
||||
sent []platform.SurfaceEvent
|
||||
menus [][]string
|
||||
png []byte
|
||||
evalFn func(string) (any, error)
|
||||
waited time.Duration
|
||||
}
|
||||
|
||||
func (d *fakeDriver) windows() ([]windowInfo, error) {
|
||||
return []windowInfo{{ID: 1, Title: "Counter", Kind: "content", Bounds: rect{10, 20, 300, 200}, Focused: true, Visible: true}}, nil
|
||||
}
|
||||
|
||||
func (d *fakeDriver) tree(window int) (int, *platform.AccessTree, map[uint64]any, error) {
|
||||
if window > 1 {
|
||||
return 0, nil, nil, errorf(codeNoWindow, "no window %d", window)
|
||||
}
|
||||
return 1, d.access, d.keys, nil
|
||||
}
|
||||
|
||||
func (d *fakeDriver) act(window int, ev platform.SurfaceEvent) error {
|
||||
d.acted = append(d.acted, ev)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *fakeDriver) input(window int, evs []platform.SurfaceEvent) error {
|
||||
d.sent = append(d.sent, evs...)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *fakeDriver) menu(window int, path []string) error {
|
||||
d.menus = append(d.menus, path)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *fakeDriver) capture(window int) ([]byte, error) { return d.png, nil }
|
||||
|
||||
func (d *fakeDriver) eval(window int, script string) (any, error) { return d.evalFn(script) }
|
||||
|
||||
func (d *fakeDriver) idle(window int, timeout time.Duration) error {
|
||||
d.waited = timeout
|
||||
return nil
|
||||
}
|
||||
|
||||
// do answers line, as JSON.
|
||||
func do(t *testing.T, d driver, line string) map[string]any {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(handle(d, []byte(line)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(b, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// errCode returns the code of the error of a response, "" for none.
|
||||
func errCode(m map[string]any) string {
|
||||
e, _ := m["error"].(map[string]any)
|
||||
code, _ := e["code"].(string)
|
||||
return code
|
||||
}
|
||||
|
||||
func TestRequestErrors(t *testing.T) {
|
||||
d := &fakeDriver{}
|
||||
for _, c := range []struct{ line, code string }{
|
||||
{`not json`, codeParse},
|
||||
{`[1, 2]`, codeParse},
|
||||
{`{"id": 1}`, codeInvalid},
|
||||
{`{"id": 1, "method": "fly"}`, codeUnknownMethod},
|
||||
{`{"id": 1, "method": "tree", "params": {"window": 1, "windwo": 2}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "tree", "params": {"window": "one"}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "tree", "params": {"window": 7}}`, codeNoWindow},
|
||||
{`{"id": 1, "method": "windows", "params": {"window": 1}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "menu", "params": {"path": []}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "idle", "params": {"timeout": -1}}`, codeInvalid},
|
||||
} {
|
||||
m := do(t, d, c.line)
|
||||
if got := errCode(m); got != c.code {
|
||||
t.Errorf("%s: error %v, want %s", c.line, m["error"], c.code)
|
||||
}
|
||||
if _, ok := m["result"]; ok {
|
||||
t.Errorf("%s: a result with the error: %v", c.line, m)
|
||||
}
|
||||
}
|
||||
// The ID comes back as it went, or null when the line has none.
|
||||
if m := do(t, d, `{"id": "a-7", "method": "fly"}`); m["id"] != "a-7" {
|
||||
t.Errorf("id %v", m["id"])
|
||||
}
|
||||
if b, _ := json.Marshal(handle(d, []byte("{"))); !bytes.Contains(b, []byte(`"id":null`)) {
|
||||
t.Errorf("an unreadable line's answer: %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindowsRequest(t *testing.T) {
|
||||
m := do(t, &fakeDriver{}, `{"id": 1, "method": "windows"}`)
|
||||
ws := m["result"].(map[string]any)["windows"].([]any)
|
||||
w := ws[0].(map[string]any)
|
||||
if w["id"] != 1.0 || w["kind"] != "content" || w["focused"] != true || w["bounds"].(map[string]any)["width"] != 300.0 {
|
||||
t.Errorf("windows: %v", ws)
|
||||
}
|
||||
}
|
||||
|
||||
// testTree is a window's tree: a button in a group, and a text field.
|
||||
func testTree() (*platform.AccessTree, map[uint64]any) {
|
||||
t := &platform.AccessTree{Focus: 1 << 60, Nodes: []platform.AccessNode{
|
||||
{ID: 7, Parent: -1, Role: platform.RoleGroup},
|
||||
{ID: 1 << 60, Parent: 0, Role: platform.RoleButton, Label: "Add", KeyShortcuts: "Ctrl+N",
|
||||
States: platform.AccessFocusable, Actions: platform.ActionPress | platform.ActionFocus,
|
||||
Bounds: platform.RectF{X: 1, Y: 2, W: 30, H: 20}},
|
||||
{ID: 9, Parent: 0, Role: platform.RoleTextField, Value: "hey", SelStart: 3, SelEnd: 3, AutoComplete: platform.AutoCompleteList},
|
||||
{ID: 11, Parent: 0, Role: platform.RoleSlider, Min: 0, Max: 10, Now: 4},
|
||||
}}
|
||||
return t, map[uint64]any{1 << 60: "add", 9: 42}
|
||||
}
|
||||
|
||||
func TestTreeRequest(t *testing.T) {
|
||||
tree, keys := testTree()
|
||||
m := do(t, &fakeDriver{access: tree, keys: keys}, `{"id": 1, "method": "tree"}`)
|
||||
r := m["result"].(map[string]any)
|
||||
if r["window"] != 1.0 || r["focus"] != "1152921504606846976" {
|
||||
t.Errorf("tree: %v", r)
|
||||
}
|
||||
nodes := r["nodes"].([]any)
|
||||
group, button, field, slider := nodes[0].(map[string]any), nodes[1].(map[string]any), nodes[2].(map[string]any), nodes[3].(map[string]any)
|
||||
if _, ok := group["parent"]; ok || group["role"] != "group" {
|
||||
t.Errorf("group: %v", group)
|
||||
}
|
||||
// IDs go as strings, which JavaScript's numbers would round.
|
||||
if button["id"] != "1152921504606846976" || button["parent"] != "7" || button["role"] != "button" || button["key"] != "add" || button["label"] != "Add" || button["keyShortcuts"] != "Ctrl+N" {
|
||||
t.Errorf("button: %v", button)
|
||||
}
|
||||
if !slices.Equal(button["states"].([]any), []any{"focusable"}) || !slices.Equal(button["actions"].([]any), []any{"press", "focus"}) {
|
||||
t.Errorf("button's states and actions: %v %v", button["states"], button["actions"])
|
||||
}
|
||||
if b := button["bounds"].(map[string]any); b["x"] != 1.0 || b["height"] != 20.0 {
|
||||
t.Errorf("button's bounds: %v", b)
|
||||
}
|
||||
if field["key"] != 42.0 || field["value"] != "hey" || !slices.Equal(field["selection"].([]any), []any{3.0, 3.0}) || field["autoComplete"] != "list" {
|
||||
t.Errorf("text field: %v", field)
|
||||
}
|
||||
if slider["max"] != 10.0 || slider["now"] != 4.0 || slider["min"] != 0.0 {
|
||||
t.Errorf("slider: %v", slider)
|
||||
}
|
||||
if _, ok := field["keyShortcuts"]; ok {
|
||||
t.Errorf("a text field with key shortcuts: %v", field)
|
||||
}
|
||||
if _, ok := button["autoComplete"]; ok {
|
||||
t.Errorf("a button with suggestions: %v", button)
|
||||
}
|
||||
if _, ok := button["min"]; ok {
|
||||
t.Errorf("a button with a range: %v", button)
|
||||
}
|
||||
}
|
||||
|
||||
// A grid gives its size and its rows and cells their places, as the app
|
||||
// gave them, and the columns a cell covers, and says it chooses several
|
||||
// rows.
|
||||
func TestTreeGrid(t *testing.T) {
|
||||
tree := &platform.AccessTree{Nodes: []platform.AccessNode{
|
||||
{ID: 1, Parent: -1, Role: platform.RoleGrid, Label: "Sheet", RowCount: 10001, ColCount: 5, States: platform.AccessSelectable | platform.AccessMultiselectable},
|
||||
{ID: 2, Parent: 0, Role: platform.RoleRow, RowIndex: 4122},
|
||||
{ID: 3, Parent: 1, Role: platform.RoleCell, Label: "B4121", ColIndex: 2, ColSpan: 2},
|
||||
}}
|
||||
m := do(t, &fakeDriver{access: tree}, `{"id": 1, "method": "tree"}`)
|
||||
nodes := m["result"].(map[string]any)["nodes"].([]any)
|
||||
grid, row, cell := nodes[0].(map[string]any), nodes[1].(map[string]any), nodes[2].(map[string]any)
|
||||
if grid["role"] != "grid" || grid["rowCount"] != 10001.0 || grid["colCount"] != 5.0 || !slices.Contains(grid["states"].([]any), "multiselectable") {
|
||||
t.Errorf("grid: %v", grid)
|
||||
}
|
||||
if row["rowIndex"] != 4122.0 || cell["colIndex"] != 2.0 || cell["colSpan"] != 2.0 {
|
||||
t.Errorf("row %v, cell %v", row, cell)
|
||||
}
|
||||
if _, ok := cell["rowIndex"]; ok {
|
||||
t.Errorf("a cell with a row index of its own: %v", cell)
|
||||
}
|
||||
if _, ok := cell["rowSpan"]; ok {
|
||||
t.Errorf("a cell covering one row with a row span: %v", cell)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActRequest(t *testing.T) {
|
||||
tree, keys := testTree()
|
||||
d := &fakeDriver{access: tree, keys: keys}
|
||||
for _, line := range []string{
|
||||
`{"id": 1, "method": "act", "params": {"id": "1152921504606846976", "action": "press"}}`,
|
||||
`{"id": 2, "method": "act", "params": {"key": "add", "action": "press"}}`,
|
||||
`{"id": 3, "method": "act", "params": {"key": 42, "action": "setValue", "text": "hi"}}`,
|
||||
`{"id": 4, "method": "act", "params": {"id": 9, "action": "selectText", "from": 1, "to": 2}}`,
|
||||
} {
|
||||
if m := do(t, d, line); m["error"] != nil {
|
||||
t.Fatalf("%s: %v", line, m["error"])
|
||||
}
|
||||
}
|
||||
want := []platform.SurfaceEvent{
|
||||
{Kind: platform.AccessAction, ID: 1 << 60, Action: platform.AccessPress},
|
||||
{Kind: platform.AccessAction, ID: 1 << 60, Action: platform.AccessPress},
|
||||
{Kind: platform.AccessAction, ID: 9, Action: platform.AccessSetValue, Text: "hi"},
|
||||
{Kind: platform.AccessAction, ID: 9, Action: platform.AccessSelectText, From: 1, To: 2},
|
||||
}
|
||||
if len(d.acted) != len(want) {
|
||||
t.Fatalf("acted %+v", d.acted)
|
||||
}
|
||||
for i := range want {
|
||||
if a, w := d.acted[i], want[i]; a.Kind != w.Kind || a.ID != w.ID || a.Action != w.Action || a.Text != w.Text || a.From != w.From || a.To != w.To {
|
||||
t.Errorf("action %d: %+v, want %+v", i, a, w)
|
||||
}
|
||||
}
|
||||
|
||||
keys[11] = "add" // two elements have it now
|
||||
for _, c := range []struct{ line, code string }{
|
||||
{`{"id": 1, "method": "act", "params": {"action": "press"}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "act", "params": {"id": "7", "key": "add", "action": "press"}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "act", "params": {"id": "7", "action": "smash"}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "act", "params": {"id": "seven", "action": "press"}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "act", "params": {"key": "remove", "action": "press"}}`, codeNoElement},
|
||||
{`{"id": 1, "method": "act", "params": {"key": "add", "action": "press"}}`, codeInvalid},
|
||||
} {
|
||||
if m := do(t, d, c.line); errCode(m) != c.code {
|
||||
t.Errorf("%s: error %v, want %s", c.line, m["error"], c.code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInputRequest(t *testing.T) {
|
||||
d := &fakeDriver{}
|
||||
m := do(t, d, `{"id": 1, "method": "input", "params": {"events": [
|
||||
{"type": "click", "x": 5, "y": 6, "clicks": 2},
|
||||
{"type": "pointerDown", "x": 1, "y": 2, "button": "right", "mods": ["shift"]},
|
||||
{"type": "wheel", "x": 1, "y": 2, "dy": 40, "precise": true},
|
||||
{"type": "key", "key": "Ctrl+Shift+Z"},
|
||||
{"type": "keyDown", "key": "Enter"},
|
||||
{"type": "keyUp", "key": "F5"},
|
||||
{"type": "text", "text": "héllo"}
|
||||
]}}`)
|
||||
if m["error"] != nil {
|
||||
t.Fatal(m["error"])
|
||||
}
|
||||
type ev struct {
|
||||
kind platform.SurfaceEventKind
|
||||
x, dy float64
|
||||
button, click int
|
||||
key platform.Key
|
||||
mods platform.Modifiers
|
||||
text string
|
||||
}
|
||||
var got []ev
|
||||
for _, e := range d.sent {
|
||||
got = append(got, ev{e.Kind, e.X, e.DY, e.Button, e.Clicks, e.Key, e.Mods, e.Text})
|
||||
}
|
||||
want := []ev{
|
||||
{kind: platform.PointerMove, x: 5},
|
||||
{kind: platform.PointerDown, x: 5, click: 1}, {kind: platform.PointerUp, x: 5, click: 1},
|
||||
{kind: platform.PointerDown, x: 5, click: 2}, {kind: platform.PointerUp, x: 5, click: 2},
|
||||
{kind: platform.PointerDown, x: 1, button: 1, click: 1, mods: platform.ModShift},
|
||||
{kind: platform.PointerScroll, x: 1, dy: 40},
|
||||
{kind: platform.KeyPressed, key: platform.KeyZ, mods: platform.ModCtrl | platform.ModShift},
|
||||
{kind: platform.KeyReleased, key: platform.KeyZ, mods: platform.ModCtrl | platform.ModShift},
|
||||
{kind: platform.KeyPressed, key: platform.KeyEnter},
|
||||
{kind: platform.KeyReleased, key: platform.KeyF5},
|
||||
{kind: platform.TextInput, text: "héllo"},
|
||||
}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("events:\n%+v\nwant\n%+v", got, want)
|
||||
}
|
||||
if !d.sent[6].Precise || d.sent[7].PhysicalKey != platform.KeyZ {
|
||||
t.Errorf("wheel %+v, key %+v", d.sent[6], d.sent[7])
|
||||
}
|
||||
|
||||
for _, events := range []string{
|
||||
`[{"type": "hover"}]`,
|
||||
`[{"type": "key", "key": "Hyper+A"}]`,
|
||||
`[{"type": "key", "key": "VolumeUp"}]`,
|
||||
`[{"type": "click", "button": "fourth"}]`,
|
||||
`[{"type": "click", "mods": ["fn"]}]`,
|
||||
`[{"type": "text"}]`,
|
||||
} {
|
||||
n := len(d.sent)
|
||||
if m := do(t, d, `{"id": 1, "method": "input", "params": {"events": `+events+`}}`); errCode(m) != codeInvalid {
|
||||
t.Errorf("%s: error %v", events, m["error"])
|
||||
}
|
||||
if len(d.sent) != n {
|
||||
t.Errorf("%s: sent events before failing", events)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMenuCaptureEvalIdle(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 3, 2)))
|
||||
d := &fakeDriver{png: buf.Bytes(), evalFn: func(s string) (any, error) {
|
||||
if s == "throw 1" {
|
||||
return nil, errors.New("Uncaught 1")
|
||||
}
|
||||
return map[string]any{"title": "E2E"}, nil
|
||||
}}
|
||||
if m := do(t, d, `{"id": 1, "method": "menu", "params": {"path": ["File", "New"]}}`); m["error"] != nil || !slices.Equal(d.menus[0], []string{"File", "New"}) {
|
||||
t.Errorf("menu: %v %v", m, d.menus)
|
||||
}
|
||||
m := do(t, d, `{"id": 1, "method": "capture"}`)
|
||||
r := m["result"].(map[string]any)
|
||||
if r["png"] == nil || r["width"] != 3.0 || r["height"] != 2.0 {
|
||||
t.Errorf("capture: %v", r)
|
||||
}
|
||||
var cr captureResult
|
||||
b, _ := json.Marshal(m["result"])
|
||||
if json.Unmarshal(b, &cr) != nil || !bytes.Equal(cr.PNG, buf.Bytes()) {
|
||||
t.Errorf("the PNG did not come back whole")
|
||||
}
|
||||
if m := do(t, d, `{"id": 1, "method": "eval", "params": {"script": "({title: document.title})"}}`); m["result"].(map[string]any)["value"].(map[string]any)["title"] != "E2E" {
|
||||
t.Errorf("eval: %v", m)
|
||||
}
|
||||
if m := do(t, d, `{"id": 1, "method": "eval", "params": {"script": "throw 1"}}`); errCode(m) != codeFailed {
|
||||
t.Errorf("eval that throws: %v", m)
|
||||
}
|
||||
if m := do(t, d, `{"id": 1, "method": "idle", "params": {"timeout": 1500}}`); m["error"] != nil || d.waited != 1500*time.Millisecond {
|
||||
t.Errorf("idle: %v, waited %v", m, d.waited)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNames(t *testing.T) {
|
||||
if len(roleNames) != int(platform.RoleComplementary)+1 {
|
||||
t.Errorf("%d role names for %d roles", len(roleNames), platform.RoleComplementary+1)
|
||||
}
|
||||
if platform.AccessStates(1)<<(len(stateNames)-1) != platform.AccessHorizontal {
|
||||
t.Errorf("%d state names", len(stateNames))
|
||||
}
|
||||
if platform.AccessActions(1)<<(len(actionNames)-1) != platform.ActionExpand {
|
||||
t.Errorf("%d action names", len(actionNames))
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, n := range roleNames {
|
||||
if seen[n] {
|
||||
t.Errorf("role name %q twice", n)
|
||||
}
|
||||
seen[n] = true
|
||||
}
|
||||
if len(actionKinds) != int(platform.AccessInsertText)+1 {
|
||||
t.Errorf("%d actions for %d", len(actionKinds), platform.AccessInsertText+1)
|
||||
}
|
||||
}
|
||||
|
||||
// socketPath returns a path for a socket, short enough for macOS's limit
|
||||
// of 104 bytes.
|
||||
func socketPath(t *testing.T) string {
|
||||
dir, err := os.MkdirTemp("", "mygo-automation")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(dir) })
|
||||
return filepath.Join(dir, "s")
|
||||
}
|
||||
|
||||
func TestServe(t *testing.T) {
|
||||
path := socketPath(t)
|
||||
l, err := listen(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.Close()
|
||||
if runtime.GOOS != "windows" {
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil || fi.Mode().Perm() != 0o600 {
|
||||
t.Errorf("socket's mode %v, %v", fi.Mode(), err)
|
||||
}
|
||||
}
|
||||
tree, keys := testTree()
|
||||
go serve(l, &fakeDriver{access: tree, keys: keys})
|
||||
|
||||
c, err := net.Dial("unix", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
// Requests answered in order, each on a line of its own.
|
||||
if _, err := c.Write([]byte("{\"id\": 1, \"method\": \"tree\"}\n\n{\"id\": 2, \"method\": \"nope\"}\n")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := bufio.NewReader(c)
|
||||
for i, want := range []string{`"id":1,"result":{"window":1,`, `"id":2,"error":{"code":"unknown_method"`} {
|
||||
line, err := r.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(line, want) {
|
||||
t.Errorf("response %d: %s", i+1, line)
|
||||
}
|
||||
}
|
||||
|
||||
// Another app's socket is left alone, as is a file that is no socket.
|
||||
if l2, err := listen(path); err == nil {
|
||||
l2.Close()
|
||||
t.Error("listened on a socket another app listens on")
|
||||
}
|
||||
file := filepath.Join(filepath.Dir(path), "f")
|
||||
os.WriteFile(file, nil, 0o600)
|
||||
if l2, err := listen(file); err == nil {
|
||||
l2.Close()
|
||||
t.Error("listened in place of a file")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStaleSocket listens where an app that ended left its socket.
|
||||
func TestStaleSocket(t *testing.T) {
|
||||
path := socketPath(t)
|
||||
l, err := listen(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l.(*net.UnixListener).SetUnlinkOnClose(false)
|
||||
l.Close()
|
||||
if _, err := os.Lstat(path); err != nil {
|
||||
t.Fatal("no socket left: ", err)
|
||||
}
|
||||
l, err = listen(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l.Close()
|
||||
if _, err := os.Lstat(path); !os.IsNotExist(err) {
|
||||
t.Errorf("the socket stays once closed: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package dev.mygo
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.Data
|
||||
import androidx.work.ExistingPeriodicWorkPolicy
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequest
|
||||
import androidx.work.PeriodicWorkRequest
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.Worker
|
||||
import androidx.work.WorkerParameters
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import org.json.JSONObject
|
||||
|
||||
/** WorkManager, each of the app's tasks a unique work of its name. */
|
||||
class BackgroundPlugin : MyGoPlugin {
|
||||
init {
|
||||
instance = this
|
||||
}
|
||||
|
||||
override fun call(method: String, args: JSONObject, reply: PluginReply) {
|
||||
val wm = WorkManager.getInstance(PluginHost.context)
|
||||
when (method) {
|
||||
"ready" -> {
|
||||
ready = true
|
||||
for (e in waiting) PluginHost.emit("background", "run", e)
|
||||
waiting.clear()
|
||||
reply.success(null)
|
||||
}
|
||||
"schedule" -> {
|
||||
val name = args.optString("name")
|
||||
// The same again, as each launch asks: what's scheduled stands.
|
||||
// Replacing it would put it off, or stop the task that started
|
||||
// this very process.
|
||||
val options = args.toString()
|
||||
if (prefs().getString(name, null) == options) {
|
||||
reply.success(null)
|
||||
return
|
||||
}
|
||||
val every = args.optDouble("every", 0.0)
|
||||
val delay = (args.optDouble("delay", 0.0) * 1000).toLong()
|
||||
val c = Constraints.Builder()
|
||||
.setRequiredNetworkType(if (args.optBoolean("network")) NetworkType.CONNECTED else NetworkType.NOT_REQUIRED)
|
||||
.setRequiresCharging(args.optBoolean("charging"))
|
||||
.build()
|
||||
val data = Data.Builder().putString("name", name).build()
|
||||
if (every > 0) {
|
||||
val r = PeriodicWorkRequest.Builder(MyGoWorker::class.java, (every * 1000).toLong(), TimeUnit.MILLISECONDS)
|
||||
.setConstraints(c).setInputData(data).setInitialDelay(delay, TimeUnit.MILLISECONDS)
|
||||
.addTag(MyGoWorker.PERIODIC).build()
|
||||
wm.enqueueUniquePeriodicWork(prefix + name, ExistingPeriodicWorkPolicy.UPDATE, r)
|
||||
} else {
|
||||
val r = OneTimeWorkRequest.Builder(MyGoWorker::class.java)
|
||||
.setConstraints(c).setInputData(data).setInitialDelay(delay, TimeUnit.MILLISECONDS).build()
|
||||
wm.enqueueUniqueWork(prefix + name, ExistingWorkPolicy.REPLACE, r)
|
||||
}
|
||||
prefs().edit().putString(name, options).apply()
|
||||
reply.success(null)
|
||||
}
|
||||
"cancel" -> {
|
||||
wm.cancelUniqueWork(prefix + args.optString("name"))
|
||||
prefs().edit().remove(args.optString("name")).apply()
|
||||
reply.success(null)
|
||||
}
|
||||
"done" -> {
|
||||
val id = args.optLong("run")
|
||||
val d = runs.remove(id)
|
||||
d?.invoke(args.optBoolean("ok"))
|
||||
reply.success(null)
|
||||
}
|
||||
else -> reply.failure(PluginFailure("UnknownMethod", method))
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val prefix = "mygo."
|
||||
internal var instance: BackgroundPlugin? = null
|
||||
private var ready = false
|
||||
private val waiting = ArrayList<Map<String, Any>>()
|
||||
private val runs = HashMap<Long, (Boolean) -> Unit>()
|
||||
private var nextRun = 1L
|
||||
|
||||
/** Runs a task, on the UI thread: Go hears of it, once it listens. */
|
||||
internal fun run(name: String, done: (Boolean) -> Unit): Long {
|
||||
val id = nextRun++
|
||||
runs[id] = done
|
||||
val e = mapOf<String, Any>("run" to id, "name" to name)
|
||||
if (ready) PluginHost.emit("background", "run", e) else waiting.add(e)
|
||||
return id
|
||||
}
|
||||
|
||||
/** The system's time ran out: what never began stays unbegun. */
|
||||
internal fun stop(id: Long) {
|
||||
runs.remove(id)
|
||||
if (!waiting.removeAll { it["run"] == id }) PluginHost.emit("background", "stop", mapOf("run" to id))
|
||||
}
|
||||
|
||||
internal fun prefs() = PluginHost.context.getSharedPreferences("mygo.background", Context.MODE_PRIVATE)
|
||||
|
||||
/** A task that runs once is done with: it may be scheduled again. */
|
||||
internal fun finished(name: String) {
|
||||
prefs().edit().remove(name).apply()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A task's turn, which may be what starts the process: Go starts with no Activity. */
|
||||
class MyGoWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
|
||||
@Volatile private var run = 0L
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private val latch = CountDownLatch(1)
|
||||
|
||||
override fun doWork(): Result {
|
||||
val name = inputData.getString("name") ?: return Result.failure()
|
||||
var ok = false
|
||||
main.post {
|
||||
HostImpl.startHeadless(applicationContext)
|
||||
run = BackgroundPlugin.run(name) {
|
||||
ok = it
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
// WorkManager's limit is 10 minutes.
|
||||
if (!latch.await(9, TimeUnit.MINUTES)) {
|
||||
onStopped()
|
||||
return Result.retry()
|
||||
}
|
||||
if (!ok) return Result.retry()
|
||||
// What repeats stays on the list, of which this run is one.
|
||||
if (!tags.contains(MyGoWorker.PERIODIC)) main.post { BackgroundPlugin.finished(name) }
|
||||
return Result.success()
|
||||
}
|
||||
|
||||
override fun onStopped() {
|
||||
val id = run
|
||||
if (id != 0L) main.post { BackgroundPlugin.stop(id) }
|
||||
latch.countDown() // WorkManager no longer waits for this thread
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val PERIODIC = "mygo.periodic"
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
// Package background runs an app's Go code while it isn't open, as the phone
|
||||
// finds the time: syncing a feed overnight, uploading what waited for a network.
|
||||
// BGTaskScheduler on iOS, WorkManager on Android; elsewhere Schedule reports
|
||||
// errors.ErrUnsupported.
|
||||
//
|
||||
// The system starts the app's process to run a task, without showing it, and
|
||||
// main runs as ever: call Handle before App.Run, so that the handler is there
|
||||
// by then.
|
||||
//
|
||||
// background.Handle("sync", func(ctx context.Context) error {
|
||||
// return syncFeed(ctx)
|
||||
// })
|
||||
// mygo.App.WhenReady(func() {
|
||||
// go background.Schedule(context.Background(), "sync", background.Options{
|
||||
// Every: 4 * time.Hour, Network: true,
|
||||
// })
|
||||
// })
|
||||
//
|
||||
// When a task runs is the system's choice: after Delay, around Every, with what
|
||||
// it knows of the battery and of how much the user opens the app. iOS gives a
|
||||
// task about 30 seconds, or minutes with Long; Android about 10 minutes. A
|
||||
// handler stops when its context ends. A repeating task outlives the process and
|
||||
// reboots until Cancel; one that runs once does until it succeeds.
|
||||
package background
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
)
|
||||
|
||||
const pluginID = "background"
|
||||
|
||||
// Options say when a task may run.
|
||||
type Options struct {
|
||||
// Every repeats it, at least 15 minutes apart on either system. Without it
|
||||
// the task runs once.
|
||||
Every time.Duration
|
||||
// Delay is the least it waits before it runs the first time.
|
||||
Delay time.Duration
|
||||
// Network waits for a network; on iOS, for Long tasks only, as the system
|
||||
// decides when others run.
|
||||
Network bool
|
||||
// Charging waits for the phone to charge; on iOS, for Long tasks only.
|
||||
Charging bool
|
||||
// Long asks for minutes, which on iOS come rarely, overnight and charging,
|
||||
// rather than half a minute.
|
||||
Long bool
|
||||
}
|
||||
|
||||
var tasks struct {
|
||||
sync.Mutex
|
||||
handlers map[string]func(context.Context) error
|
||||
running map[int64]context.CancelFunc
|
||||
}
|
||||
|
||||
// init listens, whether the app handles a task or no longer does, for the system
|
||||
// to hear back about what it still has on its list.
|
||||
func init() {
|
||||
tasks.handlers = map[string]func(context.Context) error{}
|
||||
tasks.running = map[int64]context.CancelFunc{}
|
||||
p := mygo.Native(pluginID)
|
||||
p.On("run", func(data []byte) {
|
||||
var e runEvent
|
||||
if json.Unmarshal(data, &e) == nil {
|
||||
run(e, finish)
|
||||
}
|
||||
})
|
||||
p.On("stop", func(data []byte) {
|
||||
var e runEvent
|
||||
if json.Unmarshal(data, &e) == nil {
|
||||
stop(e.Run)
|
||||
}
|
||||
})
|
||||
mygo.App.WhenReady(func() {
|
||||
if !p.Available() {
|
||||
return
|
||||
}
|
||||
// What the system started the process for waited for this.
|
||||
go func() {
|
||||
if err := p.Call(context.Background(), "ready", nil, nil); err != nil {
|
||||
log.Printf("background: %v", err)
|
||||
}
|
||||
}()
|
||||
})
|
||||
}
|
||||
|
||||
// Handle says what a task does, before App.Run. It runs on a goroutine of its
|
||||
// own, off the main thread. A task whose handler returns an error runs again
|
||||
// later.
|
||||
func Handle(name string, fn func(ctx context.Context) error) {
|
||||
tasks.Lock()
|
||||
defer tasks.Unlock()
|
||||
tasks.handlers[name] = fn
|
||||
}
|
||||
|
||||
// Schedule asks the system to run a task, in place of one of its name with other
|
||||
// options: with the same ones, as an app does each time it starts, nothing
|
||||
// changes, so that a task isn't put off again and again, nor stopped as it runs.
|
||||
// Call it off the main goroutine, or with go.
|
||||
func Schedule(ctx context.Context, name string, o Options) error {
|
||||
return mygo.Native(pluginID).Call(ctx, "schedule", map[string]any{
|
||||
"name": name, "every": o.Every.Seconds(), "delay": o.Delay.Seconds(),
|
||||
"network": o.Network, "charging": o.Charging, "long": o.Long,
|
||||
}, nil)
|
||||
}
|
||||
|
||||
// Cancel takes a task off the system's list.
|
||||
func Cancel(ctx context.Context, name string) error {
|
||||
return mygo.Native(pluginID).Call(ctx, "cancel", map[string]any{"name": name}, nil)
|
||||
}
|
||||
|
||||
type runEvent struct {
|
||||
Run int64 `json:"run"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// run runs a task's handler, and tells what came of it. What has no handler
|
||||
// finishes: the app no longer does it.
|
||||
func run(e runEvent, done func(run int64, ok bool)) {
|
||||
tasks.Lock()
|
||||
fn := tasks.handlers[e.Name]
|
||||
if fn == nil {
|
||||
tasks.Unlock()
|
||||
done(e.Run, true)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
tasks.running[e.Run] = cancel
|
||||
tasks.Unlock()
|
||||
go func() {
|
||||
err := func() (err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Printf("background: task %s: %v", e.Name, r)
|
||||
err = context.Canceled
|
||||
}
|
||||
}()
|
||||
return fn(ctx)
|
||||
}()
|
||||
if err != nil {
|
||||
log.Printf("background: task %s: %v", e.Name, err)
|
||||
}
|
||||
tasks.Lock()
|
||||
delete(tasks.running, e.Run)
|
||||
tasks.Unlock()
|
||||
cancel()
|
||||
done(e.Run, err == nil)
|
||||
}()
|
||||
}
|
||||
|
||||
// stop ends a task's context, as the system's time for it ended.
|
||||
func stop(id int64) {
|
||||
tasks.Lock()
|
||||
cancel := tasks.running[id]
|
||||
tasks.Unlock()
|
||||
if cancel != nil {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func finish(id int64, ok bool) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := mygo.Native(pluginID).Call(ctx, "done", map[string]any{"run": id, "ok": ok}, nil); err != nil {
|
||||
log.Printf("background: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package background
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/wait"
|
||||
)
|
||||
|
||||
type result struct {
|
||||
run int64
|
||||
ok bool
|
||||
}
|
||||
|
||||
func handlers(t *testing.T, m map[string]func(context.Context) error) {
|
||||
t.Helper()
|
||||
tasks.Lock()
|
||||
defer tasks.Unlock()
|
||||
tasks.handlers, tasks.running = m, map[int64]context.CancelFunc{}
|
||||
}
|
||||
|
||||
// A task runs its handler and says what came of it; one the app no longer has
|
||||
// finishes, so that the system stops asking; a panic stays in its task.
|
||||
func TestRun(t *testing.T) {
|
||||
handlers(t, map[string]func(context.Context) error{
|
||||
"fine": func(context.Context) error { return nil },
|
||||
"fails": func(context.Context) error { return errors.New("no network") },
|
||||
"panics": func(context.Context) error { panic("oh") },
|
||||
})
|
||||
done := make(chan result, 1)
|
||||
report := func(run int64, ok bool) { done <- result{run, ok} }
|
||||
for i, c := range []struct {
|
||||
name string
|
||||
ok bool
|
||||
}{{"fine", true}, {"fails", false}, {"panics", false}, {"gone", true}} {
|
||||
run(runEvent{Run: int64(i), Name: c.name}, report)
|
||||
if got := wait.For(t, c.name, done); got != (result{int64(i), c.ok}) {
|
||||
t.Errorf("%s: %+v", c.name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The system's time running out ends the handler's context.
|
||||
func TestStop(t *testing.T) {
|
||||
started := make(chan struct{})
|
||||
handlers(t, map[string]func(context.Context) error{
|
||||
"long": func(ctx context.Context) error {
|
||||
close(started)
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
},
|
||||
})
|
||||
done := make(chan result, 1)
|
||||
run(runEvent{Run: 7, Name: "long"}, func(run int64, ok bool) { done <- result{run, ok} })
|
||||
wait.For(t, "it to start", started)
|
||||
stop(7)
|
||||
if got := wait.For(t, "it to end", done); got != (result{7, false}) {
|
||||
t.Errorf("stopped: %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import BackgroundTasks
|
||||
import UIKit
|
||||
|
||||
/// BGTaskScheduler: one identifier for what takes seconds and one for what takes
|
||||
/// minutes, which the plugin's named tasks share, each with when it's due.
|
||||
final class BackgroundPlugin: MyGoPlugin {
|
||||
private struct Task: Codable {
|
||||
var every: Double
|
||||
var delay: Double
|
||||
var next: Date
|
||||
var long: Bool
|
||||
var network: Bool
|
||||
var charging: Bool
|
||||
|
||||
func sameOptions(as o: Task) -> Bool {
|
||||
every == o.every && delay == o.delay && long == o.long && network == o.network && charging == o.charging
|
||||
}
|
||||
}
|
||||
|
||||
/// What one of the system's tasks is running.
|
||||
private final class Run {
|
||||
let task: BGTask
|
||||
let long: Bool
|
||||
var left: Set<Int>
|
||||
var ok = true
|
||||
var done = false
|
||||
init(task: BGTask, long: Bool, left: Set<Int>) {
|
||||
self.task = task
|
||||
self.long = long
|
||||
self.left = left
|
||||
}
|
||||
}
|
||||
|
||||
private let refreshID: String
|
||||
private let processingID: String
|
||||
private let storeKey = "mygo.background.tasks"
|
||||
private var nextRun = 1
|
||||
private var runs: [Int: Run] = [:]
|
||||
private var names: [Int: String] = [:]
|
||||
private var ready = false
|
||||
private var waiting: [[String: Any]] = []
|
||||
|
||||
init() {
|
||||
let id = Bundle.main.bundleIdentifier ?? ""
|
||||
refreshID = id + ".mygo.refresh"
|
||||
processingID = id + ".mygo.processing"
|
||||
// Before the app finishes launching, which is why plugins register then.
|
||||
BGTaskScheduler.shared.register(forTaskWithIdentifier: refreshID, using: .main) { [weak self] t in
|
||||
self?.fired(t, long: false)
|
||||
}
|
||||
BGTaskScheduler.shared.register(forTaskWithIdentifier: processingID, using: .main) { [weak self] t in
|
||||
self?.fired(t, long: true)
|
||||
}
|
||||
}
|
||||
|
||||
func call(_ method: String, _ args: [String: Any], _ reply: @escaping PluginReply) {
|
||||
switch method {
|
||||
case "ready":
|
||||
ready = true
|
||||
for e in waiting { PluginHost.emit("background", "run", e) }
|
||||
waiting = []
|
||||
reply(.success(nil))
|
||||
case "schedule":
|
||||
var all = load()
|
||||
let name = args["name"] as? String ?? ""
|
||||
let every = (args["every"] as? Double) ?? 0
|
||||
let delay = (args["delay"] as? Double) ?? 0
|
||||
let t = Task(every: every, delay: delay, next: Date().addingTimeInterval(delay),
|
||||
long: args["long"] as? Bool ?? false, network: args["network"] as? Bool ?? false,
|
||||
charging: args["charging"] as? Bool ?? false)
|
||||
// The same again, as each launch asks: when it's due stands, or it
|
||||
// would be put off for ever by an app that's opened often.
|
||||
if let old = all[name], old.sameOptions(as: t) {
|
||||
reply(.success(nil))
|
||||
return
|
||||
}
|
||||
all[name] = t
|
||||
save(all)
|
||||
do {
|
||||
try submit(all)
|
||||
reply(.success(nil))
|
||||
} catch {
|
||||
// The simulator has no scheduler.
|
||||
reply(.failure(PluginFailure("Unavailable", "\(error)")))
|
||||
}
|
||||
case "cancel":
|
||||
var all = load()
|
||||
all[args["name"] as? String ?? ""] = nil
|
||||
save(all)
|
||||
try? submit(all)
|
||||
reply(.success(nil))
|
||||
case "done":
|
||||
finished(run: args["run"] as? Int ?? 0, ok: args["ok"] as? Bool ?? false)
|
||||
reply(.success(nil))
|
||||
default:
|
||||
reply(.failure(PluginFailure("UnknownMethod", method)))
|
||||
}
|
||||
}
|
||||
|
||||
private func load() -> [String: Task] {
|
||||
guard let d = UserDefaults.standard.data(forKey: storeKey),
|
||||
let all = try? JSONDecoder().decode([String: Task].self, from: d) else { return [:] }
|
||||
return all
|
||||
}
|
||||
|
||||
private func save(_ all: [String: Task]) {
|
||||
if let d = try? JSONEncoder().encode(all) { UserDefaults.standard.set(d, forKey: storeKey) }
|
||||
}
|
||||
|
||||
/// Asks for the earliest of what's due, of each kind.
|
||||
private func submit(_ all: [String: Task]) throws {
|
||||
let quick = all.values.filter { !$0.long }
|
||||
let long = all.values.filter { $0.long }
|
||||
BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: refreshID)
|
||||
BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: processingID)
|
||||
if let at = quick.map(\.next).min() {
|
||||
let r = BGAppRefreshTaskRequest(identifier: refreshID)
|
||||
r.earliestBeginDate = at
|
||||
try BGTaskScheduler.shared.submit(r)
|
||||
}
|
||||
if let at = long.map(\.next).min() {
|
||||
let r = BGProcessingTaskRequest(identifier: processingID)
|
||||
r.earliestBeginDate = at
|
||||
r.requiresNetworkConnectivity = long.contains { $0.network }
|
||||
r.requiresExternalPower = long.contains { $0.charging }
|
||||
try BGTaskScheduler.shared.submit(r)
|
||||
}
|
||||
}
|
||||
|
||||
private func fired(_ task: BGTask, long: Bool) {
|
||||
var all = load()
|
||||
let now = Date()
|
||||
let due = all.filter { $0.value.long == long && $0.value.next <= now.addingTimeInterval(60) }
|
||||
for (name, t) in due where t.every > 0 {
|
||||
all[name]?.next = now.addingTimeInterval(t.every)
|
||||
}
|
||||
save(all)
|
||||
try? submit(all)
|
||||
if due.isEmpty {
|
||||
task.setTaskCompleted(success: true)
|
||||
return
|
||||
}
|
||||
var ids = Set<Int>()
|
||||
for name in due.keys {
|
||||
let id = nextRun
|
||||
nextRun += 1
|
||||
ids.insert(id)
|
||||
names[id] = name
|
||||
let e: [String: Any] = ["run": id, "name": name]
|
||||
if ready {
|
||||
PluginHost.emit("background", "run", e)
|
||||
} else {
|
||||
waiting.append(e)
|
||||
}
|
||||
}
|
||||
let run = Run(task: task, long: long, left: ids)
|
||||
for id in ids { runs[id] = run }
|
||||
task.expirationHandler = { [weak self, weak run] in
|
||||
guard let self, let run else { return }
|
||||
// Handlers get a moment to let go of what they hold, as a database's
|
||||
// lock, before the system suspends the app.
|
||||
for id in run.left {
|
||||
if let i = self.waiting.firstIndex(where: { $0["run"] as? Int == id }) {
|
||||
self.waiting.remove(at: i)
|
||||
self.finished(run: id, ok: false)
|
||||
} else {
|
||||
PluginHost.emit("background", "stop", ["run": id])
|
||||
}
|
||||
}
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self, weak run] in
|
||||
guard let self, let run, !run.done else { return }
|
||||
for id in run.left { self.finished(run: id, ok: false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func finished(run id: Int, ok: Bool) {
|
||||
guard let run = runs.removeValue(forKey: id) else { return }
|
||||
run.left.remove(id)
|
||||
run.ok = run.ok && ok
|
||||
if ok, let name = names[id] {
|
||||
// Once it succeeded, what runs once is off the list; failed, it
|
||||
// stays, to run again.
|
||||
var all = load()
|
||||
if let t = all[name], t.every == 0 {
|
||||
all[name] = nil
|
||||
save(all)
|
||||
try? submit(all)
|
||||
}
|
||||
}
|
||||
names[id] = nil
|
||||
if run.left.isEmpty && !run.done {
|
||||
run.done = true
|
||||
run.task.setTaskCompleted(success: run.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"mobile": {
|
||||
"id": "background",
|
||||
"ios": {
|
||||
"sources": ["ios/*.swift"],
|
||||
"class": "BackgroundPlugin",
|
||||
"frameworks": ["BackgroundTasks"],
|
||||
"infoPlist": {
|
||||
"UIBackgroundModes": ["fetch", "processing"],
|
||||
"BGTaskSchedulerPermittedIdentifiers": ["$(IDENTIFIER).mygo.refresh", "$(IDENTIFIER).mygo.processing"]
|
||||
}
|
||||
},
|
||||
"android": {
|
||||
"sources": ["android/*.kt"],
|
||||
"class": "BackgroundPlugin",
|
||||
"dependencies": ["androidx.work:work-runtime:2.10.1"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package dev.mygo
|
||||
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.hardware.biometrics.BiometricPrompt
|
||||
import android.os.Build
|
||||
import android.os.CancellationSignal
|
||||
import org.json.JSONObject
|
||||
|
||||
class BiometricsPlugin : MyGoPlugin {
|
||||
override fun call(method: String, args: JSONObject, reply: PluginReply) {
|
||||
val ctx = PluginHost.context
|
||||
val keyguard = ctx.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
|
||||
when (method) {
|
||||
"available" -> {
|
||||
val pm = ctx.packageManager
|
||||
val kind = when {
|
||||
Build.VERSION.SDK_INT < 28 -> ""
|
||||
pm.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT) && keyguard.isDeviceSecure -> "fingerprint"
|
||||
pm.hasSystemFeature(PackageManager.FEATURE_FACE) && keyguard.isDeviceSecure -> "face"
|
||||
pm.hasSystemFeature(PackageManager.FEATURE_IRIS) && keyguard.isDeviceSecure -> "iris"
|
||||
keyguard.isDeviceSecure -> "passcode"
|
||||
else -> ""
|
||||
}
|
||||
reply.success(JSONObject().put("kind", kind))
|
||||
}
|
||||
"authenticate" -> {
|
||||
if (Build.VERSION.SDK_INT < 28 || PluginHost.activity == null) {
|
||||
reply.failure(PluginFailure("Failed", "needs Android 9"))
|
||||
return
|
||||
}
|
||||
val b = BiometricPrompt.Builder(PluginHost.activity!!)
|
||||
.setTitle(args.optString("reason").ifEmpty { " " })
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
b.setAllowedAuthenticators(android.hardware.biometrics.BiometricManager.Authenticators.BIOMETRIC_WEAK or
|
||||
android.hardware.biometrics.BiometricManager.Authenticators.DEVICE_CREDENTIAL)
|
||||
} else if (Build.VERSION.SDK_INT >= 29) {
|
||||
@Suppress("DEPRECATION")
|
||||
b.setDeviceCredentialAllowed(true)
|
||||
} else {
|
||||
b.setNegativeButton(ctx.getString(android.R.string.cancel), ctx.mainExecutor) { _, _ -> reply.failure(PluginFailure("Canceled")) }
|
||||
}
|
||||
b.build().authenticate(CancellationSignal(), ctx.mainExecutor, object : BiometricPrompt.AuthenticationCallback() {
|
||||
override fun onAuthenticationSucceeded(r: BiometricPrompt.AuthenticationResult) = reply.success(null)
|
||||
override fun onAuthenticationError(code: Int, msg: CharSequence) {
|
||||
val canceled = code == BiometricPrompt.BIOMETRIC_ERROR_USER_CANCELED || code == BiometricPrompt.BIOMETRIC_ERROR_CANCELED
|
||||
reply.failure(if (canceled) PluginFailure("Canceled") else PluginFailure("Failed", msg.toString()))
|
||||
}
|
||||
})
|
||||
}
|
||||
else -> reply.failure(PluginFailure("NoMethod", method))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// Package biometrics confirms it is the device's owner with what the device
|
||||
// has: Face ID or Touch ID on iOS (LocalAuthentication), and fingerprints or
|
||||
// faces on Android 9 and later (BiometricPrompt), falling back to the device's
|
||||
// passcode. Elsewhere its functions report errors.ErrUnsupported.
|
||||
package biometrics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
)
|
||||
|
||||
const pluginID = "biometrics"
|
||||
|
||||
// Kind is what the device confirms its owner with.
|
||||
type Kind string
|
||||
|
||||
const (
|
||||
None Kind = ""
|
||||
FaceID Kind = "face"
|
||||
TouchID Kind = "fingerprint"
|
||||
Iris Kind = "iris"
|
||||
DeviceCode Kind = "passcode"
|
||||
Biometric Kind = "biometric"
|
||||
)
|
||||
|
||||
// ErrCanceled is what Authenticate fails with as the user goes back.
|
||||
var ErrCanceled = errors.New("biometrics: canceled")
|
||||
|
||||
// ErrFailed is what Authenticate fails with as the device didn't recognize
|
||||
// the user.
|
||||
var ErrFailed = errors.New("biometrics: not recognized")
|
||||
|
||||
// Available tells what the device can confirm its owner with now, None when
|
||||
// nothing, as without a passcode set.
|
||||
func Available(ctx context.Context) (Kind, error) {
|
||||
var r struct {
|
||||
Kind string `json:"kind"`
|
||||
}
|
||||
err := mygo.Native(pluginID).Call(ctx, "available", nil, &r)
|
||||
return Kind(r.Kind), err
|
||||
}
|
||||
|
||||
// Authenticate asks the user to confirm it's them, saying reason. It returns
|
||||
// nil once they did. Call it off the main goroutine, as it waits for the user.
|
||||
func Authenticate(ctx context.Context, reason string) error {
|
||||
err := mygo.Native(pluginID).Call(ctx, "authenticate", map[string]string{"reason": reason}, nil)
|
||||
var n *mygo.NativeError
|
||||
if errors.As(err, &n) {
|
||||
switch n.Code {
|
||||
case "Canceled":
|
||||
return ErrCanceled
|
||||
case "NotRecognized":
|
||||
return ErrFailed
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import LocalAuthentication
|
||||
|
||||
final class BiometricsPlugin: MyGoPlugin {
|
||||
func call(_ method: String, _ args: [String: Any], _ reply: @escaping PluginReply) {
|
||||
switch method {
|
||||
case "available":
|
||||
let c = LAContext()
|
||||
var kind = ""
|
||||
if c.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) {
|
||||
switch c.biometryType {
|
||||
case .faceID: kind = "face"
|
||||
case .touchID: kind = "fingerprint"
|
||||
case .opticID: kind = "iris"
|
||||
default: kind = "biometric"
|
||||
}
|
||||
} else if c.canEvaluatePolicy(.deviceOwnerAuthentication, error: nil) {
|
||||
kind = "passcode"
|
||||
}
|
||||
reply(.success(["kind": kind]))
|
||||
case "authenticate":
|
||||
let reason = args["reason"] as? String ?? ""
|
||||
LAContext().evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason.isEmpty ? " " : reason) { ok, error in
|
||||
if ok {
|
||||
reply(.success(nil))
|
||||
return
|
||||
}
|
||||
switch (error as? LAError)?.code {
|
||||
case .userCancel, .appCancel, .systemCancel:
|
||||
reply(.failure(PluginFailure("Canceled")))
|
||||
case .authenticationFailed:
|
||||
reply(.failure(PluginFailure("NotRecognized")))
|
||||
default:
|
||||
reply(.failure(PluginFailure("Failed", error?.localizedDescription ?? "")))
|
||||
}
|
||||
}
|
||||
default:
|
||||
reply(.failure(PluginFailure("NoMethod", method)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"mobile": {
|
||||
"id": "biometrics",
|
||||
"ios": {
|
||||
"sources": ["ios/*.swift"],
|
||||
"class": "BiometricsPlugin",
|
||||
"frameworks": ["LocalAuthentication"],
|
||||
"infoPlist": {"NSFaceIDUsageDescription": "This app confirms it's you."}
|
||||
},
|
||||
"android": {
|
||||
"sources": ["android/*.kt"],
|
||||
"class": "BiometricsPlugin",
|
||||
"permissions": ["USE_BIOMETRIC"]
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
// Builds dist/ of the plugin package in the working directory: an ES
|
||||
// module, which imports mygo-runtime, and its type declarations. dist/ is
|
||||
// not committed, like mygo-runtime's.
|
||||
import { rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
const dir = process.cwd();
|
||||
await rm(join(dir, "dist"), { recursive: true, force: true });
|
||||
const result = await Bun.build({
|
||||
entrypoints: [join(dir, "src/index.ts")],
|
||||
outdir: join(dir, "dist"),
|
||||
format: "esm",
|
||||
target: "browser",
|
||||
external: ["mygo-runtime"],
|
||||
});
|
||||
if (!result.success) {
|
||||
for (const log of result.logs) console.error(log);
|
||||
process.exit(1);
|
||||
}
|
||||
const tsc = Bun.spawnSync(["tsc", "-p", join(dir, "tsconfig.json")], { stdout: "inherit", stderr: "inherit" });
|
||||
if (tsc.exitCode !== 0) process.exit(1);
|
||||
console.log(`wrote ${join(dir, "dist")}`);
|
||||
@@ -0,0 +1,93 @@
|
||||
package dev.mygo
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import androidx.camera.core.CameraSelector
|
||||
import androidx.camera.core.ImageCapture
|
||||
import androidx.camera.core.ImageCaptureException
|
||||
import androidx.camera.core.Preview
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
import androidx.camera.view.PreviewView
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
class CameraPlugin : MyGoPlugin {
|
||||
private class Cam(val view: PreviewView) {
|
||||
val capture = ImageCapture.Builder().build()
|
||||
var bound = false
|
||||
var error = "the camera is not running"
|
||||
}
|
||||
|
||||
private val cams = HashMap<Long, Cam>()
|
||||
|
||||
init {
|
||||
PluginHost.registerView("camera") { context, id, args ->
|
||||
val v = PreviewView(context)
|
||||
// A texture, for it to show under the surface that draws over it.
|
||||
v.implementationMode = PreviewView.ImplementationMode.COMPATIBLE
|
||||
val c = Cam(v)
|
||||
cams[id] = c
|
||||
start(c, args.optBoolean("front"))
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
private fun start(c: Cam, front: Boolean) {
|
||||
PluginHost.requestPermissions(arrayOf(Manifest.permission.CAMERA)) { granted ->
|
||||
if (!granted) {
|
||||
c.error = "the app may not use the camera"
|
||||
return@requestPermissions
|
||||
}
|
||||
val ctx = PluginHost.context
|
||||
val future = ProcessCameraProvider.getInstance(ctx)
|
||||
future.addListener({
|
||||
val owner = PluginHost.activity as? LifecycleOwner
|
||||
if (owner == null) {
|
||||
c.error = "no window to show the camera in"
|
||||
return@addListener
|
||||
}
|
||||
val preview = Preview.Builder().build().also { it.surfaceProvider = c.view.surfaceProvider }
|
||||
val which = if (front) CameraSelector.DEFAULT_FRONT_CAMERA else CameraSelector.DEFAULT_BACK_CAMERA
|
||||
runCatching {
|
||||
future.get().bindToLifecycle(owner, which, preview, c.capture)
|
||||
c.bound = true
|
||||
}.onFailure {
|
||||
c.error = it.toString()
|
||||
android.util.Log.e("mygo", "camera: $it")
|
||||
}
|
||||
}, ContextCompat.getMainExecutor(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
override fun call(method: String, args: JSONObject, reply: PluginReply) {
|
||||
val id = args.optLong("id")
|
||||
val c = cams[id]
|
||||
if (c == null) {
|
||||
reply.failure(PluginFailure("NoView"))
|
||||
return
|
||||
}
|
||||
when (method) {
|
||||
"takePhoto" -> {
|
||||
if (!c.bound) {
|
||||
reply.failure(PluginFailure("NoCamera", c.error))
|
||||
return
|
||||
}
|
||||
val ctx = PluginHost.context
|
||||
val f = File(ctx.cacheDir, "${System.nanoTime()}.jpg")
|
||||
c.capture.takePicture(ImageCapture.OutputFileOptions.Builder(f).build(), ContextCompat.getMainExecutor(ctx),
|
||||
object : ImageCapture.OnImageSavedCallback {
|
||||
override fun onImageSaved(r: ImageCapture.OutputFileResults) = reply.success(JSONObject().put("path", f.absolutePath))
|
||||
override fun onError(e: ImageCaptureException) = reply.failure(PluginFailure("Failed", e.toString()))
|
||||
})
|
||||
}
|
||||
"dispose" -> {
|
||||
cams.remove(id)
|
||||
runCatching { ProcessCameraProvider.getInstance(PluginHost.context).get().unbindAll() }
|
||||
reply.success(null)
|
||||
}
|
||||
else -> reply.failure(PluginFailure("NoMethod", method))
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
// Package camera shows what a phone's camera sees in a window's native UI, and
|
||||
// takes photos: AVCaptureSession on iOS, CameraX on Android. For a photo in the
|
||||
// system's own camera screen, use package imagepicker: it needs no permission.
|
||||
//
|
||||
// cam, err := camera.New(win, camera.Options{})
|
||||
// ...
|
||||
// ui.WebView(c, cam).Fill() // in the view; what it draws after shows over the preview
|
||||
// path, err := cam.TakePhoto(ctx)
|
||||
//
|
||||
// The preview shows under the content, as a web view does. On desktops and in
|
||||
// browsers New reports errors.ErrUnsupported.
|
||||
package camera
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
"github.com/egoist/mygo/internal/surface"
|
||||
)
|
||||
|
||||
const pluginID = "camera"
|
||||
|
||||
// Options are which camera shows.
|
||||
type Options struct {
|
||||
// Front chooses the camera on the screen's side.
|
||||
Front bool
|
||||
}
|
||||
|
||||
// Camera is a preview of a camera, which takes photos. Show it with ui.WebView.
|
||||
type Camera struct{ view *mygo.PluginView }
|
||||
|
||||
// New asks the user for the camera, the first time, and makes its preview in a
|
||||
// window showing native UI.
|
||||
func New(w *mygo.Window, o Options) (*Camera, error) {
|
||||
v, err := mygo.NewPluginView(w, "camera", map[string]any{"front": o.Front})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Camera{v}, nil
|
||||
}
|
||||
|
||||
// SurfaceWebView gives package ui the view to show.
|
||||
func (c *Camera) SurfaceWebView(conn *surface.Conn) platform.WebView {
|
||||
return c.view.SurfaceWebView(conn)
|
||||
}
|
||||
|
||||
// TakePhoto takes a photo and returns the path of its JPEG in the app's
|
||||
// temporary directory.
|
||||
func (c *Camera) TakePhoto(ctx context.Context) (string, error) {
|
||||
var r struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
err := mygo.Native(pluginID).Call(ctx, "takePhoto", map[string]any{"id": c.view.ID}, &r)
|
||||
return r.Path, err
|
||||
}
|
||||
|
||||
// Destroy stops the camera and takes its preview away.
|
||||
func (c *Camera) Destroy() {
|
||||
go mygo.Native(pluginID).Call(context.Background(), "dispose", map[string]any{"id": c.view.ID}, nil)
|
||||
c.view.Destroy()
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import AVFoundation
|
||||
import UIKit
|
||||
|
||||
private final class PreviewView: UIView, AVCapturePhotoCaptureDelegate {
|
||||
override class var layerClass: AnyClass { AVCaptureVideoPreviewLayer.self }
|
||||
let session = AVCaptureSession()
|
||||
let output = AVCapturePhotoOutput()
|
||||
var waiting: PluginReply?
|
||||
|
||||
func start(front: Bool) {
|
||||
(layer as! AVCaptureVideoPreviewLayer).session = session
|
||||
(layer as! AVCaptureVideoPreviewLayer).videoGravity = .resizeAspectFill
|
||||
AVCaptureDevice.requestAccess(for: .video) { granted in
|
||||
guard granted else { return }
|
||||
let position: AVCaptureDevice.Position = front ? .front : .back
|
||||
guard let d = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: position),
|
||||
let input = try? AVCaptureDeviceInput(device: d) else { return }
|
||||
self.session.beginConfiguration()
|
||||
if self.session.canAddInput(input) { self.session.addInput(input) }
|
||||
if self.session.canAddOutput(self.output) { self.session.addOutput(self.output) }
|
||||
self.session.commitConfiguration()
|
||||
DispatchQueue.global(qos: .userInitiated).async { self.session.startRunning() }
|
||||
}
|
||||
}
|
||||
|
||||
func stop() {
|
||||
DispatchQueue.global(qos: .userInitiated).async { self.session.stopRunning() }
|
||||
}
|
||||
|
||||
func photoOutput(_ o: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
|
||||
guard let reply = waiting else { return }
|
||||
waiting = nil
|
||||
guard let data = photo.fileDataRepresentation() else {
|
||||
reply(.failure(PluginFailure("Failed", error?.localizedDescription ?? "no photo")))
|
||||
return
|
||||
}
|
||||
let path = NSTemporaryDirectory() + UUID().uuidString + ".jpg"
|
||||
do {
|
||||
try data.write(to: URL(fileURLWithPath: path))
|
||||
reply(.success(["path": path]))
|
||||
} catch {
|
||||
reply(.failure(PluginFailure("Failed", error.localizedDescription)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class CameraPlugin: MyGoPlugin {
|
||||
private var views: [Int: PreviewView] = [:]
|
||||
|
||||
init() {
|
||||
PluginHost.registerView("camera") { [weak self] id, args in
|
||||
let v = PreviewView()
|
||||
self?.views[id] = v
|
||||
v.start(front: args["front"] as? Bool ?? false)
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
func call(_ method: String, _ args: [String: Any], _ reply: @escaping PluginReply) {
|
||||
guard let id = args["id"] as? Int, let v = views[id] else {
|
||||
return reply(.failure(PluginFailure("NoView")))
|
||||
}
|
||||
switch method {
|
||||
case "takePhoto":
|
||||
guard !v.session.outputs.isEmpty, v.session.isRunning else {
|
||||
return reply(.failure(PluginFailure("NoCamera", "the camera is not running")))
|
||||
}
|
||||
v.waiting = reply
|
||||
v.output.capturePhoto(with: AVCapturePhotoSettings(), delegate: v)
|
||||
case "dispose":
|
||||
v.stop()
|
||||
views[id] = nil
|
||||
reply(.success(nil))
|
||||
default:
|
||||
reply(.failure(PluginFailure("NoMethod", method)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"mobile": {
|
||||
"id": "camera",
|
||||
"ios": {
|
||||
"sources": ["ios/*.swift"],
|
||||
"class": "CameraPlugin",
|
||||
"frameworks": ["AVFoundation"],
|
||||
"infoPlist": {"NSCameraUsageDescription": "This app uses the camera."}
|
||||
},
|
||||
"android": {
|
||||
"sources": ["android/*.kt"],
|
||||
"class": "CameraPlugin",
|
||||
"permissions": ["CAMERA"],
|
||||
"dependencies": ["androidx.camera:camera-camera2:1.6.2", "androidx.camera:camera-lifecycle:1.6.2", "androidx.camera:camera-view:1.6.2"]
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+64
@@ -0,0 +1,64 @@
|
||||
// A Go side for the plugins' tests: the real page runtime of the bridge,
|
||||
// installed as window.mygo, whose calls go to handlers written in
|
||||
// TypeScript that stream through channels as Go methods do.
|
||||
import { createRuntime } from "../packages/bridge/src/runtime";
|
||||
import type { Outgoing } from "../packages/bridge/src/types";
|
||||
|
||||
/** A call being handled. */
|
||||
export interface GoCall {
|
||||
args: unknown[];
|
||||
/** Sends a value on the channel passed as the i-th argument. */
|
||||
send(i: number, value: unknown): void;
|
||||
/** Aborted when the page closes a channel of the call. */
|
||||
signal: AbortSignal;
|
||||
}
|
||||
|
||||
export type Handler = (call: GoCall) => unknown;
|
||||
|
||||
/** Methods whose argument 1 is a channel, as those of the plugins. */
|
||||
const streaming = new Set(["plugin:fetch.Fetch", "plugin:websocket.Connect", "plugin:watch.Watch"]);
|
||||
|
||||
/** Installs window.mygo with handlers for methods; returns what was called. */
|
||||
export function fakeGo(handlers: Record<string, Handler>): { calls: [string, unknown[]][]; uninstall(): void } {
|
||||
const calls: [string, unknown[]][] = [];
|
||||
const aborts = new Map<number, AbortController>();
|
||||
const { runtime, internal } = createRuntime(
|
||||
{ platform: "darwin", windowId: 1, version: "0.0.0-test", secret: "s", locale: "en", dir: "ltr" },
|
||||
(raw) => {
|
||||
const m = JSON.parse(raw) as Outgoing;
|
||||
if (m.t === "chan-close") aborts.get(m.c)?.abort();
|
||||
if (m.t !== "call") return;
|
||||
calls.push([m.m, m.a]);
|
||||
const abort = new AbortController();
|
||||
const chans = m.a.map((a, i) => (streaming.has(m.m) && i === 1 && handlers[m.m] ? (a as number) : 0));
|
||||
chans.forEach((c) => c && aborts.set(c, abort));
|
||||
// Like Go: a goroutine per call, the channels end before the reply.
|
||||
setTimeout(async () => {
|
||||
const handler = handlers[m.m];
|
||||
let reply: { ok: boolean; v?: unknown; e?: string };
|
||||
try {
|
||||
if (!handler) throw new Error(`method ${m.m} is not bound`);
|
||||
const v = await handler({
|
||||
args: m.a,
|
||||
send(i, value) {
|
||||
if (abort.signal.aborted) throw new Error("mygo: channel closed");
|
||||
internal.receive({ t: "chan", c: chans[i]!, k: m.k, p: value });
|
||||
},
|
||||
signal: abort.signal,
|
||||
});
|
||||
reply = { ok: true, v };
|
||||
} catch (err) {
|
||||
reply = { ok: false, e: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
for (const c of chans) if (c) internal.receive({ t: "chan", c, k: m.k, end: true });
|
||||
internal.receive({ t: "reply", id: m.id, k: m.k, ...reply });
|
||||
});
|
||||
},
|
||||
);
|
||||
(globalThis as { mygo?: unknown }).mygo = runtime;
|
||||
return { calls, uninstall: () => delete (globalThis as { mygo?: unknown }).mygo };
|
||||
}
|
||||
|
||||
export const tick = () => new Promise((r) => setTimeout(r, 1));
|
||||
|
||||
export const b64 = (s: string) => Buffer.from(s).toString("base64");
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 MyGo contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
# @mygo-plugins/fetch
|
||||
|
||||
A `fetch` for [MyGo](https://github.com/egoist/mygo) apps that makes HTTP
|
||||
requests from Go: not subject to CORS, free to set any header (Origin,
|
||||
Cookie, User-Agent, ...), with the standard options and a standard
|
||||
`Response` whose body streams as Go reads it.
|
||||
|
||||
Use the plugin in Go:
|
||||
|
||||
```go
|
||||
import "github.com/egoist/mygo/plugins/fetch"
|
||||
|
||||
mygo.Use(fetch.Plugin) // or fetch.New(fetch.Options{Client: ..., Allow: ...})
|
||||
```
|
||||
|
||||
and fetch in the frontend:
|
||||
|
||||
```ts
|
||||
import { fetch } from "@mygo-plugins/fetch";
|
||||
|
||||
const ctrl = new AbortController();
|
||||
const res = await fetch("https://api.example.com/items", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
signal: ctrl.signal, // aborting cancels the request in Go
|
||||
});
|
||||
const items = await res.json();
|
||||
```
|
||||
|
||||
- Aborting the signal, canceling the body, navigating away or closing the
|
||||
window cancels the request in Go.
|
||||
- `redirect: "manual"` returns the redirect response itself, with its
|
||||
`Location`, instead of an opaque response.
|
||||
- `mode`, `credentials`, `cache` and the like do not apply; cookies are those
|
||||
of the Go side's `http.Client` (give it a `Jar` to keep them).
|
||||
- Every response header is readable but `Set-Cookie` and `Set-Cookie2`,
|
||||
which are filtered before the response reaches the page.
|
||||
- URLs that are not http or https (the app's own pages, `data:`, `blob:`) go
|
||||
to the webview's `fetch`.
|
||||
|
||||
[The documentation](https://github.com/egoist/mygo/blob/main/docs/plugins/fetch.md)
|
||||
covers streaming, errors and the options of the Go side.
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
// Package fetch is the fetch plugin of MyGo: pages make HTTP requests from
|
||||
// Go with the fetch of its JavaScript package, @mygo-plugins/fetch, which
|
||||
// takes and returns the standard Request options and Response. Requests
|
||||
// made this way are not subject to CORS, may set any header (Origin,
|
||||
// Cookie, User-Agent, ...) and read every response header but Set-Cookie
|
||||
// and Set-Cookie2, which are filtered before sending the response to pages.
|
||||
//
|
||||
// mygo.Use(fetch.Plugin)
|
||||
//
|
||||
// and in the frontend:
|
||||
//
|
||||
// import { fetch } from "@mygo-plugins/fetch";
|
||||
//
|
||||
// const res = await fetch("https://api.example.com/items", {
|
||||
// headers: { authorization: `Bearer ${token}` },
|
||||
// });
|
||||
// const items = await res.json();
|
||||
//
|
||||
// The response body streams to the page as Go reads it, and aborting the
|
||||
// request's signal cancels it in Go. URLs that are not http or https, such
|
||||
// as the app's own pages, go to the webview's fetch.
|
||||
package fetch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/netproxy"
|
||||
)
|
||||
|
||||
// Options configure the plugin.
|
||||
type Options struct {
|
||||
// Client makes the requests; nil means a client of
|
||||
// netproxy.Transport(), which follows the system's proxy settings. Its
|
||||
// CheckRedirect limits the redirects followed when the request's
|
||||
// redirect mode is "follow".
|
||||
Client *http.Client
|
||||
// Allow, when not nil, decides whether pages may make a request; a
|
||||
// request it refuses rejects with an error.
|
||||
Allow func(r *http.Request) bool
|
||||
}
|
||||
|
||||
// Plugin is the plugin with the default options.
|
||||
var Plugin = New(Options{})
|
||||
|
||||
// New returns the plugin with options.
|
||||
func New(opts Options) mygo.Plugin {
|
||||
if opts.Client == nil {
|
||||
opts.Client = &http.Client{Transport: netproxy.Transport()}
|
||||
}
|
||||
return mygo.Plugin{Name: "fetch", Service: &service{opts}}
|
||||
}
|
||||
|
||||
type service struct{ opts Options }
|
||||
|
||||
// request is what the page asks for.
|
||||
type request struct {
|
||||
URL string `json:"url"`
|
||||
Method string `json:"method"`
|
||||
Headers [][2]string `json:"headers"`
|
||||
Body []byte `json:"body"`
|
||||
Redirect string `json:"redirect"`
|
||||
}
|
||||
|
||||
// part is the response: its head first, then chunks of its body.
|
||||
type part struct {
|
||||
Status int `json:"status,omitzero"`
|
||||
StatusText string `json:"statusText,omitzero"`
|
||||
URL string `json:"url,omitzero"`
|
||||
Redirected bool `json:"redirected,omitzero"`
|
||||
Headers [][2]string `json:"headers,omitzero"`
|
||||
Chunk []byte `json:"chunk,omitzero"`
|
||||
}
|
||||
|
||||
// Fetch makes the request and streams the response to the page.
|
||||
func (s *service) Fetch(ctx context.Context, req request, parts *mygo.Channel[part]) error {
|
||||
return s.fetch(ctx, req, parts.Send)
|
||||
}
|
||||
|
||||
// chunkSize is the most body bytes a part holds.
|
||||
const chunkSize = 64 << 10
|
||||
|
||||
func (s *service) fetch(ctx context.Context, req request, send func(part) error) error {
|
||||
r, err := http.NewRequestWithContext(ctx, req.Method, req.URL, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r.URL.Scheme != "http" && r.URL.Scheme != "https" {
|
||||
return fmt.Errorf("unsupported URL scheme %q", r.URL.Scheme)
|
||||
}
|
||||
if req.Body != nil {
|
||||
r.Body = io.NopCloser(bytes.NewReader(req.Body))
|
||||
r.ContentLength = int64(len(req.Body))
|
||||
body := req.Body
|
||||
r.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil }
|
||||
}
|
||||
for _, h := range req.Headers {
|
||||
switch http.CanonicalHeaderKey(h[0]) {
|
||||
case "Host":
|
||||
r.Host = h[1]
|
||||
case "Content-Length": // the body's
|
||||
default:
|
||||
r.Header.Add(h[0], h[1])
|
||||
}
|
||||
}
|
||||
if s.opts.Allow != nil && !s.opts.Allow(r) {
|
||||
return fmt.Errorf("the app does not allow requests to %s", r.URL.Redacted())
|
||||
}
|
||||
|
||||
client := *s.opts.Client
|
||||
redirected := false
|
||||
check := client.CheckRedirect
|
||||
client.CheckRedirect = func(next *http.Request, via []*http.Request) error {
|
||||
switch req.Redirect {
|
||||
case "manual":
|
||||
return http.ErrUseLastResponse
|
||||
case "error":
|
||||
return errors.New("redirected with redirect mode \"error\"")
|
||||
}
|
||||
if check != nil {
|
||||
if err := check(next, via); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if len(via) >= 20 { // as browsers
|
||||
return errors.New("too many redirects")
|
||||
}
|
||||
redirected = true
|
||||
return nil
|
||||
}
|
||||
res, err := client.Do(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
head := part{
|
||||
Status: res.StatusCode,
|
||||
StatusText: strings.TrimSpace(strings.TrimPrefix(res.Status, fmt.Sprint(res.StatusCode))),
|
||||
URL: res.Request.URL.String(),
|
||||
Redirected: redirected,
|
||||
Headers: [][2]string{},
|
||||
}
|
||||
for k, vs := range res.Header {
|
||||
k = strings.ToLower(k)
|
||||
if k == "set-cookie" || k == "set-cookie2" {
|
||||
continue
|
||||
}
|
||||
for _, v := range vs {
|
||||
head.Headers = append(head.Headers, [2]string{k, v})
|
||||
}
|
||||
}
|
||||
if err := send(head); err != nil {
|
||||
return err
|
||||
}
|
||||
buf := make([]byte, chunkSize)
|
||||
for {
|
||||
// What arrived goes out at once, for streamed responses.
|
||||
n, err := res.Body.Read(buf)
|
||||
if n > 0 {
|
||||
// Send encodes the chunk before returning, so buf can be reused.
|
||||
if err := send(part{Chunk: buf[:n]}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package fetch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func run(t *testing.T, s *service, req request) ([]part, error) {
|
||||
t.Helper()
|
||||
var parts []part
|
||||
err := s.fetch(context.Background(), req, func(p part) error {
|
||||
p.Chunk = append([]byte(nil), p.Chunk...)
|
||||
parts = append(parts, p)
|
||||
return nil
|
||||
})
|
||||
return parts, err
|
||||
}
|
||||
|
||||
func header(p part, name string) string {
|
||||
for _, h := range p.Headers {
|
||||
if h[0] == name {
|
||||
return h[1]
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func body(parts []part) string {
|
||||
var b strings.Builder
|
||||
for _, p := range parts[1:] {
|
||||
b.Write(p.Chunk)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func TestFetch(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
w.Header().Add("X-Multi", "a")
|
||||
w.Header().Add("X-Multi", "b")
|
||||
w.Header().Set("X-Origin", r.Header.Get("Origin"))
|
||||
w.Header().Set("X-Host", r.Host)
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
io.WriteString(w, r.Method+" "+string(b))
|
||||
})
|
||||
mux.HandleFunc("/big", func(w http.ResponseWriter, r *http.Request) {
|
||||
io.WriteString(w, strings.Repeat("x", 3*chunkSize/2))
|
||||
})
|
||||
mux.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/echo", http.StatusFound)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
s := New(Options{}).Service.(*service)
|
||||
|
||||
parts, err := run(t, s, request{
|
||||
URL: srv.URL + "/echo",
|
||||
Method: "POST",
|
||||
Headers: [][2]string{{"origin", "https://example.com"}, {"host", "api.test"}, {"content-length", "999"}},
|
||||
Body: []byte("hi"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head := parts[0]
|
||||
if head.Status != 201 || head.StatusText != "Created" || head.Redirected {
|
||||
t.Errorf("head = %+v", head)
|
||||
}
|
||||
if header(head, "x-origin") != "https://example.com" || header(head, "x-host") != "api.test" {
|
||||
t.Errorf("request headers were not sent: %v", head.Headers)
|
||||
}
|
||||
n := 0
|
||||
for _, h := range head.Headers {
|
||||
if h[0] == "x-multi" {
|
||||
n++
|
||||
}
|
||||
}
|
||||
if n != 2 {
|
||||
t.Errorf("repeated header sent %d times: %v", n, head.Headers)
|
||||
}
|
||||
if got := body(parts); got != "POST hi" {
|
||||
t.Errorf("body = %q", got)
|
||||
}
|
||||
|
||||
parts, err = run(t, s, request{URL: srv.URL + "/big", Method: "GET"})
|
||||
if err != nil || len(parts) < 3 || len(body(parts)) != 3*chunkSize/2 {
|
||||
t.Errorf("big body: %d parts, %v", len(parts), err)
|
||||
}
|
||||
for _, p := range parts[1:] {
|
||||
if len(p.Chunk) > chunkSize {
|
||||
t.Errorf("chunk of %d bytes", len(p.Chunk))
|
||||
}
|
||||
}
|
||||
|
||||
parts, err = run(t, s, request{URL: srv.URL + "/redirect", Method: "GET"})
|
||||
if err != nil || parts[0].Status != 201 || !parts[0].Redirected || parts[0].URL != srv.URL+"/echo" {
|
||||
t.Errorf("followed redirect: %+v, %v", parts, err)
|
||||
}
|
||||
parts, err = run(t, s, request{URL: srv.URL + "/redirect", Method: "GET", Redirect: "manual"})
|
||||
if err != nil || parts[0].Status != 302 || header(parts[0], "location") != "/echo" {
|
||||
t.Errorf("manual redirect: %+v, %v", parts, err)
|
||||
}
|
||||
if _, err = run(t, s, request{URL: srv.URL + "/redirect", Method: "GET", Redirect: "error"}); err == nil {
|
||||
t.Error("redirect mode error followed a redirect")
|
||||
}
|
||||
if _, err = run(t, s, request{URL: "file:///etc/passwd", Method: "GET"}); err == nil {
|
||||
t.Error("fetched a file URL")
|
||||
}
|
||||
|
||||
deny := New(Options{Allow: func(r *http.Request) bool { return r.URL.Path != "/echo" }}).Service.(*service)
|
||||
if _, err = run(t, deny, request{URL: srv.URL + "/echo", Method: "GET"}); err == nil || !strings.Contains(err.Error(), "does not allow") {
|
||||
t.Errorf("Allow: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchFiltersCookieHeaders(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Add("Set-Cookie", "session=secret; HttpOnly; Path=/")
|
||||
w.Header().Add("Set-Cookie", "other=value; Path=/")
|
||||
w.Header().Set("Set-Cookie2", "legacy=secret")
|
||||
w.Header().Set("X-Visible", "yes")
|
||||
}))
|
||||
defer srv.Close()
|
||||
jar, err := cookiejar.New(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := srv.Client()
|
||||
client.Jar = jar
|
||||
s := New(Options{Client: client}).Service.(*service)
|
||||
parts, err := run(t, s, request{URL: srv.URL, Method: "GET"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, h := range parts[0].Headers {
|
||||
if strings.EqualFold(h[0], "Set-Cookie") || strings.EqualFold(h[0], "Set-Cookie2") {
|
||||
t.Errorf("cookie header sent to the page: %v", h)
|
||||
}
|
||||
}
|
||||
if header(parts[0], "x-visible") != "yes" {
|
||||
t.Error("ordinary response header was filtered")
|
||||
}
|
||||
r, err := http.NewRequest("GET", srv.URL, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cookies := jar.Cookies(r.URL); len(cookies) != 2 {
|
||||
t.Errorf("Go cookie jar = %v; want both cookies retained", cookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchStops(t *testing.T) {
|
||||
release := make(chan struct{})
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
io.WriteString(w, "first")
|
||||
w.(http.Flusher).Flush()
|
||||
select {
|
||||
case <-release:
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
defer close(release)
|
||||
s := New(Options{}).Service.(*service)
|
||||
|
||||
// A streamed body arrives as it is written, and the request stops
|
||||
// when the page stops taking it.
|
||||
var got []string
|
||||
stop := io.ErrClosedPipe
|
||||
err := s.fetch(context.Background(), request{URL: srv.URL, Method: "GET"}, func(p part) error {
|
||||
if p.Chunk != nil {
|
||||
got = append(got, string(p.Chunk))
|
||||
return stop
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != stop || len(got) != 1 || got[0] != "first" {
|
||||
t.Errorf("got %q, %v", got, err)
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "@mygo-plugins/fetch",
|
||||
"version": "0.10.0",
|
||||
"description": "A fetch that makes HTTP requests from Go, for MyGo desktop apps",
|
||||
"keywords": [
|
||||
"mygo",
|
||||
"desktop",
|
||||
"webview",
|
||||
"go",
|
||||
"fetch"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/egoist/mygo.git",
|
||||
"directory": "plugins/fetch"
|
||||
},
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "bun run ../build.ts",
|
||||
"test": "bun test"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"mygo-runtime": "^0.10.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"mygo-runtime": "^0.10.0"
|
||||
}
|
||||
}
|
||||
+311
@@ -0,0 +1,311 @@
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { b64, fakeGo, tick, type GoCall } from "../../fake-go";
|
||||
import { fetch } from "./index";
|
||||
|
||||
let go: ReturnType<typeof fakeGo> | undefined;
|
||||
afterEach(() => go?.uninstall());
|
||||
|
||||
interface Req {
|
||||
url: string;
|
||||
method: string;
|
||||
headers: [string, string][];
|
||||
body: string | null;
|
||||
redirect: string;
|
||||
}
|
||||
|
||||
const head = (status = 200, headers: [string, string][] = []) => ({
|
||||
status,
|
||||
statusText: "OK",
|
||||
url: "https://example.com/final",
|
||||
redirected: true,
|
||||
headers,
|
||||
});
|
||||
|
||||
test("sends the request and streams the response", async () => {
|
||||
let got: Req | undefined;
|
||||
go = fakeGo({
|
||||
"plugin:fetch.Fetch": (c: GoCall) => {
|
||||
got = c.args[0] as Req;
|
||||
c.send(1, head(201, [["content-type", "application/json"], ["x-a", "1"]]));
|
||||
c.send(1, { chunk: b64('{"a":') });
|
||||
c.send(1, { chunk: b64("1}") });
|
||||
},
|
||||
});
|
||||
const res = await fetch(new URL("https://example.com/items"), {
|
||||
method: "post",
|
||||
headers: { origin: "https://app.test", "x-token": "t" },
|
||||
body: new URLSearchParams({ q: "go" }),
|
||||
});
|
||||
expect(got).toMatchObject({ url: "https://example.com/items", method: "POST", redirect: "follow" });
|
||||
expect(Object.fromEntries(got!.headers)).toEqual({
|
||||
origin: "https://app.test",
|
||||
"x-token": "t",
|
||||
"content-type": "application/x-www-form-urlencoded;charset=UTF-8",
|
||||
});
|
||||
expect(Buffer.from(got!.body!, "base64").toString()).toBe("q=go");
|
||||
expect(res).toBeInstanceOf(Response);
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.url).toBe("https://example.com/final");
|
||||
expect(res.redirected).toBe(true);
|
||||
expect(res.headers.get("x-a")).toBe("1");
|
||||
expect(await res.json()).toEqual({ a: 1 });
|
||||
});
|
||||
|
||||
test("takes a Request", async () => {
|
||||
let got: Req | undefined;
|
||||
go = fakeGo({
|
||||
"plugin:fetch.Fetch": (c) => {
|
||||
got = c.args[0] as Req;
|
||||
c.send(1, head(204));
|
||||
},
|
||||
});
|
||||
const res = await fetch(new Request("https://example.com/x", { method: "PUT", body: "hi", redirect: "manual" }));
|
||||
expect(got).toMatchObject({ method: "PUT", redirect: "manual", body: b64("hi") });
|
||||
expect(res.status).toBe(204);
|
||||
expect(res.body).toBeNull();
|
||||
});
|
||||
|
||||
test("clones preserve response metadata and independently readable bodies", async () => {
|
||||
go = fakeGo({
|
||||
"plugin:fetch.Fetch": (c) => {
|
||||
c.send(1, head(201, [["content-type", "text/plain"], ["x-test", "clone"]]));
|
||||
c.send(1, { chunk: b64("first ") });
|
||||
c.send(1, { chunk: b64("second") });
|
||||
},
|
||||
});
|
||||
const res = await fetch("https://example.com/start");
|
||||
const copy = res.clone();
|
||||
const another = copy.clone();
|
||||
for (const response of [res, copy, another]) {
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect(response.url).toBe("https://example.com/final");
|
||||
expect(response.redirected).toBe(true);
|
||||
expect(response.status).toBe(201);
|
||||
expect(response.statusText).toBe("OK");
|
||||
expect(response.headers.get("x-test")).toBe("clone");
|
||||
expect(response.bodyUsed).toBe(false);
|
||||
}
|
||||
expect(await Promise.all([res.text(), copy.text(), another.text()])).toEqual([
|
||||
"first second", "first second", "first second",
|
||||
]);
|
||||
expect(go.calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
for (const status of [101, 204]) {
|
||||
test(`clones preserve metadata of a bodyless ${status} response`, async () => {
|
||||
go = fakeGo({
|
||||
"plugin:fetch.Fetch": (c) => {
|
||||
c.send(1, { status, statusText: "", url: "https://example.com/final", redirected: true });
|
||||
},
|
||||
});
|
||||
const res = await fetch("https://example.com/start");
|
||||
const copy = res.clone().clone();
|
||||
expect(copy.status).toBe(status);
|
||||
expect(copy.url).toBe(res.url);
|
||||
expect(copy.redirected).toBe(true);
|
||||
expect(copy.body).toBeNull();
|
||||
});
|
||||
}
|
||||
|
||||
test("cloning still rejects a locked or consumed body", async () => {
|
||||
go = fakeGo({
|
||||
"plugin:fetch.Fetch": (c) => {
|
||||
c.send(1, head());
|
||||
c.send(1, { chunk: b64("body") });
|
||||
},
|
||||
});
|
||||
const res = await fetch("https://example.com/start");
|
||||
const copy = res.clone();
|
||||
const reader = copy.body!.getReader();
|
||||
expect(() => copy.clone()).toThrow(TypeError);
|
||||
reader.releaseLock();
|
||||
expect(await copy.text()).toBe("body");
|
||||
expect(() => copy.clone()).toThrow(TypeError);
|
||||
expect(await res.text()).toBe("body");
|
||||
expect(() => res.clone()).toThrow(TypeError);
|
||||
});
|
||||
|
||||
test("rejects URL credentials before calling Go", async () => {
|
||||
go = fakeGo({ "plugin:fetch.Fetch": (c) => c.send(1, head(204)) });
|
||||
for (const url of [
|
||||
"https://user:password@example.com/",
|
||||
"http://user@example.com/",
|
||||
"https://:password@example.com/",
|
||||
]) {
|
||||
for (const input of [url, new URL(url)]) {
|
||||
await expect(fetch(input)).rejects.toThrow(TypeError);
|
||||
expect(go.calls).toEqual([]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("allows an empty URL userinfo and explicit authorization", async () => {
|
||||
let got: Req | undefined;
|
||||
go = fakeGo({
|
||||
"plugin:fetch.Fetch": (c) => {
|
||||
got = c.args[0] as Req;
|
||||
c.send(1, head(204));
|
||||
},
|
||||
});
|
||||
await fetch("https://:@example.com/", { headers: { authorization: "Basic dXNlcjpwYXNzd29yZA==" } });
|
||||
expect(got?.url).toBe("https://example.com/");
|
||||
expect(got?.headers).toContainEqual(["authorization", "Basic dXNlcjpwYXNzd29yZA=="]);
|
||||
});
|
||||
|
||||
test("inherits a Request body when init.body is null or omitted", async () => {
|
||||
let got: Req | undefined;
|
||||
go = fakeGo({
|
||||
"plugin:fetch.Fetch": (c) => {
|
||||
got = c.args[0] as Req;
|
||||
c.send(1, head(204));
|
||||
},
|
||||
});
|
||||
for (const body of [undefined, null, "replacement", ""]) {
|
||||
const req = new Request("https://example.com/x", { method: "POST", body: "original" });
|
||||
await fetch(req, { body });
|
||||
expect(got?.body).toBe(b64(body ?? "original"));
|
||||
}
|
||||
});
|
||||
|
||||
test("an explicit null signal stops inheriting the Request signal", async () => {
|
||||
go = fakeGo({ "plugin:fetch.Fetch": (c) => c.send(1, head(204)) });
|
||||
const signal = AbortSignal.abort(new Error("original request aborted"));
|
||||
const req = new Request("https://example.com/x", { signal });
|
||||
expect(await fetch(req, { signal: undefined }).catch((err) => err)).toBe(signal.reason);
|
||||
expect((await fetch(req, { signal: null })).status).toBe(204);
|
||||
expect(go.calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("rejects when Go fails", async () => {
|
||||
go = fakeGo({
|
||||
"plugin:fetch.Fetch": () => {
|
||||
throw new Error("dial tcp: connection refused");
|
||||
},
|
||||
});
|
||||
const err = await fetch("https://example.com").catch((e) => e);
|
||||
expect(err).toBeInstanceOf(TypeError);
|
||||
expect(err.message).toBe("fetch failed: dial tcp: connection refused");
|
||||
});
|
||||
|
||||
test("explains a missing Go side", async () => {
|
||||
go = fakeGo({});
|
||||
const err = await fetch("https://example.com").catch((e) => e);
|
||||
expect(err.message).toBe("fetch failed: method plugin:fetch.Fetch is not bound");
|
||||
go.uninstall();
|
||||
go = fakeGo({
|
||||
"plugin:fetch.Fetch": () => {
|
||||
throw new Error("the fetch plugin is not used: call mygo.Use with it before App.Run");
|
||||
},
|
||||
});
|
||||
expect((await fetch("https://example.com").catch((e) => e)).message).toContain("mygo.Use(fetch.Plugin)");
|
||||
});
|
||||
|
||||
test("errors the body when Go fails while streaming", async () => {
|
||||
go = fakeGo({
|
||||
"plugin:fetch.Fetch": (c) => {
|
||||
c.send(1, head());
|
||||
c.send(1, { chunk: b64("par") });
|
||||
throw new Error("unexpected EOF");
|
||||
},
|
||||
});
|
||||
const res = await fetch("https://example.com");
|
||||
expect((await res.text().catch((e) => e)).message).toBe("fetch failed: unexpected EOF");
|
||||
});
|
||||
|
||||
test("aborts", async () => {
|
||||
let stopped = false;
|
||||
const streaming = (c: GoCall) =>
|
||||
new Promise<void>((resolve) => {
|
||||
c.send(1, head());
|
||||
c.send(1, { chunk: b64("first") });
|
||||
c.signal.addEventListener("abort", () => {
|
||||
stopped = true;
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
go = fakeGo({ "plugin:fetch.Fetch": streaming });
|
||||
|
||||
const ctrl = new AbortController();
|
||||
const res = await fetch("https://example.com", { signal: ctrl.signal });
|
||||
const reader = res.body!.getReader();
|
||||
expect(new TextDecoder().decode((await reader.read()).value)).toBe("first");
|
||||
ctrl.abort();
|
||||
expect((await reader.read().catch((e) => e)).name).toBe("AbortError");
|
||||
await tick();
|
||||
expect(stopped).toBe(true);
|
||||
|
||||
// Before the response.
|
||||
go.uninstall();
|
||||
go = fakeGo({ "plugin:fetch.Fetch": (c) => new Promise<void>((r) => c.signal.addEventListener("abort", () => r())) });
|
||||
const early = new AbortController();
|
||||
const p = fetch("https://example.com", { signal: early.signal });
|
||||
await tick();
|
||||
early.abort();
|
||||
expect((await p.catch((e) => e)).name).toBe("AbortError");
|
||||
expect((await fetch("https://example.com", { signal: AbortSignal.abort() }).catch((e) => e)).name).toBe("AbortError");
|
||||
|
||||
// Canceling the body stops Go too.
|
||||
go.uninstall();
|
||||
stopped = false;
|
||||
go = fakeGo({ "plugin:fetch.Fetch": streaming });
|
||||
await (await fetch("https://example.com")).body!.cancel();
|
||||
await tick();
|
||||
expect(stopped).toBe(true);
|
||||
});
|
||||
|
||||
test("leaves other schemes to the webview", async () => {
|
||||
go = fakeGo({});
|
||||
const res = await fetch("data:text/plain,hello");
|
||||
expect(await res.text()).toBe("hello");
|
||||
expect(go.calls).toEqual([]);
|
||||
});
|
||||
|
||||
test("refuses a GET body", async () => {
|
||||
go = fakeGo({});
|
||||
expect(fetch("https://example.com", { body: "x" })).rejects.toThrow(TypeError);
|
||||
});
|
||||
|
||||
test("does not send a JSON POST aborted before its body is ready", async () => {
|
||||
go = fakeGo({
|
||||
"plugin:fetch.Fetch": (c) => {
|
||||
c.send(1, head());
|
||||
},
|
||||
});
|
||||
const ctrl = new AbortController();
|
||||
const pending = fetch("https://example.com/items", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ name: "Ada" }),
|
||||
signal: ctrl.signal,
|
||||
});
|
||||
ctrl.abort();
|
||||
const result = await pending.then(() => "sent", (error: unknown) => error);
|
||||
expect(result).toBe(ctrl.signal.reason);
|
||||
expect(go.calls).toEqual([]);
|
||||
});
|
||||
|
||||
for (const source of ["init", "Request"] as const) {
|
||||
test(`does not send a request aborted while reading its ${source} body`, async () => {
|
||||
go = fakeGo({
|
||||
"plugin:fetch.Fetch": (c) => {
|
||||
c.send(1, head());
|
||||
},
|
||||
});
|
||||
let finish!: () => void;
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode("upload"));
|
||||
finish = () => controller.close();
|
||||
},
|
||||
});
|
||||
const ctrl = new AbortController();
|
||||
const reason = new Error("Upload canceled");
|
||||
const pending = source === "init"
|
||||
? fetch("https://example.com/upload", { method: "POST", body, signal: ctrl.signal })
|
||||
: fetch(new Request("https://example.com/upload", { method: "POST", body, signal: ctrl.signal }));
|
||||
ctrl.abort(reason);
|
||||
finish();
|
||||
const result = await pending.then(() => "sent", (error: unknown) => error);
|
||||
expect(result).toBe(reason);
|
||||
expect(go.calls).toEqual([]);
|
||||
});
|
||||
}
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* The fetch plugin of MyGo: a `fetch` that makes HTTP requests from Go,
|
||||
* free of CORS and of the webview's restrictions on headers. It takes the
|
||||
* standard options and returns a standard `Response`, whose body streams as
|
||||
* Go reads it. The Go side must use the plugin:
|
||||
*
|
||||
* ```go
|
||||
* mygo.Use(fetch.Plugin) // github.com/egoist/mygo/plugins/fetch
|
||||
* ```
|
||||
*
|
||||
* ```ts
|
||||
* import { fetch } from "@mygo-plugins/fetch";
|
||||
*
|
||||
* const res = await fetch("https://api.example.com/items", {
|
||||
* headers: { authorization: `Bearer ${token}` },
|
||||
* });
|
||||
* const items = await res.json();
|
||||
* ```
|
||||
*
|
||||
* URLs that are not http or https, such as the app's own pages, `data:` and
|
||||
* `blob:` URLs, go to the webview's `fetch`.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { Channel, call, isCallError } from "mygo-runtime";
|
||||
|
||||
/** What Go streams back: the response's head, then chunks of its body. */
|
||||
interface Part {
|
||||
status?: number;
|
||||
statusText?: string;
|
||||
url?: string;
|
||||
redirected?: boolean;
|
||||
headers?: [string, string][];
|
||||
/** Base64. */
|
||||
chunk?: string;
|
||||
}
|
||||
|
||||
/** Statuses whose responses have no body. */
|
||||
const NULL_BODY = new Set([101, 103, 204, 205, 304]);
|
||||
|
||||
/** Methods whose names are normalized to upper case, as `fetch` does. */
|
||||
const NORMALIZED = new Set(["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]);
|
||||
|
||||
/**
|
||||
* Makes an HTTP request from Go, with the options and result of the
|
||||
* standard `fetch`. `mode`, `credentials`, `cache` and the like have no
|
||||
* meaning there and are ignored; cookies are those of the Go side's
|
||||
* `http.Client`. Response headers are all there but `Set-Cookie` and `Set-Cookie2`.
|
||||
*/
|
||||
export async function fetch(input: RequestInfo | URL, init: RequestInit = {}): Promise<Response> {
|
||||
const req = typeof Request !== "undefined" && input instanceof Request ? input : null;
|
||||
const base = typeof location !== "undefined" ? location.href : undefined;
|
||||
const url = new URL(req ? req.url : input instanceof URL ? input.href : String(input), base);
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") return globalThis.fetch(input, init);
|
||||
if (url.username || url.password) throw new TypeError("fetch: URL must not include credentials");
|
||||
|
||||
const signal = init.signal === undefined ? req?.signal ?? null : init.signal;
|
||||
signal?.throwIfAborted();
|
||||
let method = init.method ?? req?.method ?? "GET";
|
||||
if (NORMALIZED.has(method.toUpperCase())) method = method.toUpperCase();
|
||||
// Plain Headers keep the names a Request would drop, such as Origin.
|
||||
const headers = new Headers(init.headers ?? req?.headers);
|
||||
let body: Uint8Array | null = null;
|
||||
if (init.body != null) {
|
||||
const r = new Response(init.body);
|
||||
const type = r.headers.get("content-type");
|
||||
if (type && !headers.has("content-type")) headers.set("content-type", type);
|
||||
body = new Uint8Array(await r.arrayBuffer());
|
||||
} else if (req?.body) {
|
||||
body = new Uint8Array(await req.arrayBuffer());
|
||||
}
|
||||
// Reading the body yields: it may have been aborted before Go sees it.
|
||||
signal?.throwIfAborted();
|
||||
if (body && (method === "GET" || method === "HEAD")) {
|
||||
throw new TypeError(`fetch: a ${method} request cannot have a body`);
|
||||
}
|
||||
|
||||
const parts = new Channel<Part>();
|
||||
const done = call<void>("plugin:fetch.Fetch", {
|
||||
url: url.href,
|
||||
method,
|
||||
headers: [...headers],
|
||||
body: body && toBase64(body),
|
||||
redirect: init.redirect ?? req?.redirect ?? "follow",
|
||||
}, parts);
|
||||
// Rejections are taken where they matter; this one must not go unhandled.
|
||||
const failed = done.then(
|
||||
() => null,
|
||||
(err: unknown) => failure(err),
|
||||
);
|
||||
const it = parts[Symbol.asyncIterator]();
|
||||
|
||||
let stream: ReadableStreamDefaultController<Uint8Array> | undefined;
|
||||
let rejectHead: ((reason: unknown) => void) | undefined;
|
||||
const onAbort = () => {
|
||||
parts.close();
|
||||
try {
|
||||
stream?.error(signal!.reason);
|
||||
} catch {}
|
||||
rejectHead?.(signal!.reason);
|
||||
};
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
const cleanup = () => signal?.removeEventListener("abort", onAbort);
|
||||
|
||||
let head: Part;
|
||||
try {
|
||||
const first = await new Promise<IteratorResult<Part>>((resolve, reject) => {
|
||||
rejectHead = reject;
|
||||
it.next().then(resolve, reject);
|
||||
});
|
||||
rejectHead = undefined;
|
||||
if (first.done) throw (await failed) ?? new TypeError("fetch failed: no response");
|
||||
head = first.value;
|
||||
} catch (err) {
|
||||
cleanup();
|
||||
parts.close();
|
||||
throw err;
|
||||
}
|
||||
|
||||
const status = head.status ?? 200;
|
||||
const nullBody = NULL_BODY.has(status) || method === "HEAD";
|
||||
const readable = nullBody
|
||||
? null
|
||||
: new ReadableStream<Uint8Array>(
|
||||
{
|
||||
start(controller) {
|
||||
stream = controller;
|
||||
},
|
||||
async pull(controller) {
|
||||
const next = await it.next();
|
||||
if (signal?.aborted) return;
|
||||
if (!next.done) {
|
||||
if (next.value.chunk) controller.enqueue(fromBase64(next.value.chunk));
|
||||
return;
|
||||
}
|
||||
cleanup();
|
||||
const err = await failed;
|
||||
if (err) controller.error(err);
|
||||
else controller.close();
|
||||
},
|
||||
cancel() {
|
||||
cleanup();
|
||||
parts.close();
|
||||
},
|
||||
},
|
||||
{ highWaterMark: 0 },
|
||||
);
|
||||
if (nullBody) {
|
||||
parts.close();
|
||||
cleanup();
|
||||
}
|
||||
// Response takes statuses from 200 to 599 only.
|
||||
const valid = status >= 200 && status <= 599;
|
||||
const res = new Response(readable, {
|
||||
status: valid ? status : 200,
|
||||
statusText: head.statusText ?? "",
|
||||
headers: head.headers ?? [],
|
||||
});
|
||||
return withMetadata(res, head.url ?? url.href, head.redirected ?? false, status);
|
||||
}
|
||||
|
||||
export default fetch;
|
||||
|
||||
/** Native clones copy internal response data, not the properties we add. */
|
||||
function withMetadata(res: Response, url: string, redirected: boolean, status: number): Response {
|
||||
// Capture the native method before installing the wrapper to avoid recursion.
|
||||
const clone = res.clone;
|
||||
const own = (name: string, value: unknown) => Object.defineProperty(res, name, { value, enumerable: true });
|
||||
own("url", url);
|
||||
own("redirected", redirected);
|
||||
if (res.status !== status) own("status", status);
|
||||
Object.defineProperty(res, "clone", {
|
||||
value(this: Response): Response {
|
||||
return withMetadata(clone.call(this), this.url, this.redirected, this.status);
|
||||
},
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
/** The error a failed request rejects with. */
|
||||
function failure(err: unknown): Error {
|
||||
if (!isCallError(err)) return err instanceof Error ? err : new TypeError(String(err));
|
||||
if (err.message.includes("plugin is not used")) {
|
||||
return new Error("@mygo-plugins/fetch: the Go side does not use the plugin: call mygo.Use(fetch.Plugin) before App.Run");
|
||||
}
|
||||
return new TypeError(`fetch failed: ${err.message}`, { cause: err });
|
||||
}
|
||||
|
||||
function toBase64(bytes: Uint8Array): string {
|
||||
const native = (bytes as { toBase64?: () => string }).toBase64;
|
||||
if (native) return native.call(bytes);
|
||||
let s = "";
|
||||
for (let i = 0; i < bytes.length; i += 0x8000) {
|
||||
s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000) as unknown as number[]);
|
||||
}
|
||||
return btoa(s);
|
||||
}
|
||||
|
||||
function fromBase64(s: string): Uint8Array {
|
||||
const native = (Uint8Array as { fromBase64?: (s: string) => Uint8Array }).fromBase64;
|
||||
if (native) return native(s);
|
||||
const bin = atob(s);
|
||||
const bytes = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||||
return bytes;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"extends": "../tsconfig.base.json",
|
||||
"compilerOptions": { "outDir": "dist", "rootDir": "src" },
|
||||
"include": ["src"],
|
||||
"exclude": ["src/**/*.test.ts"]
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
# game
|
||||
|
||||
What games need beyond what apps do, for [MyGo](https://github.com/egoist/mygo),
|
||||
opt-in: MyGo is an app framework.
|
||||
|
||||
- `game.View` runs a game's loop in a native UI element, in fixed steps
|
||||
with the player's input, `game.Camera` looks at its world, and
|
||||
`game.IntegerFit` shows a canvas of pixel art pixel-perfect at any size.
|
||||
- `gamepad` reads game controllers in one standard layout, on macOS
|
||||
(GameController.framework), Windows (XInput), Linux (evdev) and in
|
||||
browsers (the Gamepad API).
|
||||
|
||||
```go
|
||||
import "github.com/egoist/mygo/plugins/game/gamepad"
|
||||
|
||||
for _, pad := range gamepad.Pads() {
|
||||
s := pad.State()
|
||||
x, y := s.LeftStick()
|
||||
move(x, y)
|
||||
}
|
||||
```
|
||||
|
||||
See [the documentation](../../docs/plugins/game.md).
|
||||
+335
@@ -0,0 +1,335 @@
|
||||
// Package game has what games need beyond what apps do, opt-in, out of
|
||||
// MyGo's core ui: a game loop that updates a world in fixed steps with
|
||||
// the player's input and draws it every frame (View), and a camera that
|
||||
// looks at a 2D world (Camera), shown pixel-perfect at any size through
|
||||
// a ui.Canvas (IntegerFit). Its package gamepad reads controllers.
|
||||
//
|
||||
// type farm struct{ x, y float32 }
|
||||
//
|
||||
// func (f *farm) Update(in *game.Input) {
|
||||
// if in.Down(ui.KeyD) {
|
||||
// f.x += 2
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// func (f *farm) Draw(p *ui.Painter, r ui.Rect, alpha float64) {
|
||||
// game.Camera{X: f.x, Y: f.y, Zoom: 3}.Draw(p, r, func() { drawWorld(p) })
|
||||
// }
|
||||
//
|
||||
// ui.View(func(c *ui.Context) { game.View(c, f).Fill() })
|
||||
package game
|
||||
|
||||
import (
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// A Game is a game View runs: it updates the game's world in fixed
|
||||
// steps, whatever the display's rate, and draws it every frame, as
|
||||
// Ebitengine's Update and Draw.
|
||||
type Game interface {
|
||||
// Update advances the game one step, of 1/Rate seconds unless
|
||||
// the game has a Rate method, with the input since the step before.
|
||||
Update(in *Input)
|
||||
// Draw draws the game into r. alpha, from 0 to 1, is how far the
|
||||
// frame's time is into the next step: a game may draw what moves
|
||||
// that far between its last two places, for motion smoother than its
|
||||
// steps.
|
||||
Draw(p *ui.Painter, r ui.Rect, alpha float64)
|
||||
}
|
||||
|
||||
// Rate is how many steps a second a View runs a game, unless the
|
||||
// game has a method Rate() int giving its own.
|
||||
const Rate = 60
|
||||
|
||||
// maxCatchUp is the most time steps catch up on, after a pause such as a
|
||||
// window out of sight: MonoGame's MaxElapsedTime.
|
||||
const maxCatchUp = 250 * time.Millisecond
|
||||
|
||||
// Input is what a game's player did, as a step sees it: the keys and
|
||||
// pointer buttons held, and those pressed and released since the step
|
||||
// before, even if pressed and released between two steps. Keys are by
|
||||
// position, as PhysicalKey: KeyW is the key in W's place whatever the
|
||||
// layout, as games want for WASD.
|
||||
type Input struct {
|
||||
down, pressed, released map[ui.Key]bool
|
||||
|
||||
x, y float32
|
||||
inside bool
|
||||
buttons, bPressed, bReleased [3]bool
|
||||
wheelX, wheelY float32
|
||||
w, h float32
|
||||
focused bool
|
||||
}
|
||||
|
||||
func newInput() *Input {
|
||||
return &Input{down: map[ui.Key]bool{}, pressed: map[ui.Key]bool{}, released: map[ui.Key]bool{}}
|
||||
}
|
||||
|
||||
// Down reports whether k is held.
|
||||
func (in *Input) Down(k ui.Key) bool { return in.down[k] }
|
||||
|
||||
// Pressed reports whether k was pressed since the step before.
|
||||
func (in *Input) Pressed(k ui.Key) bool { return in.pressed[k] }
|
||||
|
||||
// Released reports whether k was released since the step before.
|
||||
func (in *Input) Released(k ui.Key) bool { return in.released[k] }
|
||||
|
||||
// Pointer returns where the pointer is in the view, from its top-left
|
||||
// corner, and whether it is over the view.
|
||||
func (in *Input) Pointer() (x, y float32, over bool) { return in.x, in.y, in.inside }
|
||||
|
||||
// PointerDown reports whether pointer button b (0 the primary, 1 the
|
||||
// secondary, 2 the middle) is held.
|
||||
func (in *Input) PointerDown(b int) bool { return b >= 0 && b < 3 && in.buttons[b] }
|
||||
|
||||
// PointerPressed reports whether button b was pressed since the step
|
||||
// before.
|
||||
func (in *Input) PointerPressed(b int) bool { return b >= 0 && b < 3 && in.bPressed[b] }
|
||||
|
||||
// PointerReleased reports whether button b was released since the step
|
||||
// before.
|
||||
func (in *Input) PointerReleased(b int) bool { return b >= 0 && b < 3 && in.bReleased[b] }
|
||||
|
||||
// Wheel returns how far the wheel or touchpad scrolled since the step
|
||||
// before, in DIPs, down and right positive.
|
||||
func (in *Input) Wheel() (dx, dy float32) { return in.wheelX, in.wheelY }
|
||||
|
||||
// Size returns the view's size.
|
||||
func (in *Input) Size() (w, h float32) { return in.w, in.h }
|
||||
|
||||
// Focused reports whether the view has the keyboard, which it loses with
|
||||
// its window or to another element: a game pauses without it, as the
|
||||
// player is elsewhere.
|
||||
func (in *Input) Focused() bool { return in.focused }
|
||||
|
||||
// step forgets what happened before this step.
|
||||
func (in *Input) step() {
|
||||
clear(in.pressed)
|
||||
clear(in.released)
|
||||
in.bPressed, in.bReleased = [3]bool{}, [3]bool{}
|
||||
in.wheelX, in.wheelY = 0, 0
|
||||
}
|
||||
|
||||
// releaseAll lets go of everything held, as when the window loses the
|
||||
// keyboard, whose releases never come.
|
||||
func (in *Input) releaseAll() {
|
||||
for k := range in.down {
|
||||
in.released[k] = true
|
||||
}
|
||||
clear(in.down)
|
||||
for b, held := range in.buttons {
|
||||
if held {
|
||||
in.bReleased[b] = true
|
||||
}
|
||||
}
|
||||
in.buttons = [3]bool{}
|
||||
}
|
||||
|
||||
// loop is what a View keeps from frame to frame.
|
||||
type loop struct {
|
||||
game Game
|
||||
in *Input
|
||||
last time.Time
|
||||
lag time.Duration
|
||||
wantFocus bool
|
||||
}
|
||||
|
||||
func (l *loop) rate() int {
|
||||
if r, ok := l.game.(interface{ Rate() int }); ok && r.Rate() > 0 {
|
||||
return r.Rate()
|
||||
}
|
||||
return Rate
|
||||
}
|
||||
|
||||
func (l *loop) input(ev ui.InputEvent) bool {
|
||||
in := l.in
|
||||
switch ev.Kind {
|
||||
case ui.InputKeyDown, ui.InputKeyUp:
|
||||
if ev.Mods&(ui.Super|ui.Ctrl|ui.Alt) != 0 && ev.Kind == ui.InputKeyDown {
|
||||
return false // the menus' shortcuts
|
||||
}
|
||||
k := ev.PhysicalKey
|
||||
if k == ui.KeyUnknown {
|
||||
k = ev.Key
|
||||
}
|
||||
if k == ui.KeyUnknown {
|
||||
return false // a modifier on its own, or a key of no name
|
||||
}
|
||||
if ev.Kind == ui.InputKeyDown {
|
||||
if !ev.Repeat && !in.down[k] {
|
||||
in.pressed[k] = true
|
||||
}
|
||||
in.down[k] = true
|
||||
} else if in.down[k] {
|
||||
in.released[k] = true
|
||||
delete(in.down, k)
|
||||
}
|
||||
return true
|
||||
case ui.InputPointerDown, ui.InputPointerUp:
|
||||
in.x, in.y = ev.X, ev.Y
|
||||
if ev.Button >= 0 && ev.Button < 3 {
|
||||
down := ev.Kind == ui.InputPointerDown
|
||||
if down && !in.buttons[ev.Button] {
|
||||
in.bPressed[ev.Button] = true
|
||||
} else if !down && in.buttons[ev.Button] {
|
||||
in.bReleased[ev.Button] = true
|
||||
}
|
||||
in.buttons[ev.Button] = down
|
||||
}
|
||||
if ev.Kind == ui.InputPointerDown {
|
||||
l.wantFocus = true
|
||||
}
|
||||
return true
|
||||
case ui.InputPointerMove:
|
||||
in.x, in.y = ev.X, ev.Y
|
||||
in.inside = ev.X >= 0 && ev.Y >= 0 && ev.X < in.w && ev.Y < in.h
|
||||
return true
|
||||
case ui.InputScroll:
|
||||
in.wheelX += ev.DX
|
||||
in.wheelY += ev.DY
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (l *loop) draw(p *ui.Painter, r ui.Rect) {
|
||||
p.AnimationFrame()
|
||||
l.in.w, l.in.h = r.W, r.H
|
||||
step := time.Second / time.Duration(l.rate())
|
||||
now := frameTime(p)
|
||||
if !l.last.IsZero() {
|
||||
// Painting twice a frame, at its one time, runs no step twice.
|
||||
l.lag += min(max(now.Sub(l.last), 0), maxCatchUp)
|
||||
}
|
||||
l.last = now
|
||||
for l.lag >= step {
|
||||
l.game.Update(l.in)
|
||||
l.in.step()
|
||||
l.lag -= step
|
||||
}
|
||||
l.game.Draw(p, r, float64(l.lag)/float64(step))
|
||||
}
|
||||
|
||||
type loopKey struct{}
|
||||
|
||||
// frameTime returns the time of the frame p paints; tests replace it.
|
||||
var frameTime = func(p *ui.Painter) time.Time { return p.Now() }
|
||||
|
||||
// View creates an element that runs g: Update in fixed steps of the game's
|
||||
// rate, with the keys, pointer and wheel the element takes as Input, and
|
||||
// Draw every frame, as long as it shows. It takes the keyboard focus as it
|
||||
// appears and when clicked, and lets go of what was held when the window
|
||||
// loses the keyboard. Size it as any element, as with Fill:
|
||||
//
|
||||
// game.View(c, g).Fill()
|
||||
func View(c *ui.Context, g Game) ui.Element {
|
||||
e := ui.Box(c).Focusable().AutoFocus()
|
||||
l := *ui.Local(e, loopKey{}, func() *loop { return &loop{in: newInput()} })
|
||||
l.game = g
|
||||
if l.wantFocus {
|
||||
l.wantFocus = false
|
||||
e.Focus()
|
||||
}
|
||||
l.in.focused = e.Focused()
|
||||
if !l.in.focused {
|
||||
l.in.releaseAll()
|
||||
}
|
||||
return e.HandleInput(l.input).Draw(l.draw)
|
||||
}
|
||||
|
||||
// IntegerFit returns where a canvas of w×h pixels shows in r as large as
|
||||
// it can with a whole number of the screen's pixels for each of its own,
|
||||
// at least one, centered (letterboxed): pixel-perfect scaling, for p's
|
||||
// screen, as Godot's viewport stretch and Stardew Valley draw pixel art.
|
||||
// k is that number. A game draws its world into a ui.Canvas of a logical
|
||||
// size, as 480×270, and shows it there:
|
||||
//
|
||||
// dst, _ := game.IntegerFit(p, 480, 270, r)
|
||||
// p.Image(world.Bitmap(), dst, ui.FillBox)
|
||||
//
|
||||
// The pointer at x, y of the view is at ((x+r.X-dst.X)*480/dst.W,
|
||||
// (y+r.Y-dst.Y)*270/dst.H) of the canvas.
|
||||
func IntegerFit(p *ui.Painter, w, h int, r ui.Rect) (dst ui.Rect, k int) {
|
||||
if w <= 0 || h <= 0 {
|
||||
return ui.Rect{}, 0
|
||||
}
|
||||
s := p.Scale()
|
||||
k = max(int(min(r.W*s/float32(w), r.H*s/float32(h))), 1)
|
||||
dw, dh := float32(w*k)/s, float32(h*k)/s
|
||||
// On whole pixels of the screen, as the snapped image is.
|
||||
x := float32(int((r.X+(r.W-dw)/2)*s+0.5)) / s
|
||||
y := float32(int((r.Y+(r.H-dh)/2)*s+0.5)) / s
|
||||
return ui.Rect{X: x, Y: y, W: dw, H: dh}, k
|
||||
}
|
||||
|
||||
// A Camera looks at a 2D world: the world's point X, Y shows at the middle
|
||||
// of the view, Zoom times as large (0 is 1), turned Rotation degrees, as
|
||||
// raylib's Camera2D. World units are DIPs at a zoom of 1.
|
||||
type Camera struct {
|
||||
X, Y float32
|
||||
Zoom float32
|
||||
Rotation float32
|
||||
}
|
||||
|
||||
func (cam Camera) zoom() float32 {
|
||||
if cam.Zoom == 0 {
|
||||
return 1
|
||||
}
|
||||
return cam.Zoom
|
||||
}
|
||||
|
||||
// Transform returns the transform from the world to the window, for the
|
||||
// view r, with the origin (0, 0): Painter.Transform(cam.Transform(r), 0, 0,
|
||||
// draw). Draw is that, snapped and clipped.
|
||||
func (cam Camera) Transform(r ui.Rect) ui.Transform {
|
||||
z := cam.zoom()
|
||||
t := ui.Translation(-cam.X, -cam.Y)
|
||||
if cam.Rotation != 0 {
|
||||
t = t.Then(ui.Rotation(-cam.Rotation))
|
||||
}
|
||||
return t.Then(ui.Scaling(z, z)).Then(ui.Translation(r.X+r.W/2, r.Y+r.H/2))
|
||||
}
|
||||
|
||||
// Draw draws what fn draws in world coordinates through the camera into r,
|
||||
// clipped to it. Unturned, the world moves by whole pixels of the screen,
|
||||
// so that the edges of tiles drawn at whole world units stay on them,
|
||||
// while parts of bitmaps, which ui.Painter.ImageRegion places where they
|
||||
// are under a transform, glide.
|
||||
func (cam Camera) Draw(p *ui.Painter, r ui.Rect, fn func()) {
|
||||
t := cam.Transform(r)
|
||||
if cam.Rotation == 0 {
|
||||
z := cam.zoom()
|
||||
s := p.Scale()
|
||||
snap := func(v float32) float32 { return float32(math.Round(float64(v*s))) / s }
|
||||
t = ui.Scaling(z, z).Then(ui.Translation(snap(r.X+r.W/2-cam.X*z), snap(r.Y+r.H/2-cam.Y*z)))
|
||||
}
|
||||
p.Clip(r, 0, func() { p.Transform(t, 0, 0, fn) })
|
||||
}
|
||||
|
||||
// ToWorld returns the world's point at x, y of the view r, from its
|
||||
// top-left corner, as Input.Pointer gives it.
|
||||
func (cam Camera) ToWorld(r ui.Rect, x, y float32) (wx, wy float32) {
|
||||
z := cam.zoom()
|
||||
dx, dy := (x-r.W/2)/z, (y-r.H/2)/z
|
||||
if cam.Rotation != 0 {
|
||||
a := float64(cam.Rotation) * math.Pi / 180
|
||||
sin, cos := float32(math.Sin(a)), float32(math.Cos(a))
|
||||
dx, dy = dx*cos-dy*sin, dx*sin+dy*cos
|
||||
}
|
||||
return cam.X + dx, cam.Y + dy
|
||||
}
|
||||
|
||||
// Visible returns the part of the world the camera shows in the view r:
|
||||
// the bounds of it when turned. A game draws only the tiles in it.
|
||||
func (cam Camera) Visible(r ui.Rect) ui.Rect {
|
||||
xs, ys := [4]float32{}, [4]float32{}
|
||||
for i, c := range [4][2]float32{{0, 0}, {r.W, 0}, {0, r.H}, {r.W, r.H}} {
|
||||
xs[i], ys[i] = cam.ToWorld(r, c[0], c[1])
|
||||
}
|
||||
x0, x1 := min(xs[0], xs[1], xs[2], xs[3]), max(xs[0], xs[1], xs[2], xs[3])
|
||||
y0, y1 := min(ys[0], ys[1], ys[2], ys[3]), max(ys[0], ys[1], ys[2], ys[3])
|
||||
return ui.Rect{X: x0, Y: y0, W: x1 - x0, H: y1 - y0}
|
||||
}
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"image/color"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// stepper records the steps a View runs.
|
||||
type stepper struct {
|
||||
steps int
|
||||
wDown, wPressed []bool
|
||||
spacePressed int
|
||||
wReleased int
|
||||
clicks int
|
||||
focused bool
|
||||
alpha float64
|
||||
draws int
|
||||
}
|
||||
|
||||
func (s *stepper) Update(in *Input) {
|
||||
s.steps++
|
||||
s.wDown = append(s.wDown, in.Down(ui.KeyW))
|
||||
s.wPressed = append(s.wPressed, in.Pressed(ui.KeyW))
|
||||
if in.Pressed(ui.KeySpace) {
|
||||
s.spacePressed++
|
||||
}
|
||||
if in.Released(ui.KeyW) {
|
||||
s.wReleased++
|
||||
}
|
||||
if in.PointerPressed(0) {
|
||||
s.clicks++
|
||||
}
|
||||
s.focused = in.Focused()
|
||||
}
|
||||
|
||||
func (s *stepper) Draw(p *ui.Painter, r ui.Rect, alpha float64) {
|
||||
s.alpha, s.draws = alpha, s.draws+1
|
||||
}
|
||||
|
||||
// gameTester tests a game in a view whose frames are at the test's
|
||||
// clock, now.
|
||||
func gameTester(t *testing.T, g Game, now *time.Time) *ui.Tester {
|
||||
before := frameTime
|
||||
frameTime = func(*ui.Painter) time.Time { return *now }
|
||||
t.Cleanup(func() { frameTime = before })
|
||||
tt := ui.NewTester(func(c *ui.Context) { View(c, g).Size(200, 100) }, 200, 100)
|
||||
tt.Frame()
|
||||
return tt
|
||||
}
|
||||
|
||||
func TestView(t *testing.T) {
|
||||
g := &stepper{}
|
||||
now := time.Unix(1000, 0)
|
||||
tt := gameTester(t, g, &now)
|
||||
if g.steps != 0 || g.draws == 0 {
|
||||
t.Fatalf("first frame: %d steps, %d draws", g.steps, g.draws)
|
||||
}
|
||||
// 100 ms are 6 steps, and a third of the next.
|
||||
now = now.Add(105 * time.Millisecond)
|
||||
tt.Frame()
|
||||
if g.steps != 6 || !g.focused {
|
||||
t.Errorf("%d steps in 105 ms, focused %v", g.steps, g.focused)
|
||||
}
|
||||
if math.Abs(g.alpha-0.3) > 0.01 {
|
||||
t.Errorf("alpha %v", g.alpha)
|
||||
}
|
||||
// Painting again at the same time runs no step.
|
||||
tt.Frame()
|
||||
if g.steps != 6 {
|
||||
t.Errorf("%d steps after painting twice", g.steps)
|
||||
}
|
||||
// W held: down in every step, pressed in the first only.
|
||||
g.wDown, g.wPressed = nil, nil
|
||||
tt.KeyDown(ui.KeyW)
|
||||
now = now.Add(50 * time.Millisecond)
|
||||
tt.Frame()
|
||||
if len(g.wDown) != 3 || !g.wDown[0] || !g.wDown[2] || !g.wPressed[0] || g.wPressed[1] {
|
||||
t.Errorf("W held: down %v, pressed %v", g.wDown, g.wPressed)
|
||||
}
|
||||
// Space tapped between two steps: pressed in the next.
|
||||
tt.Key(0, ui.KeySpace)
|
||||
now = now.Add(20 * time.Millisecond)
|
||||
tt.Frame()
|
||||
if g.spacePressed != 1 {
|
||||
t.Errorf("Space pressed in %d steps", g.spacePressed)
|
||||
}
|
||||
// The window losing the keyboard lets go of W.
|
||||
tt.SetFocused(false)
|
||||
now = now.Add(20 * time.Millisecond)
|
||||
tt.Frame()
|
||||
if g.focused {
|
||||
t.Error("focused without the keyboard")
|
||||
}
|
||||
if g.wReleased != 1 || g.wDown[len(g.wDown)-1] {
|
||||
t.Errorf("W after losing the keyboard: released %d, down %v", g.wReleased, g.wDown[len(g.wDown)-1])
|
||||
}
|
||||
tt.SetFocused(true)
|
||||
// A click.
|
||||
tt.ClickAt(10, 10)
|
||||
now = now.Add(20 * time.Millisecond)
|
||||
tt.Frame()
|
||||
if g.clicks != 1 {
|
||||
t.Errorf("%d clicks", g.clicks)
|
||||
}
|
||||
// After a long pause, a quarter of a second of steps, not all.
|
||||
before := g.steps
|
||||
now = now.Add(10 * time.Second)
|
||||
tt.Frame()
|
||||
if n := g.steps - before; n != 15 {
|
||||
t.Errorf("%d steps after 10 s", n)
|
||||
}
|
||||
}
|
||||
|
||||
// fastGame runs at its own rate.
|
||||
type fastGame struct{ stepper }
|
||||
|
||||
func (fastGame) Rate() int { return 120 }
|
||||
|
||||
func TestRate(t *testing.T) {
|
||||
g := &fastGame{}
|
||||
now := time.Unix(1000, 0)
|
||||
tt := gameTester(t, g, &now)
|
||||
now = now.Add(100 * time.Millisecond)
|
||||
tt.Frame()
|
||||
if g.steps != 12 {
|
||||
t.Errorf("%d steps in 100 ms at 120 a second", g.steps)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnyFrameRate checks that the steps keep the game's rate, and alpha
|
||||
// its place between them, whatever the frames' rate: under the steps', at
|
||||
// a display's, and far over it, as frames uncapped (MYGO_UNCAPPED) come.
|
||||
// A second of frames runs 60 steps, and alpha, from 0 to 1, grows from
|
||||
// frame to frame between two steps.
|
||||
func TestAnyFrameRate(t *testing.T) {
|
||||
for _, every := range []time.Duration{20 * time.Millisecond, 6250 * time.Microsecond, time.Millisecond, 100 * time.Microsecond} {
|
||||
g := &stepper{}
|
||||
now := time.Unix(1000, 0)
|
||||
tt := gameTester(t, g, &now)
|
||||
steps, alpha := g.steps, g.alpha
|
||||
for range time.Second / every {
|
||||
now = now.Add(every)
|
||||
tt.Frame()
|
||||
if g.alpha < 0 || g.alpha >= 1 {
|
||||
t.Fatalf("frames every %v: alpha %v", every, g.alpha)
|
||||
}
|
||||
if g.steps == steps && g.alpha <= alpha {
|
||||
t.Fatalf("frames every %v: alpha went from %v to %v within a step", every, alpha, g.alpha)
|
||||
}
|
||||
steps, alpha = g.steps, g.alpha
|
||||
}
|
||||
if g.steps != Rate {
|
||||
t.Errorf("frames every %v: %d steps in a second, want %d", every, g.steps, Rate)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var red = ui.RGB(255, 0, 0)
|
||||
|
||||
// paint renders what draw paints into a 400×300 view.
|
||||
func paint(scale float32, draw func(p *ui.Painter, r ui.Rect)) *ui.Tester {
|
||||
tt := ui.NewTester(func(c *ui.Context) { ui.Box(c).Size(400, 300).Draw(draw) }, 400, 300)
|
||||
tt.SetScale(scale)
|
||||
tt.Frame()
|
||||
return tt
|
||||
}
|
||||
|
||||
func isRed(c color.RGBA) bool { return c.R > 250 && c.G < 5 && c.B < 5 }
|
||||
|
||||
func TestCamera(t *testing.T) {
|
||||
r := ui.Rect{X: 50, Y: 20, W: 400, H: 300}
|
||||
cam := Camera{X: 100, Y: 80, Zoom: 2}
|
||||
// The camera's point shows at the middle.
|
||||
if x, y := cam.ToWorld(r, 200, 150); x != 100 || y != 80 {
|
||||
t.Errorf("middle = %v, %v", x, y)
|
||||
}
|
||||
if x, y := cam.ToWorld(r, 0, 0); x != 0 || y != 5 {
|
||||
t.Errorf("corner = %v, %v", x, y)
|
||||
}
|
||||
if v := cam.Visible(r); v != (ui.Rect{X: 0, Y: 5, W: 200, H: 150}) {
|
||||
t.Errorf("visible = %v", v)
|
||||
}
|
||||
// Transform maps the world back to where ToWorld found it: the world's
|
||||
// point at the view's top-left corner paints there.
|
||||
img := paint(1, func(p *ui.Painter, r ui.Rect) {
|
||||
wx, wy := cam.ToWorld(r, 0, 0)
|
||||
p.Transform(cam.Transform(r), 0, 0, func() {
|
||||
p.Fill(ui.Rect{X: wx, Y: wy, W: 2, H: 2}, red, 0)
|
||||
})
|
||||
}).Image()
|
||||
if !isRed(img.RGBAAt(1, 1)) || isRed(img.RGBAAt(6, 6)) {
|
||||
t.Errorf("world corner: %v at 1, 1, %v at 6, 6", img.RGBAAt(1, 1), img.RGBAAt(6, 6))
|
||||
}
|
||||
turned := Camera{Rotation: 90}
|
||||
img = paint(1, func(p *ui.Painter, r ui.Rect) {
|
||||
wx, wy := turned.ToWorld(r, 300, 150)
|
||||
p.Transform(turned.Transform(r), 0, 0, func() {
|
||||
p.Fill(ui.Rect{X: wx - 2, Y: wy - 2, W: 4, H: 4}, red, 0)
|
||||
})
|
||||
}).Image()
|
||||
if !isRed(img.RGBAAt(300, 150)) || isRed(img.RGBAAt(310, 150)) {
|
||||
t.Errorf("turned: %v at 300, 150, %v at 310, 150", img.RGBAAt(300, 150), img.RGBAAt(310, 150))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegerFit(t *testing.T) {
|
||||
var dst, small ui.Rect
|
||||
var k, smallK int
|
||||
paint(2, func(p *ui.Painter, r ui.Rect) {
|
||||
// 1000×600 DIPs at 2×: 2000×1200 pixels, for 480×270: 4 times (1920×1080).
|
||||
dst, k = IntegerFit(p, 480, 270, ui.Rect{X: 10, Y: 20, W: 1000, H: 600})
|
||||
// Smaller than the canvas: one pixel each, overflowing.
|
||||
small, smallK = IntegerFit(p, 480, 270, ui.Rect{W: 100, H: 100})
|
||||
})
|
||||
if k != 4 || dst != (ui.Rect{X: 30, Y: 50, W: 960, H: 540}) {
|
||||
t.Errorf("fit %v, k %d", dst, k)
|
||||
}
|
||||
if smallK != 1 || small.W != 240 {
|
||||
t.Errorf("fit %v, k %d in a small view", small, smallK)
|
||||
}
|
||||
}
|
||||
|
||||
// Through an unturned camera, the world moves by whole pixels: a tile at
|
||||
// whole world units has no edge pixel partly covered.
|
||||
func TestCameraSnaps(t *testing.T) {
|
||||
img := paint(2, func(p *ui.Painter, r ui.Rect) {
|
||||
Camera{X: 10.3, Y: 7.77, Zoom: 3}.Draw(p, r, func() {
|
||||
p.Fill(ui.Rect{X: 0, Y: 0, W: 16, H: 16}, red, 0)
|
||||
})
|
||||
}).Image()
|
||||
bg := img.RGBAAt(799, 599)
|
||||
reds := 0
|
||||
for y := range img.Bounds().Dy() {
|
||||
for x := range img.Bounds().Dx() {
|
||||
c := img.RGBAAt(x, y)
|
||||
if isRed(c) {
|
||||
reds++
|
||||
} else if c != bg {
|
||||
t.Fatalf("pixel %d, %d partly covered: %v", x, y, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
if reds != 96*96 {
|
||||
t.Errorf("%d red pixels", reds)
|
||||
}
|
||||
}
|
||||
|
||||
// A modifier on its own is no key of a game's, and is left to the window, as
|
||||
// Alt to the menu bar.
|
||||
func TestModifierKeyAlone(t *testing.T) {
|
||||
l := &loop{in: newInput()}
|
||||
for _, ev := range []ui.InputEvent{
|
||||
{Kind: ui.InputKeyDown, Code: ui.CodeShiftLeft, Mods: ui.Shift},
|
||||
{Kind: ui.InputKeyUp, Code: ui.CodeShiftLeft},
|
||||
{Kind: ui.InputKeyUp, Code: ui.CodeAltLeft},
|
||||
} {
|
||||
if l.input(ev) {
|
||||
t.Errorf("took %+v", ev)
|
||||
}
|
||||
}
|
||||
if l.in.Down(ui.KeyUnknown) || l.in.Pressed(ui.KeyUnknown) || l.in.Released(ui.KeyUnknown) {
|
||||
t.Error("a key of no name is held")
|
||||
}
|
||||
}
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
// Package gamepad reads game controllers: their buttons, triggers and
|
||||
// sticks in the standard layout of an Xbox controller, which the W3C's
|
||||
// Gamepad API and SDL's game controller database name, whatever pad it is:
|
||||
//
|
||||
// for _, pad := range gamepad.Pads() {
|
||||
// s := pad.State()
|
||||
// x, y := s.LeftStick()
|
||||
// if s.Pressed(gamepad.South) {
|
||||
// jump()
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// A game reads the pads' states once a frame, or once a step of its world,
|
||||
// and keeps the last to tell a button just pressed from one held
|
||||
// (State.JustPressed).
|
||||
//
|
||||
// The pads come from GameController.framework on macOS (Xbox, PlayStation,
|
||||
// Switch Pro and MFi controllers), XInput on Windows (Xbox controllers and
|
||||
// those that act as one, as Steam Input makes of others), evdev on Linux
|
||||
// (/dev/input, readable by the user at the seat), and the Gamepad API in
|
||||
// browsers. On macOS, input reaches the app in front only, as games
|
||||
// expect. Every function and method is safe to call from any goroutine.
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"math"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Button is a button of the standard layout, named by place: South is A
|
||||
// on an Xbox controller, Cross on a PlayStation one, B on a Nintendo one.
|
||||
type Button uint8
|
||||
|
||||
// The buttons, in the order of the W3C's standard gamepad.
|
||||
const (
|
||||
South Button = iota
|
||||
East
|
||||
West
|
||||
North
|
||||
LeftShoulder
|
||||
RightShoulder
|
||||
LeftTrigger // analog: Value is from 0 to 1
|
||||
RightTrigger
|
||||
Back // View, Select, Share, Minus
|
||||
Start
|
||||
LeftStickButton
|
||||
RightStickButton
|
||||
Up
|
||||
Down
|
||||
Left
|
||||
Right
|
||||
Guide // the Xbox, PlayStation or Home button, where the system leaves it
|
||||
ButtonCount
|
||||
)
|
||||
|
||||
// Axis is an axis of the sticks, from -1 to 1: right and down are
|
||||
// positive, as on the screen.
|
||||
type Axis uint8
|
||||
|
||||
// The axes.
|
||||
const (
|
||||
LeftX Axis = iota
|
||||
LeftY
|
||||
RightX
|
||||
RightY
|
||||
AxisCount
|
||||
)
|
||||
|
||||
// State is what a pad's controls read at one time.
|
||||
type State struct {
|
||||
// Buttons are from 0 to 1: 0 or 1 but for the triggers.
|
||||
Buttons [ButtonCount]float32
|
||||
// Axes are from -1 to 1, as the pad reports them, without a dead
|
||||
// zone.
|
||||
Axes [AxisCount]float32
|
||||
}
|
||||
|
||||
// Deadzone is how far from the middle a stick must move to count, as a
|
||||
// fraction of its reach: sticks rest a little off their middle.
|
||||
const Deadzone = 0.15
|
||||
|
||||
// pressThreshold is how far an analog trigger must go to be pressed.
|
||||
const pressThreshold = 0.25
|
||||
|
||||
// Value returns how far b is pressed, from 0 to 1.
|
||||
func (s State) Value(b Button) float32 {
|
||||
if b >= ButtonCount {
|
||||
return 0
|
||||
}
|
||||
return s.Buttons[b]
|
||||
}
|
||||
|
||||
// Pressed reports whether b is pressed: a trigger a quarter of the way.
|
||||
func (s State) Pressed(b Button) bool { return s.Value(b) >= pressThreshold }
|
||||
|
||||
// JustPressed reports whether b is pressed in s and was not in last, the
|
||||
// state read before.
|
||||
func (s State) JustPressed(last State, b Button) bool { return s.Pressed(b) && !last.Pressed(b) }
|
||||
|
||||
// JustReleased reports whether b was pressed in last and is not in s.
|
||||
func (s State) JustReleased(last State, b Button) bool { return !s.Pressed(b) && last.Pressed(b) }
|
||||
|
||||
// Axis returns the raw value of a, from -1 to 1.
|
||||
func (s State) Axis(a Axis) float32 {
|
||||
if a >= AxisCount {
|
||||
return 0
|
||||
}
|
||||
return s.Axes[a]
|
||||
}
|
||||
|
||||
// LeftStick returns where the left stick is, each coordinate from -1 to 1,
|
||||
// right and down positive, with a radial dead zone: 0 near the middle,
|
||||
// then from 0 at Deadzone to 1 at the rim, the same in every direction.
|
||||
func (s State) LeftStick() (x, y float32) { return stick(s.Axes[LeftX], s.Axes[LeftY]) }
|
||||
|
||||
// RightStick returns where the right stick is, as LeftStick.
|
||||
func (s State) RightStick() (x, y float32) { return stick(s.Axes[RightX], s.Axes[RightY]) }
|
||||
|
||||
func stick(x, y float32) (float32, float32) {
|
||||
m := float32(math.Hypot(float64(x), float64(y)))
|
||||
if m < Deadzone {
|
||||
return 0, 0
|
||||
}
|
||||
k := min((m-Deadzone)/(1-Deadzone), 1) / m
|
||||
return x * k, y * k
|
||||
}
|
||||
|
||||
// A Pad is a game controller, from when it connects until it disconnects;
|
||||
// connected again, it is a Pad anew.
|
||||
type Pad struct {
|
||||
dev device
|
||||
name string
|
||||
connected bool
|
||||
}
|
||||
|
||||
// Name returns the pad's name, as its maker gives it.
|
||||
func (p *Pad) Name() string { return p.name }
|
||||
|
||||
// Connected reports whether the pad is still connected.
|
||||
func (p *Pad) Connected() bool {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return p.connected
|
||||
}
|
||||
|
||||
// State reads the pad's controls now; a pad no longer connected reads
|
||||
// nothing pressed.
|
||||
func (p *Pad) State() State {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if !p.connected {
|
||||
return State{}
|
||||
}
|
||||
var s State
|
||||
if !p.dev.read(&s) {
|
||||
p.disconnect()
|
||||
return State{}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (p *Pad) disconnect() {
|
||||
p.connected = false
|
||||
p.dev.close()
|
||||
for i, q := range pads {
|
||||
if q == p {
|
||||
pads = append(pads[:i], pads[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A device is a pad as a platform knows it.
|
||||
type device interface {
|
||||
// key identifies the device while it is connected.
|
||||
key() string
|
||||
name() string
|
||||
// read reads the device's controls, and reports false once it is
|
||||
// gone.
|
||||
read(s *State) bool
|
||||
close()
|
||||
}
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
pads []*Pad
|
||||
scanned time.Time
|
||||
scanEach = time.Second // how often to look for pads anew
|
||||
)
|
||||
|
||||
// Pads returns the pads connected, in the order they connected. It looks
|
||||
// for pads connected since at most once a second.
|
||||
func Pads() []*Pad {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if now := time.Now(); scanned.IsZero() || now.Sub(scanned) >= scanEach {
|
||||
scanned = now
|
||||
known := map[string]device{}
|
||||
for _, p := range pads {
|
||||
known[p.dev.key()] = p.dev
|
||||
}
|
||||
update(scanDevices(known))
|
||||
}
|
||||
return append([]*Pad(nil), pads...)
|
||||
}
|
||||
|
||||
// scanDevices finds the devices connected, the known ones among them as
|
||||
// they are; tests replace it.
|
||||
var scanDevices = scan
|
||||
|
||||
// update takes the devices a scan found: the pads of devices gone
|
||||
// disconnect, and new devices connect as pads.
|
||||
func update(found []device) {
|
||||
present := map[string]bool{}
|
||||
for _, d := range found {
|
||||
present[d.key()] = true
|
||||
}
|
||||
for _, p := range append([]*Pad(nil), pads...) {
|
||||
if !present[p.dev.key()] {
|
||||
p.disconnect()
|
||||
}
|
||||
}
|
||||
have := map[string]bool{}
|
||||
for _, p := range pads {
|
||||
have[p.dev.key()] = true
|
||||
}
|
||||
for _, d := range found {
|
||||
if !have[d.key()] {
|
||||
have[d.key()] = true
|
||||
pads = append(pads, &Pad{dev: d, name: d.name(), connected: true})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
//go:build !ios
|
||||
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"strconv"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
"github.com/ebitengine/purego/objc"
|
||||
)
|
||||
|
||||
// macOS reads pads through GameController.framework: GCController's
|
||||
// controllers with an extended gamepad profile, which Xbox, PlayStation,
|
||||
// Switch Pro and MFi controllers have. The framework finds controllers
|
||||
// on the main run loop, which a running MyGo app turns.
|
||||
|
||||
var (
|
||||
gcOnce sync.Once
|
||||
gcOK bool
|
||||
|
||||
poolPush, poolPop uintptr
|
||||
sendFloat func(id objc.ID, sel objc.SEL) float32
|
||||
|
||||
selControllers, selCount, selObjectAt, selExtended, selVendor, selUTF8,
|
||||
selValue, selXAxis, selYAxis, selRetain, selRelease, selResponds objc.SEL
|
||||
buttonSels [ButtonCount]objc.SEL
|
||||
selDpad, selLeftStick, selRightStick, selUp, selDown, selLeft, selRight objc.SEL
|
||||
)
|
||||
|
||||
func loadGC() bool {
|
||||
gcOnce.Do(func() {
|
||||
if _, err := purego.Dlopen("/System/Library/Frameworks/GameController.framework/GameController", purego.RTLD_LAZY|purego.RTLD_GLOBAL); err != nil {
|
||||
return
|
||||
}
|
||||
libobjc, err := purego.Dlopen("/usr/lib/libobjc.A.dylib", purego.RTLD_LAZY|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if poolPush, err = purego.Dlsym(libobjc, "objc_autoreleasePoolPush"); err != nil {
|
||||
return
|
||||
}
|
||||
if poolPop, err = purego.Dlsym(libobjc, "objc_autoreleasePoolPop"); err != nil {
|
||||
return
|
||||
}
|
||||
msgSend, err := purego.Dlsym(libobjc, "objc_msgSend")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
purego.RegisterFunc(&sendFloat, msgSend)
|
||||
sel := objc.RegisterName
|
||||
selControllers, selCount, selObjectAt = sel("controllers"), sel("count"), sel("objectAtIndex:")
|
||||
selExtended, selVendor, selUTF8 = sel("extendedGamepad"), sel("vendorName"), sel("UTF8String")
|
||||
selValue, selXAxis, selYAxis = sel("value"), sel("xAxis"), sel("yAxis")
|
||||
selRetain, selRelease, selResponds = sel("retain"), sel("release"), sel("respondsToSelector:")
|
||||
selDpad, selLeftStick, selRightStick = sel("dpad"), sel("leftThumbstick"), sel("rightThumbstick")
|
||||
selUp, selDown, selLeft, selRight = sel("up"), sel("down"), sel("left"), sel("right")
|
||||
for b, name := range map[Button]string{
|
||||
South: "buttonA", East: "buttonB", West: "buttonX", North: "buttonY",
|
||||
LeftShoulder: "leftShoulder", RightShoulder: "rightShoulder",
|
||||
LeftTrigger: "leftTrigger", RightTrigger: "rightTrigger",
|
||||
Back: "buttonOptions", Start: "buttonMenu", Guide: "buttonHome",
|
||||
LeftStickButton: "leftThumbstickButton", RightStickButton: "rightThumbstickButton",
|
||||
} {
|
||||
buttonSels[b] = sel(name)
|
||||
}
|
||||
gcOK = objc.GetClass("GCController") != 0
|
||||
})
|
||||
return gcOK
|
||||
}
|
||||
|
||||
// withPool runs fn in an autorelease pool, for the objects the framework
|
||||
// returns autoreleased. A pool belongs to its thread: the goroutine stays
|
||||
// on one until the pool is popped.
|
||||
func withPool(fn func()) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
p, _, _ := purego.SyscallN(poolPush)
|
||||
defer purego.SyscallN(poolPop, p)
|
||||
fn()
|
||||
}
|
||||
|
||||
type gcPad struct {
|
||||
ctl objc.ID // retained
|
||||
title string
|
||||
}
|
||||
|
||||
func controllers() []objc.ID {
|
||||
list := objc.ID(objc.GetClass("GCController")).Send(selControllers)
|
||||
if list == 0 {
|
||||
return nil
|
||||
}
|
||||
n := int(objc.Send[uint](list, selCount))
|
||||
ids := make([]objc.ID, n)
|
||||
for i := range n {
|
||||
ids[i] = list.Send(selObjectAt, uint(i))
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func scan(known map[string]device) []device {
|
||||
if !loadGC() {
|
||||
return nil
|
||||
}
|
||||
var found []device
|
||||
withPool(func() {
|
||||
for _, c := range controllers() {
|
||||
if c.Send(selExtended) == 0 {
|
||||
continue // a remote or a micro gamepad
|
||||
}
|
||||
k := strconv.FormatUint(uint64(c), 16)
|
||||
if d, ok := known[k]; ok {
|
||||
found = append(found, d)
|
||||
continue
|
||||
}
|
||||
d := &gcPad{ctl: c.Send(selRetain)}
|
||||
if v := c.Send(selVendor); v != 0 {
|
||||
d.title = goString(objc.Send[uintptr](v, selUTF8))
|
||||
}
|
||||
found = append(found, d)
|
||||
}
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
func goString(p uintptr) string {
|
||||
if p == 0 {
|
||||
return ""
|
||||
}
|
||||
b := unsafe.Slice((*byte)(*(*unsafe.Pointer)(unsafe.Pointer(&p))), 256)
|
||||
for i, c := range b {
|
||||
if c == 0 {
|
||||
return string(b[:i])
|
||||
}
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func (d *gcPad) key() string { return strconv.FormatUint(uint64(d.ctl), 16) }
|
||||
func (d *gcPad) name() string { return d.title }
|
||||
func (d *gcPad) close() { d.ctl.Send(selRelease) }
|
||||
|
||||
// gcPresent reports whether a controller is still among the controllers;
|
||||
// tests replace it.
|
||||
var gcPresent = func(ctl objc.ID) bool {
|
||||
for _, c := range controllers() {
|
||||
if c == ctl {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func value(input objc.ID) float32 {
|
||||
if input == 0 {
|
||||
return 0
|
||||
}
|
||||
return sendFloat(input, selValue)
|
||||
}
|
||||
|
||||
func (d *gcPad) read(s *State) bool {
|
||||
ok := false
|
||||
withPool(func() {
|
||||
if ok = gcPresent(d.ctl); !ok {
|
||||
return
|
||||
}
|
||||
gp := d.ctl.Send(selExtended)
|
||||
if gp == 0 {
|
||||
ok = false
|
||||
return
|
||||
}
|
||||
for b, sel := range buttonSels {
|
||||
// Older systems have no Home or Options button.
|
||||
if sel != 0 && objc.Send[bool](gp, selResponds, sel) {
|
||||
s.Buttons[b] = value(gp.Send(sel))
|
||||
}
|
||||
}
|
||||
if pad := gp.Send(selDpad); pad != 0 {
|
||||
s.Buttons[Up] = value(pad.Send(selUp))
|
||||
s.Buttons[Down] = value(pad.Send(selDown))
|
||||
s.Buttons[Left] = value(pad.Send(selLeft))
|
||||
s.Buttons[Right] = value(pad.Send(selRight))
|
||||
}
|
||||
// GameController's y axes go up.
|
||||
if st := gp.Send(selLeftStick); st != 0 {
|
||||
s.Axes[LeftX], s.Axes[LeftY] = value(st.Send(selXAxis)), -value(st.Send(selYAxis))
|
||||
}
|
||||
if st := gp.Send(selRightStick); st != 0 {
|
||||
s.Axes[RightX], s.Axes[RightY] = value(st.Send(selXAxis)), -value(st.Send(selYAxis))
|
||||
}
|
||||
})
|
||||
return ok
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//go:build !ios
|
||||
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/ebitengine/purego/objc"
|
||||
)
|
||||
|
||||
// A controller GameController makes for tests, of the extended gamepad
|
||||
// profile, reads in this package's layout: its y axes turned to go down.
|
||||
func TestGameController(t *testing.T) {
|
||||
if !loadGC() {
|
||||
t.Skip("no GameController.framework")
|
||||
}
|
||||
saved := gcPresent
|
||||
gcPresent = func(objc.ID) bool { return true }
|
||||
defer func() { gcPresent = saved }()
|
||||
var d *gcPad
|
||||
withPool(func() {
|
||||
c := objc.ID(objc.GetClass("GCController")).Send(objc.RegisterName("controllerWithExtendedGamepad"))
|
||||
if c == 0 {
|
||||
return
|
||||
}
|
||||
d = &gcPad{ctl: c.Send(selRetain)}
|
||||
gp := c.Send(selExtended)
|
||||
setValue := objc.RegisterName("setValue:")
|
||||
gp.Send(buttonSels[South]).Send(setValue, float32(1))
|
||||
gp.Send(buttonSels[RightTrigger]).Send(setValue, float32(0.6))
|
||||
setAxes := objc.RegisterName("setValueForXAxis:yAxis:")
|
||||
gp.Send(selLeftStick).Send(setAxes, float32(0.5), float32(0.25))
|
||||
gp.Send(selDpad).Send(setAxes, float32(0), float32(1))
|
||||
})
|
||||
if d == nil {
|
||||
t.Skip("no controllerWithExtendedGamepad")
|
||||
}
|
||||
defer d.close()
|
||||
var s State
|
||||
if !d.read(&s) {
|
||||
t.Fatal("read failed")
|
||||
}
|
||||
if !s.Pressed(South) || s.Pressed(East) || !s.Pressed(Up) || s.Pressed(Down) {
|
||||
t.Errorf("buttons %v", s.Buttons)
|
||||
}
|
||||
if math.Abs(float64(s.Value(RightTrigger))-0.6) > 1e-3 {
|
||||
t.Errorf("right trigger %v", s.Value(RightTrigger))
|
||||
}
|
||||
if math.Abs(float64(s.Axes[LeftX])-0.5) > 1e-3 || math.Abs(float64(s.Axes[LeftY])+0.25) > 1e-3 {
|
||||
t.Errorf("left stick %v, %v: y should go down", s.Axes[LeftX], s.Axes[LeftY])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"syscall/js"
|
||||
)
|
||||
|
||||
// Browsers report pads through navigator.getGamepads(), each at an index
|
||||
// for as long as it is connected. Those with the "standard" mapping have
|
||||
// their buttons and axes in this package's order; others keep the order
|
||||
// the browser gives, which fits the first buttons and axes of most.
|
||||
|
||||
type jsPad struct {
|
||||
index int
|
||||
id string
|
||||
}
|
||||
|
||||
func pollPads() js.Value {
|
||||
nav := js.Global().Get("navigator")
|
||||
if !nav.Truthy() || !nav.Get("getGamepads").Truthy() {
|
||||
return js.Undefined()
|
||||
}
|
||||
return nav.Call("getGamepads")
|
||||
}
|
||||
|
||||
func scan(known map[string]device) []device {
|
||||
list := pollPads()
|
||||
if !list.Truthy() {
|
||||
return nil
|
||||
}
|
||||
var found []device
|
||||
for i := range list.Length() {
|
||||
g := list.Index(i)
|
||||
if !g.Truthy() || !g.Get("connected").Bool() {
|
||||
continue
|
||||
}
|
||||
d := &jsPad{index: i, id: g.Get("id").String()}
|
||||
if k, ok := known[d.key()]; ok {
|
||||
found = append(found, k)
|
||||
continue
|
||||
}
|
||||
found = append(found, d)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func (d *jsPad) key() string { return strconv.Itoa(d.index) + "\x00" + d.id }
|
||||
func (d *jsPad) name() string { return d.id }
|
||||
func (d *jsPad) close() {}
|
||||
|
||||
func (d *jsPad) read(s *State) bool {
|
||||
list := pollPads()
|
||||
if !list.Truthy() || d.index >= list.Length() {
|
||||
return false
|
||||
}
|
||||
g := list.Index(d.index)
|
||||
if !g.Truthy() || !g.Get("connected").Bool() || g.Get("id").String() != d.id {
|
||||
return false
|
||||
}
|
||||
buttons := g.Get("buttons")
|
||||
for i := range min(buttons.Length(), int(ButtonCount)) {
|
||||
b := buttons.Index(i)
|
||||
s.Buttons[i] = float32(b.Get("value").Float())
|
||||
if s.Buttons[i] == 0 && b.Get("pressed").Bool() {
|
||||
s.Buttons[i] = 1 // a browser that reports only pressed
|
||||
}
|
||||
}
|
||||
axes := g.Get("axes")
|
||||
for i := range min(axes.Length(), int(AxisCount)) {
|
||||
s.Axes[i] = float32(axes.Index(i).Float())
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
//go:build linux && !android && (amd64 || arm64) && !android
|
||||
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Linux reads pads from evdev, /dev/input/event*, which systemd-logind
|
||||
// lets the user at the seat read. The kernel's drivers report gamepads in
|
||||
// one layout (Documentation/input/gamepad.rst): BTN_SOUTH and the rest by
|
||||
// place, sticks on ABS_X/Y and ABS_RX/RY, triggers on ABS_Z/RZ, the
|
||||
// d-pad on a hat or buttons. Xbox controllers (xpad, and Steam's virtual
|
||||
// pad) are the exception that predates it: they report X as BTN_X, the
|
||||
// code of BTN_NORTH, and Y as BTN_Y, that of BTN_WEST.
|
||||
|
||||
// Event types and codes.
|
||||
const (
|
||||
evKey = 0x01
|
||||
evAbs = 0x03
|
||||
|
||||
btnSouth = 0x130
|
||||
btnEast = 0x131
|
||||
btnNorth = 0x133 // also BTN_X
|
||||
btnWest = 0x134 // also BTN_Y
|
||||
btnTL = 0x136
|
||||
btnTR = 0x137
|
||||
btnTL2 = 0x138
|
||||
btnTR2 = 0x139
|
||||
btnSelect = 0x13a
|
||||
btnStart = 0x13b
|
||||
btnMode = 0x13c
|
||||
btnThumbL = 0x13d
|
||||
btnThumbR = 0x13e
|
||||
btnUp = 0x220
|
||||
btnDown = 0x221
|
||||
btnLeft = 0x222
|
||||
btnRight = 0x223
|
||||
|
||||
absX = 0x00
|
||||
absY = 0x01
|
||||
absZ = 0x02
|
||||
absRX = 0x03
|
||||
absRY = 0x04
|
||||
absRZ = 0x05
|
||||
absHat0X = 0x10
|
||||
absHat0Y = 0x11
|
||||
absMax = 0x3f
|
||||
keyMax = 0x2ff
|
||||
)
|
||||
|
||||
// ioctl requests of evdev: _IOC(dir, 'E', nr, size).
|
||||
func ioc(dir, nr, size uintptr) uintptr { return dir<<30 | size<<16 | 'E'<<8 | nr }
|
||||
|
||||
const iocRead = 2
|
||||
|
||||
func eviocgname(n uintptr) uintptr { return ioc(iocRead, 0x06, n) }
|
||||
func eviocgbit(ev, n uintptr) uintptr { return ioc(iocRead, 0x20+ev, n) }
|
||||
func eviocgabs(abs uintptr) uintptr { return ioc(iocRead, 0x40+abs, unsafe.Sizeof(absInfo{})) }
|
||||
func eviocgkey(n uintptr) uintptr { return ioc(iocRead, 0x18, n) }
|
||||
func eviocgid() uintptr { return ioc(iocRead, 0x02, unsafe.Sizeof(inputID{})) }
|
||||
func ioctl(fd int, req uintptr, p unsafe.Pointer) bool {
|
||||
_, _, e := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), req, uintptr(p))
|
||||
return e == 0
|
||||
}
|
||||
|
||||
type absInfo struct{ value, minimum, maximum, fuzz, flat, resolution int32 }
|
||||
|
||||
type inputID struct{ bustype, vendor, product, version uint16 }
|
||||
|
||||
type evdevPad struct {
|
||||
path string
|
||||
fd int
|
||||
title string
|
||||
xbox bool // BTN_X and BTN_Y are X and Y, west and north
|
||||
// rightOnZ: a pad of no ABS_RX has its right stick on ABS_Z/RZ, and
|
||||
// triggers only as buttons.
|
||||
rightOnZ bool
|
||||
abs [absMax + 1]absInfo
|
||||
hasAbs [absMax + 1]bool
|
||||
keys [keyMax + 1]bool
|
||||
axes [absMax + 1]int32
|
||||
buf []byte
|
||||
}
|
||||
|
||||
func scan(known map[string]device) []device {
|
||||
paths, _ := filepath.Glob("/dev/input/event*")
|
||||
var found []device
|
||||
for _, p := range paths {
|
||||
if k, ok := known[p]; ok {
|
||||
found = append(found, k)
|
||||
continue
|
||||
}
|
||||
if d := openEvdev(p); d != nil {
|
||||
found = append(found, d)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func bit(b []byte, i int) bool { return i/8 < len(b) && b[i/8]&(1<<(i%8)) != 0 }
|
||||
|
||||
// openEvdev opens the device at path if it is a gamepad.
|
||||
func openEvdev(path string) *evdevPad {
|
||||
fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NONBLOCK|syscall.O_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
keys := make([]byte, keyMax/8+1)
|
||||
if !ioctl(fd, eviocgbit(evKey, uintptr(len(keys))), unsafe.Pointer(&keys[0])) || !bit(keys, btnSouth) {
|
||||
syscall.Close(fd)
|
||||
return nil
|
||||
}
|
||||
d := &evdevPad{path: path, fd: fd, buf: make([]byte, 24*64)}
|
||||
name := make([]byte, 256)
|
||||
if ioctl(fd, eviocgname(uintptr(len(name))), unsafe.Pointer(&name[0])) {
|
||||
d.title = strings.TrimRight(string(name), "\x00")
|
||||
}
|
||||
var id inputID
|
||||
ioctl(fd, eviocgid(), unsafe.Pointer(&id))
|
||||
d.xbox = id.vendor == 0x045e || id.vendor == 0x28de || driver(path) == "xpad"
|
||||
abs := make([]byte, absMax/8+1)
|
||||
ioctl(fd, eviocgbit(evAbs, uintptr(len(abs))), unsafe.Pointer(&abs[0]))
|
||||
for a := range absMax + 1 {
|
||||
if bit(abs, a) && ioctl(fd, eviocgabs(uintptr(a)), unsafe.Pointer(&d.abs[a])) {
|
||||
d.hasAbs[a] = true
|
||||
d.axes[a] = d.abs[a].value
|
||||
}
|
||||
}
|
||||
d.rightOnZ = !d.hasAbs[absRX] && d.hasAbs[absZ]
|
||||
state := make([]byte, keyMax/8+1)
|
||||
if ioctl(fd, eviocgkey(uintptr(len(state))), unsafe.Pointer(&state[0])) {
|
||||
for k := range keyMax + 1 {
|
||||
d.keys[k] = bit(state, k)
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// driver returns the name of the kernel driver of an evdev device.
|
||||
func driver(path string) string {
|
||||
link, err := os.Readlink("/sys/class/input/" + filepath.Base(path) + "/device/device/driver")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Base(link)
|
||||
}
|
||||
|
||||
func (d *evdevPad) key() string { return d.path }
|
||||
func (d *evdevPad) name() string { return d.title }
|
||||
func (d *evdevPad) close() { syscall.Close(d.fd) }
|
||||
|
||||
// drain reads the events waiting, and reports false once the device is
|
||||
// gone.
|
||||
func (d *evdevPad) drain() bool {
|
||||
for {
|
||||
n, err := syscall.Read(d.fd, d.buf)
|
||||
if err == syscall.EAGAIN || err == syscall.EINTR {
|
||||
return true
|
||||
}
|
||||
if err != nil || n == 0 {
|
||||
return false // ENODEV: unplugged
|
||||
}
|
||||
for i := 0; i+24 <= n; i += 24 {
|
||||
e := d.buf[i:]
|
||||
typ := binary.LittleEndian.Uint16(e[16:])
|
||||
code := binary.LittleEndian.Uint16(e[18:])
|
||||
value := int32(binary.LittleEndian.Uint32(e[20:]))
|
||||
switch {
|
||||
case typ == evKey && int(code) <= keyMax:
|
||||
d.keys[code] = value != 0
|
||||
case typ == evAbs && int(code) <= absMax:
|
||||
d.axes[code] = value
|
||||
}
|
||||
}
|
||||
if n < len(d.buf) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// norm maps axis a to -1..1, or 0..1 when half.
|
||||
func (d *evdevPad) norm(a int, half bool) float32 {
|
||||
if !d.hasAbs[a] {
|
||||
return 0
|
||||
}
|
||||
lo, hi := float32(d.abs[a].minimum), float32(d.abs[a].maximum)
|
||||
if hi <= lo {
|
||||
return 0
|
||||
}
|
||||
t := (float32(d.axes[a]) - lo) / (hi - lo)
|
||||
if half {
|
||||
return min(max(t, 0), 1)
|
||||
}
|
||||
return min(max(t*2-1, -1), 1)
|
||||
}
|
||||
|
||||
func (d *evdevPad) read(s *State) bool {
|
||||
if !d.drain() {
|
||||
return false
|
||||
}
|
||||
press := func(b Button, code int) {
|
||||
if d.keys[code] {
|
||||
s.Buttons[b] = 1
|
||||
}
|
||||
}
|
||||
press(South, btnSouth)
|
||||
press(East, btnEast)
|
||||
if d.xbox {
|
||||
press(West, btnNorth)
|
||||
press(North, btnWest)
|
||||
} else {
|
||||
press(North, btnNorth)
|
||||
press(West, btnWest)
|
||||
}
|
||||
press(LeftShoulder, btnTL)
|
||||
press(RightShoulder, btnTR)
|
||||
press(Back, btnSelect)
|
||||
press(Start, btnStart)
|
||||
press(Guide, btnMode)
|
||||
press(LeftStickButton, btnThumbL)
|
||||
press(RightStickButton, btnThumbR)
|
||||
press(Up, btnUp)
|
||||
press(Down, btnDown)
|
||||
press(Left, btnLeft)
|
||||
press(Right, btnRight)
|
||||
if d.hasAbs[absHat0X] {
|
||||
if v := d.axes[absHat0X]; v < 0 {
|
||||
s.Buttons[Left] = 1
|
||||
} else if v > 0 {
|
||||
s.Buttons[Right] = 1
|
||||
}
|
||||
if v := d.axes[absHat0Y]; v < 0 {
|
||||
s.Buttons[Up] = 1
|
||||
} else if v > 0 {
|
||||
s.Buttons[Down] = 1
|
||||
}
|
||||
}
|
||||
s.Axes[LeftX], s.Axes[LeftY] = d.norm(absX, false), d.norm(absY, false)
|
||||
if d.rightOnZ {
|
||||
s.Axes[RightX], s.Axes[RightY] = d.norm(absZ, false), d.norm(absRZ, false)
|
||||
} else {
|
||||
s.Axes[RightX], s.Axes[RightY] = d.norm(absRX, false), d.norm(absRY, false)
|
||||
s.Buttons[LeftTrigger] = d.norm(absZ, true)
|
||||
s.Buttons[RightTrigger] = d.norm(absRZ, true)
|
||||
}
|
||||
press(LeftTrigger, btnTL2)
|
||||
press(RightTrigger, btnTR2)
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//go:build linux && !android && (amd64 || arm64) && !android
|
||||
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/wait"
|
||||
)
|
||||
|
||||
// uinput makes virtual input devices.
|
||||
const (
|
||||
uiDevCreate = 1<<0 | 'U'<<8 | 1 // _IO('U', 1)
|
||||
uiDevDestroy = 'U'<<8 | 2
|
||||
uiSetEvBit = 1<<30 | 4<<16 | 'U'<<8 | 100
|
||||
uiSetKeyBit = 1<<30 | 4<<16 | 'U'<<8 | 101
|
||||
uiSetAbsBit = 1<<30 | 4<<16 | 'U'<<8 | 103
|
||||
)
|
||||
|
||||
type uinputSetup struct {
|
||||
id inputID
|
||||
name [80]byte
|
||||
ff uint32
|
||||
}
|
||||
|
||||
type uinputAbsSetup struct {
|
||||
code uint16
|
||||
_ uint16
|
||||
info absInfo
|
||||
}
|
||||
|
||||
func uiDevSetup() uintptr { return 1<<30 | unsafe.Sizeof(uinputSetup{})<<16 | 'U'<<8 | 3 }
|
||||
func uiAbsSetup() uintptr { return 1<<30 | unsafe.Sizeof(uinputAbsSetup{})<<16 | 'U'<<8 | 4 }
|
||||
|
||||
// A virtual pad, made with uinput, reads as the kernel's drivers report
|
||||
// pads: its buttons by place, sticks, triggers and hat. It needs
|
||||
// /dev/uinput and /dev/input, as in the Linux test container
|
||||
// (MYGO_UINPUT=1).
|
||||
func TestEvdev(t *testing.T) {
|
||||
if os.Getenv("MYGO_UINPUT") == "" {
|
||||
t.Skip("MYGO_UINPUT not set")
|
||||
}
|
||||
// A DualSense reports its left button, Square, as BTN_WEST; an Xbox
|
||||
// controller its left one, X, as BTN_X, BTN_NORTH's code.
|
||||
t.Run("PlayStation", func(t *testing.T) { testEvdev(t, 0x054c, btnWest) })
|
||||
t.Run("Xbox", func(t *testing.T) { testEvdev(t, 0x045e, btnNorth) })
|
||||
}
|
||||
|
||||
func testEvdev(t *testing.T, vendor uint16, west uint16) {
|
||||
fd, err := syscall.Open("/dev/uinput", syscall.O_WRONLY|syscall.O_NONBLOCK, 0)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
defer syscall.Close(fd)
|
||||
set := func(req uintptr, v int) {
|
||||
if _, _, e := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), req, uintptr(v)); e != 0 {
|
||||
t.Fatalf("ioctl %#x %d: %v", req, v, e)
|
||||
}
|
||||
}
|
||||
set(uiSetEvBit, evKey)
|
||||
set(uiSetEvBit, evAbs)
|
||||
for _, k := range []int{btnSouth, btnEast, btnNorth, btnWest, btnTL, btnTR, btnSelect, btnStart, btnMode, btnThumbL, btnThumbR} {
|
||||
set(uiSetKeyBit, k)
|
||||
}
|
||||
axes := map[uint16]absInfo{
|
||||
absX: {minimum: -32768, maximum: 32767}, absY: {minimum: -32768, maximum: 32767},
|
||||
absRX: {minimum: -32768, maximum: 32767}, absRY: {minimum: -32768, maximum: 32767},
|
||||
absZ: {maximum: 255}, absRZ: {maximum: 255},
|
||||
absHat0X: {minimum: -1, maximum: 1}, absHat0Y: {minimum: -1, maximum: 1},
|
||||
}
|
||||
for code, info := range axes {
|
||||
set(uiSetAbsBit, int(code))
|
||||
s := uinputAbsSetup{code: code, info: info}
|
||||
if !ioctl(fd, uiAbsSetup(), unsafe.Pointer(&s)) {
|
||||
t.Fatal("UI_ABS_SETUP")
|
||||
}
|
||||
}
|
||||
setup := uinputSetup{id: inputID{bustype: 3, vendor: vendor, product: 0x0ce6}}
|
||||
copy(setup.name[:], "Virtual Pad")
|
||||
if !ioctl(fd, uiDevSetup(), unsafe.Pointer(&setup)) {
|
||||
t.Fatal("UI_DEV_SETUP")
|
||||
}
|
||||
set(uiDevCreate, 0)
|
||||
// Destroyed by the test, unless it fails first.
|
||||
defer syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), uiDevDestroy, 0)
|
||||
|
||||
var pad *Pad
|
||||
wait.Until(t, "the virtual pad", func() bool {
|
||||
scanned = time.Time{}
|
||||
for _, p := range Pads() {
|
||||
if p.Name() == "Virtual Pad" {
|
||||
pad = p
|
||||
}
|
||||
}
|
||||
return pad != nil
|
||||
})
|
||||
emit := func(typ, code uint16, value int32) {
|
||||
var e [24]byte
|
||||
binary.LittleEndian.PutUint16(e[16:], typ)
|
||||
binary.LittleEndian.PutUint16(e[18:], code)
|
||||
binary.LittleEndian.PutUint32(e[20:], uint32(value))
|
||||
if _, err := syscall.Write(fd, e[:]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
emit(evKey, btnSouth, 1)
|
||||
emit(evKey, west, 1)
|
||||
emit(evAbs, absX, 32767)
|
||||
emit(evAbs, absRY, -32768)
|
||||
emit(evAbs, absRZ, 255)
|
||||
emit(evAbs, absHat0Y, -1)
|
||||
emit(0, 0, 0) // SYN_REPORT
|
||||
// State drains what the kernel passed on so far: wait until it has.
|
||||
wait.Until(t, "the report read", func() bool { return pad.State().Axes[LeftX] >= 0.99 })
|
||||
s := pad.State()
|
||||
for _, b := range []Button{South, West, RightTrigger, Up} {
|
||||
if !s.Pressed(b) {
|
||||
t.Errorf("button %d not pressed: %v", b, s.Buttons)
|
||||
}
|
||||
}
|
||||
for _, b := range []Button{East, North, LeftTrigger, Down} {
|
||||
if s.Pressed(b) {
|
||||
t.Errorf("button %d pressed: %v", b, s.Buttons)
|
||||
}
|
||||
}
|
||||
if s.Axes[LeftX] < 0.99 || s.Axes[RightY] > -0.99 || s.Axes[LeftY] < -0.01 || s.Axes[LeftY] > 0.01 {
|
||||
t.Errorf("axes %v", s.Axes)
|
||||
}
|
||||
emit(evKey, btnSouth, 0)
|
||||
emit(0, 0, 0)
|
||||
wait.Until(t, "South released", func() bool { return !pad.State().Pressed(South) })
|
||||
set(uiDevDestroy, 0)
|
||||
wait.Until(t, "the pad disconnected once destroyed", func() bool { pad.State(); return !pad.Connected() })
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build !(darwin && !ios) && !(linux && !android && (amd64 || arm64)) && !(windows && (amd64 || arm64)) && !js
|
||||
|
||||
package gamepad
|
||||
|
||||
func scan(known map[string]device) []device { return nil }
|
||||
@@ -0,0 +1,96 @@
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakeDevice is a pad whose state a test sets.
|
||||
type fakeDevice struct {
|
||||
id string
|
||||
state State
|
||||
gone bool
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (d *fakeDevice) key() string { return d.id }
|
||||
func (d *fakeDevice) name() string { return "Fake " + d.id }
|
||||
func (d *fakeDevice) close() { d.closed = true }
|
||||
func (d *fakeDevice) read(s *State) bool {
|
||||
*s = d.state
|
||||
return !d.gone
|
||||
}
|
||||
|
||||
// withDevices has scans find devs, which a test changes.
|
||||
func withDevices(t *testing.T, devs *[]device) {
|
||||
t.Helper()
|
||||
saved, savedEach := scanDevices, scanEach
|
||||
scanDevices = func(known map[string]device) []device { return *devs }
|
||||
scanEach = 0
|
||||
mu.Lock()
|
||||
pads, scanned = nil, scanned.AddDate(-1, 0, 0)
|
||||
mu.Unlock()
|
||||
t.Cleanup(func() {
|
||||
scanDevices, scanEach = saved, savedEach
|
||||
mu.Lock()
|
||||
pads = nil
|
||||
mu.Unlock()
|
||||
})
|
||||
}
|
||||
|
||||
func TestPadsConnectAndDisconnect(t *testing.T) {
|
||||
a, b := &fakeDevice{id: "a"}, &fakeDevice{id: "b"}
|
||||
devs := []device{a}
|
||||
withDevices(t, &devs)
|
||||
ps := Pads()
|
||||
if len(ps) != 1 || ps[0].Name() != "Fake a" || !ps[0].Connected() {
|
||||
t.Fatalf("pads %v", ps)
|
||||
}
|
||||
first := ps[0]
|
||||
devs = []device{b, a}
|
||||
ps = Pads()
|
||||
if len(ps) != 2 || ps[0] != first || ps[1].Name() != "Fake b" {
|
||||
t.Fatalf("pads in connecting order: %v", ps)
|
||||
}
|
||||
// Unplugged between scans: reading finds it gone.
|
||||
a.gone = true
|
||||
a.state.Buttons[South] = 1
|
||||
if first.State().Pressed(South) || first.Connected() || !a.closed {
|
||||
t.Error("a pad gone still reads, or is not closed")
|
||||
}
|
||||
// Gone from a scan.
|
||||
devs = nil
|
||||
if ps = Pads(); len(ps) != 0 {
|
||||
t.Errorf("pads after unplugging: %v", ps)
|
||||
}
|
||||
}
|
||||
|
||||
func TestState(t *testing.T) {
|
||||
var last, s State
|
||||
s.Buttons[South] = 1
|
||||
s.Buttons[LeftTrigger] = 0.2
|
||||
s.Buttons[RightTrigger] = 0.3
|
||||
if !s.Pressed(South) || s.Pressed(LeftTrigger) || !s.Pressed(RightTrigger) {
|
||||
t.Error("Pressed")
|
||||
}
|
||||
if !s.JustPressed(last, South) || s.JustPressed(s, South) || !last.JustReleased(s, South) {
|
||||
t.Error("JustPressed, JustReleased")
|
||||
}
|
||||
// Within the dead zone, nothing; at the rim, all the way, in every
|
||||
// direction alike.
|
||||
s.Axes[LeftX], s.Axes[LeftY] = 0.1, 0.05
|
||||
if x, y := s.LeftStick(); x != 0 || y != 0 {
|
||||
t.Errorf("rest = %v, %v", x, y)
|
||||
}
|
||||
s.Axes[LeftX], s.Axes[LeftY] = 0.7071, 0.7071
|
||||
if x, y := s.LeftStick(); math.Abs(math.Hypot(float64(x), float64(y))-1) > 1e-3 {
|
||||
t.Errorf("diagonal rim = %v, %v", x, y)
|
||||
}
|
||||
s.Axes[RightX] = -(Deadzone + (1-Deadzone)/2)
|
||||
if x, _ := s.RightStick(); math.Abs(float64(x)+0.5) > 1e-4 {
|
||||
t.Errorf("half way past the dead zone = %v", x)
|
||||
}
|
||||
if s.Value(ButtonCount) != 0 || s.Axis(AxisCount) != 0 {
|
||||
t.Error("out of range")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//go:build windows && (amd64 || arm64)
|
||||
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"sync"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Windows reads pads through XInput, which has four slots, for Xbox
|
||||
// controllers and those that act as one. XInputGetStateEx, exported by
|
||||
// ordinal 100, reads the Guide button too.
|
||||
|
||||
type xinputGamepad struct {
|
||||
buttons uint16
|
||||
leftTrigger uint8
|
||||
rightTrigger uint8
|
||||
thumbLX int16
|
||||
thumbLY int16
|
||||
thumbRX int16
|
||||
thumbRY int16
|
||||
}
|
||||
|
||||
type xinputState struct {
|
||||
packet uint32
|
||||
gamepad xinputGamepad
|
||||
}
|
||||
|
||||
const (
|
||||
errorSuccess = 0
|
||||
xinputSlots = 4
|
||||
xinputDpadUp = 0x0001
|
||||
xinputDpadDown = 0x0002
|
||||
xinputDpadLeft = 0x0004
|
||||
xinputDpadRight = 0x0008
|
||||
xinputStart = 0x0010
|
||||
xinputBack = 0x0020
|
||||
xinputLeftThumb = 0x0040
|
||||
xinputRightThumb = 0x0080
|
||||
xinputLeftShoulder = 0x0100
|
||||
xinputRightShoulder = 0x0200
|
||||
xinputGuide = 0x0400
|
||||
xinputA = 0x1000
|
||||
xinputB = 0x2000
|
||||
xinputX = 0x4000
|
||||
xinputY = 0x8000
|
||||
)
|
||||
|
||||
var (
|
||||
xinputOnce sync.Once
|
||||
xinputGetState uintptr
|
||||
)
|
||||
|
||||
func loadXInput() {
|
||||
xinputOnce.Do(func() {
|
||||
kernel32 := syscall.NewLazyDLL("kernel32.dll")
|
||||
getProc := kernel32.NewProc("GetProcAddress")
|
||||
for _, name := range []string{"xinput1_4.dll", "xinput1_3.dll", "xinput9_1_0.dll"} {
|
||||
lib, err := syscall.LoadLibrary(name)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
// XInputGetStateEx, by ordinal, where there is one.
|
||||
if p, _, _ := getProc.Call(uintptr(lib), 100); p != 0 {
|
||||
xinputGetState = p
|
||||
return
|
||||
}
|
||||
if p, err := syscall.GetProcAddress(lib, "XInputGetState"); err == nil {
|
||||
xinputGetState = p
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func getState(slot int, s *xinputState) bool {
|
||||
r, _, _ := syscall.SyscallN(xinputGetState, uintptr(slot), uintptr(unsafe.Pointer(s)))
|
||||
return r == errorSuccess
|
||||
}
|
||||
|
||||
type xinputPad struct{ slot int }
|
||||
|
||||
func scan(known map[string]device) []device {
|
||||
loadXInput()
|
||||
if xinputGetState == 0 {
|
||||
return nil
|
||||
}
|
||||
var found []device
|
||||
for slot := range xinputSlots {
|
||||
d := &xinputPad{slot}
|
||||
if k, ok := known[d.key()]; ok {
|
||||
// Read as it is used; a slot that empties disconnects there.
|
||||
found = append(found, k)
|
||||
continue
|
||||
}
|
||||
// Asking an empty slot is slow, which is why scans are rare.
|
||||
var st xinputState
|
||||
if getState(slot, &st) {
|
||||
found = append(found, d)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func (d *xinputPad) key() string { return "xinput" + strconv.Itoa(d.slot) }
|
||||
func (d *xinputPad) name() string { return "Xbox Controller " + strconv.Itoa(d.slot+1) }
|
||||
func (d *xinputPad) close() {}
|
||||
|
||||
func (d *xinputPad) read(s *State) bool {
|
||||
var st xinputState
|
||||
if !getState(d.slot, &st) {
|
||||
return false
|
||||
}
|
||||
g := st.gamepad
|
||||
bits := [...]struct {
|
||||
b Button
|
||||
mask uint16
|
||||
}{
|
||||
{South, xinputA}, {East, xinputB}, {West, xinputX}, {North, xinputY},
|
||||
{LeftShoulder, xinputLeftShoulder}, {RightShoulder, xinputRightShoulder},
|
||||
{Back, xinputBack}, {Start, xinputStart},
|
||||
{LeftStickButton, xinputLeftThumb}, {RightStickButton, xinputRightThumb},
|
||||
{Up, xinputDpadUp}, {Down, xinputDpadDown}, {Left, xinputDpadLeft}, {Right, xinputDpadRight},
|
||||
{Guide, xinputGuide},
|
||||
}
|
||||
for _, b := range bits {
|
||||
if g.buttons&b.mask != 0 {
|
||||
s.Buttons[b.b] = 1
|
||||
}
|
||||
}
|
||||
s.Buttons[LeftTrigger] = float32(g.leftTrigger) / 255
|
||||
s.Buttons[RightTrigger] = float32(g.rightTrigger) / 255
|
||||
// XInput's y axes go up.
|
||||
s.Axes[LeftX] = thumb(g.thumbLX)
|
||||
s.Axes[LeftY] = -thumb(g.thumbLY)
|
||||
s.Axes[RightX] = thumb(g.thumbRX)
|
||||
s.Axes[RightY] = -thumb(g.thumbRY)
|
||||
return true
|
||||
}
|
||||
|
||||
func thumb(v int16) float32 { return max(float32(v)/32767, -1) }
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
# glass
|
||||
|
||||
Liquid Glass for [MyGo](https://github.com/egoist/mygo) apps of native UI,
|
||||
as macOS 26 and later draw it, on every platform: a material that what is
|
||||
under an element shows through, frosted and bent along its edges.
|
||||
|
||||
```go
|
||||
import "github.com/egoist/mygo/plugins/glass"
|
||||
|
||||
ui.Row(c).Padding(8, 16).Radius(22).Material(glass.Glass{}).Children(func() {
|
||||
ui.Text(c, "On glass")
|
||||
})
|
||||
```
|
||||
|
||||
`glass.Group` merges panes of glass that nearly touch into one surface,
|
||||
as AppKit's `NSGlassEffectContainerView` does:
|
||||
|
||||
```go
|
||||
g := glass.NewGroup(c)
|
||||
g.Radius = 22
|
||||
g.Gap(6).Children(func() {
|
||||
g.Pane(ui.Box(c).Padding(8, 16).Center().Children(func() { ui.Text(c, "Cut") }))
|
||||
g.Pane(ui.Box(c).Padding(8, 16).Center().Children(func() { ui.Text(c, "Copy") }))
|
||||
})
|
||||
```
|
||||
|
||||
On macOS 26 and later, `glass.Glass{Native: true}` draws a toolbar over a
|
||||
`ui.WebView` with the system's `NSGlassEffectView`, which samples the page;
|
||||
elsewhere it falls back to the shader. With Reduce Transparency, the
|
||||
materials draw opaque surfaces.
|
||||
|
||||
`glass.ScrollEdge` is macOS's scroll edge effect, which content scrolling
|
||||
under a bar fades (soft) or frosts (hard) under, and `glass.Blur` blurs
|
||||
what is under an element without the glass, evenly or, with a mask,
|
||||
progressively:
|
||||
|
||||
```go
|
||||
ui.Box(c).Absolute().Top(0).Left(0).Right(0).Height(74).PassThrough().Material(glass.ScrollEdge{})
|
||||
ui.Box(c).Absolute().Top(0).Left(0).Right(0).Height(88).PassThrough().
|
||||
Material(glass.Blur{Radius: 6, Mask: &ui.LinearGradient{From: ui.RGB(0, 0, 0), To: ui.Transparent, Angle: 180}})
|
||||
```
|
||||
|
||||
See [the documentation](../../docs/plugins/glass.md), and the Glass page of
|
||||
`examples/gallery`.
|
||||
|
||||
The glass and the blur, which a hard scroll edge draws with, are effects
|
||||
of MyGo's renderers (`scene.Effect`): their shaders in Metal Shading
|
||||
Language, HLSL and GLSL (`glass.metal`, `glass.hlsl`, `glass.glsl`, and
|
||||
`blur.*`), and their twins for the CPU renderer (`pixels.go`, `blur.go`),
|
||||
which must draw the same pixels; the tests compare each GPU's drawing
|
||||
with the CPU's.
|
||||
`go generate` compiles the shaders ahead of time where it can: the Metal
|
||||
library on macOS, with Xcode (`shaders_darwin.go`), and the Direct3D
|
||||
bytecode on Windows (`shaders_windows.go`). Renderers compile the source
|
||||
when the code compiled ahead of time is older than it or than their own
|
||||
part of the shader.
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
// A level of the blur's effect in GLSL (see scene.Effect), as blur.metal
|
||||
// is in Metal Shading Language and blur.go draws it on the CPU.
|
||||
|
||||
vec4 blurAt(ivec2 p, ivec2 size) { return texelFetch(uBackdrop, clamp(p, ivec2(0), size - 1), 0); }
|
||||
|
||||
vec4 blurSample(Effect e, vec2 q) {
|
||||
q = framePoint(e, q);
|
||||
vec2 u = (q - e.area.xy) / e.down - 0.5;
|
||||
vec2 f = floor(u);
|
||||
vec2 w = u - f;
|
||||
ivec2 p = ivec2(f);
|
||||
ivec2 size = ivec2(e.area.zw);
|
||||
vec4 top = blurAt(p, size) * (1.0 - w.x) + blurAt(p + ivec2(1, 0), size) * w.x;
|
||||
vec4 bot = blurAt(p + ivec2(0, 1), size) * (1.0 - w.x) + blurAt(p + ivec2(1, 1), size) * w.x;
|
||||
return top * (1.0 - w.y) + bot * w.y;
|
||||
}
|
||||
|
||||
vec4 effect(vec2 p, Effect e) {
|
||||
vec2 d = e.p0.zw - e.p0.xy;
|
||||
float l = d.x * d.x + d.y * d.y;
|
||||
float t = 0.0;
|
||||
if (l > 0.0) {
|
||||
t = clamp(((p.x - e.p0.x) * d.x + (p.y - e.p0.y) * d.y) / max(l, 0.0001), 0.0, 1.0);
|
||||
}
|
||||
float blur = e.p1.x * (1.0 - t) + e.p1.y * t;
|
||||
float w = clamp((blur - e.p1.z) / (e.p1.w - e.p1.z), 0.0, 1.0);
|
||||
if (w <= 0.0) {
|
||||
return vec4(0.0);
|
||||
}
|
||||
vec4 c = blurSample(e, p);
|
||||
float lum = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
|
||||
c.rgb = clamp(lum + (c.rgb - lum) * (1.0 + e.p2.x) + e.p2.y * c.a, vec3(0.0), vec3(c.a));
|
||||
c += (vec4(e.p3.rgb, 1.0) - c) * e.p2.z;
|
||||
return c * w;
|
||||
}
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// Blur is a backdrop blur, a ui.Material: what was painted under the
|
||||
// element shows through it blurred, with no tint, rim or shadow. With a
|
||||
// Mask, the blur fades along a gradient, a progressive blur, as under a
|
||||
// bar that content scrolls under (ScrollEdge is macOS's own effect there):
|
||||
//
|
||||
// ui.Row(c).Absolute().Top(0).Left(0).Right(0).Height(56).Material(glass.Blur{
|
||||
// Radius: 12,
|
||||
// Mask: &ui.LinearGradient{From: ui.RGB(0, 0, 0), To: ui.Transparent, Angle: 180},
|
||||
// })
|
||||
type Blur struct {
|
||||
// Radius is how much what shows through blurs, in DIPs: the standard
|
||||
// deviation of a Gaussian, as CSS's blur() takes.
|
||||
Radius float32
|
||||
// Mask, if set, varies the blur along a gradient, by the alpha of its
|
||||
// colors, as CSS's mask-image does: what shows through blurs by Radius
|
||||
// where the gradient is opaque, by less where it is translucent, and
|
||||
// not at all where it is transparent. Its colors do not show.
|
||||
Mask *ui.LinearGradient
|
||||
}
|
||||
|
||||
// PaintMaterial paints the blur over box, rounded by radii.
|
||||
func (b Blur) PaintMaterial(p *ui.Painter, box ui.Rect, radii [4]float32) {
|
||||
paintBlur(p, box, radii, b)
|
||||
}
|
||||
|
||||
// String describes the blur, as the inspector shows it.
|
||||
func (b Blur) String() string {
|
||||
s := fmt.Sprintf("blur(%g)", b.Radius)
|
||||
if m := b.Mask; m != nil {
|
||||
s += fmt.Sprintf(" mask(%g%%→%g%% %g°)", math.Round(float64(m.From.A)/2.55), math.Round(float64(m.To.A)/2.55), m.Angle)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// blurLevel is a step of a blur that varies across its element: what was
|
||||
// painted under it, the levels before included, blurred by blur pixels,
|
||||
// shown where the blur the element wants is more than lo pixels, by how
|
||||
// far it is toward hi, and wholly from hi.
|
||||
//
|
||||
// Blurs add up as their variances do, so after the levels showing
|
||||
// wholly at a pixel, what shows there is blurred by hi pixels of the last
|
||||
// of them: the levels' his double from one level to the next, from at
|
||||
// most finestLevel pixels to the blur's most, and between two, a pixel
|
||||
// shows the blurs of both, mixed, which the eye takes for a blur between
|
||||
// them. A blur that does not vary is one level, which shows everywhere.
|
||||
type blurLevel struct{ blur, lo, hi float32 }
|
||||
|
||||
// finestLevel is the most the first level of a varying blur blurs, in
|
||||
// pixels: it shows mixed with what is not blurred, which at 2 pixels looks
|
||||
// as a blur between them. Against a blur varying per pixel, a first level
|
||||
// of 1 pixel measured no closer, and levels √2 apart rather than 2 closer
|
||||
// within the element but further along its edges, where each level reads
|
||||
// what is around the element unblurred.
|
||||
const finestLevel = 2
|
||||
|
||||
// blurLevels returns the levels of a blur varying from least to most
|
||||
// pixels.
|
||||
func blurLevels(least, most float32) []blurLevel {
|
||||
least = max(least, 0)
|
||||
if most <= least {
|
||||
if least <= 0 {
|
||||
return nil
|
||||
}
|
||||
return []blurLevel{{blur: least, lo: -1, hi: 0}}
|
||||
}
|
||||
// The levels' his, from the most down, halving.
|
||||
his := []float32{most}
|
||||
for h := most; h > finestLevel && h/2 > least; {
|
||||
h /= 2
|
||||
his = append(his, h)
|
||||
}
|
||||
var levels []blurLevel
|
||||
if least > 0 {
|
||||
levels = append(levels, blurLevel{blur: least, lo: -1, hi: 0})
|
||||
}
|
||||
lo := least
|
||||
for i := len(his) - 1; i >= 0; i-- {
|
||||
hi := his[i]
|
||||
levels = append(levels, blurLevel{blur: sqrt(hi*hi - lo*lo), lo: lo, hi: hi})
|
||||
lo = hi
|
||||
}
|
||||
return levels
|
||||
}
|
||||
|
||||
// paintBlur paints the blur b over box, rounded by radii.
|
||||
func paintBlur(p *ui.Painter, box ui.Rect, radii [4]float32, b Blur) {
|
||||
s := p.Scale()
|
||||
if box.W <= 0 || box.H <= 0 {
|
||||
return
|
||||
}
|
||||
if p.Preferences().ReduceTransparency {
|
||||
// What a blur is for, the content under a bar reading through it,
|
||||
// is transparency: the desktop asks for an opaque bar instead.
|
||||
p.FillRadii(box, radii, p.Theme().Background)
|
||||
return
|
||||
}
|
||||
// The rectangle of the element, in pixels, as the painter snaps it.
|
||||
px := scene.Rect{X: round(box.X * s), Y: round(box.Y * s)}
|
||||
px.W, px.H = round((box.X+box.W)*s)-px.X, round((box.Y+box.H)*s)-px.Y
|
||||
blurOps(px, radii == [4]float32{}, b.Radius*s, b.Mask, func(r scene.Rect, fx scene.EffectOp) {
|
||||
p.Effect(fx.Effect, ui.Rect{X: r.X / s, Y: r.Y / s, W: r.W / s, H: r.H / s}, radii, fx.Blur, fx.Params)
|
||||
})
|
||||
}
|
||||
|
||||
// blurOps calls op with the rectangle and the effect of each level
|
||||
// (blurLevels) of a blur of most pixels over r, in pixels, along mask: a
|
||||
// level after another, each where the blur is more than its lo when r is
|
||||
// square, which it then reads only what is under.
|
||||
func blurOps(r scene.Rect, square bool, most float32, mask *ui.LinearGradient, op func(r scene.Rect, fx scene.EffectOp)) {
|
||||
if r.W <= 0 || r.H <= 0 || most <= 0 {
|
||||
return
|
||||
}
|
||||
// The blur at the mask's start and end, along its line.
|
||||
var line [4]float32
|
||||
at0, at1 := most, most
|
||||
if mask != nil {
|
||||
line = maskLine(r, *mask)
|
||||
at0, at1 = most*float32(mask.From.A)/255, most*float32(mask.To.A)/255
|
||||
}
|
||||
for _, l := range blurLevels(min(at0, at1), max(at0, at1)) {
|
||||
lr := r
|
||||
if square && l.lo >= 0 {
|
||||
var ok bool
|
||||
if lr, ok = blurWanted(r, line, at0, at1, l.lo); !ok {
|
||||
continue
|
||||
}
|
||||
}
|
||||
op(lr, scene.EffectOp{Effect: blurEffect, Blur: l.blur, Params: [5][4]float32{line, {at0, at1, l.lo, l.hi}}})
|
||||
}
|
||||
}
|
||||
|
||||
// maskLine returns where the mask's From and To are, in pixels, as package
|
||||
// ui places a gradient's across the rectangle r (Element.Gradient): along
|
||||
// a line through its middle at the gradient's angle, as long as the
|
||||
// rectangle's corners are apart along it, as CSS's linear-gradient.
|
||||
func maskLine(r scene.Rect, g ui.LinearGradient) [4]float32 {
|
||||
a := float64(g.Angle) * math.Pi / 180
|
||||
dx, dy := float32(math.Sin(a)), float32(-math.Cos(a))
|
||||
half := (abs(r.W*dx) + abs(r.H*dy)) / 2
|
||||
cx, cy := r.X+r.W/2, r.Y+r.H/2
|
||||
x0, y0, x1, y1 := cx-dx*half, cy-dy*half, cx+dx*half, cy+dy*half
|
||||
start, end := g.Start, g.End
|
||||
if start == 0 && end == 0 {
|
||||
end = 1
|
||||
}
|
||||
sx, sy := x0+(x1-x0)*start, y0+(y1-y0)*start
|
||||
ex, ey := x0+(x1-x0)*end, y0+(y1-y0)*end
|
||||
if end-start < 0.5/max(2*half, 1) {
|
||||
// Stops at one place: a hard edge, half a pixel wide.
|
||||
ex, ey = sx+dx*0.5, sy+dy*0.5
|
||||
}
|
||||
return [4]float32{sx, sy, ex, ey}
|
||||
}
|
||||
|
||||
// blurWanted returns the bounds, in whole pixels, of the part of r where
|
||||
// the blur along line, from at0 at its start to at1 at its end, is more
|
||||
// than lo, and whether there is one.
|
||||
func blurWanted(r scene.Rect, line [4]float32, at0, at1, lo float32) (scene.Rect, bool) {
|
||||
if at0 == at1 {
|
||||
return r, at0 > lo
|
||||
}
|
||||
// Along the line, the blur is lo at tc, and more on one side of it:
|
||||
// the side of the half-plane n·p > c.
|
||||
dx, dy := line[2]-line[0], line[3]-line[1]
|
||||
tc := (lo - at0) / (at1 - at0)
|
||||
nx, ny := dx, dy
|
||||
c := line[0]*dx + line[1]*dy + tc*(dx*dx+dy*dy)
|
||||
if at1 < at0 {
|
||||
nx, ny, c = -nx, -ny, -c
|
||||
}
|
||||
corners := [4][2]float32{{r.X, r.Y}, {r.X + r.W, r.Y}, {r.X + r.W, r.Y + r.H}, {r.X, r.Y + r.H}}
|
||||
x0, y0 := float32(math.Inf(1)), float32(math.Inf(1))
|
||||
x1, y1 := float32(math.Inf(-1)), float32(math.Inf(-1))
|
||||
add := func(x, y float32) {
|
||||
x0, y0, x1, y1 = min(x0, x), min(y0, y), max(x1, x), max(y1, y)
|
||||
}
|
||||
for i, a := range corners {
|
||||
b := corners[(i+1)%4]
|
||||
fa, fb := nx*a[0]+ny*a[1]-c, nx*b[0]+ny*b[1]-c
|
||||
if fa > 0 {
|
||||
add(a[0], a[1])
|
||||
}
|
||||
if (fa > 0) != (fb > 0) {
|
||||
k := fa / (fa - fb)
|
||||
add(a[0]+(b[0]-a[0])*k, a[1]+(b[1]-a[1])*k)
|
||||
}
|
||||
}
|
||||
if x0 > x1 || y0 > y1 {
|
||||
return scene.Rect{}, false
|
||||
}
|
||||
x0, y0 = max(floor(x0), r.X), max(floor(y0), r.Y)
|
||||
x1, y1 = min(ceil(x1), r.X+r.W), min(ceil(y1), r.Y+r.H)
|
||||
if x1 <= x0 || y1 <= y0 {
|
||||
return scene.Rect{}, false
|
||||
}
|
||||
return scene.Rect{X: x0, Y: y0, W: x1 - x0, H: y1 - y0}, true
|
||||
}
|
||||
|
||||
// blurTone is what a level does to the colors it shows, which a blur's
|
||||
// levels leave as they are: saturation more saturation (0 for as is),
|
||||
// offset added to each channel, and mix of the opaque color over it, in
|
||||
// its parameters p2 and p3, as a scroll edge's hard style frosts.
|
||||
type blurTone struct {
|
||||
saturation, offset, mix float32
|
||||
color [3]float32
|
||||
}
|
||||
|
||||
// params returns the tone's parameters, p2 and p3.
|
||||
func (t blurTone) params() (p2, p3 [4]float32) {
|
||||
return [4]float32{t.saturation, t.offset, t.mix}, [4]float32{t.color[0], t.color[1], t.color[2], 1}
|
||||
}
|
||||
|
||||
// blurPixels draws a level of a blur on the CPU, as its shaders do on the
|
||||
// GPU.
|
||||
type blurPixels struct {
|
||||
line, band, tone, color [4]float32
|
||||
}
|
||||
|
||||
// Begin reads the level's mask, band and tone.
|
||||
func (px *blurPixels) Begin(op *scene.EffectOp, _ scene.Rect, _ [4]float32) {
|
||||
px.line, px.band, px.tone, px.color = op.Params[0], op.Params[1], op.Params[2], op.Params[3]
|
||||
}
|
||||
|
||||
// Color returns the color of the level at the pixel center (x, y), as the
|
||||
// shaders' effect does: the backdrop, toned, by how much the level shows
|
||||
// there.
|
||||
func (px *blurPixels) Color(x, y float32, b *scene.BackdropImage) [4]float32 {
|
||||
w := px.weight(x, y)
|
||||
if w <= 0 {
|
||||
return [4]float32{}
|
||||
}
|
||||
c := sampleRGBA(b, x, y)
|
||||
t := &px.tone
|
||||
l := 0.2126*c[0] + 0.7152*c[1] + 0.0722*c[2]
|
||||
for i := range 3 {
|
||||
c[i] = min(max(l+(c[i]-l)*(1+t[0])+t[1]*c[3], 0), c[3])
|
||||
}
|
||||
for i := range c {
|
||||
c[i] += (px.color[i] - c[i]) * t[2]
|
||||
}
|
||||
return [4]float32{c[0] * w, c[1] * w, c[2] * w, c[3] * w}
|
||||
}
|
||||
|
||||
// weight returns how much the level shows at (x, y), from 0 to 1: by how
|
||||
// far the blur there, along the mask, is into its band.
|
||||
func (px *blurPixels) weight(x, y float32) float32 {
|
||||
l, band := &px.line, &px.band
|
||||
dx, dy := l[2]-l[0], l[3]-l[1]
|
||||
t := float32(0)
|
||||
if d := dx*dx + dy*dy; d > 0 {
|
||||
t = min(max(((x-l[0])*dx+(y-l[1])*dy)/max(d, 0.0001), 0), 1)
|
||||
}
|
||||
blur := band[0]*(1-t) + band[1]*t
|
||||
return min(max((blur-band[2])/(band[3]-band[2]), 0), 1)
|
||||
}
|
||||
|
||||
// sampleRGBA returns the backdrop at (x, y) with its alpha, premultiplied,
|
||||
// as BackdropImage.Sample does its color, and the shaders' blurSample.
|
||||
func sampleRGBA(b *scene.BackdropImage, x, y float32) [4]float32 {
|
||||
x, y = b.Transform.Point(x, y)
|
||||
k := float32(b.Down)
|
||||
u := (x-float32(b.Area.Min.X))/k - 0.5
|
||||
v := (y-float32(b.Area.Min.Y))/k - 0.5
|
||||
fu, fv := floor(u), floor(v)
|
||||
tx, ty := u-fu, v-fv
|
||||
x0, y0 := min(max(int(fu), 0), b.W-1), min(max(int(fv), 0), b.H-1)
|
||||
x1, y1 := min(max(int(fu)+1, 0), b.W-1), min(max(int(fv)+1, 0), b.H-1)
|
||||
p00, p10 := b.Pix[4*(y0*b.W+x0):][:4], b.Pix[4*(y0*b.W+x1):][:4]
|
||||
p01, p11 := b.Pix[4*(y1*b.W+x0):][:4], b.Pix[4*(y1*b.W+x1):][:4]
|
||||
var c [4]float32
|
||||
for i := range c {
|
||||
top := p00[i]*(1-tx) + p10[i]*tx
|
||||
bot := p01[i]*(1-tx) + p11[i]*tx
|
||||
c[i] = top*(1-ty) + bot*ty
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func round(v float32) float32 { return float32(math.Round(float64(v))) }
|
||||
func floor(v float32) float32 { return float32(math.Floor(float64(v))) }
|
||||
func ceil(v float32) float32 { return float32(math.Ceil(float64(v))) }
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
// A level of the blur's effect in HLSL (see scene.Effect), as blur.metal
|
||||
// is in Metal Shading Language and blur.go draws it on the CPU.
|
||||
|
||||
float4 blurAt(int2 p, int2 size) { return backdropTex.Load(int3(clamp(p, int2(0, 0), size - 1), 0)); }
|
||||
|
||||
float4 blurSample(Effect e, float2 q) {
|
||||
q = framePoint(e, q);
|
||||
float2 u = (q - e.area.xy) / e.down - 0.5;
|
||||
float2 f = floor(u);
|
||||
float2 w = u - f;
|
||||
int2 p = int2(f);
|
||||
int2 size = int2(e.area.zw);
|
||||
float4 top = blurAt(p, size) * (1 - w.x) + blurAt(p + int2(1, 0), size) * w.x;
|
||||
float4 bot = blurAt(p + int2(0, 1), size) * (1 - w.x) + blurAt(p + int2(1, 1), size) * w.x;
|
||||
return top * (1 - w.y) + bot * w.y;
|
||||
}
|
||||
|
||||
float4 effect(float2 p, Effect e) {
|
||||
float2 d = e.p0.zw - e.p0.xy;
|
||||
float l = d.x * d.x + d.y * d.y;
|
||||
float t = 0;
|
||||
if (l > 0) {
|
||||
t = saturate(((p.x - e.p0.x) * d.x + (p.y - e.p0.y) * d.y) / max(l, 0.0001));
|
||||
}
|
||||
float blur = e.p1.x * (1 - t) + e.p1.y * t;
|
||||
float w = saturate((blur - e.p1.z) / (e.p1.w - e.p1.z));
|
||||
if (w <= 0) {
|
||||
return float4(0, 0, 0, 0);
|
||||
}
|
||||
float4 c = blurSample(e, p);
|
||||
float lum = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
|
||||
c.rgb = clamp(lum + (c.rgb - lum) * (1 + e.p2.x) + e.p2.y * c.a, 0, c.a);
|
||||
c += (float4(e.p3.rgb, 1) - c) * e.p2.z;
|
||||
return c * w;
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
// A level of the blur's effect in Metal Shading Language (see
|
||||
// scene.Effect and blurLevel), as blur.go draws it on the CPU. p0 is the
|
||||
// mask's line, from its start to its end in pixels; p1 the blur at its
|
||||
// start and at its end, and the level's band, from p1.z to p1.w; p2 and p3
|
||||
// its tone (blurTone): how much more saturated, the offset and how much of
|
||||
// the color p3 over it.
|
||||
|
||||
// blurAt returns the backdrop's texel p, with its alpha, clamped to its
|
||||
// edges.
|
||||
float4 blurAt(texture2d<float> t, int2 p, int2 size) { return t.read(uint2(clamp(p, int2(0), size - 1))); }
|
||||
|
||||
// blurSample returns the backdrop at q with its alpha, as sampleBackdrop
|
||||
// does its color (sampleRGBA).
|
||||
float4 blurSample(texture2d<float> t, Effect e, float2 q) {
|
||||
q = framePoint(e, q);
|
||||
float2 u = (q - e.area.xy) / e.down - 0.5f;
|
||||
float2 f = floor(u);
|
||||
float2 w = u - f;
|
||||
int2 p = int2(f);
|
||||
int2 size = int2(e.area.zw);
|
||||
float4 top = blurAt(t, p, size) * (1.0f - w.x) + blurAt(t, p + int2(1, 0), size) * w.x;
|
||||
float4 bot = blurAt(t, p + int2(0, 1), size) * (1.0f - w.x) + blurAt(t, p + int2(1, 1), size) * w.x;
|
||||
return top * (1.0f - w.y) + bot * w.y;
|
||||
}
|
||||
|
||||
float4 effect(float2 p, Effect e, texture2d<float> backdrop) {
|
||||
float2 d = e.p0.zw - e.p0.xy;
|
||||
float l = d.x * d.x + d.y * d.y;
|
||||
float t = 0.0f;
|
||||
if (l > 0.0f) {
|
||||
t = clamp(((p.x - e.p0.x) * d.x + (p.y - e.p0.y) * d.y) / max(l, 0.0001f), 0.0f, 1.0f);
|
||||
}
|
||||
float blur = e.p1.x * (1.0f - t) + e.p1.y * t;
|
||||
float w = clamp((blur - e.p1.z) / (e.p1.w - e.p1.z), 0.0f, 1.0f);
|
||||
if (w <= 0.0f) {
|
||||
return float4(0.0f);
|
||||
}
|
||||
float4 c = blurSample(backdrop, e, p);
|
||||
float lum = 0.2126f * c.r + 0.7152f * c.g + 0.0722f * c.b;
|
||||
c.rgb = clamp(lum + (c.rgb - lum) * (1.0f + e.p2.x) + e.p2.y * c.a, 0.0f, c.a);
|
||||
c += (float4(e.p3.rgb, 1.0f) - c) * e.p2.z;
|
||||
return c * w;
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"image"
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// TestBlurLevels checks that a varying blur's levels add up to its most,
|
||||
// halving from there down to the finest, and that one that does not vary
|
||||
// is a level showing everywhere.
|
||||
func TestBlurLevels(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
least, most float32
|
||||
n int
|
||||
}{{0, 24, 5}, {0, 2, 1}, {0, 0.5, 1}, {5, 24, 4}, {3, 3, 1}, {0, 0, 0}} {
|
||||
levels := blurLevels(c.least, c.most)
|
||||
if len(levels) != c.n {
|
||||
t.Errorf("%v to %v: %d levels, not %d: %v", c.least, c.most, len(levels), c.n, levels)
|
||||
continue
|
||||
}
|
||||
if c.n == 0 {
|
||||
continue
|
||||
}
|
||||
// The variances add up to the most's.
|
||||
var v float64
|
||||
for _, l := range levels {
|
||||
v += float64(l.blur * l.blur)
|
||||
}
|
||||
if math.Abs(math.Sqrt(v)-float64(max(c.most, c.least))) > 1e-3 {
|
||||
t.Errorf("%v to %v: the levels blur by %v in all: %v", c.least, c.most, math.Sqrt(v), levels)
|
||||
}
|
||||
last := levels[len(levels)-1]
|
||||
if c.most > c.least && last.hi != c.most {
|
||||
t.Errorf("%v to %v: the last level ends at %v", c.least, c.most, last.hi)
|
||||
}
|
||||
for i := 1; i < len(levels); i++ {
|
||||
if levels[i].lo != levels[i-1].hi && levels[i-1].lo >= 0 {
|
||||
t.Errorf("%v to %v: level %d starts at %v, after %v", c.least, c.most, i, levels[i].lo, levels[i-1].hi)
|
||||
}
|
||||
}
|
||||
if first := levels[0]; first.lo >= 0 && first.hi > finestLevel && first.lo == 0 {
|
||||
t.Errorf("%v to %v: the first level blurs by %v, over what is not blurred", c.least, c.most, first.hi)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBlurWanted checks that a level's rectangle holds every pixel it
|
||||
// shows at, and little more, at any angle of the mask.
|
||||
func TestBlurWanted(t *testing.T) {
|
||||
r := scene.Rect{X: 10, Y: 20, W: 200, H: 80}
|
||||
for _, g := range []ui.LinearGradient{
|
||||
{From: ui.RGB(0, 0, 0), Angle: 180},
|
||||
{From: ui.RGB(0, 0, 0), Angle: 0},
|
||||
{From: ui.RGB(0, 0, 0), Angle: 90, Start: 0.2, End: 0.6},
|
||||
{From: ui.RGB(0, 0, 0), Angle: 30},
|
||||
{From: ui.RGBA(0, 0, 0, 0.3), To: ui.RGB(0, 0, 0), Angle: 225},
|
||||
{From: ui.RGB(0, 0, 0), Angle: 180, Start: 0.5, End: 0.5},
|
||||
} {
|
||||
at0, at1 := 20*float32(g.From.A)/255, 20*float32(g.To.A)/255
|
||||
line := maskLine(r, g)
|
||||
for _, l := range blurLevels(min(at0, at1), max(at0, at1)) {
|
||||
if l.lo < 0 {
|
||||
continue
|
||||
}
|
||||
px := blurPixels{line: line, band: [4]float32{at0, at1, l.lo, l.hi}}
|
||||
got, ok := blurWanted(r, line, at0, at1, l.lo)
|
||||
shown := image.Rectangle{}
|
||||
for y := int(r.Y); y < int(r.Y+r.H); y++ {
|
||||
for x := int(r.X); x < int(r.X+r.W); x++ {
|
||||
if px.weight(float32(x)+0.5, float32(y)+0.5) > 0 {
|
||||
shown = shown.Union(image.Rect(x, y, x+1, y+1))
|
||||
}
|
||||
}
|
||||
}
|
||||
want := image.Rect(int(got.X), int(got.Y), int(got.X+got.W), int(got.Y+got.H))
|
||||
if !ok {
|
||||
want = image.Rectangle{}
|
||||
}
|
||||
if !shown.In(want) {
|
||||
t.Errorf("%+v, level %v: shows at %v, outside %v", g, l, shown, want)
|
||||
}
|
||||
// At most two pixels more on each side, where the edge of the
|
||||
// level, slanted, crosses the pixels' rows between their
|
||||
// centers.
|
||||
if !shown.Empty() && !want.In(shown.Inset(-2)) {
|
||||
t.Errorf("%+v, level %v: %v is much larger than where it shows, %v", g, l, want, shown)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stripes paints black columns period/2 DIPs wide, period apart, over
|
||||
// white: what blurs to gray.
|
||||
func stripes(c *ui.Context, period float32) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255)).Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
for x := float32(0); x < r.W; x += period {
|
||||
p.Fill(ui.Rect{X: r.X + x, Y: r.Y, W: period / 2, H: r.H}, ui.RGB(0, 0, 0), 0)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// contrast returns how far apart the darkest and the lightest pixels of
|
||||
// row y are, from column x0 to x1: how much of the stripes shows there.
|
||||
func contrast(img *image.RGBA, y, x0, x1 int) int {
|
||||
lo, hi := 255, 0
|
||||
for x := x0; x < x1; x++ {
|
||||
v := int(img.RGBAAt(x, y).R)
|
||||
lo, hi = min(lo, v), max(hi, v)
|
||||
}
|
||||
return hi - lo
|
||||
}
|
||||
|
||||
func TestBlurBlursWhatIsBehind(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Children(func() {
|
||||
stripes(c, 2)
|
||||
ui.Box(c).Absolute().Left(0).Top(0).Size(200, 30).Material(Blur{Radius: 4})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 200, 60)
|
||||
img := tt.Image()
|
||||
if got := contrast(img, 15, 20, 180); got > 2 {
|
||||
t.Errorf("under the blur, the stripes' contrast is %d", got)
|
||||
}
|
||||
// Stripes average to gray.
|
||||
if g := pixelAt(img, 100, 15)[0]; g < 115 || g > 140 {
|
||||
t.Errorf("under the blur, the stripes are %d", g)
|
||||
}
|
||||
if got := contrast(img, 45, 20, 180); got != 255 {
|
||||
t.Errorf("below the blur, the stripes' contrast is %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgressiveBlur(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Children(func() {
|
||||
stripes(c, 8)
|
||||
ui.Box(c).Absolute().Left(0).Top(10).Right(0).Height(80).
|
||||
Material(Blur{Radius: 6, Mask: &ui.LinearGradient{From: ui.RGB(0, 0, 0), To: ui.Transparent, Angle: 180}})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 100, 100)
|
||||
tt.SetScale(2)
|
||||
img := tt.Image()
|
||||
// The blur fades from its top, 12 pixels, to nothing at its bottom:
|
||||
// the stripes, 16 pixels apart, show more and more toward its bottom,
|
||||
// and wholly below it.
|
||||
last := -1
|
||||
for y := 20; y < 180; y += 4 {
|
||||
got := contrast(img, y, 40, 160)
|
||||
if got+1 < last {
|
||||
t.Errorf("row %d has a contrast of %d, less than above it (%d)", y, got, last)
|
||||
}
|
||||
last = max(last, got)
|
||||
}
|
||||
if top := contrast(img, 22, 40, 160); top > 1 {
|
||||
t.Errorf("at the top, the stripes' contrast is %d", top)
|
||||
}
|
||||
// Halfway, the blur is 6 pixels, which leaves 6% of the stripes'
|
||||
// first harmonic: e^(-2π²·6²/16²).
|
||||
if mid := contrast(img, 100, 40, 160); mid < 10 || mid > 40 {
|
||||
t.Errorf("halfway, the stripes' contrast is %d", mid)
|
||||
}
|
||||
if low := contrast(img, 176, 40, 160); low < 200 {
|
||||
t.Errorf("at the bottom, the stripes' contrast is %d", low)
|
||||
}
|
||||
if below := contrast(img, 182, 40, 160); below != 255 {
|
||||
t.Errorf("below the blur, the stripes' contrast is %d", below)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlurString(t *testing.T) {
|
||||
if s := (Blur{Radius: 12}).String(); s != "blur(12)" {
|
||||
t.Errorf("String: %q", s)
|
||||
}
|
||||
b := Blur{Radius: 8, Mask: &ui.LinearGradient{From: ui.RGB(0, 0, 0), To: ui.Transparent, Angle: 180}}
|
||||
if s := b.String(); s != "blur(8) mask(100%→0% 180°)" {
|
||||
t.Errorf("String: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// blurOp appends the levels of a blur of most pixels over r to s, along
|
||||
// mask, as paintBlur paints them.
|
||||
func blurOp(s *scene.Scene, r scene.Rect, radii [4]float32, most float32, mask *ui.LinearGradient, opacity float32) {
|
||||
blurOps(r, radii == [4]float32{}, most, mask, func(lr scene.Rect, fx scene.EffectOp) {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpEffect, Rect: lr, Radii: radii, Start: int32(len(s.Effects)), Opacity: opacity})
|
||||
s.Effects = append(s.Effects, fx)
|
||||
})
|
||||
}
|
||||
|
||||
// blurScene returns a 320×140 scene of blurs over stripes, which the
|
||||
// renderers must draw alike: an even blur, rounded; a progressive blur
|
||||
// from the top, and one at an angle within a rounded clip; a blur with a
|
||||
// plateau, half transparent; a blur over what is partly transparent; and
|
||||
// a hard scroll edge's tone.
|
||||
func blurScene() *scene.Scene {
|
||||
s := &scene.Scene{Width: 320, Height: 140}
|
||||
red := scene.Color{R: 220, G: 40, B: 40, A: 255}
|
||||
blue := scene.Color{R: 37, G: 99, B: 235, A: 255}
|
||||
yellow := scene.Color{R: 250, G: 204, B: 21, A: 255}
|
||||
ink := scene.Color{R: 20, G: 24, B: 32, A: 255}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: 260, H: 140}, Color: scene.Color{R: 246, G: 247, B: 249, A: 255}})
|
||||
for i := range 13 {
|
||||
c := []scene.Color{red, blue, yellow, ink}[i%4]
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i * 20), W: 8, H: 140}, Color: c})
|
||||
}
|
||||
for i := range 14 {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{Y: float32(i * 10), W: 260, H: 2}, Color: ink})
|
||||
}
|
||||
black := ui.RGB(0, 0, 0)
|
||||
blurOp(s, scene.Rect{X: 10, Y: 10, W: 90, H: 50}, r4(14), 6, nil, 0)
|
||||
blurOp(s, scene.Rect{X: 110, Y: 0, W: 120, H: 60}, [4]float32{}, 16, &ui.LinearGradient{From: black, To: ui.Transparent, Angle: 180}, 0)
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 20, Y: 70, W: 120, H: 60}, Radii: r4(16)})
|
||||
blurOp(s, scene.Rect{X: 10, Y: 66, W: 140, H: 70}, [4]float32{}, 10, &ui.LinearGradient{From: ui.Transparent, To: black, Angle: 60}, 0)
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
|
||||
blurOp(s, scene.Rect{X: 150.5, Y: 70.25, W: 60, H: 60}, [4]float32{}, 8,
|
||||
&ui.LinearGradient{From: ui.RGBA(0, 0, 0, 0.4), To: black, Angle: 90, Start: 0.3, End: 0.7}, 0.6)
|
||||
blurOp(s, scene.Rect{X: 230, Y: 20, W: 70, H: 100}, r4(10), 5, nil, 0)
|
||||
// A hard scroll edge's tone, over the edge of nothing.
|
||||
p2, p3 := blurTone{saturation: 0.25, offset: 0.03, mix: 0.6, color: [3]float32{0.9, 0.95, 1}}.params()
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpEffect, Rect: scene.Rect{X: 234, Y: 0, W: 86, H: 16}, Start: int32(len(s.Effects))})
|
||||
s.Effects = append(s.Effects, scene.EffectOp{Effect: blurEffect, Blur: 4, Params: [5][4]float32{{}, {4, 4, -1, 0}, p2, p3}})
|
||||
return s
|
||||
}
|
||||
|
||||
// TestBlurScene checks the CPU's drawing of the blurs: what is not under
|
||||
// them shows as it is, what is under the most blurred is a mix of the
|
||||
// stripes, and the nothing beside the stripes stays nothing.
|
||||
func TestBlurScene(t *testing.T) {
|
||||
s := blurScene()
|
||||
img := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(img, s)
|
||||
at := func(x, y int) [4]byte {
|
||||
p := img.Pix[y*img.Stride+4*x:]
|
||||
return [4]byte{p[2], p[1], p[0], p[3]}
|
||||
}
|
||||
if p := at(5, 105); p != [4]byte{220, 40, 40, 255} {
|
||||
t.Errorf("outside the blurs: %v", p)
|
||||
}
|
||||
// Over nothing, the blur paints nothing; along the edge of what is
|
||||
// under it, that and nothing blur together, translucent.
|
||||
if p := at(290, 70); p[3] != 0 {
|
||||
t.Errorf("the blur over nothing: %v", p)
|
||||
}
|
||||
if p := at(260, 70); p[3] < 90 || p[3] > 165 {
|
||||
t.Errorf("the blur along the edge of nothing: %v", p)
|
||||
}
|
||||
// Under the top of the progressive blur, the stripes are gone.
|
||||
lo, hi := 255, 0
|
||||
for x := 112; x < 228; x++ {
|
||||
v := int(at(x, 2)[1])
|
||||
lo, hi = min(lo, v), max(hi, v)
|
||||
}
|
||||
if hi-lo > 40 {
|
||||
t.Errorf("under the top of the progressive blur, the row varies from %d to %d", lo, hi)
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkBlur measures drawing a window with a blur under its toolbar
|
||||
// on the CPU, whole: 1360×720 pixels, stripes under a strip 176 pixels
|
||||
// high blurred by 24 pixels, evenly or fading from the top.
|
||||
func BenchmarkBlur(b *testing.B) {
|
||||
for _, bc := range []struct {
|
||||
name string
|
||||
mask *ui.LinearGradient
|
||||
}{{"even", nil}, {"progressive", &ui.LinearGradient{From: ui.RGB(0, 0, 0), To: ui.Transparent, Angle: 180}}} {
|
||||
b.Run(bc.name, func(b *testing.B) {
|
||||
s := &scene.Scene{Width: 1360, Height: 720, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}}
|
||||
colors := []scene.Color{{R: 239, G: 68, B: 68, A: 255}, {R: 245, G: 158, B: 11, A: 255}, {R: 16, G: 185, B: 129, A: 255}, {R: 59, G: 130, B: 246, A: 255}}
|
||||
for i := range 17 {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i * 80), W: 40, H: 720}, Color: colors[i%len(colors)]})
|
||||
}
|
||||
blurOp(s, scene.Rect{W: 1360, H: 176}, [4]float32{}, 24, bc.mask, 0)
|
||||
img := raster.NewImage(s.Width, s.Height)
|
||||
for b.Loop() {
|
||||
raster.Render(img, s)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
package glass
|
||||
|
||||
import "github.com/egoist/mygo/ui"
|
||||
|
||||
// ScrollEdge is the scroll edge effect of macOS 26 and later, a
|
||||
// ui.Material: what macOS draws over content scrolling under a bar of
|
||||
// controls, so that they stand out from it, as SwiftUI's safeAreaBar with
|
||||
// scrollEdgeEffectStyle does. Fill an element over the content's edge
|
||||
// with it, under the bar, as long as the bar and 10 DIPs more when soft,
|
||||
// as long as the bar when hard:
|
||||
//
|
||||
// ui.Box(c).Absolute().Top(0).Left(0).Right(0).Height(74).PassThrough().Material(glass.ScrollEdge{})
|
||||
//
|
||||
// Its looks are macOS 27's, measured from SwiftUI's: the soft edge fades
|
||||
// the content into its background, with no blur; the hard edge frosts it.
|
||||
type ScrollEdge struct {
|
||||
// Hard makes the edge hard: what is under it blurred by about 6 DIPs, its
|
||||
// colors saturated, under 82% of the background, evenly, with a
|
||||
// hairline along its other edge. Soft, it fades the background over
|
||||
// the content, from 85% at the bar's edge to nothing at the other.
|
||||
Hard bool
|
||||
// Bottom puts the bar at the element's bottom, the effect rising from
|
||||
// it, rather than at its top.
|
||||
Bottom bool
|
||||
// Background is what the content scrolls over, which the effect lays
|
||||
// over it; unset, the theme's Background.
|
||||
Background ui.Color
|
||||
}
|
||||
|
||||
// PaintMaterial paints the scroll edge over box, rounded by radii.
|
||||
func (e ScrollEdge) PaintMaterial(p *ui.Painter, box ui.Rect, radii [4]float32) {
|
||||
if box.W <= 0 || box.H <= 0 {
|
||||
return
|
||||
}
|
||||
bg := e.Background
|
||||
if bg.A == 0 {
|
||||
bg = p.Theme().Background
|
||||
}
|
||||
if p.Preferences().ReduceTransparency {
|
||||
// An opaque bar, in place of what would show through the edge.
|
||||
bg.A = 255
|
||||
p.FillRadii(box, radii, bg)
|
||||
return
|
||||
}
|
||||
if !e.Hard {
|
||||
// The background, its alpha 0.85 at the bar's edge, falling
|
||||
// linearly to 0 at the other, as AppKit's soft pocket replays the
|
||||
// window's background under a gradient mask, in sRGB.
|
||||
g := ui.LinearGradient{From: bg.Alpha(softEdge), To: bg.Alpha(0), Angle: 180}
|
||||
if e.Bottom {
|
||||
g.Angle = 0
|
||||
}
|
||||
fillGradient(p, box, radii, g)
|
||||
return
|
||||
}
|
||||
// Under a hard edge, the content blurred, saturated by 1.25
|
||||
// and lightened by 0.03, as AppKit's HardPocketContentBlur, under the
|
||||
// background at 82.45%, desaturated to 0.947 and lightened by 0.03, as
|
||||
// its HardPocketBackgroundReplay, evenly.
|
||||
s := p.Scale()
|
||||
b := hardEdgeBlur * s
|
||||
c := toned([3]float32{float32(bg.R) / 255, float32(bg.G) / 255, float32(bg.B) / 255}, 0.947, 0.03)
|
||||
p2, p3 := blurTone{saturation: 0.25, offset: 0.03, mix: 0.8245, color: c}.params()
|
||||
p.Effect(blurEffect, box, radii, b, [5][4]float32{{}, {b, b, -1, 0}, p2, p3})
|
||||
// The hairline along the other edge, outside it, half a DIP: black at
|
||||
// 10% in light mode, white at 7% in dark mode.
|
||||
line := ui.RGBA(0, 0, 0, 0.1)
|
||||
if p.Theme().Dark {
|
||||
line = ui.RGBA(255, 255, 255, 0.07)
|
||||
}
|
||||
h := max(0.5, 1/s)
|
||||
line = line.Alpha(0.5 / h)
|
||||
y := box.Y + box.H
|
||||
if e.Bottom {
|
||||
y = box.Y - h
|
||||
}
|
||||
p.Fill(ui.Rect{X: box.X, Y: y, W: box.W, H: h}, line, 0)
|
||||
}
|
||||
|
||||
// String describes the scroll edge, as the inspector shows it.
|
||||
func (e ScrollEdge) String() string {
|
||||
s := "scroll-edge soft"
|
||||
if e.Hard {
|
||||
s = "scroll-edge hard"
|
||||
}
|
||||
if e.Bottom {
|
||||
s += " bottom"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// softEdge is the alpha of the background at a soft scroll edge's bar,
|
||||
// AppKit's; hardEdgeBlur is how much a hard edge blurs, in DIPs: AppKit's
|
||||
// Gaussian of radius 6 spreads an edge 30 pixels from 10% to 90% at a
|
||||
// scale of 2, as the renderers' does at 6.4.
|
||||
const (
|
||||
softEdge = 0.85
|
||||
hardEdgeBlur = 6.4
|
||||
)
|
||||
|
||||
// toned returns c saturated by saturation around its luminance, with
|
||||
// offset added, clamped, as AppKit's color matrices tone.
|
||||
func toned(c [3]float32, saturation, offset float32) [3]float32 {
|
||||
l := 0.2126*c[0] + 0.7152*c[1] + 0.0722*c[2]
|
||||
for i := range c {
|
||||
c[i] = min(max(l+(c[i]-l)*saturation+offset, 0), 1)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// fillGradient fills box, rounded by radii, with g: as one rounded
|
||||
// rectangle when its corners are alike, else as a path.
|
||||
func fillGradient(p *ui.Painter, box ui.Rect, radii [4]float32, g ui.LinearGradient) {
|
||||
if radii[0] == radii[1] && radii[1] == radii[2] && radii[2] == radii[3] {
|
||||
p.FillGradient(box, g, radii[0])
|
||||
return
|
||||
}
|
||||
var path ui.Path
|
||||
x0, y0, x1, y1 := box.X, box.Y, box.X+box.W, box.Y+box.H
|
||||
// A cubic Bézier's control points for a quarter circle are k of the
|
||||
// radius from its ends.
|
||||
const k = 0.5523
|
||||
tl, tr, br, bl := radii[0], radii[1], radii[2], radii[3]
|
||||
path.MoveTo(x0+tl, y0).LineTo(x1-tr, y0)
|
||||
path.CubeTo(x1-tr+k*tr, y0, x1, y0+tr-k*tr, x1, y0+tr).LineTo(x1, y1-br)
|
||||
path.CubeTo(x1, y1-br+k*br, x1-br+k*br, y1, x1-br, y1).LineTo(x0+bl, y1)
|
||||
path.CubeTo(x0+bl-k*bl, y1, x0, y1-bl+k*bl, x0, y1-bl).LineTo(x0, y0+tl)
|
||||
path.CubeTo(x0, y0+tl-k*tl, x0+tl-k*tl, y0, x0+tl, y0).Close()
|
||||
p.FillPathGradient(&path, g)
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// edgeOver returns a tester of a window of black content 200 DIPs wide
|
||||
// and 100 high, with the scroll edge e over its top 40 DIPs, or its
|
||||
// bottom 40.
|
||||
func edgeOver(e ScrollEdge) *ui.Tester {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Children(func() {
|
||||
b := ui.Box(c).Absolute().Left(0).Right(0).Height(40).Material(e)
|
||||
if e.Bottom {
|
||||
b.Bottom(0)
|
||||
} else {
|
||||
b.Top(0)
|
||||
}
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 200, 100)
|
||||
tt.SetScale(2)
|
||||
return tt
|
||||
}
|
||||
|
||||
func TestSoftScrollEdge(t *testing.T) {
|
||||
// The background fades over the content from 85% at the top to
|
||||
// nothing at the edge's bottom, linearly.
|
||||
img := edgeOver(ScrollEdge{}).Image()
|
||||
for _, c := range []struct{ y, want int }{{0, 215}, {40, 108}, {79, 3}, {90, 0}} {
|
||||
if got := pixelAt(img, 100, c.y)[0]; got < c.want-3 || got > c.want+3 {
|
||||
t.Errorf("row %d is %d, not about %d", c.y, got, c.want)
|
||||
}
|
||||
}
|
||||
// From the bottom, the other way.
|
||||
img = edgeOver(ScrollEdge{Bottom: true}).Image()
|
||||
if top, bottom := pixelAt(img, 100, 121)[0], pixelAt(img, 100, 199)[0]; top > 6 || bottom < 210 {
|
||||
t.Errorf("from the bottom, the edge goes from %d to %d", top, bottom)
|
||||
}
|
||||
// Its own background, dark.
|
||||
img = edgeOver(ScrollEdge{Background: ui.RGB(0, 0, 200)}).Image()
|
||||
if p := pixelAt(img, 100, 0); p[0] != 0 || p[2] < 165 || p[2] > 172 {
|
||||
t.Errorf("over a blue background, the top is %v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHardScrollEdge(t *testing.T) {
|
||||
// Black content, toned to 0.03, under 82.45% of white: 212, evenly,
|
||||
// over a hairline of black at 10%.
|
||||
tt := edgeOver(ScrollEdge{Hard: true})
|
||||
img := tt.Image()
|
||||
for _, y := range []int{2, 40, 77} {
|
||||
if got := pixelAt(img, 100, y)[0]; got < 210 || got > 213 {
|
||||
t.Errorf("row %d is %d", y, got)
|
||||
}
|
||||
}
|
||||
if got := pixelAt(img, 100, 80)[0]; got != 0 {
|
||||
t.Errorf("the hairline over black is %d", got)
|
||||
}
|
||||
// Over white, the hairline shows: 90% of it.
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255)).Children(func() {
|
||||
ui.Box(c).Absolute().Left(0).Right(0).Top(0).Height(40).Material(ScrollEdge{Hard: true})
|
||||
})
|
||||
}
|
||||
wt := ui.NewTester(view, 200, 100)
|
||||
wt.SetScale(2)
|
||||
if got := pixelAt(wt.Image(), 100, 80)[0]; got < 228 || got > 231 {
|
||||
t.Errorf("the hairline over white is %d", got)
|
||||
}
|
||||
if got := pixelAt(wt.Image(), 100, 81)[0]; got != 255 {
|
||||
t.Errorf("below the hairline, white is %d", got)
|
||||
}
|
||||
// In dark mode, the hairline is white at 7%, over the theme's dark
|
||||
// background.
|
||||
wt.SetDark(true)
|
||||
if got := pixelAt(wt.Image(), 100, 80)[0]; got != 255 {
|
||||
t.Errorf("the dark hairline over white is %d", got)
|
||||
}
|
||||
if got := pixelAt(wt.Image(), 100, 40)[0]; got > 80 {
|
||||
t.Errorf("a dark hard edge over white is %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScrollEdgeString(t *testing.T) {
|
||||
if s := (ScrollEdge{}).String(); s != "scroll-edge soft" {
|
||||
t.Errorf("String: %q", s)
|
||||
}
|
||||
if s := (ScrollEdge{Hard: true, Bottom: true}).String(); s != "scroll-edge hard bottom" {
|
||||
t.Errorf("String: %q", s)
|
||||
}
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// The shaders of the glass and of the blur, one for each renderer, which
|
||||
// go generate compiles ahead of time where it can (shaders_darwin.go,
|
||||
// shaders_windows.go).
|
||||
var (
|
||||
//go:embed glass.metal
|
||||
metalSource string
|
||||
//go:embed glass.hlsl
|
||||
hlslSource string
|
||||
//go:embed glass.glsl
|
||||
glslSource string
|
||||
//go:embed blur.metal
|
||||
blurMetalSource string
|
||||
//go:embed blur.hlsl
|
||||
blurHLSLSource string
|
||||
//go:embed blur.glsl
|
||||
blurGLSLSource string
|
||||
)
|
||||
|
||||
// Effect is the glass's effect, which the renderers draw (see
|
||||
// scene.Effect): what is behind the pane, blurred, sampled within the
|
||||
// bezel where the curved surface refracts it (lens), mapped from its
|
||||
// lightness (tone), tinted, and lit along the rim.
|
||||
var Effect = &scene.Effect{
|
||||
Name: "glass",
|
||||
Backdrop: true,
|
||||
Metal: scene.EffectCode{Source: metalSource, Compiled: metalLibrary, Sum: metalSum},
|
||||
HLSL: scene.EffectCode{Source: hlslSource, Compiled: hlslBytecode, Sum: hlslSum},
|
||||
GLSL: glslSource,
|
||||
Pixels: func() scene.EffectPixels { return &pixels{} },
|
||||
}
|
||||
|
||||
// blurEffect is a level of a blur (blurLevel), which the renderers draw:
|
||||
// what is behind it, blurred, by how much the level shows at each pixel,
|
||||
// along the mask.
|
||||
var blurEffect = &scene.Effect{
|
||||
Name: "blur",
|
||||
Backdrop: true,
|
||||
Metal: scene.EffectCode{Source: blurMetalSource, Compiled: blurMetalLibrary, Sum: blurMetalSum},
|
||||
HLSL: scene.EffectCode{Source: blurHLSLSource, Compiled: blurBytecode, Sum: blurHLSLSum},
|
||||
GLSL: blurGLSLSource,
|
||||
Pixels: func() scene.EffectPixels { return &blurPixels{} },
|
||||
}
|
||||
|
||||
// material is a pane of glass, in device pixels: the effect's parameters.
|
||||
//
|
||||
// - blur is the standard deviation of the blur of what shows through;
|
||||
// - bezel is how far from the edge the surface curves, and refraction
|
||||
// how far, at most, the bezel bends what shows through toward the
|
||||
// middle (lens), which mirrors what is just inside the bezel into it;
|
||||
// - low and high are the lightness that black and white, blurred, show
|
||||
// at, along a curve bent by curve (1 for a straight line), and
|
||||
// saturation multiplies how far colors are from their lightness;
|
||||
// - tint colors the glass, straight RGBA, by its alpha, and wideTint
|
||||
// is it in extended sRGB, for a target that keeps colors outside the
|
||||
// sRGB gamut (ui.Painter.EffectColor);
|
||||
// - rim is how much the rim is lit, within about rimWidth of the edge:
|
||||
// the more the edge faces the light coming from the angle light
|
||||
// (radians, clockwise from the right, the opposite side alike), the
|
||||
// lighter, and the less, the darker.
|
||||
type material struct {
|
||||
blur float32
|
||||
bezel, refraction float32
|
||||
low, high, curve, saturation float32
|
||||
tint, wideTint [4]float32
|
||||
rim, rimWidth, light float32
|
||||
}
|
||||
|
||||
// params returns the effect's parameters, as its shaders read them: p0
|
||||
// the bezel, the refraction, the rim and its width; p1 the tint; p2 the
|
||||
// low, high, curve and saturation; p3 the direction of the light; p4 the
|
||||
// wide tint, which only the Metal shader reads.
|
||||
func (m *material) params() [5][4]float32 {
|
||||
return [5][4]float32{
|
||||
{m.bezel, m.refraction, m.rim, m.rimWidth},
|
||||
m.tint,
|
||||
{m.low, m.high, m.curve, m.saturation},
|
||||
{float32(math.Cos(float64(m.light))), float32(math.Sin(float64(m.light)))},
|
||||
m.wideTint,
|
||||
}
|
||||
}
|
||||
|
||||
// lens returns how far, as a fraction of the refraction, the glass bends
|
||||
// what shows through it t pixels inside its edge, within a bezel of width
|
||||
// bezel: the surface's height there is Apple's squircle profile,
|
||||
// ⁴√(1-(1-x)⁴) for x = t/bezel, and light coming straight down bends as it
|
||||
// enters glass of refractive index 1.5 (Snell's law), by the tangent of
|
||||
// the angle it turns, which is √5/2 at most, where the surface is upright.
|
||||
func lens(t, bezel float32) float32 {
|
||||
if bezel <= 0 || t >= bezel {
|
||||
return 0
|
||||
}
|
||||
u := 1 - max(t, 0)/bezel
|
||||
v := 1 - u*u*u*u
|
||||
// The surface's slope is b/a: the sine and cosine of its angle are
|
||||
// b and a over their hypotenuse.
|
||||
a := sqrt(v * sqrt(v))
|
||||
b := u * u * u
|
||||
n := sqrt(a*a + b*b)
|
||||
s, c := b/n, a/n
|
||||
st := s / 1.5
|
||||
ct := sqrt(1 - st*st)
|
||||
return (s*ct - c*st) / (c*ct + s*st) / 1.1180340
|
||||
}
|
||||
|
||||
// normal returns the direction away from the middle of a rounded rectangle
|
||||
// at p, the direction of its edge's normal there, smoothed: as of the
|
||||
// rectangle with corners half again as round, so that it turns gradually
|
||||
// around a corner. It is 0 on the lines through the middle, where two
|
||||
// sides are as near.
|
||||
func normal(px, py float32, r scene.Rect, radii [4]float32) (gx, gy float32) {
|
||||
hx, hy := r.W/2, r.H/2
|
||||
cx, cy := px-r.X-hx, py-r.Y-hy
|
||||
var rad float32
|
||||
switch {
|
||||
case cx < 0 && cy < 0:
|
||||
rad = radii[0]
|
||||
case cx >= 0 && cy < 0:
|
||||
rad = radii[1]
|
||||
case cx >= 0:
|
||||
rad = radii[2]
|
||||
default:
|
||||
rad = radii[3]
|
||||
}
|
||||
rad = min(rad*1.5, hx, hy)
|
||||
qx, qy := abs(cx)-(hx-rad), abs(cy)-(hy-rad)
|
||||
if qx > 0 || qy > 0 {
|
||||
mx, my := max(qx, 0), max(qy, 0)
|
||||
n := sqrt(mx*mx + my*my)
|
||||
return sign(cx) * mx / n, sign(cy) * my / n
|
||||
}
|
||||
if qx > qy {
|
||||
return sign(cx), 0
|
||||
}
|
||||
return 0, sign(cy)
|
||||
}
|
||||
|
||||
// tone maps the premultiplied color c behind the glass to the glass's own,
|
||||
// by its lightness, the luminance of its sRGB components, along the
|
||||
// material's curve, and keeping its colors' distance from it.
|
||||
func tone(c [3]float32, m *material) [3]float32 {
|
||||
l := 0.2126*c[0] + 0.7152*c[1] + 0.0722*c[2]
|
||||
return toneAt(c, l, m.low+(m.high-m.low)*(1-pow(max(1-l, 0), m.curve)), m)
|
||||
}
|
||||
|
||||
func toneAt(c [3]float32, l, t float32, m *material) [3]float32 {
|
||||
k := (m.high - m.low) * m.saturation
|
||||
for i := range c {
|
||||
c[i] = min(max(t+(c[i]-l)*k, 0), 1)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func sqrt(v float32) float32 { return float32(math.Sqrt(float64(v))) }
|
||||
func pow(x, y float32) float32 { return float32(math.Pow(float64(x), float64(y))) }
|
||||
|
||||
func abs(v float32) float32 {
|
||||
if v < 0 {
|
||||
return -v
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func sign(v float32) float32 {
|
||||
switch {
|
||||
case v > 0:
|
||||
return 1
|
||||
case v < 0:
|
||||
return -1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
// The glass's effect in GLSL (see scene.Effect), as glass.metal is in
|
||||
// Metal Shading Language and pixels.go draws it on the CPU.
|
||||
|
||||
float glassLens(float t, float bezel) {
|
||||
if (bezel <= 0.0 || t >= bezel) {
|
||||
return 0.0;
|
||||
}
|
||||
float u = 1.0 - max(t, 0.0) / bezel;
|
||||
float v = 1.0 - u * u * u * u;
|
||||
float a = sqrt(v * sqrt(v));
|
||||
float b = u * u * u;
|
||||
float n = sqrt(a * a + b * b);
|
||||
float s = b / n;
|
||||
float c = a / n;
|
||||
float st = s / 1.5;
|
||||
float ct = sqrt(1.0 - st * st);
|
||||
return (s * ct - c * st) / (c * ct + s * st) / 1.1180340;
|
||||
}
|
||||
|
||||
vec2 glassNormal(vec2 p, vec4 rect, vec4 radii) {
|
||||
vec2 h = rect.zw * 0.5;
|
||||
vec2 q = p - rect.xy - h;
|
||||
float r = q.x < 0.0 ? (q.y < 0.0 ? radii.x : radii.w) : (q.y < 0.0 ? radii.y : radii.z);
|
||||
r = min(r * 1.5, min(h.x, h.y));
|
||||
vec2 a = abs(q) - (h - r);
|
||||
if (a.x > 0.0 || a.y > 0.0) {
|
||||
vec2 m = max(a, vec2(0.0));
|
||||
return sign(q) * m / sqrt(m.x * m.x + m.y * m.y);
|
||||
}
|
||||
return a.x > a.y ? vec2(sign(q.x), 0.0) : vec2(0.0, sign(q.y));
|
||||
}
|
||||
|
||||
vec3 glassTone(vec3 c, vec4 tone) {
|
||||
float l = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
|
||||
float t = tone.x + (tone.y - tone.x) * (1.0 - pow(max(1.0 - l, 0.0), tone.z));
|
||||
float k = (tone.y - tone.x) * tone.w;
|
||||
return clamp(t + (c - l) * k, 0.0, 1.0);
|
||||
}
|
||||
|
||||
vec4 effect(vec2 p, Effect e) {
|
||||
float t = max(-sdRoundRect(p, e.rect, e.radii), 0.0);
|
||||
float bezel = e.p0.x;
|
||||
float rimWidth = e.p0.w;
|
||||
vec2 n = vec2(0.0);
|
||||
if (t < bezel || t < 3.0 * rimWidth) {
|
||||
n = glassNormal(p, e.rect, e.radii);
|
||||
}
|
||||
vec2 q = p;
|
||||
if (t < bezel) {
|
||||
q -= n * (e.p0.y * glassLens(t, bezel));
|
||||
}
|
||||
vec3 c = glassTone(sampleBackdrop(e, q), e.p2);
|
||||
c += (e.p1.rgb - c) * e.p1.a;
|
||||
if (e.p0.z > 0.0 && t < 3.0 * rimWidth) {
|
||||
float r = t / rimWidth;
|
||||
float a = e.p0.z * exp(-r * r);
|
||||
float l = abs(n.x * e.p3.x + n.y * e.p3.y);
|
||||
c += (l - c) * a;
|
||||
}
|
||||
return vec4(c, 1.0);
|
||||
}
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
// Package glass draws Liquid Glass in native UI, as macOS 26 and later
|
||||
// draw it (AppKit's NSGlassEffectView), on every platform: what the
|
||||
// elements under it painted shows through, blurred, bent near its edges as
|
||||
// through the rim of a lens, and lit along its hairline rim.
|
||||
// MyGo's renderers draw it with shaders of this package, on the GPU or the
|
||||
// CPU, so it looks the same everywhere.
|
||||
//
|
||||
// ui.Row(c).Padding(8, 16).Radius(22).Material(glass.Glass{})
|
||||
//
|
||||
// ScrollEdge is macOS's scroll edge effect, which content scrolling under
|
||||
// a bar fades or frosts under, and Blur blurs what is under an element
|
||||
// without the glass, evenly or fading along a gradient.
|
||||
package glass
|
||||
|
||||
//go:generate go run ./internal/gen
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// Glass is Liquid Glass, a ui.Material: Element.Material fills an element
|
||||
// with it, in place of a background, shaped by its Radius. What was
|
||||
// painted under the element shows through it, as content that scrolls
|
||||
// under a bar placed over it with Absolute, and other glass.
|
||||
type Glass struct {
|
||||
// Style is the glass's material.
|
||||
Style Style
|
||||
// Tint colors the glass, by its alpha, as for a prominent button: an
|
||||
// opaque tint lets a little of the glass show, as AppKit's does.
|
||||
Tint ui.Color
|
||||
// Interactive makes the glass grow a little while the element is
|
||||
// pressed, as AppKit's interactive glass does.
|
||||
Interactive bool
|
||||
// Native asks for the system's glass where the window has it (macOS
|
||||
// 26 and later), drawn under the content: it samples what is under the
|
||||
// window's surface, as a ui.WebView's page, not the elements the frame
|
||||
// painted. Elsewhere, and with Reduce Transparency, the shader draws
|
||||
// it.
|
||||
Native bool
|
||||
// Clarity, from 0 to 1, makes panes as large as sidebars clearer,
|
||||
// the content under them reading through: 0, the default, is
|
||||
// macOS's material, as frosty as a control's; 0.5 blurs half as much
|
||||
// and lightens (or darkens) less; 1 is nearly clear. Panes up to 100
|
||||
// DIPs keep their material whatever it is; it takes full effect from
|
||||
// 200. On Clear glass, which barely tones already, it only lights the
|
||||
// rim and curves the bezel.
|
||||
Clarity float32
|
||||
// hover follows the pointer over an interactive glass, from 0 to 1.
|
||||
hover float32
|
||||
}
|
||||
|
||||
// pressKey is the key of an interactive glass's animation.
|
||||
type pressKey struct{}
|
||||
|
||||
// hoverKey is the key of an interactive glass's hover animation.
|
||||
type hoverKey struct{}
|
||||
|
||||
// pressed is an interactive glass as its element is built: how far it
|
||||
// has grown, from 0 to 1, and how far the pointer hovers it.
|
||||
type pressed struct {
|
||||
Glass
|
||||
grow, hover float32
|
||||
}
|
||||
|
||||
// BuildMaterial follows the press and hover of an interactive glass's
|
||||
// element: the glass grows as it is pressed, and lights its rim as the
|
||||
// pointer enters it, within 150 ms, as AppKit's does.
|
||||
func (g Glass) BuildMaterial(e ui.Element) ui.Material {
|
||||
if !g.Interactive {
|
||||
return g
|
||||
}
|
||||
target := float32(0)
|
||||
if e.Pressed() {
|
||||
target = 1
|
||||
}
|
||||
hover := float32(0)
|
||||
if e.Hovered() {
|
||||
hover = 1
|
||||
}
|
||||
return pressed{g, e.Animate(pressKey{}, target, 150*time.Millisecond),
|
||||
e.Animate(hoverKey{}, hover, 120*time.Millisecond)}
|
||||
}
|
||||
|
||||
// Style is the material of Glass.
|
||||
type Style uint8
|
||||
|
||||
const (
|
||||
// Regular frosts what shows through and lightens it, or darkens it in
|
||||
// dark mode, so that what is on the glass reads over anything: for
|
||||
// bars, buttons and panels. Larger panes are frostier.
|
||||
Regular Style = iota
|
||||
// Clear barely blurs nor tones what shows through, for glass over
|
||||
// photos and video, where what is on it brings its own contrast.
|
||||
Clear
|
||||
)
|
||||
|
||||
// NativeGlass asks for the system's glass, which ui places under the
|
||||
// surface, where it has Liquid Glass.
|
||||
func (g Glass) NativeGlass() (ui.NativeGlassSpec, bool) {
|
||||
if !g.Native {
|
||||
return ui.NativeGlassSpec{}, false
|
||||
}
|
||||
style := 0
|
||||
if g.Style == Clear {
|
||||
style = 1
|
||||
}
|
||||
return ui.NativeGlassSpec{Style: style, Tint: g.Tint}, true
|
||||
}
|
||||
|
||||
// PaintMaterial paints the glass over box, rounded by radii.
|
||||
func (g Glass) PaintMaterial(p *ui.Painter, box ui.Rect, radii [4]float32) {
|
||||
if g.Native && p.NativeGlassSupported() && !p.Preferences().ReduceTransparency {
|
||||
// The system's glass, under the surface, shows through this hole.
|
||||
p.Hole(box, radii)
|
||||
return
|
||||
}
|
||||
paint(p, box, radii, g)
|
||||
}
|
||||
|
||||
// PaintMaterial paints the glass grown by how far it is pressed: as
|
||||
// macOS 27's, measured from NSGlassEffectView, by about 1.1 DIPs left and
|
||||
// right and 0.45 DIPs above and below, whatever its size. AppKit stretches
|
||||
// the content too, a pixel or so, which the children here are not.
|
||||
func (pressed) NativeGlass() (ui.NativeGlassSpec, bool) {
|
||||
return ui.NativeGlassSpec{}, false
|
||||
}
|
||||
|
||||
func (g pressed) PaintMaterial(p *ui.Painter, box ui.Rect, radii [4]float32) {
|
||||
dx, dy := 1.1*g.grow, 0.45*g.grow
|
||||
box = ui.Rect{X: box.X - dx, Y: box.Y - dy, W: box.W + 2*dx, H: box.H + 2*dy}
|
||||
for i := range radii {
|
||||
if radii[i] > 0 {
|
||||
radii[i] += dy
|
||||
}
|
||||
}
|
||||
g.Glass.hover = g.hover
|
||||
paint(p, box, radii, g.Glass)
|
||||
}
|
||||
|
||||
// String describes the glass, as the inspector shows it.
|
||||
func (g Glass) String() string {
|
||||
s := "glass"
|
||||
if g.Style == Clear {
|
||||
s += " clear"
|
||||
}
|
||||
if g.Tint.A > 0 {
|
||||
s += fmt.Sprintf(" tint(#%02x%02x%02x%02x)", g.Tint.R, g.Tint.G, g.Tint.B, g.Tint.A)
|
||||
}
|
||||
if g.Native {
|
||||
s += " native"
|
||||
}
|
||||
if g.Interactive {
|
||||
s += " interactive"
|
||||
}
|
||||
if g.Clarity > 0 {
|
||||
s += fmt.Sprintf(" clarity(%g)", g.Clarity)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Paint paints a pane of glass shaped as r rounded by radius, in a
|
||||
// drawing (Element.Draw), over what the painter painted before it.
|
||||
func Paint(p *ui.Painter, r ui.Rect, radius float32, g Glass) {
|
||||
paint(p, r, [4]float32{radius, radius, radius, radius}, g)
|
||||
}
|
||||
|
||||
// paint paints a pane of glass over box, rounded by radii.
|
||||
//
|
||||
// Its material follows macOS 27's, measured from NSGlassEffectView: the
|
||||
// regular one maps black to 54% and white to 100% in light mode, and to
|
||||
// 15% and 51% in dark mode, the clear one adds an eighth; larger panes
|
||||
// blur more, up to 10 DIPs; the bezel curves the last 36 DIPs of the
|
||||
// pane, at most half of it, and bends what shows through by up to 1.6
|
||||
// times that, mirroring what is inside it, as AppKit's do; light comes
|
||||
// from above and below, along a rim a pixel wide, and the pane casts no
|
||||
// shadow, as NSGlassEffectView's and the glass bezel's do not. Panes
|
||||
// large as sidebars and inspectors are clearer by the glass's Clarity
|
||||
// (paneMaterial).
|
||||
func paint(p *ui.Painter, box ui.Rect, radii [4]float32, g Glass) {
|
||||
if box.W <= 0 || box.H <= 0 {
|
||||
return
|
||||
}
|
||||
if p.Preferences().ReduceTransparency {
|
||||
paintOpaque(p, box, radii, g)
|
||||
return
|
||||
}
|
||||
mat := paneMaterial(min(box.W, box.H), p.Scale(), g.Clarity, g.Style == Clear, p.Theme().Dark)
|
||||
if p.Preferences().HighContrast {
|
||||
mat.rim = min(mat.rim+0.15, 1)
|
||||
mat.rimWidth = max(mat.rimWidth, 1.5)
|
||||
}
|
||||
if g.hover > 0 {
|
||||
// As the pointer enters an interactive glass, its rim lights and
|
||||
// its surface lifts a little.
|
||||
mat.rim = min(mat.rim+0.18*g.hover, 1)
|
||||
mat.low = min(mat.low+0.02*g.hover, 1)
|
||||
mat.high = min(mat.high+0.02*g.hover, 1)
|
||||
}
|
||||
if g.Tint.A > 0 {
|
||||
mat.tint, mat.wideTint = p.EffectColor(g.Tint)
|
||||
a := 0.88 * (1 + 0.1*g.hover)
|
||||
mat.tint[3] = min(mat.tint[3]*a, 1)
|
||||
mat.wideTint[3] = min(mat.wideTint[3]*a, 1)
|
||||
}
|
||||
p.Effect(Effect, box, radii, mat.blur, mat.params())
|
||||
}
|
||||
|
||||
// paintOpaque paints g as the opaque surface that the desktop asks for
|
||||
// with Reduce Transparency: the theme's surface, or its background for
|
||||
// clear glass, tinted as g is, without blur, refraction or a rim.
|
||||
func paintOpaque(p *ui.Painter, box ui.Rect, radii [4]float32, g Glass) {
|
||||
t := p.Theme()
|
||||
c := t.Surface
|
||||
if g.Style == Clear {
|
||||
c = t.Background
|
||||
}
|
||||
if g.Tint.A > 0 {
|
||||
c = c.Mix(g.Tint, float32(g.Tint.A)/255*0.88)
|
||||
}
|
||||
p.FillRadii(box, radii, c)
|
||||
if p.Preferences().HighContrast {
|
||||
p.Stroke(box, t.Border, max(radii[0], radii[1], radii[2], radii[3]), 1)
|
||||
}
|
||||
}
|
||||
|
||||
// paneMaterial is the material of a pane whose shorter side is m DIPs,
|
||||
// at scale s, of clarity k from 0 to 1, clear or regular, in dark mode or
|
||||
// light. Panes up to 100 DIPs, as controls, keep the measured material;
|
||||
// from 200, as sidebars and inspectors, theirs is clarity's; between, it
|
||||
// eases from one to the other. Clarity goes in two straight steps, each
|
||||
// half of it, from the measured material (frost) to a clearer one (mid),
|
||||
// the content under the pane reading through, and on to one nearly clear
|
||||
// (clear): see paneTone.
|
||||
func paneMaterial(m, s, k float32, clear, dark bool) material {
|
||||
f := min(max((m-100)/100, 0), 1)
|
||||
f = f * f * (3 - 2*f) // smoothstep
|
||||
k = min(max(k, 0), 1)
|
||||
if k != k { // NaN
|
||||
k = 0
|
||||
}
|
||||
at := func(v paneTone) float32 { return v.frost + (v.at(k)-v.frost)*f }
|
||||
bezel := min(at(paneBezel), m/2)
|
||||
mat := material{
|
||||
bezel: bezel * s,
|
||||
refraction: 1.6 * bezel * s,
|
||||
rim: at(paneRim),
|
||||
rimWidth: 1,
|
||||
light: math.Pi / 2,
|
||||
}
|
||||
switch {
|
||||
case clear:
|
||||
mat.blur = s
|
||||
mat.low, mat.high, mat.curve, mat.saturation = 0.125, 1.082, 1, 1
|
||||
case dark:
|
||||
mat.blur = min(max(m*0.035, 1), at(paneBlur)) * s
|
||||
mat.low, mat.high, mat.curve, mat.saturation = at(paneDarkLow), at(paneDarkHigh), 2, 2.2
|
||||
default:
|
||||
mat.blur = min(max(m*0.035, 1), at(paneBlur)) * s
|
||||
mat.low, mat.high, mat.curve, mat.saturation = at(paneLightLow), 1, 1.2, 1
|
||||
}
|
||||
return mat
|
||||
}
|
||||
|
||||
// paneTone is a parameter of a large pane's material at clarity 0
|
||||
// (frost, the measured material's), 0.5 (mid) and 1 (clear).
|
||||
type paneTone struct{ frost, mid, clear float32 }
|
||||
|
||||
// at is the parameter at clarity k, from 0 to 1.
|
||||
func (v paneTone) at(k float32) float32 {
|
||||
if k <= 0.5 {
|
||||
return v.frost + (v.mid-v.frost)*k*2
|
||||
}
|
||||
return v.mid + (v.clear-v.mid)*(k-0.5)*2
|
||||
}
|
||||
|
||||
var (
|
||||
// paneBlur is the most the pane blurs, in DIPs.
|
||||
paneBlur = paneTone{10, 5, 2}
|
||||
// paneLightLow is what black maps to in light mode, white to 1.
|
||||
paneLightLow = paneTone{0.541, 0.35, 0.2}
|
||||
// paneDarkLow and paneDarkHigh are what black and white map to in
|
||||
// dark mode.
|
||||
paneDarkLow = paneTone{0.15, 0.15, 0.1}
|
||||
paneDarkHigh = paneTone{0.51, 0.6, 0.85}
|
||||
// paneRim is how bright the rim is lit.
|
||||
paneRim = paneTone{0.35, 0.5, 0.5}
|
||||
// paneBezel is how wide the bezel curves, in DIPs.
|
||||
paneBezel = paneTone{36, 48, 48}
|
||||
)
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
// The glass's effect in HLSL (see scene.Effect), as glass.metal is in
|
||||
// Metal Shading Language and pixels.go draws it on the CPU.
|
||||
|
||||
float glassLens(float t, float bezel) {
|
||||
if (bezel <= 0 || t >= bezel) {
|
||||
return 0;
|
||||
}
|
||||
float u = 1 - max(t, 0) / bezel;
|
||||
float v = 1 - u * u * u * u;
|
||||
float a = sqrt(v * sqrt(v));
|
||||
float b = u * u * u;
|
||||
float n = sqrt(a * a + b * b);
|
||||
float s = b / n;
|
||||
float c = a / n;
|
||||
float st = s / 1.5;
|
||||
float ct = sqrt(1 - st * st);
|
||||
return (s * ct - c * st) / (c * ct + s * st) / 1.1180340;
|
||||
}
|
||||
|
||||
float2 glassNormal(float2 p, float4 rect, float4 radii) {
|
||||
float2 h = rect.zw * 0.5;
|
||||
float2 q = p - rect.xy - h;
|
||||
float r = q.x < 0 ? (q.y < 0 ? radii.x : radii.w) : (q.y < 0 ? radii.y : radii.z);
|
||||
r = min(r * 1.5, min(h.x, h.y));
|
||||
float2 a = abs(q) - (h - r);
|
||||
float2 sq = float2(sign(q));
|
||||
if (a.x > 0 || a.y > 0) {
|
||||
float2 m = max(a, 0);
|
||||
return sq * m / sqrt(m.x * m.x + m.y * m.y);
|
||||
}
|
||||
return a.x > a.y ? float2(sq.x, 0) : float2(0, sq.y);
|
||||
}
|
||||
|
||||
float3 glassTone(float3 c, float4 tone) {
|
||||
float l = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
|
||||
float t = tone.x + (tone.y - tone.x) * (1 - pow(max(1 - l, 0), tone.z));
|
||||
float k = (tone.y - tone.x) * tone.w;
|
||||
return saturate(t + (c - l) * k);
|
||||
}
|
||||
|
||||
float4 effect(float2 p, Effect e) {
|
||||
float t = max(-sdRoundRect(p, e.rect, e.radii), 0);
|
||||
float bezel = e.p0.x;
|
||||
float rimWidth = e.p0.w;
|
||||
float2 n = float2(0, 0);
|
||||
if (t < bezel || t < 3 * rimWidth) {
|
||||
n = glassNormal(p, e.rect, e.radii);
|
||||
}
|
||||
float2 q = p;
|
||||
if (t < bezel) {
|
||||
q -= n * (e.p0.y * glassLens(t, bezel));
|
||||
}
|
||||
float3 c = glassTone(sampleBackdrop(e, q), e.p2);
|
||||
c += (e.p1.rgb - c) * e.p1.a;
|
||||
if (e.p0.z > 0 && t < 3 * rimWidth) {
|
||||
float r = t / rimWidth;
|
||||
float a = e.p0.z * exp(-r * r);
|
||||
float l = abs(n.x * e.p3.x + n.y * e.p3.y);
|
||||
c += (l - c) * a;
|
||||
}
|
||||
return float4(c, 1);
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
// The glass's effect in Metal Shading Language (see scene.Effect), as
|
||||
// pixels.go draws it on the CPU. The parameters are those of material:
|
||||
// p0 the bezel, the refraction, the rim and its width; p1 the tint; p2 the
|
||||
// low, high, curve and saturation; p3 the light's direction; p4 the tint in
|
||||
// extended sRGB, for a target that keeps colors outside the sRGB gamut.
|
||||
|
||||
// glassLens returns how far, as a fraction of the refraction, the glass
|
||||
// bends what shows through it t pixels inside its edge (lens).
|
||||
float glassLens(float t, float bezel) {
|
||||
if (bezel <= 0.0f || t >= bezel) {
|
||||
return 0.0f;
|
||||
}
|
||||
float u = 1.0f - max(t, 0.0f) / bezel;
|
||||
float v = 1.0f - u * u * u * u;
|
||||
float a = sqrt(v * sqrt(v));
|
||||
float b = u * u * u;
|
||||
float n = sqrt(a * a + b * b);
|
||||
float s = b / n;
|
||||
float c = a / n;
|
||||
float st = s / 1.5f;
|
||||
float ct = sqrt(1.0f - st * st);
|
||||
return (s * ct - c * st) / (c * ct + s * st) / 1.1180340f;
|
||||
}
|
||||
|
||||
// glassNormal returns the direction of the edge's normal at p, smoothed
|
||||
// (normal).
|
||||
float2 glassNormal(float2 p, float4 rect, float4 radii) {
|
||||
float2 h = rect.zw * 0.5f;
|
||||
float2 q = p - rect.xy - h;
|
||||
float r = q.x < 0.0f ? (q.y < 0.0f ? radii.x : radii.w) : (q.y < 0.0f ? radii.y : radii.z);
|
||||
r = min(r * 1.5f, min(h.x, h.y));
|
||||
float2 a = abs(q) - (h - r);
|
||||
if (a.x > 0.0f || a.y > 0.0f) {
|
||||
float2 m = max(a, float2(0.0f));
|
||||
return sign(q) * m / sqrt(m.x * m.x + m.y * m.y);
|
||||
}
|
||||
return a.x > a.y ? float2(sign(q.x), 0.0f) : float2(0.0f, sign(q.y));
|
||||
}
|
||||
|
||||
// glassTone maps the color behind the glass to the glass's (tone).
|
||||
float3 glassTone(float3 c, float4 tone) {
|
||||
float l = 0.2126f * c.r + 0.7152f * c.g + 0.0722f * c.b;
|
||||
float t = tone.x + (tone.y - tone.x) * (1.0f - pow(max(1.0f - l, 0.0f), tone.z));
|
||||
float k = (tone.y - tone.x) * tone.w;
|
||||
return clamp(t + (c - l) * k, 0.0f, 1.0f);
|
||||
}
|
||||
|
||||
float4 effect(float2 p, Effect e, texture2d<float> backdrop) {
|
||||
float t = max(-sdRoundRect(p, e.rect, e.radii), 0.0f);
|
||||
float bezel = e.p0.x;
|
||||
float rimWidth = e.p0.w;
|
||||
float2 n = float2(0.0f);
|
||||
if (t < bezel || t < 3.0f * rimWidth) {
|
||||
n = glassNormal(p, e.rect, e.radii);
|
||||
}
|
||||
float2 q = p;
|
||||
if (t < bezel) {
|
||||
q -= n * (e.p0.y * glassLens(t, bezel));
|
||||
}
|
||||
float3 c = glassTone(sampleBackdrop(backdrop, e, q), e.p2);
|
||||
float4 tint = e.wide ? e.p4 : e.p1;
|
||||
c += (tint.rgb - c) * tint.a;
|
||||
if (e.p0.z > 0.0f && t < 3.0f * rimWidth) {
|
||||
float r = t / rimWidth;
|
||||
float a = e.p0.z * exp(-r * r);
|
||||
float l = abs(n.x * e.p3.x + n.y * e.p3.y);
|
||||
c += (l - c) * a;
|
||||
}
|
||||
return float4(c, 1.0f);
|
||||
}
|
||||
+377
@@ -0,0 +1,377 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"image"
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// pixelAt returns the color of img at (x, y).
|
||||
func pixelAt(img *image.RGBA, x, y int) [3]int {
|
||||
p := img.RGBAAt(x, y)
|
||||
return [3]int{int(p.R), int(p.G), int(p.B)}
|
||||
}
|
||||
|
||||
func TestGlassPaintsOverWhatIsBehind(t *testing.T) {
|
||||
g := Glass{}
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(20, 120, 220)).Children(func() {
|
||||
ui.Row(c).Size(200, 44).Radius(22).Material(g).Children(func() {
|
||||
ui.Text(c, "On glass")
|
||||
})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 300, 100)
|
||||
tt.SetScale(2)
|
||||
if !tt.HasText("On glass") {
|
||||
t.Error("the glass's children did not paint")
|
||||
}
|
||||
// The glass lightens the blue behind it, which shows through.
|
||||
light := pixelAt(tt.Image(), 300, 70)
|
||||
if light[0] < 100 || light[2] < light[0] {
|
||||
t.Errorf("light glass over blue is %v", light)
|
||||
}
|
||||
tt.SetDark(true)
|
||||
if dark := pixelAt(tt.Image(), 300, 70); dark[2] >= light[2] || dark[0] >= light[0] {
|
||||
t.Errorf("dark glass over blue is %v, not darker than light glass's %v", dark, light)
|
||||
}
|
||||
tt.SetDark(false)
|
||||
g.Style = Clear
|
||||
tt.Frame()
|
||||
if clear := pixelAt(tt.Image(), 300, 70); clear[0] >= light[0] {
|
||||
t.Errorf("clear glass over blue is %v, not clearer than regular glass's %v", clear, light)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInteractiveGlassGrowsWhilePressed(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Children(func() {
|
||||
ui.Box(c).Absolute().Left(50).Top(50).Size(200, 100).Radius(20).Material(Glass{Interactive: true})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 300, 200)
|
||||
tt.SetScale(2)
|
||||
// It grows at once.
|
||||
tt.SetPreferences(ui.Preferences{ReduceMotion: true})
|
||||
// The pixel left of the glass's left edge, in the middle.
|
||||
outside := func() int { return pixelAt(tt.Image(), 99, 200)[0] }
|
||||
before := outside()
|
||||
tt.Press(150, 100)
|
||||
tt.Frame()
|
||||
if grown := outside(); grown <= before+50 {
|
||||
t.Errorf("pressed, the pixel left of the glass is %d, as before (%d)", grown, before)
|
||||
}
|
||||
tt.Release(150, 100)
|
||||
tt.Frame()
|
||||
if after := outside(); after != before {
|
||||
t.Errorf("after the release, the pixel left of the glass is %d, not %d", after, before)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInteractiveGlassLightsOnHover(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Children(func() {
|
||||
ui.Box(c).Absolute().Left(40).Top(30).Size(240, 100).Radius(20).Material(Glass{Interactive: true})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 320, 160)
|
||||
tt.SetScale(2)
|
||||
tt.SetPreferences(ui.Preferences{ReduceMotion: true})
|
||||
tt.Frame()
|
||||
rim := func() int { return pixelAt(tt.Image(), 320, 62)[0] }
|
||||
before := rim()
|
||||
// The pointer enters the glass: its top rim lights.
|
||||
tt.Move(160, 80)
|
||||
tt.Frame()
|
||||
if hovered := rim(); hovered <= before {
|
||||
t.Errorf("the rim is %v while hovered, not lighter than %v", hovered, before)
|
||||
}
|
||||
// Leaving it restores the rim.
|
||||
tt.Move(10, 10)
|
||||
tt.Frame()
|
||||
if after := rim(); after != before {
|
||||
t.Errorf("the rim is %v after the pointer left, not %v", after, before)
|
||||
}
|
||||
}
|
||||
|
||||
// Panes close together merge into one surface; far apart, they do not.
|
||||
func TestGroupMergesNearPanes(t *testing.T) {
|
||||
gap := float32(8)
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Children(func() {
|
||||
g := NewGroup(c)
|
||||
g.Radius = 22
|
||||
g.Gap(gap).Children(func() {
|
||||
g.Pane(ui.Box(c).Size(80, 44))
|
||||
g.Pane(ui.Box(c).Size(80, 44))
|
||||
})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 320, 100)
|
||||
tt.SetScale(2)
|
||||
// The first pane ends at 80, the second starts at 88: their gap's
|
||||
// middle is 84, which the glass bridges.
|
||||
if p := pixelAt(tt.Image(), 168, 44); p[0] < 30 {
|
||||
t.Errorf("the gap between close panes is %v, not glass", p)
|
||||
}
|
||||
// Far apart, nothing bridges the gap.
|
||||
gap = 40
|
||||
tt.Frame()
|
||||
if p := pixelAt(tt.Image(), 200, 44); p[0] > 10 {
|
||||
t.Errorf("the gap between far panes is %v, not the background", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaintInDrawing(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
Paint(p, ui.Rect{X: 20, Y: 20, W: 100, H: 60}, 20, Glass{})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 200, 120)
|
||||
// Light glass over black is mid gray.
|
||||
if g := pixelAt(tt.Image(), 70, 50); g[0] < 100 || g[0] > 180 {
|
||||
t.Errorf("light glass over black is %v", g)
|
||||
}
|
||||
}
|
||||
|
||||
func TestString(t *testing.T) {
|
||||
if s := (Glass{Style: Clear, Tint: ui.RGB(1, 2, 3), Interactive: true}).String(); s != "glass clear tint(#010203ff) interactive" {
|
||||
t.Errorf("String: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// With Reduce Transparency, a glass pane, a blur and a scroll edge are
|
||||
// opaque: the theme's surfaces, not what is behind them.
|
||||
func TestReduceTransparency(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(20, 120, 220)).Children(func() {
|
||||
ui.Box(c).Absolute().Left(50).Top(20).Size(200, 60).Radius(12).Material(Glass{})
|
||||
ui.Box(c).Absolute().Left(50).Top(100).Size(200, 40).Radius(8).Material(ScrollEdge{Hard: true})
|
||||
ui.Box(c).Absolute().Left(50).Top(160).Size(200, 40).Radius(8).Material(Blur{Radius: 8})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 320, 220)
|
||||
tt.SetScale(2)
|
||||
glassAt := func() [3]int { return pixelAt(tt.Image(), 300, 100) }
|
||||
before := glassAt()
|
||||
if before[0] > 200 && before[1] > 200 {
|
||||
t.Fatalf("glass before Reduce Transparency is already the surface: %v", before)
|
||||
}
|
||||
tt.SetPreferences(ui.Preferences{ReduceTransparency: true})
|
||||
tt.Frame()
|
||||
theme := ui.LightTheme()
|
||||
surface := [3]int{int(theme.Surface.R), int(theme.Surface.G), int(theme.Surface.B)}
|
||||
background := [3]int{int(theme.Background.R), int(theme.Background.G), int(theme.Background.B)}
|
||||
near := func(got, want [3]int) bool {
|
||||
for i := range got {
|
||||
if got[i] < want[i]-2 || got[i] > want[i]+2 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
if got := glassAt(); !near(got, surface) {
|
||||
t.Errorf("glass is %v, not the opaque surface %v", got, surface)
|
||||
}
|
||||
if got := pixelAt(tt.Image(), 300, 240); !near(got, background) {
|
||||
t.Errorf("scroll edge is %v, not the background %v", got, background)
|
||||
}
|
||||
if got := pixelAt(tt.Image(), 300, 360); !near(got, background) {
|
||||
t.Errorf("blur is %v, not the background %v", got, background)
|
||||
}
|
||||
// The desktop's setting back off restores the backdrop.
|
||||
tt.SetPreferences(ui.Preferences{})
|
||||
tt.Frame()
|
||||
if after := glassAt(); near(after, surface) {
|
||||
t.Errorf("glass stayed opaque after Reduce Transparency: %v", after)
|
||||
}
|
||||
}
|
||||
|
||||
// High Contrast lights the glass's rim more.
|
||||
func TestHighContrastGlass(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Children(func() {
|
||||
ui.Box(c).Absolute().Left(40).Top(30).Size(240, 100).Radius(20).Material(Glass{})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 320, 160)
|
||||
tt.SetScale(2)
|
||||
tt.Frame()
|
||||
normal := pixelAt(tt.Image(), 320, 62)
|
||||
tt.SetPreferences(ui.Preferences{HighContrast: true})
|
||||
tt.Frame()
|
||||
contrast := pixelAt(tt.Image(), 320, 62)
|
||||
if contrast[0] <= normal[0] {
|
||||
t.Errorf("the rim is %v with high contrast, not lighter than %v", contrast, normal)
|
||||
}
|
||||
}
|
||||
|
||||
// Panes up to 100 DIPs, as controls, keep the measured material,
|
||||
// whatever the clarity; from 200, as sidebars, theirs is the clarity's;
|
||||
// between, it eases from one to the other.
|
||||
func TestPaneMaterial(t *testing.T) {
|
||||
near := func(a, b float32) bool { return a-b < 1e-5 && b-a < 1e-5 }
|
||||
for _, k := range []float32{0, 0.25, 0.5, 1} {
|
||||
for _, m := range []float32{20, 44, 72, 100} {
|
||||
for _, s := range []float32{1, 2} {
|
||||
bezel := min(36, m/2)
|
||||
blur := min(max(m*0.035, 1), 10) * s
|
||||
light := paneMaterial(m, s, k, false, false)
|
||||
if light.blur != blur || light.bezel != bezel*s || light.refraction != 1.6*bezel*s || light.rim != 0.35 ||
|
||||
light.low != 0.541 || light.high != 1 {
|
||||
t.Errorf("light %v DIPs at %vx, clarity %v: %+v", m, s, k, light)
|
||||
}
|
||||
dark := paneMaterial(m, s, k, false, true)
|
||||
if dark.blur != blur || dark.rim != 0.35 || dark.low != 0.15 || dark.high != 0.51 {
|
||||
t.Errorf("dark %v DIPs at %vx, clarity %v: %+v", m, s, k, dark)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, m := range []float32{200, 300, 900} {
|
||||
light, dark := paneMaterial(m, 2, 0.5, false, false), paneMaterial(m, 2, 0.5, false, true)
|
||||
if !near(light.blur, 10) || !near(light.bezel, 96) || !near(light.rim, 0.5) || !near(light.low, 0.35) || light.high != 1 {
|
||||
t.Errorf("light %v DIPs: %+v", m, light)
|
||||
}
|
||||
if !near(dark.blur, 10) || !near(dark.high, 0.6) || dark.low != 0.15 || !near(dark.rim, 0.5) {
|
||||
t.Errorf("dark %v DIPs: %+v", m, dark)
|
||||
}
|
||||
}
|
||||
// Between, every parameter lies between the two and moves one way.
|
||||
prev := paneMaterial(100, 1, 0.5, false, false)
|
||||
for m := float32(110); m <= 200; m += 10 {
|
||||
mat := paneMaterial(m, 1, 0.5, false, false)
|
||||
if mat.low > prev.low || mat.rim < prev.rim || mat.bezel < prev.bezel || mat.low < 0.35 || mat.rim > 0.5 {
|
||||
t.Errorf("%v DIPs: %+v after %+v", m, mat, prev)
|
||||
}
|
||||
prev = mat
|
||||
}
|
||||
if mid := paneMaterial(150, 1, 0.5, false, false); !near(mid.low, (0.541+0.35)/2) || !near(mid.rim, 0.425) {
|
||||
t.Errorf("150 DIPs, half way: %+v", mid)
|
||||
}
|
||||
// Clear glass's tone is the same at any size.
|
||||
if small, large := paneMaterial(60, 1, 0.5, true, false), paneMaterial(400, 1, 0.5, true, false); small.low != large.low || small.high != large.high || small.blur != large.blur {
|
||||
t.Errorf("clear: %+v and %+v", small, large)
|
||||
}
|
||||
}
|
||||
|
||||
// A large pane's clarity runs from the measured material, at 0, through
|
||||
// a clearer one at 0.5, to one nearly clear at 1, every parameter moving
|
||||
// one way; out of range it is the nearest end.
|
||||
func TestPaneClarity(t *testing.T) {
|
||||
near := func(a, b float32) bool { return a-b < 1e-5 && b-a < 1e-5 }
|
||||
type tone struct{ blur, light, darkLow, darkHigh, rim, bezel float32 }
|
||||
at := func(k float32) tone {
|
||||
l, d := paneMaterial(400, 1, k, false, false), paneMaterial(400, 1, k, false, true)
|
||||
if l.blur != d.blur || l.rim != d.rim || l.bezel != d.bezel {
|
||||
t.Errorf("clarity %v: light %+v and dark %+v differ", k, l, d)
|
||||
}
|
||||
return tone{l.blur, l.low, d.low, d.high, l.rim, l.bezel}
|
||||
}
|
||||
same := func(a, b tone) bool {
|
||||
return near(a.blur, b.blur) && near(a.light, b.light) && near(a.darkLow, b.darkLow) &&
|
||||
near(a.darkHigh, b.darkHigh) && near(a.rim, b.rim) && near(a.bezel, b.bezel)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
k float32
|
||||
want tone
|
||||
}{
|
||||
{0, tone{10, 0.541, 0.15, 0.51, 0.35, 36}},
|
||||
{0.25, tone{7.5, 0.4455, 0.15, 0.555, 0.425, 42}},
|
||||
{0.5, tone{5, 0.35, 0.15, 0.6, 0.5, 48}},
|
||||
{0.75, tone{3.5, 0.275, 0.125, 0.725, 0.5, 48}},
|
||||
{1, tone{2, 0.2, 0.1, 0.85, 0.5, 48}},
|
||||
{-1, tone{10, 0.541, 0.15, 0.51, 0.35, 36}},
|
||||
{2, tone{2, 0.2, 0.1, 0.85, 0.5, 48}},
|
||||
} {
|
||||
if got := at(c.k); !same(got, c.want) {
|
||||
t.Errorf("clarity %v: %+v, want %+v", c.k, got, c.want)
|
||||
}
|
||||
}
|
||||
// Clearer, it blurs less, lightens and darkens less, its rim brighter
|
||||
// and its bezel wider, or as before.
|
||||
prev := at(0)
|
||||
for k := float32(0.05); k <= 1.001; k += 0.05 {
|
||||
cur := at(k)
|
||||
if cur.blur > prev.blur || cur.light > prev.light || cur.darkLow > prev.darkLow || cur.darkHigh < prev.darkHigh ||
|
||||
cur.rim < prev.rim || cur.bezel < prev.bezel {
|
||||
t.Errorf("clarity %v: %+v after %+v", k, cur, prev)
|
||||
}
|
||||
prev = cur
|
||||
}
|
||||
// A pane between a control's size and a sidebar's eases toward it.
|
||||
for _, k := range []float32{0, 0.5, 1} {
|
||||
small, mid, large := paneMaterial(100, 1, k, false, false), paneMaterial(150, 1, k, false, false), paneMaterial(200, 1, k, false, false)
|
||||
if !near(mid.low, (small.low+large.low)/2) || !near(mid.rim, (small.rim+large.rim)/2) {
|
||||
t.Errorf("clarity %v, 150 DIPs: %+v, not half way between %+v and %+v", k, mid, small, large)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Glass of a clarity paints a large pane clearer: black under it
|
||||
// lighter in light mode the less clear, the same for small panes.
|
||||
func TestClarityPaints(t *testing.T) {
|
||||
gray := func(k float32, w, h float32) int {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
Paint(p, ui.Rect{X: 10, Y: 10, W: w, H: h}, 20, Glass{Clarity: k})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 420, 320)
|
||||
return pixelAt(tt.Image(), int(10+w/2), int(10+h/2))[0]
|
||||
}
|
||||
frost, mid, clear := gray(0, 400, 300), gray(0.5, 400, 300), gray(1, 400, 300)
|
||||
if !(frost > mid && mid > clear) {
|
||||
t.Errorf("black under a large pane at clarity 0, 0.5, 1: %d, %d, %d", frost, mid, clear)
|
||||
}
|
||||
if a, b := gray(0, 100, 60), gray(1, 100, 60); a != b {
|
||||
t.Errorf("black under a small pane at clarity 0 and 1: %d and %d", a, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStringClarity(t *testing.T) {
|
||||
if s := (Glass{Clarity: 0.5}).String(); s != "glass clarity(0.5)" {
|
||||
t.Errorf("String: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// At clarity 0 every pane, of any size and style, is exactly the
|
||||
// material it was before clarity: the measured one.
|
||||
func TestClarityZero(t *testing.T) {
|
||||
for _, m := range []float32{1, 20, 72, 100, 150, 199, 200, 260, 900, 4000} {
|
||||
for _, s := range []float32{1, 1.5, 2} {
|
||||
bezel := min(36, m/2)
|
||||
want := material{bezel: bezel * s, refraction: 1.6 * bezel * s, rim: 0.35, rimWidth: 1, light: math.Pi / 2}
|
||||
for _, c := range []struct {
|
||||
clear, dark bool
|
||||
blur, low, high, curve, saturation float32
|
||||
}{
|
||||
{true, false, s, 0.125, 1.082, 1, 1},
|
||||
{true, true, s, 0.125, 1.082, 1, 1},
|
||||
{false, true, min(max(m*0.035, 1), 10) * s, 0.15, 0.51, 2, 2.2},
|
||||
{false, false, min(max(m*0.035, 1), 10) * s, 0.541, 1, 1.2, 1},
|
||||
} {
|
||||
w := want
|
||||
w.blur, w.low, w.high, w.curve, w.saturation = c.blur, c.low, c.high, c.curve, c.saturation
|
||||
if got := paneMaterial(m, s, 0, c.clear, c.dark); got != w {
|
||||
t.Errorf("%v DIPs at %vx, clear %v, dark %v: %+v, want %+v", m, s, c.clear, c.dark, got, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// On clear glass, clarity leaves the tone as it is and only lights the
|
||||
// rim and curves the bezel.
|
||||
func TestClarityClear(t *testing.T) {
|
||||
frost, clear := paneMaterial(400, 1, 0, true, false), paneMaterial(400, 1, 1, true, false)
|
||||
if frost.blur != clear.blur || frost.low != clear.low || frost.high != clear.high {
|
||||
t.Errorf("tone: %+v and %+v", frost, clear)
|
||||
}
|
||||
if clear.rim != 0.5 || clear.bezel != 48 {
|
||||
t.Errorf("rim and bezel: %+v", clear)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//go:build !ios
|
||||
|
||||
package glass
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/gpu/metal"
|
||||
)
|
||||
|
||||
// TestMetal checks that Metal draws the glass as the CPU does.
|
||||
func TestMetal(t *testing.T) {
|
||||
s := testScene()
|
||||
pix, err := metal.RenderOffscreen(s)
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
gputest.Compare(t, "glass-metal", pix, s.Width*4, s)
|
||||
// With continuous corners, as macOS's.
|
||||
for i := range s.Ops {
|
||||
s.Ops[i].Continuous = true
|
||||
}
|
||||
if pix, err = metal.RenderOffscreen(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "glass-metal-continuous", pix, s.Width*4, s)
|
||||
}
|
||||
|
||||
// TestMetalBlur checks that Metal draws the blur as the CPU does.
|
||||
func TestMetalBlur(t *testing.T) {
|
||||
s := blurScene()
|
||||
pix, err := metal.RenderOffscreen(s)
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
gputest.Compare(t, "blur-metal", pix, s.Width*4, s)
|
||||
for i := range s.Ops {
|
||||
s.Ops[i].Continuous = true
|
||||
}
|
||||
if pix, err = metal.RenderOffscreen(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "blur-metal-continuous", pix, s.Width*4, s)
|
||||
}
|
||||
|
||||
// TestMetalLibrary checks that the libraries compiled ahead of time come
|
||||
// from glass.metal and blur.metal and the renderer's head and tail as
|
||||
// they are.
|
||||
func TestMetalLibrary(t *testing.T) {
|
||||
if gpu.SourceSum(metal.EffectSource(metalSource)) != metalSum {
|
||||
t.Error("glass.metal or the Metal renderer's effect.metal changed since shaders_darwin.go was generated: run go generate ./plugins/glass on macOS")
|
||||
}
|
||||
if gpu.SourceSum(metal.EffectSource(blurMetalSource)) != blurMetalSum {
|
||||
t.Error("blur.metal or the Metal renderer's effect.metal changed since shaders_darwin.go was generated: run go generate ./plugins/glass on macOS")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//go:build (amd64 || arm64) && !android
|
||||
|
||||
package glass
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gl"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// TestOpenGL checks that OpenGL 3.3 and OpenGL ES 3.0 draw the glass and
|
||||
// the blur as the CPU does.
|
||||
func TestOpenGL(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
for _, es := range []bool{false, true} {
|
||||
for _, sc := range []struct {
|
||||
name string
|
||||
scene func() *scene.Scene
|
||||
}{{"glass-gl", testScene}, {"blur-gl", blurScene}} {
|
||||
s := sc.scene()
|
||||
o, err := gl.NewOffscreen(es, s.Width, s.Height)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
t.Log(o.Info())
|
||||
pix, err := o.Render(s)
|
||||
o.Release()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, sc.name, pix, s.Width*4, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
)
|
||||
|
||||
// TestDirect3D checks that Direct3D 11 draws the glass as the CPU does.
|
||||
func TestDirect3D(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := testScene()
|
||||
pix, stride, err := d3d11.RenderOffscreen(s)
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
gputest.Compare(t, "glass-d3d11", pix, stride, s)
|
||||
s = blurScene()
|
||||
if pix, stride, err = d3d11.RenderOffscreen(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "blur-d3d11", pix, stride, s)
|
||||
}
|
||||
|
||||
// TestBytecode checks that the bytecode compiled ahead of time comes from
|
||||
// glass.hlsl and blur.hlsl and the renderer's head and tail as they are.
|
||||
func TestBytecode(t *testing.T) {
|
||||
if gpu.SourceSum(d3d11.EffectSource(hlslSource)) != hlslSum {
|
||||
t.Error("glass.hlsl or the Direct3D renderer's effect.hlsl changed since shaders_windows.go was generated: run go generate ./plugins/glass on Windows")
|
||||
}
|
||||
if gpu.SourceSum(d3d11.EffectSource(blurHLSLSource)) != blurHLSLSum {
|
||||
t.Error("blur.hlsl or the Direct3D renderer's effect.hlsl changed since shaders_windows.go was generated: run go generate ./plugins/glass on Windows")
|
||||
}
|
||||
}
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
"github.com/egoist/mygo/ui/shader"
|
||||
)
|
||||
|
||||
// Group is a row of elements on one pane of glass, whose corners merge
|
||||
// while they are close, as macOS's NSGlassEffectContainerView draws them:
|
||||
//
|
||||
// g := glass.NewGroup(c)
|
||||
// g.Radius = 22
|
||||
// g.Gap(6).Children(func() {
|
||||
// g.Pane(ui.Box(c).Padding(8, 16).Center().Children(func() { ui.Text(c, "Cut") }))
|
||||
// g.Pane(ui.Box(c).Padding(8, 16).Center().Children(func() { ui.Text(c, "Copy") }))
|
||||
// })
|
||||
//
|
||||
// The elements are an ordinary row's; the glass is painted behind them,
|
||||
// one surface over all of them, so that it merges where they nearly touch
|
||||
// instead of showing two panes. The elements keep their own backgrounds,
|
||||
// borders and hit areas.
|
||||
type Group struct {
|
||||
ui.Element
|
||||
// Style is the group's material, as Glass's.
|
||||
Style Style
|
||||
// Tint colors the glass, as Glass's.
|
||||
Tint ui.Color
|
||||
// Clarity makes large groups clearer, as Glass's.
|
||||
Clarity float32
|
||||
// Radius is the corners of each element's pane, in DIPs.
|
||||
Radius float32
|
||||
// Merge is how smoothly panes blend into one surface, in DIPs: 24 by
|
||||
// default, which bridges panes up to about 12 DIPs apart; 0 keeps
|
||||
// them apart.
|
||||
Merge float32
|
||||
// panes are the elements whose boxes the glass covers.
|
||||
panes []ui.Element
|
||||
}
|
||||
|
||||
// NewGroup returns an empty Group, a row, whose Material paints the glass
|
||||
// behind the elements its Pane adds.
|
||||
func NewGroup(c *ui.Context) *Group {
|
||||
g := &Group{Element: ui.Row(c), Merge: 24}
|
||||
g.Element.Material(g)
|
||||
return g
|
||||
}
|
||||
|
||||
// Pane adds e to the group's glass, and returns it.
|
||||
func (g *Group) Pane(e ui.Element) ui.Element {
|
||||
g.panes = append(g.panes, e)
|
||||
return e
|
||||
}
|
||||
|
||||
// PaintMaterial paints the group's glass over the union of its panes.
|
||||
func (g *Group) PaintMaterial(p *ui.Painter, box ui.Rect, _ [4]float32) {
|
||||
if box.W <= 0 || box.H <= 0 || len(g.panes) == 0 {
|
||||
return
|
||||
}
|
||||
rects := make([]ui.Rect, 0, len(g.panes))
|
||||
minSide := float32(math.MaxFloat32)
|
||||
for i := range g.panes {
|
||||
b := g.panes[i].LayoutBounds()
|
||||
if b.W <= 0 || b.H <= 0 {
|
||||
continue
|
||||
}
|
||||
b = ui.Rect{X: b.X - box.X, Y: b.Y - box.Y, W: b.W, H: b.H}
|
||||
rects = append(rects, b)
|
||||
minSide = min(minSide, b.W, b.H)
|
||||
}
|
||||
if len(rects) == 0 {
|
||||
return
|
||||
}
|
||||
if p.Preferences().ReduceTransparency {
|
||||
c := p.Theme().Surface
|
||||
if g.Style == Clear {
|
||||
c = p.Theme().Background
|
||||
}
|
||||
if g.Tint.A > 0 {
|
||||
c = c.Mix(g.Tint, float32(g.Tint.A)/255*0.88)
|
||||
}
|
||||
for _, r := range rects {
|
||||
p.FillRadii(r, [4]float32{g.Radius, g.Radius, g.Radius, g.Radius}, c)
|
||||
}
|
||||
return
|
||||
}
|
||||
mat := paneMaterial(minSide, p.Scale(), g.Clarity, g.Style == Clear, p.Theme().Dark)
|
||||
if p.Preferences().HighContrast {
|
||||
mat.rim = min(mat.rim+0.15, 1)
|
||||
mat.rimWidth = max(mat.rimWidth, 1.5)
|
||||
}
|
||||
tint := [4]float32{0, 0, 0, 0}
|
||||
if g.Tint.A > 0 {
|
||||
tint = [4]float32{float32(g.Tint.R) / 255, float32(g.Tint.G) / 255, float32(g.Tint.B) / 255, float32(g.Tint.A) / 255 * 0.88}
|
||||
}
|
||||
groupShader.Draw(p, box, shader.Options{
|
||||
Uniforms: map[string]any{
|
||||
"Count": len(rects),
|
||||
"Rects": groupRects(rects),
|
||||
"Radii": groupRadii(len(rects), g.Radius),
|
||||
"Bezel": mat.bezel / p.Scale(),
|
||||
"Refraction": mat.refraction / p.Scale(),
|
||||
"Rim": mat.rim,
|
||||
"RimWidth": mat.rimWidth / p.Scale(),
|
||||
"Low": mat.low,
|
||||
"High": mat.high,
|
||||
"Curve": mat.curve,
|
||||
"Saturation": mat.saturation,
|
||||
"Merge": g.Merge,
|
||||
"Tint": tint[:],
|
||||
"Light": []float32{float32(math.Cos(float64(mat.light))), float32(math.Sin(float64(mat.light)))},
|
||||
},
|
||||
BackdropBlur: mat.blur / p.Scale(),
|
||||
})
|
||||
}
|
||||
|
||||
// String describes the group, as the inspector shows it.
|
||||
func (g *Group) String() string {
|
||||
return fmt.Sprintf("glass group(%d)", len(g.panes))
|
||||
}
|
||||
|
||||
// groupRects lays out up to maxGroupPanes rects for the shader, in DIPs.
|
||||
func groupRects(rects []ui.Rect) []float32 {
|
||||
out := make([]float32, maxGroupPanes*4)
|
||||
for i, r := range rects {
|
||||
if i >= maxGroupPanes {
|
||||
break
|
||||
}
|
||||
out[i*4], out[i*4+1], out[i*4+2], out[i*4+3] = r.X, r.Y, r.W, r.H
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func groupRadii(n int, radius float32) []float32 {
|
||||
out := make([]float32, maxGroupPanes)
|
||||
for i := range n {
|
||||
if i >= maxGroupPanes {
|
||||
break
|
||||
}
|
||||
out[i] = radius
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const maxGroupPanes = 8
|
||||
|
||||
// groupShader draws the union of the panes: one bezel around the whole
|
||||
// surface, as the panes merge.
|
||||
var groupShader = shader.MustCompile(`package main
|
||||
|
||||
var Count int
|
||||
var Rects [32]float
|
||||
var Radii [8]float
|
||||
var Merge float
|
||||
var Bezel float
|
||||
var Refraction float
|
||||
var Rim float
|
||||
var RimWidth float
|
||||
var Low float
|
||||
var High float
|
||||
var Curve float
|
||||
var Saturation float
|
||||
var Tint vec4
|
||||
var Light vec2
|
||||
|
||||
func sdPane(p vec2, i int) float {
|
||||
r := vec4(Rects[i*4], Rects[i*4+1], Rects[i*4+2], Rects[i*4+3])
|
||||
h := r.zw / 2
|
||||
rad := min(Radii[i], min(h.x, h.y))
|
||||
q := abs(p - r.xy - h) - (h - vec2(rad, rad))
|
||||
m := max(q, vec2(0, 0))
|
||||
return length(m) + min(max(q.x, q.y), 0.0) - rad
|
||||
}
|
||||
|
||||
func smin(a float, b float, k float) float {
|
||||
if k <= 0.0 {
|
||||
return min(a, b)
|
||||
}
|
||||
h := clamp(0.5+0.5*(b-a)/k, 0.0, 1.0)
|
||||
return mix(b, a, h) - k*h*(1.0-h)
|
||||
}
|
||||
|
||||
func unionSDF(p vec2) float {
|
||||
d := 1.0e9
|
||||
for i := 0; i < 8; i++ {
|
||||
if i < Count {
|
||||
d = smin(d, sdPane(p, i), Merge)
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func normalAt(p vec2) vec2 {
|
||||
e := 1.0 / pixelScale()
|
||||
n := vec2(unionSDF(p+vec2(e, 0))-unionSDF(p-vec2(e, 0)), unionSDF(p+vec2(0, e))-unionSDF(p-vec2(0, e)))
|
||||
l := length(n)
|
||||
if l < 0.00001 {
|
||||
return vec2(0, 1)
|
||||
}
|
||||
return n / l
|
||||
}
|
||||
|
||||
func lens(t float, bezel float) float {
|
||||
if bezel <= 0.0 || t >= bezel {
|
||||
return 0.0
|
||||
}
|
||||
u := 1.0 - max(t, 0.0) / bezel
|
||||
v := 1.0 - u*u*u*u
|
||||
a := sqrt(v * sqrt(v))
|
||||
b := u*u*u
|
||||
n := sqrt(a*a + b*b)
|
||||
s := b / n
|
||||
c := a / n
|
||||
st := s / 1.5
|
||||
ct := sqrt(1.0 - st*st)
|
||||
return (s*ct - c*st) / (c*ct + s*st) / 1.118034
|
||||
}
|
||||
|
||||
func tone(c vec3) vec3 {
|
||||
l := 0.2126*c.r + 0.7152*c.g + 0.0722*c.b
|
||||
t := Low + (High-Low)*(1.0-pow(max(1.0-l, 0.0), Curve))
|
||||
k := (High - Low) * Saturation
|
||||
return clamp(vec3(t, t, t) + (c - vec3(l, l, l))*k, vec3(0, 0, 0), vec3(1, 1, 1))
|
||||
}
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
d := unionSDF(pos)
|
||||
a := clamp(0.5-d*pixelScale(), 0.0, 1.0)
|
||||
if a <= 0.0 {
|
||||
return vec4(0, 0, 0, 0)
|
||||
}
|
||||
t := max(-d, 0.0)
|
||||
n := vec2(0, 1)
|
||||
if t < Bezel || t < 3.0*RimWidth {
|
||||
n = normalAt(pos)
|
||||
}
|
||||
q := pos
|
||||
if t < Bezel {
|
||||
q = q - n*(Refraction*lens(t, Bezel))
|
||||
}
|
||||
c := tone(backdropSample(q).rgb)
|
||||
c = c + (Tint.rgb-c)*Tint.a
|
||||
if Rim > 0.0 && t < 3.0*RimWidth {
|
||||
r := t / RimWidth
|
||||
lit := Rim * exp(-r*r)
|
||||
l := abs(dot(n, Light))
|
||||
c = c + (vec3(l, l, l) - c) * lit
|
||||
}
|
||||
return vec4(c.x*a, c.y*a, c.z*a, a)
|
||||
}
|
||||
`)
|
||||
@@ -0,0 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11"
|
||||
)
|
||||
|
||||
// compile compiles the shader file within the Direct3D renderer's head
|
||||
// and tail.
|
||||
func compile(file string) (compiled string, code []byte, err error) {
|
||||
src, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
code, err = d3d11.CompileEffect(string(src))
|
||||
return d3d11.EffectSource(string(src)), code, err
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//go:build !js
|
||||
|
||||
// Command gen compiles the glass's and the blur's shaders ahead of time,
|
||||
// so that renderers start without compiling them: the Metal libraries on
|
||||
// macOS, with Xcode's metal tools, into shaders_darwin.go, and the
|
||||
// Direct3D bytecode on Windows, with the system's d3dcompiler_47.dll, into
|
||||
// shaders_windows.go. Run it on each: go generate ./plugins/glass
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"go/format"
|
||||
"log"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
)
|
||||
|
||||
// shader is a shader to compile, and the variables holding its code and
|
||||
// the SHA-256 of what that was compiled from.
|
||||
type shader struct{ file, codeVar, sumVar string }
|
||||
|
||||
func main() {
|
||||
file := "shaders_darwin.go"
|
||||
shaders := []shader{{"glass.metal", "metalLibrary", "metalSum"}, {"blur.metal", "blurMetalLibrary", "blurMetalSum"}}
|
||||
if runtime.GOOS == "windows" {
|
||||
file = "shaders_windows.go"
|
||||
shaders = []shader{{"glass.hlsl", "hlslBytecode", "hlslSum"}, {"blur.hlsl", "blurBytecode", "blurHLSLSum"}}
|
||||
}
|
||||
var names []string
|
||||
for _, sh := range shaders {
|
||||
names = append(names, sh.file)
|
||||
}
|
||||
var b bytes.Buffer
|
||||
fmt.Fprintf(&b, "// Code generated by internal/gen from %s; DO NOT EDIT.\n\n//go:build %s\n\npackage glass\n\n", strings.Join(names, " and "), runtime.GOOS)
|
||||
for _, sh := range shaders {
|
||||
compiled, code, err := compile(sh.file)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Fprintf(&b, "// %s is the SHA-256 of what %s was compiled from: %s\n// within the renderer's head and tail.\nconst %s = %q\n\n", sh.sumVar, sh.codeVar, sh.file, sh.sumVar, gpu.SourceSum(compiled))
|
||||
b.WriteString(gpu.GoBytes(sh.codeVar, code))
|
||||
b.WriteString("\n")
|
||||
}
|
||||
out, err := format.Source(b.Bytes())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(file, out, 0o644); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//go:build !ios
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/metal"
|
||||
)
|
||||
|
||||
// compile compiles the shader file within the Metal renderer's head and
|
||||
// tail.
|
||||
func compile(file string) (compiled string, code []byte, err error) {
|
||||
src, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
compiled = metal.EffectSource(string(src))
|
||||
code, err = metal.CompileLibrary(compiled)
|
||||
return compiled, code, err
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !(darwin && !ios) && !windows && !js
|
||||
|
||||
package main
|
||||
|
||||
import "errors"
|
||||
|
||||
func compile(string) (compiled string, code []byte, err error) {
|
||||
return "", nil, errors.New("the glass's shaders compile on macOS and Windows")
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// pixels draws the glass on the CPU, as its shaders do on the GPU.
|
||||
type pixels struct {
|
||||
m material
|
||||
rect scene.Rect
|
||||
radii [4]float32
|
||||
lx, ly float32
|
||||
toneTable [toneSteps + 1]float32
|
||||
toneLinear bool
|
||||
}
|
||||
|
||||
// toneSteps is how many lightnesses the CPU keeps the tone curve at,
|
||||
// between which it is a line, within 3e-5 of the curve: its power makes
|
||||
// it slow on the CPU.
|
||||
const toneSteps = 1024
|
||||
|
||||
// Begin reads the material of op and readies its tone curve.
|
||||
func (px *pixels) Begin(op *scene.EffectOp, rect scene.Rect, radii [4]float32) {
|
||||
p := &op.Params
|
||||
px.m = material{
|
||||
blur: op.Blur,
|
||||
bezel: p[0][0], refraction: p[0][1], rim: p[0][2], rimWidth: p[0][3],
|
||||
tint: p[1],
|
||||
low: p[2][0], high: p[2][1], curve: p[2][2], saturation: p[2][3],
|
||||
}
|
||||
px.lx, px.ly = p[3][0], p[3][1]
|
||||
px.rect, px.radii = rect, radii
|
||||
px.toneLinear = px.m.curve == 1
|
||||
if !px.toneLinear {
|
||||
for i := range px.toneTable {
|
||||
px.toneTable[i] = 1 - pow(1-float32(i)/toneSteps, px.m.curve)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tone is the material's tone from the table.
|
||||
func (px *pixels) tone(c [3]float32) [3]float32 {
|
||||
m := &px.m
|
||||
l := 0.2126*c[0] + 0.7152*c[1] + 0.0722*c[2]
|
||||
var v float32
|
||||
if px.toneLinear {
|
||||
v = min(max(l, 0), 1)
|
||||
} else {
|
||||
x := min(max(l, 0), 1) * toneSteps
|
||||
i := min(int(x), toneSteps-1)
|
||||
f := x - float32(i)
|
||||
v = px.toneTable[i] + (px.toneTable[i+1]-px.toneTable[i])*f
|
||||
}
|
||||
return toneAt(c, l, m.low+(m.high-m.low)*v, m)
|
||||
}
|
||||
|
||||
// Color returns the color of the glass at the pixel center (x, y), as the
|
||||
// shaders' effect does.
|
||||
func (px *pixels) Color(x, y float32, b *scene.BackdropImage) [4]float32 {
|
||||
m := &px.m
|
||||
t := max(-scene.SDRoundRect(px.rect, px.radii, x, y), 0)
|
||||
var nx, ny float32
|
||||
if t < m.bezel || t < 3*m.rimWidth {
|
||||
nx, ny = normal(x, y, px.rect, px.radii)
|
||||
}
|
||||
sx, sy := x, y
|
||||
if t < m.bezel {
|
||||
d := m.refraction * lens(t, m.bezel)
|
||||
sx, sy = x-nx*d, y-ny*d
|
||||
}
|
||||
c := px.tone(b.Sample(sx, sy))
|
||||
for i := range c {
|
||||
c[i] += (m.tint[i] - c[i]) * m.tint[3]
|
||||
}
|
||||
if m.rim > 0 && t < 3*m.rimWidth {
|
||||
q := t / m.rimWidth
|
||||
a := m.rim * float32(math.Exp(float64(-q*q)))
|
||||
l := abs(nx*px.lx + ny*px.ly)
|
||||
for i := range c {
|
||||
c[i] += (l - c[i]) * a
|
||||
}
|
||||
}
|
||||
return [4]float32{c[0], c[1], c[2], 1}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// paneOp appends a pane of glass of material m to s.
|
||||
func paneOp(s *scene.Scene, r scene.Rect, radii [4]float32, m material, opacity float32) {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpEffect, Rect: r, Radii: radii, Start: int32(len(s.Effects)), Opacity: opacity})
|
||||
s.Effects = append(s.Effects, scene.EffectOp{Effect: Effect, Blur: m.blur, Params: m.params()})
|
||||
}
|
||||
|
||||
func r4(r float32) [4]float32 { return [4]float32{r, r, r, r} }
|
||||
|
||||
// testScene returns a 320×140 scene of panes of glass over stripes and a
|
||||
// gradient, which the renderers must draw alike: blurred at a quarter of
|
||||
// the size, over each other, unblurred and tinted, clipped, half
|
||||
// transparent, dark and blurred at full size, and past the frame's edge.
|
||||
func testScene() *scene.Scene {
|
||||
s := &scene.Scene{Width: 320, Height: 140, Clear: scene.Color{R: 246, G: 247, B: 249, A: 255}}
|
||||
red := scene.Color{R: 220, G: 40, B: 40, A: 255}
|
||||
blue := scene.Color{R: 37, G: 99, B: 235, A: 255}
|
||||
yellow := scene.Color{R: 250, G: 204, B: 21, A: 255}
|
||||
ink := scene.Color{R: 20, G: 24, B: 32, A: 255}
|
||||
for i := range 8 {
|
||||
c := []scene.Color{red, blue, yellow, ink}[i%4]
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i * 40), W: 20, H: 140}, Color: c})
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{Y: 60, W: 320, H: 20}, Color: red, Color2: blue,
|
||||
Paint: scene.PaintOklab, Gradient: [4]float32{0, 0, 320, 0}})
|
||||
light := material{low: 0.541, high: 1, curve: 1.2, saturation: 1, rim: 0.35, rimWidth: 2, light: math.Pi / 2}
|
||||
m := light
|
||||
m.blur, m.bezel, m.refraction = 8, 22, 35
|
||||
paneOp(s, scene.Rect{X: 12, Y: 10, W: 140, H: 44}, r4(22), m, 0)
|
||||
m = light
|
||||
m.blur, m.bezel, m.refraction = 12, 30, 48
|
||||
paneOp(s, scene.Rect{X: 120, Y: 36, W: 60, H: 60}, r4(30), m, 0)
|
||||
m = material{low: 0.125, high: 1.082, curve: 1, saturation: 1, bezel: 16, refraction: 26, tint: [4]float32{0.15, 0.39, 0.92, 0.47},
|
||||
rim: 0.35, rimWidth: 2, light: math.Pi / 4}
|
||||
paneOp(s, scene.Rect{X: 190.5, Y: 8.25, W: 110, H: 50}, r4(16), m, 0)
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 30, Y: 70, W: 200, H: 50}, Radii: r4(12)})
|
||||
m = material{blur: 3, low: 0.15, high: 0.51, curve: 2, saturation: 2.2, bezel: 20, refraction: 30, rim: 0.35, rimWidth: 2, light: math.Pi / 2}
|
||||
paneOp(s, scene.Rect{X: 40, Y: 66, W: 240, H: 44}, [4]float32{22, 6, 22, 6}, m, 0.7)
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
|
||||
m = light
|
||||
m.blur, m.bezel, m.refraction = 6, 16, 24
|
||||
paneOp(s, scene.Rect{X: 284, Y: 94, W: 50, H: 50}, r4(14), m, 0)
|
||||
return s
|
||||
}
|
||||
|
||||
// TestToneTable checks the CPU's tone curve against the curve itself.
|
||||
func TestToneTable(t *testing.T) {
|
||||
for _, m := range []material{
|
||||
{low: 0.541, high: 1, curve: 1.2, saturation: 1},
|
||||
{low: 0.15, high: 0.51, curve: 2, saturation: 2.2},
|
||||
{low: 0.125, high: 1.082, curve: 1, saturation: 1},
|
||||
} {
|
||||
var px pixels
|
||||
op := scene.EffectOp{Effect: Effect, Params: m.params()}
|
||||
px.Begin(&op, scene.Rect{W: 10, H: 10}, [4]float32{})
|
||||
worst := float32(0)
|
||||
for i := range 1000 {
|
||||
c := [3]float32{float32(i%10) / 9, float32(i/10%10) / 9, float32(i/100) / 9}
|
||||
got, want := px.tone(c), tone(c, &m)
|
||||
for k := range got {
|
||||
worst = max(worst, abs(got[k]-want[k]))
|
||||
}
|
||||
}
|
||||
if worst > 1e-4 {
|
||||
t.Errorf("curve %v: the table is %v off the curve", m.curve, worst)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestGlassShowsWhatIsBehind checks that the glass lightens what is under
|
||||
// it, bends it near its edge and lights its rim.
|
||||
func TestGlassShowsWhatIsBehind(t *testing.T) {
|
||||
s := testScene()
|
||||
img := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(img, s)
|
||||
at := func(x, y int) [4]byte {
|
||||
p := img.Pix[y*img.Stride+4*x:]
|
||||
return [4]byte{p[2], p[1], p[0], p[3]}
|
||||
}
|
||||
// Over the ink stripe (x 120 to 140), the first pane is light gray.
|
||||
if p := at(130, 32); p[0] < 120 || p[0] > 200 {
|
||||
t.Errorf("light glass over ink is %v", p)
|
||||
}
|
||||
// Outside the panes, the stripes show as they are.
|
||||
if p := at(10, 130); p != [4]byte{220, 40, 40, 255} {
|
||||
t.Errorf("outside the glass: %v", p)
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkGlass measures drawing a window with panes of glass on the
|
||||
// CPU, whole: 1360×720 pixels, stripes under a bar, a card, a button and
|
||||
// a lens.
|
||||
func BenchmarkGlass(b *testing.B) {
|
||||
s := &scene.Scene{Width: 1360, Height: 720, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}}
|
||||
colors := []scene.Color{{R: 239, G: 68, B: 68, A: 255}, {R: 245, G: 158, B: 11, A: 255}, {R: 16, G: 185, B: 129, A: 255}, {R: 59, G: 130, B: 246, A: 255}}
|
||||
for i := range 17 {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i * 80), W: 40, H: 720}, Color: colors[i%len(colors)]})
|
||||
}
|
||||
m := material{low: 0.541, high: 1, curve: 1.2, saturation: 1, rim: 0.35, rimWidth: 2, light: math.Pi / 2}
|
||||
m.blur, m.bezel, m.refraction = 4, 58, 93
|
||||
paneOp(s, scene.Rect{X: 32, Y: 32, W: 1296, H: 116}, r4(58), m, 0)
|
||||
m.blur, m.bezel, m.refraction = 12, 72, 115
|
||||
paneOp(s, scene.Rect{X: 80, Y: 220, W: 600, H: 170}, r4(56), m, 0)
|
||||
m.blur, m.bezel, m.refraction = 2, 36, 58
|
||||
paneOp(s, scene.Rect{X: 1120, Y: 52, W: 160, H: 72}, r4(36), m, 0)
|
||||
m = material{blur: 2, low: 0.125, high: 1.082, curve: 1, saturation: 1, bezel: 72, refraction: 115, rim: 0.35, rimWidth: 2, light: math.Pi / 2}
|
||||
paneOp(s, scene.Rect{X: 840, Y: 260, W: 280, H: 280}, r4(140), m, 0)
|
||||
img := raster.NewImage(s.Width, s.Height)
|
||||
for b.Loop() {
|
||||
raster.Render(img, s)
|
||||
}
|
||||
}
|
||||
+3248
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,8 @@
|
||||
//go:build !windows
|
||||
|
||||
package glass
|
||||
|
||||
// The Direct3D bytecode compiled ahead of time is for Windows alone.
|
||||
var hlslBytecode, blurBytecode []byte
|
||||
|
||||
const hlslSum, blurHLSLSum = "", ""
|
||||
@@ -0,0 +1,8 @@
|
||||
//go:build !(darwin && !ios)
|
||||
|
||||
package glass
|
||||
|
||||
// The Metal libraries compiled ahead of time are for macOS alone.
|
||||
var metalLibrary, blurMetalLibrary []byte
|
||||
|
||||
const metalSum, blurMetalSum = "", ""
|
||||
+3610
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,75 @@
|
||||
package dev.mygo
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.MediaStore
|
||||
import androidx.core.content.FileProvider
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
class ImagePickerPlugin : MyGoPlugin {
|
||||
override fun call(method: String, args: JSONObject, reply: PluginReply) {
|
||||
when (method) {
|
||||
"pick" -> pick(args, reply)
|
||||
"capture" -> capture(reply)
|
||||
else -> reply.failure(PluginFailure("NoMethod", method))
|
||||
}
|
||||
}
|
||||
|
||||
private fun pick(args: JSONObject, reply: PluginReply) {
|
||||
val type = when (args.optString("kind")) {
|
||||
"videos" -> "video/*"
|
||||
"any" -> "*/*"
|
||||
else -> "image/*"
|
||||
}
|
||||
val limit = args.optInt("limit", 1)
|
||||
// The Photo Picker, where the system has it; Google Play brings it to
|
||||
// older ones.
|
||||
val photo = Build.VERSION.SDK_INT >= 33 || MediaStore.getPickImagesMaxLimit() > 0
|
||||
val i = if (photo) {
|
||||
Intent(MediaStore.ACTION_PICK_IMAGES).apply {
|
||||
if (type != "*/*") setType(type)
|
||||
if (limit != 1) putExtra(MediaStore.EXTRA_PICK_IMAGES_MAX, if (limit < 0) MediaStore.getPickImagesMaxLimit() else limit)
|
||||
}
|
||||
} else {
|
||||
Intent(Intent.ACTION_GET_CONTENT).setType(type).addCategory(Intent.CATEGORY_OPENABLE).putExtra(Intent.EXTRA_ALLOW_MULTIPLE, limit != 1)
|
||||
}
|
||||
PluginHost.startForResult(i) { code, data ->
|
||||
if (code != Activity.RESULT_OK || data == null) {
|
||||
reply.success(JSONObject().put("paths", JSONArray()))
|
||||
return@startForResult
|
||||
}
|
||||
val uris = ArrayList<Uri>()
|
||||
data.clipData?.let { c -> for (k in 0 until c.itemCount) uris.add(c.getItemAt(k).uri) }
|
||||
if (uris.isEmpty()) data.data?.let { uris.add(it) }
|
||||
Thread {
|
||||
try {
|
||||
val dir = File(PluginHost.context.cacheDir, "picked/${System.nanoTime()}").apply { mkdirs() }
|
||||
val out = JSONArray()
|
||||
for (u in uris) out.put(HostImpl.copyToFile(u, dir).absolutePath)
|
||||
reply.success(JSONObject().put("paths", out))
|
||||
} catch (e: Exception) {
|
||||
reply.failure(PluginFailure("Failed", e.toString()))
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
}
|
||||
|
||||
private fun capture(reply: PluginReply) {
|
||||
val ctx = PluginHost.context
|
||||
val dir = File(ctx.cacheDir, "camera").apply { mkdirs() }
|
||||
val f = File(dir, "${System.nanoTime()}.jpg")
|
||||
val uri = FileProvider.getUriForFile(ctx, ctx.packageName + ".mygo.files", f)
|
||||
val i = Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, uri).addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
|
||||
if (i.resolveActivity(ctx.packageManager) == null) {
|
||||
reply.failure(PluginFailure("NoCamera", "the device has no camera app"))
|
||||
return
|
||||
}
|
||||
PluginHost.startForResult(i) { code, _ ->
|
||||
reply.success(JSONObject().put("path", if (code == Activity.RESULT_OK && f.length() > 0) f.absolutePath else ""))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Package imagepicker lets the user choose photos and videos from their
|
||||
// library, or take one with the camera, on phones and tablets: the system's
|
||||
// own pickers (PHPickerViewController and UIImagePickerController on iOS, the
|
||||
// Photo Picker and the camera app on Android), which ask the user for no
|
||||
// permission to read the library. Elsewhere its functions report
|
||||
// errors.ErrUnsupported.
|
||||
package imagepicker
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
)
|
||||
|
||||
const pluginID = "imagepicker"
|
||||
|
||||
// Kind is what a picker shows.
|
||||
type Kind string
|
||||
|
||||
const (
|
||||
Images Kind = "images"
|
||||
Videos Kind = "videos"
|
||||
// Any shows both.
|
||||
Any Kind = "any"
|
||||
)
|
||||
|
||||
// Options are what Pick lets the user choose.
|
||||
type Options struct {
|
||||
// Kind is what it shows: Images by default.
|
||||
Kind Kind
|
||||
// Limit is how many the user may choose: 1 by default, 0 meaning 1, and
|
||||
// negative as many as they like.
|
||||
Limit int
|
||||
}
|
||||
|
||||
// Pick shows the system's picker of the user's library, and returns the paths
|
||||
// of copies of what they chose in the app's temporary directory: none when
|
||||
// they went back. Call it off the main goroutine, as it waits for the user.
|
||||
func Pick(ctx context.Context, o Options) ([]string, error) {
|
||||
if o.Kind == "" {
|
||||
o.Kind = Images
|
||||
}
|
||||
if o.Limit == 0 {
|
||||
o.Limit = 1
|
||||
}
|
||||
var r struct {
|
||||
Paths []string `json:"paths"`
|
||||
}
|
||||
err := mygo.Native(pluginID).Call(ctx, "pick", map[string]any{"kind": o.Kind, "limit": o.Limit}, &r)
|
||||
return r.Paths, err
|
||||
}
|
||||
|
||||
// Capture shows the camera, for a photo, and returns the path of a JPEG of it
|
||||
// in the app's temporary directory, "" when the user went back.
|
||||
func Capture(ctx context.Context) (string, error) {
|
||||
var r struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
err := mygo.Native(pluginID).Call(ctx, "capture", nil, &r)
|
||||
return r.Path, err
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import PhotosUI
|
||||
import UIKit
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
final class ImagePickerPlugin: NSObject, MyGoPlugin, PHPickerViewControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
|
||||
private var picking: PluginReply?
|
||||
private var capturing: PluginReply?
|
||||
|
||||
func call(_ method: String, _ args: [String: Any], _ reply: @escaping PluginReply) {
|
||||
switch method {
|
||||
case "pick":
|
||||
picking = reply
|
||||
var cfg = PHPickerConfiguration()
|
||||
switch args["kind"] as? String {
|
||||
case "videos": cfg.filter = .videos
|
||||
case "any": cfg.filter = .any(of: [.images, .videos])
|
||||
default: cfg.filter = .images
|
||||
}
|
||||
let limit = args["limit"] as? Int ?? 1
|
||||
cfg.selectionLimit = limit < 0 ? 0 : limit
|
||||
let vc = PHPickerViewController(configuration: cfg)
|
||||
vc.delegate = self
|
||||
PluginHost.present(vc)
|
||||
case "capture":
|
||||
guard UIImagePickerController.isSourceTypeAvailable(.camera) else {
|
||||
reply(.failure(PluginFailure("NoCamera", "the device has no camera")))
|
||||
return
|
||||
}
|
||||
capturing = reply
|
||||
let vc = UIImagePickerController()
|
||||
vc.sourceType = .camera
|
||||
vc.delegate = self
|
||||
PluginHost.present(vc)
|
||||
default:
|
||||
reply(.failure(PluginFailure("NoMethod", method)))
|
||||
}
|
||||
}
|
||||
|
||||
func picker(_ vc: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
|
||||
vc.dismiss(animated: true)
|
||||
guard let reply = picking else { return }
|
||||
picking = nil
|
||||
let group = DispatchGroup()
|
||||
let dir = NSTemporaryDirectory() + UUID().uuidString
|
||||
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
|
||||
var paths = [String?](repeating: nil, count: results.count)
|
||||
let lock = NSLock()
|
||||
for (i, r) in results.enumerated() {
|
||||
let p = r.itemProvider
|
||||
guard let type = p.registeredTypeIdentifiers.first else { continue }
|
||||
group.enter()
|
||||
p.loadFileRepresentation(forTypeIdentifier: type) { url, _ in
|
||||
defer { group.leave() }
|
||||
guard let url else { return }
|
||||
let to = URL(fileURLWithPath: dir).appendingPathComponent("\(i)-" + url.lastPathComponent)
|
||||
if (try? FileManager.default.copyItem(at: url, to: to)) != nil {
|
||||
lock.lock()
|
||||
paths[i] = to.path
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
group.notify(queue: .main) { reply(.success(["paths": paths.compactMap { $0 }])) }
|
||||
}
|
||||
|
||||
func imagePickerController(_ vc: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
|
||||
vc.dismiss(animated: true)
|
||||
guard let reply = capturing else { return }
|
||||
capturing = nil
|
||||
guard let image = info[.originalImage] as? UIImage, let jpeg = image.jpegData(compressionQuality: 0.9) else {
|
||||
reply(.failure(PluginFailure("Failed", "no photo")))
|
||||
return
|
||||
}
|
||||
let path = NSTemporaryDirectory() + UUID().uuidString + ".jpg"
|
||||
do {
|
||||
try jpeg.write(to: URL(fileURLWithPath: path))
|
||||
reply(.success(["path": path]))
|
||||
} catch {
|
||||
reply(.failure(PluginFailure("Failed", error.localizedDescription)))
|
||||
}
|
||||
}
|
||||
|
||||
func imagePickerControllerDidCancel(_ vc: UIImagePickerController) {
|
||||
vc.dismiss(animated: true)
|
||||
capturing?(.success(["path": ""]))
|
||||
capturing = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"mobile": {
|
||||
"id": "imagepicker",
|
||||
"ios": {
|
||||
"sources": ["ios/*.swift"],
|
||||
"class": "ImagePickerPlugin",
|
||||
"frameworks": ["PhotosUI", "Photos"],
|
||||
"infoPlist": {"NSCameraUsageDescription": "This app takes photos with the camera."}
|
||||
},
|
||||
"android": {
|
||||
"sources": ["android/*.kt"],
|
||||
"class": "ImagePickerPlugin"
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
# Notice
|
||||
|
||||
The indicators of this package follow those of loading-dev
|
||||
(https://github.com/jakubkrehel/loading, https://loading.dev): their
|
||||
shapes, including the SVG path data of Clock and Radar, their keyframes and
|
||||
their timings. loading-dev's license:
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Jakub Krehel
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
# loading
|
||||
|
||||
The 29 loading indicators of [loading.dev](https://loading.dev) for
|
||||
[MyGo](https://github.com/egoist/mygo) apps of native UI: arcs, rings,
|
||||
dots, bars and blocks that MyGo draws itself, as loading.dev's look and
|
||||
move.
|
||||
|
||||
```go
|
||||
import "github.com/egoist/mygo/plugins/loading"
|
||||
|
||||
loading.Arc(c).Label("Saving")
|
||||
loading.Ring(c, loading.Options{Size: 32, Color: t.Accent, Easing: loading.EaseInOut})
|
||||
```
|
||||
|
||||
See [the documentation](../../docs/plugins/loading.md), and
|
||||
`examples/loading`.
|
||||
|
||||
The indicators follow loading.dev's SVG and CSS (`loading-dev` 0.3.5,
|
||||
MIT, © Jakub Krehel; see [NOTICE.md](NOTICE.md)): their shapes in the
|
||||
same viewBoxes and fractions of their size, their keyframes, staggers and
|
||||
timing functions, and their poses for reduced motion. Compared with
|
||||
loading-dev rendered by a browser at the same points of their cycles,
|
||||
they differ only where the browser snaps borders to pixels (Atom's
|
||||
rings), in antialiasing, and on macOS in the corners of rounded squares
|
||||
(Blocks, Gather, Morph, Swirl, Flip), which the renderers draw
|
||||
continuous, as macOS does, so that they need no mask rasterized every
|
||||
frame.
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
package loading
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// drawing is an indicator's frame being painted: its square of side s at
|
||||
// (x, y), how many cycles it has run, and its options.
|
||||
type drawing struct {
|
||||
p *ui.Painter
|
||||
sh *shape
|
||||
x, y, s float32
|
||||
cycles float64
|
||||
color ui.Color
|
||||
o Options
|
||||
// still draws the indicator at rest, where the desktop asks for less
|
||||
// motion.
|
||||
still bool
|
||||
}
|
||||
|
||||
// at returns how far into its cycle the part step of count is, from 0 to
|
||||
// 1, the parts staggered as loading.dev's: each a count-th of a cycle
|
||||
// behind the one before, the first a whole cycle ahead, as a negative
|
||||
// animation-delay. A count of 0 is the indicator's own cycle.
|
||||
func (d *drawing) at(step, count int) float64 {
|
||||
t := d.cycles
|
||||
if count > 0 {
|
||||
t += float64(count-step) / float64(count)
|
||||
}
|
||||
return t - math.Floor(t)
|
||||
}
|
||||
|
||||
// turn returns how much of a turn the indicator has turned at p of its
|
||||
// cycle, the other way if reverse, as Options.Easing says.
|
||||
func (d *drawing) turn(p float64, reverse bool) float64 {
|
||||
if reverse {
|
||||
p = 1 - p
|
||||
}
|
||||
switch d.o.Easing {
|
||||
case EaseInOut:
|
||||
return easeInOut(p)
|
||||
case Stacked:
|
||||
return p + easeInOut(p)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// alpha returns the indicator's color at opacity a.
|
||||
func (d *drawing) alpha(a float64) ui.Color { return d.color.Alpha(float32(a)) }
|
||||
|
||||
// view returns the transform from a viewBox of side n, as loading.dev's
|
||||
// SVGs draw in, to the indicator's square.
|
||||
func (d *drawing) view(n float32) affine {
|
||||
k := d.s / n
|
||||
return affine{a: k, d: k, e: d.x, f: d.y}
|
||||
}
|
||||
|
||||
// begin empties the shape and has it draw through m.
|
||||
func (d *drawing) begin(m affine) *shape {
|
||||
d.sh.Reset()
|
||||
d.sh.m = m
|
||||
return d.sh
|
||||
}
|
||||
|
||||
// fill fills the shape in the indicator's color at opacity a.
|
||||
func (d *drawing) fill(a float64) { d.p.FillPath(&d.sh.Path, d.alpha(a)) }
|
||||
|
||||
// fade returns the opacity of part step of count of the indicators whose
|
||||
// parts fade in turn (loading.dev's fadeCss): from 1 down to dim through
|
||||
// each cycle, at rest at rest.
|
||||
func (d *drawing) fade(step, count int, dim, rest float64) float64 {
|
||||
if d.still {
|
||||
return rest
|
||||
}
|
||||
return 1 + (dim-1)*d.at(step, count)
|
||||
}
|
||||
|
||||
// The timing functions of CSS.
|
||||
var (
|
||||
easeInOut = bezier(0.42, 0, 0.58, 1)
|
||||
easeOut = bezier(0, 0, 0.58, 1)
|
||||
overshoot = bezier(0.68, -0.75, 0.265, 1.75) // Cascade's
|
||||
linearEase = func(t float64) float64 { return t }
|
||||
)
|
||||
|
||||
// bezier returns CSS's cubic-bezier(x1, y1, x2, y2).
|
||||
func bezier(x1, y1, x2, y2 float64) func(float64) float64 {
|
||||
cx := 3 * x1
|
||||
bx := 3*(x2-x1) - cx
|
||||
ax := 1 - cx - bx
|
||||
cy := 3 * y1
|
||||
by := 3*(y2-y1) - cy
|
||||
ay := 1 - cy - by
|
||||
x := func(s float64) float64 { return ((ax*s+bx)*s + cx) * s }
|
||||
return func(t float64) float64 {
|
||||
if t <= 0 || t >= 1 {
|
||||
return t
|
||||
}
|
||||
// Newton's method, then bisection where the slope is flat.
|
||||
s := t
|
||||
for range 8 {
|
||||
e := x(s) - t
|
||||
if math.Abs(e) < 1e-7 {
|
||||
return ((ay*s+by)*s + cy) * s
|
||||
}
|
||||
dx := (3*ax*s+2*bx)*s + cx
|
||||
if math.Abs(dx) < 1e-6 {
|
||||
break
|
||||
}
|
||||
s -= e / dx
|
||||
}
|
||||
lo, hi := 0.0, 1.0
|
||||
s = t
|
||||
for range 40 {
|
||||
if x(s) < t {
|
||||
lo = s
|
||||
} else {
|
||||
hi = s
|
||||
}
|
||||
s = (lo + hi) / 2
|
||||
}
|
||||
return ((ay*s+by)*s + cy) * s
|
||||
}
|
||||
}
|
||||
|
||||
// key is a keyframe: a value at a point of a cycle.
|
||||
type key struct{ at, v float64 }
|
||||
|
||||
// frames returns the value of keyframes ks at p of a cycle, easing each
|
||||
// stretch between two keyframes, as CSS's timing functions do.
|
||||
func frames(p float64, ease func(float64) float64, ks ...key) float64 {
|
||||
for i := 1; i < len(ks); i++ {
|
||||
a, b := ks[i-1], ks[i]
|
||||
if p <= b.at {
|
||||
if b.at <= a.at {
|
||||
return b.v
|
||||
}
|
||||
return a.v + (b.v-a.v)*ease((p-a.at)/(b.at-a.at))
|
||||
}
|
||||
}
|
||||
return ks[len(ks)-1].v
|
||||
}
|
||||
|
||||
// affine maps (x, y) to (a*x + c*y + e, b*x + d*y + f).
|
||||
type affine struct{ a, b, c, d, e, f float32 }
|
||||
|
||||
// apply maps a point.
|
||||
func (m affine) apply(x, y float32) (float32, float32) {
|
||||
return m.a*x + m.c*y + m.e, m.b*x + m.d*y + m.f
|
||||
}
|
||||
|
||||
// then returns m after n: n maps first.
|
||||
func (m affine) then(n affine) affine {
|
||||
return affine{
|
||||
a: m.a*n.a + m.c*n.b, b: m.b*n.a + m.d*n.b,
|
||||
c: m.a*n.c + m.c*n.d, d: m.b*n.c + m.d*n.d,
|
||||
e: m.a*n.e + m.c*n.f + m.e, f: m.b*n.e + m.d*n.f + m.f,
|
||||
}
|
||||
}
|
||||
|
||||
// rotate returns m turning what it maps by deg degrees clockwise around
|
||||
// (cx, cy), as CSS's rotate().
|
||||
func (m affine) rotate(deg float64, cx, cy float32) affine {
|
||||
s, c := math.Sincos(deg * math.Pi / 180)
|
||||
sf, cf := float32(s), float32(c)
|
||||
return m.then(affine{a: cf, b: sf, c: -sf, d: cf, e: cx - cf*cx + sf*cy, f: cy - sf*cx - cf*cy})
|
||||
}
|
||||
|
||||
// scale returns m scaling what it maps by sx and sy around (cx, cy).
|
||||
func (m affine) scale(sx, sy, cx, cy float32) affine {
|
||||
return m.then(affine{a: sx, d: sy, e: cx - sx*cx, f: cy - sy*cy})
|
||||
}
|
||||
|
||||
// move returns m moving what it maps by (dx, dy).
|
||||
func (m affine) move(dx, dy float32) affine { return m.then(affine{a: 1, d: 1, e: dx, f: dy}) }
|
||||
|
||||
// unit returns how many DIPs a length of 1 is through m, for strokes.
|
||||
func (m affine) unit() float32 {
|
||||
return float32(math.Sqrt(math.Abs(float64(m.a*m.d - m.b*m.c))))
|
||||
}
|
||||
|
||||
// transform returns m as a ui.Transform, false if it collapses what it
|
||||
// maps: a scaling, a skew along x, a rotation, then a translation.
|
||||
func (m affine) transform() (ui.Transform, bool) {
|
||||
sx := float32(math.Hypot(float64(m.a), float64(m.b)))
|
||||
det := m.a*m.d - m.b*m.c
|
||||
if sx == 0 || det == 0 {
|
||||
return ui.Transform{}, false
|
||||
}
|
||||
sy := det / sx
|
||||
t := ui.Scaling(sx, sy)
|
||||
if k := (m.a*m.c + m.b*m.d) / sx; k != 0 {
|
||||
t = t.Then(ui.Skewing(float32(deg(math.Atan(float64(k/sy)))), 0))
|
||||
}
|
||||
if m.b != 0 || m.a < 0 {
|
||||
t = t.Then(ui.Rotation(float32(deg(math.Atan2(float64(m.b), float64(m.a))))))
|
||||
}
|
||||
return t.Then(ui.Translation(m.e, m.f)), true
|
||||
}
|
||||
|
||||
// shape is a path drawn through a transform, in the coordinates of a
|
||||
// viewBox or of the indicator's own.
|
||||
type shape struct {
|
||||
ui.Path
|
||||
m affine
|
||||
}
|
||||
|
||||
func (s *shape) move(x, y float32) *shape { s.MoveTo(s.m.apply(x, y)); return s }
|
||||
|
||||
func (s *shape) line(x, y float32) *shape { s.LineTo(s.m.apply(x, y)); return s }
|
||||
|
||||
func (s *shape) cube(x1, y1, x2, y2, x, y float32) *shape {
|
||||
ax, ay := s.m.apply(x1, y1)
|
||||
bx, by := s.m.apply(x2, y2)
|
||||
cx, cy := s.m.apply(x, y)
|
||||
s.CubeTo(ax, ay, bx, by, cx, cy)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *shape) close() *shape { s.Close(); return s }
|
||||
|
||||
// arc adds the arc of the circle around (cx, cy) of radius r from angle
|
||||
// a0 to a1, in radians clockwise from the right, as SVG's circles start
|
||||
// and go: from its start if first, or a line to it.
|
||||
func (s *shape) arc(cx, cy, r float32, a0, a1 float64, first bool) *shape {
|
||||
at := func(a float64) (float32, float32) {
|
||||
sin, cos := math.Sincos(a)
|
||||
return cx + r*float32(cos), cy + r*float32(sin)
|
||||
}
|
||||
if first {
|
||||
s.move(at(a0))
|
||||
} else {
|
||||
s.line(at(a0))
|
||||
}
|
||||
n := int(math.Ceil(math.Abs(a1-a0) / (math.Pi / 2)))
|
||||
h := (a1 - a0) / float64(n)
|
||||
k := float32(4.0 / 3 * math.Tan(h/4))
|
||||
for i := range n {
|
||||
b0, b1 := a0+float64(i)*h, a0+float64(i+1)*h
|
||||
s0, c0 := math.Sincos(b0)
|
||||
s1, c1 := math.Sincos(b1)
|
||||
x0, y0 := cx+r*float32(c0), cy+r*float32(s0)
|
||||
x1, y1 := cx+r*float32(c1), cy+r*float32(s1)
|
||||
s.cube(x0-k*r*float32(s0), y0+k*r*float32(c0), x1+k*r*float32(s1), y1-k*r*float32(c1), x1, y1)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// circle adds a circle, counterclockwise if ccw, as a hole in one.
|
||||
func (s *shape) circle(cx, cy, r float32, ccw bool) *shape {
|
||||
if ccw {
|
||||
return s.arc(cx, cy, r, 0, -2*math.Pi, true).close()
|
||||
}
|
||||
return s.arc(cx, cy, r, 0, 2*math.Pi, true).close()
|
||||
}
|
||||
|
||||
// ring adds the ring between radii in and out, as a circle's border.
|
||||
func (s *shape) ring(cx, cy, out, in float32) *shape {
|
||||
s.circle(cx, cy, out, false)
|
||||
if in > 0 {
|
||||
s.circle(cx, cy, in, true)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// stroke draws an arc of the circle of radius r around (cx, cy) in the
|
||||
// shape's coordinates, w wide, from angle a0 to a1 (as arc's), ended as
|
||||
// Options.Cap says, at opacity a. m maps without turning: the arc is
|
||||
// drawn from angle 0 and turned to a0 by the renderer, so that an arc of
|
||||
// the same length is the same mask from frame to frame.
|
||||
func (d *drawing) stroke(m affine, cx, cy, r, w float32, a0, a1 float64, a float64) {
|
||||
if a1 <= a0 {
|
||||
return
|
||||
}
|
||||
d.turned(m, cx, cy, a0, func(m affine) {
|
||||
s := d.begin(m)
|
||||
if d.o.Cap == FlatCap {
|
||||
s.arc(cx, cy, r+w/2, 0, a1-a0, true)
|
||||
s.arc(cx, cy, r-w/2, a1-a0, 0, false).close()
|
||||
d.fill(a)
|
||||
return
|
||||
}
|
||||
s.arc(cx, cy, r, 0, a1-a0, true)
|
||||
d.p.StrokePath(&s.Path, w*m.unit(), d.alpha(a))
|
||||
})
|
||||
}
|
||||
|
||||
// turned draws what fn draws through m turned by angle radians clockwise
|
||||
// around (cx, cy) in m's coordinates. The renderer turns it: what fn
|
||||
// draws at rest is the same path from frame to frame, whose mask it
|
||||
// rasterizes once, where drawing it turned would rasterize another every
|
||||
// frame. fn draws through the m it is given, which rasterizes the mask
|
||||
// twice as fine, for the renderer to sample it turned as sharp.
|
||||
func (d *drawing) turned(m affine, cx, cy float32, angle float64, fn func(m affine)) {
|
||||
px, py := m.apply(cx, cy)
|
||||
d.p.Transform(ui.Scaling(0.5, 0.5).Then(ui.Rotation(float32(deg(angle)))), px, py, func() {
|
||||
fn(identity.scale(2, 2, px, py).then(m))
|
||||
})
|
||||
}
|
||||
|
||||
// rounded draws the rectangle (x, y, w, h) with corners of radius r in
|
||||
// m's coordinates, filled, or its border bw wide if bw > 0, at opacity
|
||||
// a. The renderers draw it themselves, through any transform, as an
|
||||
// element's background: no path to rasterize into a mask, as moving
|
||||
// paths need every frame. Its corners are the platform's: circles and
|
||||
// pills are round, smaller corners continuous on macOS.
|
||||
func (d *drawing) rounded(m affine, x, y, w, h, r, bw float32, a float64) {
|
||||
if t, ok := m.move(x, y).transform(); ok {
|
||||
d.roundedIn(t, w, h, r, bw, a)
|
||||
}
|
||||
}
|
||||
|
||||
// roundedIn is rounded through t, which maps the rectangle w×h at the
|
||||
// origin to the indicator.
|
||||
func (d *drawing) roundedIn(t ui.Transform, w, h, r, bw float32, a float64) {
|
||||
if w <= 0 || h <= 0 || a <= 0 {
|
||||
return
|
||||
}
|
||||
// Fill and Stroke put a rectangle and its border on whole pixels:
|
||||
// drawn zoom times as large and scaled back, they keep their sizes to
|
||||
// a zoom-th of a pixel, as they move and grow.
|
||||
const zoom = 8
|
||||
box := ui.Rect{W: w * zoom, H: h * zoom}
|
||||
c := d.alpha(a)
|
||||
d.p.Transform(ui.Scaling(1.0/zoom, 1.0/zoom).Then(t), 0, 0, func() {
|
||||
if bw > 0 {
|
||||
d.p.Stroke(box, c, r*zoom, bw*zoom)
|
||||
} else {
|
||||
d.p.Fill(box, c, r*zoom)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// dot draws the circle of radius r around (cx, cy) in m's coordinates at
|
||||
// opacity a.
|
||||
func (d *drawing) dot(m affine, cx, cy, r float32, a float64) {
|
||||
d.rounded(m, cx-r, cy-r, 2*r, 2*r, r, 0, a)
|
||||
}
|
||||
|
||||
// hoop draws the ring between radii out and in around (cx, cy) in m's
|
||||
// coordinates at opacity a, as a circle's border.
|
||||
func (d *drawing) hoop(m affine, cx, cy, out, in float32, a float64) {
|
||||
d.rounded(m, cx-out, cy-out, 2*out, 2*out, out, max(0, out-in), a)
|
||||
}
|
||||
|
||||
// dashes calls fn with each dash of a pattern of dashes dash long and
|
||||
// gaps gap long, shifted by offset as SVG's stroke-dashoffset shifts it,
|
||||
// on a path length long: from and to along it.
|
||||
func dashes(length, dash, gap, offset float64, fn func(from, to float64)) {
|
||||
period := dash + gap
|
||||
if dash <= 0 || period <= 0 {
|
||||
return
|
||||
}
|
||||
// From the last dash starting before the path.
|
||||
for at := math.Mod(-offset, period) - period; at < length; at += period {
|
||||
from, to := max(at, 0), min(at+dash, length)
|
||||
if to > from {
|
||||
fn(from, to)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// capsule draws the line from (x0, y0) to (x1, y1) in m's coordinates, w
|
||||
// wide, with round ends, at opacity a.
|
||||
func (d *drawing) capsule(m affine, x0, y0, x1, y1, w float32, a float64) {
|
||||
dx, dy := float64(x1-x0), float64(y1-y0)
|
||||
m = m.rotate(deg(math.Atan2(dy, dx)), x0, y0)
|
||||
l := float32(math.Hypot(dx, dy))
|
||||
d.rounded(m, x0-w/2, y0-w/2, l+w, w, w/2, 0, a)
|
||||
}
|
||||
|
||||
// polar returns the point at radius r and angle a (radians clockwise
|
||||
// from the right) around (cx, cy).
|
||||
func polar(cx, cy, r float32, a float64) (float32, float32) {
|
||||
s, c := math.Sincos(a)
|
||||
return cx + r*float32(c), cy + r*float32(s)
|
||||
}
|
||||
|
||||
// rad converts degrees to radians.
|
||||
func rad(deg float64) float64 { return deg * math.Pi / 180 }
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
// Package loading has the 29 loading indicators of loading.dev
|
||||
// (https://loading.dev, Jakub Krehel's loading-dev for React) for native
|
||||
// UI: arcs, dots, bars and blocks that MyGo draws itself, each a ui
|
||||
// element that moves as long as it shows.
|
||||
//
|
||||
// loading.Arc(c)
|
||||
// loading.Ring(c, loading.Options{Size: 32, Color: t.Accent, Easing: loading.EaseInOut})
|
||||
// ui.Row(c).Gap(8).Children(func() {
|
||||
// loading.BouncingDots(c, loading.Options{Size: 12})
|
||||
// ui.Text(c, "Thinking")
|
||||
// })
|
||||
//
|
||||
// An indicator is Options.Size DIPs high, 20 unless set, and as wide, or
|
||||
// wider for a row of dots; the element's own size, as Size or Fill set it,
|
||||
// scales it. It draws in the theme's text color unless Options.Color says
|
||||
// otherwise, and runs at loading.dev's pace unless Options.Duration says
|
||||
// otherwise. Where the desktop asks for less motion
|
||||
// (ui.Preferences.ReduceMotion) it stands still, in loading.dev's pose for
|
||||
// reduced motion; Options.Paused stops it where it is.
|
||||
//
|
||||
// Assistive technology sees a progress indicator of unknown length; name
|
||||
// it with Label.
|
||||
package loading
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// Options are the settings of an indicator, each meaning loading.dev's
|
||||
// default when zero.
|
||||
type Options struct {
|
||||
// Size is the indicator's height in DIPs, 20 if 0. Its width is the
|
||||
// same, except for BouncingDots's and LinearDots's rows of dots.
|
||||
Size float32
|
||||
// Color is what the indicator draws in, the theme's Text if zero.
|
||||
Color ui.Color
|
||||
// Duration is the time of one cycle of the indicator's motion, its
|
||||
// own (as loading.dev's) if 0.
|
||||
Duration time.Duration
|
||||
// Paused stops the indicator where it is, and it goes on from there
|
||||
// once false again, as CSS's paused animation-play-state.
|
||||
Paused bool
|
||||
// Easing is how the indicators that turn (Arc, Atom, Clock, Comet,
|
||||
// Dual, Orbit, Radar, Ring, Snake and Trace) turn: Linear by default.
|
||||
Easing Easing
|
||||
// Cap is the end of the strokes of Arc, Cascade, Dual, Ring, Snake
|
||||
// and Trace: RoundCap by default.
|
||||
Cap Cap
|
||||
// Sweep is the order in which Blocks's blocks shrink: Diagonal by
|
||||
// default.
|
||||
Sweep Sweep
|
||||
// Direction is where Ripple's rings go: RippleOut by default.
|
||||
Direction RippleDirection
|
||||
// Origin is where Wave's bars grow from: WaveCenter by default.
|
||||
Origin WaveOrigin
|
||||
}
|
||||
|
||||
// Easing is how an indicator that turns moves through a turn.
|
||||
type Easing uint8
|
||||
|
||||
const (
|
||||
// Linear turns at one speed.
|
||||
Linear Easing = iota
|
||||
// EaseInOut starts and ends each turn slowly, as CSS's ease-in-out.
|
||||
EaseInOut
|
||||
// Stacked adds a turn at one speed and one easing in and out: two
|
||||
// turns a cycle, fast in its middle.
|
||||
Stacked
|
||||
)
|
||||
|
||||
// Cap is how a stroke ends.
|
||||
type Cap uint8
|
||||
|
||||
const (
|
||||
// RoundCap ends a stroke in a half circle.
|
||||
RoundCap Cap = iota
|
||||
// FlatCap ends a stroke square, where it ends.
|
||||
FlatCap
|
||||
)
|
||||
|
||||
// Sweep is the order of Blocks's blocks.
|
||||
type Sweep uint8
|
||||
|
||||
const (
|
||||
// Diagonal sweeps from the top left corner to the bottom right one.
|
||||
Diagonal Sweep = iota
|
||||
// Rows sweeps from the top row down.
|
||||
Rows
|
||||
// Columns sweeps from the left column right.
|
||||
Columns
|
||||
)
|
||||
|
||||
// RippleDirection is where Ripple's rings go.
|
||||
type RippleDirection uint8
|
||||
|
||||
const (
|
||||
// RippleOut spreads the rings out from the center.
|
||||
RippleOut RippleDirection = iota
|
||||
// RippleIn draws the rings in to the center.
|
||||
RippleIn
|
||||
)
|
||||
|
||||
// WaveOrigin is where Wave's bars grow from.
|
||||
type WaveOrigin uint8
|
||||
|
||||
const (
|
||||
// WaveCenter grows the bars up and down from their middle.
|
||||
WaveCenter WaveOrigin = iota
|
||||
// WaveBottom grows the bars up from the bottom.
|
||||
WaveBottom
|
||||
)
|
||||
|
||||
// DefaultSize is an indicator's height when Options.Size is 0.
|
||||
const DefaultSize = 20
|
||||
|
||||
// A Spinner is one of the indicators, by name, as a gallery lists them.
|
||||
type Spinner struct {
|
||||
// Name is the indicator's name, as loading.dev's: "Arc", "Bouncing dots".
|
||||
Name string
|
||||
// New creates the indicator, as the function of its name does.
|
||||
New func(c *ui.Context, o ...Options) ui.Element
|
||||
}
|
||||
|
||||
// All returns the indicators, by name.
|
||||
func All() []Spinner {
|
||||
return []Spinner{
|
||||
{"Arc", Arc}, {"Atom", Atom}, {"Blocks", Blocks}, {"Bouncing dots", BouncingDots},
|
||||
{"Cascade", Cascade}, {"Circular dots", CircularDots}, {"Classic", Classic},
|
||||
{"Classic v2", ClassicV2}, {"Clock", Clock}, {"Comet", Comet}, {"Compass", Compass},
|
||||
{"Dual", Dual}, {"Eclipse", Eclipse}, {"Flip", Flip}, {"Gather", Gather}, {"Leap", Leap},
|
||||
{"Linear dots", LinearDots}, {"Loading", Loading}, {"Morph", Morph}, {"Orbit", Orbit},
|
||||
{"Pulse", Pulse}, {"Radar", Radar}, {"Ring", Ring}, {"Ripple", Ripple}, {"Slide", Slide},
|
||||
{"Snake", Snake}, {"Swirl", Swirl}, {"Trace", Trace}, {"Wave", Wave},
|
||||
}
|
||||
}
|
||||
|
||||
// spec is what an indicator is: how long its cycle is, how wide it is for
|
||||
// its height, and how it draws.
|
||||
type spec struct {
|
||||
cycle time.Duration
|
||||
aspect float32
|
||||
draw func(d *drawing)
|
||||
}
|
||||
|
||||
// timerKey keys an indicator's timer in its element.
|
||||
type timerKey struct{}
|
||||
|
||||
// timer is how long an indicator has run: since start, or held while
|
||||
// paused.
|
||||
type timer struct {
|
||||
start time.Time
|
||||
held time.Duration
|
||||
paused bool
|
||||
// sh is the shape the indicator draws with, its storage kept from
|
||||
// frame to frame.
|
||||
sh shape
|
||||
}
|
||||
|
||||
// show creates an indicator of s with the options given, at most one.
|
||||
func show(c *ui.Context, s *spec, opts []Options) ui.Element {
|
||||
if len(opts) > 1 {
|
||||
panic("loading: at most one Options")
|
||||
}
|
||||
var o Options
|
||||
if len(opts) == 1 {
|
||||
o = opts[0]
|
||||
}
|
||||
size := o.Size
|
||||
if size <= 0 {
|
||||
size = DefaultSize
|
||||
}
|
||||
color := o.Color
|
||||
if color == (ui.Color{}) {
|
||||
color = c.Theme().Text
|
||||
}
|
||||
cycle := s.cycle
|
||||
if o.Duration > 0 {
|
||||
cycle = o.Duration
|
||||
}
|
||||
still := c.Preferences().ReduceMotion
|
||||
// A progress indicator of unknown length, as ui.Spinner.
|
||||
e := ui.Box(c).Size(size*s.aspect, size).Shrink(0).Role(ui.RoleProgress).Range(0, 1, -1)
|
||||
now := c.Now()
|
||||
k := ui.Local(e, timerKey{}, func() timer { return timer{start: now} })
|
||||
switch {
|
||||
case o.Paused && !k.paused:
|
||||
k.held, k.paused = now.Sub(k.start), true
|
||||
case !o.Paused && k.paused:
|
||||
k.start, k.paused = now.Add(-k.held), false
|
||||
}
|
||||
e.Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
d := drawing{p: p, sh: &k.sh, color: color, o: o, still: still}
|
||||
d.s = min(r.H, r.W/s.aspect)
|
||||
d.x, d.y = r.X+(r.W-d.s*s.aspect)/2, r.Y+(r.H-d.s)/2
|
||||
if !still {
|
||||
ran := k.held
|
||||
if !k.paused {
|
||||
ran = p.Now().Sub(k.start)
|
||||
p.AnimationFrame()
|
||||
}
|
||||
d.cycles = float64(ran) / float64(cycle)
|
||||
}
|
||||
s.draw(&d)
|
||||
})
|
||||
return e
|
||||
}
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
package loading
|
||||
|
||||
import (
|
||||
"image"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// tester shows the indicator s alone, named by its name, with o.
|
||||
func tester(s Spinner, o *Options) *ui.Tester {
|
||||
return ui.NewTester(func(c *ui.Context) {
|
||||
ui.Column(c).Fill().Center().Background(ui.RGB(255, 255, 255)).Children(func() {
|
||||
s.New(c, *o).Label(s.Name)
|
||||
})
|
||||
}, 64, 64)
|
||||
}
|
||||
|
||||
// at returns the tester's frame at its time.
|
||||
func at(tt *ui.Tester) *image.RGBA {
|
||||
tt.Frame()
|
||||
return clone(tt.Image())
|
||||
}
|
||||
|
||||
func clone(img *image.RGBA) *image.RGBA {
|
||||
c := image.NewRGBA(img.Rect)
|
||||
copy(c.Pix, img.Pix)
|
||||
return c
|
||||
}
|
||||
|
||||
// ink counts the pixels not white inside r, and outside it.
|
||||
func ink(img *image.RGBA, r image.Rectangle) (in, out int) {
|
||||
b := img.Bounds()
|
||||
for y := b.Min.Y; y < b.Max.Y; y++ {
|
||||
for x := b.Min.X; x < b.Max.X; x++ {
|
||||
p := img.PixOffset(x, y)
|
||||
if img.Pix[p] > 250 && img.Pix[p+1] > 250 && img.Pix[p+2] > 250 {
|
||||
continue
|
||||
}
|
||||
if image.Pt(x, y).In(r) {
|
||||
in++
|
||||
} else {
|
||||
out++
|
||||
}
|
||||
}
|
||||
}
|
||||
return in, out
|
||||
}
|
||||
|
||||
// differ reports whether two frames differ by more than rounding.
|
||||
func differ(a, b *image.RGBA) bool {
|
||||
for i := range a.Pix {
|
||||
d := int(a.Pix[i]) - int(b.Pix[i])
|
||||
if d > 2 || d < -2 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestAll(t *testing.T) {
|
||||
all := All()
|
||||
if len(all) != 29 {
|
||||
t.Fatalf("%d indicators, want loading.dev's 29", len(all))
|
||||
}
|
||||
names := map[string]bool{}
|
||||
for _, s := range all {
|
||||
if names[s.Name] || s.New == nil {
|
||||
t.Errorf("indicator %q repeated or without its function", s.Name)
|
||||
}
|
||||
names[s.Name] = true
|
||||
}
|
||||
}
|
||||
|
||||
// Every indicator draws in its box, at every point of its cycle, and
|
||||
// nothing outside it.
|
||||
func TestDrawsInItsBox(t *testing.T) {
|
||||
o := Options{Size: 40, Duration: time.Second}
|
||||
for _, s := range All() {
|
||||
tt := tester(s, &o)
|
||||
r, ok := tt.Find(s.Name)
|
||||
if !ok {
|
||||
t.Fatalf("%s: not found", s.Name)
|
||||
}
|
||||
var aspect float32 = 1
|
||||
switch s.Name {
|
||||
case "Bouncing dots":
|
||||
aspect = 1.15
|
||||
case "Linear dots":
|
||||
aspect = 0.9375
|
||||
}
|
||||
if r.H != 40 || r.W != 40*aspect {
|
||||
t.Errorf("%s: %v×%v, want %v×40", s.Name, r.W, r.H, 40*aspect)
|
||||
}
|
||||
box := image.Rect(int(r.X)-1, int(r.Y)-1, int(r.X+r.W)+2, int(r.Y+r.H)+2)
|
||||
for step := range 8 {
|
||||
// Flip is edge on a quarter and three quarters into its cycle.
|
||||
if s.Name == "Flip" && step%4 == 2 {
|
||||
tt.Advance(time.Second / 8)
|
||||
continue
|
||||
}
|
||||
in, out := ink(at(tt), box)
|
||||
if in < 20 || out > 0 {
|
||||
t.Errorf("%s at %d/8: %d pixels drawn in its box, %d outside", s.Name, step, in, out)
|
||||
}
|
||||
tt.Advance(time.Second / 8)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every indicator moves, asking for frames as it does, and comes back
|
||||
// where it was after two cycles: Bouncing dots's go up in one and down in
|
||||
// the next.
|
||||
func TestMovesInCycles(t *testing.T) {
|
||||
o := Options{Duration: time.Second}
|
||||
for _, s := range All() {
|
||||
tt := tester(s, &o)
|
||||
start := at(tt)
|
||||
if !tt.FramePending() {
|
||||
t.Errorf("%s: asks for no frame", s.Name)
|
||||
}
|
||||
tt.Advance(300 * time.Millisecond)
|
||||
a := at(tt)
|
||||
tt.Advance(2 * time.Second)
|
||||
b := at(tt)
|
||||
if !differ(start, a) {
|
||||
t.Errorf("%s: the same 0.3 cycles in", s.Name)
|
||||
}
|
||||
if differ(a, b) {
|
||||
t.Errorf("%s: not the same two cycles later", s.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Where the desktop asks for less motion, an indicator stands still and
|
||||
// asks for no frames.
|
||||
func TestReduceMotion(t *testing.T) {
|
||||
var o Options
|
||||
for _, s := range All() {
|
||||
tt := tester(s, &o)
|
||||
tt.SetPreferences(ui.Preferences{ReduceMotion: true, TextScale: 1})
|
||||
still := at(tt)
|
||||
if tt.FramePending() {
|
||||
t.Errorf("%s: asks for frames at rest", s.Name)
|
||||
}
|
||||
tt.Advance(time.Second)
|
||||
if differ(still, at(tt)) {
|
||||
t.Errorf("%s: moves at rest", s.Name)
|
||||
}
|
||||
if in, _ := ink(still, still.Bounds()); in == 0 {
|
||||
t.Errorf("%s: draws nothing at rest", s.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Paused, an indicator stops where it is, and goes on from there.
|
||||
func TestPaused(t *testing.T) {
|
||||
o := Options{Duration: time.Second}
|
||||
for _, s := range All() {
|
||||
tt := tester(s, &o)
|
||||
tt.Advance(300 * time.Millisecond)
|
||||
o.Paused = true
|
||||
held := at(tt)
|
||||
if tt.FramePending() {
|
||||
t.Errorf("%s: asks for frames paused", s.Name)
|
||||
}
|
||||
tt.Advance(400 * time.Millisecond)
|
||||
if differ(held, at(tt)) {
|
||||
t.Errorf("%s: moves paused", s.Name)
|
||||
}
|
||||
o.Paused = false
|
||||
if differ(held, at(tt)) {
|
||||
t.Errorf("%s: not where it stopped as it goes on", s.Name)
|
||||
}
|
||||
tt.Advance(200 * time.Millisecond)
|
||||
if !differ(held, at(tt)) {
|
||||
t.Errorf("%s: does not go on", s.Name)
|
||||
}
|
||||
o.Paused = false
|
||||
}
|
||||
}
|
||||
|
||||
// An indicator draws in the color given, and in the theme's text color
|
||||
// without one.
|
||||
func TestColor(t *testing.T) {
|
||||
red := ui.RGB(255, 0, 0)
|
||||
for _, color := range []ui.Color{{}, red} {
|
||||
var text ui.Color
|
||||
img := ui.Render(func(c *ui.Context) {
|
||||
text = c.Theme().Text
|
||||
ui.Column(c).Fill().Center().Children(func() { Morph(c, Options{Size: 40, Color: color}) })
|
||||
}, 64, 64, 1)
|
||||
want := color
|
||||
if want == (ui.Color{}) {
|
||||
want = text
|
||||
}
|
||||
p := img.PixOffset(32, 32)
|
||||
if got := (ui.Color{R: img.Pix[p], G: img.Pix[p+1], B: img.Pix[p+2], A: 255}); got != want {
|
||||
t.Errorf("color %v: drawn in %v, want %v", color, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOneOptions(t *testing.T) {
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Error("two Options did not panic")
|
||||
}
|
||||
}()
|
||||
ui.Render(func(c *ui.Context) { Arc(c, Options{}, Options{}) }, 32, 32, 1)
|
||||
}
|
||||
|
||||
func TestBezier(t *testing.T) {
|
||||
for _, c := range []struct{ t, want float64 }{{0, 0}, {0.5, 0.5}, {1, 1}, {0.25, 0.1291}} {
|
||||
if got := easeInOut(c.t); got < c.want-1e-3 || got > c.want+1e-3 {
|
||||
t.Errorf("ease-in-out(%v) = %v, want %v", c.t, got, c.want)
|
||||
}
|
||||
}
|
||||
// Cascade's overshoots below 0 and past 1.
|
||||
if overshoot(0.1) >= 0 || overshoot(0.9) <= 1 {
|
||||
t.Errorf("overshoot: %v at 0.1, %v at 0.9", overshoot(0.1), overshoot(0.9))
|
||||
}
|
||||
}
|
||||
+651
@@ -0,0 +1,651 @@
|
||||
package loading
|
||||
|
||||
import (
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// The indicators follow loading.dev's, drawn in their SVG's viewBox or in
|
||||
// fractions of their size as its CSS places them, with its keyframes and
|
||||
// timing functions.
|
||||
|
||||
// identity is the transform that maps nothing elsewhere.
|
||||
var identity = affine{a: 1, d: 1}
|
||||
|
||||
// spin returns the angle, in radians, that an indicator turning once a
|
||||
// cycle has turned, as Options.Easing says, the other way if reverse; at
|
||||
// rest, rest.
|
||||
func (d *drawing) spin(reverse bool, rest float64) float64 {
|
||||
if d.still {
|
||||
return rest
|
||||
}
|
||||
return d.turn(d.at(0, 0), reverse) * 2 * math.Pi
|
||||
}
|
||||
|
||||
// deg converts radians to degrees.
|
||||
func deg(r float64) float64 { return r * 180 / math.Pi }
|
||||
|
||||
// center returns the middle of the indicator's square.
|
||||
func (d *drawing) center() (float32, float32) { return d.x + d.s/2, d.y + d.s/2 }
|
||||
|
||||
var arc = spec{cycle: 800 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
a := d.spin(false, 0)
|
||||
d.stroke(d.view(24), 12, 12, 10, 2.5, a, a+18.0/10, 1)
|
||||
}}
|
||||
|
||||
// Arc creates a single open stroke turning in a circle.
|
||||
func Arc(c *ui.Context, o ...Options) ui.Element { return show(c, &arc, o) }
|
||||
|
||||
var atom = spec{cycle: time.Second, aspect: 1, draw: func(d *drawing) {
|
||||
cx, cy := d.center()
|
||||
r := d.s / 2
|
||||
d.hoop(identity, cx, cy, r, r-0.055*d.s, 1)
|
||||
// Each orbit, tilted a third of a half turn more than the one before,
|
||||
// is a ring turning in 3D around its diameter, seen from the front: an
|
||||
// ellipse growing and shrinking across it.
|
||||
for i := range 3 {
|
||||
a := rad(60)
|
||||
if !d.still {
|
||||
a = d.turn(d.at(i, 3), false) * 2 * math.Pi
|
||||
}
|
||||
k := float32(math.Cos(a))
|
||||
if math.Abs(float64(k)) < 1e-4 {
|
||||
continue
|
||||
}
|
||||
d.hoop(identity.rotate(float64(i)*60, cx, cy).scale(k, 1, cx, cy), cx, cy, r, r-0.045*d.s, 1)
|
||||
}
|
||||
}}
|
||||
|
||||
// Atom creates three rings tumbling inside a circle.
|
||||
func Atom(c *ui.Context, o ...Options) ui.Element { return show(c, &atom, o) }
|
||||
|
||||
var blocks = spec{cycle: 1300 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
cell, gap := d.s*0.8/3, d.s*0.1
|
||||
for row := range 3 {
|
||||
for col := range 3 {
|
||||
place, count := row+col, 5
|
||||
switch d.o.Sweep {
|
||||
case Rows:
|
||||
place, count = row, 3
|
||||
case Columns:
|
||||
place, count = col, 3
|
||||
}
|
||||
k := 0.8
|
||||
if !d.still {
|
||||
k = frames(d.at(place, count), easeInOut, key{0, 1}, key{0.35, 0}, key{0.7, 1}, key{1, 1})
|
||||
}
|
||||
if k <= 0 {
|
||||
continue
|
||||
}
|
||||
x, y := d.x+float32(col)*(cell+gap), d.y+float32(row)*(cell+gap)
|
||||
sk := float32(k)
|
||||
d.rounded(identity.scale(sk, sk, x+cell/2, y+cell/2), x, y, cell, cell, 0.0625*d.s, 0, 1)
|
||||
}
|
||||
}
|
||||
}}
|
||||
|
||||
// Blocks creates nine blocks shrinking and growing in a sweep across a
|
||||
// grid, in the order Options.Sweep says.
|
||||
func Blocks(c *ui.Context, o ...Options) ui.Element { return show(c, &blocks, o) }
|
||||
|
||||
var bouncingDots = spec{cycle: 500 * time.Millisecond, aspect: 1.15, draw: func(d *drawing) {
|
||||
dot := 0.25 * d.s
|
||||
for i := range 3 {
|
||||
// Up and down on alternate cycles.
|
||||
y := 0.0
|
||||
if !d.still {
|
||||
t := d.cycles + float64(3-i)/3
|
||||
n := math.Floor(t)
|
||||
p := t - n
|
||||
if int64(n)%2 == 1 {
|
||||
p = 1 - p
|
||||
}
|
||||
y = 0.28 - easeInOut(p)
|
||||
}
|
||||
cx := d.x + dot/2 + float32(i)*0.45*d.s
|
||||
d.dot(identity, cx, d.y+d.s/2+float32(y)*dot, dot/2, 1)
|
||||
}
|
||||
}}
|
||||
|
||||
// BouncingDots creates three staggered dots bouncing up and down, in a
|
||||
// row 1.15 times as wide as it is high.
|
||||
func BouncingDots(c *ui.Context, o ...Options) ui.Element { return show(c, &bouncingDots, o) }
|
||||
|
||||
var cascade = spec{cycle: 1500 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
for i, r := range [3]float32{10.5, 7, 3.5} {
|
||||
a := 0.0
|
||||
if !d.still {
|
||||
a = overshoot(d.at(i, 24)) * 2 * math.Pi
|
||||
}
|
||||
d.stroke(d.view(24), 12, 12, r, 2, a, a+math.Pi/2, 1)
|
||||
}
|
||||
}}
|
||||
|
||||
// Cascade creates three nested arcs fanning into a spiral, then snapping
|
||||
// back in line.
|
||||
func Cascade(c *ui.Context, o ...Options) ui.Element { return show(c, &cascade, o) }
|
||||
|
||||
// eightDots are Circular dots' dots, in a viewBox of 16.
|
||||
var eightDots = [8][2]float32{
|
||||
{8, 1.5}, {12.5962, 3.4038}, {14.5, 8}, {12.5962, 12.5962},
|
||||
{8, 14.5}, {3.4038, 12.5962}, {1.5, 8}, {3.4038, 3.4038},
|
||||
}
|
||||
|
||||
var circularDots = spec{cycle: 800 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
for i, at := range eightDots {
|
||||
d.dot(d.view(16), at[0], at[1], 1.5, d.fade(i, 8, 0.2, 0.6))
|
||||
}
|
||||
}}
|
||||
|
||||
// CircularDots creates eight dots in a ring, the brightest going around.
|
||||
func CircularDots(c *ui.Context, o ...Options) ui.Element { return show(c, &circularDots, o) }
|
||||
|
||||
var classic = spec{cycle: 1200 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
// The bars are placed as loading.dev's CSS places them: around a point
|
||||
// a little right of the middle.
|
||||
cx, cy := d.x+0.52*d.s, d.y+0.501*d.s
|
||||
w, h := 0.24*d.s, 0.08*d.s
|
||||
for i := range 12 {
|
||||
m := identity.rotate(float64(i)*30, cx, cy).move(1.46*w, 0)
|
||||
d.rounded(m, cx-w/2, cy-h/2, w, h, min(6, h/2), 0, d.fade(i, 12, 0.15, 0.5))
|
||||
}
|
||||
}}
|
||||
|
||||
// Classic creates twelve fading bars in a radial pattern.
|
||||
func Classic(c *ui.Context, o ...Options) ui.Element { return show(c, &classic, o) }
|
||||
|
||||
var classicV2 = spec{cycle: 800 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
for i := range 8 {
|
||||
d.capsule(d.view(16).rotate(float64(i)*45, 8, 8), 8, 2.0/3, 8, 10.0/3, 4.0/3, d.fade(i, 8, 0.4, 0.5))
|
||||
}
|
||||
}}
|
||||
|
||||
// ClassicV2 creates eight ticks in a ring, lit in turn.
|
||||
func ClassicV2(c *ui.Context, o ...Options) ui.Element { return show(c, &classicV2, o) }
|
||||
|
||||
var clock = spec{cycle: 1200 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
v := d.view(16)
|
||||
d.dot(v, 8, 8, 8, 0.1)
|
||||
d.turned(v, 8, 8, d.spin(false, 0), d.hand)
|
||||
}}
|
||||
|
||||
// hand draws Clock's hand through v, in its viewBox of 16, pointing up.
|
||||
func (d *drawing) hand(v affine) {
|
||||
s := d.begin(v)
|
||||
s.move(11.1937, 2.92061)
|
||||
s.cube(10.5206, 2.49739, 9.77304, 2.21397, 8.9954, 2.08314)
|
||||
s.cube(8.45076, 1.99151, 8, 2.44772, 8, 3)
|
||||
s.line(8, 7.20324)
|
||||
s.cube(8, 7.49211, 8.12492, 7.76686, 8.34259, 7.95677)
|
||||
s.line(11.8999, 11.0603)
|
||||
s.cube(12.3287, 11.4344, 12.9913, 11.378, 13.2643, 10.8787)
|
||||
s.cube(13.6356, 10.1998, 13.8736, 9.45248, 13.9617, 8.67713)
|
||||
s.cube(14.0892, 7.55433, 13.8971, 6.41834, 13.4074, 5.39993)
|
||||
s.cube(12.9177, 4.38152, 12.1503, 3.5221, 11.1937, 2.92061)
|
||||
s.close()
|
||||
d.fill(1)
|
||||
}
|
||||
|
||||
// Clock creates a clock hand sweeping around a faint face.
|
||||
func Clock(c *ui.Context, o ...Options) ui.Element { return show(c, &clock, o) }
|
||||
|
||||
var comet = spec{cycle: 700 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
cx, cy := d.center()
|
||||
r, w := d.s/2, 0.12*d.s
|
||||
a := deg(d.spin(false, 0))
|
||||
// The tail, a ring fading in from transparent around a turn, and the
|
||||
// head at its end.
|
||||
s := d.begin(identity).ring(cx, cy, r, r-w)
|
||||
d.p.FillPathConicGradient(&s.Path, ui.ConicGradient{Angle: float32(a), Stops: []ui.GradientStop{
|
||||
{Color: d.alpha(0), At: 0}, {Color: d.color, At: 1},
|
||||
}})
|
||||
d.dot(identity.rotate(a, cx, cy), cx, d.y+w/2, w/2, 1)
|
||||
}}
|
||||
|
||||
// Comet creates a full ring fading into its tail.
|
||||
func Comet(c *ui.Context, o ...Options) ui.Element { return show(c, &comet, o) }
|
||||
|
||||
var compass = spec{cycle: 500 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
a := 0.0
|
||||
if !d.still {
|
||||
a = 90 * easeInOut(d.at(0, 0))
|
||||
}
|
||||
for i := range 4 {
|
||||
d.capsule(d.view(16).rotate(a+float64(i)*90, 8, 8), 8, 2.0/3, 8, 10.0/3, 4.0/3, 1)
|
||||
}
|
||||
}}
|
||||
|
||||
// Compass creates four ticks turning a quarter turn at a time.
|
||||
func Compass(c *ui.Context, o ...Options) ui.Element { return show(c, &compass, o) }
|
||||
|
||||
var dual = spec{cycle: time.Second, aspect: 1, draw: func(d *drawing) {
|
||||
v := d.view(24)
|
||||
a := d.spin(false, 0)
|
||||
d.stroke(v, 12, 12, 10, 2.5, a, a+18.0/10, 1)
|
||||
b := d.spin(true, math.Pi)
|
||||
d.stroke(v, 12, 12, 5.5, 2.5, b, b+10/5.5, 1)
|
||||
}}
|
||||
|
||||
// Dual creates two arcs turning in opposite directions.
|
||||
func Dual(c *ui.Context, o ...Options) ui.Element { return show(c, &dual, o) }
|
||||
|
||||
var eclipse = spec{cycle: 1200 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
cx, cy := d.center()
|
||||
dot := 0.4 * d.s
|
||||
for i := range 2 {
|
||||
// Across and back, nearer (larger) on the way there and farther
|
||||
// on the way back.
|
||||
x, a, k := float64(i)*1.5-0.75, 1.0, 1.0
|
||||
if !d.still {
|
||||
p := d.at(i, 2)
|
||||
x = frames(p, easeInOut, key{0, 0.75}, key{0.5, -0.75}, key{1, 0.75})
|
||||
a = frames(p, easeInOut, key{0, 0.75}, key{0.25, 1}, key{0.5, 0.75}, key{0.75, 0.5}, key{1, 0.75})
|
||||
k = frames(p, easeInOut, key{0, 1}, key{0.25, 1.3}, key{0.5, 1}, key{0.75, 0.7}, key{1, 1})
|
||||
}
|
||||
d.dot(identity, cx+float32(x)*dot, cy, dot/2*float32(k), a)
|
||||
}
|
||||
}}
|
||||
|
||||
// Eclipse creates two dots trading places, one passing behind the other.
|
||||
func Eclipse(c *ui.Context, o ...Options) ui.Element { return show(c, &eclipse, o) }
|
||||
|
||||
var flip = spec{cycle: 1200 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
cx, cy := d.center()
|
||||
half, r := 0.32*d.s, 0.06*d.s
|
||||
ax, ay := 0.0, 0.0
|
||||
if !d.still {
|
||||
p := d.at(0, 0)
|
||||
ax = frames(p, easeInOut, key{0, 0}, key{0.5, -180}, key{1, -180})
|
||||
ay = frames(p, easeInOut, key{0, 0}, key{0.5, 0}, key{1, -180})
|
||||
}
|
||||
// The square turned in 3D, around its horizontal axis and then its
|
||||
// vertical one (CSS's rotateX(ax) rotateY(ay)), seen in perspective
|
||||
// from three times the indicator's size.
|
||||
t := ui.Translation(-half, -half).Then(ui.RotationY(float32(ay))).Then(ui.RotationX(float32(ax))).
|
||||
Then(ui.Perspective(3 * d.s)).Then(ui.Translation(cx, cy))
|
||||
d.roundedIn(t, 2*half, 2*half, r, 0, 1)
|
||||
}}
|
||||
|
||||
// Flip creates a square flipping over one axis, then the other.
|
||||
func Flip(c *ui.Context, o ...Options) ui.Element { return show(c, &flip, o) }
|
||||
|
||||
var gather = spec{cycle: 1600 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
cx, cy := d.center()
|
||||
b, gap := 0.38*d.s, 0.24*d.s
|
||||
pull, turn := 0.0, 0.0
|
||||
if !d.still {
|
||||
p := d.at(0, 0)
|
||||
pull = frames(p, easeInOut, key{0, 0}, key{0.3, 1}, key{0.6, 1}, key{1, 0})
|
||||
turn = frames(p, easeInOut, key{0, 0}, key{0.3, 0}, key{0.6, 90}, key{1, 90})
|
||||
}
|
||||
// Each block pulls in toward the middle by a fifth of its size.
|
||||
in := float32(pull) * 0.211 * b
|
||||
m := identity.rotate(turn, cx, cy)
|
||||
for i := range 4 {
|
||||
col, row := float32(i%2), float32(i/2)
|
||||
x := d.x + col*(b+gap) + (1-2*col)*in
|
||||
y := d.y + row*(b+gap) + (1-2*row)*in
|
||||
d.rounded(m, x, y, b, b, 0.14*d.s, 0, 1)
|
||||
}
|
||||
}}
|
||||
|
||||
// Gather creates four blocks pulling together, turning, and pushing
|
||||
// apart.
|
||||
func Gather(c *ui.Context, o ...Options) ui.Element { return show(c, &gather, o) }
|
||||
|
||||
var leap = spec{cycle: 1800 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
// Whole DIPs, as loading.dev rounds them to pixels.
|
||||
round := func(v float32) float32 { return float32(math.Round(float64(v))) }
|
||||
dot := round(0.22 * d.s)
|
||||
gap := float32(math.Floor(float64(d.s-dot) / 2))
|
||||
top := round((d.s - dot) / 2)
|
||||
left := d.s - dot - 2*gap
|
||||
// The middle of the stretch a dot leaps over.
|
||||
mx, my := d.x+left+gap+dot/2, d.y+top+dot/2
|
||||
for i := range 3 {
|
||||
// The last dot leaps over the others to the front, as they slide
|
||||
// back a place each.
|
||||
x, a := float64(i)*float64(gap), 0.0
|
||||
if !d.still {
|
||||
p := d.at(i, 3)
|
||||
g := float64(gap)
|
||||
x = frames(p, easeInOut, key{0, 0}, key{0.3333, 0}, key{0.6666, -g}, key{1, -2 * g})
|
||||
a = frames(p, easeInOut, key{0, 0}, key{0.3333, 180}, key{0.6666, 180}, key{1, 180})
|
||||
}
|
||||
px, py := polar(mx+float32(x), my, gap, rad(a+180))
|
||||
d.dot(identity, px, py, dot/2, 1)
|
||||
}
|
||||
}}
|
||||
|
||||
// Leap creates three dots in a row, the last one leaping to the front.
|
||||
func Leap(c *ui.Context, o ...Options) ui.Element { return show(c, &leap, o) }
|
||||
|
||||
var linearDots = spec{cycle: 900 * time.Millisecond, aspect: 0.9375, draw: func(d *drawing) {
|
||||
dot := 0.1875 * d.s
|
||||
for i := range 3 {
|
||||
a := 0.75
|
||||
if !d.still {
|
||||
a = frames(d.at(i, 3), linearEase, key{0, 1}, key{0.6667, 0.5}, key{1, 1})
|
||||
}
|
||||
d.dot(identity, d.x+dot/2+float32(i)*2*dot, d.y+d.s/2, dot/2, a)
|
||||
}
|
||||
}}
|
||||
|
||||
// LinearDots creates three dots lighting up in turn from left to right,
|
||||
// in a row nearly as wide as it is high.
|
||||
func LinearDots(c *ui.Context, o ...Options) ui.Element { return show(c, &linearDots, o) }
|
||||
|
||||
// segments are where the Loading mark's segments are, in a viewBox of 15.
|
||||
var segments = [8][2]float32{{12, 6}, {10, 10}, {6, 12}, {2, 10}, {0, 6}, {2, 2}, {6, 0}, {10, 2}}
|
||||
|
||||
var loadingMark = spec{cycle: time.Second, aspect: 1, draw: func(d *drawing) {
|
||||
v := d.view(15)
|
||||
for i, at := range segments {
|
||||
a := d.fade(i, 8, 0.2, 0.6)
|
||||
for _, b := range [4][2]float32{{0, 0}, {2, 0}, {0, 2}, {2, 2}} {
|
||||
d.rounded(v, at[0]+b[0], at[1]+b[1], 1, 1, 0, 0, a)
|
||||
}
|
||||
}
|
||||
}}
|
||||
|
||||
// Loading creates the loading.dev mark, its brightest segment circling
|
||||
// the ring.
|
||||
func Loading(c *ui.Context, o ...Options) ui.Element { return show(c, &loadingMark, o) }
|
||||
|
||||
var morph = spec{cycle: 1200 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
cx, cy := d.center()
|
||||
side := 0.64 * d.s
|
||||
r, a := 0.08*float64(d.s), 0.0
|
||||
if !d.still {
|
||||
p := d.at(0, 0)
|
||||
r = frames(p, easeInOut, key{0, r}, key{0.5, float64(side) / 2}, key{1, r})
|
||||
a = frames(p, easeInOut, key{0, 0}, key{0.5, 45}, key{1, 90})
|
||||
}
|
||||
d.rounded(identity.rotate(a, cx, cy), cx-side/2, cy-side/2, side, side, float32(r), 0, 1)
|
||||
}}
|
||||
|
||||
// Morph creates a square rounding into a circle and back as it turns.
|
||||
func Morph(c *ui.Context, o ...Options) ui.Element { return show(c, &morph, o) }
|
||||
|
||||
var orbit = spec{cycle: 750 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
cx, cy := d.center()
|
||||
d.dot(identity, cx, cy, 0.125*d.s, 1)
|
||||
// Half a ring, from transparent at its start to opaque at its end.
|
||||
r, w := 0.42*d.s, 0.0625*d.s
|
||||
d.turned(identity, cx, cy, d.spin(false, 0), func(m affine) {
|
||||
a0, a1 := math.Pi/2, 3*math.Pi/2
|
||||
s := d.begin(m).arc(cx, cy, r, a0, a1, true).arc(cx, cy, r-w, a1, a0, false).close()
|
||||
// Empty subpaths at the corners of the whole ring's box, which the
|
||||
// gradient turns around the middle of.
|
||||
s.move(cx-r, cy-r).line(cx-r, cy-r).close().move(cx+r, cy+r).line(cx+r, cy+r).close()
|
||||
d.p.FillPathConicGradient(&s.Path, ui.ConicGradient{Angle: 180, Stops: []ui.GradientStop{
|
||||
{Color: d.alpha(0), At: 0}, {Color: d.color, At: 0.5}, {Color: d.color, At: 1},
|
||||
}})
|
||||
})
|
||||
}}
|
||||
|
||||
// Orbit creates a fading half ring turning around a dot.
|
||||
func Orbit(c *ui.Context, o ...Options) ui.Element { return show(c, &orbit, o) }
|
||||
|
||||
var pulse = spec{cycle: 1200 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
v := d.view(16)
|
||||
k, a := 1.0, 0.2
|
||||
if !d.still {
|
||||
e := easeOut(d.at(0, 0))
|
||||
k, a = 0.25+0.75*e, 0.4*(1-e)
|
||||
}
|
||||
d.dot(v, 8, 8, 8*float32(k), a)
|
||||
d.dot(v, 8, 8, 2, 1)
|
||||
}}
|
||||
|
||||
// Pulse creates a ring rippling outward from a dot.
|
||||
func Pulse(c *ui.Context, o ...Options) ui.Element { return show(c, &pulse, o) }
|
||||
|
||||
var radar = spec{cycle: 1500 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
v := d.view(16)
|
||||
d.dot(v, 8, 8, 8, 0.2)
|
||||
d.hoop(v, 8, 8, 6, 5, 0.2)
|
||||
d.turned(v, 8, 8, d.spin(false, 0), d.beam)
|
||||
d.dot(v, 8, 8, 2, 1)
|
||||
}}
|
||||
|
||||
// beam draws Radar's beam through m, in its viewBox of 16: a sector of
|
||||
// the ring between radii 3 and 8, from the top to its leading edge,
|
||||
// opaque inside a third of the radius and fading to transparent at its
|
||||
// rim, as loading.dev's radial gradient.
|
||||
func (d *drawing) beam(m affine) {
|
||||
const in, out, solid = 3, 8, 8 * 0.3334
|
||||
// The leading edge, from the inner circle to the outer one.
|
||||
ix, iy, ox, oy := 10.4707-8, 9.69922-8, 14.249-8, 12.9951-8
|
||||
opacity := func(r float64) float64 { return max(0, min(1, 1-(r-solid)/(out-solid))) }
|
||||
// Sectors of growing radii over each other, each as opaque as makes
|
||||
// the ring between its radius and the one before the gradient's
|
||||
// opacity there: their edges inside the beam meet no other edge, as
|
||||
// bands side by side would.
|
||||
n := int(max(6, min(40, math.Ceil(float64(out-in)*float64(m.unit())/1.5))))
|
||||
band := func(k int) float64 { return in + (out-in)*(float64(k)-0.5)/float64(n) }
|
||||
for k := 1; k <= n; k++ {
|
||||
inside, beyond := opacity(band(k)), 0.0
|
||||
if k < n {
|
||||
beyond = opacity(band(k + 1))
|
||||
}
|
||||
a := 1 - (1-inside)/(1-beyond)
|
||||
r := in + (out-in)*float64(k)/float64(n)
|
||||
// Where the leading edge crosses the circle of radius r.
|
||||
dx, dy := ox-ix, oy-iy
|
||||
qa, qb, qc := dx*dx+dy*dy, 2*(ix*dx+iy*dy), ix*ix+iy*iy-r*r
|
||||
u := max(0, min(1, (-qb+math.Sqrt(max(0, qb*qb-4*qa*qc)))/(2*qa)))
|
||||
end := math.Atan2(iy+u*dy, ix+u*dx)
|
||||
s := d.begin(m)
|
||||
s.move(8, 8-in).line(8, 8-float32(r))
|
||||
s.arc(8, 8, float32(r), -math.Pi/2, end, false)
|
||||
s.line(float32(8+ix), float32(8+iy))
|
||||
s.arc(8, 8, in, math.Atan2(iy, ix), -math.Pi/2, false).close()
|
||||
d.fill(a)
|
||||
}
|
||||
}
|
||||
|
||||
// Radar creates a fading beam sweeping around a faint dish.
|
||||
func Radar(c *ui.Context, o ...Options) ui.Element { return show(c, &radar, o) }
|
||||
|
||||
var ring = spec{cycle: 800 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
v := d.view(24)
|
||||
d.hoop(v, 12, 12, 11.25, 8.75, 0.2)
|
||||
a := d.spin(false, 0)
|
||||
d.stroke(v, 12, 12, 10, 2.5, a, a+16.0/10, 1)
|
||||
}}
|
||||
|
||||
// Ring creates an arc turning in a faint circle.
|
||||
func Ring(c *ui.Context, o ...Options) ui.Element { return show(c, &ring, o) }
|
||||
|
||||
var ripple = spec{cycle: 1200 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
cx, cy := d.center()
|
||||
for i := range 3 {
|
||||
k, a := float64(i+1)/3, 0.4
|
||||
if !d.still {
|
||||
p := d.at(i, 3)
|
||||
if d.o.Direction == RippleIn {
|
||||
p = 1 - p
|
||||
}
|
||||
e := easeOut(p)
|
||||
k, a = e, 1-e
|
||||
}
|
||||
if k <= 0 {
|
||||
continue
|
||||
}
|
||||
r := d.s / 2 * float32(k)
|
||||
d.hoop(identity, cx, cy, r, r-0.08*d.s*float32(k), a)
|
||||
}
|
||||
}}
|
||||
|
||||
// Ripple creates three rings spreading out from the center, or drawing in
|
||||
// to it, as Options.Direction says.
|
||||
func Ripple(c *ui.Context, o ...Options) ui.Element { return show(c, &ripple, o) }
|
||||
|
||||
var slide = spec{cycle: 2400 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
dot := 0.34 * d.s
|
||||
far := 1.588 * float64(dot)
|
||||
rest := [3][2]float64{{far, 0}, {0, 0}, {0, far}}
|
||||
for i := range 3 {
|
||||
// Around the square's corners, to the one empty, and waiting
|
||||
// there for the others.
|
||||
x, y := rest[i][0], rest[i][1]
|
||||
if !d.still {
|
||||
p := d.at(i, 3)
|
||||
x = frames(p, easeInOut, key{0, far}, key{0.0833, far}, key{0.25, far}, key{0.3333, 0}, key{0.5, 0},
|
||||
key{0.5833, 0}, key{0.75, 0}, key{0.8333, far}, key{1, far})
|
||||
y = frames(p, easeInOut, key{0, 0}, key{0.0833, far}, key{0.25, far}, key{0.3333, far}, key{0.5, far},
|
||||
key{0.5833, 0}, key{0.75, 0}, key{0.8333, 0}, key{1, 0})
|
||||
}
|
||||
d.dot(identity, d.x+0.06*d.s+dot/2+float32(x), d.y+0.06*d.s+dot/2+float32(y), dot/2, 1)
|
||||
}
|
||||
}}
|
||||
|
||||
// Slide creates three dots sliding into the empty corner of a square.
|
||||
func Slide(c *ui.Context, o ...Options) ui.Element { return show(c, &slide, o) }
|
||||
|
||||
var snake = spec{cycle: 1400 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
v := d.view(24)
|
||||
a := d.spin(false, 0)
|
||||
// A dash stretching to 45 long, then going on at that length, as its
|
||||
// start catches up with its end.
|
||||
dash, offset := 18.0, 0.0
|
||||
if !d.still {
|
||||
p := d.at(0, 0)
|
||||
dash = frames(p, easeInOut, key{0, 1}, key{0.5, 45}, key{1, 45})
|
||||
offset = frames(p, easeInOut, key{0, 0}, key{0.5, -17}, key{1, -62})
|
||||
}
|
||||
dashes(2*math.Pi*10, dash, 100, offset, func(from, to float64) {
|
||||
d.stroke(v, 12, 12, 10, 2.5, a+from/10, a+to/10, 1)
|
||||
})
|
||||
}}
|
||||
|
||||
// Snake creates an arc stretching and shrinking as it circles.
|
||||
func Snake(c *ui.Context, o ...Options) ui.Element { return show(c, &snake, o) }
|
||||
|
||||
// swirlSteps are the order of Swirl's cells, by rows, around the grid,
|
||||
// -1 for its empty middle.
|
||||
var swirlSteps = [9]int{0, 1, 2, 7, -1, 3, 6, 5, 4}
|
||||
|
||||
var swirl = spec{cycle: 1200 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
pad, gap := 0.0625*d.s, 0.15625*d.s
|
||||
cell := (d.s - 2*pad - 2*gap) / 3
|
||||
for i, step := range swirlSteps {
|
||||
if step < 0 {
|
||||
continue
|
||||
}
|
||||
x, y := d.x+pad+float32(i%3)*(cell+gap), d.y+pad+float32(i/3)*(cell+gap)
|
||||
d.rounded(identity, x, y, cell, cell, 0.0625*d.s, 0, d.fade(step, 8, 0.2, 0.6))
|
||||
}
|
||||
}}
|
||||
|
||||
// Swirl creates a bright cell chasing its trail around a square.
|
||||
func Swirl(c *ui.Context, o ...Options) ui.Element { return show(c, &swirl, o) }
|
||||
|
||||
// Trace's rounded square, in its viewBox of 20, and its dash.
|
||||
const (
|
||||
traceAt, traceSide, traceRadius, traceWidth = 1.25, 17.5, 4, 2.5
|
||||
traceDash = 16
|
||||
)
|
||||
|
||||
// tracePerimeter is the length of Trace's rounded square.
|
||||
var tracePerimeter = 4*(traceSide-2*traceRadius) + 2*math.Pi*traceRadius
|
||||
|
||||
var trace = spec{cycle: 1200 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
v := d.view(20)
|
||||
const out = traceWidth / 2
|
||||
d.rounded(v, traceAt-out, traceAt-out, traceSide+2*out, traceSide+2*out, traceRadius+out, traceWidth, 0.2)
|
||||
at := 0.0
|
||||
if !d.still {
|
||||
at = d.turn(d.at(0, 0), false) * tracePerimeter
|
||||
}
|
||||
dashes(tracePerimeter, traceDash, tracePerimeter-traceDash, -at, func(from, to float64) {
|
||||
d.traceDash(v, from, to)
|
||||
})
|
||||
}}
|
||||
|
||||
// traceDash draws Trace's dash from from to to along its rounded square,
|
||||
// through v.
|
||||
func (d *drawing) traceDash(v affine, from, to float64) {
|
||||
// along returns the point at length u along the square, from the
|
||||
// start of its top side, as SVG's rect starts, and the direction it
|
||||
// goes there, in radians.
|
||||
const straight = traceSide - 2*traceRadius
|
||||
corner := math.Pi / 2 * traceRadius
|
||||
along := func(u float64) (x, y, dir float64) {
|
||||
side := min(3, int(u/(straight+corner)))
|
||||
u -= float64(side) * (straight + corner)
|
||||
dir = float64(side) * math.Pi / 2
|
||||
sin, cos := math.Sincos(dir)
|
||||
// Where the side starts: the top's after the top left corner.
|
||||
starts := [4][2]float64{
|
||||
{traceAt + traceRadius, traceAt}, {traceAt + traceSide, traceAt + traceRadius},
|
||||
{traceAt + traceSide - traceRadius, traceAt + traceSide}, {traceAt, traceAt + traceSide - traceRadius},
|
||||
}
|
||||
x, y = starts[side][0], starts[side][1]
|
||||
if u <= straight {
|
||||
return x + u*cos, y + u*sin, dir
|
||||
}
|
||||
// Around the corner, whose center is inward of the side's end.
|
||||
x, y = x+straight*cos-traceRadius*sin, y+straight*sin+traceRadius*cos
|
||||
a := dir - math.Pi/2 + (u-straight)/traceRadius
|
||||
sa, ca := math.Sincos(a)
|
||||
return x + traceRadius*ca, y + traceRadius*sa, a + math.Pi/2
|
||||
}
|
||||
n := int(math.Ceil((to-from)/0.4)) + 1
|
||||
s := d.begin(v)
|
||||
if d.o.Cap == FlatCap {
|
||||
// The dash's outline: one edge there, the other back.
|
||||
for i := range 2 * n {
|
||||
j, side := i, -1.0
|
||||
if i >= n {
|
||||
j, side = 2*n-1-i, 1
|
||||
}
|
||||
x, y, dir := along(from + (to-from)*float64(j)/float64(n-1))
|
||||
sin, cos := math.Sincos(dir)
|
||||
px, py := float32(x-side*traceWidth/2*sin), float32(y+side*traceWidth/2*cos)
|
||||
if i == 0 {
|
||||
s.move(px, py)
|
||||
} else {
|
||||
s.line(px, py)
|
||||
}
|
||||
}
|
||||
s.close()
|
||||
d.fill(1)
|
||||
return
|
||||
}
|
||||
for i := range n {
|
||||
x, y, _ := along(from + (to-from)*float64(i)/float64(n-1))
|
||||
if i == 0 {
|
||||
s.move(float32(x), float32(y))
|
||||
} else {
|
||||
s.line(float32(x), float32(y))
|
||||
}
|
||||
}
|
||||
d.p.StrokePath(&s.Path, traceWidth*v.unit(), d.color)
|
||||
}
|
||||
|
||||
// Trace creates a dash tracing the outline of a rounded square.
|
||||
func Trace(c *ui.Context, o ...Options) ui.Element { return show(c, &trace, o) }
|
||||
|
||||
var wave = spec{cycle: 900 * time.Millisecond, aspect: 1, draw: func(d *drawing) {
|
||||
w := 0.12 * d.s
|
||||
for i := range 5 {
|
||||
h := 0.4 + 0.15*float64(i)
|
||||
if !d.still {
|
||||
h = frames(d.at(i, 5), easeInOut, key{0, 0.3}, key{0.5, 1}, key{1, 0.3})
|
||||
}
|
||||
bh := float32(h) * d.s
|
||||
y := d.y + (d.s-bh)/2
|
||||
if d.o.Origin == WaveBottom {
|
||||
y = d.y + d.s - bh
|
||||
}
|
||||
d.rounded(identity, d.x+float32(i)*(d.s-w)/4, y, w, bh, w/2, 0, 1)
|
||||
}
|
||||
}}
|
||||
|
||||
// Wave creates five bars rising and falling in a wave, from their middle
|
||||
// or their bottom as Options.Origin says.
|
||||
func Wave(c *ui.Context, o ...Options) ui.Element { return show(c, &wave, o) }
|
||||
@@ -0,0 +1,79 @@
|
||||
package dev.mygo
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.location.Location
|
||||
import android.location.LocationListener
|
||||
import android.location.LocationManager
|
||||
import android.os.Build
|
||||
import android.os.Looper
|
||||
import org.json.JSONObject
|
||||
|
||||
class LocationPlugin : MyGoPlugin {
|
||||
private val manager get() = PluginHost.context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
|
||||
private val perms = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
|
||||
private var listener: LocationListener? = null
|
||||
|
||||
private fun encode(l: Location) = JSONObject()
|
||||
.put("latitude", l.latitude).put("longitude", l.longitude)
|
||||
.put("altitude", if (l.hasAltitude()) l.altitude else -1.0)
|
||||
.put("speed", if (l.hasSpeed()) l.speed.toDouble() else -1.0)
|
||||
.put("heading", if (l.hasBearing()) l.bearing.toDouble() else -1.0)
|
||||
.put("accuracy", if (l.hasAccuracy()) l.accuracy.toDouble() else -1.0)
|
||||
.put("time", l.time)
|
||||
|
||||
private fun provider(): String? {
|
||||
val providers = manager.getProviders(true)
|
||||
return when {
|
||||
LocationManager.FUSED_PROVIDER in providers -> LocationManager.FUSED_PROVIDER
|
||||
LocationManager.GPS_PROVIDER in providers -> LocationManager.GPS_PROVIDER
|
||||
LocationManager.NETWORK_PROVIDER in providers -> LocationManager.NETWORK_PROVIDER
|
||||
else -> providers.firstOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
override fun call(method: String, args: JSONObject, reply: PluginReply) {
|
||||
when (method) {
|
||||
"requestPermission" -> PluginHost.requestPermissions(perms) { reply.success(JSONObject().put("granted", it)) }
|
||||
"current" -> PluginHost.requestPermissions(perms) { granted ->
|
||||
if (!granted) {
|
||||
reply.failure(PluginFailure("Denied", "the app may not know where the device is"))
|
||||
return@requestPermissions
|
||||
}
|
||||
val p = provider()
|
||||
if (p == null) {
|
||||
reply.failure(PluginFailure("Failed", "the device has location turned off"))
|
||||
return@requestPermissions
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
manager.getCurrentLocation(p, null, PluginHost.context.mainExecutor) { l ->
|
||||
if (l != null) reply.success(encode(l)) else reply.failure(PluginFailure("Failed", "no fix"))
|
||||
}
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
manager.requestSingleUpdate(p, { l: Location -> reply.success(encode(l)) }, Looper.getMainLooper())
|
||||
}
|
||||
}
|
||||
"start" -> PluginHost.requestPermissions(perms) { granted ->
|
||||
val p = provider()
|
||||
if (!granted || p == null) {
|
||||
reply.failure(PluginFailure("Denied", "the app may not know where the device is"))
|
||||
return@requestPermissions
|
||||
}
|
||||
listener?.let { manager.removeUpdates(it) }
|
||||
val l = LocationListener { loc -> PluginHost.emit("location", "fix", encode(loc)) }
|
||||
listener = l
|
||||
manager.requestLocationUpdates(p, 1000L, 1f, l, Looper.getMainLooper())
|
||||
reply.success(null)
|
||||
}
|
||||
"stop" -> {
|
||||
listener?.let { manager.removeUpdates(it) }
|
||||
listener = null
|
||||
reply.success(null)
|
||||
}
|
||||
else -> reply.failure(PluginFailure("NoMethod", method))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import CoreLocation
|
||||
import Foundation
|
||||
|
||||
final class LocationPlugin: NSObject, MyGoPlugin, CLLocationManagerDelegate {
|
||||
private let manager = CLLocationManager()
|
||||
private var waitingFix: [PluginReply] = []
|
||||
private var waitingAuth: [PluginReply] = []
|
||||
private var watching = false
|
||||
|
||||
override init() {
|
||||
super.init()
|
||||
manager.delegate = self
|
||||
manager.desiredAccuracy = kCLLocationAccuracyBest
|
||||
}
|
||||
|
||||
private var granted: Bool {
|
||||
let s = manager.authorizationStatus
|
||||
return s == .authorizedWhenInUse || s == .authorizedAlways
|
||||
}
|
||||
|
||||
func call(_ method: String, _ args: [String: Any], _ reply: @escaping PluginReply) {
|
||||
switch method {
|
||||
case "requestPermission":
|
||||
if manager.authorizationStatus == .notDetermined {
|
||||
waitingAuth.append(reply)
|
||||
manager.requestWhenInUseAuthorization()
|
||||
} else {
|
||||
reply(.success(["granted": granted]))
|
||||
}
|
||||
case "current":
|
||||
waitingFix.append(reply)
|
||||
if manager.authorizationStatus == .notDetermined {
|
||||
manager.requestWhenInUseAuthorization()
|
||||
} else if !granted {
|
||||
failFixes(PluginFailure("Denied", "the app may not know where the device is"))
|
||||
} else {
|
||||
manager.requestLocation()
|
||||
}
|
||||
case "start":
|
||||
watching = true
|
||||
if manager.authorizationStatus == .notDetermined { manager.requestWhenInUseAuthorization() }
|
||||
manager.startUpdatingLocation()
|
||||
reply(.success(nil))
|
||||
case "stop":
|
||||
watching = false
|
||||
manager.stopUpdatingLocation()
|
||||
reply(.success(nil))
|
||||
default:
|
||||
reply(.failure(PluginFailure("NoMethod", method)))
|
||||
}
|
||||
}
|
||||
|
||||
private func failFixes(_ f: PluginFailure) {
|
||||
let list = waitingFix
|
||||
waitingFix = []
|
||||
for r in list { r(.failure(f)) }
|
||||
}
|
||||
|
||||
func locationManagerDidChangeAuthorization(_ m: CLLocationManager) {
|
||||
guard m.authorizationStatus != .notDetermined else { return }
|
||||
let auth = waitingAuth
|
||||
waitingAuth = []
|
||||
for r in auth { r(.success(["granted": granted])) }
|
||||
if !waitingFix.isEmpty {
|
||||
if granted {
|
||||
m.requestLocation()
|
||||
} else {
|
||||
failFixes(PluginFailure("Denied", "the app may not know where the device is"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func encode(_ l: CLLocation) -> [String: Any] {
|
||||
["latitude": l.coordinate.latitude, "longitude": l.coordinate.longitude, "altitude": l.verticalAccuracy >= 0 ? l.altitude : -1,
|
||||
"speed": l.speed, "heading": l.course, "accuracy": l.horizontalAccuracy, "time": Int64(l.timestamp.timeIntervalSince1970 * 1000)]
|
||||
}
|
||||
|
||||
func locationManager(_ m: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
|
||||
guard let l = locations.last else { return }
|
||||
let fix = encode(l)
|
||||
let list = waitingFix
|
||||
waitingFix = []
|
||||
for r in list { r(.success(fix)) }
|
||||
if watching { PluginHost.emit("location", "fix", fix) }
|
||||
}
|
||||
|
||||
func locationManager(_ m: CLLocationManager, didFailWithError error: Error) {
|
||||
failFixes(PluginFailure("Failed", error.localizedDescription))
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
// Package location tells where the device is, on phones and tablets: Core
|
||||
// Location on iOS, and LocationManager on Android, without Google's services.
|
||||
// Importing it adds the permissions it needs to the app, with a usage
|
||||
// description on iOS that ios.infoPlist in the app's configuration replaces:
|
||||
//
|
||||
// "NSLocationWhenInUseUsageDescription": "Shows nearby stores."
|
||||
//
|
||||
// Elsewhere its functions report errors.ErrUnsupported.
|
||||
package location
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
)
|
||||
|
||||
const pluginID = "location"
|
||||
|
||||
// Fix is a place the device was at.
|
||||
type Fix struct {
|
||||
// Latitude and Longitude are in degrees.
|
||||
Latitude, Longitude float64
|
||||
// Altitude is in meters above sea level, Speed in meters a second, and
|
||||
// Heading in degrees clockwise from north; negative where not known.
|
||||
Altitude, Speed, Heading float64
|
||||
// Accuracy is how far off it may be, in meters.
|
||||
Accuracy float64
|
||||
// Time is when it was measured.
|
||||
Time time.Time
|
||||
}
|
||||
|
||||
type wireFix struct {
|
||||
Latitude float64 `json:"latitude"`
|
||||
Longitude float64 `json:"longitude"`
|
||||
Altitude float64 `json:"altitude"`
|
||||
Speed float64 `json:"speed"`
|
||||
Heading float64 `json:"heading"`
|
||||
Accuracy float64 `json:"accuracy"`
|
||||
TimeMS int64 `json:"time"`
|
||||
}
|
||||
|
||||
func (w wireFix) fix() Fix {
|
||||
return Fix{w.Latitude, w.Longitude, w.Altitude, w.Speed, w.Heading, w.Accuracy, time.UnixMilli(w.TimeMS)}
|
||||
}
|
||||
|
||||
// RequestPermission asks the user to let the app know where the device is,
|
||||
// the first time, and reports whether it may. Call it off the main goroutine,
|
||||
// as it waits for the user.
|
||||
func RequestPermission(ctx context.Context) (bool, error) {
|
||||
var r struct {
|
||||
Granted bool `json:"granted"`
|
||||
}
|
||||
err := mygo.Native(pluginID).Call(ctx, "requestPermission", nil, &r)
|
||||
return r.Granted, err
|
||||
}
|
||||
|
||||
// Current finds where the device is now, asking for permission if it must.
|
||||
func Current(ctx context.Context) (Fix, error) {
|
||||
var w wireFix
|
||||
if err := mygo.Native(pluginID).Call(ctx, "current", nil, &w); err != nil {
|
||||
return Fix{}, err
|
||||
}
|
||||
return w.fix(), nil
|
||||
}
|
||||
|
||||
// Watch calls fn on the main thread as the device moves, until stop is called.
|
||||
func Watch(ctx context.Context, fn func(Fix)) (stop func(), err error) {
|
||||
p := mygo.Native(pluginID)
|
||||
off := p.On("fix", func(data []byte) {
|
||||
var w wireFix
|
||||
if json.Unmarshal(data, &w) == nil {
|
||||
fn(w.fix())
|
||||
}
|
||||
})
|
||||
if err := p.Call(ctx, "start", nil, nil); err != nil {
|
||||
off()
|
||||
return nil, err
|
||||
}
|
||||
return func() {
|
||||
off()
|
||||
go p.Call(context.Background(), "stop", nil, nil)
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"mobile": {
|
||||
"id": "location",
|
||||
"ios": {
|
||||
"sources": ["ios/*.swift"],
|
||||
"class": "LocationPlugin",
|
||||
"frameworks": ["CoreLocation"],
|
||||
"infoPlist": {"NSLocationWhenInUseUsageDescription": "This app shows where you are."}
|
||||
},
|
||||
"android": {
|
||||
"sources": ["android/*.kt"],
|
||||
"class": "LocationPlugin",
|
||||
"permissions": ["ACCESS_FINE_LOCATION", "ACCESS_COARSE_LOCATION"]
|
||||
}
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package dev.mygo
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.osmdroid.config.Configuration
|
||||
import org.osmdroid.events.MapEventsReceiver
|
||||
import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase
|
||||
import org.osmdroid.tileprovider.tilesource.TileSourceFactory
|
||||
import org.osmdroid.util.GeoPoint
|
||||
import org.osmdroid.util.MapTileIndex
|
||||
import org.osmdroid.views.CustomZoomButtonsController
|
||||
import org.osmdroid.views.MapView
|
||||
import org.osmdroid.views.overlay.MapEventsOverlay
|
||||
import org.osmdroid.views.overlay.Marker
|
||||
import java.io.File
|
||||
|
||||
/** A map's tiles from a server of the app's. */
|
||||
private class Tiles(private val template: String) : OnlineTileSourceBase("mygo", 0, 22, 256, "", arrayOf(template)) {
|
||||
override fun getTileURLString(index: Long): String = template
|
||||
.replace("{z}", MapTileIndex.getZoom(index).toString())
|
||||
.replace("{x}", MapTileIndex.getX(index).toString())
|
||||
.replace("{y}", MapTileIndex.getY(index).toString())
|
||||
}
|
||||
|
||||
class MapsPlugin : MyGoPlugin {
|
||||
private class Holder(val id: Long, val map: MapView) {
|
||||
val pins = HashMap<String, Marker>()
|
||||
}
|
||||
|
||||
private val maps = HashMap<Long, Holder>()
|
||||
|
||||
init {
|
||||
PluginHost.registerView("map") { context, id, args ->
|
||||
val conf = Configuration.getInstance()
|
||||
conf.userAgentValue = context.packageName
|
||||
conf.osmdroidBasePath = File(context.cacheDir, "osmdroid")
|
||||
conf.osmdroidTileCache = File(context.cacheDir, "osmdroid/tiles")
|
||||
val map = MapView(context)
|
||||
val template = args.optString("tileURL")
|
||||
map.setTileSource(if (template.isEmpty()) TileSourceFactory.MAPNIK else Tiles(template))
|
||||
map.setMultiTouchControls(true)
|
||||
map.isTilesScaledToDpi = true // legible on a dense screen
|
||||
map.zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER)
|
||||
map.controller.setZoom(args.optDouble("zoom", 2.0))
|
||||
map.controller.setCenter(GeoPoint(args.optDouble("lat"), args.optDouble("lng")))
|
||||
val h = Holder(id, map)
|
||||
maps[id] = h
|
||||
map.overlays.add(MapEventsOverlay(object : MapEventsReceiver {
|
||||
override fun singleTapConfirmedHelper(p: GeoPoint): Boolean {
|
||||
PluginHost.emit("maps", "tap", mapOf("id" to id, "lat" to p.latitude, "lng" to p.longitude))
|
||||
return true
|
||||
}
|
||||
override fun longPressHelper(p: GeoPoint) = false
|
||||
}))
|
||||
map.onResume()
|
||||
map
|
||||
}
|
||||
}
|
||||
|
||||
override fun call(method: String, args: JSONObject, reply: PluginReply) {
|
||||
val id = args.optLong("id")
|
||||
val h = maps[id]
|
||||
if (h == null) {
|
||||
reply.failure(PluginFailure("NoMap", "no map $id"))
|
||||
return
|
||||
}
|
||||
val at = GeoPoint(args.optDouble("lat"), args.optDouble("lng"))
|
||||
when (method) {
|
||||
"setCamera" -> {
|
||||
if (args.optBoolean("animated")) {
|
||||
h.map.controller.animateTo(at, args.optDouble("zoom", h.map.zoomLevelDouble), null)
|
||||
} else {
|
||||
h.map.controller.setZoom(args.optDouble("zoom", h.map.zoomLevelDouble))
|
||||
h.map.controller.setCenter(at)
|
||||
}
|
||||
reply.success(null)
|
||||
}
|
||||
"camera" -> {
|
||||
val c = h.map.mapCenter
|
||||
reply.success(mapOf("Lat" to c.latitude, "Lng" to c.longitude, "Zoom" to h.map.zoomLevelDouble))
|
||||
}
|
||||
"addMarker" -> {
|
||||
val name = args.optString("marker")
|
||||
h.pins.remove(name)?.let {
|
||||
it.closeInfoWindow()
|
||||
h.map.overlays.remove(it)
|
||||
}
|
||||
val m = Marker(h.map)
|
||||
m.position = at
|
||||
m.title = args.optString("title").ifEmpty { null }
|
||||
m.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM)
|
||||
m.setOnMarkerClickListener { marker, map ->
|
||||
PluginHost.emit("maps", "markerTap", mapOf("id" to id, "marker" to name))
|
||||
if (marker.title != null) marker.showInfoWindow()
|
||||
map.controller.animateTo(marker.position)
|
||||
true
|
||||
}
|
||||
h.pins[name] = m
|
||||
h.map.overlays.add(m)
|
||||
h.map.invalidate()
|
||||
reply.success(null)
|
||||
}
|
||||
"removeMarker" -> {
|
||||
h.pins.remove(args.optString("marker"))?.let {
|
||||
it.closeInfoWindow()
|
||||
h.map.overlays.remove(it)
|
||||
}
|
||||
h.map.invalidate()
|
||||
reply.success(null)
|
||||
}
|
||||
"dispose" -> {
|
||||
maps.remove(id)
|
||||
h.map.onPause()
|
||||
h.map.onDetach()
|
||||
reply.success(null)
|
||||
}
|
||||
else -> reply.failure(PluginFailure("UnknownMethod", method))
|
||||
}
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
import MapKit
|
||||
import UIKit
|
||||
|
||||
/// A pin, which knows its ID.
|
||||
private final class Pin: MKPointAnnotation {
|
||||
var id = ""
|
||||
}
|
||||
|
||||
/// Zoom as web maps have it, from MapKit's span of longitude.
|
||||
private func span(zoom: Double, height: CGFloat, width: CGFloat) -> MKCoordinateSpan {
|
||||
let lng = 360 / pow(2, zoom)
|
||||
let ratio = width > 0 ? Double(height / width) : 1
|
||||
return MKCoordinateSpan(latitudeDelta: min(lng * ratio, 180), longitudeDelta: min(lng, 360))
|
||||
}
|
||||
|
||||
private final class MapHolder: NSObject, MKMapViewDelegate, UIGestureRecognizerDelegate {
|
||||
let id: Int
|
||||
let map = MKMapView()
|
||||
var pins: [String: Pin] = [:]
|
||||
/// What to show once the view has a size.
|
||||
var pending: (CLLocationCoordinate2D, Double)?
|
||||
/// The pin selected by the tap being handled, which has told already.
|
||||
weak var justSelected: Pin?
|
||||
|
||||
init(id: Int) {
|
||||
self.id = id
|
||||
super.init()
|
||||
map.delegate = self
|
||||
// A tap once a double tap, which zooms, is ruled out.
|
||||
let twice = UITapGestureRecognizer()
|
||||
twice.numberOfTapsRequired = 2
|
||||
twice.delegate = self
|
||||
map.addGestureRecognizer(twice)
|
||||
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
|
||||
tap.delegate = self
|
||||
tap.require(toFail: twice)
|
||||
map.addGestureRecognizer(tap)
|
||||
}
|
||||
|
||||
func show(_ place: CLLocationCoordinate2D, zoom: Double, animated: Bool) {
|
||||
// MapKit raises on what's off its map.
|
||||
let at = CLLocationCoordinate2D(latitude: max(-85, min(85, place.latitude)), longitude: max(-180, min(180, place.longitude)))
|
||||
guard map.bounds.width > 0 else {
|
||||
pending = (at, zoom)
|
||||
return
|
||||
}
|
||||
map.setRegion(MKCoordinateRegion(center: at, span: span(zoom: zoom, height: map.bounds.height, width: map.bounds.width)), animated: animated)
|
||||
}
|
||||
|
||||
func gestureRecognizer(_ g: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool { true }
|
||||
|
||||
@objc func tapped(_ g: UITapGestureRecognizer) {
|
||||
let p = g.location(in: map)
|
||||
// A pin's own tap, not the map's: mapView(_:didSelect:) tells of its first,
|
||||
// and this of those while it stays selected.
|
||||
var v = map.hitTest(p, with: nil)
|
||||
while let view = v, !(view is MKAnnotationView) { v = view.superview }
|
||||
if let pin = (v as? MKAnnotationView)?.annotation as? Pin {
|
||||
if justSelected !== pin { PluginHost.emit("maps", "markerTap", ["id": id, "marker": pin.id]) }
|
||||
justSelected = nil
|
||||
return
|
||||
}
|
||||
justSelected = nil
|
||||
let at = map.convert(p, toCoordinateFrom: map)
|
||||
PluginHost.emit("maps", "tap", ["id": id, "lat": at.latitude, "lng": at.longitude])
|
||||
}
|
||||
|
||||
func mapViewDidChangeVisibleRegion(_ m: MKMapView) {
|
||||
if let (at, zoom) = pending, m.bounds.width > 0 {
|
||||
pending = nil
|
||||
show(at, zoom: zoom, animated: false)
|
||||
}
|
||||
}
|
||||
|
||||
func mapView(_ m: MKMapView, didSelect annotation: MKAnnotation) {
|
||||
if let pin = annotation as? Pin {
|
||||
justSelected = pin
|
||||
PluginHost.emit("maps", "markerTap", ["id": id, "marker": pin.id])
|
||||
}
|
||||
}
|
||||
|
||||
func mapView(_ m: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
|
||||
guard annotation is Pin else { return nil }
|
||||
let v = m.dequeueReusableAnnotationView(withIdentifier: "pin") as? MKMarkerAnnotationView
|
||||
?? MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "pin")
|
||||
v.annotation = annotation
|
||||
v.canShowCallout = annotation.title != nil
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
final class MapsPlugin: MyGoPlugin {
|
||||
private var maps: [Int: MapHolder] = [:]
|
||||
|
||||
init() {
|
||||
PluginHost.registerView("map") { [weak self] id, args in
|
||||
let h = MapHolder(id: id)
|
||||
self?.maps[id] = h
|
||||
h.show(CLLocationCoordinate2D(latitude: args["lat"] as? Double ?? 0, longitude: args["lng"] as? Double ?? 0),
|
||||
zoom: args["zoom"] as? Double ?? 2, animated: false)
|
||||
return h.map
|
||||
}
|
||||
}
|
||||
|
||||
func call(_ method: String, _ args: [String: Any], _ reply: @escaping PluginReply) {
|
||||
guard let id = args["id"] as? Int, let h = maps[id] else {
|
||||
reply(.failure(PluginFailure("NoMap", "no map \(args["id"] ?? "")")))
|
||||
return
|
||||
}
|
||||
let at = CLLocationCoordinate2D(latitude: args["lat"] as? Double ?? 0, longitude: args["lng"] as? Double ?? 0)
|
||||
switch method {
|
||||
case "setCamera":
|
||||
h.show(at, zoom: args["zoom"] as? Double ?? 2, animated: args["animated"] as? Bool ?? false)
|
||||
reply(.success(nil))
|
||||
case "camera":
|
||||
let r = h.map.region
|
||||
let zoom = r.span.longitudeDelta > 0 ? log2(360 / r.span.longitudeDelta) : 0
|
||||
reply(.success(["Lat": r.center.latitude, "Lng": r.center.longitude, "Zoom": zoom]))
|
||||
case "addMarker":
|
||||
let name = args["marker"] as? String ?? ""
|
||||
if let old = h.pins[name] { h.map.removeAnnotation(old) }
|
||||
let pin = Pin()
|
||||
pin.id = name
|
||||
pin.coordinate = at
|
||||
if let t = args["title"] as? String, !t.isEmpty { pin.title = t }
|
||||
h.pins[name] = pin
|
||||
h.map.addAnnotation(pin)
|
||||
reply(.success(nil))
|
||||
case "removeMarker":
|
||||
let name = args["marker"] as? String ?? ""
|
||||
if let old = h.pins.removeValue(forKey: name) { h.map.removeAnnotation(old) }
|
||||
reply(.success(nil))
|
||||
case "dispose":
|
||||
maps[id] = nil
|
||||
reply(.success(nil))
|
||||
default:
|
||||
reply(.failure(PluginFailure("UnknownMethod", method)))
|
||||
}
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
// Package maps shows a map in a window's native UI: MapKit on iOS, and on Android
|
||||
// osmdroid, with OpenStreetMap's tiles by default, which needs no account or key.
|
||||
//
|
||||
// m, err := maps.New(win, maps.Options{Center: maps.LatLng{Lat: 48.86, Lng: 2.35}, Zoom: 12})
|
||||
// ...
|
||||
// ui.WebView(c, m).Fill() // in the view; what it draws after shows over the map
|
||||
// m.OnTap(func(at maps.LatLng) { ... })
|
||||
// m.AddMarker(ctx, maps.Marker{ID: "home", At: at, Title: "Home"})
|
||||
//
|
||||
// A finger pans, pinches and taps it. OpenStreetMap's tile servers are for light
|
||||
// use: an app with many users gives Options.TileURL a server of its own (Android;
|
||||
// iOS shows Apple's maps). On desktops and in browsers New reports
|
||||
// errors.ErrUnsupported.
|
||||
package maps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
"github.com/egoist/mygo/internal/surface"
|
||||
)
|
||||
|
||||
const pluginID = "maps"
|
||||
|
||||
// LatLng is a place, in degrees.
|
||||
type LatLng struct {
|
||||
Lat float64 `json:"lat"`
|
||||
Lng float64 `json:"lng"`
|
||||
}
|
||||
|
||||
// Options say what a map shows first.
|
||||
type Options struct {
|
||||
Center LatLng
|
||||
// Zoom is as on web maps: 0 shows the whole world, 18 a street; 2 by default.
|
||||
Zoom float64
|
||||
// TileURL is where Android's map gets its tiles, with {z}, {x} and {y}; by
|
||||
// default OpenStreetMap's.
|
||||
TileURL string
|
||||
}
|
||||
|
||||
// Marker is a pin on a map.
|
||||
type Marker struct {
|
||||
// ID tells it apart: OnMarkerTap reports it, and adding it again moves it.
|
||||
ID string `json:"id"`
|
||||
At LatLng `json:"at"`
|
||||
// Title shows as it's tapped.
|
||||
Title string `json:"title,omitempty"`
|
||||
}
|
||||
|
||||
// Map is a map in a window. Show it with ui.WebView.
|
||||
type Map struct {
|
||||
view *mygo.PluginView
|
||||
offs []func()
|
||||
}
|
||||
|
||||
// New makes a map in a window showing native UI.
|
||||
func New(w *mygo.Window, o Options) (*Map, error) {
|
||||
zoom := o.Zoom
|
||||
if zoom == 0 {
|
||||
zoom = 2
|
||||
}
|
||||
v, err := mygo.NewPluginView(w, "map", map[string]any{"lat": o.Center.Lat, "lng": o.Center.Lng, "zoom": zoom, "tileURL": o.TileURL})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Map{view: v}, nil
|
||||
}
|
||||
|
||||
// SurfaceWebView gives package ui the view to show.
|
||||
func (m *Map) SurfaceWebView(conn *surface.Conn) platform.WebView {
|
||||
return m.view.SurfaceWebView(conn)
|
||||
}
|
||||
|
||||
func (m *Map) call(ctx context.Context, method string, args map[string]any, reply any) error {
|
||||
args["id"] = m.view.ID
|
||||
return mygo.Native(pluginID).Call(ctx, method, args, reply)
|
||||
}
|
||||
|
||||
// SetCamera moves the map to a place, gliding there if animated.
|
||||
func (m *Map) SetCamera(ctx context.Context, center LatLng, zoom float64, animated bool) error {
|
||||
return m.call(ctx, "setCamera", map[string]any{"lat": center.Lat, "lng": center.Lng, "zoom": zoom, "animated": animated}, nil)
|
||||
}
|
||||
|
||||
// Camera returns what the map shows now, as the user panned it.
|
||||
func (m *Map) Camera(ctx context.Context) (center LatLng, zoom float64, err error) {
|
||||
var r struct {
|
||||
Lat, Lng, Zoom float64
|
||||
}
|
||||
err = m.call(ctx, "camera", map[string]any{}, &r)
|
||||
return LatLng{r.Lat, r.Lng}, r.Zoom, err
|
||||
}
|
||||
|
||||
// AddMarker puts a pin on the map, in place of one of its ID.
|
||||
func (m *Map) AddMarker(ctx context.Context, marker Marker) error {
|
||||
return m.call(ctx, "addMarker", map[string]any{"marker": marker.ID, "lat": marker.At.Lat, "lng": marker.At.Lng, "title": marker.Title}, nil)
|
||||
}
|
||||
|
||||
// RemoveMarker takes a pin off the map.
|
||||
func (m *Map) RemoveMarker(ctx context.Context, id string) error {
|
||||
return m.call(ctx, "removeMarker", map[string]any{"marker": id}, nil)
|
||||
}
|
||||
|
||||
// OnTap calls fn on the main thread as a finger taps the map, not one of its pins.
|
||||
func (m *Map) OnTap(fn func(at LatLng)) {
|
||||
id := m.view.ID
|
||||
m.offs = append(m.offs, mygo.Native(pluginID).On("tap", func(data []byte) {
|
||||
var e struct {
|
||||
ID int
|
||||
Lat, Lng float64
|
||||
}
|
||||
if json.Unmarshal(data, &e) == nil && e.ID == id {
|
||||
fn(LatLng{e.Lat, e.Lng})
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
// OnMarkerTap calls fn on the main thread as a finger taps a pin.
|
||||
func (m *Map) OnMarkerTap(fn func(id string)) {
|
||||
view := m.view.ID
|
||||
m.offs = append(m.offs, mygo.Native(pluginID).On("markerTap", func(data []byte) {
|
||||
var e struct {
|
||||
ID int
|
||||
Marker string
|
||||
}
|
||||
if json.Unmarshal(data, &e) == nil && e.ID == view {
|
||||
fn(e.Marker)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
// Destroy takes the map away, which closing its window doesn't: call it before.
|
||||
func (m *Map) Destroy() {
|
||||
for _, off := range m.offs {
|
||||
off()
|
||||
}
|
||||
m.offs = nil
|
||||
go mygo.Native(pluginID).Call(context.Background(), "dispose", map[string]any{"id": m.view.ID}, nil)
|
||||
m.view.Destroy()
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"mobile": {
|
||||
"id": "maps",
|
||||
"ios": {
|
||||
"sources": ["ios/*.swift"],
|
||||
"class": "MapsPlugin",
|
||||
"frameworks": ["MapKit"]
|
||||
},
|
||||
"android": {
|
||||
"sources": ["android/*.kt"],
|
||||
"class": "MapsPlugin",
|
||||
"permissions": ["INTERNET", "ACCESS_NETWORK_STATE"],
|
||||
"dependencies": ["org.osmdroid:osmdroid-android:6.1.20"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# Notice
|
||||
|
||||
This package follows PermissionFlow
|
||||
(https://github.com/jaywcjlove/PermissionFlow, at cb96db4), a Swift
|
||||
package for macOS: what its guide does (System Settings opened at the
|
||||
page, a panel under its window that follows it, with the app to drag into
|
||||
the list, and which closes with it), the panes it covers and which of
|
||||
them take a drag, the pasteboard types of the dragged app, the panel's
|
||||
geometry and text, and how it tells the status of each permission. The
|
||||
code is MyGo's own, in Go: none of PermissionFlow's is copied.
|
||||
PermissionFlow's license:
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 小弟调调
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,22 @@
|
||||
# permissionflow
|
||||
|
||||
The permissions the system keeps for the user to give, such as
|
||||
Accessibility, Screen Recording and the microphone, for
|
||||
[MyGo](https://github.com/egoist/mygo) apps: checked, asked for with the
|
||||
system's prompt, and a guide to System Settings, where a panel under its
|
||||
window holds the app to drag into the list, as
|
||||
[PermissionFlow](https://github.com/jaywcjlove/PermissionFlow) does for
|
||||
Swift apps. macOS and Windows; it is all Go.
|
||||
|
||||
```go
|
||||
import "github.com/egoist/mygo/plugins/permissionflow"
|
||||
|
||||
st, err := permissionflow.Check(permissionflow.Accessibility)
|
||||
if err == nil && st != permissionflow.Granted {
|
||||
st, err = permissionflow.Guide(ctx, permissionflow.Accessibility, permissionflow.GuideOptions{})
|
||||
}
|
||||
```
|
||||
|
||||
See [the documentation](../../docs/plugins/permissionflow.md), and
|
||||
`examples/permissionflow`. It follows PermissionFlow (MIT, © 小弟调调;
|
||||
see [NOTICE.md](NOTICE.md)).
|
||||
Loaded 100 of 2538 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user