tgstation-server
The /tg/station 13 server suite
Console.cs
Go to the documentation of this file.
1 using System;
2 using System.Text;
3 using System.Threading;
4 using System.Threading.Tasks;
5 
6 namespace Tgstation.Server.Host.IO
7 {
9  sealed class Console : IConsole
10  {
12  public bool Available => Environment.UserInteractive;
13 
15  {
16  if (!Available)
17  throw new InvalidOperationException("Console unavailable");
18  }
19 
21  public Task PressAnyKeyAsync(CancellationToken cancellationToken) => Task.Factory.StartNew(() =>
22  {
23  CheckAvailable();
24  System.Console.Read();
25  }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current);
26 
28  public Task<string> ReadLineAsync(bool usePasswordChar, CancellationToken cancellationToken) => Task.Factory.StartNew(() =>
29  {
30  //TODO Make this better: https://stackoverflow.com/questions/9479573/how-to-interrupt-console-readline
31  CheckAvailable();
32  if (!usePasswordChar)
33  return System.Console.ReadLine();
34 
35  var passwordBuilder = new StringBuilder();
36  do
37  {
38  var keyDescription = System.Console.ReadKey(true);
39  if (keyDescription.Key == ConsoleKey.Enter)
40  break;
41  else if (keyDescription.Key == ConsoleKey.Backspace)
42  {
43  if (passwordBuilder.Length > 0)
44  {
45  --passwordBuilder.Length;
46  System.Console.Write("\b \b");
47  }
48  }
49  else if (keyDescription.KeyChar != '\u0000') // KeyChar == '\u0000' if the key pressed does not correspond to a printable character, e.g. F1, Pause-Break, etc
50  {
51  passwordBuilder.Append(keyDescription.KeyChar);
52  System.Console.Write('*');
53  }
54  }
55  while (!cancellationToken.IsCancellationRequested);
56  cancellationToken.ThrowIfCancellationRequested();
57  System.Console.WriteLine();
58  return passwordBuilder.ToString();
59  }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current);
60 
62  public Task WriteAsync(string text, bool newLine, CancellationToken cancellationToken) => Task.Factory.StartNew(() =>
63  {
64  CheckAvailable();
65  if (text == null)
66  {
67  if (!newLine)
68  throw new InvalidOperationException("Cannot write null text without a new line!");
69  System.Console.WriteLine();
70  }
71  else if (newLine)
72  System.Console.WriteLine(text);
73  else
74  System.Console.Write(text);
75  }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current);
76  }
77 }
Abstraction for System.Console
Definition: IConsole.cs:9