File: input.go

package info (click to toggle)
peco 0.5.10-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 548 kB
  • sloc: makefile: 95
file content (87 lines) | stat: -rw-r--r-- 1,805 bytes parent folder | download
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
package peco

import (
	"time"

	"context"

	"github.com/lestrrat-go/pdebug"
	"github.com/nsf/termbox-go"
)

func NewInput(state *Peco, am ActionMap, src chan termbox.Event) *Input {
	return &Input{
		actions: am,
		evsrc:   src,
		state:   state,
	}
}

func (i *Input) Loop(ctx context.Context, cancel func()) error {
	defer cancel()

	for {
		select {
		case <-ctx.Done():
			return nil
		case ev := <-i.evsrc:
			if err := i.handleInputEvent(ctx, ev); err != nil {
				return nil
			}
		}
	}
}

func (i *Input) handleInputEvent(ctx context.Context, ev termbox.Event) error {
	if pdebug.Enabled {
		g := pdebug.Marker("event received from user: %#v", ev)
		defer g.End()
	}

	switch ev.Type {
	case termbox.EventError:
		return nil
	case termbox.EventResize:
		i.state.Hub().SendDraw(ctx, nil)
		return nil
	case termbox.EventKey:
		// ModAlt is a sequence of letters with a leading \x1b (=Esc).
		// It would be nice if termbox differentiated this for us, but
		// we workaround it by waiting (juuuust a few milliseconds) for
		// extra key events. If no extra events arrive, it should be Esc

		m := &i.mutex

		// Smells like Esc or Alt. mod == nil checks for the presence
		// of a previous timer
		m.Lock()
		if ev.Ch == 0 && ev.Key == 27 && i.mod == nil {
			tmp := ev
			i.mod = time.AfterFunc(50*time.Millisecond, func() {
				m.Lock()
				i.mod = nil
				m.Unlock()
				i.state.Keymap().ExecuteAction(ctx, i.state, tmp)
			})
			m.Unlock()
			return nil
		}
		m.Unlock()

		// it doesn't look like this is Esc or Alt. If we have a previous
		// timer, stop it because this is probably Alt+ this new key
		m.Lock()
		if i.mod != nil {
			i.mod.Stop()
			i.mod = nil
			ev.Mod |= termbox.ModAlt
		}
		m.Unlock()

		i.state.Keymap().ExecuteAction(ctx, i.state, ev)

		return nil
	}

	return nil
}