-
Notifications
You must be signed in to change notification settings - Fork 16
/
menu.go
292 lines (264 loc) · 7.5 KB
/
menu.go
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package main
import (
"errors"
"fmt"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"unicode"
"github.com/xyproto/vt100"
)
const konami = "↑↑↓↓←→←→ba"
var (
errNoLetter = errors.New("no letter")
smallWords = []string{"a", "and", "at", "by", "in", "is", "let", "of", "or", "the", "to"}
)
// RuneAndPosition is used to store a rune and a position within a string
type RuneAndPosition struct {
r rune
pos uint
}
// getLetter returns the Nth letter in a given string, as lowercase. Ignores numbers, special characters, whitespace etc.
func getLetter(s string, pos int) (rune, error) {
counter := 0
for _, letter := range s {
if unicode.IsLetter(letter) {
if counter == pos {
return unicode.ToLower(letter), nil
}
counter++
}
}
return rune(0), errNoLetter
}
// Check if the position pos points to a letter in a small word like "to", "at" or "the".
func inSmallWordOrSpace(s string, pos int) bool {
var (
stopAtNextSpace bool
wordRunes []rune
)
for i, r := range s {
if i == pos {
if r == ' ' {
// The given position is at a space
return true
}
// We have reached the target position, continue collecting letters of this word until the next space
stopAtNextSpace = true
}
if r == ' ' {
if stopAtNextSpace {
// Done collecting the current word
break
}
// Start collecting the next word
wordRunes = []rune{}
} else {
wordRunes = append(wordRunes, r)
}
}
word := strings.ToLower(string(wordRunes))
for _, smallWord := range smallWords {
if word == smallWord {
return true
}
}
return false
}
// selectionLetterForChoices loops through the choices and finds a unique letter (possibly the first one in the choice text),
// that can be used later for selecting that choice. The returned map maps from the letter to the choice index.
// choices where no appropriate letter were found are skipped. q is ignored, because it's reserved for "quit".
// Only the first N letters of each choice are considered.
func selectionLettersForChoices(choices []string) map[string]*RuneAndPosition {
// TODO: Find the next item starting with this letter, with wraparound
// Select the item that starts with this letter, if possible. Try the first, then the second, etc, up to N
N := 16
selectionLetterMap := make(map[string]*RuneAndPosition)
for choiceIndex, choiceString := range choices {
for pos := 0; pos < N; pos++ {
if pos >= len(choiceString) {
break
}
letter, err := getLetter(choiceString, pos)
if err != nil {
continue
}
// Check if this letter is already picked
exists := false
for _, v := range selectionLetterMap {
if v.r == letter {
exists = true
break
}
}
// If the letter is not already stored in the keymap, and it's not q,
// and it's not in a small word like "at" or "to"
if !exists && (letter != 'q') && !inSmallWordOrSpace(choiceString, pos) {
//fmt.Printf("Using %s [%d] for %s\n", string(letter), index, choice)
// Use this letter!
selectionLetterMap[choiceString] = &RuneAndPosition{letter, uint(choiceIndex)}
// Found a letter for this choice, move on
break
}
}
// Did not find a letter for this choice, move on
}
return selectionLetterMap
}
// Menu starts a loop where keypresses are handled. When a choice is made, a number is returned.
// -1 is "no choice", 0 and up is which choice were selected.
// initialMenuIndex is the choice that should be highlighted when displaying the choices.
func (e *Editor) Menu(status *StatusBar, tty *vt100.TTY, title string, choices []string, bgColor, titleColor, arrowColor, textColor, highlightColor, selectedColor vt100.AttributeColor, initialMenuIndex int, extraDashes bool) int {
// Clear the existing handler
signal.Reset(syscall.SIGWINCH)
var (
selectionLetterMap = selectionLettersForChoices(choices)
selectedDelay = 100 * time.Millisecond
c = vt100.NewCanvas()
menu = NewMenuWidget(title, choices, titleColor, arrowColor, textColor, highlightColor, selectedColor, c.W(), c.H(), extraDashes, selectionLetterMap)
sigChan = make(chan os.Signal, 1)
running = true
changed = true
)
// Set up a new resize handler
signal.Notify(sigChan, syscall.SIGWINCH)
go func() {
for range sigChan {
resizeMut.Lock()
// Create a new canvas, with the new size
nc := c.Resized()
if nc != nil {
vt100.Clear()
c = nc
menu.Draw(c)
c.Redraw()
changed = true
}
// Inform all elements that the terminal was resized
resizeMut.Unlock()
}
}()
vt100.Clear()
vt100.Reset()
c.FillBackground(bgColor)
c.Redraw()
// Set the initial menu index
menu.SelectIndex(uint(initialMenuIndex))
var collectedString string
for running {
// Draw elements in their new positions
if changed {
resizeMut.RLock()
menu.Draw(c)
resizeMut.RUnlock()
// Update the canvas
c.Draw()
}
// Handle events
key := tty.String()
switch key {
case "↑", "←", "c:16": // Up, left or ctrl-p
resizeMut.Lock()
menu.Up(c)
changed = true
resizeMut.Unlock()
case "↓", "→", "c:14": // Down, right or ctrl-n
resizeMut.Lock()
menu.Down(c)
changed = true
resizeMut.Unlock()
case "c:1": // Top, ctrl-a
resizeMut.Lock()
menu.SelectFirst()
changed = true
resizeMut.Unlock()
case "c:5": // Bottom, ctrl-e
resizeMut.Lock()
menu.SelectLast()
changed = true
resizeMut.Unlock()
case "c:27", "q", "c:3", "c:17", "c:15": // ESC, q, ctrl-c, ctrl-q or ctrl-o
running = false
changed = true
case " ", "c:13": // Space or Return
resizeMut.Lock()
menu.Select()
resizeMut.Unlock()
running = false
changed = true
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9": // 0 .. 9
number, err := strconv.Atoi(key)
if err != nil {
break
}
resizeMut.Lock()
menu.SelectIndex(uint(number))
changed = true
resizeMut.Unlock()
default:
if len([]rune(key)) == 0 {
// this happens if pgup or pgdn is pressed
break
}
// Check if the key matches the first letter (A-Z, a-z) in the choices
r := []rune(key)[0]
if !(65 <= r && r <= 90) && !(97 <= r && r <= 122) {
break
}
// Choose the index for the letter that was pressed and found in the keymap, if found
for _, runeAndPosition := range selectionLetterMap {
if r == runeAndPosition.r {
resizeMut.Lock()
menu.SelectIndex(runeAndPosition.pos)
changed = true
resizeMut.Unlock()
}
}
}
// Konami code collector
if len([]rune(key)) == 1 {
collectedString += key
// pop a letter in front of the collected string if it's too long
if len(collectedString) > len(konami) {
runes := []rune(collectedString)
collectedString = string(runes[1:])
}
}
// Was it the konami code?
if collectedString == konami {
collectedString = ""
// Start the game
if ctrlq, err := Game(); err != nil {
// This should never happen
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
} else if ctrlq {
// ctrl-q was pressed, quit entirely
running = false
e.quit = true
} else {
// The game ended, return from the menu
running = false
changed = true
}
}
// If the menu was changed, draw the canvas
if changed {
c.Draw()
}
}
if menu.Selected() >= 0 {
// Draw the selected item in a different color for a very short while
resizeMut.Lock()
menu.SelectDraw(c)
resizeMut.Unlock()
c.Draw()
time.Sleep(selectedDelay)
}
// Restore the resize handler
e.SetUpSignalHandlers(c, tty, status)
return menu.Selected()
}