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

@@ -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 })
}
@@ -0,0 +1,57 @@
//go:build darwin && !ios
package e2e
import (
"slices"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// TestAccessPasswordWrite sets a password field's value and types into
// it through accessibility, as a password manager fills it: the text
// reaches the app, but no assistive app reads it back, as none reads
// NSSecureTextField's.
func TestAccessPasswordWrite(t *testing.T) {
var frames atomic.Int32
secret := ""
view := func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Fill().Padding(20).Children(func() {
ui.TextInput(c, &secret).Label("Password").Password()
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Password", Width: 400, Height: 200, Content: ui.View(view)})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
field := func() (accessNode, bool) {
nodes, _ := accessibility(w)
i := slices.IndexFunc(nodes, func(n accessNode) bool { return n.label == "Password" })
if i < 0 {
return accessNode{}, false
}
return nodes[i], true
}
eventually(t, "the password field", func() bool { _, ok := field(); return ok })
read := func() string {
var s string
mygo.RunOnMain(func() { s = secret })
return s
}
if !accessPerform(w, "Password", "value", "hunter2") {
t.Fatal("cannot set the password field's value")
}
eventually(t, "the password set", func() bool { return read() == "hunter2" })
if !accessPerform(w, "Password", "insert", "!") {
t.Fatal("cannot insert text into the password field")
}
eventually(t, "the text inserted", func() bool { return read() == "hunter2!" })
if n, _ := field(); n.value != "" {
t.Errorf("the password field's value reads %q, want it empty", n.value)
}
if v, _, _, _ := axAttribute(w, "Password", "AXSelectedText"); v != "" {
t.Errorf("the password field's selected text reads %q, want it empty", v)
}
}
@@ -0,0 +1,51 @@
//go:build darwin && !ios
package e2e
import (
"strings"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// TestAccessDescribedByErrorMessageSearch reads, as VoiceOver does, a
// search field of the app's own described by a hint (AXHelp), invalid,
// and pointing at the element holding its error (AXErrorMessageElements,
// as WebKit's aria-errormessage), which it names only while invalid.
func TestAccessDescribedByErrorMessageSearch(t *testing.T) {
var frames atomic.Int32
var bad atomic.Bool
bad.Store(true)
view := func(c *ui.Context) {
frames.Add(1)
var query string
ui.Column(c).Fill().Padding(20).Gap(10).Children(func() {
hint := ui.Text(c, "Titles only")
msg := ui.Text(c, "Type a word")
ui.TextInput(c, &query).Label("Find").Search().DescribedBy(hint).Invalid(bad.Load()).ErrorMessage(msg)
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Relations", Width: 400, Height: 300, Content: ui.View(view)})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
for _, c := range []struct{ attr, want string }{
{"AXSubrole", "AXSearchField"},
{"AXHelp", "Type a word\nTitles only"},
{"AXInvalid", "true"},
{"AXErrorMessageElements", "MyGoAccessibilityElement"},
} {
eventually(t, "the field's "+c.attr, func() bool {
v, _, named, ok := axAttribute(w, "Find", c.attr)
return ok && (named || c.attr == "AXSubrole") && strings.Contains(v, c.want)
})
}
bad.Store(false)
w.Invalidate()
eventually(t, "the valid field", func() bool {
v, _, named, ok := axAttribute(w, "Find", "AXErrorMessageElements")
help, _, _, _ := axAttribute(w, "Find", "AXHelp")
return ok && !named && v == "" && help == "Titles only"
})
}
@@ -0,0 +1,110 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"slices"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/ui"
)
// TestAccessDescribedByErrorOrientationSearch reads, as Orca does through
// ATK, a search field described by a hint (its description, described-by
// and description-for back), marked invalid without a message and then
// with the element holding it (error-message and error-for back, only
// while invalid), a toolbar and a separator told their orientation, and
// a price deleted and inserted.
func TestAccessDescribedByErrorOrientationSearch(t *testing.T) {
var frames atomic.Int32
var bad, message atomic.Bool
view := func(c *ui.Context) {
frames.Add(1)
var query string
ui.Column(c).Fill().Padding(20).Gap(10).Children(func() {
hint := ui.Text(c, "Titles only")
in := ui.TextInput(c, &query).Label("Find").Search().DescribedBy(hint).Invalid(bad.Load())
if message.Load() {
in.ErrorMessage(ui.Text(c, "Type a word"))
}
ui.Column(c).Role(ui.RoleToolbar).Label("Tools").Orientation(ui.Vertical).Children(func() {
ui.Button(c, "Bold")
})
ui.Box(c).Size(2, 40).Role(ui.RoleSeparator).Label("Rule").Orientation(ui.Horizontal)
ui.Row(c).Gap(6).Children(func() {
ui.Text(c, "$40").Strikethrough().Role(ui.RoleDeletion)
ui.Text(c, "$30").Role(ui.RoleInsertion)
})
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Relations", Width: 400, Height: 400, 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")
}
read := func(label string) (n linux.TestAccessNode, states []string, relations map[string][]string, ok bool) {
mygo.RunOnMain(func() {
nodes, _ := linux.TestAccessibility(w.NativeHandle())
for _, node := range nodes {
if node.Label == label {
n = node
}
}
states, relations, ok = linux.TestAccessStatesAndRelations(w.NativeHandle(), label)
})
return n, states, relations, ok
}
eventually(t, "the search field described by its hint", func() bool {
n, states, rel, ok := read("Find")
return ok && n.Role == "entry" && n.Description == "Titles only" && n.Attributes["xml-roles"] == "searchbox" &&
n.Attributes["text-input-type"] == "search" && slices.Equal(rel["described-by"], []string{"Titles only"}) &&
!slices.Contains(states, "invalid-entry")
})
eventually(t, "the hint describing the field", func() bool {
_, _, rel, ok := read("Titles only")
return ok && slices.Equal(rel["description-for"], []string{"Find"})
})
eventually(t, "the toolbar running up and down", func() bool {
_, states, _, ok := read("Tools")
return ok && slices.Contains(states, "vertical") && !slices.Contains(states, "horizontal")
})
eventually(t, "the rule told it runs across", func() bool {
_, states, _, ok := read("Rule")
return ok && slices.Contains(states, "horizontal") && !slices.Contains(states, "vertical")
})
for label, role := range map[string]string{"$40": "content deletion", "$30": "content insertion"} {
eventually(t, label+" as "+role, func() bool {
n, _, _, ok := read(label)
return ok && n.Role == role
})
}
// Invalid without a message: the state alone, the description as it
// was.
bad.Store(true)
w.Invalidate()
eventually(t, "the field invalid without a message", func() bool {
n, states, rel, ok := read("Find")
return ok && slices.Contains(states, "invalid-entry") && n.Description == "Titles only" && rel["error-message"] == nil
})
// Then with the element holding it, read first.
message.Store(true)
w.Invalidate()
eventually(t, "the field pointing at its error", func() bool {
n, _, rel, ok := read("Find")
return ok && n.Description == "Type a word\nTitles only" && slices.Equal(rel["error-message"], []string{"Type a word"})
})
eventually(t, "the error naming its field", func() bool {
_, _, rel, ok := read("Type a word")
return ok && slices.Equal(rel["error-for"], []string{"Find"})
})
// Valid again, the message points at nothing.
bad.Store(false)
w.Invalidate()
eventually(t, "the valid field", func() bool {
n, states, rel, ok := read("Find")
return ok && !slices.Contains(states, "invalid-entry") && n.Description == "Titles only" && rel["error-message"] == nil
})
}
@@ -0,0 +1,69 @@
//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"
)
// TestAccessLiveRegionAttributes reads, as Orca does through ATK, the
// object attributes of landmarks and live regions: their ARIA role in
// xml-roles, how a live region is read, and, on what is inside it, how
// the region around it is.
func TestAccessLiveRegionAttributes(t *testing.T) {
var frames atomic.Int32
w := newWindow(t, mygo.WindowOptions{Title: "Live regions", Width: 400, Height: 400, Content: ui.View(landmarksAndLiveRegions(&frames))})
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 := 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
}
for _, c := range []struct {
label string
attrs map[string]string
}{
{"Activity", map[string]string{"xml-roles": "region"}},
{"Site search", map[string]string{"xml-roles": "search"}},
{"Messages", map[string]string{"xml-roles": "log", "live": "polite", "container-live": "polite", "container-live-role": "log", "atomic": "false"}},
{"Hi", map[string]string{"container-live": "polite", "container-live-role": "log", "container-relevant": "additions text"}},
{"Time left", map[string]string{"xml-roles": "timer"}},
{"Top bar", map[string]string{"xml-roles": "banner"}},
{"Messages area", map[string]string{"xml-roles": "main"}},
{"Folders", map[string]string{"xml-roles": "complementary"}},
{"Footer", map[string]string{"xml-roles": "contentinfo"}},
{"Settings panel", map[string]string{"xml-roles": "tabpanel"}},
{"Error", map[string]string{"xml-roles": "alert", "live": "assertive", "atomic": "true"}},
{"Name is required", map[string]string{"container-live": "assertive", "container-atomic": "true"}},
} {
eventually(t, c.label+"'s attributes", func() bool {
n, ok := find(c.label)
if !ok {
return false
}
for k, v := range c.attrs {
if n.Attributes[k] != v {
return false
}
}
return true
})
}
if n, _ := find("Time left"); n.Attributes["live"] != "" || n.Attributes["container-live"] != "" {
t.Errorf("the timer is a live region: %v", n.Attributes)
}
}
+145
View File
@@ -0,0 +1,145 @@
//go:build !js
package e2e
import (
"runtime"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// landmarksAndLiveRegions shows a region, a search landmark, an article,
// a log, a timer, an alert, a tab panel, the main, banner, content information and complementary landmarks, a toolbar's rule and a table's row header, labelled to be found but for
// the rule, which is the toolbar's only child but its buttons.
func landmarksAndLiveRegions(frames *atomic.Int32) func(c *ui.Context) {
return func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Fill().Padding(20).Gap(10).Children(func() {
ui.Column(c).Role(ui.RoleRegion).Label("Activity").Children(func() {
ui.Text(c, "Ann joined")
})
ui.Row(c).Role(ui.RoleSearch).Label("Site search").Children(func() {
ui.Button(c, "Go")
})
ui.Column(c).Role(ui.RoleArticle).Label("Post by Ann").Children(func() {
ui.Text(c, "Shipped the beta")
})
ui.Column(c).Role(ui.RoleLog).Label("Messages").Children(func() {
ui.Text(c, "Hi")
})
ui.Row(c).Role(ui.RoleTimer).Label("Time left").Children(func() {
ui.Text(c, "5:00")
})
ui.Column(c).Role(ui.RoleAlert).Label("Error").Children(func() {
ui.Text(c, "Name is required")
})
ui.Row(c).Role(ui.RoleToolbar).Label("Format").Height(24).Gap(4).Children(func() {
ui.Button(c, "Bold")
ui.Divider(c).Role(ui.RoleSeparator)
ui.Button(c, "Left")
})
ui.Row(c).Role(ui.RoleBanner).Label("Top bar").Children(func() {
ui.Text(c, "Mail")
})
ui.Column(c).Role(ui.RoleMain).Label("Messages area").Children(func() {
ui.Text(c, "Hello")
})
ui.Column(c).Role(ui.RoleComplementary).Label("Folders").Children(func() {
ui.Text(c, "Inbox")
})
ui.Row(c).Role(ui.RoleContentInfo).Label("Footer").Children(func() {
ui.Text(c, "3 unread")
})
ui.Column(c).Role(ui.RoleTabPanel).Label("Settings panel").Children(func() {
ui.Text(c, "Volume")
})
ui.Column(c).Role(ui.RoleTable).Label("Prices").Children(func() {
ui.Row(c).Role(ui.RoleRow).Children(func() {
ui.Text(c, "Apples").Role(ui.RoleRowHeader)
ui.Text(c, "3").Role(ui.RoleCell)
})
})
})
}
}
// TestAccessLandmarksAndLiveRegions reads, as screen readers do, the
// roles WAI-ARIA's Core Accessibility API Mappings give a region, a
// search landmark, an article, a log, a timer, an alert, a separator and
// a row header on each platform.
func TestAccessLandmarksAndLiveRegions(t *testing.T) {
var frames atomic.Int32
w := newWindow(t, mygo.WindowOptions{Title: "Landmarks and live regions", Width: 400, Height: 400, Content: ui.View(landmarksAndLiveRegions(&frames))})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
if _, ok := accessibility(w); !ok {
t.Skip("accessibility automation not available on this platform")
}
// The roles by label; the separator, unlabelled, by "".
want := map[string]map[string]string{
"darwin": {"Activity": "AXGroup/AXLandmarkRegion", "Site search": "AXGroup/AXLandmarkSearch",
"Post by Ann": "AXGroup/AXDocumentArticle", "Messages": "AXGroup/AXApplicationLog", "Time left": "AXGroup/AXApplicationTimer",
"Error": "AXGroup/AXApplicationAlert", "": "AXSplitter", "Apples": "AXCell", "Settings panel": "AXGroup",
"Top bar": "AXGroup/AXLandmarkBanner", "Messages area": "AXGroup/AXLandmarkMain", "Folders": "AXGroup/AXLandmarkComplementary", "Footer": "AXGroup/AXLandmarkContentInfo"},
"linux": {"Activity": "landmark", "Site search": "landmark", "Post by Ann": "article", "Messages": "log", "Time left": "timer", "Error": "notification", "": "separator",
"Apples": "row header", "Settings panel": "scroll pane",
"Top bar": "landmark", "Messages area": "landmark", "Folders": "landmark", "Footer": "landmark"},
"windows": {"Activity": "Group", "Site search": "Group", "Post by Ann": "Group", "Messages": "Group", "Time left": "Group", "Error": "Group", "": "Separator",
"Apples": "HeaderItem", "Settings panel": "Pane",
"Top bar": "Group", "Messages area": "Group", "Folders": "Group", "Footer": "Group"},
}[runtime.GOOS]
if want == nil {
t.Skipf("no roles to expect on %s", runtime.GOOS)
}
for label, role := range want {
eventually(t, label+" as "+role, func() bool {
nodes, _ := accessibility(w)
for _, n := range nodes {
if n.label == label && n.role == role {
return true
}
}
return false
})
}
}
// TestAccessDeletionInsertion reads, as screen readers do, the roles
// Core-AAM gives ARIA's deletion and insertion, an old price struck out
// and the new one, on each platform.
func TestAccessDeletionInsertion(t *testing.T) {
var frames atomic.Int32
view := func(c *ui.Context) {
frames.Add(1)
ui.Row(c).Fill().Padding(20).Gap(6).Children(func() {
ui.Text(c, "$40").Strikethrough().Role(ui.RoleDeletion)
ui.Text(c, "$30").Role(ui.RoleInsertion)
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Deletion and insertion", Width: 300, 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")
}
want := map[string]map[string]string{
"darwin": {"$40": "AXGroup/AXDeleteStyleGroup", "$30": "AXGroup/AXInsertStyleGroup"},
"linux": {"$40": "content deletion", "$30": "content insertion"},
"windows": {"$40": "Text", "$30": "Text"},
}[runtime.GOOS]
if want == nil {
t.Skipf("no roles to expect on %s", runtime.GOOS)
}
for label, role := range want {
eventually(t, label+" as "+role, func() bool {
nodes, _ := accessibility(w)
for _, n := range nodes {
if n.label == label && n.role == role {
return true
}
}
return false
})
}
}
@@ -0,0 +1,71 @@
//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"
)
// TestAccessBusyAndCurrent reads, as Orca does through ATK, a region
// loading, busy until a press loads it, and a breadcrumb trail: a landmark
// whose xml-roles is navigation, its last crumb the current page, active.
func TestAccessBusyAndCurrent(t *testing.T) {
var frames atomic.Int32
loading := true
view := func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Fill().Padding(20).Gap(10).Children(func() {
chosen := 0
ui.Breadcrumbs(c, []string{"Home", "Settings"}, &chosen).Label("Path")
if ui.Button(c, "Load").Clicked() {
loading = false
}
ui.Column(c).Label("Messages").Busy(loading).Children(func() {
ui.Text(c, "Inbox")
})
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Busy and current", 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")
}
eventually(t, "the navigation landmark", func() bool {
n, ok := find("Path")
return ok && n.Role == "landmark" && n.Attributes["xml-roles"] == "navigation"
})
eventually(t, "the current page", func() bool {
n, ok := find("Settings")
return ok && n.Active && n.Attributes["current"] == "page"
})
if n, _ := find("Home"); n.Active || n.Attributes["current"] != "" {
t.Errorf("the link home is current: %+v", n)
}
eventually(t, "the busy region", func() bool {
n, ok := find("Messages")
return ok && n.Busy
})
if !accessPerform(w, "Load", "press", "") {
t.Fatal("cannot press the button")
}
eventually(t, "the region loaded", func() bool {
n, ok := find("Messages")
return ok && !n.Busy
})
}
@@ -0,0 +1,80 @@
//go:build darwin && !ios
package e2e
import (
"slices"
"strings"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// TestAccessRoleDescriptionPopupSelected reads, as VoiceOver does, a
// carousel's role description, a button opening a list box, and a
// grid's day chosen without painting it.
func TestAccessRoleDescriptionPopupSelected(t *testing.T) {
var frames atomic.Int32
view := func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Fill().Padding(20).Gap(10).Children(func() {
ui.Column(c).Role(ui.RoleGroup).Label("Highlights").RoleDescription("carousel")
ui.Button(c, "Fruit").HasPopup(ui.PopupListBox)
ui.Column(c).Role(ui.RoleTable).Label("November").Children(func() {
ui.Row(c).Role(ui.RoleRow).Gap(8).Children(func() {
ui.Text(c, "Day").Role(ui.RoleColumnHeader).Sort(ui.SortDescending)
ui.Text(c, "Note").Role(ui.RoleColumnHeader)
})
ui.Row(c).Role(ui.RoleRow).Gap(8).Children(func() {
ui.Text(c, "1").Role(ui.RoleCell).Checked(false)
ui.Text(c, "2").Role(ui.RoleCell).Checked(true)
})
})
})
}
w := newWindow(t, mygo.WindowOptions{Title: "States", Width: 400, Height: 300, Content: ui.View(view)})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
// The headers' roles through the newer API, which VoiceOver reads,
// as through the older one below.
for label, want := range map[string]string{"Day": "AXButton/AXSortButton", "Note": "AXCell"} {
eventually(t, label+"'s role", func() bool {
nodes, _ := accessibility(w)
return slices.ContainsFunc(nodes, func(n accessNode) bool {
return n.label == label && n.role == want
})
})
}
// VoiceOver asks for the attributes an element names, and reads a
// table's choice by its rows, as NSTableView's: the row of the chosen
// cell is chosen, and the cells say which column they are in, under
// which header. It reads no cell's AXSelected, so the chosen cell
// says it after its name. The header sorting the rows is a sort
// button, as NSTableHeaderView's.
// The ranges and arrays read as descriptions, which hold want.
for _, c := range []struct{ label, attr, want string }{
{"Highlights", "AXRoleDescription", "carousel"},
{"Fruit", "AXPopupValue", "listbox"},
{"2, selected", "AXSelected", "1"},
{"1", "AXSelected", "0"},
{"1", "AXColumnIndexRange", "{0, 1}"},
{"2, selected", "AXColumnIndexRange", "{1, 1}"},
{"2, selected", "AXRowIndexRange", "{1, 1}"},
{"1", "AXColumnHeaderUIElements", "MyGoAccessibilityElement"},
{"November", "AXSelectedCells", "MyGoAccessibilityElement"},
{"November", "AXSelectedRows", "MyGoAccessibilityElement"},
{"November", "AXColumnHeaderUIElements", "MyGoAccessibilityElement"},
{"Day", "AXRole", "AXButton"},
{"Day", "AXSubrole", "AXSortButton"},
{"Day", "AXSortDirection", "AXDescendingSortDirection"},
{"Note", "AXRole", "AXCell"},
{"Note", "AXSortDirection", "AXUnknownSortDirection"},
} {
eventually(t, c.label+"'s "+c.attr, func() bool {
v, _, named, ok := axAttribute(w, c.label, c.attr)
partial := strings.HasSuffix(c.attr, "Range") || strings.HasSuffix(c.attr, "s")
return ok && (named || c.attr == "AXRole" || c.attr == "AXSubrole") && (v == c.want || partial && strings.Contains(v, c.want))
})
}
}
@@ -0,0 +1,95 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"slices"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/ui"
)
// TestAccessControlsPopupSortSelected reads, as Orca does through ATK, a
// carousel's role description, a disclosure button controlling the region
// it opens (controller-for, and controlled-by back), a button opening a
// list box (has-popup), a column sorted in another order, and a grid's
// day chosen without painting it (selected, not checked), with Checked
// or AccessSelected.
func TestAccessControlsPopupSortSelected(t *testing.T) {
var frames atomic.Int32
view := func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Fill().Padding(20).Gap(10).Children(func() {
ui.Column(c).Role(ui.RoleGroup).Label("Highlights").RoleDescription("carousel")
toggle := ui.Button(c, "Details").Expanded(true)
details := ui.Column(c).Role(ui.RoleRegion).Label("More details").Children(func() {
ui.Text(c, "Shipped today")
})
toggle.Controls(details)
ui.Button(c, "Fruit").HasPopup(ui.PopupListBox)
ui.Column(c).Role(ui.RoleTable).Label("November").Children(func() {
ui.Row(c).Role(ui.RoleRow).Gap(8).Children(func() {
ui.Text(c, "Day").Role(ui.RoleColumnHeader).Sort(ui.SortOther)
})
ui.Row(c).Role(ui.RoleRow).Gap(8).Children(func() {
ui.Text(c, "1").Role(ui.RoleCell).Checked(false)
ui.Text(c, "2").Role(ui.RoleCell).Checked(true)
ui.Text(c, "3").Role(ui.RoleCell).AccessSelected(true)
ui.Text(c, "4").Role(ui.RoleCell).AccessSelected(false)
})
})
})
}
w := newWindow(t, mygo.WindowOptions{Title: "States", Width: 400, Height: 400, 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")
}
read := func(label string) (n linux.TestAccessNode, states []string, relations map[string][]string, ok bool) {
mygo.RunOnMain(func() {
nodes, _ := linux.TestAccessibility(w.NativeHandle())
for _, node := range nodes {
if node.Label == label {
n = node
}
}
states, relations, ok = linux.TestAccessStatesAndRelations(w.NativeHandle(), label)
})
return n, states, relations, ok
}
eventually(t, "the carousel", func() bool {
n, _, _, ok := read("Highlights")
return ok && n.Attributes["roledescription"] == "carousel"
})
eventually(t, "the button controlling the region", func() bool {
_, _, rel, ok := read("Details")
return ok && slices.Equal(rel["controller-for"], []string{"More details"})
})
eventually(t, "the region controlled by the button", func() bool {
_, _, rel, ok := read("More details")
return ok && slices.Equal(rel["controlled-by"], []string{"Details"})
})
eventually(t, "the button opening a list box", func() bool {
n, states, _, ok := read("Fruit")
return ok && n.Attributes["haspopup"] == "listbox" && slices.Contains(states, "has-popup")
})
eventually(t, "the column sorted otherwise", func() bool {
n, _, _, ok := read("Day")
return ok && n.Attributes["sort"] == "other"
})
eventually(t, "the day chosen", func() bool {
_, states, _, ok := read("2")
return ok && slices.Contains(states, "selectable") && slices.Contains(states, "selected") && !slices.Contains(states, "checked")
})
for _, day := range []string{"1", "4"} {
if _, states, _, _ := read(day); !slices.Contains(states, "selectable") || slices.Contains(states, "selected") {
t.Errorf("the day %s not chosen: %v", day, states)
}
}
if _, states, _, _ := read("3"); !slices.Contains(states, "selectable") || !slices.Contains(states, "selected") || slices.Contains(states, "checked") {
t.Errorf("the day 3 chosen with AccessSelected: %v", states)
}
}
+36
View File
@@ -0,0 +1,36 @@
//go:build windows
package e2e
import (
"fmt"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// TestAppFocusKeepsFront brings the app forward with the window in front
// staying there, as macOS does, rather than another of the app's windows.
func TestAppFocusKeepsFront(t *testing.T) {
var ws []*mygo.Window
for i := range 3 {
ws = append(ws, newWindow(t, mygo.WindowOptions{
Title: fmt.Sprint("Window ", i), Width: 300, Height: 200, X: 100 + 40*i, Y: 100 + 40*i,
Content: ui.View(func(c *ui.Context) { ui.Text(c, "window") }),
}))
}
for _, w := range ws {
w.Focus()
eventually(t, w.Title()+" focused", w.IsFocused)
mygo.App.Focus()
for _, other := range ws {
if other != w && other.IsFocused() {
t.Errorf("with %s in front, App.Focus brought %s forward", w.Title(), other.Title())
}
}
if !w.IsFocused() {
t.Errorf("App.Focus took the focus from %s", w.Title())
}
}
}
+165
View File
@@ -0,0 +1,165 @@
//go:build !js
package e2e
import (
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
"time"
"github.com/egoist/mygo"
)
// TestInstalledApps lists the installed apps, sorted, with names, IDs and
// paths whose icons the shell draws, and launches one where that is
// harmless: on Linux an app of a desktop entry the test adds, which leaves
// a file behind, and on Windows CI Notepad.
func TestInstalledApps(t *testing.T) {
var marker, entryID string
if runtime.GOOS == "linux" {
// GLib reads the XDG directories once: the test adds an entry only
// where the runner points them, as CI does.
data := os.Getenv("XDG_DATA_HOME")
if data == "" {
t.Log("XDG_DATA_HOME unset: not adding a desktop entry")
} else {
marker = filepath.Join(t.TempDir(), "launched")
entryID = "mygo-e2e-launcher-test.desktop"
entry := filepath.Join(data, "applications", entryID)
os.MkdirAll(filepath.Dir(entry), 0o755)
os.WriteFile(entry, []byte("[Desktop Entry]\nType=Application\nName=MyGo Launcher Test\nName[fr]=Test du lanceur\nExec=touch "+marker+"\nIcon=folder\n"), 0o644)
t.Cleanup(func() { os.Remove(entry) })
}
}
var apps []mygo.InstalledApp
eventually(t, "the installed apps", func() bool {
var err error
if apps, err = mygo.Shell.InstalledApps(); err != nil {
t.Fatal(err)
}
return len(apps) > 0 && (entryID == "" || slices.ContainsFunc(apps, func(a mygo.InstalledApp) bool { return a.ID == entryID }))
})
t.Logf("%d apps, the first %+v", len(apps), apps[0])
if !slices.IsSortedFunc(apps, func(a, b mygo.InstalledApp) int {
return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
}) {
t.Error("the apps are not sorted by name")
}
for i, a := range apps {
if a.Name == "" || a.ID == "" || a.Path == "" {
t.Errorf("app %d lacks a name, an ID or a path: %+v", i, a)
}
if runtime.GOOS != "windows" {
if _, err := os.Stat(a.Path); err != nil {
t.Errorf("%s: %v", a.Name, err)
}
}
}
for _, a := range apps[:min(len(apps), 10)] {
if _, err := mygo.Shell.FileIcon(a.Path, 32); err != nil {
t.Errorf("the icon of %s (%s): %v", a.Name, a.Path, err)
}
}
switch runtime.GOOS {
case "darwin":
i := slices.IndexFunc(apps, func(a mygo.InstalledApp) bool { return a.ID == "com.apple.finder" })
if i < 0 || apps[i].Path != "/System/Library/CoreServices/Finder.app" {
t.Errorf("Finder is not listed as itself: %v", i)
}
if slices.ContainsFunc(apps, func(a mygo.InstalledApp) bool { return strings.HasSuffix(a.Name, ".app") }) {
t.Error("a name ends with .app")
}
case "linux":
if entryID == "" {
return
}
i := slices.IndexFunc(apps, func(a mygo.InstalledApp) bool { return a.ID == entryID })
if apps[i].Name != "MyGo Launcher Test" {
t.Errorf("the entry's name is %q", apps[i].Name)
}
if err := mygo.Shell.LaunchApp(apps[i]); err != nil {
t.Fatal(err)
}
eventually(t, "the app launched", func() bool { _, err := os.Stat(marker); return err == nil })
case "windows":
if os.Getenv("GITHUB_ACTIONS") == "" {
return // not on someone's desktop
}
i := slices.IndexFunc(apps, func(a mygo.InstalledApp) bool { return strings.HasSuffix(strings.ToLower(a.ID), `\notepad.exe`) })
if i < 0 {
t.Log("no Notepad to launch")
return
}
if err := mygo.Shell.LaunchApp(apps[i]); err != nil {
t.Fatal(err)
}
eventually(t, "Notepad running", func() bool {
out, _ := exec.Command("tasklist", "/FI", "IMAGENAME eq notepad.exe").Output()
return strings.Contains(strings.ToLower(string(out)), "notepad.exe")
})
exec.Command("taskkill", "/IM", "notepad.exe", "/F").Run()
time.Sleep(100 * time.Millisecond)
}
}
// TestDefaultAppOfFiles asks for the app that opens a folder, a file
// without an extension and a file its whole name tells, which GIO knows
// from the file and not from an extension: on Linux, where the test names
// the default apps, only where the runner points the XDG directories, as
// TestInstalledApps.
func TestDefaultAppOfFiles(t *testing.T) {
data := os.Getenv("XDG_DATA_HOME")
if runtime.GOOS != "linux" || data == "" {
t.Skip("needs Linux with XDG_DATA_HOME set, to name the default apps")
}
apps := filepath.Join(data, "applications")
os.MkdirAll(apps, 0o755)
// The defaults go where no other test writes: GLib reads a mimeapps.list
// beside the entries too.
defaults := "[Default Applications]\n"
entry := func(name, mime string) string {
id := "mygo-e2e-opens-" + name + ".desktop"
os.WriteFile(filepath.Join(apps, id), []byte("[Desktop Entry]\nType=Application\nName=MyGo Opens "+name+"\nExec=true %U\nMimeType="+mime+";\n"), 0o644)
t.Cleanup(func() { os.Remove(filepath.Join(apps, id)) })
defaults += mime + "=" + id + "\n"
return id
}
folders := entry("folders", "inode/directory")
texts := entry("texts", "text/plain")
makefiles := entry("makefiles", "text/x-makefile")
os.WriteFile(filepath.Join(apps, "mimeapps.list"), []byte(defaults), 0o644)
t.Cleanup(func() { os.Remove(filepath.Join(apps, "mimeapps.list")) })
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "notes"), []byte("some words\n"), 0o644)
os.WriteFile(filepath.Join(dir, "Makefile"), []byte("all:\n\ttrue\n"), 0o644)
for _, c := range []struct{ url, id string }{
{"file://" + dir, folders},
{dir, folders},
{"file://" + dir + "/notes", texts}, // by what it holds
{"file://" + dir + "/Makefile", makefiles}, // by its whole name
{"file://" + dir + "/no/Makefile", makefiles}, // no such file: by its name
{"file://" + dir + "/no/notes.txt", texts},
} {
var app mygo.InstalledApp
var err error
ok := func() bool {
app, err = mygo.Shell.DefaultApp(c.url)
return err == nil && app.ID == c.id
}
// GLib finds the entries a moment after they are written.
for deadline := time.Now().Add(10 * time.Second); !ok() && time.Now().Before(deadline); {
time.Sleep(50 * time.Millisecond)
}
if !ok() {
t.Errorf("DefaultApp(%q) = %q, %v; want %q", c.url, app.ID, err, c.id)
}
}
}
+130
View File
@@ -0,0 +1,130 @@
//go:build !js
package e2e
import (
"os"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
)
// A page muted before its web view is made (WebView2 makes it
// asynchronously) starts muted, stays muted as it navigates, and plays
// again once unmuted. A page that plays nothing is not audible. CI's
// machines may have no audio device, so whether a page that plays is
// audible is TestPageAudible's, run by hand.
func TestPageAudioMuted(t *testing.T) {
w := newWindow(t, mygo.WindowOptions{Title: "Audio muted", Width: 300, Height: 200})
p := w.Page()
p.SetAudioMuted(true)
if !p.IsAudioMuted() {
t.Fatal("IsAudioMuted = false right after SetAudioMuted(true)")
}
p.LoadHTML(`<p>one</p>`, "")
waitFor(t, w, `document.body.textContent === "one" && document.readyState === "complete"`)
if !p.IsAudioMuted() {
t.Error("IsAudioMuted = false once the page loaded, muted before")
}
if p.IsAudible() {
t.Error("IsAudible = true for a page playing nothing")
}
p.LoadHTML(`<p>two</p>`, "")
waitFor(t, w, `document.body.textContent === "two" && document.readyState === "complete"`)
if !p.IsAudioMuted() {
t.Error("IsAudioMuted = false after a navigation")
}
// WebView2 may take a moment to settle a change that follows another
// at once (CI's Windows read false right after muting again), so
// these wait for it, and fail only if it never comes.
p.SetAudioMuted(false)
wait.Until(t, "IsAudioMuted false after SetAudioMuted(false)", func() bool { return !p.IsAudioMuted() })
p.SetAudioMuted(true)
wait.Until(t, "IsAudioMuted true after SetAudioMuted(true) again", p.IsAudioMuted)
// A burst of changes ends in the last one: WebView2 may lose or
// reorder IsMuted puts that follow each other at once.
for range 5 {
p.SetAudioMuted(false)
p.SetAudioMuted(true)
}
wait.Until(t, "IsAudioMuted true after a burst ending muted", p.IsAudioMuted)
mustEval(t, w, `1`) // a round trip, for a late put to land
time.Sleep(200 * time.Millisecond)
if !p.IsAudioMuted() {
t.Error("IsAudioMuted = false a while after a burst ending muted")
}
p.SetAudioMuted(false)
wait.Until(t, "IsAudioMuted false after unmuting a burst", func() bool { return !p.IsAudioMuted() })
mustEval(t, w, `1`)
time.Sleep(200 * time.Millisecond)
if p.IsAudioMuted() {
t.Error("IsAudioMuted = true a while after unmuting a burst")
}
}
// audiblePage loops a quiet 440 Hz tone in an <audio> element, from a WAV
// it makes, once allowed to: a page may need a click to play (autoplay
// policies), which the button takes.
const audiblePage = `<!doctype html><button id=play>Play</button><p id=state>waiting</p><script>
const rate = 8000, samples = rate;
const buf = new ArrayBuffer(44 + samples * 2), v = new DataView(buf);
const str = (o, s) => [...s].forEach((c, i) => v.setUint8(o + i, c.charCodeAt(0)));
str(0, "RIFF"); v.setUint32(4, 36 + samples * 2, true); str(8, "WAVEfmt ");
v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true);
v.setUint32(24, rate, true); v.setUint32(28, rate * 2, true); v.setUint16(32, 2, true);
v.setUint16(34, 16, true); str(36, "data"); v.setUint32(40, samples * 2, true);
for (let i = 0; i < samples; i++) v.setInt16(44 + i * 2, Math.sin(2 * Math.PI * 440 * i / rate) * 3000, true);
window.audio = new Audio(URL.createObjectURL(new Blob([buf], {type: "audio/wav"})));
audio.loop = true;
const play = () => audio.play().then(() => { document.getElementById("state").textContent = "playing"; }, (e) => { document.getElementById("state").textContent = "blocked: " + e.name; });
document.getElementById("play").onclick = play;
play();
</script>`
// A page playing sound is audible, tells it, and stops being audible once
// it stops. It needs an audio device, so it runs only with
// MYGO_E2E_AUDIO=1, by hand: listen for a quiet tone that goes silent for
// the muted part, and click Play if the page is not allowed to play by
// itself.
func TestPageAudible(t *testing.T) {
if os.Getenv("MYGO_E2E_AUDIO") != "1" {
t.Skip("plays sound: set MYGO_E2E_AUDIO=1 on a machine with an audio device")
}
w := newWindow(t, mygo.WindowOptions{Title: "Audible", Width: 300, Height: 200})
p := w.Page()
changes := make(chan bool, 64) // listeners must not block
defer p.OnAudibleChanged(func(audible bool) { changes <- audible })()
p.LoadHTML(audiblePage, "")
t.Log("a quiet tone should play; click Play in the window if it says blocked")
waitFor(t, w, `document.getElementById("state").textContent === "playing"`)
if !wait.For(t, "the page playing", changes) || !p.IsAudible() {
t.Fatalf("the page playing: not audible (IsAudible = %v)", p.IsAudible())
}
t.Log("muted: the tone should stop for a while")
p.SetAudioMuted(true)
if !p.IsAudioMuted() {
t.Error("IsAudioMuted = false after SetAudioMuted(true)")
}
t.Logf("IsAudible while muted: %v", p.IsAudible())
listen() // for the tester's ears only: nothing waits on it
p.SetAudioMuted(false)
t.Log("unmuted: the tone should play again")
listen()
mustEval(t, w, `audio.pause()`)
t.Log("paused: the tone should stop")
// Muting may have told changes too, which come first.
for {
audible := wait.For(t, "the page stopping", changes)
if !audible && !p.IsAudible() {
break
}
}
}
// listen gives the tester of TestPageAudible time to hear the page.
func listen() { time.Sleep(2 * time.Second) }
+229
View File
@@ -0,0 +1,229 @@
//go:build !js
package e2e
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"math/big"
"net"
"net/http"
"net/http/httptest"
"net/url"
"runtime"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
)
// offer sends v on ch unless ch is full: handlers run on the main thread,
// which must not wait for the test, and macOS asks once per connection.
func offer[T any](ch chan T, v T) {
select {
case ch <- v:
default:
}
}
// basicAuthServer serves a page to alice with her password, and its
// refusal to the others.
func basicAuthServer(realm string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if user, pass, ok := r.BasicAuth(); ok && user == "alice" && pass == "s3cret" {
fmt.Fprintf(w, "<!doctype html><title>welcome %s</title>", user)
return
}
w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, "<!doctype html><title>denied</title>")
}))
}
func TestAuthHandler(t *testing.T) {
server := basicAuthServer("mygo e2e")
defer server.Close()
u, _ := url.Parse(server.URL)
port, _ := strconv.Atoi(u.Port())
w := newWindow(t, mygo.WindowOptions{Title: "Auth", Width: 300, Height: 200})
asked := make(chan mygo.AuthRequest, 8)
w.Page().SetAuthHandler(func(req mygo.AuthRequest) mygo.AuthResponse {
offer(asked, req)
return mygo.AuthResponse{Username: "alice", Password: "s3cret"}
})
if err := w.Page().LoadURL(server.URL + "/"); err != nil {
t.Fatal(err)
}
req := wait.For(t, "the auth handler", asked)
want := mygo.AuthRequest{Host: "127.0.0.1", Port: port, Realm: "mygo e2e", Scheme: "basic"}
if req != want {
t.Errorf("request = %+v, want %+v", req, want)
}
waitFor(t, w, `document.title === "welcome alice"`)
// An empty answer cancels: the page gets the server's refusal.
other := basicAuthServer("elsewhere")
defer other.Close()
w.Page().SetAuthHandler(func(req mygo.AuthRequest) mygo.AuthResponse {
offer(asked, req)
return mygo.AuthResponse{}
})
if err := w.Page().LoadURL(other.URL + "/"); err != nil {
t.Fatal(err)
}
if req := wait.For(t, "the auth handler", asked); req.Realm != "elsewhere" {
t.Errorf("request = %+v", req)
}
waitFor(t, w, `document.title === "denied"`)
}
func TestClientCertificateHandler(t *testing.T) {
cert := selfSigned(t)
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// A client without a certificate never gets here.
fmt.Fprint(w, "<!doctype html><title>mutual</title>")
}))
server.TLS = &tls.Config{Certificates: []tls.Certificate{cert}, ClientAuth: tls.RequireAnyClientCert}
server.StartTLS()
defer server.Close()
u, _ := url.Parse(server.URL)
port, _ := strconv.Atoi(u.Port())
w := newWindow(t, mygo.WindowOptions{Title: "Client certificate", Width: 300, Height: 200})
// The server's own certificate does not verify: let it through, for
// what this test asks about is the certificate the server asks of
// the client after that. A TLS exception ends the first load without
// OnDidFailLoad and reloads; count only the ends after the handler
// has been asked, which is the cancel this test is about.
w.Page().SetCertificateErrorHandler(func(mygo.CertificateError) bool { return true })
var asks atomic.Int32
asked := make(chan mygo.ClientCertificateRequest, 8)
ended := make(chan int, 8)
end := func() {
select {
case ended <- int(asks.Load()):
default:
}
}
w.Page().OnDidFailLoad(func(*mygo.LoadError) { end() })
w.Page().OnDidFinishLoad(end)
w.Page().SetClientCertificateHandler(func(req mygo.ClientCertificateRequest) mygo.ClientCertificateResponse {
asks.Add(1)
offer(asked, req)
return mygo.ClientCertificateResponse{Cancel: true}
})
if err := w.Page().LoadURL(server.URL + "/"); err != nil {
t.Fatal(err)
}
req := wait.For(t, "the client certificate handler", asked)
if req.Host != "127.0.0.1" || req.Port != port || req.IsProxy {
t.Errorf("request = %+v", req)
}
// WebKitGTK lists no certificates to offer.
if runtime.GOOS == "linux" && len(req.Certificates) != 0 {
t.Errorf("linux offered certificates: %+v", req.Certificates)
}
// Canceling refuses the challenge: the load ends without the page.
// On Linux that end is a cancellation, which OnDidFinishLoad reports
// and OnDidFailLoad does not; elsewhere it fails the load.
want := int(asks.Load())
for {
n := wait.For(t, "the load to end after a cancel", ended)
if n >= want {
break
}
}
if title := mustEval(t, w, `document.title`); title == "mutual" {
t.Fatal("the page loaded although the handler canceled")
}
}
// selfSigned returns a certificate for 127.0.0.1 that no one issued.
func selfSigned(t *testing.T) tls.Certificate {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(time.Now().UnixNano()),
Subject: pkix.Name{CommonName: "mygo e2e"},
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}
}
func TestCertificateErrorHandler(t *testing.T) {
cert := selfSigned(t)
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "<!doctype html><title>trusted</title>")
}))
server.TLS = &tls.Config{Certificates: []tls.Certificate{cert}}
server.StartTLS()
defer server.Close()
// A window for each answer: after a failed load, WebKitGTK loads
// its error page, which would replace the next load.
open := func(handler func(mygo.CertificateError) bool) (*mygo.Window, chan *mygo.LoadError) {
t.Helper()
w := newWindow(t, mygo.WindowOptions{Title: "Certificates", Width: 300, Height: 200})
failed := make(chan *mygo.LoadError, 8)
w.Page().OnDidFailLoad(func(e *mygo.LoadError) { offer(failed, e) })
if handler != nil {
w.Page().SetCertificateErrorHandler(handler)
}
if err := w.Page().LoadURL(server.URL + "/"); err != nil {
t.Fatal(err)
}
return w, failed
}
// By default the load fails.
_, failed := open(nil)
if e := wait.For(t, "the load to fail without a handler", failed); !strings.HasPrefix(e.URL, server.URL) {
t.Errorf("failed load = %+v", e)
}
// The handler is asked, and a no fails the load too.
asked := make(chan mygo.CertificateError, 8)
w, failed := open(func(e mygo.CertificateError) bool {
offer(asked, e)
return false
})
e := wait.For(t, "the certificate error handler", asked)
if e.Host != "127.0.0.1" || !strings.HasPrefix(e.URL, server.URL) || e.Error == "" {
t.Errorf("certificate error = %+v", e)
}
if !bytes.Equal(e.Certificate, cert.Certificate[0]) {
t.Error("the handler got another certificate than the server's")
}
wait.For(t, "the load to fail after the handler said no", failed)
if title := mustEval(t, w, `document.title`); title == "trusted" {
t.Fatal("the page loaded although the handler said no")
}
// A yes loads it.
w, _ = open(func(e mygo.CertificateError) bool {
return e.Host == "127.0.0.1" && bytes.Equal(e.Certificate, cert.Certificate[0])
})
waitFor(t, w, `document.title === "trusted"`)
}
+138
View File
@@ -0,0 +1,138 @@
//go:build !mygo_noinspector && !js
package e2e
import (
"bytes"
"image/png"
"os"
"path/filepath"
"strings"
"testing"
"github.com/egoist/mygo/internal/automationcli"
"github.com/egoist/mygo/internal/wait"
)
// TestAutomationCLI drives automationApp with mygo-automation's commands,
// as an agent does: it opens a session, reads the window's elements with
// refs, acts on them and reads what changed once the window settled,
// types, chooses a menu item, saves a screenshot, sees a ref go stale and
// closes the session, which leaves the app running.
func TestAutomationCLI(t *testing.T) {
app := startAutomationApp(t)
app.dial(t).Close()
dir := t.TempDir()
// run runs a command line and returns its output and exit status.
run := func(args ...string) (string, int) {
var out bytes.Buffer
args = append(args, "--session", "e2e")
code := automationcli.Run(args, strings.NewReader(""), &out, &out, automationcli.Options{Dir: dir})
return out.String(), code
}
// must runs a command line that succeeds, and checks that its output
// has the lines want, in order.
must := func(want []string, args ...string) string {
t.Helper()
out, code := run(args...)
if code != 0 {
t.Fatalf("mygo-automation %s: exit %d\n%s", strings.Join(args, " "), code, out)
}
rest := out
for _, w := range want {
i := strings.Index(rest, w+"\n")
if i < 0 || (i > 0 && rest[i-1] != '\n') {
t.Fatalf("mygo-automation %s:\n%s\nlacks the line, in order: %s", strings.Join(args, " "), out, w)
}
rest = rest[i+len(w)+1:]
}
return out
}
// --timeout 0: the window settles; how long it takes is the machine's.
settle := func(want []string, args ...string) string {
t.Helper()
return must(want, append(args, "--settle", "--timeout", "0")...)
}
must([]string{"opened " + app.path + " (session e2e)"}, "open", "--socket", app.path)
wait.Until(t, "the app's window", func() bool {
out, _ := run("windows")
return strings.HasPrefix(out, "w") && strings.Contains(out, `[content] "Automation"`)
})
must(nil, "wait", "--timeout", "0")
must([]string{
`@e1 [text] "Count: 0"`,
`@e2 [button] "Add" key=add`,
`@e3 [textField] "Name" key=name`,
}, "snapshot")
if out := must(nil, "snapshot", "-i"); strings.Contains(out, "Count") || !strings.Contains(out, `@e2 [button] "Add"`) {
t.Errorf("snapshot -i:\n%s", out)
}
// Pressing by ref and by key, as assistive technology does, and the
// counter's change once the window settled.
settle([]string{`- @e1 [text] "Count: 0"`, `+ @e1 [text] "Count: 1"`}, "press", "@e2")
settle([]string{`- @e1 [text] "Count: 1"`, `+ @e1 [text] "Count: 2"`}, "press", "key=add")
// Filling the field shows the greeting, with a ref of its own.
out := settle([]string{`- @e3 [textField] "Name" key=name`, `+ @e4 [text] "Hello, Ada"`}, "fill", "@e3", "Ada")
if !strings.Contains(out, `+ @e3 [textField] "Name" value="Ada" key=name`) {
t.Errorf("fill:\n%s", out)
}
// Clicking the field, then typing and pressing keys.
settle(nil, "click", "@e3")
settle([]string{`+ @e4 [text] "Hello, Ada L"`}, "type", " L")
settle([]string{`+ @e4 [text] "Hello, Ada "`}, "key", "Backspace")
// The greeting goes, and its ref with it: it never names what comes
// back in its place.
settle([]string{`- @e4 [text] "Hello, Ada "`}, "fill", "@e3", "")
if out, code := run("click", "@e4"); code != 1 || !strings.Contains(out, "stale ref @e4") {
t.Errorf("clicking a stale ref: exit %d\n%s", code, out)
}
settle([]string{`+ @e5 [text] "Hello, Bo"`}, "fill", "@e3", "Bo")
// A page's script, in native UI.
if out, code := run("eval", "1"); code != 1 || !strings.Contains(out, "unsupported") {
t.Errorf("eval in native UI: exit %d\n%s", code, out)
}
// The window as an image, in a file.
shot := filepath.Join(t.TempDir(), "shot.png")
must(nil, "screenshot", shot)
f, err := os.Open(shot)
if err != nil {
t.Fatal(err)
}
img, err := png.Decode(f)
f.Close()
if err != nil {
t.Fatal(err)
}
if s := img.Bounds().Size(); s.X < 200 || s.Y < 150 {
t.Errorf("the screenshot is %v", s)
}
// The application menu, where the platform lets the plugin choose.
if out, code := run("menu", "Test", "Reset", "--settle", "--timeout", "0"); code == 0 {
if !strings.Contains(out, `+ @e1 [text] "Count: 0"`) {
t.Errorf("menu Test Reset:\n%s", out)
}
} else {
t.Logf("menus cannot be chosen on this platform: %s", out)
}
// Closing the session leaves the app running.
must([]string{"closed session e2e"}, "close")
if out, code := run("snapshot"); code != 1 || !strings.Contains(out, `no session "e2e"`) {
t.Errorf("snapshot after close: exit %d\n%s", code, out)
}
select {
case err := <-app.exited:
app.ended = true
t.Fatalf("the app exited: %v", err)
default:
}
app.dial(t).Close()
}
+6
View File
@@ -0,0 +1,6 @@
//go:build mygo_noinspector && !js
package e2e
// Builds without the inspector leave plugins/automation out.
func automationApp() {}
+390
View File
@@ -0,0 +1,390 @@
//go:build !mygo_noinspector && !js
package e2e
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"image/png"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
_ "github.com/egoist/mygo/plugins/automation"
"github.com/egoist/mygo/ui"
)
// automationApp is the app TestAutomation and TestAutomationCLI drive
// from another process: a counter, a text field of native UI and a
// greeting shown while the field has text, and a menu that resets the
// counter and quits. MYGO_AUTOMATION names its socket; with
// MYGO_E2E_AUTOMATION_HIDDEN set, the window never shows.
func automationApp() {
count, name := 0, ""
var w *mygo.Window
mygo.App.SetMenu(mygo.NewMenu([]*mygo.MenuItem{{Label: "Test", Submenu: []*mygo.MenuItem{
{Label: "Reset", Click: func(*mygo.MenuItem, *mygo.Window) {
count = 0
w.Invalidate()
}},
{Label: "Quit", Click: func(*mygo.MenuItem, *mygo.Window) { mygo.App.Quit() }},
}}}))
view := func(c *ui.Context) {
ui.Column(c).Fill().Padding(20).Gap(10).Children(func() {
ui.Text(c, fmt.Sprintf("Count: %d", count))
if ui.Button(c, "Add").Key("add").Clicked() {
count++
}
c.Key("name")
ui.TextInput(c, &name).Label("Name")
if name != "" {
ui.Text(c, "Hello, "+name)
}
})
}
mygo.App.WhenReady(func() {
w = mygo.NewWindow(mygo.WindowOptions{Title: "Automation", Width: 400, Height: 300, Content: ui.View(view),
Hidden: os.Getenv("MYGO_E2E_AUTOMATION_HIDDEN") != ""})
})
if err := mygo.App.Run(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
// automationClient sends requests to an app's socket, one at a time.
type automationClient struct {
t *testing.T
conn net.Conn
r *bufio.Reader
n int
}
type automationError struct{ Code, Message string }
// call sends a request and returns its result, or its error.
func (c *automationClient) call(method string, params any) (json.RawMessage, *automationError) {
c.t.Helper()
c.n++
line, err := json.Marshal(map[string]any{"id": c.n, "method": method, "params": params})
if err != nil {
c.t.Fatal(err)
}
if _, err := c.conn.Write(append(line, '\n')); err != nil {
c.t.Fatal(err)
}
answer, err := c.r.ReadBytes('\n')
if err != nil {
c.t.Fatalf("%s: %v", method, err)
}
var res struct {
ID int
Result json.RawMessage
Error *automationError
}
if err := json.Unmarshal(answer, &res); err != nil || res.ID != c.n {
c.t.Fatalf("%s: answer %s (%v)", method, answer, err)
}
return res.Result, res.Error
}
// must is call for requests that succeed, decoding the result into v.
func (c *automationClient) must(method string, params any, v any) {
c.t.Helper()
res, e := c.call(method, params)
if e != nil {
c.t.Fatalf("%s %v: %s: %s", method, params, e.Code, e.Message)
}
if v != nil {
if err := json.Unmarshal(res, v); err != nil {
c.t.Fatalf("%s: %s: %v", method, res, err)
}
}
}
type automationNode struct {
ID, Role, Label, Value string
Key any
Bounds struct{ X, Y, Width, Height float64 }
}
// automationProc is automationApp running in a process of its own.
type automationProc struct {
path string
exited chan error
// ended is set once exited was read.
ended bool
}
// startAutomationApp starts automationApp listening on a socket of its
// own, with the environment variables of env too, and stops it when the
// test ends.
func startAutomationApp(t *testing.T, env ...string) *automationProc {
t.Helper()
dir, err := os.MkdirTemp("", "mygo-e2e")
if err != nil {
t.Fatal(err)
}
p := &automationProc{path: filepath.Join(dir, "app.sock"), exited: make(chan error, 1)}
cmd := exec.Command(os.Args[0], "-test.run=^$")
cmd.Env = append(os.Environ(), "MYGO_E2E_AUTOMATION_APP=1", "MYGO_AUTOMATION="+p.path)
cmd.Env = append(cmd.Env, env...)
var out bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &out
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
go func() { p.exited <- cmd.Wait() }()
t.Cleanup(func() {
if !p.ended {
cmd.Process.Kill()
<-p.exited
}
if t.Failed() {
t.Logf("the app's output:\n%s", out.String())
}
os.RemoveAll(dir)
})
return p
}
// dial connects to the app's socket once it listens.
func (p *automationProc) dial(t *testing.T) net.Conn {
t.Helper()
var conn net.Conn
wait.Until(t, "the app's socket", func() bool {
select {
case err := <-p.exited:
p.ended = true
t.Fatalf("the app exited: %v", err)
default:
}
var err error
conn, err = net.Dial("unix", p.path)
return err == nil
})
return conn
}
// TestAutomation drives an app of native UI from another process through
// plugins/automation's socket: it lists the windows, reads the elements,
// presses a button, clicks a text field and types, chooses menu items,
// captures the window and waits for it to settle.
func TestAutomation(t *testing.T) {
app := startAutomationApp(t)
path := app.path
conn := app.dial(t)
defer conn.Close()
if runtime.GOOS != "windows" {
if fi, err := os.Stat(path); err != nil || fi.Mode().Perm() != 0o600 {
t.Errorf("the socket's mode: %v, %v", fi.Mode(), err)
}
}
c := &automationClient{t: t, conn: conn, r: bufio.NewReader(conn)}
type window struct {
ID int
Title, Kind string
}
var win window
wait.Until(t, "the app's window", func() bool {
var res struct{ Windows []window }
c.must("windows", nil, &res)
if len(res.Windows) == 1 {
win = res.Windows[0]
}
return len(res.Windows) == 1
})
if win.Title != "Automation" || win.Kind != "content" {
t.Fatalf("window %+v", win)
}
at := map[string]any{"window": win.ID}
c.must("idle", at, nil)
tree := func() []automationNode {
var res struct{ Nodes []automationNode }
c.must("tree", at, &res)
return res.Nodes
}
find := func(role, label string) automationNode {
t.Helper()
nodes := tree()
for _, n := range nodes {
if n.Role == role && n.Label == label {
return n
}
}
t.Fatalf("no %s %q in %+v", role, label, nodes)
return automationNode{}
}
find("text", "Count: 0")
add := find("button", "Add")
if add.Key != "add" || add.ID == "" || add.Bounds.Width == 0 {
t.Errorf("the button %+v", add)
}
field := find("textField", "Name")
if field.Key != "name" {
t.Errorf("the text field %+v", field)
}
// Pressing as assistive technology does, by the key and by the ID.
c.must("act", map[string]any{"window": win.ID, "key": "add", "action": "press"}, nil)
c.must("idle", at, nil)
find("text", "Count: 1")
c.must("act", map[string]any{"window": win.ID, "id": add.ID, "action": "press"}, nil)
c.must("idle", at, nil)
find("text", "Count: 2")
// Clicking the text field, then typing into it.
b := field.Bounds
c.must("input", map[string]any{"window": win.ID, "events": []any{
map[string]any{"type": "click", "x": b.X + b.Width/2, "y": b.Y + b.Height/2},
}}, nil)
c.must("idle", at, nil)
c.must("input", map[string]any{"window": win.ID, "events": []any{map[string]any{"type": "text", "text": "Grace"}}}, nil)
c.must("idle", at, nil)
find("text", "Hello, Grace")
c.must("input", map[string]any{"window": win.ID, "events": []any{map[string]any{"type": "key", "key": "Backspace"}}}, nil)
c.must("idle", at, nil)
if f := find("textField", "Name"); f.Value != "Grac" {
t.Errorf("the text field after Backspace: %+v", f)
}
// The window as an image.
var shot struct {
PNG string
Width, Height int
}
c.must("capture", at, &shot)
data, err := base64.StdEncoding.DecodeString(shot.PNG)
if err != nil {
t.Fatal(err)
}
img, err := png.Decode(bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
if s := img.Bounds().Size(); s.X != shot.Width || s.Y != shot.Height || s.X < 200 || s.Y < 150 {
t.Errorf("the capture is %v, said %dx%d", s, shot.Width, shot.Height)
}
// What the window cannot do, and what no window can.
if _, e := c.call("eval", map[string]any{"window": win.ID, "script": "1"}); e == nil || e.Code != "unsupported" {
t.Errorf("eval in native UI: %+v", e)
}
if _, e := c.call("tree", map[string]any{"window": win.ID + 1000}); e == nil || e.Code != "no_window" {
t.Errorf("tree of no window: %+v", e)
}
if _, e := c.call("act", map[string]any{"window": win.ID, "id": "1", "action": "press"}); e == nil || e.Code != "no_element" {
t.Errorf("act on no element: %+v", e)
}
// The application menu.
if _, e := c.call("menu", map[string]any{"window": win.ID, "path": []string{"Test", "Reset"}}); e != nil {
t.Skipf("menus cannot be chosen on this platform: %s: %s", e.Code, e.Message)
}
c.must("idle", at, nil)
find("text", "Count: 0")
// Quitting closes the socket, which leaves no file. The answer may
// not come.
line, _ := json.Marshal(map[string]any{"id": 0, "method": "menu", "params": map[string]any{"window": win.ID, "path": []string{"Test", "Quit"}}})
conn.Write(append(line, '\n'))
if err := wait.For(t, "the app to quit", app.exited); err != nil {
t.Errorf("the app exited: %v", err)
}
app.ended = true
if _, err := os.Lstat(path); !os.IsNotExist(err) {
t.Errorf("the socket stays: %v", err)
}
}
// TestAutomationOutOfSight drives a window that never shows, as a window
// behind the locked screen, whose surface draws no frame until it shows
// on macOS: a press, a click, a change the app makes and a capture build
// the frame they wait for, so that the press is taken, and the tree, idle
// and the capture tell what the window shows now.
func TestAutomationOutOfSight(t *testing.T) {
if runtime.GOOS != "darwin" {
t.Skip("elsewhere a hidden window counts as one that shows, and only a minimized one as out of sight")
}
app := startAutomationApp(t, "MYGO_E2E_AUTOMATION_HIDDEN=1")
conn := app.dial(t)
defer conn.Close()
c := &automationClient{t: t, conn: conn, r: bufio.NewReader(conn)}
var win struct {
ID int
Visible bool
}
wait.Until(t, "the app's window", func() bool {
var res struct {
Windows []struct {
ID int
Visible bool
}
}
c.must("windows", nil, &res)
if len(res.Windows) == 1 {
win = res.Windows[0]
}
return len(res.Windows) == 1
})
if win.Visible {
t.Fatal("the hidden window is visible")
}
at := map[string]any{"window": win.ID}
find := func(role, label string) automationNode {
t.Helper()
var res struct{ Nodes []automationNode }
c.must("tree", at, &res)
for _, n := range res.Nodes {
if n.Role == role && n.Label == label {
return n
}
}
t.Fatalf("no %s %q in %+v", role, label, res.Nodes)
return automationNode{}
}
capture := func() string {
t.Helper()
var shot struct{ PNG string }
c.must("capture", at, &shot)
return shot.PNG
}
idle := map[string]any{"window": win.ID, "timeout": 5000}
c.must("idle", idle, nil)
add := find("button", "Add")
before := capture()
c.must("act", map[string]any{"window": win.ID, "key": "add", "action": "press"}, nil)
c.must("idle", idle, nil)
find("text", "Count: 1")
if capture() == before {
t.Error("the capture after the press shows the window as before it")
}
b := add.Bounds
c.must("input", map[string]any{"window": win.ID, "events": []any{
map[string]any{"type": "click", "x": b.X + b.Width/2, "y": b.Y + b.Height/2},
}}, nil)
c.must("idle", idle, nil)
find("text", "Count: 2")
// A change of the app's own, which asks for a frame (Window.Invalidate).
before = capture()
if _, e := c.call("menu", map[string]any{"window": win.ID, "path": []string{"Test", "Reset"}}); e != nil {
t.Fatalf("menu: %s: %s", e.Code, e.Message)
}
c.must("idle", idle, nil)
find("text", "Count: 0")
if capture() == before {
t.Error("the capture after the reset shows the window as before it")
}
}
+123
View File
@@ -0,0 +1,123 @@
//go:build !js
package e2e
import (
"context"
"encoding/json"
"os"
"os/exec"
"runtime"
"strings"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
)
// autoplayPage plays 30 seconds of silence, unmuted, as soon as it loads,
// with no user gesture, and tells in state whether play() resolved. The
// track is silent so that the test makes no sound, but it is an audio
// track all the same, which the autoplay policies decide on; they never
// look at the samples. pauses counts the pause events, as a policy that
// lets play() resolve may pause the element once it finds its sound.
const autoplayPage = `<!doctype html><p>Autoplay</p><script>
const rate = 8000, samples = rate * 30;
const buf = new ArrayBuffer(44 + samples * 2), v = new DataView(buf);
const str = (o, s) => [...s].forEach((c, i) => v.setUint8(o + i, c.charCodeAt(0)));
str(0, "RIFF"); v.setUint32(4, 36 + samples * 2, true); str(8, "WAVEfmt ");
v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true);
v.setUint32(24, rate, true); v.setUint32(28, rate * 2, true); v.setUint16(32, 2, true);
v.setUint16(34, 16, true); str(36, "data"); v.setUint32(40, samples * 2, true);
window.state = "waiting"; window.pauses = 0;
window.audio = new Audio(URL.createObjectURL(new Blob([buf], {type: "audio/wav"})));
audio.onpause = () => pauses++;
audio.play().then(() => { state = "playing"; }, (e) => { state = "blocked: " + e.name; });
</script>`
// autoplayState is what a page of autoplayPage did.
type autoplayState struct {
State string `json:"state"`
CurrentTime float64 `json:"currentTime"`
Paused bool `json:"paused"`
Muted bool `json:"muted"`
Pauses int `json:"pauses"`
}
// played reports whether the page plays its unmuted audio.
func (s autoplayState) played() bool {
return s.State == "playing" && !s.Paused && !s.Muted && s.CurrentTime >= autoplayPlayed
}
// autoplayPlayed is the time, in seconds of the track, that a playing
// page reaches, which its clock only reaches if it plays.
const autoplayPlayed = 0.5
// autoplayIn shows autoplayPage in a hidden window, which gets no user
// gesture, with autoplay, and returns what it did once play() settled and,
// had it resolved, once the audio played on or paused.
func autoplayIn(t *testing.T, autoplay mygo.Autoplay) autoplayState {
t.Helper()
w := newWindow(t, mygo.WindowOptions{Title: "Autoplay", Hidden: true, Width: 300, Height: 200,
Page: mygo.PageOptions{Autoplay: autoplay}})
w.Page().LoadHTML(autoplayPage, "")
waitFor(t, w, `window.state && state !== "waiting"`)
waitFor(t, w, `state !== "playing" || audio.paused || audio.currentTime >= 0.5`)
v, err := mygo.EvalAs[string](w.Page(), `JSON.stringify({state, currentTime: audio.currentTime, paused: audio.paused, muted: audio.muted, pauses})`)
if err != nil {
t.Fatal(err)
}
var s autoplayState
if err := json.Unmarshal([]byte(v), &s); err != nil {
t.Fatalf("%s: %v", v, err)
}
return s
}
// TestAutoplay plays audio, unmuted, from the page of a hidden window,
// which no user gesture reaches: with AutoplayAllow, play() resolves and
// the audio's clock goes on. Without it, WebKitGTK refuses the page
// (NotAllowedError); what WKWebView and WebView2 do then is only logged,
// as their policies have not been checked to refuse this page on the CI
// runners.
//
// On Windows the policy is the argument of WebView2's browser, which the
// first page decides: AutoplayAllow runs in a test process whose first
// pages ask for it, with a user data folder of its own, as a browser
// running with other arguments refuses it this process's.
func TestAutoplay(t *testing.T) {
child := os.Getenv("MYGO_E2E_AUTOPLAY") != ""
if !child {
s := autoplayIn(t, mygo.AutoplayUserGesture)
t.Logf("AutoplayUserGesture: %+v", s)
if runtime.GOOS == "linux" && (s.played() || !strings.HasPrefix(s.State, "blocked") && !s.Paused) {
t.Errorf("AutoplayUserGesture: the page played unmuted audio without a gesture: %+v", s)
}
}
if runtime.GOOS == "windows" && !child {
ctx, cancel := context.WithTimeout(t.Context(), 4*wait.Guard)
defer cancel()
data, err := os.MkdirTemp("", "mygo-autoplay")
if err != nil {
t.Fatal(err)
}
// The browser may hold the folder a moment after the test ends.
defer os.RemoveAll(data)
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestAutoplay$", "-test.v")
cmd.Env = append(os.Environ(), "MYGO_E2E_AUTOPLAY=1", "LOCALAPPDATA="+data)
out, err := cmd.CombinedOutput()
t.Logf("%s", out)
// The child's windows had the foreground, which the tests after
// expect this process's to get.
takeForeground(newWindow(t, mygo.WindowOptions{Title: "front", Width: 120, Height: 80}))
if err != nil {
t.Fatal(err)
}
return
}
s := autoplayIn(t, mygo.AutoplayAllow)
t.Logf("AutoplayAllow: %+v", s)
if !s.played() {
t.Errorf("AutoplayAllow: the page did not play unmuted audio without a gesture: %+v", s)
}
}
@@ -0,0 +1,190 @@
//go:build !js
package e2e
import (
"context"
"fmt"
"os"
"os/exec"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/ui"
)
// throttlingPage counts the ticks of a 10 ms timer and the animation
// frames, stamped with Date.now(), whose clock the pages and the test
// share.
const throttlingPage = `<!doctype html><html><body style="margin:0;height:100vh;background:#fff">
<script>
window.ticks = []; window.frames = [];
setInterval(() => ticks.push(Date.now()), 10);
(function frame() { frames.push(Date.now()); requestAnimationFrame(frame); })();
window.between = (list, from, to) => list.filter((t) => t >= from && t < to).length;
window.ready = true;
</script></body></html>`
// TestBackgroundThrottling measures the rates over throttleSpan, after
// letting the window's change settle for throttleSettle.
const (
throttleSettle = 500 * time.Millisecond
throttleSpan = 2 * time.Second
)
// throttlingPageIn shows throttlingPage with throttling in a new window,
// or in a web view in a new window of native UI, and returns the window
// and the page.
func throttlingPageIn(t *testing.T, webView bool, throttling mygo.BackgroundThrottling, x int) (*mygo.Window, *mygo.Page) {
t.Helper()
opts := mygo.WindowOptions{Title: fmt.Sprintf("Throttling %d", throttling), X: x, Y: 80, Width: 300, Height: 200}
if !webView {
opts.Page.BackgroundThrottling = throttling
w := newWindow(t, opts)
w.Page().LoadHTML(throttlingPage, "")
waitFor(t, w, "window.ready && frames.length > 2")
return w, w.Page()
}
var view atomic.Pointer[mygo.WebView]
opts.Content = ui.View(func(c *ui.Context) {
if v := view.Load(); v != nil {
ui.WebView(c, v).Fill()
}
})
w := newWindow(t, opts)
v, err := w.NewWebView(mygo.WebViewOptions{Page: mygo.PageOptions{BackgroundThrottling: throttling}})
if err != nil {
t.Fatal(err)
}
w.Update(func() { view.Store(v) })
v.Page().LoadHTML(throttlingPage, "")
waitForPage(t, v.Page(), "window.ready && frames.length > 2")
return w, v.Page()
}
// TestBackgroundThrottling hides windows (then, where the platform can,
// minimizes them, and covers them with another window) and counts how
// often the timers of their pages ran meanwhile: with ThrottlingOff they
// keep close to their rate, 100 ticks a second, where a throttled page
// gets one a second or none. A page that keeps the default is only
// logged, as the animation frames are: whether and how much a web view
// throttles varies.
func TestBackgroundThrottling(t *testing.T) {
if runtime.GOOS == "windows" && os.Getenv("MYGO_E2E_UNTHROTTLED") == "" {
// WebView2's browser takes the arguments of the first page, the
// warm-up's in this process: the test runs in one whose warm-up
// asks for them, with a user data folder of its own, as a browser
// running with other arguments refuses it this process's.
ctx, cancel := context.WithTimeout(t.Context(), 4*wait.Guard)
defer cancel()
data, err := os.MkdirTemp("", "mygo-unthrottled")
if err != nil {
t.Fatal(err)
}
// The browser may hold the folder a moment after the test ends.
defer os.RemoveAll(data)
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestBackgroundThrottling$", "-test.v")
cmd.Env = append(os.Environ(), "MYGO_E2E_UNTHROTTLED=1", "LOCALAPPDATA="+data)
out, err := cmd.CombinedOutput()
t.Logf("%s", out)
// The child's windows had the foreground, which the tests after
// expect this process's to get.
takeForeground(newWindow(t, mygo.WindowOptions{Title: "front", Width: 120, Height: 80}))
if err != nil {
t.Fatal(err)
}
return
}
type state struct {
name string
// do changes the windows, and returns what changes them back.
do func(t *testing.T, ws []*mygo.Window) (undo func())
}
states := []state{{"hidden", func(t *testing.T, ws []*mygo.Window) func() {
for _, w := range ws {
w.Hide()
}
for _, w := range ws {
eventually(t, "the window hidden", func() bool { return !w.IsVisible() })
}
return func() {
for _, w := range ws {
w.Show()
}
}
}}}
if runtime.GOOS != "linux" { // Xvfb has no window manager to minimize or stack windows
states = append(states, state{"minimized", func(t *testing.T, ws []*mygo.Window) func() {
for _, w := range ws {
w.Minimize()
}
for _, w := range ws {
eventually(t, "the window minimized", w.IsMinimized)
}
return func() {
for _, w := range ws {
w.Restore()
}
}
}}, state{"covered", func(t *testing.T, ws []*mygo.Window) func() {
d := mygo.Screen.PrimaryDisplay()
cover := mygo.NewWindow(mygo.WindowOptions{Title: "Cover", Frameless: true,
X: d.Bounds.X, Y: d.Bounds.Y, Width: d.Bounds.Width, Height: d.Bounds.Height, AlwaysOnTop: true,
Content: ui.View(func(c *ui.Context) { ui.Text(c, "Cover") })})
cover.Focus()
eventually(t, "the cover focused", cover.IsFocused)
return cover.Destroy
}})
}
for _, s := range states {
for _, webView := range []bool{false, true} {
name := s.name + "/window"
if webView {
name = s.name + "/web view"
}
t.Run(name, func(t *testing.T) {
offWin, off := throttlingPageIn(t, webView, mygo.ThrottlingOff, 80)
onWin, on := throttlingPageIn(t, webView, mygo.ThrottlingOn, 420)
ok, settings := throttlingOff(offWin, webView)
if settings == 0 && runtime.GOOS == "linux" {
t.Skip("WebKitGTK older than 2.42 has no features to turn off")
}
if settings > 0 && !ok {
t.Errorf("ThrottlingOff: the page's settings throttle it (of %d)", settings)
}
if ok, settings := throttlingOff(onWin, webView); settings > 0 && ok && runtime.GOOS != "windows" {
// On Windows, the browser's arguments are every page's.
t.Errorf("ThrottlingOn: the page's settings keep it running (of %d)", settings)
}
undo := sync.OnceFunc(s.do(t, []*mygo.Window{offWin, onWin}))
t.Cleanup(undo) // a cover must not stay over the next tests
from := time.Now().Add(throttleSettle)
to := from.Add(throttleSpan)
// Wait in the time of the unthrottled page, which goes on.
waitForPage(t, off, fmt.Sprintf("Date.now() >= %d", to.UnixMilli()))
undo()
count := func(p *mygo.Page, list string) int {
n, err := mygo.EvalAs[int](p, fmt.Sprintf("between(%s, %d, %d)", list, from.UnixMilli(), to.UnixMilli()))
if err != nil {
t.Fatal(err)
}
return n
}
waitForPage(t, on, "true") // back, it answers again
offTicks := count(off, "ticks")
t.Logf("%s for %v: ThrottlingOff %d ticks, %d frames; ThrottlingOn %d ticks, %d frames",
name, throttleSpan, offTicks, count(off, "frames"), count(on, "ticks"), count(on, "frames"))
// 10 a second: a tenth of the timer's rate, ten times a
// throttled page's.
if want := int(throttleSpan / (100 * time.Millisecond)); offTicks < want {
t.Errorf("%s with ThrottlingOff: %d ticks of a 10 ms timer in %v, want %d or more", name, offTicks, throttleSpan, want)
}
})
}
}
}
+193
View File
@@ -0,0 +1,193 @@
//go:build !js
package e2e
import (
"fmt"
"net/http"
"strconv"
"strings"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/ui"
)
// The benchmarks time what the real backend adds to the Go side that the
// root package's benchmarks measure: the webview's messages, its custom
// scheme, and opening windows. Like the tests, they need a desktop session:
//
// MYGO_E2E=1 go test -run '^$' -bench . ./internal/e2e
// Bench is the service the benchmarks' pages call.
type Bench struct{}
type BenchItem struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
Tags []string `json:"tags"`
}
func (Bench) Noop() {}
func (Bench) Items(v []BenchItem) []BenchItem { return v }
var benchTick = mygo.NewEvent[Tick]("bench:tick")
// useBench serves the benchmarks' responses: /bench/1mb is a megabyte.
func useBench(mux *http.ServeMux) {
mb := []byte(strings.Repeat("x", 1<<20))
mux.HandleFunc("/bench/1mb", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", strconv.Itoa(len(mb)))
w.Write(mb)
})
}
// benchWindow opens a visible window, as webviews in hidden ones may be
// throttled, with the page of the tests loaded.
func benchWindow(b *testing.B) *mygo.Window {
b.Helper()
w := mygo.NewWindow(mygo.WindowOptions{Title: "Bench", Width: 400, Height: 300})
b.Cleanup(w.Destroy)
if err := w.Page().LoadURL("app://localhost/"); err != nil {
b.Fatal(err)
}
waitFor(b, w, "window.run")
return w
}
// benchPage runs b.N rounds of the page's script, in which N stands for
// b.N: the page does the work, so each operation costs what it costs a
// page, without a round trip from Go.
func benchPage(b *testing.B, w *mygo.Window, script string) {
b.Helper()
b.ResetTimer()
n, err := mygo.EvalAs[int](w.Page(), "(async (N) => {"+script+"; return N})("+strconv.Itoa(b.N)+")")
b.StopTimer()
if err != nil || n != b.N {
b.Fatalf("the page ran %d of %d: %v", n, b.N, err)
}
}
// BenchmarkPageCall awaits calls of a Go method from a page, one at a
// time.
func BenchmarkPageCall(b *testing.B) {
w := benchWindow(b)
benchPage(b, w, `for (let i = 0; i < N; i++) await mygo.call("Bench.Noop")`)
}
// BenchmarkPageCallItems sends a thousand structs from a page to Go and
// gets them back.
func BenchmarkPageCallItems(b *testing.B) {
w := benchWindow(b)
benchPage(b, w, `const items = Array.from({ length: 1000 }, (_, i) => ({ id: i, title: "Item number " + i, done: i % 2 === 0, tags: ["alpha", "beta"] }));
for (let i = 0; i < N; i++) {
const got = await mygo.call("Bench.Items", items);
if (got.length !== items.length) throw new Error("got " + got.length + " items");
}`)
}
// BenchmarkPageChannel streams values from a Go method to a page through a
// channel.
func BenchmarkPageChannel(b *testing.B) {
w := benchWindow(b)
benchPage(b, w, `const ch = mygo.channel();
const done = mygo.call("Streams.Count", N, ch);
let n = 0;
for await (const v of ch) if (v !== n++) throw new Error("out of order: " + v);
await done;
if (n !== N) throw new Error("got " + n + " values")`)
}
// BenchmarkPageEvent emits events to a page, until the page has them all.
func BenchmarkPageEvent(b *testing.B) {
w := benchWindow(b)
if _, err := w.Page().Eval(`window.benchEvents = (N) => new Promise((resolve) => {
let n = 0;
const off = mygo.on("bench:tick", () => { if (++n === N) { off(); resolve(n) } });
})`); err != nil {
b.Fatal(err)
}
b.ResetTimer()
done := make(chan error, 1)
go func() {
n, err := mygo.EvalAs[int](w.Page(), "benchEvents("+strconv.Itoa(b.N)+")")
if err == nil && n != b.N {
err = fmt.Errorf("the page got %d of %d events", n, b.N)
}
done <- err
}()
// The page listens once the script above has run, which a script
// evaluated after it tells.
if _, err := w.Page().Eval("0"); err != nil {
b.Fatal(err)
}
for i := range b.N {
if err := benchTick.Emit(w, Tick{N: i}); err != nil {
b.Fatal(err)
}
}
if err := <-done; err != nil {
b.Fatal(err)
}
}
// BenchmarkPageFetch1MB fetches a megabyte from the app's custom scheme in
// a page.
func BenchmarkPageFetch1MB(b *testing.B) {
w := benchWindow(b)
b.SetBytes(1 << 20)
benchPage(b, w, `for (let i = 0; i < N; i++) {
const body = await (await fetch("/bench/1mb")).arrayBuffer();
if (body.byteLength !== 1 << 20) throw new Error("got " + body.byteLength + " bytes");
}`)
}
// BenchmarkWindowOpen opens a window loading a page from the app's scheme,
// until its DOM is ready.
func BenchmarkWindowOpen(b *testing.B) {
ready := make(chan struct{}, 1)
for b.Loop() {
w := mygo.NewWindow(mygo.WindowOptions{Title: "Bench", Width: 400, Height: 300})
w.Page().OnDOMReady(func() { ready <- struct{}{} })
if err := w.Page().LoadURL("app://localhost/"); err != nil {
b.Fatal(err)
}
select {
case <-ready:
case <-time.After(wait.Guard):
b.Fatal("the page did not load")
}
w.Destroy()
}
}
// BenchmarkContentWindowOpen opens a window of native UI, until its view
// has built the first frame.
func BenchmarkContentWindowOpen(b *testing.B) {
built := make(chan struct{}, 1)
view := func(c *ui.Context) {
ui.Box(c).Fill().Padding(16).Gap(8).Children(func() {
ui.Text(c, "Bench").FontSize(20)
for i := range 20 {
ui.Text(c, "Row "+strconv.Itoa(i))
}
})
select {
case built <- struct{}{}:
default:
}
}
for b.Loop() {
w := mygo.NewWindow(mygo.WindowOptions{Title: "Bench", Width: 400, Height: 300, Content: ui.View(view)})
select {
case <-built:
case <-time.After(wait.Guard):
b.Fatal("no frame")
}
w.Destroy()
}
}
@@ -0,0 +1,32 @@
//go:build windows
package e2e
import (
"testing"
"github.com/egoist/mygo"
win "github.com/egoist/mygo/internal/windows"
)
// WebView2's own keys, as F5 and Ctrl+R, which reload the page without
// asking OnWillNavigate, come with the inspector: a page without one, as
// in production builds, has them off, as WKWebView and WebKitGTK do.
func TestBrowserAcceleratorKeys(t *testing.T) {
for _, tc := range []struct {
devTools mygo.DevTools
want bool
}{{mygo.DevToolsDisabled, false}, {mygo.DevToolsEnabled, true}} {
w := newWindow(t, mygo.WindowOptions{Title: "Keys", Width: 300, Height: 200, Page: mygo.PageOptions{DevTools: tc.devTools}})
w.Page().LoadHTML("<p>keys</p>", "")
waitFor(t, w, "document.readyState == 'complete'")
var on, ok bool
mygo.RunOnMain(func() { on, ok = win.TestBrowserAcceleratorKeys(w.NativeHandle()) })
if !ok {
t.Skip("the WebView2 Runtime has no ICoreWebView2Settings3")
}
if on != tc.want {
t.Errorf("DevTools %v: the browser's keys are on: %v, want %v", tc.devTools, on, tc.want)
}
}
}
+174
View File
@@ -0,0 +1,174 @@
//go:build !js
package e2e
import (
"os"
"runtime"
"slices"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
)
// capturePage captures with getUserMedia() at app://localhost/capture, a
// secure context the app trusts, which gets the devices it asks for.
// capture answers "ok" or the error, and track tells the state of the
// stream's track of a kind.
const capturePage = `<!doctype html><p id=state>idle</p><script>
window.capture = async (constraints) => {
try {
window.stream = await navigator.mediaDevices.getUserMedia(constraints);
return "ok";
} catch (e) {
return "error: " + e.name + ": " + e.message;
}
};
window.track = (kind) => {
const t = window.stream && window.stream.getTracks().find((t) => t.kind === kind);
return t ? t.readyState + (t.muted ? " muted" : "") : "none";
};
</script>`
// A page that captures nothing captures no kind, and setting a kind's
// state changes nothing.
func TestCaptureStateWithoutCapture(t *testing.T) {
w := newWindow(t, mygo.WindowOptions{Title: "No capture", Width: 300, Height: 200})
p := w.Page()
changes := make(chan mygo.CaptureKind, 16) // listeners must not block
defer p.OnCaptureStateChanged(func(kind mygo.CaptureKind, _ mygo.CaptureState) { changes <- kind })()
p.LoadHTML(`<p>nothing</p>`, "")
waitFor(t, w, `document.body.textContent === "nothing" && document.readyState === "complete"`)
kinds := []mygo.CaptureKind{mygo.CaptureCamera, mygo.CaptureMicrophone, mygo.CaptureDisplay}
for _, kind := range kinds {
p.SetCaptureState(kind, mygo.CaptureMuted)
}
mustEval(t, w, `1`) // a round trip, for the changes to land
for _, kind := range kinds {
if s := p.CaptureState(kind); s != mygo.CaptureNone {
t.Errorf("CaptureState(%d) = %d for a page capturing nothing", kind, s)
}
}
select {
case kind := <-changes:
t.Errorf("a page capturing nothing changed its capture of %d", kind)
default:
}
}
// The page captures the camera and the microphone, which the app mutes,
// unmutes and stops, and the page stops the microphone itself. It runs
// with WebKit's mock devices: on Linux, and on macOS with
// MYGO_E2E_CAPTURE=1, where WebKit may yet ask the system; WebView2 tells
// no capture.
func TestCaptureState(t *testing.T) {
if runtime.GOOS == "darwin" && os.Getenv("MYGO_E2E_CAPTURE") != "1" {
t.Skip("captures WebKit's mock devices: set MYGO_E2E_CAPTURE=1")
}
w := newWindow(t, mygo.WindowOptions{Title: "Capture", Width: 300, Height: 200})
if !mockCapture(w) {
t.Skip("no mock capture devices")
}
p := w.Page()
type change struct {
kind mygo.CaptureKind
state mygo.CaptureState
}
changes := make(chan change, 64) // listeners must not block
defer p.OnCaptureStateChanged(func(kind mygo.CaptureKind, s mygo.CaptureState) { changes <- change{kind, s} })()
// told waits until the last change listeners heard of kind is to s,
// and CaptureState says so too: a change on the way, as SetAudioMuted
// on macOS mutes the camera with the microphone and unmutes it again,
// may be heard after the one before it is done. The changes of other
// kinds, which may come first, are kept for later.
var heard []change
told := func(what string, kind mygo.CaptureKind, s mygo.CaptureState) {
t.Helper()
for {
last := -1
for i, c := range heard {
if c.kind == kind {
last = i
}
}
if last >= 0 && heard[last].state == s && p.CaptureState(kind) == s {
heard = slices.DeleteFunc(heard, func(c change) bool { return c.kind == kind })
break
}
heard = append(heard, wait.For(t, what, changes))
}
}
if err := p.LoadURL("app://localhost/capture"); err != nil {
t.Fatal(err)
}
waitFor(t, w, `location.pathname === "/capture" && window.capture`)
ctx := wait.Context(t)
if got, err := p.EvalContext(ctx, `capture({audio: true, video: true})`); err != nil || got != "ok" {
info := mustEval(t, w, `[isSecureContext, typeof navigator.mediaDevices].join(" ")`)
t.Skipf("the page can't capture: %v %v (secure context, navigator.mediaDevices: %v)", got, err, info)
}
told("the camera capturing", mygo.CaptureCamera, mygo.CaptureActive)
told("the microphone capturing", mygo.CaptureMicrophone, mygo.CaptureActive)
if s := p.CaptureState(mygo.CaptureDisplay); s != mygo.CaptureNone {
t.Errorf("CaptureState(CaptureDisplay) = %d without getDisplayMedia()", s)
}
p.SetCaptureState(mygo.CaptureMicrophone, mygo.CaptureMuted)
told("the microphone muted", mygo.CaptureMicrophone, mygo.CaptureMuted)
waitFor(t, w, `track("audio") === "live muted"`)
if s := p.CaptureState(mygo.CaptureCamera); s != mygo.CaptureActive {
t.Errorf("muting the microphone: the camera %d", s)
}
// Muting the page's sound keeps the microphone muted, and the camera
// live. Muting the camera next tells it once the page took both.
p.SetAudioMuted(true)
p.SetCaptureState(mygo.CaptureCamera, mygo.CaptureMuted)
told("the camera muted", mygo.CaptureCamera, mygo.CaptureMuted)
if s := p.CaptureState(mygo.CaptureMicrophone); s != mygo.CaptureMuted {
t.Errorf("SetAudioMuted(true) unmuted the microphone: %d", s)
}
p.SetCaptureState(mygo.CaptureCamera, mygo.CaptureActive)
told("the camera unmuted", mygo.CaptureCamera, mygo.CaptureActive)
p.SetAudioMuted(false)
p.SetCaptureState(mygo.CaptureCamera, mygo.CaptureMuted)
told("the camera muted again", mygo.CaptureCamera, mygo.CaptureMuted)
if s := p.CaptureState(mygo.CaptureMicrophone); s != mygo.CaptureMuted {
t.Errorf("SetAudioMuted(false) unmuted the microphone: %d", s)
}
p.SetCaptureState(mygo.CaptureCamera, mygo.CaptureActive)
told("the camera unmuted again", mygo.CaptureCamera, mygo.CaptureActive)
// So does a burst of them, whose changes WebKit may tell on the way.
for range 5 {
p.SetAudioMuted(true)
p.SetAudioMuted(false)
}
p.SetCaptureState(mygo.CaptureCamera, mygo.CaptureMuted)
told("the camera muted after a burst", mygo.CaptureCamera, mygo.CaptureMuted)
if s := p.CaptureState(mygo.CaptureMicrophone); s != mygo.CaptureMuted {
t.Errorf("a burst of SetAudioMuted unmuted the microphone: %d", s)
}
p.SetCaptureState(mygo.CaptureCamera, mygo.CaptureActive)
told("the camera unmuted after a burst", mygo.CaptureCamera, mygo.CaptureActive)
p.SetCaptureState(mygo.CaptureMicrophone, mygo.CaptureActive)
told("the microphone unmuted", mygo.CaptureMicrophone, mygo.CaptureActive)
waitFor(t, w, `track("audio") === "live"`)
p.SetCaptureState(mygo.CaptureCamera, mygo.CaptureNone)
told("the camera stopped", mygo.CaptureCamera, mygo.CaptureNone)
waitFor(t, w, `track("video") === "ended"`)
if s := p.CaptureState(mygo.CaptureMicrophone); s != mygo.CaptureActive {
t.Errorf("stopping the camera: the microphone %d", s)
}
p.SetCaptureState(mygo.CaptureCamera, mygo.CaptureMuted) // the page captures none
mustEval(t, w, `stream.getAudioTracks()[0].stop()`)
told("the page stopping the microphone", mygo.CaptureMicrophone, mygo.CaptureNone)
// The page captures the camera again, unmuted.
if got, err := p.EvalContext(ctx, `capture({video: true})`); err != nil || got != "ok" {
t.Fatalf("capturing again: %v %v", got, err)
}
told("the camera capturing again", mygo.CaptureCamera, mygo.CaptureActive)
}
+65
View File
@@ -0,0 +1,65 @@
//go:build !js
package e2e
import (
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// TestContentPolylineFrames checks continuous GPU drawing, idle and restart.
func TestContentPolylineFrames(t *testing.T) {
var frames atomic.Int32
var moving atomic.Bool
moving.Store(true)
w := newWindow(t, mygo.WindowOptions{Title: "Polyline frames", Width: 400, Height: 300, Content: ui.View(func(c *ui.Context) {
if moving.Load() {
c.AnimationFrame()
}
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255)).Draw(func(p *ui.Painter, r ui.Rect) {
p.StrokePolyline([][2]float32{{20, 30}, {60, 90}, {100, 30}, {140, 90}}, 3, ui.RGB(20, 60, 230))
frames.Add(1)
})
})})
eventually(t, "continuous frames", func() bool { return frames.Load() >= 10 })
moving.Store(false)
w.Invalidate()
time.Sleep(300 * time.Millisecond)
before := frames.Load()
time.Sleep(100 * time.Millisecond)
if frames.Load() != before {
t.Fatal("idle chart keeps drawing")
}
if how, pix, _, _, ok := glSurface(w); ok && how == "opengl" {
ink := 0
for i := 0; i+3 < len(pix); i += 4 {
if pix[i] > 180 && pix[i+2] < 120 {
ink++
}
}
if ink < 150 {
t.Fatal("idle GPU texture lost the line", ink)
}
}
moving.Store(true)
w.Invalidate()
eventually(t, "frames after idle", func() bool { return frames.Load() >= before+10 })
}
// TestContentWindowAnimationFrames checks that frames a frame asks for as
// it is drawn keep coming. Named for the CI step that draws native UI with
// OpenGL: on Linux the GtkGLArea renders them, and a render asked for
// within its render signal used to be lost after the first.
func TestContentWindowAnimationFrames(t *testing.T) {
var frames atomic.Int32
newWindow(t, mygo.WindowOptions{Title: "Animation frames", Width: 400, Height: 300, Content: ui.View(func(c *ui.Context) {
c.AnimationFrame()
frames.Add(1)
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255))
})})
eventually(t, "frames while animating", func() bool { return frames.Load() >= 30 })
}
@@ -0,0 +1,279 @@
//go:build darwin && !ios
package e2e
import (
"os"
"slices"
"strconv"
"strings"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/darwin"
)
// inFrontOf reports whether a shows in front of b.
func inFrontOf(a, b *mygo.Window) bool {
var order []uintptr
mygo.RunOnMain(func() { order = darwin.TestWindowOrder() })
i, j := slices.Index(order, a.NativeHandle()), slices.Index(order, b.NativeHandle())
return i >= 0 && j >= 0 && i < j
}
// pointFromEnv reads the point "x,y" of an environment variable, which
// places the windows of the child window tests where the person running
// them wants them, on a display of their choice.
func pointFromEnv(t *testing.T, name string) (p mygo.Point, ok bool) {
t.Helper()
s := os.Getenv(name)
if s == "" {
return mygo.Point{}, false
}
xs, ys, found := strings.Cut(s, ",")
x, errX := strconv.Atoi(strings.TrimSpace(xs))
y, errY := strconv.Atoi(strings.TrimSpace(ys))
if !found || errX != nil || errY != nil {
t.Fatalf("%s=%q, want x,y", name, s)
}
return mygo.Point{X: x, Y: y}, true
}
// childWindowsOrigin is where the child window tests put their first
// window, each next one 40 pixels further right and down:
// MYGO_E2E_ORIGIN=x,y, or near the top-left of the primary display's work
// area.
func childWindowsOrigin(t *testing.T) mygo.Point {
t.Helper()
if p, ok := pointFromEnv(t, "MYGO_E2E_ORIGIN"); ok {
return p
}
work := mygo.Screen.PrimaryDisplay().WorkArea
return mygo.Point{X: work.X + 80, Y: work.Y + 80}
}
// TestChildWindowAboveRaisedParent raises a child window's parent, which
// AppKit orders in front of the child, as it does when the parent is
// clicked: the child goes back above it, the key parent's too.
func TestChildWindowAboveRaisedParent(t *testing.T) {
o := childWindowsOrigin(t)
parent := newWindow(t, mygo.WindowOptions{Title: "Raised parent", Width: 500, Height: 400, X: o.X, Y: o.Y})
child := newWindow(t, mygo.WindowOptions{Title: "Child of the raised parent", Parent: parent, Width: 260, Height: 200, X: o.X + 40, Y: o.Y + 40})
waitOnScreen(child)
eventually(t, "the child above its parent", func() bool { return inFrontOf(child, parent) })
parent.Focus()
eventually(t, "the parent focused", parent.IsFocused)
eventually(t, "the child above its focused parent", func() bool { return inFrontOf(child, parent) })
parent.Focus() // the key window already
eventually(t, "the child above its parent raised again", func() bool { return inFrontOf(child, parent) })
if !parent.IsFocused() {
t.Error("the parent lost the keyboard to its child")
}
}
// TestChildWindowsOrderByFocus shows two child windows of a window, the
// second above the first, and focuses the first: it comes above the
// second, as any window the user clicks does, and both stay above their
// parent.
func TestChildWindowsOrderByFocus(t *testing.T) {
o := childWindowsOrigin(t)
parent := newWindow(t, mygo.WindowOptions{Title: "Children's parent", Width: 500, Height: 400, X: o.X, Y: o.Y})
first := newWindow(t, mygo.WindowOptions{Title: "First child", Parent: parent, Width: 260, Height: 200, X: o.X + 40, Y: o.Y + 40})
second := newWindow(t, mygo.WindowOptions{Title: "Second child", Parent: parent, Width: 260, Height: 200, X: o.X + 80, Y: o.Y + 80})
waitOnScreen(first)
waitOnScreen(second)
eventually(t, "the second child above the first", func() bool { return inFrontOf(second, first) })
first.Focus()
eventually(t, "the first child focused", first.IsFocused)
eventually(t, "the first child above the second", func() bool { return inFrontOf(first, second) })
if !inFrontOf(first, parent) || !inFrontOf(second, parent) {
t.Error("a child window is no longer above its parent")
}
// The parent raised keeps its children in the order they are in.
parent.Focus()
eventually(t, "both children above their raised parent, the first in front", func() bool {
return inFrontOf(first, second) && inFrontOf(second, parent)
})
second.Focus()
eventually(t, "the second child above the first again", func() bool { return inFrontOf(second, first) })
}
// TestChildWindowHidesWithParent miniaturizes and hides a child window's
// parent, which hides the child, and restores and shows it, which shows
// the child again above it. A child hidden by itself stays hidden.
func TestChildWindowHidesWithParent(t *testing.T) {
o := childWindowsOrigin(t)
parent := newWindow(t, mygo.WindowOptions{Title: "Parent hiding", Width: 400, Height: 300, X: o.X, Y: o.Y})
child := newWindow(t, mygo.WindowOptions{Title: "Child hiding with its parent", Parent: parent, Width: 240, Height: 180, X: o.X + 40, Y: o.Y + 40})
hidden := newWindow(t, mygo.WindowOptions{Title: "Child hidden by itself", Parent: parent, Width: 240, Height: 180, X: o.X + 80, Y: o.Y + 80})
waitOnScreen(child)
waitOnScreen(hidden)
hidden.Hide()
parent.Minimize()
eventually(t, "the parent minimized", parent.IsMinimized)
eventually(t, "the child hidden with its minimized parent", func() bool { return !child.IsVisible() })
parent.Restore()
eventually(t, "the child back above its restored parent", func() bool { return child.IsVisible() && inFrontOf(child, parent) })
parent.Hide()
eventually(t, "the child hidden with its parent", func() bool { return !child.IsVisible() })
parent.Show()
eventually(t, "the child back above its parent", func() bool { return child.IsVisible() && inFrontOf(child, parent) })
if hidden.IsVisible() {
t.Error("the child hidden by itself showed with its parent")
}
}
// TestChildWindowOnAnotherDisplay moves a child window to another display,
// where it stays, showing, rather than being pulled back to its parent's
// or ordered out, and goes above its parent as the parent is raised. It
// needs two displays; MYGO_E2E_OTHER_DISPLAY=x,y is where on the other
// one the child goes, else near the top-left of the work area of a display
// that is not the parent's.
func TestChildWindowOnAnotherDisplay(t *testing.T) {
displays := mygo.Screen.Displays()
if len(displays) < 2 {
t.Skip("one display")
}
o := childWindowsOrigin(t)
parent := newWindow(t, mygo.WindowOptions{Title: "Parent on the first display", Width: 400, Height: 300, X: o.X, Y: o.Y})
child := newWindow(t, mygo.WindowOptions{Title: "Child moving across displays", Parent: parent, Width: 240, Height: 180, X: o.X + 40, Y: o.Y + 40})
waitOnScreen(child)
home := mygo.Screen.DisplayMatching(parent.Bounds())
there, ok := pointFromEnv(t, "MYGO_E2E_OTHER_DISPLAY")
if !ok {
// The first display that is not the parent's, which need not be
// the primary one, nor the first listed.
i := slices.IndexFunc(displays, func(d mygo.Display) bool { return d.ID != home.ID })
work := displays[i].WorkArea
there = mygo.Point{X: work.X + 60, Y: work.Y + 60}
}
other := mygo.Screen.DisplayMatching(mygo.Rectangle{X: there.X, Y: there.Y, Width: 240, Height: 180})
if other.ID == home.ID {
t.Fatalf("the other display's point %+v is on the parent's display %d", there, home.ID)
}
child.SetPosition(there.X, there.Y)
want := mygo.Rectangle{X: there.X, Y: there.Y, Width: child.Bounds().Width, Height: child.Bounds().Height}
eventually(t, "the child at its place on the other display", func() bool { return child.Bounds() == want })
waitOnScreen(child)
parent.Focus()
eventually(t, "the child above its raised parent", func() bool { return inFrontOf(child, parent) })
if b := child.Bounds(); b != want {
t.Errorf("the child moved to %+v as its parent was raised, want %+v", b, want)
}
if d := mygo.Screen.DisplayMatching(child.Bounds()); d.ID != other.ID {
t.Errorf("the child is on display %d, want the other one, %d", d.ID, other.ID)
}
if !child.IsVisible() {
t.Error("the child on the other display was ordered out")
}
}
// TestChildPanelAboveRaisedParent raises the parent of a child window that
// is a panel (WindowOptions.Panel), which NSApp's orderedWindows leaves
// out: it goes back above its parent too, and hides and shows with it.
func TestChildPanelAboveRaisedParent(t *testing.T) {
o := childWindowsOrigin(t)
parent := newWindow(t, mygo.WindowOptions{Title: "Child panel's parent", Width: 500, Height: 400, X: o.X, Y: o.Y})
panel := newWindow(t, mygo.WindowOptions{Title: "Child panel", Parent: parent, Panel: true, Width: 260, Height: 200, X: o.X + 40, Y: o.Y + 40})
waitOnScreen(panel)
eventually(t, "the panel above its parent", func() bool { return inFrontOf(panel, parent) })
parent.Focus()
eventually(t, "the parent focused", parent.IsFocused)
eventually(t, "the panel above its raised parent", func() bool { return inFrontOf(panel, parent) })
parent.Hide()
eventually(t, "the panel hidden with its parent", func() bool { return !panel.IsVisible() })
parent.Show()
eventually(t, "the panel back above its parent", func() bool { return panel.IsVisible() && inFrontOf(panel, parent) })
}
// onActiveSpace reports whether w is on the Space that shows.
func onActiveSpace(w *mygo.Window) (on bool) {
mygo.RunOnMain(func() { on = darwin.TestOnActiveSpace(w.NativeHandle()) })
return on
}
// windowLevel returns w's window level.
func windowLevel(w *mygo.Window) (l int) {
mygo.RunOnMain(func() { l = darwin.TestWindowLevel(w.NativeHandle()) })
return l
}
// TestChildWindowAboveOnTopParent shows a child window of a window that is
// always on top: the child takes its level, staying above it and above the
// windows its parent is above, and follows it as its parent stops being
// on top and is again, while it does not report being on top itself.
func TestChildWindowAboveOnTopParent(t *testing.T) {
o := childWindowsOrigin(t)
other := newWindow(t, mygo.WindowOptions{Title: "Window under the on-top parent", Width: 500, Height: 400, X: o.X, Y: o.Y})
parent := newWindow(t, mygo.WindowOptions{Title: "On-top parent", AlwaysOnTop: true, Width: 400, Height: 300, X: o.X + 40, Y: o.Y + 40})
child := newWindow(t, mygo.WindowOptions{Title: "Child of the on-top parent", Parent: parent, Width: 240, Height: 180, X: o.X + 80, Y: o.Y + 80})
waitOnScreen(other)
waitOnScreen(child)
eventually(t, "the child above its on-top parent", func() bool { return inFrontOf(child, parent) })
if l, pl := windowLevel(child), windowLevel(parent); l < pl {
t.Errorf("the child's level %d is below its parent's %d", l, pl)
}
if child.IsAlwaysOnTop() {
t.Error("the child reports being on top, as its parent is")
}
other.Focus()
eventually(t, "the other window focused", other.IsFocused)
eventually(t, "the on-top parent and its child above the focused window", func() bool {
return inFrontOf(child, parent) && inFrontOf(parent, other)
})
parent.Focus()
eventually(t, "the child above its raised on-top parent", func() bool { return inFrontOf(child, parent) })
parent.SetAlwaysOnTop(false)
eventually(t, "the parent no longer on top", func() bool { return !parent.IsAlwaysOnTop() })
if l, pl := windowLevel(child), windowLevel(parent); l != pl {
t.Errorf("the child's level %d once its parent is no longer on top, want its parent's %d", l, pl)
}
other.Focus()
eventually(t, "the focused window above the parent no longer on top, and its child", func() bool {
return inFrontOf(other, child) && inFrontOf(child, parent)
})
parent.SetAlwaysOnTop(true)
eventually(t, "the child above its parent on top again, and above the other window", func() bool {
return inFrontOf(child, parent) && inFrontOf(child, other)
})
}
// TestChildWindowFollowsFullScreenParent puts a child window's parent in
// full screen, a Space of its own: the child goes there with it, above it,
// and comes back with it.
func TestChildWindowFollowsFullScreenParent(t *testing.T) {
o := childWindowsOrigin(t)
parent := newWindow(t, mygo.WindowOptions{Title: "Full-screen parent", Width: 400, Height: 300, X: o.X, Y: o.Y})
child := newWindow(t, mygo.WindowOptions{Title: "Child of the full-screen parent", Parent: parent, Width: 240, Height: 180, X: o.X + 40, Y: o.Y + 40})
waitOnScreen(child)
eventually(t, "the child above its parent", func() bool { return inFrontOf(child, parent) })
parent.SetFullScreen(true)
eventually(t, "the parent in full screen", parent.IsFullScreen)
eventually(t, "the child on its full-screen parent's Space, above it", func() bool {
return onActiveSpace(parent) && onActiveSpace(child) && child.IsVisible() && inFrontOf(child, parent)
})
parent.SetFullScreen(false)
eventually(t, "the parent out of full screen", func() bool { return !parent.IsFullScreen() })
eventually(t, "the child back with its parent, above it", func() bool {
return onActiveSpace(parent) && onActiveSpace(child) && child.IsVisible() && inFrontOf(child, parent)
})
parent.Focus()
eventually(t, "the child above its raised parent after full screen", func() bool { return inFrontOf(child, parent) })
}
+38
View File
@@ -0,0 +1,38 @@
//go:build linux && !android && (amd64 || arm64) && !android
package e2e
import (
"bytes"
"os/exec"
"slices"
"strings"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/transfer"
)
func TestUnifiedClipboardGTKForeignHTML(t *testing.T) {
xclip, err := exec.LookPath("xclip")
if err != nil {
t.Skip("xclip is needed to exercise a non-MyGo selection owner")
}
preserveClipboard(t)
const html = "<b>foreign HTML 日本語</b>"
cmd := exec.Command(xclip, "-selection", "clipboard", "-target", "text/html")
cmd.Stdin = strings.NewReader(html)
// xclip forks a selection owner after publishing. Its child exits when
// cleanup restores the clipboard and GTK takes ownership back.
if err := cmd.Run(); err != nil {
t.Fatal(err)
}
eventually(t, "foreign HTML selection", func() bool { return slices.Contains(mygo.Clipboard.Formats(), transfer.HTML) })
b, err := mygo.Clipboard.ReadFormat(transfer.HTML)
if err != nil || !bytes.Equal(b, []byte(html)) {
t.Fatalf("foreign HTML bytes %q: %v", b, err)
}
if got := mygo.Clipboard.ReadHTML(); got != html {
t.Fatalf("native HTML convenience %q", got)
}
}
+364
View File
@@ -0,0 +1,364 @@
//go:build !js
package e2e
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"image"
"image/color"
"image/png"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/transfer"
"github.com/egoist/mygo/ui"
)
const clipboardCustom transfer.Format = "application/vnd.mygo.clipboard-e2e"
type clipboardPeerResult struct {
Items int
Values map[transfer.Format][]byte
Text, HTML string
Image []byte
Files []string
Native []string // AvailableFormats, the platform's own names
}
func clipboardTestData(provider func() ([]byte, error)) transfer.Data {
img := image.NewNRGBA(image.Rect(0, 0, 2, 2))
img.SetNRGBA(0, 0, color.NRGBA{R: 40, G: 80, B: 120, A: 255})
var encoded bytes.Buffer
_ = png.Encode(&encoded, img)
return transfer.New(
transfer.NewItem(transfer.Bytes(transfer.Text, []byte("hello 日本語")), transfer.Bytes(transfer.HTML, []byte("<b>hello 日本語</b>")), transfer.Bytes(transfer.PNG, encoded.Bytes()), transfer.Lazy(clipboardCustom, provider)),
transfer.NewItem(transfer.Bytes(transfer.Text, []byte("second")), transfer.Bytes(clipboardCustom, []byte{3, 0})),
)
}
// clipboardPeer runs a real, independent native clipboard client. It does
// not start any window or webview. The parent app's loop stays running while
// this process requests delayed representations or owns a foreign selection.
func clipboardPeer(mode string) {
mygo.App.SetName("MyGoClipboardPeer")
mygo.App.SetActivationPolicy(mygo.ActivationPolicyAccessory)
mygo.App.WhenReady(func() {
go func() {
if mode == "persist-text" {
mygo.Clipboard.WriteText("persisted clipboard 日本語")
mygo.App.Quit()
return
}
if mode == "read" {
var formats []transfer.Format
_ = json.Unmarshal([]byte(os.Getenv("MYGO_CLIPBOARD_FORMATS")), &formats)
d, err := mygo.Clipboard.Read(formats...)
if err != nil {
fmt.Fprintln(os.Stderr, "clipboard peer read:", err)
os.Exit(1)
}
r := clipboardPeerResult{Items: len(d.Items()), Values: map[transfer.Format][]byte{}, Text: mygo.Clipboard.ReadText(), HTML: mygo.Clipboard.ReadHTML(), Image: mygo.Clipboard.ReadImage(), Native: mygo.Clipboard.AvailableFormats()}
r.Files, _ = d.Files()
for _, f := range d.Formats() {
r.Values[f], _ = d.Read(f)
}
b, _ := json.Marshal(r)
fmt.Println(string(b))
mygo.App.Quit()
return
}
d := clipboardTestData(func() ([]byte, error) { return []byte{0, 1, 2, 0}, nil })
if err := mygo.Clipboard.Write(d); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if mode == "persist" {
mygo.App.Quit()
return
}
fmt.Println("ready")
_, _ = bufio.NewReader(os.Stdin).ReadString('\n')
mygo.App.Quit()
}()
})
if err := mygo.App.Run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func readClipboardPeer(t *testing.T, formats ...transfer.Format) clipboardPeerResult {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), wait.Guard)
defer cancel()
b, _ := json.Marshal(formats)
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^$")
cmd.Env = append(os.Environ(), "MYGO_E2E_CLIPBOARD_PEER=read", "MYGO_CLIPBOARD_FORMATS="+string(b))
var stderr bytes.Buffer
cmd.Stderr = &stderr
out, err := cmd.Output()
if err != nil {
t.Fatalf("clipboard peer: %v; %s", err, stderr.String())
}
var r clipboardPeerResult
if err := json.Unmarshal(bytes.TrimSpace(out), &r); err != nil {
t.Fatalf("peer reply %q: %v", out, err)
}
return r
}
func preserveClipboard(t *testing.T) {
t.Helper()
d, err := mygo.Clipboard.Read()
t.Cleanup(func() {
if err == nil {
_ = mygo.Clipboard.Write(d)
_ = mygo.Clipboard.Flush()
} else {
mygo.Clipboard.Clear()
}
})
}
func TestUnifiedClipboardNativeRoundTrip(t *testing.T) {
preserveClipboard(t)
var calls, releases atomic.Int32
d := clipboardTestData(func() ([]byte, error) { calls.Add(1); return []byte{0, 1, 2, 0}, nil })
w := newWindow(t, mygo.WindowOptions{Hidden: true, Content: ui.View(func(c *ui.Context) { ui.Box(c) })})
if err := mygo.Clipboard.Write(d, mygo.ClipboardOptions{OnRelease: func() { releases.Add(1) }}); err != nil {
t.Fatal(err)
}
if f := mygo.Clipboard.Formats(); !slices.Equal(f, d.Formats()) || calls.Load() != 0 {
t.Fatalf("lazy discovery %v, calls %d", f, calls.Load())
}
w.Destroy()
if calls.Load() != 0 || releases.Load() != 0 {
t.Fatal("window destruction requested or released clipboard providers")
}
local, err := mygo.Clipboard.Read(transfer.Text)
if err != nil || len(local.Items()) != 2 || calls.Load() != 0 {
t.Fatalf("local items %d, calls %d: %v", len(local.Items()), calls.Load(), err)
}
r := readClipboardPeer(t, d.Formats()...)
for _, f := range d.Formats() {
want, _ := d.Read(f)
if !bytes.Equal(r.Values[f], want) {
t.Errorf("foreign %s: %v, want %v", f, r.Values[f], want)
}
}
// One invocation for the native snapshot; d.Read above invokes its
// independent original provider cache once as well.
if calls.Load() != 2 {
t.Fatalf("provider calls %d", calls.Load())
}
wantText := "hello 日本語\nsecond"
if r.Text != wantText || r.HTML != "<b>hello 日本語</b>" {
t.Fatalf("native conveniences: %q, %q", r.Text, r.HTML)
}
if img, err := png.Decode(bytes.NewReader(r.Image)); err != nil || img.Bounds().Dx() != 2 {
t.Fatalf("native image: %v", err)
}
if runtime.GOOS == "darwin" && r.Items != 2 {
t.Fatal("AppKit lost item boundaries")
}
if err := mygo.Clipboard.Flush(); err != nil && !errors.Is(err, mygo.ErrClipboardPersistence) {
t.Fatal(err)
}
eventually(t, "clipboard provider release", func() bool { return releases.Load() == 1 })
r = readClipboardPeer(t, clipboardCustom)
if !bytes.Equal(r.Values[clipboardCustom], []byte{0, 1, 2, 0}) {
t.Fatalf("flushed custom bytes: %v", r.Values[clipboardCustom])
}
mygo.Clipboard.Clear()
mygo.RunOnMain(func() {})
if releases.Load() != 1 {
t.Fatal("native source released twice")
}
if b, err := local.Read(transfer.Text); err != nil || string(b) != "hello 日本語\nsecond" {
t.Fatal("read snapshot depended on a closed window/clipboard owner")
}
}
func TestUnifiedClipboardConcealed(t *testing.T) {
preserveClipboard(t)
mark := map[string]string{"darwin": "org.nspasteboard.ConcealedType", "linux": "x-kde-passwordManagerHint", "windows": "ExcludeClipboardContentFromMonitorProcessing"}[runtime.GOOS]
formats := []transfer.Format{transfer.Text}
if runtime.GOOS == "linux" {
// Klipper and CopyQ compare the hint's value.
formats = append(formats, transfer.Format(mark))
}
if err := mygo.Clipboard.Write(transfer.TextData("hunter2"), mygo.ClipboardOptions{Concealed: true}); err != nil {
t.Fatal(err)
}
for _, flushed := range []bool{false, true} {
if flushed {
if err := mygo.Clipboard.Flush(); err != nil && !errors.Is(err, mygo.ErrClipboardPersistence) {
t.Fatal(err)
}
}
r := readClipboardPeer(t, formats...)
if r.Text != "hunter2" || !slices.Contains(r.Native, mark) {
t.Fatalf("flushed %t: text %q, native formats %q lack %q", flushed, r.Text, r.Native, mark)
}
if runtime.GOOS == "linux" && string(r.Values[transfer.Format(mark)]) != "secret" {
t.Fatalf("flushed %t: hint %q", flushed, r.Values[transfer.Format(mark)])
}
}
if err := mygo.Clipboard.Write(transfer.TextData("plain")); err != nil {
t.Fatal(err)
}
if r := readClipboardPeer(t, transfer.Text); slices.Contains(r.Native, mark) {
t.Fatalf("an ordinary write kept the mark: %q", r.Native)
}
}
func TestUnifiedClipboardNativeFilesAndFailures(t *testing.T) {
preserveClipboard(t)
paths := []string{filepath.Join(t.TempDir(), "file #%.txt"), filepath.Join(t.TempDir(), "日本語.txt")}
for _, path := range paths {
if err := os.WriteFile(path, []byte("file"), 0600); err != nil {
t.Fatal(err)
}
}
if err := mygo.Clipboard.WriteFiles(paths...); err != nil {
t.Fatal(err)
}
r := readClipboardPeer(t, transfer.FileList, transfer.URIList)
if !slices.Equal(r.Files, paths) {
t.Fatalf("foreign file list %q, want %q", r.Files, paths)
}
boom := errors.New("encode failed")
var calls atomic.Int32
d := transfer.New(transfer.NewItem(transfer.Bytes(transfer.Text, []byte("fallback")), transfer.Lazy(clipboardCustom, func() ([]byte, error) { calls.Add(1); return nil, boom })))
if err := mygo.Clipboard.Write(d); err != nil {
t.Fatal(err)
}
for range 2 {
if _, err := mygo.Clipboard.ReadFormat(clipboardCustom); !errors.Is(err, boom) {
t.Fatalf("provider read error: %v", err)
}
if err := mygo.Clipboard.Flush(); !errors.Is(err, boom) {
t.Fatalf("provider flush error: %v", err)
}
}
// External readers receive a failed native representation, while the
// source retains its cached error and usable plain-text alternative.
for range 2 {
ctx, cancel := context.WithTimeout(context.Background(), wait.Guard)
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^$")
formats, _ := json.Marshal([]transfer.Format{clipboardCustom})
cmd.Env = append(os.Environ(), "MYGO_E2E_CLIPBOARD_PEER=read", "MYGO_CLIPBOARD_FORMATS="+string(formats))
out, err := cmd.CombinedOutput()
cancel()
if err == nil || !bytes.Contains(out, []byte("clipboard peer read:")) {
t.Fatalf("failed native provider was acknowledged: %v, %s", err, out)
}
}
if calls.Load() != 1 || mygo.Clipboard.ReadText() != "fallback" {
t.Fatal("native failure lost ownership or retried a provider")
}
}
func TestUnifiedClipboardForeignOwnershipAndShutdown(t *testing.T) {
preserveClipboard(t)
var releases atomic.Int32
if err := mygo.Clipboard.Write(transfer.TextData("old"), mygo.ClipboardOptions{OnRelease: func() { releases.Add(1) }}); err != nil {
t.Fatal(err)
}
var foreignChanges atomic.Int32
t.Cleanup(mygo.Clipboard.OnChanged(func() {
if slices.Contains(mygo.Clipboard.Formats(), clipboardCustom) {
foreignChanges.Add(1)
}
}))
ctx, cancel := context.WithTimeout(context.Background(), wait.Guard)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^$")
cmd.Env = append(os.Environ(), "MYGO_E2E_CLIPBOARD_PEER=own")
stdin, err := cmd.StdinPipe()
if err != nil {
t.Fatal(err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
t.Fatal(err)
}
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
stopped := false
t.Cleanup(func() {
if !stopped {
_ = stdin.Close()
_ = cmd.Wait()
}
})
ready, err := bufio.NewReader(stdout).ReadString('\n')
if err != nil || ready != "ready\n" {
t.Fatalf("foreign owner startup %q: %v, %s", ready, err, stderr.String())
}
eventually(t, "foreign clipboard change notification", func() bool { return foreignChanges.Load() > 0 })
eventually(t, "foreign clipboard ownership", func() bool { return slices.Contains(mygo.Clipboard.Formats(), clipboardCustom) })
eventually(t, "old provider release", func() bool { return releases.Load() == 1 })
d, err := mygo.Clipboard.Read(clipboardCustom)
if err != nil {
t.Fatalf("foreign read: %v; peer stderr: %s", err, stderr.String())
}
if b, _ := d.Read(clipboardCustom); !bytes.Equal(b, []byte{0, 1, 2, 0}) {
t.Fatalf("foreign custom bytes %v", b)
}
// Flushing from a non-owner must leave the other process's data intact.
if err := mygo.Clipboard.Flush(); err != nil {
t.Fatal(err)
}
if _, err := mygo.Clipboard.ReadFormat(clipboardCustom); err != nil {
t.Fatal("non-owner flush changed the clipboard")
}
_, _ = stdin.Write([]byte("\n"))
_ = stdin.Close()
err = cmd.Wait()
stopped = true
if err != nil {
t.Fatalf("foreign owner shutdown: %v; %s", err, stderr.String())
}
if runtime.GOOS != "linux" {
b, err := mygo.Clipboard.ReadFormat(clipboardCustom)
if err != nil || !bytes.Equal(b, []byte{0, 1, 2, 0}) {
t.Fatalf("data after source app exits: %v, %v", b, err)
}
}
}
func TestUnifiedClipboardNativePersistence(t *testing.T) {
preserveClipboard(t)
mygo.Clipboard.WriteText("persistence probe")
if err := mygo.Clipboard.Flush(); errors.Is(err, mygo.ErrClipboardPersistence) {
t.Skip("desktop has no clipboard manager for persistence after exit")
} else if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), wait.Guard)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^$")
cmd.Env = append(os.Environ(), "MYGO_E2E_CLIPBOARD_PEER=persist-text")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("clipboard writer shutdown: %v; %s", err, out)
}
if got := mygo.Clipboard.ReadText(); got != "persisted clipboard 日本語" {
t.Fatalf("text after application exit: %q", got)
}
}
+63
View File
@@ -0,0 +1,63 @@
//go:build !js
package e2e
import (
"slices"
"sync"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
)
// clipboardChanges records the text the clipboard held at each change a
// listener heard.
type clipboardChanges struct {
mu sync.Mutex
texts []string
}
func (c *clipboardChanges) listen() {
text := mygo.Clipboard.ReadText()
c.mu.Lock()
c.texts = append(c.texts, text)
c.mu.Unlock()
}
func (c *clipboardChanges) heard(text string) func() bool {
return func() bool {
c.mu.Lock()
defer c.mu.Unlock()
return slices.Contains(c.texts, text)
}
}
func (c *clipboardChanges) count() int {
c.mu.Lock()
defer c.mu.Unlock()
return len(c.texts)
}
func TestClipboardChangeNotifications(t *testing.T) {
preserveClipboard(t)
var first, second clipboardChanges
off := mygo.Clipboard.OnChanged(first.listen)
t.Cleanup(off)
mygo.Clipboard.WriteText("clipboard observation 日本語")
wait.Until(t, "a change with the text written", first.heard("clipboard observation 日本語"))
mygo.Clipboard.Clear()
wait.Until(t, "a change for the cleared clipboard", first.heard(""))
// A listener that stays tells when a change was delivered: once it heard
// the next one, the listener removed before could have heard it too.
t.Cleanup(mygo.Clipboard.OnChanged(second.listen))
off()
off()
heard := first.count()
mygo.Clipboard.WriteText("after unsubscribe")
wait.Until(t, "the remaining listener to hear the change", second.heard("after unsubscribe"))
if n := first.count(); n != heard {
t.Fatalf("a removed listener heard %d more changes", n-heard)
}
}
+47
View File
@@ -0,0 +1,47 @@
//go:build darwin && !ios
package e2e
import (
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/darwin"
"github.com/egoist/mygo/ui"
)
// TestCloseOrdersOutFirst closes a window of native UI that shows, with
// Destroy and as its close button does, and checks that it was ordered
// out by the time it told it closed, which follows its content going:
// AppKit's animation fades the window as it orders it out, which faded
// an empty window when the content went first (#1931).
func TestCloseOrdersOutFirst(t *testing.T) {
for _, c := range []struct {
name string
close func(w *mygo.Window, handle uintptr)
}{
{"Destroy", func(w *mygo.Window, _ uintptr) { w.Destroy() }},
{"close button", func(_ *mygo.Window, handle uintptr) {
mygo.RunOnMain(func() { darwin.TestPerformClose(handle) })
}},
} {
t.Run(c.name, func(t *testing.T) {
w := newWindow(t, mygo.WindowOptions{Width: 320, Height: 240, Content: ui.View(func(c *ui.Context) {
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255))
})})
waitOnScreen(w)
handle := w.NativeHandle()
var closed, orderedIn atomic.Bool
w.OnClosed(func() {
orderedIn.Store(darwin.TestOrderedIn(handle))
closed.Store(true)
})
c.close(w, handle)
eventually(t, "the window closing", closed.Load)
if orderedIn.Load() {
t.Error("the window was still ordered in once its content went")
}
})
}
}
+101
View File
@@ -0,0 +1,101 @@
//go:build !js
package e2e
import (
"runtime"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/editor"
)
// The code editor takes the system's input methods: a composition
// replacing text the input method names, its commit, and text typed.
func TestContentWindowCodeEditor(t *testing.T) {
var frames atomic.Int32
st := &editor.State{Buffer: editor.NewBuffer("first\ncafe")}
w := newWindow(t, mygo.WindowOptions{Title: "Code editor", Width: 500, Height: 240, Content: ui.View(func(c *ui.Context) {
editor.View(c, st).Fill().AutoFocus()
frames.Add(1)
})})
eventually(t, "an editor frame", func() bool { return frames.Load() > 0 })
if _, _, ok := inputClient(w); !ok {
t.Skip("native input automation unavailable")
}
// The end of the second line.
if !click(w, 400, 30) {
t.Skip("click automation unavailable")
}
eventually(t, "the caret at the end", func() bool {
var head int
mygo.RunOnMain(func() { head = st.Cursor() })
return head == len("first\ncafe")
})
// The e, in UTF-16 units on macOS, runes elsewhere: the same here.
composeOver(w, "e", 1, false, 9, 1)
composeOver(w, "é", 1, true, -1, 0)
eventually(t, "the composition committed", func() bool {
var text string
mygo.RunOnMain(func() { text = st.Buffer.String() })
return text == "first\ncafé"
})
if runtime.GOOS == "darwin" {
// Typed text, and Return indenting nothing.
if !clickAndType(w, 400, 30, "!") {
return
}
eventually(t, "text typed", func() bool {
var text string
mygo.RunOnMain(func() { text = st.Buffer.String() })
return text == "first\ncafé!"
})
// Up arrow (key code 126) moves the caret to the first line.
pressKey(w, 126, "")
eventually(t, "the caret up a line", func() bool {
var p editor.Pos
mygo.RunOnMain(func() { p = st.CursorPos() })
return p.Line == 0
})
}
}
// With NoInputMethod, keys type the characters of the layout, which come
// to OnInput as text, without going through the input method.
func TestContentWindowCodeEditorNoInputMethod(t *testing.T) {
var frames atomic.Int32
var typed atomic.Value
typed.Store("")
st := &editor.State{Buffer: editor.NewBuffer("abc"), NoInputMethod: true, CursorShape: editor.CursorBlock}
st.OnInput = func(ev ui.InputEvent) bool {
if ev.Kind == ui.InputText {
typed.Store(typed.Load().(string) + ev.Text)
return true
}
return false
}
w := newWindow(t, mygo.WindowOptions{Title: "Code editor", Width: 500, Height: 240, Content: ui.View(func(c *ui.Context) {
editor.View(c, st).Fill().AutoFocus()
frames.Add(1)
})})
eventually(t, "an editor frame", func() bool { return frames.Load() > 0 })
if !click(w, 400, 30) {
t.Skip("click automation unavailable")
}
eventually(t, "the editor focused", func() bool {
var focused bool
mygo.RunOnMain(func() { focused = st.Focused() })
return focused
})
if !pressKey(w, 38, "j") && !pressKeys("j") { // kVK_ANSI_J on macOS
t.Skip("key automation unavailable")
}
eventually(t, "j for OnInput", func() bool { return typed.Load().(string) == "j" })
var text string
mygo.RunOnMain(func() { text = st.Buffer.String() })
if text != "abc" {
t.Fatalf("the text is %q, want it untouched", text)
}
}
+290
View File
@@ -0,0 +1,290 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"bufio"
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync/atomic"
"testing"
"unsafe"
"github.com/ebitengine/purego"
"github.com/egoist/mygo"
)
// On a desktop whose dark style is only in the settings portal, as
// GNOME's, pages are dark from the first, and follow the portal's changes
// while the app has not chosen an appearance (#1120). The app runs on a
// bus of its own, with a fake portal.
func TestPageColorSchemePortal(t *testing.T) {
daemon, err := exec.LookPath("dbus-daemon")
if err != nil {
t.Skip("dbus-daemon is needed for a bus of the test's own")
}
dir := t.TempDir()
config := filepath.Join(dir, "bus.conf")
// A bus without services to start, so that nothing but the fake answers
// for the portal.
if err := os.WriteFile(config, []byte(`<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>session</type>
<listen>unix:path=`+filepath.Join(dir, "bus")+`</listen>
<policy context="default">
<allow send_destination="*" eavesdrop="true"/>
<allow eavesdrop="true"/>
<allow own="*"/>
</policy>
</busconfig>
`), 0o644); err != nil {
t.Fatal(err)
}
bus := exec.CommandContext(t.Context(), daemon, "--config-file="+config, "--nofork", "--print-address")
busOut, err := bus.StdoutPipe()
if err != nil {
t.Fatal(err)
}
if err := bus.Start(); err != nil {
t.Fatal(err)
}
defer func() { bus.Process.Kill(); bus.Wait() }()
// The daemon prints its address once it listens.
address, err := bufio.NewReader(busOut).ReadString('\n')
if err != nil {
t.Fatalf("dbus-daemon: %v", err)
}
env := append(os.Environ(), "DBUS_SESSION_BUS_ADDRESS="+strings.TrimSpace(address))
var portalErr bytes.Buffer
portal := exec.CommandContext(t.Context(), os.Args[0])
portal.Env = append(env, "MYGO_E2E_FAKE_PORTAL=1")
portal.Stderr = &portalErr
portalIn, err := portal.StdinPipe()
if err != nil {
t.Fatal(err)
}
portalOut, err := portal.StdoutPipe()
if err != nil {
t.Fatal(err)
}
if err := portal.Start(); err != nil {
t.Fatal(err)
}
defer func() { portalIn.Close(); portal.Wait() }()
// It says ready once it owns the portal's name.
if line, err := bufio.NewReader(portalOut).ReadString('\n'); line != "ready\n" {
portalIn.Close()
portal.Wait()
t.Fatalf("the fake portal: %q, %v\n%s", line, err, portalErr.String())
}
// The app asks for the portal's changes on its output, which the test
// passes on. The helper's waits have their guard, after which it fails
// and says what it waited for.
app := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^TestPageColorSchemePortalApp$", "-test.v")
app.Env = append(env, "MYGO_E2E_PORTAL_APP=1")
appOut, err := app.StdoutPipe()
if err != nil {
t.Fatal(err)
}
app.Stderr = app.Stdout
if err := app.Start(); err != nil {
t.Fatal(err)
}
var log strings.Builder
lines := bufio.NewScanner(appOut)
for lines.Scan() {
line := lines.Text()
log.WriteString(line + "\n")
if scheme, ok := strings.CutPrefix(line, "portal: "); ok {
fmt.Fprintln(portalIn, scheme)
}
}
if err := app.Wait(); err != nil {
t.Errorf("%v:\n%s\nthe fake portal:\n%s", err, log.String(), portalErr.String())
}
}
// TestPageColorSchemePortalApp is TestPageColorSchemePortal's app, which
// starts on a dark desktop.
func TestPageColorSchemePortalApp(t *testing.T) {
if os.Getenv("MYGO_E2E_PORTAL_APP") == "" {
t.Skip("TestPageColorSchemePortal runs it, on a bus of its own")
}
w := newWindow(t, mygo.WindowOptions{Title: "Portal color scheme", Width: 300, Height: 200})
w.Page().LoadHTML(`<meta name="color-scheme" content="light dark"><p>scheme</p>`, "")
waitFor(t, w, "document.readyState === 'complete'")
var updates atomic.Int32
defer mygo.Theme.OnUpdated(func() { updates.Add(1) })()
// setPortal has the fake portal change the color scheme (1 dark, 2
// light, 0 no preference), and waits for the app to hear of it.
setPortal := func(scheme int) {
t.Helper()
n := updates.Load()
fmt.Printf("portal: %d\n", scheme)
eventually(t, fmt.Sprintf("Theme.OnUpdated after the portal's color scheme %d", scheme), func() bool { return updates.Load() > n })
}
expect := func(what string, dark bool) {
t.Helper()
waitFor(t, w, fmt.Sprintf("matchMedia('(prefers-color-scheme: dark)').matches === %v", dark))
if got := mygo.Theme.IsDark(); got != dark {
t.Errorf("%s: Theme.IsDark() = %v", what, got)
}
}
expect("a dark desktop", true)
setPortal(2)
expect("a light desktop", false)
setPortal(1)
expect("a dark desktop again", true)
// Without a preference, GTK's theme decides: Adwaita is light.
setPortal(0)
expect("no preference", false)
// The appearance the app chooses wins over the portal's.
mygo.Theme.SetSource(mygo.ThemeLight)
setPortal(1)
expect("ThemeLight on a dark desktop", false)
mygo.Theme.SetSource(mygo.ThemeSystem)
expect("ThemeSystem on a dark desktop", true)
mygo.Theme.SetSource(mygo.ThemeDark)
setPortal(2)
expect("ThemeDark on a light desktop", true)
mygo.Theme.SetSource(mygo.ThemeSystem)
expect("ThemeSystem on a light desktop", false)
}
// fakePortal serves the settings portal's color scheme on the session bus
// (org.freedesktop.portal.Settings), dark at first, and changes it to each
// number its input gives, with the SettingChanged signal.
func fakePortal() {
runtime.LockOSThread()
gio, err := purego.Dlopen("libgio-2.0.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
var (
busGetSync func(busType int32, cancellable uintptr, gerr *uintptr) uintptr
nodeInfoNewForXML func(xml string, gerr *uintptr) uintptr
nodeInfoLookup func(node uintptr, name string) uintptr
registerObject func(conn uintptr, path string, iface uintptr, vtable unsafe.Pointer, data, free uintptr, gerr *uintptr) uint32
callSync func(conn uintptr, name, path, iface, method string, params, replyType uintptr, flags, timeout int32, cancellable uintptr, gerr *uintptr) uintptr
emitSignal func(conn uintptr, dest uintptr, path, iface, signal string, params uintptr, gerr *uintptr) bool
variantParse func(typ uintptr, text string, limit, endptr uintptr, gerr *uintptr) uintptr
variantPrint func(v uintptr, annotate bool) string
returnValue func(invocation, v uintptr)
returnDBusError func(invocation uintptr, name, message string)
mainLoopNew func(ctx uintptr, running bool) uintptr
mainLoopRun func(loop uintptr)
scheme atomic.Uint32
vtable [11]uintptr // GDBusInterfaceVTable: method_call, get_property, set_property, padding
settingsIface = "org.freedesktop.portal.Settings"
portalPath = "/org/freedesktop/portal/desktop"
appearance, colorID = "org.freedesktop.appearance", "color-scheme"
)
for name, fn := range map[string]any{
"g_bus_get_sync": &busGetSync, "g_dbus_node_info_new_for_xml": &nodeInfoNewForXML,
"g_dbus_node_info_lookup_interface": &nodeInfoLookup, "g_dbus_connection_register_object": &registerObject,
"g_dbus_connection_call_sync": &callSync, "g_dbus_connection_emit_signal": &emitSignal,
"g_variant_parse": &variantParse, "g_variant_print": &variantPrint,
"g_dbus_method_invocation_return_value": &returnValue, "g_dbus_method_invocation_return_dbus_error": &returnDBusError,
"g_main_loop_new": &mainLoopNew, "g_main_loop_run": &mainLoopRun,
} {
purego.RegisterLibFunc(fn, gio, name)
}
cstr := func(p uintptr) string {
base := *(*unsafe.Pointer)(unsafe.Pointer(&p))
var b []byte
for c := (*byte)(base); *c != 0; c = (*byte)(unsafe.Add(unsafe.Pointer(c), 1)) {
b = append(b, *c)
}
return string(b)
}
fail := func(what string, gerr uintptr) {
msg := "unknown error"
if gerr != 0 {
msg = cstr(*(*uintptr)(unsafe.Add(*(*unsafe.Pointer)(unsafe.Pointer(&gerr)), 8))) // GError's message
}
fmt.Fprintf(os.Stderr, "%s: %s\n", what, msg)
os.Exit(1)
}
parse := func(text string) uintptr {
var gerr uintptr
v := variantParse(0, text, 0, 0, &gerr)
if v == 0 {
fail("g_variant_parse "+text, gerr)
}
return v
}
var gerr uintptr
conn := busGetSync(2, 0, &gerr) // G_BUS_TYPE_SESSION
if conn == 0 {
fail("the session bus", gerr)
}
node := nodeInfoNewForXML(`<node><interface name="`+settingsIface+`">
<method name="Read"><arg type="s" direction="in"/><arg type="s" direction="in"/><arg type="v" direction="out"/></method>
<method name="ReadAll"><arg type="as" direction="in"/><arg type="a{sa{sv}}" direction="out"/></method>
<signal name="SettingChanged"><arg type="s"/><arg type="s"/><arg type="v"/></signal>
</interface></node>`, &gerr)
if node == 0 {
fail("the portal's interface", gerr)
}
scheme.Store(1)
vtable[0] = purego.NewCallback(func(conn, sender, path, iface, method, params, invocation, data uintptr) {
args := variantPrint(params, false)
switch cstr(method) {
case "Read":
if args != fmt.Sprintf("('%s', '%s')", appearance, colorID) {
returnDBusError(invocation, "org.freedesktop.portal.Error.NotFound", "Requested setting not found")
return
}
// The portal wraps the value in a second variant.
returnValue(invocation, parse(fmt.Sprintf("(<<uint32 %d>>,)", scheme.Load())))
case "ReadAll":
returnValue(invocation, parse(fmt.Sprintf("({'%s': {'%s': <uint32 %d>}},)", appearance, colorID, scheme.Load())))
}
})
if registerObject(conn, portalPath, nodeInfoLookup(node, settingsIface), unsafe.Pointer(&vtable), 0, 0, &gerr) == 0 {
fail("the portal's object", gerr)
}
// DBUS_NAME_FLAG_DO_NOT_QUEUE; the reply is 1 for the primary owner.
res := callSync(conn, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "RequestName",
parse("('org.freedesktop.portal.Desktop', uint32 4)"), 0, 0, -1, 0, &gerr)
if res == 0 {
fail("the portal's name", gerr)
}
if reply := variantPrint(res, false); reply != "(1,)" {
fmt.Fprintf(os.Stderr, "the portal's name: %s\n", reply)
os.Exit(1)
}
fmt.Println("ready")
go func() {
lines := bufio.NewScanner(os.Stdin)
for lines.Scan() {
var s uint32
if _, err := fmt.Sscan(lines.Text(), &s); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
scheme.Store(s)
var gerr uintptr
if !emitSignal(conn, 0, portalPath, settingsIface, "SettingChanged",
parse(fmt.Sprintf("('%s', '%s', <uint32 %d>)", appearance, colorID, s)), &gerr) {
fail("SettingChanged", gerr)
}
}
os.Exit(0) // the test is done with it
}()
mainLoopRun(mainLoopNew(0, false))
runtime.KeepAlive(&vtable)
}
@@ -0,0 +1,7 @@
//go:build !(linux && !android && (amd64 || arm64)) && !js
package e2e
// fakePortal serves the settings portal of Linux desktops, which other
// systems do not have.
func fakePortal() {}
+61
View File
@@ -0,0 +1,61 @@
//go:build !js
package e2e
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
"github.com/egoist/mygo"
)
// A page follows the appearance the app sets, as its prefers-color-scheme,
// also when it changes, and so does Theme.IsDark.
func TestPageColorScheme(t *testing.T) {
w := newWindow(t, mygo.WindowOptions{Title: "Color scheme", Width: 300, Height: 200})
w.Page().LoadHTML(`<meta name="color-scheme" content="light dark"><p>scheme</p>`, "")
waitFor(t, w, "document.readyState === 'complete'")
if os.Getenv("MYGO_E2E_DARK_THEME") != "" && !mygo.Theme.IsDark() {
t.Fatal("GTK's theme is not Adwaita-dark")
}
defer mygo.Theme.SetSource(mygo.Theme.Source())
for _, source := range []mygo.ThemeSource{mygo.ThemeLight, mygo.ThemeDark, mygo.ThemeLight} {
mygo.Theme.SetSource(source)
dark := source == mygo.ThemeDark
waitFor(t, w, fmt.Sprintf("matchMedia('(prefers-color-scheme: dark)').matches === %v", dark))
if got := mygo.Theme.IsDark(); got != dark {
t.Errorf("%s: Theme.IsDark() = %v", source, got)
}
}
}
// On a desktop whose GTK theme is named for its dark variant, as Ubuntu's
// Yaru-dark in dark mode, ThemeLight makes pages light too (#224):
// WebKitGTK takes such a theme for dark whatever
// gtk-application-prefer-dark-theme says.
func TestPageColorSchemeDarkTheme(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("GTK's theme is Linux's")
}
if os.Getenv("MYGO_E2E_DARK_THEME") != "" {
t.Skip("in the helper process")
}
config := t.TempDir()
if err := os.MkdirAll(filepath.Join(config, "gtk-3.0"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(config, "gtk-3.0", "settings.ini"), []byte("[Settings]\ngtk-theme-name=Adwaita-dark\n"), 0o644); err != nil {
t.Fatal(err)
}
// The helper's waits have their guard, after which it fails and says
// what it waited for.
cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^TestPageColorScheme$", "-test.v")
cmd.Env = append(os.Environ(), "MYGO_E2E_DARK_THEME=1", "XDG_CONFIG_HOME="+config)
if out, err := cmd.CombinedOutput(); err != nil {
t.Errorf("%v:\n%s", err, out)
}
}
+138
View File
@@ -0,0 +1,138 @@
//go:build !js
package e2e
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
)
// TestContentRules loads a page whose script the rules block and one of
// whose elements they hide, then loads it again without the rules.
func TestContentRules(t *testing.T) {
var adLoads atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/ads/ad.js":
adLoads.Add(1)
w.Header().Set("Content-Type", "text/javascript")
fmt.Fprint(w, "window.adLoaded = true")
return
case "/ads/data":
adLoads.Add(1)
fmt.Fprint(w, "data")
return
case "/app.js":
w.Header().Set("Content-Type", "text/javascript")
fmt.Fprint(w, "window.appLoaded = true")
return
}
fmt.Fprint(w, `<!doctype html><title>page</title>
<div class="banner" id="banner">ad</div><div id="text">text</div>
<script src="/app.js"></script><script src="/ads/ad.js"></script>
<script>document.title = "loaded"</script>`)
}))
defer server.Close()
// Rules of their own per run, so that they compile rather than load,
// and replace the list of the run before.
const id = "e2e"
source := `[
{"trigger":{"url-filter":"/run-` + fmt.Sprint(time.Now().UnixNano()) + `/"},"action":{"type":"block"}},
{"trigger":{"url-filter":"/ads/","resource-type":["script"]},"action":{"type":"block"}},
{"trigger":{"url-filter":"/ads/data","resource-type":["raw"]},"action":{"type":"block"}},
{"trigger":{"url-filter":".*"},"action":{"type":"css-display-none","selector":".banner"}}]`
_, err := mygo.CompileContentRules(id, source)
if errors.Is(err, errors.ErrUnsupported) {
t.Skip(err)
}
if err != nil {
t.Fatal(err)
}
// The same rules again load the list compiled.
rules, err := mygo.CompileContentRules(id, source)
if err != nil {
t.Fatal(err)
}
// WebKit takes no alternatives, nor a list without a rule; it skips a
// rule whose selector it cannot parse.
for _, bad := range []string{
`[{"trigger":{"url-filter":"a|b"},"action":{"type":"block"}}]`,
`[]`,
} {
if _, err := mygo.CompileContentRules(id+"-bad", bad); err == nil {
t.Errorf("%s compiled", bad)
}
}
if _, err := mygo.CompileContentRules(id+"-bad", `[
{"trigger":{"url-filter":".*"},"action":{"type":"css-display-none","selector":"a[[["}},
{"trigger":{"url-filter":"x"},"action":{"type":"block"}}]`); err != nil {
t.Errorf("a rule of a selector the engine cannot parse: %v", err)
}
w := newWindow(t, mygo.WindowOptions{Title: "Content rules", Width: 300, Height: 200, Page: mygo.PageOptions{ContentRules: []*mygo.ContentRules{rules}}})
if err := w.Page().LoadURL(server.URL + "/"); err != nil {
t.Fatal(err)
}
waitFor(t, w, "document.title === 'loaded'")
state := func() string {
s, err := mygo.EvalAs[string](w.Page(), `[!!window.appLoaded, !!window.adLoaded,
getComputedStyle(document.getElementById("banner")).display,
getComputedStyle(document.getElementById("text")).display].join(" ")`)
if err != nil {
t.Fatal(err)
}
return s
}
if got := state(); got != "true false none block" {
t.Errorf("with the rules: app, ad, banner and text are %q, want the ad blocked and the banner hidden", got)
}
// A blocked fetch or XMLHttpRequest fails as the network would.
loads := func() string {
s, err := mygo.EvalAs[string](w.Page(), `(async () => {
const f = await fetch("/ads/data").then(r => "resolved " + r.status, () => "rejected");
const x = await new Promise(done => {
const r = new XMLHttpRequest();
r.onload = () => done("load " + r.status);
r.onerror = () => done("error");
r.open("GET", "/ads/data");
r.send();
});
return f + ", " + x;
})()`)
if err != nil {
t.Fatal(err)
}
return s
}
if got := loads(); got != "rejected, error" {
t.Errorf("blocked fetch and XMLHttpRequest: %q, want them failing", got)
}
if n := adLoads.Load(); n != 0 {
t.Errorf("what the rules block was requested %d times", n)
}
// A page setting its own adopted style sheets keeps what hides.
if got, err := mygo.EvalAs[string](w.Page(), `(() => {
document.adoptedStyleSheets = [new CSSStyleSheet()];
return getComputedStyle(document.getElementById("banner")).display;
})()`); err != nil || got != "none" {
t.Errorf("the banner after the page adopted its style sheets: %q, %v", got, err)
}
w.Page().SetContentRules()
w.Page().Reload()
waitFor(t, w, "document.title === 'loaded' && window.adLoaded === true")
if got := state(); got != "true true block block" {
t.Errorf("without the rules: %q", got)
}
if got := loads(); got != "resolved 200, load 200" {
t.Errorf("fetch and XMLHttpRequest without the rules: %q", got)
}
}
+184
View File
@@ -0,0 +1,184 @@
//go:build !js
package e2e
import (
"slices"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
)
const contextMenuPage = `<!doctype html><body style="margin:0;font:16px sans-serif">
<a id=link href="https://example.com/doc" style="position:absolute;left:0;top:0;width:200px;height:40px;display:block">Example link</a>
<input id=field value="hello" style="position:absolute;left:0;top:100px;width:200px;height:30px">
<p id=text style="position:absolute;left:0;top:180px;margin:0;font-size:24px">Some text</p>
</body>`
// contextMenuSeen is what a test's listener heard of a context menu.
type contextMenuSeen struct {
link, linkText, selection string
editable bool
ids []string
}
func menuIDs(m *mygo.Menu) []string {
var ids []string
for _, it := range m.Items() {
ids = append(ids, it.ID)
}
return ids
}
// A page's context menu tells its listeners what was right-clicked, and
// shows the menu they make of the web view's: without the items they
// removed, with those they renamed doing what they do, and with those
// they added, whose Click runs as one is chosen. PreventDefault shows
// none.
func TestPageContextMenu(t *testing.T) {
w := newWindow(t, mygo.WindowOptions{Title: "Context menu", Width: 400, Height: 300})
if !pageMenusHooked {
t.Skip("right-clicking a page is not hooked here")
}
w.Page().LoadHTML(contextMenuPage, "")
waitFor(t, w, "document.readyState === 'complete' && window.mygo")
seen := make(chan contextMenuSeen, 4)
clicked := make(chan *mygo.Window, 4)
off := w.Page().OnContextMenu(func(e *mygo.ContextMenuEvent) {
seen <- contextMenuSeen{e.LinkURL, e.LinkText, e.SelectionText, e.Editable, menuIDs(e.Menu)}
e.Menu.Remove(mygo.ContextMenuReload, mygo.ContextMenuBack, mygo.ContextMenuForward, mygo.ContextMenuInspect)
if it := e.Menu.ItemByID(mygo.ContextMenuSelectAll); it != nil {
it.SetLabel("Select Everything")
}
e.Menu.Append(mygo.Separator(), &mygo.MenuItem{Label: "Open in Browser", Click: func(_ *mygo.MenuItem, w *mygo.Window) {
clicked <- w
}})
})
open := func(what string, x, y float64) (contextMenuSeen, []string) {
t.Helper()
if !rightClickPage(w, x, y) {
t.Fatalf("%s: right-clicking the page failed", what)
}
var got contextMenuSeen
select {
case got = <-seen:
case <-time.After(wait.Guard):
t.Fatalf("%s: the listener never heard of the menu", what)
}
var labels []string
wait.Until(t, what+": the menu shown", func() bool {
var shown bool
labels, shown = pageMenu()
return shown
})
t.Logf("%s: %+v, shown %q", what, got, labels)
return got, labels
}
got, labels := open("the link", 20, 20)
if got.link != "https://example.com/doc" || got.linkText != "Example link" || got.editable {
t.Errorf("the link: heard %+v", got)
}
if !slices.Contains(got.ids, mygo.ContextMenuCopyLink) {
t.Errorf("the link: the web view's items %q have no %q", got.ids, mygo.ContextMenuCopyLink)
}
if !slices.Contains(labels, "Open in Browser") || slices.Contains(labels, "Reload") {
t.Errorf("the link: the menu shows %q", labels)
}
if !choosePageMenuItem("Open in Browser") {
t.Fatalf("the link: no item Open in Browser in %q", labels)
}
select {
case cw := <-clicked:
if cw != w {
t.Errorf("Click got window %v, want the page's", cw)
}
case <-time.After(wait.Guard):
t.Fatal("the app's item was chosen, and its Click never ran")
}
wait.Until(t, "the menu closed", func() bool { _, shown := pageMenu(); return !shown })
got, _ = open("the field", 50, 115)
if !got.editable || got.link != "" {
t.Errorf("the field: heard %+v", got)
}
if !slices.Contains(got.ids, mygo.ContextMenuPaste) {
t.Errorf("the field: the web view's items %q have no %q", got.ids, mygo.ContextMenuPaste)
}
// The web view's item, renamed, still does what it does. WebKit on
// macOS has no Select All there.
if slices.Contains(got.ids, mygo.ContextMenuSelectAll) {
mustEval(t, w, "field.setSelectionRange(5, 5), true")
if !choosePageMenuItem("Select Everything") {
t.Fatal("the field: no item Select Everything")
}
waitFor(t, w, "field.selectionStart === 0 && field.selectionEnd === 5")
} else {
dismissPageMenu()
}
wait.Until(t, "the menu closed", func() bool { _, shown := pageMenu(); return !shown })
// Pressing outside the field the menu focused would clear a selection
// made while it has the focus.
mustEval(t, w, `document.activeElement.blur(), getSelection().selectAllChildren(document.getElementById("text")), true`)
got, _ = open("the selection", 30, 192)
if got.selection != "Some text" || got.editable {
t.Errorf("the selection: heard %+v", got)
}
if !slices.Contains(got.ids, mygo.ContextMenuCopy) {
t.Errorf("the selection: the web view's items %q have no %q", got.ids, mygo.ContextMenuCopy)
}
dismissPageMenu()
off()
w.Page().OnContextMenu(func(e *mygo.ContextMenuEvent) {
seen <- contextMenuSeen{link: e.LinkURL}
e.PreventDefault()
})
wait.Until(t, "the menu closed", func() bool { _, shown := pageMenu(); return !shown })
if !rightClickPage(w, 20, 20) {
t.Fatal("right-clicking the page failed")
}
select {
case <-seen:
case <-time.After(wait.Guard):
t.Fatal("the listener that prevents the menu never heard of it")
}
// A menu would show at once, as the listener returns.
for range 10 {
if labels, shown := pageMenu(); shown {
dismissPageMenu()
t.Fatalf("PreventDefault: a menu shows %q", labels)
}
time.Sleep(30 * time.Millisecond)
}
}
// A page whose own contextmenu handler cancels the event shows no menu,
// and its listeners hear of none.
func TestPageContextMenuCancelled(t *testing.T) {
w := newWindow(t, mygo.WindowOptions{Title: "Cancelled context menu", Width: 400, Height: 300})
if !pageMenusHooked {
t.Skip("right-clicking a page is not hooked here")
}
w.Page().LoadHTML(contextMenuPage+`<script>addEventListener("contextmenu", (e) => { e.preventDefault(); window.cancelled = (window.cancelled || 0) + 1 })</script>`, "")
waitFor(t, w, "document.readyState === 'complete' && window.mygo")
heard := make(chan bool, 1)
w.Page().OnContextMenu(func(*mygo.ContextMenuEvent) { heard <- true })
if !rightClickPage(w, 20, 20) {
t.Fatal("right-clicking the page failed")
}
waitFor(t, w, "window.cancelled === 1")
select {
case <-heard:
t.Error("the listener heard of a menu the page cancelled")
case <-time.After(300 * time.Millisecond):
}
if labels, shown := pageMenu(); shown {
dismissPageMenu()
t.Errorf("a menu shows %q", labels)
}
}
@@ -0,0 +1,9 @@
//go:build !js && !(windows && (amd64 || arm64))
package e2e
// cookieViewApp is TestCookieViewReleased's helper, on Windows only.
func cookieViewApp() {}
// webViewProcesses is WebView2's processes, which run on Windows only.
func webViewProcesses() []int { return nil }
@@ -0,0 +1,123 @@
//go:build windows && (amd64 || arm64)
package e2e
import (
"fmt"
"os"
"os/exec"
"slices"
"strings"
"syscall"
"testing"
"time"
"unsafe"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/ui"
)
// TestCookieViewReleased makes cookie calls in an app showing native UI
// only, whose calls go through a hidden web view: once none needs it, the
// web view closes and WebView2's processes exit, unless it alone keeps a
// session cookie (#1109). The helper runs in a user data folder of its
// own, so that the browser process is its child, not that of the test
// process's pages.
func TestCookieViewReleased(t *testing.T) {
// Not t.TempDir: the browser processes outlive the helper for a
// moment and keep files of the folder open.
folder, err := os.MkdirTemp("", "mygo-cookie-view-")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
wait.Until(t, "WebView2's browser processes to let go of "+folder, func() bool { return os.RemoveAll(folder) == nil })
})
cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^$")
cmd.Env = append(os.Environ(), "MYGO_E2E_COOKIE_VIEW=1", "WEBVIEW2_USER_DATA_FOLDER="+folder)
out, err := cmd.CombinedOutput()
if err != nil || !strings.Contains(string(out), "cookie view: released\n") {
t.Errorf("exit: %v, output %q", err, out)
}
}
// cookieViewApp is the helper process of TestCookieViewReleased.
func cookieViewApp() {
report := func(format string, args ...any) { fmt.Printf("cookie view: "+format+"\n", args...) }
mygo.App.WhenReady(func() {
mygo.NewWindow(mygo.WindowOptions{Title: "Cookie view", Width: 200, Height: 100,
Content: ui.View(func(c *ui.Context) { ui.Text(c, "Native UI") })})
go func() {
defer mygo.App.Quit()
if _, err := mygo.Cookies.List(mygo.CookieFilter{URL: "https://example.com/"}); err != nil {
report("List: %v", err)
return
}
if !wait.Poll(func() bool { return len(webViewProcesses()) == 0 }) {
report("WebView2's processes still run after List: %v", webViewProcesses())
return
}
// A session cookie lives as long as WebView2's processes: the
// hidden web view stays. Checking that nothing happens may
// wait a while: longer than the backend keeps an idle hidden
// web view before it checks (cookieViewIdle), which a slow
// machine only makes this miss.
c := mygo.Cookie{Name: fmt.Sprintf("mygo%dsession", time.Now().UnixNano()), Value: "kept", Domain: "mygo-cookie-view.test"}
if err := mygo.Cookies.Set(c); err != nil {
report("Set: %v", err)
return
}
time.Sleep(8 * time.Second)
if list, err := mygo.Cookies.List(mygo.CookieFilter{Name: c.Name}); err != nil || len(list) != 1 {
report("the session cookie went: %+v %v", list, err)
return
}
if err := mygo.Cookies.Delete(c); err != nil {
report("Delete: %v", err)
return
}
if !wait.Poll(func() bool { return len(webViewProcesses()) == 0 }) {
report("WebView2's processes still run after Delete: %v", webViewProcesses())
return
}
report("released")
}()
})
if err := mygo.App.Run(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
// webViewProcesses returns the WebView2 processes this process started,
// and theirs.
func webViewProcesses() []int {
snap, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
if err != nil {
return nil
}
defer syscall.CloseHandle(snap)
children := map[int][]int{}
names := map[int]string{}
var e syscall.ProcessEntry32
e.Size = uint32(unsafe.Sizeof(e))
for err := syscall.Process32First(snap, &e); err == nil; err = syscall.Process32Next(snap, &e) {
children[int(e.ParentProcessID)] = append(children[int(e.ParentProcessID)], int(e.ProcessID))
names[int(e.ProcessID)] = syscall.UTF16ToString(e.ExeFile[:])
}
var out []int
seen := map[int]bool{os.Getpid(): true}
for queue := slices.Clone(children[os.Getpid()]); len(queue) > 0; queue = queue[1:] {
p := queue[0]
if seen[p] {
continue
}
seen[p] = true
if strings.EqualFold(names[p], "msedgewebview2.exe") {
out = append(out, p)
}
queue = append(queue, children[p]...)
}
return out
}
+268
View File
@@ -0,0 +1,268 @@
//go:build !js
package e2e
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
"testing"
"time"
"github.com/egoist/mygo"
)
// getCookie returns the cookie of name, domain and path.
func getCookie(name, domain, path string) (mygo.Cookie, bool, error) {
if path == "" {
path = "/"
}
list, err := mygo.Cookies.List(mygo.CookieFilter{Name: name, Domain: domain, Path: path})
for _, c := range list {
if c.Domain == domain {
return c, true, err
}
}
return mygo.Cookie{}, false, err
}
func TestCookies(t *testing.T) {
prefix := fmt.Sprintf("mygo%d", time.Now().UnixNano())
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/seed" {
http.SetCookie(w, &http.Cookie{Name: prefix + "server", Value: "private", Path: "/", HttpOnly: true})
}
if r.URL.Path == "/echo" {
fmt.Fprint(w, r.Header.Get("Cookie"))
return
}
fmt.Fprint(w, "<!doctype html><title>cookies</title><body>cookies</body>")
}))
defer server.Close()
w := newWindow(t, mygo.WindowOptions{Title: "Cookies", Width: 300, Height: 200})
if err := w.Page().LoadURL(server.URL + "/seed"); err != nil {
t.Fatal(err)
}
waitFor(t, w, "document.title === 'cookies'")
t.Cleanup(func() {
for _, suffix := range []string{"server", "plain", "hidden", "deep", "persistent"} {
_ = mygo.Cookies.Delete(mygo.Cookie{Name: prefix + suffix, Domain: "127.0.0.1"})
_ = mygo.Cookies.Delete(mygo.Cookie{Name: prefix + suffix, Domain: "127.0.0.1", Path: "/deep/path"})
}
})
c, found, err := getCookie(prefix+"server", "127.0.0.1", "/")
if err != nil || !found || !c.HTTPOnly {
t.Fatalf("server cookie: %+v %v %v", c, found, err)
}
for _, suffix := range []string{"plain", "hidden", "deep", "persistent"} {
c := mygo.Cookie{Name: prefix + suffix, Value: "value", Domain: "127.0.0.1", HTTPOnly: suffix == "hidden"}
if suffix == "deep" {
c.Path = "/deep/path"
}
if suffix == "persistent" {
c.Expires = time.Now().Add(time.Hour).UTC().Truncate(time.Second)
}
if err := mygo.Cookies.Set(c); err != nil {
t.Fatal(err)
}
got, found, err := getCookie(c.Name, c.Domain, c.Path)
if err != nil || !found || got.Expires.IsZero() != c.Expires.IsZero() {
t.Fatalf("roundtrip %s: %+v %v %v", suffix, got, found, err)
}
}
visible, err := mygo.EvalAs[string](w.Page(), "document.cookie")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(visible, prefix+"plain=") || strings.Contains(visible, prefix+"hidden=") || strings.Contains(visible, prefix+"server=") || strings.Contains(visible, prefix+"deep=") {
t.Fatalf("document.cookie visibility wrong: %q", visible)
}
header, err := mygo.EvalAs[string](w.Page(), "fetch('/echo').then(r=>r.text())")
if err != nil || !strings.Contains(header, prefix+"hidden=") {
t.Fatalf("HTTPOnly request missing: %q %v", header, err)
}
// A URL chooses the cookies a request to it sends, as the engine does.
sent, err := mygo.Cookies.List(mygo.CookieFilter{URL: server.URL + "/echo"})
if err != nil {
t.Fatal(err)
}
var names []string
for _, c := range sent {
if strings.HasPrefix(c.Name, prefix) {
names = append(names, strings.TrimPrefix(c.Name, prefix))
}
}
if strings.Join(names, " ") != "hidden persistent plain server" {
t.Fatalf("cookies for /echo: %q", names)
}
deep, err := mygo.Cookies.List(mygo.CookieFilter{URL: server.URL + "/deep/path/x", Name: prefix + "deep"})
if err != nil || len(deep) != 1 {
t.Fatalf("cookies for /deep/path/x: %+v %v", deep, err)
}
sibling := newWindow(t, mygo.WindowOptions{Title: "Cookie sibling", Width: 300, Height: 200})
if err := sibling.Page().LoadURL(server.URL); err != nil {
t.Fatal(err)
}
waitFor(t, sibling, "document.title === 'cookies'")
visible, err = mygo.EvalAs[string](sibling.Page(), "document.cookie")
if err != nil || !strings.Contains(visible, prefix+"plain=") {
t.Fatalf("shared cookie: %q %v", visible, err)
}
w.Destroy()
if err := mygo.Cookies.Delete(mygo.Cookie{Name: prefix + "plain", Domain: "127.0.0.1"}); err != nil {
t.Fatal(err)
}
if _, found, err := getCookie(prefix+"plain", "127.0.0.1", ""); err != nil || found {
t.Fatalf("deleted cookie still there: %v %v", found, err)
}
if _, found, err := getCookie(prefix+"deep", "127.0.0.1", "/deep/path"); err != nil || !found {
t.Fatalf("deep sibling lost: %v %v", found, err)
}
// A domain cookie of a site no page has opened, with every attribute.
want := mygo.Cookie{Name: prefix + "domain", Value: "v1", Domain: ".mygo-cookies.test", Path: "/",
Expires: time.Now().Add(time.Hour).UTC().Truncate(time.Second), Secure: true, HTTPOnly: true, SameSite: mygo.CookieSameSiteNone}
for _, site := range []mygo.CookieSameSite{mygo.CookieSameSiteNone, mygo.CookieSameSiteStrict, mygo.CookieSameSiteLax} {
want.SameSite = site
if err := mygo.Cookies.Set(want); err != nil {
t.Fatalf("Set %s: %v", site, err)
}
got, found, err := getCookie(want.Name, want.Domain, want.Path)
if err != nil || !found || got != want {
t.Fatalf("domain cookie, SameSite %s: %+v %v %v, want %+v", site, got, found, err, want)
}
}
// The host's cookie of the same name is another cookie.
host := mygo.Cookie{Name: want.Name, Value: "v2", Domain: "mygo-cookies.test"}
if err := mygo.Cookies.Set(host); err != nil {
t.Fatal(err)
}
if err := mygo.Cookies.Delete(host); err != nil {
t.Fatal(err)
}
if _, found, err := getCookie(host.Name, host.Domain, ""); err != nil || found {
t.Fatalf("deleted host cookie still there: %v %v", found, err)
}
if got, found, err := getCookie(want.Name, want.Domain, want.Path); err != nil || !found || got.Value != want.Value {
t.Fatalf("deleting the host's cookie changed the domain's: %+v %v %v", got, found, err)
}
// Values take what browsers take.
for _, v := range []string{`a b,"c"\d`, "caf\u00e9", "x=y, Path=/z"} {
want.Value = v
if err := mygo.Cookies.Set(want); err != nil {
t.Fatalf("Set value %q: %v", v, err)
}
if got, found, err := getCookie(want.Name, want.Domain, want.Path); err != nil || !found || got.Value != v {
t.Fatalf("value %q: %+v %v %v", v, got, found, err)
}
}
if err := mygo.Cookies.Delete(want); err != nil {
t.Fatal(err)
}
if _, found, err := getCookie(want.Name, want.Domain, want.Path); err != nil || found {
t.Fatalf("deleted domain cookie still there: %v %v", found, err)
}
if _, err := sibling.Page().Eval("localStorage.setItem('cookies-test','keep')"); err != nil {
t.Fatal(err)
}
if err := mygo.Cookies.Clear(); err != nil {
t.Fatal(err)
}
storage, err := mygo.EvalAs[string](sibling.Page(), "localStorage.getItem('cookies-test')")
if err != nil || storage != "keep" {
t.Fatalf("cookie Clear changed localStorage: %q %v", storage, err)
}
if err := mygo.App.ClearBrowsingData(); err != nil {
t.Fatal(err)
}
sibling.Page().Reload()
waitFor(t, sibling, "document.title === 'cookies' && localStorage.getItem('cookies-test') === null")
}
func TestCookieCallbackStress(t *testing.T) {
w := newWindow(t, mygo.WindowOptions{Title: "Cookie callback stress", Width: 200, Height: 100})
w.Page().LoadHTML("<title>cookie stress</title>", "")
waitFor(t, w, "document.title === 'cookie stress'")
for i := 0; i < 2100; i++ {
if _, err := mygo.Cookies.List(mygo.CookieFilter{}); err != nil {
t.Fatalf("List %d: %v", i, err)
}
}
}
// TestCookiesBeforePages sets a cookie before a window shows a page, which
// its first request sends. On Windows, without another window showing a
// page, the cookie goes through a hidden web view.
func TestCookiesBeforePages(t *testing.T) {
name := fmt.Sprintf("mygo%dearly", time.Now().UnixNano())
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c, _ := r.Cookie(name)
v := ""
if c != nil {
v = c.Value
}
fmt.Fprintf(w, "<!doctype html><title>early:%s</title>", v)
}))
defer server.Close()
host := strings.TrimPrefix(server.URL, "http://")
host = host[:strings.LastIndex(host, ":")]
if err := mygo.Cookies.Set(mygo.Cookie{Name: name, Value: "first", Domain: host}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = mygo.Cookies.Delete(mygo.Cookie{Name: name, Domain: host}) })
w := newWindow(t, mygo.WindowOptions{Title: "Early cookie", Width: 200, Height: 100, URL: server.URL})
waitFor(t, w, "document.title === 'early:first'")
}
// TestCookieCallsWhileWindowOpens reads cookies as a window is made, before
// any window shows a page, so on Windows the calls take the hidden web view
// while the window's own web view is being made: closing that view from the
// callback that finished the calls crashed the message loop. The test
// process has windows showing pages from TestMain, so the calls run in a
// helper process with none.
func TestCookieCallsWhileWindowOpens(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^$")
cmd.Env = append(os.Environ(), "MYGO_E2E_COOKIES_WHILE_OPENING=1")
out, err := cmd.CombinedOutput()
if err != nil || !strings.Contains(string(out), "cookies: the page loaded\n") {
t.Errorf("exit: %v, output %q", err, out)
}
}
// cookiesWhileOpening is the helper process of TestCookieCallsWhileWindowOpens.
func cookiesWhileOpening() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "<!doctype html><title>opened</title>")
}))
defer server.Close()
mygo.App.WhenReady(func() {
go func() {
defer mygo.App.Quit()
w := mygo.NewWindow(mygo.WindowOptions{Title: "Cookies while opening", Width: 200, Height: 100, URL: server.URL})
defer w.Destroy()
for i := 0; i < 16; i++ {
if _, err := mygo.Cookies.List(mygo.CookieFilter{}); err != nil {
fmt.Printf("cookies: List %d: %v\n", i, err)
return
}
time.Sleep(50 * time.Millisecond)
}
for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) {
if loaded, err := mygo.EvalAs[bool](w.Page(), "document.title === 'opened'"); err == nil && loaded {
fmt.Println("cookies: the page loaded")
return
}
}
fmt.Println("cookies: the page did not load")
}()
})
if err := mygo.App.Run(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
@@ -0,0 +1,30 @@
//go:build darwin && !ios
package e2e
import (
"testing"
"github.com/egoist/mygo"
)
// TestCornerRadius reads the corners macOS rounds windows with: a titled window's the system's, larger with
// TitleBarHiddenInset's toolbar than without (26 and 16 on macOS 26), a frameless one's its CornerRadius, or the system's
// without one.
func TestCornerRadius(t *testing.T) {
plain := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, TitleBarStyle: mygo.TitleBarHidden})
inset := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, TitleBarStyle: mygo.TitleBarHiddenInset})
rp, ri := plain.CornerRadius(), inset.CornerRadius()
if rp <= 0 || ri < rp {
t.Errorf("titled: %v without a toolbar, %v with one; want both rounded, the toolbar's larger", rp, ri)
}
t.Logf("corners: %v without a toolbar, %v with one", rp, ri)
rounded := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, Frameless: true, CornerRadius: 12})
if r := rounded.CornerRadius(); r != 12 {
t.Errorf("frameless with CornerRadius 12: %v", r)
}
plainFrameless := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, Frameless: true})
if r := plainFrameless.CornerRadius(); r != rp { // titled under its hidden title bar: the system's corners
t.Errorf("frameless without CornerRadius: %v, want the system's %v", r, rp)
}
}
+14
View File
@@ -0,0 +1,14 @@
//go:build darwin && !ios
package e2e
import (
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/darwin"
"github.com/egoist/mygo/transfer"
)
func dropNativeData(w *mygo.Window, x, y float64, d transfer.Data, ops transfer.Operation) (operation transfer.Operation, dropped, supported bool) {
mygo.RunOnMain(func() { operation, dropped = darwin.TestDropData(w.NativeHandle(), x, y, d, ops) })
return operation, dropped, true
}
+175
View File
@@ -0,0 +1,175 @@
//go:build linux && !android && (amd64 || arm64) && !android
package e2e
import (
"bytes"
"path/filepath"
"slices"
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/transfer"
"github.com/egoist/mygo/ui"
)
func gtkPressSource(t *testing.T, w *mygo.Window) {
t.Helper()
var supported bool
mygo.RunOnMain(func() {
supported = linux.TestMoveSurfacePointer(w.NativeHandle(), 30, 30) && linux.TestPressButton(true)
})
if !supported {
t.Skip("GTK drag tracking needs X11 and XTEST")
}
eventually(t, "the source pointer press", func() bool {
ready := false
mygo.RunOnMain(func() { ready = linux.TestDataDragReady(w.NativeHandle()) })
return ready
})
}
func gtkDragResult(t *testing.T, result <-chan transfer.Result) transfer.Result {
t.Helper()
select {
case r := <-result:
return r
case <-time.After(wait.Guard):
t.Fatal("GTK drag did not complete")
}
return transfer.Result{}
}
// TestNativeGTKDataDrag uses GTK's tracker and XTEST input, including the
// asynchronous selection path used for sources outside the MyGo registry.
func TestNativeGTKDataDrag(t *testing.T) {
custom := transfer.Format("application/vnd.mygo.e2e+json")
var frames, providers atomic.Int32
var drops []transfer.Drop
var over atomic.Bool
targetOperations := transfer.Copy | transfer.Move
source := newWindow(t, mygo.WindowOptions{Title: "GTK source", X: 30, Y: 40, Width: 240, Height: 200, Content: ui.View(func(c *ui.Context) { ui.Box(c).Fill() })})
target := newWindow(t, mygo.WindowOptions{Title: "GTK destination", X: 340, Y: 40, Width: 240, Height: 200, Content: ui.View(func(c *ui.Context) {
frames.Add(1)
e := ui.Box(c).Fill()
opts := transfer.DropOptions{Formats: []transfer.Format{custom, transfer.Text, transfer.FileList, transfer.URIList}, Operations: targetOperations}
_, hover := ui.DataDragOver(e, opts)
over.Store(hover)
if d, ok := ui.DropData(e, opts); ok {
drops = append(drops, d)
}
})})
t.Cleanup(func() {
mygo.RunOnMain(func() { linux.TestPressButton(false); linux.TestCancelDataDrag(source.NativeHandle()) })
})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
url, _ := transfer.URLData("https://example.com/a#b")
path := filepath.Join(t.TempDir(), "file #%.txt")
files, _ := transfer.FileData(path)
customData := transfer.New(transfer.NewItem(transfer.Lazy(custom, func() ([]byte, error) { providers.Add(1); return []byte("{\"id\":7}"), nil })))
cases := []struct {
name string
data transfer.Data
want transfer.Operation
}{
{"text", transfer.TextData("hello 日本語"), transfer.Copy},
{"url", url, transfer.Copy},
{"files", files, transfer.Copy},
{"custom move", customData, transfer.Move},
}
for n, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if tc.want == transfer.Move {
before := frames.Load()
target.Update(func() { targetOperations = transfer.Move })
eventually(t, "move-only destination frame", func() bool { return frames.Load() > before })
}
gtkPressSource(t, source)
result := make(chan transfer.Result, 2)
var started bool
mygo.RunOnMain(func() {
started = linux.TestStartSerializedDrag(source.NativeHandle(), tc.data, transfer.Copy|transfer.Move, func(r transfer.Result) { result <- r })
})
if !started {
t.Fatal("native source did not start")
}
mygo.RunOnMain(func() { linux.TestMoveSurfacePointer(target.NativeHandle(), 60, 60) })
eventually(t, "the native destination hover", over.Load)
if providers.Load() != 0 {
t.Fatal("GTK fetched custom data during hover")
}
mygo.RunOnMain(func() { linux.TestPressButton(false) })
r := gtkDragResult(t, result)
if r.Operation != tc.want || r.Err != nil {
t.Fatalf("native result %+v", r)
}
eventually(t, "the serialized drop", func() bool { count := 0; mygo.RunOnMain(func() { count = len(drops) }); return count == n+1 })
var got transfer.Data
mygo.RunOnMain(func() { got = drops[n].Data })
switch tc.name {
case "files":
paths, err := got.Files()
if err != nil || !slices.Equal(paths, []string{path}) {
t.Fatalf("files %v: %v", paths, err)
}
case "custom move":
b, err := got.Read(custom)
if err != nil || !bytes.Equal(b, []byte("{\"id\":7}")) {
t.Fatalf("custom %q: %v", b, err)
}
default:
for _, f := range tc.data.Formats() {
want, _ := tc.data.Read(f)
b, err := got.Read(f)
if err != nil || !bytes.Equal(b, want) {
t.Errorf("%s %q: %v", f, b, err)
}
}
}
if tc.name == "custom move" && providers.Load() != 1 {
t.Fatalf("provider called %d times", providers.Load())
}
select {
case <-result:
t.Fatal("source completed twice")
default:
}
})
}
}
func TestNativeGTKDragCancellationCleanup(t *testing.T) {
for _, destroy := range []bool{false, true} {
t.Run(map[bool]string{false: "cancel", true: "source destruction"}[destroy], func(t *testing.T) {
source := newWindow(t, mygo.WindowOptions{Title: "GTK cancel", X: 30, Y: 40, Width: 240, Height: 200, Content: ui.View(func(c *ui.Context) { ui.Box(c).Fill() })})
gtkPressSource(t, source)
result := make(chan transfer.Result, 2)
mygo.RunOnMain(func() {
linux.TestStartSerializedDrag(source.NativeHandle(), transfer.TextData("cancel"), transfer.Copy, func(r transfer.Result) { result <- r })
})
if destroy {
source.Destroy()
} else {
mygo.RunOnMain(func() { linux.TestCancelDataDrag(source.NativeHandle()) })
}
mygo.RunOnMain(func() { linux.TestPressButton(false) })
r := gtkDragResult(t, result)
if !r.Canceled || !r.Escaped || r.Operation != transfer.None {
t.Fatalf("result %+v", r)
}
eventually(t, "released GTK drag resources", func() bool {
count := 1
mygo.RunOnMain(func() { count = linux.TestDataDragResources() })
return count == 0
})
select {
case <-result:
t.Fatal("source completed twice")
default:
}
})
}
}
+12
View File
@@ -0,0 +1,12 @@
//go:build !(darwin && !ios) && !(windows && (amd64 || arm64)) && !js
package e2e
import (
"github.com/egoist/mygo"
"github.com/egoist/mygo/transfer"
)
func dropNativeData(*mygo.Window, float64, float64, transfer.Data, transfer.Operation) (transfer.Operation, bool, bool) {
return transfer.None, false, false
}
+81
View File
@@ -0,0 +1,81 @@
//go:build !js
package e2e
import (
"bytes"
"errors"
"path/filepath"
"slices"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/transfer"
"github.com/egoist/mygo/ui"
)
// TestNativeDataRepresentations drives native serialized providers and
// destination callbacks. The Linux test below also drives the GTK tracker
// and asynchronous selection exchange with XTEST input.
func TestNativeDataRepresentations(t *testing.T) {
custom := transfer.Format("application/vnd.mygo.e2e+json")
opts := transfer.DropOptions{Formats: []transfer.Format{custom, transfer.Text, transfer.FileList, transfer.URIList}, Operations: transfer.Copy | transfer.Move}
var frames atomic.Int32
var drops []transfer.Drop
w := newWindow(t, mygo.WindowOptions{Title: "Data destinations", Width: 400, Height: 220, Content: ui.View(func(c *ui.Context) {
frames.Add(1)
e := ui.Box(c).Size(220, 150)
if d, ok := ui.DropData(e, opts); ok {
drops = append(drops, d)
}
})})
eventually(t, "a destination frame", func() bool { return frames.Load() > 0 })
url, _ := transfer.URLData("https://example.com/a?q=1#b")
file := filepath.Join(t.TempDir(), "sp ace#%.txt")
files, _ := transfer.FileData(file)
var calls atomic.Int32
for n, data := range []transfer.Data{transfer.TextData("hello 日本語"), url, files, transfer.New(transfer.NewItem(transfer.Lazy(custom, func() ([]byte, error) { calls.Add(1); return []byte(`{"id":7}`), nil })))} {
op, dropped, supported := dropNativeData(w, 50, 50, data, transfer.Copy|transfer.Move)
if !supported {
t.Skip("native serialized drop hook unavailable; GTK uses TestNativeGTKDataDrag")
}
if !dropped || op != transfer.Copy {
t.Fatalf("case %d: effect %v, dropped %v", n, op, dropped)
}
eventually(t, "the delivered data", func() bool { count := 0; mygo.RunOnMain(func() { count = len(drops) }); return count == n+1 })
var got transfer.Data
mygo.RunOnMain(func() { got = drops[n].Data })
for _, f := range data.Formats() {
want, _ := data.Read(f)
actual, err := got.Read(f)
if err != nil || !bytes.Equal(actual, want) {
t.Errorf("case %d %s: %q, want %q (%v)", n, f, actual, want, err)
}
}
}
if calls.Load() != 2 {
t.Fatalf("provider requests %d; native snapshot and original each read once", calls.Load())
}
mygo.RunOnMain(func() { opts.Operations = transfer.Move })
w.Invalidate()
before := frames.Load()
eventually(t, "move-only destination frame", func() bool { return frames.Load() > before })
if op, dropped, _ := dropNativeData(w, 50, 50, transfer.TextData("move"), transfer.Copy|transfer.Move); op != transfer.Move || !dropped {
t.Fatalf("move negotiation: %v, %v", op, dropped)
}
if op, dropped, _ := dropNativeData(w, 50, 50, transfer.TextData("copy only"), transfer.Copy); op != transfer.None || dropped {
t.Fatalf("incompatible effects: %v, %v", op, dropped)
}
mygo.RunOnMain(func() { opts = transfer.DropOptions{Formats: []transfer.Format{custom}} })
w.Invalidate()
before = frames.Load()
eventually(t, "custom-only destination", func() bool { return frames.Load() > before })
broken := transfer.New(transfer.NewItem(transfer.Lazy(custom, func() ([]byte, error) { return nil, errors.New("cannot serialize") })))
if _, dropped, _ := dropNativeData(w, 50, 50, broken, transfer.Copy); dropped {
t.Fatal("failed native provider acknowledged a drop")
}
if data, _ := files.Files(); !slices.Equal(data, []string{file}) {
t.Fatal("file transfer changed its source")
}
}
+14
View File
@@ -0,0 +1,14 @@
//go:build windows && (amd64 || arm64)
package e2e
import (
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/windows"
"github.com/egoist/mygo/transfer"
)
func dropNativeData(w *mygo.Window, x, y float64, d transfer.Data, ops transfer.Operation) (operation transfer.Operation, dropped, supported bool) {
mygo.RunOnMain(func() { operation, dropped = windows.TestDropData(w.NativeHandle(), x, y, d, ops) })
return operation, dropped, true
}
+113
View File
@@ -0,0 +1,113 @@
//go:build linux && !android && (amd64 || arm64) && !android
package e2e
import (
"fmt"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/ui"
)
func decorations(w *mygo.Window) (d linux.Decorations) {
mygo.RunOnMain(func() { d = linux.TestDecorations(w.NativeHandle()) })
return d
}
// GTK decorates frameless windows and windows with a hidden title bar
// itself on Wayland, with an empty title bar: its shadow and border go
// around the page, which keeps the size asked for, and GTK drops them while
// the window is maximized or in full screen (#597). Windows without a
// shadow, transparent ones and panels stay undecorated, as every window
// without a title bar on X11.
func TestClientSideDecorations(t *testing.T) {
content := func() *ui.Content { return ui.View(func(c *ui.Context) { ui.Text(c, "decorations") }) }
for _, tc := range []struct {
name string
opts mygo.WindowOptions
csd bool
}{
{"frameless", mygo.WindowOptions{Frameless: true}, true},
{"hidden title bar", mygo.WindowOptions{TitleBarStyle: mygo.TitleBarHidden}, true},
{"hidden window buttons", mygo.WindowOptions{TitleBarStyle: mygo.TitleBarHidden, HideWindowButtons: true}, true},
{"fixed frameless", mygo.WindowOptions{Frameless: true, DisableResize: true}, true},
{"without shadow", mygo.WindowOptions{Frameless: true, DisableShadow: true}, false},
{"transparent", mygo.WindowOptions{Frameless: true, Transparent: true}, false},
{"panel", mygo.WindowOptions{Frameless: true, Panel: true}, false},
} {
t.Run(tc.name, func(t *testing.T) {
opts := tc.opts
opts.Width, opts.Height, opts.UseContentSize = 400, 300, true
opts.Content = content()
w := newWindow(t, opts)
d := decorations(w)
want := tc.csd && !d.OnX11
if d.CSD != want {
t.Fatalf("GTK decorates the window: %v, want %v (X11: %v)", d.CSD, want, d.OnX11)
}
size := func(width, height int) func(linux.Decorations) bool {
return func(d linux.Decorations) bool { return d.Content == [2]int{width, height} }
}
shadowed := func(d linux.Decorations) bool {
return d.Room[0] > 0 && d.Room[1] > 0 && d.Room[2] > 0 && d.Room[3] > 0
}
bare := func(d linux.Decorations) bool { return d.Room == [4]int{} }
// is waits for the window's decorations and its content to be
// laid out as asked.
is := func(what string, conds ...func(linux.Decorations) bool) {
t.Helper()
var d linux.Decorations
if !wait.Poll(func() bool {
d = decorations(w)
for _, c := range conds {
if !c(d) {
return false
}
}
return true
}) {
t.Fatalf("%s never happened: %+v", what, d)
}
}
if !want {
is("an undecorated window of 400x300", bare, size(400, 300))
if tc.opts.DisableShadow && w.HasShadow() {
t.Error("HasShadow = true, want false")
}
return
}
is("decorations around content of 400x300", shadowed, size(400, 300))
if width, height := w.ContentSize(); width != 400 || height != 300 {
t.Errorf("content size = %dx%d, want 400x300", width, height)
}
if b := w.Bounds(); b.Width != 400 || b.Height != 300 {
t.Errorf("bounds = %+v, want 400x300 without the shadow", b)
}
if !w.HasShadow() {
t.Error("HasShadow = false, want true")
}
if tc.opts.DisableResize {
return
}
// Maximized and in full screen, GTK drops the decorations.
w.Maximize()
eventually(t, "a maximized window", w.IsMaximized)
is("a maximized window without decorations", bare)
w.Unmaximize()
eventually(t, "an unmaximized window", func() bool { return !w.IsMaximized() })
is("the decorations back around content of 400x300", shadowed, size(400, 300))
w.SetFullScreen(true)
eventually(t, "a window in full screen", w.IsFullScreen)
display := mygo.Screen.DisplayNearestPoint(mygo.Point{X: w.Bounds().X, Y: w.Bounds().Y}).Bounds
is(fmt.Sprintf("full screen content of %dx%d", display.Width, display.Height), bare, size(display.Width, display.Height))
w.SetFullScreen(false)
eventually(t, "a window out of full screen", func() bool { return !w.IsFullScreen() })
is("the decorations back around content of 400x300", shadowed, size(400, 300))
})
}
}
+152
View File
@@ -0,0 +1,152 @@
//go:build darwin && !ios
package e2e
import (
"path/filepath"
"slices"
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/darwin"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/ui"
)
// TestDialogFromClick shows each kind of dialog from a button's Clicked,
// as the frame that reports the click runs: the dialog shows and waits
// until it is dismissed. A frame drawn as AppKit displayed the view ran in
// its display cycle, where the panel never showed and runModal returned at
// once, and a sheet never showed nor ended (#883). The window draws again
// once the dialog is gone.
func TestDialogFromClick(t *testing.T) {
dir := t.TempDir()
cases := []struct {
name string
show func(parent *mygo.Window)
}{
{"open", func(*mygo.Window) {
mygo.Dialog.Open(mygo.OpenDialogOptions{DefaultPath: dir, Directory: true, Multiple: true})
}},
{"save", func(*mygo.Window) {
mygo.Dialog.Save(mygo.SaveDialogOptions{DefaultPath: filepath.Join(dir, "note.txt")})
}},
{"message", func(*mygo.Window) {
mygo.Dialog.Message(mygo.MessageOptions{Message: "From a click", Buttons: []string{"OK", "Cancel"}})
}},
{"open sheet", func(w *mygo.Window) {
mygo.Dialog.Open(mygo.OpenDialogOptions{Parent: w, DefaultPath: dir})
}},
{"message sheet", func(w *mygo.Window) {
mygo.Dialog.Message(mygo.MessageOptions{Parent: w, Message: "From a click"})
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var w *mygo.Window // main thread only
var frames atomic.Int32
var clicked, returned atomic.Bool
view := func(c *ui.Context) {
frames.Add(1)
if ui.Button(c, "Show").Width(120).Height(30).Clicked() {
clicked.Store(true)
tc.show(w)
returned.Store(true)
}
}
var handle uintptr
mygo.RunOnMain(func() {
w = mygo.NewWindow(mygo.WindowOptions{Title: "Dialog from a click", Width: 300, Height: 200, Content: ui.View(view)})
handle = w.NativeHandle()
})
win := w
t.Cleanup(win.Destroy)
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
// Frames pause, so that the click's frame is one after a pause,
// which AppKit drew as it displayed the view.
time.Sleep(200 * time.Millisecond)
// The button lays out at the top-left of the window.
click(win, 60, 15)
eventually(t, "the click", clicked.Load)
eventually(t, "the dialog to show", func() bool {
var running, shows bool
mygo.RunOnMain(func() { running, shows = darwin.TestModal(handle) })
return running && shows
})
if returned.Load() {
t.Fatal("the dialog returned before it was dismissed")
}
var canceled bool
mygo.RunOnMain(func() { canceled = darwin.TestCancelModal(handle) })
if !canceled {
t.Fatal("no dialog to dismiss")
}
eventually(t, "the dialog to return", returned.Load)
n := frames.Load()
win.Invalidate()
eventually(t, "a frame after the dialog", func() bool { return frames.Load() > n })
})
}
}
func TestMessageButtonRoles(t *testing.T) {
type key struct {
code uint16
chars string
cmd bool
}
ret, esc, cmdPeriod := key{36, "\r", false}, key{53, "\x1b", false}, key{47, ".", true}
cancelIsDefault := mygo.MessageOptions{Buttons: []string{"Continue Editing", "Discard"}, DestructiveButtons: []int{1}}
// The first button must not be destructive: AppKit may suppress Return
// for it even when it is the default.
noDefault := mygo.MessageOptions{Buttons: []string{"Continue", "Cancel"}, DefaultButton: -1}
cases := []struct {
name string
opts mygo.MessageOptions
keys []key
destructive []bool
want int
}{
{"Return on a default that cancels", cancelIsDefault, []key{ret}, []bool{false, true}, 0},
{"Escape on a default that cancels", cancelIsDefault, []key{esc}, []bool{false, true}, 0},
{"Return and Cmd+. without a default", noDefault, []key{ret, cmdPeriod}, []bool{false, false}, 1},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var w *mygo.Window
mygo.RunOnMain(func() {
w = mygo.NewWindow(mygo.WindowOptions{Title: "Message keys", Width: 300, Height: 200, Content: ui.View(func(*ui.Context) {})})
})
t.Cleanup(w.Destroy)
eventually(t, "the window to show", w.IsVisible)
answered := make(chan mygo.MessageResult, 1)
go func() {
opts := tc.opts
opts.Parent, opts.Message = w, "Message keys"
res, err := mygo.Dialog.Message(opts)
if err != nil {
t.Error(err)
}
answered <- res
}()
handle := w.NativeHandle()
var destructive []bool
eventually(t, "the sheet", func() bool {
var ok bool
mygo.RunOnMain(func() { destructive, ok = darwin.TestSheetDestructive(handle) })
return ok && len(destructive) == len(tc.destructive)
})
if !slices.Equal(destructive, tc.destructive) {
t.Errorf("destructive buttons %v, want %v", destructive, tc.destructive)
}
for _, k := range tc.keys {
mygo.RunOnMain(func() { darwin.TestSheetKey(handle, k.code, k.chars, k.cmd) })
}
if res := wait.For(t, "the message's answer", answered); res.Button != tc.want {
t.Errorf("the keys answered button %d, want %d", res.Button, tc.want)
}
})
}
}
+214
View File
@@ -0,0 +1,214 @@
//go:build !js
package e2e
import (
"errors"
"io"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/egoist/mygo"
)
// notes are the documents of the tests: plain text, asking to save when
// they close, as on Windows and Linux.
var notes = sync.OnceValue(func() *mygo.Documents[string] {
return mygo.NewDocuments(mygo.DocumentsOptions[string]{
Types: []mygo.DocumentType{{Name: "E2E Note", Extensions: []string{"e2enote"}}},
Autosave: mygo.AutosaveOff,
NoUntitled: true,
Read: func(r io.Reader) (string, error) {
b, err := io.ReadAll(r)
return string(b), err
},
Write: func(w io.Writer, s string) error {
_, err := io.WriteString(w, s)
return err
},
Window: func(*mygo.Document[string]) *mygo.Window {
return mygo.NewWindow(mygo.WindowOptions{Width: 420, Height: 260})
},
})
})
// TestDocumentWindow opens a document and checks what its window shows
// of it: its name in the title, its file's icon in the title bar and the
// dot of an edited document on macOS, a "*" before the title elsewhere.
// Saving from the File menu writes it, and closing it edited asks first
// (macOS, whose sheet the test answers).
func TestDocumentWindow(t *testing.T) {
mygo.App.SetPath(mygo.PathUserData, t.TempDir())
defer mygo.App.SetPath(mygo.PathUserData, "")
docs := notes()
old := mygo.App.Menu()
mygo.App.SetMenu(mygo.NewMenu([]*mygo.MenuItem{{Role: mygo.RoleAppMenu}, {Role: mygo.RoleFileMenu}}))
defer mygo.App.SetMenu(old)
dir, _ := filepath.EvalSymlinks(t.TempDir())
path := filepath.Join(dir, "chrome.e2enote")
if err := os.WriteFile(path, []byte("one"), 0o644); err != nil {
t.Fatal(err)
}
doc, err := docs.Open(path)
if err != nil {
t.Fatal(err)
}
w := doc.Window()
t.Cleanup(func() {
doc.SetEdited(false)
if !w.IsDestroyed() {
w.Destroy()
}
})
want := "chrome.e2enote"
if runtime.GOOS != "darwin" {
want += " - " + mygo.App.Name()
}
if _, _, _, _, ok := documentChrome(w); !ok {
t.Skip("no window title to read on " + runtime.GOOS)
}
eventually(t, "the document's title", func() bool {
title, file, icon, _, _ := documentChrome(w)
return title == want && (runtime.GOOS != "darwin" || file == path && icon)
})
doc.Set("two")
eventually(t, "the edited mark", func() bool {
title, _, _, edited, _ := documentChrome(w)
if runtime.GOOS == "darwin" {
return edited && title == want
}
return title == "*"+want
})
if w.Title() != want {
t.Errorf("Title() = %q, want it without the mark", w.Title())
}
if err := activateMenu(w, "File", "Save"); err != nil {
t.Fatalf("File > Save: %v", err)
}
eventually(t, "the document to be saved", func() bool {
b, _ := os.ReadFile(path)
return string(b) == "two" && !doc.IsEdited()
})
eventually(t, "the edited mark to go", func() bool {
title, _, _, edited, _ := documentChrome(w)
return !edited && title == want
})
if _, _, _, supported := sheet(w); !supported {
return
}
// Revert asks, then reads the file again.
doc.Set("unwanted")
eventually(t, "the edited mark", func() bool { _, _, _, edited, _ := documentChrome(w); return edited })
if err := activateMenu(w, "File", "Revert to Saved"); err != nil {
t.Fatalf("File > Revert to Saved: %v", err)
}
eventually(t, "the sheet asking to revert", func() bool {
texts, buttons, ok, _ := sheet(w)
return ok && slices.Contains(texts, "Do you want to revert “chrome.e2enote” to the last saved version?") && len(buttons) == 2
})
endSheetButton(w, 0)
eventually(t, "the document to revert", func() bool { return doc.Content() == "two" && !doc.IsEdited() })
// Closing it edited asks first, in a sheet; Cancel keeps it open.
doc.Set("three")
w.Close()
var texts, buttons []string
eventually(t, "the sheet asking to save", func() bool {
var ok bool
texts, buttons, ok, _ = sheet(w)
return ok && len(buttons) == 3
})
if !slices.Contains(texts, "Do you want to save the changes made to the document “chrome.e2enote”?") ||
!slices.Equal(buttons, []string{"Save", "Cancel", "Don’t Save"}) {
t.Errorf("the sheet says %q with %q", texts, buttons)
}
if !endSheetButton(w, slices.Index(buttons, "Cancel")) {
t.Fatal("no sheet to end")
}
eventually(t, "the sheet to close", func() bool { _, _, ok, _ := sheet(w); return !ok })
if w.IsDestroyed() {
t.Fatal("Cancel closed the window")
}
// Save saves it, then closes it.
w.Close()
eventually(t, "the sheet asking again", func() bool { _, b, ok, _ := sheet(w); return ok && len(b) == 3 })
endSheetButton(w, 0)
eventually(t, "the window to close", w.IsDestroyed)
if b, _ := os.ReadFile(path); string(b) != "three" {
t.Errorf("the file has %q after Save", b)
}
if !slices.ContainsFunc(mygo.App.RecentDocuments(), func(p string) bool { return strings.HasSuffix(p, "chrome.e2enote") }) {
t.Errorf("recent documents %q", mygo.App.RecentDocuments())
}
}
// TestDocumentOtherApps checks that a document follows what other apps do
// to its file, through the watch of the file: a save as editors do it, a
// rename and a removal.
func TestDocumentOtherApps(t *testing.T) {
mygo.App.SetPath(mygo.PathUserData, t.TempDir())
defer mygo.App.SetPath(mygo.PathUserData, "")
dir, _ := filepath.EvalSymlinks(t.TempDir())
path := filepath.Join(dir, "other.e2enote")
if err := os.WriteFile(path, []byte("one"), 0o644); err != nil {
t.Fatal(err)
}
doc, err := notes().Open(path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if w := doc.Window(); w != nil && !w.IsDestroyed() {
w.Destroy()
}
})
if err := os.WriteFile(path+".tmp", []byte("two, longer"), 0o644); err != nil {
t.Fatal(err)
}
if err := renameAsApps(path+".tmp", path); err != nil {
t.Fatal(err)
}
eventually(t, "the document to read the new file", func() bool { return doc.Content() == "two, longer" })
renamed := filepath.Join(dir, "renamed.e2enote")
if err := renameAsApps(path, renamed); err != nil {
t.Fatal(err)
}
eventually(t, "the document to follow the rename", func() bool { return doc.Path() == renamed })
if err := os.WriteFile(renamed, []byte("three"), 0o644); err != nil {
t.Fatal(err)
}
eventually(t, "the document to read the renamed file", func() bool { return doc.Content() == "three" })
if err := os.Remove(renamed); err != nil {
t.Fatal(err)
}
eventually(t, "the document to be deleted", func() bool { return doc.State().Deleted })
}
// renameAsApps renames as the apps saving a document do on Windows: they
// try again while the system refuses, which it does as long as any
// program holds either file open without sharing its deletion, as a
// virus scanner reading a file just written, or the shell a recent
// document. The guard only stops a rename that never succeeds.
func renameAsApps(from, to string) error {
deadline := time.Now().Add(time.Minute)
for {
err := os.Rename(from, to)
if err == nil || runtime.GOOS != "windows" || time.Now().After(deadline) ||
// ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION
!errors.Is(err, syscall.Errno(5)) && !errors.Is(err, syscall.Errno(32)) {
return err
}
time.Sleep(10 * time.Millisecond)
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,9 @@
//go:build !js && !(windows && (amd64 || arm64))
package e2e
import "github.com/egoist/mygo"
// firstFrameRevealed reports whether w shows its first frame once shown:
// only Windows keeps a window out of sight after it showed (cloaked).
func firstFrameRevealed(*mygo.Window) bool { return true }
+98
View File
@@ -0,0 +1,98 @@
//go:build !js
package e2e
import (
"math"
"os"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/ui"
)
// TestContentWindowHiddenReadyToShow checks that a window of native UI
// made hidden draws its first frame while hidden, which no paint or
// refresh of the display asks for, and so becomes ready to show:
// OnReadyToShow(w.Show) never showed it (#905). It shows once shown, with
// its content drawn as any window's: on the GPU where it draws there.
func TestContentWindowHiddenReadyToShow(t *testing.T) {
var frames atomic.Int32
var firstWidth atomic.Uint64 // of the first frame drawn
var w *mygo.Window
readyHidden := make(chan bool, 1)
mygo.RunOnMain(func() {
w = newWindow(t, mygo.WindowOptions{Width: 320, Height: 240, Hidden: true, Content: ui.View(func(c *ui.Context) {
frames.Add(1)
c.Root().Background(ui.RGB(30, 30, 30)).Draw(func(_ *ui.Painter, r ui.Rect) {
firstWidth.CompareAndSwap(0, math.Float64bits(float64(r.W)))
})
})})
w.OnReadyToShow(func() {
readyHidden <- !w.IsVisible()
w.Show()
})
})
if !wait.For(t, "ready to show", readyHidden) {
t.Fatalf("ready to show once visible, not while hidden (%d builds)", frames.Load())
}
// Drawn at the window's size, not at none before it ever showed.
if got := math.Float64frombits(firstWidth.Load()); got < 100 {
t.Errorf("the first frame drawn %v wide", got)
}
eventually(t, "the window shown", func() bool { return w.IsVisible() && firstFrameRevealed(w) })
// With MYGO_GPU=1 Linux draws with OpenGL without a GPU too: the first
// frame, drawn in memory while the window was hidden, leaves the frames
// once shown to OpenGL.
if os.Getenv("MYGO_GPU") == "1" {
if _, _, _, _, ok := glSurface(w); ok {
var how string
var pix []byte
eventually(t, "a frame drawn in the GtkGLArea", func() bool {
how, pix, _, _, _ = glSurface(w)
return how != ""
})
if how != "opengl" || len(pix) < 4 {
t.Fatalf("the surface draws %q, not with OpenGL", how)
}
if c := pix[:4]; c[0] != 30 || c[1] != 30 || c[2] != 30 {
t.Errorf("the background is %v (BGRA) in the GtkGLArea", c)
}
}
}
}
// TestContentViewRunsAfterNewWindow checks that the view of a window of
// native UI that NewWindow shows first runs once NewWindow returned on the
// main thread, so that it can use the window kept from NewWindow: systems
// draw a window's first frame as it shows, as AppKit may in orderFront and
// Windows in the resize of a window maximized (#1053). The window shows
// all the same, with its first frame.
func TestContentViewRunsAfterNewWindow(t *testing.T) {
for _, maximized := range []bool{false, true} {
var w *mygo.Window
var frames, early atomic.Int32
mygo.RunOnMain(func() {
w = newWindow(t, mygo.WindowOptions{Title: "After NewWindow", Width: 320, Height: 240, Maximized: maximized, Content: ui.View(func(c *ui.Context) {
frames.Add(1)
if w == nil {
early.Add(1)
return
}
ui.Text(c, w.Title())
})})
if n := frames.Load(); n != 0 {
t.Errorf("maximized %v: %d frames built in NewWindow", maximized, n)
}
})
eventually(t, "the window shown with its first frame", func() bool {
return frames.Load() > 0 && w.IsVisible() && firstFrameRevealed(w)
})
if n := early.Load(); n != 0 {
t.Errorf("maximized %v: the view ran %d times before NewWindow returned", maximized, n)
}
w.Destroy()
}
}
@@ -0,0 +1,121 @@
//go:build windows && (amd64 || arm64)
package e2e
import (
"strconv"
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
win "github.com/egoist/mygo/internal/windows"
"github.com/egoist/mygo/ui"
)
// cloaked reports whether DWM keeps w out of sight, and whether its first
// frame reached its surface.
func cloaked(w *mygo.Window) (cloaked, drawn bool) {
mygo.RunOnMain(func() { cloaked, drawn = win.TestCloaked(w.NativeHandle()) })
return
}
// TestContentWindowCloakedUntilFirstFrame checks that a window of native
// UI stays out of sight, though shown, until its first frame shows in it:
// it showed white until then, as the GPU renderer started (#905).
func TestContentWindowCloakedUntilFirstFrame(t *testing.T) {
var w atomic.Pointer[mygo.Window]
// atBuild is how the first build found the window: 1 cloaked, 2 not,
// 3 not found. The build may run while NewWindow creates the window,
// before w is set (at 200%, say), so it looks for windows not drawn yet.
var atBuild atomic.Int32
var ready atomic.Bool
mygo.RunOnMain(func() {
nw := newWindow(t, mygo.WindowOptions{Width: 320, Height: 240, Content: ui.View(func(c *ui.Context) {
c.Root().Background(ui.RGB(30, 30, 30))
if atBuild.Load() != 0 {
return
}
switch n, cloaked := win.TestUndrawnCloaked(); {
case n == 0:
atBuild.Store(3)
case cloaked:
atBuild.Store(1)
default:
atBuild.Store(2)
}
})})
w.Store(nw)
nw.OnReadyToShow(func() { ready.Store(true) })
})
eventually(t, "ready to show", ready.Load)
switch atBuild.Load() {
case 2:
t.Fatal("shown before its first frame: not cloaked as it drew it")
case 3:
t.Fatal("no window of native UI waiting for its first frame as it built")
}
eventually(t, "the window uncloaked after its first frame", func() bool {
c, drawn := cloaked(w.Load())
return !c && drawn
})
if !w.Load().IsVisible() {
t.Error("not visible")
}
}
// firstFrameRevealed reports whether w, whose first frame was drawn, is
// out of DWM's cloak: shown, it showed its frame.
func firstFrameRevealed(w *mygo.Window) bool {
c, drawn := cloaked(w)
return !c && drawn
}
// TestShownFlyoutCloakedUntilComposed checks that a flyout of native UI
// made hidden and shown before it drew a frame, whose frames show through
// DirectComposition, stays out of sight after the WM_PAINT that drew its
// first frame until DWM composed it: uncloaked at once, it showed black for
// a refresh or more, as the frame reached DWM after the window (#1591).
func TestShownFlyoutCloakedUntilComposed(t *testing.T) {
work := mygo.Screen.PrimaryDisplay().WorkArea
parent := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, X: work.X + 100, Y: work.Y + 100})
var fl *mygo.Window
var release func()
var composed bool
mygo.RunOnMain(func() {
release = win.TestHoldReveal()
fl = mygo.NewFlyout(mygo.FlyoutOptions{Parent: parent, Hidden: true, Shadow: true, Width: 220, Height: 240, Content: ui.View(func(c *ui.Context) {
c.Root().Background(ui.RGB(30, 30, 30))
for i := range 10 {
ui.Text(c, "Row "+strconv.Itoa(i))
}
})})
fl.Show()
composed = win.TestSurfaceComposed(fl.NativeHandle())
})
released := false
unhold := func() {
if !released {
released = true
mygo.RunOnMain(release)
}
}
defer unhold()
defer fl.Destroy()
eventually(t, "the flyout's first frame drawn", func() bool {
_, drawn := cloaked(fl)
return drawn
})
if !fl.IsVisible() {
t.Fatal("the flyout is not visible")
}
if composed {
// Some refreshes later, DWM has still not composed it, as held.
time.Sleep(150 * time.Millisecond)
if c, _ := cloaked(fl); !c {
t.Fatal("shown after its first frame's WM_PAINT, before DWM composed the frame")
}
}
unhold()
eventually(t, "the flyout uncloaked once its first frame was composed", func() bool { return firstFrameRevealed(fl) })
}
+232
View File
@@ -0,0 +1,232 @@
//go:build !js
package e2e
import (
"bytes"
"image/png"
"math"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/ui"
)
const fitPage = `<!doctype html><body style="margin:0;background:#fc0"><div id="d" style="width:120px;height:80px"></div></body>`
// waitSize waits for size to return width and height, and says what it
// returned and what the page measured if it never does.
func waitSize(t *testing.T, what string, w *mygo.Window, size func() (int, int), width, height int) {
t.Helper()
var gotW, gotH int
if !wait.Poll(func() bool {
gotW, gotH = size()
return gotW == width && gotH == height
}) {
t.Fatalf("%s: %dx%d never happened (waited %v): %dx%d; page %v", what, width, height, wait.Guard, gotW, gotH, pageMeasures(w))
}
}
// pageMeasures returns what a page measures of its viewport and its root
// element, for a failure to say.
func pageMeasures(w *mygo.Window) any {
v, err := w.Page().Eval(`(() => { const r = document.documentElement, b = r.getBoundingClientRect(); return {inner: [innerWidth, innerHeight], client: [r.clientWidth, r.clientHeight], scroll: [r.scrollWidth, r.scrollHeight], root: [b.width, b.height], zoom: devicePixelRatio} })()`)
if err != nil {
return err
}
return v
}
// scrollbarHeight returns the height of the page's horizontal scrollbar in
// CSS pixels: 0 where scrollbars overlay the page.
func scrollbarHeight(t *testing.T, w *mygo.Window) float64 {
t.Helper()
v, _ := mustEval(t, w, `innerHeight - document.documentElement.clientHeight`).(float64)
return v
}
// TestFlyoutFitContent sizes a flyout to its page's content, follows the
// content as it changes, within the limits, wraps text at the maximum
// width, and takes the page's zoom into account.
func TestFlyoutFitContent(t *testing.T) {
work := mygo.Screen.PrimaryDisplay().WorkArea
parent := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, X: work.X + 100, Y: work.Y + 100})
fl := mygo.NewFlyout(mygo.FlyoutOptions{
Parent: parent,
Anchor: mygo.Rectangle{X: 10, Y: 10},
Width: 50,
Height: 50,
FitContent: true,
MinWidth: 100,
MinHeight: 40,
MaxWidth: 300,
MaxHeight: 200,
})
defer fl.Destroy()
size := func() (int, int) { b := fl.Bounds(); return b.Width, b.Height }
fl.Page().LoadHTML(fitPage, "")
waitSize(t, "the content's size", fl, size, 120, 80)
mustEval(t, fl, `d.style.width = "180px"; d.style.height = "150px"`)
waitSize(t, "larger content", fl, size, 180, 150)
mustEval(t, fl, `d.style.width = "20px"; d.style.height = "10px"`)
waitSize(t, "content below the minimum", fl, size, 100, 40)
mustEval(t, fl, `d.style.width = "500px"; d.style.height = "400px"`)
waitSize(t, "content beyond the maximum", fl, size, 300, 200)
// Text wraps at the maximum width, the room of a vertical scrollbar
// left out of it, and the page scrolls.
mustEval(t, fl, `d.style.width = d.style.height = ""; d.textContent = "word ".repeat(400)`)
waitSize(t, "wrapped text", fl, size, 300, 200)
waitFor(t, fl, `document.scrollingElement.scrollWidth <= document.scrollingElement.clientWidth && document.scrollingElement.scrollHeight > 200`)
// The content shrinks back, and its scrollbar goes.
mustEval(t, fl, `d.textContent = ""; d.style.width = "150px"; d.style.height = "60px"`)
waitSize(t, "smaller content", fl, size, 150, 60)
// A zoomed page's CSS pixels are larger.
fl.Page().SetZoomFactor(2)
waitSize(t, "zoomed content", fl, size, 300, 120)
mustEval(t, fl, `d.style.width = "60px"`)
waitSize(t, "narrower zoomed content", fl, size, 120, 120)
// Wider than the maximum, the page scrolls sideways, and the window
// takes the room of a horizontal scrollbar that doesn't overlay the
// page, as on Windows.
mustEval(t, fl, `d.style.width = "400px"`)
waitFor(t, fl, `document.documentElement.scrollWidth > document.documentElement.clientWidth`)
waitSize(t, "wider zoomed content", fl, size, 300, 120+int(math.Ceil(2*scrollbarHeight(t, fl))))
}
// TestFlyoutFitNativeContent sizes a flyout of native UI to its content,
// follows the content as it changes, within the limits, and draws the
// content at the size the flyout took.
func TestFlyoutFitNativeContent(t *testing.T) {
work := mygo.Screen.PrimaryDisplay().WorkArea
parent := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, X: work.X + 100, Y: work.Y + 100})
var w, h atomic.Int32
w.Store(120)
h.Store(80)
fl := mygo.NewFlyout(mygo.FlyoutOptions{
Parent: parent,
Anchor: mygo.Rectangle{X: 10, Y: 10},
Width: 50,
Height: 50,
FitContent: true,
MinWidth: 100,
MinHeight: 40,
MaxWidth: 300,
MaxHeight: 200,
Content: ui.View(func(c *ui.Context) {
ui.Box(c).Size(float32(w.Load()), float32(h.Load())).Background(ui.RGB(255, 204, 0))
}),
})
defer fl.Destroy()
size := func() (int, int) { b := fl.Bounds(); return b.Width, b.Height }
resize := func(width, height int32) {
fl.Update(func() { w.Store(width); h.Store(height) })
}
waitSize(t, "the content's size", fl, size, 120, 80)
resize(180, 150)
waitSize(t, "larger content", fl, size, 180, 150)
resize(20, 10)
waitSize(t, "content below the minimum", fl, size, 100, 40)
resize(500, 400)
waitSize(t, "content beyond the maximum", fl, size, 300, 200)
resize(150, 60)
waitSize(t, "smaller content", fl, size, 150, 60)
// The last frame was laid out at the flyout's size.
var gotW, gotH int
if !wait.Poll(func() bool {
b, err := fl.CapturePage()
if err != nil {
return false
}
img, err := png.Decode(bytes.NewReader(b))
if err != nil {
return false
}
gotW, gotH = img.Bounds().Dx(), img.Bounds().Dy()
scale := float64(gotW) / 150
return math.Abs(float64(gotH)-60*scale) <= 1
}) {
t.Errorf("the last frame is %dx%d pixels, for a flyout of 150x60 DIPs", gotW, gotH)
}
}
// TestFlyoutFitNativeContentHidden shows a hidden flyout of native UI
// whose content changed while it was hidden at the size that content
// takes, before its first Show and after it hid again: a hidden window
// draws no frames, so nothing measured the content before it showed.
func TestFlyoutFitNativeContentHidden(t *testing.T) {
work := mygo.Screen.PrimaryDisplay().WorkArea
parent := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, X: work.X + 100, Y: work.Y + 100})
var w, h atomic.Int32
w.Store(120)
h.Store(80)
fl := mygo.NewFlyout(mygo.FlyoutOptions{
Parent: parent,
Anchor: mygo.Rectangle{X: 10, Y: 10},
Width: 50,
Height: 50,
FitContent: true,
MinWidth: 100,
MinHeight: 40,
MaxWidth: 300,
MaxHeight: 200,
Hidden: true,
Content: ui.View(func(c *ui.Context) {
ui.Box(c).Size(float32(w.Load()), float32(h.Load())).Background(ui.RGB(255, 204, 0))
}),
})
defer fl.Destroy()
size := func() (int, int) { b := fl.Bounds(); return b.Width, b.Height }
// The flyout's size as it shows, which OnShow hears on the main
// thread, as Show returns.
var shownW, shownH int
fl.OnShow(func() { shownW, shownH = size() })
showAt := func(what string, show func(), width, height int) {
t.Helper()
show()
if shownW != width || shownH != height {
t.Errorf("%s: shown at %dx%d, want %dx%d", what, shownW, shownH, width, height)
}
waitSize(t, what, fl, size, width, height)
}
resize := func(width, height int32) {
fl.Update(func() { w.Store(width); h.Store(height) })
}
// Its first frame draws while it is hidden.
waitSize(t, "the content's size, hidden", fl, size, 120, 80)
resize(180, 150)
showAt("changed before its first Show", fl.Show, 180, 150)
fl.Hide()
resize(150, 60)
showAt("changed while hidden", fl.ShowInactive, 150, 60)
}
// TestWindowFitContent sizes a window's page area to its content, and
// keeps a size given to it until the content changes, in the dimension it
// changes in.
func TestWindowFitContent(t *testing.T) {
w := newWindow(t, mygo.WindowOptions{Width: 500, Height: 400, FitContent: true})
w.Page().LoadHTML(`<!doctype html><body style="margin:0"><div id="d" style="width:320px;height:180px"></div></body>`, "")
waitSize(t, "the content's size", w, w.ContentSize, 320, 180)
mustEval(t, w, `d.style.height = "240px"`)
waitSize(t, "taller content", w, w.ContentSize, 320, 240)
w.SetContentSize(400, 300)
waitSize(t, "the size given to it", w, w.ContentSize, 400, 300)
mustEval(t, w, `d.style.height = "260px"`)
waitSize(t, "taller content again", w, w.ContentSize, 400, 260)
// The content changes right as the window is resized, before its page
// takes the size, and shows a vertical scrollbar for a moment: the
// width given to it holds.
w.SetContentSize(450, 260)
mustEval(t, w, `d.style.height = "280px"`)
waitSize(t, "taller content right after a resize", w, w.ContentSize, 450, 280)
}
+437
View File
@@ -0,0 +1,437 @@
//go:build !js
package e2e
import (
"bytes"
"image"
"image/draw"
"image/png"
"os"
"runtime"
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
const flyoutPage = `<body style="margin:0;background:transparent">` +
`<button id="b" style="width:100%;height:100px;background:#fc0" onclick="window.clicked=(window.clicked||0)+1">x</button></body>`
// TestFlyout places a flyout below an anchor in its parent, beyond the
// parent's bottom edge, flips it above where the work area ends, and
// keeps it next to the anchor as the parent moves.
func TestFlyout(t *testing.T) {
work := mygo.Screen.PrimaryDisplay().WorkArea
parent := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, X: work.X + 100, Y: work.Y + 100})
anchor := mygo.Rectangle{X: 20, Y: 150, Width: 80, Height: 24}
fl := mygo.NewFlyout(mygo.FlyoutOptions{Parent: parent, Anchor: anchor, Gap: 4, Width: 220, Height: 160})
defer fl.Destroy()
if !fl.IsFlyout() || fl.Parent() != parent || !fl.IsVisible() {
t.Fatalf("flyout: IsFlyout %v, parent %v, visible %v", fl.IsFlyout(), fl.Parent() == parent, fl.IsVisible())
}
below := func() mygo.Rectangle {
c := parent.ContentBounds()
return mygo.Rectangle{X: c.X + anchor.X, Y: c.Y + anchor.Y + anchor.Height + 4, Width: 220, Height: 160}
}
eventuallyAt(t, "the flyout below its anchor", fl, below)
if p, f := parent.Bounds(), fl.Bounds(); f.Y+f.Height <= p.Y+p.Height {
t.Errorf("flyout %+v does not extend beyond its parent %+v", f, p)
}
// A click in a flyout that is not focusable reaches its page and
// leaves the keyboard in the parent.
fl.Page().LoadHTML(flyoutPage, "")
waitFor(t, fl, "document.getElementById('b')")
parent.Focus()
eventually(t, "the parent focused", parent.IsFocused)
if click(fl, 50, 50) {
waitFor(t, fl, "window.clicked === 1")
if fl.IsFocused() || !parent.IsFocused() {
t.Errorf("after a click in the flyout: flyout focused %v, parent focused %v", fl.IsFocused(), parent.IsFocused())
}
}
// It follows the parent.
parent.SetPosition(work.X+160, work.Y+140)
eventuallyAt(t, "the flyout following its parent", fl, below)
// Where the work area has no room below, it goes above.
parent.SetPosition(work.X+100, work.Y+work.Height-210)
eventuallyAt(t, "the flyout above its anchor", fl, func() mygo.Rectangle {
c := parent.ContentBounds()
return mygo.Rectangle{X: c.X + anchor.X, Y: c.Y + anchor.Y - 4 - 160, Width: 220, Height: 160}
})
// SetAnchor and SetSize place it again.
parent.SetPosition(work.X+100, work.Y+100)
anchor = mygo.Rectangle{X: 200, Y: 10, Width: 40, Height: 20}
fl.SetAnchor(anchor)
fl.SetSize(120, 90)
eventuallyAt(t, "the flyout at its new anchor and size", fl, func() mygo.Rectangle {
c := parent.ContentBounds()
return mygo.Rectangle{X: c.X + anchor.X, Y: c.Y + anchor.Y + anchor.Height + 4, Width: 120, Height: 90}
})
// It closes with its parent.
parent.Destroy()
eventually(t, "the flyout closed with its parent", fl.IsDestroyed)
}
// eventuallyAt waits for a flyout to be at the bounds want returns.
func eventuallyAt(t *testing.T, what string, fl *mygo.Window, want func() mygo.Rectangle) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for fl.Bounds() != want() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s: at %+v, not %+v", what, fl.Bounds(), want())
}
time.Sleep(20 * time.Millisecond)
}
}
// TestFocusableFlyout gives a focusable flyout the keyboard and closes it
// when the parent takes the keyboard back, unless OnClose prevents it.
func TestFocusableFlyout(t *testing.T) {
parent := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200})
parent.Focus()
eventually(t, "the parent focused", parent.IsFocused)
fl := mygo.NewFlyout(mygo.FlyoutOptions{Parent: parent, Anchor: mygo.Rectangle{X: 10, Y: 10}, Width: 200, Height: 120, Focusable: true})
defer fl.Destroy()
eventually(t, "the flyout focused", fl.IsFocused)
keep := true
closes := 0
fl.OnClose(func(e *mygo.CloseEvent) {
closes++
if keep {
e.PreventDefault()
}
})
parent.Focus()
eventually(t, "the flyout asked to close", func() bool { return closes == 1 })
if fl.IsDestroyed() {
t.Fatal("the flyout closed though OnClose prevented it")
}
keep = false
fl.Focus()
eventually(t, "the flyout focused again", fl.IsFocused)
parent.Focus()
eventually(t, "the flyout closed", fl.IsDestroyed)
eventually(t, "the parent focused", parent.IsFocused)
}
// TestFlyoutModalWindow opens a window modal to a focusable flyout, which
// takes the keyboard and keeps the flyout open, over it; the flyout gets
// the keyboard back as it closes, and closes it as it closes.
func TestFlyoutModalWindow(t *testing.T) {
parent := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200})
parent.Focus()
eventually(t, "the parent focused", parent.IsFocused)
fl := mygo.NewFlyout(mygo.FlyoutOptions{Parent: parent, Anchor: mygo.Rectangle{X: 10, Y: 10}, Width: 160, Height: 100, Focusable: true, Content: ui.View(func(c *ui.Context) {})})
defer fl.Destroy()
eventually(t, "the flyout focused", fl.IsFocused)
var closes atomic.Int32
fl.OnClose(func(*mygo.CloseEvent) { closes.Add(1) })
open := func() *mygo.Window {
t.Helper()
dialog := mygo.NewWindow(mygo.WindowOptions{Parent: fl, Modal: true, Width: 360, Height: 160, Content: ui.View(func(c *ui.Context) {})})
eventually(t, "the modal window focused", dialog.IsFocused)
return dialog
}
dialog := open()
if b, f := dialog.Bounds(), fl.Bounds(); b.X > f.X || b.X+b.Width < f.X+f.Width {
t.Errorf("the modal window at %+v does not cover the flyout at %+v", b, f)
}
dialog.Close()
eventually(t, "the modal window closed", dialog.IsDestroyed)
eventually(t, "the flyout focused again", fl.IsFocused)
if fl.IsDestroyed() || closes.Load() != 0 {
t.Fatalf("the flyout closed (%d times asked) for its modal window", closes.Load())
}
dialog = open()
fl.Close()
eventually(t, "the modal window closed with the flyout", dialog.IsDestroyed)
eventually(t, "the flyout closed", fl.IsDestroyed)
}
// TestPopoverFlyout shows a flyout in a popover of the system where there
// is one (macOS), which closes as the user clicks elsewhere when it is
// focusable, and is a plain flyout elsewhere.
func TestPopoverFlyout(t *testing.T) {
parent := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200})
parent.Focus()
eventually(t, "the parent focused", parent.IsFocused)
fl := mygo.NewFlyout(mygo.FlyoutOptions{Parent: parent, Anchor: mygo.Rectangle{X: 100, Y: 20, Width: 80, Height: 24}, Width: 200, Height: 100, Popover: true})
defer fl.Destroy()
fl.Page().LoadHTML(flyoutPage, "")
waitFor(t, fl, "document.getElementById('b')")
if !fl.IsVisible() {
t.Fatal("the popover does not show")
}
b, c := fl.Bounds(), parent.ContentBounds()
if b.Width < 200 || b.Height < 100 || b.Y < c.Y+20+24 {
t.Errorf("popover at %+v, below the anchor at %+v in %+v", b, mygo.Rectangle{X: 100, Y: 20, Width: 80, Height: 24}, c)
}
fl.Hide()
eventually(t, "the popover hidden", func() bool { return !fl.IsVisible() })
fl.ShowInactive()
eventually(t, "the popover shown again", fl.IsVisible)
if fl.IsDestroyed() {
t.Fatal("hiding the popover closed it")
}
if appClick(fl, 50, 50) {
waitFor(t, fl, "window.clicked === 1")
}
if fl.IsDestroyed() {
t.Fatal("a click in the popover closed it")
}
focusable := mygo.NewFlyout(mygo.FlyoutOptions{Parent: parent, Anchor: mygo.Rectangle{X: 10, Y: 150}, Width: 150, Height: 80, Popover: true, Focusable: true})
defer focusable.Destroy()
eventually(t, "the focusable popover focused", focusable.IsFocused)
closes := 0
focusable.OnClose(func(*mygo.CloseEvent) { closes++ })
if appClick(parent, 280, 10) {
eventually(t, "the focusable popover closed", focusable.IsDestroyed)
if closes != 1 {
t.Errorf("OnClose heard %d closes", closes)
}
}
}
// TestFlyoutToggle opens a focusable flyout from a button of its parent,
// and closes it with a second click on the button, which the closing
// does not turn into opening it again: quick, or held as a user clicks,
// whose press closes the flyout before the release would click the button
// where the press goes on (macOS) but for the flyout's anchor. The click
// hooks return once the app handled the click: a frame the parent builds
// after that reports a click the button got.
func TestFlyoutToggle(t *testing.T) {
var parent, fl *mygo.Window // main thread only
var shown atomic.Pointer[mygo.Window]
var builds atomic.Int64
opened := make(chan struct{}, 4)
closed := make(chan struct{}, 4)
view := func(c *ui.Context) {
builds.Add(1)
if !ui.Button(c.Key("toggle"), "Toggle").Width(120).Height(30).Clicked() {
return
}
if fl != nil {
fl.Close()
return
}
fl = mygo.NewFlyout(mygo.FlyoutOptions{Parent: parent, Anchor: mygo.Rectangle{Width: 120, Height: 30}, Width: 150, Height: 100, Focusable: true, Content: ui.View(func(c *ui.Context) {})})
shown.Store(fl)
fl.OnClosed(func() {
fl = nil
closed <- struct{}{}
})
opened <- struct{}{}
}
drawn := make(chan struct{}, 1)
mygo.RunOnMain(func() {
parent = mygo.NewWindow(mygo.WindowOptions{Width: 300, Height: 200, Hidden: true, Content: ui.View(view)})
parent.OnReadyToShow(func() { drawn <- struct{}{} })
parent.Show()
})
defer parent.Destroy()
wait := func(ch chan struct{}, what string) {
t.Helper()
select {
case <-ch:
case <-time.After(5 * time.Second):
t.Fatalf("timed out waiting for %s", what)
}
}
// built waits for the parent to build a frame after the clicks the
// hooks handled, which reports a click of the button.
built := func() {
t.Helper()
n := builds.Load()
parent.Invalidate()
eventually(t, "a frame of the parent built", func() bool { return builds.Load() > n })
}
wait(drawn, "the parent drawn")
parent.Focus()
eventually(t, "the parent focused", parent.IsFocused)
// The button lays out at the top-left of the window.
for i, closing := range []func(*mygo.Window, float64, float64) bool{heldAppClick, appClick} {
if !appClick(parent, 60, 15) {
t.Skip("clicks not available on this platform")
}
wait(opened, "the flyout opened")
// A user clicks again once the flyout shows, with the keyboard.
eventually(t, "the flyout focused", func() bool { return shown.Load().IsFocused() || len(closed) > 0 })
select {
case <-closed:
// It closes as another app takes the keyboard.
t.Fatal("the flyout closed before the click that closes it: was the app deactivated?")
default:
}
closing(parent, 60, 15)
wait(closed, "the flyout closed")
built()
select {
case <-opened:
t.Fatalf("the click that closed the flyout opened it again (held %v)", i == 0)
default:
}
}
}
// TestFlyoutEscape closes a focusable flyout of native UI, or showing a
// page, on an Escape its content does not handle, and keeps one whose
// content does.
func TestFlyoutEscape(t *testing.T) {
parent := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200})
parent.Focus()
eventually(t, "the parent focused", parent.IsFocused)
var handled, received atomic.Bool
native := mygo.NewFlyout(mygo.FlyoutOptions{Parent: parent, Width: 150, Height: 100, Focusable: true, Content: ui.View(func(c *ui.Context) {
if handled.Load() && c.Shortcut(0, ui.KeyEscape) {
received.Store(true)
}
})})
defer native.Destroy()
eventually(t, "the flyout focused", native.IsFocused)
// The view asks for Escape from the frame that handles the key on,
// whether or not a frame built since showed it.
handled.Store(true)
if !pressEscape(native) {
t.Skip("keys not available on this platform")
}
// Posting the native key does not wait for the content to receive it.
eventually(t, "the content handling Escape", func() bool { return received.Load() || native.IsDestroyed() })
if native.IsDestroyed() {
t.Fatal("an Escape the content handled closed the flyout")
}
// It no longer does, from the frame that handles the key on.
handled.Store(false)
pressEscape(native)
eventually(t, "the flyout of native UI closed", native.IsDestroyed)
parent.Focus()
eventually(t, "the parent focused", parent.IsFocused)
page := mygo.NewFlyout(mygo.FlyoutOptions{Parent: parent, Width: 150, Height: 100, Focusable: true})
defer page.Destroy()
page.Page().LoadHTML(`<input id=i autofocus>`, "")
waitFor(t, page, "document.activeElement && document.activeElement.id === 'i'")
eventually(t, "the page's flyout focused", page.IsFocused)
pressEscape(page)
eventually(t, "the page's flyout closed", page.IsDestroyed)
// A flyout of native UI showing a web view whose page has the
// keyboard closes on an Escape the page leaves.
parent.Focus()
eventually(t, "the parent focused", parent.IsFocused)
var view *mygo.WebView
var shown atomic.Int32
reader := mygo.NewFlyout(mygo.FlyoutOptions{Parent: parent, Width: 150, Height: 100, Focusable: true, Content: ui.View(func(c *ui.Context) {
if view != nil {
ui.WebView(c, view).Fill()
shown.Add(1)
}
})})
defer reader.Destroy()
v, err := reader.NewWebView(mygo.WebViewOptions{Page: mygo.PageOptions{Untrusted: true}})
if err != nil {
t.Fatal(err)
}
reader.Update(func() { view = v })
v.Page().LoadHTML(`<p>Text to read.</p><script>window.ready = true</script>`, "")
waitForPage(t, v.Page(), "window.ready")
eventually(t, "two frames showing the web view", func() bool {
reader.Invalidate()
return shown.Load() >= 2
})
eventually(t, "the reader focused", reader.IsFocused)
v.Focus()
waitForPage(t, v.Page(), "document.hasFocus()")
pressEscape(reader)
eventually(t, "the reader closed", reader.IsDestroyed)
// A popover of the system's (macOS) closes so too.
parent.Focus()
eventually(t, "the parent focused", parent.IsFocused)
popover := mygo.NewFlyout(mygo.FlyoutOptions{Parent: parent, Width: 150, Height: 100, Focusable: true, Popover: true, Content: ui.View(func(c *ui.Context) {})})
defer popover.Destroy()
eventually(t, "the popover focused", popover.IsFocused)
pressEscape(popover)
eventually(t, "the popover closed", popover.IsDestroyed)
}
// TestTrayFlyout places a flyout next to a tray icon, below the macOS menu
// bar's or above an icon of a taskbar at the bottom, and in the middle of
// the primary display's work area where the icon has no bounds. (Clicks
// on the icon, which toggle it, are TestTrayPopoverToggle's on macOS.)
func TestTrayFlyout(t *testing.T) {
tray, err := mygo.NewTray(mygo.TrayOptions{Icon: squarePNG(), ToolTip: "flyout"})
if err != nil {
t.Skip("no tray: ", err)
}
defer tray.Destroy()
waitTrayLaidOut(tray)
for _, popover := range []bool{false, true} {
fl := mygo.NewFlyout(mygo.FlyoutOptions{Tray: tray, Placement: mygo.PlacementBottom, Gap: 4, Width: 200, Height: 120, Focusable: true, Popover: popover,
Content: ui.View(func(c *ui.Context) {})})
eventually(t, "the flyout shown", fl.IsVisible)
if popover && runtime.GOOS == "darwin" {
// AppKit places a popover, its arrow pointing at the icon.
eventually(t, "the popover below the icon", func() bool {
b, icon := fl.Bounds(), tray.Bounds()
return b.Y > icon.Y && b.Y <= icon.Y+icon.Height+30 && b.X < icon.X+icon.Width/2 && b.X+b.Width > icon.X+icon.Width/2
})
} else if icon := tray.Bounds(); icon.Width > 0 && icon.Height > 0 {
eventually(t, "the flyout next to the icon", func() bool {
b := fl.Bounds()
return (b.Y == icon.Y+icon.Height+4 || b.Y+b.Height == icon.Y-4) && b.Width == 200 && b.Height == 120
})
} else if runtime.GOOS != "linux" || os.Getenv("WAYLAND_DISPLAY") == "" {
work := mygo.Screen.PrimaryDisplay().WorkArea
want := mygo.Rectangle{X: work.X + (work.Width-200)/2, Y: work.Y + (work.Height-120)/2, Width: 200, Height: 120}
eventuallyAt(t, "the flyout in the middle of the work area", fl, func() mygo.Rectangle { return want })
}
fl.Destroy()
}
}
// waitTrayLaidOut waits for the menu bar to lay a tray icon out, which it
// does after the icon was made, off the screen until then, as a click on
// it would find it.
func waitTrayLaidOut(tray *mygo.Tray) {
onScreen := func() bool {
r := tray.Bounds()
for _, d := range mygo.Screen.Displays() {
b := d.Bounds
if r.Width > 0 && r.Height > 0 && r.X >= b.X && r.X+r.Width <= b.X+b.Width && r.Y >= b.Y-2 && r.Y+r.Height <= b.Y+b.Height {
return true
}
}
return false
}
last, still := tray.Bounds(), 0
for deadline := time.Now().Add(3 * time.Second); still < 10 && time.Now().Before(deadline); {
time.Sleep(30 * time.Millisecond)
if b := tray.Bounds(); b == last && onScreen() {
still++
} else {
last, still = b, 0
}
}
}
// squarePNG returns a black square, 32 pixels wide.
func squarePNG() []byte {
img := image.NewNRGBA(image.Rect(0, 0, 32, 32))
draw.Draw(img, image.Rect(4, 4, 28, 28), image.Black, image.Point{}, draw.Src)
var b bytes.Buffer
_ = png.Encode(&b, img)
return b.Bytes()
}
+46
View File
@@ -0,0 +1,46 @@
//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"
)
// GTK's frame clock waits the refresh interval of the last frame's timings
// before the next frame, 1/60 s while none tells it, and GDK learns it
// only from the compositor: never for a window it composites with OpenGL
// on Wayland, nor on X11 without a compositor. A GtkGLArea drew 60 frames
// a second on a 165 Hz display under Niri (#1219). The frames of a window
// tell the clock the rate of the monitor showing it: 16666 µs under Xvfb
// or weston, whose displays refresh at 60 Hz, where GTK's own guess is
// 16667.
func TestFrameClockFollowsMonitor(t *testing.T) {
var frames atomic.Int32
var moving atomic.Bool
moving.Store(true)
defer moving.Store(false)
w := newWindow(t, mygo.WindowOptions{Title: "Frame clock", Width: 400, Height: 300, Content: ui.View(func(c *ui.Context) {
if moving.Load() {
c.AnimationFrame()
}
frames.Add(1)
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255))
})})
eventually(t, "frames while animating", func() bool { return frames.Load() >= 10 })
clock := func() (interval int64, mhz int32) {
mygo.RunOnMain(func() { interval, mhz = linux.TestFrameClockInterval(w.NativeHandle()) })
return interval, mhz
}
if _, mhz := clock(); mhz <= 0 {
t.Skip("GDK knows no refresh rate of the display: the frame clock keeps 60 Hz")
}
eventually(t, "the monitor's refresh interval in the frame clock", func() bool {
interval, mhz := clock()
return interval == 1_000_000_000/int64(mhz)
})
}
@@ -0,0 +1,65 @@
//go:build windows && (amd64 || arm64)
package e2e
import (
"fmt"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
win "github.com/egoist/mygo/internal/windows"
"github.com/egoist/mygo/ui"
)
// TestNativeUIFramelessEdges checks that a frameless window of native UI
// shows its content up to its edges, on the screen: on Windows 10, a white
// line went around it, between the content and the shadow, the visible
// pixel of the borders DWM draws in the non-client area, and the frame
// extended for the shadow along the top (#916). Windows 11 draws a border
// of its own over the outermost pixels, inside which the content shows.
// The content is the issue's: the root has no background, a column filling
// it has one.
func TestNativeUIFramelessEdges(t *testing.T) {
var frames atomic.Int32
w := newWindow(t, mygo.WindowOptions{X: 80, Y: 80, Width: 480, Height: 360, Frameless: true, AlwaysOnTop: true,
Content: ui.View(func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Fill().Background(ui.RGB(180, 20, 20))
})})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
red := func(c [3]uint8) bool {
near := func(v, want uint8) bool { return int(v) >= int(want)-8 && int(v) <= int(want)+8 }
return near(c[0], 180) && near(c[1], 20) && near(c[2], 20)
}
eventually(t, "the content on the screen", func() bool {
r, g, b, ok := screenColor(w, 240, 180)
return ok && red([3]uint8{r, g, b})
})
var last string
t.Cleanup(func() {
if t.Failed() && last != "" {
t.Logf("at the edges, %s", last)
}
})
eventually(t, "the content at the window's edges", func() bool {
var edges [4][3]uint8
var in int32
var ok bool
mygo.RunOnMain(func() { edges, in, ok = win.TestWindowEdges(w.NativeHandle()) })
if !ok {
last = "unreadable"
return false
}
last = ""
for i, name := range []string{"left", "top", "right", "bottom"} {
if c := edges[i]; !red(c) {
last += fmt.Sprintf(" %s #%02x%02x%02x", name, c[0], c[1], c[2])
}
}
if last != "" {
last = fmt.Sprintf("%d pixels in:%s", in, last)
}
return last == ""
})
}
+75
View File
@@ -0,0 +1,75 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"image"
"os"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/ui"
)
// GTK 3 tells a Wayland compositor what each paint of a window it
// composites with OpenGL changed in the window's coordinates unscaled,
// where EGL takes the buffer's pixels: at a scale of 2 the compositor
// learned of a change at the top of the window in its lower half, at half
// its size, and showed title buttons that flickered and a shadow missing
// on some sides (#1071). The window tells it what GTK repaints, in the
// surface's coordinates: a box that changes color within the GtkGLArea,
// below GTK's title bar and shadow, is in it. It runs on Wayland at a
// scale of 2 or more (weston --scale=2), with MYGO_GPU=1.
func TestGLDamageWayland(t *testing.T) {
if os.Getenv("MYGO_GPU") != "1" {
t.Skip("needs the GtkGLArea: MYGO_GPU=1")
}
var frames atomic.Int32
var lit atomic.Bool
box := ui.Rect{X: 300, Y: 200, W: 40, H: 30}
view := func(c *ui.Context) {
frames.Add(1)
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255)).Draw(func(pt *ui.Painter, r ui.Rect) {
color := ui.RGB(200, 200, 200)
if lit.Load() {
color = ui.RGB(255, 0, 0)
}
pt.Fill(ui.Rect{X: r.X + box.X, Y: r.Y + box.Y, W: box.W, H: box.H}, color, 0)
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Damage", Width: 400, Height: 300, Content: ui.View(view)})
eventually(t, "a frame with OpenGL", func() bool {
how, _, _, _, _ := glSurface(w)
return how == "opengl"
})
glDamage := func() (d []image.Rectangle, area image.Point, scale int, ok bool) {
mygo.RunOnMain(func() { d, area, scale, ok = linux.TestGLDamage(w.NativeHandle()) })
return d, area, scale, ok
}
_, area, scale, ok := glDamage()
if !ok {
t.Skip("GTK tells the compositor what changed itself but on Wayland")
}
if scale < 2 {
t.Skipf("GTK tells the compositor what changed itself at a scale of %d", scale)
}
want := image.Rect(int(box.X), int(box.Y), int(box.X+box.W), int(box.Y+box.H)).Add(area)
var damage []image.Rectangle
before := frames.Load()
w.Update(func() { lit.Store(true) })
eventually(t, "the box's change told to the compositor", func() bool {
d, _, _, _ := glDamage()
damage = append(damage, d...)
if frames.Load() == before {
return false
}
for _, r := range damage {
if want.In(r) {
return true
}
}
return false
})
}
+37
View File
@@ -0,0 +1,37 @@
//go:build linux && !android && (amd64 || arm64) && !android
package e2e
import (
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
)
// TestGLProbeWindow checks that the probe of OpenGL leaves its window to
// GDK, which frees it once the X server says it destroyed it. Freed
// before, GDK handled that DestroyNotify on freed memory, and apps whose
// first window of native UI probed a GPU crashed as they started.
func TestGLProbeWindow(t *testing.T) {
var (
failure string
freed func() bool
early bool
)
mygo.RunOnMain(func() {
if _, failure, freed = linux.TestProbeGL(); freed != nil {
early = freed()
}
})
if freed == nil {
t.Skipf("no probe window to watch, off X11 or before it (%s)", failure)
}
if early {
t.Fatal("the probe freed its window before the X server destroyed it")
}
eventually(t, "GDK freeing the probe's window", func() (ok bool) {
mygo.RunOnMain(func() { ok = freed() })
return ok
})
}
+119
View File
@@ -0,0 +1,119 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"math"
"slices"
"strings"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/ui"
)
// gtk4Frame is the sheet of #1121, which gives GTK 3's frame the look of
// GTK 4's: a flat header bar and round title buttons of 24 px.
const gtk4Frame = `decoration { border-radius: 12px; box-shadow: 0 3px 9px 1px rgba(0, 0, 0, .28); }
.maximized decoration, .fullscreen decoration, .tiled decoration { border-radius: 0; }
.csd.popup decoration, tooltip.csd decoration { border-radius: 5px; }
headerbar { min-height: 46px; padding: 0 6px; background-color: #f9fafb;
background-image: none; border-width: 0; box-shadow: none; }
button.titlebutton { min-width: 24px; min-height: 24px; margin: 0 3px; padding: 0;
border: none; border-radius: 9999px; background-color: transparent; }`
func titleBarStyle() (s linux.TitleBarStyle) {
mygo.RunOnMain(func() { s = linux.TestTitleBarStyle() })
return s
}
func titleButtonSizes(w *mygo.Window) (sizes [][2]int) {
mygo.RunOnMain(func() { sizes = linux.TestTitleButtonSizes(w.NativeHandle()) })
return sizes
}
func sameColor(a, b [4]float64) bool {
for i := range a {
if math.Abs(a[i]-b[i]) > 1e-6 {
return false
}
}
return true
}
// Theme.SetGTKCSS styles the widgets GTK draws, above the theme: a header
// bar and its title buttons, the window's own among them. A second sheet
// replaces the first rather than adding to it, one that does not parse
// fails and leaves the sheet before, and "" gives the theme back (#1121).
func TestGTKCSS(t *testing.T) {
t.Cleanup(func() { _ = mygo.Theme.SetGTKCSS("") })
theme := titleBarStyle()
if theme.Button == [2]int{24, 24} {
t.Fatalf("the theme's title buttons are 24x24 already")
}
w := newWindow(t, mygo.WindowOptions{Width: 400, Height: 300, TitleBarStyle: mygo.TitleBarHidden,
Content: ui.View(func(c *ui.Context) { ui.Text(c, "GTK CSS") })})
// From a goroutine other than the main one, as tests run.
if err := mygo.Theme.SetGTKCSS(gtk4Frame); err != nil {
t.Fatal(err)
}
s := titleBarStyle()
if s.Button != [2]int{24, 24} {
t.Errorf("title button = %v, want 24x24", s.Button)
}
if want := [4]float64{249.0 / 255, 250.0 / 255, 251.0 / 255, 1}; !sameColor(s.Background, want) {
t.Errorf("header bar background = %v, want #f9fafb", s.Background)
}
// The window's title buttons, where the desktop's layout has any.
if len(titleButtonSizes(w)) > 0 {
var sizes [][2]int
if !wait.Poll(func() bool {
sizes = titleButtonSizes(w)
return len(sizes) > 0 && !slices.ContainsFunc(sizes, func(s [2]int) bool { return s != [2]int{24, 24} })
}) {
t.Errorf("the window's title buttons are %v, never 24x24", sizes)
}
}
// A second sheet replaces the first: the header bar has the theme's
// background again.
const big = `button.titlebutton { min-width: 40px; min-height: 40px; padding: 0; border: none; }`
if err := mygo.Theme.SetGTKCSS(big); err != nil {
t.Fatal(err)
}
s = titleBarStyle()
if s.Button != [2]int{40, 40} {
t.Errorf("title button after another sheet = %v, want 40x40", s.Button)
}
if !sameColor(s.Background, theme.Background) {
t.Errorf("header bar background after another sheet = %v, want the theme's %v", s.Background, theme.Background)
}
// A sheet that does not parse fails, and the one before stays.
err := mygo.Theme.SetGTKCSS(`button.titlebutton { min-width: nonsense; }`)
if err == nil || !strings.HasPrefix(err.Error(), "mygo: Theme.SetGTKCSS: ") {
t.Errorf("SetGTKCSS of a sheet that does not parse = %v, want GTK's error", err)
}
if s := titleBarStyle(); s.Button != [2]int{40, 40} {
t.Errorf("title button after a sheet that does not parse = %v, want 40x40 still", s.Button)
}
// No sheet, the theme's style.
if err := mygo.Theme.SetGTKCSS(""); err != nil {
t.Fatal(err)
}
if s := titleBarStyle(); s != theme {
t.Errorf("style without a sheet = %+v, want the theme's %+v", s, theme)
}
}
// gtkCSSBeforeRun sets a sheet on the main goroutine before Run, which
// keeps it for Run to load, and returns whether GTK styles with it. Main
// thread only.
func gtkCSSBeforeRun() (applied func() bool) {
err := mygo.Theme.SetGTKCSS(`button.titlebutton { min-width: 32px; min-height: 32px; padding: 0; border: none; }`)
return func() bool { return err == nil && linux.TestTitleBarStyle().Button == [2]int{32, 32} }
}
+12
View File
@@ -0,0 +1,12 @@
//go:build !js && !(linux && !android && (amd64 || arm64))
package e2e
import "github.com/egoist/mygo"
// gtkCSSBeforeRun gives Theme.SetGTKCSS a sheet that does not even parse,
// which it ignores where GTK draws nothing for the app.
func gtkCSSBeforeRun() (applied func() bool) {
err := mygo.Theme.SetGTKCSS("button {")
return func() bool { return err == nil }
}
@@ -0,0 +1,52 @@
//go:build darwin && !ios
package e2e
import (
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/ui"
)
// TestHideOnScreenInFrame hides a window that shows on screen from its own
// content as it builds a frame, and the content goes on asking for a
// frame in each: the main thread still runs what is posted to it. The
// window server tells that the window left the screen a pass of the run
// loop later, and package ui holds no frame until then: drawn at once
// each, from the backend's queue, those frames never let that pass come.
// TestHideInFrame hides its window as soon as it has it, before it shows
// on screen unless the runner is slow, and hung only then.
func TestHideOnScreenInFrame(t *testing.T) {
var self atomic.Pointer[mygo.Window]
var hide, hidden, still atomic.Bool
w := newWindow(t, mygo.WindowOptions{Width: 320, Height: 240, Content: ui.View(func(c *ui.Context) {
if w := self.Load(); w != nil && hide.Load() && !hidden.Load() {
w.Hide()
hidden.Store(true)
}
if !still.Load() {
c.AnimationFrame()
}
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255))
})})
self.Store(w)
waitOnScreen(w)
hide.Store(true)
eventually(t, "the window hiding itself", hidden.Load)
ran := make(chan struct{})
go func() {
mygo.RunOnMain(func() {})
close(ran)
}()
select {
case <-ran:
case <-time.After(wait.Guard):
// Without frames to draw, the main thread runs the cleanups.
still.Store(true)
t.Fatalf("the main thread never ran what was posted to it after the window hid itself (waited %v)", wait.Guard)
}
}
+478
View File
@@ -0,0 +1,478 @@
//go:build darwin && !ios
package e2e
import (
"log"
"os/exec"
"slices"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/darwin"
"github.com/egoist/mygo/internal/wait"
)
// recentDocumentRecorded reports whether path is among the app's recent
// documents.
func recentDocumentRecorded(path string) (recorded, supported bool) {
var paths []string
mygo.RunOnMain(func() { paths = darwin.TestRecentDocuments() })
return slices.Contains(paths, path), true
}
func activateMenu(w *mygo.Window, path ...string) (err error) {
mygo.RunOnMain(func() { err = darwin.TestPerformMenuItem(path...) })
return err
}
func menuItemEnabled(_ *mygo.Window, path ...string) (enabled bool, err error) {
mygo.RunOnMain(func() { enabled, err = darwin.TestMenuItemEnabled(path...) })
return enabled, err
}
func pressShortcut(key string, shift bool) (handled bool, supported bool) {
mygo.RunOnMain(func() { handled = darwin.TestPerformKeyEquivalent(key, shift) })
return handled, true
}
func endSheet(w *mygo.Window) (ok bool, supported bool) {
mygo.RunOnMain(func() { ok = darwin.TestEndSheet(w.NativeHandle()) })
return ok, true
}
func click(w *mygo.Window, x, y float64) bool {
waitOnScreen(w)
mygo.RunOnMain(func() { darwin.TestClick(w.NativeHandle(), x, y) })
return true
}
// clickPage clicks a window's page: click reaches web views too.
func clickPage(w *mygo.Window, x, y float64) bool { return click(w, x, y) }
// appClick clicks through the application, whose event monitors see it.
func appClick(w *mygo.Window, x, y float64) bool {
waitOnScreen(w)
mygo.RunOnMain(func() { darwin.TestAppClick(w.NativeHandle(), x, y) })
return true
}
// heldAppClick is appClick with the button held down, as a user clicks:
// what the press did runs before the release, the work it left for the
// main thread too.
func heldAppClick(w *mygo.Window, x, y float64) bool {
waitOnScreen(w)
mygo.RunOnMain(func() { darwin.TestAppPress(w.NativeHandle(), x, y, true) })
mygo.RunOnMain(func() {}) // after what the press posted
mygo.RunOnMain(func() { darwin.TestAppPress(w.NativeHandle(), x, y, false) })
return true
}
// waitOnScreen waits for a window to show on screen, as a user sees a
// window before clicking it: a window shows a while after it is ordered
// front and made key, longer on a busy runner, and AppKit puts a click
// made for it before then elsewhere in it, as outside its content, where
// it clicks nothing. wait.Guard is a hang guard: it says so if the window
// did not show by then, before the click that will miss.
func waitOnScreen(w *mygo.Window) {
if !wait.Poll(func() (on bool) {
mygo.RunOnMain(func() { on = darwin.TestOnScreen(w.NativeHandle()) })
return on
}) {
log.Printf("e2e: the window %q did not show on screen in %v: a click made for it misses", w.Title(), wait.Guard)
}
}
func sideButton(w *mygo.Window, back bool) (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestSideButton(w.NativeHandle(), back) })
return ok
}
// pinch pinches the touchpad at (x, y) by scale, and returns the scale
// the platform reports.
func pinch(w *mygo.Window, x, y, scale float64) (got float64, ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestPinch(w.NativeHandle(), x, y, scale-1) })
return scale, ok
}
func drag(w *mygo.Window, points [][2]float64) bool {
mygo.RunOnMain(func() { darwin.TestDrag(w.NativeHandle(), points) })
return true
}
// wheel turns the wheel at (x, y) of a window's content, through the
// window's own hit testing.
// The wheel over a web view is covered by internal/darwin's
// TestEmbeddedWebViewScrollReachesSurface, with AppKit's events.
func wheel(*mygo.Window, float64, float64) bool { return false }
func hitView(w *mygo.Window, x, y float64) (class string) {
mygo.RunOnMain(func() { class = darwin.TestHitView(w.NativeHandle(), x, y) })
return class
}
func webViewAttached(w *mygo.Window) (attached bool, supported bool) {
mygo.RunOnMain(func() { attached = darwin.TestWebViewAttached(w.NativeHandle()) })
return attached, true
}
// deactivateApp activates the Finder, as the user would.
func deactivateApp() bool {
return exec.Command("open", "-a", "Finder").Run() == nil
}
func appActive() (active bool, supported bool) {
mygo.RunOnMain(func() { active = darwin.TestIsFrontmost() })
return active, true
}
func collectionBehavior(w *mygo.Window) (behavior uint, supported bool) {
mygo.RunOnMain(func() { behavior = darwin.TestCollectionBehavior(w.NativeHandle()) })
return behavior, true
}
func material(w *mygo.Window) (class string, style int, radius float64, active bool, supported bool) {
mygo.RunOnMain(func() { class, style, radius, active = darwin.TestMaterial(w.NativeHandle()) })
return class, style, radius, active, true
}
// materialState returns the NSVisualEffectState of the window's material.
func materialState(w *mygo.Window) (state int, supported bool) {
mygo.RunOnMain(func() { state = darwin.TestMaterialState(w.NativeHandle()) })
return state, true
}
func roundedBacking(w *mygo.Window) (opaque bool, alpha, red float64, supported bool) {
mygo.RunOnMain(func() { opaque, alpha, red = darwin.TestRoundedBacking(w.NativeHandle()) })
return opaque, alpha, red, true
}
// windowBacking reports whether the window is opaque, and the alpha of its
// background color.
func windowBacking(w *mygo.Window) (opaque bool, alpha float64, supported bool) {
mygo.RunOnMain(func() { opaque, alpha = darwin.TestWindowBacking(w.NativeHandle()) })
return opaque, alpha, true
}
func dockDevTools(w *mygo.Window) (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestDockInspector(w.NativeHandle()) })
return ok
}
func dockedDevToolsPlace(w *mygo.Window) (place string) {
mygo.RunOnMain(func() { place = darwin.TestInspectorPlace(w.NativeHandle()) })
return place
}
// Context menus track the mouse in a modal loop; not automated.
func dismissPopups() (int, bool) { return 0, false }
func setDroppedFiles(w *mygo.Window, paths []string) bool {
mygo.RunOnMain(func() { darwin.TestSetDroppedFiles(w.NativeHandle(), paths) })
return true
}
func dockTileImage() (png []byte, supported bool) {
mygo.RunOnMain(func() { png = darwin.TestDockTileImage() })
return png, true
}
func defaultURLHandler(string) (string, bool) { return "", false }
func dockMenu(click int) (titles []string, supported bool) {
mygo.RunOnMain(func() { titles = darwin.TestDockMenu(click) })
return titles, true
}
// Posting key events needs the accessibility permission on macOS.
func pressCtrlShiftK() bool { return false }
// Only Linux binds global shortcuts through a desktop portal.
func usePortalShortcuts() (func(), bool) { return nil, false }
func pressKeys(...string) bool { return false }
func fullScreenHidesToolbar(w *mygo.Window) (hides bool, supported bool) {
mygo.RunOnMain(func() { hides = darwin.TestFullScreenHidesToolbar(w.NativeHandle()) })
return hides, true
}
func trafficLights(w *mygo.Window) (x, y float64, supported bool) {
mygo.RunOnMain(func() { x, y = darwin.TestTrafficLights(w.NativeHandle()) })
return x, y, true
}
func setWindowAppearance(w *mygo.Window, dark bool) {
mygo.RunOnMain(func() { darwin.TestSetWindowAppearance(w.NativeHandle(), dark) })
}
// Frameless windows keep native resize borders here.
func movePointer(int, int) bool { return false }
func pressButton(bool) bool { return false }
func resizeCursor(*mygo.Window) (string, bool) { return "", false }
// The menu bar belongs to the application on macOS.
func menuBarShown(*mygo.Window) (bool, bool) { return false, false }
func activateAccelerator(*mygo.Window, string) (bool, bool) { return false, false }
func enterMenuBar(*mygo.Window, string) (bool, bool, bool) { return false, false, false }
func openMenus(*mygo.Window, byte) bool { return false }
func closeMenus() {}
// The traffic lights are AppKit's own.
func titleButtons(*mygo.Window) ([]string, bool) { return nil, false }
func pressTitleButton(*mygo.Window, string) bool { return false }
func topNonClient(*mygo.Window) (int32, int32, bool) { return 0, 0, false }
func menuBarColors(*mygo.Window) (uint32, uint32, bool) { return 0, 0, false }
func titleButtonColor(*mygo.Window, string) (uint8, uint8, uint8, bool) { return 0, 0, 0, false }
// AppKit composes the window: there is no redirection bitmap to go without.
func composition(*mygo.Window) (bool, bool, bool) { return false, false, false }
func canCompose() bool { return false }
func loseComposition(bool) bool { return false }
// WebKit creates web views with their windows.
func failWebViews(int) bool { return false }
func clickAndType(w *mygo.Window, x, y float64, text string) (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestClickAndType(w.NativeHandle(), x, y, text) })
return ok
}
// pressKey presses the key of a virtual key code in a window of native UI,
// through the input method.
func pressKey(w *mygo.Window, code uint16, chars string) (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestKey(w.NativeHandle(), code, chars) })
return ok
}
// AppKit routes a drag to the view under the pointer, which
// dropFiles, dropping on the content's, skips.
func dragFiles(*mygo.Window, float64, float64, []string) (bool, bool) { return false, false }
// pressTab presses Tab in a window of native UI, with Shift when back, as
// the keyboard does: in the content or in the page of a web view.
func pressTab(w *mygo.Window, back bool) (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestKeyShift(w.NativeHandle(), 48, "\t", back) })
return ok
}
// pressKeyComposing presses a key in a window of native UI with the test
// standing in for the input method: it commits commit, unless empty, then
// passes the key on as command (doCommandBySelector:), unless empty.
func pressKeyComposing(w *mygo.Window, code uint16, chars, commit, command string) (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestKeyComposing(w.NativeHandle(), code, chars, commit, command) })
return ok
}
func compose(w *mygo.Window, text string, caret int, commit bool) (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestCompose(w.NativeHandle(), text, caret, commit) })
return ok
}
func controlClick(w *mygo.Window, x, y float64) bool {
mygo.RunOnMain(func() { darwin.TestControlClick(w.NativeHandle(), x, y) })
return true
}
func secondaryClickAsPrimary(w *mygo.Window, x, y float64) (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestSecondaryClickAsPrimary(w.NativeHandle(), x, y) })
return ok
}
func composeOver(w *mygo.Window, text string, caret int, commit bool, from, length int) (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestComposeOver(w.NativeHandle(), text, caret, commit, from, length) })
return ok
}
func inputClient(w *mygo.Window) (selected [2]int, document string, ok bool) {
mygo.RunOnMain(func() { selected, document = darwin.TestInputClient(w.NativeHandle()) })
return selected, document, true
}
func dropFiles(w *mygo.Window, x, y float64, paths []string) (over, dropped, ok bool) {
mygo.RunOnMain(func() { over, dropped = darwin.TestDropFiles(w.NativeHandle(), x, y, paths) })
return over, dropped, true
}
// The roles of elements in the accessibility API of AppKit.
const roleText, roleButton, roleCheckBox, roleTextField, roleSlider = "AXStaticText", "AXButton", "AXCheckBox", "AXTextField", "AXSlider"
// roleListItem is the role of the rows of a List.
const roleListItem = "AXRow/AXTableRow"
func accessibility(w *mygo.Window) (nodes []accessNode, ok bool) {
mygo.RunOnMain(func() {
for _, n := range darwin.TestAccessibility(w.NativeHandle()) {
role := n.Role
if n.Subrole != "" {
role += "/" + n.Subrole
}
nodes = append(nodes, accessNode{role, n.Label, n.Value})
}
})
return nodes, true
}
// axAttribute reads an attribute of an element through AppKit's older
// accessibility API, which only macOS has.
func axAttribute(w *mygo.Window, label, attr string) (value string, settable, named, ok bool) {
mygo.RunOnMain(func() { value, settable, named, ok = darwin.TestAccessibilityAttribute(w.NativeHandle(), label, attr) })
return value, settable, named, ok
}
func accessPerform(w *mygo.Window, label, action, value string) (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestAccessibilityPerform(w.NativeHandle(), label, action, value) })
return ok
}
// observe has key-value observing watch the view of a window showing
// native UI and its elements, until stop.
func observe(w *mygo.Window) (stop func(), supported bool) {
var end func()
mygo.RunOnMain(func() { end = darwin.TestObserve(w.NativeHandle()) })
return func() { mygo.RunOnMain(end) }, true
}
// Only Linux draws native UI in a GtkGLArea, nor waits to load the GPU's
// driver.
func glSurface(*mygo.Window) (string, []byte, int, int, bool) { return "", nil, 0, 0, false }
func memoryUI(*testing.T) bool { return false }
func surfaceOnScreen(*mygo.Window) ([]byte, bool) { return nil, false }
// Only Windows reads the screen over native UI.
func screenColor(*mygo.Window, float64, float64) (uint8, uint8, uint8, bool) { return 0, 0, 0, false }
// Context menus are not automated on macOS: one shown waits for the user.
func rightClick(*mygo.Window, float64, float64) bool { return false }
func popupMenus() ([][]string, bool) { return nil, false }
func choosePopupItem(string) bool { return false }
func popupItemEnabled(string) (bool, bool) { return false, false }
// pressEscape presses Escape in the key window, as the keyboard does.
func pressEscape(*mygo.Window) bool {
mygo.RunOnMain(func() { darwin.TestAppKey(53, "\x1b") })
return true
}
func documentChrome(w *mygo.Window) (title, file string, icon, edited, supported bool) {
mygo.RunOnMain(func() { title, file, icon, edited = darwin.TestDocumentChrome(w.NativeHandle()) })
return title, file, icon, edited, true
}
func sheet(w *mygo.Window) (texts, buttons []string, ok, supported bool) {
mygo.RunOnMain(func() { texts, buttons, ok = darwin.TestSheet(w.NativeHandle()) })
return texts, buttons, ok, true
}
func endSheetButton(w *mygo.Window, i int) (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestEndSheetButton(w.NativeHandle(), i) })
return ok
}
// Panels' window styles are Windows'.
func panelStyles(*mygo.Window) (bool, bool, bool, bool) { return false, false, false, false }
// throttlingOff reports whether the page of w, or of its first web view,
// is set up to keep running while it can't be seen, and how many of the
// settings that take the platform has.
func throttlingOff(w *mygo.Window, webView bool) (off bool, settings int) {
mygo.RunOnMain(func() { off, settings = darwin.TestBackgroundThrottlingOff(w.NativeHandle(), webView) })
return off, settings
}
// mockCapture gives a window's page WebKit's mock camera and microphone.
func mockCapture(w *mygo.Window) (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestMockCaptureDevices(w.NativeHandle()) })
return ok
}
// pageGestures reports whether a swipe navigates and a pinch magnifies the
// page of a window, or with webView 0 or more, of its web view of that
// index.
func pageGestures(w *mygo.Window, webView int) (swipe, pinch, ok bool) {
mygo.RunOnMain(func() { swipe, pinch, ok = darwin.TestPageGestures(w.NativeHandle(), webView) })
return swipe, pinch, ok
}
// A WKWebView's magnification follows a trackpad's gesture through its
// phases, which a test can't make.
func pinchPage(*mygo.Window, int, float64, float64, ...float64) bool { return false }
// pageMenusHooked tells that the tests can right-click a page and read
// the menu it opens, through rightClickPage, pageMenu, choosePageMenuItem
// and dismissPageMenu.
const pageMenusHooked = true
// rightClickPage right-clicks (x, y) in a window's page.
func rightClickPage(w *mygo.Window, x, y float64) bool {
waitOnScreen(w)
mygo.RunOnMain(func() { darwin.TestRightClickPage(w.NativeHandle(), x, y) })
return true
}
// pageMenu returns the titles of the items of the web view's context menu
// shown over a page, "-" for separators, and whether one is shown. AppKit
// tracks the menu in a loop of its own, which runs the main thread's work.
func pageMenu() (labels []string, shown bool) {
mygo.RunOnMain(func() { labels, shown = darwin.TestPageMenu() })
return labels, shown
}
// choosePageMenuItem chooses an item of that menu by its title.
func choosePageMenuItem(label string) (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestChoosePageMenuItem(label) })
return ok
}
func dismissPageMenu() { mygo.RunOnMain(darwin.TestDismissPageMenu) }
// Only Windows' tests start a process that takes the foreground.
func takeForeground(*mygo.Window) {}
// pressLetter presses the key of an uppercase letter, with Command held
// when cmd is set, as the keyboard does in a window of native UI: in the
// content, or in the page of a web view that has the keyboard.
func pressLetter(w *mygo.Window, letter byte, cmd bool) (ok bool) {
code, known := map[byte]uint16{'J': 0x26, 'K': 0x28, 'L': 0x25}[letter]
if !known {
return false
}
chars := string(rune(letter - 'A' + 'a'))
mygo.RunOnMain(func() {
if cmd {
ok = darwin.TestKeyCmd(w.NativeHandle(), code, chars)
} else {
ok = darwin.TestKey(w.NativeHandle(), code, chars)
}
})
return ok
}
func glassTint(w *mygo.Window) (red, green, blue, alpha float64, ok bool) {
mygo.RunOnMain(func() { red, green, blue, alpha = darwin.TestGlassTint(w.NativeHandle()) })
return red, green, blue, alpha, true
}
func nativeGlassSupported() (ok bool) {
mygo.RunOnMain(func() { ok = darwin.TestNativeGlassSupported() })
return ok
}
func nativeGlass(w *mygo.Window) (class string, frame [4]float64, style int, ok bool) {
mygo.RunOnMain(func() { class, frame, style, ok = darwin.TestNativeGlass(w.NativeHandle()) })
return class, frame, style, ok
}
func nativeGlassTint(w *mygo.Window) (red, green, blue, alpha float64) {
mygo.RunOnMain(func() { red, green, blue, alpha = darwin.TestNativeGlassTint(w.NativeHandle()) })
return red, green, blue, alpha
}
func activateApp() { mygo.RunOnMain(darwin.TestActivate) }
// Only X servers keep a keyboard's state for the tests after a test: see
// left_behind_linux_test.go.
func keyboardState() (state string, restore func()) { return "", func() {} }
+451
View File
@@ -0,0 +1,451 @@
//go:build linux && !android && (amd64 || arm64) && !android
package e2e
import (
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/internal/wait"
)
func activateMenu(w *mygo.Window, path ...string) (err error) {
mygo.RunOnMain(func() { err = linux.TestActivateMenuItem(w.NativeHandle(), path...) })
return err
}
func menuItemEnabled(w *mygo.Window, path ...string) (enabled bool, err error) {
mygo.RunOnMain(func() { enabled, err = linux.TestMenuItemEnabled(w.NativeHandle(), path...) })
return enabled, err
}
// Key presses and dialogs need an input device under Xvfb; not covered.
func pressShortcut(string, bool) (bool, bool) { return false, false }
func endSheet(*mygo.Window) (bool, bool) { return false, false }
// fake runs a hook that fakes input through XTEST, and returns once the
// app handled that input, as the hooks of macOS and Windows do: the X
// server makes the events and the app gets them later, on the main
// thread, after other work queued there. A test that went on at once
// would race them: Edit > Copy while the press of a drag was handled but
// not its release, a composition the click's press then ended.
func fake(hook func() bool) (ok bool) {
mygo.RunOnMain(func() { ok = hook() })
if !ok {
return false
}
// The hook synced with the X server: the events wait in the app's
// queue, and it has handled them once it has no events left. All but
// a last motion, which GDK holds until its next frame to merge it with
// the ones that follow: a test moving the pointer alone waits for
// what the move does.
wait.Poll(func() (pending bool) {
mygo.RunOnMain(func() { pending = linux.TestInputPending() })
return !pending
})
return true
}
// Clicks reach windows showing native UI only, through XTEST.
func click(w *mygo.Window, x, y float64) bool {
return fake(func() bool { return linux.TestClickSurface(w.NativeHandle(), x, y) })
}
// clickPage clicks a window's page, through XTEST.
func clickPage(w *mygo.Window, x, y float64) bool {
return fake(func() bool { return linux.TestClickPage(w.NativeHandle(), x, y) })
}
// appClick is click, already through XTEST.
func appClick(w *mygo.Window, x, y float64) bool { return click(w, x, y) }
// heldAppClick is appClick: the grab of a focusable flyout eats the press
// that closes it, however long it is held.
func heldAppClick(w *mygo.Window, x, y float64) bool { return appClick(w, x, y) }
func sideButton(w *mygo.Window, back bool) bool {
return fake(func() bool { return linux.TestSideButton(w.NativeHandle(), back) })
}
// pinch pinches the touchpad at (x, y) by scale with GDK's events, which
// only Wayland makes.
func pinch(w *mygo.Window, x, y, scale float64) (got float64, ok bool) {
mygo.RunOnMain(func() { ok = linux.TestPinchSurface(w.NativeHandle(), x, y, scale) })
return scale, ok
}
func drag(w *mygo.Window, points [][2]float64) bool {
return fake(func() bool { return linux.TestDragSurface(w.NativeHandle(), points) })
}
// wheel turns the mouse's wheel a notch down at (x, y), through XTEST.
func wheel(w *mygo.Window, x, y float64) bool {
return fake(func() bool { return linux.TestWheelSurface(w.NativeHandle(), x, y) })
}
func webViewAttached(*mygo.Window) (bool, bool) { return false, false }
// Collection behaviors and deactivating the app are macOS's.
func collectionBehavior(*mygo.Window) (uint, bool) { return 0, false }
func deactivateApp() bool { return false }
func material(*mygo.Window) (string, int, float64, bool, bool) { return "", 0, 0, false, false }
func materialState(*mygo.Window) (int, bool) { return 0, false }
func roundedBacking(*mygo.Window) (bool, float64, float64, bool) { return false, 0, 0, false }
func windowBacking(*mygo.Window) (bool, float64, bool) { return false, 0, false }
func appActive() (bool, bool) { return false, false }
// WebKitGTK docks the inspector inside the web view.
func dockDevTools(*mygo.Window) bool { return false }
func dockedDevToolsPlace(*mygo.Window) string { return "" }
func dismissPopups() (n int, supported bool) {
mygo.RunOnMain(func() { n = linux.TestDismissPopups() })
return n, true
}
func setDroppedFiles(w *mygo.Window, paths []string) bool {
mygo.RunOnMain(func() { linux.TestSetDroppedFiles(w.NativeHandle(), paths) })
return true
}
// The progress bar is shown by the shell, out of the app's reach.
func dockTileImage() ([]byte, bool) { return nil, false }
func defaultURLHandler(scheme string) (id string, supported bool) {
mygo.RunOnMain(func() { id = linux.TestDefaultURLHandler(scheme) })
return id, true
}
func dockMenu(int) ([]string, bool) { return nil, false }
// recentDocumentRecorded reports whether path is among the user's recently
// used files.
func recentDocumentRecorded(path string) (recorded, supported bool) {
mygo.RunOnMain(func() { recorded = linux.TestHasRecentItem(path) })
return recorded, true
}
// pressCtrlShiftK presses Ctrl+Shift+K like a keyboard.
func pressCtrlShiftK() bool {
return fake(func() bool { return linux.TestPressKeys("Control_L", "Shift_L", "k") })
}
// usePortalShortcuts makes global shortcuts bind through the XDG desktop
// portal, as on Wayland, when the desktop offers it.
func usePortalShortcuts() (restore func(), ok bool) {
mygo.RunOnMain(func() { ok = linux.TestUsePortalShortcuts(true) })
return func() { mygo.RunOnMain(func() { linux.TestUsePortalShortcuts(false) }) }, ok
}
// pressKeys presses keys, X keysym names such as "Control_L", together.
func pressKeys(keys ...string) bool {
return fake(func() bool { return linux.TestPressKeys(keys...) })
}
// Only macOS windows have a toolbar.
func fullScreenHidesToolbar(*mygo.Window) (bool, bool) { return false, false }
// Only macOS windows have traffic lights.
func trafficLights(*mygo.Window) (float64, float64, bool) { return 0, 0, false }
func setWindowAppearance(*mygo.Window, bool) {}
// movePointer moves the pointer to a point of the screen, and pressButton
// presses or releases the first mouse button, like a mouse.
func movePointer(x, y int) bool {
return fake(func() bool { return linux.TestMovePointer(x, y) })
}
func pressButton(press bool) bool {
return fake(func() bool { return linux.TestPressButton(press) })
}
func resizeCursor(w *mygo.Window) (name string, supported bool) {
mygo.RunOnMain(func() { name = linux.TestResizeCursor(w.NativeHandle()) })
return name, true
}
func menuBarShown(w *mygo.Window) (shown, supported bool) {
mygo.RunOnMain(func() { shown, _ = linux.TestMenuBarState(w.NativeHandle()) })
return shown, true
}
func activateAccelerator(w *mygo.Window, accel string) (handled, supported bool) {
mygo.RunOnMain(func() { handled = linux.TestActivateAccelerator(w.NativeHandle(), accel) })
return handled, true
}
// enterMenuBar presses key, an X keysym name, on the window: the bar should
// show with its first menu open. Then it closes the menus, as Escape does.
func enterMenuBar(w *mygo.Window, key string) (during, after, supported bool) {
if !w.IsFocused() || !pressKeys(key) {
return false, false, false
}
state := func() (shown, open bool) {
mygo.RunOnMain(func() { shown, open = linux.TestMenuBarState(w.NativeHandle()) })
return shown, open
}
during = wait.Poll(func() bool { shown, open := state(); return shown && open })
mygo.RunOnMain(func() { linux.TestCloseMenuBar(w.NativeHandle()) })
wait.Poll(func() bool { after, _ = state(); return !after })
return during, after, true
}
// Alt opens the menus in the bar here (enterMenuBar), and the items of GTK
// menus have no letters.
func openMenus(*mygo.Window, byte) bool { return false }
func closeMenus() {}
// titleButtons returns GTK's title buttons over the page of a window with
// a hidden title bar.
func titleButtons(w *mygo.Window) (names []string, supported bool) {
mygo.RunOnMain(func() { names = linux.TestTitleButtons(w.NativeHandle()) })
return names, true
}
func pressTitleButton(w *mygo.Window, name string) (ok bool) {
mygo.RunOnMain(func() { ok = linux.TestPressTitleButton(w.NativeHandle(), name) })
return ok
}
func topNonClient(*mygo.Window) (int32, int32, bool) { return 0, 0, false }
func menuBarColors(*mygo.Window) (uint32, uint32, bool) { return 0, 0, false }
func titleButtonColor(*mygo.Window, string) (uint8, uint8, uint8, bool) { return 0, 0, 0, false }
// Linux shows no material.
func composition(*mygo.Window) (bool, bool, bool) { return false, false, false }
func canCompose() bool { return false }
func loseComposition(bool) bool { return false }
// WebKitGTK creates web views with their windows.
func failWebViews(int) bool { return false }
// A Control-click is a secondary click on macOS only.
func controlClick(*mygo.Window, float64, float64) bool { return false }
func secondaryClickAsPrimary(*mygo.Window, float64, float64) bool { return false }
// composeOver does what an input method that edits typed text does through
// GTK: it deletes the text around the caret it composes over, then
// composes or commits.
func composeOver(w *mygo.Window, text string, caret int, commit bool, from, length int) (ok bool) {
mygo.RunOnMain(func() { ok = linux.TestComposeOver(w.NativeHandle(), text, caret, commit, from, length) })
return ok
}
// inputClient returns the caret and the text around it that input methods
// get through GTK, which knows no selection, and no composition in it.
func inputClient(w *mygo.Window) (selected [2]int, document string, ok bool) {
mygo.RunOnMain(func() {
var caret int
document, caret, ok = linux.TestSurrounding(w.NativeHandle())
selected = [2]int{caret, 0}
})
return selected, document, ok
}
func dropFiles(w *mygo.Window, x, y float64, paths []string) (over, dropped, ok bool) {
mygo.RunOnMain(func() { over, dropped = linux.TestDropFiles(w.NativeHandle(), x, y, paths) })
return over, dropped, true
}
// The roles of elements in ATK.
const roleText, roleButton, roleCheckBox, roleTextField, roleSlider = "label", "button", "check box", "entry", "slider"
// roleListItem is the role of the rows of a List.
const roleListItem = "list item"
func accessibility(w *mygo.Window) (nodes []accessNode, ok bool) {
mygo.RunOnMain(func() {
var list []linux.TestAccessNode
list, ok = linux.TestAccessibility(w.NativeHandle())
for _, n := range list {
nodes = append(nodes, accessNode{n.Role, n.Label, n.Value})
}
})
return nodes, ok
}
func accessPerform(w *mygo.Window, label, action, value string) (ok bool) {
mygo.RunOnMain(func() { ok = linux.TestAccessibilityPerform(w.NativeHandle(), label, action, value) })
return ok
}
// Typing into native UI is only automated on macOS.
func clickAndType(*mygo.Window, float64, float64, string) bool { return false }
func compose(*mygo.Window, string, int, bool) bool { return false }
// glSurface returns how the native UI of a window draws ("opengl",
// "memory", "cairo") and, for a GtkGLArea, the pixels of its framebuffer,
// premultiplied BGRA rows from the top.
func glSurface(w *mygo.Window) (how string, pix []byte, width, height int, supported bool) {
mygo.RunOnMain(func() { how, pix, width, height = linux.TestSurfaceGL(w.NativeHandle()) })
return how, pix, width, height, true
}
// memoryUI has the windows of native UI created from now on draw in
// memory, in a GtkDrawingArea, as without a GPU.
func memoryUI(t *testing.T) bool {
t.Setenv("MYGO_GPU", "0")
return true
}
// surfaceOnScreen returns, as a PNG, what the display shows of a window's
// native UI.
// Only Windows reads the screen over native UI.
func screenColor(*mygo.Window, float64, float64) (uint8, uint8, uint8, bool) { return 0, 0, 0, false }
func surfaceOnScreen(w *mygo.Window) (png []byte, supported bool) {
mygo.RunOnMain(func() { png = linux.TestSurfaceOnScreen(w.NativeHandle()) })
return png, true
}
// rightClick clicks (x, y) in a window showing native UI with the
// secondary button, through XTEST.
func rightClick(w *mygo.Window, x, y float64) bool {
return fake(func() bool { return linux.TestRightClickSurface(w.NativeHandle(), x, y) })
}
// popupMenus returns the labels of the items of the context menus shown.
func popupMenus() (menus [][]string, supported bool) {
mygo.RunOnMain(func() { menus = linux.TestPopups() })
return menus, true
}
func choosePopupItem(label string) (ok bool) {
mygo.RunOnMain(func() { ok = linux.TestChoosePopupItem(label) })
return ok
}
func popupItemEnabled(label string) (enabled, ok bool) {
mygo.RunOnMain(func() { enabled, ok = linux.TestPopupItemEnabled(label) })
return enabled, ok
}
// Only macOS has key-value observing.
func observe(*mygo.Window) (func(), bool) { return nil, false }
// Input methods keep the keys typed while they compose from the content
// themselves here (GTK's filtering, IMM32's VK_PROCESSKEY), which a
// composition the test makes up does not show.
func pressKey(*mygo.Window, uint16, string) bool { return false }
func pressKeyComposing(*mygo.Window, uint16, string, string, string) bool { return false }
// X routes a drag to the window under the pointer, which
// dropFiles, dropping on the content's, skips.
func dragFiles(*mygo.Window, float64, float64, []string) (bool, bool) { return false, false }
// pressTab presses Tab, with Shift when back, as the keyboard does.
func pressTab(_ *mygo.Window, back bool) bool {
if back {
return pressKeys("Shift_L", "Tab")
}
return pressKeys("Tab")
}
// AppKit's older accessibility API is macOS's.
func axAttribute(*mygo.Window, string, string) (string, bool, bool, bool) {
return "", false, false, false
}
// pressEscape presses Escape, as the keyboard does.
func pressEscape(*mygo.Window) bool { return pressKeys("Escape") }
// GTK shows no document but the title.
func documentChrome(w *mygo.Window) (title, file string, icon, edited, supported bool) {
mygo.RunOnMain(func() { title = linux.TestWindowTitle(w.NativeHandle()) })
return title, "", false, false, true
}
func sheet(*mygo.Window) ([]string, []string, bool, bool) { return nil, nil, false, false }
func endSheetButton(*mygo.Window, int) bool { return false }
// Panels' window styles are Windows'.
func panelStyles(*mygo.Window) (bool, bool, bool, bool) { return false, false, false, false }
// throttlingOff reports whether the page of w, or of its first web view,
// is set up to keep running while it can't be seen, and how many of the
// settings that take the platform has.
func throttlingOff(w *mygo.Window, webView bool) (off bool, settings int) {
mygo.RunOnMain(func() { off, settings = linux.TestBackgroundThrottlingOff(w.NativeHandle(), webView) })
return off, settings
}
// mockCapture gives a window's page WebKit's mock camera and microphone.
func mockCapture(w *mygo.Window) (ok bool) {
mygo.RunOnMain(func() { ok = linux.TestMockCaptureDevices(w.NativeHandle()) })
return ok
}
// pageGestures reports whether a swipe navigates and a pinch zooms the page
// of a window, or with webView 0 or more, of its web view of that index.
func pageGestures(w *mygo.Window, webView int) (swipe, pinch, ok bool) {
mygo.RunOnMain(func() { swipe, pinch, ok = linux.TestPageGestures(w.NativeHandle(), webView) })
return swipe, pinch, ok
}
// pinchPage pinches the touchpad over the page of a window, or of its web
// view, from 1 through scales, with GDK's events, which only Wayland
// makes.
func pinchPage(w *mygo.Window, webView int, x, y float64, scales ...float64) (ok bool) {
mygo.RunOnMain(func() { ok = linux.TestPinchPage(w.NativeHandle(), webView, x, y, scales) })
return ok
}
// pageMenusHooked tells that the tests can right-click a page and read
// the menu it opens, through rightClickPage, pageMenu, choosePageMenuItem
// and dismissPageMenu.
const pageMenusHooked = true
// rightClickPage clicks (x, y) in a window's page with the secondary
// button, through XTEST.
func rightClickPage(w *mygo.Window, x, y float64) bool {
return fake(func() bool { return linux.TestRightClickPage(w.NativeHandle(), x, y) })
}
// pageMenu returns the labels of the items of the web view's context menu
// shown over a page, "-" for separators, and whether one is shown.
func pageMenu() (labels []string, shown bool) {
mygo.RunOnMain(func() { labels, shown = linux.TestPageMenu() })
return labels, shown
}
// choosePageMenuItem chooses an item of that menu by its label.
func choosePageMenuItem(label string) (ok bool) {
mygo.RunOnMain(func() { ok = linux.TestChoosePageMenuItem(label) })
return ok
}
func dismissPageMenu() { mygo.RunOnMain(linux.TestDismissPageMenu) }
// Only Windows' tests start a process that takes the foreground.
func takeForeground(*mygo.Window) {}
// pressLetter presses the key of an uppercase letter, with Ctrl held when
// cmd is set, like a keyboard.
func pressLetter(_ *mygo.Window, letter byte, cmd bool) bool {
key := string(rune(letter - 'A' + 'a'))
if cmd {
return pressKeys("Control_L", key)
}
return pressKeys(key)
}
func glassTint(*mygo.Window) (red, green, blue, alpha float64, ok bool) { return 0, 0, 0, 0, false }
func nativeGlassSupported() bool { return false }
func nativeGlass(*mygo.Window) (class string, frame [4]float64, style int, ok bool) {
return "", frame, 0, false
}
func nativeGlassTint(*mygo.Window) (red, green, blue, alpha float64) { return 0, 0, 0, 0 }
func activateApp() {}
func hitView(*mygo.Window, float64, float64) string { return "" }
+205
View File
@@ -0,0 +1,205 @@
//go:build !(darwin && !ios) && !(linux && !android && (amd64 || arm64)) && !(windows && (amd64 || arm64)) && !js
package e2e
import (
"errors"
"testing"
"github.com/egoist/mygo"
)
// Platforms without a backend run no GUI tests.
func activateMenu(*mygo.Window, ...string) error { return errors.New("unsupported") }
func menuItemEnabled(*mygo.Window, ...string) (bool, error) { return false, errors.ErrUnsupported }
func pressShortcut(string, bool) (bool, bool) { return false, false }
func endSheet(*mygo.Window) (bool, bool) { return false, false }
func recentDocumentRecorded(string) (recorded, supported bool) { return false, false }
func click(*mygo.Window, float64, float64) bool { return false }
func appClick(*mygo.Window, float64, float64) bool { return false }
func clickPage(*mygo.Window, float64, float64) bool { return false }
func heldAppClick(*mygo.Window, float64, float64) bool { return false }
func drag(*mygo.Window, [][2]float64) bool { return false }
func sideButton(*mygo.Window, bool) bool { return false }
func pinch(*mygo.Window, float64, float64, float64) (float64, bool) { return 0, false }
func wheel(*mygo.Window, float64, float64) bool { return false }
func webViewAttached(*mygo.Window) (bool, bool) { return false, false }
// Collection behaviors and deactivating the app are macOS's.
func collectionBehavior(*mygo.Window) (uint, bool) { return 0, false }
func deactivateApp() bool { return false }
func material(*mygo.Window) (string, int, float64, bool, bool) { return "", 0, 0, false, false }
func materialState(*mygo.Window) (int, bool) { return 0, false }
func roundedBacking(*mygo.Window) (bool, float64, float64, bool) { return false, 0, 0, false }
func windowBacking(*mygo.Window) (bool, float64, bool) { return false, 0, false }
func appActive() (bool, bool) { return false, false }
func dockDevTools(*mygo.Window) bool { return false }
func dockedDevToolsPlace(*mygo.Window) string { return "" }
func dismissPopups() (int, bool) { return 0, false }
func setDroppedFiles(*mygo.Window, []string) bool { return false }
// The progress bar is shown by the shell, out of the app's reach.
func dockTileImage() ([]byte, bool) { return nil, false }
func defaultURLHandler(string) (string, bool) { return "", false }
func dockMenu(int) ([]string, bool) { return nil, false }
// Posting key events needs the accessibility permission on macOS.
func pressCtrlShiftK() bool { return false }
// Only Linux binds global shortcuts through a desktop portal.
func usePortalShortcuts() (func(), bool) { return nil, false }
func pressKeys(...string) bool { return false }
// Only macOS windows have a toolbar.
func fullScreenHidesToolbar(*mygo.Window) (bool, bool) { return false, false }
// Only macOS windows have traffic lights.
func trafficLights(*mygo.Window) (float64, float64, bool) { return 0, 0, false }
func setWindowAppearance(*mygo.Window, bool) {}
func movePointer(int, int) bool { return false }
func pressButton(bool) bool { return false }
func resizeCursor(*mygo.Window) (string, bool) { return "", false }
func menuBarShown(*mygo.Window) (bool, bool) { return false, false }
func activateAccelerator(*mygo.Window, string) (bool, bool) { return false, false }
func enterMenuBar(*mygo.Window, string) (bool, bool, bool) { return false, false, false }
func openMenus(*mygo.Window, byte) bool { return false }
func closeMenus() {}
func titleButtons(*mygo.Window) ([]string, bool) { return nil, false }
func pressTitleButton(*mygo.Window, string) bool { return false }
func topNonClient(*mygo.Window) (int32, int32, bool) { return 0, 0, false }
func menuBarColors(*mygo.Window) (uint32, uint32, bool) { return 0, 0, false }
func titleButtonColor(*mygo.Window, string) (uint8, uint8, uint8, bool) { return 0, 0, 0, false }
func composition(*mygo.Window) (bool, bool, bool) { return false, false, false }
func canCompose() bool { return false }
func loseComposition(bool) bool { return false }
func failWebViews(int) bool { return false }
// A Control-click is a secondary click on macOS only.
func controlClick(*mygo.Window, float64, float64) bool { return false }
func secondaryClickAsPrimary(*mygo.Window, float64, float64) bool { return false }
// Input methods, file drops and assistive technology are only automated
// on macOS.
func composeOver(*mygo.Window, string, int, bool, int, int) bool { return false }
func inputClient(*mygo.Window) ([2]int, string, bool) { return [2]int{}, "", false }
func dropFiles(*mygo.Window, float64, float64, []string) (bool, bool, bool) {
return false, false, false
}
func accessibility(*mygo.Window) ([]accessNode, bool) { return nil, false }
func accessPerform(*mygo.Window, string, string, string) bool { return false }
const roleText, roleButton, roleCheckBox, roleTextField, roleSlider = "text", "button", "check box", "text field", "slider"
// roleListItem is the role of the rows of a List.
const roleListItem = "list item"
// Typing into native UI is only automated on macOS.
func clickAndType(*mygo.Window, float64, float64, string) bool { return false }
func compose(*mygo.Window, string, int, bool) bool { return false }
// Only Linux draws native UI in a GtkGLArea, nor waits to load the GPU's
// driver.
func glSurface(*mygo.Window) (string, []byte, int, int, bool) { return "", nil, 0, 0, false }
func memoryUI(*testing.T) bool { return false }
func surfaceOnScreen(*mygo.Window) ([]byte, bool) { return nil, false }
// Only Windows reads the screen over native UI.
func screenColor(*mygo.Window, float64, float64) (uint8, uint8, uint8, bool) { return 0, 0, 0, false }
// Only macOS has key-value observing.
func observe(*mygo.Window) (func(), bool) { return nil, false }
func rightClick(*mygo.Window, float64, float64) bool { return false }
func popupMenus() ([][]string, bool) { return nil, false }
func choosePopupItem(string) bool { return false }
func popupItemEnabled(string) (bool, bool) { return false, false }
// Input methods keep the keys typed while they compose from the content
// themselves here (GTK's filtering, IMM32's VK_PROCESSKEY), which a
// composition the test makes up does not show.
func pressKey(*mygo.Window, uint16, string) bool { return false }
func pressTab(*mygo.Window, bool) bool { return false }
func pressKeyComposing(*mygo.Window, uint16, string, string, string) bool { return false }
func dragFiles(*mygo.Window, float64, float64, []string) (bool, bool) { return false, false }
// AppKit's older accessibility API is macOS's.
func axAttribute(*mygo.Window, string, string) (string, bool, bool, bool) {
return "", false, false, false
}
func pressEscape(*mygo.Window) bool { return false }
func documentChrome(*mygo.Window) (string, string, bool, bool, bool) {
return "", "", false, false, false
}
func sheet(*mygo.Window) ([]string, []string, bool, bool) { return nil, nil, false, false }
func endSheetButton(*mygo.Window, int) bool { return false }
// Panels' window styles are Windows'.
func panelStyles(*mygo.Window) (bool, bool, bool, bool) { return false, false, false, false }
func throttlingOff(*mygo.Window, bool) (bool, int) { return false, 0 }
func mockCapture(*mygo.Window) bool { return false }
func pageGestures(*mygo.Window, int) (bool, bool, bool) { return false, false, false }
func pinchPage(*mygo.Window, int, float64, float64, ...float64) bool { return false }
// Right-clicking a page and reading the menu it opens are not hooked here.
const pageMenusHooked = false
func rightClickPage(*mygo.Window, float64, float64) bool { return false }
func pageMenu() ([]string, bool) { return nil, false }
func choosePageMenuItem(string) bool { return false }
func dismissPageMenu() {}
func takeForeground(*mygo.Window) {}
func pressLetter(*mygo.Window, byte, bool) bool { return false }
func glassTint(*mygo.Window) (red, green, blue, alpha float64, ok bool) { return 0, 0, 0, 0, false }
func nativeGlassSupported() bool { return false }
func nativeGlass(*mygo.Window) (class string, frame [4]float64, style int, ok bool) {
return "", frame, 0, false
}
func nativeGlassTint(*mygo.Window) (red, green, blue, alpha float64) { return 0, 0, 0, 0 }
func activateApp() {}
func hitView(*mygo.Window, float64, float64) string { return "" }
// Only X servers keep a keyboard's state for the tests after a test: see
// left_behind_linux_test.go.
func keyboardState() (state string, restore func()) { return "", func() {} }
+511
View File
@@ -0,0 +1,511 @@
//go:build windows && (amd64 || arm64)
package e2e
import (
"log"
"slices"
"strings"
"testing"
"time"
"github.com/egoist/mygo"
win "github.com/egoist/mygo/internal/windows"
)
func activateMenu(w *mygo.Window, path ...string) (err error) {
mygo.RunOnMain(func() { err = win.TestActivateMenuItem(w.NativeHandle(), path...) })
return err
}
func menuItemEnabled(w *mygo.Window, path ...string) (enabled bool, err error) {
mygo.RunOnMain(func() { enabled, err = win.TestMenuItemEnabled(w.NativeHandle(), path...) })
return enabled, err
}
// Keyboard, dialog and popup automation are not wired on Windows.
func pressShortcut(string, bool) (bool, bool) { return false, false }
func endSheet(*mygo.Window) (bool, bool) { return false, false }
// recentDocumentRecorded reports whether path is in the Recent category of
// the app's jump list.
func recentDocumentRecorded(path string) (recorded, supported bool) {
var paths []string
mygo.RunOnMain(func() { paths = win.TestRecentDocuments() })
return slices.ContainsFunc(paths, func(p string) bool { return strings.EqualFold(p, path) }), true
}
// Clicks reach windows showing native UI only: WebView2 takes the mouse in
// windows of its own process.
func click(w *mygo.Window, x, y float64) (ok bool) {
mygo.RunOnMain(func() { ok = win.TestClickSurface(w.NativeHandle(), x, y) })
return ok
}
// Clicks reach windows showing native UI only: a web view's page is
// not clicked.
func clickPage(*mygo.Window, float64, float64) bool { return false }
// appClick clicks with the system's input, which activates windows, and
// returns once the app handled the click.
func appClick(w *mygo.Window, x, y float64) (ok bool) {
var missed string
mygo.RunOnMain(func() { ok, missed = win.TestInputClick(w.NativeHandle(), x, y) })
if missed != "" {
log.Printf("e2e: the click at (%v, %v) did not reach the app; the window there: %s", x, y, missed)
}
return ok
}
// heldAppClick is appClick: the owner of a focusable flyout eats the
// click that closes it, however long it is held.
func heldAppClick(w *mygo.Window, x, y float64) bool { return appClick(w, x, y) }
func sideButton(w *mygo.Window, back bool) (ok bool) {
mygo.RunOnMain(func() { ok = win.TestSideButton(w.NativeHandle(), back) })
return ok
}
// pinch pinches the touchpad at (x, y) as Windows sends it, scrolling
// with Ctrl held, which rounds scale.
func pinch(w *mygo.Window, x, y, scale float64) (got float64, ok bool) {
mygo.RunOnMain(func() { got, ok = win.TestPinchSurface(w.NativeHandle(), x, y, scale) })
return got, ok
}
func drag(w *mygo.Window, points [][2]float64) (ok bool) {
mygo.RunOnMain(func() { ok = win.TestDragSurface(w.NativeHandle(), points) })
return ok
}
// wheel turns the mouse's wheel a notch down at (x, y), with the message
// Windows sends.
func wheel(w *mygo.Window, x, y float64) (ok bool) {
mygo.RunOnMain(func() { ok = win.TestWheelSurface(w.NativeHandle(), x, y) })
return ok
}
func webViewAttached(*mygo.Window) (bool, bool) { return false, false }
// Collection behaviors and deactivating the app are macOS's.
func collectionBehavior(*mygo.Window) (uint, bool) { return 0, false }
func deactivateApp() bool { return false }
func material(*mygo.Window) (string, int, float64, bool, bool) { return "", 0, 0, false, false }
func materialState(*mygo.Window) (int, bool) { return 0, false }
func roundedBacking(*mygo.Window) (bool, float64, float64, bool) { return false, 0, 0, false }
func windowBacking(*mygo.Window) (bool, float64, bool) { return false, 0, false }
func appActive() (bool, bool) { return false, false }
// WebView2 opens DevTools in a window of its own.
func dockDevTools(*mygo.Window) bool { return false }
func dockedDevToolsPlace(*mygo.Window) string { return "" }
func dismissPopups() (int, bool) { return 0, false }
func setDroppedFiles(w *mygo.Window, paths []string) bool {
mygo.RunOnMain(func() { win.TestSetDroppedFiles(w.NativeHandle(), paths) })
return true
}
// The progress bar is shown by the shell, out of the app's reach.
func dockTileImage() ([]byte, bool) { return nil, false }
func defaultURLHandler(string) (string, bool) { return "", false }
func dockMenu(int) ([]string, bool) { return nil, false }
func pressCtrlShiftK() bool {
mygo.RunOnMain(func() { win.TestPressKeys(0x11, 0x10, 'K') }) // VK_CONTROL, VK_SHIFT
return true
}
// Only Linux binds global shortcuts through a desktop portal.
func usePortalShortcuts() (func(), bool) { return nil, false }
func pressKeys(...string) bool { return false }
// Only macOS windows have a toolbar.
func fullScreenHidesToolbar(*mygo.Window) (bool, bool) { return false, false }
// Only macOS windows have traffic lights.
func trafficLights(*mygo.Window) (float64, float64, bool) { return 0, 0, false }
func setWindowAppearance(*mygo.Window, bool) {}
// Frameless windows keep native resize borders here.
func movePointer(int, int) bool { return false }
func pressButton(bool) bool { return false }
func resizeCursor(*mygo.Window) (string, bool) { return "", false }
func menuBarShown(w *mygo.Window) (shown, supported bool) {
mygo.RunOnMain(func() { shown = win.TestMenuBarShown(w.NativeHandle()) })
return shown, true
}
func activateAccelerator(w *mygo.Window, accel string) (handled, supported bool) {
mygo.RunOnMain(func() { handled = win.TestActivateAccelerator(w.NativeHandle(), accel) })
return handled, true
}
// enterMenuBar sends the window the SC_KEYMENU that Alt and F10 become, and
// leaves the menus from inside the menu loop, which runs the app's work.
func enterMenuBar(w *mygo.Window, _ string) (during, after, supported bool) {
hwnd := w.NativeHandle()
inLoop := make(chan bool, 1)
go func() {
time.Sleep(300 * time.Millisecond)
mygo.RunOnMain(func() {
inLoop <- win.TestMenuBarShown(hwnd)
win.TestEndMenu()
})
}()
mygo.RunOnMain(func() { supported = win.TestEnterMenuBar(hwnd) })
if !supported {
return false, false, false
}
during = <-inLoop
mygo.RunOnMain(func() { after = win.TestMenuBarShown(hwnd) })
return during, after, true
}
// openMenus opens the window's menus from the keyboard: Alt alone, or Alt
// and letter (a virtual key, such as 'A'). Their loop runs the app's work
// until closeMenus.
func openMenus(w *mygo.Window, letter byte) (supported bool) {
hwnd := w.NativeHandle()
mygo.RunOnMain(func() { supported = win.TestForeground(hwnd) })
if !supported {
return false
}
if letter == 0 {
go mygo.RunOnMain(func() { win.TestEnterMenuBar(hwnd) }) // returns once the menus close
} else {
mygo.RunOnMain(func() { win.TestPressKeys(0x12, letter) }) // VK_MENU
}
return true
}
// inMenuLoop reports whether the window runs a menu loop, which reads the
// keys typed from then on.
func inMenuLoop(w *mygo.Window) (in bool) {
mygo.RunOnMain(func() { in = win.TestInMenuLoop(w.NativeHandle()) })
return in
}
// closeMenus leaves the menus, as Escape does.
func closeMenus() { mygo.RunOnMain(win.TestEndMenu) }
// titleButtons returns the window controls of a hidden title bar, named
// after the hit-test codes over them.
func titleButtons(w *mygo.Window) (names []string, supported bool) {
mygo.RunOnMain(func() { names = win.TestCaptionButtons(w.NativeHandle()) })
return names, true
}
func pressTitleButton(w *mygo.Window, name string) (ok bool) {
mygo.RunOnMain(func() { ok = win.TestPressCaptionButton(w.NativeHandle(), name) })
return ok
}
// menuBarColors returns the colors of a window's menu bar and of the line
// below it, as 0xBBGGRR.
func menuBarColors(w *mygo.Window) (bar, line uint32, supported bool) {
mygo.RunOnMain(func() { bar, line, supported = win.TestMenuBarColors(w.NativeHandle()) })
return bar, line, supported
}
// topNonClient returns how many pixels at the top of a window are not its
// page's, and how many a hidden title bar keeps there.
func topNonClient(w *mygo.Window) (px, want int32, supported bool) {
mygo.RunOnMain(func() { px, want = win.TestTopNonClient(w.NativeHandle()) })
return px, want, true
}
// frameExtension returns how far a window's frame extends over the top and
// the bottom of its client area, -1 for all over.
func frameExtension(w *mygo.Window) (top, bottom int32) {
mygo.RunOnMain(func() { top, bottom = win.TestFrameExtension(w.NativeHandle()) })
return top, bottom
}
// titleButtonColor puts the pointer over a window control of a hidden
// title bar and returns the color on the screen beside its glyph.
func titleButtonColor(w *mygo.Window, name string) (r, g, b uint8, ok bool) {
mygo.RunOnMain(func() { r, g, b, ok = win.TestCaptionColor(w.NativeHandle(), name) })
return r, g, b, ok
}
// composition reports whether a window has no redirection bitmap, for the
// material behind its page, and whether the controls of its hidden title
// bar show through DirectComposition.
func composition(w *mygo.Window) (noRedirect, composed, supported bool) {
mygo.RunOnMain(func() { noRedirect, composed = win.TestComposed(w.NativeHandle()) })
return noRedirect, composed, true
}
// canCompose reports whether DirectComposition is available.
func canCompose() (ok bool) {
mygo.RunOnMain(func() { ok = win.TestCanCompose() })
return ok
}
// loseComposition takes the device of DirectComposition away, as a draw
// that finds it invalid does, or, with removed, as a removed GPU does.
func loseComposition(removed bool) (ok bool) {
mygo.RunOnMain(func() { ok = win.TestLoseComposition(removed) })
return ok
}
// failWebViews makes WebView2 fail to create the next n webviews.
func failWebViews(n int) bool {
mygo.RunOnMain(func() { win.TestFailWebViews(n) })
return true
}
// A Control-click is a secondary click on macOS only.
func controlClick(*mygo.Window, float64, float64) bool { return false }
func secondaryClickAsPrimary(*mygo.Window, float64, float64) bool { return false }
// composeOver does what an input method that converts typed text again
// does through IMM32: it settles the range it reconverts, then composes or
// commits.
func composeOver(w *mygo.Window, text string, caret int, commit bool, from, length int) (ok bool) {
mygo.RunOnMain(func() { ok = win.TestComposeOver(w.NativeHandle(), text, caret, commit, from, length) })
return ok
}
// inputClient returns the selection and the text around it that input
// methods get with IMR_DOCUMENTFEED, which holds no composition.
func inputClient(w *mygo.Window) (selected [2]int, document string, ok bool) {
mygo.RunOnMain(func() {
var start, length int
document, start, length, ok = win.TestDocumentFeed(w.NativeHandle())
selected = [2]int{start, length}
})
return selected, document, ok
}
func dropFiles(w *mygo.Window, x, y float64, paths []string) (over, dropped, ok bool) {
mygo.RunOnMain(func() { over, dropped = win.TestDropFiles(w.NativeHandle(), x, y, paths) })
return over, dropped, true
}
// The control types of elements in UI Automation.
const roleText, roleButton, roleCheckBox, roleTextField, roleSlider = "Text", "Button", "CheckBox", "Edit", "Slider"
// roleListItem is the role of the rows of a List.
const roleListItem = "ListItem"
func accessibility(w *mygo.Window) (nodes []accessNode, ok bool) {
mygo.RunOnMain(func() {
var list []win.TestAccessNode
list, ok = win.TestAccessibility(w.NativeHandle())
for _, n := range list {
nodes = append(nodes, accessNode{n.Role, n.Label, n.Value})
}
})
return nodes, ok
}
func accessPerform(w *mygo.Window, label, action, value string) (ok bool) {
mygo.RunOnMain(func() { ok = win.TestAccessibilityPerform(w.NativeHandle(), label, action, value) })
return ok
}
// Typing into native UI is only automated on macOS.
func clickAndType(*mygo.Window, float64, float64, string) bool { return false }
func compose(*mygo.Window, string, int, bool) bool { return false }
// Only Linux draws native UI in a GtkGLArea, nor waits to load the GPU's
// driver.
func glSurface(*mygo.Window) (string, []byte, int, int, bool) { return "", nil, 0, 0, false }
func memoryUI(*testing.T) bool { return false }
func surfaceOnScreen(*mygo.Window) ([]byte, bool) { return nil, false }
// screenColor returns the color the screen shows at (x, y), in DIPs, in a
// window showing native UI, or false when the screen cannot be read.
func screenColor(w *mygo.Window, x, y float64) (r, g, b uint8, ok bool) {
mygo.RunOnMain(func() { r, g, b, ok = win.TestSurfacePixel(w.NativeHandle(), x, y) })
return r, g, b, ok
}
// Only macOS has key-value observing.
func observe(*mygo.Window) (func(), bool) { return nil, false }
// rightClick clicks (x, y) in a window showing native UI with the
// secondary button, with the messages a mouse sends.
func rightClick(w *mygo.Window, x, y float64) (ok bool) {
mygo.RunOnMain(func() { ok = win.TestRightClickSurface(w.NativeHandle(), x, y) })
return ok
}
// popupMenus returns the labels of the items of the context menus shown.
// The modal loop of a menu runs the main thread's work.
func popupMenus() (menus [][]string, supported bool) {
mygo.RunOnMain(func() { menus = win.TestPopups() })
return menus, true
}
func choosePopupItem(label string) (ok bool) {
mygo.RunOnMain(func() { ok = win.TestChoosePopupItem(label) })
return ok
}
func popupItemEnabled(label string) (enabled, ok bool) {
mygo.RunOnMain(func() { enabled, ok = win.TestPopupItemEnabled(label) })
return enabled, ok
}
// Input methods keep the keys typed while they compose from the content
// themselves here (GTK's filtering, IMM32's VK_PROCESSKEY), which a
// composition the test makes up does not show.
func pressKey(*mygo.Window, uint16, string) bool { return false }
func pressKeyComposing(*mygo.Window, uint16, string, string, string) bool { return false }
// dragFiles drags files from another application to (x, y) of a window of
// native UI and drops them, as OLE does, waiting for the target to answer.
func dragFiles(w *mygo.Window, x, y float64, paths []string) (dropped, ok bool) {
mygo.RunOnMain(func() { dropped = win.TestDragFiles(w.NativeHandle(), x, y, paths) })
return dropped, true
}
// pressTab presses Tab, with Shift when back, on the keyboard, in the
// window brought to the front.
func pressTab(w *mygo.Window, back bool) (ok bool) {
mygo.RunOnMain(func() {
if ok = win.TestForeground(w.NativeHandle()); !ok {
return
}
if back {
win.TestPressKeys(0x10, 0x09) // VK_SHIFT, VK_TAB
} else {
win.TestPressKeys(0x09)
}
})
return ok
}
// AppKit's older accessibility API is macOS's.
func axAttribute(*mygo.Window, string, string) (string, bool, bool, bool) {
return "", false, false, false
}
// pressEscape presses Escape, as the keyboard does.
func pressEscape(*mygo.Window) bool {
mygo.RunOnMain(func() { win.TestPressKeys(0x1B) }) // VK_ESCAPE
return true
}
// Windows shows no document but the title.
func documentChrome(w *mygo.Window) (title, file string, icon, edited, supported bool) {
mygo.RunOnMain(func() { title = win.TestWindowTitle(w.NativeHandle()) })
return title, "", false, false, true
}
func sheet(*mygo.Window) ([]string, []string, bool, bool) { return nil, nil, false, false }
func endSheetButton(*mygo.Window, int) bool { return false }
func panelStyles(w *mygo.Window) (tool, topmost, owned, supported bool) {
mygo.RunOnMain(func() { tool, topmost, owned = win.TestPanelStyles(w.NativeHandle()) })
return tool, topmost, owned, true
}
// throttlingOff reports whether the page of w, or of its first web view,
// is set up to keep running while it can't be seen, and how many of the
// settings that take the platform has.
func throttlingOff(w *mygo.Window, webView bool) (off bool, settings int) {
mygo.RunOnMain(func() { off, settings = win.TestBackgroundThrottlingOff(w.NativeHandle(), webView) })
return off, settings
}
// WebView2 tells no capture.
func mockCapture(*mygo.Window) bool { return false }
// pageGestures reports whether a swipe navigates and a pinch zooms the page
// of a window, or with webView 0 or more, of its web view of that index.
func pageGestures(w *mygo.Window, webView int) (swipe, pinch, ok bool) {
mygo.RunOnMain(func() { swipe, pinch, ok = win.TestPageGestures(w.NativeHandle(), webView) })
return swipe, pinch, ok
}
// WebView2 takes touch input from Windows' pointer messages, which a test
// can't send it.
func pinchPage(*mygo.Window, int, float64, float64, ...float64) bool { return false }
// pageMenusHooked tells that the tests can right-click a page and read
// the menu it opens, through rightClickPage, pageMenu, choosePageMenuItem
// and dismissPageMenu. A menu WebView2 draws itself can't be read: the
// tests change theirs, which MyGo draws.
const pageMenusHooked = true
// rightClickPage right-clicks (x, y) in a window's page, with the
// DevTools protocol's mouse events.
func rightClickPage(w *mygo.Window, x, y float64) (ok bool) {
mygo.RunOnMain(func() { ok = win.TestRightClickPage(w.NativeHandle(), x, y) })
return ok
}
// pageMenu returns the labels of the items of the context menu MyGo
// draws over a page, "-" for separators, and whether one is shown. The
// modal loop of a menu runs the main thread's work.
func pageMenu() (labels []string, shown bool) {
mygo.RunOnMain(func() { labels, shown = win.TestPageMenu() })
return labels, shown
}
// choosePageMenuItem chooses an item of that menu by its label.
func choosePageMenuItem(label string) (ok bool) {
mygo.RunOnMain(func() { ok = win.TestChoosePageMenuItem(label) })
return ok
}
func dismissPageMenu() { mygo.RunOnMain(win.TestEndMenu) }
// takeForeground brings a window to the foreground, after Alt pressed and
// released when Windows refuses it: a process that sent the last input may
// take the foreground.
func takeForeground(w *mygo.Window) {
mygo.RunOnMain(func() {
if !win.TestForeground(w.NativeHandle()) {
win.TestPressKeys(0x12) // VK_MENU
win.TestForeground(w.NativeHandle())
}
})
}
// pressLetter presses the key of an uppercase letter, with Ctrl held when
// cmd is set, like a keyboard, in the window brought to the foreground.
func pressLetter(w *mygo.Window, letter byte, cmd bool) (ok bool) {
mygo.RunOnMain(func() {
if ok = win.TestForeground(w.NativeHandle()); !ok {
return
}
if cmd {
win.TestPressKeys(0x11, letter) // VK_CONTROL
} else {
win.TestPressKeys(letter)
}
})
return ok
}
func glassTint(*mygo.Window) (red, green, blue, alpha float64, ok bool) { return 0, 0, 0, 0, false }
func nativeGlassSupported() bool { return false }
func nativeGlass(*mygo.Window) (class string, frame [4]float64, style int, ok bool) {
return "", frame, 0, false
}
func nativeGlassTint(*mygo.Window) (red, green, blue, alpha float64) { return 0, 0, 0, 0 }
func activateApp() {}
func hitView(*mygo.Window, float64, float64) string { return "" }
// Only X servers keep a keyboard's state for the tests after a test: see
// left_behind_linux_test.go.
func keyboardState() (state string, restore func()) { return "", func() {} }
+96
View File
@@ -0,0 +1,96 @@
//go:build !js
package e2e
import (
"bytes"
"fmt"
"image/png"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/egoist/mygo"
)
// TestFileIcon draws the icons of an application, a folder and a file at
// the size asked for, and fails for a path that does not exist.
func TestFileIcon(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "notes.txt")
os.WriteFile(file, []byte("hello"), 0o644)
paths := []string{dir, file}
switch runtime.GOOS {
case "darwin":
paths = append(paths, "/System/Applications/Calculator.app")
case "windows":
paths = append(paths, filepath.Join(os.Getenv("SystemRoot"), "System32", "notepad.exe"))
case "linux":
// A desktop entry's icon is its application's, from the theme.
entry := filepath.Join(dir, "editor.desktop")
os.WriteFile(entry, []byte("[Desktop Entry]\nType=Application\nName=Editor\nExec=true\nIcon=folder\n"), 0o644)
// One whose icon the theme lacks, as Byobu's on Ubuntu, gets the
// icon of desktop entries.
missing := filepath.Join(dir, "unknown.desktop")
os.WriteFile(missing, []byte("[Desktop Entry]\nType=Application\nName=Unknown\nExec=true\nIcon=mygo-no-such-icon\n"), 0o644)
paths = append(paths, entry, missing)
}
for _, p := range paths {
for _, size := range []int{16, 64} {
data, err := mygo.Shell.FileIcon(p, size)
checkIcon(t, fmt.Sprintf("FileIcon(%q, %d)", p, size), data, err, size)
}
}
if runtime.GOOS == "linux" {
// The entry above names the icon of folders.
entry, _ := mygo.Shell.FileIcon(filepath.Join(dir, "editor.desktop"), 32)
folder, _ := mygo.Shell.FileIcon(dir, 32)
if !bytes.Equal(entry, folder) {
t.Error("a desktop entry's icon is not the one it names")
}
}
if _, err := mygo.Shell.FileIcon(filepath.Join(dir, "missing"), 32); err == nil {
t.Error("FileIcon of a missing file did not fail")
}
}
// TestTypeIcon draws the icons of file types no file has, and of a type
// no application knows, at the size asked for.
func TestTypeIcon(t *testing.T) {
for _, ext := range []string{"pdf", ".txt", "zip", "mygo-unknown", ""} {
for _, size := range []int{16, 64} {
data, err := mygo.Shell.TypeIcon(ext, size)
checkIcon(t, fmt.Sprintf("TypeIcon(%q, %d)", ext, size), data, err, size)
}
}
}
// checkIcon checks that an icon is a PNG of size by size pixels that
// draws at least an eighth of them.
func checkIcon(t *testing.T, call string, data []byte, err error, size int) {
t.Helper()
if err != nil {
t.Errorf("%s: %v", call, err)
return
}
img, err := png.Decode(bytes.NewReader(data))
if err != nil {
t.Errorf("%s: not a PNG: %v", call, err)
return
}
if b := img.Bounds(); b.Dx() != size || b.Dy() != size {
t.Errorf("%s is %dx%d", call, b.Dx(), b.Dy())
}
opaque := 0
for y := 0; y < size; y++ {
for x := 0; x < size; x++ {
if _, _, _, a := img.At(x, y).RGBA(); a > 0 {
opaque++
}
}
}
if opaque < size*size/8 {
t.Errorf("%s draws %d of %d pixels", call, opaque, size*size)
}
}
@@ -0,0 +1,72 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// TestInputRegion clicks a desktop pet: a frameless, transparent window
// over another, whose input region takes the clicks on its character and
// lets those elsewhere through to the window behind, through the X
// server's input shape, as a user's would be.
func TestInputRegion(t *testing.T) {
var behind, pet, character atomic.Int32
var drawn atomic.Int32
counted := func(n *atomic.Int32, e ui.Element) {
if e.Clicked() {
n.Add(1)
}
e.Draw(func(*ui.Painter, ui.Rect) { drawn.Add(1) })
}
back := newWindow(t, mygo.WindowOptions{Title: "Behind", X: 120, Y: 120, Width: 320, Height: 240, Content: ui.View(func(c *ui.Context) {
counted(&behind, ui.Box(c).Fill().Background(ui.RGB(240, 240, 240)))
})})
front := newWindow(t, mygo.WindowOptions{Title: "Pet", X: 120, Y: 120, Width: 320, Height: 240, Frameless: true, Transparent: true, AlwaysOnTop: true, Content: ui.View(func(c *ui.Context) {
c.Root().Background(ui.Transparent)
root := ui.Box(c).Fill()
counted(&pet, root)
root.Children(func() {
counted(&character, ui.Box(c).Absolute().Left(20).Top(30).Size(60, 50).Background(ui.RGB(220, 30, 40)))
})
})})
eventually(t, "both windows drawn", func() bool { return back.IsVisible() && front.IsVisible() && drawn.Load() >= 3 })
front.SetInputRegion([]mygo.Rectangle{{X: 20, Y: 30, Width: 60, Height: 50}})
if !click(front, 50, 50) {
t.Skip("surface click automation unavailable")
}
eventually(t, "the character clicked", func() bool { return character.Load() == 1 })
onPet := pet.Load() // the character's click, if it reaches the root too
click(front, 200, 150)
eventually(t, "the window behind clicked", func() bool { return behind.Load() == 1 })
if n := pet.Load(); n != onPet {
t.Fatalf("the pet took %d clicks off the character", n-onPet)
}
// An empty region lets all of it through, and nil none of it.
front.SetInputRegion([]mygo.Rectangle{})
click(front, 50, 50)
eventually(t, "the window behind clicked through the character", func() bool { return behind.Load() == 2 })
front.SetInputRegion(nil)
click(front, 200, 150)
eventually(t, "the pet clicked again", func() bool { return pet.Load() == onPet+1 })
if n := behind.Load(); n != 2 {
t.Fatalf("the window behind took %d clicks, want 2", n)
}
}
// TestInputRegionPage shapes the input of a window showing a page, which
// has no native UI's surface.
func TestInputRegionPage(t *testing.T) {
w := newWindow(t, mygo.WindowOptions{Title: "Page region", Width: 240, Height: 160})
eventually(t, "the window shown", w.IsVisible)
w.SetInputRegion([]mygo.Rectangle{{X: 10, Y: 10, Width: 50, Height: 40}})
w.SetIgnoreMouseEvents(true)
w.SetIgnoreMouseEvents(false)
w.SetInputRegion(nil)
}
+70
View File
@@ -0,0 +1,70 @@
//go:build !mygo_noinspector && !js
package e2e
import (
"bytes"
"image/color"
"image/png"
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// TestContentWindowInspector opens the inspector of native UI with the
// Toggle Developer Tools menu item, beside the content, and closes it.
func TestContentWindowInspector(t *testing.T) {
var frames atomic.Int32
var width atomic.Value
width.Store(float32(0))
view := func(c *ui.Context) {
frames.Add(1)
w, _ := c.Size()
width.Store(w)
ui.Box(c).Fill().Background(ui.RGB(30, 144, 255))
}
w := newWindow(t, mygo.WindowOptions{Title: "Inspector", Width: 600, Height: 400, Content: ui.View(view),
Page: mygo.PageOptions{DevTools: mygo.DevToolsEnabled}})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
full := width.Load().(float32)
menu := mygo.NewMenu([]*mygo.MenuItem{{Label: "Test", Submenu: []*mygo.MenuItem{{Role: mygo.RoleToggleDevTools}}}})
mygo.App.SetMenu(menu)
defer mygo.App.SetMenu(nil)
w.Focus()
time.Sleep(100 * time.Millisecond)
if err := activateMenu(w, "Test", "Toggle Developer Tools"); err != nil {
t.Skip("menu automation not available on this platform: ", err)
}
eventually(t, "the content beside the inspector", func() bool {
w := width.Load().(float32)
return w > 0 && w < full
})
beside := width.Load().(float32)
data, err := w.CapturePage()
if err != nil {
t.Fatal(err)
}
img, err := png.Decode(bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
s := deviceScale(w)
b := img.Bounds()
at := func(x, y float64) color.RGBA {
return color.RGBAModel.Convert(img.At(b.Min.X+int(x*s), b.Min.Y+int(y*s))).(color.RGBA)
}
if c := at(float64(beside)-20, 200); c.B < 200 || c.R > 60 {
t.Errorf("the content's background is %v", c)
}
// The panel's background, in the theme's colors, not the content's.
if c := at(float64(beside)+100, 200); c.A < 255 || c.B >= 200 && c.R <= 60 {
t.Errorf("the inspector's background is %v", c)
}
if err := activateMenu(w, "Test", "Toggle Developer Tools"); err != nil {
t.Fatal(err)
}
eventually(t, "the content filling the window again", func() bool { return width.Load().(float32) == full })
}
+69
View File
@@ -0,0 +1,69 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"sync"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/ui"
)
// TestShortcutRepeatedGTK holds a key down through XTEST, whose presses
// with no release between GTK reports with no flag of auto-repeat: the
// surface tells the repeats from the first press (keysDown).
func TestShortcutRepeatedGTK(t *testing.T) {
var mu sync.Mutex
var seen []bool
frames := make(chan struct{}, 1)
view := func(c *ui.Context) {
if c.Shortcut(0, ui.KeyUp) {
mu.Lock()
seen = append(seen, c.ShortcutRepeated())
mu.Unlock()
}
ui.Text(c, "hold Up")
select {
case frames <- struct{}{}:
default:
}
}
w := newWindow(t, mygo.WindowOptions{Title: "Key repeat", Width: 300, Height: 200, Content: ui.View(view)})
<-frames
if !click(w, 150, 100) {
t.Skip("pointer automation not available")
}
// Held, the key repeats by the X server's auto-repeat until released.
if !fake(func() bool { return linux.TestHoldKey("Up", true) }) {
t.Skip("key automation not available")
}
got := func() []bool {
mu.Lock()
defer mu.Unlock()
return append([]bool(nil), seen...)
}
eventually(t, "the key to repeat", func() bool { return len(got()) >= 3 })
fake(func() bool { return linux.TestHoldKey("Up", false) })
s := got()
if s[0] || !s[1] || !s[2] {
t.Fatalf("repeats %v, want false then true", s)
}
// The repeats still queued come before the press after the release.
pressKeys("Up")
presses := func(s []bool) int { return len(s) - countTrue(s) }
eventually(t, "a press after the release", func() bool { return presses(got()) == 2 })
if s := got(); s[len(s)-1] {
t.Fatalf("repeats %v: a press after the release came as a repeat", s)
}
}
func countTrue(s []bool) (n int) {
for _, v := range s {
if v {
n++
}
}
return n
}
@@ -0,0 +1,90 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"sync"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/ui"
)
// TestKeysByPositionGTK presses keys through XTEST, as a keyboard does, and sees
// them reach an element by position, down and up, with no name for them.
func TestKeysByPositionGTK(t *testing.T) {
type seen struct {
kind ui.InputKind
code ui.KeyCode
mods ui.Modifiers
}
var mu sync.Mutex
var got []seen
frames := make(chan struct{}, 1)
view := func(c *ui.Context) {
ui.Box(c).Grow(1).Focusable().AutoFocus().HandleInput(func(ev ui.InputEvent) bool {
if ev.Kind == ui.InputKeyDown || ev.Kind == ui.InputKeyUp {
mu.Lock()
got = append(got, seen{ev.Kind, ev.Code, ev.Mods})
mu.Unlock()
return true
}
return false
})
select {
case frames <- struct{}{}:
default:
}
}
w := newWindow(t, mygo.WindowOptions{Title: "Keys by position", Width: 300, Height: 200, Content: ui.View(view)})
<-frames
if !click(w, 150, 100) {
t.Skip("pointer automation not available")
}
for _, c := range []struct {
keysym string
code ui.KeyCode
mods ui.Modifiers // while pressed
}{
{"Super_L", ui.CodeSuperLeft, ui.Super},
{"Super_R", ui.CodeSuperRight, ui.Super},
{"Shift_L", ui.CodeShiftLeft, ui.Shift},
{"Shift_R", ui.CodeShiftRight, ui.Shift},
{"Control_R", ui.CodeControlRight, ui.Ctrl},
{"Alt_L", ui.CodeAltLeft, ui.Alt},
{"Caps_Lock", ui.CodeCapsLock, 0},
{"Scroll_Lock", ui.CodeScrollLock, 0},
{"Pause", ui.CodePause, 0},
{"KP_Add", ui.CodeNumpadAdd, 0},
} {
mu.Lock()
got = nil
mu.Unlock()
tap := func() bool {
return fake(func() bool { return linux.TestHoldKey(c.keysym, true) && linux.TestHoldKey(c.keysym, false) })
}
if !tap() {
t.Skip("key automation not available")
}
if c.keysym == "Caps_Lock" || c.keysym == "Scroll_Lock" {
// The X server outlives the test: a lock left on changes the keys
// of the tests after this one, as Caps Lock turns l into L.
t.Cleanup(func() { tap() })
}
eventually(t, c.keysym+" down and up", func() bool {
mu.Lock()
defer mu.Unlock()
return len(got) >= 2
})
mu.Lock()
down, up := got[0], got[len(got)-1]
mu.Unlock()
if down.kind != ui.InputKeyDown || down.code != c.code || down.mods != c.mods {
t.Errorf("%s pressed: %+v, want code %#x, mods %v", c.keysym, down, uint16(c.code), c.mods)
}
if up.kind != ui.InputKeyUp || up.code != c.code || up.mods != 0 {
t.Errorf("%s released: %+v, want code %#x, no mods", c.keysym, up, uint16(c.code))
}
}
}
+58
View File
@@ -0,0 +1,58 @@
//go:build linux && !android && (amd64 || arm64)
package e2e
import (
"strings"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
)
func keyboardState() (state string, restore func()) {
var k linux.TestKeyboard
var ok bool
mygo.RunOnMain(func() { k, ok = linux.TestKeyboardState() })
if !ok {
return "", func() {}
}
return k.String(), func() { mygo.RunOnMain(func() { linux.TestRestoreKeyboard(k) }) }
}
// TestLeftBehindKeyboard turns Caps Lock on and holds a key, as a test that
// forgets to undo them does: the check says so, and undoes them.
func TestLeftBehindKeyboard(t *testing.T) {
// The server has the keyboard's keys once a window showed.
w := newWindow(t, mygo.WindowOptions{Title: "Left behind", Width: 200, Height: 100})
w.Focus()
eventually(t, "the window to have the keyboard", w.IsFocused)
before, _ := keyboardState()
if before == "" {
t.Skip("key automation not available")
}
check := watchLeftBehind()
// Up first: the X server then has the layout of the keyboard XTEST
// fakes, whatever the desktop's own does with Caps Lock.
if !fake(func() bool { return linux.TestHoldKey("Up", true) }) {
t.Skip("key automation not available")
}
if !fake(func() bool { return linux.TestHoldKey("Caps_Lock", true) && linux.TestHoldKey("Caps_Lock", false) }) {
fake(func() bool { return linux.TestHoldKey("Up", false) })
t.Skip("no Caps Lock key")
}
var got []string
check(func(format string, args ...any) {
for _, a := range args {
if s, ok := a.(string); ok {
got = append(got, s)
}
}
})
if len(got) == 0 || !strings.Contains(got[0], "Caps_Lock") || !strings.Contains(got[0], "holding Up") {
t.Errorf("reported %q, want Caps Lock on and Up held", got)
}
if after, _ := keyboardState(); after != before {
t.Errorf("the keyboard is left with %s, want %s", after, before)
}
}
+48
View File
@@ -0,0 +1,48 @@
//go:build !js
package e2e
import (
"slices"
"strings"
"testing"
"github.com/egoist/mygo"
)
// watchLeftBehind notes what a package's tests share and one can change for
// those after it: the keyboard, whose lock keys outlive a window and even
// the process on an X server, and the windows open. The function it returns
// reports what changed since and puts it back, so that the test at fault
// fails, by name, rather than one that runs much later and did nothing wrong.
func watchLeftBehind() (check func(report func(format string, args ...any))) {
keyboard, restore := keyboardState()
windows := mygo.Windows()
return func(report func(format string, args ...any)) {
if now, _ := keyboardState(); now != keyboard {
report("the test left the keyboard with %s, and found it with %s: tests after it would get other keys; a test that presses a lock key or holds one lets it go in a cleanup", now, keyboard)
restore()
}
for _, w := range mygo.Windows() {
if !slices.Contains(windows, w) {
report("the test left a window open, titled %q: it can take the keyboard from the tests after it", w.Title())
w.Destroy()
}
}
}
}
// TestLeftBehindWindow leaves a window open: the check says so and closes it.
func TestLeftBehindWindow(t *testing.T) {
check := watchLeftBehind()
w := mygo.NewWindow(mygo.WindowOptions{Title: "Left open", Hidden: true})
var got []string
check(func(format string, args ...any) { got = append(got, format) })
if len(got) != 1 || !strings.Contains(got[0], "window") {
t.Errorf("reported %q, want the window", got)
}
if !w.IsDestroyed() {
t.Error("the window is still open")
w.Destroy()
}
}
+115
View File
@@ -0,0 +1,115 @@
//go:build !js
package e2e
import (
"bytes"
"os/exec"
"runtime"
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// localeLanguages makes the app written in langs for a test, following
// the user's languages again after it.
func localeLanguages(t *testing.T, langs ...string) {
t.Helper()
mygo.App.SetLanguages(langs...)
t.Cleanup(func() {
mygo.App.SetLocale("")
mygo.App.SetLanguages()
})
}
// localePage records the language the bridge has as the page starts, and
// what its listeners hear of mygo:locale.
const localePage = `<!doctype html><p>locale</p><script>
window.started = mygo.locale + " " + mygo.dir;
window.heard = [];
mygo.on("mygo:locale", (p) => window.heard.push(p.locale + " " + p.dir));
</script>`
// TestLocaleAtDocumentStart checks, in a real web view, that a page loaded
// after App.SetLocale starts in the new language, and that its listeners
// hear of a language the page did not have only, not as it loads.
func TestLocaleAtDocumentStart(t *testing.T) {
localeLanguages(t, "en", "ar", "ja")
// SetLanguages queues its update. Choose the initial language on the
// main thread after it, rather than reading the previous locale or
// assuming the user's preferred language is written left to right.
mygo.RunOnMain(func() { mygo.App.SetLocale("en") })
w := newWindow(t, mygo.WindowOptions{Hidden: true})
w.Page().LoadHTML(localePage, "app://localhost/")
waitFor(t, w, `window.started === "en ltr"`)
mygo.App.SetLocale("ar")
waitFor(t, w, `mygo.locale === "ar" && mygo.dir === "rtl" && window.heard.join() === "ar rtl"`)
if v, err := w.Page().Eval("navigator.languages.join()"); err == nil {
t.Logf("the page's languages: %v", v)
}
w.Page().Reload()
waitFor(t, w, `window.started === "ar rtl" && document.readyState === "complete"`)
// Go tells a loading page the language again, which it has.
time.Sleep(300 * time.Millisecond)
waitFor(t, w, `window.heard.length === 0`)
mygo.App.SetLocale("ja")
waitFor(t, w, `window.heard.join() === "ja ltr"`)
// Another page, in a new window, starts in it too.
w2 := newWindow(t, mygo.WindowOptions{Hidden: true})
w2.Page().LoadHTML(localePage, "app://localhost/")
waitFor(t, w2, `window.started === "ja ltr"`)
}
// TestTextLanguage checks that native UI draws text in the language the
// app shows, which an element's Lang overrides: 直 and 骨 are drawn apart
// in Japanese and in Chinese.
func TestTextLanguage(t *testing.T) {
if runtime.GOOS == "linux" && (!hasFonts("ja") || !hasFonts("zh-cn")) {
t.Skip("fontconfig has no Japanese or Chinese fonts (fonts-noto-cjk)")
}
localeLanguages(t, "en", "ja", "zh-Hans")
var seen atomic.Value
var override atomic.Value
override.Store("")
view := func(c *ui.Context) {
seen.Store(c.Locale())
ui.Text(c, "直骨").FontSize(48).Lang(override.Load().(string))
}
w := newWindow(t, mygo.WindowOptions{Title: "Text language", Width: 200, Height: 100, Content: ui.View(view)})
capture := func(locale, lang string) []byte {
t.Helper()
override.Store(lang)
mygo.App.SetLocale(locale)
eventually(t, "the view in "+locale, func() bool { return seen.Load() == locale })
w.Update(func() {})
time.Sleep(100 * time.Millisecond)
data, err := w.CapturePage()
if err != nil {
t.Fatal(err)
}
return data
}
ja, hans := capture("ja", ""), capture("zh-Hans", "")
if bytes.Equal(ja, hans) {
t.Fatal("直骨 looks the same in Japanese and in Chinese")
}
// A Japanese quote in a Chinese app, and the other way round.
if got := capture("zh-Hans", "ja"); !bytes.Equal(got, ja) {
t.Error("Lang(ja) in a Chinese app draws other glyphs than Japanese")
}
if got := capture("ja", "zh-Hans"); !bytes.Equal(got, hans) {
t.Error("Lang(zh-Hans) in a Japanese app draws other glyphs than Chinese")
}
}
// hasFonts reports whether fontconfig has fonts for a language.
func hasFonts(lang string) bool {
out, err := exec.Command("fc-list", ":lang="+lang, "family").Output()
return err == nil && len(bytes.TrimSpace(out)) > 0
}
@@ -0,0 +1,33 @@
//go:build windows && (amd64 || arm64)
package e2e
import (
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// A window with a material and the system's title bar extends its frame all
// over while restored, and from the bottom while maximized: a frame extended
// all over has DWM draw the caption buttons of a maximized window past its
// title bar, under the translucent content.
func TestContentWindowMaximizedMaterialFrame(t *testing.T) {
w := newWindow(t, mygo.WindowOptions{X: 80, Y: 80, Width: 480, Height: 320, Vibrancy: mygo.VibrancyMica,
Content: ui.View(func(c *ui.Context) { ui.Text(c, "native") })})
allOver := func() bool {
top, _ := frameExtension(w)
return top == -1
}
if !allOver() {
t.Error("a restored window doesn't extend its frame all over")
}
w.Maximize()
eventually(t, "the frame extended from the bottom", func() bool {
top, bottom := frameExtension(w)
return top == 0 && bottom > 0
})
w.Unmaximize()
eventually(t, "the frame extended all over", allOver)
}
@@ -0,0 +1,43 @@
//go:build windows
package e2e
import (
"testing"
"github.com/egoist/mygo"
win "github.com/egoist/mygo/internal/windows"
"github.com/egoist/mygo/ui"
)
// The maximize button a view draws, in a window without the system's
// buttons, answers Windows' hit test as the system's does, which brings
// the snap layouts, and still clicks as the view's own button.
func TestViewMaximizeButton(t *testing.T) {
clicks := 0
w := newWindow(t, mygo.WindowOptions{X: 80, Y: 80, Width: 400, Height: 240,
TitleBarStyle: mygo.TitleBarHidden, HideWindowButtons: true,
Content: ui.View(func(c *ui.Context) {
ui.Row(c).Fill().Children(func() {
ui.Spacer(c)
b := ui.ButtonBase(c.Key("max")).Size(40, 30).Label("Maximize").MaximizeButton()
if b.Clicked() {
clicks++
}
})
})})
at := func(press bool) (hit uintptr) {
mygo.RunOnMain(func() { hit = win.TestMaximizeButton(w.NativeHandle(), press) })
return hit
}
const htMaxButton = 9
eventually(t, "a window over the view's maximize button", func() bool { return at(false) == htMaxButton })
if hit := at(true); hit != htMaxButton {
t.Fatalf("hit test = %d, want HTMAXBUTTON", hit)
}
eventually(t, "the press to click the view's button", func() bool {
var n int
mygo.RunOnMain(func() { n = clicks })
return n == 1
})
}
+99
View File
@@ -0,0 +1,99 @@
//go:build windows
package e2e
import (
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
win "github.com/egoist/mygo/internal/windows"
)
// Alt alone, or held with Control or Shift, keeps a popup menu MyGo shows
// open, as it keeps open the menus of Windows 11 itself, WinUI's flyouts:
// the keyboard still reaches the menu afterwards to choose an item, which it
// couldn't were the menu gone.
func TestPageMenuKeepsOpenOnAlt(t *testing.T) {
if !pageMenusHooked {
t.Skip("right-clicking a page is not hooked here")
}
w := newWindow(t, mygo.WindowOptions{Title: "Alt menu", Width: 400, Height: 300})
w.Page().LoadHTML(contextMenuPage, "")
waitFor(t, w, "document.readyState === 'complete' && window.mygo")
chosen := make(chan struct{}, 1)
off := w.Page().OnContextMenu(func(e *mygo.ContextMenuEvent) {
// The web view's items gone, one of MyGo's own left: the keyboard's
// first Down and Return reach it.
for _, it := range e.Menu.Items() {
if it.ID != "" {
e.Menu.Remove(it.ID)
}
}
e.Menu.Append(&mygo.MenuItem{Label: "Choose", Click: func(*mygo.MenuItem, *mygo.Window) {
chosen <- struct{}{}
}})
})
defer off()
for _, c := range []struct {
name string
keys []byte
}{
{"Alt", []byte{0x12}}, // VK_MENU
{"Control then Alt", []byte{0x11, 0x12}}, // VK_CONTROL, which Windows takes for AltGr
{"Shift then Alt", []byte{0x10, 0x12}}, // VK_SHIFT
} {
// The keyboard types in the window in front.
front := false
mygo.RunOnMain(func() { front = win.TestForeground(w.NativeHandle()) })
if !front {
t.Skip("the window cannot come to the front, where the keyboard types")
}
if !rightClickPage(w, 20, 20) {
t.Fatalf("%s: right-clicking the page failed", c.name)
}
wait.Until(t, c.name+": the menu shown", func() bool { _, shown := pageMenu(); return shown })
keys := c.keys
mygo.RunOnMain(func() { win.TestPressKeys(keys...) })
// The menu's own keys, after theirs: they reach it only if it
// stayed open, as Windows 11's menus do.
mygo.RunOnMain(func() { win.TestPressKeys(0x28, 0x0D) }) // VK_DOWN, VK_RETURN
select {
case <-chosen:
case <-time.After(wait.Guard):
if _, shown := pageMenu(); shown {
t.Fatalf("%s: the menu stayed, and every key missed it", c.name)
}
t.Fatalf("%s: the menu left: the keyboard never chose its item", c.name)
}
wait.Until(t, c.name+": the menu closed", func() bool { _, shown := pageMenu(); return !shown })
}
}
// Alt alone leaves the menus of a window's own menu bar, as Win32 has them
// leave: MyGo keeps it open only in the popups it shows itself, not in the
// dropdowns Windows opens from the bar.
func TestMenuBarClosesOnAlt(t *testing.T) {
prev := mygo.App.Menu()
defer mygo.App.SetMenu(prev)
mygo.App.SetMenu(mygo.NewMenu([]*mygo.MenuItem{{Label: "App", Submenu: []*mygo.MenuItem{{Label: "Item"}}}}))
w := newWindow(t, mygo.WindowOptions{Title: "Alt in the bar", Width: 400, Height: 300})
eventually(t, "the menu bar on the window", func() bool { shown, _ := menuBarShown(w); return shown })
if !openMenus(w, 0) {
t.Skip("the window cannot come to the front, where the keyboard types")
}
// openMenus enters the bar from another goroutine: a key typed before
// its loop starts goes to the window, or to its page, not to the bar.
eventually(t, "the keyboard in the menu bar", func() bool { return inMenuLoop(w) })
// A Down in the bar opens its first menu, a menu of Windows'. The page,
// another process's window, would read some of the keys typed in the
// menus, had the bar not taken the keyboard from it.
mygo.RunOnMain(func() { win.TestPressKeys(0x28) }) // VK_DOWN
eventually(t, "the first menu of the bar open", func() bool { menus, _ := popupMenus(); return len(menus) > 0 })
mygo.RunOnMain(func() { win.TestPressKeys(0x12) }) // VK_MENU
eventually(t, "Alt to close the menu of the bar", func() bool { menus, _ := popupMenus(); return len(menus) == 0 })
closeMenus()
}
+80
View File
@@ -0,0 +1,80 @@
//go:build linux && !android && (amd64 || arm64) && !android
package e2e
import (
"image/color"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/linux"
"github.com/egoist/mygo/ui"
)
// Menu items show icons beside their labels, with their checks, and change
// them in place: replaced, removed, given one.
func TestMenuIconsLinux(t *testing.T) {
japan := menuIcon(t, 48, 32, color.NRGBA{255, 0, 0, 255}) // 3:2, as flags
square := menuIcon(t, 64, 64, color.NRGBA{0, 0, 255, 255})
var chosen string
click := func(it *mygo.MenuItem, _ *mygo.Window) { chosen = it.ID }
menu := mygo.NewMenu([]*mygo.MenuItem{
{Label: "Servers", Icon: japan, Submenu: []*mygo.MenuItem{
{ID: "tokyo", Label: "Tokyo", Type: mygo.MenuItemRadio, Checked: true, Icon: japan, Click: click},
{ID: "ny", Label: "New York", Type: mygo.MenuItemRadio, Icon: square, Click: click},
{ID: "direct", Label: "Direct", Type: mygo.MenuItemRadio, Click: click},
}},
})
w := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, Content: ui.View(func(c *ui.Context) { ui.Text(c, "menus") })})
w.SetMenu(menu)
type state struct {
w, h int
checked bool
}
at := func(path ...string) (s state) {
var err error
mygo.RunOnMain(func() { s.w, s.h, s.checked, err = linux.TestMenuItemIcon(w.NativeHandle(), path...) })
if err != nil {
t.Fatal(err)
}
return s
}
want := func(what string, got, want state) {
t.Helper()
if got != want {
t.Errorf("%s = %+v, want %+v", what, got, want)
}
}
want("Tokyo", at("Servers", "Tokyo"), state{16, 11, true})
want("New York", at("Servers", "New York"), state{16, 16, false})
want("Direct", at("Servers", "Direct"), state{0, 0, false})
want("the menu bar's item", at("Servers"), state{0, 0, false})
menu.ItemByID("direct").SetIcon(square)
eventually(t, "Direct to get an icon", func() bool { return at("Servers", "Direct") == state{16, 16, false} })
menu.ItemByID("tokyo").SetIcon(nil)
eventually(t, "Tokyo to lose its icon", func() bool { return at("Servers", "Tokyo") == state{0, 0, true} })
menu.ItemByID("tokyo").SetIcon(square)
eventually(t, "Tokyo to get an icon again", func() bool { return at("Servers", "Tokyo") == state{16, 16, true} })
menu.ItemByID("ny").SetIcon(japan)
menu.ItemByID("ny").SetLabel("Osaka")
eventually(t, "New York to become Osaka", func() bool {
var err error
mygo.RunOnMain(func() { _, _, _, err = linux.TestMenuItemIcon(w.NativeHandle(), "Servers", "Osaka") })
return err == nil
})
want("Osaka", at("Servers", "Osaka"), state{16, 11, false})
// The item with an icon is chosen as any other, its check following.
if err := activateMenu(w, "Servers", "Osaka"); err != nil {
t.Fatal(err)
}
eventually(t, "Osaka to be chosen", func() bool {
var c string
mygo.RunOnMain(func() { c = chosen })
return c == "ny"
})
eventually(t, "Osaka checked, Tokyo not", func() bool {
return at("Servers", "Osaka").checked && !at("Servers", "Tokyo").checked
})
}
+29
View File
@@ -0,0 +1,29 @@
package e2e
import (
"bytes"
"image"
"image/color"
"image/png"
"testing"
"github.com/egoist/mygo"
)
// menuIcon makes a menu icon of w by h pixels in one color.
func menuIcon(t *testing.T, w, h int, c color.NRGBA) *mygo.MenuIcon {
t.Helper()
img := image.NewNRGBA(image.Rect(0, 0, w, h))
for i := 0; i < len(img.Pix); i += 4 {
img.Pix[i], img.Pix[i+1], img.Pix[i+2], img.Pix[i+3] = c.R, c.G, c.B, c.A
}
var b bytes.Buffer
if err := png.Encode(&b, img); err != nil {
t.Fatal(err)
}
ic, err := mygo.NewMenuIcon(b.Bytes(), false)
if err != nil {
t.Fatal(err)
}
return ic
}
@@ -0,0 +1,82 @@
//go:build windows && (amd64 || arm64)
package e2e
import (
"image/color"
"testing"
"github.com/egoist/mygo"
win "github.com/egoist/mygo/internal/windows"
"github.com/egoist/mygo/ui"
)
// Menu items show icons beside their labels, with their checks, change
// them in place, and free their bitmaps (Windows 10's) as they do and as
// their menus go.
func TestMenuIconsWindows(t *testing.T) {
japan := menuIcon(t, 48, 32, color.NRGBA{255, 0, 0, 255}) // 3:2, as flags
square := menuIcon(t, 64, 64, color.NRGBA{0, 0, 255, 128})
menu := mygo.NewMenu([]*mygo.MenuItem{
{Label: "Servers", Icon: japan, Submenu: []*mygo.MenuItem{
{ID: "tokyo", Label: "Tokyo", Type: mygo.MenuItemRadio, Checked: true, Icon: japan},
{ID: "ny", Label: "New York", Type: mygo.MenuItemRadio, Icon: square},
{ID: "direct", Label: "Direct", Type: mygo.MenuItemRadio},
}},
})
w := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, Content: ui.View(func(c *ui.Context) { ui.Text(c, "menus") })})
w.SetMenu(menu)
type state struct {
w, h int
checked bool
}
at := func(path ...string) (s state) {
var err error
mygo.RunOnMain(func() { s.w, s.h, s.checked, err = win.TestMenuItemIcon(w.NativeHandle(), path...) })
if err != nil {
t.Fatal(err)
}
return s
}
want := func(what string, got, want state) {
t.Helper()
if got != want {
t.Errorf("%s = %+v, want %+v", what, got, want)
}
}
want("Tokyo", at("Servers", "Tokyo"), state{16, 11, true})
want("New York", at("Servers", "New York"), state{16, 16, false})
want("Direct", at("Servers", "Direct"), state{0, 0, false})
menu.ItemByID("direct").SetIcon(square)
eventually(t, "Direct to get an icon", func() bool { return at("Servers", "Direct") == state{16, 16, false} })
menu.ItemByID("tokyo").SetIcon(nil)
eventually(t, "Tokyo to lose its icon", func() bool { return at("Servers", "Tokyo") == state{0, 0, true} })
menu.ItemByID("ny").SetChecked(true)
eventually(t, "New York checked with its icon", func() bool {
return at("Servers", "New York") == state{16, 16, true} && !at("Servers", "Tokyo").checked
})
// Replacing icons and building the menu again leaves no bitmaps behind.
var before int
mygo.RunOnMain(func() { before = win.TestGDIObjects() })
for i := range 200 {
ic := japan
if i%2 == 1 {
ic = square
}
for _, id := range []string{"tokyo", "ny", "direct"} {
menu.ItemByID(id).SetIcon(ic)
}
if i%10 == 0 {
w.SetMenu(menu)
}
}
w.SetMenu(menu)
eventually(t, "the last icons", func() bool { return at("Servers", "Tokyo") == state{16, 16, false} })
var after int
mygo.RunOnMain(func() { after = win.TestGDIObjects() })
if after > before+8 {
t.Errorf("GDI objects went from %d to %d over 600 replaced icons", before, after)
}
}
@@ -0,0 +1,102 @@
//go:build linux && !android
package e2e
import (
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// The shortcuts of the app's menu items work in a window of native UI:
// before the content, which gets the rest. The roles' keys, as Edit ›
// Copy's Ctrl+C, go to the content first, as a terminal's Ctrl+C.
func TestNativeMenuShortcutsLinux(t *testing.T) {
var settings, split, copied, typed int
prev := mygo.App.Menu()
defer mygo.App.SetMenu(prev)
mygo.App.SetMenu(mygo.NewMenu([]*mygo.MenuItem{
{Label: "App", Submenu: []*mygo.MenuItem{
{Label: "Settings", Accelerator: "Ctrl+,", Click: func(*mygo.MenuItem, *mygo.Window) { settings++ }},
{Label: "Split", Accelerator: "Alt+Shift+=", Click: func(*mygo.MenuItem, *mygo.Window) { split++ }},
}},
{Role: mygo.RoleEditMenu},
}))
w := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, Content: ui.View(func(c *ui.Context) {
c.OnShortcut(ui.Ctrl, ui.KeyC, func() { copied++ })
c.OnShortcut(ui.Ctrl, ui.KeyComma, func() { typed++ })
ui.Text(c, "shortcuts")
})})
// A click gives the window the keyboard, which needs no window manager.
if !click(w, 50, 50) {
t.Skip("click automation unavailable")
}
counts := func() (s, p, c, ty int) {
mygo.RunOnMain(func() { s, p, c, ty = settings, split, copied, typed })
return
}
if !pressKeys("Control_L", "comma") {
t.Skip("no X server to press keys with")
}
eventually(t, "Ctrl+, to run Settings", func() bool { s, _, _, _ := counts(); return s == 1 })
pressKeys("Alt_L", "Shift_L", "equal")
eventually(t, "Alt+Shift+= to run Split", func() bool { _, p, _, _ := counts(); return p == 1 })
pressKeys("Control_L", "c")
eventually(t, "the content's Ctrl+C", func() bool { _, _, c, _ := counts(); return c == 1 })
if _, _, _, ty := counts(); ty != 0 {
t.Errorf("Ctrl+, reached the content %d times", ty)
}
}
// An edit role's item, made insensitive when its menu opened with nothing
// of the native UI to act on, takes its shortcut again in a page of the
// window: GTK drops the shortcut of an insensitive item.
func TestWebViewEditShortcutLinux(t *testing.T) {
prev := mygo.App.Menu()
defer mygo.App.SetMenu(prev)
mygo.App.SetMenu(mygo.NewMenu([]*mygo.MenuItem{{Label: "Edit", Submenu: []*mygo.MenuItem{
{Role: mygo.RoleSelectAll, Accelerator: "Ctrl+Shift+Y"},
}}}))
var view *mygo.WebView
var frames atomic.Int32
w := newWindow(t, mygo.WindowOptions{Width: 400, Height: 300, Content: ui.View(func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Fill().AlignItems(ui.Stretch).Children(func() {
ui.Text(c, "native")
if view != nil {
ui.WebView(c, view).Grow(1)
}
})
})})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
v, err := w.NewWebView(mygo.WebViewOptions{})
if err != nil {
t.Fatal(err)
}
w.Update(func() { view = v })
v.Page().LoadHTML(`<textarea id=t>MyGo</textarea><script>window.ready = true</script>`, "")
waitForPage(t, v.Page(), "window.ready")
if !click(w, 20, 8) {
t.Skip("click automation unavailable")
}
if on, err := menuItemEnabled(w, "Edit", "Select All"); err != nil || on {
t.Fatalf("nothing focused: Edit > Select All enabled = %v (%v), want false", on, err)
}
if !pressKeys("Tab") {
t.Skip("no X server to press keys with")
}
eventually(t, "Tab into the page", func() bool {
id, _ := mygo.EvalAs[string](v.Page(), "document.hasFocus() && document.activeElement ? document.activeElement.id : ''")
return id == "t"
})
if _, err := v.Page().Eval("document.getElementById('t').setSelectionRange(0, 0)"); err != nil {
t.Fatal(err)
}
pressKeys("Control_L", "Shift_L", "y")
eventually(t, "Ctrl+Shift+Y to select the page's text", func() bool {
n, _ := mygo.EvalAs[int](v.Page(), "document.getElementById('t').selectionEnd - document.getElementById('t').selectionStart")
return n == 4
})
}
@@ -0,0 +1,167 @@
//go:build windows
package e2e
import (
"strings"
"testing"
"time"
"github.com/egoist/mygo"
win "github.com/egoist/mygo/internal/windows"
"github.com/egoist/mygo/transfer"
"github.com/egoist/mygo/ui"
)
// The shortcuts of the app's menu items work in a window of native UI, as
// in a page: before the content, which gets the rest. The roles' keys, as
// Edit › Copy's Ctrl+C, go to the content first, as a terminal's Ctrl+C.
func TestNativeMenuShortcuts(t *testing.T) {
var settings, split, copied, typed int
prev := mygo.App.Menu()
defer mygo.App.SetMenu(prev)
mygo.App.SetMenu(mygo.NewMenu([]*mygo.MenuItem{
{Label: "App", Submenu: []*mygo.MenuItem{
{Label: "Settings", Accelerator: "Ctrl+,", Click: func(*mygo.MenuItem, *mygo.Window) { settings++ }},
{Label: "Split", Accelerator: "Alt+Shift+=", Click: func(*mygo.MenuItem, *mygo.Window) { split++ }},
}},
{Role: mygo.RoleEditMenu},
}))
w := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, Content: ui.View(func(c *ui.Context) {
c.OnShortcut(ui.Ctrl, ui.KeyC, func() { copied++ })
c.OnShortcut(ui.Ctrl, ui.KeyComma, func() { typed++ })
ui.Text(c, "shortcuts")
})})
const vkControl, vkShift, vkMenu, vkComma, vkEqual = 0x11, 0x10, 0x12, 0xBC, 0xBB
key := func(vk byte, mods ...byte) {
t.Helper()
var ok bool
mygo.RunOnMain(func() { ok = win.TestSurfaceKey(w.NativeHandle(), vk, mods...) })
if !ok {
t.Fatal("no window of native UI to press keys in")
}
}
counts := func() (s, p, c, ty int) {
mygo.RunOnMain(func() { s, p, c, ty = settings, split, copied, typed })
return
}
key(vkComma, vkControl)
key(vkEqual, vkMenu, vkShift)
key('C', vkControl)
eventually(t, "the content's Ctrl+C", func() bool { _, _, c, _ := counts(); return c == 1 })
if s, p, _, ty := counts(); s != 1 || p != 1 || ty != 0 {
t.Errorf("Ctrl+, ran Settings %d times and reached the content %d, Alt+Shift+= ran Split %d times; want once, never, once", s, ty, p)
}
}
// In a page, the edit roles' keys are the page's, as in a browser and as in
// native UI: WebView2 pastes with the page's own paste event and every
// format of the clipboard.
func TestPageEditKeys(t *testing.T) {
prev := mygo.App.Menu()
defer mygo.App.SetMenu(prev)
mygo.App.SetMenu(mygo.NewMenu([]*mygo.MenuItem{{Role: mygo.RoleEditMenu}}))
w := newWindow(t, mygo.WindowOptions{Width: 400, Height: 300})
w.Page().LoadHTML(`<textarea id=t></textarea><script>
addEventListener("paste", (e) => { window.pasted = e.clipboardData.types.join(" ") })
</script>`, "")
waitFor(t, w, "document.getElementById('t') !== null")
if err := mygo.Clipboard.Write(transfer.New(transfer.NewItem(
transfer.Bytes(transfer.Text, []byte("MyGo")), transfer.Bytes(transfer.HTML, []byte("<b>MyGo</b>"))))); err != nil {
t.Fatal(err)
}
var front bool
mygo.RunOnMain(func() { front = win.TestForeground(w.NativeHandle()) })
if !front {
t.Fatal("the window did not come to the front")
}
if _, err := w.Page().Eval("document.getElementById('t').focus()"); err != nil {
t.Fatal(err)
}
mygo.RunOnMain(func() { win.TestPressKeys(0x11, 'V') }) // VK_CONTROL
waitFor(t, w, "window.pasted !== undefined")
if types, _ := mygo.EvalAs[string](w.Page(), "window.pasted"); !strings.Contains(types, "text/html") {
t.Errorf("the page's paste had %q, want text/html among them", types)
}
}
// Activating Edit › Paste gives the page the clipboard's formats and lets
// the browser insert the text. Paste and Match Style still types only text.
func TestPageMenuPaste(t *testing.T) {
prev := mygo.App.Menu()
defer mygo.App.SetMenu(prev)
mygo.App.SetMenu(mygo.NewMenu([]*mygo.MenuItem{{Role: mygo.RoleEditMenu}}))
w := newWindow(t, mygo.WindowOptions{Width: 400, Height: 300})
w.Page().LoadHTML(`<textarea id=t></textarea><script>
window.pastes = [];
window.keys = [];
addEventListener("paste", (e) => {
pastes.push({types: Array.from(e.clipboardData.types), html: e.clipboardData.getData("text/html")});
});
for (const type of ["keydown", "keyup"]) {
addEventListener(type, (e) => { keys.push({type, key: e.key, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey, meta: e.metaKey}) });
}
</script>`, "")
waitFor(t, w, "document.getElementById('t') !== null")
if err := mygo.Clipboard.Write(transfer.New(transfer.NewItem(
transfer.Bytes(transfer.Text, []byte("MyGo")), transfer.Bytes(transfer.HTML, []byte("<b>MyGo</b>"))))); err != nil {
t.Fatal(err)
}
var front bool
mygo.RunOnMain(func() { front = win.TestForeground(w.NativeHandle()) })
if !front {
t.Fatal("the window did not come to the front")
}
if _, err := w.Page().Eval("document.getElementById('t').focus()"); err != nil {
t.Fatal(err)
}
var err error
mygo.RunOnMain(func() { err = win.TestActivateMenuItem(w.NativeHandle(), "Edit", "Paste") })
if err != nil {
t.Fatal(err)
}
waitFor(t, w, "document.getElementById('t').value === 'MyGo'")
if ok, err := mygo.EvalAs[bool](w.Page(), `pastes.length === 1 && pastes[0].types.includes("text/html") && pastes[0].html.includes("<b>MyGo</b>")`); err != nil || !ok {
pastes, _ := w.Page().Eval("JSON.stringify(pastes)")
t.Fatalf("the page's paste events were %v, want one with the clipboard's HTML: %v", pastes, err)
}
waitFor(t, w, `keys.some(e => e.type === "keyup" && e.key === "Unidentified")`)
if ok, err := mygo.EvalAs[bool](w.Page(), `keys.filter(e => e.key === "Unidentified").length === 2 && !keys.some(e => e.key === "Unidentified" && (e.ctrl || e.alt || e.shift || e.meta))`); err != nil || !ok {
t.Errorf("menu paste did not send a pair of keys without modifiers: %v", err)
}
if _, err := w.Page().Eval("document.getElementById('t').value = ''; window.pastes = []"); err != nil {
t.Fatal(err)
}
var handled bool
mygo.RunOnMain(func() { handled = win.TestEditRole(w.NativeHandle(), "pasteAndMatchStyle") })
if !handled {
t.Fatal("Paste and Match Style was not handled")
}
waitFor(t, w, "document.getElementById('t').value === 'MyGo'")
if count, err := mygo.EvalAs[int](w.Page(), "pastes.length"); err != nil || count != 0 {
t.Errorf("Paste and Match Style fired %d paste events, want none: %v", count, err)
}
}
// Ctrl+V in a text field pastes once: the field takes the key, and Edit ›
// Paste, whose key it is too, leaves it.
func TestNativeFieldPastesOnce(t *testing.T) {
prev := mygo.App.Menu()
defer mygo.App.SetMenu(prev)
mygo.App.SetMenu(mygo.NewMenu([]*mygo.MenuItem{{Role: mygo.RoleEditMenu}}))
mygo.RunOnMain(func() { mygo.Clipboard.WriteText("host.ts.net") })
var value string
w := newWindow(t, mygo.WindowOptions{Width: 300, Height: 200, Content: ui.View(func(c *ui.Context) {
ui.TextInput(c, &value).AutoFocus()
})})
read := func() (v string) { mygo.RunOnMain(func() { v = value }); return }
time.Sleep(500 * time.Millisecond) // the field shows and takes the focus
const vkControl = 0x11
mygo.RunOnMain(func() { win.TestSurfaceKey(w.NativeHandle(), 'V', vkControl) })
eventually(t, "the paste", func() bool { return read() != "" })
time.Sleep(300 * time.Millisecond)
if got := read(); got != "host.ts.net" {
t.Errorf("after Ctrl+V the field has %q, want %q", got, "host.ts.net")
}
}
@@ -0,0 +1,41 @@
//go:build darwin && !ios
package e2e
import (
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/darwin"
)
// A menu item shows its subtitle on a line of its own from macOS 14, else
// after its title, and loses it as it changes.
func TestMenuItemSubtitle(t *testing.T) {
prev := mygo.App.Menu()
defer mygo.App.SetMenu(prev)
menu := mygo.NewMenu([]*mygo.MenuItem{{Label: "App", Submenu: []*mygo.MenuItem{
{ID: "code", Label: "123456", Subtitle: "GitHub"},
}}})
mygo.App.SetMenu(menu)
look := func(path ...string) (title, subtitle string, err error) {
mygo.RunOnMain(func() { title, subtitle, err = darwin.TestMenuItemSubtitle(path...) })
return title, subtitle, err
}
var title, subtitle string
eventually(t, "the item in the menu", func() bool {
var err error
if title, subtitle, err = look("App", "123456"); err != nil {
title, subtitle, err = look("App", "123456 — GitHub")
}
return err == nil
})
if !(title == "123456" && subtitle == "GitHub" || title == "123456 — GitHub" && subtitle == "") {
t.Errorf("title %q, subtitle %q", title, subtitle)
}
menu.ItemByID("code").SetSubtitle("")
eventually(t, "the item without its subtitle", func() bool {
title, subtitle, err := look("App", "123456")
return err == nil && title == "123456" && subtitle == ""
})
}
@@ -0,0 +1,65 @@
//go:build windows && (amd64 || arm64)
package e2e
import (
"sync/atomic"
"testing"
"github.com/egoist/mygo"
win "github.com/egoist/mygo/internal/windows"
"github.com/egoist/mygo/ui"
)
// The items MyGo draws of a context menu are as wide as they need, at the
// window's DPI, with long labels, checks, shortcuts and submenus: Windows
// widens them by as much as it doesn't tell (#922). The first menu may be
// wider than it needs; the next, measured knowing that, are no wider.
func TestContextMenuItemWidths(t *testing.T) {
var frames atomic.Int32
view := func(c *ui.Context) {
frames.Add(1)
ui.Box(c).Fill().ContextMenu(func(m *ui.Menu) {
m.Item("复制歌名和歌手")
m.Separator()
m.Item("查看歌手:房东的猫")
m.Item("查看专辑:云烟成雨")
m.Item("Show the artist: The Landlord's Cat").Checked(true)
m.Item("Copy the song's name").Shortcut(ui.Ctrl|ui.Shift, ui.KeyC)
m.Submenu("添加到歌单", func(m *ui.Menu) {
m.Item("日常")
})
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Menu widths", Width: 400, Height: 300, Content: ui.View(view)})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
for _, pass := range []string{"the first menu", "the next"} {
if !rightClick(w, 100, 50) {
t.Fatalf("%s: right-clicking failed", pass)
}
eventually(t, pass+" to show", func() bool { menus, _ := popupMenus(); return len(menus) == 1 })
// The menu shows; the next waits for Windows' widening learned
// from its items drawn.
var items []win.PopupItemWidth
eventually(t, pass+" to draw", func() bool {
var known bool
mygo.RunOnMain(func() { items, known = win.TestPopupItemWidths(w.NativeHandle()) })
return known || len(items) == 0
})
closeMenus()
eventually(t, pass+" to close", func() bool { menus, _ := popupMenus(); return len(menus) == 0 })
if len(items) == 0 {
t.Skip("Windows draws the items of menus here")
}
var needs int32
for _, it := range items {
if it.Shown < it.Needs {
t.Errorf("%s: %q shows %d pixels wide, needs %d", pass, it.Label, it.Shown, it.Needs)
}
needs = max(needs, it.Needs)
}
if pass == "the next" && items[0].Shown != needs {
t.Errorf("%s: the items show %d pixels wide, the widest needs %d", pass, items[0].Shown, needs)
}
}
}
+25
View File
@@ -0,0 +1,25 @@
package e2e
import (
"testing"
"time"
"github.com/egoist/mygo"
)
// TestNetwork reads the network status through the real backend. The
// computers that run the tests are online (they downloaded the module), so
// the first Status, which starts the monitor on macOS and waits for its
// first path, says so. Changes are covered through internal/fake.
func TestNetwork(t *testing.T) {
start := time.Now()
s := mygo.Network.Status()
t.Logf("%+v in %v", s, time.Since(start))
if !s.Online {
t.Errorf("Status = %+v, want online", s)
}
mygo.Network.OnChanged(func(mygo.NetworkStatus) {})()
if again := mygo.Network.Status(); again != s {
t.Logf("the status changed to %+v", again)
}
}
+153
View File
@@ -0,0 +1,153 @@
//go:build linux && !android && (amd64 || arm64) && !android
package e2e
import (
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"sync"
"testing"
"time"
"github.com/egoist/mygo"
)
// TestNowPlayingMPRIS drives the app's MPRIS player as the desktop's
// media controls do, with gdbus: the metadata lists each artist, and
// Raise brings the window that had the keyboard last forward.
func TestNowPlayingMPRIS(t *testing.T) {
gdbus, err := exec.LookPath("gdbus")
if err != nil {
t.Skip("gdbus is needed to act as an MPRIS client")
}
call := func(args ...string) (string, error) {
out, err := exec.Command(gdbus, append([]string{"call", "--session"}, args...)...).CombinedOutput()
return strings.TrimSpace(string(out)), err
}
var (
mu sync.Mutex
cmds []string
)
off := mygo.NowPlaying.OnCommand(func(cmd mygo.MediaCommand, pos time.Duration) {
mu.Lock()
cmds = append(cmds, fmt.Sprint(cmd, " ", pos))
mu.Unlock()
if cmd == mygo.MediaPause {
mygo.NowPlaying.SetPlayback(mygo.PlaybackPaused, 10*time.Second)
}
})
defer off()
mygo.NowPlaying.Set(mygo.NowPlayingInfo{
Title: "Spring", Artists: []string{"Antonio Vivaldi", "I Musici"}, Album: "The Four Seasons", Artwork: []byte("\x89PNG\r\n\x1a\n"),
Duration: 3 * time.Minute, Position: 10 * time.Second, State: mygo.PlaybackPaused,
Commands: mygo.MediaPlay | mygo.MediaPause | mygo.MediaNext | mygo.MediaSeek,
})
defer mygo.NowPlaying.Clear()
var name string
eventually(t, "the player's bus name", func() bool {
out, _ := call("-d", "org.freedesktop.DBus", "-o", "/org/freedesktop/DBus", "-m", "org.freedesktop.DBus.ListNames")
// A list of quoted names, as (['org.freedesktop.DBus', ':1.0'],)
name = regexp.MustCompile(fmt.Sprintf(`org\.mpris\.MediaPlayer2\.[^']+\.instance%d\b`, os.Getpid())).FindString(out)
return name != ""
})
player := func(args ...string) string {
t.Helper()
out, err := call(append([]string{"-d", name, "-o", "/org/mpris/MediaPlayer2", "-m"}, args...)...)
if err != nil {
t.Fatalf("%v: %v: %s", args, err, out)
}
return out
}
get := func(prop string) string {
t.Helper()
return player("org.freedesktop.DBus.Properties.Get", "org.mpris.MediaPlayer2.Player", prop)
}
if got := player("org.freedesktop.DBus.Properties.Get", "org.mpris.MediaPlayer2", "CanRaise"); got != "(<true>,)" {
t.Errorf("CanRaise = %s", got)
}
if got := get("PlaybackStatus"); got != "(<'Paused'>,)" {
t.Errorf("PlaybackStatus = %s", got)
}
if got := get("Position"); got != "(<int64 10000000>,)" {
t.Errorf("Position = %s, want 10 s while paused", got)
}
meta := get("Metadata")
for _, want := range []string{"'xesam:title': <'Spring'>", "'xesam:artist': <['Antonio Vivaldi', 'I Musici']>", "'xesam:album': <'The Four Seasons'>", "'mpris:length': <int64 180000000>", "'mpris:artUrl': <'file://"} {
if !strings.Contains(meta, want) {
t.Errorf("Metadata %s lacks %s", meta, want)
}
}
for prop, want := range map[string]string{"CanPlay": "true", "CanPause": "true", "CanGoNext": "true", "CanGoPrevious": "false", "CanSeek": "true"} {
if got := get(prop); got != "(<"+want+">,)" {
t.Errorf("%s = %s, want %s", prop, got, want)
}
}
player("org.mpris.MediaPlayer2.Player.PlayPause") // paused: play
player("org.mpris.MediaPlayer2.Player.Previous") // not offered
player("org.mpris.MediaPlayer2.Player.Seek", "5000000") // 10 s + 5 s
player("org.mpris.MediaPlayer2.Player.SetPosition", "/x", "1") // another track
track := meta[strings.Index(meta, "/org/mygo/track/"):]
track = track[:strings.IndexByte(track, '\'')]
player("org.mpris.MediaPlayer2.Player.SetPosition", track, "60000000")
want := []string{
fmt.Sprint(mygo.MediaPlay, " 10s"), // where it was paused
fmt.Sprint(mygo.MediaSeek, " 15s"),
fmt.Sprint(mygo.MediaSeek, " 1m0s"),
}
eventually(t, "the commands", func() bool {
mu.Lock()
defer mu.Unlock()
return len(cmds) >= len(want)
})
mu.Lock()
got := strings.Join(cmds, ", ")
mu.Unlock()
if got != strings.Join(want, ", ") {
t.Errorf("commands = %s, want %s", got, strings.Join(want, ", "))
}
// Raise shows and focuses the window that had the keyboard last: b,
// as a had it before. Both hide, the focused one last: a window still
// showing could take the keyboard as it hides, under the pointer
// without a window manager, and be the latest.
a := newWindow(t, mygo.WindowOptions{Title: "Raise A", Width: 200, Height: 100})
b := newWindow(t, mygo.WindowOptions{Title: "Raise B", Width: 200, Height: 100})
for _, w := range []*mygo.Window{a, b} {
w.Focus()
eventually(t, "the window to have the keyboard", w.IsFocused)
}
a.Hide()
b.Hide()
player("org.mpris.MediaPlayer2.Raise")
eventually(t, "b raised", func() bool { return b.IsVisible() && b.IsFocused() })
if a.IsVisible() {
t.Error("Raise showed a, which had the keyboard before b")
}
// Then a had it, after b.
a.Show()
eventually(t, "a to have the keyboard", a.IsFocused)
b.Hide()
a.Hide()
player("org.mpris.MediaPlayer2.Raise")
eventually(t, "a raised", func() bool { return a.IsVisible() && a.IsFocused() })
if b.IsVisible() {
t.Error("Raise showed b, which had the keyboard before a")
}
mu.Lock()
if len(cmds) != len(want) {
t.Errorf("Raise reached OnCommand: %s", strings.Join(cmds[len(want):], ", "))
}
mu.Unlock()
mygo.NowPlaying.Clear()
eventually(t, "the player leaving the bus", func() bool {
out, _ := call("-d", "org.freedesktop.DBus", "-o", "/org/freedesktop/DBus", "-m", "org.freedesktop.DBus.NameHasOwner", name)
return out == "(false,)"
})
}
+120
View File
@@ -0,0 +1,120 @@
//go:build !js
package e2e
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
)
// A page the web view kept as it was left, and shows again on Back
// without loading it, runs no script again. It hears events as before,
// and the call it left unanswered fails, as Go canceled it.
func TestPageShownAgainFromCache(t *testing.T) {
w := newWindow(t, mygo.WindowOptions{Title: "Page cache", Width: 400, Height: 300})
p := w.Page()
var ready atomic.Int32
p.OnDOMReady(func() { ready.Add(1) })
if err := p.LoadURL("app://localhost/"); err != nil {
t.Fatal(err)
}
waitFor(t, w, "window.run")
mustEval(t, w, `(() => {
addEventListener("pageshow", (e) => { window.shownAgain = e.persisted; });
window.left = mygo.call("Streams.Forever", mygo.channel()).then(() => "returned", (e) => "failed: " + e.message);
})()`)
if err := p.LoadURL("app://localhost/capture"); err != nil {
t.Fatal(err)
}
waitFor(t, w, `location.pathname === "/capture" && document.readyState === "complete"`)
wait.For(t, "the call of the page left to be canceled", streams.stopped)
wait.Until(t, "the DOM of the second page ready", func() bool { return ready.Load() == 2 })
p.GoBack()
// A page loaded again has neither the listener nor window.left: only
// the page kept hears pageshow.
waitFor(t, w, `location.pathname === "/" && document.readyState === "complete" && (window.shownAgain !== undefined || window.left === undefined)`)
if mustEval(t, w, "window.shownAgain === true") != true {
t.Skip("the engine loaded the page again instead of keeping it")
}
wait.Until(t, "the DOM of the page shown again ready", func() bool { return ready.Load() == 3 })
if err := ticked.Emit(w, Tick{N: 9}); err != nil {
t.Fatal(err)
}
waitFor(t, w, "results.includes('tick9')")
if got := mustEval(t, w, "window.left"); got != "failed: the page was left before the call returned" {
t.Errorf("the call the page left unanswered: %v", got)
}
if got := mustEval(t, w, `mygo.call("Greeter.Greet", "again")`); got != "Hello, again!" {
t.Errorf("a call of the page shown again = %v", got)
}
}
// Evals that run in a page as the navigation away from it commits answer,
// although the web view keeps the page frozen: WebKit runs what they
// queued to answer before it freezes the page (the bridge's pagehide
// listener), not when Back shows it again. Before, the poll of waitFor
// that ran then in TestPageShownAgainFromCache waited for good.
func TestEvalAsPageIsCached(t *testing.T) {
w := newWindow(t, mygo.WindowOptions{Title: "Eval as the page is cached", Width: 400, Height: 300})
p := w.Page()
if err := p.LoadURL("app://localhost/"); err != nil {
t.Fatal(err)
}
waitFor(t, w, "window.run")
// The page streams from Go as it is left, as in
// TestPageShownAgainFromCache, whose waitFor met this.
mustEval(t, w, `(() => {
addEventListener("pageshow", (e) => { window.shownAgain = e.persisted; });
mygo.call("Streams.Forever", mygo.channel()).catch(() => {});
})()`)
var committed atomic.Bool
off := p.OnDidNavigate(func(string) { committed.Store(true) })
defer off()
if err := p.LoadURL("app://localhost/capture"); err != nil {
t.Fatal(err)
}
// Evals, one after the other, until Go hears the navigation commit and
// a few more: some run in the page left, the last ones as it is left.
ctx := wait.Context(t)
var wg sync.WaitGroup
var mu sync.Mutex
var failed []string
for i, after := 0, 0; after < 5; i++ {
if committed.Load() {
after++
}
wg.Add(1)
go func() {
defer wg.Done()
// An engine may fail an eval of a page it destroys: it must
// not wait for good.
if _, err := p.EvalContext(ctx, "location.pathname"); errors.Is(err, context.DeadlineExceeded) {
mu.Lock()
failed = append(failed, fmt.Sprintf("eval %d never answered", i))
mu.Unlock()
}
}()
time.Sleep(time.Millisecond) // spreads them over the navigation
}
wg.Wait()
for _, f := range failed {
t.Error(f)
}
wait.For(t, "the call of the page left to be canceled", streams.stopped)
waitFor(t, w, `location.pathname === "/capture" && document.readyState === "complete"`)
p.GoBack()
waitFor(t, w, `location.pathname === "/" && document.readyState === "complete"`)
if mustEval(t, w, "window.shownAgain === true") != true {
t.Skip("the engine loaded the page again instead of keeping it")
}
}
+109
View File
@@ -0,0 +1,109 @@
//go:build !js
package e2e
import (
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
const gesturesPage = `<!doctype html><html><body style="margin:0;height:100vh">
<p>Pinch me</p><script>window.ready = true</script></body></html>`
// TestPageGestures checks that each platform's webview swipes between
// pages and zooms with a pinch only when PageOptions ask for it: in the
// pages of windows and of web views in native UI, as the webview's own
// settings read back.
func TestPageGestures(t *testing.T) {
both := mygo.PageOptions{SwipeNavigation: true, PinchZoom: true}
plain := newWindow(t, mygo.WindowOptions{Title: "No gestures", Width: 300, Height: 200})
on := newWindow(t, mygo.WindowOptions{Title: "Gestures", Width: 300, Height: 200, Page: both})
swipeOnly := newWindow(t, mygo.WindowOptions{Title: "Swipes", Width: 300, Height: 200, Page: mygo.PageOptions{SwipeNavigation: true}})
var views atomic.Pointer[[2]*mygo.WebView]
var frames atomic.Int32
host := newWindow(t, mygo.WindowOptions{Title: "Web views' gestures", Width: 400, Height: 300, Content: ui.View(func(c *ui.Context) {
frames.Add(1)
ui.Column(c).Fill().AlignItems(ui.Stretch).Children(func() {
if v := views.Load(); v != nil {
ui.WebView(c, v[0]).Grow(1)
ui.WebView(c, v[1]).Grow(1)
}
})
})})
eventually(t, "a frame", func() bool { return frames.Load() > 0 })
plainView, err := host.NewWebView(mygo.WebViewOptions{})
if err != nil {
t.Fatal(err)
}
onView, err := host.NewWebView(mygo.WebViewOptions{Page: both})
if err != nil {
t.Fatal(err)
}
host.Update(func() { views.Store(&[2]*mygo.WebView{plainView, onView}) })
// The pages load, so that the web views are made: WebView2 makes its
// own after the window.
for _, p := range []*mygo.Page{plain.Page(), on.Page(), swipeOnly.Page(), plainView.Page(), onView.Page()} {
p.LoadHTML(gesturesPage, "")
waitForPage(t, p, "window.ready")
}
for _, tc := range []struct {
name string
w *mygo.Window
webView int
swipe, pinch bool
}{
{"a window's page by default", plain, -1, false, false},
{"a window's page with both", on, -1, true, true},
{"a window's page with SwipeNavigation", swipeOnly, -1, true, false},
{"a web view by default", host, 0, false, false},
{"a web view with both", host, 1, true, true},
} {
swipe, pinch, ok := pageGestures(tc.w, tc.webView)
if !ok {
t.Skip("the webview's gesture settings can't be read here")
}
if swipe != tc.swipe || pinch != tc.pinch {
t.Errorf("%s swipes %v and pinches %v, want %v and %v", tc.name, swipe, pinch, tc.swipe, tc.pinch)
}
}
}
// TestPinchZoomPage pinches the touchpad over a page that asked for
// PinchZoom and over one that did not, each in turn, until the first
// zooms: the same pinches leave the second as it is, as WebKitGTK zooms
// on a pinch unless MyGo stops it.
func TestPinchZoomPage(t *testing.T) {
zoomed := newWindow(t, mygo.WindowOptions{Title: "Pinch zoom", Width: 300, Height: 200, Page: mygo.PageOptions{PinchZoom: true}})
plain := newWindow(t, mygo.WindowOptions{Title: "No pinch zoom", Width: 300, Height: 200})
for _, w := range []*mygo.Window{zoomed, plain} {
w.Page().LoadHTML(gesturesPage, "")
waitFor(t, w, "window.ready")
}
// The page answers its scripts after the events before them.
scale := func(w *mygo.Window) float64 {
s, _ := mygo.EvalAs[float64](w.Page(), "window.visualViewport ? visualViewport.scale : 1")
return s
}
pinches := 0
// WebKit asks the page where it is before it zooms: a pinch over a
// page that has not answered yet does nothing, and a later one zooms.
eventually(t, "a pinch zooming the page", func() bool {
if !pinchPage(zoomed, -1, 150, 100, 1.5, 2, 2) || !pinchPage(plain, -1, 150, 100, 1.5, 2, 2) {
t.Skip("pinch automation unavailable")
}
pinches++
if s := scale(plain); s != 1 {
t.Fatalf("%d pinches zoomed a page without PinchZoom to %v", pinches, s)
}
return scale(zoomed) > 1
})
if s := scale(plain); s != 1 {
t.Errorf("%d pinches zoomed a page without PinchZoom to %v", pinches, s)
}
}
@@ -0,0 +1,65 @@
//go:build darwin && !ios
package e2e
import (
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/darwin"
"github.com/egoist/mygo/ui"
)
// A panel's native UI hears the pointer while another app is active, as
// a panel never makes its app active.
func TestPanelHoverWhileInactive(t *testing.T) {
var moves atomic.Int32
var drawn atomic.Bool
view := func(c *ui.Context) {
ui.Box(c).Fill().HandleInput(func(ev ui.InputEvent) bool {
if ev.Kind == ui.InputPointerMove {
moves.Add(1)
}
return false
}).Draw(func(*ui.Painter, ui.Rect) { drawn.Store(true) })
}
// The app activates as it starts: done before another app is.
other := newWindow(t, mygo.WindowOptions{Title: "Other", Width: 200, Height: 100})
other.Focus()
eventually(t, "the app active", func() bool { active, _ := appActive(); return active })
panel := newWindow(t, mygo.WindowOptions{Title: "Panel hover", Width: 300, Height: 200, Panel: true, Hidden: true, Content: ui.View(view)})
if !deactivateApp() {
t.Skip("cannot activate another app")
}
// The tests after this one find the app active, as TestPanel needs.
t.Cleanup(func() {
activateApp()
eventually(t, "the app active again", func() bool { active, _ := appActive(); return active })
})
eventually(t, "the app deactivated", func() bool { active, _ := appActive(); return !active })
panel.ShowInactive()
eventually(t, "the first frame", drawn.Load)
if active, _ := appActive(); active {
t.Fatal("showing the panel activated the app")
}
// The window server may place the panel after ShowInactive returns:
// the pointer moves over it until the panel hears it.
b := panel.ContentBounds()
dx := 0.0
eventually(t, "the pointer moving over the panel", func() bool {
var ok bool
mygo.RunOnMain(func() {
ok = darwin.TestPostMouseMove(float64(b.X)+float64(b.Width)/2+dx, float64(b.Y)+float64(b.Height)/2)
})
if !ok {
t.Skip("this process may not post events (Accessibility)")
}
dx = 10 - dx
return moves.Load() > 0
})
if active, _ := appActive(); active {
t.Error("the panel activated the app")
}
}
+101
View File
@@ -0,0 +1,101 @@
//go:build !js
package e2e
import (
"sync/atomic"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// TestPanel shows a panel above other windows with the keyboard, unable
// to minimize or maximize, and closes it on an Escape its page leaves, as
// the user closing it, which an OnClose listener turns into hiding it. On
// macOS it floats on every Space, full-screen ones included, out of the
// window cycle, and takes the keyboard without activating the app.
func TestPanel(t *testing.T) {
other := newWindow(t, mygo.WindowOptions{Title: "Other", Width: 300, Height: 200})
other.Focus()
eventually(t, "the other window focused", other.IsFocused)
panel := newWindow(t, mygo.WindowOptions{Title: "Panel", Width: 400, Height: 120, Panel: true, Hidden: true})
if !panel.IsPanel() || other.IsPanel() {
t.Fatalf("IsPanel: panel %v, other window %v", panel.IsPanel(), other.IsPanel())
}
if !panel.IsAlwaysOnTop() || panel.IsMinimizable() || panel.IsMaximizable() {
t.Errorf("panel: always on top %v, minimizable %v, maximizable %v", panel.IsAlwaysOnTop(), panel.IsMinimizable(), panel.IsMaximizable())
}
const canJoinAllSpaces, ignoresCycle, auxiliary = 1 << 0, 1 << 6, 1 << 8 // NSWindowCollectionBehavior…
if b, ok := collectionBehavior(panel); ok && b&(canJoinAllSpaces|ignoresCycle|auxiliary) != canJoinAllSpaces|ignoresCycle|auxiliary {
t.Errorf("collection behavior %#x, want CanJoinAllSpaces, IgnoresCycle and FullScreenAuxiliary", b)
}
if tool, topmost, owned, ok := panelStyles(panel); ok && !(tool && topmost && owned) {
t.Errorf("panel: tool window without a window menu %v, topmost %v, owned by the application window %v", tool, topmost, owned)
}
panel.Page().LoadHTML(`<input id=i autofocus>`, "")
waitFor(t, panel, "document.getElementById('i')")
// Shown while another app is active, it takes the keyboard and leaves
// that app active (macOS).
deactivated := deactivateApp()
if deactivated {
eventually(t, "the app deactivated", func() bool { active, _ := appActive(); return !active })
}
panel.Show()
eventually(t, "the panel focused", panel.IsFocused)
waitFor(t, panel, "document.hasFocus() && document.activeElement.id === 'i'")
if deactivated {
time.Sleep(300 * time.Millisecond)
if active, _ := appActive(); active {
t.Error("showing the panel activated the app")
}
}
var closes atomic.Int32
off := panel.OnClose(func(e *mygo.CloseEvent) {
closes.Add(1)
e.PreventDefault()
panel.Hide()
})
if !pressEscape(panel) {
t.Skip("keys not available on this platform")
}
eventually(t, "the panel hidden on Escape", func() bool { return !panel.IsVisible() })
if n := closes.Load(); n != 1 || panel.IsDestroyed() {
t.Fatalf("after Escape: %d close requests, destroyed %v", n, panel.IsDestroyed())
}
// An Escape the page handles keeps it.
panel.Show()
eventually(t, "the panel focused again", panel.IsFocused)
panel.Page().Eval(`window.keep = true; addEventListener('keydown', e => { if (e.key === 'Escape' && window.keep) { e.preventDefault(); window.escaped = true } })`)
pressEscape(panel)
waitFor(t, panel, "window.escaped === true")
time.Sleep(300 * time.Millisecond)
if !panel.IsVisible() || closes.Load() != 1 {
t.Fatalf("an Escape the page handled: visible %v, %d close requests", panel.IsVisible(), closes.Load())
}
// Without the listener, an Escape closes it.
off()
panel.Page().Eval(`window.keep = false`)
pressEscape(panel)
eventually(t, "the panel closed on Escape", panel.IsDestroyed)
}
// TestPanelNativeUI closes a panel of native UI on an Escape its content
// leaves.
func TestPanelNativeUI(t *testing.T) {
panel := newWindow(t, mygo.WindowOptions{Width: 300, Height: 100, Panel: true, Content: ui.View(func(c *ui.Context) {
ui.Text(c, "Panel")
})})
eventually(t, "the panel focused", panel.IsFocused)
time.Sleep(200 * time.Millisecond)
if !pressEscape(panel) {
t.Skip("keys not available on this platform")
}
eventually(t, "the panel closed on Escape", panel.IsDestroyed)
}
+60
View File
@@ -0,0 +1,60 @@
//go:build windows
package e2e
import (
"sync/atomic"
"testing"
"github.com/egoist/mygo"
win "github.com/egoist/mygo/internal/windows"
)
// TestPanelAltF4 asks to close a panel on Alt+F4, which has no window menu
// (TestPanelStyles), with a material behind its page.
func TestPanelAltF4(t *testing.T) {
panel := newWindow(t, mygo.WindowOptions{Panel: true, Frameless: true, Transparent: true, Vibrancy: mygo.VibrancyPopover, Width: 400, Height: 200})
panel.Page().LoadHTML(`<body style="background:transparent">panel</body>`, "")
eventually(t, "the panel focused", panel.IsFocused)
var closes atomic.Int32
panel.OnClose(func(e *mygo.CloseEvent) { closes.Add(1); e.PreventDefault() })
mygo.RunOnMain(func() { win.TestPressKeys(0x12, 0x73) }) // VK_MENU, VK_F4
eventually(t, "Alt+F4 asks to close", func() bool { return closes.Load() > 0 })
}
// A panel the app maximizes fills the work area of its display, as other
// windows do, rather than the whole display: Windows gives a window
// without a maximize box the whole monitor, and the panel, topmost, would
// hide the taskbar. What shows of it, without its invisible borders, is the
// work area; the test reads the window's rectangles in pixels, as Windows
// keeps them, rather than in DIPs through the page or its bounds.
func TestPanelMaximizedInWorkArea(t *testing.T) {
panel := newWindow(t, mygo.WindowOptions{Panel: true, Frameless: true, Transparent: true, Vibrancy: mygo.VibrancyAcrylic, X: 100, Y: 100, Width: 400, Height: 200})
panel.Page().LoadHTML(`<body style="background:transparent">panel</body>`, "")
eventually(t, "the panel shown", panel.IsVisible)
type rects struct {
window, shown, client, monitor, work [4]int32
zoomed bool
}
read := func() (r rects) {
mygo.RunOnMain(func() {
r.window, r.shown, r.client, r.monitor, r.work, r.zoomed = win.TestMaximizedRects(panel.NativeHandle())
})
return r
}
if r := read(); r.work == r.monitor {
t.Skip("the monitor has no work area apart from its bounds: no taskbar to keep clear")
}
panel.Maximize()
eventually(t, "the panel maximized", panel.IsMaximized)
var last rects
defer func() {
if t.Failed() {
t.Logf("last rectangles (left, top, right, bottom, pixels): %+v", last)
}
}()
eventually(t, "the panel in the work area", func() bool {
last = read()
return last.zoomed && last.shown == last.work && last.client == last.work
})
}
+132
View File
@@ -0,0 +1,132 @@
//go:build !js
package e2e
import (
"bytes"
"compress/zlib"
"encoding/hex"
"io"
"regexp"
"runtime"
"strconv"
"strings"
"testing"
"unicode/utf16"
"github.com/egoist/mygo"
)
// The PDFs that WebKit prints on macOS name radicals for many Chinese
// characters in their ToUnicode maps, ⼈ (U+2F08) for 人 in PingFang SC and
// ⼜ (U+2F1C) for 口 in Songti SC; PrintToPDF gives the characters back.
func TestPrintToPDFText(t *testing.T) {
if runtime.GOOS != "darwin" {
t.Skip("the radicals in the text of printed PDFs are a quirk of CoreGraphics")
}
const text = "人工智能让写作更容易。用户点击按钮后,页面会显示一个对话框。门口停着一辆车。"
w := newWindow(t, mygo.WindowOptions{Title: "PDF text", Width: 400, Height: 300})
w.Page().LoadHTML(`<html lang="zh-CN"><p style="font-family: 'PingFang SC'">`+text+`</p><p style="font-family: 'Songti SC'">`+text+`</p></html>`, "")
waitFor(t, w, `document.readyState === "complete" && document.querySelectorAll("p").length === 2`)
pdf, err := w.Page().PrintToPDF(mygo.PDFOptions{})
if err != nil {
t.Fatal(err)
}
texts := printedTexts(t, pdf)
if len(texts) != 2 {
t.Fatalf("%d ToUnicode maps, want one for each font", len(texts))
}
for _, s := range texts {
for _, r := range s {
if !strings.ContainsRune(text, r) {
t.Errorf("the PDF's text has %q (%U), which the page does not", r, r)
}
}
}
}
// printedTexts returns the texts of the ToUnicode maps of pdf, the newest
// object of each number, as an update to the PDF appends them.
func printedTexts(t *testing.T, pdf []byte) []string {
t.Helper()
objects := map[string][]byte{}
header := regexp.MustCompile(`(?m)^(\d+) \d+ obj\s*`)
for _, at := range header.FindAllSubmatchIndex(pdf, -1) {
if end := bytes.Index(pdf[at[1]:], []byte("endobj")); end >= 0 {
objects[string(pdf[at[2]:at[3]])] = pdf[at[1] : at[1]+end]
}
}
refs := map[string]bool{}
for _, obj := range objects {
if m := regexp.MustCompile(`/ToUnicode\s+(\d+)\s+\d+\s+R`).FindSubmatch(obj); m != nil {
refs[string(m[1])] = true
}
}
var texts []string
for n := range refs {
obj := objects[n]
start := bytes.Index(obj, []byte("stream"))
end := bytes.LastIndex(obj, []byte("endstream"))
if start < 0 || end < start {
t.Fatalf("ToUnicode map %s has no stream", n)
}
r, err := zlib.NewReader(bytes.NewReader(bytes.TrimLeft(obj[start+len("stream"):end], "\r\n")))
if err != nil {
t.Fatalf("ToUnicode map %s: %v", n, err)
}
cmap, err := io.ReadAll(r)
if err != nil {
t.Fatalf("ToUnicode map %s: %v", n, err)
}
texts = append(texts, cmapText(t, cmap))
}
return texts
}
// cmapText returns the texts that a CMap maps codes to, run together.
func cmapText(t *testing.T, cmap []byte) string {
t.Helper()
var b strings.Builder
sections := regexp.MustCompile(`(?s)begin(bfchar|bfrange)(.*?)end(?:bfchar|bfrange)`)
strs := regexp.MustCompile(`<([0-9A-Fa-f]*)>|\[|\]`)
for _, section := range sections.FindAllSubmatch(cmap, -1) {
tokens := strs.FindAllSubmatch(section[2], -1)
for i := 0; i < len(tokens); {
if string(section[1]) == "bfchar" {
b.WriteString(utf16Hex(t, string(tokens[i+1][1])))
i += 2
continue
}
lo, _ := strconv.ParseUint(string(tokens[i][1]), 16, 32)
hi, _ := strconv.ParseUint(string(tokens[i+1][1]), 16, 32)
i += 2
if string(tokens[i][0]) == "[" {
for i++; string(tokens[i][0]) != "]"; i++ {
b.WriteString(utf16Hex(t, string(tokens[i][1])))
}
i++
continue
}
first := string(tokens[i][1])
last, _ := strconv.ParseUint(first[len(first)-2:], 16, 8)
for c := lo; c <= hi; c++ {
b.WriteString(utf16Hex(t, first[:len(first)-2]+strconv.FormatUint(0x100+last+c-lo, 16)[1:]))
}
i++
}
}
return b.String()
}
func utf16Hex(t *testing.T, h string) string {
t.Helper()
data, err := hex.DecodeString(h)
if err != nil || len(data)%2 != 0 {
t.Fatalf("not UTF-16: <%s>", h)
}
units := make([]uint16, len(data)/2)
for i := range units {
units[i] = uint16(data[2*i])<<8 | uint16(data[2*i+1])
}
return string(utf16.Decode(units))
}
@@ -0,0 +1,34 @@
//go:build darwin && !ios
package e2e
import (
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/darwin"
)
// allowsPictureInPicture reports whether a window's page lets its videos
// go into picture in picture.
func allowsPictureInPicture(w *mygo.Window) (allowed, supported bool) {
mygo.RunOnMain(func() { allowed, supported = darwin.TestAllowsPictureInPicture(w.NativeHandle()) })
return allowed, supported
}
// PictureInPicture turns WebKit's preference on, which WKWebView keeps
// off outside Safari.
func TestPictureInPicturePreference(t *testing.T) {
plain := newWindow(t, mygo.WindowOptions{Title: "No picture in picture", Width: 300, Height: 200})
allowed, supported := allowsPictureInPicture(plain)
if !supported {
t.Skip("WebKit doesn't answer _allowsPictureInPictureMediaPlayback")
}
if allowed {
t.Error("a page without PictureInPicture lets its videos go into picture in picture")
}
w := newWindow(t, mygo.WindowOptions{Title: "Picture in picture", Width: 300, Height: 200, Page: mygo.PageOptions{PictureInPicture: true}})
if allowed, _ := allowsPictureInPicture(w); !allowed {
t.Error("PictureInPicture did not turn WebKit's preference on")
}
}
+101
View File
@@ -0,0 +1,101 @@
//go:build !js
package e2e
import (
"os"
"runtime"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
)
// pipPage plays a video with sound, which it records from a canvas and a
// quiet tone first, at app://localhost/pip: large and with sound, as the
// video WebKit picks for its media controls is. window.restored tells
// that the page came back from the back/forward cache. A page may need a
// click to play (autoplay policies), which the button takes.
const pipPage = `<!doctype html><button id=play>Play</button><p id=state>recording</p>
<video id=video width=640 height=360 loop playsinline></video><script>
addEventListener("pageshow", (e) => { window.restored = e.persisted; });
const canvas = Object.assign(document.createElement("canvas"), {width: 320, height: 180}), g = canvas.getContext("2d");
let frame = 0;
const draw = () => { g.fillStyle = "hsl(" + (frame++ * 6 % 360) + " 70% 50%)"; g.fillRect(0, 0, 320, 180); requestAnimationFrame(draw); };
draw();
const audio = new AudioContext(), tone = audio.createOscillator(), gain = audio.createGain(), out = audio.createMediaStreamDestination();
gain.gain.value = 0.02;
tone.connect(gain).connect(out);
tone.start();
const recorder = new MediaRecorder(new MediaStream([...canvas.captureStream(30).getVideoTracks(), ...out.stream.getAudioTracks()])), chunks = [];
const play = () => video.play().then(() => { state.textContent = "playing"; }, (e) => { state.textContent = "blocked: " + e.name; });
recorder.ondataavailable = (e) => chunks.push(e.data);
recorder.onstop = () => { video.src = URL.createObjectURL(new Blob(chunks, {type: recorder.mimeType})); play(); };
recorder.start();
setTimeout(() => recorder.stop(), 2000);
document.getElementById("play").onclick = () => { audio.resume(); play(); };
</script>`
// A page without a video has none in picture in picture, and toggling
// moves nothing.
func TestPictureInPictureWithoutVideo(t *testing.T) {
w := newWindow(t, mygo.WindowOptions{Title: "No video", Width: 300, Height: 200, Page: mygo.PageOptions{PictureInPicture: true}})
p := w.Page()
p.LoadHTML(`<p>no video</p>`, "")
waitFor(t, w, `document.body.textContent === "no video" && document.readyState === "complete"`)
if p.IsPictureInPictureActive() {
t.Error("IsPictureInPictureActive = true for a page without a video")
}
p.TogglePictureInPicture()
mustEval(t, w, `1`) // a round trip, for the toggle to land
if p.IsPictureInPictureActive() {
t.Error("IsPictureInPictureActive = true after toggling a page without a video")
}
}
// TogglePictureInPicture moves a playing video into picture in picture
// and back, and a page that leaves with its video out comes back without
// it. It opens the system's picture in picture window, which needs a
// display, and its page plays sound, so it runs only with
// MYGO_E2E_PIP=1, by hand: click Play if the page is not allowed to play
// by itself, and watch the video float out and come back.
func TestPictureInPicture(t *testing.T) {
if os.Getenv("MYGO_E2E_PIP") != "1" {
t.Skip("opens a picture in picture window: set MYGO_E2E_PIP=1 on a machine with a display")
}
if runtime.GOOS == "linux" {
t.Skip("WebKitGTK has no picture in picture")
}
w := newWindow(t, mygo.WindowOptions{Title: "Picture in picture", Width: 700, Height: 480, Page: mygo.PageOptions{PictureInPicture: true}})
p := w.Page()
if err := p.LoadURL("app://localhost/pip"); err != nil {
t.Fatal(err)
}
t.Log("a video should play; click Play in the window if it says blocked")
waitFor(t, w, `document.getElementById("state").textContent === "playing"`)
active := func(want bool) func() bool {
return func() bool { return p.IsPictureInPictureActive() == want }
}
p.TogglePictureInPicture()
wait.Until(t, "the video in picture in picture", active(true))
p.TogglePictureInPicture()
wait.Until(t, "the video back in the page", active(false))
// WebKit restores a page from its back/forward cache believing that
// its video is still out, unless it was kept out of the cache.
p.TogglePictureInPicture()
wait.Until(t, "the video in picture in picture again", active(true))
mustEval(t, w, `location.href = "/"`)
waitFor(t, w, `location.pathname === "/" && document.readyState === "complete"`)
wait.Until(t, "no video in picture in picture on the next page", active(false))
p.GoBack()
waitFor(t, w, `location.pathname === "/pip" && document.readyState === "complete"`)
restored := mustEval(t, w, `window.restored === true`)
if p.IsPictureInPictureActive() || mustEval(t, w, `document.pictureInPictureElement !== null`) == true {
t.Errorf("the page came back believing its video is in picture in picture (restored from the cache: %v)", restored)
}
if runtime.GOOS == "darwin" && restored == true {
t.Error("WebKit kept a page that left with its video in picture in picture in its back/forward cache")
}
}
+57
View File
@@ -0,0 +1,57 @@
//go:build !js
package e2e
import (
"math"
"sync/atomic"
"testing"
"github.com/egoist/mygo"
"github.com/egoist/mygo/ui"
)
// A touchpad's pinch over an element of native UI comes to it as
// InputZoom, with the scale and where the pointer is over the element.
func TestPinchZooms(t *testing.T) {
type zoom struct{ x, y, scale float32 }
var got atomic.Pointer[zoom]
var drawn atomic.Bool
var missed atomic.Pointer[zoom] // a pinch outside the element
view := func(c *ui.Context) {
ui.Box(c).Fill().HandleInput(func(ev ui.InputEvent) bool {
if ev.Kind == ui.InputZoom {
missed.Store(&zoom{ev.X, ev.Y, ev.Scale})
}
return false
}).Children(func() {
ui.Box(c).Absolute().Left(40).Top(30).Size(200, 120).HandleInput(func(ev ui.InputEvent) bool {
if ev.Kind != ui.InputZoom {
return false
}
z := zoom{ev.X, ev.Y, ev.Scale}
if p := got.Load(); p != nil {
z.scale *= p.scale
}
got.Store(&z)
return true
}).Draw(func(*ui.Painter, ui.Rect) { drawn.Store(true) })
})
}
w := newWindow(t, mygo.WindowOptions{Title: "Pinch", Width: 320, Height: 220, Content: ui.View(view)})
eventually(t, "the first frame", drawn.Load)
want, ok := pinch(w, 100, 90, 1.5)
if !ok {
t.Skip("pinch automation unavailable")
}
eventually(t, "the pinch", func() bool {
if m := missed.Load(); m != nil {
t.Fatalf("the pinch zoomed by %v at (%v, %v) of the window, outside the element", m.scale, m.x, m.y)
}
return got.Load() != nil
})
z := got.Load()
if math.Abs(float64(z.scale)-want) > 1e-3 || math.Abs(float64(z.x-60)) > 1 || math.Abs(float64(z.y-60)) > 1 {
t.Fatalf("the pinch zoomed by %v at (%v, %v), want %v at (60, 60)", z.scale, z.x, z.y, want)
}
}
+296
View File
@@ -0,0 +1,296 @@
//go:build !js
package e2e
import (
"bufio"
"crypto/sha1"
"encoding/base64"
"encoding/binary"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/internal/wait"
"github.com/egoist/mygo/plugins/fetch"
"github.com/egoist/mygo/plugins/sqlite"
"github.com/egoist/mygo/plugins/watch"
"github.com/egoist/mygo/plugins/websocket"
)
// pluginsPage loads the plugins' JavaScript packages, as built, with an
// import map in place of a bundler.
const pluginsPage = `<!doctype html><html><head>
<script type="importmap">{"imports": {
"mygo-runtime": "/js/runtime.js",
"@mygo-plugins/fetch": "/js/fetch.js",
"@mygo-plugins/sqlite": "/js/sqlite.js",
"@mygo-plugins/websocket": "/js/websocket.js",
"@mygo-plugins/watch": "/js/watch.js"
}}</script>
<script type="module">
import { fetch } from "@mygo-plugins/fetch";
import { open } from "@mygo-plugins/sqlite";
import { WebSocket } from "@mygo-plugins/websocket";
import { watch } from "@mygo-plugins/watch";
window.plugins = { fetch, WebSocket, open, watch };
</script></head><body>plugins</body></html>`
// A request of the page that the page aborted.
var aborted = make(chan struct{}, 1)
// Requests to /hold that were not canceled within a second.
var held = make(chan struct{}, 1)
var watchPluginRoot string
// usePlugins adds the plugins and serves their test page.
func usePlugins(mux *http.ServeMux) {
mygo.Use(fetch.Plugin, websocket.Plugin, sqlite.Plugin)
dir, err := os.MkdirTemp("", "mygo-watch-e2e-")
if err != nil {
panic(err)
}
watchPluginRoot, err = filepath.EvalSymlinks(dir)
if err != nil {
panic(err)
}
mygo.Use(watch.New(watch.Options{Roots: map[string]watch.Root{"project": {Path: watchPluginRoot}}, MaxWatchesPerPage: 1}))
mygo.App.OnQuit(func() { _ = os.Remove(watchPluginRoot) })
mux.HandleFunc("/plugins.html", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
io.WriteString(w, pluginsPage)
})
for name, path := range map[string]string{
"runtime": "../../packages/runtime/dist/index.js",
"fetch": "../../plugins/fetch/dist/index.js",
"sqlite": "../../plugins/sqlite/dist/index.js",
"websocket": "../../plugins/websocket/dist/index.js",
"watch": "../../plugins/watch/dist/index.js",
} {
mux.HandleFunc("/js/"+name+".js", func(w http.ResponseWriter, r *http.Request) {
b, err := os.ReadFile(path)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/javascript")
w.Write(b)
})
}
}
// pluginServer is a server the page reaches through the plugins: it sends
// no CORS headers.
func pluginServer() *httptest.Server {
mux := http.NewServeMux()
mux.HandleFunc("/origin", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "origin "+r.Header.Get("Origin"))
})
mux.HandleFunc("/stream", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "first")
w.(http.Flusher).Flush()
select {
case <-r.Context().Done():
aborted <- struct{}{}
case <-time.After(10 * time.Second):
}
})
mux.HandleFunc("/hold", func(w http.ResponseWriter, r *http.Request) {
select {
case <-r.Context().Done():
case <-time.After(time.Second):
held <- struct{}{}
}
})
mux.HandleFunc("/ws", wsEcho)
return httptest.NewServer(mux)
}
// wsEcho answers text messages with the X-Token of the handshake and the
// message, and the closing handshake with the same code.
func wsEcho(w http.ResponseWriter, r *http.Request) {
h := sha1.Sum([]byte(r.Header.Get("Sec-WebSocket-Key") + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))
conn, brw, err := http.NewResponseController(w).Hijack()
if err != nil {
return
}
defer conn.Close()
fmt.Fprintf(brw, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\n\r\n",
base64.StdEncoding.EncodeToString(h[:]))
brw.Flush()
for {
op, p, err := readClientFrame(brw.Reader)
if err != nil {
return
}
if op == 0x8 {
conn.Write(append([]byte{0x88, byte(min(len(p), 2))}, p[:min(len(p), 2)]...))
return
}
reply := r.Header.Get("X-Token") + ":" + string(p)
conn.Write(append([]byte{0x81, byte(len(reply))}, reply...))
}
}
// readClientFrame reads a short masked frame.
func readClientFrame(br *bufio.Reader) (byte, []byte, error) {
var h [2]byte
if _, err := io.ReadFull(br, h[:]); err != nil {
return 0, nil, err
}
n := int(h[1] & 0x7f)
if n == 126 {
var l [2]byte
io.ReadFull(br, l[:])
n = int(binary.BigEndian.Uint16(l[:]))
}
var mask [4]byte
io.ReadFull(br, mask[:])
p := make([]byte, n)
if _, err := io.ReadFull(br, p); err != nil {
return 0, nil, err
}
for i := range p {
p[i] ^= mask[i%4]
}
return h[0] & 0x0f, p, nil
}
func TestPlugins(t *testing.T) {
for _, dist := range []string{"../../packages/runtime/dist", "../../plugins/fetch/dist", "../../plugins/websocket/dist", "../../plugins/sqlite/dist"} {
if _, err := os.Stat(dist); err != nil {
t.Skip("the JavaScript packages are not built; run bun run build")
}
}
srv := pluginServer()
defer srv.Close()
w := newWindow(t, mygo.WindowOptions{Hidden: true})
if err := w.Page().LoadURL("app://localhost/plugins.html"); err != nil {
t.Fatal(err)
}
waitFor(t, w, "window.plugins")
// No CORS, and headers a page may not set.
got, err := mygo.EvalAs[string](w.Page(), fmt.Sprintf(`(async () => {
const res = await plugins.fetch(%q, { headers: { origin: "https://example.test" } });
return res.status + ":" + await res.text();
})()`, srv.URL+"/origin"))
if want := "200:origin https://example.test"; err != nil || got != want {
t.Errorf("fetch: %q, %v; want %q", got, err, want)
}
// The body streams, and aborting stops the request in Go.
got, err = mygo.EvalAs[string](w.Page(), fmt.Sprintf(`(async () => {
const ctrl = new AbortController();
const res = await plugins.fetch(%q, { signal: ctrl.signal });
const reader = res.body.getReader();
const first = new TextDecoder().decode((await reader.read()).value);
ctrl.abort();
return first + ":" + await reader.read().then(() => "read", (e) => e.name);
})()`, srv.URL+"/stream"))
if want := "first:AbortError"; err != nil || got != want {
t.Errorf("aborted fetch: %q, %v; want %q", got, err, want)
}
select {
case <-aborted:
case <-time.After(wait.Guard):
t.Error("the server's request was not canceled")
}
// Aborted right away, before Go even started the request.
got, err = mygo.EvalAs[string](w.Page(), fmt.Sprintf(`(async () => {
const ctrl = new AbortController();
const res = plugins.fetch(%q, { signal: ctrl.signal });
ctrl.abort();
return await res.then(() => "resolved", (e) => e.name);
})()`, srv.URL+"/hold"))
if err != nil || got != "AbortError" {
t.Errorf("fetch aborted at once: %q, %v", got, err)
}
select {
case <-held:
t.Error("the request aborted at once ran in Go")
case <-time.After(1500 * time.Millisecond):
}
got, err = mygo.EvalAs[string](w.Page(), fmt.Sprintf(`new Promise((resolve, reject) => {
const ws = new plugins.WebSocket(%q, [], { headers: { "x-token": "secret" } });
let data;
ws.onopen = () => ws.send("hi");
ws.onmessage = (e) => { data = e.data; ws.close(1000, "done"); };
ws.onerror = () => reject(new Error("WebSocket error"));
ws.onclose = (e) => resolve(data + ":" + e.code + ":" + e.wasClean);
})`, "ws"+strings.TrimPrefix(srv.URL, "http")+"/ws"))
if want := "secret:hi:1000:true"; err != nil || got != want {
t.Errorf("WebSocket: %q, %v; want %q", got, err, want)
}
}
// TestSQLitePlugin exercises the built client through the real IPC transport:
// parameters, int64/BLOB values, rollback and page-owned connection cleanup.
func TestSQLitePlugin(t *testing.T) {
for _, dist := range []string{"../../packages/runtime/dist", "../../plugins/fetch/dist", "../../plugins/websocket/dist", "../../plugins/sqlite/dist"} {
if _, err := os.Stat(dist); err != nil {
t.Skip("run bun run build first")
}
}
w := newWindow(t, mygo.WindowOptions{Hidden: true})
if err := w.Page().LoadURL("app://localhost/plugins.html"); err != nil {
t.Fatal(err)
}
waitFor(t, w, "window.plugins")
got, err := mygo.EvalAs[string](w.Page(), `(async () => {
const db = await plugins.open(":memory:");
await db.execute("CREATE TABLE items(id INTEGER PRIMARY KEY, title TEXT, bytes BLOB)");
const big = 9223372036854775807n;
const inserted = await db.execute("INSERT INTO items VALUES (?, ?, ?)", [big, "中文🙂", new Uint8Array([0, 255])]);
let rolledBack = false;
try {
await db.transaction([
{ sql: "INSERT INTO items VALUES (1, 'rollback', NULL)" },
{ sql: "INSERT INTO items VALUES (?, 'duplicate', NULL)", params: [big] },
]);
} catch { rolledBack = true; }
const result = await db.query("SELECT id, title, bytes FROM items");
await db.close();
return [String(inserted.lastInsertId), rolledBack, result.rows.length,
String(result.rows[0][0]), result.rows[0][1], [...result.rows[0][2]].join(",")].join(":");
})()`)
if want := "9223372036854775807:true:1:9223372036854775807:中文🙂:0,255"; err != nil || got != want {
t.Fatalf("SQLite: %q, %v; want %q", got, err, want)
}
// Retain just the old handle across a navigation: the new page's context
// must not be able to use the connection of the page it replaced.
id, err := mygo.EvalAs[string](w.Page(), `(async () => {
window.sqliteDB = await plugins.open(":memory:");
return window.sqliteDB.id;
})()`)
if err != nil {
t.Fatal(err)
}
other := newWindow(t, mygo.WindowOptions{Hidden: true})
if err := other.Page().LoadURL("app://localhost/plugins.html"); err != nil {
t.Fatal(err)
}
waitFor(t, other, "window.plugins")
got, err = mygo.EvalAs[string](other.Page(), fmt.Sprintf(`mygo.call("plugin:sqlite.Query", %q, "SELECT 1", []).then(() => "allowed", e => e.message)`, id))
if err != nil || !strings.Contains(got, "another page") {
t.Fatalf("SQLite ownership: %q %v", got, err)
}
if err := w.Page().LoadURL("app://localhost/plugins.html"); err != nil {
t.Fatal(err)
}
waitFor(t, w, "window.plugins && !window.sqliteDB")
got, err = mygo.EvalAs[string](w.Page(), fmt.Sprintf(`mygo.call("plugin:sqlite.Query", %q, "SELECT 1", []).then(() => "allowed", e => e.message)`, id))
if err != nil || !strings.Contains(got, "closed") {
t.Fatalf("SQLite after navigation: %q %v", got, err)
}
}
Loaded 100 of 2538 files, more files were not shown because too many files have changed in this diff. Show more