-
Notifications
You must be signed in to change notification settings - Fork 514
/
Copy pathConsoleHelpers.cs
174 lines (140 loc) · 4.96 KB
/
ConsoleHelpers.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
// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Nethermind.Runner;
public static class ConsoleHelpers
{
private static LineInterceptingTextWriter _interceptingWriter;
public static event EventHandler<string>? LineWritten;
public static string[] GetRecentMessages() => _interceptingWriter.GetRecentMessages();
public static void EnableConsoleColorOutput()
{
const int STD_OUTPUT_HANDLE = -11;
const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4;
Console.OutputEncoding = System.Text.Encoding.UTF8;
// Capture original out
TextWriter originalOut = Console.Out;
// Create our intercepting writer
_interceptingWriter = new LineInterceptingTextWriter(originalOut);
_interceptingWriter.LineWritten += (sender, line) =>
{
LineWritten?.Invoke(sender, line);
};
// Redirect Console.Out
Console.SetOut(_interceptingWriter);
if (!OperatingSystem.IsWindowsVersionAtLeast(10))
return;
try
{
// If using Cmd and not set in registry
// enable ANSI escape sequences here
var handle = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleMode(handle, out var mode);
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(handle, mode);
}
catch
{
}
}
[DllImport("kernel32.dll")]
private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll")]
private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
}
public sealed class LineInterceptingTextWriter : TextWriter
{
// Event raised every time a full line ending with Environment.NewLine is written
public event EventHandler<string>? LineWritten;
// The "real" underlying writer (i.e., the original Console.Out)
private readonly TextWriter _underlyingWriter;
// Buffer used to accumulate written data until we detect a new line
private readonly StringBuilder _buffer;
public LineInterceptingTextWriter(TextWriter underlyingWriter)
{
_underlyingWriter = underlyingWriter ?? throw new ArgumentNullException(nameof(underlyingWriter));
_buffer = new StringBuilder();
}
// You must override Encoding, even if just forwarding
public override Encoding Encoding => _underlyingWriter.Encoding;
// Overriding WriteLine(string) is handy for direct calls to Console.WriteLine(...).
// However, you also want to handle the general case in Write(string).
public override void WriteLine(string? value)
{
Write(value);
Write(Environment.NewLine);
}
public override void Write(string? value)
{
if (value == null)
{
return;
}
// Append to the buffer
_buffer.Append(value);
// Pass the data along to the underlying writer
_underlyingWriter.Write(value);
// Check if we can extract lines from the buffer
CheckForLines();
}
public override void Write(char value)
{
_buffer.Append(value);
_underlyingWriter.Write(value);
CheckForLines();
}
public override void Flush()
{
base.Flush();
_underlyingWriter.Flush();
}
private void CheckForLines()
{
// Environment.NewLine might be "\r\n" or "\n" depending on platform
// so let's find each occurrence and split it off
string newLine = Environment.NewLine;
while (true)
{
// Find the next index of the new line
int newLinePos = _buffer.ToString().IndexOf(newLine, StringComparison.Ordinal);
// If there's no complete new line, break
if (newLinePos < 0)
{
break;
}
// Extract the line up to the new line
string line = _buffer.ToString(0, newLinePos);
// Remove that portion (including the new line) from the buffer
_buffer.Remove(0, newLinePos + newLine.Length);
// Raise the event
OnLineWritten(line);
}
}
public string[] GetRecentMessages()
{
lock (_recentMessages)
{
return _recentMessages.ToArray();
}
}
Queue<string> _recentMessages = new(capacity: 100);
private void OnLineWritten(string line)
{
lock (_recentMessages)
{
if (_recentMessages.Count > 100)
{
_recentMessages.Dequeue();
}
_recentMessages.Enqueue(line);
}
// Raise the event, if subscribed
LineWritten?.Invoke(this, line);
}
}