-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathStdInReader.cs
426 lines (373 loc) · 17.5 KB
/
StdInReader.cs
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace System.IO
{
/* This class is used by for reading from the stdin.
* It is designed to read stdin in raw mode for interpreting
* key press events and maintain its own buffer for the same.
* which is then used for all the Read operations
*/
internal sealed class StdInReader : TextReader
{
private static string? s_moveLeftString; // string written to move the cursor to the left
private static string? s_clearToEol; // string written to clear from cursor to end of line
private readonly StringBuilder _readLineSB; // SB that holds readLine output. This is a field simply to enable reuse; it's only used in ReadLine.
private readonly Stack<ConsoleKeyInfo> _tmpKeys = new Stack<ConsoleKeyInfo>(); // temporary working stack; should be empty outside of ReadLine
private readonly Stack<ConsoleKeyInfo> _availableKeys = new Stack<ConsoleKeyInfo>(); // a queue of already processed key infos available for reading
private readonly Encoding _encoding;
private char[] _unprocessedBufferToBeRead; // Buffer that might have already been read from stdin but not yet processed.
private const int BytesToBeRead = 1024; // No. of bytes to be read from the stream at a time.
private int _startIndex; // First unprocessed index in the buffer;
private int _endIndex; // Index after last unprocessed index in the buffer;
internal StdInReader(Encoding encoding, int bufferSize)
{
_encoding = encoding;
_unprocessedBufferToBeRead = new char[encoding.GetMaxCharCount(BytesToBeRead)];
_startIndex = 0;
_endIndex = 0;
_readLineSB = new StringBuilder();
}
/// <summary> Checks whether the unprocessed buffer is empty. </summary>
internal bool IsUnprocessedBufferEmpty()
{
return _startIndex >= _endIndex; // Everything has been processed;
}
internal unsafe void AppendExtraBuffer(byte* buffer, int bufferLength)
{
// Then convert the bytes to chars
int charLen = _encoding.GetMaxCharCount(bufferLength);
char* charPtr = stackalloc char[charLen];
charLen = _encoding.GetChars(buffer, bufferLength, charPtr, charLen);
// Ensure our buffer is large enough to hold all of the data
if (IsUnprocessedBufferEmpty())
{
_startIndex = _endIndex = 0;
}
else
{
Debug.Assert(_endIndex > 0);
int spaceRemaining = _unprocessedBufferToBeRead.Length - _endIndex;
if (spaceRemaining < charLen)
{
Array.Resize(ref _unprocessedBufferToBeRead, _unprocessedBufferToBeRead.Length * 2);
}
}
// Copy the data into our buffer
Marshal.Copy((IntPtr)charPtr, _unprocessedBufferToBeRead, _endIndex, charLen);
_endIndex += charLen;
}
internal unsafe int ReadStdin(byte* buffer, int bufferSize)
{
int result = Interop.CheckIo(Interop.Sys.ReadStdin(buffer, bufferSize));
Debug.Assert(result >= 0 && result <= bufferSize); // may be 0 if hits EOL
return result;
}
public override string? ReadLine()
{
return ReadLine(consumeKeys: true);
}
private string? ReadLine(bool consumeKeys)
{
Debug.Assert(_tmpKeys.Count == 0);
string? readLineStr = null;
Interop.Sys.InitializeConsoleBeforeRead();
try
{
// Read key-by-key until we've read a line.
while (true)
{
// Read the next key. This may come from previously read keys, from previously read but
// unprocessed data, or from an actual stdin read.
bool previouslyProcessed;
ConsoleKeyInfo keyInfo = ReadKey(out previouslyProcessed);
if (!consumeKeys && keyInfo.Key != ConsoleKey.Backspace) // backspace is the only character not written out in the below if/elses.
{
_tmpKeys.Push(keyInfo);
}
// Handle the next key. Since for other functions we may have ended up reading some of the user's
// input, we need to be able to handle manually processing that input, and so we do that processing
// for all input. As such, we need to special-case a few characters, e.g. recognizing when Enter is
// pressed to end a line. We also need to handle Backspace specially, to fix up both our buffer of
// characters and the position of the cursor. More advanced processing would be possible, but we
// try to keep this very simple, at least for now.
if (keyInfo.Key == ConsoleKey.Enter)
{
readLineStr = _readLineSB.ToString();
_readLineSB.Clear();
if (!previouslyProcessed)
{
Console.WriteLine();
}
break;
}
else if (IsEol(keyInfo.KeyChar))
{
string line = _readLineSB.ToString();
_readLineSB.Clear();
if (line.Length > 0)
{
readLineStr = line;
}
break;
}
else if (keyInfo.Key == ConsoleKey.Backspace)
{
int len = _readLineSB.Length;
if (len > 0)
{
_readLineSB.Length = len - 1;
if (!previouslyProcessed)
{
// The ReadLine input may wrap accross terminal rows and we need to handle that.
// note: ConsolePal will cache the cursor position to avoid making many slow cursor position fetch operations.
if (ConsolePal.TryGetCursorPosition(out int left, out int top, reinitializeForRead: true) &&
left == 0 && top > 0)
{
if (s_clearToEol == null)
{
s_clearToEol = ConsolePal.TerminalFormatStrings.Instance.ClrEol ?? string.Empty;
}
// Move to end of previous line
ConsolePal.SetCursorPosition(ConsolePal.WindowWidth - 1, top - 1);
// Clear from cursor to end of the line
ConsolePal.WriteStdoutAnsiString(s_clearToEol, mayChangeCursorPosition: false);
}
else
{
if (s_moveLeftString == null)
{
string? moveLeft = ConsolePal.TerminalFormatStrings.Instance.CursorLeft;
s_moveLeftString = !string.IsNullOrEmpty(moveLeft) ? moveLeft + " " + moveLeft : string.Empty;
}
Console.Write(s_moveLeftString);
}
}
}
}
else if (keyInfo.Key == ConsoleKey.Tab)
{
_readLineSB.Append(keyInfo.KeyChar);
if (!previouslyProcessed)
{
Console.Write(' ');
}
}
else if (keyInfo.Key == ConsoleKey.Clear)
{
_readLineSB.Clear();
if (!previouslyProcessed)
{
Console.Clear();
}
}
else if (keyInfo.KeyChar != '\0')
{
_readLineSB.Append(keyInfo.KeyChar);
if (!previouslyProcessed)
{
Console.Write(keyInfo.KeyChar);
}
}
}
}
finally
{
Interop.Sys.UninitializeConsoleAfterRead();
// If we're not consuming the read input, make the keys available for a future read
while (_tmpKeys.Count > 0)
{
_availableKeys.Push(_tmpKeys.Pop());
}
}
return readLineStr;
}
public override int Read() => ReadOrPeek(peek: false);
public override int Peek() => ReadOrPeek(peek: true);
private int ReadOrPeek(bool peek)
{
// If there aren't any keys in our processed keys stack, read a line to populate it.
if (_availableKeys.Count == 0)
{
ReadLine(consumeKeys: false);
}
// Now if there are keys, use the first.
if (_availableKeys.Count > 0)
{
ConsoleKeyInfo keyInfo = peek ? _availableKeys.Peek() : _availableKeys.Pop();
if (!IsEol(keyInfo.KeyChar))
{
return keyInfo.KeyChar;
}
}
// EOL
return -1;
}
private static bool IsEol(char c)
{
return
c != ConsolePal.s_posixDisableValue &&
(c == ConsolePal.s_veolCharacter || c == ConsolePal.s_veol2Character || c == ConsolePal.s_veofCharacter);
}
internal ConsoleKey GetKeyFromCharValue(char x, out bool isShift, out bool isCtrl)
{
isShift = false;
isCtrl = false;
switch (x)
{
case '\b':
return ConsoleKey.Backspace;
case '\t':
return ConsoleKey.Tab;
case '\n':
return ConsoleKey.Enter;
case (char)(0x1B):
return ConsoleKey.Escape;
case '*':
return ConsoleKey.Multiply;
case '+':
return ConsoleKey.Add;
case '-':
return ConsoleKey.Subtract;
case '/':
return ConsoleKey.Divide;
case (char)(0x7F):
return ConsoleKey.Delete;
case ' ':
return ConsoleKey.Spacebar;
default:
// 1. Ctrl A to Ctrl Z.
if (x >= 1 && x <= 26)
{
isCtrl = true;
return ConsoleKey.A + x - 1;
}
// 2. Numbers from 0 to 9.
if (x >= '0' && x <= '9')
{
return ConsoleKey.D0 + x - '0';
}
//3. A to Z
if (x >= 'A' && x <= 'Z')
{
isShift = true;
return ConsoleKey.A + (x - 'A');
}
// 4. a to z.
if (x >= 'a' && x <= 'z')
{
return ConsoleKey.A + (x - 'a');
}
break;
}
return default(ConsoleKey);
}
internal bool MapBufferToConsoleKey(out ConsoleKey key, out char ch, out bool isShift, out bool isAlt, out bool isCtrl)
{
Debug.Assert(!IsUnprocessedBufferEmpty());
// Try to get the special key match from the TermInfo static information.
ConsoleKeyInfo keyInfo;
int keyLength;
if (ConsolePal.TryGetSpecialConsoleKey(_unprocessedBufferToBeRead, _startIndex, _endIndex, out keyInfo, out keyLength))
{
key = keyInfo.Key;
isShift = (keyInfo.Modifiers & ConsoleModifiers.Shift) != 0;
isAlt = (keyInfo.Modifiers & ConsoleModifiers.Alt) != 0;
isCtrl = (keyInfo.Modifiers & ConsoleModifiers.Control) != 0;
ch = ((keyLength == 1) ? _unprocessedBufferToBeRead[_startIndex] : '\0'); // ignore keyInfo.KeyChar
_startIndex += keyLength;
return true;
}
// Check if we can match Esc + combination and guess if alt was pressed.
isAlt = isCtrl = isShift = false;
if (_unprocessedBufferToBeRead[_startIndex] == (char)0x1B && // Alt is send as an escape character
_endIndex - _startIndex >= 2) // We have at least two characters to read
{
_startIndex++;
if (MapBufferToConsoleKey(out key, out ch, out isShift, out isAlt, out isCtrl))
{
isAlt = true;
return true;
}
else
{
// We could not find a matching key here so, Alt+ combination assumption is in-correct.
// The current key needs to be marked as Esc key.
// Also, we do not increment _startIndex as we already did it.
key = ConsoleKey.Escape;
ch = (char)0x1B;
isAlt = false;
return true;
}
}
// Try reading the first char in the buffer and interpret it as a key.
ch = _unprocessedBufferToBeRead[_startIndex++];
key = GetKeyFromCharValue(ch, out isShift, out isCtrl);
return key != default(ConsoleKey);
}
/// <summary>
/// Try to intercept the key pressed.
///
/// Unlike Windows, Unix has no concept of virtual key codes.
/// Hence, in case we do not recognize a key, we can't really
/// get the ConsoleKey key code associated with it.
/// As a result, we try to recognize the key, and if that does
/// not work, we simply return the char associated with that
/// key with ConsoleKey set to default value.
/// </summary>
public unsafe ConsoleKeyInfo ReadKey(out bool previouslyProcessed)
{
// Order of reading:
// 1. A read should first consult _availableKeys, as this contains input that has already been both read from stdin and processed into ConsoleKeyInfos.
// 2. If _availableKeys is empty, then _unprocessedBufferToRead should be consulted. This is input from stdin that was read in bulk but has yet to be processed.
// 3. Finally if _unprocessedBufferToRead is empty, input must be obtained from ReadStdinUnbuffered.
if (_availableKeys.Count > 0)
{
previouslyProcessed = true;
return _availableKeys.Pop();
}
previouslyProcessed = false;
Interop.Sys.InitializeConsoleBeforeRead();
try
{
ConsoleKey key;
char ch;
bool isAlt, isCtrl, isShift;
if (IsUnprocessedBufferEmpty())
{
// Read in bytes
byte* bufPtr = stackalloc byte[BytesToBeRead];
int result = ReadStdin(bufPtr, BytesToBeRead);
if (result > 0)
{
// Append them
AppendExtraBuffer(bufPtr, result);
}
else
{
// Could be empty if EOL entered on its own. Pick one of the EOL characters we have,
// or just use 0 if none are available.
return new ConsoleKeyInfo((char)
(ConsolePal.s_veolCharacter != ConsolePal.s_posixDisableValue ? ConsolePal.s_veolCharacter :
ConsolePal.s_veol2Character != ConsolePal.s_posixDisableValue ? ConsolePal.s_veol2Character :
ConsolePal.s_veofCharacter != ConsolePal.s_posixDisableValue ? ConsolePal.s_veofCharacter :
0),
default(ConsoleKey), false, false, false);
}
}
MapBufferToConsoleKey(out key, out ch, out isShift, out isAlt, out isCtrl);
return new ConsoleKeyInfo(ch, key, isShift, isAlt, isCtrl);
}
finally
{
Interop.Sys.UninitializeConsoleAfterRead();
}
}
/// <summary>Gets whether there's input waiting on stdin.</summary>
internal bool StdinReady { get { return Interop.Sys.StdinReady(); } }
}
}