v0.2.0 13c6a90

input.go RawHistoryFolder

1// Package headlessinput converts scripted text into keyboard events.
2package headlessinput
3
4import (
5	"context"
6	"math"
7	"strconv"
8	"strings"
9	"time"
10	"unicode"
11
12	"github.com/bnema/neferwl/internal/adapters/xkb"
13	"github.com/bnema/neferwl/internal/ports"
14	"github.com/bnema/zerowrap"
15)
16
17// Run owns the keymap and converts script lines into input events. A keymap
18// received on keymaps replaces the current one, which is closed. Scripted
19// moves are global logical coordinates; moveCursor, when set, places the
20// software cursor of the output under them (physical position on it), using
21// the latest layout from layouts.
22func Run(ctx context.Context, km *xkb.Keymap, keymaps <-chan *xkb.Keymap, script <-chan string, input chan<- ports.InputEvent, layouts <-chan ports.Layout, moveCursor func(output string, x, y float64), log zerowrap.Logger) error {
23	return RunSecure(ctx, km, keymaps, script, input, layouts, moveCursor, log, nil)
24}
25
26// RunSecure snapshots the protection epoch before each event enters the input
27// queue. Scripts are a headless test transport, never an unlock authority.
28func RunSecure(ctx context.Context, km *xkb.Keymap, keymaps <-chan *xkb.Keymap, script <-chan string, input chan<- ports.InputEvent, layouts <-chan ports.Layout, moveCursor func(output string, x, y float64), log zerowrap.Logger, security ports.SessionSecurity) error {
29	snapshot := func() ports.SecurityState {
30		if security != nil {
31			return security.Snapshot()
32		}
33		return ports.SecurityState{}
34	}
35	stamp := func(ev ports.InputEvent, state ports.SecurityState) ports.InputEvent {
36		if security == nil {
37			return ev
38		}
39		return ports.SecurityInput{State: state, Event: ev}
40	}
41	// Script payloads can contain credentials even when parsing fails. Keep a
42	// useful generic warning while protected, never input-derived fields.
43	warnInput := func(field, value, message string) {
44		entry := log.Warn()
45		if snapshot().Protected {
46			entry.Msg("invalid script input")
47			return
48		}
49		entry.Str(field, value).Msg(message)
50	}
51	var layout ports.Layout
52	defer func() { km.Close() }()
53	emit := func(code uint32, down bool) error {
54		state := snapshot()
55		var key ports.KeyEvent
56		if security != nil {
57			var deliver bool
58			var err error
59			key, deliver, err = km.KeySecure(code, down, msec(monotonic()), state)
60			if err != nil {
61				return err
62			}
63			if !deliver {
64				return nil
65			}
66		} else {
67			key = km.Key(code, down, msec(monotonic()))
68		}
69		ev := stamp(key, state)
70		select {
71		case <-ctx.Done():
72			return ctx.Err()
73		case input <- ev:
74		}
75		timer := time.NewTimer(2 * time.Millisecond)
76		defer timer.Stop()
77		select {
78		case <-ctx.Done():
79			return ctx.Err()
80		case <-timer.C:
81			return nil
82		}
83	}
84	stroke := func(name string, mods []uint32) error {
85		code, shift, ok := km.KeycodeFor(name)
86		if !ok {
87			warnInput("key", name, "unknown key")
88			return nil
89		}
90		if shift {
91			found := false
92			for _, m := range mods {
93				if m == 42 || m == 54 {
94					found = true
95				}
96			}
97			if !found {
98				mods = append(mods, 42)
99			}
100		}
101		for _, m := range mods {
102			if err := emit(m, true); err != nil {
103				return err
104			}
105		}
106		if err := emit(code, true); err != nil {
107			return err
108		}
109		if err := emit(code, false); err != nil {
110			return err
111		}
112		for i := len(mods) - 1; i >= 0; i-- {
113			if err := emit(mods[i], false); err != nil {
114				return err
115			}
116		}
117		return nil
118	}
119	punctuation := map[rune]string{' ': "space", '\n': "Return", '.': "period", ',': "comma", '-': "minus", '_': "underscore", '/': "slash", ':': "colon", ';': "semicolon", '!': "exclam", '?': "question", '\'': "apostrophe", '"': "quotedbl", '(': "parenleft", ')': "parenright", '=': "equal", '+': "plus", '\\': "backslash", '@': "at", '#': "numbersign", '$': "dollar", '%': "percent", '&': "ampersand", '*': "asterisk", '[': "bracketleft", ']': "bracketright", '{': "braceleft", '}': "braceright", '<': "less", '>': "greater", '|': "bar", '`': "grave", '~': "asciitilde", '^': "asciicircum"}
120	for {
121		select {
122		case <-ctx.Done():
123			return ctx.Err()
124		case next := <-keymaps:
125			if security != nil {
126				next.QuarantineFrom(km)
127			}
128			km.Close()
129			km = next
130			log.Info().Msg("keymap replaced")
131		case layout = <-layouts:
132		case line, ok := <-script:
133			if !ok {
134				return nil
135			}
136			fields := strings.Fields(line)
137			sendPointer := func(ev ports.InputEvent) error {
138				ev = stamp(ev, snapshot())
139				select {
140				case <-ctx.Done():
141					return ctx.Err()
142				case input <- ev:
143					return nil
144				}
145			}
146			buttonCode := func(name string) uint32 {
147				switch name {
148				case "left":
149					return 0x110
150				case "right":
151					return 0x111
152				case "middle":
153					return 0x112
154				}
155				return 0
156			}
157			now := msec(monotonic())
158			if len(fields) > 0 && fields[0] == "move" {
159				if len(fields) == 3 {
160					x, ex := strconv.ParseFloat(fields[1], 64)
161					y, ey := strconv.ParseFloat(fields[2], 64)
162					if ex == nil && ey == nil && !math.IsNaN(x) && !math.IsNaN(y) && !math.IsInf(x, 0) && !math.IsInf(y, 0) {
163						if o, ok := layout.At(x, y); ok && moveCursor != nil {
164							moveCursor(o.Info.Name, (x-float64(o.X))*o.Scale, (y-float64(o.Y))*o.Scale)
165						}
166						if err := sendPointer(ports.PointerMotion{X: x, Y: y, TimeMsec: now}); err != nil {
167							return err
168						}
169						continue
170					}
171				}
172				warnInput("line", line, "invalid move")
173				continue
174			}
175			if len(fields) > 0 && (fields[0] == "swipe" || fields[0] == "swipe4") {
176				dirs := map[string][2]float64{"up": {0, -1}, "down": {0, 1}, "left": {-1, 0}, "right": {1, 0}}
177				d, ok := [2]float64{}, len(fields) == 2
178				if ok {
179					d, ok = dirs[fields[1]]
180				}
181				if !ok {
182					warnInput("line", line, "invalid swipe")
183					continue
184				}
185				fingers := 3
186				if fields[0] == "swipe4" {
187					fingers = 4
188				}
189				for _, ev := range swipeEvents(fingers, d[0], d[1], monotonic()) {
190					if err := sendPointer(ev); err != nil {
191						return err
192					}
193				}
194				continue
195			}
196			if len(fields) > 0 && (fields[0] == "click" || fields[0] == "down" || fields[0] == "up") {
197				name := "left"
198				if len(fields) == 2 {
199					name = fields[1]
200				}
201				code := buttonCode(name)
202				if len(fields) > 2 || (len(fields) != 2 && fields[0] != "click") || code == 0 {
203					warnInput("line", line, "invalid button")
204					continue
205				}
206				if fields[0] != "up" {
207					if err := sendPointer(ports.PointerButton{Button: code, Pressed: true, TimeMsec: now}); err != nil {
208						return err
209					}
210				}
211				if fields[0] != "down" {
212					if err := sendPointer(ports.PointerButton{Button: code, TimeMsec: now}); err != nil {
213						return err
214					}
215				}
216				continue
217			}
218			switch {
219			case strings.HasPrefix(line, "type "):
220				for _, r := range strings.TrimPrefix(line, "type ") {
221					name := punctuation[r]
222					if name == "" && (unicode.IsLetter(r) || unicode.IsDigit(r)) {
223						name = string(r)
224					}
225					if name == "" {
226						warnInput("rune", string(r), "unknown rune")
227						continue
228					}
229					if err := stroke(name, nil); err != nil {
230						return err
231					}
232				}
233			case strings.HasPrefix(line, "key "):
234				parts := strings.Split(strings.TrimPrefix(line, "key "), "+")
235				var mods []uint32
236				valid := true
237				for _, part := range parts[:len(parts)-1] {
238					switch part {
239					case "Super":
240						mods = append(mods, 125)
241					case "Shift":
242						mods = append(mods, 42)
243					case "Ctrl":
244						mods = append(mods, 29)
245					case "Alt":
246						mods = append(mods, 56)
247					default:
248						valid = false
249					}
250				}
251				if !valid {
252					warnInput("combo", line, "unknown modifier")
253					continue
254				}
255				if err := stroke(parts[len(parts)-1], mods); err != nil {
256					return err
257				}
258			case strings.HasPrefix(line, "sleep "):
259				d, err := time.ParseDuration(strings.TrimPrefix(line, "sleep "))
260				if err != nil || d < 0 {
261					warnInput("line", line, "invalid sleep")
262					continue
263				}
264				timer := time.NewTimer(d)
265				select {
266				case <-ctx.Done():
267					timer.Stop()
268					return ctx.Err()
269				case <-timer.C:
270				}
271			default:
272				warnInput("line", line, "unknown script line")
273			}
274		}
275	}
276}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 25

Tags 10

↑↓ moveenter openesc close