summaryrefslogtreecommitdiff
path: root/src/ui_readline.c
blob: 12f4ac87220e68e923e830dc0fe2370341b4b447 (plain)
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
/*
Copyright (c) 2008-2014
	Lars-Dominik Braun <lars@6xq.net>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

//#include <stdlib.h>
//#include <stdio.h>
//#include <string.h>
//#include <unistd.h>
//#include <assert.h>

#include "ui_readline.h"
#include "console.h"
#include <stdio.h>
#include <assert.h>

static inline char* BarReadlineNextUtf8 (char* ptr) {
    if ((*ptr & 0x80) == 0)
        return ptr + 1;
    else if ((*ptr & 0xE0) == 0xC0)
        return ptr + 2;
    else if ((*ptr & 0xF0) == 0xE0)
        return ptr + 3;
    else if ((*ptr & 0xF8) == 0xF0)
        return ptr + 4;
    else
        return ptr;
}

static inline char* BarReadlinePriorUtf8 (char* ptr) {
    while ((*(--ptr) & 0xC0) == 0x80)
        /*continue*/;

    return ptr;
}

static inline int BarReadlineEncodeUtf8 (int codePoint, char* utf8) {
    if (codePoint < 0x80) {
        utf8[0] = (char)codePoint;
        return 1;
    }
    else if (codePoint < 0x0800) {
        utf8[0] = (char)(0xC0 | ((codePoint >> 6) & 0x1F));
        utf8[1] = (char)(0x80 | ((codePoint >> 0) & 0x3F));
        return 2;
    }
    else if (codePoint < 0x10000) {
        utf8[0] = (char)(0xE0 | ((codePoint >> 12) & 0x0F));
        utf8[1] = (char)(0x80 | ((codePoint >>  6) & 0x3F));
        utf8[2] = (char)(0x80 | ((codePoint >>  0) & 0x3F));
        return 3;
    }
    else if (codePoint < 0x110000) {
        utf8[0] = (char)(0xF0 | ((codePoint >> 18) & 0x07));
        utf8[1] = (char)(0x80 | ((codePoint >> 12) & 0x3F));
        utf8[2] = (char)(0x80 | ((codePoint >>  6) & 0x3F));
        utf8[2] = (char)(0x80 | ((codePoint >>  0) & 0x3F));
        return 4;
    }
    else
        return 0;
}

struct _BarReadline_t {
	DWORD  DefaultAttr;
};

void BarReadlineInit(BarReadline_t* rl) {
	static struct _BarReadline_t instance;
	*rl = &instance;
}

void BarReadlineDestroy(BarReadline_t rl) {
}

/*	return size of previous UTF-8 character
 */
static size_t BarReadlinePrevUtf8 (char *ptr) {
	size_t i = 0;

	do {
		++i;
		--ptr;
	} while ((*ptr & (1 << 7)) && !(*ptr & (1 << 6)));

	return i;
}

/*	readline replacement
 *	@param buffer
 *	@param buffer size
 *	@param accept these characters
 *	@param readline
 *	@param flags
 *	@param timeout (seconds) or -1 (no timeout)
 *	@return number of bytes read from stdin
 */
