~eliasnaur/gio

ref: 6a9a87046221602d1a323887cd619e75c81cc24e gio/cmd/gogio/wayland_test.go -rw-r--r-- 4.6 KiB
6a9a8704Sebastien Binet app{,/internal/window}: make app.Main blocking on desktop platforms 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// SPDX-License-Identifier: Unlicense OR MIT

package main_test

import (
	"bufio"
	"bytes"
	"context"
	"fmt"
	"image"
	"image/png"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
	"sync"
	"text/template"
	"time"
)

type WaylandTestDriver struct {
	driverBase

	runtimeDir string
	socket     string
	display    string
}

// No bars or anything fancy. Just a white background with our dimensions.
var tmplSwayConfig = template.Must(template.New("").Parse(`
output * bg #FFFFFF solid_color
output * mode {{.Width}}x{{.Height}}
default_border none
`))

var rxSwayReady = regexp.MustCompile(`Running compositor on wayland display '(.*)'`)

func (d *WaylandTestDriver) Start(path string) {
	// We want os.Environ, so that it can e.g. find $DISPLAY to run within
	// X11. wlroots env vars are documented at:
	// https://github.com/swaywm/wlroots/blob/master/docs/env_vars.md
	env := os.Environ()
	if *headless {
		env = append(env, "WLR_BACKENDS=headless")
	}

	d.needPrograms(
		"sway",    // to run a wayland compositor
		"grim",    // to take screenshots
		"swaymsg", // to send input
	)

	// First, build the app.
	dir := d.tempDir("gio-endtoend-wayland")
	bin := filepath.Join(dir, "red")
	flags := []string{"build", "-tags", "nox11", "-o=" + bin}
	if raceEnabled {
		flags = append(flags, "-race")
	}
	flags = append(flags, path)
	cmd := exec.Command("go", flags...)
	if out, err := cmd.CombinedOutput(); err != nil {
		d.Fatalf("could not build app: %s:\n%s", err, out)
	}

	conf := filepath.Join(dir, "config")
	f, err := os.Create(conf)
	if err != nil {
		d.Fatal(err)
	}
	defer f.Close()
	if err := tmplSwayConfig.Execute(f, struct{ Width, Height int }{
		d.width, d.height,
	}); err != nil {
		d.Fatal(err)
	}

	d.socket = filepath.Join(dir, "socket")
	env = append(env, "SWAYSOCK="+d.socket)
	d.runtimeDir = dir
	env = append(env, "XDG_RUNTIME_DIR="+d.runtimeDir)

	var wg sync.WaitGroup
	d.Cleanup(wg.Wait)

	// First, start sway.
	{
		ctx, cancel := context.WithCancel(context.Background())
		cmd := exec.CommandContext(ctx, "sway", "--config", conf, "--verbose")
		cmd.Env = env
		stderr, err := cmd.StderrPipe()
		if err != nil {
			d.Fatal(err)
		}
		if err := cmd.Start(); err != nil {
			d.Fatal(err)
		}
		d.Cleanup(cancel)
		d.Cleanup(func() {
			// Give it a chance to exit gracefully, cleaning up
			// after itself. After 10ms, the deferred cancel above
			// will signal an os.Kill.
			cmd.Process.Signal(os.Interrupt)
			time.Sleep(10 * time.Millisecond)
		})

		// Wait for sway to be ready. We probably don't need a deadline
		// here.
		br := bufio.NewReader(stderr)
		for {
			line, err := br.ReadString('\n')
			if err != nil {
				d.Fatal(err)
			}
			if m := rxSwayReady.FindStringSubmatch(line); m != nil {
				d.display = m[1]
				break
			}
		}

		wg.Add(1)
		go func() {
			if err := cmd.Wait(); err != nil && ctx.Err() == nil && !strings.Contains(err.Error(), "interrupt") {
				// Don't print all stderr, since we use --verbose.
				// TODO(mvdan): if it's useful, probably filter
				// errors and show them.
				d.Error(err)
			}
			wg.Done()
		}()
	}

	// Then, start our program on the sway compositor above.
	{
		ctx, cancel := context.WithCancel(context.Background())
		cmd := exec.CommandContext(ctx, bin)
		cmd.Env = []string{"XDG_RUNTIME_DIR=" + d.runtimeDir, "WAYLAND_DISPLAY=" + d.display}
		output, err := cmd.StdoutPipe()
		if err != nil {
			d.Fatal(err)
		}
		cmd.Stderr = cmd.Stdout
		d.output = output
		if err := cmd.Start(); err != nil {
			d.Fatal(err)
		}
		d.Cleanup(cancel)
		wg.Add(1)
		go func() {
			if err := cmd.Wait(); err != nil && ctx.Err() == nil {
				d.Error(err)
			}
			wg.Done()
		}()
	}

	// Wait for the gio app to render.
	d.waitForFrame()
}

func (d *WaylandTestDriver) Screenshot() image.Image {
	cmd := exec.Command("grim", "/dev/stdout")
	cmd.Env = []string{"XDG_RUNTIME_DIR=" + d.runtimeDir, "WAYLAND_DISPLAY=" + d.display}
	out, err := cmd.CombinedOutput()
	if err != nil {
		d.Errorf("%s", out)
		d.Fatal(err)
	}
	img, err := png.Decode(bytes.NewReader(out))
	if err != nil {
		d.Fatal(err)
	}
	return img
}

func (d *WaylandTestDriver) swaymsg(args ...interface{}) {
	strs := []string{"--socket", d.socket}
	for _, arg := range args {
		strs = append(strs, fmt.Sprint(arg))
	}
	cmd := exec.Command("swaymsg", strs...)
	if out, err := cmd.CombinedOutput(); err != nil {
		d.Errorf("%s", out)
		d.Fatal(err)
	}
}

func (d *WaylandTestDriver) Click(x, y int) {
	d.swaymsg("seat", "-", "cursor", "set", x, y)
	d.swaymsg("seat", "-", "cursor", "press", "button1")
	d.swaymsg("seat", "-", "cursor", "release", "button1")

	// Wait for the gio app to render after this click.
	d.waitForFrame()
}