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

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

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

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

No files matched your search

+177
View File
@@ -0,0 +1,177 @@
// Package accelerator parses Electron style keyboard accelerators such as
// "CmdOrCtrl+Shift+Z" into a platform neutral representation.
package accelerator
import (
"fmt"
"strings"
)
// Modifiers is a bit set of modifier keys.
type Modifiers uint8
// Modifier keys. Super is Command on macOS and the Windows/Super key
// elsewhere.
const (
Super Modifiers = 1 << iota
Ctrl
Alt
Shift
)
// Accelerator is a parsed accelerator.
type Accelerator struct {
Modifiers Modifiers
// Key is either a single lower case character ("a", "1", ",") or one of
// the named keys: F1-F24, Enter, Tab, Space, Backspace, Delete, Insert,
// Escape, Up, Down, Left, Right, Home, End, PageUp, PageDown,
// VolumeUp, VolumeDown, VolumeMute, MediaNextTrack, MediaPreviousTrack,
// MediaStop, MediaPlayPause, PrintScreen, Num0-Num9, NumDec, NumAdd,
// NumSub, NumMult, NumDiv, CapsLock, NumLock, ScrollLock.
Key string
}
// Has reports whether all modifiers in m are set.
func (a Accelerator) Has(m Modifiers) bool { return a.Modifiers&m == m }
// String formats the accelerator in canonical form.
func (a Accelerator) String() string {
var parts []string
if a.Has(Super) {
parts = append(parts, "Super")
}
if a.Has(Ctrl) {
parts = append(parts, "Ctrl")
}
if a.Has(Alt) {
parts = append(parts, "Alt")
}
if a.Has(Shift) {
parts = append(parts, "Shift")
}
key := a.Key
if len(key) == 1 {
key = strings.ToUpper(key)
}
return strings.Join(append(parts, key), "+")
}
var namedKeys = map[string]string{
"plus": "+",
"space": "Space",
"tab": "Tab",
"capslock": "CapsLock",
"numlock": "NumLock",
"scrolllock": "ScrollLock",
"backspace": "Backspace",
"delete": "Delete",
"del": "Delete",
"insert": "Insert",
"ins": "Insert",
"return": "Enter",
"enter": "Enter",
"up": "Up",
"down": "Down",
"left": "Left",
"right": "Right",
"home": "Home",
"end": "End",
"pageup": "PageUp",
"pagedown": "PageDown",
"escape": "Escape",
"esc": "Escape",
"volumeup": "VolumeUp",
"volumedown": "VolumeDown",
"volumemute": "VolumeMute",
"medianexttrack": "MediaNextTrack",
"mediaprevioustrack": "MediaPreviousTrack",
"mediastop": "MediaStop",
"mediaplaypause": "MediaPlayPause",
"printscreen": "PrintScreen",
"numdec": "NumDec",
"numadd": "NumAdd",
"numsub": "NumSub",
"nummult": "NumMult",
"numdiv": "NumDiv",
}
// Parse parses an accelerator for the given GOOS. "CmdOrCtrl" resolves to
// Super (Command) on darwin and Ctrl elsewhere.
func Parse(s, goos string) (Accelerator, error) {
var a Accelerator
if strings.TrimSpace(s) == "" {
return a, fmt.Errorf("accelerator: empty accelerator")
}
parts := splitParts(s)
for i, raw := range parts {
p := strings.TrimSpace(raw)
if p == "" {
return a, fmt.Errorf("accelerator: invalid accelerator %q", s)
}
last := i == len(parts)-1
if m, ok := modifier(p, goos); ok && !last {
a.Modifiers |= m
continue
}
if !last {
return a, fmt.Errorf("accelerator: unknown modifier %q in %q", p, s)
}
key, err := parseKey(p)
if err != nil {
return a, fmt.Errorf("accelerator: %w in %q", err, s)
}
a.Key = key
}
return a, nil
}
// splitParts splits on "+" while allowing "+" itself as the key, as in
// "CmdOrCtrl++".
func splitParts(s string) []string {
parts := strings.Split(s, "+")
if strings.HasSuffix(s, "++") {
parts = append(parts[:len(parts)-2], "+")
} else if s == "+" {
parts = []string{"+"}
}
return parts
}
func modifier(p, goos string) (Modifiers, bool) {
switch strings.ToLower(p) {
case "command", "cmd", "super", "meta", "win":
return Super, true
case "control", "ctrl":
return Ctrl, true
case "commandorcontrol", "cmdorctrl":
if goos == "darwin" {
return Super, true
}
return Ctrl, true
case "alt", "option", "altgr":
return Alt, true
case "shift":
return Shift, true
}
return 0, false
}
func parseKey(p string) (string, error) {
lower := strings.ToLower(p)
if len([]rune(p)) == 1 {
return strings.ToLower(p), nil
}
if k, ok := namedKeys[lower]; ok {
return k, nil
}
if len(lower) >= 2 && lower[0] == 'f' {
var n int
if _, err := fmt.Sscanf(lower[1:], "%d", &n); err == nil && n >= 1 && n <= 24 && fmt.Sprint(n) == lower[1:] {
return fmt.Sprintf("F%d", n), nil
}
}
if strings.HasPrefix(lower, "num") && len(lower) == 4 && lower[3] >= '0' && lower[3] <= '9' {
return "Num" + lower[3:], nil
}
return "", fmt.Errorf("unknown key %q", p)
}
@@ -0,0 +1,76 @@
package accelerator
import "testing"
func TestParse(t *testing.T) {
tests := []struct {
in string
goos string
want Accelerator
}{
{"CmdOrCtrl+Q", "darwin", Accelerator{Super, "q"}},
{"CmdOrCtrl+Q", "linux", Accelerator{Ctrl, "q"}},
{"CommandOrControl+Shift+Z", "windows", Accelerator{Ctrl | Shift, "z"}},
{"Alt+F4", "windows", Accelerator{Alt, "F4"}},
{"Option+Cmd+I", "darwin", Accelerator{Alt | Super, "i"}},
{"F11", "linux", Accelerator{0, "F11"}},
{"Ctrl+Plus", "linux", Accelerator{Ctrl, "+"}},
{"CmdOrCtrl++", "darwin", Accelerator{Super, "+"}},
{"CmdOrCtrl+=", "darwin", Accelerator{Super, "="}},
{"Cmd+,", "darwin", Accelerator{Super, ","}},
{"Shift+Return", "darwin", Accelerator{Shift, "Enter"}},
{"Esc", "darwin", Accelerator{0, "Escape"}},
{"Ctrl+Num5", "linux", Accelerator{Ctrl, "Num5"}},
{"Super+Space", "linux", Accelerator{Super, "Space"}},
{"ctrl + shift + up", "linux", Accelerator{Ctrl | Shift, "Up"}},
}
for _, tt := range tests {
got, err := Parse(tt.in, tt.goos)
if err != nil {
t.Errorf("Parse(%q): %v", tt.in, err)
continue
}
if got != tt.want {
t.Errorf("Parse(%q, %s) = %+v, want %+v", tt.in, tt.goos, got, tt.want)
}
}
}
func TestParseErrors(t *testing.T) {
for _, in := range []string{"", "Ctrl+", "Hyper+A", "Ctrl+F25", "Ctrl+Foo", "Ctrl+A+B"} {
if _, err := Parse(in, "linux"); err == nil {
t.Errorf("Parse(%q) succeeded, want error", in)
}
}
}
func TestString(t *testing.T) {
a, _ := Parse("Shift+CmdOrCtrl+k", "linux")
if got := a.String(); got != "Ctrl+Shift+K" {
t.Errorf("String() = %q", got)
}
}
func TestXDGTrigger(t *testing.T) {
for in, want := range map[string]string{
"Shift+CmdOrCtrl+K": "CTRL+SHIFT+k",
"Super+Space": "LOGO+space",
"Alt+Shift+Enter": "ALT+SHIFT+Return",
"CmdOrCtrl+,": "CTRL+comma",
"Ctrl+Plus": "CTRL+plus",
"Ctrl+Alt+Super+F12": "CTRL+ALT+LOGO+F12",
"Ctrl+Num7": "CTRL+KP_7",
"Ctrl+PageDown": "CTRL+Page_Down",
"MediaPlayPause": "XF86AudioPlay",
"Ctrl+1": "CTRL+1",
"Ctrl+é": "CTRL+U00E9",
} {
a, err := Parse(in, "linux")
if err != nil {
t.Fatal(err)
}
if got := a.XDGTrigger(); got != want {
t.Errorf("XDGTrigger(%q) = %q, want %q", in, got, want)
}
}
}
+55
View File
@@ -0,0 +1,55 @@
package accelerator
import (
"fmt"
"strings"
)
// Keysym returns the XKB (and X11) name of the key, as in "a", "comma",
// "Return", "F5" or "KP_Add".
func (a Accelerator) Keysym() string {
if name, ok := keysyms[a.Key]; ok {
return name
}
if strings.HasPrefix(a.Key, "Num") && len(a.Key) == 4 {
return "KP_" + a.Key[3:]
}
if r := []rune(a.Key); len(r) == 1 && r[0] > '~' {
return fmt.Sprintf("U%04X", r[0])
}
return a.Key // letters, digits and F1-F24
}
// XDGTrigger formats the accelerator as a trigger of the XDG shortcuts
// specification, as in "CTRL+SHIFT+k", which desktop portals take.
func (a Accelerator) XDGTrigger() string {
var parts []string
for _, m := range []struct {
mod Modifiers
name string
}{{Ctrl, "CTRL"}, {Alt, "ALT"}, {Shift, "SHIFT"}, {Super, "LOGO"}} {
if a.Has(m.mod) {
parts = append(parts, m.name)
}
}
return strings.Join(append(parts, a.Keysym()), "+")
}
var keysyms = map[string]string{
"!": "exclam", `"`: "quotedbl", "#": "numbersign", "$": "dollar", "%": "percent",
"&": "ampersand", "'": "apostrophe", "(": "parenleft", ")": "parenright", "*": "asterisk",
"+": "plus", ",": "comma", "-": "minus", ".": "period", "/": "slash", ":": "colon",
";": "semicolon", "<": "less", "=": "equal", ">": "greater", "?": "question", "@": "at",
"[": "bracketleft", `\`: "backslash", "]": "bracketright", "^": "asciicircum",
"_": "underscore", "`": "grave", "{": "braceleft", "|": "bar", "}": "braceright", "~": "asciitilde",
"Enter": "Return", "Tab": "Tab", "Space": "space", "Backspace": "BackSpace",
"Delete": "Delete", "Insert": "Insert", "Escape": "Escape",
"Up": "Up", "Down": "Down", "Left": "Left", "Right": "Right",
"Home": "Home", "End": "End", "PageUp": "Page_Up", "PageDown": "Page_Down",
"VolumeUp": "XF86AudioRaiseVolume", "VolumeDown": "XF86AudioLowerVolume", "VolumeMute": "XF86AudioMute",
"MediaNextTrack": "XF86AudioNext", "MediaPreviousTrack": "XF86AudioPrev",
"MediaStop": "XF86AudioStop", "MediaPlayPause": "XF86AudioPlay",
"PrintScreen": "Print", "CapsLock": "Caps_Lock", "NumLock": "Num_Lock", "ScrollLock": "Scroll_Lock",
"NumDec": "KP_Decimal", "NumAdd": "KP_Add", "NumSub": "KP_Subtract",
"NumMult": "KP_Multiply", "NumDiv": "KP_Divide",
}
+84
View File
@@ -0,0 +1,84 @@
package automationcli
import (
"fmt"
"strings"
)
// usageError is a command line the command does not take.
type usageError struct{ msg string }
func (e *usageError) Error() string { return e.msg }
func usagef(format string, args ...any) error {
return &usageError{fmt.Sprintf(format, args...)}
}
// args are a command's arguments: its positional ones and its flags.
type args struct {
pos []string
bools map[string]bool
vals map[string]string
}
// flagSpec lists the flags a command takes: true for a flag with a
// value, false for a switch.
type flagSpec map[string]bool
// aliases are the short spellings of flags.
var aliases = map[string]string{"i": "interactive"}
// parseArgs parses a command's arguments, with flags anywhere among them
// (press @e2 --settle), written -f, --f, --f=v or --f v. "--" ends the
// flags; a negative number, as wheel's -120, and "-" alone are
// positional.
func parseArgs(in []string, spec flagSpec) (*args, error) {
a := &args{bools: map[string]bool{}, vals: map[string]string{}}
for i := 0; i < len(in); i++ {
s := in[i]
if s == "--" {
a.pos = append(a.pos, in[i+1:]...)
break
}
if len(s) < 2 || s[0] != '-' || (s[1] >= '0' && s[1] <= '9') || s[1] == '.' {
a.pos = append(a.pos, s)
continue
}
name := strings.TrimLeft(s, "-")
val, hasVal := "", false
if k, v, ok := strings.Cut(name, "="); ok {
name, val, hasVal = k, v, true
}
if long, ok := aliases[name]; ok {
name = long
}
takesValue, ok := spec[name]
if !ok {
return nil, usagef("unknown flag %s", s)
}
switch {
case takesValue && !hasVal:
if i+1 >= len(in) {
return nil, usagef("flag --%s needs a value", name)
}
i++
a.vals[name] = in[i]
case takesValue:
a.vals[name] = val
case hasVal:
return nil, usagef("flag --%s takes no value", name)
default:
a.bools[name] = true
}
}
return a, nil
}
// want checks that the command got between min and max positional
// arguments, max -1 for any number.
func (a *args) want(min, max int, usage string) error {
if len(a.pos) < min || (max >= 0 && len(a.pos) > max) {
return usagef("usage: mygo-automation %s", usage)
}
return nil
}
+973
View File
@@ -0,0 +1,973 @@
// Package automationcli is mygo-automation, the command line client of
// plugins/automation's socket made for agents: compact snapshots of a
// window's elements with short refs, actions on them, and diffs of what
// the window shows once it settled. The command lives in
// plugins/automation/cmd/mygo-automation, which embeds its SKILL.md; the
// package is here so that internal/e2e can drive a real app with it.
package automationcli
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"os"
"path/filepath"
"runtime/debug"
"slices"
"strconv"
"strings"
"time"
)
// Options are what the command takes besides its arguments.
type Options struct {
// Skill is the SKILL.md that skills prints.
Skill []byte
// Dir keeps the sessions' files; empty, it is mygo/automation in the
// user's cache directory.
Dir string
}
const usage = `usage: mygo-automation <command> [arguments] [--session name]
Run "mygo-automation skills" for the guide: commands, selectors, refs, --settle.
open [--socket path] attach a session to an app (default: $MYGO_AUTOMATION)
close end the session (the app keeps running)
windows | window <w> list windows | pick the one commands target
snapshot [-i] [--full] [--json]
diff what changed since the last snapshot or diff
press | focus <sel> fill <sel> <text> act <sel> <action> [args]
click <sel>|<x> <y> pointer move|down|up <sel>|<x> <y>
wheel <sel>|<x> <y> <dx> <dy>
type <text> key <key>... menu <label>...
eval <script>|- wait [<sel>] [--text s] [--gone]
screenshot <file.png> skills version
`
// defaultTimeout is how long --settle and wait wait unless --timeout says.
const defaultTimeout = 10 * time.Second
// Run runs a command line, without the program's name, and returns the
// exit status: 0, 1 when the command failed, 2 when it was used wrong.
func Run(argv []string, stdin io.Reader, stdout, stderr io.Writer, opts Options) int {
err := run(argv, stdin, stdout, stderr, opts)
if err == nil {
return 0
}
var ue *usageError
if errors.As(err, &ue) {
fmt.Fprintf(stderr, "error: %v\n", err)
return 2
}
fmt.Fprintf(stderr, "error: %v\n", err)
return 1
}
// command is a command of the CLI.
type command struct {
flags flagSpec
// noSession marks the commands that run without an open session.
noSession bool
run func(*cmd) error
}
// The flags commands share.
var (
windowFlag = flagSpec{"window": true}
actFlags = flagSpec{"window": true, "settle": false, "timeout": true}
)
func with(specs ...flagSpec) flagSpec {
out := flagSpec{}
for _, s := range specs {
for k, v := range s {
out[k] = v
}
}
return out
}
var commands map[string]*command
// Commands returns the names of the commands, sorted.
func Commands() []string {
return slices.Sorted(maps.Keys(commands))
}
func init() {
pointerFlags := flagSpec{"button": true, "clicks": true, "mods": true}
commands = map[string]*command{
"open": {flags: flagSpec{"socket": true}, noSession: true, run: (*cmd).open},
"close": {noSession: true, run: (*cmd).close},
"windows": {flags: flagSpec{"json": false}, run: (*cmd).windows},
"window": {run: (*cmd).window},
"snapshot": {flags: with(windowFlag, flagSpec{"interactive": false, "full": false, "json": false}), run: (*cmd).snapshot},
"diff": {flags: windowFlag, run: (*cmd).diff},
"press": {flags: actFlags, run: func(c *cmd) error { return c.action("press", "press <sel>") }},
"focus": {flags: actFlags, run: func(c *cmd) error { return c.action("focus", "focus <sel>") }},
"fill": {flags: actFlags, run: func(c *cmd) error { return c.action("setValue", "fill <sel> <text>") }},
"act": {flags: actFlags, run: (*cmd).act},
"click": {flags: with(actFlags, pointerFlags), run: (*cmd).click},
"pointer": {flags: with(actFlags, pointerFlags), run: (*cmd).pointer},
"wheel": {flags: with(actFlags, flagSpec{"precise": false, "mods": true}), run: (*cmd).wheel},
"type": {flags: actFlags, run: (*cmd).typeText},
"key": {flags: with(actFlags, flagSpec{"down": false, "up": false}), run: (*cmd).key},
"menu": {flags: actFlags, run: (*cmd).menu},
"eval": {flags: with(windowFlag, flagSpec{"json": false}), run: (*cmd).eval},
"wait": {flags: with(actFlags, flagSpec{"text": true, "gone": false}), run: (*cmd).wait},
"screenshot": {flags: windowFlag, run: (*cmd).screenshot},
"skills": {noSession: true, run: func(c *cmd) error { _, err := c.stdout.Write(c.opts.Skill); return err }},
"version": {noSession: true, run: func(c *cmd) error { fmt.Fprintln(c.stdout, Version()); return nil }},
}
}
// cmd is a command running.
type cmd struct {
stdin io.Reader
stdout, stderr io.Writer
opts Options
a *args
s *session
c *client
timeout time.Duration
}
func run(argv []string, stdin io.Reader, stdout, stderr io.Writer, opts Options) error {
if len(argv) == 0 || argv[0] == "help" || argv[0] == "-h" || argv[0] == "--help" {
io.WriteString(stdout, usage)
if len(argv) == 0 {
return usagef("no command")
}
return nil
}
name := argv[0]
cm, ok := commands[name]
if !ok {
return usagef("no command %q: run mygo-automation help", name)
}
a, err := parseArgs(argv[1:], with(cm.flags, flagSpec{"session": true}))
if err != nil {
return err
}
c := &cmd{stdin: stdin, stdout: stdout, stderr: stderr, opts: opts, a: a, timeout: defaultTimeout}
if v, ok := a.vals["timeout"]; ok {
if c.timeout, err = parseTimeout(v); err != nil {
return err
}
}
if cm.noSession {
return cm.run(c)
}
if c.s, err = c.loadSession(); err != nil {
return err
}
var deadline time.Time
if c.timeout > 0 {
// A request the app never answers, as from a main thread that
// hangs, fails rather than holding the agent forever.
deadline = time.Now().Add(c.timeout + 30*time.Second)
}
if c.c, err = dial(c.s.Socket, deadline); err != nil {
return err
}
defer c.c.Close()
return cm.run(c)
}
// parseTimeout reads a duration, as 5s or 500ms; a bare number is in
// milliseconds, as the protocol's.
func parseTimeout(v string) (time.Duration, error) {
if ms, err := strconv.Atoi(v); err == nil && ms >= 0 {
return time.Duration(ms) * time.Millisecond, nil
}
d, err := time.ParseDuration(v)
if err != nil || d < 0 {
return 0, usagef("--timeout %s: write a duration, as 5s or 500ms (0 waits forever)", v)
}
return d, nil
}
// Version is the version of MyGo the command was built from: the
// module's version when go install got it, as v0.8.0, the version an
// app's go.mod requires when installed from the app's module, or (devel).
func Version() string {
bi, ok := debug.ReadBuildInfo()
if !ok {
return "(devel)"
}
mods := append([]*debug.Module{&bi.Main}, bi.Deps...)
for _, m := range mods {
if m.Path != "github.com/egoist/mygo" || m.Version == "" {
continue
}
if m.Replace != nil {
return m.Version + " (replaced by " + m.Replace.Path + ")"
}
return m.Version
}
return "(devel)"
}
// sessionName is the session's name: --session, else
// $MYGO_AUTOMATION_SESSION, else default.
func (c *cmd) sessionName() string {
if v, ok := c.a.vals["session"]; ok {
return v
}
if v := os.Getenv("MYGO_AUTOMATION_SESSION"); v != "" {
return v
}
return "default"
}
func (c *cmd) dir() (string, error) {
if c.opts.Dir != "" {
return c.opts.Dir, nil
}
cache, err := os.UserCacheDir()
if err != nil {
return "", err
}
return filepath.Join(cache, "mygo", "automation"), nil
}
func (c *cmd) loadSession() (*session, error) {
dir, err := c.dir()
if err != nil {
return nil, err
}
return loadSession(dir, c.sessionName())
}
func (c *cmd) ok() error {
_, err := io.WriteString(c.stdout, "ok\n")
return err
}
// open attaches a session to the app listening on the socket.
func (c *cmd) open() error {
if err := c.a.want(0, 0, "open [--socket path] [--session name]"); err != nil {
return err
}
path := c.a.vals["socket"]
if path == "" {
path = os.Getenv("MYGO_AUTOMATION")
}
if path == "" {
return usagef("open needs --socket <path>: the path the app's MYGO_AUTOMATION names")
}
path, err := filepath.Abs(path)
if err != nil {
return err
}
dir, err := c.dir()
if err != nil {
return err
}
name := c.sessionName()
file, err := sessionPath(dir, name)
if err != nil {
return usagef("%v", err)
}
cl, err := dial(path, time.Now().Add(time.Minute))
if err != nil {
return err
}
defer cl.Close()
var res struct{ Windows []windowInfo }
if err := cl.call("windows", nil, &res); err != nil {
return err
}
s := &session{Socket: path, Next: 1, name: name, path: file}
if old, err := loadSession(dir, name); err == nil {
// Opening again forgets what windows showed, and its refs go
// stale rather than come back for other elements.
s.Next = max(old.Next, 1)
}
if err := s.save(); err != nil {
return err
}
fmt.Fprintf(c.stdout, "opened %s (session %s)\n", path, name)
for _, w := range res.Windows {
fmt.Fprintln(c.stdout, windowLine(w, false))
}
return nil
}
// close ends the session, leaving the app running.
func (c *cmd) close() error {
if err := c.a.want(0, 0, "close [--session name]"); err != nil {
return err
}
dir, err := c.dir()
if err != nil {
return err
}
name := c.sessionName()
path, err := sessionPath(dir, name)
if err != nil {
return usagef("%v", err)
}
if err := os.Remove(path); errors.Is(err, os.ErrNotExist) {
fmt.Fprintf(c.stdout, "no session %s\n", name)
return nil
} else if err != nil {
return err
}
fmt.Fprintf(c.stdout, "closed session %s\n", name)
return nil
}
func (c *cmd) windows() error {
if err := c.a.want(0, 0, "windows [--json]"); err != nil {
return err
}
raw, err := c.c.callRaw("windows", nil)
if err != nil {
return err
}
if c.a.bools["json"] {
return c.printJSON(raw)
}
var res struct{ Windows []windowInfo }
if err := json.Unmarshal(raw, &res); err != nil {
return err
}
if len(res.Windows) == 0 {
fmt.Fprintln(c.stdout, "(no windows)")
}
for _, w := range res.Windows {
fmt.Fprintln(c.stdout, windowLine(w, w.ID == c.s.Window))
}
return nil
}
// window picks the window that commands target unless they name one.
func (c *cmd) window() error {
if err := c.a.want(1, 1, "window <w1|auto>"); err != nil {
return err
}
id, err := parseWindow(c.a.pos[0])
if err != nil {
return err
}
var res struct{ Windows []windowInfo }
if err := c.c.call("windows", nil, &res); err != nil {
return err
}
if id == 0 {
c.s.Window = 0
fmt.Fprintln(c.stdout, "commands target the focused window")
return c.s.save()
}
for _, w := range res.Windows {
if w.ID == id {
c.s.Window = id
fmt.Fprintln(c.stdout, windowLine(w, true))
return c.s.save()
}
}
return &protoError{"no_window", fmt.Sprintf("no window %d: run windows", id)}
}
// parseWindow reads a window, as w2 or 2; auto or 0 is the focused one.
func parseWindow(s string) (int, error) {
if s == "auto" || s == "focused" {
return 0, nil
}
n, err := strconv.Atoi(strings.TrimPrefix(s, "w"))
if err != nil || n < 0 {
return 0, usagef("window %q: write w1, 1 or auto", s)
}
return n, nil
}
// targetWindow is the window a command without a ref targets: --window,
// else the session's, else 0 for the focused one.
func (c *cmd) targetWindow() (int, error) {
if v, ok := c.a.vals["window"]; ok {
return parseWindow(v)
}
return c.s.Window, nil
}
func (c *cmd) printJSON(raw json.RawMessage) error {
var b bytes.Buffer
if err := json.Compact(&b, raw); err != nil {
return err
}
b.WriteByte('\n')
_, err := c.stdout.Write(b.Bytes())
return err
}
// tree reads the elements of a window, saying how to read a page instead.
func (c *cmd) tree(window int) (*tree, json.RawMessage, error) {
raw, err := c.c.callRaw("tree", map[string]any{"window": window})
if err != nil {
var pe *protoError
if errors.As(err, &pe) && pe.Code == "unsupported" {
what, _, _ := strings.Cut(pe.Message, ":")
return nil, nil, &protoError{pe.Code, what + ", which has no elements here: read it with eval"}
}
if errors.As(err, &pe) && pe.Code == "no_window" && window != 0 {
c.s.forget(window)
c.s.save()
}
return nil, nil, err
}
t := &tree{}
if err := json.Unmarshal(raw, t); err != nil {
return nil, nil, err
}
return t, raw, nil
}
func (c *cmd) snapshot() error {
if err := c.a.want(0, 0, "snapshot [-i] [--full] [--json] [--window w]"); err != nil {
return err
}
window, err := c.targetWindow()
if err != nil {
return err
}
t, raw, err := c.tree(window)
if err != nil {
return err
}
c.s.observe(t)
if err := c.s.save(); err != nil {
return err
}
if c.a.bools["json"] {
return c.printJSON(raw)
}
writeSnapshot(c.stdout, c.s.Seen[strconv.Itoa(t.Window)], t.Announcements, c.a.bools["interactive"], c.a.bools["full"])
return nil
}
func (c *cmd) diff() error {
if err := c.a.want(0, 0, "diff [--window w]"); err != nil {
return err
}
window, err := c.targetWindow()
if err != nil {
return err
}
return c.printDiff(window)
}
// printDiff prints what changed in the window since the last snapshot or
// diff, and takes what it shows now.
func (c *cmd) printDiff(window int) error {
t, _, err := c.tree(window)
if err != nil {
var pe *protoError
if errors.As(err, &pe) && pe.Code == "unsupported" {
// A page settled; it has no elements to compare.
fmt.Fprintln(c.stdout, "ok (a web page: read it with eval)")
return nil
}
return err
}
before := c.s.observe(t)
if err := c.s.save(); err != nil {
return err
}
lines := diff(before, c.s.Seen[strconv.Itoa(t.Window)], 1)
if len(lines) == 0 {
fmt.Fprintln(c.stdout, "(no changes)")
}
for _, l := range lines {
fmt.Fprintln(c.stdout, l)
}
writeAnnouncements(c.stdout, t.Announcements)
return nil
}
// done ends an action on window: with --settle, it waits for the window
// to settle and prints the diff; otherwise it prints ok.
func (c *cmd) done(window int) error {
if !c.a.bools["settle"] {
return c.ok()
}
if err := c.idle(window); err != nil {
var pe *protoError
if !errors.As(err, &pe) || pe.Code != "timeout" {
return err
}
fmt.Fprintf(c.stderr, "warning: the window did not settle in %v; the diff may miss what comes after\n", c.timeout)
}
return c.printDiff(window)
}
// idle waits for the window to settle, for --timeout.
func (c *cmd) idle(window int) error {
return c.c.call("idle", map[string]any{"window": window, "timeout": c.timeout.Milliseconds()}, nil)
}
// target is an element a selector names.
type target struct {
window int
id string
// ref is the selector when it is a ref, for errors.
ref string
}
// resolve finds the element a selector names: @e7 (a ref), key=<key>
// (the app's key) or id=<digits> (an element ID, as --json shows).
func (c *cmd) resolve(sel string) (target, error) {
if n, ok := parseRef(sel); ok {
w, id, err := c.s.lookup(n)
if err != nil {
return target{}, err
}
return target{w, id, ref(n)}, nil
}
window, err := c.targetWindow()
if err != nil {
return target{}, err
}
if id, ok := strings.CutPrefix(sel, "id="); ok {
if _, err := strconv.ParseUint(id, 10, 64); err != nil {
return target{}, usagef("selector %q: an element ID is a string of digits", sel)
}
return target{window: window, id: id}, nil
}
k, ok := strings.CutPrefix(sel, "key=")
if !ok {
return target{}, usagef("selector %q: write a ref (@e7), key=<key> or id=<digits>", sel)
}
want := keyJSON(k)
t, _, err := c.tree(window)
if err != nil {
return target{}, err
}
var found []string
for _, n := range t.Nodes {
var got bytes.Buffer
if len(n.Key) > 0 && json.Compact(&got, n.Key) == nil && bytes.Equal(got.Bytes(), want) {
found = append(found, n.ID)
}
}
switch len(found) {
case 0:
return target{}, &protoError{"no_element", fmt.Sprintf("window %d shows no element with the key %s", t.Window, want)}
case 1:
return target{window: t.Window, id: found[0]}, nil
}
return target{}, &protoError{"invalid_request", fmt.Sprintf("%d elements of window %d have the key %s: use a ref", len(found), t.Window, want)}
}
// gone turns the app's answer that a ref's element or window is gone
// into a stale ref.
func gone(t target, err error) error {
var pe *protoError
if t.ref == "" || !errors.As(err, &pe) {
return err
}
switch pe.Code {
case "no_element":
return &staleError{t.ref, fmt.Sprintf("window %d no longer shows its element", t.window)}
case "no_window":
return &staleError{t.ref, fmt.Sprintf("its window %d closed", t.window)}
}
return err
}
// actOn performs an action of assistive technology on an element.
func (c *cmd) actOn(t target, action string, extra map[string]any) error {
p := map[string]any{"window": t.window, "id": t.id, "action": action}
for k, v := range extra {
p[k] = v
}
if err := c.c.call("act", p, nil); err != nil {
return gone(t, err)
}
return c.done(t.window)
}
// action runs press, focus and fill.
func (c *cmd) action(action, use string) error {
n := 1
if action == "setValue" {
n = 2
}
if err := c.a.want(n, n, use+" [--settle]"); err != nil {
return err
}
t, err := c.resolve(c.a.pos[0])
if err != nil {
return err
}
var extra map[string]any
if action == "setValue" {
extra = map[string]any{"text": c.a.pos[1]}
}
return c.actOn(t, action, extra)
}
// actions are the protocol's actions, which act takes.
var actions = []string{"press", "focus", "increment", "decrement", "setValue", "insertText", "selectText", "scrollIntoView", "expand", "collapse"}
func (c *cmd) act() error {
const use = "act <sel> <action> [<text> | <from> <to>] [--settle]"
if err := c.a.want(2, 4, use); err != nil {
return err
}
action := c.a.pos[1]
if !slices.Contains(actions, action) {
return usagef("no action %q: %s", action, strings.Join(actions, ", "))
}
extra := map[string]any{}
switch rest := c.a.pos[2:]; {
case action == "setValue" || action == "insertText":
if len(rest) != 1 {
return usagef("usage: mygo-automation act <sel> %s <text>", action)
}
extra["text"] = rest[0]
case action == "selectText":
if len(rest) != 2 {
return usagef("usage: mygo-automation act <sel> selectText <from> <to>")
}
for i, k := range []string{"from", "to"} {
n, err := strconv.Atoi(rest[i])
if err != nil || n < 0 {
return usagef("selectText takes rune offsets, not %q", rest[i])
}
extra[k] = n
}
case len(rest) > 0:
return usagef("action %s takes no arguments", action)
}
t, err := c.resolve(c.a.pos[0])
if err != nil {
return err
}
return c.actOn(t, action, extra)
}
// point reads where a pointer goes: an element's center, from pos[0], or
// x and y, from pos[0:2]. It returns the window, the point, and how many
// arguments it read.
func (c *cmd) point(pos []string) (window int, x, y float64, used int, t target, err error) {
if len(pos) >= 2 {
if x, err1 := strconv.ParseFloat(pos[0], 64); err1 == nil {
y, err2 := strconv.ParseFloat(pos[1], 64)
if err2 != nil {
return 0, 0, 0, 0, t, usagef("y %q is no number", pos[1])
}
window, err = c.targetWindow()
return window, x, y, 2, t, err
}
}
if len(pos) == 0 {
return 0, 0, 0, 0, t, usagef("a pointer needs a selector or x and y")
}
if t, err = c.resolve(pos[0]); err != nil {
return 0, 0, 0, 0, t, err
}
tr, _, err := c.tree(t.window)
if err != nil {
return 0, 0, 0, 0, t, gone(t, err)
}
for _, n := range tr.Nodes {
if n.ID == t.id {
b := n.Bounds
return tr.Window, b.X + b.Width/2, b.Y + b.Height/2, 1, t, nil
}
}
return 0, 0, 0, 0, t, gone(t, &protoError{"no_element", fmt.Sprintf("window %d shows no element %s", tr.Window, t.id)})
}
// pointerEvent makes an event of the pointer's flags.
func (c *cmd) pointerEvent(typ string, x, y float64) (inputEvent, error) {
ev := inputEvent{Type: typ, X: x, Y: y, Button: c.a.vals["button"]}
if v, ok := c.a.vals["clicks"]; ok {
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
return ev, usagef("--clicks %q: 1 or more", v)
}
ev.Clicks = n
}
if v := c.a.vals["mods"]; v != "" {
ev.Mods = strings.Split(v, ",")
}
return ev, nil
}
// input sends events to a window, then ends as actions do.
func (c *cmd) input(window int, t target, evs ...inputEvent) error {
if err := c.c.call("input", map[string]any{"window": window, "events": evs}, nil); err != nil {
return gone(t, err)
}
return c.done(window)
}
func (c *cmd) click() error {
const use = "click <sel> | <x> <y> [--button left|right|middle] [--clicks n] [--mods shift,ctrl,alt,super,cmdOrCtrl] [--settle]"
if err := c.a.want(1, 2, use); err != nil {
return err
}
window, x, y, used, t, err := c.point(c.a.pos)
if err != nil {
return err
}
if used != len(c.a.pos) {
return usagef("usage: mygo-automation %s", use)
}
ev, err := c.pointerEvent("click", x, y)
if err != nil {
return err
}
return c.input(window, t, ev)
}
func (c *cmd) pointer() error {
const use = "pointer move|down|up <sel> | <x> <y> [--button b] [--clicks n] [--mods m] [--settle]"
if err := c.a.want(2, 3, use); err != nil {
return err
}
typ, ok := map[string]string{"move": "pointerMove", "down": "pointerDown", "up": "pointerUp"}[c.a.pos[0]]
if !ok {
return usagef("usage: mygo-automation %s", use)
}
window, x, y, used, t, err := c.point(c.a.pos[1:])
if err != nil {
return err
}
if used != len(c.a.pos)-1 {
return usagef("usage: mygo-automation %s", use)
}
ev, err := c.pointerEvent(typ, x, y)
if err != nil {
return err
}
return c.input(window, t, ev)
}
func (c *cmd) wheel() error {
const use = "wheel <sel> <dx> <dy> | <x> <y> <dx> <dy> [--precise] [--mods m] [--settle]"
if err := c.a.want(3, 4, use); err != nil {
return err
}
at := c.a.pos[:len(c.a.pos)-2]
window, x, y, used, t, err := c.point(at)
if err != nil {
return err
}
if used != len(at) {
return usagef("usage: mygo-automation %s", use)
}
var d [2]float64
for i, s := range c.a.pos[len(at):] {
if d[i], err = strconv.ParseFloat(s, 64); err != nil {
return usagef("wheel distance %q is no number", s)
}
}
ev := inputEvent{Type: "wheel", X: x, Y: y, DX: d[0], DY: d[1], Precise: c.a.bools["precise"]}
if v := c.a.vals["mods"]; v != "" {
ev.Mods = strings.Split(v, ",")
}
return c.input(window, t, ev)
}
func (c *cmd) typeText() error {
if err := c.a.want(1, 1, "type <text> [--settle]"); err != nil {
return err
}
window, err := c.targetWindow()
if err != nil {
return err
}
if c.a.pos[0] == "" {
return usagef("type needs text")
}
return c.input(window, target{}, inputEvent{Type: "text", Text: c.a.pos[0]})
}
func (c *cmd) key() error {
if err := c.a.want(1, -1, "key <key>... [--down|--up] [--settle], as key Enter or key CmdOrCtrl+A Backspace"); err != nil {
return err
}
typ := "key"
switch {
case c.a.bools["down"] && c.a.bools["up"]:
return usagef("key takes --down or --up, not both")
case c.a.bools["down"]:
typ = "keyDown"
case c.a.bools["up"]:
typ = "keyUp"
}
window, err := c.targetWindow()
if err != nil {
return err
}
evs := make([]inputEvent, len(c.a.pos))
for i, k := range c.a.pos {
evs[i] = inputEvent{Type: typ, Key: k}
}
return c.input(window, target{}, evs...)
}
func (c *cmd) menu() error {
if err := c.a.want(1, -1, "menu <label>... [--settle], as menu File \"New Window\""); err != nil {
return err
}
window, err := c.targetWindow()
if err != nil {
return err
}
if err := c.c.call("menu", map[string]any{"window": window, "path": c.a.pos}, nil); err != nil {
return err
}
return c.done(window)
}
func (c *cmd) eval() error {
if err := c.a.want(1, 1, "eval <script> | - [--json] [--window w]"); err != nil {
return err
}
script := c.a.pos[0]
if script == "-" {
b, err := io.ReadAll(c.stdin)
if err != nil {
return err
}
script = string(b)
}
window, err := c.targetWindow()
if err != nil {
return err
}
raw, err := c.c.callRaw("eval", map[string]any{"window": window, "script": script})
if err != nil {
var pe *protoError
if errors.As(err, &pe) && pe.Code == "unsupported" {
what, _, _ := strings.Cut(pe.Message, ":")
return &protoError{pe.Code, what + ": read it with snapshot (scripts reach only windows showing a web page, not web views inside native UI)"}
}
return err
}
var res struct{ Value json.RawMessage }
if err := json.Unmarshal(raw, &res); err != nil {
return err
}
if len(res.Value) == 0 {
res.Value = json.RawMessage("null")
}
var s string
if !c.a.bools["json"] && json.Unmarshal(res.Value, &s) == nil {
_, err := fmt.Fprintln(c.stdout, s)
return err
}
return c.printJSON(res.Value)
}
// pollEvery is how often wait reads the window again while what it
// waits for has not come.
const pollEvery = 50 * time.Millisecond
func (c *cmd) wait() error {
if err := c.a.want(0, 1, "wait [<sel>] [--text s] [--gone] [--timeout d] [--settle]"); err != nil {
return err
}
text, hasText := c.a.vals["text"]
if !hasText && len(c.a.pos) == 0 {
if c.a.bools["gone"] {
return usagef("wait --gone needs a selector or --text")
}
window, err := c.targetWindow()
if err != nil {
return err
}
if err := c.idle(window); err != nil {
return err
}
return c.done(window)
}
if hasText && len(c.a.pos) > 0 {
return usagef("wait takes a selector or --text, not both")
}
window, err := c.targetWindow()
if err != nil {
return err
}
// match tells whether the window shows what is waited for.
var match func(n *node) bool
var what string
if hasText {
what = "text " + strconv.Quote(text)
match = func(n *node) bool { return strings.Contains(n.Label, text) || strings.Contains(n.Value, text) }
} else {
sel := c.a.pos[0]
what = sel
if n, ok := parseRef(sel); ok {
w, id, err := c.s.lookup(n)
if err != nil {
return err
}
window = w
match = func(n *node) bool { return n.ID == id }
} else if id, ok := strings.CutPrefix(sel, "id="); ok {
match = func(n *node) bool { return n.ID == id }
} else if k, ok := strings.CutPrefix(sel, "key="); ok {
want := keyJSON(k)
match = func(n *node) bool {
var got bytes.Buffer
return len(n.Key) > 0 && json.Compact(&got, n.Key) == nil && bytes.Equal(got.Bytes(), want)
}
} else {
return usagef("selector %q: write a ref (@e7), key=<key> or id=<digits>", sel)
}
}
want := !c.a.bools["gone"]
start := time.Now()
for {
// Read the condition even while the window keeps drawing.
// Only --settle waits for idle, after the condition is met.
t, _, err := c.tree(window)
if err != nil {
return err
}
found := slices.ContainsFunc(t.Nodes, func(n node) bool { return match(&n) })
if found == want {
return c.done(window)
}
if c.timeout > 0 && time.Since(start) > c.timeout {
state := "does not show"
if !want {
state = "still shows"
}
return &protoError{"timeout", fmt.Sprintf("window %d %s %s after %v", t.Window, state, what, c.timeout)}
}
time.Sleep(pollEvery)
}
}
func (c *cmd) screenshot() error {
if err := c.a.want(1, 1, "screenshot <file.png> [--window w]"); err != nil {
return err
}
window, err := c.targetWindow()
if err != nil {
return err
}
var res struct {
PNG []byte
Width, Height int
}
if err := c.c.call("capture", map[string]any{"window": window}, &res); err != nil {
return err
}
path := c.a.pos[0]
if err := os.WriteFile(path, res.PNG, 0o644); err != nil {
return err
}
_, err = fmt.Fprintf(c.stdout, "%s %dx%d\n", path, res.Width, res.Height)
return err
}
+391
View File
@@ -0,0 +1,391 @@
package automationcli
import (
"bufio"
"bytes"
"encoding/json"
"net"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"github.com/egoist/mygo/internal/wait"
)
func TestParseArgs(t *testing.T) {
spec := flagSpec{"settle": false, "timeout": true, "interactive": false, "mods": true}
a, err := parseArgs([]string{"@e2", "--settle", "-i", "0", "-120", "--timeout=2s", "--mods", "shift,ctrl", "-.5", "-", "--", "--settle"}, spec)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(a.pos, []string{"@e2", "0", "-120", "-.5", "-", "--settle"}) || !a.bools["settle"] || !a.bools["interactive"] || a.vals["timeout"] != "2s" || a.vals["mods"] != "shift,ctrl" {
t.Errorf("parsed %+v", a)
}
for _, bad := range [][]string{{"--nope"}, {"--timeout"}, {"--settle=1"}} {
if _, err := parseArgs(bad, spec); err == nil {
t.Errorf("%v parsed", bad)
}
}
}
// fakeApp answers the socket's requests as an app does, with a window of
// native UI (1) and one showing a page (2).
type fakeApp struct {
mu sync.Mutex
nodes []map[string]any
focus string
calls []string
// acted are the params of act and input requests.
acted []map[string]any
// idle can keep a request waiting while the app still draws.
idle func()
// trees are successive snapshots, as work changes what the app shows.
trees [][]map[string]any
}
func (f *fakeApp) answer(method string, p map[string]any) (any, *protoError) {
if method == "idle" && f.idle != nil {
f.idle()
}
f.mu.Lock()
defer f.mu.Unlock()
f.calls = append(f.calls, method)
window := 0
if w, ok := p["window"].(float64); ok {
window = int(w)
}
if window > 2 {
return nil, &protoError{"no_window", "no such window"}
}
page := window == 2
switch method {
case "windows":
return map[string]any{"windows": []map[string]any{
{"id": 1, "title": "Contacts", "kind": "content", "focused": true, "visible": true},
{"id": 2, "title": "Docs", "kind": "page", "url": "http://localhost/", "visible": true},
}}, nil
case "tree":
if page {
return nil, &protoError{"unsupported", "window 2 shows a web page: use eval"}
}
if len(f.trees) > 0 {
f.nodes, f.trees = f.trees[0], f.trees[1:]
}
return map[string]any{"window": 1, "focus": f.focus, "nodes": f.nodes}, nil
case "idle":
return map[string]any{}, nil
case "act":
f.acted = append(f.acted, p)
for _, n := range f.nodes {
if n["id"] == p["id"] {
if p["id"] == "11077037771207380721" && p["action"] == "press" && f.focus == "" {
// Add shows a text field.
f.nodes = append(f.nodes, map[string]any{"id": "42", "role": "textField", "label": "First name", "actions": []string{"focus", "setValue"}})
}
if p["action"] == "setValue" {
n["value"] = p["text"]
f.focus = n["id"].(string)
}
return map[string]any{}, nil
}
}
return nil, &protoError{"no_element", "window 1 shows no element " + p["id"].(string)}
case "input", "menu":
if page && method == "input" {
return nil, &protoError{"unsupported", "window 2 shows a web page: use eval"}
}
f.acted = append(f.acted, p)
return map[string]any{}, nil
case "eval":
if !page {
return nil, &protoError{"unsupported", "window 1 shows native UI, not a web page: use tree"}
}
if p["script"] == "document.title" {
return map[string]any{"value": "Docs"}, nil
}
return map[string]any{"value": map[string]any{"n": 1}}, nil
case "capture":
return map[string]any{"png": []byte("\x89PNG fake"), "width": 2, "height": 1}, nil
}
return nil, &protoError{"unknown_method", method}
}
// serve answers the socket's connections until the test ends.
func (f *fakeApp) serve(t *testing.T) string {
dir, err := os.MkdirTemp("", "mygo-automation")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(dir) })
path := filepath.Join(dir, "app.sock")
l, err := net.Listen("unix", path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { l.Close() })
go func() {
for {
c, err := l.Accept()
if err != nil {
return
}
go func() {
defer c.Close()
sc := bufio.NewScanner(c)
for sc.Scan() {
var req struct {
ID json.RawMessage
Method string
Params map[string]any
}
json.Unmarshal(sc.Bytes(), &req)
res, perr := f.answer(req.Method, req.Params)
line, _ := json.Marshal(map[string]any{"id": req.ID, "result": res, "error": perr})
if perr != nil {
line, _ = json.Marshal(map[string]any{"id": req.ID, "error": perr})
}
c.Write(append(line, '\n'))
}
}()
}
}()
return path
}
// cli runs the CLI's command lines in one directory of sessions.
type cli struct {
t *testing.T
dir string
}
// run runs a command line and returns its output and exit status.
func (c cli) run(args ...string) (string, int) {
c.t.Helper()
var out bytes.Buffer
code := Run(args, strings.NewReader("1 + 1"), &out, &out, Options{Dir: c.dir, Skill: []byte("---\nname: mygo-automation\n---\nguide\n")})
return out.String(), code
}
// must runs a command line that succeeds and checks its output.
func (c cli) must(want string, args ...string) {
c.t.Helper()
out, code := c.run(args...)
if code != 0 || out != want {
c.t.Errorf("mygo-automation %s: exit %d\n%s\nwant:\n%s", strings.Join(args, " "), code, out, want)
}
}
// fails runs a command line that fails, with an output that has want.
func (c cli) fails(code int, want string, args ...string) {
c.t.Helper()
out, got := c.run(args...)
if got != code || !strings.Contains(out, want) {
c.t.Errorf("mygo-automation %s: exit %d (want %d)\n%s\nwant it to say: %s", strings.Join(args, " "), got, code, out, want)
}
}
func TestCommands(t *testing.T) {
app := &fakeApp{nodes: []map[string]any{
{"id": "1", "role": "heading", "label": "Contacts"},
{"id": "11077037771207380721", "role": "button", "key": "add", "label": "Add", "states": []string{"focusable"}, "actions": []string{"press", "focus"}},
{"id": "3", "role": "list", "label": "People"},
{"id": "4", "parent": "3", "role": "listItem", "label": "Ada", "key": 7, "actions": []string{"press"}, "bounds": map[string]any{"x": 10, "y": 20, "width": 100, "height": 30}},
}}
path := app.serve(t)
c := cli{t, t.TempDir()}
c.fails(1, "no session \"default\": run mygo-automation open", "snapshot")
c.fails(2, "open needs --socket", "open")
c.must("opened "+path+" (session default)\nw1 [content] \"Contacts\" focused\nw2 [page] \"Docs\" url=http://localhost/\n", "open", "--socket", path)
c.must("@e2 [button] \"Add\" key=add\n@e4 [listItem] \"Ada\" key=7\n", "snapshot", "-i")
c.must("@e1 [heading] \"Contacts\"\n@e2 [button] \"Add\" key=add\n@e3 [list] \"People\"\n @e4 [listItem] \"Ada\" key=7\n", "snapshot")
// Acting, then what changed once the window settled, with the
// elements around the change and the new element's ref.
c.must("= @e4 [listItem] \"Ada\" key=7\n+ @e5 [textField] \"First name\"\n", "press", "@e2", "--settle")
c.must("= @e4 [listItem] \"Ada\" key=7\n- @e5 [textField] \"First name\"\n+ @e5 [textField] \"First name\" value=\"Ada\" focused\n", "fill", "@e5", "Ada", "--settle")
c.must("(no changes)\n", "diff")
c.must("ok\n", "press", "key=add")
if got := app.acted[len(app.acted)-1]; got["id"] != "11077037771207380721" || got["window"] != float64(1) {
t.Errorf("press key=add sent %v", got)
}
c.must("ok\n", "press", "key=7")
c.must("ok\n", "act", "@e5", "selectText", "0", "2")
if got := app.acted[len(app.acted)-1]; got["action"] != "selectText" || got["from"] != float64(0) || got["to"] != float64(2) {
t.Errorf("act selectText sent %v", got)
}
// Pointers go to an element's center, or to a point.
c.must("ok\n", "click", "@e4", "--button", "right", "--mods", "shift")
c.must("ok\n", "wheel", "@e4", "0", "-120", "--precise")
c.must("ok\n", "pointer", "down", "5", "6.5")
c.must("ok\n", "key", "CmdOrCtrl+A", "Backspace")
c.must("ok\n", "type", "Grace")
c.must("ok\n", "menu", "File", "New Window")
var events []any
for _, p := range app.acted[len(app.acted)-6:] {
if e, ok := p["events"].([]any); ok {
events = append(events, e...)
} else {
events = append(events, p["path"])
}
}
got, _ := json.Marshal(events)
want := `[{"button":"right","mods":["shift"],"type":"click","x":60,"y":35},{"dy":-120,"precise":true,"type":"wheel","x":60,"y":35},{"type":"pointerDown","x":5,"y":6.5},{"key":"CmdOrCtrl+A","type":"key"},{"key":"Backspace","type":"key"},{"text":"Grace","type":"text"},["File","New Window"]]`
if string(got) != want {
t.Errorf("events\n got %s\nwant %s", got, want)
}
// A ref whose element is gone is rejected, never given to another.
app.mu.Lock()
app.nodes = slices.Delete(app.nodes, 3, 4)
app.mu.Unlock()
c.fails(1, "stale ref @e4: window 1 no longer shows its element", "press", "@e4")
c.fails(1, "stale ref @e4: window 1 no longer shows its element", "click", "@e4")
c.must("= @e3 [list] \"People\"\n- @e4 [listItem] \"Ada\" key=7\n= @e5 [textField] \"First name\" value=\"Ada\" focused\n", "diff")
c.fails(1, "stale ref @e4: its element is gone", "press", "@e4")
c.fails(1, "stale ref @e9: no snapshot or diff", "press", "@e9")
c.fails(1, "no_element: window 1 shows no element with the key 7", "press", "key=7")
c.fails(2, `selector "Add"`, "press", "Add")
// Pages are read with eval; native UI is not.
c.must("w2 [page] \"Docs\" url=http://localhost/ selected\n", "window", "w2")
c.must("w1 [content] \"Contacts\" focused\nw2 [page] \"Docs\" url=http://localhost/ selected\n", "windows")
c.fails(1, "window 2 shows a web page, which has no elements here: read it with eval", "snapshot")
c.must("Docs\n", "eval", "document.title")
c.must("{\"n\":1}\n", "eval", "-")
c.must("\"Docs\"\n", "eval", "document.title", "--json")
c.must("ok (a web page: read it with eval)\n", "wait", "--settle")
c.fails(1, "window 1 shows native UI, not a web page: read it with snapshot", "eval", "1", "--window", "w1")
c.must("commands target the focused window\n", "window", "auto")
shot := filepath.Join(t.TempDir(), "shot.png")
c.must(shot+" 2x1\n", "screenshot", shot)
if b, err := os.ReadFile(shot); err != nil || string(b) != "\x89PNG fake" {
t.Errorf("the screenshot's file: %q, %v", b, err)
}
// Sessions keep refs of their own.
c.must("opened "+path+" (session b)\nw1 [content] \"Contacts\" focused\nw2 [page] \"Docs\" url=http://localhost/\n", "open", "--socket", path, "--session", "b")
c.must("@e1 [heading] \"Contacts\"\n@e2 [button] \"Add\" key=add\n@e3 [list] \"People\"\n@e4 [textField] \"First name\" value=\"Ada\" focused\n", "snapshot", "--session", "b")
c.fails(1, "stale ref @e4", "press", "@e4")
// Opening a session again makes its refs stale, never names others
// with them.
c.must("opened "+path+" (session b)\nw1 [content] \"Contacts\" focused\nw2 [page] \"Docs\" url=http://localhost/\n", "open", "--socket", path, "--session", "b")
c.fails(1, "stale ref @e1: its element is gone", "press", "@e1", "--session", "b")
c.must("@e6 [button] \"Add\" key=add\n@e8 [textField] \"First name\" value=\"Ada\" focused\n", "snapshot", "-i", "--session", "b")
c.must("---\nname: mygo-automation\n---\nguide\n", "skills")
c.must("closed session default\n", "close")
c.must("no session default\n", "close")
c.fails(1, "no session \"default\"", "snapshot")
c.fails(2, "no command \"nope\"", "nope")
}
func TestWaitText(t *testing.T) {
app := &fakeApp{nodes: []map[string]any{{"id": "1", "role": "text", "label": "Saving…"}}}
path := app.serve(t)
c := cli{t, t.TempDir()}
c.must("opened "+path+" (session default)\nw1 [content] \"Contacts\" focused\nw2 [page] \"Docs\" url=http://localhost/\n", "open", "--socket", path)
c.must("ok\n", "wait", "--text", "Saving")
c.fails(1, `timeout: window 1 does not show text "Saved" after 1ms`, "wait", "--text", "Saved", "--timeout", "1ms")
c.fails(1, `timeout: window 1 still shows text "Saving" after 1ms`, "wait", "--text", "Saving", "--gone", "--timeout", "1")
c.fails(2, "wait --gone needs", "wait", "--gone")
}
// A condition can be met while a window keeps drawing. Waiting for it
// must not need that drawing to stop, even with no timeout.
func TestWaitWhileDrawing(t *testing.T) {
ready := []map[string]any{{"id": "1", "role": "text", "label": "Ready", "key": "ready"}}
saving := []map[string]any{{"id": "1", "role": "text", "label": "Saving"}}
value := []map[string]any{{"id": "1", "role": "textField", "value": "Ready"}}
for _, tc := range []struct {
name string
args []string
trees [][]map[string]any
snapshot bool
code int
out string
}{
{"visible", []string{"--text", "Ready"}, [][]map[string]any{ready}, false, 0, "ok\n"},
{"no-timeout", []string{"--text", "Ready", "--timeout", "0"}, [][]map[string]any{ready}, false, 0, "ok\n"},
{"later", []string{"--text", "Ready", "--timeout", "0"}, [][]map[string]any{saving, ready}, false, 0, "ok\n"},
{"value", []string{"--text", "Ready", "--timeout", "0"}, [][]map[string]any{saving, value}, false, 0, "ok\n"},
{"key", []string{"key=ready", "--timeout", "0"}, [][]map[string]any{nil, ready}, false, 0, "ok\n"},
{"gone-text", []string{"--text", "Saving", "--gone", "--timeout", "0"}, [][]map[string]any{saving, ready}, false, 0, "ok\n"},
{"gone-id", []string{"id=1", "--gone", "--timeout", "0"}, [][]map[string]any{ready, nil}, false, 0, "ok\n"},
{"gone-ref", []string{"@e1", "--gone", "--timeout", "0"}, [][]map[string]any{ready, ready, nil}, true, 0, "ok\n"},
{"timeout", []string{"--text", "Ready", "--timeout", "1ms"}, [][]map[string]any{saving}, false, 1, "error: timeout: window 1 does not show text \"Ready\" after 1ms\n"},
} {
t.Run(tc.name, func(t *testing.T) {
app := &fakeApp{trees: tc.trees}
idle := make(chan struct{}, 1)
stopDrawing := make(chan struct{})
stop := sync.OnceFunc(func() { close(stopDrawing) })
defer stop()
app.idle = func() {
select {
case idle <- struct{}{}:
default:
}
<-stopDrawing
}
path := app.serve(t)
c := cli{t, t.TempDir()}
if out, code := c.run("open", "--socket", path); code != 0 {
t.Fatalf("open: exit %d: %s", code, out)
}
if tc.snapshot {
c.must("@e1 [text] \"Ready\" key=ready\n", "snapshot")
}
type result struct {
out string
code int
}
done := make(chan result, 1)
go func() {
out, code := c.run(append([]string{"wait"}, tc.args...)...)
done <- result{out, code}
}()
var got result
select {
case got = <-done:
case <-idle:
t.Error("condition wait needs the window to stop drawing")
stop()
got = wait.For(t, "the wait command to finish", done)
case <-wait.Context(t).Done():
t.Fatal("the wait command never finished or asked the app to settle")
}
if got.code != tc.code || got.out != tc.out {
t.Errorf("wait: exit %d: %s; want exit %d: %s", got.code, got.out, tc.code, tc.out)
}
})
}
}
func TestWaitSettles(t *testing.T) {
for _, condition := range []bool{false, true} {
app := &fakeApp{nodes: []map[string]any{{"id": "1", "role": "text", "label": "Ready"}}}
app.idle = func() {
app.mu.Lock()
defer app.mu.Unlock()
app.nodes = []map[string]any{{"id": "1", "role": "text", "label": "Settled"}}
}
path := app.serve(t)
c := cli{t, t.TempDir()}
if out, code := c.run("open", "--socket", path); code != 0 {
t.Fatalf("open: exit %d: %s", code, out)
}
if condition {
c.must("+ @e1 [text] \"Settled\"\n", "wait", "--text", "Ready", "--settle")
} else {
c.must("ok\n", "wait")
c.must("@e1 [text] \"Settled\"\n", "snapshot")
}
}
}
+162
View File
@@ -0,0 +1,162 @@
package automationcli
import (
"bufio"
"encoding/json"
"fmt"
"net"
"time"
)
// client sends requests to an app's socket, one at a time, as
// docs/plugins/automation.md describes.
type client struct {
conn net.Conn
r *bufio.Reader
n int
}
// dial connects to the socket at path. A request that the app does not
// answer by deadline fails, unless deadline is zero.
func dial(path string, deadline time.Time) (*client, error) {
conn, err := net.Dial("unix", path)
if err != nil {
return nil, fmt.Errorf("cannot reach the app at %s (did it quit? is MYGO_AUTOMATION set and the plugin imported?): %v", path, err)
}
conn.SetDeadline(deadline)
return &client{conn: conn, r: bufio.NewReader(conn)}, nil
}
func (c *client) Close() error { return c.conn.Close() }
// protoError is the error of an answer: a code from the protocol's table
// and its message.
type protoError struct {
Code string `json:"code"`
Message string `json:"message"`
}
func (e *protoError) Error() string { return e.Code + ": " + e.Message }
// call sends a request and decodes its result into result, unless nil.
// It returns the answer's error as a *protoError.
func (c *client) call(method string, params any, result any) error {
raw, err := c.callRaw(method, params)
if err != nil {
return err
}
if result != nil {
if err := json.Unmarshal(raw, result); err != nil {
return fmt.Errorf("%s: the app's answer: %v", method, err)
}
}
return nil
}
// callRaw sends a request and returns its result as the app wrote it.
func (c *client) callRaw(method string, params any) (json.RawMessage, error) {
c.n++
line, err := json.Marshal(map[string]any{"id": c.n, "method": method, "params": params})
if err != nil {
return nil, err
}
if _, err := c.conn.Write(append(line, '\n')); err != nil {
return nil, fmt.Errorf("%s: %v", method, err)
}
answer, err := c.r.ReadBytes('\n')
if err != nil {
return nil, fmt.Errorf("%s: the app did not answer: %v", method, err)
}
var res struct {
ID int `json:"id"`
Result json.RawMessage `json:"result"`
Error *protoError `json:"error"`
}
if err := json.Unmarshal(answer, &res); err != nil {
return nil, fmt.Errorf("%s: the app's answer: %v", method, err)
}
if res.Error != nil {
return nil, res.Error
}
if res.ID != c.n {
return nil, fmt.Errorf("%s: an answer to request %d, not %d", method, res.ID, c.n)
}
return res.Result, nil
}
// windowInfo is a window the windows method lists.
type windowInfo struct {
ID int `json:"id"`
Title string `json:"title"`
Kind string `json:"kind"`
URL string `json:"url,omitempty"`
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"`
}
// tree is the tree method's result.
type tree struct {
Window int `json:"window"`
Focus string `json:"focus,omitempty"`
Nodes []node `json:"nodes"`
Announcements []string `json:"announcements,omitempty"`
}
// node is an element of a tree, with the fields the protocol gives.
type node struct {
ID string `json:"id"`
Parent string `json:"parent,omitempty"`
Role string `json:"role"`
Key json.RawMessage `json:"key,omitempty"`
Label string `json:"label,omitempty"`
Value string `json:"value,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
Description string `json:"description,omitempty"`
Shortcuts string `json:"keyShortcuts,omitempty"`
Bounds rect `json:"bounds"`
States []string `json:"states,omitempty"`
Actions []string `json:"actions,omitempty"`
Min *float64 `json:"min,omitempty"`
Max *float64 `json:"max,omitempty"`
Now *float64 `json:"now,omitempty"`
Step *float64 `json:"step,omitempty"`
Selection *[2]int `json:"selection,omitempty"`
Level int `json:"level,omitempty"`
PosInSet int `json:"posInSet,omitempty"`
SetSize int `json:"setSize,omitempty"`
RowCount int `json:"rowCount,omitempty"`
ColCount int `json:"colCount,omitempty"`
RowIndex int `json:"rowIndex,omitempty"`
ColIndex int `json:"colIndex,omitempty"`
RowSpan int `json:"rowSpan,omitempty"`
ColSpan int `json:"colSpan,omitempty"`
Current string `json:"current,omitempty"`
Complete string `json:"autoComplete,omitempty"`
WebView bool `json:"webView,omitempty"`
// RoleDescription and HasPopup are aria-roledescription and
// aria-haspopup.
RoleDescription string `json:"roleDescription,omitempty"`
HasPopup string `json:"hasPopup,omitempty"`
}
// inputEvent is an event of the input method.
type inputEvent struct {
Type string `json:"type"`
X float64 `json:"x,omitempty"`
Y float64 `json:"y,omitempty"`
Button string `json:"button,omitempty"`
Clicks int `json:"clicks,omitempty"`
DX float64 `json:"dx,omitempty"`
DY float64 `json:"dy,omitempty"`
Precise bool `json:"precise,omitempty"`
Key string `json:"key,omitempty"`
Mods []string `json:"mods,omitempty"`
Text string `json:"text,omitempty"`
}
+297
View File
@@ -0,0 +1,297 @@
package automationcli
import (
"bytes"
"encoding/json"
"fmt"
"io"
"regexp"
"strconv"
"strings"
)
// maxText is how many characters of a label or a value a line shows,
// unless full.
const maxText = 120
// line describes an element on a line, without its ref: its role, its
// label, value, key and key shortcuts, and its states, leaving out what
// it lacks. full adds what agents seldom need: placeholders under a
// label, descriptions, ranges, selections, levels, actions, bounds and
// the element's ID, and writes long text whole.
func line(n *node, focus string, full bool) string {
var b strings.Builder
b.WriteString("[" + n.Role + "]")
if n.Label != "" {
b.WriteString(" " + quote(n.Label, full))
}
if n.Value != "" {
b.WriteString(" value=" + quote(n.Value, full))
} else if n.Now != nil {
b.WriteString(" value=" + num(*n.Now))
}
if n.Placeholder != "" && (full || n.Label == "") {
b.WriteString(" placeholder=" + quote(n.Placeholder, full))
}
if len(n.Key) > 0 {
b.WriteString(" key=" + keyText(n.Key))
}
if n.Shortcuts != "" {
b.WriteString(" keyshortcuts=" + quote(n.Shortcuts, true))
}
for _, s := range n.States {
// Every control can take the focus: saying so is noise.
if s != "focusable" {
b.WriteString(" " + s)
}
}
if n.Current != "" {
b.WriteString(" current=" + n.Current)
}
if n.Complete != "" {
b.WriteString(" autocomplete=" + n.Complete)
}
if n.HasPopup != "" {
b.WriteString(" haspopup=" + n.HasPopup)
}
if n.RoleDescription != "" {
b.WriteString(" roledescription=" + quote(n.RoleDescription, full))
}
if n.ID == focus {
b.WriteString(" focused")
}
if n.WebView {
b.WriteString(" webview")
}
if !full {
return b.String()
}
if n.Description != "" {
b.WriteString(" description=" + quote(n.Description, true))
}
if n.Min != nil && n.Max != nil {
b.WriteString(" range=" + num(*n.Min) + ".." + num(*n.Max))
}
if n.Step != nil && *n.Step != 0 {
b.WriteString(" step=" + num(*n.Step))
}
if n.Selection != nil {
fmt.Fprintf(&b, " selection=%d,%d", n.Selection[0], n.Selection[1])
}
if n.Level != 0 {
fmt.Fprintf(&b, " level=%d", n.Level)
}
if n.SetSize != 0 {
fmt.Fprintf(&b, " item=%d/%d", n.PosInSet, n.SetSize)
}
// A table's or a grid's size and the place of a row or a cell in it,
// as the app gave them (aria-rowcount and the like), and the rows and
// columns a cell covers (aria-rowspan, aria-colspan).
for _, v := range [...]struct {
name string
n int
}{{"rowcount", n.RowCount}, {"colcount", n.ColCount}, {"rowindex", n.RowIndex}, {"colindex", n.ColIndex},
{"rowspan", n.RowSpan}, {"colspan", n.ColSpan}} {
if v.n != 0 {
fmt.Fprintf(&b, " %s=%d", v.name, v.n)
}
}
if len(n.Actions) > 0 {
b.WriteString(" actions=" + strings.Join(n.Actions, ","))
}
r := n.Bounds
fmt.Fprintf(&b, " bounds=%s,%s,%sx%s id=%s", num(r.X), num(r.Y), num(r.Width), num(r.Height), n.ID)
return b.String()
}
// quote quotes s, cut to maxText characters unless full.
func quote(s string, full bool) string {
if !full {
if r := []rune(s); len(r) > maxText {
return strconv.Quote(string(r[:maxText])+"…") + fmt.Sprintf(" (%d more)", len(r)-maxText)
}
}
return strconv.Quote(s)
}
func num(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) }
var bareKey = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_.:/-]*$`)
// keyText writes a key as selectors take it: a string that reads as no
// other value bare, other strings quoted, numbers and booleans as JSON
// writes them.
func keyText(k json.RawMessage) string {
var s string
if json.Unmarshal(k, &s) == nil && bareKey.MatchString(s) && s != "true" && s != "false" && s != "null" {
return s
}
var b bytes.Buffer
if json.Compact(&b, k) != nil {
return string(k)
}
return b.String()
}
// keyJSON is the JSON a key selector names: JSON as itself, as key=5,
// key=true or key="a b", anything else as a string.
func keyJSON(s string) []byte {
var v any
if json.Unmarshal([]byte(s), &v) == nil {
switch v.(type) {
case string, float64, bool:
var b bytes.Buffer
json.Compact(&b, []byte(s))
return b.Bytes()
}
}
b, _ := json.Marshal(s)
return b
}
// controls are the roles snapshot -i keeps even when they have no action
// now, as a disabled button.
var controls = map[string]bool{
"button": true, "link": true, "checkBox": true, "radio": true, "switch": true,
"slider": true, "textField": true, "popUpButton": true, "tab": true,
"menuButton": true, "toggleButton": true, "comboBox": true, "disclosure": true,
"stepper": true, "colorWell": true, "menuItem": true, "menuItemCheckBox": true,
"menuItemRadio": true, "treeItem": true,
}
// interactive tells whether snapshot -i shows n: controls, and elements
// with actions other than scrolling into view.
func interactive(n *node) bool {
if controls[n.Role] || n.WebView {
return true
}
for _, a := range n.Actions {
if a != "scrollIntoView" {
return true
}
}
return false
}
// writeSnapshot writes a window's elements, a line each, indented under
// the elements shown around them.
func writeSnapshot(w io.Writer, sn *seen, announcements []string, interactiveOnly, full bool) {
// inner is the depth of an element's children.
inner := make(map[string]int, len(sn.Nodes))
shown := 0
for i := range sn.Nodes {
n := &sn.Nodes[i]
depth := inner[n.Parent]
show := !interactiveOnly || interactive(n)
inner[n.ID] = depth
if !show {
continue
}
inner[n.ID] = depth + 1
shown++
fmt.Fprintf(w, "%s%s %s\n", strings.Repeat(" ", depth), ref(sn.Refs[n.ID]), line(n, sn.Focus, full))
}
switch {
case shown > 0:
case interactiveOnly && len(sn.Nodes) > 0:
fmt.Fprintln(w, "(no interactive elements: run snapshot without -i)")
default:
fmt.Fprintln(w, "(no elements)")
}
writeAnnouncements(w, announcements)
}
func writeAnnouncements(w io.Writer, announcements []string) {
for _, a := range announcements {
fmt.Fprintf(w, "announced %s\n", quote(a, false))
}
}
// windowLine describes a window on a line.
func windowLine(w windowInfo, selected bool) string {
var b strings.Builder
fmt.Fprintf(&b, "w%d [%s] %s", w.ID, w.Kind, quote(w.Title, false))
if w.URL != "" {
b.WriteString(" url=" + w.URL)
}
if w.Focused {
b.WriteString(" focused")
}
if !w.Visible {
b.WriteString(" hidden")
}
if selected {
b.WriteString(" selected")
}
return b.String()
}
// diffLine is a line of a diff: '+' an element added, '-' one gone or as
// it was, '=' one unchanged around them.
type diffLine struct {
op byte
ref int
text string
}
func (d diffLine) String() string { return string(d.op) + " " + ref(d.ref) + " " + d.text }
// diff compares what a window showed before with what it shows now, in
// the order of now, and keeps context unchanged elements around each
// change. An element whose line changed shows twice, as it was ('-') and
// as it is ('+'), with its ref; one gone shows with its ref, now stale.
func diff(before, now *seen, context int) []diffLine {
if before == nil {
before = &seen{}
}
at := make(map[string]int, len(before.Nodes))
for i, n := range before.Nodes {
if _, ok := at[n.ID]; !ok {
at[n.ID] = i
}
}
stays := make(map[string]bool, len(now.Nodes))
for _, n := range now.Nodes {
stays[n.ID] = true
}
var all []diffLine
next := 0
gone := func(upTo int) {
for ; next < upTo; next++ {
if n := &before.Nodes[next]; !stays[n.ID] {
all = append(all, diffLine{'-', before.Refs[n.ID], line(n, before.Focus, false)})
}
}
}
for i := range now.Nodes {
n := &now.Nodes[i]
r, text := now.Refs[n.ID], line(n, now.Focus, false)
p, ok := at[n.ID]
if !ok {
all = append(all, diffLine{'+', r, text})
continue
}
if p >= next {
gone(p)
next = p + 1
}
if was := line(&before.Nodes[p], before.Focus, false); was != text {
all = append(all, diffLine{'-', r, was}, diffLine{'+', r, text})
} else {
all = append(all, diffLine{'=', r, text})
}
}
gone(len(before.Nodes))
var out []diffLine
for i, d := range all {
keep := d.op != '='
for j := max(i-context, 0); !keep && j <= min(i+context, len(all)-1); j++ {
keep = all[j].op != '='
}
if keep {
out = append(out, d)
}
}
return out
}
+122
View File
@@ -0,0 +1,122 @@
package automationcli
import (
"encoding/json"
"strings"
"testing"
)
func f(v float64) *float64 { return &v }
func TestLine(t *testing.T) {
for _, c := range []struct {
n node
full bool
want string
}{
{node{ID: "1", Role: "text", Label: "Count: 0"}, false, `[text] "Count: 0"`},
{node{ID: "2", Role: "button", Label: "Add", Key: json.RawMessage(`"add"`), States: []string{"focusable", "disabled"}, Actions: []string{"press"}}, false, `[button] "Add" key=add disabled`},
// The focused element, a value, and a placeholder only under no label.
{node{ID: "3", Role: "textField", Label: "Name", Value: "Ada", Placeholder: "Your name"}, false, `[textField] "Name" value="Ada" focused`},
{node{ID: "4", Role: "textField", Placeholder: "Search"}, false, `[textField] placeholder="Search"`},
// Keys that read as other values, quoted; numbers as themselves.
{node{ID: "5", Role: "button", Key: json.RawMessage(`"true"`)}, false, `[button] key="true"`},
{node{ID: "5", Role: "button", Key: json.RawMessage(`"a b"`)}, false, `[button] key="a b"`},
{node{ID: "5", Role: "listItem", Key: json.RawMessage(`7`)}, false, `[listItem] key=7`},
// A slider's value, when it has no text for it.
{node{ID: "6", Role: "slider", Label: "Volume", Min: f(0), Max: f(1), Now: f(0.25), Step: f(0.05)}, false, `[slider] "Volume" value=0.25`},
{node{ID: "6", Role: "slider", Label: "Volume", Min: f(0), Max: f(1), Now: f(0.25), Step: f(0.05)}, true, `[slider] "Volume" value=0.25 range=0..1 step=0.05 bounds=0,0,0x0 id=6`},
{node{ID: "7", Role: "group", WebView: true}, false, `[group] webview`},
// What its suggestions complete, after its states.
{node{ID: "10", Role: "comboBox", Label: "City", States: []string{"focusable", "expanded"}, Complete: "list"}, false, `[comboBox] "City" expanded autocomplete=list`},
// The keys that press it, after its key.
{node{ID: "9", Role: "button", Label: "Redo", Key: json.RawMessage(`"redo"`), Shortcuts: "Ctrl+Shift+Z Ctrl+Y"}, false, `[button] "Redo" key=redo keyshortcuts="Ctrl+Shift+Z Ctrl+Y"`},
{
node{ID: "18446744073709551615", Role: "textField", Label: "Name", Value: "Ada", Placeholder: "Your name", Description: "Who", Selection: &[2]int{1, 3}, Actions: []string{"focus", "setValue"}, Bounds: rect{20, 90.5, 360, 32}},
true,
`[textField] "Name" value="Ada" placeholder="Your name" description="Who" selection=1,3 actions=focus,setValue bounds=20,90.5,360x32 id=18446744073709551615`,
},
{node{ID: "8", Role: "treeItem", Label: "src", Level: 2, PosInSet: 1, SetSize: 3, States: []string{"expandable", "expanded"}}, true, `[treeItem] "src" expandable expanded level=2 item=1/3 bounds=0,0,0x0 id=8`},
// A grid's size and a row's place in it, as the app gave them.
{node{ID: "10", Role: "grid", Label: "Sheet", RowCount: 10001, ColCount: 5, States: []string{"multiselectable"}}, true, `[grid] "Sheet" multiselectable rowcount=10001 colcount=5 bounds=0,0,0x0 id=10`},
{node{ID: "11", Role: "row", RowIndex: 4122}, true, `[row] rowindex=4122 bounds=0,0,0x0 id=11`},
{node{ID: "11", Role: "row", RowIndex: 4122}, false, `[row]`},
{node{ID: "12", Role: "cell", Label: "Total", ColSpan: 2}, true, `[cell] "Total" colspan=2 bounds=0,0,0x0 id=12`},
} {
if got := line(&c.n, "3", c.full); got != c.want {
t.Errorf("line(%+v, full %v)\n got %s\nwant %s", c.n, c.full, got, c.want)
}
}
}
func TestLongText(t *testing.T) {
long := strings.Repeat("é", maxText+30)
n := node{ID: "1", Role: "textField", Value: long}
want := `[textField] value="` + strings.Repeat("é", maxText) + `…" (30 more)`
if got := line(&n, "", false); got != want {
t.Errorf("got %s", got)
}
if got := line(&n, "", true); !strings.Contains(got, `value="`+long+`"`) {
t.Errorf("full cuts the text: %s", got)
}
// Lines stay lines.
n.Value = "a\nb"
if got := line(&n, "", false); got != `[textField] value="a\nb"` {
t.Errorf("got %s", got)
}
}
// TestKeys checks that a key, as lines write it, is a selector that
// names it.
func TestKeys(t *testing.T) {
for _, k := range []string{`"add"`, `"a b"`, `"true"`, `"5"`, `5`, `true`, `"row/1"`, `"null"`, `""`} {
text := keyText(json.RawMessage(k))
if got := string(keyJSON(text)); got != k {
t.Errorf("key %s writes %s, which selects %s", k, text, got)
}
}
}
func TestSnapshot(t *testing.T) {
sn := &seen{Focus: "4", Refs: map[string]int{"1": 1, "2": 2, "3": 3, "4": 4, "5": 5}, Nodes: []node{
{ID: "1", Role: "dialog", Label: "Settings"},
{ID: "2", Parent: "1", Role: "text", Label: "Theme"},
{ID: "3", Parent: "1", Role: "group"},
{ID: "4", Parent: "3", Role: "checkBox", Label: "Dark", States: []string{"focusable", "checked"}, Actions: []string{"press", "focus"}},
{ID: "5", Role: "button", Label: "Close", Actions: []string{"press"}},
}}
var b strings.Builder
writeSnapshot(&b, sn, []string{"Saved"}, false, false)
want := `@e1 [dialog] "Settings"
@e2 [text] "Theme"
@e3 [group]
@e4 [checkBox] "Dark" checked focused
@e5 [button] "Close"
announced "Saved"
`
if b.String() != want {
t.Errorf("snapshot:\n%s\nwant:\n%s", b.String(), want)
}
b.Reset()
writeSnapshot(&b, sn, nil, true, false)
want = `@e4 [checkBox] "Dark" checked focused
@e5 [button] "Close"
`
if b.String() != want {
t.Errorf("snapshot -i:\n%s\nwant:\n%s", b.String(), want)
}
b.Reset()
writeSnapshot(&b, &seen{Nodes: sn.Nodes[:3], Refs: sn.Refs}, nil, true, false)
if !strings.HasPrefix(b.String(), "(no interactive elements") {
t.Errorf("snapshot -i of no controls: %s", b.String())
}
}
func TestWindowLine(t *testing.T) {
if got := windowLine(windowInfo{ID: 2, Title: "Docs", Kind: "page", URL: "http://localhost:5173/", Visible: false}, true); got != `w2 [page] "Docs" url=http://localhost:5173/ hidden selected` {
t.Errorf("got %s", got)
}
if got := windowLine(windowInfo{ID: 1, Title: "Counter", Kind: "content", Focused: true, Visible: true}, false); got != `w1 [content] "Counter" focused` {
t.Errorf("got %s", got)
}
}
+174
View File
@@ -0,0 +1,174 @@
package automationcli
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
)
// session is what a session keeps between commands, in a file of its own:
// the socket, the window commands target, and the elements of each window
// as the last snapshot or diff showed them, with their refs.
type session struct {
Socket string `json:"socket"`
// Window is the window commands target unless they name one, 0 for
// the focused window.
Window int `json:"window,omitempty"`
// Next is the number of the next ref. Numbers are never given twice
// in a session, so that a stale ref can't name another element.
Next int `json:"next"`
// Seen are the windows' elements as last shown, by window ID.
Seen map[string]*seen `json:"seen,omitempty"`
name, path string
}
// seen is a window's elements as a snapshot or a diff last showed them.
type seen struct {
Focus string `json:"focus,omitempty"`
Nodes []node `json:"nodes"`
// Refs are the elements' refs, by element ID.
Refs map[string]int `json:"refs"`
}
var sessionName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
// sessionPath returns the file of the session name in dir.
func sessionPath(dir, name string) (string, error) {
if !sessionName.MatchString(name) {
return "", fmt.Errorf("session name %q: use letters, digits, '.', '_' and '-'", name)
}
return filepath.Join(dir, name+".json"), nil
}
// loadSession reads the session name, which open made.
func loadSession(dir, name string) (*session, error) {
path, err := sessionPath(dir, name)
if err != nil {
return nil, err
}
b, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("no session %q: run mygo-automation open --socket <path> first", name)
}
if err != nil {
return nil, err
}
s := &session{}
if err := json.Unmarshal(b, s); err != nil {
return nil, fmt.Errorf("session %q is damaged (%v): run mygo-automation open again", name, err)
}
s.name, s.path = name, path
return s, nil
}
// save writes the session, replacing its file at once so that a command
// killed halfway leaves the one before.
func (s *session) save() error {
if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil {
return err
}
b, err := json.Marshal(s)
if err != nil {
return err
}
f, err := os.CreateTemp(filepath.Dir(s.path), s.name+".*.tmp")
if err != nil {
return err
}
_, err = f.Write(b)
if cerr := f.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.Rename(f.Name(), s.path)
}
if err != nil {
os.Remove(f.Name())
}
return err
}
// ref is how outputs name an element: @e and its number.
func ref(n int) string { return "@e" + strconv.Itoa(n) }
// parseRef returns the number of a ref, written @e7 or e7.
func parseRef(s string) (int, bool) {
s = strings.TrimPrefix(s, "@")
if !strings.HasPrefix(s, "e") {
return 0, false
}
n, err := strconv.Atoi(s[1:])
if err != nil || n <= 0 || strconv.Itoa(n) != s[1:] {
return 0, false
}
return n, true
}
// lookup returns the window and the element ID of ref number n. A ref
// lasts while its element is in what the last snapshot or diff of its
// window saw; it is stale once that showed the element gone.
func (s *session) lookup(n int) (window int, id string, err error) {
for w, sn := range s.Seen {
for id, r := range sn.Refs {
if r == n {
window, _ := strconv.Atoi(w)
return window, id, nil
}
}
}
if n < s.Next {
return 0, "", &staleError{ref(n), "its element is gone"}
}
return 0, "", &staleError{ref(n), "no snapshot or diff of this session gave it"}
}
// staleError rejects a ref that names no element now. The CLI never
// takes it for another element.
type staleError struct{ ref, why string }
func (e *staleError) Error() string {
return fmt.Sprintf("stale ref %s: %s; use a ref from the latest snapshot or diff (run snapshot)", e.ref, e.why)
}
// observe takes the elements of a window as they are now: elements seen
// before keep their refs, new ones get new refs and the refs of elements
// gone become stale. It returns what the window showed before, nil if
// nothing.
func (s *session) observe(t *tree) *seen {
if s.Seen == nil {
s.Seen = map[string]*seen{}
}
key := strconv.Itoa(t.Window)
old := s.Seen[key]
if s.Next < 1 {
s.Next = 1
}
now := &seen{Focus: t.Focus, Nodes: t.Nodes, Refs: make(map[string]int, len(t.Nodes))}
for _, n := range t.Nodes {
if _, ok := now.Refs[n.ID]; ok {
continue
}
if old != nil {
if r, ok := old.Refs[n.ID]; ok {
now.Refs[n.ID] = r
continue
}
}
now.Refs[n.ID] = s.Next
s.Next++
}
s.Seen[key] = now
return old
}
// forget drops what a window showed, as when it closed.
func (s *session) forget(window int) {
delete(s.Seen, strconv.Itoa(window))
}
+165
View File
@@ -0,0 +1,165 @@
package automationcli
import (
"errors"
"slices"
"strings"
"testing"
)
func nodes(spec ...string) []node {
var out []node
for _, s := range spec {
id, label, _ := strings.Cut(s, ":")
out = append(out, node{ID: id, Role: "text", Label: label})
}
return out
}
func diffText(lines []diffLine) []string {
var out []string
for _, l := range lines {
out = append(out, l.String())
}
return out
}
// TestRefs checks the life of refs: elements keep theirs while windows
// show them, new ones get new numbers, and the refs of elements gone are
// rejected, never given to another element.
func TestRefs(t *testing.T) {
s := &session{}
s.observe(&tree{Window: 1, Nodes: nodes("10:a", "11:b", "12:c")})
s.observe(&tree{Window: 2, Nodes: nodes("10:other window")})
want := func(n, window int, id string) {
t.Helper()
w, got, err := s.lookup(n)
if err != nil || w != window || got != id {
t.Errorf("%s: window %d, element %s, %v; want %d, %s", ref(n), w, got, err, window, id)
}
}
stale := func(n int, why string) {
t.Helper()
_, _, err := s.lookup(n)
var se *staleError
if !errors.As(err, &se) || !strings.Contains(err.Error(), why) {
t.Errorf("%s: %v, want stale: %s", ref(n), err, why)
}
}
want(1, 1, "10")
want(2, 1, "11")
want(3, 1, "12")
want(4, 2, "10")
stale(5, "no snapshot or diff")
// 11 goes, 13 comes; 12 moves before 10.
before := s.observe(&tree{Window: 1, Nodes: nodes("12:c", "10:a", "13:d")})
if before == nil || len(before.Nodes) != 3 {
t.Fatalf("observe returned %+v", before)
}
want(1, 1, "10")
want(3, 1, "12")
want(5, 1, "13")
stale(2, "gone")
want(4, 2, "10")
// 11 coming back is a new element to the session: the old ref stays
// stale, so that a ref read before never acts on what is there now.
s.observe(&tree{Window: 1, Nodes: nodes("11:b")})
want(6, 1, "11")
stale(2, "gone")
stale(1, "gone")
s.forget(2)
stale(4, "gone")
if s.Next != 7 {
t.Errorf("next ref %d", s.Next)
}
}
func TestParseRef(t *testing.T) {
for s, want := range map[string]int{"@e1": 1, "e12": 12, "@e0": 0, "@e": 0, "@x1": 0, "@e01": 0, "@e-1": 0, "e1a": 0, "key=a": 0} {
if n, ok := parseRef(s); n != want || ok != (want > 0) {
t.Errorf("parseRef(%q) = %d, %v", s, n, ok)
}
}
}
func TestSessionFile(t *testing.T) {
dir := t.TempDir()
if _, err := sessionPath(dir, "../x"); err == nil {
t.Error("a session name with a path")
}
if _, err := loadSession(dir, "a"); err == nil || !strings.Contains(err.Error(), "open") {
t.Errorf("loading no session: %v", err)
}
path, _ := sessionPath(dir, "a")
s := &session{Socket: "/tmp/app.sock", Window: 2, Next: 1, name: "a", path: path}
s.observe(&tree{Window: 2, Focus: "10", Nodes: nodes("10:a")})
if err := s.save(); err != nil {
t.Fatal(err)
}
// Another session keeps refs of its own.
other := &session{Socket: "/tmp/app.sock", Next: 1, name: "b"}
other.path, _ = sessionPath(dir, "b")
other.observe(&tree{Window: 2, Nodes: nodes("20:x", "10:a")})
if err := other.save(); err != nil {
t.Fatal(err)
}
got, err := loadSession(dir, "a")
if err != nil {
t.Fatal(err)
}
if got.Socket != s.Socket || got.Window != 2 || got.Next != 2 || got.Seen["2"].Focus != "10" {
t.Errorf("loaded %+v", got)
}
if w, id, err := got.lookup(1); w != 2 || id != "10" || err != nil {
t.Errorf("@e1 after loading: %d %s %v", w, id, err)
}
}
func TestDiff(t *testing.T) {
s := &session{}
s.observe(&tree{Window: 1, Nodes: nodes("1:title", "2:a", "3:b", "4:c", "5:d", "6:e", "7:f", "8:g")})
// b changes, e goes, x comes after f; focus moves to g.
before := s.observe(&tree{Window: 1, Focus: "8", Nodes: nodes("1:title", "2:a", "3:B", "4:c", "5:d", "7:f", "9:x", "8:g")})
got := diffText(diff(before, s.Seen["1"], 1))
want := []string{
`= @e2 [text] "a"`,
`- @e3 [text] "b"`,
`+ @e3 [text] "B"`,
`= @e4 [text] "c"`,
`= @e5 [text] "d"`,
`- @e6 [text] "e"`,
`= @e7 [text] "f"`,
`+ @e9 [text] "x"`,
`- @e8 [text] "g"`,
`+ @e8 [text] "g" focused`,
}
if !slices.Equal(got, want) {
t.Errorf("diff:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
}
// Nothing changed.
before = s.observe(&tree{Window: 1, Focus: "8", Nodes: nodes("1:title", "2:a", "3:B", "4:c", "5:d", "7:f", "9:x", "8:g")})
if got := diff(before, s.Seen["1"], 1); len(got) != 0 {
t.Errorf("diff of the same: %v", diffText(got))
}
// Moves alone change nothing; a window seen for the first time is all
// new.
before = s.observe(&tree{Window: 1, Focus: "8", Nodes: nodes("8:g", "1:title", "2:a", "3:B", "4:c", "5:d", "7:f", "9:x")})
if got := diff(before, s.Seen["1"], 1); len(got) != 0 {
t.Errorf("diff of a move: %v", diffText(got))
}
before = s.observe(&tree{Window: 3, Nodes: nodes("1:new")})
if got := diffText(diff(before, s.Seen["3"], 1)); !slices.Equal(got, []string{`+ @e10 [text] "new"`}) {
t.Errorf("diff of a new window: %v", got)
}
// Everything gone.
before = s.observe(&tree{Window: 3})
if got := diffText(diff(before, s.Seen["3"], 1)); !slices.Equal(got, []string{`- @e10 [text] "new"`}) {
t.Errorf("diff of an emptied window: %v", got)
}
}
+130
View File
@@ -0,0 +1,130 @@
// Package bridge embeds the renderer runtime that MyGo injects into pages.
//
// bridge.js is built from ../../packages/bridge by `bun run build` and
// committed, so building a MyGo application never requires Bun.
package bridge
import (
_ "embed"
"encoding/json"
"github.com/egoist/mygo/internal/platform"
)
//go:embed bridge.js
var source string
// Config is passed to the bridge as __MYGO_CONFIG__.
type Config struct {
Platform string `json:"platform"`
WindowID int `json:"windowId"`
Version string `json:"version"`
// Secret prefixes every message the bridge posts.
Secret string `json:"secret"`
// Locale is the language the app shows, e.g. "zh-Hans", and Dir the
// direction it is written in, "ltr" or "rtl", which pages read as
// mygo.locale and mygo.dir from document start.
Locale string `json:"locale"`
Dir string `json:"dir"`
// Fit is the limits of a window that takes the size of its page's
// content (FitContent), nil for other windows.
Fit *FitContent `json:"fit,omitempty"`
}
// Script returns the bridge source configured for one window.
func Script(cfg Config) string {
b, _ := json.Marshal(cfg)
return "(function(__MYGO_CONFIG__){\n" + source + "})(" + string(b) + ");"
}
// TitleBarEvent tells a page of a window with a hidden title bar the room
// the window controls take. The bridge keeps it in the --mygo-titlebar-*
// CSS variables.
const TitleBarEvent = "mygo:title-bar"
// LocaleEvent tells the pages of a window that the language the app shows
// changed, with a Locale. The bridge configuration tells pages the
// language at document start; the event is sent as a page loads too, for
// one that started loading as the language changed, and the bridge tells
// its listeners only of a language the page did not have.
const LocaleEvent = "mygo:locale"
// Locale is the payload of LocaleEvent.
type Locale struct {
Locale string `json:"locale"`
Dir string `json:"dir"`
}
// TitleBar is the payload of TitleBarEvent, in CSS pixels.
type TitleBar struct {
Height float64 `json:"height"`
Left float64 `json:"left"`
Right float64 `json:"right"`
Bottom float64 `json:"bottom"`
}
// NewTitleBar converts the room of the window controls to the CSS pixels
// of a page shown at zoom.
func NewTitleBar(tb platform.TitleBar, zoom float64) TitleBar {
if zoom <= 0 {
zoom = 1
}
return TitleBar{Height: float64(tb.Height) / zoom, Left: float64(tb.Left) / zoom, Right: float64(tb.Right) / zoom, Bottom: float64(tb.Bottom) / zoom}
}
// FitContentEvent tells the page of a window that takes the size of its
// content (FitContent) the limits of that size, with a FitContent, when
// the page's zoom changed them. The bridge configuration tells them at
// document start.
const FitContentEvent = "mygo:fit-content"
// FitContent is the limits of the size of a window that takes its
// content's, in CSS pixels; 0 is none. The bridge lays the page's root
// element out within them.
type FitContent struct {
MinWidth float64 `json:"minWidth"`
MinHeight float64 `json:"minHeight"`
MaxWidth float64 `json:"maxWidth"`
MaxHeight float64 `json:"maxHeight"`
}
// NewFitContent converts the limits of a window's size, in DIPs, to the CSS
// pixels of a page shown at zoom.
func NewFitContent(minSize, maxSize platform.Size, zoom float64) FitContent {
if zoom <= 0 {
zoom = 1
}
return FitContent{
MinWidth: float64(minSize.Width) / zoom,
MinHeight: float64(minSize.Height) / zoom,
MaxWidth: float64(maxSize.Width) / zoom,
MaxHeight: float64(maxSize.Height) / zoom,
}
}
// TitleBarScript delivers TitleBarEvent at document start, after the
// bridge, so that a page lays out around the window controls before it
// first paints.
func TitleBarScript(tb platform.TitleBar, zoom float64) string {
p, _ := json.Marshal(NewTitleBar(tb, zoom))
return `window.__mygo&&window.__mygo.receive({"t":"event","n":"` + TitleBarEvent + `","p":` + string(p) + `});`
}
// WindowActiveEvent tells a page whether its window is drawn as active,
// true or false: the bridge keeps it for mygo-runtime's windowActive(),
// and sets the attribute data-mygo-window-inactive of <html> while it is
// not. Pages start active; a page that loads in an inactive window hears
// it as its DOM is ready.
const WindowActiveEvent = "mygo:window-active"
// PreferencesEvent tells a page the accent color and the accessibility
// settings of the desktop, as mygo.ThemePreferences encodes them. The
// bridge keeps the latest for mygo-runtime's preferences(), the accent in
// the --mygo-accent CSS variable and the text scale in --mygo-text-scale.
const PreferencesEvent = "mygo:preferences"
// PreferencesScript delivers PreferencesEvent with the JSON prefs at
// document start, after the bridge has registered its handler.
func PreferencesScript(prefs []byte) string {
return `window.__mygo&&window.__mygo.receive({"t":"event","n":"` + PreferencesEvent + `","p":` + string(prefs) + `});`
}
+2
View File
@@ -0,0 +1,2 @@
// Code generated by `bun run build` from packages/bridge. DO NOT EDIT.
(()=>{var ae=new Set(["button","checkbox","color","file","hidden","image","radio","range","reset","submit"]);function V(e,t){let n={},o=e?.closest("input,textarea")??null,s=o&&!(o.type&&ae.has(o.type.toLowerCase()));if(s&&!o.readOnly&&!o.disabled)n.e=!0;else if(e?.isContentEditable)n.e=!0;if(s&&o.type?.toLowerCase()!=="password"){let c=o.selectionStart??0,b=o.selectionEnd??0;if(b>c)t=(o.value??"").slice(c,b)}else if(s)t="";if(t)n.s=t;if(!e)return n;let a=e.closest("a[href],area[href]");if(a){let c=typeof a.href==="string"?a.href:a.href?.baseVal??"";if(c)n.l=c;let b=(a.innerText??a.textContent??"").trim();if(b)n.lt=b}let u=e.closest("img");if(u){let c=u.currentSrc||u.src;if(c)n.i=c}let m=e.closest("video,audio");if(m){let c=m.currentSrc||m.src;if(c)n.m=c}return n}var C=null,N=null,W=()=>typeof CSS<"u"&&("highlights"in CSS)&&typeof Highlight<"u";function ce(e,t){let n=[];if(!e||!document.body)return n;let o=t?e:e.toLowerCase(),s=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,{acceptNode(a){let u=a.parentElement;if(!u||/^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE|TEXTAREA)$/.test(u.tagName))return NodeFilter.FILTER_REJECT;return u.getClientRects().length?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(let a=s.nextNode();a;a=s.nextNode()){let u=t?a.nodeValue:a.nodeValue.toLowerCase();for(let m=u.indexOf(o);m>=0;m=u.indexOf(o,m+o.length)){let c=document.createRange();c.setStart(a,m),c.setEnd(a,m+o.length),n.push(c)}}return n}function de(){if(N||!("adoptedStyleSheets"in document))return;N=new CSSStyleSheet,N.replaceSync("::highlight(mygo-find){background-color:#fdeb62;color:#000}::highlight(mygo-find-active){background-color:#ff9632;color:#000}"),document.adoptedStyleSheets=[...document.adoptedStyleSheets,N]}function q(e,t={}){let n=!!t.matchCase;if(!t.next||!C||C.text!==e||C.matchCase!==n)C={text:e,matchCase:n,ranges:ce(e,n),active:-1};let o=C.ranges.length;if(o===0)return H(),{matches:0,active:0};C.active=C.active<0?t.backward?o-1:0:(C.active+(t.backward?o-1:1))%o;let s=C.ranges[C.active];if(W())de(),CSS.highlights.set("mygo-find",new Highlight(...C.ranges)),CSS.highlights.set("mygo-find-active",new Highlight(s));else{let a=getSelection();a?.removeAllRanges(),a?.addRange(s)}return s.startContainer.parentElement?.scrollIntoView({block:"center",inline:"nearest"}),{matches:o,active:C.active+1}}function H(){if(C&&!W())getSelection()?.removeAllRanges();if(C=null,W())CSS.highlights.delete("mygo-find"),CSS.highlights.delete("mygo-find-active")}function ue(e,t){let n=["width:max-content"];if(e.minWidth>0)n.push(`min-width:${Math.max(e.minWidth-t,0)}px`);if(e.maxWidth>0)n.push(`max-width:${Math.max(e.maxWidth-t,0)}px`);if(e.minHeight>0)n.push(`min-height:${e.minHeight}px`);return`:where(:root){${n.join(";")}}`}function B(e){let t=null;return(n)=>{if(t&&t.w===n.w&&t.h===n.h&&t.sw===n.sw&&t.sh===n.sh)return;t=n,e(n)}}function J(e,t,n){let o=B(n),s=0,a=!1,u=!1,m=()=>t(ue(e,s)),c=(b)=>{let p=document.documentElement;if(!p)return;let h=document.scrollingElement??p,y=Math.max(innerWidth-h.clientWidth,0),O=Math.max(innerHeight-h.clientHeight,0),x=p.getBoundingClientRect(),r=e.maxHeight>0&&x.height>e.maxHeight?y:0;if(r!==s){if(s=r,!b)m(),x=p.getBoundingClientRect();else if(!u)u=!0,requestAnimationFrame(()=>{u=!1,m()})}let S=document.body,E=!!S&&S.scrollWidth>S.clientWidth;o({w:x.width,h:x.height,sw:y,sh:E?O:0})};return m(),{start(){if(a)return;if(a=!0,c(!1),typeof ResizeObserver<"u"&&document.documentElement)new ResizeObserver(()=>c(!0)).observe(document.documentElement);addEventListener("resize",()=>c(!1))},setLimits(b){if(e=b,m(),a)c(!1)},again(){if(o=B(n),a)c(!1)}}}var j=(e)=>setTimeout(()=>{throw e});function Y(e){if(e.reason!==void 0)return e.reason;return Error("mygo: the call was aborted")}class D extends Error{method;constructor(e,t){super(t);this.method=e;this.name="CallError"}}function X(e,t){let n=Math.random().toString(36).slice(2)+Date.now().toString(36),o=new Map,s=new Map,a={accent:null,reduceMotion:!1,reduceTransparency:!1,highContrast:!1,textScale:1},u=0,m=new Map,c=new WeakMap,b=0,p=e.locale||"en",h=e.dir==="rtl"?"rtl":"ltr",y=!0,O=(f)=>t(JSON.stringify(f)),x=(f,...i)=>S(f,i),r=(f,i,l)=>{let d=l?.signal;if(!d)return S(f,i);if(d.aborted)return Promise.reject(Y(d));return S(f,i,d)},S=(f,i,l)=>{let d=++u;return new Promise((L,A)=>{let M;for(let w of i){let v=typeof w==="object"&&w!==null?c.get(w):void 0;if(!v)continue;if(v.id||v.closed){M?.forEach((g)=>{m.delete(g.id),g.id=0}),A(Error("mygo: a channel can be passed to one call, before it is closed"));return}v.id=++b,m.set(v.id,v),(M??=[]).push(v)}let k,P;if(l)k=()=>{o.delete(d),M?.forEach((w)=>{m.delete(w.id),w.id=0});try{O({t:"cancel",id:d,k:n})}catch{}A(Y(l))},l.addEventListener("abort",k,{once:!0}),P=()=>l.removeEventListener("abort",k);o.set(d,{method:f,resolve:L,reject:A,channels:M,done:P});try{O({t:"call",id:d,k:n,m:f,a:i,cancel:l?!0:void 0})}catch(w){if(o.delete(d),k)l?.removeEventListener("abort",k);M?.forEach((v)=>{m.delete(v.id),v.id=0}),A(Line truncated
+587
View File
@@ -0,0 +1,587 @@
// Package contentrules matches loads against rules in WebKit's content
// blocker format, for the backends whose engine has no content blockers
// (WebView2). Only the backends' content rules reach it, so that apps
// that never compile rules don't link it.
package contentrules
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"regexp/syntax"
"slices"
"strings"
"golang.org/x/net/publicsuffix"
)
// Type is a set of the kinds of resources of WebKit's resource-type.
type Type uint16
const (
Document Type = 1 << iota
Image
StyleSheet
Script
Font
Raw
SVGDocument
Media
Popup
Ping
Fetch
WebSocket
Other
)
// typeNamed returns the type of a name of resource-type, 0 for none.
// It and actionNamed switch rather than look up a map, which package
// initialization would make in every app of a backend importing this.
func typeNamed(name string) Type {
switch name {
case "document":
return Document
case "image":
return Image
case "style-sheet":
return StyleSheet
case "script":
return Script
case "font":
return Font
case "raw":
return Raw
case "svg-document":
return SVGDocument
case "media":
return Media
case "popup":
return Popup
case "ping":
return Ping
case "fetch":
return Fetch
case "websocket":
return WebSocket
case "other":
return Other
}
return 0
}
type action uint8
const (
invalid action = iota
block
blockCookies
makeHTTPS
hide
ignorePrevious
)
func actionNamed(name string) action {
switch name {
case "block":
return block
case "block-cookies":
return blockCookies
case "make-https":
return makeHTTPS
case "css-display-none":
return hide
case "ignore-previous-rules":
return ignorePrevious
}
return invalid
}
// List is a list of rules, parsed. Match it from one goroutine at a time:
// it compiles the rules' regular expressions as it first needs them.
type List struct {
rules []rule
// byDomain holds the indexes of the rules whose url-filter matches
// only URLs of a domain and its subdomains, by that domain; byGram
// those of the others whose literal has four bytes or more, by four
// of them (gram), which every URL they match has; others the rest,
// which Match tries for every load. css-display-none rules are only
// in cosmetic.
byDomain map[string][]int32
byGram map[uint32][]int32
others []int32
// cosmetic is the css-display-none and ignore-previous-rules rules
// for HidingScript, as JSON.
cosmetic string
}
type rule struct {
filter pattern
types Type // 0 for every type
loadType uint8
ifDomain []string
unless bool // ifDomain lists unless-domain
topURL []pattern
unlessTop bool // topURL lists unless-top-url
action action
hasDomains bool
}
const (
anyParty uint8 = iota
firstParty
thirdParty
)
// pattern is a regular expression of WebKit's, compiled when first
// matched, with a literal every match contains, to skip it cheaply.
type pattern struct {
source string
literal string // lowercase unless sensitive
sensitive bool
re *regexp.Regexp
}
func newPattern(source string, sensitive bool) (pattern, error) {
if err := webKitRegexp(source); err != nil {
return pattern{}, fmt.Errorf("invalid or unsupported regular expression %q: %w", source, err)
}
flags := syntax.Perl
if !sensitive {
flags |= syntax.FoldCase
}
re, err := syntax.Parse(source, flags)
if err != nil {
return pattern{}, fmt.Errorf("invalid regular expression %q: %w", source, err)
}
p := pattern{source: source, sensitive: sensitive, literal: longestLiteral(re.Simplify())}
if !sensitive {
p.literal = strings.ToLower(p.literal)
}
return p, nil
}
// webKitRegexp reports what of source WebKit's content blockers do not
// take: alternatives, counted repetitions, classes as \d, "^" but at the
// start, and other than ASCII.
func webKitRegexp(source string) error {
class := false
for i := 0; i < len(source); i++ {
c := source[i]
switch {
case c >= 0x80:
return errors.New("not ASCII")
case c == '\\':
i++
if i < len(source) && strings.IndexByte("dDwWsSbB", source[i]) >= 0 {
return fmt.Errorf("\\%c", source[i])
}
case class:
class = c != ']'
case c == '[':
class = true
if strings.HasPrefix(source[i+1:], "^") {
i++
}
case c == '|', c == '{':
return fmt.Errorf("%q", c)
case c == '^' && i > 0:
return errors.New(`"^" but at the start`)
}
}
return nil
}
// longestLiteral returns the longest string every match of re contains.
func longestLiteral(re *syntax.Regexp) string {
switch re.Op {
case syntax.OpLiteral:
return string(re.Rune)
case syntax.OpCapture:
return longestLiteral(re.Sub[0])
case syntax.OpPlus:
return longestLiteral(re.Sub[0])
case syntax.OpConcat:
best, run := "", ""
for _, sub := range re.Sub {
if sub.Op == syntax.OpLiteral {
run += string(sub.Rune)
continue
}
best = longer(best, run)
run = ""
best = longer(best, longestLiteral(sub))
}
return longer(best, run)
}
return ""
}
func longer(a, b string) string {
if len(b) > len(a) {
return b
}
return a
}
// match reports whether s, and lower, s in lowercase, match.
func (p *pattern) match(s, lower string) bool {
if p.literal != "" {
in := lower
if p.sensitive {
in = s
}
if !strings.Contains(in, p.literal) {
return false
}
}
if p.re == nil {
src := p.source
if !p.sensitive {
src = "(?i)" + src
}
p.re = regexp.MustCompile(src) // newPattern parsed it
}
return p.re.MatchString(s)
}
// domainPrefix starts the url-filters that match a domain and its
// subdomains, as converters write Adblock Plus's "||".
const domainPrefix = `^[^:]+://+([^:/]+\.)?`
// filterDomain returns the domain a url-filter matches only URLs of,
// with its subdomains, if it is one written as domainPrefix writes them.
func filterDomain(filter string) string {
rest, ok := strings.CutPrefix(filter, domainPrefix)
if !ok {
return ""
}
var domain strings.Builder
for len(rest) > 0 {
c := rest[0]
switch {
case c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_':
domain.WriteByte(c | 0x20*boolByte(c >= 'A' && c <= 'Z'))
rest = rest[1:]
continue
case strings.HasPrefix(rest, `\.`):
domain.WriteByte('.')
rest = rest[2:]
continue
}
break
}
// The domain ends where the host does.
for _, end := range []string{`[:/]`, `[/:]`, `/`, `:`} {
if after, ok := strings.CutPrefix(rest, end); ok && !strings.HasPrefix(after, "*") && !strings.HasPrefix(after, "?") && !strings.HasPrefix(after, "+") {
if d := domain.String(); d != "" && !strings.HasPrefix(d, ".") && !strings.HasSuffix(d, ".") {
return d
}
}
}
return ""
}
func boolByte(b bool) byte {
if b {
return 1
}
return 0
}
// Parse parses rules in WebKit's content blocker format, failing as
// WebKit does on what it would not compile.
func Parse(rules string) (*List, error) {
var raw []struct {
Trigger json.RawMessage `json:"trigger"`
Action struct {
Type string `json:"type"`
Selector string `json:"selector"`
} `json:"action"`
}
if err := json.Unmarshal([]byte(rules), &raw); err != nil {
return nil, fmt.Errorf("rules are not a JSON array of rules: %w", err)
}
l := &List{byDomain: map[string][]int32{}, byGram: map[uint32][]int32{}}
var cosmetic []cosmeticEntry
for i, r := range raw {
var t struct {
URLFilter *string `json:"url-filter"`
CaseSensitive bool `json:"url-filter-is-case-sensitive"`
IfDomain []string `json:"if-domain"`
UnlessDomain []string `json:"unless-domain"`
ResourceType []string `json:"resource-type"`
LoadType []string `json:"load-type"`
IfTopURL []string `json:"if-top-url"`
UnlessTopURL []string `json:"unless-top-url"`
}
if err := json.Unmarshal(r.Trigger, &t); err != nil || t.URLFilter == nil {
return nil, fmt.Errorf("rule %d: a trigger needs a url-filter", i)
}
ru := rule{action: actionNamed(r.Action.Type)}
if ru.action == invalid {
return nil, fmt.Errorf("rule %d: invalid action type %q", i, r.Action.Type)
}
if ru.action == hide && strings.TrimSpace(r.Action.Selector) == "" {
return nil, fmt.Errorf("rule %d: css-display-none needs a selector", i)
}
var err error
if ru.filter, err = newPattern(*t.URLFilter, t.CaseSensitive); err != nil {
return nil, fmt.Errorf("rule %d: %w", i, err)
}
for _, name := range t.ResourceType {
typ := typeNamed(name)
if typ == 0 {
return nil, fmt.Errorf("rule %d: invalid resource-type %q", i, name)
}
ru.types |= typ
}
for _, name := range t.LoadType {
switch name {
case "first-party":
ru.loadType = firstParty
case "third-party":
ru.loadType = thirdParty
default:
return nil, fmt.Errorf("rule %d: invalid load-type %q", i, name)
}
}
if len(t.LoadType) > 1 {
ru.loadType = anyParty
}
if conditions := min(len(t.IfDomain), 1) + min(len(t.UnlessDomain), 1) + min(len(t.IfTopURL), 1) + min(len(t.UnlessTopURL), 1); conditions > 1 {
return nil, fmt.Errorf("rule %d: a trigger takes one of if-domain, unless-domain, if-top-url and unless-top-url", i)
}
ru.ifDomain, ru.unless = t.IfDomain, len(t.UnlessDomain) > 0
if ru.unless {
ru.ifDomain = t.UnlessDomain
}
ru.hasDomains = len(ru.ifDomain) > 0
for _, d := range ru.ifDomain {
for _, c := range []byte(d) {
if c >= 'A' && c <= 'Z' || c >= 0x80 {
return nil, fmt.Errorf("rule %d: domains must be lowercase ASCII (punycode)", i)
}
}
}
ru.unlessTop = len(t.UnlessTopURL) > 0
for _, src := range slices.Concat(t.IfTopURL, t.UnlessTopURL) {
p, err := newPattern(src, t.CaseSensitive)
if err != nil {
return nil, fmt.Errorf("rule %d: %w", i, err)
}
ru.topURL = append(ru.topURL, p)
}
if ru.action == hide || ru.action == ignorePrevious {
cosmetic = appendCosmetic(cosmetic, r.Trigger, cosmeticEntry{
URL: *t.URLFilter, Sensitive: t.CaseSensitive, IfDomain: t.IfDomain, UnlessDomain: t.UnlessDomain,
IfTopURL: t.IfTopURL, UnlessTopURL: t.UnlessTopURL, Ignore: ru.action == ignorePrevious,
}, r.Action.Selector)
if ru.action == hide {
continue
}
}
l.rules = append(l.rules, ru)
index := int32(len(l.rules) - 1)
if d := filterDomain(*t.URLFilter); d != "" {
l.byDomain[d] = append(l.byDomain[d], index)
} else if g, ok := l.rarestGram(strings.ToLower(ru.filter.literal)); ok {
l.byGram[g] = append(l.byGram[g], index)
} else {
l.others = append(l.others, index)
}
}
if len(raw) == 0 {
return nil, errors.New("no rules")
}
if hasHide(cosmetic) {
data, err := json.Marshal(cosmetic)
if err != nil {
return nil, err
}
l.cosmetic = string(data)
}
return l, nil
}
func gram(s string) uint32 {
return uint32(s[0]) | uint32(s[1])<<8 | uint32(s[2])<<16 | uint32(s[3])<<24
}
// rarestGram returns the four bytes of literal fewest rules are indexed
// by, if it has four.
func (l *List) rarestGram(literal string) (uint32, bool) {
best, count := uint32(0), -1
for i := 0; i+4 <= len(literal); i++ {
g := gram(literal[i:])
if n := len(l.byGram[g]); count < 0 || n < count {
best, count = g, n
}
}
return best, count >= 0
}
// Request is a load to match.
type Request struct {
// URL is what loads, TopURL the page it loads for, the URL itself
// for a page.
URL, TopURL string
// Type is what kind of resource it is: a type or several, any of
// which a rule's resource-type may name.
Type Type
}
// Result is what rules do to a load.
type Result struct {
Block, BlockCookies, MakeHTTPS bool
}
// Match returns what the lists do to the load: each list applies its
// rules in order, and a list's ignore-previous-rules undoes only what
// its own rules before it did.
func Match(lists []*List, r Request) Result {
var c matchContext
c.init(r)
var out Result
for _, l := range lists {
res := l.match(&c)
out.Block = out.Block || res.Block
out.BlockCookies = out.BlockCookies || res.BlockCookies
out.MakeHTTPS = out.MakeHTTPS || res.MakeHTTPS
}
return out
}
type matchContext struct {
r Request
url, top string // lowercase
host, topHost string
thirdParty bool
candidates []int32
}
func (c *matchContext) init(r Request) {
c.r = r
if c.r.TopURL == "" {
c.r.TopURL = r.URL
}
c.url, c.top = strings.ToLower(r.URL), strings.ToLower(c.r.TopURL)
c.host, c.topHost = urlHost(c.url), urlHost(c.top)
c.thirdParty = site(c.host) != site(c.topHost)
}
// urlHost returns the host of a lowercase URL, without its port.
func urlHost(u string) string {
_, rest, ok := strings.Cut(u, "://")
if !ok {
return ""
}
if i := strings.IndexAny(rest, "/?#"); i >= 0 {
rest = rest[:i]
}
if i := strings.LastIndexByte(rest, '@'); i >= 0 {
rest = rest[i+1:]
}
if strings.HasPrefix(rest, "[") {
if i := strings.IndexByte(rest, ']'); i >= 0 {
return rest[:i+1]
}
}
if i := strings.IndexByte(rest, ':'); i >= 0 {
rest = rest[:i]
}
return strings.TrimSuffix(rest, ".")
}
// site returns the registrable domain of a host, which tells first-party
// loads from third-party ones.
func site(host string) string {
if d, err := publicsuffix.EffectiveTLDPlusOne(host); err == nil {
return d
}
return host
}
func (l *List) match(c *matchContext) Result {
// The rules of the host's domains, of the URL's grams, and the
// others, in order.
candidates := l.others
c.candidates = c.candidates[:0]
for h := c.host; h != ""; {
c.candidates = append(c.candidates, l.byDomain[h]...)
_, parent, ok := strings.Cut(h, ".")
if !ok {
break
}
h = parent
}
if len(l.byGram) > 0 {
for i := 0; i+4 <= len(c.url); i++ {
c.candidates = append(c.candidates, l.byGram[gram(c.url[i:])]...)
}
}
if len(c.candidates) > 0 {
c.candidates = append(c.candidates, l.others...)
slices.Sort(c.candidates)
c.candidates = slices.Compact(c.candidates)
candidates = c.candidates
}
var out Result
for _, i := range candidates {
ru := &l.rules[i]
if !ru.matches(c) {
continue
}
switch ru.action {
case block:
out.Block = true
case blockCookies:
out.BlockCookies = true
case makeHTTPS:
out.MakeHTTPS = strings.HasPrefix(c.url, "http:") || strings.HasPrefix(c.url, "ws:")
case ignorePrevious:
out = Result{}
}
}
return out
}
func (ru *rule) matches(c *matchContext) bool {
if ru.types != 0 && ru.types&c.r.Type == 0 {
return false
}
if ru.loadType == firstParty && c.thirdParty || ru.loadType == thirdParty && !c.thirdParty {
return false
}
if ru.hasDomains && domainListed(ru.ifDomain, c.topHost) == ru.unless {
return false
}
if len(ru.topURL) > 0 {
matched := false
for i := range ru.topURL {
if ru.topURL[i].match(c.r.TopURL, c.top) {
matched = true
break
}
}
if matched == ru.unlessTop {
return false
}
}
return ru.filter.match(c.r.URL, c.url)
}
// domainListed reports whether host is one of domains, where "*" before
// a domain takes its subdomains too.
func domainListed(domains []string, host string) bool {
for _, d := range domains {
if sub, ok := strings.CutPrefix(d, "*"); ok {
if host == sub || strings.HasSuffix(host, "."+sub) {
return true
}
} else if host == d {
return true
}
}
return false
}
@@ -0,0 +1,203 @@
package contentrules
import (
"encoding/json"
"fmt"
"strings"
"testing"
)
func mustParse(t testing.TB, rules string) *List {
t.Helper()
l, err := Parse(rules)
if err != nil {
t.Fatalf("Parse: %v", err)
}
return l
}
const page = "https://news.example/article"
func TestMatch(t *testing.T) {
tests := []struct {
name string
rules string
req Request
want Result
}{
{"domain blocks", `[{"trigger":{"url-filter":"^[^:]+://+([^:/]+\\.)?ads\\.test[:/]"},"action":{"type":"block"}}]`,
Request{URL: "https://cdn.ads.test/x.js", TopURL: page, Type: Script}, Result{Block: true}},
{"domain spares others", `[{"trigger":{"url-filter":"^[^:]+://+([^:/]+\\.)?ads\\.test[:/]"},"action":{"type":"block"}}]`,
Request{URL: "https://notads.test/x.js", TopURL: page, Type: Script}, Result{}},
{"domain spares a longer host", `[{"trigger":{"url-filter":"^[^:]+://+([^:/]+\\.)?ads\\.test[:/]"},"action":{"type":"block"}}]`,
Request{URL: "https://ads.test.example/x.js", TopURL: page, Type: Script}, Result{}},
{"path", `[{"trigger":{"url-filter":"/banner/.*\\.gif"},"action":{"type":"block"}}]`,
Request{URL: "https://a.example/img/BANNER/top.gif", TopURL: page, Type: Image}, Result{Block: true}},
{"case-sensitive", `[{"trigger":{"url-filter":"/Banner/","url-filter-is-case-sensitive":true},"action":{"type":"block"}}]`,
Request{URL: "https://a.example/banner/top.gif", TopURL: page, Type: Image}, Result{}},
{"resource-type matches", `[{"trigger":{"url-filter":"track","resource-type":["script","raw"]},"action":{"type":"block"}}]`,
Request{URL: "https://a.example/track.js", TopURL: page, Type: Script}, Result{Block: true}},
{"resource-type spares", `[{"trigger":{"url-filter":"track","resource-type":["script"]},"action":{"type":"block"}}]`,
Request{URL: "https://a.example/track.png", TopURL: page, Type: Image}, Result{}},
{"third-party", `[{"trigger":{"url-filter":"pixel","load-type":["third-party"]},"action":{"type":"block"}}]`,
Request{URL: "https://t.other.example/pixel", TopURL: page, Type: Image}, Result{Block: true}},
{"third-party spares the site", `[{"trigger":{"url-filter":"pixel","load-type":["third-party"]},"action":{"type":"block"}}]`,
Request{URL: "https://static.news.example/pixel", TopURL: page, Type: Image}, Result{}},
{"first-party", `[{"trigger":{"url-filter":"pixel","load-type":["first-party"]},"action":{"type":"block"}}]`,
Request{URL: "https://static.news.example/pixel", TopURL: page, Type: Image}, Result{Block: true}},
{"public suffix sites differ", `[{"trigger":{"url-filter":"pixel","load-type":["third-party"]},"action":{"type":"block"}}]`,
Request{URL: "https://b.github.io/pixel", TopURL: "https://a.github.io/", Type: Image}, Result{Block: true}},
{"if-domain", `[{"trigger":{"url-filter":"ad","if-domain":["*news.example"]},"action":{"type":"block"}}]`,
Request{URL: "https://x.example/ad.js", TopURL: "https://www.news.example/", Type: Script}, Result{Block: true}},
{"if-domain exact", `[{"trigger":{"url-filter":"ad","if-domain":["news.example"]},"action":{"type":"block"}}]`,
Request{URL: "https://x.example/ad.js", TopURL: "https://www.news.example/", Type: Script}, Result{}},
{"unless-domain", `[{"trigger":{"url-filter":"ad","unless-domain":["*news.example"]},"action":{"type":"block"}}]`,
Request{URL: "https://x.example/ad.js", TopURL: page, Type: Script}, Result{}},
{"if-top-url", `[{"trigger":{"url-filter":"ad","if-top-url":["^https://news\\.example/art"]},"action":{"type":"block"}}]`,
Request{URL: "https://x.example/ad.js", TopURL: page, Type: Script}, Result{Block: true}},
{"unless-top-url", `[{"trigger":{"url-filter":"ad","unless-top-url":["/article"]},"action":{"type":"block"}}]`,
Request{URL: "https://x.example/ad.js", TopURL: page, Type: Script}, Result{}},
{"ignore-previous-rules", `[
{"trigger":{"url-filter":"^[^:]+://+([^:/]+\\.)?ads\\.test[:/]"},"action":{"type":"block"}},
{"trigger":{"url-filter":".*","if-domain":["*news.example"]},"action":{"type":"ignore-previous-rules"}}]`,
Request{URL: "https://ads.test/x.js", TopURL: page, Type: Script}, Result{}},
{"block after ignore", `[
{"trigger":{"url-filter":".*","if-domain":["*news.example"]},"action":{"type":"ignore-previous-rules"}},
{"trigger":{"url-filter":"^[^:]+://+([^:/]+\\.)?ads\\.test[:/]"},"action":{"type":"block"}}]`,
Request{URL: "https://ads.test/x.js", TopURL: page, Type: Script}, Result{Block: true}},
{"block-cookies", `[{"trigger":{"url-filter":"tracker"},"action":{"type":"block-cookies"}}]`,
Request{URL: "https://tracker.example/", TopURL: page, Type: Raw}, Result{BlockCookies: true}},
{"make-https", `[{"trigger":{"url-filter":"^http://plain\\.example/"},"action":{"type":"make-https"}}]`,
Request{URL: "http://plain.example/a", TopURL: page, Type: Image}, Result{MakeHTTPS: true}},
{"hiding does not block", `[{"trigger":{"url-filter":".*"},"action":{"type":"css-display-none","selector":".ad"}}]`,
Request{URL: "https://x.example/", TopURL: page, Type: Document}, Result{}},
{"page is its own top", `[{"trigger":{"url-filter":"ad","load-type":["first-party"]},"action":{"type":"block"}}]`,
Request{URL: "https://ad.example/", Type: Document}, Result{Block: true}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Match([]*List{mustParse(t, tt.rules)}, tt.req); got != tt.want {
t.Errorf("Match = %+v, want %+v", got, tt.want)
}
})
}
}
// Each list's ignore-previous-rules undoes only its own rules.
func TestMatchLists(t *testing.T) {
blocks := mustParse(t, `[{"trigger":{"url-filter":"ads"},"action":{"type":"block"}}]`)
ignores := mustParse(t, `[{"trigger":{"url-filter":".*"},"action":{"type":"ignore-previous-rules"}}]`)
if got := Match([]*List{blocks, ignores}, Request{URL: "https://ads.example/", TopURL: page}); !got.Block {
t.Errorf("a later list's ignore-previous-rules undid an earlier list's block")
}
}
func TestParseErrors(t *testing.T) {
for _, rules := range []string{
`{}`,
`[{"trigger":{},"action":{"type":"block"}}]`,
`[{"trigger":{"url-filter":"("},"action":{"type":"block"}}]`,
`[{"trigger":{"url-filter":".*"},"action":{"type":"redirect"}}]`,
`[{"trigger":{"url-filter":".*"},"action":{"type":"css-display-none"}}]`,
`[{"trigger":{"url-filter":".*","resource-type":["video"]},"action":{"type":"block"}}]`,
`[{"trigger":{"url-filter":".*","load-type":["second-party"]},"action":{"type":"block"}}]`,
`[{"trigger":{"url-filter":".*","if-domain":["a"],"unless-domain":["b"]},"action":{"type":"block"}}]`,
`[{"trigger":{"url-filter":".*","if-domain":["a"],"if-top-url":["b"]},"action":{"type":"block"}}]`,
`[{"trigger":{"url-filter":".*","if-domain":["Example.com"]},"action":{"type":"block"}}]`,
`[{"trigger":{"url-filter":"a|b"},"action":{"type":"block"}}]`,
`[{"trigger":{"url-filter":"a{2}"},"action":{"type":"block"}}]`,
`[{"trigger":{"url-filter":"a\\d"},"action":{"type":"block"}}]`,
`[{"trigger":{"url-filter":"a^b"},"action":{"type":"block"}}]`,
`[{"trigger":{"url-filter":"é"},"action":{"type":"block"}}]`,
`[]`,
} {
if _, err := Parse(rules); err == nil {
t.Errorf("Parse(%s) took it", rules)
}
}
}
// What WebKit takes, as tried on macOS.
func TestParseTakes(t *testing.T) {
for _, filter := range []string{`[^a-z]x`, `(ab)?c`, `(ab)+c`, `.*?x`, `x$`, `^x`, `\\/x`, `[a\\-z]`, `a\\.b\\?c`,
`[.]x`, `a\\|b`, `[|{^]`, `^[^:]+://+([^:/]+\\.)?ex\\.com[/:]`} {
rules := `[{"trigger":{"url-filter":"` + filter + `","unknown":1},"action":{"type":"block"}}]`
if _, err := Parse(rules); err != nil {
t.Errorf("Parse(%s): %v", rules, err)
}
}
}
func TestFilterDomain(t *testing.T) {
for filter, want := range map[string]string{
`^[^:]+://+([^:/]+\.)?ads\.example\.com[:/]`: "ads.example.com",
`^[^:]+://+([^:/]+\.)?Ads\.Example\.com[/:]`: "ads.example.com",
`^[^:]+://+([^:/]+\.)?ads\.example\.com/banner`: "ads.example.com",
`^[^:]+://+([^:/]+\.)?ads\.example\.com`: "",
`^[^:]+://+([^:/]+\.)?ads\.example\.co.*[:/]`: "",
`^[^:]+://+([^:/]+\.)?ads\.example\.com/*x`: "",
`^https?://ads\.example\.com/`: "",
} {
if got := filterDomain(filter); got != want {
t.Errorf("filterDomain(%s) = %q, want %q", filter, got, want)
}
}
}
func TestLongestLiteral(t *testing.T) {
for source, want := range map[string]string{
`/banner/.*\.gif`: "/banner/",
`^https?://ads\.example\.com/`: "://ads.example.com/",
`.*`: "",
`(foo)+bar`: "foo",
} {
p, err := newPattern(source, true)
if err != nil {
t.Fatal(err)
}
if p.literal != want {
t.Errorf("literal of %s = %q, want %q", source, p.literal, want)
}
}
}
func TestHidingScript(t *testing.T) {
l := mustParse(t, `[
{"trigger":{"url-filter":".*"},"action":{"type":"css-display-none","selector":".ad"}},
{"trigger":{"url-filter":".*"},"action":{"type":"css-display-none","selector":"#banner"}},
{"trigger":{"url-filter":".*","if-domain":["*news.example"]},"action":{"type":"css-display-none","selector":".promo"}},
{"trigger":{"url-filter":".*","if-domain":["*shop.example"]},"action":{"type":"ignore-previous-rules"}},
{"trigger":{"url-filter":"ads"},"action":{"type":"block"}}]`)
var entries []cosmeticEntry
if err := json.Unmarshal([]byte(l.cosmetic), &entries); err != nil {
t.Fatal(err)
}
if len(entries) != 3 || fmt.Sprint(entries[0].Selectors) != "[.ad #banner]" || entries[0].URL != "" ||
fmt.Sprint(entries[1].IfDomain) != "[*news.example]" || !entries[2].Ignore {
t.Errorf("entries = %+v", entries)
}
if s := HidingScript([]*List{l}); !strings.Contains(s, `".promo"`) || !strings.HasPrefix(s, "(()=>{") {
t.Errorf("script = %.200s", s)
}
if s := HidingScript([]*List{mustParse(t, `[{"trigger":{"url-filter":"ads"},"action":{"type":"block"}}]`)}); s != "" {
t.Errorf("a list hiding nothing made a script: %.100s", s)
}
}
// BenchmarkMatch matches a load against a list of the size of EasyList's
// network rules.
func BenchmarkMatch(b *testing.B) {
var rules []string
for i := range 30000 {
rules = append(rules, fmt.Sprintf(`{"trigger":{"url-filter":"^[^:]+://+([^:/]+\\.)?ads%d\\.example[:/]"},"action":{"type":"block"}}`, i))
if i%2 == 0 {
rules = append(rules, fmt.Sprintf(`{"trigger":{"url-filter":"/banner%d/"},"action":{"type":"block"}}`, i))
}
}
l := mustParse(b, "["+strings.Join(rules, ",")+"]")
req := Request{URL: "https://cdn.news.example/assets/app.js?v=3", TopURL: page, Type: Script}
b.ResetTimer()
for b.Loop() {
Match([]*List{l}, req)
}
}
+93
View File
@@ -0,0 +1,93 @@
package contentrules
import (
"bytes"
"encoding/json"
"strings"
)
// cosmeticEntry is a css-display-none rule, or several of the same
// trigger in a row, or an ignore-previous-rules rule, as the script
// matches them against the document's URL.
type cosmeticEntry struct {
Selectors []string `json:"s,omitempty"`
URL string `json:"u,omitempty"`
Sensitive bool `json:"c,omitempty"`
IfDomain []string `json:"d,omitempty"`
UnlessDomain []string `json:"n,omitempty"`
IfTopURL []string `json:"t,omitempty"`
UnlessTopURL []string `json:"nt,omitempty"`
Ignore bool `json:"i,omitempty"`
trigger json.RawMessage
}
// appendCosmetic adds a rule to the entries, to the last one when that
// hides elements for the same trigger.
func appendCosmetic(entries []cosmeticEntry, trigger json.RawMessage, e cosmeticEntry, selector string) []cosmeticEntry {
if e.URL == ".*" {
e.URL = ""
}
if !e.Ignore {
if n := len(entries); n > 0 && !entries[n-1].Ignore && bytes.Equal(entries[n-1].trigger, trigger) {
entries[n-1].Selectors = append(entries[n-1].Selectors, selector)
return entries
}
e.Selectors = []string{selector}
}
e.trigger = trigger
return append(entries, e)
}
func hasHide(entries []cosmeticEntry) bool {
for _, e := range entries {
if !e.Ignore {
return true
}
}
return false
}
// HidingScript returns JavaScript that hides, in a document of a page applying
// the lists, the elements their css-display-none rules select for its
// URL, or "" when the lists hide nothing. Each selector gets a style rule
// of its own, so that one the engine does not take leaves the others be.
func HidingScript(lists []*List) string {
var data []string
for _, l := range lists {
if l.cosmetic != "" {
data = append(data, l.cosmetic)
}
}
if len(data) == 0 {
return ""
}
return "(()=>{const lists=[" + strings.Join(data, ",") + "];" + cosmeticScript + "})();"
}
// cosmeticScript hides what lists select, through a style sheet the
// document adopts, which needs no element to exist yet, and which a page
// setting the document's adoptedStyleSheets keeps. Unlike WebKit's
// user style sheet, it is the page's own: an element's inline style with
// !important wins over it. The domains of
// the rules are the page's, as in WebKit, which a frame of another
// origin knows by its referrer.
const cosmeticScript = `const url=location.href;
let top;try{top=window.top.location.href}catch(e){top=document.referrer||url}
let host;try{host=new URL(top).hostname.toLowerCase().replace(/\.$/,"")}catch(e){host=location.hostname}
const listed=ds=>ds.some(d=>d[0]==="*"?host===d.slice(1)||host.endsWith("."+d.slice(1)):host===d);
const test=(src,s,c)=>new RegExp(src,c?"":"i").test(s);
const css=[];
for(const list of lists){let hidden=[];for(const e of list){
if(e.u&&!test(e.u,url,e.c))continue;
if(e.d&&!listed(e.d)||e.n&&listed(e.n))continue;
if(e.t&&!e.t.some(t=>test(t,top,e.c))||e.nt&&e.nt.some(t=>test(t,top,e.c)))continue;
if(e.i)hidden=[];else hidden.push(...e.s)}
for(const s of hidden)css.push(s+"{display:none!important}")}
if(css.length===0)return;
const sheet=new CSSStyleSheet();sheet.replaceSync(css.join("\n"));
const adopted=Object.getOwnPropertyDescriptor(Document.prototype,"adoptedStyleSheets");
adopted.set.call(document,[...adopted.get.call(document),sheet]);
Object.defineProperty(document,"adoptedStyleSheets",{configurable:true,enumerable:true,
get(){return adopted.get.call(this)},
set(v){adopted.set.call(this,Array.prototype.includes.call(v,sheet)?v:[...v,sheet])}});`
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,132 @@
//go:build darwin && !ios
package darwin
import (
"runtime"
"sync"
"testing"
"github.com/ebitengine/purego"
"github.com/egoist/mygo/internal/platform"
)
var (
accessClassTestOnce sync.Once
accessNoteTestOnce sync.Once
accessNoteTestCall uintptr
accessNoteTestHook func(id)
)
// A native accessibility notification can synchronously call back into MyGo.
// Keep one callback for its ABI, rather than leaking one per test or element.
func observeAccessNotes(t *testing.T, hook func(id)) {
t.Helper()
loadAccess()
accessNoteTestOnce.Do(func() {
accessNoteTestCall = purego.NewCallback(func(obj, _ uintptr) {
if accessNoteTestHook != nil {
accessNoteTestHook(id(obj))
}
})
})
previous := postAccessNote
postAccessNote, accessNoteTestHook = accessNoteTestCall, hook
t.Cleanup(func() { postAccessNote, accessNoteTestHook = previous, nil })
}
func accessFixture(t *testing.T) *surface {
t.Helper()
runtime.LockOSThread()
t.Cleanup(runtime.UnlockOSThread)
load()
accessClassTestOnce.Do(registerAccessClass)
b := &Backend{byAccess: map[id]*accessElement{}}
s := &surface{w: &window{b: b}}
withPool(func() { s.view = send(send(class("NSView"), "alloc"), "init") })
previous := theBackend
theBackend = b
t.Cleanup(func() {
withPool(func() {
s.w.closed = true
s.destroyAccess()
release(s.view)
})
theBackend = previous
})
return s
}
func accessPair(child uint64) *platform.AccessTree {
return &platform.AccessTree{Nodes: []platform.AccessNode{
{ID: 1, Parent: -1, Role: platform.RoleGroup},
{ID: child, Parent: 0, Role: platform.RoleButton, Label: "Button"},
}}
}
func TestAccessibilityNotificationQueuesLatestTree(t *testing.T) {
s := accessFixture(t)
s.UpdateAccessibility(accessPair(2))
removed, root := s.elements[2].obj, s.elements[1].obj
called := false
latest := accessPair(5)
latest.Nodes[0].Controls = []uint64{5}
observeAccessNotes(t, func(obj id) {
if obj == removed && !called {
called = true
s.UpdateAccessibility(accessPair(4))
s.UpdateAccessibility(latest)
}
})
// Removing node 2 posts AXUIElementDestroyed. A nested update used to
// remove node 3 from the outer transaction and panic at el.linked.
s.UpdateAccessibility(accessPair(3))
if !called || len(s.elements) != 2 || s.elements[5] == nil || s.elements[3] != nil || s.elements[4] != nil {
t.Fatal("nested updates did not settle on the latest complete tree")
}
if len(s.access.Nodes) != 2 || s.access.Nodes[1].ID != 5 || s.updating {
t.Fatal("the published accessibility tree does not match its native elements")
}
if links := s.elements[1].linked; s.elements[1].obj != root || len(links) != 1 || links[0] != s.elements[5].obj || len(s.w.b.byAccess) != 2 {
t.Fatal("the latest tree lost its control links or leaked retired native elements")
}
}
func TestAccessibilityNotificationCanDestroySurface(t *testing.T) {
s := accessFixture(t)
s.UpdateAccessibility(accessPair(2))
removed := s.elements[2].obj
called := false
observeAccessNotes(t, func(obj id) {
if obj == removed && !called {
called = true
s.UpdateAccessibility(accessPair(4))
s.w.closed = true
s.destroyAccess()
}
})
s.UpdateAccessibility(accessPair(3))
if !called || len(s.elements) != 0 || len(s.w.b.byAccess) != 0 || s.topLevel != 0 || len(s.access.Nodes) != 0 || s.updating {
t.Fatal("surface destruction left accessibility objects or resumed a stale update")
}
// A late frame cannot resurrect a destroyed surface's native elements.
s.UpdateAccessibility(accessPair(4))
if len(s.elements) != 0 {
t.Fatal("late update resurrected destroyed accessibility elements")
}
}
func TestAccessibilityDestroyNotificationIsReentrant(t *testing.T) {
s := accessFixture(t)
s.UpdateAccessibility(accessPair(2))
calls := 0
observeAccessNotes(t, func(obj id) {
calls++
s.destroyAccess()
s.UpdateAccessibility(accessPair(3))
})
s.destroyAccess()
if calls != 2 || len(s.elements) != 0 || len(s.w.b.byAccess) != 0 || s.topLevel != 0 || len(s.access.Nodes) != 0 {
t.Fatal("recursive destruction released an element twice or allowed it to be recreated")
}
}
@@ -0,0 +1,75 @@
//go:build darwin && !ios
package darwin
import (
"sync"
"testing"
"github.com/ebitengine/purego"
"github.com/egoist/mygo/internal/platform"
)
var (
accessInfoTestOnce sync.Once
accessInfoTestCall uintptr
accessInfoTestHook func(obj id, name string, info id)
)
// observeAccessInfo has hook see the notifications posted with a userInfo
// (NSAccessibilityPostNotificationWithUserInfo) in place of AppKit.
func observeAccessInfo(t *testing.T, hook func(obj id, name string, info id)) {
t.Helper()
loadAccess()
accessInfoTestOnce.Do(func() {
accessInfoTestCall = purego.NewCallback(func(obj, name, info uintptr) {
if accessInfoTestHook != nil {
accessInfoTestHook(id(obj), stringOf(id(name)), id(info))
}
})
})
previous := postAccessInfo
postAccessInfo, accessInfoTestHook = accessInfoTestCall, hook
t.Cleanup(func() { postAccessInfo, accessInfoTestHook = previous, nil })
}
// A caret moving down a text field, its text the same, posts
// AXSelectedTextChanged with how it moved, a line down, which VoiceOver
// reads the new line at; an edit posts none of it.
func TestAccessibilitySelectionMoveNotification(t *testing.T) {
s := accessFixture(t)
field := func(value string, sel int) *platform.AccessTree {
return &platform.AccessTree{Nodes: []platform.AccessNode{
{ID: 1, Parent: -1, Role: platform.RoleTextField, Label: "Code", Value: value, SelStart: sel, SelEnd: sel, States: platform.AccessMultiline},
}}
}
withPool(func() { s.UpdateAccessibility(field("one\ntwo\nthree", 1)) })
type note struct {
obj id
name string
typ, dir, granularity int
element id
}
var notes []note
observeAccessInfo(t, func(obj id, name string, info id) {
value := func(key string) id { return send(info, "objectForKey:", uintptr(nsString(key))) }
notes = append(notes, note{obj, name, sendInt(value("AXTextStateChangeType"), "intValue"),
sendInt(value("AXTextSelectionDirection"), "intValue"), sendInt(value("AXTextSelectionGranularity"), "intValue"),
value("AXTextChangeElement")})
})
withPool(func() { s.UpdateAccessibility(field("one\ntwo\nthree", 5)) })
obj := s.elements[1].obj
want := note{obj, "AXSelectedTextChanged", platform.TextChangeMove, platform.TextDirectionNext, platform.TextGranularityLine, obj}
if len(notes) != 1 || notes[0] != want {
t.Fatalf("moving the caret down posted %+v, want %+v", notes, want)
}
notes = nil
withPool(func() { s.UpdateAccessibility(field("one\ntwo!\nthree", 8)) })
if len(notes) != 0 {
t.Fatalf("an edit posted %+v", notes)
}
withPool(func() { s.UpdateAccessibility(field("one\ntwo!\nthree", 8)) })
if len(notes) != 0 {
t.Fatalf("a frame changing nothing posted %+v", notes)
}
}
+133
View File
@@ -0,0 +1,133 @@
//go:build darwin && !ios
package darwin
import (
"unicode/utf16"
"github.com/egoist/mygo/internal/platform"
)
// attributedAccessString returns the attributed string of the UTF-16
// range r of a text field's value, with the formats of its runs in the
// keys of NSAccessibility (AXFont, AXForegroundColor, AXUnderline, …),
// autoreleased.
func attributedAccessString(n *platform.AccessNode, r nsRange) id {
runes := []rune(n.Value)
u := utf16.Encode(runes)
lo := int(min(r.Location, uint(len(u))))
hi := int(min(uint(lo)+r.Length, uint(len(u))))
str := nsString(string(utf16.Decode(u[lo:hi])))
as := autorelease(send(send(class("NSMutableAttributedString"), "alloc"), "initWithString:", uintptr(str)))
if hi == lo {
return as
}
// The UTF-16 offset of each rune.
units := make([]int, len(runes)+1)
for i, c := range runes {
units[i+1] = units[i] + utf16.RuneLen(c)
}
add := func(key string, value id, a, z int) {
a, z = max(a, lo), min(z, hi)
if value == 0 || a >= z {
return
}
send(as, "addAttribute:value:range:", uintptr(nsString(key)), uintptr(value), uintptr(a-lo), uintptr(z-a))
}
add("AXFont", accessFont(platform.AccessTextRun{}), lo, hi)
for _, run := range n.TextRuns {
a, z := units[max(0, min(run.Start, len(runes)))], units[max(0, min(run.End, len(runes)))]
if z <= lo || a >= hi {
continue
}
add("AXFont", accessFont(run), a, z)
if run.Color[3] > 0 {
add("AXForegroundColor", accessColor(run.Color), a, z)
}
if run.Background[3] > 0 {
add("AXBackgroundColor", accessColor(run.Background), a, z)
}
if run.Underline {
add("AXUnderline", nsNumberInt(1), a, z)
}
if run.Strikethrough {
add("AXStrikethrough", nsBool(true), a, z)
}
if run.Link != "" {
if url := send(class("NSURL"), "URLWithString:", uintptr(nsString(run.Link))); url != 0 {
add("AXLink", url, a, z)
}
}
}
return as
}
// accessFont returns the AXFont of a run: the dictionary of its font's
// name, family and size, the font as AppKit finds it for the run's family,
// weight and italics.
func accessFont(run platform.AccessTextRun) id {
size := float64(run.Size)
if size <= 0 {
size = 14
}
var font id
if run.Family == "monospace" {
font = msgFloat2ID(class("NSFont"), sel("monospacedSystemFontOfSize:weight:"), size, nsFontWeight(run.Weight))
} else if run.Family != "" && run.Family != "system-ui" {
var traits uint
if run.Weight >= 600 {
traits |= 2 // NSBoldFontMask
}
if run.Italic {
traits |= 1 // NSItalicFontMask
}
font = msgFontFamily(send(class("NSFontManager"), "sharedFontManager"), sel("fontWithFamily:traits:weight:size:"),
nsString(run.Family), traits, 5, size)
}
if font == 0 {
font = msgFloat2ID(class("NSFont"), sel("systemFontOfSize:weight:"), size, nsFontWeight(run.Weight))
if run.Italic && font != 0 {
font = send(send(class("NSFontManager"), "sharedFontManager"), "convertFont:toHaveTrait:", uintptr(font), 1)
}
}
d := send(class("NSMutableDictionary"), "dictionary")
if font != 0 {
name := send(font, "fontName")
send(d, "setObject:forKey:", uintptr(name), uintptr(nsString("AXFontName")))
send(d, "setObject:forKey:", uintptr(send(font, "familyName")), uintptr(nsString("AXFontFamily")))
send(d, "setObject:forKey:", uintptr(send(font, "displayName")), uintptr(nsString("AXVisibleName")))
}
send(d, "setObject:forKey:", uintptr(msgFloatID(class("NSNumber"), sel("numberWithDouble:"), size)), uintptr(nsString("AXFontSize")))
return d
}
// nsFontWeight returns the NSFontWeight of a CSS weight.
func nsFontWeight(w int) float64 {
switch {
case w <= 0:
return 0
case w < 200:
return -0.8
case w < 300:
return -0.6
case w < 400:
return -0.4
case w < 500:
return 0
case w < 600:
return 0.23
case w < 700:
return 0.3
case w < 800:
return 0.4
case w < 900:
return 0.56
}
return 0.62
}
// accessColor returns the CGColor of an RGBA color, which the NSColor
// autoreleased with it keeps.
func accessColor(c [4]uint8) id {
return send(nsColor(platform.Color{R: c[0], G: c[1], B: c[2], A: c[3]}), "CGColor")
}
+535
View File
@@ -0,0 +1,535 @@
//go:build darwin && !ios
package darwin
import (
"strings"
"unsafe"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
// Backend is the macOS implementation of platform.Backend.
type Backend struct {
h platform.AppHandler
app id
delegate id
source uintptr
mainLoop uintptr
// background is AppOptions.Background: the app does not come to the
// front as it finishes launching.
background bool
// Lookup tables for Objective-C callbacks. Main thread only.
byDelegate map[id]*window
byWebView map[id]*window
byNSWindow map[id]*window
bySurface map[id]*surface
byAccess map[id]*accessElement
menuTarget id
menuItems map[int][]id
appMenu []int
trays map[id]*tray
hotkeys map[int]uintptr
hkInstalled bool
// sparePopovers are the NSPopovers of closed popover flyouts, which
// the next ones show in (takePopover); closingPopovers those of them
// that have not finished closing yet, whose delegate is spareDelegate
// until they have (givePopover). Main thread only.
sparePopovers []id
closingPopovers map[id]bool
spareDelegate id
notifyDelegate id
// notifyAnswered records that the user has answered whether the app
// may show notifications; notifyWaiting holds those shown meanwhile.
notifyAnswered bool
notifyWaiting []waitingNotification
notifyPreparing map[string]func()
stepping int
quitAfterModal bool
// orderingChildren tells that child windows are being ordered above
// their parent, or out with it (child_window.go): what AppKit tells
// of their ordering then orders nothing more.
orderingChildren bool
dockProgress dockProgress
// openedAtLogin records whether the system started the app as a login
// item (WasOpenedAtLogin).
openedAtLogin bool
// dockMenu is returned by applicationDockMenu: (retained).
dockMenu id
dockMenuOwner int
}
// New creates the macOS backend.
func New() *Backend {
load()
return &Backend{
byDelegate: map[id]*window{},
byWebView: map[id]*window{},
byNSWindow: map[id]*window{},
bySurface: map[id]*surface{},
byAccess: map[id]*accessElement{},
menuItems: map[int][]id{},
trays: map[id]*tray{},
hotkeys: map[int]uintptr{},
}
}
var theBackend *Backend
func (b *Backend) Name() string { return "darwin/wkwebview" }
func (b *Backend) IsMainThread() bool {
r, _, _ := purego.SyscallN(mainNPFn)
return int32(r) != 0
}
const (
nsApplicationActivationPolicyRegular = 0
nsApplicationActivationPolicyAccessory = 1
nsApplicationActivationPolicyProhibited = 2
)
func activationPolicy(p string) uintptr {
switch p {
case "accessory":
return nsApplicationActivationPolicyAccessory
case "prohibited":
return nsApplicationActivationPolicyProhibited
}
return nsApplicationActivationPolicyRegular
}
func (b *Backend) Init(h platform.AppHandler, opts platform.AppOptions) error {
b.h = h
b.background = opts.Background
theBackend = b
registerClasses()
// AppKit's AutoFill heuristics watch every text input client for
// contact and password fields, in a helper process ("AutoFill (App)")
// and with sync calls that cost CPU and stall scrolling on macOS 26.
// MyGo draws its own text fields, which never take those suggestions.
// Ghostty, Zed and Chromium turn it off the same way. macOS 26 reads
// NSAutoFillHeuristicControllerEnabled; macOS 27 reads only
// NSAutoFillHeuristicsEnabled, and without it starts Safari's AutoFill
// helper as soon as a view takes text input.
no := nsBool(false)
send(send(class("NSUserDefaults"), "standardUserDefaults"), "registerDefaults:",
uintptr(send(class("NSDictionary"), "dictionaryWithObjects:forKeys:",
uintptr(nsArray(no, no)),
uintptr(nsArray(nsString("NSAutoFillHeuristicControllerEnabled"), nsString("NSAutoFillHeuristicsEnabled"))))))
b.app = send(class("NSApplication"), "sharedApplication")
send(b.app, "setActivationPolicy:", activationPolicy(opts.ActivationPolicy))
// No automatic "Show Tab Bar" items and window tabbing.
send(class("NSWindow"), "setAllowsAutomaticWindowTabbing:", 0)
b.delegate = alloc("MyGoAppDelegate")
send(b.app, "setDelegate:", uintptr(b.delegate))
b.menuTarget = alloc("MyGoMenuTarget")
b.attachNotificationDelegate()
// A run loop source drives the queue of functions posted from other
// goroutines. It fires in every run loop mode, including while menus
// are tracked, windows are resized and modal dialogs run.
b.mainLoop = cfRunLoopGetMain()
var ctx [10]uintptr // CFRunLoopSourceContext; perform is the last field
ctx[9] = dispatchCallback
b.source = cfRunLoopSourceCreate(0, 0, unsafe.Pointer(&ctx[0]))
cfRunLoopAddSource(b.mainLoop, b.source, kCFRunLoopCommonModes)
// Appearance (dark mode) and display configuration changes.
send(b.app, "addObserver:forKeyPath:options:context:", uintptr(b.delegate), uintptr(nsString("effectiveAppearance")), 1, 0)
center := send(class("NSNotificationCenter"), "defaultCenter")
send(center, "addObserver:selector:name:object:", uintptr(b.delegate), uintptr(sel("screensChanged:")),
uintptr(nsString("NSApplicationDidChangeScreenParametersNotification")), 0)
// The accent color, and the display settings of accessibility.
send(center, "addObserver:selector:name:object:", uintptr(b.delegate), uintptr(sel("preferencesChanged:")),
uintptr(nsString("NSSystemColorsDidChangeNotification")), 0)
send(send(workspace(), "notificationCenter"), "addObserver:selector:name:object:", uintptr(b.delegate), uintptr(sel("preferencesChanged:")),
uintptr(nsString("NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification")), 0)
// The languages and regional formats of the user: Foundation tells of
// a new current locale, and System Settings of new languages, a new
// time and date format, which the current locale may not change. The
// time format's notification comes before the current locale has the
// new format, so the region is read again at the current locale's,
// which Foundation posts under the constant's value, not its name.
send(center, "addObserver:selector:name:object:", uintptr(b.delegate), uintptr(sel("localeChanged:")),
uintptr(currentLocaleDidChange()), 0)
distributed := send(class("NSDistributedNotificationCenter"), "defaultCenter")
for _, name := range []string{"AppleLanguagePreferencesChangedNotification", "AppleTimePreferencesChangedNotification", "AppleDatePreferencesChangedNotification"} {
send(distributed, "addObserver:selector:name:object:", uintptr(b.delegate), uintptr(sel("localeChanged:")), uintptr(nsString(name)), 0)
}
return nil
}
var dispatchCallback = purego.NewCallback(func(info uintptr) {
withPool(func() {
drainMainQueue()
theBackend.h.Dispatch()
})
})
func (b *Backend) Run() error {
send(b.app, "run")
return nil
}
func (b *Backend) Quit() {
if send(b.app, "modalWindow") != 0 {
// stop: would end the modal session (an app-modal dialog) rather
// than the event loop: abort the session, and stop once it has
// unwound (see runPanel).
b.quitAfterModal = true
send(b.app, "abortModal")
return
}
send(b.app, "stop:", 0)
// stop: takes effect after the next event; make sure there is one.
b.postEvent(0)
}
func (b *Backend) Signal() {
if b.source != 0 {
purego.SyscallN(cfRunLoopSourceSignalFn, b.source)
purego.SyscallN(cfRunLoopWakeUpFn, b.mainLoop)
}
}
const (
nsEventTypeApplicationDefined = 15
wakeSubtype = 0x6d67 // 'mg'
)
func (b *Backend) postEvent(subtype int16) {
withPool(func() {
ev := msgOtherEvent(class("NSEvent"), sel("otherEventWithType:location:modifierFlags:timestamp:windowNumber:context:subtype:data1:data2:"),
nsEventTypeApplicationDefined, NSPoint{}, 0, 0, 0, 0, subtype, 0, 0)
send(b.app, "postEvent:atStart:", uintptr(ev), 1)
})
}
func (b *Backend) Step() {
b.stepping++
defer func() { b.stepping-- }()
withPool(func() {
until := msgDateSince(class("NSDate"), sel("dateWithTimeIntervalSinceNow:"), 0.5)
mode := nsString("kCFRunLoopDefaultMode")
ev := msgNextEvent(b.app, sel("nextEventMatchingMask:untilDate:inMode:dequeue:"), ^uint64(0), until, mode, true)
if ev == 0 {
return
}
if sendInt(ev, "type") == nsEventTypeApplicationDefined && int16(sendInt(ev, "subtype")) == wakeSubtype {
return
}
send(b.app, "sendEvent:", uintptr(ev))
})
}
// Wake makes a pending Step return. It is called from any goroutine.
func (b *Backend) Wake() {
if b.app == 0 {
return
}
b.postEvent(wakeSubtype)
}
func (b *Backend) App() platform.AppController { return appController{b} }
func (b *Backend) Dialogs() platform.Dialogs { return dialogs{b} }
func (b *Backend) Clipboard() platform.Clipboard { return clipboard{} }
func (b *Backend) Shell() platform.Shell { return shell{} }
func (b *Backend) Screen() platform.Screen { return screen{} }
func (b *Backend) Theme() platform.Theme { return theme{b} }
func (b *Backend) Power() platform.Power { return power{b} }
func (b *Backend) Secrets() platform.Secrets { return secrets{} }
var classesOnce bool
func registerClasses() {
if classesOnce {
return
}
classesOnce = true
registerAppDelegate()
registerWindowClasses()
registerSurfaceClass()
registerClipboardClass()
registerAccessClass()
registerMenuTarget()
registerSchemeHandler()
registerTrayTarget()
registerNotificationDelegate()
}
const (
nsTerminateCancel = 0
nsTerminateNow = 1
kCoreEventClass = 0x61657674 // 'aevt'
kAEQuitApplication = 0x71756974 // 'quit'
keyErrorNumber = 0x6572726E // 'errn'
userCanceledErr = -128
)
func registerAppDelegate() {
classDef("MyGoAppDelegate", "NSObject", []string{"NSApplicationDelegate"}, []objc.MethodDef{
// The end of a PrintToPDF job (printJobs). WebKit's print operations
// may finish on a background thread.
method("mygoPrintOperationDidRun:success:contextInfo:", func(self id, _ objc.SEL, op id, success bool, job uintptr) {
theBackend.runOnMain(func() {
if j := printJobs[job]; j != nil {
delete(printJobs, job)
j.done(success)
}
})
}),
method("applicationWillFinishLaunching:", func(self id, _ objc.SEL, n id) {
// Handle the quit Apple Event (Dock > Quit, AppleScript, logout)
// ourselves so the sender gets a proper reply while Run still
// returns normally. AppKit installs its default handlers right
// before this notification.
aem := send(class("NSAppleEventManager"), "sharedAppleEventManager")
send(aem, "setEventHandler:andSelector:forEventClass:andEventID:", uintptr(self),
uintptr(sel("mygoHandleQuitEvent:withReplyEvent:")), kCoreEventClass, kAEQuitApplication)
theBackend.openedAtLogin = launchedAsLoginItem()
}),
method("applicationDidFinishLaunching:", func(self id, _ objc.SEL, n id) {
b := theBackend
if send(b.app, "activationPolicy") == nsApplicationActivationPolicyRegular && !b.background {
// Plain executables (go run) do not come to the front on
// their own.
send(b.app, "activateIgnoringOtherApps:", 1)
}
b.h.Ready()
}),
// terminate: (Cmd+Q and the Quit menu item) ends up here. Rather
// than letting AppKit exit the process, stop the run loop so Run
// returns and deferred cleanup in main runs.
method("applicationShouldTerminate:", func(self id, _ objc.SEL, app id) uint {
b := theBackend
if b.h.QuitRequested() {
b.Quit()
}
return nsTerminateCancel
}),
// Power and session notifications (Backend.Power().Watch).
method("mygoPowerNotification:", func(self id, _ objc.SEL, n id) {
if event := powerEvents[goString(send(n, "name"))]; event != "" {
theBackend.h.PowerEvent(event)
}
}),
method("mygoHandleQuitEvent:withReplyEvent:", func(self id, _ objc.SEL, event, reply id) {
b := theBackend
if b.h.QuitRequested() {
b.Quit()
return
}
if reply != 0 {
canceled := int32(userCanceledErr)
code := send(class("NSAppleEventDescriptor"), "descriptorWithInt32:", uintptr(uint32(canceled)))
send(reply, "setParamDescriptor:forKeyword:", uintptr(code), keyErrorNumber)
}
}),
method("applicationWillTerminate:", func(self id, _ objc.SEL, n id) {
theBackend.h.Terminating()
}),
method("applicationDockMenu:", func(self id, _ objc.SEL, app id) id {
return theBackend.dockMenu
}),
method("applicationShouldHandleReopen:hasVisibleWindows:", func(self id, _ objc.SEL, app id, visible bool) bool {
theBackend.h.Activated(visible)
return true
}),
method("applicationDidBecomeActive:", func(self id, _ objc.SEL, n id) {
theBackend.h.DidBecomeActive()
}),
method("applicationDidResignActive:", func(self id, _ objc.SEL, n id) {
theBackend.h.DidResignActive()
}),
method("application:openURLs:", func(self id, _ objc.SEL, app id, urls id) {
var files, links []string
for _, u := range arrayItems(urls) {
if sendBool(u, "isFileURL") {
files = append(files, goString(send(u, "path")))
} else {
links = append(links, goString(send(u, "absoluteString")))
}
}
if len(files) > 0 {
theBackend.h.OpenFiles(files)
}
if len(links) > 0 {
theBackend.h.OpenURLs(links)
}
}),
method("applicationSupportsSecureRestorableState:", func(self id, _ objc.SEL, app id) bool { return true }),
method("applicationShouldTerminateAfterLastWindowClosed:", func(self id, _ objc.SEL, app id) bool { return false }),
method("observeValueForKeyPath:ofObject:change:context:", func(self id, _ objc.SEL, keyPath, object, change id, ctx uintptr) {
if goString(keyPath) == "effectiveAppearance" {
theBackend.refreshSystemBackings()
theBackend.h.ThemeChanged()
}
}),
method("screensChanged:", func(self id, _ objc.SEL, n id) {
theBackend.h.DisplaysChanged()
}),
method("preferencesChanged:", func(self id, _ objc.SEL, n id) {
theBackend.refreshSystemBackings()
theBackend.h.ThemeChanged()
}),
method("localeChanged:", func(self id, _ objc.SEL, n id) {
theBackend.h.LocaleChanged()
}),
})
}
type appController struct{ b *Backend }
func (a appController) SetActivationPolicy(p string) {
send(a.b.app, "setActivationPolicy:", activationPolicy(p))
if p == "regular" {
send(a.b.app, "activateIgnoringOtherApps:", 1)
}
}
func (a appController) Activate() { send(a.b.app, "activateIgnoringOtherApps:", 1) }
func (a appController) AllowForeground() {}
func (a appController) WithActivationToken(_ string, fn func()) { fn() }
func (a appController) Hide() { send(a.b.app, "hide:", 0) }
func (a appController) Unhide() { send(a.b.app, "unhide:", 0) }
func (a appController) IsHidden() bool { return sendBool(a.b.app, "isHidden") }
func (a appController) IsActive() bool { return sendBool(a.b.app, "isActive") }
func (a appController) SetBadge(label string) {
tile := send(a.b.app, "dockTile")
var s id
if label != "" {
s = nsString(label)
}
send(tile, "setBadgeLabel:", uintptr(s))
}
func (a appController) Badge() string {
return goString(send(send(a.b.app, "dockTile"), "badgeLabel"))
}
func (a appController) Bounce(critical bool) int {
kind := 10 // NSInformationalRequest
if critical {
kind = 0 // NSCriticalRequest
}
return sendInt(a.b.app, "requestUserAttention:", uintptr(kind))
}
func (a appController) CancelBounce(requestID int) {
send(a.b.app, "cancelUserAttentionRequest:", uintptr(requestID))
}
func (a appController) SetDockMenu(m *platform.Menu) {
b := a.b
if b.dockMenuOwner == 0 {
b.dockMenuOwner = newOwner()
}
withPool(func() {
dropOwner(b.dockMenuOwner)
release(b.dockMenu)
b.dockMenu = 0
if m != nil {
b.dockMenu = retain(b.buildMenu(m, "", b.dockMenuOwner))
}
})
}
func (a appController) SetDockIcon(png []byte) error {
var img id
if len(png) > 0 {
img = send(send(class("NSImage"), "alloc"), "initWithData:", uintptr(nsData(png)))
if img == 0 {
return errInvalidImage
}
defer release(img)
}
send(a.b.app, "setApplicationIconImage:", uintptr(img))
return nil
}
func (a appController) ShowAboutPanel(o platform.AboutPanelOptions) {
dict := send(class("NSMutableDictionary"), "dictionary")
set := func(key, value string) {
if value != "" {
send(dict, "setObject:forKey:", uintptr(nsString(value)), uintptr(nsString(key)))
}
}
set("ApplicationName", o.ApplicationName)
set("ApplicationVersion", o.ApplicationVersion)
set("Version", o.Version)
set("Copyright", o.Copyright)
if o.Credits != "" {
credits := autorelease(send(send(class("NSAttributedString"), "alloc"), "initWithString:", uintptr(nsString(o.Credits))))
send(dict, "setObject:forKey:", uintptr(credits), uintptr(nsString("Credits")))
}
send(a.b.app, "activateIgnoringOtherApps:", 1)
send(a.b.app, "orderFrontStandardAboutPanelWithOptions:", uintptr(dict))
}
func (a appController) Package() (platform.PackageInfo, bool) {
var info platform.PackageInfo
ok := false
withPool(func() {
bundle := send(class("NSBundle"), "mainBundle")
path := goString(send(bundle, "bundlePath"))
if !strings.HasSuffix(path, ".app") {
return
}
ok = true
get := func(key string) string {
return goString(send(bundle, "objectForInfoDictionaryKey:", uintptr(nsString(key))))
}
info.Name = get("CFBundleDisplayName")
if info.Name == "" {
info.Name = get("CFBundleName")
}
info.Version = get("CFBundleShortVersionString")
info.Identifier = goString(send(bundle, "bundleIdentifier"))
})
return info, ok
}
func (a appController) ClearBrowsingData(store platform.DataStore, types platform.SiteData, done func(error)) {
a.removeData(store, types, done)
}
// AddRecentDocument and ClearRecentDocuments use the shared document
// controller, as Electron does: AppKit lists its recent documents in the
// Dock menu, and in an Open Recent menu.
func (a appController) AddRecentDocument(path string) error {
withPool(func() {
send(send(class("NSDocumentController"), "sharedDocumentController"), "noteNewRecentDocumentURL:", uintptr(fileURL(path)))
})
return nil
}
func (a appController) ClearRecentDocuments() error {
withPool(func() {
send(send(class("NSDocumentController"), "sharedDocumentController"), "clearRecentDocuments:", 0)
})
return nil
}
func (appController) SetJumpList(platform.JumpList) error { return nil }
// WebViewAvailable reports whether a window showing a web page can have
// one. WKWebView is part of macOS, so this holds wherever the app runs.
func (b *Backend) WebViewAvailable() bool { return hasClass("WKWebView") }
+94
View File
@@ -0,0 +1,94 @@
//go:build darwin && !ios
package darwin
import (
"os"
"path/filepath"
"strings"
"github.com/egoist/mygo/internal/platform"
)
// appDirs are the folders apps are installed in, as Spotlight and Launchpad
// find them: apps in a folder of their own one level down too.
func appDirs() []string {
dirs := []string{
"/Applications",
"/System/Applications",
"/System/Library/CoreServices/Applications",
}
if home, err := os.UserHomeDir(); err == nil {
dirs = append(dirs, filepath.Join(home, "Applications"))
}
return dirs
}
// Applications finds the .app bundles in the folders apps are installed in
// and those one level down (Utilities, an app's folder), without looking
// inside bundles, and Finder (which is in CoreServices), each once: an app
// a symbolic link points to, as /Applications/Safari.app does, is listed
// at the link, which FileIcon draws without the badge of links. Each has the
// name Finder shows (localized, without .app) and its bundle identifier,
// or its path without one.
func (b *Backend) Applications() ([]platform.Application, error) {
var paths []string
seen := map[string]bool{}
add := func(p string) {
real := p
if r, err := filepath.EvalSymlinks(p); err == nil {
real = r
}
if !seen[real] {
seen[real] = true
paths = append(paths, p)
}
}
for _, dir := range appDirs() {
entries, _ := os.ReadDir(dir)
for _, e := range entries {
p := filepath.Join(dir, e.Name())
if strings.HasSuffix(e.Name(), ".app") {
add(p)
continue
}
if info, err := os.Stat(p); err != nil || !info.IsDir() {
continue
}
sub, _ := os.ReadDir(p)
for _, s := range sub {
if strings.HasSuffix(s.Name(), ".app") {
add(filepath.Join(p, s.Name()))
}
}
}
}
add("/System/Library/CoreServices/Finder.app")
apps := make([]platform.Application, 0, len(paths))
withPool(func() {
fm := send(class("NSFileManager"), "defaultManager")
for _, p := range paths {
ns := nsString(p)
bundle := send(class("NSBundle"), "bundleWithPath:", uintptr(ns))
if bundle == 0 {
continue
}
a := platform.Application{
// Finder shows .app where the user has it show all
// extensions; Launchpad and Spotlight never do.
Name: strings.TrimSuffix(goString(send(fm, "displayNameAtPath:", uintptr(ns))), ".app"),
ID: goString(send(bundle, "bundleIdentifier")),
Path: p,
}
if a.ID == "" {
a.ID = p // as Steam's shortcuts to games, which have none
}
apps = append(apps, a)
}
})
return apps, nil
}
// OpenApplication starts an app, or brings it to the front.
func (s shell) OpenApplication(path string) error { return s.OpenPath(path) }
+311
View File
@@ -0,0 +1,311 @@
//go:build darwin && !ios
package darwin
import (
"strconv"
"strings"
"sync"
"unsafe"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
// HTTP authentication and server certificates of pages: the navigation
// delegate's webView:didReceiveAuthenticationChallenge:completionHandler:,
// whose completion handler takes an NSURLSessionAuthChallengeDisposition
// and a credential.
const (
authUseCredential = 0
authDefault = 1
authReject = 3 // NSURLSessionAuthChallengeRejectProtectionSpace
)
// authScheme names the NSURLAuthenticationMethods of HTTP, "" the
// others, which get WebKit's default handling. Client certificates are
// asked about apart, in clientCertificate.
func authScheme(method string) string {
switch method {
case "NSURLAuthenticationMethodDefault", "NSURLAuthenticationMethodHTTPBasic":
return "basic"
case "NSURLAuthenticationMethodHTTPDigest":
return "digest"
case "NSURLAuthenticationMethodNTLM":
return "ntlm"
case "NSURLAuthenticationMethodNegotiate":
return "negotiate"
}
return ""
}
// trustAPI is what checking server certificates and listing client
// certificate identities takes of the Security framework, loaded with
// the first use.
var trustAPI = sync.OnceValue(func() *trustFuncs {
lib, err := purego.Dlopen("/System/Library/Frameworks/Security.framework/Security", purego.RTLD_GLOBAL|purego.RTLD_NOW)
if err != nil {
return nil
}
main, err := purego.Dlsym(purego.RTLD_DEFAULT, "_dispatch_main_q")
if err != nil {
return nil
}
return &trustFuncs{
evaluate: mustDlsym(lib, "SecTrustEvaluateAsyncWithError"),
chain: mustDlsym(lib, "SecTrustCopyCertificateChain"),
data: mustDlsym(lib, "SecCertificateCopyData"),
mainQueue: main, // dispatch_get_main_queue()
item: mustDlsym(lib, "SecItemCopyMatching"),
identityCert: mustDlsym(lib, "SecIdentityCopyCertificate"),
commonName: mustDlsym(lib, "SecCertificateCopyCommonName"),
secClass: cfConstant(lib, "kSecClass"),
secClassIdent: cfConstant(lib, "kSecClassIdentity"),
secReturnRef: cfConstant(lib, "kSecReturnRef"),
secMatchLimit: cfConstant(lib, "kSecMatchLimit"),
secMatchLimitAll: cfConstant(lib, "kSecMatchLimitAll"),
boolTrue: cfConstant(libCF, "kCFBooleanTrue"),
}
})
type trustFuncs struct {
evaluate, chain, data, mainQueue uintptr
item, identityCert, commonName uintptr
// The query constants, their values read from the Security framework,
// and kCFBooleanTrue. CFStringRef and CFBooleanRef are toll-free
// bridged to NSString and NSNumber, so an NSDictionary takes them.
secClass, secClassIdent, secReturnRef, secMatchLimit, secMatchLimitAll, boolTrue uintptr
}
// cfConstant reads a constant a framework exports, kSecClass say: its
// symbol is a CFStringRef, and the constant is that string.
func cfConstant(lib uintptr, name string) uintptr {
addr := mustDlsym(lib, name)
return *(*uintptr)(*(*unsafe.Pointer)(unsafe.Pointer(&addr)))
}
// authChallenge answers a challenge of the page or of what it loads.
func (w *window) authChallenge(challenge id, handler uintptr) {
space := send(challenge, "protectionSpace")
method := goString(send(space, "authenticationMethod"))
switch method {
case "NSURLAuthenticationMethodServerTrust":
w.serverTrust(challenge, space, handler)
return
case "NSURLAuthenticationMethodClientCertificate":
w.clientCertificate(space, handler)
return
}
scheme := authScheme(method)
if scheme == "" {
callBlock(handler, authDefault, 0)
return
}
resp := w.h.AuthRequested(platform.AuthRequest{
Host: goString(send(space, "host")),
Port: sendInt(space, "port"),
Realm: goString(send(space, "realm")),
Scheme: scheme,
IsProxy: sendBool(space, "isProxy"),
})
switch {
case resp.Default:
callBlock(handler, authDefault, 0)
case resp.Username == "" && resp.Password == "":
// Without credentials: the server's refusal.
callBlock(handler, authReject, 0)
default:
withPool(func() {
const forSession = 1 // NSURLCredentialPersistenceForSession
cred := send(class("NSURLCredential"), "credentialWithUser:password:persistence:",
uintptr(nsString(resp.Username)), uintptr(nsString(resp.Password)), forSession)
callBlock(handler, authUseCredential, uintptr(cred))
})
}
}
// clientCertificate asks the app which identity to give a server that
// asks for one: every identity the keychain holds, with its certificate
// DER-encoded, as Electron offers them; the server's acceptable issuers
// (protectionSpace.distinguishedNames) are the app's to filter by. What
// the app does not take is refused, for the platform has no choice of
// its own to leave it to.
func (w *window) clientCertificate(space id, handler uintptr) {
api := trustAPI()
if api == nil || !w.h.HandlesClientCertificates() {
// Without a handler the challenge is the web view's, and the
// keychain is not asked about: it would ask the user.
callBlock(handler, authDefault, 0)
return
}
certs, identities := keychainIdentities(api)
// The array owns the identities, which an answer uses: it lives as
// long as they do. The keychain may hold none.
if identities != 0 {
defer cfRelease(uintptr(identities))
}
resp := w.h.ClientCertificateRequested(platform.ClientCertificateRequest{
Host: goString(send(space, "host")),
Port: sendInt(space, "port"),
IsProxy: sendBool(space, "isProxy"),
Certificates: certs,
})
switch {
case resp.Default:
callBlock(handler, authDefault, 0)
case resp.Certificate != nil && resp.Certificate.Native != 0:
withPool(func() {
const forSession = 1 // NSURLCredentialPersistenceForSession
cred := send(class("NSURLCredential"), "credentialWithIdentity:certificates:persistence:",
resp.Certificate.Native, uintptr(identityCertificates(api, resp.Certificate.Native)), forSession)
callBlock(handler, authUseCredential, uintptr(cred))
})
default:
callBlock(handler, authReject, 0)
}
}
// identityCertificates returns the array of certificates an identity's
// credential carries: the identity's own certificate, which the
// handshake needs.
func identityCertificates(api *trustFuncs, identity uintptr) id {
chain := send(class("NSMutableArray"), "array")
cert := identityCertificate(api, identity)
if cert == 0 {
return chain
}
defer cfRelease(cert)
send(chain, "addObject:", cert)
return chain
}
// identityCertificate returns the certificate of an identity, which the
// caller releases, or 0. SecIdentityCopyCertificate returns an OSStatus
// and writes the certificate to its second argument.
func identityCertificate(api *trustFuncs, identity uintptr) uintptr {
var cert uintptr
if status, _, _ := purego.SyscallN(api.identityCert, identity, uintptr(unsafe.Pointer(&cert))); int32(status) != 0 {
return 0
}
return cert
}
// keychainIdentities lists the identities of the keychain, their
// certificates DER-encoded with their common names. The array
// SecItemCopyMatching returns owns the identities; it is returned too,
// for the caller to keep alive as long as an answer uses them.
func keychainIdentities(api *trustFuncs) ([]platform.ClientCertificate, id) {
var certs []platform.ClientCertificate
var array id
withPool(func() {
query := send(class("NSMutableDictionary"), "dictionary")
send(query, "setObject:forKey:", api.secClassIdent, api.secClass)
send(query, "setObject:forKey:", api.boolTrue, api.secReturnRef)
send(query, "setObject:forKey:", api.secMatchLimitAll, api.secMatchLimit)
var result uintptr
if status, _, _ := purego.SyscallN(api.item, uintptr(query), uintptr(unsafe.Pointer(&result))); int32(status) != 0 || result == 0 {
return // errSecItemNotFound, among the others: no identities
}
array = id(result)
for i, n := 0, sendInt(array, "count"); i < n; i++ {
identity := send(array, "objectAtIndex:", uintptr(i))
cert := identityCertificate(api, uintptr(identity))
if cert == 0 {
continue
}
c := platform.ClientCertificate{Native: uintptr(identity)}
if data, _, _ := purego.SyscallN(api.data, cert); data != 0 {
c.DER = goBytes(id(data))
cfRelease(data)
}
// Security has no public call for the issuer or the validity
// on macOS: they are read from the certificate itself.
if issuer, from, to, ok := platform.CertificateIssuer(c.DER); ok {
c.Issuer, c.ValidFrom, c.ValidTo = issuer, from, to
}
var name uintptr
if status, _, _ := purego.SyscallN(api.commonName, cert, uintptr(unsafe.Pointer(&name))); int32(status) == 0 && name != 0 {
c.Subject = goString(id(name))
cfRelease(name)
}
cfRelease(cert)
if c.DER != nil {
certs = append(certs, c)
}
}
})
return certs, array
}
// serverTrust checks the server's certificate while the app handles
// certificate errors, and asks it about one that does not verify: WebKit
// checks it again otherwise (default handling), and fails the load.
func (w *window) serverTrust(challenge, space id, handler uintptr) {
api := trustAPI()
trust := send(space, "serverTrust")
if api == nil || trust == 0 || !w.h.HandlesCertificateErrors() {
callBlock(handler, authDefault, 0)
return
}
host, port := goString(send(space, "host")), sendInt(space, "port")
handler = blockCopy(handler)
retain(challenge) // and its trust, until the check ends
// SecTrustEvaluateAsyncWithError calls back on the queue it was
// called from, the main one.
block := newBlock(func(_ objc.Block, _ id, ok bool, nserr id) {
defer release(challenge)
defer blockRelease(handler)
if ok || w.closed {
callBlock(handler, authDefault, 0)
return
}
origin := host
if strings.Contains(host, ":") {
origin = "[" + host + "]" // IPv6
}
if port != 443 && port != 0 {
origin += ":" + strconv.Itoa(port)
}
e := platform.CertificateError{
URL: "https://" + origin,
Host: host,
Error: goString(send(nserr, "localizedDescription")), // a CFError is an NSError
Certificate: leafCertificate(api, trust),
}
if !w.h.CertificateError(e) {
callBlock(handler, authDefault, 0)
return
}
withPool(func() {
callBlock(handler, authUseCredential, uintptr(send(class("NSURLCredential"), "credentialForTrust:", uintptr(trust))))
})
})
status, _, _ := purego.SyscallN(api.evaluate, uintptr(trust), api.mainQueue, uintptr(block))
block.Release()
if int32(status) != 0 { // errSecSuccess: the block never runs otherwise
release(challenge)
callBlock(handler, authDefault, 0)
blockRelease(handler)
}
}
// leafCertificate returns the DER encoding of the server's own
// certificate in trust.
func leafCertificate(api *trustFuncs, trust id) []byte {
chain, _, _ := purego.SyscallN(api.chain, uintptr(trust))
if chain == 0 {
return nil
}
defer release(id(chain))
if sendInt(id(chain), "count") == 0 {
return nil
}
data, _, _ := purego.SyscallN(api.data, uintptr(send(id(chain), "objectAtIndex:", 0)))
defer release(id(data))
return goBytes(id(data))
}
+98
View File
@@ -0,0 +1,98 @@
//go:build darwin && !ios
package darwin
import (
"unsafe"
"github.com/ebitengine/purego"
)
var (
cfRunLoopGetMain func() uintptr
cfRunLoopSourceCreate func(alloc uintptr, order int, ctx unsafe.Pointer) uintptr
cfRunLoopAddSource func(rl, src, mode uintptr)
cfRelease func(obj uintptr)
kCFRunLoopCommonModes uintptr
// LaunchServices.
lsSetDefaultHandlerForURLScheme func(scheme, bundleID id) int32
lsCopyDefaultHandlerForURLScheme func(scheme id) id
// Power.
iopsCopyPowerSourcesInfo func() uintptr
iopsGetProvidingPowerSourceType func(snapshot uintptr) id
cgEventSourceSecondsSinceLastType func(state int32, eventType uint32) float64
// cgEventGetLocation is CGEventGetLocation: where an event happened,
// in the display space of Core Graphics.
cgEventGetLocation func(event uintptr) NSPoint
cgDisplayIsBuiltin func(display uint32) bool
cgDisplayRotation func(display uint32) float64
nsBeep func()
// Carbon hot keys.
getApplicationEventTarget func() uintptr
registerEventHotKey func(keyCode, modifiers uint32, hotKeyID eventHotKeyID, target uintptr, options uint32, outRef *uintptr) int32
unregisterEventHotKey func(ref uintptr) int32
installEventHandler func(target, handler uintptr, numTypes uint32, list *eventTypeSpec, userData uintptr, outRef *uintptr) int32
getEventParameter func(event uintptr, name, typ uint32, outType uintptr, size uintptr, outSize uintptr, data unsafe.Pointer) int32
)
// Called by address on every Signal, like the hot functions of objc.go.
var cfRunLoopSourceSignalFn, cfRunLoopWakeUpFn uintptr
type eventHotKeyID struct {
Signature uint32
ID uint32
}
type eventTypeSpec struct {
Class uint32
Kind uint32
}
func loadCF() {
purego.RegisterLibFunc(&cfRunLoopGetMain, libCF, "CFRunLoopGetMain")
purego.RegisterLibFunc(&cfRunLoopSourceCreate, libCF, "CFRunLoopSourceCreate")
purego.RegisterLibFunc(&cfRunLoopAddSource, libCF, "CFRunLoopAddSource")
cfRunLoopSourceSignalFn = mustDlsym(libCF, "CFRunLoopSourceSignal")
cfRunLoopWakeUpFn = mustDlsym(libCF, "CFRunLoopWakeUp")
purego.RegisterLibFunc(&cfRelease, libCF, "CFRelease")
p, err := purego.Dlsym(libCF, "kCFRunLoopCommonModes")
if err != nil {
panic(err)
}
kCFRunLoopCommonModes = **(**uintptr)(unsafe.Pointer(&p))
purego.RegisterLibFunc(&lsSetDefaultHandlerForURLScheme, libCoreServices, "LSSetDefaultHandlerForURLScheme")
purego.RegisterLibFunc(&lsCopyDefaultHandlerForURLScheme, libCoreServices, "LSCopyDefaultHandlerForURLScheme")
if iokit, err := purego.Dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", purego.RTLD_GLOBAL|purego.RTLD_NOW); err == nil {
purego.RegisterLibFunc(&iopsCopyPowerSourcesInfo, iokit, "IOPSCopyPowerSourcesInfo")
purego.RegisterLibFunc(&iopsGetProvidingPowerSourceType, iokit, "IOPSGetProvidingPowerSourceType")
}
purego.RegisterLibFunc(&cgEventSourceSecondsSinceLastType, libCG, "CGEventSourceSecondsSinceLastEventType")
purego.RegisterLibFunc(&cgEventGetLocation, libCG, "CGEventGetLocation")
purego.RegisterLibFunc(&cgDisplayIsBuiltin, libCG, "CGDisplayIsBuiltin")
purego.RegisterLibFunc(&cgDisplayRotation, libCG, "CGDisplayRotation")
purego.RegisterLibFunc(&nsBeep, libAppKit, "NSBeep")
purego.RegisterLibFunc(&getApplicationEventTarget, libCarbon, "GetApplicationEventTarget")
purego.RegisterLibFunc(&registerEventHotKey, libCarbon, "RegisterEventHotKey")
purego.RegisterLibFunc(&unregisterEventHotKey, libCarbon, "UnregisterEventHotKey")
purego.RegisterLibFunc(&installEventHandler, libCarbon, "InstallEventHandler")
purego.RegisterLibFunc(&getEventParameter, libCarbon, "GetEventParameter")
}
// constString reads an exported NSString constant such as
// NSPasteboardTypeString.
func constString(lib uintptr, name string) id {
p, err := purego.Dlsym(lib, name)
if err != nil || p == 0 {
return 0
}
return **(**id)(unsafe.Pointer(&p))
}
+352
View File
@@ -0,0 +1,352 @@
//go:build darwin && !ios
package darwin
import (
"slices"
"github.com/ebitengine/purego/objc"
)
// A window with a Parent stays above it by being ordered there, not
// attached as an AppKit child window (addChildWindow:ordered:). AppKit
// keeps a child window on its parent's Space, and each display has Spaces
// of its own: moved to another display, a child window is not drawn
// there, though the window server lists it, and the clicks in its frame
// go to the windows behind. Detached with removeChildWindow:, it stays on
// its parent's Space all the same. AppKit also keeps child windows in the
// order they were attached in, whichever the user brings in front. An
// ordinary window goes to the Space of the display it is on, so a child
// window stays one: it is ordered above its parent and the parent's
// other children as it shows, and the parent's children are ordered
// above it again whenever the parent is ordered in
// (orderWindowRelativeTo), takes the keyboard or is restored from the
// Dock, in the order they are in. It hides with its
// parent, as AppKit's child windows do, and shows again with it. Sheets
// and flyouts are still attached, as AppKit attaches them.
//
// Ordered across levels, a child window would go behind a parent that is
// always on top: it takes its parent's level when that is higher, as
// AppKit gives an attached child window (applyLevel). And a full-screen
// window has a Space of its own, which an ordinary window does not
// follow it to: the child windows that show are attached as AppKit's
// while their parent is in full screen, which takes them there, and
// detached as it comes out of it, back on its display's Space.
// isChild tells that w is a child window kept above its parent: one with
// a Parent that is neither a sheet, nor a flyout or popover, nor a web
// view in native UI.
func (w *window) isChild() bool {
return w.parent != nil && !w.parent.closed && !w.closed &&
w.host == nil && w.opts.Flyout == nil && !w.opts.Modal && !w.sheet
}
// onScreen tells that a window shows: visible and not in the Dock.
func (w *window) onScreen() bool {
return !w.closed && sendBool(w.win, "isVisible") && !sendBool(w.win, "isMiniaturized")
}
// showAboveParent shows w, as the key window for Show (key): a child
// window above its parent and the parent's other child windows, as AppKit
// puts the child window attached last, or as any window while its parent
// does not show. Then its own children go above it.
func (w *window) showAboveParent(key bool) {
w.hiddenWithParent, w.hidMiniaturized = false, false
switch {
case w.isChild() && w.parent.onScreen():
w.b.orderingChildren = true
w.orderAbove(w.parent.frontmost(w))
w.b.orderingChildren = false
if key {
send(w.win, "makeKeyWindow")
}
case key:
send(w.win, "makeKeyAndOrderFront:", 0)
default:
send(w.win, "orderFrontRegardless")
}
w.attach()
w.orderChildrenLater()
}
// frontmost returns the frontmost window that shows of w and the child
// windows above it, with theirs, leaving out skip and its own.
func (w *window) frontmost(skip *window) id {
top := w.win
withPool(func() {
for _, x := range w.b.windowsFrontToBack() {
c := w.b.byNSWindow[x]
switch {
case c == w:
return
case c != nil && c != skip && c.onScreen() && c.descends(w) && !c.descends(skip):
top = x
return
}
}
})
return top
}
// descends tells that w is a child window kept above a, or above one of
// a's.
func (w *window) descends(a *window) bool {
for c := w; c.isChild(); c = c.parent {
if c.parent == a {
return true
}
}
return false
}
// windowsFrontToBack returns the app's windows that show, on any Space,
// front to back. NSApp's orderedWindows would leave panels out
// (WindowOptions.Panel), which can be child windows too. Call it in a
// pool.
func (b *Backend) windowsFrontToBack() []id {
const allSpaces = 1 << 4 // NSWindowNumberListAllSpaces
nums := arrayItems(send(class("NSWindow"), "windowNumbersWithOptions:", allSpaces))
wins := make([]id, 0, len(nums))
for _, n := range nums {
if x := send(b.app, "windowWithWindowNumber:", uintptr(sendInt(n, "integerValue"))); x != 0 {
wins = append(wins, x)
}
}
return wins
}
// orderAbove orders w right above the window rel.
func (w *window) orderAbove(rel id) {
send(w.win, "orderWindow:relativeTo:", 1, uintptr(sendInt(rel, "windowNumber"))) // NSWindowAbove
}
// orderChildrenLater orders w's child windows above it once the current
// event is handled: AppKit is still ordering w, or making it key, when it
// tells. Once for the calls made before then, and not at all for a
// window without children, as most are: AppKit tells of every ordering of
// every window.
func (w *window) orderChildrenLater() {
if w.orderPending || w.closed || !w.hasChildren() {
return
}
w.orderPending = true
w.b.post(func() {
w.orderPending = false
if w.closed || w.b.orderingChildren || !w.onScreen() || !w.hasChildren() {
return
}
w.b.orderingChildren = true
w.orderChildren()
w.b.orderingChildren = false
})
}
// hasChildren tells that w has a child window kept above it.
func (w *window) hasChildren() bool {
for _, c := range w.b.byNSWindow {
if c.parent == w && c.isChild() {
return true
}
}
return false
}
// orderChildren orders w's child windows that show, and those that hid
// with it, right above it, in the order they are in, each with its own
// children above it, and returns the frontmost window it ordered, or w's.
func (w *window) orderChildren() id {
top := w.win
kids := w.children(true)
for i := len(kids) - 1; i >= 0; i-- { // back to front
c := kids[i]
c.hiddenWithParent = false
c.orderAbove(top)
c.attach()
top = c.orderChildren()
}
return top
}
// hideChildren orders out w's child windows that show, and theirs, as w
// hides or miniaturizes, remembering them to show again with it.
func (w *window) hideChildren() {
if w.b.orderingChildren || !w.hasChildren() {
return
}
w.b.orderingChildren = true
defer func() { w.b.orderingChildren = false }()
w.hideChildrenNow()
}
func (w *window) hideChildrenNow() {
for i, c := range w.children(false) {
c.hiddenWithParent, c.hiddenRank = true, i
send(c.win, "orderOut:", 0)
c.hideChildrenNow()
}
}
// children returns w's child windows that show, front to back, then,
// with hidden, those that hid with it, as they were.
func (w *window) children(hidden bool) []*window {
var front, gone []*window
withPool(func() {
for _, x := range w.b.windowsFrontToBack() {
if c := w.b.byNSWindow[x]; c != nil {
front = append(front, c)
}
}
})
if hidden {
for _, c := range w.b.byNSWindow {
if c.parent == w && c.isChild() && c.hiddenWithParent && !c.onScreen() {
gone = append(gone, c)
}
}
}
return childOrder(front, func(c *window) bool { return c.parent == w && c.isChild() && c.onScreen() },
gone, func(c *window) int { return c.hiddenRank })
}
// childOrder returns the child windows to order above their parent, front
// to back: those of the app's windows front to back (front) that shows
// tells show, in that order, then those that hid with their parent
// (hidden), by rank, the frontmost 0.
func childOrder[W comparable](front []W, shows func(W) bool, hidden []W, rank func(W) int) []W {
var kids []W
for _, x := range front {
if shows(x) {
kids = append(kids, x)
}
}
// An insertion sort, stable: a window has few children, and
// slices.SortStableFunc would add its code to every app.
hidden = slices.Clone(hidden)
for i := 1; i < len(hidden); i++ {
for j := i; j > 0 && rank(hidden[j]) < rank(hidden[j-1]); j-- {
hidden[j], hidden[j-1] = hidden[j-1], hidden[j]
}
}
for _, x := range hidden {
if !slices.Contains(kids, x) {
kids = append(kids, x)
}
}
return kids
}
// applyLevel gives w the level AlwaysOnTop asked for, or its parent's
// when that is higher, as a child window ordered above its parent across
// levels would go behind it; then its child windows theirs.
func (w *window) applyLevel() {
if w.closed || w.host != nil || w.opts.Flyout != nil {
return
}
level := nsNormalWindowLevel
if w.onTop {
level = nsFloatingWindowLevel
}
if w.isChild() || w.modalToFlyout() && !w.parent.closed && w.parent.win != 0 {
level = max(level, sendInt(w.parent.win, "level"))
}
if sendInt(w.win, "level") != level {
send(w.win, "setLevel:", uintptr(level))
}
for _, c := range w.b.byNSWindow {
if c.parent == w && c.isChild() {
c.applyLevel()
}
}
}
// attach makes w an AppKit child window of its parent while the parent is
// in full screen, or attached itself, so that it goes to the parent's
// Space; then its own child windows.
func (w *window) attach() {
if w.attached || !w.isChild() || !(w.parent.childrenAttached || w.parent.attached) ||
!w.onScreen() || !w.parent.onScreen() {
return
}
// AppKit orders w above its parent, which orders nothing more.
ordering := w.b.orderingChildren
w.b.orderingChildren = true
send(w.parent.win, "addChildWindow:ordered:", uintptr(w.win), 1) // NSWindowAbove
w.b.orderingChildren = ordering
w.attached = true
w.attachChildren()
}
// attachChildren attaches w's child windows that show, back to front, as
// AppKit keeps the one attached last in front.
func (w *window) attachChildren() {
kids := w.children(false)
for i := len(kids) - 1; i >= 0; i-- {
kids[i].attach()
}
}
// detach stops w being an AppKit child window (attach), and its child
// windows too unless w is in full screen itself, giving each its own
// level back.
func (w *window) detach() {
if !w.attached {
return
}
if w.parent != nil {
send(w.parent.win, "removeChildWindow:", uintptr(w.win))
}
w.attached = false
if !w.childrenAttached {
w.detachChildren()
}
w.applyLevel()
}
func (w *window) detachChildren() {
for _, c := range w.b.byNSWindow {
if c.parent == w && c.attached {
c.detach()
}
}
}
// leftFullScreen detaches w's child windows as w comes out of full screen,
// or fails to go in, and orders them above it again.
func (w *window) leftFullScreen() {
w.childrenAttached = false
if !w.attached {
w.detachChildren()
}
w.orderChildrenLater()
}
// releaseChildren detaches w's child windows as w closes, and gives them
// their own level back.
func (w *window) releaseChildren() {
for _, c := range w.b.byNSWindow {
if c.parent == w && !c.closed {
c.detach()
c.applyLevel()
}
}
}
// orderWindowRelativeTo overrides orderWindow:relativeTo: of the class
// named, which AppKit orders a window in or out with whatever orders it:
// orderFront:, makeKeyAndOrderFront:, orderFrontRegardless, orderBack:,
// a click, the Dock, Mission Control, assistive technology raising it. A
// window ordered in orders its child windows above it again once AppKit
// is done, for the key window too, which tells nothing else as it comes
// in front of its children. The orderings of the children themselves,
// while orderingChildren, order nothing more.
func orderWindowRelativeTo(className string) func(self id, cmd objc.SEL, place, other int) {
return func(self id, cmd objc.SEL, place, other int) {
sendSuper(self, className, cmd, uintptr(place), uintptr(other))
const out = 0 // NSWindowOut
if b := theBackend; b != nil && place != out && !b.orderingChildren {
if w := b.byNSWindow[self]; w != nil {
w.orderChildrenLater()
}
}
}
}
+32
View File
@@ -0,0 +1,32 @@
//go:build darwin && !ios
package darwin
import (
"slices"
"testing"
)
// TestChildOrder checks the order child windows go above their parent
// in: those that show as the app's windows are, front to back, then
// those that hid with the parent, by rank.
func TestChildOrder(t *testing.T) {
ranks := map[string]int{"h0": 0, "h1": 1, "h2": 2, "a": 0}
shows := func(w string) bool { return w[0] == 'a' || w[0] == 'b' } // a and b are children
rank := func(w string) int { return ranks[w] }
for _, c := range []struct {
name string
front, hidden []string
want []string
}{
{"none", []string{"x", "parent"}, nil, nil},
{"among other windows", []string{"b", "x", "a", "parent", "y"}, nil, []string{"b", "a"}},
{"behind their parent too", []string{"parent", "a", "b"}, nil, []string{"a", "b"}},
{"hidden ones by rank, behind", []string{"a", "parent"}, []string{"h2", "h0", "h1"}, []string{"a", "h0", "h1", "h2"}},
{"hidden and shown again once", []string{"a", "parent"}, []string{"a"}, []string{"a"}},
} {
if got := childOrder(c.front, shows, c.hidden, rank); !slices.Equal(got, c.want) {
t.Errorf("%s: childOrder(%q, %q) = %q, want %q", c.name, c.front, c.hidden, got, c.want)
}
}
}
+381
View File
@@ -0,0 +1,381 @@
//go:build darwin && !ios
package darwin
import (
"errors"
"slices"
"strings"
"sync"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/transfer"
)
var (
clipboardClassOnce sync.Once
macClipboard *macClipboardSource
macClipboardProviders = map[id]*macClipboardSource{}
)
type macClipboardSource struct {
obj id
change int
data transfer.Data
items map[id]transfer.Item
concealed bool
released func()
}
// macConcealedType is nspasteboard.org's mark of confidential content, for
// the clipboard managers that read it. It goes on every item, with no data,
// next to the content.
const macConcealedType = "org.nspasteboard.ConcealedType"
// prepareMacClipboard takes the pasteboard for new contents, as clearContents
// does; concealed contents stay on this host, off Universal Clipboard
// (NSPasteboardContentsCurrentHostOnly), until the next write clears it.
func prepareMacClipboard(board id, concealed bool) {
if concealed {
send(board, "prepareForNewContentsWithOptions:", 1)
return
}
send(board, "clearContents")
}
// pasteboardItem makes the NSPasteboardItem that promises item's
// representations through s, autoreleased.
func (s *macClipboardSource) pasteboardItem(item transfer.Item) id {
pb := autorelease(send(send(class("NSPasteboardItem"), "alloc"), "init"))
s.items[pb] = item
var types []id
for _, typ := range macClipboardTypes(item) {
types = append(types, nsString(typ))
}
send(pb, "setDataProvider:forTypes:", uintptr(s.obj), uintptr(nsArray(types...)))
if s.concealed {
send(pb, "setData:forType:", uintptr(nsData(nil)), uintptr(nsString(macConcealedType)))
}
return pb
}
func registerClipboardClass() {
clipboardClassOnce.Do(func() {
classDef("MyGoClipboardProvider", "NSObject", []string{"NSPasteboardItemDataProvider"}, []objc.MethodDef{
method("pasteboard:item:provideDataForType:", func(self id, _ objc.SEL, board, item, typ id) {
s := macClipboardProviders[self]
if s == nil {
return
}
name := goString(typ)
f := macClipboardFormat(name)
b, err := s.items[item].Read(f)
if err != nil {
return
}
if name == "public.url" || name == "public.file-url" {
b = []byte(strings.TrimSpace(strings.Split(string(b), "\n")[0]))
}
send(item, "setData:forType:", uintptr(nsData(b)), uintptr(typ))
}),
method("pasteboardFinishedWithDataProvider:", func(self id, _ objc.SEL, board id) {
if s := macClipboardProviders[self]; s != nil {
s.release()
}
}),
})
})
}
func (s *macClipboardSource) release() {
if s.obj == 0 {
return
}
delete(macClipboardProviders, s.obj)
if macClipboard == s {
macClipboard = nil
}
// AppKit may still be in a callback on self; its own references are
// independent of our +1. Drop all Go closures before notifying the core.
autorelease(s.obj)
s.obj, s.data, s.items = 0, transfer.Data{}, nil
if fn := s.released; fn != nil {
s.released = nil
fn()
}
}
func currentMacClipboard() *macClipboardSource {
s := macClipboard
if s != nil && sendInt(pasteboard(), "changeCount") != s.change {
s.release()
return nil
}
return s
}
// A file-list representation can contain several URLs. Keep its complete
// bytes alongside AppKit's single-file URL interoperability representation.
func macClipboardFormat(name string) transfer.Format {
if name == "public.utf16-plain-text" || name == "public.utf16-external-plain-text" {
return transfer.Text
}
if name == "dev.mygo.file-list" || name == "NSFilenamesPboardType" {
return transfer.FileList
}
return macFormat(name)
}
func macClipboardTypes(item transfer.Item) []string {
var types []string
for _, f := range item.Formats() {
types = append(types, macType(f))
if f == transfer.URIList {
types = append(types, "public.url")
}
if f == transfer.FileList {
types = append(types, "dev.mygo.file-list")
}
}
return types
}
func (clipboard) WriteData(data transfer.Data, concealed bool, released func()) error {
var err error
withPool(func() {
registerClipboardClass()
if len(data.Formats()) == 0 {
clipboard{}.Clear()
if released != nil {
released()
}
return
}
s := &macClipboardSource{data: data, items: map[id]transfer.Item{}, concealed: concealed, released: released}
s.obj = send(send(class("MyGoClipboardProvider"), "alloc"), "init")
macClipboardProviders[s.obj] = s
var items []id
for _, item := range data.Items() {
items = append(items, s.pasteboardItem(item))
}
board := pasteboard()
prepareMacClipboard(board, concealed)
if old := macClipboard; old != nil {
old.release()
}
if !sendBool(board, "writeObjects:", uintptr(nsArray(items...))) {
s.released = nil
s.release()
err = errors.New("mygo: cannot write pasteboard items")
return
}
s.change = sendInt(board, "changeCount")
if s.obj != 0 {
macClipboard = s
}
})
return err
}
func (clipboard) Formats() []transfer.Format {
var out []transfer.Format
withPool(func() {
if s := currentMacClipboard(); s != nil {
out = s.data.Formats()
return
}
for _, typ := range arrayItems(send(pasteboard(), "types")) {
name := goString(typ)
f := macClipboardFormat(name)
if name == utTIFF {
f = transfer.PNG
}
if f == "" || strings.ContainsAny(string(f), "\x00\r\n") || f == platform.DragSessionFormat {
continue
}
if !slices.Contains(out, f) {
out = append(out, f)
}
if f == transfer.FileList && !slices.Contains(out, transfer.URIList) {
out = append(out, transfer.URIList)
}
}
})
return out
}
func (c clipboard) ReadData(formats []transfer.Format) (transfer.Data, error) {
var result transfer.Data
var err error
withPool(func() {
board := pasteboard()
change := sendInt(board, "changeCount")
if len(formats) == 0 {
formats = c.Formats()
if len(formats) == 0 {
return
}
}
if s := currentMacClipboard(); s != nil {
result, err = s.data.Materialize(formats)
} else {
var items []transfer.Item
for _, item := range arrayItems(send(board, "pasteboardItems")) {
reps, e := macClipboardReadItem(item, formats)
if e != nil {
err = e
return
}
if len(reps) != 0 {
items = append(items, transfer.NewItem(reps...))
}
}
result = transfer.New(items...)
if len(result.Formats()) == 0 {
err = transfer.ErrFormat
}
}
if sendInt(board, "changeCount") != change {
result, err = transfer.Data{}, platform.ErrClipboardChanged
}
})
return result, err
}
func macClipboardReadItem(item id, formats []transfer.Format) ([]transfer.Representation, error) {
available := map[transfer.Format][]string{}
for _, typ := range arrayItems(send(item, "types")) {
name := goString(typ)
f := macClipboardFormat(name)
if name == utTIFF {
f = transfer.PNG
}
if f == "" || f == platform.DragSessionFormat || strings.ContainsAny(string(f), "\x00\r\n") {
continue
}
available[f] = append(available[f], name)
if f == transfer.FileList {
available[transfer.URIList] = append(available[transfer.URIList], name)
}
}
var reps []transfer.Representation
for n, f := range formats {
if slices.Contains(formats[:n], f) {
continue
}
names := available[f]
// Put full serialized URI/file lists before single URL fallbacks.
preferred := []string{macType(f)}
if f == transfer.FileList {
preferred = []string{"dev.mygo.file-list", macType(f)}
}
if f == transfer.URIList {
preferred = []string{macType(f), "dev.mygo.file-list"}
}
var ordered []string
for _, name := range append(preferred, names...) {
if slices.Contains(names, name) && !slices.Contains(ordered, name) {
ordered = append(ordered, name)
}
}
var b []byte
found := false
for _, name := range ordered {
typ := nsString(name)
if name == "NSFilenamesPboardType" {
var paths []string
for _, value := range arrayItems(send(item, "propertyListForType:", uintptr(typ))) {
paths = append(paths, goString(value))
}
files, err := transfer.FileData(paths...)
if err != nil {
return nil, err
}
b, err = files.Read(f)
if err != nil {
continue
}
found = true
break
}
value := send(item, "dataForType:", uintptr(typ))
if value == 0 {
continue
}
if send(value, "length") > 64<<20 {
return nil, errors.New("mygo: clipboard representation exceeds 64 MiB")
}
b = goBytes(value)
if name == "public.file-url" {
b = filePathURLBytes(b)
}
if f == transfer.Text && name != utString {
// AppKit decodes legacy/UTF-16 text into an NSString.
b = []byte(goString(send(item, "stringForType:", uintptr(typ))))
}
if f == transfer.PNG && name == utTIFF {
rep := send(class("NSBitmapImageRep"), "imageRepWithData:", uintptr(value))
if rep == 0 {
return nil, errors.New("mygo: cannot convert clipboard image")
}
b = goBytes(send(rep, "representationUsingType:properties:", 4, uintptr(send(class("NSDictionary"), "dictionary"))))
}
found = true
break
}
if found {
reps = append(reps, transfer.Bytes(f, b))
}
}
return reps, nil
}
func (clipboard) Flush() error {
var err error
withPool(func() {
s := currentMacClipboard()
if s == nil {
return
}
d, e := s.data.Materialize(s.data.Formats())
if e != nil {
err = e
return
}
if currentMacClipboard() != s {
err = platform.ErrClipboardChanged
return
}
var items []id
for _, item := range d.Items() {
pb := autorelease(send(send(class("NSPasteboardItem"), "alloc"), "init"))
for _, name := range macClipboardTypes(item) {
b, _ := item.Read(macClipboardFormat(name))
if name == "public.url" || name == "public.file-url" {
b = []byte(strings.TrimSpace(strings.Split(string(b), "\n")[0]))
}
send(pb, "setData:forType:", uintptr(nsData(b)), uintptr(nsString(name)))
}
if s.concealed {
send(pb, "setData:forType:", uintptr(nsData(nil)), uintptr(nsString(macConcealedType)))
}
items = append(items, pb)
}
board := pasteboard()
prepareMacClipboard(board, s.concealed)
if !sendBool(board, "writeObjects:", uintptr(nsArray(items...))) {
err = errors.New("mygo: cannot persist pasteboard items")
}
s.release()
})
return err
}
func (clipboard) Close() {
withPool(func() {
if s := currentMacClipboard(); s != nil {
send(pasteboard(), "clearContents")
s.release()
}
})
}
+137
View File
@@ -0,0 +1,137 @@
//go:build darwin && !ios
package darwin
import (
"bytes"
"fmt"
"image"
"image/png"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/transfer"
)
func TestClipboardNativeAliasesAndFileList(t *testing.T) {
load()
withPool(func() {
item := autorelease(send(send(class("NSPasteboardItem"), "alloc"), "init"))
const utf16 = "public.utf16-external-plain-text"
send(item, "setString:forType:", uintptr(nsString("hello 日本語")), uintptr(nsString(utf16)))
files := []byte("file:///tmp/a%20%23.txt\r\nfile:///tmp/b.txt")
send(item, "setData:forType:", uintptr(nsData([]byte("file:///tmp/a%20%23.txt"))), uintptr(nsString("public.file-url")))
send(item, "setData:forType:", uintptr(nsData(files)), uintptr(nsString("dev.mygo.file-list")))
var encoded bytes.Buffer
_ = png.Encode(&encoded, image.NewNRGBA(image.Rect(0, 0, 2, 3)))
rep := send(class("NSBitmapImageRep"), "imageRepWithData:", uintptr(nsData(encoded.Bytes())))
tiff := send(rep, "representationUsingType:properties:", 0, uintptr(send(class("NSDictionary"), "dictionary")))
send(item, "setData:forType:", uintptr(tiff), uintptr(nsString(utTIFF)))
reps, err := macClipboardReadItem(item, []transfer.Format{transfer.Text, transfer.FileList, transfer.URIList, transfer.PNG, transfer.Text})
if err != nil {
t.Fatal(err)
}
d := transfer.New(transfer.NewItem(reps...))
if b, _ := d.Read(transfer.Text); string(b) != "hello 日本語" {
t.Fatalf("UTF-16 conversion %q", b)
}
for _, f := range []transfer.Format{transfer.FileList, transfer.URIList} {
if b, _ := d.Read(f); !bytes.Equal(b, files) {
t.Fatalf("complete %s: %q", f, b)
}
}
b, _ := d.Read(transfer.PNG)
img, err := png.Decode(bytes.NewReader(b))
if err != nil || img.Bounds() != image.Rect(0, 0, 2, 3) {
t.Fatalf("TIFF conversion: %v", err)
}
})
}
// Finder copies file reference URLs (file:///.file/id=…), which must be
// read as paths.
func TestClipboardFileReferenceURL(t *testing.T) {
load()
path := filepath.Join(t.TempDir(), "a b.txt")
if err := os.WriteFile(path, nil, 0o600); err != nil {
t.Fatal(err)
}
want, _ := filepath.EvalSymlinks(path)
withPool(func() {
ref := goString(send(send(fileURL(path), "fileReferenceURL"), "absoluteString"))
if !strings.HasPrefix(ref, "file:///.file/id=") {
t.Fatalf("reference URL %q", ref)
}
item := autorelease(send(send(class("NSPasteboardItem"), "alloc"), "init"))
send(item, "setData:forType:", uintptr(nsData([]byte(ref))), uintptr(nsString("public.file-url")))
for _, f := range []transfer.Format{transfer.FileList, transfer.URIList} {
reps, err := macClipboardReadItem(item, []transfer.Format{f})
if err != nil {
t.Fatal(err)
}
b, _ := transfer.New(transfer.NewItem(reps...)).Read(f)
files, err := transfer.New(transfer.NewItem(transfer.Bytes(transfer.FileList, b))).Files()
if err != nil || len(files) != 1 || files[0] != want {
t.Fatalf("%s: files %q, %v; want %q", f, files, err, want)
}
}
})
}
func TestClipboardConcealedItem(t *testing.T) {
load()
registerClipboardClass()
withPool(func() {
for _, concealed := range []bool{false, true} {
s := &macClipboardSource{items: map[id]transfer.Item{}, concealed: concealed}
s.obj = send(send(class("MyGoClipboardProvider"), "alloc"), "init")
macClipboardProviders[s.obj] = s
pb := s.pasteboardItem(transfer.NewItem(transfer.Bytes(transfer.Text, []byte("hunter2"))))
var types []string
for _, typ := range arrayItems(send(pb, "types")) {
types = append(types, goString(typ))
}
if slices.Contains(types, macConcealedType) != concealed || !slices.Contains(types, utString) {
t.Fatalf("concealed %t: types %q", concealed, types)
}
if mark := send(pb, "dataForType:", uintptr(nsString(macConcealedType))); (mark != 0) != concealed {
t.Fatalf("concealed %t: mark data %d", concealed, mark)
}
s.release()
}
})
}
// testPasteboardCalls records what prepareMacClipboard sent to a
// MyGoTestPasteboard, a class registered once for every run of the test.
var testPasteboardCalls []string
func TestClipboardConcealedWritesForCurrentHostOnly(t *testing.T) {
load()
if objc.GetClass("MyGoTestPasteboard") == 0 {
classDef("MyGoTestPasteboard", "NSObject", nil, []objc.MethodDef{
method("clearContents", func(self id, _ objc.SEL) int {
testPasteboardCalls = append(testPasteboardCalls, "clearContents")
return 0
}),
method("prepareForNewContentsWithOptions:", func(self id, _ objc.SEL, options uint) int {
testPasteboardCalls = append(testPasteboardCalls, fmt.Sprintf("prepareForNewContentsWithOptions:%d", options))
return 0
}),
})
}
testPasteboardCalls = nil
withPool(func() {
board := autorelease(send(send(class("MyGoTestPasteboard"), "alloc"), "init"))
prepareMacClipboard(board, false)
prepareMacClipboard(board, true)
})
// 1 is NSPasteboardContentsCurrentHostOnly.
if want := []string{"clearContents", "prepareForNewContentsWithOptions:1"}; !slices.Equal(testPasteboardCalls, want) {
t.Fatalf("pasteboard calls %q, want %q", testPasteboardCalls, want)
}
}
+62
View File
@@ -0,0 +1,62 @@
//go:build darwin && !ios
package darwin
import (
"sync"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
)
var macClipboardWatch struct {
once sync.Once
timer id
change int
notify func()
newTimer func(id, objc.SEL, float64, id, objc.SEL, id, bool) id
}
// AppKit has no public pasteboard-change notification. Poll only its change
// count while asked, never its types/data (which can invoke lazy providers).
func (clipboard) WatchChanges(changed func()) (func(), error) {
w := &macClipboardWatch
withPool(func() {
w.once.Do(func() {
purego.RegisterFunc(&w.newTimer, msgSendAddr)
classDef("MyGoClipboardObserver", "NSObject", nil, []objc.MethodDef{
method("clipboardTick:", func(_ id, _ objc.SEL, timer id) {
if timer != w.timer || w.notify == nil {
return
}
withPool(func() {
change := sendInt(pasteboard(), "changeCount")
if change != w.change {
w.change = change
w.notify()
}
})
}),
})
})
w.change = sendInt(pasteboard(), "changeCount")
w.notify = changed
observer := alloc("MyGoClipboardObserver")
w.timer = retain(w.newTimer(class("NSTimer"), sel("timerWithTimeInterval:target:selector:userInfo:repeats:"), .25, observer, sel("clipboardTick:"), 0, true))
release(observer) // NSTimer retains its target until invalidated.
// A tenth of the interval, as Apple asks of repeating timers, lets
// the system fire it with its other wakeups: nobody notices a
// change 25 ms later, and the app idles in fewer of them.
msgSetFloat(w.timer, sel("setTolerance:"), .025)
send(send(class("NSRunLoop"), "mainRunLoop"), "addTimer:forMode:", uintptr(w.timer), kCFRunLoopCommonModes)
})
timer := w.timer
return func() {
if w.timer != timer {
return
}
w.timer, w.notify = 0, nil
send(timer, "invalidate")
release(timer)
}, nil
}
+146
View File
@@ -0,0 +1,146 @@
//go:build darwin && !ios
package darwin
import (
"fmt"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
// contentRules is the code of content rules, which LinkContentRules
// links: the backend's methods are linked into every app, and only call
// it.
var contentRules struct {
compile func(b *Backend, id, identifier, rules string, done func(any, error))
set func(w *window, lists []any)
}
// LinkContentRules links the code of content rules, when the app first
// compiles rules.
func LinkContentRules() {
contentRules.compile, contentRules.set = compileContentRules, setContentRules
}
func (a appController) CompileContentRules(id, identifier, rules string, done func(any, error)) {
if contentRules.compile == nil {
done(nil, platform.ErrUnsupported)
return
}
contentRules.compile(a.b, id, identifier, rules, done)
}
func (w *window) SetContentRules(lists []any) {
if contentRules.set != nil {
contentRules.set(w, lists)
}
}
// compileContentRules makes a WKContentRuleList in the default
// WKContentRuleListStore, which keeps compiled lists in the app's
// container across launches: the list kept as identifier, else one
// compiled from rules, after which the lists of id's earlier rules go.
// The handle is the list, retained for good: a page may apply it at any
// time.
func compileContentRules(b *Backend, contentID, identifier, rules string, done func(any, error)) {
if class("WKContentRuleListStore") == 0 {
done(nil, fmt.Errorf("content rules need macOS 10.13 or newer: %w", platform.ErrUnsupported))
return
}
finish := func(list, err id) {
switch {
case list != 0:
done(retain(list), nil)
case err != 0:
done(nil, contentRulesError(err))
default:
done(nil, fmt.Errorf("WebKit made no list"))
}
}
store := retain(send(class("WKContentRuleListStore"), "defaultStore"))
compile := func() {
compiled := newBlock(func(_ objc.Block, list, err id) {
retain(list)
retain(err)
b.runOnMain(func() {
defer release(store)
defer release(list)
defer release(err)
if list != 0 {
removeStaleContentRules(store, contentID, identifier)
}
finish(list, err)
})
})
send(store, "compileContentRuleListForIdentifier:encodedContentRuleList:completionHandler:",
uintptr(nsString(identifier)), uintptr(nsString(rules)), uintptr(compiled))
compiled.Release()
}
withPool(func() {
found := newBlock(func(_ objc.Block, list, _ id) {
retain(list)
b.runOnMain(func() {
defer release(list)
if list == 0 {
withPool(compile)
return
}
release(store)
finish(list, 0)
})
})
send(store, "lookUpContentRuleListForIdentifier:completionHandler:", uintptr(nsString(identifier)), uintptr(found))
found.Release()
})
}
// contentRulesError describes an error of the store, which puts what is
// wrong with the rules in NSHelpAnchorErrorKey.
func contentRulesError(err id) error {
info := send(err, "userInfo")
if reason := send(info, "objectForKey:", uintptr(nsString("NSHelpAnchor"))); reason != 0 {
return fmt.Errorf("%s", goString(reason))
}
return nsError(err)
}
// removeStaleContentRules removes the lists the store keeps for id but
// current.
func removeStaleContentRules(store id, contentID, current string) {
retain(store)
listed := newBlock(func(_ objc.Block, identifiers id) {
var stale []string
withPool(func() {
for _, s := range arrayItems(identifiers) {
if name := goString(s); platform.StaleContentRules(contentID, current, name) {
stale = append(stale, name)
}
}
for _, name := range stale {
removed := newBlock(func(objc.Block, id) {})
send(store, "removeContentRuleListForIdentifier:completionHandler:", uintptr(nsString(name)), uintptr(removed))
removed.Release()
}
})
release(store)
})
send(store, "getAvailableContentRuleListIdentifiers:", uintptr(listed))
listed.Release()
}
// setContentRules replaces the lists of the window's content controller,
// which WebKit applies to the loads from then on.
func setContentRules(w *window, lists []any) {
if w.ucc == 0 || w.closed {
return
}
withPool(func() {
send(w.ucc, "removeAllContentRuleLists")
for _, l := range lists {
if list, ok := l.(id); ok {
send(w.ucc, "addContentRuleList:", uintptr(list))
}
}
})
}
+345
View File
@@ -0,0 +1,345 @@
//go:build darwin && !ios
package darwin
import (
"strings"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
// A page's context menu: WebKit builds its NSMenu and pops it up over the
// web view, which AppKit tells the view as -[NSView willOpenMenu:withEvent:]
// before the menu shows. MyGo describes the menu there, asks the core, and
// changes it in place: WebKit's items, which carry what they do, go back
// where the core put them, and the app's are made as those of its other
// menus. WebKit tells nothing of what was clicked: the core has it from
// the page (bridge.go).
var (
// contextWindow is the window the context menu shown last opened
// over, whose window handler hears the app's items chosen, which
// AppKit sends once the menu closed. contextOwner owns those items,
// released as the next menu opens.
contextWindow *window
contextOwner int
// openContextMenu is the context menu being shown, for the tests: one
// a listener heard of, with items.
openContextMenu id
)
// contextMenuMethods are the overrides of MyGoWebView that hear of its
// context menus.
func contextMenuMethods() []objc.MethodDef {
return []objc.MethodDef{
method("willOpenMenu:withEvent:", func(self id, cmd objc.SEL, menu, ev id) {
sendSuper(self, "MyGoWebView", cmd, uintptr(menu), uintptr(ev))
// A listener the core heard of was added after the code was
// linked: HandlesContextMenu, which takes the listeners' lock,
// sees showContextMenu set.
if w := theBackend.byWebView[self]; w != nil && w.h.HandlesContextMenu() && showContextMenu != nil {
showContextMenu(w, menu, ev)
}
}),
method("didCloseMenu:withEvent:", func(self id, cmd objc.SEL, menu, ev id) {
sendSuper(self, "MyGoWebView", cmd, uintptr(menu), uintptr(ev))
if menu == openContextMenu {
openContextMenu = 0
}
}),
}
}
// showContextMenu is (*window).contextMenu once LinkContextMenus linked
// it.
var showContextMenu func(w *window, menu, ev id)
// LinkContextMenus links the code of pages' context menus, when the app
// first listens to them (Page.OnContextMenu).
func LinkContextMenus() { showContextMenu = (*window).contextMenu }
// webKitMenu reports whether menu is WebKit's context menu, rather than a
// menu of the app's popped up over the web view (Menu.Popup): an item of
// it does what WebKit does, or bears one of its identifiers.
func webKitMenu(menu id) bool {
forward := sel("forwardContextMenuAction:")
for i := range sendInt(menu, "numberOfItems") {
item := send(menu, "itemAtIndex:", uintptr(i))
if objc.SEL(send(item, "action")) == forward || strings.HasPrefix(itemIdentifier(item), "WKMenuItemIdentifier") {
return true
}
}
return false
}
func itemIdentifier(item id) string {
if !respondsTo(item, "identifier") {
return ""
}
return goString(send(item, "identifier"))
}
// contextMenu asks the core about the menu WebKit is about to show, and
// changes it as the core answers.
func (w *window) contextMenu(menu, ev id) {
if !webKitMenu(menu) {
return
}
var natives []id
defer func() {
for _, item := range natives {
release(item)
}
}()
m := &platform.ContextMenu{Items: describeContextMenu(menu, &natives)}
// The event that opened the menu: a right or Control-click, at a point
// of the window, which the page's contextmenu event tells in CSS
// pixels from the web view's top-left corner.
if ev != 0 {
switch sendInt(ev, "type") {
case 1, 2, 3, 4, 25, 26: // NSEventTypeLeftMouseDown to RightMouseUp, OtherMouseDown and Up
p := msgPointFromView(w.web, sel("convertPoint:fromView:"), msgPoint(ev, sel("locationInWindow")), 0)
if !sendBool(w.web, "isFlipped") {
p.Y = msgRect(w.web, sel("bounds")).Size.Height - p.Y
}
m.Pointer, m.X, m.Y = true, p.X, p.Y
}
}
resp := w.h.ContextMenu(m)
if resp.Default {
openContextMenu = menu
return
}
if contextOwner != 0 {
dropOwner(contextOwner)
}
contextWindow, contextOwner = w, newOwner()
c := contextFill{w: w, natives: natives, was: map[int]*platform.MenuItem{}}
c.index(m.Items)
send(menu, "removeAllItems")
if resp.Menu != nil {
c.fill(menu, resp.Menu.Items)
}
if sendInt(menu, "numberOfItems") > 0 {
openContextMenu = menu
return
}
// An empty menu shows nothing, but AppKit still tracks it, and WebKit
// pops up no other until it closed: it closes once its tracking began.
retain(menu)
theBackend.post(func() {
send(menu, "cancelTrackingWithoutAnimation")
release(menu)
})
}
// describeContextMenu describes WebKit's items of menu and its submenus,
// numbering each, and retains it in natives, which keeps it while the
// menus are emptied and filled again.
func describeContextMenu(menu id, natives *[]id) []*platform.MenuItem {
n := sendInt(menu, "numberOfItems")
items := make([]*platform.MenuItem, 0, n)
for i := range n {
item := send(menu, "itemAtIndex:", uintptr(i))
*natives = append(*natives, retain(item))
it := &platform.MenuItem{Native: len(*natives), Enabled: sendBool(item, "isEnabled"), Visible: !sendBool(item, "isHidden")}
items = append(items, it)
if sendBool(item, "isSeparatorItem") {
it.Type = platform.MenuItemSeparator
continue
}
it.Label = goString(send(item, "title"))
it.Name = contextItemName(item)
if sendInt(item, "state") == 1 { // NSControlStateValueOn
it.Type, it.Checked = platform.MenuItemCheckbox, true
}
if sub := send(item, "submenu"); sub != 0 {
it.Type, it.Submenu = platform.MenuItemSubmenu, &platform.Menu{Items: describeContextMenu(sub, natives)}
}
}
return items
}
// contextIdentifiers are MyGo's names of the items WebKit identifies
// (WKMenuItemIdentifiers.h, macOS 11) that other platforms have too.
var contextIdentifiers = map[string]string{
"WKMenuItemIdentifierCopy": "copy",
"WKMenuItemIdentifierCopyImage": "copyImage",
"WKMenuItemIdentifierCopyLink": "copyLink",
"WKMenuItemIdentifierCopyMediaLink": "copyMediaURL",
"WKMenuItemIdentifierDownloadImage": "downloadImage",
"WKMenuItemIdentifierDownloadLinkedFile": "downloadLink",
"WKMenuItemIdentifierDownloadMedia": "downloadMedia",
"WKMenuItemIdentifierGoBack": "back",
"WKMenuItemIdentifierGoForward": "forward",
"WKMenuItemIdentifierInspectElement": "inspect",
"WKMenuItemIdentifierLookUp": "lookUp",
"WKMenuItemIdentifierOpenFrameInNewWindow": "openFrameInNewWindow",
"WKMenuItemIdentifierOpenImageInNewWindow": "openImageInNewWindow",
"WKMenuItemIdentifierOpenLink": "openLink",
"WKMenuItemIdentifierOpenLinkInNewWindow": "openLinkInNewWindow",
"WKMenuItemIdentifierOpenMediaInNewWindow": "openMediaInNewWindow",
"WKMenuItemIdentifierPaste": "paste",
"WKMenuItemIdentifierReload": "reload",
"WKMenuItemIdentifierSearchWeb": "searchWeb",
"WKMenuItemIdentifierShowHideMediaControls": "mediaControls",
"WKMenuItemIdentifierToggleFullScreen": "mediaFullScreen",
"WKMenuItemIdentifierShareMenu": "share",
}
// contextTags name WebKit's items without an identifier by their tags,
// WebCore's ContextMenuAction values, which hold for the first of them.
var contextTags = [...]string{
1: "openLinkInNewWindow", 2: "downloadLink", 3: "copyLink", 4: "openImageInNewWindow", 5: "downloadImage",
6: "copyImage", 7: "openFrameInNewWindow", 8: "copy", 9: "back", 10: "forward", 11: "stop", 12: "reload",
13: "cut", 14: "paste", 15: "spellingGuess", 21: "searchWeb", 22: "lookUp",
}
// contextSelectors name AppKit's items by their actions, as the editing
// items of a text field's menu.
var contextSelectors = map[string]string{
"cut:": "cut", "copy:": "copy", "paste:": "paste", "pasteAsPlainText:": "pasteAndMatchStyle",
"delete:": "delete", "selectAll:": "selectAll", "undo:": "undo", "redo:": "redo",
}
// contextItemName names an item of WebKit's menu: MyGo's name for the
// items other platforms have, else WebKit's identifier, "" for an item
// that has none.
func contextItemName(item id) string {
ident := itemIdentifier(item)
if name, ok := contextIdentifiers[ident]; ok {
return name
}
// AppKit names an item WebKit gave no identifier by its action, as
// "forwardContextMenuAction:", which tells nothing.
if strings.HasPrefix(ident, "WKMenuItemIdentifier") {
return ident
}
action := objc.SEL(send(item, "action"))
if action == 0 {
return ""
}
if action == sel("forwardContextMenuAction:") {
if tag := sendInt(item, "tag"); tag > 0 && tag < len(contextTags) {
return contextTags[tag]
}
return ""
}
for s, name := range contextSelectors {
if action == sel(s) {
return name
}
}
return ""
}
// contextFill fills a context menu as the core answered.
type contextFill struct {
w *window
natives []id
// was describes WebKit's items as they were, by number.
was map[int]*platform.MenuItem
}
func (c *contextFill) index(items []*platform.MenuItem) {
for _, it := range items {
c.was[it.Native] = it
if it.Submenu != nil {
c.index(it.Submenu.Items)
}
}
}
// fill adds items to menu, emptied: WebKit's, as the core changed them,
// and the app's.
func (c *contextFill) fill(menu id, items []*platform.MenuItem) {
for _, it := range items {
if !it.Visible {
continue
}
if it.Native != 0 && it.Native <= len(c.natives) {
send(menu, "addItem:", uintptr(c.native(c.natives[it.Native-1], it)))
} else {
send(menu, "addItem:", uintptr(c.app(it)))
}
}
}
// native gives WebKit's item the label, the state and the submenu the
// core gave it. A submenu left as it was is not filled again, which keeps
// those AppKit fills as they open, as Services.
func (c *contextFill) native(item id, it *platform.MenuItem) id {
was := c.was[it.Native]
if it.Type == platform.MenuItemSeparator || was == nil {
return item
}
if it.Label != was.Label {
send(item, "setTitle:", uintptr(nsString(it.Label)))
}
send(item, "setEnabled:", boolArg(it.Enabled))
if it.Checked != was.Checked {
send(item, "setState:", boolArg(it.Checked))
}
if it.Accelerator != was.Accelerator {
key, mods := keyEquivalent(it.Accelerator)
send(item, "setKeyEquivalent:", uintptr(nsString(key)))
send(item, "setKeyEquivalentModifierMask:", uintptr(mods))
}
if sub := send(item, "submenu"); sub != 0 && it.Submenu != nil && was.Submenu != nil && !c.unchanged(it.Submenu.Items, was.Submenu.Items) {
send(sub, "removeAllItems")
c.fill(sub, it.Submenu.Items)
}
return item
}
// unchanged reports whether a submenu holds WebKit's items as they were.
func (c *contextFill) unchanged(items, was []*platform.MenuItem) bool {
if len(items) != len(was) {
return false
}
for i, it := range items {
w := was[i]
if it.Native == 0 || it.Native != w.Native || !it.Visible || it.Label != w.Label || it.Enabled != w.Enabled ||
it.Checked != w.Checked || it.Accelerator != w.Accelerator || (it.Submenu == nil) != (w.Submenu == nil) {
return false
}
if it.Submenu != nil && !c.unchanged(it.Submenu.Items, w.Submenu.Items) {
return false
}
}
return true
}
// app makes an item of the app's, as its other menus' (buildItem), whose
// choice the window's handler hears.
func (c *contextFill) app(it *platform.MenuItem) id {
if it.Type == platform.MenuItemSeparator {
item := send(class("NSMenuItem"), "separatorItem")
track(contextOwner, it.ID, item)
return item
}
plain := *it
plain.Submenu = nil
item := theBackend.buildItem(&plain, contextOwner, menuMetrics{})
if it.Submenu != nil {
sub := autorelease(send(send(class("NSMenu"), "alloc"), "initWithTitle:", uintptr(nsString(it.Label))))
send(sub, "setAutoenablesItems:", 0)
c.fill(sub, it.Submenu.Items)
send(item, "setAction:", 0)
send(item, "setTarget:", 0)
send(item, "setSubmenu:", uintptr(sub))
} else if objc.SEL(send(item, "action")) == sel("mygoMenuItemClicked:") {
send(item, "setAction:", uintptr(sel("mygoContextItemClicked:")))
}
return item
}
// contextItemClicked reports an item of the app's chosen from a page's
// context menu to its window.
func contextItemClicked(self id, _ objc.SEL, item id) {
if w := contextWindow; w != nil && !w.closed {
w.h.MenuItemClicked(sendInt(item, "tag"))
}
}
+185
View File
@@ -0,0 +1,185 @@
//go:build darwin && !ios
package darwin
import (
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
// cookieStore returns the WKHTTPCookieStore of store, nil for the
// default one.
func cookieStore(s platform.DataStore) (id, error) {
store := websiteDataStore(s)
if !sendBool(store, "respondsToSelector:", uintptr(sel("httpCookieStore"))) || !sendBool(class("NSHTTPCookie"), "instancesRespondToSelector:", uintptr(sel("sameSitePolicy"))) {
return 0, fmt.Errorf("mygo: cookies: requires macOS 10.15 or newer: %w", platform.ErrUnsupported)
}
return send(store, "httpCookieStore"), nil
}
func readCookie(c id) platform.Cookie {
out := platform.Cookie{Name: goString(send(c, "name")), Value: goString(send(c, "value")), Domain: strings.ToLower(goString(send(c, "domain"))), Path: goString(send(c, "path")), Secure: sendBool(c, "isSecure"), HTTPOnly: sendBool(c, "isHTTPOnly")}
// Foundation names only Lax and Strict, and macOS 26 gives a cookie
// set with SameSite=None no policy, which WebKit sends as None
// (coreSameSitePolicy in CookieCocoa.mm).
out.SameSite = strings.ToLower(goString(send(c, "sameSitePolicy")))
if out.SameSite == "" {
out.SameSite = "none"
}
date := send(c, "expiresDate")
if date != 0 && !sendBool(c, "isSessionOnly") {
out.Expires = time.Unix(int64(msgFloat(date, sel("timeIntervalSince1970"))), 0).UTC()
}
return out
}
// ListCookies lists every cookie, and matches them with the URL in Go:
// WKHTTPCookieStore cannot.
func (a appController) ListCookies(s platform.DataStore, rawURL string, done func([]platform.Cookie, error)) {
var u *url.URL
if rawURL != "" {
var err error
if u, err = url.Parse(rawURL); err != nil {
done(nil, err)
return
}
}
withPool(func() {
store, err := cookieStore(s)
if err != nil {
done(nil, err)
return
}
block := newBlock(func(_ objc.Block, array id) {
var result []platform.Cookie
withPool(func() {
for _, c := range arrayItems(array) {
if c := readCookie(c); u == nil || platform.CookieMatchesURL(c, u) {
result = append(result, c)
}
}
})
a.b.runOnMain(func() { done(result, nil) })
})
send(store, "getAllCookies:", uintptr(block))
block.Release()
})
}
func (a appController) SetCookie(s platform.DataStore, c platform.Cookie, done func(error)) {
withPool(func() {
store, err := cookieStore(s)
if err != nil {
done(err)
return
}
host := strings.TrimPrefix(c.Domain, ".")
if strings.Contains(host, ":") {
host = "[" + host + "]"
}
scheme := "http"
if c.Secure {
scheme = "https"
}
// Foundation parses the attributes, with a stand-in name and value:
// it would split a value with ", " in it as two cookies.
header := "n=v; Path=" + c.Path + "; SameSite=" + c.SameSite
if strings.HasPrefix(c.Domain, ".") {
header += "; Domain=" + c.Domain
}
if !c.Expires.IsZero() {
header += "; Expires=" + c.Expires.Format(http.TimeFormat)
}
if c.Secure {
header += "; Secure"
}
if c.HTTPOnly {
header += "; HttpOnly"
}
headers := send(class("NSDictionary"), "dictionaryWithObject:forKey:", uintptr(nsString(header)), uintptr(nsString("Set-Cookie")))
array := send(class("NSHTTPCookie"), "cookiesWithResponseHeaderFields:forURL:", uintptr(headers), uintptr(nsURL(scheme+"://"+host+"/")))
if sendInt(array, "count") != 1 {
done(fmt.Errorf("mygo: cookies: Set could not construct NSHTTPCookie"))
return
}
props := send(send(send(array, "objectAtIndex:", 0), "properties"), "mutableCopy")
send(props, "setObject:forKey:", uintptr(nsString(c.Name)), uintptr(constString(libFoundation, "NSHTTPCookieName")))
send(props, "setObject:forKey:", uintptr(nsString(c.Value)), uintptr(constString(libFoundation, "NSHTTPCookieValue")))
native := send(class("NSHTTPCookie"), "cookieWithProperties:", uintptr(props))
release(props)
if native == 0 {
done(fmt.Errorf("mygo: cookies: Set could not construct NSHTTPCookie"))
return
}
parsed := readCookie(native)
if parsed.Name != c.Name || parsed.Domain != c.Domain || parsed.Path != c.Path || parsed.Value != c.Value || parsed.Secure != c.Secure || parsed.HTTPOnly != c.HTTPOnly || parsed.SameSite != c.SameSite {
// Say what differs, without the value.
parsed.Value, c.Value = "", ""
done(fmt.Errorf("mygo: cookies: Set made NSHTTPCookie %+v of %+v", parsed, c))
return
}
block := newBlock(func(objc.Block) { a.b.runOnMain(func() { done(nil) }) })
send(store, "setCookie:completionHandler:", uintptr(native), uintptr(block))
block.Release()
})
}
func (a appController) DeleteCookie(s platform.DataStore, key platform.CookieKey, done func(error)) {
withPool(func() {
store, err := cookieStore(s)
if err != nil {
done(err)
return
}
retain(store)
block := newBlock(func(_ objc.Block, array id) {
// The borrowed array must survive dispatch to main.
retain(array)
a.b.runOnMain(func() {
withPool(func() {
defer release(array)
var match id
for _, c := range arrayItems(array) {
if goString(send(c, "name")) == key.Name && strings.ToLower(goString(send(c, "domain"))) == key.Domain && goString(send(c, "path")) == key.Path {
if match != 0 {
release(store)
done(fmt.Errorf("mygo: cookies: ambiguous cookie key"))
return
}
match = c
}
}
if match == 0 {
release(store)
done(nil)
return
}
retain(match)
completion := newBlock(func(objc.Block) { a.b.runOnMain(func() { release(match); release(store); done(nil) }) })
send(store, "deleteCookie:completionHandler:", uintptr(match), uintptr(completion))
completion.Release()
})
})
})
send(store, "getAllCookies:", uintptr(block))
block.Release()
})
}
// ClearCookies removes the cookies of the data store, its other data
// kept.
func (a appController) ClearCookies(s platform.DataStore, done func(error)) {
var err error
withPool(func() { _, err = cookieStore(s) })
if err != nil {
done(err)
return
}
a.removeData(s, platform.SiteDataCookies, done)
}
+39
View File
@@ -0,0 +1,39 @@
//go:build darwin && !ios
package darwin
import (
"testing"
"github.com/egoist/mygo/internal/platform"
)
// TestCursors gives every cursor an NSCursor: AppKit's own, a private
// one, or the nearest public one where macOS lacks it.
func TestCursors(t *testing.T) {
load()
withPool(func() {
arrow := send(class("NSCursor"), "arrowCursor")
// Without a window server, as over SSH, AppKit gives no arrow or
// I-beam, which it draws from the system's cursors: the others
// must still come, and none may raise (_moveCursor did).
server := arrow != 0
if !server {
t.Log("no window server: the arrow and the I-beam are nil")
}
for c := platform.CursorDefault; c <= platform.CursorNoDrop; c++ {
cur := nsCursor(c)
if cur == 0 && (server || c != platform.CursorDefault && c != platform.CursorText) {
t.Errorf("cursor %d: no NSCursor", c)
}
if c != platform.CursorDefault && cur == arrow {
t.Logf("cursor %d: the arrow (macOS has none of its own)", c)
}
}
for _, c := range []platform.Cursor{platform.CursorNoDrop, platform.CursorCell, platform.CursorAllScroll} {
if nsCursor(c) == arrow {
t.Errorf("cursor %d is the arrow, though its fallback is public", c)
}
}
})
}
+59
View File
@@ -0,0 +1,59 @@
//go:build darwin && !ios
package darwin
import (
"fmt"
"strings"
"github.com/egoist/mygo/internal/platform"
)
// The URL schemes of a bundle are declared in its Info.plist
// (CFBundleURLTypes), which Launch Services registers. What an app can do
// at run time is become the default handler of one of them.
func (a appController) RegisterURLScheme(scheme, id, name string) error {
var err error
withPool(func() {
bundle := send(class("NSBundle"), "mainBundle")
if !declaresScheme(bundle, scheme) {
err = fmt.Errorf("mygo: the app does not declare the URL scheme %q: list it in urlSchemes in mygo.config.ts", scheme)
return
}
if status := lsSetDefaultHandlerForURLScheme(nsString(scheme), send(bundle, "bundleIdentifier")); status != 0 {
err = fmt.Errorf("mygo: cannot handle the URL scheme %q (Launch Services error %d)", scheme, status)
}
})
return err
}
// UnregisterURLScheme is not supported: the scheme belongs to the bundle.
func (a appController) UnregisterURLScheme(string, string, string) error {
return platform.ErrUnsupported
}
func (a appController) IsURLSchemeRegistered(scheme, id, name string) bool {
ok := false
withPool(func() {
handler := lsCopyDefaultHandlerForURLScheme(nsString(scheme))
if handler == 0 {
return
}
defer cfRelease(uintptr(handler))
ok = strings.EqualFold(goString(handler), goString(send(send(class("NSBundle"), "mainBundle"), "bundleIdentifier")))
})
return ok
}
// declaresScheme reports whether the Info.plist of bundle lists scheme.
func declaresScheme(bundle id, scheme string) bool {
for _, t := range arrayItems(send(bundle, "objectForInfoDictionaryKey:", uintptr(nsString("CFBundleURLTypes")))) {
for _, s := range arrayItems(send(t, "objectForKey:", uintptr(nsString("CFBundleURLSchemes")))) {
if strings.EqualFold(goString(s), scheme) {
return true
}
}
}
return false
}
+343
View File
@@ -0,0 +1,343 @@
//go:build darwin && !ios
package darwin
import (
"os"
"path/filepath"
"strings"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
type dialogs struct{ b *Backend }
const nsModalResponseOK = 1
// runPanel shows a panel or alert as a sheet of parent when possible, else
// application modal, and calls done with the modal response.
func runPanel(obj id, parent *window, sheetSel string, done func(resp int)) {
if parent != nil && !parent.closed && sendBool(parent.win, "isVisible") { // not in the Dock
retain(obj)
blk := newBlock(func(_ objc.Block, resp int) {
withPool(func() { done(resp) })
release(obj)
})
send(obj, sheetSel, uintptr(parent.win), uintptr(blk))
blk.Release()
return
}
send(theBackend.app, "activateIgnoringOtherApps:", 1)
done(sendInt(obj, "runModal"))
if b := theBackend; b.quitAfterModal {
b.quitAfterModal = false
b.Quit()
}
}
func asWindow(pw platform.Window) *window {
w, _ := pw.(*window)
return w
}
// setupSavePanel applies the options shared by open and save panels.
func setupSavePanel(panel id, title, message, button, defaultPath string, filters []platform.FileFilter, hidden, mkdir, packages bool) {
if title != "" {
send(panel, "setTitle:", uintptr(nsString(title)))
}
if message != "" {
send(panel, "setMessage:", uintptr(nsString(message)))
}
if button != "" {
send(panel, "setPrompt:", uintptr(nsString(button)))
}
send(panel, "setShowsHiddenFiles:", boolArg(hidden))
send(panel, "setCanCreateDirectories:", boolArg(mkdir))
send(panel, "setTreatsFilePackagesAsDirectories:", boolArg(packages))
if defaultPath != "" {
if st, err := os.Stat(defaultPath); err == nil && st.IsDir() {
send(panel, "setDirectoryURL:", uintptr(fileURL(defaultPath)))
} else {
send(panel, "setDirectoryURL:", uintptr(fileURL(filepath.Dir(defaultPath))))
send(panel, "setNameFieldStringValue:", uintptr(nsString(filepath.Base(defaultPath))))
}
}
var exts, mimes []string
for _, f := range filters {
for _, e := range f.Extensions {
if e == "*" {
return
}
exts = append(exts, strings.TrimPrefix(e, "."))
}
for _, m := range f.MIMETypes {
if m == "*/*" || m == "*" {
return
}
mimes = append(mimes, strings.ToLower(m))
}
}
if len(exts) == 0 && len(mimes) == 0 {
return
}
if hasClass("UTType") {
var types []id
for _, e := range exts {
if t := send(class("UTType"), "typeWithFilenameExtension:", uintptr(nsString(e))); t != 0 {
types = append(types, t)
}
}
for _, m := range mimes {
var t id
if kind := mimeKinds[m]; kind != "" {
t = send(class("UTType"), "typeWithIdentifier:", uintptr(nsString(kind)))
} else {
t = send(class("UTType"), "typeWithMIMEType:", uintptr(nsString(m)))
}
if t != 0 {
types = append(types, t)
}
}
send(panel, "setAllowedContentTypes:", uintptr(nsArray(types...)))
return
}
// Before macOS 11, file types are extensions or identifiers of types:
// those of the kinds of MIME types.
var names []id
for _, e := range exts {
names = append(names, nsString(e))
}
for _, m := range mimes {
if kind := mimeKinds[m]; kind != "" {
names = append(names, nsString(kind))
}
}
if len(names) > 0 {
send(panel, "setAllowedFileTypes:", uintptr(nsArray(names...)))
}
}
// mimeKinds are the types of files (UTTypes) that MIME types of a kind
// are, as WebKit takes them for an input's accept.
var mimeKinds = map[string]string{
"image/*": "public.image",
"audio/*": "public.audio",
"video/*": "public.movie",
"text/*": "public.text",
"font/*": "public.font",
}
func (d dialogs) ShowOpenDialog(parent platform.Window, o *platform.OpenDialogOptions, cb func([]string, error)) {
withPool(func() {
panel := send(class("NSOpenPanel"), "openPanel")
send(panel, "setCanChooseFiles:", boolArg(o.OpenFiles))
send(panel, "setCanChooseDirectories:", boolArg(o.OpenDirectories))
send(panel, "setAllowsMultipleSelection:", boolArg(o.Multiple))
setupSavePanel(panel, o.Title, o.Message, o.ButtonLabel, o.DefaultPath, o.Filters,
o.ShowHiddenFiles, o.CreateDirectories, o.TreatPackagesAsDirectories)
runPanel(panel, asWindow(parent), "beginSheetModalForWindow:completionHandler:", func(resp int) {
if resp != nsModalResponseOK {
cb(nil, nil)
return
}
var paths []string
for _, u := range arrayItems(send(panel, "URLs")) {
paths = append(paths, goString(send(u, "path")))
}
cb(paths, nil)
})
})
}
func (d dialogs) ShowSaveDialog(parent platform.Window, o *platform.SaveDialogOptions, cb func(string, error)) {
withPool(func() {
panel := send(class("NSSavePanel"), "savePanel")
if o.NameFieldLabel != "" {
send(panel, "setNameFieldLabel:", uintptr(nsString(o.NameFieldLabel)))
}
setupSavePanel(panel, o.Title, o.Message, o.ButtonLabel, o.DefaultPath, o.Filters,
o.ShowHiddenFiles, o.CreateDirectories, o.TreatPackagesAsDirectories)
runPanel(panel, asWindow(parent), "beginSheetModalForWindow:completionHandler:", func(resp int) {
if resp != nsModalResponseOK {
cb("", nil)
return
}
cb(goString(send(send(panel, "URL"), "path")), nil)
})
})
}
const nsAlertFirstButtonReturn = 1000
func newAlert(kind, message, detail string, buttons []string, defaultID int, destructive []int) id {
alert := autorelease(alloc("NSAlert"))
style := uintptr(1) // NSAlertStyleInformational
switch kind {
case "warning":
style = 0
case "error":
style = 2
}
send(alert, "setAlertStyle:", style)
send(alert, "setMessageText:", uintptr(nsString(message)))
if detail != "" {
send(alert, "setInformativeText:", uintptr(nsString(detail)))
}
for _, b := range buttons {
send(alert, "addButtonWithTitle:", uintptr(nsString(b)))
}
items := arrayItems(send(alert, "buttons"))
for i, btn := range items {
key := ""
if i == defaultID {
key = "\r"
}
send(btn, "setKeyEquivalent:", uintptr(nsString(key)))
}
for _, i := range destructive {
if i >= 0 && i < len(items) && respondsTo(items[i], "setHasDestructiveAction:") {
send(items[i], "setHasDestructiveAction:", 1)
}
}
return alert
}
// alertKeys handles Escape and Cmd+. because a button has only one key
// equivalent, already used by Return when cancel is the default.
// The monitor is made once, with the first cancelable alert.
var alertKeys id
// alertCancels maps the window of each alert showing to its cancel
// button. Main thread only.
var alertCancels = map[id]id{}
func runAlert(alert id, parent *window, cancelID int, done func(resp int)) {
win := send(alert, "window")
if items := arrayItems(send(alert, "buttons")); cancelID >= 0 && cancelID < len(items) {
alertCancels[win] = items[cancelID]
watchAlertKeys()
}
runPanel(alert, parent, "beginSheetModalForWindow:completionHandler:", func(resp int) {
delete(alertCancels, win)
done(resp)
})
}
func watchAlertKeys() {
if alertKeys != 0 {
return
}
const mask = 1 << 10 // NSEventMaskKeyDown
blk := newBlock(func(_ objc.Block, ev id) id {
win := send(ev, "window")
btn := alertCancels[win]
if btn == 0 {
return ev
}
// A key typed while the input method composes in a prompt's field
// is the input method's, as Escape giving the composition up.
if field := send(win, "firstResponder"); respondsTo(field, "hasMarkedText") && sendBool(field, "hasMarkedText") {
return ev
}
// Shift may type the period, as on AZERTY, which AppKit's key
// bindings allow.
mods, chars := eventMods(ev), goString(send(ev, "charactersIgnoringModifiers"))
if mods == 0 && chars == "\x1b" || mods&^platform.ModShift == platform.ModSuper && chars == "." {
send(btn, "performClick:", 0)
return 0
}
return ev
})
alertKeys = retain(send(class("NSEvent"), "addLocalMonitorForEventsMatchingMask:handler:", mask, uintptr(blk)))
}
func (d dialogs) ShowMessageBox(parent platform.Window, o *platform.MessageBoxOptions, cb func(platform.MessageBoxResult, error)) {
withPool(func() {
message, detail := o.Message, o.Detail
if message == "" {
message, detail = o.Title, o.Detail
}
alert := newAlert(o.Type, message, detail, o.Buttons, o.DefaultID, o.DestructiveIDs)
if o.CheckboxLabel != "" {
send(alert, "setShowsSuppressionButton:", 1)
btn := send(alert, "suppressionButton")
send(btn, "setTitle:", uintptr(nsString(o.CheckboxLabel)))
send(btn, "setState:", boolArg(o.CheckboxChecked))
}
runAlert(alert, asWindow(parent), o.CancelID, func(resp int) {
res := platform.MessageBoxResult{Response: resp - nsAlertFirstButtonReturn}
if o.CheckboxLabel != "" {
res.CheckboxChecked = sendInt(send(alert, "suppressionButton"), "state") == 1
}
cb(res, nil)
})
})
}
// JavaScript panels requested by WKUIDelegate. The completion handler block
// must be called exactly once.
func jsAlert(w *window, message string, handler uintptr) {
handler = blockCopy(handler)
withPool(func() {
alert := newAlert("info", message, "", []string{platform.CurrentTexts().OK}, 0, nil)
runAlert(alert, w, 0, func(int) {
callBlock(handler)
blockRelease(handler)
})
})
}
func jsConfirm(w *window, message string, handler uintptr) {
handler = blockCopy(handler)
withPool(func() {
tx := platform.CurrentTexts()
alert := newAlert("info", message, "", []string{tx.OK, tx.Cancel}, 0, nil)
runAlert(alert, w, 1, func(resp int) {
callBlock(handler, boolArg(resp == nsAlertFirstButtonReturn))
blockRelease(handler)
})
})
}
func jsPrompt(w *window, prompt, defaultText string, handler uintptr) {
handler = blockCopy(handler)
withPool(func() {
tx := platform.CurrentTexts()
alert := newAlert("info", prompt, "", []string{tx.OK, tx.Cancel}, 0, nil)
field := autorelease(msgInitRect(send(class("NSTextField"), "alloc"), sel("initWithFrame:"), NSRect{Size: NSSize{280, 24}}))
send(field, "setStringValue:", uintptr(nsString(defaultText)))
send(alert, "setAccessoryView:", uintptr(field))
send(send(alert, "window"), "setInitialFirstResponder:", uintptr(field))
runAlert(alert, w, 1, func(resp int) {
var result id
if resp == nsAlertFirstButtonReturn {
result = send(field, "stringValue")
}
callBlock(handler, uintptr(result))
blockRelease(handler)
})
})
}
func jsFileInput(w *window, params id, handler uintptr) {
handler = blockCopy(handler)
withPool(func() {
panel := send(class("NSOpenPanel"), "openPanel")
send(panel, "setCanChooseFiles:", 1)
send(panel, "setAllowsMultipleSelection:", boolArg(sendBool(params, "allowsMultipleSelection")))
if respondsTo(params, "allowsDirectories") {
send(panel, "setCanChooseDirectories:", boolArg(sendBool(params, "allowsDirectories")))
}
runPanel(panel, w, "beginSheetModalForWindow:completionHandler:", func(resp int) {
var urls id
if resp == nsModalResponseOK {
urls = send(panel, "URLs")
}
callBlock(handler, uintptr(urls))
blockRelease(handler)
})
})
}
+68
View File
@@ -0,0 +1,68 @@
//go:build darwin && !ios
package darwin
import "github.com/egoist/mygo/internal/platform"
// The Dock tile shows progress (Window.SetProgressBar) under the app icon.
// NSProgressIndicator does not draw in a Dock tile, which renders its
// content view offscreen, so the bar is made of two custom NSBoxes, which
// draw themselves.
type dockProgress struct {
view, icon, track, fill id
}
func (b *Backend) setDockProgress(state string, value float64) {
withPool(func() { b.updateDockProgress(state, value) })
}
func (b *Backend) updateDockProgress(state string, value float64) {
tile := send(b.app, "dockTile")
p := &b.dockProgress
if state == "" {
if p.view != 0 {
send(tile, "setContentView:", 0)
for _, v := range []id{p.view, p.icon, p.track, p.fill} {
release(v)
}
*p = dockProgress{}
send(tile, "display")
}
return
}
size := msgSize(tile, sel("size"))
const height, inset = 14.0, 6.0
if p.view == 0 {
frame := NSRect{Size: size}
p.view = alloc("NSView")
msgSetRect(p.view, sel("setFrame:"), frame)
p.icon = alloc("NSImageView")
msgSetRect(p.icon, sel("setFrame:"), frame)
send(p.view, "addSubview:", uintptr(p.icon))
box := func(fill, border platform.Color, width float64) id {
v := alloc("NSBox")
send(v, "setBoxType:", 4) // NSBoxCustom
send(v, "setTitlePosition:", 0) // NSNoTitle
send(v, "setFillColor:", uintptr(nsColor(fill)))
send(v, "setBorderColor:", uintptr(nsColor(border)))
msgSetFloat(v, sel("setBorderWidth:"), width)
msgSetFloat(v, sel("setCornerRadius:"), height/2)
send(p.view, "addSubview:", uintptr(v))
return v
}
p.track = box(platform.Color{R: 40, G: 40, B: 40, A: 200}, platform.Color{R: 160, G: 160, B: 160, A: 255}, 1.5)
p.fill = box(platform.Color{R: 51, G: 153, B: 255, A: 255}, platform.Color{R: 51, G: 153, B: 255, A: 255}, 0)
send(tile, "setContentView:", uintptr(p.view))
}
send(p.icon, "setImage:", uintptr(send(b.app, "applicationIconImage")))
track := NSRect{Origin: NSPoint{inset, inset}, Size: NSSize{size.Width - 2*inset, height}}
msgSetRect(p.track, sel("setFrame:"), track)
if state == "indeterminate" {
value = 1
}
fill := track
fill.Size.Width = max(height, track.Size.Width*value)
send(p.fill, "setHidden:", boolArg(value <= 0))
msgSetRect(p.fill, sel("setFrame:"), fill)
send(tile, "display")
}
+107
View File
@@ -0,0 +1,107 @@
//go:build darwin && !ios
package darwin
import (
"fmt"
"unsafe"
"github.com/ebitengine/purego"
"github.com/egoist/mygo/internal/accelerator"
)
// Global shortcuts use Carbon's RegisterEventHotKey, which needs no
// accessibility permission.
const (
hotKeySignature = 0x4D79476F // 'MyGo'
kEventClassKeyboard = 0x6B657962 // 'keyb'
kEventHotKeyPressed = 5
kEventParamDirectObject = 0x2D2D2D2D // '----'
typeEventHotKeyID = 0x686B6964 // 'hkid'
carbonCmd = 1 << 8
carbonShift = 1 << 9
carbonOption = 1 << 11
carbonControl = 1 << 12
)
// keyCodes maps accelerator keys to macOS virtual key codes (ANSI layout).
var keyCodes = map[string]uint32{
"a": 0x00, "s": 0x01, "d": 0x02, "f": 0x03, "h": 0x04, "g": 0x05, "z": 0x06, "x": 0x07,
"c": 0x08, "v": 0x09, "b": 0x0B, "q": 0x0C, "w": 0x0D, "e": 0x0E, "r": 0x0F, "y": 0x10,
"t": 0x11, "1": 0x12, "2": 0x13, "3": 0x14, "4": 0x15, "6": 0x16, "5": 0x17, "=": 0x18,
"9": 0x19, "7": 0x1A, "-": 0x1B, "8": 0x1C, "0": 0x1D, "]": 0x1E, "o": 0x1F, "u": 0x20,
"[": 0x21, "i": 0x22, "p": 0x23, "l": 0x25, "j": 0x26, "'": 0x27, "k": 0x28, ";": 0x29,
"\\": 0x2A, ",": 0x2B, "/": 0x2C, "n": 0x2D, "m": 0x2E, ".": 0x2F, "`": 0x32,
"Enter": 0x24, "Tab": 0x30, "Space": 0x31, "Backspace": 0x33, "Escape": 0x35,
"Delete": 0x75, "Home": 0x73, "End": 0x77, "PageUp": 0x74, "PageDown": 0x79, "Insert": 0x72,
"Left": 0x7B, "Right": 0x7C, "Down": 0x7D, "Up": 0x7E,
"F1": 0x7A, "F2": 0x78, "F3": 0x63, "F4": 0x76, "F5": 0x60, "F6": 0x61, "F7": 0x62, "F8": 0x64,
"F9": 0x65, "F10": 0x6D, "F11": 0x67, "F12": 0x6F, "F13": 0x69, "F14": 0x6B, "F15": 0x71,
"F16": 0x6A, "F17": 0x40, "F18": 0x4F, "F19": 0x50, "F20": 0x5A,
"VolumeUp": 0x48, "VolumeDown": 0x49, "VolumeMute": 0x4A,
"Num0": 0x52, "Num1": 0x53, "Num2": 0x54, "Num3": 0x55, "Num4": 0x56, "Num5": 0x57,
"Num6": 0x58, "Num7": 0x59, "Num8": 0x5B, "Num9": 0x5C, "NumDec": 0x41, "NumMult": 0x43,
"NumAdd": 0x45, "NumDiv": 0x4B, "NumSub": 0x4E,
}
var hotKeyHandler = purego.NewCallback(func(next, event, userData uintptr) uintptr {
var hk eventHotKeyID
if getEventParameter(event, kEventParamDirectObject, typeEventHotKeyID, 0, unsafe.Sizeof(hk), 0, unsafe.Pointer(&hk)) == 0 {
theBackend.h.HotkeyPressed(int(hk.ID))
}
return 0
})
func (b *Backend) RegisterHotkey(hid int, acc, _ string) error {
a, err := accelerator.Parse(acc, "darwin")
if err != nil {
return err
}
key := a.Key
mods := uint32(0)
if key == "+" {
key = "="
mods |= carbonShift
}
code, ok := keyCodes[key]
if !ok {
return fmt.Errorf("mygo: key %q cannot be used in a global shortcut", a.Key)
}
if a.Has(accelerator.Super) {
mods |= carbonCmd
}
if a.Has(accelerator.Ctrl) {
mods |= carbonControl
}
if a.Has(accelerator.Alt) {
mods |= carbonOption
}
if a.Has(accelerator.Shift) {
mods |= carbonShift
}
if !b.hkInstalled {
spec := eventTypeSpec{Class: kEventClassKeyboard, Kind: kEventHotKeyPressed}
var ref uintptr
if st := installEventHandler(getApplicationEventTarget(), hotKeyHandler, 1, &spec, 0, &ref); st != 0 {
return fmt.Errorf("mygo: cannot install hot key handler (%d)", st)
}
b.hkInstalled = true
}
var ref uintptr
st := registerEventHotKey(code, mods, eventHotKeyID{Signature: hotKeySignature, ID: uint32(hid)}, getApplicationEventTarget(), 0, &ref)
if st != 0 {
return fmt.Errorf("mygo: cannot register shortcut %s, it may be used by another application (%d)", acc, st)
}
b.hotkeys[hid] = ref
return nil
}
func (b *Backend) UnregisterHotkey(hid int) {
if ref, ok := b.hotkeys[hid]; ok {
unregisterEventHotKey(ref)
delete(b.hotkeys, hid)
}
}
+80
View File
@@ -0,0 +1,80 @@
//go:build darwin && !ios
package darwin
import (
"fmt"
"path/filepath"
)
// FileIcon returns the icon Finder shows for a file, a folder or an
// application (NSWorkspace iconForFile:), drawn at size by size pixels
// from the representation that fits it best. A symbolic link gets the
// icon of what it points to, without the arrow Finder adds to links.
func (shell) FileIcon(path string, size int) ([]byte, error) {
real, err := filepath.EvalSymlinks(path)
if err != nil {
return nil, err
}
path = real
var png []byte
withPool(func() {
if img := send(workspace(), "iconForFile:", uintptr(nsString(path))); img != 0 {
png = pngOfImage(img, size)
}
})
if png == nil {
return nil, fmt.Errorf("mygo: no icon for %q", path)
}
return png, nil
}
// TypeIcon returns the icon Finder shows for files with the extension ext
// (NSWorkspace iconForContentType:, or iconForFileType: before macOS 11),
// drawn as FileIcon draws its icon.
func (shell) TypeIcon(ext string, size int) ([]byte, error) {
var png []byte
withPool(func() {
var img id
if hasClass("UTType") {
if t := send(class("UTType"), "typeWithFilenameExtension:", uintptr(nsString(ext))); t != 0 {
img = send(workspace(), "iconForContentType:", uintptr(t))
}
}
if img == 0 {
img = send(workspace(), "iconForFileType:", uintptr(nsString(ext)))
}
if img != 0 {
png = pngOfImage(img, size)
}
})
if png == nil {
return nil, fmt.Errorf("mygo: no icon for files of type %q", ext)
}
return png, nil
}
// pngOfImage draws an NSImage into an sRGB bitmap of size by size pixels,
// one pixel to the point, and encodes it as PNG. It must run in a pool.
func pngOfImage(img id, size int) []byte {
rep := autorelease(msgInitBitmap(send(class("NSBitmapImageRep"), "alloc"),
sel("initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bytesPerRow:bitsPerPixel:"),
0, size, size, 8, 4, true, false, nsString("NSCalibratedRGBColorSpace"), 0, 0))
if rep == 0 {
return nil
}
rep = send(rep, "bitmapImageRepByRetaggingWithColorSpace:", uintptr(send(class("NSColorSpace"), "sRGBColorSpace")))
ctx := send(class("NSGraphicsContext"), "graphicsContextWithBitmapImageRep:", uintptr(rep))
if ctx == 0 {
return nil
}
gc := class("NSGraphicsContext")
send(gc, "saveGraphicsState")
send(gc, "setCurrentContext:", uintptr(ctx))
send(ctx, "setImageInterpolation:", 3) // NSImageInterpolationHigh
const sourceOver = 2 // NSCompositingOperationSourceOver
dst := NSRect{Size: NSSize{float64(size), float64(size)}}
msgDrawImage(img, sel("drawInRect:fromRect:operation:fraction:"), dst, NSRect{}, sourceOver, 1)
send(gc, "restoreGraphicsState")
return goBytes(send(rep, "representationUsingType:properties:", 4, uintptr(send(class("NSDictionary"), "dictionary")))) // NSBitmapImageFileTypePNG
}
+94
View File
@@ -0,0 +1,94 @@
//go:build darwin && !ios
package darwin
import (
"sync"
"github.com/ebitengine/purego"
)
var (
coreTextOnce sync.Once
ctFontCreateWithName func(name id, size float64, matrix uintptr) uintptr
ctFontCopyPostScriptName func(font uintptr) id
ctFontGetGlyphsForCharacters func(font uintptr, chars, glyphs *uint16, count int) bool
)
// ideographBlocks are where RadicalIdeographs looks for the ideograph of a
// radical's glyph, in order: CJK Unified Ideographs, then Extension A.
var ideographBlocks = [...]struct{ first, last uint16 }{{0x4E00, 0x9FFF}, {0x3400, 0x4DBF}}
// RadicalIdeographs returns the ideographs that the installed font of the
// PostScript name draws with the glyphs of the radicals, as PingFang SC
// draws ⼈ (U+2F08) with the glyph of 人: for each radical whose glyph an
// ideograph has too, the first such ideograph of CJK Unified Ideographs,
// else of Extension A. It returns nil when no font has the name. It may be
// called from any goroutine.
func RadicalIdeographs(font string, radicals []rune) map[rune]rune {
load()
coreTextOnce.Do(func() {
lib := mustDlopen("/System/Library/Frameworks/CoreText.framework/CoreText")
purego.RegisterLibFunc(&ctFontCreateWithName, lib, "CTFontCreateWithName")
purego.RegisterLibFunc(&ctFontCopyPostScriptName, lib, "CTFontCopyPostScriptName")
purego.RegisterLibFunc(&ctFontGetGlyphsForCharacters, lib, "CTFontGetGlyphsForCharacters")
})
var found map[rune]rune
withPool(func() {
f := ctFontCreateWithName(nsString(font), 12, 0)
if f == 0 {
return
}
defer cfRelease(f)
// CoreText stands in another font for a name it does not know.
name := ctFontCopyPostScriptName(f)
if name == 0 {
return
}
same := goString(name) == font
cfRelease(uintptr(name))
if !same {
return
}
chars := make([]uint16, 0, len(radicals))
for _, r := range radicals {
if r > 0 && r <= 0xFFFF {
chars = append(chars, uint16(r))
}
}
if len(chars) == 0 {
return
}
// The radicals of each glyph, which may be several: Songti SC draws
// ⼝ (U+2F1D) and ⼜ (U+2F1C) as 口.
glyphs := make([]uint16, len(chars))
ctFontGetGlyphsForCharacters(f, &chars[0], &glyphs[0], len(chars))
wanted := map[uint16][]rune{}
for i, g := range glyphs {
if g != 0 {
wanted[g] = append(wanted[g], rune(chars[i]))
}
}
found = map[rune]rune{}
for _, b := range ideographBlocks {
if len(wanted) == 0 {
break
}
chars = make([]uint16, int(b.last-b.first)+1)
for i := range chars {
chars[i] = b.first + uint16(i)
}
glyphs = make([]uint16, len(chars))
// It reports whether every character has a glyph, which few
// fonts give them all; the others get glyph 0.
ctFontGetGlyphsForCharacters(f, &chars[0], &glyphs[0], len(chars))
for i, g := range glyphs {
for _, r := range wanted[g] {
found[r] = rune(chars[i])
}
delete(wanted, g)
}
}
})
return found
}
+25
View File
@@ -0,0 +1,25 @@
//go:build darwin && !ios
package darwin
import "testing"
// PingFang SC and Songti SC come with macOS. Songti SC of macOS 26 also
// draws ⼜ (U+2F1C), the radical of 又, with the glyph of 口; the PDF tests
// of package mygo cover what that does to printed text.
func TestRadicalIdeographs(t *testing.T) {
for font, want := range map[string]map[rune]rune{
"PingFangSC-Regular": {'⼈': '人', '⼝': '口', '⼜': '又'},
"STSongti-SC-Regular": {'⼈': '人', '⼝': '口'},
} {
got := RadicalIdeographs(font, []rune{'⼈', '⼝', '⼜'})
for r, i := range want {
if got[r] != i {
t.Errorf("%s: %c → %q, want %c", font, r, got[r], i)
}
}
}
if got := RadicalIdeographs("NoSuchFont-Regular", []rune{'⼈'}); got != nil {
t.Errorf("a font that is not installed gave %q", got)
}
}
+170
View File
@@ -0,0 +1,170 @@
//go:build darwin && !ios
package darwin
import (
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
// An input region (SetInputRegion) lets the mouse through a window but
// where its rectangles are, as a desktop pet's window lets clicks through
// to the apps under it but on its character. AppKit has no such region:
// the window server hands a press to the window under it, and a window
// takes the mouse everywhere or nowhere (ignoresMouseEvents). Hit testing
// in the window (hitTest:) cannot help, since the window server already
// gave the press to the app: it never goes on to another app's window.
//
// So the window lets the mouse through while the pointer is outside the
// region, and takes it while the pointer is in it, switched as the
// pointer moves, before the press comes: a press then goes where the
// pointer is as it would through a region. The moves come from two
// monitors of the app's events, which only observe: the global one sees
// those the window server sends other apps, as while the window lets the
// mouse through, and the local one those this app gets, as while it takes
// it, which a tracking area of the content view, active always, asks for
// over the window when the app is not active. The pointer is read as it
// is now (mouseLocation), not where the event says it was, a move behind
// it. A button held keeps the window as it is, so that a drag that
// started on the character ends there, as one that started under the
// window ends there, and its release settles it
// (platform.LetsMouseThrough). A window moving or resizing under a still
// pointer, as a pet walking, follows it too (windowDidMove:,
// windowDidResize:), and so does a new region.
//
// The monitors exist while a window has a region: a global monitor of
// moves wakes the app at every move of the mouse over other apps.
var (
// regionGlobal and regionLocal are the monitors of the pointer's
// moves and releases while windows have input regions, or 0;
// regionMovedGlobal and regionMovedLocal their handlers, made once.
regionGlobal, regionLocal id
regionMovedGlobal, regionMovedLocal objc.Block
regionBlocksMade bool
// inputRegionMoved is (*window).followPointer and inputRegionClosed
// (*window).closeInputRegion once the app set an input region, for
// what every app has, the window's delegate, cleanup and
// SetIgnoreMouseEvents, to call.
inputRegionMoved, inputRegionClosed func(w *window)
)
// regionTracking is the options of the tracking area that asks for the
// pointer's moves over a window with an input region: moves, active
// always, in the visible rect.
const regionTracking = 0x02 | 0x80 | 0x200
func (w *window) IgnoresMouseEvents() bool { return w.ignoreMouse }
func (w *window) SetIgnoreMouseEvents(v bool) {
w.ignoreMouse = v
w.ignoring = v
send(w.win, "setIgnoresMouseEvents:", boolArg(v))
if inputRegionMoved != nil {
inputRegionMoved(w) // false gives the region back the mouse
}
}
func (w *window) SetInputRegion(region []platform.Rect) {
inputRegionMoved, inputRegionClosed = (*window).followPointer, (*window).closeInputRegion
had := w.inputRegion != nil
w.inputRegion = region
switch {
case region != nil && !had:
if msgInitTracking == nil {
purego.RegisterFunc(&msgInitTracking, msgSendAddr)
}
w.regionTracking = msgInitTracking(send(class("NSTrackingArea"), "alloc"), sel("initWithRect:options:owner:userInfo:"), NSRect{}, regionTracking, w.view, 0)
send(w.view, "addTrackingArea:", uintptr(w.regionTracking))
case region == nil && had:
w.forgetInputRegion()
if !w.ignoreMouse && w.ignoring {
w.ignoring = false
send(w.win, "setIgnoresMouseEvents:", boolArg(false))
}
}
w.b.watchInputRegions()
w.followPointer()
}
// forgetInputRegion removes the tracking area of the window's region.
func (w *window) forgetInputRegion() {
if w.regionTracking != 0 {
send(w.view, "removeTrackingArea:", uintptr(w.regionTracking))
release(w.regionTracking)
w.regionTracking = 0
}
}
// closeInputRegion forgets the region of a window closing, which cleanup
// took out of the backend's windows, and the monitors once no window has
// one.
func (w *window) closeInputRegion() {
if w.inputRegion != nil {
w.forgetInputRegion()
w.b.watchInputRegions()
}
}
// followPointer lets the mouse through a window with an input region, or
// has it take the mouse, as the pointer is outside the region or in it.
func (w *window) followPointer() {
if w.closed || w.ignoreMouse || w.inputRegion == nil {
return
}
p := msgPoint(class("NSEvent"), sel("mouseLocation"))
c := msgRectToRect(w.win, sel("contentRectForFrameRect:"), msgRect(w.win, sel("frame")))
held := send(class("NSEvent"), "pressedMouseButtons") != 0
// AppKit's y goes up from the bottom of the content.
through := platform.LetsMouseThrough(w.inputRegion, p.X-c.Origin.X, c.Origin.Y+c.Size.Height-p.Y, held, w.ignoring)
if through != w.ignoring {
w.ignoring = through
send(w.win, "setIgnoresMouseEvents:", boolArg(through))
}
}
// watchInputRegions has the monitors watch the pointer while a window has
// an input region, and removes them once none has.
func (b *Backend) watchInputRegions() {
regions := false
for _, w := range b.byNSWindow {
if w.inputRegion != nil && !w.closed {
regions = true
break
}
}
if regions == (regionGlobal != 0) {
return
}
if !regions {
send(class("NSEvent"), "removeMonitor:", uintptr(regionGlobal))
send(class("NSEvent"), "removeMonitor:", uintptr(regionLocal))
release(regionGlobal)
release(regionLocal)
regionGlobal, regionLocal = 0, 0
return
}
if !regionBlocksMade {
regionBlocksMade = true
regionMovedGlobal = newBlock(func(_ objc.Block, ev id) { b.pointerMoved() })
regionMovedLocal = newBlock(func(_ objc.Block, ev id) id {
b.pointerMoved()
return ev
})
}
// Moves, and left, right and other mouse up.
const mask = 1<<5 | 1<<2 | 1<<4 | 1<<26
regionGlobal = retain(send(class("NSEvent"), "addGlobalMonitorForEventsMatchingMask:handler:", mask, uintptr(regionMovedGlobal)))
regionLocal = retain(send(class("NSEvent"), "addLocalMonitorForEventsMatchingMask:handler:", mask, uintptr(regionMovedLocal)))
}
// pointerMoved has each window with an input region follow the pointer.
func (b *Backend) pointerMoved() {
for _, w := range b.byNSWindow {
if w.inputRegion != nil {
w.followPointer()
}
}
}
+8
View File
@@ -0,0 +1,8 @@
//go:build darwin && !ios
package darwin
import "github.com/egoist/mygo/internal/platform"
// The core reaches a window's input region through the interface alone.
var _ platform.InputRegionWindow = (*window)(nil)
+156
View File
@@ -0,0 +1,156 @@
//go:build darwin && !ios
package darwin
import (
"strings"
"sync"
"github.com/ebitengine/purego"
"github.com/egoist/mygo/internal/platform"
)
// The languages and regional formats of the user, and the language the app
// chose for itself.
//
// The languages the user reads are the global AppleLanguages, which System
// Settings orders: NSLocale's preferredLanguages are the app's own when its
// defaults have an AppleLanguages, as System Settings' language of an app
// writes, and as SaveLocale does. That one is what AppKit and WebKit show
// their own texts in from the next launch.
var (
prefsOnce sync.Once
cfPreferencesCopyValue func(key, app, user, host uintptr) uintptr
cfPreferencesSetValue func(key, value, app, user, host uintptr)
cfPreferencesSynchronize func(app, user, host uintptr) bool
// The domains of CFPreferences.
cfAnyApplication, cfCurrentApplication, cfCurrentUser, cfAnyHost uintptr
)
func loadPreferences() {
prefsOnce.Do(func() {
purego.RegisterLibFunc(&cfPreferencesCopyValue, libCF, "CFPreferencesCopyValue")
purego.RegisterLibFunc(&cfPreferencesSetValue, libCF, "CFPreferencesSetValue")
purego.RegisterLibFunc(&cfPreferencesSynchronize, libCF, "CFPreferencesSynchronize")
cfAnyApplication = uintptr(constString(libCF, "kCFPreferencesAnyApplication"))
cfCurrentApplication = uintptr(constString(libCF, "kCFPreferencesCurrentApplication"))
cfCurrentUser = uintptr(constString(libCF, "kCFPreferencesCurrentUser"))
cfAnyHost = uintptr(constString(libCF, "kCFPreferencesAnyHost"))
})
}
// appleLanguages reads AppleLanguages of the current user, of the app's
// own domain alone when own, else of the global domain alone.
func appleLanguages(own bool) []string {
loadPreferences()
app := cfAnyApplication
if own {
app = cfCurrentApplication
}
var out []string
withPool(func() {
cfPreferencesSynchronize(app, cfCurrentUser, cfAnyHost)
v := id(cfPreferencesCopyValue(uintptr(nsString("AppleLanguages")), app, cfCurrentUser, cfAnyHost))
if v == 0 {
return
}
defer cfRelease(uintptr(v))
if !sendBool(v, "isKindOfClass:", uintptr(class("NSArray"))) {
return
}
for _, s := range arrayItems(v) {
if sendBool(s, "isKindOfClass:", uintptr(class("NSString"))) {
out = append(out, goString(s))
}
}
})
return out
}
func (a appController) PreferredLanguages() []string {
if langs := appleLanguages(false); len(langs) > 0 {
return langs
}
// A user who never ordered languages: the system's.
var out []string
withPool(func() {
for _, s := range arrayItems(send(class("NSLocale"), "preferredLanguages")) {
out = append(out, goString(s))
}
})
return out
}
func (a appController) SavedLocale() (string, bool) {
if langs := appleLanguages(true); len(langs) > 0 {
return langs[0], true
}
return "", true
}
func (a appController) SaveLocale(tag string) bool {
loadPreferences()
withPool(func() {
var value uintptr
if tag != "" {
value = uintptr(nsArray(nsString(tag)))
}
cfPreferencesSetValue(uintptr(nsString("AppleLanguages")), value, cfCurrentApplication, cfCurrentUser, cfAnyHost)
cfPreferencesSynchronize(cfCurrentApplication, cfCurrentUser, cfAnyHost)
})
return true
}
// SetLanguages does nothing: AppKit and WKWebView take the app's language,
// and its direction, from its AppleLanguages, at launch.
func (a appController) SetLanguages([]string, bool) {}
// Region reads the current locale, which macOS makes of the region and the
// formats the user chose, its calendar's first day of the week, and its
// hour cycle: the hour of the skeleton "j" in its date formats, which the
// 24-hour time setting changes.
func (a appController) Region() platform.Region {
r := platform.Region{FirstWeekday: -1}
withPool(func() {
locale := send(class("NSLocale"), "autoupdatingCurrentLocale")
r.Locale = goString(send(locale, "localeIdentifier"))
calendar := send(class("NSCalendar"), "autoupdatingCurrentCalendar")
if d := sendInt(calendar, "firstWeekday"); d >= 1 && d <= 7 {
r.FirstWeekday = d - 1
}
format := goString(send(class("NSDateFormatter"), "dateFormatFromTemplate:options:locale:",
uintptr(nsString("j")), 0, uintptr(locale)))
r.HourCycle = hourCycle(format)
})
return r
}
// currentLocaleDidChange is NSCurrentLocaleDidChangeNotification: the name
// Foundation posts it under, kCFLocaleCurrentLocaleDidChangeNotification,
// which isn't the constant's name.
func currentLocaleDidChange() id {
if name := constString(libFoundation, "NSCurrentLocaleDidChangeNotification"); name != 0 {
return name
}
return nsString("kCFLocaleCurrentLocaleDidChangeNotification")
}
// hourCycle returns the hour cycle of a date format pattern: 12 for h and
// K, 24 for H and k, 0 for none. Quoted text is not a field.
func hourCycle(pattern string) int {
quoted := false
for _, c := range pattern {
switch {
case c == '\'':
quoted = !quoted
case quoted:
case strings.ContainsRune("hK", c):
return 12
case strings.ContainsRune("Hk", c):
return 24
}
}
return 0
}
+56
View File
@@ -0,0 +1,56 @@
//go:build darwin && !ios
package darwin
import (
"slices"
"testing"
)
func TestHourCycle(t *testing.T) {
for pattern, want := range map[string]int{"h a": 12, "HH": 24, "K a": 12, "k": 24, "'h'": 0, "a 'o''clock' h": 12, "": 0} {
if got := hourCycle(pattern); got != want {
t.Errorf("hourCycle(%q) = %d, want %d", pattern, got, want)
}
}
}
// The current locale's change is observed under the name Foundation posts
// it under: observed by the constant's name, it never comes, and the region
// is read only at the time format's notification, before the current
// locale has the new format, one change behind.
func TestCurrentLocaleDidChangeName(t *testing.T) {
load()
if got := goString(currentLocaleDidChange()); got != "kCFLocaleCurrentLocaleDidChangeNotification" {
t.Errorf("NSCurrentLocaleDidChangeNotification is posted as %q", got)
}
}
// TestLocales reads the user's languages and formats, and keeps the app's
// language in its own defaults, where the global languages do not see it.
func TestLocales(t *testing.T) {
load()
a := appController{}
langs := a.PreferredLanguages()
if len(langs) == 0 {
t.Fatal("no preferred languages")
}
if r := a.Region(); r.Locale == "" || r.FirstWeekday < 0 || r.HourCycle == 0 {
t.Errorf("Region() = %+v", r)
}
if tag, kept := a.SavedLocale(); !kept || tag != "" {
t.Fatalf("SavedLocale() = %q, %v before saving", tag, kept)
}
t.Cleanup(func() { a.SaveLocale("") })
a.SaveLocale("x-test")
if tag, _ := a.SavedLocale(); tag != "x-test" {
t.Errorf("SavedLocale() = %q after saving x-test", tag)
}
if got := a.PreferredLanguages(); !slices.Equal(got, langs) {
t.Errorf("the app's language changed the user's: %q, were %q", got, langs)
}
a.SaveLocale("")
if tag, _ := a.SavedLocale(); tag != "" {
t.Errorf("SavedLocale() = %q after forgetting it", tag)
}
}
+153
View File
@@ -0,0 +1,153 @@
//go:build darwin && !ios
package darwin
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"unsafe"
"github.com/ebitengine/purego/objc"
)
// Starting at login: on macOS 13 and later the app is a login item of the
// user through SMAppService (System Settings > General > Login Items); on
// macOS 12 a launch agent opens it. Both need an app bundle.
// SMAppService statuses.
const (
smNotRegistered = 0
smEnabled = 1
smRequiresApproval = 2
)
// mainAppService returns the SMAppService of the app, or 0 before macOS 13.
func mainAppService() id {
c := id(objc.GetClass("SMAppService"))
if c == 0 {
return 0
}
return send(c, "mainAppService")
}
func bundlePath() (string, error) {
path := goString(send(send(class("NSBundle"), "mainBundle"), "bundlePath"))
if !strings.HasSuffix(path, ".app") {
return "", errors.New("mygo: starting at login needs an app bundle; run the app with mygo dev or build it with mygo build")
}
return path, nil
}
func (a appController) SetOpenAtLogin(open bool, appID, name, arg string) error {
var err error
withPool(func() {
var app string
if app, err = bundlePath(); err != nil {
return
}
svc := mainAppService()
if svc == 0 {
err = setLaunchAgent(open, appID, app, arg)
return
}
if !open && sendInt(svc, "status") == smNotRegistered {
return
}
selector := "unregisterAndReturnError:"
if open {
selector = "registerAndReturnError:"
}
var nserr id
if !sendBool(svc, selector, uintptr(unsafe.Pointer(&nserr))) {
err = fmt.Errorf("mygo: %s", goString(send(nserr, "localizedDescription")))
return
}
if open && sendInt(svc, "status") == smRequiresApproval {
err = fmt.Errorf("mygo: allow %s to open at login in System Settings > General > Login Items", name)
}
})
return err
}
func (a appController) OpenAtLogin(appID, name, arg string) bool {
ok := false
withPool(func() {
if _, err := bundlePath(); err != nil {
return
}
if svc := mainAppService(); svc != 0 {
ok = sendInt(svc, "status") == smEnabled
return
}
_, err := os.Stat(launchAgentPath(appID))
ok = err == nil
})
return ok
}
// OpenedAtLogin reports whether the launch Apple Event said the app was
// started as a login item, recorded in applicationWillFinishLaunching:.
func (a appController) OpenedAtLogin() bool { return a.b.openedAtLogin }
// launchedAsLoginItem reports whether the Apple Event being handled, the
// one that launched the app, marks it as started at login.
func launchedAsLoginItem() bool {
const keyAEPropData, keyAELaunchedAsLogInItem = 'p'<<24 | 'r'<<16 | 'd'<<8 | 't', 'l'<<24 | 'g'<<16 | 'i'<<8 | 't'
ev := send(send(class("NSAppleEventManager"), "sharedAppleEventManager"), "currentAppleEvent")
if ev == 0 {
return false
}
prop := send(ev, "paramDescriptorForKeyword:", keyAEPropData)
return prop != 0 && uint32(send(prop, "enumCodeValue")) == keyAELaunchedAsLogInItem
}
func launchAgentPath(appID string) string {
home, _ := os.UserHomeDir()
return filepath.Join(home, "Library", "LaunchAgents", appID+".plist")
}
// setLaunchAgent adds or removes a launch agent that opens the app at
// login.
func setLaunchAgent(open bool, appID, app, arg string) error {
path := launchAgentPath(appID)
if !open {
if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
return nil
}
esc := func(s string) string {
var b bytes.Buffer
_ = xml.EscapeText(&b, []byte(s))
return b.String()
}
plist := `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>` + esc(appID) + `</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/open</string>
<string>-a</string>
<string>` + esc(app) + `</string>
<string>--args</string>
<string>` + esc(arg) + `</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
`
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
return os.WriteFile(path, []byte(plist), 0o644)
}
File diff suppressed because it is too large. Load diff
+395
View File
@@ -0,0 +1,395 @@
//go:build darwin && !ios
package darwin
import (
"encoding/base64"
"strings"
"testing"
"github.com/egoist/mygo/internal/platform"
)
// titleTab returns the x the badge of item starts at, zero when it has none.
func titleTab(item id) float64 {
return attributedTab(send(item, "attributedTitle"))
}
// attributedTab returns the right-aligned tab stop of a title, zero when it
// has none.
func attributedTab(title id) float64 {
if title == 0 {
return 0
}
style := send(title, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSParagraphStyle")), 0, 0)
if style == 0 {
return 0
}
tabs := arrayItems(send(style, "tabStops"))
if len(tabs) == 0 {
return 0
}
return msgFloat(tabs[0], sel("location"))
}
// TestMenuBadgeTitle checks that a badge takes an attributed title whose
// tab stop sits in the column the menu's badges share, aligned as the item
// says, and that clearing the badge restores the plain title.
func TestMenuBadgeTitle(t *testing.T) {
load()
withPool(func() {
longest := "A longer node name without a badge"
start, width := badgeColumn(&platform.Menu{Items: []*platform.MenuItem{
{Label: "Node", Badge: "120 ms", Visible: true},
{Label: "A longer node name", Badge: "1.2s", Visible: true},
{Label: longest, Visible: true},
}})
if start <= textWidth(longest, menuFont()) {
t.Fatalf("column start %v does not clear the longest label", start)
}
item := autorelease(send(send(class("NSMenuItem"), "alloc"), "initWithTitle:action:keyEquivalent:",
uintptr(nsString("Node")), 0, uintptr(nsString(""))))
for _, a := range []struct {
align platform.BadgeAlignment
tab float64
want int
}{
{platform.BadgeAlignLeft, start, nsTextAlignmentLeft},
{platform.BadgeAlignCenter, start + width/2, nsTextAlignmentCenter},
{platform.BadgeAlignRight, start + width, nsTextAlignmentRight},
} {
setItemTitle(item, "Node", "120 ms", a.tab, a.align)
title := send(item, "attributedTitle")
if title == 0 || goString(send(title, "string")) != "Node\t120 ms" {
t.Fatalf("%s attributed title missing: %v", a.align, title)
}
if got := titleTab(item); got != a.tab {
t.Errorf("%s tab stop at %v, want %v", a.align, got, a.tab)
}
style := send(title, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSParagraphStyle")), 0, 0)
if tabs := arrayItems(send(style, "tabStops")); len(tabs) != 1 || sendInt(tabs[0], "alignment") != a.want {
t.Errorf("%s tab stop has alignment %d, want %d", a.align, sendInt(tabs[0], "alignment"), a.want)
}
}
setItemTitle(item, "Node", "", 0, platform.BadgeAlignRight)
if got := goString(send(item, "title")); got != "Node" {
t.Errorf("title after clearing = %q", got)
}
if at := send(item, "attributedTitle"); at != 0 && goString(send(at, "string")) != "Node" {
t.Errorf("attributed title after clearing = %q", goString(send(at, "string")))
}
})
}
// TestMenuBadgeIconColumn checks that an item with an icon puts its badge
// in the same column as the items without one.
func TestMenuBadgeIconColumn(t *testing.T) {
load()
LinkMenuIcons()
defer func() { menuImage = nil }()
png, err := base64.StdEncoding.DecodeString("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=")
if err != nil {
t.Fatal(err)
}
withPool(func() {
b := &Backend{}
m := &platform.Menu{Items: []*platform.MenuItem{
{ID: 1, Label: "Node", Badge: "45 ms", Visible: true, Enabled: true},
{ID: 2, Label: "Node", Badge: "45 ms", Visible: true, Enabled: true, Icon: &platform.MenuIcon{PNG: png}},
}}
owner := newOwner()
menu := b.buildMenu(m, "", owner)
defer dropOwner(owner)
plain := send(menu, "itemAtIndex:", 0)
icon := send(menu, "itemAtIndex:", 1)
if got, want := titleTab(icon), titleTab(plain); got != want {
t.Errorf("icon item tab = %v, want %v", got, want)
}
})
}
// TestMenuBadgeRetab checks that a badge set, a label made wider, or an
// item hidden after the menu was built moves the tab stop the menu's badges
// start at: the menu no longer keeps the column it was built with.
func TestMenuBadgeRetab(t *testing.T) {
load()
registerMenuTarget()
withPool(func() {
b := &Backend{}
m := &platform.Menu{Items: []*platform.MenuItem{
{ID: 1, Label: "Node", Visible: true, Enabled: true},
{ID: 2, Label: "A longer node name", Visible: true, Enabled: true},
}}
owner := newOwner()
menu := b.buildMenu(m, "", owner)
defer dropOwner(owner)
node := send(menu, "itemAtIndex:", 0)
long := send(menu, "itemAtIndex:", 1)
if tab := titleTab(node); tab != 0 {
t.Fatalf("badgeless item has a tab stop at %v", tab)
}
// A badge given after the menu was built gets the column now.
b.UpdateMenuItem(&platform.MenuItem{ID: 1, Label: "Node", Badge: "120 ms", Visible: true, Enabled: true})
tab := titleTab(node)
if tab <= textWidth("Node", menuFont()) {
t.Fatalf("badge tab %v does not clear the label", tab)
}
if got := goString(send(send(node, "attributedTitle"), "string")); got != "Node\t120 ms" {
t.Fatalf("node title = %q", got)
}
// A label made wider moves the badges of the menu along.
wider := "A node name much longer than the one before"
b.UpdateMenuItem(&platform.MenuItem{ID: 2, Label: wider, Visible: true, Enabled: true})
if got := titleTab(node); got <= tab || got <= textWidth(wider, menuFont()) {
t.Errorf("badge tab after a wider label = %v, was %v", got, tab)
}
tab = titleTab(node)
// Hiding the longest item brings them back.
b.UpdateMenuItem(&platform.MenuItem{ID: 2, Label: wider, Visible: false, Enabled: true})
if got := titleTab(node); got >= tab {
t.Errorf("badge tab after hiding the longest item = %v, was %v", got, tab)
}
if !sendBool(long, "isHidden") {
t.Error("hidden item is shown")
}
// Clearing the last badge restores the plain titles.
b.UpdateMenuItem(&platform.MenuItem{ID: 1, Label: "Node", Visible: true, Enabled: true})
if at := send(node, "attributedTitle"); at != 0 && goString(send(at, "string")) != "Node" {
t.Errorf("attributed title after clearing = %q", goString(send(at, "string")))
}
if got := goString(send(node, "title")); got != "Node" {
t.Errorf("title after clearing = %q", got)
}
})
}
// TestMenuBadgeSubtitle checks that the tab stop clears the subtitle where
// the item shows it after the title, and the title alone where the subtitle
// has a line of its own.
func TestMenuBadgeSubtitle(t *testing.T) {
load()
withPool(func() {
itString := (&platform.MenuItem{Label: "Node", Subtitle: "Hong Kong", Badge: "120 ms"}).LabelWithSubtitle()
start, _ := badgeColumn(&platform.Menu{Items: []*platform.MenuItem{
{Label: "Node", Subtitle: "Hong Kong", Badge: "120 ms", Visible: true},
}})
want := "Node"
if !subtitleOnLine() {
want = itString
}
if base := textWidth(want, menuFont()); start <= base {
t.Errorf("column start %v does not clear %q", start, want)
}
})
}
func TestTextAlignments(t *testing.T) {
for _, c := range []struct {
arch string
center, right int
}{
{"arm64", 1, 2},
{"amd64", 2, 1},
} {
if center, right := textAlignments(c.arch); center != c.center || right != c.right {
t.Errorf("%s: center %d, right %d, want %d, %d", c.arch, center, right, c.center, c.right)
}
}
}
// TestMenuBadgeStyledTitle checks the square background and text color of
// a system-drawn badge, and that retabbing keeps them.
func TestMenuBadgeStyledTitle(t *testing.T) {
load()
withPool(func() {
b := &Backend{}
m := &platform.Menu{Items: []*platform.MenuItem{
{ID: 1, Label: "Node", Badge: "120 ms", Visible: true, Enabled: true,
BadgeShape: platform.BadgeShapeSquare,
BadgeColor: &platform.Color{R: 215, G: 245, B: 223, A: 255},
BadgeTextColor: &platform.Color{R: 11, G: 107, B: 46, A: 255}},
{ID: 2, Label: "Other", Badge: "7 ms", Visible: true, Enabled: true,
BadgeTextColor: &platform.Color{R: 107, G: 82, B: 0, A: 255}},
}}
owner := newOwner()
menu := b.buildMenu(m, "", owner)
defer dropOwner(owner)
item := send(menu, "itemAtIndex:", 0)
title := send(item, "attributedTitle")
if title == 0 || !strings.Contains(goString(send(title, "string")), "\t"+menuBadgePad+"120 ms"+menuBadgePad) {
t.Fatalf("styled title = %q", goString(send(title, "string")))
}
at := uintptr(len([]rune("Node\t")))
if send(title, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSBackgroundColor")), at, 0) == 0 {
t.Error("styled badge has no background")
}
if send(title, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSColor")), at, 0) == 0 {
t.Error("styled badge has no text color")
}
if label, badge, _ := itemTitleParts(item); label != "Node" || badge != "120 ms" {
t.Errorf("parsed title = %q, %q", label, badge)
}
// A text color alone colors the badge without a background.
other := send(menu, "itemAtIndex:", 1)
otherTitle := send(other, "attributedTitle")
if !strings.Contains(goString(send(otherTitle, "string")), "\t7 ms") {
t.Errorf("text-only title = %q", goString(send(otherTitle, "string")))
}
at = uintptr(len([]rune("Other\t")))
if send(otherTitle, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSColor")), at, 0) == 0 {
t.Error("text-only badge has no text color")
}
if send(otherTitle, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSBackgroundColor")), at, 0) != 0 {
t.Error("text-only badge has a background")
}
// Retabbing from another item keeps the styled badge.
b.UpdateMenuItem(&platform.MenuItem{ID: 2, Label: "A wider label", Badge: "7 ms",
Visible: true, Enabled: true, BadgeTextColor: &platform.Color{R: 107, G: 82, B: 0, A: 255}})
title = send(item, "attributedTitle")
at = uintptr(len([]rune("Node\t")))
if send(title, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSBackgroundColor")), at, 0) == 0 {
t.Error("background went away after retabbing")
}
})
}
// TestMenuBadgeStyledUpdate checks that a system badge restyles and rewidens
// in place, and loses its background when the style is cleared.
func TestMenuBadgeStyledUpdate(t *testing.T) {
load()
withPool(func() {
b := &Backend{}
m := &platform.Menu{Items: []*platform.MenuItem{
{ID: 1, Label: "Node", Badge: "3 ms", Visible: true, Enabled: true,
BadgeShape: platform.BadgeShapeSquare,
BadgeColor: &platform.Color{R: 215, G: 245, B: 223, A: 255}},
{ID: 2, Label: "Other", Badge: "7 ms", Visible: true, Enabled: true},
}}
owner := newOwner()
menu := b.buildMenu(m, "", owner)
defer dropOwner(owner)
styled := send(menu, "itemAtIndex:", 0)
other := send(menu, "itemAtIndex:", 1)
before := titleTab(other)
// A wider badge moves the column and keeps its background.
b.UpdateMenuItem(&platform.MenuItem{ID: 1, Label: "Node", Badge: "1200 ms", Visible: true, Enabled: true,
BadgeShape: platform.BadgeShapeSquare,
BadgeColor: &platform.Color{R: 255, G: 224, B: 221, A: 255},
BadgeTextColor: &platform.Color{R: 163, G: 37, B: 26, A: 255}})
title := send(styled, "attributedTitle")
if !strings.Contains(goString(send(title, "string")), "\t"+menuBadgePad+"1200 ms"+menuBadgePad) {
t.Fatalf("styled title after update = %q", goString(send(title, "string")))
}
at := uintptr(len([]rune("Node\t")))
if send(title, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSBackgroundColor")), at, 0) == 0 {
t.Error("background went away after a badge update")
}
if got := titleTab(other); got <= before {
t.Errorf("sibling tab = %v, want past %v", got, before)
}
// Clearing the shape and colors restores the plain title.
b.UpdateMenuItem(&platform.MenuItem{ID: 1, Label: "Node", Badge: "1 ms", Visible: true, Enabled: true})
title = send(styled, "attributedTitle")
if got := goString(send(title, "string")); got != "Node\t1 ms" {
t.Errorf("title after clearing = %q", got)
}
at = uintptr(len([]rune("Node\t")))
if send(title, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSBackgroundColor")), at, 0) != 0 {
t.Error("background left after clearing the style")
}
if send(title, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSColor")), at, 0) != 0 {
t.Error("text color left after clearing the style")
}
})
}
// TestMenuBadgeColumnIncludesPadding checks that a background's padding is
// part of the width the menu's badges share.
func TestMenuBadgeColumnIncludesPadding(t *testing.T) {
load()
withPool(func() {
_, width := badgeColumn(&platform.Menu{Items: []*platform.MenuItem{
{Label: "Node", Badge: "1200 ms", Visible: true, BadgeShape: platform.BadgeShapeSquare},
{Label: "A longer node name", Badge: "7 ms", Visible: true},
}})
want := textWidth("1200 ms", menuBadgeFont()) + 2*textWidth(menuBadgePad, menuBadgeFont())
if width != want {
t.Errorf("column width = %v, want %v with padding", width, want)
}
})
}
// TestMenuBadgeStyledTitleAstral checks that a badge after an astral
// character keeps its attributes on the badge, not a UTF-16 unit early.
func TestMenuBadgeStyledTitleAstral(t *testing.T) {
load()
withPool(func() {
m := &platform.Menu{Items: []*platform.MenuItem{{
ID: 1, Label: "🔥 Hot", Badge: "3 ms", Visible: true, Enabled: true,
BadgeShape: platform.BadgeShapeSquare,
BadgeColor: &platform.Color{R: 215, G: 245, B: 223, A: 255},
BadgeTextColor: &platform.Color{R: 11, G: 107, B: 46, A: 255},
}}}
owner := newOwner()
b := &Backend{}
menu := b.buildMenu(m, "", owner)
defer dropOwner(owner)
item := send(menu, "itemAtIndex:", 0)
title := send(item, "attributedTitle")
start := units([]rune("🔥 Hot\t"))
length := units([]rune(menuBadgePad + "3 ms" + menuBadgePad))
if send(title, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSBackgroundColor")), uintptr(start), 0) == 0 {
t.Errorf("no background at UTF-16 index %d", start)
}
wrong := len([]rune("🔥 Hot\t"))
if send(title, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSBackgroundColor")), uintptr(wrong), 0) != 0 {
t.Errorf("background at rune index %d, one unit early", wrong)
}
if send(title, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSBackgroundColor")), uintptr(start+length-1), 0) == 0 {
t.Error("background does not cover the badge")
}
})
}
// TestMenuBadgeTransparentBackgroundTextColor checks that a translucent
// background does not force white text: the menu's own color is used.
func TestMenuBadgeTransparentBackgroundTextColor(t *testing.T) {
load()
registerMenuTarget()
withPool(func() {
clear := &platform.Color{R: 0, G: 0, B: 0, A: 10}
b := &Backend{}
m := &platform.Menu{Items: []*platform.MenuItem{
{ID: 1, Label: "Node", Badge: "3 ms", Visible: true, Enabled: true,
BadgeShape: platform.BadgeShapeSquare, BadgeColor: clear},
{ID: 2, Label: "Other", Badge: "7 ms", Visible: true, Enabled: true, KeepOpen: true,
BadgeShape: platform.BadgeShapePill, BadgeColor: clear},
}}
owner := newOwner()
menu := b.buildMenu(m, "", owner)
defer dropOwner(owner)
title := send(send(menu, "itemAtIndex:", 0), "attributedTitle")
at := uintptr(len([]rune("Node\t")))
if send(title, "attribute:atIndex:effectiveRange:", uintptr(nsString("NSColor")), at, 0) != 0 {
t.Error("translucent system background forced a text color")
}
badge := send(send(send(menu, "itemAtIndex:", 1), "view"), "viewWithTag:", menuViewBadge)
label := send(class("NSColor"), "labelColor")
if !sendBool(send(badge, "textColor"), "isEqual:", uintptr(label)) {
t.Error("translucent KeepOpen background did not use the label color")
}
})
}
+471
View File
@@ -0,0 +1,471 @@
//go:build darwin && !ios
package darwin
import (
"encoding/base64"
"testing"
"github.com/egoist/mygo/internal/platform"
)
// TestMenuKeepOpenView checks the view MyGo draws for an item that keeps
// its menu open: its label, badge, check mark and the update path.
func TestMenuKeepOpenView(t *testing.T) {
load()
registerMenuTarget()
withPool(func() {
b := &Backend{}
item := &platform.MenuItem{
ID: 42, Label: "Node", Badge: "45 ms", KeepOpen: true,
Visible: true, Enabled: true, Type: platform.MenuItemCheckbox, Checked: true,
}
m := &platform.Menu{Items: []*platform.MenuItem{
item,
{Label: "Other", Visible: true, Enabled: true, KeepOpen: true},
}}
menu := b.buildMenu(m, "", 1)
defer dropOwner(1)
native := send(menu, "itemAtIndex:", 0)
view := send(native, "view")
if view == 0 {
t.Fatal("KeepOpen item has no view")
}
if got := goString(send(view, "identifier")); got != "42" {
t.Errorf("view identifier = %q", got)
}
// The menu is at least as wide as its views, whose right the titles
// do not account for.
viewWidth := msgRect(view, sel("frame")).Size.Width
if got := msgFloat(menu, sel("minimumWidth")); got < viewWidth {
t.Errorf("menu minimum width = %v, view width = %v", got, viewWidth)
}
check := send(view, "viewWithTag:", menuViewCheck)
if check == 0 || sendBool(check, "isHidden") {
t.Fatal("checked item has no check mark")
}
label := send(view, "viewWithTag:", menuViewLabel)
if label == 0 {
t.Fatal("KeepOpen view has no label")
}
if got := goString(send(label, "stringValue")); got != "Node\t45 ms" {
t.Errorf("label = %q", got)
}
backdrop := menuBackdrop(view)
if backdrop == 0 || !sendBool(backdrop, "isHidden") {
t.Fatal("KeepOpen view should start without a highlight")
}
// NSMenu highlights items itself, keyboard included: its delegate
// follows the highlight in the views.
delegate := send(menu, "delegate")
if delegate == 0 {
t.Fatal("menu with KeepOpen views has no delegate")
}
send(delegate, "menu:willHighlightItem:", uintptr(menu), uintptr(native))
if sendBool(backdrop, "isHidden") {
t.Error("delegate did not highlight the view")
}
send(delegate, "menu:willHighlightItem:", uintptr(menu), 0)
if !sendBool(backdrop, "isHidden") {
t.Error("delegate did not clear the highlight")
}
setMenuViewHighlighted(view, true)
if sendBool(backdrop, "isHidden") {
t.Error("highlight not shown")
}
setMenuViewHighlighted(view, false)
if !sendBool(backdrop, "isHidden") {
t.Error("highlight not hidden")
}
// The view answers the keyboard and VoiceOver as an item does.
if !sendBool(view, "acceptsFirstResponder") || !sendBool(view, "canBecomeKeyView") {
t.Error("view cannot take the keyboard")
}
if !sendBool(view, "isAccessibilityElement") {
t.Error("view is not an accessibility element")
}
if got := goString(send(view, "accessibilityRole")); got != "AXMenuItem" {
t.Errorf("accessibility role = %q", got)
}
if got := goString(send(view, "accessibilityLabel")); got != "Node" {
t.Errorf("accessibility label = %q", got)
}
if got := goString(send(view, "accessibilityValue")); got != "45 ms" {
t.Errorf("accessibility value = %q", got)
}
if !sendBool(view, "accessibilityEnabled") {
t.Error("view is not enabled")
}
if got := goString(send(view, "accessibilityMenuItemMarkChar")); got != "✓" {
t.Errorf("accessibility mark of a checked item = %q", got)
}
if names := arrayItems(send(view, "accessibilityActionNames")); len(names) != 1 || goString(names[0]) != "AXPress" {
t.Errorf("accessibility actions = %v", names)
}
for _, method := range []string{"accessibilityPerformPress", "keyDown:", "mouseUp:"} {
if !respondsTo(view, method) {
t.Errorf("view does not answer %s", method)
}
}
// Arrow keys are taken by the view while the menu is up.
down := msgKeyEvent(class("NSEvent"), sel("keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:"),
10 /* keyDown */, NSPoint{}, 0, 0, 0, 0, nsString(""), nsString(""), false, 125)
send(view, "keyDown:", uintptr(down))
// A wider label or badge of any of the menu's view items lays its
// views out again.
width := msgRect(view, sel("frame")).Size.Width
tab := attributedTab(send(label, "attributedStringValue"))
b.UpdateMenuItem(&platform.MenuItem{ID: 0, Label: "A node name much longer than the one before, wide enough to widen the views", Visible: true, Enabled: true, KeepOpen: true})
if got := msgRect(view, sel("frame")).Size.Width; got <= width {
t.Errorf("view width after a wider label = %v, was %v", got, width)
}
if got := msgFloat(menu, sel("minimumWidth")); got < msgRect(view, sel("frame")).Size.Width {
t.Errorf("menu minimum width after a wider label = %v, view width = %v", got, msgRect(view, sel("frame")).Size.Width)
}
if got := attributedTab(send(label, "attributedStringValue")); got <= tab {
t.Errorf("badge tab after a wider label = %v, was %v", got, tab)
}
item.Label, item.Badge, item.Checked, item.Enabled = "Node 2", "123456 ms", false, false
b.UpdateMenuItem(item)
if !sendBool(check, "isHidden") {
t.Error("unchecked item still shows the check mark")
}
if got := goString(send(label, "stringValue")); got != "Node 2\t123456 ms" {
t.Errorf("label after update = %q", got)
}
if got := msgFloat(view, sel("alphaValue")); got != 0.45 {
t.Errorf("disabled view alpha = %v", got)
}
if got := goString(send(view, "accessibilityValue")); got != "123456 ms" {
t.Errorf("accessibility value after update = %q", got)
}
if sendBool(view, "accessibilityEnabled") {
t.Error("disabled item's view is enabled")
}
if mark := send(view, "accessibilityMenuItemMarkChar"); mark != 0 {
t.Errorf("unchecked item's mark = %q", goString(mark))
}
})
}
// TestMenuKeepOpenSubtitleAndIcon checks that a KeepOpen item shows its
// subtitle after the label, since its view has one line, and that an icon
// takes a column of its own in the views of the menu.
func TestMenuKeepOpenSubtitleAndIcon(t *testing.T) {
load()
registerMenuTarget()
LinkMenuIcons()
defer func() { menuImage = nil }()
png, err := base64.StdEncoding.DecodeString("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=")
if err != nil {
t.Fatal(err)
}
withPool(func() {
b := &Backend{}
m := &platform.Menu{Items: []*platform.MenuItem{
{ID: 7, Label: "Node", Subtitle: "Hong Kong", Badge: "45 ms", KeepOpen: true,
Visible: true, Enabled: true, Icon: &platform.MenuIcon{PNG: png, Template: true}},
{ID: 8, Label: "Other", KeepOpen: true, Visible: true, Enabled: true},
}}
owner := newOwner()
menu := b.buildMenu(m, "", owner)
defer dropOwner(owner)
view := send(send(menu, "itemAtIndex:", 0), "view")
label := send(view, "viewWithTag:", menuViewLabel)
if got := goString(send(label, "stringValue")); got != "Node — Hong Kong\t45 ms" {
t.Errorf("label = %q", got)
}
if got := goString(send(view, "accessibilityLabel")); got != "Node — Hong Kong" {
t.Errorf("accessibility label = %q", got)
}
icon := send(view, "viewWithTag:", menuViewIcon)
if icon == 0 || sendBool(icon, "isHidden") {
t.Fatal("item with an icon shows none")
}
if got := msgFloat(menu, sel("minimumWidth")); got < msgRect(view, sel("frame")).Size.Width {
t.Errorf("menu minimum width = %v, view width = %v", got, msgRect(view, sel("frame")).Size.Width)
}
// The views of the menu share the icon column, whether or not
// their own item has an icon.
for i, want := range []float64{menuKeepOpenIconLabelX, menuKeepOpenIconLabelX} {
itemView := send(send(menu, "itemAtIndex:", uintptr(i)), "view")
field := send(itemView, "viewWithTag:", menuViewLabel)
if got := msgRect(field, sel("frame")).Origin.X; got != want {
t.Errorf("item %d label x = %v, want %v", i, got, want)
}
}
})
}
// TestMenuKeepOpenBadgePill checks that a KeepOpen badge draws as a pill
// behind its text, with its colors, and follows updates in place.
func TestMenuKeepOpenBadgePill(t *testing.T) {
load()
registerMenuTarget()
withPool(func() {
b := &Backend{}
green := &platform.Color{R: 52, G: 199, B: 89, A: 255}
item := &platform.MenuItem{
ID: 7, Label: "Node", Badge: "120 ms", KeepOpen: true,
BadgeShape: platform.BadgeShapePill, BadgeColor: green,
BadgeTextColor: &platform.Color{R: 255, G: 255, B: 255, A: 255},
Visible: true, Enabled: true,
}
m := &platform.Menu{Items: []*platform.MenuItem{
item,
{Label: "Other", Badge: "1.2s", KeepOpen: true, Visible: true, Enabled: true},
}}
menu := b.buildMenu(m, "", 1)
defer dropOwner(1)
native := send(menu, "itemAtIndex:", 0)
view := send(native, "view")
label := send(view, "viewWithTag:", menuViewLabel)
badge := send(view, "viewWithTag:", menuViewBadge)
if label == 0 || badge == 0 {
t.Fatal("KeepOpen view has no label or badge")
}
if sendBool(badge, "isHidden") {
t.Fatal("pill badge is hidden")
}
if got := goString(send(badge, "stringValue")); got != "120 ms" {
t.Errorf("pill text = %q", got)
}
if got := goString(send(label, "stringValue")); got != "Node" {
t.Errorf("label with a pill = %q", got)
}
if width := msgRect(badge, sel("frame")).Size.Width; width <= textWidth("120 ms", menuBadgeFont()) {
t.Errorf("pill width %v has no padding", width)
}
if send(badge, "textColor") == 0 {
t.Error("pill has no text color")
}
if layer := send(badge, "layer"); layer == 0 || send(layer, "backgroundColor") == 0 {
t.Error("pill has no background")
}
if got := goString(send(view, "accessibilityValue")); got != "120 ms" {
t.Errorf("accessibility value = %q", got)
}
if got := goString(send(view, "accessibilityLabel")); got != "Node" {
t.Errorf("accessibility label = %q", got)
}
// The item without a pill keeps its badge in the label.
other := send(menu, "itemAtIndex:", 1)
otherBadge := send(send(other, "view"), "viewWithTag:", menuViewBadge)
otherLabel := send(send(other, "view"), "viewWithTag:", menuViewLabel)
if otherBadge == 0 || !sendBool(otherBadge, "isHidden") {
t.Error("badge of an item without a pill is shown")
}
if got := goString(send(otherLabel, "stringValue")); got != "Other\t1.2s" {
t.Errorf("label without a pill = %q", got)
}
// A badge set later updates the pill in place.
b.UpdateMenuItem(&platform.MenuItem{
ID: 7, Label: "Node", Badge: "1.2s", KeepOpen: true,
BadgeShape: platform.BadgeShapePill, BadgeColor: &platform.Color{R: 255, G: 59, B: 48, A: 255},
BadgeAlign: platform.BadgeAlignLeft, Visible: true, Enabled: true,
})
if got := goString(send(badge, "stringValue")); got != "1.2s" {
t.Errorf("pill text after update = %q", got)
}
if got := msgRect(badge, sel("frame")).Origin.X; got == 0 {
t.Error("pill did not move to the left of its column")
}
})
}
// TestMenuKeepOpenBadgePillColumn checks that the pills of a view menu
// share their right edge, padding included.
func TestMenuKeepOpenBadgePillColumn(t *testing.T) {
load()
registerMenuTarget()
withPool(func() {
b := &Backend{}
var items []*platform.MenuItem
for i, badge := range []string{"3 ms", "18 ms", "7 ms"} {
items = append(items, &platform.MenuItem{
ID: i + 1, Label: "Node", Badge: badge, KeepOpen: true,
BadgeShape: platform.BadgeShapePill, BadgeAlign: platform.BadgeAlignRight,
BadgeColor: &platform.Color{R: 52, G: 199, B: 89, A: 255},
Visible: true, Enabled: true,
})
}
menu := b.buildMenu(&platform.Menu{Items: items}, "", 1)
defer dropOwner(1)
var right float64
for i := range items {
badge := send(send(send(menu, "itemAtIndex:", uintptr(i)), "view"), "viewWithTag:", menuViewBadge)
frame := msgRect(badge, sel("frame"))
if frame.Size.Width == 0 || sendBool(badge, "isHidden") {
t.Fatalf("item %d has no pill", i)
}
maxX := frame.Origin.X + frame.Size.Width
if i == 0 {
right = maxX
continue
}
if maxX != right {
t.Errorf("pill %d right edge = %v, want %v", i, maxX, right)
}
}
})
}
// TestMenuKeepOpenBadgePillAfterClose checks that closing a menu keeps the
// badge styles of its views, which updates still use.
func TestMenuKeepOpenBadgePillAfterClose(t *testing.T) {
load()
registerMenuTarget()
withPool(func() {
b := &Backend{}
m := &platform.Menu{Items: []*platform.MenuItem{
{ID: 1, Label: "Node", Badge: "3 ms", KeepOpen: true, BadgeShape: platform.BadgeShapePill,
BadgeColor: &platform.Color{R: 52, G: 199, B: 89, A: 255}, Visible: true, Enabled: true},
{ID: 2, Label: "Other", Badge: "18 ms", KeepOpen: true, BadgeShape: platform.BadgeShapePill,
BadgeColor: &platform.Color{R: 52, G: 199, B: 89, A: 255}, Visible: true, Enabled: true},
}}
menu := b.buildMenu(m, "", 1)
defer dropOwner(1)
if delegate := send(menu, "delegate"); delegate != 0 {
send(delegate, "menuDidClose:", uintptr(menu))
}
b.UpdateMenuItem(&platform.MenuItem{ID: 2, Label: "Other", Badge: "7 ms",
BadgeShape: platform.BadgeShapePill, BadgeColor: &platform.Color{R: 52, G: 199, B: 89, A: 255},
KeepOpen: true, Visible: true, Enabled: true})
first := send(send(menu, "itemAtIndex:", 0), "view")
firstBadge := send(first, "viewWithTag:", menuViewBadge)
if firstBadge == 0 || sendBool(firstBadge, "isHidden") {
t.Fatal("first pill went away after the menu closed")
}
if got := goString(send(firstBadge, "stringValue")); got != "3 ms" {
t.Errorf("first pill text = %q", got)
}
if layer := send(firstBadge, "layer"); layer == 0 || send(layer, "backgroundColor") == 0 {
t.Error("first pill lost its background")
}
})
}
// TestMenuKeepOpenBadgePillDefaultColor checks that a pill without a color
// takes the dynamic default again when the state refreshes.
func TestMenuKeepOpenBadgePillDefaultColor(t *testing.T) {
load()
registerMenuTarget()
withPool(func() {
b := &Backend{}
m := &platform.Menu{Items: []*platform.MenuItem{{
ID: 1, Label: "Node", Badge: "3 ms", KeepOpen: true,
BadgeShape: platform.BadgeShapeRounded, Visible: true, Enabled: true,
}}}
menu := b.buildMenu(m, "", 1)
defer dropOwner(1)
view := send(send(menu, "itemAtIndex:", 0), "view")
badge := send(view, "viewWithTag:", menuViewBadge)
if layer := send(badge, "layer"); layer == 0 || send(layer, "backgroundColor") == 0 {
t.Fatal("pill has no default background")
}
send(send(badge, "layer"), "setBackgroundColor:", 0)
setMenuViewColors(view)
if layer := send(badge, "layer"); send(layer, "backgroundColor") == 0 {
t.Error("default background not applied again")
}
})
}
// TestMenuKeepOpenBadgeRightInset checks the room after a badge. The badges
// end menuKeepOpenRight from the view's right edge and the menu's minimum
// width carries no room beyond that: the earlier 40pt reserve showed as an
// empty band after the delays and cost the menu that width.
func TestMenuKeepOpenBadgeRightInset(t *testing.T) {
load()
registerMenuTarget()
withPool(func() {
b := &Backend{}
items := []*platform.MenuItem{
{ID: 1, Label: "A rather long node name here", Badge: "3 ms", KeepOpen: true,
BadgeShape: platform.BadgeShapeSquare, BadgeAlign: platform.BadgeAlignRight,
BadgeColor: &platform.Color{R: 52, G: 199, B: 89, A: 255},
Visible: true, Enabled: true},
{ID: 2, Label: "Short", Badge: "1200 ms", KeepOpen: true,
BadgeShape: platform.BadgeShapeSquare, BadgeAlign: platform.BadgeAlignRight,
BadgeColor: &platform.Color{R: 255, G: 69, B: 58, A: 255},
Visible: true, Enabled: true},
}
menu := b.buildMenu(&platform.Menu{Items: items}, "", 1)
defer dropOwner(1)
minWidth := msgFloat(menu, sel("minimumWidth"))
for i := range items {
view := send(send(menu, "itemAtIndex:", uintptr(i)), "view")
width := msgRect(view, sel("frame")).Size.Width
badge := send(view, "viewWithTag:", menuViewBadge)
frame := msgRect(badge, sel("frame"))
right := frame.Origin.X + frame.Size.Width
if got := width - right; got < menuKeepOpenRight-0.01 || got > menuKeepOpenRight+0.01 {
t.Errorf("item %d: room after badge = %v, want %v", i, got, menuKeepOpenRight)
}
if got := minWidth - right; got < menuKeepOpenRight-0.01 || got > menuKeepOpenRight+0.01 {
t.Errorf("item %d: menu width past the badge = %v, want %v", i, got, menuKeepOpenRight)
}
}
})
}
// TestMenuKeepOpenViewFollowsMenuWidth checks a row whose item is wider than
// the widest KeepOpen row: a long item NSMenu draws itself sets the menu's
// width, AppKit widens the view to fill it, and the backdrop must cover the
// row rather than stopping halfway, with the badge still at the right inset.
func TestMenuKeepOpenViewFollowsMenuWidth(t *testing.T) {
load()
registerMenuTarget()
withPool(func() {
b := &Backend{}
items := []*platform.MenuItem{
{ID: 1, Label: "Node", Badge: "3 ms", KeepOpen: true,
BadgeShape: platform.BadgeShapeSquare, BadgeAlign: platform.BadgeAlignRight,
BadgeColor: &platform.Color{R: 52, G: 199, B: 89, A: 255},
Visible: true, Enabled: true},
{ID: 2, Label: "A long item NSMenu draws itself, which makes the menu wider than its views",
Visible: true, Enabled: true},
}
menu := b.buildMenu(&platform.Menu{Items: items}, "", 1)
defer dropOwner(1)
native := send(menu, "itemAtIndex:", 0)
view := send(native, "view")
frame := msgRect(view, sel("frame"))
wider := frame.Size.Width + 60
frame.Size.Width = wider
msgSetRect(view, sel("setFrame:"), frame)
// An update while the menu is open recomputes the row: it must keep
// the frame AppKit gave it and lay the row out to that width.
updateKeepOpenView(view, items[0], 0)
retabKeepOpenMenu(native, "Node", "3 ms", platform.BadgeAlignRight)
if got := msgRect(view, sel("frame")).Size.Width; got < wider {
t.Errorf("view width = %v, want at least %v", got, wider)
}
backdrop := menuBackdrop(view)
if got := msgRect(backdrop, sel("frame")).Size.Width; got < wider-8 {
t.Errorf("backdrop width = %v, want %v", got, wider-8)
}
if got := int(send(backdrop, "autoresizingMask")); got&2 == 0 {
t.Errorf("backdrop autoresizing mask = %v, want width-sizable", got)
}
badge := send(view, "viewWithTag:", menuViewBadge)
bf := msgRect(badge, sel("frame"))
if got := wider - (bf.Origin.X + bf.Size.Width); got < menuKeepOpenRight-0.01 || got > menuKeepOpenRight+0.01 {
t.Errorf("room after badge = %v, want %v", got, menuKeepOpenRight)
}
if got := int(send(badge, "autoresizingMask")); got&1 == 0 {
t.Errorf("badge autoresizing mask = %v, want a flexible left margin", got)
}
})
}
+121
View File
@@ -0,0 +1,121 @@
//go:build darwin && !ios
package darwin
import (
"sync"
"time"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
// Network.framework, a C API: no Objective-C objects, no reference
// counting beyond the monitor itself, and blocks instead of a delegate.
var (
nwPathMonitorCreate func() uintptr
nwPathMonitorSetUpdateHandler func(monitor, handler uintptr)
nwPathMonitorSetQueue func(monitor, queue uintptr)
nwPathMonitorStart func(monitor uintptr)
nwPathGetStatus func(path uintptr) int32
nwPathIsExpensive func(path uintptr) bool
nwPathIsConstrained func(path uintptr) bool
dispatchQueueCreate func(label *byte, attr uintptr) uintptr
)
// nw_path_status_satisfied: the path has a usable route to send and
// receive data on.
const nwPathStatusSatisfied = 1
// networkMonitor is the app's single path monitor, started by the first
// Status or Watch. Its handler runs on a queue of its own, so that Status
// can wait on the main thread for the first path, which the monitor
// reports asynchronously, as Chromium's NetworkChangeNotifierApple waits
// for its first connection type.
var networkMonitor struct {
once sync.Once
ready chan struct{} // closed with the first path
mu sync.Mutex
status platform.NetworkStatus
watching bool // on the main thread
}
type network struct{ b *Backend }
func (b *Backend) Network() platform.Network { return network{b} }
// Status returns the status of the monitor's latest path.
func (network) Status() platform.NetworkStatus {
startNetworkMonitor()
select {
case <-networkMonitor.ready:
case <-time.After(time.Second):
// The first path comes within milliseconds; never hang the app
// on a monitor that does not answer.
}
networkMonitor.mu.Lock()
defer networkMonitor.mu.Unlock()
return networkMonitor.status
}
// Watch reports the paths after the first to AppHandler.NetworkChanged.
func (network) Watch() {
networkMonitor.watching = true
startNetworkMonitor()
}
// startNetworkMonitor creates and starts the monitor once. Network.framework
// is loaded only then, by apps that ask.
func startNetworkMonitor() {
networkMonitor.once.Do(func() {
networkMonitor.ready = make(chan struct{})
lib := mustDlopen("/System/Library/Frameworks/Network.framework/Network")
purego.RegisterLibFunc(&nwPathMonitorCreate, lib, "nw_path_monitor_create")
purego.RegisterLibFunc(&nwPathMonitorSetUpdateHandler, lib, "nw_path_monitor_set_update_handler")
purego.RegisterLibFunc(&nwPathMonitorSetQueue, lib, "nw_path_monitor_set_queue")
purego.RegisterLibFunc(&nwPathMonitorStart, lib, "nw_path_monitor_start")
purego.RegisterLibFunc(&nwPathGetStatus, lib, "nw_path_get_status")
purego.RegisterLibFunc(&nwPathIsExpensive, lib, "nw_path_is_expensive")
purego.RegisterLibFunc(&nwPathIsConstrained, lib, "nw_path_is_constrained")
purego.RegisterLibFunc(&dispatchQueueCreate, purego.RTLD_DEFAULT, "dispatch_queue_create")
m := nwPathMonitorCreate()
if m == 0 {
close(networkMonitor.ready)
return
}
first := true
// The handler runs on the monitor's serial queue, never on the main
// thread, and touches no Objective-C object.
blk := newBlock(func(_ objc.Block, path uintptr) {
s := platform.NetworkStatus{
Online: nwPathGetStatus(path) == nwPathStatusSatisfied,
Metered: nwPathIsExpensive(path) || nwPathIsConstrained(path),
}
networkMonitor.mu.Lock()
networkMonitor.status = s
networkMonitor.mu.Unlock()
if first {
first = false
close(networkMonitor.ready)
return
}
theBackend.post(func() {
if networkMonitor.watching {
theBackend.h.NetworkChanged(s)
}
})
})
// The monitor copies the handler.
nwPathMonitorSetUpdateHandler(m, uintptr(blk))
blk.Release()
label := []byte("mygo.network\x00")
nwPathMonitorSetQueue(m, dispatchQueueCreate(&label[0], 0))
// The monitor lives as long as the app.
nwPathMonitorStart(m)
})
}
+255
View File
@@ -0,0 +1,255 @@
//go:build darwin && !ios
package darwin
import (
"sync"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
// Notifications use UNUserNotificationCenter, which only works for apps
// running from a bundle with an identifier.
var (
mainQueueMu sync.Mutex
mainQueue []func()
// Registered by NewNotification so apps without senders do not link Intents.
prepareCommunication func(*Backend, *platform.Notification, id, func(error)) bool
)
// runOnMain runs fn on the main thread; used by callbacks the system
// delivers on background queues.
func (b *Backend) runOnMain(fn func()) {
if b.IsMainThread() {
fn()
return
}
b.post(fn)
}
// post runs fn on the main thread after the current event, even when
// called there.
func (b *Backend) post(fn func()) {
mainQueueMu.Lock()
mainQueue = append(mainQueue, fn)
mainQueueMu.Unlock()
b.Signal()
}
// drainMainQueue runs the functions posted, one at a time, as loop.drain
// does: one running a loop of its own, as a frame showing a modal dialog
// does (drawSoon), leaves those behind it to that loop, signaled again.
func drainMainQueue() {
for {
mainQueueMu.Lock()
if len(mainQueue) == 0 {
mainQueueMu.Unlock()
return
}
fn := mainQueue[0]
mainQueue[0] = nil
mainQueue = mainQueue[1:]
more := len(mainQueue) > 0
mainQueueMu.Unlock()
if more {
theBackend.Signal()
}
fn()
}
}
func registerNotificationDelegate() {
if !hasClass("UNUserNotificationCenter") {
return
}
classDef("MyGoNotificationDelegate", "NSObject", []string{"UNUserNotificationCenterDelegate"}, []objc.MethodDef{
method("userNotificationCenter:willPresentNotification:withCompletionHandler:", func(self id, _ objc.SEL, center, n id, handler uintptr) {
// Show banners even while the app is in the foreground.
callBlock(handler, 1<<1|1<<3|1<<4) // sound | list | banner
}),
method("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:", func(self id, _ objc.SEL, center, resp id, handler uintptr) {
ident := goString(send(send(send(send(resp, "notification"), "request"), "identifier"), "self"))
theBackend.runOnMain(func() { theBackend.h.NotificationClicked(ident) })
callBlock(handler)
}),
})
}
func (b *Backend) NotificationsSupported() bool {
_, packaged := appController{b}.Package()
return packaged && hasClass("UNUserNotificationCenter")
}
// notificationCenter returns the app's notification center. It throws
// when the app does not run from a bundle: check NotificationsSupported
// first.
func notificationCenter() id {
return send(class("UNUserNotificationCenter"), "currentNotificationCenter")
}
// attachNotificationDelegate gives the notification center the delegate
// that receives clicks, at launch: the system delivers the click that
// launched the app before the app has finished launching, and drops it
// when the center has no delegate yet.
func (b *Backend) attachNotificationDelegate() {
if !b.NotificationsSupported() {
return
}
b.notifyDelegate = alloc("MyGoNotificationDelegate")
withPool(func() {
send(notificationCenter(), "setDelegate:", uintptr(b.notifyDelegate))
})
}
// waitingNotification is a notification shown before the user has answered
// whether the app may show notifications.
type waitingNotification struct {
n *platform.Notification
done func(error)
}
// notifyOptions are the permissions asked for: badge, sound and alert.
const notifyOptions = 1<<0 | 1<<1 | 1<<2
func (b *Backend) ShowNotification(n *platform.Notification, done func(error)) {
if !b.NotificationsSupported() {
done(platform.ErrUnsupported)
return
}
if b.notifyAnswered {
b.addNotification(n, done)
return
}
// The system drops what it is given before the user has answered
// whether the app may show notifications, so the first notification
// asks and the ones shown meanwhile wait for the answer. The system
// only prompts the first time; afterwards it answers at once, and
// adding a notification fails when System Settings does not allow it.
b.notifyWaiting = append(b.notifyWaiting, waitingNotification{n, done})
if len(b.notifyWaiting) > 1 {
return
}
withPool(func() {
blk := newBlock(func(_ objc.Block, granted bool, err id) {
b.runOnMain(func() {
b.notifyAnswered = true
waiting := b.notifyWaiting
b.notifyWaiting = nil
for _, w := range waiting {
b.addNotification(w.n, w.done)
}
})
})
send(notificationCenter(), "requestAuthorizationWithOptions:completionHandler:",
notifyOptions, uintptr(blk))
blk.Release()
})
}
// addNotification gives the system a request to show a notification. Its
// trigger is nil, which shows it at once.
func (b *Backend) addNotification(n *platform.Notification, done func(error)) {
b.cancelPreparingNotification(n.ID)
withPool(func() {
content := autorelease(alloc("UNMutableNotificationContent"))
send(content, "setTitle:", uintptr(nsString(n.Title)))
if n.Subtitle != "" {
send(content, "setSubtitle:", uintptr(nsString(n.Subtitle)))
}
send(content, "setBody:", uintptr(nsString(n.Body)))
if !n.Silent {
send(content, "setSound:", uintptr(send(class("UNNotificationSound"), "defaultSound")))
}
if n.Group != "" {
send(content, "setThreadIdentifier:", uintptr(nsString(n.Group)))
}
if len(n.Image) > 0 && attachNotificationImage != nil {
done = attachNotificationImage(content, n.Image, done)
}
if n.Sender != nil && prepareCommunication != nil && prepareCommunication(b, n, content, done) {
return
}
b.submitNotification(n, content, done)
})
}
func (b *Backend) submitNotification(n *platform.Notification, content id, done func(error)) {
req := send(class("UNNotificationRequest"), "requestWithIdentifier:content:trigger:",
uintptr(nsString(n.ID)), uintptr(content), 0)
blk := newBlock(func(_ objc.Block, nsErr id) {
// The error is the caller's only while the block runs.
var err error
withPool(func() { err = notificationError(nsErr) })
b.runOnMain(func() { done(err) })
})
send(notificationCenter(), "addNotificationRequest:withCompletionHandler:", uintptr(req), uintptr(blk))
blk.Release()
}
func (b *Backend) cancelPreparingNotification(ident string) {
if cancel := b.notifyPreparing[ident]; cancel != nil {
delete(b.notifyPreparing, ident)
cancel()
}
}
// unErrorNotificationsNotAllowed is UNErrorCodeNotificationsNotAllowed.
const unErrorNotificationsNotAllowed = 1
// notificationError describes an error of the notification center.
func notificationError(err id) error {
if err == 0 {
return nil
}
if goString(send(err, "domain")) == "UNErrorDomain" && sendInt(err, "code") == unErrorNotificationsNotAllowed {
return platform.ErrNotificationsDenied
}
return nsError(err)
}
func (b *Backend) RemoveNotification(ident string) {
b.cancelPreparingNotification(ident)
if !b.NotificationsSupported() {
return
}
// One still waiting for the user's answer is not shown.
waiting := b.notifyWaiting[:0]
for _, w := range b.notifyWaiting {
if w.n.ID == ident {
w.done(nil)
} else {
waiting = append(waiting, w)
}
}
b.notifyWaiting = waiting
withPool(func() {
center := notificationCenter()
ids := nsArray(nsString(ident))
send(center, "removeDeliveredNotificationsWithIdentifiers:", uintptr(ids))
send(center, "removePendingNotificationRequestsWithIdentifiers:", uintptr(ids))
})
}
func (b *Backend) RemoveAllNotifications() {
preparing := b.notifyPreparing
b.notifyPreparing = nil
for _, cancel := range preparing {
cancel()
}
if !b.NotificationsSupported() {
return
}
waiting := b.notifyWaiting
b.notifyWaiting = nil
for _, w := range waiting {
w.done(nil)
}
withPool(func() {
center := notificationCenter()
send(center, "removeAllDeliveredNotifications")
send(center, "removeAllPendingNotificationRequests")
})
}
+168
View File
@@ -0,0 +1,168 @@
//go:build darwin && !ios
package darwin
import (
"cmp"
"sync"
"unsafe"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
var enableNotificationSenders sync.Once
// EnableNotificationSenders registers the opt-in translator before a sender
// notification can reach the backend. Later constructors only read the Once.
func EnableNotificationSenders() {
enableNotificationSenders.Do(func() { prepareCommunication = (*Backend).addCommunicationNotification })
}
var communicationAuthorization struct {
once sync.Once
granted bool
}
func communicationAuthorized() bool {
communicationAuthorization.once.Do(func() { communicationAuthorization.granted = checkCommunicationAuthorization() })
return communicationAuthorization.granted
}
func checkCommunicationAuthorization() bool {
lib, err := purego.Dlopen("/System/Library/Frameworks/Intents.framework/Intents", purego.RTLD_GLOBAL|purego.RTLD_NOW)
if err != nil || lib == 0 || !hasClass("INSendMessageIntent") || !sendBool(class("UNMutableNotificationContent"), "instancesRespondToSelector:", uintptr(sel("contentByUpdatingWithProvider:error:"))) {
return false
}
security, err := purego.Dlopen("/System/Library/Frameworks/Security.framework/Security", purego.RTLD_NOW)
if err != nil {
return false
}
var createTask func(uintptr) uintptr
var copyEntitlement func(uintptr, id, uintptr) id
purego.RegisterLibFunc(&createTask, security, "SecTaskCreateFromSelf")
purego.RegisterLibFunc(&copyEntitlement, security, "SecTaskCopyValueForEntitlement")
task := createTask(0)
if task == 0 {
return false
}
defer cfRelease(task)
value := copyEntitlement(task, nsString("com.apple.developer.usernotifications.communication"), 0)
if value == 0 {
return false
}
defer cfRelease(uintptr(value))
return sendBool(value, "boolValue")
}
// communicationIntent returns an owned intent, or nil for an incomplete sender.
func communicationIntent(n *platform.Notification) id {
s := n.Sender
if s == nil || s.ID == "" || len(s.Avatar) == 0 {
return 0
}
data := communicationAvatar(s.Avatar)
if data == 0 {
return 0
}
// IDs are app-defined, so they are not inferred to be contact details.
handle := send(send(class("INPersonHandle"), "alloc"), "initWithValue:type:", uintptr(nsString(s.ID)), 0)
defer send(handle, "release")
image := send(class("INImage"), "imageWithImageData:", uintptr(data))
person := send(send(class("INPerson"), "alloc"), "initWithPersonHandle:nameComponents:displayName:image:contactIdentifier:customIdentifier:isMe:suggestionType:",
uintptr(handle), 0, uintptr(nsString(s.Name)), uintptr(image), 0, uintptr(nsString(s.ID)), 0, 0)
defer send(person, "release")
body := n.Body
if n.Subtitle != "" {
body = n.Subtitle
if n.Body != "" {
body += "\n" + n.Body
}
}
return send(send(class("INSendMessageIntent"), "alloc"), "initWithRecipients:outgoingMessageType:content:speakableGroupName:conversationIdentifier:serviceName:sender:attachments:",
0, 1, uintptr(nsString(body)), 0, uintptr(nsString(cmp.Or(n.Group, n.ID))), 0, uintptr(person), 0)
}
func communicationInteraction(intent id) id {
interaction := send(send(class("INInteraction"), "alloc"), "initWithIntent:response:", uintptr(intent), 0)
send(interaction, "setDirection:", 2) // incoming
return interaction
}
// communicationContent keeps the ordinary content when conversion fails.
func communicationContent(content, intent id) id {
prepared := autorelease(send(content, "mutableCopy"))
send(prepared, "setBody:", uintptr(send(intent, "content")))
var nativeErr id
updated := send(prepared, "contentByUpdatingWithProvider:error:", uintptr(intent), uintptr(unsafe.Pointer(&nativeErr)))
if nativeErr != 0 || updated == 0 {
return content
}
return updated
}
type preparingNotification struct{ done func(error) }
func (p *preparingNotification) finish(err error) {
if done := p.done; done != nil {
p.done = nil
done(err)
}
}
func (b *Backend) addCommunicationNotification(n *platform.Notification, content id, done func(error)) bool {
if !communicationAuthorized() {
return false
}
intent := communicationIntent(n)
if intent == 0 {
return false
}
if b.notifyPreparing == nil {
b.notifyPreparing = make(map[string]func())
}
p := &preparingNotification{done: done}
b.notifyPreparing[n.ID] = func() { p.finish(nil) }
send(content, "retain")
interaction := communicationInteraction(intent)
blk := newBlock(func(_ objc.Block, nativeErr id) {
failed := nativeErr != 0
b.runOnMain(func() {
withPool(func() {
defer send(content, "release")
defer send(intent, "release")
defer send(interaction, "release")
// Close, Clear or replacement may have canceled this while donating.
if p.done == nil {
return
}
delete(b.notifyPreparing, n.ID)
ready := content
if !failed {
ready = communicationContent(content, intent)
}
b.submitNotification(n, ready, p.finish)
})
})
})
send(interaction, "donateInteractionWithCompletion:", uintptr(blk))
blk.Release()
return true
}
// communicationAvatar returns image bytes accepted by the notification image service.
func communicationAvatar(avatar []byte) id {
data := nsData(avatar)
decoded := send(send(class("NSImage"), "alloc"), "initWithData:", uintptr(data))
if decoded == 0 {
return 0
}
defer send(decoded, "release")
// NSImage accepts SVG, but the Intents image service requires a raster image.
png := pngFromImage(decoded)
if len(png) == 0 {
return 0
}
return nsData(png)
}
@@ -0,0 +1,117 @@
//go:build darwin && !ios
package darwin
import (
"bytes"
"image"
"image/png"
"testing"
"github.com/egoist/mygo/internal/platform"
)
func TestCommunicationIntent(t *testing.T) {
load()
var avatar bytes.Buffer
if err := png.Encode(&avatar, image.NewRGBA(image.Rect(0, 0, 8, 8))); err != nil {
t.Fatal(err)
}
withPool(func() {
if communicationAuthorized() {
t.Fatal("a plain Go test executable has no communication entitlement")
}
n := &platform.Notification{ID: "mail:7", Group: "thread:3", Title: "小明", Subtitle: "午饭", Body: "十二点见",
Sender: &platform.NotificationSender{ID: "ming@example.com", Name: "小明", Avatar: avatar.Bytes()}}
intent := communicationIntent(n)
if intent == 0 {
t.Fatal("no communication intent")
}
defer send(intent, "release")
person := send(intent, "sender")
if goString(send(person, "displayName")) != "小明" || goString(send(person, "customIdentifier")) != "ming@example.com" || send(person, "image") == 0 || sendBool(person, "isMe") {
t.Fatal("incorrect sender identity or avatar")
}
if goString(send(send(person, "personHandle"), "value")) != "ming@example.com" || goString(send(intent, "conversationIdentifier")) != "thread:3" || send(send(intent, "recipients"), "count") != 0 {
t.Fatal("incorrect sender handle or direct conversation")
}
if goString(send(intent, "content")) != "午饭\n十二点见" {
t.Fatal("the subject or body was lost")
}
interaction := communicationInteraction(intent)
defer send(interaction, "release")
if send(interaction, "direction") != 2 {
t.Fatal("received messages must donate an incoming interaction")
}
content := autorelease(alloc("UNMutableNotificationContent"))
send(content, "setBody:", uintptr(nsString("original")))
send(content, "setSound:", uintptr(send(class("UNNotificationSound"), "defaultSound")))
send(content, "setThreadIdentifier:", uintptr(nsString("thread:3")))
updated := communicationContent(content, intent)
if goString(send(updated, "body")) != "午饭\n十二点见" || send(updated, "sound") == 0 || goString(send(updated, "threadIdentifier")) != "thread:3" {
t.Fatal("communication conversion lost content, sound or grouping")
}
if goString(send(content, "body")) != "original" {
t.Fatal("preparing communication changed the ordinary fallback")
}
b := new(Backend)
if b.addCommunicationNotification(n, content, func(error) { t.Fatal("unentitled donation completed") }) || len(b.notifyPreparing) != 0 {
t.Fatal("an unentitled process started donating a communication")
}
n.Group, n.Subtitle = "", ""
fallback := communicationIntent(n)
defer send(fallback, "release")
if goString(send(fallback, "conversationIdentifier")) != "mail:7" || goString(send(fallback, "content")) != "十二点见" || goString(send(send(fallback, "sender"), "displayName")) != "小明" {
t.Fatal("notification ID default, sender name or empty subject were lost")
}
for _, sender := range []*platform.NotificationSender{nil, {Name: "Ada", Avatar: avatar.Bytes()}, {ID: "ada"}, {ID: "ada", Avatar: []byte("not an image")}} {
n.Sender = sender
if intent := communicationIntent(n); intent != 0 {
send(intent, "release")
t.Fatal("incomplete sender must fall back to a plain notification")
}
}
})
}
func TestCommunicationNotificationCancellation(t *testing.T) {
load()
calls := 0
p := &preparingNotification{done: func(error) { calls++ }}
b := &Backend{notifyPreparing: map[string]func(){"mail:7": func() { p.finish(nil) }}}
b.RemoveNotification("mail:7")
p.finish(nil) // a late donation completion must not complete Show twice
if calls != 1 || len(b.notifyPreparing) != 0 || p.done != nil {
t.Fatal("Close left a pending communication or completed it twice")
}
p = &preparingNotification{done: func(error) { calls++ }}
b.notifyPreparing["mail:8"] = func() { p.finish(nil) }
b.RemoveAllNotifications()
p.finish(nil)
if calls != 2 || len(b.notifyPreparing) != 0 || p.done != nil {
t.Fatal("Clear left a pending communication or completed it twice")
}
}
func TestCommunicationAvatarPNG(t *testing.T) {
load()
withPool(func() {
svg := []byte(`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" fill="#2563eb"/></svg>`)
var bitmap bytes.Buffer
if err := png.Encode(&bitmap, image.NewRGBA(image.Rect(0, 0, 8, 8))); err != nil {
t.Fatal(err)
}
for _, input := range [][]byte{svg, bitmap.Bytes()} {
data := communicationAvatar(input)
img, err := png.Decode(bytes.NewReader(goBytes(data)))
if err != nil || img.Bounds().Empty() {
t.Fatalf("notification avatar is not a raster PNG: %v", err)
}
}
for _, input := range [][]byte{nil, []byte("not an image")} {
if communicationAvatar(input) != 0 {
t.Fatal("invalid avatar must keep the ordinary notification")
}
}
})
}
+56
View File
@@ -0,0 +1,56 @@
//go:build darwin && !ios
package darwin
import (
"bytes"
"os"
"unsafe"
)
// attachNotificationImage is attachImage once LinkNotificationImages
// links it: the backend's methods are linked into every app, and only
// call it.
var attachNotificationImage func(content id, image []byte, done func(error)) func(error)
// LinkNotificationImages links the code of notifications' images, when
// the app first makes a notification with one.
func LinkNotificationImages() { attachNotificationImage = attachImage }
// attachImage gives a notification's content its image, as an attachment,
// which UserNotifications makes only of a file, its format told by its
// extension. The system moves the file into its own store as it adds the
// request; done, which attachImage returns wrapped, removes it if it is
// still there. An image the system does not take leaves the content
// without one.
func attachImage(content id, image []byte, done func(error)) func(error) {
ext := ".png"
if bytes.HasPrefix(image, []byte{0xff, 0xd8, 0xff}) {
ext = ".jpg"
}
f, err := os.CreateTemp("", "mygo-notification-*"+ext)
if err != nil {
return done
}
path := f.Name()
_, err = f.Write(image)
if cerr := f.Close(); err == nil {
err = cerr
}
if err != nil {
os.Remove(path)
return done
}
var nsErr id
attachment := send(class("UNNotificationAttachment"), "attachmentWithIdentifier:URL:options:error:",
uintptr(nsString("")), uintptr(fileURL(path)), 0, uintptr(unsafe.Pointer(&nsErr)))
if attachment == 0 {
os.Remove(path)
return done
}
send(content, "setAttachments:", uintptr(nsArray(attachment)))
return func(err error) {
os.Remove(path)
done(err)
}
}
+195
View File
@@ -0,0 +1,195 @@
//go:build darwin && !ios
package darwin
import (
"sync"
"time"
"unsafe"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
func (b *Backend) NowPlaying() platform.NowPlaying { return nowPlaying{b} }
// nowPlaying is MediaPlayer's MPNowPlayingInfoCenter, which Control
// Center and the menu bar show, and MPRemoteCommandCenter, whose commands
// the media keys, headsets and those controls send.
type nowPlaying struct{ b *Backend }
// nowPlayingSet is the code of NowPlaying, which LinkNowPlaying links:
// the backend's methods are linked into every app, and only call it.
var nowPlayingSet func(b *Backend, info *platform.NowPlayingInfo)
// LinkNowPlaying links the code of NowPlaying, when the app first shows
// what it plays.
func LinkNowPlaying() { nowPlayingSet = setNowPlaying }
func (n nowPlaying) Set(info *platform.NowPlayingInfo) {
if nowPlayingSet != nil {
nowPlayingSet(n.b, info)
}
}
// The remote commands, by the command each reports.
var remoteCommands = []struct {
getter string
cmd platform.MediaCommand
}{
{"playCommand", platform.MediaPlay},
{"pauseCommand", platform.MediaPause},
{"togglePlayPauseCommand", platform.MediaTogglePlayPause},
{"stopCommand", platform.MediaStop},
{"nextTrackCommand", platform.MediaNext},
{"previousTrackCommand", platform.MediaPrevious},
{"changePlaybackPositionCommand", platform.MediaSeek},
}
// MPNowPlayingPlaybackState.
const (
mpPlaybackPlaying = 1
mpPlaybackPaused = 2
mpPlaybackStopped = 3
)
var (
libMediaPlayer uintptr
mediaPlayerOnce sync.Once
remoteHandled bool // the commands have their handlers
msgInitArtwork func(obj id, sel objc.SEL, size NSSize, handler objc.Block) id
mediaPlayerProps map[string]id
)
// mediaPlayer loads MediaPlayer.framework and its keys, which it exports
// as NSString constants.
func mediaPlayer() bool {
mediaPlayerOnce.Do(func() {
lib, err := purego.Dlopen("/System/Library/Frameworks/MediaPlayer.framework/MediaPlayer", purego.RTLD_GLOBAL|purego.RTLD_NOW)
if err != nil {
return
}
libMediaPlayer = lib
purego.RegisterFunc(&msgInitArtwork, msgSendAddr)
mediaPlayerProps = map[string]id{}
for _, name := range []string{
"MPMediaItemPropertyTitle", "MPMediaItemPropertyArtist", "MPMediaItemPropertyAlbumTitle",
"MPMediaItemPropertyPlaybackDuration", "MPMediaItemPropertyArtwork",
"MPNowPlayingInfoPropertyElapsedPlaybackTime", "MPNowPlayingInfoPropertyPlaybackRate",
"MPNowPlayingInfoPropertyDefaultPlaybackRate", "MPNowPlayingInfoPropertyMediaType",
} {
if p, err := purego.Dlsym(lib, name); err == nil {
mediaPlayerProps[name] = **(**id)(unsafe.Pointer(&p))
}
}
})
return libMediaPlayer != 0
}
func setNowPlaying(b *Backend, info *platform.NowPlayingInfo) {
if !mediaPlayer() {
return
}
withPool(func() {
center := send(class("MPNowPlayingInfoCenter"), "defaultCenter")
commands := send(class("MPRemoteCommandCenter"), "sharedCommandCenter")
if center == 0 || commands == 0 {
return
}
if !remoteHandled {
remoteHandled = true
for _, c := range remoteCommands {
cmd := c.cmd
// Blocks share one callback per signature (purego's
// cache), and the command keeps its copy for good.
handler := newBlock(func(_ objc.Block, event id) int {
var pos time.Duration
if cmd == platform.MediaSeek {
pos = time.Duration(msgFloat(event, sel("positionTime")) * float64(time.Second))
}
b.runOnMain(func() { b.h.MediaCommand(cmd, pos) })
return 0 // MPRemoteCommandHandlerStatusSuccess
})
send(send(commands, c.getter), "addTargetWithHandler:", uintptr(handler))
handler.Release()
}
}
var enabled platform.MediaCommand
if info != nil {
enabled = info.Commands
if enabled&(platform.MediaPlay|platform.MediaPause) != 0 {
enabled |= platform.MediaTogglePlayPause
}
if info.Duration == 0 {
enabled &^= platform.MediaSeek
}
}
for _, c := range remoteCommands {
send(send(commands, c.getter), "setEnabled:", boolArg(enabled&c.cmd != 0))
}
if info == nil {
send(center, "setNowPlayingInfo:", 0)
send(center, "setPlaybackState:", mpPlaybackStopped)
return
}
d := send(class("NSMutableDictionary"), "dictionary")
put := func(key string, v id) {
if k := mediaPlayerProps[key]; k != 0 && v != 0 {
send(d, "setObject:forKey:", uintptr(v), uintptr(k))
}
}
number := func(v float64) id { return msgFloatID(class("NSNumber"), sel("numberWithDouble:"), v) }
if info.Title != "" {
put("MPMediaItemPropertyTitle", nsString(info.Title))
}
if info.Artist != "" {
put("MPMediaItemPropertyArtist", nsString(info.Artist))
}
if info.Album != "" {
put("MPMediaItemPropertyAlbumTitle", nsString(info.Album))
}
if info.Duration > 0 {
put("MPMediaItemPropertyPlaybackDuration", number(info.Duration.Seconds()))
}
put("MPNowPlayingInfoPropertyMediaType", nsNumberInt(1)) // MPNowPlayingInfoMediaTypeAudio
put("MPNowPlayingInfoPropertyElapsedPlaybackTime", number(info.Position.Seconds()))
put("MPNowPlayingInfoPropertyDefaultPlaybackRate", number(1))
rate, state := 0.0, mpPlaybackPaused
switch info.State {
case "playing":
rate, state = info.Rate, mpPlaybackPlaying
case "stopped":
state = mpPlaybackStopped
}
put("MPNowPlayingInfoPropertyPlaybackRate", number(rate))
if art := artwork(info.Artwork); art != 0 {
put("MPMediaItemPropertyArtwork", art)
}
send(center, "setNowPlayingInfo:", uintptr(d))
send(center, "setPlaybackState:", uintptr(state))
})
}
// artwork returns an autoreleased MPMediaItemArtwork of a PNG or JPEG, or
// 0. Its handler decodes the image whenever the system asks, from the
// bytes it holds, so no image outlives the artwork.
func artwork(data []byte) id {
if len(data) == 0 || msgInitArtwork == nil {
return 0
}
img := send(send(class("NSImage"), "alloc"), "initWithData:", uintptr(nsData(data)))
if img == 0 {
return 0
}
size := msgSize(img, sel("size"))
release(img)
// The handler takes a CGSize, which goes as two doubles.
handler := newBlock(func(_ objc.Block, w, h float64) id {
return autorelease(send(send(class("NSImage"), "alloc"), "initWithData:", uintptr(nsData(data))))
})
defer handler.Release()
art := msgInitArtwork(send(class("MPMediaItemArtwork"), "alloc"), sel("initWithBoundsSize:requestHandler:"), size, handler)
return autorelease(art)
}
+530
View File
@@ -0,0 +1,530 @@
//go:build darwin && !ios
// Package darwin implements the macOS backend (AppKit + WKWebView) in pure
// Go: Objective-C is driven through the runtime with purego, no cgo.
package darwin
import (
"fmt"
"runtime"
"strings"
"sync"
"unsafe"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
)
type id = objc.ID
// NSPoint, NSSize and NSRect mirror the CoreGraphics structs (64-bit).
type NSPoint struct{ X, Y float64 }
type NSSize struct{ Width, Height float64 }
type NSRect struct {
Origin NSPoint
Size NSSize
}
// caFrameRateRange mirrors Core Animation's CAFrameRateRange.
type caFrameRateRange struct{ Minimum, Maximum, Preferred float32 }
var (
msgSendAddr uintptr
msgSendSuperAddr uintptr
// Typed variants of objc_msgSend for float and struct arguments.
msgRect func(obj id, sel objc.SEL) NSRect
msgSetRect func(obj id, sel objc.SEL, r NSRect)
msgSetRectBool func(obj id, sel objc.SEL, r NSRect, b bool)
msgRectForRect func(obj id, sel objc.SEL, r NSRect, style uint) NSRect
msgRectToRect func(obj id, sel objc.SEL, r NSRect) NSRect
msgConvertRectView func(obj id, sel objc.SEL, r NSRect, view id) NSRect
msgFloat func(obj id, sel objc.SEL) float64
msgFloat32 func(obj id, sel objc.SEL) float32
msgSetFloat func(obj id, sel objc.SEL, v float64)
msgSize func(obj id, sel objc.SEL) NSSize
msgSetSize func(obj id, sel objc.SEL, s NSSize)
msgSuperSetSize func(sup uintptr, sel objc.SEL, s NSSize)
msgSuperPoint func(sup uintptr, sel objc.SEL, p NSPoint) id
msgPoint func(obj id, sel objc.SEL) NSPoint
msgSetPoint func(obj id, sel objc.SEL, p NSPoint)
msgInitRect func(obj id, sel objc.SEL, r NSRect) id
msgInitRectID func(obj id, sel objc.SEL, r NSRect, a id) id
msgRectIDUint func(obj id, sel objc.SEL, r NSRect, a id, n uint)
msgInitIDPoint func(obj id, sel objc.SEL, a id, p NSPoint) id
msgInitWindow func(obj id, sel objc.SEL, r NSRect, style uint, backing uint, deferFlag bool) id
msgColor func(cls id, sel objc.SEL, r, g, b, a float64) id
msgOtherEvent func(cls id, sel objc.SEL, typ uint, loc NSPoint, flags uint, ts float64, wn int, ctx id, subtype int16, d1, d2 int) id
msgPopUpMenu func(menu id, sel objc.SEL, item id, loc NSPoint, view id) bool
msgNextEvent func(app id, sel objc.SEL, mask uint64, until id, mode id, dequeue bool) id
msgPointFromView func(obj id, sel objc.SEL, p NSPoint, view id) NSPoint
msgDateSince func(cls id, sel objc.SEL, seconds float64) id
msgFloatID func(obj id, sel objc.SEL, v float64) id
msgFloat2ID func(obj id, sel objc.SEL, a, b float64) id
msgFontFamily func(obj id, sel objc.SEL, family id, traits uint, weight int, size float64) id
msgMouseEvent func(cls id, sel objc.SEL, typ uint, loc NSPoint, flags uint, ts float64, wn int, ctx id, eventNumber int, clickCount int, pressure float32) id
msgHitTest func(obj id, sel objc.SEL, p NSPoint) id
msgKeyEvent func(cls id, sel objc.SEL, typ uint, loc NSPoint, flags uint, ts float64, wn int, ctx id, chars, charsIgnoring id, repeat bool, keyCode uint16) id
msgDrawImage func(obj id, sel objc.SEL, dst, src NSRect, op uint, fraction float64)
msgInitBitmap func(obj id, sel objc.SEL, planes uintptr, width, height, bitsPerSample, samplesPerPixel int, alpha, planar bool, colorSpace id, bytesPerRow, bitsPerPixel int) id
msgInitTextTab func(obj id, sel objc.SEL, alignment uint, location float64, options id) id
msgInitMenuTrack func(obj id, sel objc.SEL, r NSRect, options uint, owner, info id) id
msgSetRateRange func(obj id, sel objc.SEL, r caFrameRateRange)
blockCopy func(block uintptr) uintptr
blockRelease func(block uintptr)
// Functions on hot paths, called by address: RegisterFunc's wrappers
// use reflection and allocate on every call.
poolPushFn, poolPopFn, mainNPFn uintptr
)
func mustDlsym(lib uintptr, name string) uintptr {
p, err := purego.Dlsym(lib, name)
if err != nil {
panic(fmt.Sprintf("mygo: %v", err))
}
return p
}
func mustDlopen(path string) uintptr {
h, err := purego.Dlopen(path, purego.RTLD_GLOBAL|purego.RTLD_NOW)
if err != nil {
panic(fmt.Sprintf("mygo: cannot load %s: %v", path, err))
}
return h
}
var (
libObjC, libCF, libCG, libAppKit, libWebKit, libFoundation, libCarbon uintptr
libCoreServices uintptr
loadOnce sync.Once
)
// load opens the frameworks and prepares the typed message functions.
func load() {
loadOnce.Do(func() {
libObjC = mustDlopen("/usr/lib/libobjc.A.dylib")
libFoundation = mustDlopen("/System/Library/Frameworks/Foundation.framework/Foundation")
libCF = mustDlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
libCG = mustDlopen("/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics")
libAppKit = mustDlopen("/System/Library/Frameworks/AppKit.framework/AppKit")
libWebKit = mustDlopen("/System/Library/Frameworks/WebKit.framework/WebKit")
libCarbon = mustDlopen("/System/Library/Frameworks/Carbon.framework/Carbon")
libCoreServices = mustDlopen("/System/Library/Frameworks/CoreServices.framework/CoreServices")
// Optional frameworks, loaded so their classes are registered.
_, _ = purego.Dlopen("/System/Library/Frameworks/UniformTypeIdentifiers.framework/UniformTypeIdentifiers", purego.RTLD_GLOBAL|purego.RTLD_NOW)
_, _ = purego.Dlopen("/System/Library/Frameworks/UserNotifications.framework/UserNotifications", purego.RTLD_GLOBAL|purego.RTLD_NOW)
_, _ = purego.Dlopen("/System/Library/Frameworks/ServiceManagement.framework/ServiceManagement", purego.RTLD_GLOBAL|purego.RTLD_NOW)
var err error
msgSendAddr, err = purego.Dlsym(libObjC, "objc_msgSend")
if err != nil {
panic(err)
}
// Methods returning structs larger than 16 bytes use a different
// entry point on amd64.
stret := msgSendAddr
if runtime.GOARCH == "amd64" {
stret, err = purego.Dlsym(libObjC, "objc_msgSend_stret")
if err != nil {
panic(err)
}
}
msgSendSuperAddr, err = purego.Dlsym(libObjC, "objc_msgSendSuper")
if err != nil {
panic(err)
}
purego.RegisterFunc(&msgRect, stret)
purego.RegisterFunc(&msgRectForRect, stret)
purego.RegisterFunc(&msgRectToRect, stret)
purego.RegisterFunc(&msgConvertRectView, stret)
purego.RegisterFunc(&msgSetRect, msgSendAddr)
purego.RegisterFunc(&msgDrawImage, msgSendAddr)
purego.RegisterFunc(&msgInitBitmap, msgSendAddr)
purego.RegisterFunc(&msgInitTextTab, msgSendAddr)
purego.RegisterFunc(&msgInitMenuTrack, msgSendAddr)
purego.RegisterFunc(&msgSetRateRange, msgSendAddr)
purego.RegisterFunc(&msgSetRectBool, msgSendAddr)
purego.RegisterFunc(&msgFloat, msgSendAddr)
purego.RegisterFunc(&msgFloat32, msgSendAddr)
purego.RegisterFunc(&msgSetFloat, msgSendAddr)
purego.RegisterFunc(&msgSize, msgSendAddr)
purego.RegisterFunc(&msgSetSize, msgSendAddr)
purego.RegisterFunc(&msgSuperSetSize, msgSendSuperAddr)
purego.RegisterFunc(&msgSuperPoint, msgSendSuperAddr)
purego.RegisterFunc(&msgPoint, msgSendAddr)
purego.RegisterFunc(&msgSetPoint, msgSendAddr)
purego.RegisterFunc(&msgInitRect, msgSendAddr)
purego.RegisterFunc(&msgInitRectID, msgSendAddr)
purego.RegisterFunc(&msgRectIDUint, msgSendAddr)
purego.RegisterFunc(&msgInitIDPoint, msgSendAddr)
purego.RegisterFunc(&msgInitWindow, msgSendAddr)
purego.RegisterFunc(&msgColor, msgSendAddr)
purego.RegisterFunc(&msgOtherEvent, msgSendAddr)
purego.RegisterFunc(&msgPopUpMenu, msgSendAddr)
purego.RegisterFunc(&msgNextEvent, msgSendAddr)
purego.RegisterFunc(&msgPointFromView, msgSendAddr)
purego.RegisterFunc(&msgDateSince, msgSendAddr)
purego.RegisterFunc(&msgFloatID, msgSendAddr)
purego.RegisterFunc(&msgFloat2ID, msgSendAddr)
purego.RegisterFunc(&msgFontFamily, msgSendAddr)
purego.RegisterFunc(&msgKeyEvent, msgSendAddr)
purego.RegisterFunc(&msgMouseEvent, msgSendAddr)
purego.RegisterFunc(&msgHitTest, msgSendAddr)
poolPushFn = mustDlsym(libObjC, "objc_autoreleasePoolPush")
poolPopFn = mustDlsym(libObjC, "objc_autoreleasePoolPop")
purego.RegisterLibFunc(&blockCopy, libObjC, "_Block_copy")
purego.RegisterLibFunc(&blockRelease, libObjC, "_Block_release")
mainNPFn = mustDlsym(purego.RTLD_DEFAULT, "pthread_main_np")
loadCF()
})
}
var (
selMu sync.RWMutex
selCache = map[string]objc.SEL{}
clsCache = map[string]id{}
superCache = map[string]id{}
)
// sel returns the selector for name, cached.
func sel(name string) objc.SEL {
selMu.RLock()
s, ok := selCache[name]
selMu.RUnlock()
if ok {
return s
}
s = objc.RegisterName(name)
selMu.Lock()
selCache[name] = s
selMu.Unlock()
return s
}
// class returns the class object for name, cached. It panics for classes
// that do not exist since that is a programming error.
func class(name string) id {
selMu.RLock()
c, ok := clsCache[name]
selMu.RUnlock()
if ok {
return c
}
c = id(objc.GetClass(name))
if c == 0 {
panic("mygo: Objective-C class " + name + " not found")
}
selMu.Lock()
clsCache[name] = c
selMu.Unlock()
return c
}
// hasClass reports whether a class exists (for APIs of newer macOS versions).
func hasClass(name string) bool { return objc.GetClass(name) != 0 }
// send sends a message whose arguments are integers or pointers. Go
// pointers converted in the call, as in uintptr(unsafe.Pointer(&x)), are
// moved to the heap and kept alive until it returns (go:uintptrescapes):
// otherwise stack growth could move x while Objective-C uses it.
//
//go:uintptrescapes
func send(obj id, selector string, args ...uintptr) id {
return sendSel(obj, sel(selector), args...)
}
//go:uintptrescapes
func sendSel(obj id, s objc.SEL, args ...uintptr) id {
var a [12]uintptr
a[0], a[1] = uintptr(obj), uintptr(s)
n := copy(a[2:], args)
r, _, _ := purego.SyscallN(msgSendAddr, a[:n+2]...)
return id(r)
}
// sendBool sends a message returning BOOL.
//
//go:uintptrescapes
func sendBool(obj id, selector string, args ...uintptr) bool {
return byte(send(obj, selector, args...)) != 0
}
// sendInt sends a message returning NSInteger.
//
//go:uintptrescapes
func sendInt(obj id, selector string, args ...uintptr) int {
return int(send(obj, selector, args...))
}
// objcSuper mirrors struct objc_super.
type objcSuper struct {
receiver id
superClass id
}
// superOf returns the struct objc_super that calls the superclass of
// className with self, pinned until pin is unpinned: passed as an integer,
// it must stay off the stack, which may move. The superclass is resolved
// from className rather than from the object's class, which the runtime may
// replace with a generated subclass (key-value observing does): resolving
// "super" from it would call the override again and recurse forever.
func superOf(self id, className string, pin *runtime.Pinner) uintptr {
sup := &objcSuper{receiver: self, superClass: superclass(className)}
pin.Pin(sup)
return uintptr(unsafe.Pointer(sup))
}
// superclass returns the superclass of a class, cached: overrides call it
// as often as AppKit calls them, as setFrameSize: while a window resizes.
func superclass(name string) id {
selMu.RLock()
c, ok := superCache[name]
selMu.RUnlock()
if ok {
return c
}
c = id(objc.Class(class(name)).SuperClass())
selMu.Lock()
superCache[name] = c
selMu.Unlock()
return c
}
// sendSuper calls the superclass implementation of a method overridden in
// className (see superOf).
//
//go:uintptrescapes
func sendSuper(self id, className string, s objc.SEL, args ...uintptr) id {
var pin runtime.Pinner
defer pin.Unpin()
var a [10]uintptr
a[0], a[1] = superOf(self, className, &pin), uintptr(s)
n := copy(a[2:], args)
r, _, _ := purego.SyscallN(msgSendSuperAddr, a[:n+2]...)
return id(r)
}
// sendSuperSize is sendSuper for a method taking an NSSize, which travels in
// floating-point registers and so cannot go through the integer arguments.
func sendSuperSize(self id, className string, s objc.SEL, size NSSize) {
var pin runtime.Pinner
defer pin.Unpin()
msgSuperSetSize(superOf(self, className, &pin), s, size)
}
// sendSuperPoint is sendSuper for a method taking an NSPoint and
// returning an object, as hitTest:.
func sendSuperPoint(self id, className string, s objc.SEL, p NSPoint) id {
var pin runtime.Pinner
defer pin.Unpin()
return msgSuperPoint(superOf(self, className, &pin), s, p)
}
func respondsTo(obj id, selector string) bool {
return obj != 0 && sendBool(obj, "respondsToSelector:", uintptr(sel(selector)))
}
func boolArg(b bool) uintptr {
if b {
return 1
}
return 0
}
func retain(obj id) id {
if obj == 0 {
return 0
}
return send(obj, "retain")
}
func release(obj id) {
if obj != 0 {
send(obj, "release")
}
}
func autorelease(obj id) id {
if obj == 0 {
return 0
}
return send(obj, "autorelease")
}
// appKitString returns an NSString constant that AppKit exports, such as
// NSPrintJobSavingURL, whose value may differ from its name.
func appKitString(name string) id {
p, err := purego.Dlsym(libAppKit, name)
if err != nil {
return nsString(name)
}
return **(**id)(unsafe.Pointer(&p))
}
// alloc creates an owned (+1) instance of a class with init.
func alloc(className string) id {
return send(send(class(className), "alloc"), "init")
}
// withPool runs fn inside an autorelease pool. A pool belongs to the thread
// that pushed it, and popping it on another one crashes, so the goroutine
// stays on its thread meanwhile: off the main thread, where public methods
// such as App.Name read the bundle, it would move between threads.
func withPool(fn func()) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
pool, _, _ := purego.SyscallN(poolPushFn)
defer purego.SyscallN(poolPopFn, pool)
fn()
}
const nsUTF8StringEncoding = 4
// nsString returns an autoreleased NSString.
func nsString(s string) id {
b := unsafe.StringData(s)
str := send(send(class("NSString"), "alloc"), "initWithBytes:length:encoding:",
uintptr(unsafe.Pointer(b)), uintptr(len(s)), nsUTF8StringEncoding)
runtime.KeepAlive(s)
return autorelease(str)
}
// goString copies an NSString into a Go string.
func goString(str id) string {
if str == 0 {
return ""
}
p := send(str, "UTF8String")
if p == 0 {
return ""
}
n := sendInt(str, "lengthOfBytesUsingEncoding:", nsUTF8StringEncoding)
return string(unsafe.Slice(*(**byte)(unsafe.Pointer(&p)), n))
}
// nsData returns an autoreleased NSData with a copy of b.
func nsData(b []byte) id {
var p unsafe.Pointer
if len(b) > 0 {
p = unsafe.Pointer(&b[0])
}
d := send(class("NSData"), "dataWithBytes:length:", uintptr(p), uintptr(len(b)))
runtime.KeepAlive(b)
return d
}
// goBytes copies the contents of an NSData.
func goBytes(data id) []byte {
if data == 0 {
return nil
}
n := sendInt(data, "length")
if n == 0 {
return []byte{}
}
p := send(data, "bytes")
return append([]byte(nil), unsafe.Slice(*(**byte)(unsafe.Pointer(&p)), n)...)
}
func nsURL(s string) id { return send(class("NSURL"), "URLWithString:", uintptr(nsString(s))) }
// filePathURLBytes resolves a file reference URL (file:///.file/id=…,
// which Finder puts on the pasteboard when it drags or copies files) to a
// file URL of its path. Other URLs come back unchanged.
func filePathURLBytes(b []byte) []byte {
s := strings.TrimRight(string(b), "\x00")
if !strings.HasPrefix(s, "file:///.file/") {
return b
}
u := nsURL(s)
if u == 0 {
return b
}
if p := send(u, "filePathURL"); p != 0 {
if r := goString(send(p, "absoluteString")); r != "" {
return []byte(r)
}
}
return b
}
func fileURL(path string) id {
return send(class("NSURL"), "fileURLWithPath:", uintptr(nsString(path)))
}
// nsArray returns an autoreleased NSArray of objs.
func nsArray(objs ...id) id {
arr := send(class("NSMutableArray"), "arrayWithCapacity:", uintptr(len(objs)))
for _, o := range objs {
send(arr, "addObject:", uintptr(o))
}
return arr
}
func arrayItems(arr id) []id {
if arr == 0 {
return nil
}
n := sendInt(arr, "count")
out := make([]id, n)
for i := range n {
out[i] = send(arr, "objectAtIndex:", uintptr(i))
}
return out
}
func nsNumberInt(v int) id { return send(class("NSNumber"), "numberWithLongLong:", uintptr(v)) }
func nsBool(v bool) id { return send(class("NSNumber"), "numberWithBool:", boolArg(v)) }
// callBlock invokes an Objective-C block received from the system, such as
// a WebKit completion handler.
func callBlock(block uintptr, args ...uintptr) {
lit := *(**[3]uintptr)(unsafe.Pointer(&block))
var a [8]uintptr
a[0] = block
n := copy(a[1:], args)
purego.SyscallN(lit[2], a[:n+1]...)
}
// newBlock creates a block backed by a Go function. The function must take
// objc.Block as its first parameter.
func newBlock(fn any) objc.Block { return objc.NewBlock(fn) }
// nsError describes an NSError, preferring the JavaScript exception message
// WebKit attaches.
func nsError(err id) error {
if err == 0 {
return nil
}
info := send(err, "userInfo")
if msg := send(info, "objectForKey:", uintptr(nsString("WKJavaScriptExceptionMessage"))); msg != 0 {
return fmt.Errorf("%s", goString(msg))
}
return fmt.Errorf("%s", goString(send(err, "localizedDescription")))
}
// classDef builds an Objective-C class once.
func classDef(name, super string, protocols []string, methods []objc.MethodDef) id {
var ps []*objc.Protocol
for _, p := range protocols {
if proto := objc.GetProtocol(p); proto != nil {
ps = append(ps, proto)
}
}
c, err := objc.RegisterClass(name, objc.GetClass(super), ps, nil, methods)
if err != nil {
panic(fmt.Sprintf("mygo: cannot register class %s: %v", name, err))
}
selMu.Lock()
clsCache[name] = id(c)
selMu.Unlock()
return id(c)
}
func method(selector string, fn any) objc.MethodDef {
return objc.MethodDef{Cmd: sel(selector), Fn: fn}
}
+40
View File
@@ -0,0 +1,40 @@
//go:build darwin && !ios
package darwin
import (
"go/ast"
"go/parser"
"go/token"
"path/filepath"
"strings"
"testing"
)
// TestSuperFromDefinedClass rejects purego's objc.ID.SendSuper, which
// resolves super from the object's class: once key-value observing gives
// the object a subclass of its own, it calls the override again, until the
// stack overflows. Overrides call sendSuper with the class they are defined
// in.
func TestSuperFromDefinedClass(t *testing.T) {
files, err := filepath.Glob("*.go")
if err != nil {
t.Fatal(err)
}
fset := token.NewFileSet()
for _, name := range files {
if strings.HasSuffix(name, "_test.go") {
continue
}
f, err := parser.ParseFile(fset, name, nil, 0)
if err != nil {
t.Fatal(err)
}
ast.Inspect(f, func(n ast.Node) bool {
if s, ok := n.(*ast.SelectorExpr); ok && s.Sel.Name == "SendSuper" {
t.Errorf("%s: SendSuper resolves super from the object's class; call sendSuper", fset.Position(s.Pos()))
}
return true
})
}
}
+106
View File
@@ -0,0 +1,106 @@
//go:build darwin && !ios
package darwin
import (
"runtime"
"testing"
"github.com/ebitengine/purego"
"github.com/egoist/mygo/internal/platform"
)
func TestKeyAtCodeANSI(t *testing.T) {
// Carbon Events.h kVK_ANSI_* values.
want := map[uint16]platform.Key{
0x00: platform.KeyA, 0x01: platform.KeyS, 0x06: platform.KeyZ, 0x09: platform.KeyV, 0x0B: platform.KeyB,
0x10: platform.KeyY, 0x2E: platform.KeyM, 0x2D: platform.KeyN, 0x1F: platform.KeyO, 0x23: platform.KeyP,
0x12: platform.Key1, 0x13: platform.Key2, 0x14: platform.Key3, 0x15: platform.Key4, 0x17: platform.Key5,
0x16: platform.Key6, 0x1A: platform.Key7, 0x1C: platform.Key8, 0x19: platform.Key9, 0x1D: platform.Key0,
0x18: platform.KeyEqual, 0x1B: platform.KeyMinus, 0x1E: platform.KeyBracketRight, 0x21: platform.KeyBracketLeft,
0x27: platform.KeyQuote, 0x29: platform.KeySemicolon, 0x2A: platform.KeyBackslash, 0x2B: platform.KeyComma,
0x2C: platform.KeySlash, 0x2F: platform.KeyPeriod, 0x32: platform.KeyBackquote,
// Non-text keys come from macKeys.
0x24: platform.KeyEnter, 0x31: platform.KeySpace, 0x7B: platform.KeyLeft,
}
for code, k := range want {
if got := keyAtCode(code); got != k {
t.Errorf("code %#x: got %v, want %v", code, got, k)
}
}
if keyAtCode(0x0A) != platform.KeyUnknown || keyAtCode(0x7F) != platform.KeyUnknown {
t.Error("unmapped codes must be KeyUnknown")
}
// Letters cover all 26 keys exactly once.
seen := map[platform.Key]bool{}
for _, k := range ansiKeys {
if seen[k] {
t.Errorf("key %v mapped twice", k)
}
seen[k] = true
}
if len(ansiKeys) != 26+10+11 {
t.Errorf("ansiKeys has %d entries, want 47", len(ansiKeys))
}
}
func TestKeyboardLayoutType(t *testing.T) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
lib, err := purego.Dlopen("/System/Library/Frameworks/Carbon.framework/Carbon", purego.RTLD_NOW)
if err != nil {
t.Fatal(err)
}
defer purego.Dlclose(lib)
var layoutType func(int16) uint32
purego.RegisterLibFunc(&layoutType, lib, "KBGetLayoutType")
// Gestalt.h identifies these keyboard types as third-party ANSI/ISO.
if got := layoutType(40); got != 0x414E5349 { // kKeyboardANSI
t.Errorf("ANSI keyboard layout type: got %#x", got)
}
if got := layoutType(41); got != macISOLayoutType {
t.Errorf("ISO keyboard layout type: got %#x", got)
}
}
func TestKeyAtCodeISO(t *testing.T) {
// ISO swaps the upper-left key's virtual code with the extra key beside
// left Shift. The latter has no platform.Key counterpart.
if got := keyAtCodeForLayout(0x0A, macISOLayoutType); got != platform.KeyBackquote {
t.Errorf("ISO upper-left key: got %v, want KeyBackquote", got)
}
if got := keyAtCodeForLayout(0x32, macISOLayoutType); got != platform.KeyUnknown {
t.Errorf("ISO extra key: got %v, want KeyUnknown", got)
}
if got := keyAtCodeForLayout(0x01, macISOLayoutType); got != platform.KeyS {
t.Errorf("ISO S key: got %v, want KeyS", got)
}
for _, layout := range []uint32{0x414E5349, 0} { // kKeyboardANSI, unknown
if got := keyAtCodeForLayout(0x32, layout); got != platform.KeyBackquote {
t.Errorf("layout %#x upper-left key: got %v, want KeyBackquote", layout, got)
}
if got := keyAtCodeForLayout(0x0A, layout); got != platform.KeyUnknown {
t.Errorf("layout %#x ISO-only key: got %v, want KeyUnknown", layout, got)
}
}
}
func TestKeyCodeForLayout(t *testing.T) {
const ansi = 0
for _, c := range []struct {
code uint16
layout uint32
want platform.KeyCode
}{
{macANSIGraveCode, ansi, platform.CodeBackquote},
{macISOSectionCode, ansi, platform.CodeIntlBackslash},
{macISOSectionCode, macISOLayoutType, platform.CodeBackquote},
{macANSIGraveCode, macISOLayoutType, platform.CodeIntlBackslash},
{0x00, macISOLayoutType, platform.CodeKeyA},
} {
if got := keyCodeForLayout(c.code, c.layout); got != c.want {
t.Errorf("code %#x, layout %#x: got %#x, want %#x", c.code, c.layout, got, c.want)
}
}
}
+32
View File
@@ -0,0 +1,32 @@
//go:build darwin && !ios
package darwin
import (
"runtime"
"sync"
"testing"
)
// TestPoolOffMainThread pushes and pops autorelease pools from many
// goroutines, as public methods that call native code directly do
// (App.Name reads the bundle): a pool belongs to the thread that pushed
// it, and popping it on another one, where a goroutine yielding in between
// may resume, crashes.
func TestPoolOffMainThread(t *testing.T) {
load()
defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(max(4, runtime.NumCPU())))
var wg sync.WaitGroup
for range 32 {
wg.Go(func() {
for range 100 {
withPool(func() {
nsString("pool")
runtime.Gosched()
})
appController{}.Package()
}
})
}
wg.Wait()
}
+324
View File
@@ -0,0 +1,324 @@
//go:build darwin && !ios
package darwin
import (
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
// A flyout with Flyout.Popover shows its web view or surface in an
// NSPopover, which draws the system's material and arrow, and animates.
// AppKit places it against the anchor: the arrow points at the anchor's
// middle, on the side the flyout asks for, which AppKit flips where the
// screen has no room. The popover makes its window as it shows: w.win is
// that window while it shows. AppKit gives a popover that shows the
// keyboard, focusable or not, while its parent stays the key window, which
// the popover's window says it is too. A focusable flyout's popover is
// transient: it asks the delegate (popoverShouldClose:) before it closes on
// a click elsewhere or on its anchor, as WindowHandler.ShouldClose decides.
const (
popoverBehaviorApplicationDefined = 0
popoverBehaviorTransient = 1
)
// holdPopover keeps a transient popover open as a window is modal to it,
// as an application-defined one, until it hides: refusing AppKit's close
// instead left it open for good, as AppKit then no longer closed it on
// clicks elsewhere, and ate the clicks on its tray icon (#1055, as #1050).
// Making it transient again once it shows does not have AppKit close it
// on clicks elsewhere either: held (popoverHeld), the clicks elsewhere
// close it as they close other focusable flyouts (closeHeldPopovers).
func (w *window) holdPopover() {
if w.popover == 0 || w.closed || !w.flyout.Focusable || w.popoverHeld {
return
}
w.popoverHeld = true
send(w.popover, "setBehavior:", popoverBehaviorApplicationDefined)
w.b.watchOutsideClicks()
}
// closeHeldPopovers closes the popovers held open (holdPopover) that no
// window is modal to anymore, for a press in another window, in the app
// (win), or outside it (0), unless on a popover's tray icon, whose click
// toggles it.
func (b *Backend) closeHeldPopovers(win id) {
var open []*window
for _, w := range b.byNSWindow {
if !w.popoverHeld || w.closed || w.win == win || !sendBool(w.popover, "isShown") || w.modalChild() != nil {
continue
}
if t, ok := w.flyout.Tray.(*tray); ok && (t.pressed() || win != 0 && t.button != 0 && send(t.button, "window") == win) {
continue
}
open = append(open, w)
}
for _, w := range open {
if !w.closed && w.h.ShouldClose() {
w.Close()
}
}
}
func (w *window) createPopover(content NSRect) {
w.delegate = alloc("MyGoWindowDelegate")
w.createContent(content)
send(w.view, "setAutoresizingMask:", nsViewWidthHeightSizable)
w.popoverController = alloc("NSViewController")
send(w.popoverController, "setView:", uintptr(w.view))
w.popover = w.b.takePopover()
send(w.popover, "setContentViewController:", uintptr(w.popoverController))
msgSetSize(w.popover, sel("setContentSize:"), content.Size)
behavior := uintptr(popoverBehaviorApplicationDefined)
if w.flyout.Focusable {
behavior = popoverBehaviorTransient
}
send(w.popover, "setBehavior:", behavior)
send(w.popover, "setDelegate:", uintptr(w.delegate))
w.register()
}
// popoverAnchor returns the view the popover shows from, the anchor in it
// and the edge of it the popover goes to: the parent's content view, which
// is not flipped, or the button of a tray's status item. view is 0 when
// there is none.
func (w *window) popoverAnchor() (view id, r NSRect, edge uint) {
// NSRectEdge
edge = map[platform.Side]uint{platform.SideBottom: 1, platform.SideTop: 3, platform.SideRight: 2, platform.SideLeft: 0}[w.flyout.Side]
if t, ok := w.flyout.Tray.(*tray); ok {
if t.item == 0 {
return 0, r, edge
}
return t.button, msgRect(t.button, sel("bounds")), edge
}
a, p := w.flyout.Anchor, w.parent
if p == nil || p.closed || p.view == 0 {
return 0, r, edge
}
h := msgRect(p.view, sel("bounds")).Size.Height
r = NSRect{
Origin: NSPoint{float64(a.X), h - float64(a.Y) - float64(max(a.Height, 1))},
Size: NSSize{float64(max(a.Width, 1)), float64(max(a.Height, 1))},
}
return p.view, r, edge
}
func (w *window) showPopover() {
view, r, edge := w.popoverAnchor()
if view == 0 || sendBool(w.popover, "isShown") {
return
}
w.popoverClosing = false
if w.popoverHeld {
w.popoverHeld = false
send(w.popover, "setBehavior:", popoverBehaviorTransient)
}
// A status item's contrast appearance can differ from the app's theme.
// Give the whole popover (including its arrow) the content's appearance.
send(w.popover, "setAppearance:", uintptr(send(w.b.app, "effectiveAppearance")))
if w.flyout.Tray != nil {
// The popover of a menu bar app takes the keyboard of an app the
// user did not activate, as AppKit's own status items' do.
send(w.b.app, "activateIgnoringOtherApps:", 1)
}
msgSetSize(w.popover, sel("setContentSize:"), NSSize{float64(w.flyoutSize.Width), float64(w.flyoutSize.Height)})
msgRectIDUint(w.popover, sel("showRelativeToRect:ofView:preferredEdge:"), r, view, edge)
w.adoptPopoverWindow()
w.highlightTray(true)
}
// highlightTray highlights the tray icon a popover shows from while it
// shows, as AppKit's status items are while their menus show.
func (w *window) highlightTray(on bool) {
if t, ok := w.flyout.Tray.(*tray); ok && t.item != 0 {
send(t.button, "highlight:", boolArg(on))
}
}
// adoptPopoverWindow makes the window the popover shows in the flyout's.
func (w *window) adoptPopoverWindow() {
win := send(w.view, "window")
if win == 0 || win == w.win {
return
}
w.forgetPopoverWindow()
w.win = win
w.b.byNSWindow[win] = w
if w.surface != nil {
send(win, "makeFirstResponder:", uintptr(w.surface.view))
}
}
func (w *window) forgetPopoverWindow() {
if w.win == 0 {
return
}
delete(w.b.byNSWindow, w.win)
w.win = 0
}
// placePopover moves a popover that shows to the anchor, at the size.
func (w *window) placePopover() {
if !sendBool(w.popover, "isShown") {
return
}
msgSetSize(w.popover, sel("setContentSize:"), NSSize{float64(w.flyoutSize.Width), float64(w.flyoutSize.Height)})
if _, r, _ := w.popoverAnchor(); w.flyout.Tray == nil {
msgSetRect(w.popover, sel("setPositioningRect:"), r)
}
}
// hidePopover closes the popover, which shows again with Show, and gives
// the keyboard it had back to the parent.
func (w *window) hidePopover() {
if !sendBool(w.popover, "isShown") {
return
}
key := w.win != 0 && sendBool(w.win, "isKeyWindow")
w.popoverClosing = true
send(w.popover, "close")
if p := w.parent; key && p != nil && !p.closed && sendBool(p.win, "isVisible") {
send(p.win, "makeKeyWindow")
}
}
// closePopover destroys the flyout, at once.
func (w *window) closePopover() {
send(w.popover, "setAnimates:", 0)
w.hidePopover()
w.cleanup()
w.h.Closed()
}
func (w *window) cleanupPopover() {
w.forgetPopoverWindow()
p := w.popover
w.popover = 0
// A popover that Hide closes with its animation still shows (isShown),
// and tells it closed (popoverDidClose:) only as the animation ends,
// which can be after the flyout is gone.
closing := w.popoverClosing || sendBool(p, "isShown")
w.b.givePopover(p, closing)
if sendBool(p, "isShown") {
w.highlightTray(false)
send(p, "setAnimates:", 0)
send(p, "close")
}
send(p, "setContentViewController:", 0)
release(w.popoverController)
}
// takePopover returns an NSPopover for a flyout to show in: one a closed
// flyout gave back (givePopover), or a new one.
func (b *Backend) takePopover() id {
if n := len(b.sparePopovers); n > 0 {
p := b.sparePopovers[n-1]
b.sparePopovers = b.sparePopovers[:n-1]
send(p, "setAnimates:", 1) // closePopover turned it off
return p
}
return alloc("NSPopover")
}
// givePopover keeps the NSPopover of a closed flyout for the next one to
// show in, instead of releasing it. On macOS 26 an NSPopover that has
// shown leaves its material's backdrop behind once it is released, a
// graphics surface a little larger than the popover (3.4 MB for one of
// 280×230), so an app that shows a new popover flyout at each click of
// its tray icon grew by that much at each. Reused, a popover keeps one
// backdrop: the app holds as many as it showed at once.
//
// A popover still closing becomes spare once it tells it closed, to
// spareDelegate (spareClosed): shown by another flyout before that, it
// showed nothing, and its late popoverDidClose: closed that flyout.
func (b *Backend) givePopover(p id, closing bool) {
if b.spareDelegate == 0 {
b.spareDelegate = alloc("MyGoWindowDelegate") // in no window: windowFor is nil
b.closingPopovers = map[id]bool{}
}
send(p, "setDelegate:", uintptr(b.spareDelegate))
if closing {
b.closingPopovers[p] = true
return
}
b.sparePopovers = append(b.sparePopovers, p)
}
// spareClosed makes a popover a closed flyout gave back while it was
// closing spare, as it tells it closed.
func (b *Backend) spareClosed(p id) {
if b.closingPopovers[p] {
delete(b.closingPopovers, p)
b.sparePopovers = append(b.sparePopovers, p)
}
}
func popoverDelegateMethods() []objc.MethodDef {
b := func() *Backend { return theBackend }
return []objc.MethodDef{
// The user clicked elsewhere, in a transient popover, or on its
// tray icon, the positioning view, whose click AppKit eats: the
// icon's action never comes, so the click only closes it. AppKit
// asks on the release (macOS 26) or on the press, and keeping it
// open on a press on the icon kept it open for good, as it then no
// longer closed on clicks elsewhere either (#1050).
method("popoverShouldClose:", func(self id, _ objc.SEL, popover id) bool {
if w := b().windowFor(self); w != nil {
return w.h.ShouldClose()
}
return true
}),
method("popoverDidClose:", func(self id, _ objc.SEL, n id) {
if self == b().spareDelegate {
b().spareClosed(send(n, "object"))
return
}
w := b().windowFor(self)
if w == nil {
return
}
w.highlightTray(false)
w.forgetPopoverWindow()
if w.popoverClosing {
w.popoverClosing = false
return
}
w.cleanup()
w.h.Closed()
}),
}
}
// pressed reports whether the user is pressing the icon's button: the
// event being handled is a press on it, or a mouse button is down with the
// pointer over it, or over the copy of it the user last clicked (frame),
// as when the app hears of the press only after it made the app resign,
// or in a monitor of other apps' events, which the menu bar's are on
// recent macOS.
func (t *tray) pressed() bool {
if t.item == 0 {
return false
}
win := send(t.button, "window")
if win == 0 {
return false
}
if ev := send(t.b.app, "currentEvent"); ev != 0 && send(ev, "window") == win {
switch sendInt(ev, "type") {
case 1, 3: // NSEventTypeLeftMouseDown, RightMouseDown
p := msgPointFromView(t.button, sel("convertPoint:fromView:"), msgPoint(ev, sel("locationInWindow")), 0)
return inRect(p, msgRect(t.button, sel("bounds")))
}
}
if send(class("NSEvent"), "pressedMouseButtons") == 0 {
return false
}
return inRect(msgPoint(class("NSEvent"), sel("mouseLocation")), t.frame())
}
// inRect reports whether p is in r, its far edges excluded.
func inRect(p NSPoint, r NSRect) bool {
return p.X >= r.Origin.X && p.Y >= r.Origin.Y && p.X < r.Origin.X+r.Size.Width && p.Y < r.Origin.Y+r.Size.Height
}
+90
View File
@@ -0,0 +1,90 @@
//go:build darwin && !ios
package darwin
import "time"
type power struct{ b *Backend }
// powerEvents maps the notifications the app delegate observes to power
// events.
var powerEvents = map[string]string{
"NSWorkspaceWillSleepNotification": "suspend",
"NSWorkspaceDidWakeNotification": "resume",
"com.apple.screenIsLocked": "lock-screen",
"com.apple.screenIsUnlocked": "unlock-screen",
}
func (p power) Watch() {
withPool(func() {
observe := func(center id, name string) {
send(center, "addObserver:selector:name:object:", uintptr(p.b.delegate), uintptr(sel("mygoPowerNotification:")), uintptr(nsString(name)), 0)
}
workspace := send(send(class("NSWorkspace"), "sharedWorkspace"), "notificationCenter")
observe(workspace, "NSWorkspaceWillSleepNotification")
observe(workspace, "NSWorkspaceDidWakeNotification")
// Screen locking is only announced to other processes.
distributed := send(class("NSDistributedNotificationCenter"), "defaultCenter")
observe(distributed, "com.apple.screenIsLocked")
observe(distributed, "com.apple.screenIsUnlocked")
})
}
// Options of NSProcessInfo's activities.
const (
activityIdleSystemSleepDisabled = 1 << 20
activityIdleDisplaySleepDisabled = 1 << 40
// activityUserInitiated is NSActivityUserInitiated, which keeps App
// Nap off and the Mac from sleeping when idle: the second it leaves
// out (NSActivityUserInitiatedAllowingIdleSystemSleep).
activityUserInitiated = 0x00FFFFFF | activityIdleSystemSleepDisabled
)
func (p power) KeepAwake(display bool, reason string) func() {
opts := uint64(activityIdleSystemSleepDisabled)
if display {
opts |= activityIdleDisplaySleepDisabled
}
return beginActivity(opts, reason)
}
// KeepRunning holds NSActivityUserInitiatedAllowingIdleSystemSleep, an
// activity of the user's that keeps App Nap off while the Mac still sleeps
// when idle: the system does not suppress the app (proc_pidinfo's
// PROC_FLAG_SUPPRESSED) once none of its windows shows. KeepAwake's
// activity keeps App Nap off too, but the Mac awake as well, and shows in
// pmset -g assertions, which this one does not.
func (p power) KeepRunning(reason string) func() {
return beginActivity(activityUserInitiated&^activityIdleSystemSleepDisabled, reason)
}
// beginActivity begins an activity of NSProcessInfo with the options, which
// the function it returns ends.
func beginActivity(opts uint64, reason string) func() {
var token id
withPool(func() {
info := send(class("NSProcessInfo"), "processInfo")
token = retain(send(info, "beginActivityWithOptions:reason:", uintptr(opts), uintptr(nsString(reason))))
})
return func() {
send(send(class("NSProcessInfo"), "processInfo"), "endActivity:", uintptr(token))
release(token)
}
}
func (p power) OnBattery() bool {
if iopsCopyPowerSourcesInfo == nil {
return false
}
info := iopsCopyPowerSourcesInfo()
if info == 0 {
return false
}
defer cfRelease(info)
return goString(iopsGetProvidingPowerSourceType(info)) == "Battery Power"
}
func (p power) IdleTime() time.Duration {
const combinedSessionState, anyInputEvent = 0, ^uint32(0)
return time.Duration(cgEventSourceSecondsSinceLastType(combinedSessionState, anyInputEvent) * float64(time.Second))
}
+35
View File
@@ -0,0 +1,35 @@
//go:build darwin && !ios
package darwin
import (
"errors"
"os"
"unsafe"
)
// ReplaceFile replaces target with -[NSFileManager
// replaceItemAtURL:withItemAtURL:…], NSDocument's safe save: the target
// keeps its permissions, creation date, extended attributes (Finder tags,
// Finder info) and ACLs, and its identity, so that aliases still find it.
func (*Backend) ReplaceFile(target, replacement string) error {
if _, err := os.Lstat(target); os.IsNotExist(err) {
return os.Rename(replacement, target)
}
load()
var err error
withPool(func() {
fm := send(class("NSFileManager"), "defaultManager")
var nsErr id
ok := sendBool(fm, "replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:",
uintptr(fileURL(target)), uintptr(fileURL(replacement)), 0, 0, 0, uintptr(unsafe.Pointer(&nsErr)))
if !ok {
msg := "cannot replace the file"
if nsErr != 0 {
msg = goString(send(nsErr, "localizedDescription"))
}
err = &os.LinkError{Op: "replace", Old: replacement, New: target, Err: errors.New(msg)}
}
})
return err
}
+174
View File
@@ -0,0 +1,174 @@
//go:build darwin && !ios
package darwin
import (
"bytes"
"context"
"io"
"net/http"
"strings"
"unsafe"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
var theSchemeHandler id
func schemeHandler() id {
if theSchemeHandler == 0 {
theSchemeHandler = alloc("MyGoSchemeHandler")
}
return theSchemeHandler
}
// schemeTask is the platform.SchemeResponder of a WKURLSchemeTask. All
// methods run on the main thread.
type schemeTask struct {
task id
cancel context.CancelFunc
stopped bool
responded bool
done bool
}
// schemeTasks maps live WKURLSchemeTask objects to their state.
var schemeTasks = map[id]*schemeTask{}
func registerSchemeHandler() {
classDef("MyGoSchemeHandler", "NSObject", []string{"WKURLSchemeHandler"}, []objc.MethodDef{
method("webView:startURLSchemeTask:", func(self id, _ objc.SEL, web, task id) {
w := theBackend.byWebView[web]
ctx, cancel := context.WithCancel(context.Background())
st := &schemeTask{task: retain(task), cancel: cancel}
schemeTasks[task] = st
if w == nil || w.closed {
st.Respond(http.StatusServiceUnavailable, nil)
st.Finish()
return
}
req := readRequest(task)
req.Context = ctx
req.Responder = st
w.h.SchemeRequest(req)
}),
method("webView:stopURLSchemeTask:", func(self id, _ objc.SEL, web, task id) {
if st := schemeTasks[task]; st != nil {
st.stopped = true
st.cancel()
st.release()
}
}),
})
}
func readRequest(task id) *platform.SchemeRequest {
header := http.Header{}
req := &platform.SchemeRequest{Header: header}
withPool(func() {
r := send(task, "request")
req.URL = goString(send(send(r, "URL"), "absoluteString"))
req.Method = goString(send(r, "HTTPMethod"))
if req.Method == "" {
req.Method = http.MethodGet
}
fields := send(r, "allHTTPHeaderFields")
for _, k := range arrayItems(send(fields, "allKeys")) {
header.Add(goString(k), goString(send(fields, "objectForKey:", uintptr(k))))
}
if data := send(r, "HTTPBody"); data != 0 {
req.Body = io.NopCloser(bytes.NewReader(goBytes(data)))
} else if stream := send(r, "HTTPBodyStream"); stream != 0 {
req.Body = io.NopCloser(bytes.NewReader(readStream(stream)))
}
})
return req
}
// readStream drains an NSInputStream.
func readStream(stream id) []byte {
send(stream, "open")
defer send(stream, "close")
var out []byte
buf := make([]byte, 64<<10)
for {
n := sendInt(stream, "read:maxLength:", uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
if n <= 0 {
return out
}
out = append(out, buf[:n]...)
}
}
func (st *schemeTask) release() {
if st.done {
return
}
st.done = true
delete(schemeTasks, st.task)
release(st.task)
}
// schemeDispositions records the Content-Disposition of the latest custom
// scheme responses by URL, which the navigation policy needs to recognize
// attachments.
var schemeDispositions = map[string]string{}
func (st *schemeTask) Respond(status int, h map[string][]string) {
header := http.Header(h)
if st.stopped || st.done || st.responded {
return
}
st.responded = true
withPool(func() {
if len(schemeDispositions) > 64 {
clear(schemeDispositions)
}
schemeDispositions[goString(send(send(send(st.task, "request"), "URL"), "absoluteString"))] = header.Get("Content-Disposition")
fields := send(class("NSMutableDictionary"), "dictionary")
for k, vs := range header {
send(fields, "setObject:forKey:", uintptr(nsString(strings.Join(vs, ", "))), uintptr(nsString(k)))
}
url := send(send(st.task, "request"), "URL")
resp := send(send(class("NSHTTPURLResponse"), "alloc"), "initWithURL:statusCode:HTTPVersion:headerFields:",
uintptr(url), uintptr(status), uintptr(nsString("HTTP/1.1")), uintptr(fields))
send(st.task, "didReceiveResponse:", uintptr(resp))
release(resp)
})
}
func (st *schemeTask) Write(p []byte) {
if st.stopped || st.done || len(p) == 0 {
return
}
if !st.responded {
st.Respond(http.StatusOK, nil)
}
withPool(func() { send(st.task, "didReceiveData:", uintptr(nsData(p))) })
}
func (st *schemeTask) Finish() {
if st.stopped || st.done {
return
}
if !st.responded {
st.Respond(http.StatusOK, nil)
}
send(st.task, "didFinish")
st.release()
}
func (st *schemeTask) Fail(err error) {
if st.stopped || st.done {
return
}
withPool(func() {
info := send(class("NSMutableDictionary"), "dictionary")
send(info, "setObject:forKey:", uintptr(nsString(err.Error())), uintptr(nsString("NSLocalizedDescription")))
nserr := send(class("NSError"), "errorWithDomain:code:userInfo:", uintptr(nsString("mygo")), ^uintptr(0), uintptr(info))
send(st.task, "didFailWithError:", uintptr(nserr))
})
st.release()
}
+162
View File
@@ -0,0 +1,162 @@
//go:build darwin && !ios
package darwin
import (
"errors"
"fmt"
"sync"
"unsafe"
"github.com/ebitengine/purego"
"github.com/egoist/mygo/internal/platform"
)
// secrets keeps secrets as generic passwords of the login Keychain, the
// service and account as keytar does. It uses the file-based keychain:
// the data protection one needs a signed app with a keychain-access-groups
// entitlement (unsigned builds get errSecMissingEntitlement).
type secrets struct{}
const (
errSecItemNotFound = -25300
errSecDuplicateItem = -25299
)
// The Security framework, loaded with the first secret.
var keychain = sync.OnceValue(func() *keychainAPI {
lib, err := purego.Dlopen("/System/Library/Frameworks/Security.framework/Security", purego.RTLD_GLOBAL|purego.RTLD_NOW)
if err != nil {
return &keychainAPI{err: fmt.Errorf("cannot load the Security framework: %w", err)}
}
k := &keychainAPI{
add: mustDlsym(lib, "SecItemAdd"),
copy: mustDlsym(lib, "SecItemCopyMatching"),
update: mustDlsym(lib, "SecItemUpdate"),
delete: mustDlsym(lib, "SecItemDelete"),
message: mustDlsym(lib, "SecCopyErrorMessageString"),
}
k.class = constString(lib, "kSecClass")
k.genericPassword = constString(lib, "kSecClassGenericPassword")
k.service = constString(lib, "kSecAttrService")
k.account = constString(lib, "kSecAttrAccount")
k.label = constString(lib, "kSecAttrLabel")
k.valueData = constString(lib, "kSecValueData")
k.returnData = constString(lib, "kSecReturnData")
k.matchLimit = constString(lib, "kSecMatchLimit")
k.matchLimitOne = constString(lib, "kSecMatchLimitOne")
k.cfTrue = constString(libCF, "kCFBooleanTrue")
return k
})
type keychainAPI struct {
err error
add, copy, update, delete, message uintptr
class, genericPassword id
service, account, label id
valueData, returnData id
matchLimit, matchLimitOne, cfTrue id
}
// query returns an autoreleased dictionary that finds the item of service
// and account.
func (k *keychainAPI) query(service, account string) id {
q := send(class("NSMutableDictionary"), "dictionary")
set := func(key, v id) { send(q, "setObject:forKey:", uintptr(v), uintptr(key)) }
set(k.class, k.genericPassword)
set(k.service, nsString(service))
set(k.account, nsString(account))
return q
}
// status converts an OSStatus into an error with the system's message.
func (k *keychainAPI) status(op string, s int32) error {
switch s {
case 0:
return nil
case errSecItemNotFound:
return platform.ErrSecretNotFound
}
msg := ""
if str, _, _ := purego.SyscallN(k.message, uintptr(s), 0); str != 0 {
msg = goString(id(str))
cfRelease(str)
}
if msg == "" {
msg = "unknown error"
}
return fmt.Errorf("keychain: %s: %s (OSStatus %d)", op, msg, s)
}
func osStatus(r uintptr) int32 { return int32(uint32(r)) }
func (secrets) SetSecret(service, account string, secret []byte) (err error) {
k := keychain()
if k.err != nil {
return k.err
}
withPool(func() {
data := nsData(secret)
update := send(class("NSMutableDictionary"), "dictionary")
send(update, "setObject:forKey:", uintptr(data), uintptr(k.valueData))
r, _, _ := purego.SyscallN(k.update, uintptr(k.query(service, account)), uintptr(update))
if s := osStatus(r); s != errSecItemNotFound {
err = k.status("update", s)
return
}
add := k.query(service, account)
send(add, "setObject:forKey:", uintptr(data), uintptr(k.valueData))
send(add, "setObject:forKey:", uintptr(nsString(service)), uintptr(k.label))
r, _, _ = purego.SyscallN(k.add, uintptr(add), 0)
if s := osStatus(r); s == errSecDuplicateItem {
// Added by another thread or process since the update.
r, _, _ = purego.SyscallN(k.update, uintptr(k.query(service, account)), uintptr(update))
err = k.status("update", osStatus(r))
} else {
err = k.status("add", s)
}
})
return err
}
func (secrets) Secret(service, account string) (secret []byte, err error) {
k := keychain()
if k.err != nil {
return nil, k.err
}
withPool(func() {
q := k.query(service, account)
send(q, "setObject:forKey:", uintptr(k.cfTrue), uintptr(k.returnData))
send(q, "setObject:forKey:", uintptr(k.matchLimitOne), uintptr(k.matchLimit))
var data uintptr
r, _, _ := purego.SyscallN(k.copy, uintptr(q), uintptr(unsafe.Pointer(&data)))
if err = k.status("read", osStatus(r)); err != nil {
return
}
if data == 0 {
err = errors.New("keychain: read: no data")
return
}
secret = goBytes(id(data))
if secret == nil {
secret = []byte{}
}
cfRelease(data)
})
return secret, err
}
func (secrets) DeleteSecret(service, account string) (err error) {
k := keychain()
if k.err != nil {
return k.err
}
withPool(func() {
r, _, _ := purego.SyscallN(k.delete, uintptr(k.query(service, account)))
if err = k.status("delete", osStatus(r)); errors.Is(err, platform.ErrSecretNotFound) {
err = nil
}
})
return err
}
+105
View File
@@ -0,0 +1,105 @@
//go:build darwin && !ios
package darwin
import (
"log"
"sync"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
// Sessions (mygo.Session): a store is a WKWebsiteDataStore, which the
// configuration of each web view of the session names. window.open hands
// the opener's configuration over, and its store with it.
// dataStore holds a WKWebsiteDataStore, retained until Close.
type dataStore struct {
store id
closed bool
}
var inMemoryOnce sync.Once
// NewDataStore makes the store of a session: a persistent one is
// +dataStoreForIdentifier: of the session's UUID (macOS 14), kept in
// memory until the app quits on older systems, an ephemeral one
// +nonPersistentDataStore.
func (a appController) NewDataStore(opts platform.DataStoreOptions) (platform.DataStore, error) {
s := &dataStore{}
withPool(func() {
cls := class("WKWebsiteDataStore")
if !opts.Ephemeral && sendBool(cls, "respondsToSelector:", uintptr(sel("dataStoreForIdentifier:"))) {
uuid := send(send(class("NSUUID"), "alloc"), "initWithUUIDString:", uintptr(nsString(opts.ID)))
s.store = retain(send(cls, "dataStoreForIdentifier:", uintptr(uuid)))
release(uuid)
return
}
if !opts.Ephemeral {
inMemoryOnce.Do(func() {
log.Print("mygo: sessions keep their data in memory until the app quits before macOS 14")
})
}
s.store = retain(send(cls, "nonPersistentDataStore"))
})
return s, nil
}
// Close releases the store, which its web views keep while they live.
func (s *dataStore) Close() {
if !s.closed {
s.closed = true
release(s.store)
}
}
// websiteDataStore returns the WKWebsiteDataStore of store, the default
// one for nil.
func websiteDataStore(store platform.DataStore) id {
if s, ok := store.(*dataStore); ok {
return s.store
}
return send(class("WKWebsiteDataStore"), "defaultDataStore")
}
// websiteDataTypes returns the set of WKWebsiteDataTypes of types, those
// of the system's WebKit.
func websiteDataTypes(types platform.SiteData) id {
if types.All() {
return send(class("WKWebsiteDataStore"), "allWebsiteDataTypes")
}
set := send(class("NSMutableSet"), "set")
add := func(names ...string) {
for _, name := range names {
if t := constString(libWebKit, name); t != 0 {
send(set, "addObject:", uintptr(t))
}
}
}
if types&platform.SiteDataCookies != 0 {
add("WKWebsiteDataTypeCookies")
}
if types&platform.SiteDataLocalStorage != 0 {
add("WKWebsiteDataTypeLocalStorage", "WKWebsiteDataTypeSessionStorage")
}
if types&platform.SiteDataIndexedDB != 0 {
add("WKWebsiteDataTypeIndexedDBDatabases", "WKWebsiteDataTypeWebSQLDatabases")
}
if types&platform.SiteDataCaches != 0 {
add("WKWebsiteDataTypeDiskCache", "WKWebsiteDataTypeMemoryCache", "WKWebsiteDataTypeOfflineWebApplicationCache", "WKWebsiteDataTypeFetchCache")
}
if types&platform.SiteDataServiceWorkers != 0 {
add("WKWebsiteDataTypeServiceWorkerRegistrations")
}
return set
}
// removeData removes the data of types from store, whatever its age.
func (a appController) removeData(store platform.DataStore, types platform.SiteData, done func(error)) {
withPool(func() {
blk := newBlock(func(_ objc.Block) { a.b.runOnMain(func() { done(nil) }) })
send(websiteDataStore(store), "removeDataOfTypes:modifiedSince:completionHandler:", uintptr(websiteDataTypes(types)), uintptr(send(class("NSDate"), "distantPast")), uintptr(blk))
blk.Release()
})
}
File diff suppressed because it is too large. Load diff
+366
View File
@@ -0,0 +1,366 @@
//go:build darwin && !ios
package darwin
import (
"bytes"
"encoding/hex"
"errors"
"image"
"image/png"
"math"
"slices"
"strings"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/transfer"
)
var (
msgDraggingFrame func(id, objc.SEL, NSRect, id)
msgDragKeyEvent func(id, objc.SEL, uint, NSPoint, uint, float64, int, id, id, id, bool, uint16) id
macDragSources = map[id]*macDataSource{}
macDragProviders = map[id]*macDataProvider{}
macDragTypes = map[transfer.Format]string{}
macDragFormats = map[string]transfer.Format{}
)
type macDataSource struct {
r platform.DragRequest
s *surface
obj, session id
providers []id
err error
// escaped is set when the drag was given up (Escape, or
// CancelDataDrag), not let go over no target.
escaped bool
end platform.Point
}
type macDataProvider struct {
src *macDataSource
item transfer.Item
}
func registerDataDragClasses() {
purego.RegisterFunc(&msgDraggingFrame, msgSendAddr)
purego.RegisterFunc(&msgDragKeyEvent, msgSendAddr)
classDef("MyGoDragSource", "NSObject", []string{"NSDraggingSource"}, []objc.MethodDef{
method("draggingSession:sourceOperationMaskForDraggingContext:", func(self id, _ objc.SEL, session id, context int) uint {
if src := macDragSources[self]; src != nil {
return macOperations(src.r.Operations)
}
return 0
}),
method("draggingSession:endedAtPoint:operation:", func(self id, _ objc.SEL, session id, point NSPoint, operation uint) {
if src := macDragSources[self]; src != nil {
// AppKit's tracking loop takes Escape itself; the event
// that ended the session tells it from letting go.
if ev := send(src.s.w.b.app, "currentEvent"); ev != 0 && sendInt(ev, "type") == 10 && uint16(send(ev, "keyCode")) == 53 {
src.escaped = true
}
src.end = platform.Point{X: int(math.Round(point.X)), Y: int(math.Round(primaryScreenHeight() - point.Y))}
src.finish(operation)
}
}),
})
classDef("MyGoDragProvider", "NSObject", []string{"NSPasteboardItemDataProvider"}, []objc.MethodDef{
method("pasteboard:item:provideDataForType:", func(self id, _ objc.SEL, board, item, typ id) {
p := macDragProviders[self]
if p == nil {
return
}
name := goString(typ)
var b []byte
var err error
if name == macType(platform.DragSessionFormat) {
b = []byte(p.src.r.Session)
} else {
f := macFormat(name)
b, err = p.item.Read(f)
if f == transfer.FileList || name == "public.url" {
b = []byte(strings.TrimSpace(strings.Split(string(b), "\n")[0]))
}
}
if err != nil {
p.src.err = err
return
}
send(item, "setData:forType:", uintptr(nsData(b)), uintptr(typ))
}),
})
}
func macType(f transfer.Format) string {
switch f {
case transfer.Text:
return utString
case transfer.HTML:
return utHTML
case transfer.PNG:
return utPNG
case transfer.FileList:
return "public.file-url"
case transfer.URIList:
// public.url carries one URL. Keep the full URI-list bytes in a
// separate type and offer public.url as an interoperable fallback.
return "dev.mygo.uri-list"
}
if t := macDragTypes[f]; t != "" {
return t
}
var t string
if cls := class("UTType"); cls != 0 {
ut := send(cls, "typeWithMIMEType:", uintptr(nsString(string(f))))
if ut != 0 {
t = goString(send(ut, "identifier"))
}
}
if t == "" {
t = "dev.mygo.mime." + hex.EncodeToString([]byte(f))
}
macDragTypes[f], macDragFormats[t] = t, f
return t
}
func macFormat(t string) transfer.Format {
switch t {
case utString, "public.plain-text", "NSStringPboardType":
return transfer.Text
case utHTML:
return transfer.HTML
case utPNG:
return transfer.PNG
case "public.file-url":
return transfer.FileList
case "public.url", "dev.mygo.uri-list":
return transfer.URIList
}
if f := macDragFormats[t]; f != "" {
return f
}
if strings.HasPrefix(t, "dev.mygo.mime.") {
if b, err := hex.DecodeString(strings.TrimPrefix(t, "dev.mygo.mime.")); err == nil && len(b) > 0 {
return transfer.Format(b)
}
}
if cls := class("UTType"); cls != 0 {
ut := send(cls, "typeWithIdentifier:", uintptr(nsString(t)))
if ut != 0 {
if mime := goString(send(ut, "preferredMIMEType")); mime != "" {
return transfer.Format(mime)
}
}
}
return transfer.Format(t)
}
func macOperations(o transfer.Operation) uint {
var n uint
if o&transfer.Copy != 0 {
n |= 1
}
if o&transfer.Move != 0 {
n |= 16
}
return n
}
func goOperations(n uint) transfer.Operation {
var o transfer.Operation
if n&1 != 0 {
o |= transfer.Copy
}
if n&16 != 0 {
o |= transfer.Move
}
return o
}
func (s *surface) SetDropFormats(formats []transfer.Format) {
var types []id
for _, f := range formats {
types = append(types, nsString(macType(f)))
}
if slices.Contains(formats, transfer.URIList) {
types = append(types, nsString("public.url"))
}
send(s.view, "registerForDraggedTypes:", uintptr(nsArray(types...)))
}
func (s *surface) StartDataDrag(r platform.DragRequest) {
if s.w.closed || s.w.lastMouseDown == 0 {
r.Done(transfer.Result{Err: errors.New("mygo: native drag needs a pointer gesture")})
return
}
withPool(func() {
src := &macDataSource{r: r, s: s, obj: send(send(class("MyGoDragSource"), "alloc"), "init")}
macDragSources[src.obj], s.dataDrag = src, src
img := send(class("NSImage"), "imageNamed:", uintptr(nsString("NSMultipleDocuments")))
width, height := r.Width, r.Height
if len(r.Preview) > 0 {
pix := bytes.Clone(r.Preview)
for i := 0; i < len(pix); i += 4 {
pix[i], pix[i+2] = pix[i+2], pix[i]
}
var b bytes.Buffer
png.Encode(&b, &image.RGBA{Pix: pix, Stride: 4 * width, Rect: image.Rect(0, 0, width, height)})
img = autorelease(send(send(class("NSImage"), "alloc"), "initWithData:", uintptr(nsData(b.Bytes()))))
} else {
width, height = 32, 32
}
x, y := r.X, r.Y
if x < 0 || y < 0 {
p := msgPointFromView(s.view, sel("convertPoint:fromView:"), msgPoint(s.w.lastMouseDown, sel("locationInWindow")), 0)
x, y = p.X, p.Y
}
var dragging []id
for n, pb := range src.pasteboardItems() {
di := autorelease(send(send(class("NSDraggingItem"), "alloc"), "initWithPasteboardWriter:", uintptr(pb)))
frame := NSRect{Origin: NSPoint{x - float64(r.HotX) + float64(n*3), y - float64(r.HotY) + float64(n*3)}, Size: NSSize{float64(width), float64(height)}}
msgDraggingFrame(di, sel("setDraggingFrame:contents:"), frame, img)
dragging = append(dragging, di)
}
src.session = retain(send(s.view, "beginDraggingSessionWithItems:event:source:", uintptr(nsArray(dragging...)), uintptr(s.w.lastMouseDown), uintptr(src.obj)))
if src.session == 0 {
src.err = errors.New("mygo: AppKit failed to start drag")
src.end = screen{}.CursorPoint()
src.finish(0)
return
}
send(src.session, "setAnimatesToStartingPositionsOnCancelOrFail:", 1)
})
}
func (src *macDataSource) pasteboardItems() []id {
var items []id
for _, item := range src.r.Data.Items() {
pb := autorelease(send(send(class("NSPasteboardItem"), "alloc"), "init"))
provider := send(send(class("MyGoDragProvider"), "alloc"), "init")
macDragProviders[provider] = &macDataProvider{src, item}
src.providers = append(src.providers, provider)
var types []id
for _, f := range item.Formats() {
types = append(types, nsString(macType(f)))
if f == transfer.URIList {
types = append(types, nsString("public.url"))
}
}
types = append(types, nsString(macType(platform.DragSessionFormat)))
send(pb, "setDataProvider:forTypes:", uintptr(provider), uintptr(nsArray(types...)))
items = append(items, pb)
}
return items
}
func (src *macDataSource) finish(operation uint) {
delete(macDragSources, src.obj)
if src.s.dataDrag == src {
src.s.dataDrag = nil
}
for _, p := range src.providers {
delete(macDragProviders, p)
release(p)
}
release(src.session)
// The callback still uses self. Autorelease after AppKit returns.
autorelease(src.obj)
op := goOperations(operation)
if src.err != nil {
op = transfer.None
}
done := src.r.Done
src.r = platform.DragRequest{}
canceled := op == transfer.None && src.err == nil
done(transfer.Result{Operation: op, Canceled: canceled, Escaped: canceled && src.escaped,
Point: image.Point{X: src.end.X, Y: src.end.Y}, Err: src.err})
}
func (s *surface) CancelDataDrag() {
if s.dataDrag == nil {
return
}
s.dataDrag.escaped = true
// NSDraggingSession has no public cancel method. Posting Escape to
// AppKit's tracking loop cancels through its normal keyboard path.
withPool(func() {
ev := msgDragKeyEvent(id(class("NSEvent")), sel("keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:"),
10, NSPoint{}, 0, 0, sendInt(s.w.win, "windowNumber"), 0, nsString("\x1b"), nsString("\x1b"), false, 53)
send(s.w.b.app, "postEvent:atStart:", uintptr(ev), 1)
})
}
func (s *surface) nativeDataEvent(info id, kind platform.SurfaceEventKind) bool {
s.dragOperation = transfer.None
pb := send(info, "draggingPasteboard")
d := &platform.DataDragEvent{Offer: transfer.Offer{Operations: goOperations(uint(send(info, "draggingSourceOperationMask")))}}
d.Session = goString(send(pb, "stringForType:", uintptr(nsString(macType(platform.DragSessionFormat)))))
items := arrayItems(send(pb, "pasteboardItems"))
for _, item := range items {
for _, t := range arrayItems(send(item, "types")) {
f := macFormat(goString(t))
if f == platform.DragSessionFormat {
continue
}
if !slices.Contains(d.Offer.Formats, f) {
d.Offer.Formats = append(d.Offer.Formats, f)
}
if f == transfer.FileList {
d.HasFiles = true
if !slices.Contains(d.Offer.Formats, transfer.URIList) {
d.Offer.Formats = append(d.Offer.Formats, transfer.URIList)
}
}
}
}
mods := eventMods(send(s.w.b.app, "currentEvent"))
if mods&platform.ModAlt != 0 {
d.Offer.Suggested = transfer.Copy
} else if mods&platform.ModSuper != 0 {
d.Offer.Suggested = transfer.Move
}
x, y := s.dragPoint(info)
if kind == platform.DataDragLeave {
return s.send(platform.SurfaceEvent{Kind: kind, Drag: d})
}
if !s.send(platform.SurfaceEvent{Kind: platform.DataDragOver, X: x, Y: y, Drag: d}) {
return false
}
s.dragOperation = d.Operation
if kind == platform.DataDragOver {
return true
}
// The native pasteboard is only read after the content accepted formats.
var dataItems []transfer.Item
for _, item := range items {
var reps []transfer.Representation
for _, f := range d.Formats {
t := macType(f)
available := send(item, "dataForType:", uintptr(nsString(t)))
if available == 0 && f == transfer.URIList {
available = send(item, "dataForType:", uintptr(nsString("public.url")))
if available == 0 {
t = "public.file-url"
available = send(item, "dataForType:", uintptr(nsString(t)))
}
}
if available != 0 {
b := goBytes(available)
if t == "public.file-url" {
b = filePathURLBytes(b)
}
reps = append(reps, transfer.Bytes(f, b))
}
}
if len(reps) > 0 {
dataItems = append(dataItems, transfer.NewItem(reps...))
}
}
d.Data = transfer.New(dataItems...)
return s.send(platform.SurfaceEvent{Kind: platform.DataDrop, X: x, Y: y, Drag: d})
}
func (s *surface) nativeDataOperation(info id) uint {
if !s.nativeDataEvent(info, platform.DataDragOver) {
return 0
}
return macOperations(s.dragOperation)
}
+49
View File
@@ -0,0 +1,49 @@
//go:build darwin && !ios
package darwin
import (
"bytes"
"testing"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/transfer"
)
// Format translation needs Foundation/AppKit, but no application or window.
func TestDataDragFormatMappings(t *testing.T) {
load()
withPool(func() {
registerDataDragClasses()
for _, f := range []transfer.Format{transfer.Text, transfer.HTML, transfer.PNG, transfer.URIList, transfer.FileList, "application/vnd.mygo.test+json"} {
typ := macType(f)
if got := macFormat(typ); got != f {
t.Errorf("%s -> %s -> %s", f, typ, got)
}
item := autorelease(send(send(class("NSPasteboardItem"), "alloc"), "init"))
if !sendBool(item, "setData:forType:", uintptr(nsData([]byte("a\r\nb"))), uintptr(nsString(typ))) {
t.Errorf("pasteboard rejected type %s", typ)
}
}
if macType(transfer.URIList) == "public.url" {
t.Fatal("URI lists were narrowed to a single URL")
}
payload := []byte("https://example.com/a\r\nhttps://example.com/b")
src := &macDataSource{r: platform.DragRequest{Data: transfer.New(transfer.NewItem(transfer.Bytes(transfer.URIList, payload)))}}
item := src.pasteboardItems()[0]
defer func() {
for _, p := range src.providers {
delete(macDragProviders, p)
release(p)
}
}()
actual := goBytes(send(item, "dataForType:", uintptr(nsString(macType(transfer.URIList)))))
if !bytes.Equal(actual, payload) {
t.Errorf("URI-list provider: %q", actual)
}
first := goBytes(send(item, "dataForType:", uintptr(nsString("public.url"))))
if string(first) != "https://example.com/a" {
t.Errorf("public URL fallback: %q", first)
}
})
}
+117
View File
@@ -0,0 +1,117 @@
//go:build darwin && !ios
package darwin
import (
"testing"
"github.com/egoist/mygo/internal/platform"
)
// frameHandler is a window handler that leaves the paced frames it is
// sent to draw later while wait is true.
type frameHandler struct {
platform.WindowHandler
wait bool
paced []bool
}
func (h *frameHandler) SurfaceEvent(ev platform.SurfaceEvent) bool {
if ev.Kind != platform.SurfaceFrame {
return false
}
h.paced = append(h.paced, ev.Paced)
return ev.Paced && h.wait
}
// TestDeferredFrames checks that the display link keeps running while the
// content leaves a paced frame to draw later, and only then: once FrameNow
// draws it, and once the content draws any other frame instead (as a
// resize's, or a paced one it can draw), which draws what the one left
// would have, as the content then never calls FrameNow for it.
func TestDeferredFrames(t *testing.T) {
h := &frameHandler{}
s := &surface{w: &window{h: h}}
h.wait = true
s.frameNow(true)
if !s.deferred {
t.Fatal("a paced frame left to draw later: not deferred")
}
h.wait = false
s.FrameNow()
if s.deferred || h.paced[len(h.paced)-1] {
t.Fatalf("drawn at once: deferred %v, sent paced %v", s.deferred, h.paced[len(h.paced)-1])
}
// A frame AppKit displays, not paced, draws the one left.
h.wait = true
s.frameNow(true)
s.frameNow(false)
if s.deferred {
t.Fatal("a frame drawn meanwhile left the link running")
}
// A paced frame the content draws, as after its renderer was let go.
s.frameNow(true)
h.wait = false
s.frameNow(true)
if s.deferred {
t.Fatal("a paced frame drawn left the link running")
}
// Refreshes passing while the content waits keep it deferred.
h.wait = true
s.frameNow(true)
s.frameNow(true)
if !s.deferred {
t.Fatal("refreshes passing while the content waits: not deferred")
}
}
// TestDrawSoon checks that a frame asked for after a pause draws from the
// backend's queue, outside AppKit's display of views (#883), once however
// often it is asked for meanwhile, and not at all when another drew
// first, as a resize's does when AppKit displays the view, unless it was
// asked for again after that one.
func TestDrawSoon(t *testing.T) {
h := &frameHandler{}
b := &Backend{bySurface: map[id]*surface{}}
s := &surface{w: &window{b: b, h: h}, view: 1}
b.bySurface[s.view] = s
s.drawSoon()
s.drawSoon()
if len(h.paced) != 0 {
t.Fatal("drew at once")
}
drainMainQueue()
if len(h.paced) != 1 || h.paced[0] {
t.Fatalf("frames drawn from the queue: %v, want one not paced", h.paced)
}
s.drawSoon()
s.frameNow(false)
drainMainQueue()
if len(h.paced) != 2 {
t.Fatalf("drew %d frames, want the one drawn meanwhile alone", len(h.paced)-1)
}
// One asked for after the frame drawn meanwhile, as once the window
// whose first frame AppKit drew while the window was out of sight
// shows (SurfaceShown), still draws: dropped with the first, what
// moves would stop for good.
s.drawSoon()
s.frameNow(false)
s.drawSoon()
drainMainQueue()
if len(h.paced) != 4 || s.soon {
t.Fatalf("asked for after the frame drawn meanwhile: drew %d frames from the queue, want 1", len(h.paced)-3)
}
// A window closed meanwhile draws none.
s.drawSoon()
s.w.closed = true
drainMainQueue()
if len(h.paced) != 4 || s.soon {
t.Fatalf("a closed window drew %d frames (soon %v)", len(h.paced)-4, s.soon)
}
}
+221
View File
@@ -0,0 +1,221 @@
//go:build darwin && !ios
package darwin
import (
"strings"
"unicode/utf16"
"github.com/egoist/mygo/internal/platform"
)
// Input methods see the text around the caret of the focused text input
// as their document: the content's TextInputState.Text, with the marked
// text, the composition, in place of the selection while there is one.
// NSTextInputClient counts in UTF-16 units of that document; the content
// gets rune offsets in TextInputState.Text.
// document returns the text input methods see, and where the selection,
// or the marked text, starts and ends in it, in runes.
func (s *surface) document() (doc []rune, start, end int) {
text := []rune(s.input.Text)
start = max(0, min(s.input.Start, len(text)))
end = max(start, min(s.input.End, len(text)))
if s.marked == "" {
return text, start, end
}
m := []rune(s.marked)
doc = make([]rune, 0, len(text)-(end-start)+len(m))
doc = append(append(append(doc, text[:start]...), m...), text[end:]...)
return doc, start, start + len(m)
}
// units returns how many UTF-16 units runes take.
func units(runes []rune) int {
n := 0
for _, r := range runes {
n += utf16.RuneLen(r)
}
return n
}
// runeAt returns the rune of runes that UTF-16 unit u starts, or the end.
func runeAt(runes []rune, u int) int {
for i, r := range runes {
if u <= 0 {
return i
}
u -= utf16.RuneLen(r)
}
return len(runes)
}
func (s *surface) markedRange() nsRange {
if c := s.input.Client; c != nil {
if r, ok := c.MarkedRange(); ok {
return nsRange{Location: uint(r.Start), Length: uint(max(0, r.End-r.Start))}
}
return nsRange{Location: nsNotFound}
}
if s.marked == "" {
return nsRange{Location: nsNotFound}
}
doc, start, end := s.document()
return nsRange{Location: uint(units(doc[:start])), Length: uint(units(doc[start:end]))}
}
func (s *surface) selectedRange() nsRange {
if !s.input.Active {
return nsRange{Location: nsNotFound}
}
if c := s.input.Client; c != nil {
r := c.Selection().Range
return nsRange{Location: uint(r.Start), Length: uint(max(0, r.End-r.Start))}
}
doc, start, end := s.document()
if s.marked != "" {
return nsRange{Location: uint(units(doc[:start])) + s.markedSel.Location, Length: s.markedSel.Length}
}
return nsRange{Location: uint(units(doc[:start])), Length: uint(units(doc[start:end]))}
}
// textRange converts a range of the document, in UTF-16 units, into runes
// of TextInputState.Text: a range in the marked text stands for the
// selection it replaces.
func (s *surface) textRange(r nsRange) (from, to int) {
doc, start, end := s.document()
lo := runeAt(doc, int(min(r.Location, uint(1<<31))))
hi := runeAt(doc, int(min(r.Location+r.Length, uint(1<<31))))
if s.marked == "" {
return lo, hi
}
n := len([]rune(s.input.Text))
sel := max(0, min(s.input.End, n)) - max(0, min(s.input.Start, n))
conv := func(i int, after bool) int {
switch {
case i <= start:
return i
case i < end: // in the marked text
if after {
return start + max(sel, 0)
}
return start
}
return i - (end - start) + max(sel, 0)
}
return conv(lo, false), conv(hi, true)
}
func (s *surface) substring(r nsRange, actual *nsRange) id {
if c := s.input.Client; c != nil {
text, rangeUsed := c.TextForRange(platform.TextRange{Start: int(min(r.Location, uint(1<<31))), End: int(min(r.Location+r.Length, uint(1<<31)))})
if actual != nil {
*actual = nsRange{Location: uint(rangeUsed.Start), Length: uint(max(0, rangeUsed.End-rangeUsed.Start))}
}
return autorelease(send(send(class("NSAttributedString"), "alloc"), "initWithString:", uintptr(nsString(text))))
}
doc, _, _ := s.document()
u := utf16.Encode(doc)
lo := int(min(r.Location, uint(len(u))))
hi := int(min(uint(lo)+r.Length, uint(len(u))))
if actual != nil {
*actual = nsRange{Location: uint(lo), Length: uint(hi - lo)}
}
str := send(send(class("NSAttributedString"), "alloc"), "initWithString:", uintptr(nsString(string(utf16.Decode(u[lo:hi])))))
return autorelease(str)
}
func (s *surface) setMarkedText(text string, selected, replacement nsRange) {
if c := s.input.Client; c != nil {
c.SetMarkedText(clientRange(replacement), text, platform.TextRange{Start: int(selected.Location), End: int(selected.Location + selected.Length)})
return
}
ev := platform.SurfaceEvent{Kind: platform.TextComposition, Text: text, Caret: runesBefore(text, int(selected.Location))}
if replacement.Location != nsNotFound {
ev.Replace = true
ev.From, ev.To = s.textRange(replacement)
}
s.marked, s.markedSel = text, selected
if !s.send(ev) && text != "" {
// The content left it, as a terminal does the dead key of a key
// it sent as Alt (Option as Alt): given up, rather than composed
// with the next key.
if s.keyDown {
s.refused = true
} else {
s.discardComposition()
}
}
}
// discardComposition has the input method give up its composition.
func (s *surface) discardComposition() {
s.marked = ""
send(send(s.view, "inputContext"), "discardMarkedText")
}
func (s *surface) insertText(text string, replacement nsRange) {
if c := s.input.Client; c != nil {
c.ReplaceText(clientRange(replacement), text)
return
}
ev := platform.SurfaceEvent{Kind: platform.TextInput, Text: text}
if replacement.Location != nsNotFound {
ev.Replace = true
ev.From, ev.To = s.textRange(replacement)
}
if s.marked != "" {
s.marked = ""
s.send(platform.SurfaceEvent{Kind: platform.TextComposition})
}
if text != "" || ev.Replace {
s.send(ev)
}
}
func clientRange(r nsRange) *platform.TextRange {
if r.Location == nsNotFound {
return nil
}
v := platform.TextRange{Start: int(min(r.Location, uint(1<<31))), End: int(min(r.Location+r.Length, uint(1<<31)))}
return &v
}
func (s *surface) hasMarkedText() bool {
if c := s.input.Client; c != nil {
_, ok := c.MarkedRange()
return ok
}
return s.marked != ""
}
func (s *surface) unmarkText() {
if c := s.input.Client; c != nil {
c.UnmarkText()
return
}
if s.marked != "" {
s.marked = ""
s.send(platform.SurfaceEvent{Kind: platform.TextComposition})
}
}
// interpretKeys has the input method interpret a key the surface's view
// got; it answers with the view's NSTextInputClient methods. The GUI tests
// stand in for an input method here (TestKeyComposing).
var interpretKeys = func(view, ev id) {
send(view, "interpretKeyEvents:", uintptr(nsArray(ev)))
}
// typedChars returns the text of a key's characters, without the control
// characters of Return, Tab, Escape and Delete, nor the private-use ones
// AppKit gives the arrows and function keys (NSUpArrowFunctionKey…),
// which come as keys.
func typedChars(chars string) string {
return strings.Map(func(r rune) rune {
if r < 0x20 || r == 0x7F || r >= 0xF700 && r <= 0xF8FF {
return -1
}
return r
}, chars)
}
+29
View File
@@ -0,0 +1,29 @@
//go:build darwin && !ios
package darwin
import "testing"
// TestStringOf reads text from strings and attributed strings, and from the
// NSNumber VoiceOver sends as a text field's AXValue (issue #802), which
// has no UTF8String.
func TestStringOf(t *testing.T) {
load()
withPool(func() {
attributed := autorelease(send(send(class("NSAttributedString"), "alloc"), "initWithString:", uintptr(nsString("rich"))))
for name, c := range map[string]struct {
obj id
want string
}{
"string": {nsString("plain"), "plain"},
"attributed": {attributed, "rich"},
"number": {nsNumberInt(42), "42"},
"null": {send(class("NSNull"), "null"), ""},
"nil": {0, ""},
} {
if got := stringOf(c.obj); got != c.want {
t.Errorf("stringOf(%s) = %q, want %q", name, got, c.want)
}
}
})
}
+395
View File
@@ -0,0 +1,395 @@
//go:build darwin && !ios
package darwin
import (
"errors"
"fmt"
"math"
"strings"
"sync"
"unsafe"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/transfer"
)
// Clipboard (NSPasteboard).
type clipboard struct{}
const (
utString = "public.utf8-plain-text"
utHTML = "public.html"
utPNG = "public.png"
utTIFF = "public.tiff"
)
func pasteboard() id { return send(class("NSPasteboard"), "generalPasteboard") }
func (clipboard) ReadText() string {
var s string
withPool(func() { s = goString(send(pasteboard(), "stringForType:", uintptr(nsString(utString)))) })
return s
}
func (c clipboard) WriteText(text string) { _ = c.WriteData(transfer.TextData(text), false, nil) }
func (clipboard) ReadHTML() string {
var s string
withPool(func() { s = goString(send(pasteboard(), "stringForType:", uintptr(nsString(utHTML)))) })
return s
}
func (c clipboard) WriteHTML(markup string) {
_ = c.WriteData(transfer.New(transfer.NewItem(transfer.Bytes(transfer.HTML, []byte(markup)), transfer.Bytes(transfer.Text, []byte(markup)))), false, nil)
}
func (clipboard) ReadImage() []byte {
var out []byte
withPool(func() {
pb := pasteboard()
if data := send(pb, "dataForType:", uintptr(nsString(utPNG))); data != 0 {
out = goBytes(data)
return
}
if data := send(pb, "dataForType:", uintptr(nsString(utTIFF))); data != 0 {
rep := send(class("NSBitmapImageRep"), "imageRepWithData:", uintptr(data))
if rep != 0 {
out = goBytes(send(rep, "representationUsingType:properties:", 4, uintptr(send(class("NSDictionary"), "dictionary"))))
}
}
})
return out
}
func (c clipboard) WriteImage(png []byte) error {
var err error
withPool(func() {
img := autorelease(send(send(class("NSImage"), "alloc"), "initWithData:", uintptr(nsData(png))))
if img == 0 {
err = errInvalidImage
}
})
if err != nil {
return err
}
return c.WriteData(transfer.New(transfer.NewItem(transfer.Bytes(transfer.PNG, png))), false, nil)
}
func (clipboard) Clear() {
withPool(func() {
send(pasteboard(), "clearContents")
if s := macClipboard; s != nil {
s.release()
}
})
}
func (clipboard) AvailableFormats() []string {
var out []string
withPool(func() {
for _, t := range arrayItems(send(pasteboard(), "types")) {
out = append(out, goString(t))
}
})
return out
}
// Shell (NSWorkspace).
type shell struct{}
func workspace() id { return send(class("NSWorkspace"), "sharedWorkspace") }
func (shell) OpenExternal(url string) error {
var err error
withPool(func() {
u := nsURL(url)
if u == 0 {
err = fmt.Errorf("mygo: invalid URL %q", url)
return
}
if !sendBool(workspace(), "openURL:", uintptr(u)) {
err = fmt.Errorf("mygo: no application can open %q", url)
}
})
return err
}
func (shell) OpenPath(path string) error {
var err error
withPool(func() {
if !sendBool(workspace(), "openURL:", uintptr(fileURL(path))) {
err = fmt.Errorf("mygo: cannot open %q", path)
}
})
return err
}
func (shell) ShowItemInFolder(path string) {
withPool(func() {
send(workspace(), "activateFileViewerSelectingURLs:", uintptr(nsArray(fileURL(path))))
})
}
func (shell) TrashItem(path string) error {
var err error
withPool(func() {
var nserr id
fm := send(class("NSFileManager"), "defaultManager")
if !sendBool(fm, "trashItemAtURL:resultingItemURL:error:", uintptr(fileURL(path)), 0, uintptr(unsafe.Pointer(&nserr))) {
err = nsError(nserr)
if err == nil {
err = errors.New("mygo: cannot move to trash")
}
}
})
return err
}
// TrashItemResult moves the item at path to the trash and returns the
// path where it landed inside the trash directory, so an app can put it
// back exactly. trashItemAtURL:resultingItemURL:error: writes the URL of
// the trashed item where the system left it; TrashItem passes nil for it
// and the path is lost. Finder renames an item that collides with one
// already in the trash ("foo.txt" -> "foo 2.txt"), so the returned path is
// the only way to find the trashed item.
func (shell) TrashItemResult(path string) (string, error) {
var trashPath string
var err error
withPool(func() {
var result id
var nserr id
fm := send(class("NSFileManager"), "defaultManager")
if !sendBool(fm, "trashItemAtURL:resultingItemURL:error:", uintptr(fileURL(path)), uintptr(unsafe.Pointer(&result)), uintptr(unsafe.Pointer(&nserr))) {
err = nsError(nserr)
if err == nil {
err = errors.New("mygo: cannot move to trash")
}
return
}
// result is set on success and nil on failure; pull its file path.
if result != 0 {
if p := send(result, "path"); p != 0 {
trashPath = goString(p)
}
}
})
return trashPath, err
}
// Quick Look: QLPreviewPanel is the panel Finder opens with the space bar.
// The app does not link QuickLook, so the framework is opened on first use,
// before its class and data source protocol can be looked up.
var (
quickLookOnce sync.Once
quickLookErr error
// previewSource is the retained data source; the panel keeps its data
// source unretained, so this one lives as long as the process.
previewSource id
previewURLMu sync.RWMutex
previewURL id
)
// loadQuickLook opens QuickLook.framework.
func loadQuickLook() error {
quickLookOnce.Do(func() {
_, quickLookErr = purego.Dlopen("/System/Library/Frameworks/QuickLook.framework/QuickLook", purego.RTLD_GLOBAL|purego.RTLD_NOW)
})
return quickLookErr
}
// previewDataSource returns the object QLPreviewPanel asks for the item to
// show: one item, the retained URL of the last PreviewItem call.
func previewDataSource() id {
if previewSource != 0 {
return previewSource
}
cls := classDef("MyGoPreviewDataSource", "NSObject", []string{"QLPreviewPanelDataSource"}, []objc.MethodDef{
method("numberOfPreviewItemsInPreviewPanel:", func(self id, _ objc.SEL, panel id) int { return 1 }),
method("previewPanel:previewItemAtIndex:", func(self id, _ objc.SEL, panel id, index int) id {
previewURLMu.RLock()
defer previewURLMu.RUnlock()
return previewURL
}),
})
previewSource = retain(send(send(cls, "alloc"), "init"))
return previewSource
}
// PreviewItem shows the item at path in the Quick Look panel, as Finder's
// space bar does. The panel stays open until the user closes it; asking
// again replaces the item it shows.
func (shell) PreviewItem(path string) error {
if err := loadQuickLook(); err != nil {
return fmt.Errorf("mygo: cannot load Quick Look: %w", err)
}
var err error
withPool(func() {
if !hasClass("QLPreviewPanel") {
err = platform.ErrUnsupported
return
}
src := previewDataSource()
u := retain(fileURL(path))
previewURLMu.Lock()
old := previewURL
previewURL = u
previewURLMu.Unlock()
release(old)
panel := send(class("QLPreviewPanel"), "sharedPreviewPanel")
send(panel, "setDataSource:", uintptr(src))
send(panel, "reloadData")
if theBackend != nil {
send(theBackend.app, "activateIgnoringOtherApps:", 1)
}
send(panel, "makeKeyAndOrderFront:", 0)
})
return err
}
func (shell) Beep() { nsBeep() }
// DefaultApp returns the application the system would use to open url.
// url may be a web URL (https://example.com), a file:// URL, or any URL
// whose scheme is registered with Launch Services. The name, bundle
// identifier and path of the .app bundle are returned.
func (shell) DefaultApp(url string) (platform.Application, error) {
var app platform.Application
var err error
withPool(func() {
u := nsURL(url)
if u == 0 {
err = fmt.Errorf("mygo: invalid URL %q", url)
return
}
// NSWorkspace -URLForApplicationToOpenURL: (10.10+) returns the
// .app bundle URL of the default handler.
appURL := send(workspace(), "URLForApplicationToOpenURL:", uintptr(u))
if appURL == 0 {
err = fmt.Errorf("mygo: no application found for %q", url)
return
}
// Pull the file-system path from the NSURL.
path := goString(send(appURL, "path"))
if path == "" {
err = fmt.Errorf("mygo: no application found for %q", url)
return
}
// Resolve name and bundle ID from the .app bundle.
bundle := send(class("NSBundle"), "bundleWithPath:", uintptr(nsString(path)))
fm := send(class("NSFileManager"), "defaultManager")
name := strings.TrimSuffix(goString(send(fm, "displayNameAtPath:", uintptr(nsString(path)))), ".app")
id := ""
if bundle != 0 {
id = goString(send(bundle, "bundleIdentifier"))
}
if id == "" {
id = path
}
app = platform.Application{Name: name, ID: id, Path: path}
})
return app, err
}
// Screen (NSScreen).
type screen struct{}
func (screen) Displays() []platform.Display {
var out []platform.Display
withPool(func() {
screens := arrayItems(send(class("NSScreen"), "screens"))
if len(screens) == 0 {
return
}
key := nsString("NSScreenNumber")
for i, s := range screens {
num := send(send(s, "deviceDescription"), "objectForKey:", uintptr(key))
displayID := uint32(send(num, "unsignedIntValue"))
d := platform.Display{
ID: int64(displayID),
Bounds: rectFromMac(msgRect(s, sel("frame"))),
WorkArea: rectFromMac(msgRect(s, sel("visibleFrame"))),
ScaleFactor: msgFloat(s, sel("backingScaleFactor")),
Rotation: int(math.Round(cgDisplayRotation(displayID))),
Internal: cgDisplayIsBuiltin(displayID),
Primary: i == 0,
}
if respondsTo(s, "localizedName") {
d.Label = goString(send(s, "localizedName"))
}
out = append(out, d)
}
})
return out
}
func (screen) CursorPoint() platform.Point {
p := msgPoint(class("NSEvent"), sel("mouseLocation"))
return platform.Point{X: int(math.Round(p.X)), Y: int(math.Round(primaryScreenHeight() - p.Y))}
}
// Theme (NSAppearance).
type theme struct{ b *Backend }
// UIFont is Core Text's to find: the system font.
func (theme) UIFont() string { return "" }
func (theme) FontRendering() platform.FontRendering { return platform.FontRendering{} }
// Preferences reads the accent color and the display settings of
// accessibility.
func (t theme) Preferences() platform.Preferences {
var p platform.Preferences
withPool(func() {
ws := workspace()
p.ReduceMotion = sendBool(ws, "accessibilityDisplayShouldReduceMotion")
p.ReduceTransparency = sendBool(ws, "accessibilityDisplayShouldReduceTransparency")
p.HighContrast = sendBool(ws, "accessibilityDisplayShouldIncreaseContrast")
// The accent, as the app's appearance draws it.
var c id
appearance := class("NSAppearance")
prev := send(appearance, "currentAppearance")
send(appearance, "setCurrentAppearance:", uintptr(send(t.b.app, "effectiveAppearance")))
if accent := send(class("NSColor"), "controlAccentColor"); accent != 0 {
c = send(accent, "colorUsingColorSpace:", uintptr(send(class("NSColorSpace"), "sRGBColorSpace")))
}
send(appearance, "setCurrentAppearance:", uintptr(prev))
if c != 0 {
var r, g, b, a float64
send(c, "getRed:green:blue:alpha:", uintptr(unsafe.Pointer(&r)), uintptr(unsafe.Pointer(&g)), uintptr(unsafe.Pointer(&b)), uintptr(unsafe.Pointer(&a)))
byteOf := func(v float64) uint8 { return uint8(max(0, min(v, 1))*255 + 0.5) }
p.Accent = platform.Color{R: byteOf(r), G: byteOf(g), B: byteOf(b), A: 255}
}
})
return p
}
func (t theme) IsDark() bool {
var dark bool
withPool(func() {
appearance := send(t.b.app, "effectiveAppearance")
names := nsArray(nsString("NSAppearanceNameAqua"), nsString("NSAppearanceNameDarkAqua"))
dark = goString(send(appearance, "bestMatchFromAppearancesWithNames:", uintptr(names))) == "NSAppearanceNameDarkAqua"
})
return dark
}
func (t theme) SetSource(source string) {
withPool(func() {
var appearance id
switch source {
case "light":
appearance = send(class("NSAppearance"), "appearanceNamed:", uintptr(nsString("NSAppearanceNameAqua")))
case "dark":
appearance = send(class("NSAppearance"), "appearanceNamed:", uintptr(nsString("NSAppearanceNameDarkAqua")))
}
send(t.b.app, "setAppearance:", uintptr(appearance))
})
}
File diff suppressed because it is too large. Load diff
+61
View File
@@ -0,0 +1,61 @@
//go:build darwin && !ios
package darwin
import "testing"
// TestSecondaryClick tells a status item's right-clicks from its clicks: the
// right button's, and the primary button's with Control held, whatever else is.
func TestSecondaryClick(t *testing.T) {
const (
leftUp, rightUp = 2, 4
shift, control, option, command = 1 << 17, 1 << 18, 1 << 19, 1 << 20
)
for _, c := range []struct {
typ, flags uint
want bool
}{
{leftUp, 0, false},
{leftUp, shift, false},
{leftUp, option, false},
{leftUp, command, false},
{leftUp, control, true},
{leftUp, control | shift, true},
{rightUp, 0, true},
{rightUp, control, true},
} {
if got := secondaryClick(c.typ, c.flags); got != c.want {
t.Errorf("type %d, flags %#x: %v, want %v", c.typ, c.flags, got, c.want)
}
}
}
// TestClickedCopy finds the copy of a menu bar item that a click hit from the
// pointer's place on screen and the click's place in the item's window: here a
// copy on an external display, far from the item's window.
func TestClickedCopy(t *testing.T) {
got := clickedCopy(NSPoint{X: 2251, Y: 1422}, NSPoint{X: 30, Y: 12}, NSSize{Width: 54, Height: 24})
want := NSRect{Origin: NSPoint{X: 2221, Y: 1410}, Size: NSSize{Width: 54, Height: 24}}
if got != want {
t.Errorf("clickedCopy = %+v, want %+v", got, want)
}
}
// TestItemFrame keeps the copy clicked while the item's window keeps the frame
// it had at the click, and goes back to the window's frame without a click or
// once the window moved.
func TestItemFrame(t *testing.T) {
window := NSRect{Origin: NSPoint{X: 159, Y: 1050}, Size: NSSize{Width: 54, Height: 24}}
clicked := NSRect{Origin: NSPoint{X: 2221, Y: 1410}, Size: NSSize{Width: 54, Height: 24}}
if got := itemFrame(window, NSRect{}, NSRect{}); got != window {
t.Errorf("no click: %+v, want the window's %+v", got, window)
}
if got := itemFrame(window, clicked, window); got != clicked {
t.Errorf("clicked: %+v, want the copy's %+v", got, clicked)
}
moved := window
moved.Origin.X -= 40
if got := itemFrame(moved, clicked, window); got != moved {
t.Errorf("window moved: %+v, want its new frame %+v", got, moved)
}
}
+445
View File
@@ -0,0 +1,445 @@
//go:build darwin && !ios
package darwin
import (
"errors"
"os"
"runtime"
"strings"
"sync"
"unsafe"
"github.com/ebitengine/purego"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/internal/watchdriver"
)
// Watches use FSEvents: one stream per directory target, covering the whole
// tree beneath it, so a watch costs no descriptor per file and a large
// folder is fine. The stream reports what changed (with
// kFSEventStreamCreateFlagFileEvents) rather than only that something did,
// but the notices stay hints: the core compares snapshots, and a notice
// that changes may have been dropped (MustScanSubDirs, a user or kernel
// drop) makes it look at everything again, as an overflow does elsewhere.
// FSEventStreamCreateFlags.
const (
fseNoDefer = 0x00000002 // kFSEventStreamCreateFlagNoDefer
fseWatchRoot = 0x00000004 // kFSEventStreamCreateFlagWatchRoot
fseFileEvents = 0x00000010 // kFSEventStreamCreateFlagFileEvents
)
// FSEventStreamEventFlags.
const (
fseMustScanSubDirs = 0x00000001
fseUserDropped = 0x00000002
fseKernelDropped = 0x00000004
fseEventIdsWrapped = 0x00000008
fseHistoryDone = 0x00000010
fseRootChanged = 0x00000020
fseMount = 0x00000040
fseUnmount = 0x00000080
fseItemCreated = 0x00000100
fseItemRemoved = 0x00000200
fseItemInodeMeta = 0x00000400
fseItemRenamed = 0x00000800
fseItemModified = 0x00001000
fseItemFinderInfo = 0x00002000
fseItemChangeOwner = 0x00004000
fseItemXattr = 0x00008000
fseItemIsFile = 0x00010000
fseItemIsDir = 0x00020000
fseItemIsSymlink = 0x00040000
)
const (
// fseLatency is how long FSEvents may coalesce events: 10 ms, well
// under the core's 50 ms Debounce, so the core's trailing debounce
// does the coalescing an app sees and the stream only batches bursts.
// With fseNoDefer the first event after a quiet period is delivered
// at once rather than after the latency, and the events that follow
// it within the latency are batched.
fseLatency = 0.01
// fseQueueSize is how many notices a watch holds before it asks the
// core to look at everything again.
fseQueueSize = 4096
// fseUTF8 is kCFStringEncodingUTF8.
fseUTF8 = 0x08000100
// fseFramework is where the FSEvents C API lives.
fseFramework = "/System/Library/Frameworks/CoreServices.framework/Frameworks/FSEvents.framework/FSEvents"
)
// The FSEvents API, bound once.
var (
fseStreamCreate func(alloc, callback uintptr, context *fseContext, paths uintptr, sinceWhen uint64, latency float64, flags uint32) uintptr
fseStreamStart func(stream uintptr) uint8
fseStreamStop func(stream uintptr)
fseStreamInvalidate func(stream uintptr)
fseStreamRelease func(stream uintptr)
fseStreamSetQueue func(stream, queue uintptr)
cfStringCreateWithCString func(alloc uintptr, s *byte, encoding uint32) uintptr
cfArrayCreate func(alloc uintptr, values *uintptr, n int, callbacks uintptr) uintptr
kCFTypeArrayCallBacks uintptr
watchQueueCreate func(label *byte, attr uintptr) uintptr
dispatchSyncF func(queue, context, work uintptr)
libcRealpath func(path, resolved *byte) uintptr
// fseCallback is the process's one FSEventStreamCallback, and fseFlush
// what dispatch_sync_f runs to wait for the callbacks already queued:
// created with the first watch and never freed.
fseCallback, fseFlush uintptr
// fseQueue is the one serial queue every stream delivers on, off the
// main thread, so stopping a stream can wait for a callback already
// running with dispatch_sync_f.
fseQueue uintptr
fseOnce sync.Once
)
// loadFSEvents binds FSEvents, CoreFoundation's string and array
// constructors and libdispatch, once, whoever asks first (NewFileWatch can
// run before the app does, and tests make a Backend directly).
func loadFSEvents() {
fseOnce.Do(func() {
load()
lib := libCoreServices
// CoreServices re-exports FSEvents; the subframework, when it is
// there, pins the symbols to it.
if h, err := purego.Dlopen(fseFramework, purego.RTLD_GLOBAL|purego.RTLD_NOW); err == nil {
lib = h
}
purego.RegisterLibFunc(&fseStreamCreate, lib, "FSEventStreamCreate")
purego.RegisterLibFunc(&fseStreamStart, lib, "FSEventStreamStart")
purego.RegisterLibFunc(&fseStreamStop, lib, "FSEventStreamStop")
purego.RegisterLibFunc(&fseStreamInvalidate, lib, "FSEventStreamInvalidate")
purego.RegisterLibFunc(&fseStreamRelease, lib, "FSEventStreamRelease")
purego.RegisterLibFunc(&fseStreamSetQueue, lib, "FSEventStreamSetDispatchQueue")
purego.RegisterLibFunc(&cfStringCreateWithCString, libCF, "CFStringCreateWithCString")
purego.RegisterLibFunc(&cfArrayCreate, libCF, "CFArrayCreate")
kCFTypeArrayCallBacks = mustDlsym(libCF, "kCFTypeArrayCallBacks")
purego.RegisterLibFunc(&watchQueueCreate, purego.RTLD_DEFAULT, "dispatch_queue_create")
purego.RegisterLibFunc(&dispatchSyncF, purego.RTLD_DEFAULT, "dispatch_sync_f")
// The UNIX03 realpath on Intel; Apple silicon has only one.
realpath := "realpath$DARWIN_EXTSN"
if _, err := purego.Dlsym(purego.RTLD_DEFAULT, realpath); err != nil {
realpath = "realpath"
}
purego.RegisterLibFunc(&libcRealpath, purego.RTLD_DEFAULT, realpath)
fseCallback = purego.NewCallback(fseEvents)
// Our callback never blocks, so waiting for it cannot deadlock.
fseFlush = purego.NewCallback(func() {})
label := []byte("mygo.watch\x00")
fseQueue = watchQueueCreate(&label[0], 0)
})
}
// fseContext mirrors FSEventStreamContext. FSEvents copies it, and hands
// info back to the callback, which is how the one callback finds its stream.
type fseContext struct {
version uintptr
info uintptr
retain uintptr
release uintptr
copyDescription uintptr
}
// fseStream is one FSEventStream watching one directory target.
type fseStream struct {
id uint64
path string
subtree bool
driver *fseWatch
stream uintptr
started bool
context fseContext
}
// fseStreams routes the one FSEventStreamCallback of the process to the
// stream of the event, by the context info FSEvents hands back.
var fseStreams = struct {
sync.Mutex
m map[uintptr]*fseStream
}{m: map[uintptr]*fseStream{}}
// fseEvents is the FSEventStreamCallback. Without
// kFSEventStreamCreateFlagUseCFTypes the paths are a C array of C strings.
func fseEvents(stream, info, numEvents, paths, flags, ids uintptr) uintptr {
if info == 0 {
return 0
}
fseStreams.Lock()
s := fseStreams.m[info]
fseStreams.Unlock()
if s == nil {
return 0
}
// The addresses come from FSEvents, not from Go: keep them out of
// uintptr conversions the compiler and the GC don't understand.
eventPaths, eventFlags := ptrOf(paths), ptrOf(flags)
for i := uintptr(0); i < numEvents; i++ {
p := *(*uintptr)(unsafe.Add(eventPaths, i*unsafe.Sizeof(uintptr(0))))
if p == 0 {
continue
}
path := cString(ptrOf(p))
if n, ok := s.event(path, *(*uint32)(unsafe.Add(eventFlags, i*4))); ok {
s.deliver(n)
}
}
return 0
}
// ptrOf returns the pointer at the native address p.
func ptrOf(p uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&p)) }
// cString copies the NUL-terminated string at p.
func cString(p unsafe.Pointer) string {
n := 0
for *(*byte)(unsafe.Add(p, n)) != 0 {
n++
}
return string(unsafe.Slice((*byte)(p), n))
}
// event translates one FSEvents event of the stream into a notice: pure,
// so the mapping can be tested without the framework.
func (s *fseStream) event(path string, flags uint32) (platform.FileWatchNotice, bool) {
prefix := s.path
if !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
rel, ok := strings.CutPrefix(path, prefix)
if !ok {
if path != s.path {
return platform.FileWatchNotice{}, false
}
rel = ""
}
if flags&(fseMustScanSubDirs|fseUserDropped|fseKernelDropped|fseEventIdsWrapped) != 0 {
// Changes were dropped: the core lists everything again.
return platform.FileWatchNotice{Target: s.id, Err: platform.ErrFileWatchOverflow}, true
}
if !s.subtree && strings.Contains(rel, "/") {
// FSEvents is recursive, but a target without Subtree is about its
// directory and the entries in it, which a change deeper down
// doesn't change: a directory's own changes are not reported.
return platform.FileWatchNotice{}, false
}
n := platform.FileWatchNotice{Target: s.id, Name: rel}
switch {
case flags&fseHistoryDone != 0:
return platform.FileWatchNotice{}, false
case flags&fseRootChanged != 0:
// The watched directory was moved, renamed or replaced: the core
// stats it and ends the watch when it is gone.
return n, true
case flags&fseUnmount != 0:
n.Kind = platform.FileWatchLost
case flags&fseMount != 0:
// A volume appeared in the tree.
case flags&(fseItemRemoved|fseItemRenamed|fseItemCreated) != 0:
// Dirty: the core looks. A write on APFS sets ItemCreated too (an
// O_TRUNC write reports the file as created), and a metadata
// change can carry ItemModified, so the structural flags must win:
// only a plain content write is a Write hint, and the core's
// snapshot comparison reports the writes that are dirty instead.
case flags&fseItemModified != 0 && flags&fseItemIsFile != 0:
n.Kind = platform.FileWatchWrite
}
return n, true
}
// deliver hands a notice to Wait, or, with the queue full, asks the core to
// look at everything again. It never blocks: it runs on the dispatch queue,
// which a stream's teardown waits on.
func (s *fseStream) deliver(n platform.FileWatchNotice) {
d := s.driver
d.mu.Lock()
if len(d.notices) < fseQueueSize {
d.notices = append(d.notices, n)
} else {
d.overflow = true
}
d.mu.Unlock()
d.Wake()
}
// stop stops and releases the stream. Only the goroutine of the watch calls
// it, but a callback may be running: dispatch_sync_f waits for the queue,
// after which nothing touches s.
func (s *fseStream) stop() {
if s.stream == 0 {
return
}
if s.started {
fseStreamStop(s.stream)
s.started = false
}
fseStreamInvalidate(s.stream)
dispatchSyncF(fseQueue, 0, fseFlush)
fseStreams.Lock()
delete(fseStreams.m, s.context.info)
fseStreams.Unlock()
fseStreamRelease(s.stream)
s.stream = 0
}
// fseWatch is the FSEvents implementation of watchdriver.Driver: one stream
// per directory target, all delivering on fseQueue.
type fseWatch struct {
// notices are filled by the callback, on the dispatch queue, and taken
// by Wait on the goroutine of the watch; overflow says there were too
// many, so the core must look at everything.
mu sync.Mutex
notices []platform.FileWatchNotice
overflow bool
// wake interrupts Wait, buffered so Wake never waits.
wake chan struct{}
// streams are the running streams by target ID; only the goroutine of
// the watch (Add, Remove, Close) uses it.
streams map[uint64]*fseStream
}
func (*Backend) NewFileWatch(notify func(platform.FileWatchNotice)) (platform.FileWatch, error) {
loadFSEvents()
if fseQueue == 0 {
return nil, errors.New("cannot create the watch dispatch queue")
}
d := &fseWatch{wake: make(chan struct{}, 1), streams: map[uint64]*fseStream{}}
return watchdriver.New(d, notify), nil
}
// canonicalPath resolves path with realpath, which gives the names as they
// are on disk, or returns it as it is when it can't.
func canonicalPath(path string) string {
in := append([]byte(path), 0)
var out [1024]byte // PATH_MAX
if libcRealpath(&in[0], &out[0]) == 0 {
return path
}
for i, c := range out {
if c == 0 {
return string(out[:i])
}
}
return path
}
// covered reports whether a whole tree above path is already watched: a
// target the core enrolls below it needs no stream of its own. Only the
// goroutine of the watch calls it, so streams needs no lock.
func (d *fseWatch) covered(path string) bool {
for _, s := range d.streams {
prefix := s.path
if !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
if path == s.path || strings.HasPrefix(path, prefix) {
return true
}
}
return false
}
func (d *fseWatch) Add(t platform.FileWatchTarget) error {
if !t.Directory {
// A file is covered by the stream of the directory that holds it,
// which the core enrolls for a file watch (watchParent), and
// FSEvents watches trees, not single files.
return platform.ErrUnsupported
}
// FSEvents reports paths as they are on disk, which a path given on a
// case-insensitive volume may not be.
streamPath := canonicalPath(t.Path)
if d.covered(streamPath) {
// A stream above t already watches its whole tree: FSEvents is
// recursive, so a target beneath it needs no stream of its own.
// The core enrolls the directories in a directory it doesn't
// watch recursively, which the stream above names, without what
// changes in them, which the core doesn't report.
return nil
}
info, err := os.Lstat(streamPath)
if err != nil {
return err
}
if !os.SameFile(info, t.Info) {
return errors.New("watch target identity changed")
}
path := append([]byte(streamPath), 0)
cfPath := cfStringCreateWithCString(0, &path[0], fseUTF8)
runtime.KeepAlive(path)
if cfPath == 0 {
return errors.New("cannot make the watch path a CFString")
}
values := []uintptr{cfPath}
cfPaths := cfArrayCreate(0, &values[0], 1, kCFTypeArrayCallBacks)
runtime.KeepAlive(values)
if cfPaths == 0 {
cfRelease(cfPath)
return errors.New("cannot make the watch paths a CFArray")
}
s := &fseStream{id: t.ID, path: streamPath, subtree: t.Subtree, driver: d}
s.context.info = uintptr(unsafe.Pointer(s))
// kFSEventStreamEventIdSinceNow: the core's snapshot is taken already.
stream := fseStreamCreate(0, fseCallback, &s.context, cfPaths, ^uint64(0), fseLatency, fseNoDefer|fseFileEvents|fseWatchRoot)
cfRelease(cfPaths)
cfRelease(cfPath)
if stream == 0 {
return errors.New("cannot create an FSEventStream")
}
s.stream = stream
fseStreams.Lock()
fseStreams.m[s.context.info] = s
fseStreams.Unlock()
fseStreamSetQueue(stream, fseQueue)
if fseStreamStart(stream) == 0 {
s.stop()
return errors.New("cannot start an FSEventStream")
}
s.started = true
d.streams[t.ID] = s
return nil
}
func (d *fseWatch) Remove(id uint64) {
if s := d.streams[id]; s != nil {
s.stop()
delete(d.streams, id)
}
}
// Wait returns the notices that came in, or, after an overflow, one notice
// that makes the core look at everything again. Wake makes it return, so
// that the command Wake announced is taken.
func (d *fseWatch) Wait() ([]platform.FileWatchNotice, error) {
<-d.wake
d.mu.Lock()
defer d.mu.Unlock()
notices := d.notices
d.notices = nil
if d.overflow {
// The notices held are covered by the core's full scan.
d.overflow = false
return []platform.FileWatchNotice{{Err: platform.ErrFileWatchOverflow}}, nil
}
return notices, nil
}
func (d *fseWatch) Wake() {
select {
case d.wake <- struct{}{}:
default:
}
}
func (d *fseWatch) Close() {
for id, s := range d.streams {
s.stop()
delete(d.streams, id)
}
}
+298
View File
@@ -0,0 +1,298 @@
//go:build darwin && !ios
package darwin
import (
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/internal/wait"
)
func TestFSEventsEventMapping(t *testing.T) {
sub := &fseStream{id: 7, path: "/w", subtree: true}
plain := &fseStream{id: 7, path: "/w"}
for _, tc := range []struct {
name string
s *fseStream
path string
flags uint32
want string
kind platform.FileWatchKind
err error
ok bool
}{
{"root", sub, "/w", fseItemModified | fseItemIsFile, "", platform.FileWatchWrite, nil, true},
{"child", sub, "/w/child", fseItemModified | fseItemIsFile, "child", platform.FileWatchWrite, nil, true},
{"subtree deep", sub, "/w/a/b", fseItemCreated, "a/b", platform.FileWatchDirty, nil, true},
{"plain deep", plain, "/w/a/b", fseItemCreated, "", 0, nil, false},
{"plain deep dropped", plain, "/w/a/b", fseKernelDropped | fseMustScanSubDirs, "", 0, platform.ErrFileWatchOverflow, true},
{"created", sub, "/w/a", fseItemCreated, "a", platform.FileWatchDirty, nil, true},
{"removed", sub, "/w/a", fseItemRemoved, "a", platform.FileWatchDirty, nil, true},
{"renamed", sub, "/w/a", fseItemRenamed, "a", platform.FileWatchDirty, nil, true},
{"metadata", sub, "/w/a", fseItemInodeMeta | fseItemIsFile, "a", platform.FileWatchDirty, nil, true},
{"created and modified", sub, "/w/a", fseItemCreated | fseItemModified | fseItemIsFile, "a", platform.FileWatchDirty, nil, true},
{"removed and modified", sub, "/w/a", fseItemRemoved | fseItemModified | fseItemIsFile, "a", platform.FileWatchDirty, nil, true},
{"modified directory", sub, "/w/a", fseItemModified | fseItemIsDir, "a", platform.FileWatchDirty, nil, true},
{"root changed", sub, "/w", fseRootChanged, "", platform.FileWatchDirty, nil, true},
{"mount", sub, "/w/a", fseMount, "a", platform.FileWatchDirty, nil, true},
{"unmount", sub, "/w/a", fseUnmount, "a", platform.FileWatchLost, nil, true},
{"must scan", sub, "/w/a", fseMustScanSubDirs, "", 0, platform.ErrFileWatchOverflow, true},
{"user dropped", sub, "/w/a", fseUserDropped, "", 0, platform.ErrFileWatchOverflow, true},
{"kernel dropped", sub, "/w/a", fseKernelDropped, "", 0, platform.ErrFileWatchOverflow, true},
{"ids wrapped", sub, "/w/a", fseEventIdsWrapped, "", 0, platform.ErrFileWatchOverflow, true},
{"history done", sub, "/w/a", fseHistoryDone, "", 0, nil, false},
{"outside", sub, "/other/a", fseItemCreated, "", 0, nil, false},
{"sibling prefix", sub, "/w2/a", fseItemCreated, "", 0, nil, false},
{"volume root", &fseStream{id: 7, path: "/", subtree: true}, "/a/b", fseItemCreated, "a/b", platform.FileWatchDirty, nil, true},
} {
t.Run(tc.name, func(t *testing.T) {
n, ok := tc.s.event(tc.path, tc.flags)
if ok != tc.ok {
t.Fatalf("ok = %v, want %v", ok, tc.ok)
}
if !ok {
return
}
if n.Target != 7 || n.Kind != tc.kind || n.Name != tc.want || !errors.Is(n.Err, tc.err) {
t.Fatalf("notice = %+v, want kind %v name %q err %v", n, tc.kind, tc.want, tc.err)
}
})
}
}
// watchTestDir is a temp directory with its symlinks resolved, as the core
// resolves what it watches (macOS's /tmp is /private/tmp).
func watchTestDir(t *testing.T) string {
t.Helper()
dir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
return dir
}
// watchTest makes a backend watch, closed when the test ends.
func watchTest(t *testing.T) (platform.FileWatch, chan platform.FileWatchNotice) {
t.Helper()
notices := make(chan platform.FileWatchNotice, 256)
w, err := (&Backend{}).NewFileWatch(func(n platform.FileWatchNotice) { notices <- n })
if err != nil {
t.Fatal(err)
}
t.Cleanup(w.Close)
return w, notices
}
// watchTestNext waits for a notice of kind about a target naming one of
// names, and fails when none comes.
func watchTestNext(t *testing.T, notices chan platform.FileWatchNotice, target uint64, kind platform.FileWatchKind, names ...string) {
t.Helper()
watchTestNextKinds(t, notices, target, []platform.FileWatchKind{kind}, names...)
}
// watchTestNextKinds is watchTestNext for events whose flags vary: a write
// on APFS carries ItemCreated and ItemModified at once, for example, which
// the mapping calls dirty.
func watchTestNextKinds(t *testing.T, notices chan platform.FileWatchNotice, target uint64, kinds []platform.FileWatchKind, names ...string) {
t.Helper()
deadline := time.Now().Add(wait.Guard)
for time.Now().Before(deadline) {
select {
case n := <-notices:
if n.Target == target && slices.Contains(kinds, n.Kind) && slices.Contains(names, n.Name) {
return
}
case <-time.After(time.Until(deadline)):
}
}
t.Fatalf("no notice of %v for %q on target %d", kinds, names, target)
}
func watchTestAdd(t *testing.T, w platform.FileWatch, id uint64, path string, subtree bool) {
t.Helper()
info, err := os.Lstat(path)
if err != nil {
t.Fatal(err)
}
if err := w.Add(platform.FileWatchTarget{ID: id, Path: path, Directory: info.IsDir(), Info: info, Subtree: subtree}); err != nil {
t.Fatal(err)
}
}
func watchTestWrite(t *testing.T, path, content string) {
t.Helper()
if err := os.WriteFile(path, []byte(content), 0600); err != nil {
t.Fatal(err)
}
}
// watchTestWritten is what a write is reported as: written for FSEvents'
// plain content events, dirty for the writes APFS also calls created.
var watchTestWritten = []platform.FileWatchKind{platform.FileWatchWrite, platform.FileWatchDirty}
func TestFSEventsWatch(t *testing.T) {
dir := watchTestDir(t)
sub := filepath.Join(dir, "sub")
if err := os.Mkdir(sub, 0700); err != nil {
t.Fatal(err)
}
file := filepath.Join(sub, "file")
watchTestWrite(t, file, "one")
w, notices := watchTest(t)
// FSEvents is recursive by nature: a Subtree target must be watched,
// not refused.
watchTestAdd(t, w, 1, dir, true)
// A target without Subtree watches the directory and its direct
// children, and drops events deeper down.
other := watchTestDir(t)
otherFile := filepath.Join(other, "file")
watchTestWrite(t, otherFile, "one")
watchTestAdd(t, w, 2, other, false)
watchTestWrite(t, file, "two, longer")
watchTestNextKinds(t, notices, 1, watchTestWritten, "sub/file")
watchTestWrite(t, otherFile, "two, longer")
watchTestNextKinds(t, notices, 2, watchTestWritten, "file")
// A directory beneath a watched tree needs no stream of its own: the
// core enrolls children of a directory it doesn't watch recursively,
// which the stream above names, and what changes in them is dropped.
child := filepath.Join(other, "child")
if err := os.Mkdir(child, 0700); err != nil {
t.Fatal(err)
}
watchTestNext(t, notices, 2, platform.FileWatchDirty, "child")
watchTestAdd(t, w, 3, child, false)
watchTestWrite(t, filepath.Join(child, "inside"), "one")
watchTestWrite(t, otherFile, "after inside")
for timeout := time.After(10 * time.Second); ; {
var n platform.FileWatchNotice
select {
case n = <-notices:
case <-timeout:
t.Fatal("no notice for file")
}
if n.Target == 2 && n.Name == "child" {
t.Fatalf("change inside a child reported: %+v", n)
}
if n.Target == 2 && n.Name == "file" {
break
}
}
if err := os.WriteFile(filepath.Join(sub, "new"), nil, 0600); err != nil {
t.Fatal(err)
}
watchTestNext(t, notices, 1, platform.FileWatchDirty, "sub/new")
if err := os.Remove(filepath.Join(sub, "new")); err != nil {
t.Fatal(err)
}
watchTestNext(t, notices, 1, platform.FileWatchDirty, "sub/new")
if err := os.Mkdir(filepath.Join(sub, "deeper"), 0700); err != nil {
t.Fatal(err)
}
watchTestNext(t, notices, 1, platform.FileWatchDirty, "sub/deeper")
if err := os.Remove(filepath.Join(sub, "deeper")); err != nil {
t.Fatal(err)
}
watchTestNext(t, notices, 1, platform.FileWatchDirty, "sub/deeper")
// A rename reports both names.
if err := os.Rename(file, filepath.Join(sub, "moved")); err != nil {
t.Fatal(err)
}
watchTestNext(t, notices, 1, platform.FileWatchDirty, "sub/file", "sub/moved")
// Removing a target doesn't panic, and its stream stops.
w.Remove(1)
watchTestWrite(t, filepath.Join(sub, "after-remove"), "x")
watchTestWrite(t, otherFile, "three, longer")
watchTestNextKinds(t, notices, 2, watchTestWritten, "file")
}
// A file is watched through the directory that holds it, whose stream
// reports it by name: a file target is refused, so that the core enrolls
// no files.
func TestFSEventsWatchFile(t *testing.T) {
dir := watchTestDir(t)
file := filepath.Join(dir, "config.json")
watchTestWrite(t, file, "one")
w, notices := watchTest(t)
watchTestAdd(t, w, 1, dir, false)
info, err := os.Lstat(file)
if err != nil {
t.Fatal(err)
}
if err := w.Add(platform.FileWatchTarget{ID: 2, Path: file, Info: info}); !errors.Is(err, platform.ErrUnsupported) {
t.Fatalf("file target: %v", err)
}
watchTestWrite(t, file, "two, longer")
watchTestNextKinds(t, notices, 1, watchTestWritten, "config.json")
}
func TestFSEventsWatchIdentity(t *testing.T) {
w, _ := watchTest(t)
dir := filepath.Join(watchTestDir(t), "a")
if err := os.Mkdir(dir, 0700); err != nil {
t.Fatal(err)
}
info, err := os.Lstat(dir)
if err != nil {
t.Fatal(err)
}
if err := os.Remove(dir); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(dir, 0700); err != nil {
t.Fatal(err)
}
err = w.Add(platform.FileWatchTarget{ID: 1, Path: dir, Directory: true, Info: info})
if err == nil || !strings.Contains(err.Error(), "identity") {
t.Fatalf("Add of a replaced directory: %v", err)
}
}
// TestFSEventsWatchManyFiles watches a directory with more entries than
// other backends' limit of 8192: one stream covers it all.
func TestFSEventsWatchManyFiles(t *testing.T) {
if testing.Short() {
t.Skip("creates 10001 files")
}
dir := watchTestDir(t)
start := time.Now()
for i := range 10001 {
if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("file-%05d", i)), []byte("x"), 0600); err != nil {
t.Fatal(err)
}
}
if d := time.Since(start); d > 2*time.Second {
t.Logf("created 10001 files in %v", d)
}
w, notices := watchTest(t)
watchTestAdd(t, w, 1, dir, true)
watchTestWrite(t, filepath.Join(dir, "file-00042"), "written")
watchTestNextKinds(t, notices, 1, watchTestWritten, "file-00042")
}
// A path given in another case than the disk's, on a case-insensitive
// volume, is watched as the disk names it, which is how FSEvents reports it.
func TestFSEventsWatchCase(t *testing.T) {
dir := watchTestDir(t)
if err := os.Mkdir(filepath.Join(dir, "Proj"), 0700); err != nil {
t.Fatal(err)
}
lower := filepath.Join(dir, "proj")
if _, err := os.Lstat(lower); err != nil {
t.Skip("the volume is case-sensitive")
}
w, notices := watchTest(t)
watchTestAdd(t, w, 1, lower, true)
watchTestWrite(t, filepath.Join(dir, "Proj", "file"), "one")
watchTestNextKinds(t, notices, 1, append(watchTestWritten, platform.FileWatchDirty), "file")
}
+609
View File
@@ -0,0 +1,609 @@
//go:build darwin && !ios
package darwin
import (
"errors"
"math"
"slices"
"sync"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
// A web view in a window of native UI (platform.Surface.NewWebView) is a
// window of this package without an NSWindow of its own: win is its
// host's, which its sheets and panels use, and its MyGoWebView sits in a
// clip view, a subview of the host's content view under the surface. The
// surface's frames are transparent where the content shows the web view
// (holes), so what the content paints after it shows over the page, and
// its hitTest: lets the pointer through to the page there; the web view
// takes no mouse moves where the content painted over it. Its delegate is
// the web view's alone, never the NSWindow's, so it hears only of its
// page.
//
// Between the clip view and the web view, a pane at the web view's frame
// cuts it to the corners of the content's hole. A transform of the
// content scaling the page scales the pane's bounds: the web view keeps
// its size, which the page lays out at, and shows scaled, as AppKit draws
// and finds the pointer in views of scaled bounds.
// nsViewMinYMargin is NSViewMinYMargin: the margin below a view grows,
// which keeps its distance to the top of an unflipped superview.
const nsViewMinYMargin = 8
func (s *surface) NewWebView(o *platform.WindowOptions, h platform.WindowHandler) (platform.WebView, error) {
host := s.w
b := host.b
v := &window{b: b, h: h, opts: o, win: host.win, host: host, downloads: map[id][2]string{}}
withPool(func() {
v.delegate = alloc("MyGoWindowDelegate")
v.createWebView(NSRect{})
send(v.web, "setAutoresizingMask:", 0)
v.clip = msgInitRect(send(class("MyGoClipView"), "alloc"), sel("initWithFrame:"), NSRect{})
send(v.clip, "setWantsLayer:", 1)
send(send(v.clip, "layer"), "setMasksToBounds:", 1)
send(v.clip, "setAutoresizingMask:", nsViewMinYMargin)
send(v.clip, "setHidden:", 1)
v.pane = msgInitRect(send(class("MyGoClipView"), "alloc"), sel("initWithFrame:"), NSRect{})
send(v.pane, "setWantsLayer:", 1)
send(send(v.pane, "layer"), "setMasksToBounds:", 1)
if o.BackgroundColor != nil && !o.Transparent {
v.clipBackground(*o.BackgroundColor)
}
send(v.pane, "addSubview:", uintptr(v.web))
send(v.clip, "addSubview:", uintptr(v.pane))
send(host.view, "addSubview:positioned:relativeTo:", uintptr(v.clip), nsWindowBelow, uintptr(s.view))
})
b.byDelegate[v.delegate] = v
b.byWebView[v.web] = v
host.webViews = append(host.webViews, v)
return v, nil
}
// EmbedView puts a view of a native module under the surface, which places
// it as it places web views.
func (s *surface) EmbedView(view uintptr) (platform.WebView, error) {
host := s.w
if host.closed {
return nil, errors.New("darwin: the window is closed")
}
// It has no page to tell of: its handler is its host's, which hears
// nothing from it.
v := &window{b: host.b, h: host.h, opts: &platform.WindowOptions{}, win: host.win, host: host, foreign: true, web: id(view)}
withPool(func() {
retain(v.web)
send(v.web, "removeFromSuperview")
send(v.web, "setAutoresizingMask:", 0)
v.clip = msgInitRect(send(class("MyGoClipView"), "alloc"), sel("initWithFrame:"), NSRect{})
send(v.clip, "setWantsLayer:", 1)
send(send(v.clip, "layer"), "setMasksToBounds:", 1)
send(v.clip, "setAutoresizingMask:", nsViewMinYMargin)
send(v.clip, "setHidden:", 1)
v.pane = msgInitRect(send(class("MyGoClipView"), "alloc"), sel("initWithFrame:"), NSRect{})
send(v.pane, "setWantsLayer:", 1)
send(send(v.pane, "layer"), "setMasksToBounds:", 1)
send(v.pane, "addSubview:", uintptr(v.web))
send(v.clip, "addSubview:", uintptr(v.pane))
send(host.view, "addSubview:positioned:relativeTo:", uintptr(v.clip), nsWindowBelow, uintptr(s.view))
})
host.webViews = append(host.webViews, v)
return v, nil
}
// nsWindowBelow is NSWindowBelow, for addSubview:positioned:relativeTo:.
const nsWindowBelow = ^uintptr(0)
// clipBackground fills the pane with c until the page paints, inside the
// page's corners.
func (w *window) clipBackground(c platform.Color) {
send(send(w.pane, "layer"), "setBackgroundColor:", uintptr(send(nsColor(c), "CGColor")))
}
// PlaceWebViews shows the window's web views where the content shows
// them, in its paint order under the surface, and hides the others.
func (s *surface) PlaceWebViews(views []platform.WebViewPlacement) {
host := s.w
if host.closed {
return
}
s.placed = append(s.placed[:0], views...)
height := msgRect(host.view, sel("bounds")).Size.Height
shown := make([]*window, 0, len(views))
withPool(func() {
for _, p := range views {
v, ok := p.WebView.(*window)
if !ok || v.host != host || v.closed {
continue
}
if v.foreign && send(v.web, "superview") != v.pane {
// A view of a native module that another window showed
// since: back to this one.
send(v.pane, "addSubview:", uintptr(v.web))
}
c, f := p.Clip, p.Frame
pw, ph := p.Size()
msgSetRect(v.clip, sel("setFrame:"), NSRect{Origin: NSPoint{c.X, height - c.Y - c.H}, Size: NSSize{c.W, c.H}})
// The clip view is flipped, and so is the pane, whose bounds
// are the page's size, scaled to its frame.
msgSetRect(v.pane, sel("setFrame:"), NSRect{Origin: NSPoint{f.X - c.X, f.Y - c.Y}, Size: NSSize{f.W, f.H}})
msgSetSize(v.pane, sel("setBoundsSize:"), NSSize{pw, ph})
msgSetRect(v.web, sel("setFrame:"), NSRect{Size: NSSize{pw, ph}})
v.roundPane(p.Radii, pw, ph)
// The placement's opacity fades the page itself, over what is
// behind the window too, as a flyout over a parent left live.
// The layer's own opacity is a 32-bit float, which a double's
// low half reads as none at all: the view's alpha takes a
// CGFloat, and fades what is inside it, the page with it.
msgSetFloat(v.clip, sel("setAlphaValue:"), p.Opacity)
if sendBool(v.clip, "isHidden") {
send(v.clip, "setHidden:", 0)
}
shown = append(shown, v)
}
for _, v := range host.webViews {
if !slices.Contains(shown, v) && !sendBool(v.clip, "isHidden") {
if v.hasKeyboard() {
// A hidden view keeps no keyboard: it goes back to the
// content.
send(host.win, "makeFirstResponder:", uintptr(s.view))
}
send(v.clip, "setHidden:", 1)
}
}
s.stackWebViews(shown)
if len(s.glassShown) > 0 {
s.stackGlass(s.glassShown, true)
}
})
}
var (
paneOnce sync.Once
msgPointToLayer func(obj id, sel objc.SEL, p NSPoint) NSPoint
cgPathCreate func() uintptr
cgPathMoveTo func(path, transform uintptr, x, y float64)
cgPathArcTo func(path, transform uintptr, x1, y1, x2, y2, radius float64)
cgPathClose func(path uintptr)
cgPathRelease func(path uintptr)
)
// roundPane cuts the pane of the web view w, its bounds width by height,
// to corners of radii, in its bounds' units, from the top-left clockwise,
// as continuous as the content's when they are the same.
func (w *window) roundPane(radii [4]float64, width, height float64) {
paneOnce.Do(func() {
purego.RegisterFunc(&msgPointToLayer, msgSendAddr)
purego.RegisterLibFunc(&cgPathCreate, libCG, "CGPathCreateMutable")
purego.RegisterLibFunc(&cgPathMoveTo, libCG, "CGPathMoveToPoint")
purego.RegisterLibFunc(&cgPathArcTo, libCG, "CGPathAddArcToPoint")
purego.RegisterLibFunc(&cgPathClose, libCG, "CGPathCloseSubpath")
purego.RegisterLibFunc(&cgPathRelease, libCG, "CGPathRelease")
})
layer := send(w.pane, "layer")
if radii == [4]float64{} {
msgSetFloat(layer, sel("setCornerRadius:"), 0)
w.unmask(layer)
return
}
// The pane's corners in its layer, which AppKit scales and flips as
// it does: by the layer's own transform, or its sublayers'.
toLayer := func(x, y float64) NSPoint { return msgPointToLayer(w.pane, sel("convertPointToLayer:"), NSPoint{x, y}) }
corners := [4]NSPoint{toLayer(0, 0), toLayer(width, 0), toLayer(width, height), toLayer(0, height)}
k := math.Abs(corners[1].X-corners[0].X) / width // the layer's units per the bounds'
same, r := true, 0.0
for _, v := range radii {
if v > 0 && r > 0 && v != r {
same = false
}
r = max(r, v)
}
if same {
// kCALayerMinXMinYCorner and the others, for the corners whose
// radius is not 0, by where they are in the layer.
var mask uint
for i, v := range radii {
if v <= 0 {
continue
}
p, o := corners[i], corners[(i+2)%4]
bit := uint(1)
if p.X > o.X {
bit <<= 1
}
if p.Y > o.Y {
bit <<= 2
}
mask |= bit
}
w.unmask(layer)
msgSetFloat(layer, sel("setCornerRadius:"), r*k)
send(layer, "setCornerCurve:", uintptr(nsString("continuous")))
send(layer, "setMaskedCorners:", uintptr(mask))
return
}
// Corners of different radii, circular: a mask of their path, at the
// layer's bounds, which may not start at 0, 0.
msgSetFloat(layer, sel("setCornerRadius:"), 0)
b := msgRect(layer, sel("bounds"))
for i := range corners {
corners[i].X -= b.Origin.X
corners[i].Y -= b.Origin.Y
}
path := cgPathCreate()
mid := func(a, b NSPoint) NSPoint { return NSPoint{(a.X + b.X) / 2, (a.Y + b.Y) / 2} }
start := mid(corners[3], corners[0])
cgPathMoveTo(path, 0, start.X, start.Y)
for i := range 4 {
p, next := corners[i], mid(corners[i], corners[(i+1)%4])
cgPathArcTo(path, 0, p.X, p.Y, next.X, next.Y, radii[i]*k)
}
cgPathClose(path)
send(class("CATransaction"), "begin")
send(class("CATransaction"), "setDisableActions:", 1)
if w.mask == 0 {
w.mask = send(send(class("CAShapeLayer"), "alloc"), "init")
send(layer, "setMask:", uintptr(w.mask))
}
msgSetRect(w.mask, sel("setFrame:"), b)
send(w.mask, "setPath:", path)
send(class("CATransaction"), "commit")
cgPathRelease(path)
}
// unmask takes away the mask of the pane's layer.
func (w *window) unmask(layer id) {
if w.mask != 0 {
send(layer, "setMask:", 0)
release(w.mask)
w.mask = 0
}
}
// stackWebViews puts the clip views of the web views shown in the order
// the content painted them, under the surface, unless they are.
func (s *surface) stackWebViews(shown []*window) {
if len(shown) < 2 {
return
}
subviews := send(s.w.view, "subviews")
n := sendInt(subviews, "count")
at := 0
for i := range n {
if at < len(shown) && send(subviews, "objectAtIndex:", uintptr(i)) == shown[at].clip {
at++
}
}
if at == len(shown) {
return
}
// Moving a view out of its superview takes the keyboard from it: the
// first responder goes back to it.
first := send(s.w.win, "firstResponder")
for _, v := range shown {
retain(v.clip)
send(v.clip, "removeFromSuperview")
send(s.w.view, "addSubview:positioned:relativeTo:", uintptr(v.clip), nsWindowBelow, uintptr(s.view))
release(v.clip)
}
if first != 0 && first != send(s.w.win, "firstResponder") {
send(s.w.win, "makeFirstResponder:", uintptr(first))
}
}
// webViewAt returns the web view that takes the pointer at x, y in the
// surface: the last placed, as the content painted it over the others,
// whose placement takes it.
func (s *surface) webViewAt(x, y float64) *window {
for i := len(s.placed) - 1; i >= 0; i-- {
if p := &s.placed[i]; p.At(x, y) {
if v, ok := p.WebView.(*window); ok && !v.closed {
return v
}
}
}
return nil
}
// covered reports whether the content painted over the web view w where
// the mouse event ev happened, or does not show it there.
func (w *window) covered(ev id) bool {
s := w.host.surface
if s == nil {
return false
}
x, y := s.location(ev)
return s.webViewAt(x, y) != w
}
// top returns the window that shows w: its host for a web view.
func (w *window) top() *window {
if w.host != nil {
return w.host
}
return w
}
// hasKeyboard reports whether the web view, or a view in it, is the first
// responder of its window.
func (w *window) hasKeyboard() bool {
r := send(w.win, "firstResponder")
return r != 0 && sendBool(r, "isKindOfClass:", uintptr(class("NSView"))) &&
sendBool(r, "isDescendantOf:", uintptr(w.web))
}
// pressed tells the content of the window that a button went down on the
// web view w, which takes the press.
func (w *window) pressed(ev id, button int) {
if s := w.host.surface; s != nil && !w.host.closed {
x, y := s.location(ev)
s.send(platform.SurfaceEvent{Kind: platform.WebViewPress, X: x, Y: y, Button: button, Mods: eventMods(ev)})
}
}
// TabInto gives the web view the keyboard as the window's key view loop
// does, which tells WebKit to focus the page's first element, or its last
// going back: the web view follows the surface in the loop, or precedes
// it.
func (w *window) TabInto(back bool) {
s := w.host.surface
if w.closed || s == nil {
return
}
withPool(func() {
if back {
send(w.web, "setNextKeyView:", uintptr(s.view))
send(w.win, "selectKeyViewPrecedingView:", uintptr(s.view))
} else {
send(s.view, "setNextKeyView:", uintptr(w.web))
send(w.win, "selectKeyViewFollowingView:", uintptr(s.view))
}
})
}
// tabOut gives the content the keyboard back as Tab leaves the page of the
// web view w past its last element, or Shift+Tab past its first.
func (w *window) tabOut(back bool) {
s := w.host.surface
if s == nil || w.host.closed {
return
}
send(w.win, "makeFirstResponder:", uintptr(s.view))
ev := platform.SurfaceEvent{Kind: platform.WebViewTabOut, Key: platform.KeyTab, WebView: w}
if back {
ev.Mods = platform.ModShift
}
s.send(ev)
}
// webViewOf returns the web view that is view or holds it.
func webViewOf(view id) *window {
for v := view; v != 0; v = send(v, "superview") {
if w := theBackend.byWebView[v]; w != nil {
return w
}
}
return nil
}
// closeWebView closes a web view: by Close, or as its window closes.
func (w *window) closeWebView() {
if w.closed {
return
}
w.closed = true
b := w.b
withPool(func() {
if w.hasKeyboard() && w.host.surface != nil {
send(w.win, "makeFirstResponder:", uintptr(w.host.surface.view))
}
if w.foreign {
send(w.web, "removeFromSuperview")
send(w.clip, "removeFromSuperview")
release(w.web)
release(w.mask)
release(w.pane)
release(w.clip)
return
}
w.stopObserving()
send(w.ucc, "removeScriptMessageHandlerForName:", uintptr(nsString("mygo")))
if w.opts.PictureInPicture {
send(w.ucc, "removeScriptMessageHandlerForName:", uintptr(nsString(pipHandler)))
}
send(w.ucc, "removeAllUserScripts")
send(w.web, "stopLoading")
send(w.web, "setNavigationDelegate:", 0)
send(w.web, "setUIDelegate:", 0)
send(w.clip, "removeFromSuperview")
delete(b.byDelegate, w.delegate)
delete(b.byWebView, w.web)
release(w.lastMouseDown)
w.lastMouseDown = 0
release(w.ucc)
release(w.web)
release(w.mask)
release(w.pane)
release(w.clip)
// WebKit may still hold the delegate as the page goes.
autorelease(w.delegate)
})
h := w.host
h.webViews = slices.DeleteFunc(h.webViews, func(v *window) bool { return v == w })
if s := h.surface; s != nil {
s.placed = slices.DeleteFunc(s.placed, func(p platform.WebViewPlacement) bool { return p.WebView == platform.WebView(w) })
}
}
// closeWebViews closes the web views of a window that closes.
func (w *window) closeWebViews() {
for len(w.webViews) > 0 {
w.webViews[len(w.webViews)-1].closeWebView()
}
}
var (
exitOnce sync.Once
msgExitEvent func(cls id, sel objc.SEL, typ uint, loc NSPoint, flags uint, ts float64, wn int, ctx id, en, tn int, data uintptr) id
)
// leave tells the page of the web view w that the pointer left it, as it
// went onto what the content painted over the page: an exit outside the
// view, which WebKit takes as a move there, unhovering what was under the
// pointer.
func (w *window) leave(ev id) {
exitOnce.Do(func() { purego.RegisterFunc(&msgExitEvent, msgSendAddr) })
const typeMouseExited = 9 // NSEventTypeMouseExited
exit := msgExitEvent(class("NSEvent"), sel("enterExitEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:trackingNumber:userData:"),
typeMouseExited, NSPoint{X: -1e5, Y: -1e5}, 0, msgFloat(ev, sel("timestamp")), sendInt(w.win, "windowNumber"), 0, 0, 0, 0)
sendSuper(w.web, "MyGoWebView", sel("mouseExited:"), uintptr(exit))
}
// webViewMethods are the overrides of MyGoWebView for web views in a
// window of native UI: a press tells the content, which closes its
// popovers, and the mouse moving where the content painted over the page
// is the content's alone, which sets the cursor there; the page hears
// that it left.
func webViewMethods() []objc.MethodDef {
press := func(button int) func(id, objc.SEL, id) {
return func(self id, cmd objc.SEL, ev id) {
if w := theBackend.byWebView[self]; w != nil && w.host != nil {
w.pressed(ev, button)
}
sendSuper(self, "MyGoWebView", cmd, uintptr(ev))
}
}
moved := func(self id, cmd objc.SEL, ev id) {
if w := theBackend.byWebView[self]; w != nil && w.host != nil {
if w.covered(ev) {
if w.pointerIn {
w.pointerIn = false
w.leave(ev)
}
return
}
w.pointerIn = true
}
sendSuper(self, "MyGoWebView", cmd, uintptr(ev))
}
exited := func(self id, cmd objc.SEL, ev id) {
if w := theBackend.byWebView[self]; w != nil {
w.pointerIn = false
}
sendSuper(self, "MyGoWebView", cmd, uintptr(ev))
}
return []objc.MethodDef{
// The first click in a window that is not key is the page's, as it
// is native UI's (MyGoSurfaceView): WKWebView answers no, which
// spends the click on making the window key.
method("acceptsFirstMouse:", func(self id, _ objc.SEL, ev id) bool { return true }),
method("scrollWheel:", func(self id, cmd objc.SEL, ev id) {
w := theBackend.byWebView[self]
if w == nil || w.host == nil || w.host.surface == nil || w.opts == nil || !w.opts.ScrollToContainer {
sendSuper(self, "MyGoWebView", cmd, uintptr(ev))
return
}
scrollWheel(w.host.surface, ev)
}),
method("rightMouseDown:", press(1)),
method("otherMouseDown:", press(2)),
method("mouseMoved:", moved),
method("mouseEntered:", moved),
method("mouseExited:", exited),
method("cursorUpdate:", moved),
// The content resizes a web view as its window resizes, frame by
// frame: told of the window's live resize, WebKit would show the
// page's scrollers throughout it, at the page's last width.
method("viewWillStartLiveResize", func(self id, cmd objc.SEL) {
if w := theBackend.byWebView[self]; w == nil || w.host == nil {
sendSuper(self, "MyGoWebView", cmd)
}
}),
method("viewDidEndLiveResize", func(self id, cmd objc.SEL) {
if w := theBackend.byWebView[self]; w == nil || w.host == nil {
sendSuper(self, "MyGoWebView", cmd)
}
}),
method("accessibilityParent", func(self id, cmd objc.SEL) id {
if w := theBackend.byWebView[self]; w != nil && w.accessParent != 0 {
return w.accessParent
}
return sendSuper(self, "MyGoWebView", cmd)
}),
}
}
// unhandledKey gives the content a key that the page of the web view in
// the clip view clip left unhandled, and reports whether it did. WebKit
// sends such a key on up the responder chain, to the clip view: the
// surface, a sibling of the clip view, would never get it. Tab stays out
// of it, as WebKit moves the keyboard with it.
func unhandledKey(clip, ev id) bool {
w := clipWebView(clip)
if w == nil {
return false
}
k := eventKey(ev)
if k == platform.KeyTab {
return false
}
w.host.surface.send(platform.SurfaceEvent{Kind: platform.WebViewKey, Key: k, PhysicalKey: physicalKey(ev), Mods: eventMods(ev), Repeat: sendBool(ev, "isARepeat"), WebView: w})
return true
}
// unhandledCommand gives the content the key k of a command the page of
// the web view in the clip view clip left, and reports whether it did.
func unhandledCommand(clip id, k platform.Key) bool {
w := clipWebView(clip)
if w == nil {
return false
}
w.host.surface.send(platform.SurfaceEvent{Kind: platform.WebViewKey, Key: k, WebView: w})
return true
}
// clipWebView returns the web view in the clip view clip, or in the pane
// inside it, which is the web view's next responder, while its window
// shows native UI.
func clipWebView(clip id) *window {
for _, v := range theBackend.byWebView {
if v.clip == clip || v.pane == clip {
if v.host == nil || v.host.closed || v.host.surface == nil {
return nil
}
return v
}
}
return nil
}
func registerClipViewClass() {
classDef("MyGoClipView", "NSView", nil, []objc.MethodDef{
method("isFlipped", func(self id, _ objc.SEL) bool { return true }),
method("keyDown:", func(self id, cmd objc.SEL, ev id) {
if !unhandledKey(self, ev) {
sendSuper(self, "MyGoClipView", cmd, uintptr(ev))
}
}),
// An Escape (or Cmd+.) the page left comes as the command it stands
// for: WebKit sends the commands its web process does not know up
// the responder chain first, and resends the key only if no
// responder took the command, which a panel, as a flyout's, does.
// NSView has no cancelOperation: of its own: a command no web view
// takes goes on up the responder chain, as NSResponder's
// doCommandBySelector: sends it.
method("cancelOperation:", func(self id, cmd objc.SEL, sender id) {
if !unhandledCommand(self, platform.KeyEscape) {
if next := send(self, "nextResponder"); next != 0 {
send(next, "doCommandBySelector:", uintptr(cmd))
}
}
}),
// Assistive technology finds the page in the element of the
// content showing it, not beside the content.
method("accessibilityChildren", func(self id, _ objc.SEL) id { return nsArray() }),
})
}
+84
View File
@@ -0,0 +1,84 @@
//go:build darwin && !ios
package darwin
import (
"testing"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/platform"
)
type webViewScrollHandler struct {
platform.WindowHandler
events []platform.SurfaceEvent
}
func (h *webViewScrollHandler) SurfaceEvent(ev platform.SurfaceEvent) bool {
h.events = append(h.events, ev)
return true
}
func TestEmbeddedWebViewScrollReachesSurface(t *testing.T) {
load()
withPool(func() {
h := &webViewScrollHandler{}
view := msgInitRect(send(class("NSView"), "alloc"), sel("initWithFrame:"), NSRect{Size: NSSize{Width: 400, Height: 300}})
s := &surface{w: &window{h: h}, view: view}
w := &window{host: &window{h: h, surface: s}, opts: &platform.WindowOptions{ScrollToContainer: true}}
web := id(objc.GetClass("MyGoWebView"))
if web == 0 {
classDef("MyGoWebView", "NSView", nil, webViewMethods())
}
webView := msgInitRect(send(class("MyGoWebView"), "alloc"), sel("initWithFrame:"), NSRect{Size: NSSize{Width: 400, Height: 300}})
w.web = webView
if theBackend == nil {
theBackend = &Backend{byWebView: make(map[id]*window)}
}
theBackend.byWebView[webView] = w
defer delete(theBackend.byWebView, webView)
var create func(uintptr) uintptr
purego.RegisterLibFunc(&create, libCG, "CGEventCreate")
purego.RegisterLibFunc(&cgEventSetType, libCG, "CGEventSetType")
cg := create(0)
var setDouble func(uintptr, uint32, float64)
purego.RegisterLibFunc(&setDouble, libCG, "CGEventSetDoubleValueField")
cgEventSetType(cg, 22) // kCGEventScrollWheel
setDouble(cg, 11, -2) // kCGScrollWheelEventDeltaAxis1
setDouble(cg, 12, 1) // kCGScrollWheelEventDeltaAxis2
event := send(class("NSEvent"), "eventWithCGEvent:", cg)
if event == 0 || sendInt(event, "type") != 22 {
t.Fatal("could not construct a native scroll-wheel event")
}
send(webView, "scrollWheel:", uintptr(event))
if len(h.events) != 1 {
t.Fatalf("surface scroll events = %d, want 1", len(h.events))
}
got := h.events[0]
if got.Kind != platform.PointerScroll || got.DX != -40 || got.DY != 80 || got.Precise {
t.Fatalf("surface scroll = %+v, want line-scaled pointer deltas", got)
}
var createScroll func(uintptr, uint32, uint32, int32, int32) uintptr
purego.RegisterLibFunc(&createScroll, libCG, "CGEventCreateScrollWheelEvent")
cg = createScroll(0, 0, 2, 3, 0) // kCGScrollEventUnitPixel
event = send(class("NSEvent"), "eventWithCGEvent:", cg)
send(webView, "scrollWheel:", uintptr(event))
if len(h.events) != 2 {
t.Fatalf("surface trackpad events = %d, want 2", len(h.events))
}
got = h.events[1]
if got.Kind != platform.PointerScroll || got.DX != 0 || got.DY != -3 || !got.Precise {
t.Fatalf("surface trackpad scroll = %+v, want precise pointer deltas", got)
}
w.opts.ScrollToContainer = false
send(webView, "scrollWheel:", uintptr(event))
if len(h.events) != 2 {
t.Fatal("a page that scrolls itself lost its wheel to the native surface")
}
send(webView, "removeFromSuperview")
send(webView, "release")
send(view, "release")
})
}
File diff suppressed because it is too large. Load diff
+290
View File
@@ -0,0 +1,290 @@
//go:build darwin && !ios
package darwin
import (
"math"
"github.com/ebitengine/purego/objc"
)
// Drag regions move the window with a press (StartDrag): the press of a
// page's `--app-region: drag`, which the page tells a few milliseconds
// after the web view got it, or of native UI's DragWindow, which asks while
// the surface handles the press.
//
// The window server moves the window best (performWindowDragWithEvent:):
// it takes the window to other Spaces and tiles it. But it may not begin
// when the pointer has moved since the press by the time it is asked: AppKit
// logs "Window move completed without beginning" and the window stays where
// it was, which a quick press and drag hits now and then (issue #528). So
// MyGo watches the press. When the pointer has not moved yet, it asks the
// window server; when it has, or when the press's drags still reach the app
// past a few points, a few drags after the ask, and the window server has
// not begun, MyGo moves the window itself, keeping the point pressed under
// the pointer, as the window server would. Either way the press's drags are
// the window's, not the content's.
//
// The window server tells the window as it begins (windowWillMove:), within
// a drag or two of being asked; MyGo's own moves (setFrameOrigin:) never
// do. The window's frame says so late: AppKit learns where the window is
// about every tenth of a second while the window server moves it. Should
// MyGo take a frame that has not moved for a window server that did not
// begin, both would move the window, the window server to where the pointer
// is and MyGo to where it was an event before, and the window shakes. So
// MyGo waits for a few drags before taking over, however far the first
// goes, and leaves the window alone as soon as the window server says it
// begins, even once MyGo has taken over: the window not being where MyGo put
// it tells MyGo only late, and not at all for a slow drag, whose every move
// puts the frame back where MyGo wants it.
// dragPhase is where a press stands in moving its window.
type dragPhase uint8
const (
dragIdle dragPhase = iota // no press, or one that did not ask
dragPressed // the button is down: a drag may be asked
dragNative // the window server was asked to move it
dragManual // MyGo moves it with the pointer
dragServer // the window server moves it
)
func (p dragPhase) String() string {
return [...]string{"idle", "pressed", "native", "manual", "server"}[p]
}
const (
// dragStill is how far, in points, the pointer may have gone when
// the drag is asked, for the window server to be asked to move the
// window: a hand on a touchpad trembles.
dragStill = 1
// dragSlop is how far the pointer may go, with the press's drags
// still reaching the app and the window not moving, before MyGo
// moves the window itself: the window server did not begin.
dragSlop = 3
// dragWait is how many drags the window server is given after the
// ask to say it begins, before MyGo moves the window itself: a
// quick hand is past dragSlop with the first.
dragWait = 3
// dragAway is how far, in points, the window may be from where MyGo
// put it, which AppKit rounds, before MyGo takes it that the window
// server moves it.
dragAway = 2
)
// windowDrag follows the press of the left button, for StartDrag. Points
// are in the display space of Core Graphics (top-left origin of the
// primary display, y down), where events keep their place when the window
// moves; window origins are AppKit's (bottom-left, y up).
type windowDrag struct {
phase dragPhase
win id // the window pressed
press NSPoint // where the press was
at NSPoint // where the pointer was last, with the button down
// origin is the window's frame origin when the drag was asked.
origin NSPoint
// put is the origin MyGo last moved the window to, while manual.
put NSPoint
// drags counts the drags since the window server was asked.
drags int
}
// down notes a press of the left button in win at the point at.
func (d *windowDrag) down(win id, at NSPoint) {
*d = windowDrag{phase: dragPressed, win: win, press: at, at: at}
}
// willMove notes that the window server begins to move win, which it
// does only when asked, though it may be after MyGo took over.
func (d *windowDrag) willMove(win id) {
if (d.phase == dragNative || d.phase == dragManual) && d.win == win {
d.phase = dragServer
}
}
// up notes the release of the button, or a press elsewhere.
func (d *windowDrag) up() { *d = windowDrag{} }
// dragStart is what StartDrag does.
type dragStart uint8
const (
startNone dragStart = iota // nothing: no press of win is down
startNative // ask the window server
startManual // move the window to target, and with the pointer
)
// start asks to move win, whose frame origin is origin, with the press.
// A press asks once.
func (d *windowDrag) start(win id, origin NSPoint) dragStart {
if d.phase != dragPressed || d.win != win {
return startNone
}
d.origin = origin
if distance(d.at, d.press) >= dragStill {
d.phase = dragManual
return startManual
}
d.phase = dragNative
return startNative
}
// dragged notes the pointer at the point at with the button down, the
// pressed window's frame origin being origin. It reports whether the event
// is the window's move rather than the content's, and whether to move the
// window (to target).
func (d *windowDrag) dragged(at, origin NSPoint) (eat, move bool) {
switch d.phase {
case dragPressed:
d.at = at
case dragNative:
d.at = at
if origin != d.origin {
d.phase = dragServer
return true, false
}
d.drags++
if distance(at, d.press) < dragSlop || d.drags < dragWait {
// The pointer has hardly moved yet, or the window
// server may still say it begins.
return true, false
}
d.phase = dragManual
return true, true
case dragManual:
d.at = at
if distance(origin, d.put) > dragAway {
// The window server began after all.
d.phase = dragServer
return true, false
}
return true, true
case dragServer:
d.at = at
return true, false
}
return false, false
}
// placed notes that MyGo moved the window to origin.
func (d *windowDrag) placed(origin NSPoint) { d.put = origin }
// target is the window's origin that keeps the point pressed under the
// pointer.
func (d *windowDrag) target() NSPoint {
return NSPoint{d.origin.X + d.at.X - d.press.X, d.origin.Y - (d.at.Y - d.press.Y)}
}
func distance(a, b NSPoint) float64 { return math.Hypot(a.X-b.X, a.Y-b.Y) }
// belowMenuBar returns the origin of a window as tall as height, moved down
// so that its top edge stays at or below top, as AppKit keeps a title bar
// out of the menu bar.
func belowMenuBar(origin NSPoint, height, top float64) NSPoint {
if origin.Y+height > top {
origin.Y = top - height
}
return origin
}
// theDrag is the press that may move a window. Main thread only.
var theDrag windowDrag
// dragMonitor sees the drags and the release of a press before the
// window does. It is made once, with the first press of a web view or a
// surface.
var dragMonitor id
// pressedLeft notes a press of the left button in w's web view or
// surface, which a drag region may ask to move w with.
func (w *window) pressedLeft(ev id) {
watchWindowDrags()
release(w.lastMouseDown)
w.lastMouseDown = retain(ev)
theDrag.down(w.win, eventPoint(ev))
}
func watchWindowDrags() {
if dragMonitor != 0 {
return
}
const mask = 1<<1 | 1<<2 | 1<<6 // left mouse down, up and dragged
blk := newBlock(func(_ objc.Block, ev id) id {
if theDrag.phase == dragIdle {
return ev
}
switch sendInt(ev, "type") {
case 6: // NSEventTypeLeftMouseDragged
if send(ev, "window") != theDrag.win {
return ev
}
eat, move := theDrag.dragged(eventPoint(ev), msgRect(theDrag.win, sel("frame")).Origin)
if move {
moveDraggedWindow()
}
if eat {
return 0
}
default:
// A release, or a press the window has yet to see, which
// notes itself if it may drag.
theDrag.up()
}
return ev
})
dragMonitor = retain(send(class("NSEvent"), "addLocalMonitorForEventsMatchingMask:handler:", mask, uintptr(blk)))
}
// eventPoint returns where a mouse event happened, in the display space
// of Core Graphics.
func eventPoint(ev id) NSPoint {
if cg := send(ev, "CGEvent"); cg != 0 {
return cgEventGetLocation(uintptr(cg))
}
p := msgPoint(class("NSEvent"), sel("mouseLocation"))
return NSPoint{p.X, primaryScreenHeight() - p.Y}
}
// moveDraggedWindow moves the window of theDrag to its target, below the
// menu bar of the screen with the pointer.
func moveDraggedWindow() {
d := &theDrag
origin := d.target()
screens := arrayItems(send(class("NSScreen"), "screens"))
if len(screens) > 0 {
primary := msgRect(screens[0], sel("frame"))
p := NSPoint{d.at.X, primary.Origin.Y + primary.Size.Height - d.at.Y}
for _, s := range screens {
if f := msgRect(s, sel("frame")); p.X >= f.Origin.X && p.X < f.Origin.X+f.Size.Width && p.Y >= f.Origin.Y && p.Y < f.Origin.Y+f.Size.Height {
v := msgRect(s, sel("visibleFrame"))
origin = belowMenuBar(origin, msgRect(d.win, sel("frame")).Size.Height, v.Origin.Y+v.Size.Height)
break
}
}
}
d.placed(origin)
msgSetPoint(d.win, sel("setFrameOrigin:"), origin)
}
// StartDrag moves the window with the press of a drag region, while the
// button is down.
func (w *window) StartDrag() {
if w.closed || w.lastMouseDown == 0 || !sendBool(w.win, "isMovable") || w.hasStyle(styleFullScreen) {
return
}
switch theDrag.start(w.win, msgRect(w.win, sel("frame")).Origin) {
case startNative:
send(w.win, "performWindowDragWithEvent:", uintptr(w.lastMouseDown))
case startManual:
moveDraggedWindow()
}
}
// forgetDrag forgets the press of a window that closes.
func (w *window) forgetDrag() {
if theDrag.win == w.win {
theDrag.up()
}
release(w.lastMouseDown)
w.lastMouseDown = 0
}
+245
View File
@@ -0,0 +1,245 @@
//go:build darwin && !ios
package darwin
import "testing"
// A press that has not moved when its drag is asked goes to the window
// server, which moves the window: the drags that still reach the app are
// the window's, and MyGo leaves the window alone.
func TestWindowDragNative(t *testing.T) {
var d windowDrag
d.down(1, NSPoint{100, 50})
if got := d.start(1, NSPoint{10, 500}); got != startNative {
t.Fatalf("start = %v, want the window server's move", got)
}
// The window server moved the window by the time the drag came.
if eat, move := d.dragged(NSPoint{140, 70}, NSPoint{50, 480}); !eat || move {
t.Errorf("dragged while the window server moves the window = eat %v, move %v; want eaten, no move", eat, move)
}
if d.phase != dragServer {
t.Errorf("phase = %v, want the window server's", d.phase)
}
// Even back where it was, the window stays the window server's.
if eat, move := d.dragged(NSPoint{108, 50}, NSPoint{10, 500}); !eat || move {
t.Errorf("dragged back to the start = eat %v, move %v; want eaten, no move", eat, move)
}
d.up()
if d.phase != dragIdle {
t.Errorf("phase after the release = %v, want idle", d.phase)
}
}
// Issue #528: a quick press and drag has moved by the time the page asks
// for the drag. MyGo moves the window itself, at once to where the pointer
// is, and then with it.
func TestWindowDragMovedBeforeAsked(t *testing.T) {
var d windowDrag
d.down(1, NSPoint{100, 50})
for _, p := range []NSPoint{{104, 52}, {120, 60}} {
if eat, move := d.dragged(p, NSPoint{10, 500}); eat || move {
t.Fatalf("a drag before the drag is asked = eat %v, move %v; want the content's", eat, move)
}
}
if got := d.start(1, NSPoint{10, 500}); got != startManual {
t.Fatalf("start = %v, want MyGo's move", got)
}
// Right 20, down 10 in Core Graphics' space: down 10 in AppKit's.
if got, want := d.target(), (NSPoint{30, 490}); got != want {
t.Errorf("target = %v, want %v", got, want)
}
d.placed(d.target())
eat, move := d.dragged(NSPoint{150, 40}, NSPoint{30, 490})
if !eat || !move {
t.Errorf("dragged = eat %v, move %v; want eaten and moved", eat, move)
}
if got, want := d.target(), (NSPoint{60, 510}); got != want {
t.Errorf("target = %v, want %v", got, want)
}
}
// The window server begins and says so before its frame moves: the frame
// AppKit gives lags a tenth of a second, and MyGo took the window too, which
// shook as both moved it. The press's drags stay the window server's.
func TestWindowDragNativeWillMove(t *testing.T) {
var d windowDrag
origin := NSPoint{10, 500}
d.down(1, NSPoint{100, 50})
d.start(1, origin)
d.willMove(2)
if d.phase != dragNative {
t.Fatalf("phase after another window's move = %v, want native", d.phase)
}
d.willMove(1)
for _, p := range []NSPoint{{108, 50}, {160, 70}} {
if eat, move := d.dragged(p, origin); !eat || move {
t.Errorf("dragged %v with the window's frame still = eat %v, move %v; want eaten, no move", p, eat, move)
}
}
if d.phase != dragServer {
t.Errorf("phase = %v, want the window server's", d.phase)
}
}
// The window server did not begin: the press's drags still reach the app
// and the window stays. Past the slop, once the window server has had a few
// drags to say it begins, MyGo moves the window itself.
func TestWindowDragNativeDidNotBegin(t *testing.T) {
var d windowDrag
origin := NSPoint{10, 500}
d.down(1, NSPoint{100, 50})
if got := d.start(1, origin); got != startNative {
t.Fatalf("start = %v, want the window server's move", got)
}
if eat, move := d.dragged(NSPoint{101, 51}, origin); !eat || move {
t.Errorf("dragged within the slop = eat %v, move %v; want eaten, no move", eat, move)
}
if eat, move := d.dragged(NSPoint{104, 50}, origin); !eat || move {
t.Errorf("dragged past the slop at once = eat %v, move %v; want eaten, no move", eat, move)
}
if eat, move := d.dragged(NSPoint{108, 50}, origin); !eat || !move {
t.Errorf("dragged past the slop = eat %v, move %v; want eaten and moved", eat, move)
}
if d.phase != dragManual {
t.Errorf("phase = %v, want manual", d.phase)
}
if got, want := d.target(), (NSPoint{18, 500}); got != want {
t.Errorf("target = %v, want %v", got, want)
}
}
// A quick hand is past the slop with the first drag after the ask, before
// the window server says it begins: MyGo took the window too, and the
// window shook as both moved it. MyGo waits, and the window server's
// windowWillMove: leaves the press to it.
func TestWindowDragNativeQuickBeforeWillMove(t *testing.T) {
var d windowDrag
origin := NSPoint{10, 500}
d.down(1, NSPoint{100, 50})
d.start(1, origin)
if eat, move := d.dragged(NSPoint{112, 54}, origin); !eat || move {
t.Errorf("first drag past the slop = eat %v, move %v; want eaten, no move", eat, move)
}
d.willMove(1)
for _, p := range []NSPoint{{124, 58}, {136, 62}, {148, 66}} {
if eat, move := d.dragged(p, origin); !eat || move {
t.Errorf("dragged %v after the window server began = eat %v, move %v; want eaten, no move", p, eat, move)
}
}
}
// The window server says it begins after MyGo took over, and the drag goes
// on slowly: the window was where MyGo put it within the rounding at every
// drag, so MyGo kept moving it beside the window server, which shook it.
// windowWillMove: leaves the press to the window server.
func TestWindowDragManualWillMove(t *testing.T) {
var d windowDrag
origin := NSPoint{10, 500}
d.down(1, NSPoint{100, 50})
d.start(1, origin)
for _, p := range []NSPoint{{102, 50}, {104, 50}, {106, 50}} {
d.dragged(p, origin)
}
if d.phase != dragManual {
t.Fatalf("phase = %v, want manual", d.phase)
}
d.placed(d.target())
d.willMove(2)
if d.phase != dragManual {
t.Fatalf("phase after another window's move = %v, want manual", d.phase)
}
d.willMove(1)
// A point a drag: the window server's frame is never 2 points from MyGo's.
for i, p := range []NSPoint{{107, 50}, {108, 50}, {109, 50}} {
if eat, move := d.dragged(p, NSPoint{16 + float64(i), 500}); !eat || move {
t.Errorf("dragged %v after the window server began = eat %v, move %v; want eaten, no move", p, eat, move)
}
}
if d.phase != dragServer {
t.Errorf("phase = %v, want the window server's", d.phase)
}
}
// The window server begins after MyGo took over: both would move the
// window, which shakes. Once the window is not where MyGo put it, MyGo
// leaves it to the window server.
func TestWindowDragNativeBeganLate(t *testing.T) {
var d windowDrag
origin := NSPoint{10, 500}
d.down(1, NSPoint{100, 50})
d.start(1, origin)
d.dragged(NSPoint{102, 50}, origin)
d.dragged(NSPoint{104, 50}, origin)
if _, move := d.dragged(NSPoint{108, 50}, origin); !move {
t.Fatal("dragged past the slop did not move the window")
}
d.placed(d.target())
if _, move := d.dragged(NSPoint{120.4, 50}, NSPoint{18, 500}); !move {
t.Fatal("dragged with the window where MyGo put it did not move the window")
}
d.placed(d.target())
// AppKit rounds the origin MyGo put.
if eat, move := d.dragged(NSPoint{130, 51}, NSPoint{30, 500}); !eat || !move {
t.Errorf("dragged with the window's origin rounded = eat %v, move %v; want eaten and moved", eat, move)
}
d.placed(d.target())
// The window server moved it to the pointer.
for _, p := range []NSPoint{{160, 54}, {170, 55}} {
if eat, move := d.dragged(p, NSPoint{70, 496}); !eat || move {
t.Errorf("dragged with the window server moving the window = eat %v, move %v; want eaten, no move", eat, move)
}
}
if d.phase != dragServer {
t.Errorf("phase = %v, want the window server's", d.phase)
}
}
// A drag is asked once a press, only for the window pressed, and only
// while the button is down.
func TestWindowDragAsked(t *testing.T) {
var d windowDrag
if got := d.start(1, NSPoint{}); got != startNone {
t.Errorf("start without a press = %v, want none", got)
}
d.down(1, NSPoint{100, 50})
if got := d.start(2, NSPoint{}); got != startNone {
t.Errorf("start for another window = %v, want none", got)
}
if got := d.start(1, NSPoint{}); got != startNative {
t.Errorf("start = %v, want the window server's move", got)
}
if got := d.start(1, NSPoint{}); got != startNone {
t.Errorf("start again = %v, want none", got)
}
d.down(1, NSPoint{100, 50})
d.up()
if got := d.start(1, NSPoint{}); got != startNone {
t.Errorf("start after the release = %v, want none", got)
}
// Drags of no press are the content's.
if eat, move := d.dragged(NSPoint{200, 200}, NSPoint{}); eat || move {
t.Errorf("dragged without a press = eat %v, move %v; want the content's", eat, move)
}
// A hand on a touchpad trembles: still enough for the window server.
d.down(1, NSPoint{100, 50})
d.dragged(NSPoint{100.5, 50.25}, NSPoint{})
if got := d.start(1, NSPoint{}); got != startNative {
t.Errorf("start after a tremble = %v, want the window server's move", got)
}
}
func TestBelowMenuBar(t *testing.T) {
for _, c := range []struct {
origin NSPoint
height float64
want NSPoint
}{
{NSPoint{10, 300}, 400, NSPoint{10, 300}}, // top at 700
{NSPoint{10, 500}, 400, NSPoint{10, 475}}, // top at 900, past 875
{NSPoint{-40, 475}, 400, NSPoint{-40, 475}},
} {
if got := belowMenuBar(c.origin, c.height, 875); got != c.want {
t.Errorf("belowMenuBar(%v, %v, 875) = %v, want %v", c.origin, c.height, got, c.want)
}
}
}
+252
View File
@@ -0,0 +1,252 @@
package diff
// compact slides the groups of changed lines of one side (r, its lines
// interned as ids and as text) up and down where the same lines frame
// them, as git's xdl_change_compact: groups merge when they meet, line
// up with a group of the other side (ro) where they can, and otherwise
// take the place the indent heuristic scores best.
func compact(r, ro []bool, ids []int32, lines []string) {
g, gOther := groupInit(r), groupInit(ro)
for {
if g.end != g.start {
var size, earliestEnd int
endMatchingOther := -1
for {
size = g.end - g.start
endMatchingOther = -1
for g.slideUp(r, ids) {
gOther.previous(ro)
}
earliestEnd = g.end
if gOther.end > gOther.start {
endMatchingOther = g.end
}
for g.slideDown(r, ids) {
gOther.next(ro)
if gOther.end > gOther.start {
endMatchingOther = g.end
}
}
if size == g.end-g.start {
break
}
}
switch {
case g.end == earliestEnd:
// It could not move.
case endMatchingOther != -1:
// Back to the last place matching a group of the other side.
for gOther.end == gOther.start {
if !g.slideUp(r, ids) || !gOther.previous(ro) {
break
}
}
default:
shift := max(earliestEnd, g.end-size-1, g.end-maxSliding)
best := -1
var bestScore score
for ; shift <= g.end; shift++ {
var s score
s.add(measure(lines, shift))
s.add(measure(lines, shift-size))
if best == -1 || s.cmp(bestScore) <= 0 {
bestScore, best = s, shift
}
}
for g.end > best {
if !g.slideUp(r, ids) || !gOther.previous(ro) {
break
}
}
}
}
if !g.next(r) || !gOther.next(ro) {
return
}
}
}
// group is a run of changed lines, maybe empty, between unchanged ones.
type group struct{ start, end int }
func groupInit(r []bool) group {
g := group{}
for g.end < len(r) && r[g.end] {
g.end++
}
return g
}
func (g *group) next(r []bool) bool {
if g.end >= len(r) {
return false
}
g.start = g.end + 1
for g.end = g.start; g.end < len(r) && r[g.end]; g.end++ {
}
return true
}
func (g *group) previous(r []bool) bool {
if g.start <= 0 {
return false
}
g.end = g.start - 1
for g.start = g.end; g.start > 0 && r[g.start-1]; g.start-- {
}
return true
}
func (g *group) slideDown(r []bool, ids []int32) bool {
if g.start < g.end && g.end < len(r) && ids[g.start] == ids[g.end] {
r[g.start] = false
g.start++
r[g.end] = true
g.end++
for g.end < len(r) && r[g.end] {
g.end++
}
return true
}
return false
}
func (g *group) slideUp(r []bool, ids []int32) bool {
if g.start < g.end && g.start > 0 && ids[g.start-1] == ids[g.end-1] {
g.start--
r[g.start] = true
g.end--
r[g.end] = false
for g.start > 0 && r[g.start-1] {
g.start--
}
return true
}
return false
}
// The weights of git's indent heuristic (xdiffi.c), tuned on a corpus
// of real changes.
const (
maxIndent = 200
maxBlanks = 20
startOfFilePenalty = 1
endOfFilePenalty = 21
totalBlankWeight = -30
postBlankWeight = 6
relativeIndentPenalty = -4
relativeIndentWithBlankPenalty = 10
relativeOutdentPenalty = 24
relativeOutdentWithBlank = 17
relativeDedentPenalty = 23
relativeDedentWithBlank = 17
indentWeight = 60
maxSliding = 100
)
// indent is how far a line is indented, tabs to multiples of 8, or -1
// for a blank line.
func indent(s string) int {
n := 0
for i := 0; i < len(s); i++ {
switch s[i] {
case ' ':
n++
case '\t':
n += 8 - n%8
case '\r', '\n', '\f', '\v':
default:
return n
}
if n >= maxIndent {
return maxIndent
}
}
return -1
}
type split struct {
endOfFile bool
indent int
preBlank, preIndent int
postBlank, postIndent int
}
func measure(lines []string, at int) split {
var m split
if at >= len(lines) {
m.endOfFile, m.indent = true, -1
} else {
m.indent = indent(lines[at])
}
m.preIndent = -1
for i := at - 1; i >= 0; i-- {
if m.preIndent = indent(lines[i]); m.preIndent != -1 {
break
}
if m.preBlank++; m.preBlank == maxBlanks {
m.preIndent = 0
break
}
}
m.postIndent = -1
for i := at + 1; i < len(lines); i++ {
if m.postIndent = indent(lines[i]); m.postIndent != -1 {
break
}
if m.postBlank++; m.postBlank == maxBlanks {
m.postIndent = 0
break
}
}
return m
}
type score struct{ effectiveIndent, penalty int }
func (s *score) add(m split) {
if m.preIndent == -1 && m.preBlank == 0 {
s.penalty += startOfFilePenalty
}
if m.endOfFile {
s.penalty += endOfFilePenalty
}
postBlank := 0
if m.indent == -1 {
postBlank = 1 + m.postBlank
}
totalBlank := m.preBlank + postBlank
s.penalty += totalBlankWeight*totalBlank + postBlankWeight*postBlank
in := m.indent
if in == -1 {
in = m.postIndent
}
blanks := totalBlank != 0
s.effectiveIndent += in
switch {
case in == -1, m.preIndent == -1, in == m.preIndent:
case in > m.preIndent:
s.penalty += pick(blanks, relativeIndentWithBlankPenalty, relativeIndentPenalty)
case m.postIndent != -1 && m.postIndent > in:
s.penalty += pick(blanks, relativeOutdentWithBlank, relativeOutdentPenalty)
default:
s.penalty += pick(blanks, relativeDedentWithBlank, relativeDedentPenalty)
}
}
func pick(c bool, a, b int) int {
if c {
return a
}
return b
}
func (s score) cmp(o score) int {
c := 0
if s.effectiveIndent > o.effectiveIndent {
c = 1
} else if s.effectiveIndent < o.effectiveIndent {
c = -1
}
return indentWeight*c + s.penalty - o.penalty
}
+119
View File
@@ -0,0 +1,119 @@
// Package diff compares sequences: the lines of two texts, or the words
// of two lines. It finds the changes with the histogram algorithm of git
// (xhistogram.c), which anchors on lines that occur rarely and so keeps
// the matches people expect in source code, falling back to Myers's O(ND)
// algorithm, with xdiff's cost limit, where every line repeats too often.
// Groups of changed lines are then slid to start and end where blank
// lines and indentation make them read as whole blocks, with git's indent
// heuristic.
package diff
// Hunk is a change: the elements A0 to A1 of the old sequence replaced by
// B0 to B1 of the new one. A0 == A1 is an insertion before A0, B0 == B1 a
// deletion.
type Hunk struct{ A0, A1, B0, B1 int }
// Ints compares two sequences of interned elements, equal elements having
// equal values, and returns the hunks turning a into b, in order.
func Ints(a, b []int32) []Hunk {
d := differ{a: a, b: b}
d.histogram(0, len(a), 0, len(b), 0)
return d.hunks()
}
// Lines compares the lines of two texts and returns the hunks of lines
// turning a into b, slid to read as blocks of code.
func Lines(a, b []string) []Hunk {
ia, ib := Intern(a, b)
d := differ{a: ia, b: ib}
d.histogram(0, len(ia), 0, len(ib), 0)
if d.da == nil {
return nil
}
compact(d.da, d.db, ia, a)
compact(d.db, d.da, ib, b)
return d.hunks()
}
// Intern numbers the distinct strings of a and b, equal strings sharing a
// number.
func Intern(a, b []string) ([]int32, []int32) {
ids := make(map[string]int32, len(a)+len(b))
conv := func(s []string) []int32 {
out := make([]int32, len(s))
for i, v := range s {
id, ok := ids[v]
if !ok {
id = int32(len(ids))
ids[v] = id
}
out[i] = id
}
return out
}
return conv(a), conv(b)
}
// differ marks the elements of a and b that the hunks change.
type differ struct {
a, b []int32
da, db []bool // changed elements
next, cnt []int // histogram scratch, by position in a
recs map[int32]record
recsCap int
myersV []int
myersExtra int
}
type record struct{ first, count int }
func (d *differ) mark(a0, a1, b0, b1 int) {
if a0 == a1 && b0 == b1 {
return
}
if d.da == nil {
d.da, d.db = make([]bool, len(d.a)), make([]bool, len(d.b))
}
for i := a0; i < a1; i++ {
d.da[i] = true
}
for i := b0; i < b1; i++ {
d.db[i] = true
}
}
// hunks turns the marks into hunks.
func (d *differ) hunks() []Hunk {
if d.da == nil {
return nil
}
var out []Hunk
i, j := 0, 0
for i < len(d.a) || j < len(d.b) {
if i < len(d.a) && j < len(d.b) && !d.da[i] && !d.db[j] {
i++
j++
continue
}
h := Hunk{A0: i, B0: j}
for i < len(d.a) && d.da[i] {
i++
}
for j < len(d.b) && d.db[j] {
j++
}
h.A1, h.B1 = i, j
if h.A0 == h.A1 && h.B0 == h.B1 {
// Unpaired unchanged elements cannot happen; never loop.
if i < len(d.a) {
i++
}
if j < len(d.b) {
j++
}
continue
}
out = append(out, h)
}
return out
}
+194
View File
@@ -0,0 +1,194 @@
package diff
import (
"math/rand/v2"
"reflect"
"slices"
"strings"
"testing"
)
// apply turns a into b with the hunks, checking that what they leave
// alone is the same on both sides.
func apply(t *testing.T, a, b []string, hunks []Hunk) {
t.Helper()
var out []string
i, j := 0, 0
for _, h := range hunks {
if h.A0 < i || h.B0 < j || h.A0-i != h.B0-j || h.A1 < h.A0 || h.B1 < h.B0 {
t.Fatalf("hunk %+v out of order after %d, %d", h, i, j)
}
for ; i < h.A0; i, j = i+1, j+1 {
if a[i] != b[j] {
t.Fatalf("unchanged line %d of a %q is %q in b", i, a[i], b[j])
}
out = append(out, a[i])
}
out = append(out, b[h.B0:h.B1]...)
i, j = h.A1, h.B1
}
if len(a)-i != len(b)-j {
t.Fatalf("tails differ: %d of a, %d of b", len(a)-i, len(b)-j)
}
out = append(out, a[i:]...)
if !reflect.DeepEqual(out, b) && !(len(out) == 0 && len(b) == 0) {
t.Fatalf("applying %v gives %q, want %q", hunks, out, b)
}
}
func lines(s string) []string {
if s == "" {
return nil
}
return strings.Split(s, "\n")
}
func TestLines(t *testing.T) {
for _, c := range []struct {
a, b string
want []Hunk
}{
{"", "", nil},
{"a", "a", nil},
{"", "a\nb", []Hunk{{0, 0, 0, 2}}},
{"a\nb", "", []Hunk{{0, 2, 0, 0}}},
{"a\nb\nc", "a\nx\nc", []Hunk{{1, 2, 1, 2}}},
{"a\nb\nc", "a\nc", []Hunk{{1, 2, 1, 1}}},
{"a\nc", "a\nb\nc", []Hunk{{1, 1, 1, 2}}},
{"a\nb\nc\nd", "b\nc\nd\ne", []Hunk{{0, 1, 0, 0}, {4, 4, 3, 4}}},
} {
got := Lines(lines(c.a), lines(c.b))
if !reflect.DeepEqual(got, c.want) {
t.Errorf("Lines(%q, %q) = %v, want %v", c.a, c.b, got, c.want)
}
apply(t, lines(c.a), lines(c.b), got)
}
}
// A function added between two others shows as the function and the
// blank line after it, not as the end of one function and the start of
// the next, as git's indent heuristic places it.
func TestLinesSlide(t *testing.T) {
a := lines("func a() {\n\tx()\n}\n\nfunc c() {\n\tx()\n}")
b := lines("func a() {\n\tx()\n}\n\nfunc b() {\n\tx()\n}\n\nfunc c() {\n\tx()\n}")
got := Lines(a, b)
want := []Hunk{{4, 4, 4, 8}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("Lines = %v, want %v: %q", got, want, b[got[0].B0:got[0].B1])
}
apply(t, a, b, got)
}
// Histogram anchors on rare lines: moving a block keeps the unique lines
// matched rather than the braces that repeat.
func TestLinesHistogram(t *testing.T) {
a := lines("one\n{\n}\ntwo\n{\n}\nthree")
b := lines("two\n{\n}\none\n{\n}\nthree")
got := Lines(a, b)
apply(t, a, b, got)
changed := 0
for _, h := range got {
changed += h.A1 - h.A0 + h.B1 - h.B0
}
if changed > 6 {
t.Fatalf("Lines = %v, %d lines changed", got, changed)
}
}
func TestLinesRandom(t *testing.T) {
r := rand.New(rand.NewPCG(1, 2))
words := []string{"a", "b", "c", "{", "}", "", "x := 1", "return"}
gen := func(n int) []string {
out := make([]string, n)
for i := range out {
out[i] = words[r.IntN(len(words))]
}
return out
}
for range 2000 {
a := gen(r.IntN(40))
b := append([]string(nil), a...)
// Edit some.
for range r.IntN(6) {
if len(b) == 0 || r.IntN(2) == 0 {
at := r.IntN(len(b) + 1)
b = append(b[:at], append(gen(r.IntN(4)+1), b[at:]...)...)
} else {
at := r.IntN(len(b))
b = append(b[:at], b[min(len(b), at+r.IntN(3)+1):]...)
}
}
if r.IntN(5) == 0 {
b = gen(r.IntN(40))
}
apply(t, a, b, Lines(a, b))
ia, ib := Intern(a, b)
d := differ{a: ia, b: ib}
d.myers(0, len(ia), 0, len(ib))
apply(t, a, b, d.hunks())
}
}
// Myers's cost limit keeps unrelated texts quick and the result valid.
func TestMyersCostLimit(t *testing.T) {
r := rand.New(rand.NewPCG(3, 4))
gen := func(n int) []string {
out := make([]string, n)
for i := range out {
out[i] = string(rune('a' + r.IntN(3)))
}
return out
}
a, b := gen(5000), gen(5000)
apply(t, a, b, Lines(a, b))
}
func TestWords(t *testing.T) {
a := "return foo(bar, baz)"
b := "return foo(qux, baz)"
ra, rb, same := Words(a, b)
if !reflect.DeepEqual(ra, []Range{{11, 14}}) || !reflect.DeepEqual(rb, []Range{{11, 14}}) {
t.Fatalf("Words = %v, %v", ra, rb)
}
if same < 0.8 {
t.Fatalf("same = %v", same)
}
// Changed words across whitespace join.
ra, rb, _ = Words("a b c d", "a x y d")
if !reflect.DeepEqual(ra, []Range{{2, 5}}) || !reflect.DeepEqual(rb, []Range{{2, 5}}) {
t.Fatalf("Words joined = %v, %v", ra, rb)
}
ra, rb, _ = Chars("colour", "color")
if !reflect.DeepEqual(ra, []Range{{4, 5}}) || rb != nil {
t.Fatalf("Chars = %v, %v", ra, rb)
}
}
func BenchmarkLines(b *testing.B) {
var sb strings.Builder
for i := range 20000 {
sb.WriteString("line ")
sb.WriteString(strings.Repeat("x", i%40))
sb.WriteString("\n")
}
a := lines(sb.String())
c := append([]string(nil), a...)
for i := 100; i < len(c); i += 997 {
c[i] = "changed"
}
b.ResetTimer()
for range b.N {
Lines(a, c)
}
}
// The rarity of a line is its record's count in the region, as git's,
// so that the last of repeated lines is not taken for a unique anchor.
func TestHistogramRarity(t *testing.T) {
a := []string{"", "", "", "\tv14 := f13()", "\tv22 := f25()", "}", ""}
b := []string{"\t\treturn err", "\treturn nil", "", "", "\tv22 := f25()", "}", ""}
got, want := Lines(a, b), []Hunk{{0, 0, 0, 2}, {2, 4, 4, 4}} // git diff --histogram's
if !slices.Equal(got, want) {
t.Errorf("hunks %v, want git's %v", got, want)
}
}
+141
View File
@@ -0,0 +1,141 @@
package diff
// maxChain is how often an element may occur in a region of a for the
// histogram algorithm to anchor on it, as git's.
const maxChain = 64
// maxDepth bounds the recursion of histogram, past which a region is
// compared with Myers's algorithm.
const maxDepth = 256
// histogram compares a[a0:a1] with b[b0:b1]: it finds the longest common
// run of elements that occur least often in a, and compares what is
// before and after it the same way.
func (d *differ) histogram(a0, a1, b0, b1, depth int) {
for {
// Common prefix and suffix.
for a0 < a1 && b0 < b1 && d.a[a0] == d.b[b0] {
a0++
b0++
}
for a0 < a1 && b0 < b1 && d.a[a1-1] == d.b[b1-1] {
a1--
b1--
}
if a0 == a1 || b0 == b1 {
d.mark(a0, a1, b0, b1)
return
}
if depth > maxDepth {
d.myers(a0, a1, b0, b1)
return
}
la0, la1, lb0, lb1, ok := d.lcs(a0, a1, b0, b1)
if !ok {
d.myers(a0, a1, b0, b1)
return
}
if la0 == la1 {
// Nothing in common.
d.mark(a0, a1, b0, b1)
return
}
depth++
// Recurse into the smaller side, loop on the other.
if la0-a0+lb0-b0 < a1-la1+b1-lb1 {
d.histogram(a0, la0, b0, lb0, depth)
a0, b0 = la1, lb1
} else {
d.histogram(la1, a1, lb1, b1, depth)
a1, b1 = la0, lb0
}
}
}
// lcs finds the longest run common to a[a0:a1] and b[b0:b1] whose
// rarest element occurs least often in a. ok is false when every
// element both have occurs too often in a, for Myers's algorithm.
func (d *differ) lcs(a0, a1, b0, b1 int) (la0, la1, lb0, lb1 int, ok bool) {
n := a1 - a0
if cap(d.next) < n {
d.next, d.cnt = make([]int, n), make([]int, n)
}
next, cnt := d.next[:n], d.cnt[:n]
// Clearing costs the map's capacity: a small region takes a new one.
if d.recs == nil || d.recsCap > 8*n+64 {
d.recs, d.recsCap = make(map[int32]record, n), n
} else {
clear(d.recs)
}
recs := d.recs
// From the end, so each record's chain goes forward from its first.
for i := a1 - 1; i >= a0; i-- {
r, seen := recs[d.a[i]]
if seen {
next[i-a0] = r.first
r.count++
} else {
next[i-a0] = -1
r.count = 1
}
r.first = i
recs[d.a[i]] = r
}
// How rare each line is: its record's count in the region, as git's
// CNT, not the count from it to the region's end, which makes the last
// of many blank lines look unique.
for i := a0; i < a1; i++ {
cnt[i-a0] = recs[d.a[i]].count
}
best := maxChain + 1
common := false
la0, la1 = a0, a0
for bi := b0; bi < b1; {
bnext := bi + 1
r, found := recs[d.b[bi]]
if !found {
bi = bnext
continue
}
common = true
if r.count > best {
bi = bnext
continue
}
for as := r.first; as >= 0; {
s, bs, e, be := as, bi, as+1, bi+1
rc := cnt[as-a0]
for s > a0 && bs > b0 && d.a[s-1] == d.b[bs-1] {
s--
bs--
if rc > 1 {
rc = min(rc, cnt[s-a0])
}
}
for e < a1 && be < b1 && d.a[e] == d.b[be] {
if rc > 1 {
rc = min(rc, cnt[e-a0])
}
e++
be++
}
if bnext < be {
bnext = be
}
if la1-la0 < e-s || rc < best {
la0, la1, lb0, lb1, best = s, e, bs, be, rc
}
// The next occurrence past this run.
np := next[as-a0]
for np >= 0 && np < e {
np = next[np-a0]
}
as = np
}
bi = bnext
}
if common && best > maxChain {
return 0, 0, 0, 0, false
}
return la0, la1, lb0, lb1, true
}
+152
View File
@@ -0,0 +1,152 @@
package diff
// Myers's algorithm in linear space, as git's xdiff runs it (xdiffi.c):
// the middle snake of each region splits it in two, until the cost of a
// region passes a limit, where the furthest diagonals reached split it,
// which bounds the time on large unrelated texts at the price of a
// minimal diff.
const (
maxCostMin = 256 // XDL_MAX_COST_MIN
lineMax = int(^uint(0) >> 2)
)
func (d *differ) myers(a0, a1, b0, b1 int) {
n := len(d.a) + len(d.b) + 3
if len(d.myersV) < 2*n {
d.myersV = make([]int, 2*n)
}
cost := 1
for cost*cost < n {
cost <<= 1
}
d.myersExtra = max(cost, maxCostMin)
d.recsCmp(a0, a1, b0, b1, false)
}
func (d *differ) recsCmp(off1, lim1, off2, lim2 int, needMin bool) {
for off1 < lim1 && off2 < lim2 && d.a[off1] == d.b[off2] {
off1++
off2++
}
for off1 < lim1 && off2 < lim2 && d.a[lim1-1] == d.b[lim2-1] {
lim1--
lim2--
}
if off1 == lim1 || off2 == lim2 {
d.mark(off1, lim1, off2, lim2)
return
}
i1, i2, minLo, minHi := d.split(off1, lim1, off2, lim2, needMin)
d.recsCmp(off1, i1, off2, i2, minLo)
d.recsCmp(i1, lim1, i2, lim2, minHi)
}
// split finds where to split a[off1:lim1] and b[off2:lim2]: the middle
// snake, or past the cost limit the best diagonal reached.
func (d *differ) split(off1, lim1, off2, lim2 int, needMin bool) (int, int, bool, bool) {
ha1, ha2 := d.a, d.b
nd := len(d.a) + len(d.b) + 3
base := len(d.b) + 1
// Diagonal k is at base+k of each vector.
vf, vb := d.myersV[:nd], d.myersV[nd:2*nd]
dmin, dmax := off1-lim2, lim1-off2
fmid, bmid := off1-off2, lim1-lim2
odd := (fmid-bmid)&1 != 0
fmin, fmax := fmid, fmid
bmin, bmax := bmid, bmid
vf[base+fmid] = off1
vb[base+bmid] = lim1
for ec := 1; ; ec++ {
// Forward.
if fmin > dmin {
fmin--
vf[base+fmin-1] = -1
} else {
fmin++
}
if fmax < dmax {
fmax++
vf[base+fmax+1] = -1
} else {
fmax--
}
for k := fmax; k >= fmin; k -= 2 {
var i1 int
if vf[base+k-1] >= vf[base+k+1] {
i1 = vf[base+k-1] + 1
} else {
i1 = vf[base+k+1]
}
i2 := i1 - k
for i1 < lim1 && i2 < lim2 && ha1[i1] == ha2[i2] {
i1++
i2++
}
vf[base+k] = i1
if odd && bmin <= k && k <= bmax && vb[base+k] <= i1 {
return i1, i2, true, true
}
}
// Backward.
if bmin > dmin {
bmin--
vb[base+bmin-1] = lineMax
} else {
bmin++
}
if bmax < dmax {
bmax++
vb[base+bmax+1] = lineMax
} else {
bmax--
}
for k := bmax; k >= bmin; k -= 2 {
var i1 int
if vb[base+k-1] < vb[base+k+1] {
i1 = vb[base+k-1]
} else {
i1 = vb[base+k+1] - 1
}
i2 := i1 - k
for i1 > off1 && i2 > off2 && ha1[i1-1] == ha2[i2-1] {
i1--
i2--
}
vb[base+k] = i1
if !odd && fmin <= k && k <= fmax && i1 <= vf[base+k] {
return i1, i2, true, true
}
}
if needMin || ec < d.myersExtra {
continue
}
// Too costly: split where the furthest diagonals got.
fbest, fbest1 := -1, -1
for k := fmax; k >= fmin; k -= 2 {
i1 := min(vf[base+k], lim1)
i2 := i1 - k
if lim2 < i2 {
i1, i2 = lim2+k, lim2
}
if fbest < i1+i2 {
fbest, fbest1 = i1+i2, i1
}
}
bbest, bbest1 := lineMax, lineMax
for k := bmax; k >= bmin; k -= 2 {
i1 := max(off1, vb[base+k])
i2 := i1 - k
if i2 < off2 {
i1, i2 = off2+k, off2
}
if i1+i2 < bbest {
bbest, bbest1 = i1+i2, i1
}
}
if (lim1+lim2)-bbest < fbest-(off1+off2) {
return fbest1, fbest - fbest1, true, false
}
return bbest1, bbest - bbest1, false, true
}
}
+132
View File
@@ -0,0 +1,132 @@
package diff
import (
"unicode"
"unicode/utf8"
)
// Range is a range of bytes, Start to End.
type Range struct{ Start, End int }
// Words compares two texts word by word, as review tools highlight what
// changed within lines: words (letters, digits and underscores), runs of
// whitespace and other characters one at a time. It returns the byte
// ranges of a and b that changed, joined across the whitespace between
// them, and how much of the two texts stayed the same, from 0 to 1, by
// their bytes.
func Words(a, b string) (ra, rb []Range, same float64) {
return tokens(a, b, wordTokens)
}
// Chars compares two texts character by character, as Words does by words.
func Chars(a, b string) (ra, rb []Range, same float64) {
return tokens(a, b, charTokens)
}
func tokens(a, b string, split func(string, []Range) []Range) (ra, rb []Range, same float64) {
ta, tb := split(a, nil), split(b, nil)
ids := make(map[string]int32, len(ta)+len(tb))
conv := func(s string, t []Range) []int32 {
out := make([]int32, len(t))
for i, r := range t {
v := s[r.Start:r.End]
id, ok := ids[v]
if !ok {
id = int32(len(ids))
ids[v] = id
}
out[i] = id
}
return out
}
ia, ib := conv(a, ta), conv(b, tb)
hunks := Ints(ia, ib)
changed := 0
for _, h := range hunks {
if h.A0 < h.A1 {
ra = join(ra, Range{ta[h.A0].Start, ta[h.A1-1].End}, a)
changed += ta[h.A1-1].End - ta[h.A0].Start
}
if h.B0 < h.B1 {
rb = join(rb, Range{tb[h.B0].Start, tb[h.B1-1].End}, b)
changed += tb[h.B1-1].End - tb[h.B0].Start
}
}
if total := len(a) + len(b); total > 0 {
same = 1 - float64(changed)/float64(total)
} else {
same = 1
}
return ra, rb, same
}
// join appends r to rs, merged with the last range when only whitespace
// is between them.
func join(rs []Range, r Range, s string) []Range {
if n := len(rs); n > 0 {
last := &rs[n-1]
gap := s[last.End:r.Start]
blank := true
for _, c := range gap {
if c == '\n' || !unicode.IsSpace(c) {
blank = false
break
}
}
if blank {
last.End = r.End
return rs
}
}
return append(rs, r)
}
func isWord(r rune) bool {
return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r)
}
func wordTokens(s string, out []Range) []Range {
for i := 0; i < len(s); {
r, n := utf8.DecodeRuneInString(s[i:])
j := i + n
switch {
case isWord(r):
for j < len(s) {
r, n := utf8.DecodeRuneInString(s[j:])
if !isWord(r) {
break
}
j += n
}
case r != '\n' && unicode.IsSpace(r):
for j < len(s) {
r, n := utf8.DecodeRuneInString(s[j:])
if r == '\n' || !unicode.IsSpace(r) {
break
}
j += n
}
}
out = append(out, Range{i, j})
i = j
}
return out
}
func charTokens(s string, out []Range) []Range {
for i := 0; i < len(s); {
_, n := utf8.DecodeRuneInString(s[i:])
// Combining marks stay with their base.
j := i + n
for j < len(s) {
r, n := utf8.DecodeRuneInString(s[j:])
if !unicode.Is(unicode.Mn, r) && !unicode.Is(unicode.Me, r) && r != 0x200d && !(r >= 0xfe00 && r <= 0xfe0f) {
break
}
j += n
}
out = append(out, Range{i, j})
i = j
}
return out
}
+234
View File
@@ -0,0 +1,234 @@
// Package download fetches the files that MyGo keeps in the user's cache:
// the native libraries plugins name in their mygo-plugin.json, which the
// CLI and unpackaged programs download into <cache>/mygo/natives/<sha256>/,
// and the tools the CLI runs, as NSIS. Every download checks the file's
// SHA-256, tries again when the host fails in passing, and processes that
// need one file at once (two apps, `go test` running packages side by
// side) download it once, one after the other.
package download
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"time"
)
// File is a file to download.
type File struct {
URL string
// SHA256 is the file's SHA-256 in lowercase hex.
SHA256 string
// Client sends the requests; nil means http.DefaultClient.
Client *http.Client
// Header is added to every request.
Header http.Header
// Progress, when set, returns where each attempt copies what arrives
// too, given the length the response announces (or -1).
Progress func(total int64) io.Writer
}
// Backoff is how long Get waits before each new attempt after a transient
// failure: 5xx, 408 and 429 responses, and connections that fail or break
// off. Hosts like GitHub's release downloads answer 502 and 504 now and
// then, and the next request succeeds.
var Backoff = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second}
// maxSize bounds what a download may write.
const maxSize = 64 << 20
// StatusError is a response other than 200 OK.
type StatusError struct {
URL string
Code int
Status string
}
func (e *StatusError) Error() string { return fmt.Sprintf("GET %s: %s", e.URL, e.Status) }
// transient reports whether err is a failure that a new request may not
// have: an overloaded or restarting server, or a connection that failed or
// broke off. Timeouts are not: a host that did not answer in time is
// unlikely to answer the next request sooner, and waiting for it again
// would hold up the next copy of the file; nor is a name that does not
// resolve, or a file that is not the expected one.
func transient(err error) bool {
if se, ok := errors.AsType[*StatusError](err); ok {
return se.Code >= 500 || se.Code == http.StatusRequestTimeout || se.Code == http.StatusTooManyRequests
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return false
}
if ne, ok := errors.AsType[net.Error](err); ok && ne.Timeout() {
return false
}
if de, ok := errors.AsType[*net.DNSError](err); ok && de.IsNotFound {
return false
}
if _, ok := errors.AsType[*bodyError](err); ok {
return true
}
if _, ok := errors.AsType[*net.OpError](err); ok {
return true
}
return errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF)
}
// Get downloads f into the file path, which it creates or truncates, and
// checks its SHA-256. It tries again, after Backoff, when an attempt fails
// in passing (see transient); the error is the last attempt's.
func Get(ctx context.Context, f File, path string) error {
var err error
for attempt := 0; ; attempt++ {
err = get(ctx, f, path)
if err == nil || attempt == len(Backoff) || !transient(err) {
return err
}
select {
case <-ctx.Done():
return err
case <-time.After(Backoff[attempt]):
}
}
}
func get(ctx context.Context, f File, path string) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, f.URL, nil)
if err != nil {
return err
}
for k, v := range f.Header {
req.Header[k] = v
}
client := f.Client
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return &StatusError{URL: f.URL, Code: resp.StatusCode, Status: resp.Status}
}
out, err := os.Create(path)
if err != nil {
return err
}
h := sha256.New()
w := io.MultiWriter(out, h)
if f.Progress != nil {
w = io.MultiWriter(out, h, f.Progress(resp.ContentLength))
}
_, err = io.Copy(w, io.LimitReader(bodyReader{resp.Body}, maxSize))
if cerr := out.Close(); err == nil {
err = cerr
}
if be, ok := errors.AsType[*bodyError](err); ok {
return fmt.Errorf("GET %s: %w", f.URL, be)
} else if err != nil {
return err
}
if got := hex.EncodeToString(h.Sum(nil)); got != f.SHA256 {
return fmt.Errorf("%s has the SHA-256 %s, not %s", f.URL, got, f.SHA256)
}
return nil
}
// bodyReader tells the errors of reading a response's body, which broke
// off, from those of writing the file.
type bodyReader struct{ r io.Reader }
func (b bodyReader) Read(p []byte) (int, error) {
n, err := b.r.Read(p)
if err != nil && err != io.EOF {
err = &bodyError{err}
}
return n, err
}
type bodyError struct{ err error }
func (e *bodyError) Error() string { return e.err.Error() }
func (e *bodyError) Unwrap() error { return e.err }
// Cached makes the file path hold f, downloading it when it is missing or
// differs, executable, as native libraries are. It holds a lock on the
// directory of path while it checks and downloads, so that processes that
// need the file at the same time download it once: the first downloads it
// and renames it into place, the others wait for it, then find it there.
//
// Without the lock, each would rename its own download onto path, and on
// Windows renaming onto a file that another process has open or loaded,
// or is renaming itself, fails with "Access is denied".
func Cached(ctx context.Context, f File, path string) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
unlock, err := Lock(filepath.Join(dir, ".lock"), func() { waiting(path) })
if err != nil {
return err
}
defer unlock()
if Check(path, f.SHA256) {
return nil
}
tmp, err := os.CreateTemp(dir, ".download-*")
if err != nil {
return err
}
tmp.Close()
defer os.Remove(tmp.Name())
if err := Get(ctx, f, tmp.Name()); err != nil {
return err
}
if err := os.Chmod(tmp.Name(), 0o755); err != nil {
return err
}
if err := rename(tmp.Name(), path); err != nil {
// Where processes do not take the lock (see Lock), another one may
// have put the file there meanwhile, and may have it loaded, which
// Windows won't replace.
if Check(path, f.SHA256) {
return nil
}
return err
}
return nil
}
// rename is os.Rename, and waiting is called when Cached waits for
// another process to download the file, both for tests to replace.
var (
rename = os.Rename
waiting = func(path string) {}
)
// Check reports whether the file path exists and has the SHA-256 sum.
func Check(path, sum string) bool {
got, err := FileSHA256(path)
return err == nil && got == sum
}
// FileSHA256 returns the SHA-256 of a file, in hex.
func FileSHA256(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
+180
View File
@@ -0,0 +1,180 @@
package download
import (
"context"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func sum(b []byte) string {
s := sha256.Sum256(b)
return hex.EncodeToString(s[:])
}
func noBackoff(t *testing.T) {
saved := Backoff
Backoff = make([]time.Duration, len(saved))
t.Cleanup(func() { Backoff = saved })
}
// TestGetRetriesTransientFailures downloads through a host that answers
// 502 and 504, and breaks a connection off, before it answers with the
// file, as GitHub's release downloads do now and then; and gives up at
// once on failures a new request would not change.
func TestGetRetriesTransientFailures(t *testing.T) {
noBackoff(t)
content := []byte(strings.Repeat("the library ", 1000))
var requests atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n := requests.Add(1)
switch r.URL.Path {
case "/flaky":
switch n {
case 1:
http.Error(w, "bad gateway", http.StatusBadGateway)
case 2:
http.Error(w, "gateway timeout", http.StatusGatewayTimeout)
case 3:
// Announce the whole file, send part of it, and hang up.
w.Header().Set("Content-Length", "12000")
w.Write(content[:100])
conn, _, err := http.NewResponseController(w).Hijack()
if err == nil {
conn.Close()
}
default:
w.Header().Set("Content-Length", strconv.Itoa(len(content)))
w.Write(content)
}
case "/missing":
http.NotFound(w, r)
case "/down":
http.Error(w, "unavailable", http.StatusServiceUnavailable)
case "/other":
w.Write([]byte("another file"))
}
}))
defer srv.Close()
dir := t.TempDir()
path := filepath.Join(dir, "lib")
// Each attempt starts its progress over.
var totals []int64
f := File{URL: srv.URL + "/flaky", SHA256: sum(content), Progress: func(total int64) io.Writer {
totals = append(totals, total)
return io.Discard
}}
if err := Get(context.Background(), f, path); err != nil {
t.Fatalf("after two 5xx and a connection broken off: %v", err)
}
if b, err := os.ReadFile(path); err != nil || string(b) != string(content) {
t.Errorf("the file holds %d bytes, %v", len(b), err)
}
if n := requests.Load(); n != 4 {
t.Errorf("%d requests, want 4", n)
}
if want := []int64{12000, int64(len(content))}; !slices.Equal(totals, want) {
t.Errorf("progress totals %v, want %v", totals, want)
}
for _, c := range []struct {
path, err string
requests int32
}{
{"/missing", "GET " + srv.URL + "/missing: 404 Not Found", 1},
{"/other", srv.URL + "/other has the SHA-256 " + sum([]byte("another file")) + ", not " + sum(content), 1},
// A host that stays down fails the download after the retries.
{"/down", "GET " + srv.URL + "/down: 503 Service Unavailable", int32(len(Backoff)) + 1},
} {
requests.Store(0)
err := Get(context.Background(), File{URL: srv.URL + c.path, SHA256: sum(content)}, path)
if err == nil || err.Error() != c.err {
t.Errorf("%s: %v, want %s", c.path, err, c.err)
}
if n := requests.Load(); n != c.requests {
t.Errorf("%s: %d requests, want %d", c.path, n, c.requests)
}
}
}
// TestCachedDownloadsOnceForConcurrentProcesses has a second download of a
// file start into the cache while a first one is under way, as `go test
// ./...` runs plugins/terminal and plugins/terminal/internal/vt side by
// side and two apps may start at once: the second waits for the first and
// takes the file it put there, instead of downloading it again and
// renaming its copy onto the first's, which Windows refuses ("Access is
// denied") when the first has it open or loaded.
func TestCachedDownloadsOnceForConcurrentProcesses(t *testing.T) {
content := []byte("the native library")
var (
requests atomic.Int32
firstAsks = make(chan struct{})
secondWaits = make(chan struct{})
secondAsks = make(chan struct{})
)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if requests.Add(1) == 1 {
close(firstAsks)
// Hold the first download until the second one is under way
// too: waiting for it, or downloading it as well.
select {
case <-secondWaits:
case <-secondAsks:
}
} else {
close(secondAsks)
}
w.Write(content)
}))
defer srv.Close()
var mu sync.Mutex
var replaced []string
savedRename, savedWaiting := rename, waiting
defer func() { rename, waiting = savedRename, savedWaiting }()
rename = func(from, to string) error {
if _, err := os.Stat(to); err == nil {
mu.Lock()
replaced = append(replaced, to)
mu.Unlock()
}
return os.Rename(from, to)
}
waiting = func(string) { close(secondWaits) }
path := filepath.Join(t.TempDir(), "natives", sum(content), "libx.so")
f := File{URL: srv.URL + "/libx.so", SHA256: sum(content)}
first := make(chan error, 1)
go func() { first <- Cached(context.Background(), f, path) }()
<-firstAsks // the first holds the lock now
if err := Cached(context.Background(), f, path); err != nil {
t.Fatal(err)
}
if err := <-first; err != nil {
t.Fatal(err)
}
if n := requests.Load(); n != 1 {
t.Errorf("the file was downloaded %d times", n)
}
if len(replaced) > 0 {
t.Errorf("a download was renamed onto the other's file %v", replaced)
}
if b, err := os.ReadFile(path); err != nil || string(b) != string(content) {
t.Errorf("the cache holds %q, %v", b, err)
}
if entries, _ := os.ReadDir(filepath.Dir(path)); len(entries) != 2 { // the file and .lock
t.Errorf("the cache directory holds %v", entries)
}
}
+7
View File
@@ -0,0 +1,7 @@
//go:build !((darwin && !ios) || dragonfly || freebsd || (linux && !android) || netbsd || openbsd || windows)
package download
// Lock takes no lock where MyGo has no lock to take: processes there each
// download a file, and Cached keeps the one renamed into place first.
func Lock(path string, wait func()) (unlock func(), err error) { return func() {}, nil }
+42
View File
@@ -0,0 +1,42 @@
//go:build (darwin && !ios) || dragonfly || freebsd || (linux && !android) || netbsd || openbsd
package download
import (
"os"
"syscall"
)
// Lock takes an exclusive lock on the file path, which it creates, and
// returns what releases it. When another process (or another call) holds
// it, Lock calls wait, if set, then waits for it. The system releases the
// lock too when the process ends, so a process that dies downloading
// leaves no stale lock behind.
func Lock(path string, wait func()) (unlock func(), err error) {
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o644)
if err != nil {
return nil, err
}
how := syscall.LOCK_EX | syscall.LOCK_NB
for {
err = syscall.Flock(int(f.Fd()), how)
if err == syscall.EWOULDBLOCK && how&syscall.LOCK_NB != 0 {
if wait != nil {
wait()
}
how = syscall.LOCK_EX
continue
}
if err != syscall.EINTR {
break
}
}
if err != nil {
f.Close()
return nil, &os.PathError{Op: "flock", Path: path, Err: err}
}
return func() {
syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
f.Close()
}, nil
}
+57
View File
@@ -0,0 +1,57 @@
package download
import (
"os"
"syscall"
"unsafe"
)
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procLockFileEx = kernel32.NewProc("LockFileEx")
procUnlockFileEx = kernel32.NewProc("UnlockFileEx")
)
const (
lockfileFailImmediately = 0x1
lockfileExclusiveLock = 0x2
allBytes = uintptr(^uint32(0))
errorLockViolation syscall.Errno = 33 // ERROR_LOCK_VIOLATION
)
// Lock takes an exclusive lock on the file path, which it creates, and
// returns what releases it. When another process (or another call) holds
// it, Lock calls wait, if set, then waits for it. The system releases the
// lock too when the process ends, so a process that dies downloading
// leaves no stale lock behind.
func Lock(path string, wait func()) (unlock func(), err error) {
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o644)
if err != nil {
return nil, err
}
// The whole file, as cmd/go's lockedfile locks it. The handle is
// synchronous, so LockFileEx returns once it holds the lock.
ol := new(syscall.Overlapped)
lock := func(flags uintptr) error {
if r, _, e := procLockFileEx.Call(f.Fd(), flags, 0, allBytes, allBytes, uintptr(unsafe.Pointer(ol))); r == 0 {
return e
}
return nil
}
err = lock(lockfileExclusiveLock | lockfileFailImmediately)
if err == errorLockViolation {
if wait != nil {
wait()
}
err = lock(lockfileExclusiveLock)
}
if err != nil {
f.Close()
return nil, &os.PathError{Op: "LockFileEx", Path: path, Err: err}
}
return func() {
procUnlockFileEx.Call(f.Fd(), 0, allBytes, allBytes, uintptr(unsafe.Pointer(ol)))
f.Close()
}, nil
}
@@ -0,0 +1,39 @@
//go:build darwin && !ios
package e2e
import (
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// TestAccessAutoComplete reads, as VoiceOver does, what the suggestions
// of combo boxes complete (aria-autocomplete) in AXAutocompleteValue, as
// WebKit's elements give it; a text field without suggestions names no
// such attribute.
func TestAccessAutoComplete(t *testing.T) {
var frames atomic.Int32
var city, word, note string
view := func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Padding(20).Gap(10).Children(func() {
ui.Autocomplete(c, &city, []string{"Paris", "Prague"}).Label("City")
ui.TextInputBase(c, &word).Role(ui.RoleComboBox).Label("Word").AutoComplete(ui.AutoCompleteBoth)
ui.TextInput(c, &note).Label("Note")
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Autocomplete", Width: 400, Height: 300, Content: ui.View(view)})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
for label, want := range map[string]string{"City": "list", "Word": "both"} {
eventually(t, label+"'s AXAutocompleteValue", func() bool {
v, _, named, ok := axAttribute(w, label, "AXAutocompleteValue")
return ok && named && v == want
})
}
if v, _, named, ok := axAttribute(w, "Note", "AXAutocompleteValue"); !ok || named {
t.Errorf("Note's AXAutocompleteValue %q, named %v, found %v", v, named, ok)
}
}
@@ -0,0 +1,55 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/ui"
)
// TestAccessAutoComplete reads, as Orca does through ATK, what the
// suggestions of combo boxes complete (aria-autocomplete): the
// supports-autocompletion state and the autocomplete object attribute, as
// Core-AAM maps it, and neither on a text field without suggestions.
func TestAccessAutoComplete(t *testing.T) {
var frames atomic.Int32
var city, word, note string
view := func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Padding(20).Gap(10).Children(func() {
ui.Autocomplete(c, &city, []string{"Paris", "Prague"}).Label("City")
ui.TextInputBase(c, &word).Role(ui.RoleComboBox).Label("Word").AutoComplete(ui.AutoCompleteBoth)
ui.TextInput(c, &note).Label("Note")
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Autocomplete", Width: 400, Height: 300, Content: ui.View(view)})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
find := func(label string) (n linux.TestAccessNode, ok bool) {
mygo.RunOnMain(func() {
nodes, _ := linux.TestAccessibility(w.NativeHandle())
for _, node := range nodes {
if node.Label == label {
n, ok = node, true
}
}
})
return n, ok
}
if _, ok := accessibility(w); !ok {
t.Skip("accessibility automation not available on this platform")
}
for label, want := range map[string]string{"City": "list", "Word": "both"} {
eventually(t, label+"'s autocomplete", func() bool {
n, ok := find(label)
return ok && n.Role == "combo box" && n.SupportsAutocompletion && n.Attributes["autocomplete"] == want
})
}
n, ok := find("Note")
if _, has := n.Attributes["autocomplete"]; !ok || has || n.SupportsAutocompletion {
t.Errorf("Note: %+v, found %v", n, ok)
}
}
@@ -0,0 +1,59 @@
//go:build darwin && !ios
package e2e
import (
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// TestAccessDisabled reads, as VoiceOver does, a button that is only
// unavailable (AccessDisabled, aria-disabled): AXEnabled false, yet
// focused when assistive technology asks, and not pressed, where a button
// Disabled takes neither.
func TestAccessDisabled(t *testing.T) {
var frames, deleted atomic.Int32
var focused atomic.Bool
view := func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Padding(20).Gap(10).Children(func() {
del := ui.Button(c, "Delete project").AccessDisabled(true)
focused.Store(del.Focused())
if del.Clicked() {
deleted.Add(1)
}
ui.Button(c, "Close").Disabled(true)
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Unavailable", Width: 400, Height: 200, Content: ui.View(view)})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
for _, label := range []string{"Delete project", "Close"} {
var v string
var named, ok bool
for end := time.Now().Add(30 * time.Second); ; time.Sleep(50 * time.Millisecond) {
if v, _, named, ok = axAttribute(w, label, "AXEnabled"); ok && v == "0" {
break
}
if time.Now().After(end) {
t.Fatalf("%s: AXEnabled %q (listed %v, found %v), want 0", label, v, named, ok)
}
}
}
if accessPerform(w, "Close", "focus", "") {
t.Error("assistive technology focused the disabled button")
}
if accessPerform(w, "Delete project", "press", "") {
t.Error("assistive technology pressed the unavailable button")
}
if !accessPerform(w, "Delete project", "focus", "") {
t.Fatal("cannot focus the unavailable button")
}
eventually(t, "the unavailable button focused", focused.Load)
if deleted.Load() != 0 {
t.Error("the unavailable button was pressed")
}
}
@@ -0,0 +1,55 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/ui"
)
// TestAccessDisabled reads, as Orca does through ATK, a button that is
// only unavailable (AccessDisabled, aria-disabled): not enabled, yet
// focusable, and focused when assistive technology asks, where a button
// Disabled is neither.
func TestAccessDisabled(t *testing.T) {
var frames atomic.Int32
var focused atomic.Bool
view := func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Padding(20).Gap(10).Children(func() {
del := ui.Button(c, "Delete project").AccessDisabled(true)
focused.Store(del.Focused())
ui.Button(c, "Close").Disabled(true)
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Unavailable", Width: 400, Height: 200, Content: ui.View(view)})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
if _, ok := accessibility(w); !ok {
t.Skip("accessibility automation not available on this platform")
}
states := func(label string) (enabled, focusable, ok bool) {
mygo.RunOnMain(func() { enabled, focusable, ok = linux.TestAccessibilityEnabled(w.NativeHandle(), label) })
return enabled, focusable, ok
}
eventually(t, "the unavailable button", func() bool {
enabled, focusable, ok := states("Delete project")
return ok && !enabled && focusable
})
if enabled, focusable, ok := states("Close"); !ok || enabled || focusable {
t.Errorf("Close: enabled %v, focusable %v, found %v", enabled, focusable, ok)
}
if accessPerform(w, "Delete project", "press", "") {
t.Error("assistive technology pressed the unavailable button")
}
if accessPerform(w, "Close", "focus", "") {
t.Error("assistive technology focused the disabled button")
}
if !accessPerform(w, "Delete project", "focus", "") {
t.Fatal("cannot focus the unavailable button")
}
eventually(t, "the unavailable button focused", focused.Load)
}
+103
View File
@@ -0,0 +1,103 @@
//go:build darwin && !ios
package e2e
import (
"fmt"
"strings"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/darwin"
"github.com/egoist/mygo/ui"
)
// TestAccessGrid reads, as VoiceOver does, a spreadsheet of 10,000 rows
// built only where it shows: a table whose size is in AXARIARowCount and
// AXARIAColumnCount, and AXRowCount, whose rows say which of all they are
// (AXIndex) and, with its cells, their places in AXARIARowIndex and
// AXARIAColumnIndex, as WebKit's grids do; a cell without a column of its
// own names no AXARIAColumnIndex, and one covering two columns says so in
// the length of its AXColumnIndexRange (aria-colspan), the cell after it
// in the column after those.
func TestAccessGrid(t *testing.T) {
var frames atomic.Int32
cell := func(c *ui.Context, name string) ui.Element {
return ui.Box(c).Role(ui.RoleCell).Label(name).Padding(2).Children(func() { ui.Text(c, name) })
}
view := func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Fill().Padding(20).Gap(10).Children(func() {
ui.Column(c).Role(ui.RoleGrid).Label("Sheet").RowCount(10001).ColumnCount(3).Multiselectable(true).Children(func() {
for r := 4120; r < 4122; r++ {
ui.Row(c).Role(ui.RoleRow).RowIndex(r + 1).Selected(r == 4121).Children(func() {
cell(c, fmt.Sprintf("A%d", r))
cell(c, fmt.Sprintf("C%d", r)).ColumnIndex(3)
})
}
ui.Row(c).Role(ui.RoleRow).RowIndex(10001).Children(func() {
cell(c, "Total").ColumnSpan(2)
cell(c, "Sum")
})
})
ui.Column(c).Role(ui.RoleTreeGrid).Label("Outline").Children(func() {
ui.Row(c).Role(ui.RoleRow).Level(1).Children(func() { cell(c, "src") })
})
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Grid", Width: 400, Height: 300, Content: ui.View(view)})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
// find reads the element named label through the newer API, which
// VoiceOver reads its role, rows and places through.
find := func(label string) (n darwin.TestAccessNode, ok bool) {
mygo.RunOnMain(func() {
for _, node := range darwin.TestAccessibility(w.NativeHandle()) {
if node.Label == label && !ok {
n, ok = node, true
}
}
})
return n, ok
}
eventually(t, "the grid", func() bool {
n, ok := find("Sheet")
return ok && n.Role == "AXTable" && n.RowCount == 10001
})
if n, _ := find("Outline"); n.Role != "AXTable" {
t.Errorf("the tree grid: %+v", n)
}
if n, _ := find("A4121 C4121"); n.Role != "AXRow" || n.Index != 4121 {
t.Errorf("row 4,122: %+v", n)
}
// The older API, which says the role as the newer one does, and the
// counts and places as WebKit's grids do.
for _, c := range []struct{ label, attr, want string }{
{"Sheet", "AXRole", "AXTable"},
{"Sheet", "AXARIARowCount", "10001"},
{"Sheet", "AXARIAColumnCount", "3"},
{"A4121 C4121", "AXARIARowIndex", "4122"},
{"C4121", "AXARIAColumnIndex", "3"},
{"C4121", "AXARIARowIndex", "4122"},
{"A4121", "AXARIARowIndex", "4122"},
} {
eventually(t, c.label+"'s "+c.attr, func() bool {
v, _, named, ok := axAttribute(w, c.label, c.attr)
return ok && (named || c.attr == "AXRole") && v == c.want
})
}
if v, _, named, ok := axAttribute(w, "A4121", "AXARIAColumnIndex"); !ok || named {
t.Errorf("A4121's AXARIAColumnIndex %q, named %v, found %v", v, named, ok)
}
// The ranges, which read as descriptions holding want.
for _, c := range []struct{ label, attr, want string }{
{"Total", "AXColumnIndexRange", "{0, 2}"},
{"Total", "AXRowIndexRange", "{10000, 1}"},
{"Sum", "AXColumnIndexRange", "{2, 1}"},
} {
eventually(t, c.label+"'s "+c.attr, func() bool {
v, _, named, ok := axAttribute(w, c.label, c.attr)
return ok && named && strings.Contains(v, c.want)
})
}
}
+111
View File
@@ -0,0 +1,111 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"fmt"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/ui"
)
// TestAccessGrid reads, as Orca does through ATK, a spreadsheet of 10,000
// rows built only where it shows: a table whose xml-roles is grid, with
// its size in the rowcount and colcount attributes, choosing several rows
// (multiselectable, AtkSelection), whose rows and cells say their places
// (rowindex, colindex), a cell covering two columns its span (colspan);
// a List shown as a grid, whose rows are table rows; and a tree grid, a
// tree table.
func TestAccessGrid(t *testing.T) {
var frames atomic.Int32
cell := func(c *ui.Context, name string) ui.Element {
return ui.Box(c).Role(ui.RoleCell).Label(name).Padding(2).Children(func() { ui.Text(c, name) })
}
cursor := -1
files := ui.ListState{Selected: &cursor}
view := func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Fill().Padding(20).Gap(10).Children(func() {
ui.Column(c).Role(ui.RoleGrid).Label("Sheet").RowCount(10001).ColumnCount(3).Multiselectable(true).Children(func() {
ui.Row(c).Role(ui.RoleRow).RowIndex(1).Children(func() {
for _, col := range []string{"A", "B", "C"} {
ui.Box(c).Role(ui.RoleColumnHeader).Label(col).Padding(2).Children(func() { ui.Text(c, col) })
}
})
for r := 4120; r < 4122; r++ {
ui.Row(c).Role(ui.RoleRow).RowIndex(r + 1).Selected(r == 4121).Children(func() {
cell(c, fmt.Sprintf("A%d", r))
cell(c, fmt.Sprintf("C%d", r)).ColumnIndex(3)
})
}
ui.Row(c).Role(ui.RoleRow).RowIndex(10001).Children(func() {
cell(c, "Total").ColumnSpan(2)
cell(c, "Sum")
})
})
ui.List(c, &files, 500, func(i int) {
ui.Row(c).Children(func() { cell(c, fmt.Sprintf("File %d", i)) })
}).Role(ui.RoleGrid).Label("Files").Height(100)
ui.Column(c).Role(ui.RoleTreeGrid).Label("Outline").Children(func() {
ui.Row(c).Role(ui.RoleRow).Level(1).Children(func() { cell(c, "src") })
})
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Grid", Width: 400, Height: 500, Content: ui.View(view)})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
// find returns the first element named label, of the role named role
// if given.
find := func(label string, role ...string) (n linux.TestAccessNode, ok bool) {
mygo.RunOnMain(func() {
nodes, _ := linux.TestAccessibility(w.NativeHandle())
for _, node := range nodes {
if node.Label == label && (len(role) == 0 || node.Role == role[0]) && !ok {
n, ok = node, true
}
}
})
return n, ok
}
if _, ok := accessibility(w); !ok {
t.Skip("accessibility automation not available on this platform")
}
eventually(t, "the grid", func() bool {
n, ok := find("Sheet")
return ok && n.Role == "table" && n.Attributes["xml-roles"] == "grid" && n.Attributes["rowcount"] == "10001" &&
n.Attributes["colcount"] == "3" && n.Multiselectable && n.Selection
})
row, _ := find("A4121 C4121")
if row.Role != "table row" || row.Attributes["rowindex"] != "4122" || !row.Selectable || !row.Selected {
t.Errorf("the row chosen: %+v", row)
}
if row, _ := find("A4120 C4120"); row.Attributes["rowindex"] != "4121" || !row.Selectable || row.Selected {
t.Errorf("the row not chosen: %+v", row)
}
if c, _ := find("C4121"); c.Role != "table cell" || c.Attributes["colindex"] != "3" || c.Attributes["rowindex"] != "4122" {
t.Errorf("C4121: %+v", c)
}
if c, ok := find("A4121"); !ok || c.Attributes["colindex"] != "" {
t.Errorf("A4121 has a column index of its own: %+v", c)
}
if c, _ := find("Total"); c.Role != "table cell" || c.Attributes["colspan"] != "2" || c.Attributes["rowspan"] != "" || c.Attributes["rowindex"] != "10001" {
t.Errorf("a cell covering two columns: %+v", c)
}
if c, ok := find("Sum"); !ok || c.Attributes["colspan"] != "" {
t.Errorf("a cell covering one column: %+v", c)
}
if h, _ := find("B"); h.Role != "column header" && h.Role != "table column header" || h.Attributes["rowindex"] != "1" {
t.Errorf("the header B: %+v", h)
}
if g, _ := find("Files"); g.Role != "table" || g.Attributes["xml-roles"] != "grid" || g.Multiselectable || g.Attributes["setsize"] != "500" {
t.Errorf("the list shown as a grid: %+v", g)
}
if r, ok := find("File 1", "table row"); !ok || r.Attributes["posinset"] != "2" || r.Attributes["setsize"] != "500" {
t.Errorf("a row of the list shown as a grid: %+v", r)
}
if g, _ := find("Outline"); g.Role != "tree table" || g.Attributes["xml-roles"] != "treegrid" {
t.Errorf("the tree grid: %+v", g)
}
}
@@ -0,0 +1,38 @@
//go:build darwin && !ios
package e2e
import (
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// TestAccessKeyShortcuts reads, as VoiceOver does, the keys that press a
// toolbar's buttons (aria-keyshortcuts) in AXKeyShortcutsValue, as
// WebKit's elements give them, written as the menus write them; a button
// without names no such attribute.
func TestAccessKeyShortcuts(t *testing.T) {
var frames atomic.Int32
view := func(c *ui.Context) {
frames.Add(1)
ui.Row(c).Role(ui.RoleToolbar).Label("Tools").Padding(20).Gap(10).Children(func() {
ui.Button(c, "Search").KeyShortcuts(ui.Cmd, ui.KeyK)
ui.Button(c, "Redo").KeyShortcuts(ui.Cmd|ui.Shift, ui.KeyZ).KeyShortcuts(ui.Cmd, ui.KeyY)
ui.Button(c, "Share")
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Key shortcuts", Width: 400, Height: 200, Content: ui.View(view)})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
for label, want := range map[string]string{"Search": "⌘K", "Redo": "⇧⌘Z ⌘Y"} {
eventually(t, label+"'s AXKeyShortcutsValue", func() bool {
v, _, named, ok := axAttribute(w, label, "AXKeyShortcutsValue")
return ok && named && v == want
})
}
if v, _, named, ok := axAttribute(w, "Share", "AXKeyShortcutsValue"); !ok || named {
t.Errorf("Share's AXKeyShortcutsValue %q, named %v, found %v", v, named, ok)
}
}
@@ -0,0 +1,53 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/ui"
)
// TestAccessKeyShortcuts reads, as Orca does through ATK, the keys that
// press a toolbar's buttons (aria-keyshortcuts) in their keyshortcuts
// object attribute, and none on a button without.
func TestAccessKeyShortcuts(t *testing.T) {
var frames atomic.Int32
view := func(c *ui.Context) {
frames.Add(1)
ui.Row(c).Role(ui.RoleToolbar).Label("Tools").Padding(20).Gap(10).Children(func() {
ui.Button(c, "Search").KeyShortcuts(ui.Ctrl, ui.KeyK)
ui.Button(c, "Redo").KeyShortcuts(ui.Ctrl|ui.Shift, ui.KeyZ).KeyShortcuts(ui.Ctrl, ui.KeyY)
ui.Button(c, "Share")
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Key shortcuts", Width: 400, Height: 200, Content: ui.View(view)})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
find := func(label string) (n linux.TestAccessNode, ok bool) {
mygo.RunOnMain(func() {
nodes, _ := linux.TestAccessibility(w.NativeHandle())
for _, node := range nodes {
if node.Label == label {
n, ok = node, true
}
}
})
return n, ok
}
if _, ok := accessibility(w); !ok {
t.Skip("accessibility automation not available on this platform")
}
for label, want := range map[string]string{"Search": "Ctrl+K", "Redo": "Ctrl+Shift+Z Ctrl+Y"} {
eventually(t, label+"'s key shortcuts", func() bool {
n, ok := find(label)
return ok && n.Role == "button" && n.Attributes["keyshortcuts"] == want
})
}
n, ok := find("Share")
if _, has := n.Attributes["keyshortcuts"]; !ok || has {
t.Errorf("Share: %+v, found %v", n, ok)
}
}
@@ -0,0 +1,139 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"strconv"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/ui"
)
// TestAccessListBox reads, as Orca does through ATK, a list box built by
// hand (RoleListBox, RoleOption) and a SelectBase's popup: list boxes of
// selectable list items, the option chosen or highlighted selected.
// Focusing an option of the select highlights it without choosing it,
// and pressing one chooses it (#1172). Options of a list box built only
// where it shows say which of all they are (posinset, setsize), and
// options and tabs showing their choice their own way are selected
// (AccessSelected, #1181).
func TestAccessListBox(t *testing.T) {
var frames atomic.Int32
size, own := "b", 0
result := func(i int) string { return "Result " + strconv.Itoa(i) }
view := func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Fill().Padding(20).Gap(10).Children(func() {
ui.Column(c).Role(ui.RoleListBox).Label("People").Children(func() {
for i, name := range []string{"Ada", "Grace"} {
opt := ui.Row(c).Role(ui.RoleOption).Label(name).Checked(i == own)
if opt.Clicked() {
own = i
}
opt.Children(func() { ui.Text(c, name) })
}
})
ui.Column(c).Role(ui.RoleListBox).Label("Results").Children(func() {
for i := 11; i <= 13; i++ {
ui.Row(c).Role(ui.RoleOption).Label(result(i)).PositionInSet(i, 50).AccessSelected(i == 12).
Children(func() { ui.Text(c, result(i)) })
}
})
ui.Row(c).Role(ui.RoleTabList).Label("Views").Gap(8).Children(func() {
for i, name := range []string{"List", "Board"} {
ui.ButtonBase(c).Role(ui.RoleTab).Label(name).AccessSelected(i == 1).
Children(func() { ui.Text(c, name) })
}
})
sel := ui.SelectBase(c, &size)
sel.Trigger.Label("Size").Padding(4).Children(func() { ui.Text(c, "Size "+size) })
sel.Popup(func(panel ui.Element) {
panel.Label("Sizes")
for _, v := range []string{"a", "b", "c"} {
sel.Item(v).Label("size " + v).Padding(4).Children(func() { ui.Text(c, v) })
}
})
})
}
w := newWindow(t, mygo.WindowOptions{Title: "List boxes", Width: 400, Height: 500, Content: ui.View(view)})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
if _, ok := accessibility(w); !ok {
t.Skip("accessibility automation not available on this platform")
}
// find returns the first node labeled label: an option, not its text.
find := func(label string) (n linux.TestAccessNode, ok bool) {
mygo.RunOnMain(func() {
nodes, _ := linux.TestAccessibility(w.NativeHandle())
for _, node := range nodes {
if node.Label == label && !ok {
n, ok = node, true
}
}
})
return n, ok
}
option := func(label string, selected bool) func() bool {
return func() bool {
n, ok := find(label)
return ok && n.Role == "list item" && n.Selectable && n.Selected == selected
}
}
chosen := func() (s string, o int) {
mygo.RunOnMain(func() { s, o = size, own })
return s, o
}
eventually(t, "the list box built by hand", func() bool {
n, ok := find("People")
return ok && n.Role == "list box"
})
eventually(t, "Result 12 of 50 selected", func() bool {
n, ok := find("Result 12")
return ok && n.Role == "list item" && n.Selectable && n.Selected && n.Attributes["posinset"] == "12" && n.Attributes["setsize"] == "50"
})
if n, _ := find("Result 11"); n.Selected || n.Attributes["posinset"] != "11" || n.Attributes["setsize"] != "50" {
t.Errorf("Result 11: %+v", n)
}
if n, _ := find("Board"); n.Role != "page tab" || !n.Selected {
t.Errorf("the tab chosen: %+v", n)
}
if n, _ := find("List"); n.Role != "page tab" || n.Selected {
t.Errorf("the tab not chosen: %+v", n)
}
eventually(t, "Ada selected", option("Ada", true))
eventually(t, "Grace not selected", option("Grace", false))
if !accessPerform(w, "Grace", "press", "") {
t.Fatal("cannot press Grace")
}
eventually(t, "Grace chosen", func() bool { _, o := chosen(); return o == 1 })
eventually(t, "Grace selected", option("Grace", true))
if !accessPerform(w, "Size", "press", "") {
t.Fatal("cannot press the select")
}
eventually(t, "the select's list box", func() bool {
n, ok := find("Sizes")
return ok && n.Role == "list box"
})
eventually(t, "the choice selected", option("size b", true))
eventually(t, "size a not selected", option("size a", false))
// Focusing an option highlights it, and chooses nothing.
if !accessPerform(w, "size c", "focus", "") {
t.Fatal("cannot focus size c")
}
eventually(t, "size c selected", option("size c", true))
if s, _ := chosen(); s != "b" {
t.Errorf("focusing size c chose %q", s)
}
if _, open := find("size a"); !open {
t.Error("focusing size c closed the popup")
}
if !accessPerform(w, "size a", "press", "") {
t.Fatal("cannot press size a")
}
eventually(t, "size a chosen", func() bool { s, _ := chosen(); return s == "a" })
eventually(t, "the popup closed", func() bool { _, open := find("size a"); return !open })
}
Loaded 100 of 2538 files, more files were not shown because too many files have changed in this diff. Show more