size_t BarReadline (char *buf, const size_t bufSize, const char *mask,
		BarReadline_t input, const BarReadlineFlags_t flags, int timeout) {
	HANDLE handle = BarConsoleGetStdIn();
	DWORD timeStamp, waitResult;
	int bufPos = 0, bufLen = 0;
	char* bufOut = buf;

	const bool overflow = flags & BAR_RL_FULLRETURN;
	const bool echo     = !(flags & BAR_RL_NOECHO);

	assert(buf != NULL);
	assert(bufSize > 0);
	assert(input != NULL);

	memset(buf, 0, bufSize);

	if (timeout != INFINITE) {
		// convert timeout to ms
		timeout *= 1000;

		// get time stamp, required for simulating non-locking input timeouts
		timeStamp = GetTickCount();
	}
	else
		timeStamp = 0;

	while (true) {
		if (timeout != INFINITE) {
			DWORD now = GetTickCount();
			if ((int)(now - timeStamp) < timeout) {
				timeout -= (int)(now - timeStamp);
				timeStamp = now;
			}
			else
				timeout = 0;
		}

		waitResult = WaitForSingleObject(handle, timeout);

		if (WAIT_OBJECT_0 == waitResult) {
			INPUT_RECORD inputRecords[8];
			INPUT_RECORD* record;
			DWORD recordsRead, i;

			ReadConsoleInput(handle, inputRecords, sizeof(inputRecords) / sizeof(*inputRecords), &recordsRead);

			for (i = 0, record = inputRecords; i < recordsRead; ++i, ++record)
			{
				int codePoint, keyCode;

				if ((record->EventType != KEY_EVENT) || !record->Event.KeyEvent.bKeyDown)
					continue;

				keyCode   = record->Event.KeyEvent.wVirtualKeyCode;
				codePoint = record->Event.KeyEvent.uChar.UnicodeChar;

				switch (keyCode) {
					case VK_LEFT:
						if (bufPos > 0)
						{
							if (echo) {
								BarConsoleMoveCursor(-1);
							}
							bufOut = BarReadlinePriorUtf8(bufOut);
							--bufPos;
						}
						break;

					case VK_RIGHT:
						if (bufPos < bufLen)
						{
							if (echo) {
								BarConsoleMoveCursor(1);
							}
							bufOut = BarReadlineNextUtf8(bufOut);
							++bufPos;
						}
						break;

					case VK_HOME:
						if (echo) {
							BarConsoleMoveCursor(-bufPos);
						}
						bufPos = 0;
						bufOut = buf;
						break;

					case VK_END:
						if (echo) {
							BarConsoleMoveCursor(bufLen - bufPos);
						}
						bufPos = bufLen;
						bufOut = buf + strlen(buf);
						break;

					case VK_BACK:
						if (bufPos > 0) {
							int moveSize;

							char* oldBufOut = bufOut;
							bufOut = BarReadlinePriorUtf8(bufOut);
							moveSize = strlen(bufOut) - (oldBufOut - bufOut);
							memmove(bufOut, oldBufOut, moveSize);
							bufOut[moveSize] = '\0';

							if (echo) {
								BarConsoleMoveCursor(-1);
								BarConsoleEraseCharacter();
							}

							--bufPos;
							--bufLen;
						}
						break;

					case VK_DELETE:
						if (bufPos < bufLen) {
							int moveSize;

							if (echo) {
								BarConsoleEraseCharacter();
							}

							char* nextCharOut = BarReadlineNextUtf8(bufOut);
							moveSize = strlen(bufOut) - (bufOut - nextCharOut);
							memmove(bufOut, nextCharOut, moveSize);
							bufOut[moveSize] = '\0';

							--bufLen;
						}
						break;

					case VK_RETURN:
						if (echo)
							fputc('\n', stdout);
						return bufLen;

					default: {
							char encodedCodePoint[5];
							int encodedCodePointLength;

							/*
							if (keyCode == VK_MEDIA_PLAY_PAUSE) {
							codePoint = 'p';
							PlaySoundA("SystemNotification", NULL, SND_ASYNC);
							}
							else if (keyCode == VK_MEDIA_NEXT_TRACK) {
							codePoint = 'n';
							PlaySoundA("SystemNotification", NULL, SND_ASYNC);
							}
							*/

							if (codePoint <= 0x1F)
								break;

							/* don't accept chars not in mask */
							if (mask != NULL && (codePoint > 255 || !strchr(mask, (char)codePoint)))
								break;

							encodedCodePointLength = BarReadlineEncodeUtf8(codePoint, encodedCodePoint);
							encodedCodePoint[encodedCodePointLength] = '\0';

							if (bufLen + encodedCodePointLength < (int)bufSize)
							{
								strncpy(bufOut, encodedCodePoint, encodedCodePointLength);

								if (echo) {
									fputs(encodedCodePoint, stdout);
									fflush(stdout);
								}

								bufOut += encodedCodePointLength;
								++bufPos;
								++bufLen;

								if ((bufLen >= (int)(bufSize - 1)) && overflow)
								{
									if (echo)
										fputc('\n', stdout);
									return bufLen;
								}
							}
						}
						break;
				}
			}
		}
		else if (WAIT_TIMEOUT == waitResult)
			break;
		else
			/* TODO: Handle errors. */
			break;
	}

	return bufLen;
}

/*	Read string from stdin
 *	@param buffer
 *	@param buffer size
 *	@return number of bytes read from stdin
 */
size_t BarReadlineStr (char *buf, const size_t bufSize,
		BarReadline_t input, const BarReadlineFlags_t flags) {
	return BarReadline (buf, bufSize, NULL, input, flags, -1);
}

/*	Read int from stdin
 *	@param write result into this variable
 *	@return number of bytes read from stdin
 */
size_t BarReadlineInt (int *ret, BarReadline_t input) {
	int rlRet = 0;
	char buf[16];

	rlRet = BarReadline (buf, sizeof (buf), "0123456789", input,
			BAR_RL_DEFAULT, -1);
	*ret = atoi ((char *) buf);

	return rlRet;
}

/*	Yes/No?
 *	@param default (user presses enter)
 */
bool BarReadlineYesNo (bool def, BarReadline_t input) {
	char buf[2];
	BarReadline (buf, sizeof (buf), "yYnN", input, BAR_RL_FULLRETURN, -1);
	if (*buf == 'y' || *buf == 'Y' || (def == true && *buf == '\0')) {
		return true;
	} else {
		return false;
	}
}