-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
ConsoleHelper.cs
528 lines (503 loc) · 14.9 KB
/
ConsoleHelper.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
namespace Towel;
/// <summary>Contains static helper methods for <see cref="Console"/>.</summary>
public static class ConsoleHelper
{
/// <summary>Flushes the console input buffer.</summary>
/// <param name="intercept">
/// Determines whether to display the pressed key in the console window.
/// true to not display the pressed key; otherwise, false.
/// </param>
public static void FlushInputBuffer(bool intercept = true)
{
while (Console.KeyAvailable)
{
Console.ReadKey(intercept);
}
}
/// <summary>Prompts the user to press [enter] in the console before continuing.</summary>
/// <param name="key">The key to wait for the user to press before continuing.</param>
public static void PressToContinue(ConsoleKey key = ConsoleKey.Enter)
{
if (!key.IsDefined())
{
throw new ArgumentOutOfRangeException(nameof(key), key, $"{nameof(key)} is not a defined value in the {nameof(ConsoleKey)} enum");
}
while (Console.ReadKey(true).Key != key)
{
continue;
}
}
/// <summary>Prompts the user to press [enter] in the console before continuing.</summary>
/// <param name="prompt">The prompt to display to the user. Default: "Press [enter] to continue...".</param>
/// <param name="key">The key to wait for the user to press before continuing.</param>
public static void PromptPressToContinue(string? prompt = null, ConsoleKey key = ConsoleKey.Enter)
{
if (!key.IsDefined())
{
throw new ArgumentOutOfRangeException(nameof(key), key, $"{nameof(key)} is not a defined value in the {nameof(ConsoleKey)} enum");
}
prompt ??= $"Press [{key}] to continue...";
Console.Write(prompt);
PressToContinue(key);
}
/// <summary>Prompts the user to select a menu option in the console before continuing.</summary>
/// <param name="options">The options of the menu.</param>
public static void IntMenu(params (string DisplayName, Action Action)[] options) =>
IntMenu(null, null, null, options);
/// <summary>Prompts the user to select a menu option in the console before continuing.</summary>
/// <param name="title">The title of the menu.</param>
/// <param name="prompt">The prompt message to display when requesting console input from the user.</param>
/// <param name="invalidMessage">The message to display if invalid input is detected.</param>
/// <param name="options">The options of the menu.</param>
public static void IntMenu(
string? title = null,
string? prompt = null,
string? invalidMessage = null,
params (string DisplayName, Action Action)[] options)
{
if (options is null) throw new ArgumentNullException(nameof(options));
if (options.Length <= 0)
{
throw new ArgumentException($"{nameof(options)} is empty", nameof(options));
}
prompt ??= $"Choose an option (1-{options.Length}): ";
invalidMessage ??= "Invalid Input. Try Again...";
if (title is not null)
{
Console.WriteLine(title);
}
for (int i = 0; i < options.Length; i++)
{
Console.WriteLine($"{i + 1}. {options[i].DisplayName ?? "null"}");
}
int inputValue;
Console.Write(prompt);
while (!int.TryParse(Console.ReadLine(), out inputValue) || inputValue < 1 || options.Length < inputValue)
{
Console.WriteLine(invalidMessage);
Console.Write(prompt);
}
options[inputValue - 1].Action?.Invoke();
}
/// <summary>Gets console input from the user.</summary>
/// <typeparam name="T">The generic type of console input to get from the user.</typeparam>
/// <param name="prompt">The prompt message to display when requesting console input from the user.</param>
/// <param name="invalidMessage">The message to display if invalid input is detected.</param>
/// <param name="tryParse">The <see cref="TryParse"/> method for converting <see cref="string"/> into a <typeparamref name="T"/> value.</param>
/// <param name="validation">The predicate for validating the value of the input.</param>
/// <returns>The validated value of the console input provided by the user.</returns>
public static T? GetInput<T>(
string? prompt = null,
string? invalidMessage = null,
Func<string, (bool Success, T? Value)>? tryParse = null,
Predicate<T?>? validation = null)
{
if (tryParse is null && (typeof(T) != typeof(string) && !typeof(T).IsEnum && Meta.GetTryParseMethod<T>() is null))
{
throw new InvalidOperationException($"Using {nameof(ConsoleHelper)}.{nameof(GetInput)} without providing a {nameof(tryParse)} delegate for a non-supported type {typeof(T).Name}.");
}
tryParse ??= typeof(T) == typeof(string)
? s => (true, (T)(object)s)
: TryParse<T>;
validation ??= v => true;
GetInput:
Console.Write(prompt ?? $"Input a {typeof(T).Name} value: ");
string? readLine = Console.ReadLine();
if (readLine is null)
{
throw new ArgumentException($"{nameof(System)}.{nameof(Console)}.{nameof(Console.ReadLine)} returned null");
}
var (success, value) = tryParse(readLine);
if (!success || !validation(value))
{
Console.WriteLine(invalidMessage ?? $"Invalid input. Try again...");
goto GetInput;
}
return value;
}
/// <summary>Similar to <see cref="Console.ReadLine"/> but with hidden input characters.</summary>
/// <param name="shownCharacter">The display character to use for all input.</param>
/// <returns>The <see cref="string"/> input provided by the user.</returns>
public static string HiddenReadLine(char shownCharacter = '*')
{
System.Collections.Generic.List<char> list = new();
HiddenReadLineBase(
shownCharacter: shownCharacter,
GetLength: () => list.Count,
Append: list.Add,
InsertAt: list.Insert,
RemoveAt: list.RemoveAt,
RemoveRange: list.RemoveRange,
Clear: list.Clear);
return string.Concat(list);
}
internal static void HiddenReadLineBase(
char shownCharacter,
Func<int> GetLength,
Action<char> Append,
Action<int, char> InsertAt,
Action<int> RemoveAt,
Action<int, int>? RemoveRange = null,
Action? Clear = null)
{
int position = 0;
RemoveRange ??= (index, length) =>
{
for (int i = 0; i < length; i++)
{
RemoveAt(index);
}
};
Clear ??= () => RemoveRange(0, GetLength());
void MoveToOrigin() => MoveNegative(position);
void MoveToTail() => MovePositive(GetLength() - position);
while (true)
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (keyInfo.Key is ConsoleKey.Enter)
{
if (!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control) &&
!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift) &&
!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Alt))
{
MovePositive(GetLength() - position);
Console.WriteLine();
break;
}
}
else if (keyInfo.Key is ConsoleKey.Backspace)
{
if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
{
MoveToOrigin();
ConsoleWriteString(new string(shownCharacter, GetLength() - position) + new string(' ', position));
MoveNegative(GetLength());
RemoveRange(0, position);
position = 0;
}
else if (position > 0)
{
if (position == GetLength())
{
MoveNegative(1);
ConsoleWriteChar(' ');
MoveNegative(1);
}
else
{
MoveToTail();
MoveNegative(1);
ConsoleWriteChar(' ');
MoveNegative(GetLength() - position + 1);
}
RemoveAt(position - 1);
position--;
}
}
else if (keyInfo.Key is ConsoleKey.Delete)
{
if (!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control) &&
!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift) &&
!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Alt))
{
if (position < GetLength())
{
int left = Console.CursorLeft;
int top = Console.CursorTop;
MoveToTail();
MoveNegative(1);
ConsoleWriteChar(' ');
Console.CursorLeft = left;
Console.CursorTop = top;
RemoveAt(position);
continue;
}
}
}
else if (keyInfo.Key is ConsoleKey.Escape)
{
if (!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control) &&
!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift) &&
!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Alt))
{
MoveToOrigin();
int left = Console.CursorLeft;
int top = Console.CursorTop;
ConsoleWriteString(new string(' ', GetLength()));
Console.CursorLeft = left;
Console.CursorTop = top;
Clear();
position = 0;
}
}
else if (keyInfo.Key is ConsoleKey.Home)
{
if (!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift) &&
!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Alt))
{
if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
{
MoveToOrigin();
ConsoleWriteString(new string(shownCharacter, GetLength() - position) + new string(' ', position));
MoveNegative(GetLength());
RemoveRange(0, position);
position = 0;
}
else
{
MoveToOrigin();
position = 0;
}
}
}
else if (keyInfo.Key is ConsoleKey.End)
{
if (!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift) &&
!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Alt))
{
if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
{
MoveToOrigin();
ConsoleWriteString(new string(shownCharacter, position) + new string(' ', GetLength() - position));
MoveNegative(GetLength() - position);
RemoveRange(position, GetLength() - position);
}
else
{
MoveToTail();
position = GetLength();
}
}
}
else if (keyInfo.Key is ConsoleKey.LeftArrow)
{
if (!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift) &&
!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Alt))
{
if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
{
MoveToOrigin();
position = 0;
}
else
{
if (position > 0)
{
MoveNegative(1);
position--;
}
}
}
}
else if (keyInfo.Key is ConsoleKey.RightArrow)
{
if (!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift) &&
!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Alt))
{
if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
{
MoveToTail();
position = GetLength();
}
else
{
if (position < GetLength())
{
MovePositive(1);
position++;
}
}
}
}
else
{
if (keyInfo.KeyChar is not '\0')
{
if (position == GetLength())
{
ConsoleWriteChar(shownCharacter);
Append(keyInfo.KeyChar);
position++;
}
else
{
int left = Console.CursorLeft;
int top = Console.CursorTop;
MoveToTail();
ConsoleWriteChar(shownCharacter);
Console.CursorLeft = left;
Console.CursorTop = top;
MovePositive(1);
InsertAt(position, keyInfo.KeyChar);
position++;
}
}
}
}
}
/// <summary>Animates an elipsis in the console to indicate processing.</summary>
/// <param name="condition">The condition of the loop.</param>
/// <param name="delay">The delay function.</param>
/// <param name="length">The length of the ellipsis.</param>
public static void AnimatedEllipsis(
Func<bool> condition,
Action delay,
int length = 3)
{
if (condition is null) throw new ArgumentNullException(nameof(condition));
if (delay is null) throw new ArgumentNullException(nameof(delay));
if (sourceof(length < 1, out string c1)) throw new ArgumentOutOfRangeException(nameof(length), length, c1);
void MoveToOrigin() => MoveNegative(length);
void Render(int frame)
{
for (int i = 0; i < frame; i++)
{
ConsoleWriteChar('.');
}
for (int i = frame; i < length; i++)
{
ConsoleWriteChar(' ');
}
}
int frame = 0;
Render(frame++);
while (condition())
{
MoveToOrigin();
Render(frame++);
delay();
if (frame > length)
{
frame = 0;
}
}
MoveToOrigin();
ConsoleWriteString(new string(' ', length));
MoveToOrigin();
}
/// <summary>Displays a progress bar in the console.</summary>
/// <param name="action">The action to track the progress of.</param>
/// <param name="length">The character length of the progress bar (must be >= 6).</param>
/// <param name="header">The header character of the progress bar.</param>
/// <param name="footer">The footer character of the progress bar.</param>
/// <param name="done">The character for represening completed progress.</param>
/// <param name="remaining">The character representing ongoing processing.</param>
/// <param name="errorDigit">The characters to display in the numerical display when an invalid percentage is recieved.</param>
/// <param name="postClear">Whether or not to clear the progress bar from the view when complete.</param>
public static void ProgressBar(
Action<Action<double>> action,
int length = 17,
char header = '[',
char footer = ']',
char done = '=',
char remaining = '-',
char errorDigit = '?',
bool postClear = true)
{
if (action is null) throw new ArgumentNullException(nameof(action));
if (sourceof(length < 6, out string c1)) throw new ArgumentOutOfRangeException(nameof(length), length, c1);
void MoveToOrigin() => MoveNegative(length);
void Render(double percentage)
{
ConsoleWriteChar(header);
if (percentage < 0 || percentage > 100)
{
ConsoleWriteString(new string(remaining, length - 7));
}
else
{
int doneCount = (int)(percentage / 100 * (length - 7));
int remainingCount = length - 7 - doneCount;
ConsoleWriteString(new string(done, doneCount));
ConsoleWriteString(new string(remaining, remainingCount));
}
ConsoleWriteChar(footer);
ConsoleWriteChar(' ');
if (percentage < 0 || percentage > 100)
{
ConsoleWriteString(new string(errorDigit, 2));
ConsoleWriteChar('%');
ConsoleWriteChar(' ');
}
else
{
string percentString = ((int)percentage).ToString(System.Globalization.CultureInfo.InvariantCulture);
ConsoleWriteString(percentString);
ConsoleWriteChar('%');
for (int i = percentString.Length; i < 3; i++)
{
ConsoleWriteChar(' ');
}
}
}
Render(0);
action(percent => { MoveToOrigin(); Render(percent); });
if (postClear)
{
MoveToOrigin();
ConsoleWriteString(new string(' ', length));
MoveToOrigin();
}
else
{
MoveToOrigin();
Render(100);
}
}
internal static void MoveNegative(int count)
{
int bufferWidth = Console.BufferWidth;
int left = Console.CursorLeft;
int top = Console.CursorTop;
for (int i = 0; i < count; i++)
{
if (left > 0)
{
left--;
}
else
{
top--;
left = bufferWidth - 1;
}
}
Console.CursorLeft = left;
Console.CursorTop = top;
}
internal static void MovePositive(int count)
{
int bufferWidth = Console.BufferWidth;
int left = Console.CursorLeft;
int top = Console.CursorTop;
for (int i = 0; i < count; i++)
{
if (left == bufferWidth - 1)
{
top++;
left = 0;
}
else
{
left++;
}
}
Console.CursorLeft = left;
Console.CursorTop = top;
}
internal static void ConsoleWriteChar(char @char)
{
int temp = Console.CursorLeft;
Console.Write(@char);
if (Console.CursorLeft == temp)
{
MovePositive(1);
}
}
internal static void ConsoleWriteString(string @string)
{
foreach (char c in @string)
{
ConsoleWriteChar(c);
}
}
}