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							tx, ty := o.ToTarget(x, y)
165							moveCursor(o.Info.Name, tx, ty)
166						}
167						if err := sendPointer(ports.PointerMotion{X: x, Y: y, TimeMsec: now}); err != nil {
168							return err
169						}
170						continue
171					}
172				}
173				warnInput("line", line, "invalid move")
174				continue
175			}
176			if len(fields) > 0 && (fields[0] == "swipe" || fields[0] == "swipe4") {
177				dirs := map[string][2]float64{"up": {0, -1}, "down": {0, 1}, "left": {-1, 0}, "right": {1, 0}}
178				d, ok := [2]float64{}, len(fields) == 2
179				if ok {
180					d, ok = dirs[fields[1]]
181				}
182				if !ok {
183					warnInput("line", line, "invalid swipe")
184					continue
185				}
186				fingers := 3
187				if fields[0] == "swipe4" {
188					fingers = 4
189				}
190				for _, ev := range swipeEvents(fingers, d[0], d[1], monotonic()) {
191					if err := sendPointer(ev); err != nil {
192						return err
193					}
194				}
195				continue
196			}
197			if len(fields) > 0 && (fields[0] == "click" || fields[0] == "down" || fields[0] == "up") {
198				name := "left"
199				if len(fields) == 2 {
200					name = fields[1]
201				}
202				code := buttonCode(name)
203				if len(fields) > 2 || (len(fields) != 2 && fields[0] != "click") || code == 0 {
204					warnInput("line", line, "invalid button")
205					continue
206				}
207				if fields[0] != "up" {
208					if err := sendPointer(ports.PointerButton{Button: code, Pressed: true, TimeMsec: now}); err != nil {
209						return err
210					}
211				}
212				if fields[0] != "down" {
213					if err := sendPointer(ports.PointerButton{Button: code, TimeMsec: now}); err != nil {
214						return err
215					}
216				}
217				continue
218			}
219			switch {
220			case strings.HasPrefix(line, "type "):
221				for _, r := range strings.TrimPrefix(line, "type ") {
222					name := punctuation[r]
223					if name == "" && (unicode.IsLetter(r) || unicode.IsDigit(r)) {
224						name = string(r)
225					}
226					if name == "" {
227						warnInput("rune", string(r), "unknown rune")
228						continue
229					}
230					if err := stroke(name, nil); err != nil {
231						return err
232					}
233				}
234			case strings.HasPrefix(line, "key "):
235				parts := strings.Split(strings.TrimPrefix(line, "key "), "+")
236				var mods []uint32
237				valid := true
238				for _, part := range parts[:len(parts)-1] {
239					switch part {
240					case "Super":
241						mods = append(mods, 125)
242					case "Shift":
243						mods = append(mods, 42)
244					case "Ctrl":
245						mods = append(mods, 29)
246					case "Alt":
247						mods = append(mods, 56)
248					default:
249						valid = false
250					}
251				}
252				if !valid {
253					warnInput("combo", line, "unknown modifier")
254					continue
255				}
256				if err := stroke(parts[len(parts)-1], mods); err != nil {
257					return err
258				}
259			case strings.HasPrefix(line, "sleep "):
260				d, err := time.ParseDuration(strings.TrimPrefix(line, "sleep "))
261				if err != nil || d < 0 {
262					warnInput("line", line, "invalid sleep")
263					continue
264				}
265				timer := time.NewTimer(d)
266				select {
267				case <-ctx.Done():
268					timer.Stop()
269					return ctx.Err()
270				case <-timer.C:
271				}
272			default:
273				warnInput("line", line, "unknown script line")
274			}
275		}
276	}
277}

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