File: runereader.go

package info (click to toggle)
golang-github-alecaivazis-survey 2.3.6%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-backports
  • size: 636 kB
  • sloc: makefile: 12
file content (386 lines) | stat: -rw-r--r-- 10,603 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
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package terminal

import (
	"fmt"
	"unicode"

	"golang.org/x/text/width"
)

type RuneReader struct {
	stdio Stdio
	state runeReaderState
}

func NewRuneReader(stdio Stdio) *RuneReader {
	return &RuneReader{
		stdio: stdio,
		state: newRuneReaderState(stdio.In),
	}
}

func (rr *RuneReader) printChar(char rune, mask rune) error {
	// if we don't need to mask the input
	if mask == 0 {
		// just print the character the user pressed
		_, err := fmt.Fprintf(rr.stdio.Out, "%c", char)
		return err
	}
	// otherwise print the mask we were given
	_, err := fmt.Fprintf(rr.stdio.Out, "%c", mask)
	return err
}

type OnRuneFn func(rune, []rune) ([]rune, bool, error)

func (rr *RuneReader) ReadLine(mask rune, onRunes ...OnRuneFn) ([]rune, error) {
	return rr.ReadLineWithDefault(mask, []rune{}, onRunes...)
}

func (rr *RuneReader) ReadLineWithDefault(mask rune, d []rune, onRunes ...OnRuneFn) ([]rune, error) {
	line := []rune{}
	// we only care about horizontal displacements from the origin so start counting at 0
	index := 0

	cursor := &Cursor{
		In:  rr.stdio.In,
		Out: rr.stdio.Out,
	}

	onRune := func(r rune, line []rune) ([]rune, bool, error) {
		return line, false, nil
	}

	// if the user pressed a key the caller was interested in capturing
	if len(onRunes) > 0 {
		onRune = onRunes[0]
	}

	// we get the terminal width and height (if resized after this point the property might become invalid)
	terminalSize, _ := cursor.Size(rr.Buffer())
	// we set the current location of the cursor once
	cursorCurrent, _ := cursor.Location(rr.Buffer())

	increment := func() {
		if cursorCurrent.CursorIsAtLineEnd(terminalSize) {
			cursorCurrent.X = COORDINATE_SYSTEM_BEGIN
			cursorCurrent.Y++
		} else {
			cursorCurrent.X++
		}
	}
	decrement := func() {
		if cursorCurrent.CursorIsAtLineBegin() {
			cursorCurrent.X = terminalSize.X
			cursorCurrent.Y--
		} else {
			cursorCurrent.X--
		}
	}

	if len(d) > 0 {
		index = len(d)
		if _, err := fmt.Fprint(rr.stdio.Out, string(d)); err != nil {
			return d, err
		}
		line = d
		for range d {
			increment()
		}
	}

	for {
		// wait for some input
		r, _, err := rr.ReadRune()
		if err != nil {
			return line, err
		}

		if l, stop, err := onRune(r, line); stop || err != nil {
			return l, err
		}

		// if the user pressed enter or some other newline/termination like ctrl+d
		if r == '\r' || r == '\n' || r == KeyEndTransmission {
			// delete what's printed out on the console screen (cleanup)
			for index > 0 {
				if cursorCurrent.CursorIsAtLineBegin() {
					EraseLine(rr.stdio.Out, ERASE_LINE_END)
					cursor.PreviousLine(1)
					cursor.Forward(int(terminalSize.X))
				} else {
					cursor.Back(1)
				}
				decrement()
				index--
			}
			// move the cursor the a new line
			cursor.MoveNextLine(cursorCurrent, terminalSize)

			// we're done processing the input
			return line, nil
		}
		// if the user interrupts (ie with ctrl+c)
		if r == KeyInterrupt {
			// go to the beginning of the next line
			if _, err := fmt.Fprint(rr.stdio.Out, "\r\n"); err != nil {
				return line, err
			}

			// we're done processing the input, and treat interrupt like an error
			return line, InterruptErr
		}

		// allow for backspace/delete editing of inputs
		if r == KeyBackspace || r == KeyDelete {
			// and we're not at the beginning of the line
			if index > 0 && len(line) > 0 {
				// if we are at the end of the word
				if index == len(line) {
					// just remove the last letter from the internal representation
					// also count the number of cells the rune before the cursor occupied
					cells := runeWidth(line[len(line)-1])
					line = line[:len(line)-1]
					// go back one
					if cursorCurrent.X == 1 {
						cursor.PreviousLine(1)
						cursor.Forward(int(terminalSize.X))
					} else {
						cursor.Back(cells)
					}

					// clear the rest of the line
					EraseLine(rr.stdio.Out, ERASE_LINE_END)
				} else {
					// we need to remove a character from the middle of the word

					cells := runeWidth(line[index-1])

					// remove the current index from the list
					line = append(line[:index-1], line[index:]...)

					// save the current position of the cursor, as we have to move the cursor one back to erase the current symbol
					// and then move the cursor for each symbol in line[index-1:] to print it out, afterwards we want to restore
					// the cursor to its previous location.
					cursor.Save()

					// clear the rest of the line
					cursor.Back(cells)

					// print what comes after
					for _, char := range line[index-1:] {
						//Erase symbols which are left over from older print
						EraseLine(rr.stdio.Out, ERASE_LINE_END)
						// print characters to the new line appropriately
						if err := rr.printChar(char, mask); err != nil {
							return line, err
						}
					}
					// erase what's left over from last print
					if cursorCurrent.Y < terminalSize.Y {
						cursor.NextLine(1)
						EraseLine(rr.stdio.Out, ERASE_LINE_END)
					}
					// restore cursor
					cursor.Restore()
					if cursorCurrent.CursorIsAtLineBegin() {
						cursor.PreviousLine(1)
						cursor.Forward(int(terminalSize.X))
					} else {
						cursor.Back(cells)
					}
				}

				// decrement the index
				index--
				decrement()
			} else {
				// otherwise the user pressed backspace while at the beginning of the line
				_ = soundBell(rr.stdio.Out)
			}

			// we're done processing this key
			continue
		}

		// if the left arrow is pressed
		if r == KeyArrowLeft {
			// if we have space to the left
			if index > 0 {
				//move the cursor to the prev line if necessary
				if cursorCurrent.CursorIsAtLineBegin() {
					cursor.PreviousLine(1)
					cursor.Forward(int(terminalSize.X))
				} else {
					cursor.Back(runeWidth(line[index-1]))
				}
				//decrement the index
				index--
				decrement()

			} else {
				// otherwise we are at the beginning of where we started reading lines
				// sound the bell
				_ = soundBell(rr.stdio.Out)
			}

			// we're done processing this key press
			continue
		}

		// if the right arrow is pressed
		if r == KeyArrowRight {
			// if we have space to the right
			if index < len(line) {
				// move the cursor to the next line if necessary
				if cursorCurrent.CursorIsAtLineEnd(terminalSize) {
					cursor.NextLine(1)
				} else {
					cursor.Forward(runeWidth(line[index]))
				}
				index++
				increment()

			} else {
				// otherwise we are at the end of the word and can't go past
				// sound the bell
				_ = soundBell(rr.stdio.Out)
			}

			// we're done processing this key press
			continue
		}
		// the user pressed one of the special keys
		if r == SpecialKeyHome {
			for index > 0 {
				if cursorCurrent.CursorIsAtLineBegin() {
					cursor.PreviousLine(1)
					cursor.Forward(int(terminalSize.X))
					cursorCurrent.Y--
					cursorCurrent.X = terminalSize.X
				} else {
					cursor.Back(runeWidth(line[index-1]))
					cursorCurrent.X -= Short(runeWidth(line[index-1]))
				}
				index--
			}
			continue
			// user pressed end
		} else if r == SpecialKeyEnd {
			for index != len(line) {
				if cursorCurrent.CursorIsAtLineEnd(terminalSize) {
					cursor.NextLine(1)
					cursorCurrent.Y++
					cursorCurrent.X = COORDINATE_SYSTEM_BEGIN
				} else {
					cursor.Forward(runeWidth(line[index]))
					cursorCurrent.X += Short(runeWidth(line[index]))
				}
				index++
			}
			continue
			// user pressed forward delete key
		} else if r == SpecialKeyDelete {
			// if index at the end of the line nothing to delete
			if index != len(line) {
				// save the current position of the cursor, as we have to  erase the current symbol
				// and then move the cursor for each symbol in line[index:] to print it out, afterwards we want to restore
				// the cursor to its previous location.
				cursor.Save()
				// remove the symbol after the cursor
				line = append(line[:index], line[index+1:]...)
				// print the updated line
				for _, char := range line[index:] {
					EraseLine(rr.stdio.Out, ERASE_LINE_END)
					// print out the character
					if err := rr.printChar(char, mask); err != nil {
						return line, err
					}
				}
				// erase what's left on last line
				if cursorCurrent.Y < terminalSize.Y {
					cursor.NextLine(1)
					EraseLine(rr.stdio.Out, ERASE_LINE_END)
				}
				// restore cursor
				cursor.Restore()
				if len(line) == 0 || index == len(line) {
					EraseLine(rr.stdio.Out, ERASE_LINE_END)
				}
			}
			continue
		}

		// if the letter is another escape sequence
		if unicode.IsControl(r) || r == IgnoreKey {
			// ignore it
			continue
		}

		// the user pressed a regular key

		// if we are at the end of the line
		if index == len(line) {
			// just append the character at the end of the line
			line = append(line, r)
			// save the location of the cursor
			index++
			increment()
			// print out the character
			if err := rr.printChar(r, mask); err != nil {
				return line, err
			}
		} else {
			// we are in the middle of the word so we need to insert the character the user pressed
			line = append(line[:index], append([]rune{r}, line[index:]...)...)
			// save the current position of the cursor, as we have to move the cursor back to erase the current symbol
			// and then move for each symbol in line[index:] to print it out, afterwards we want to restore
			// cursor's location to its previous one.
			cursor.Save()
			EraseLine(rr.stdio.Out, ERASE_LINE_END)
			// remove the symbol after the cursor
			// print the updated line
			for _, char := range line[index:] {
				EraseLine(rr.stdio.Out, ERASE_LINE_END)
				// print out the character
				if err := rr.printChar(char, mask); err != nil {
					return line, err
				}
				increment()
			}
			// if we are at the last line, we want to visually insert a new line and append to it.
			if cursorCurrent.CursorIsAtLineEnd(terminalSize) && cursorCurrent.Y == terminalSize.Y {
				// add a new line to the terminal
				if _, err := fmt.Fprintln(rr.stdio.Out); err != nil {
					return line, err
				}
				// restore the position of the cursor horizontally
				cursor.Restore()
				// restore the position of the cursor vertically
				cursor.PreviousLine(1)
			} else {
				// restore cursor
				cursor.Restore()
			}
			// check if cursor needs to move to next line
			cursorCurrent, _ = cursor.Location(rr.Buffer())
			if cursorCurrent.CursorIsAtLineEnd(terminalSize) {
				cursor.NextLine(1)
			} else {
				cursor.Forward(runeWidth(r))
			}
			// increment the index
			index++
			increment()

		}
	}
}

func runeWidth(r rune) int {
	switch width.LookupRune(r).Kind() {
	case width.EastAsianWide, width.EastAsianFullwidth:
		return 2
	}
	return 1
}