MongoExtensions / src / InteractiveReadLine / ConsoleReadLine.cs
Code · 198 lines · 6090 bytes
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
using InteractiveReadLine.Abstractions;
using InteractiveReadLine.Formatting;

// https://github.com/mattj23/InteractiveReadLine

#nullable disable

namespace InteractiveReadLine
{
	/// <summary>
	/// Exposes a IReadLineProvider that's wrapping a IConsole object, which by default is a wrapper around the System.Console.
	/// This class is the standard implementation of a ReadLine provider, intended for use with console applications.
	/// </summary>
	public class ConsoleReadLine : IReadLineProvider
	{
		private readonly IConsole console;
		private FormattedText lastWrittenText;
		private int lastWrittenCursor;

		private int startingRow;
		private int startingCol;
		public ConsoleReadLine(IConsole console = null)
		{
			this.console = console ?? new SystemConsoleWrapper();
			this.Start();
		}

		/// <summary>
		/// Reads a console key from the underlying provider. This method blocks until a key is received.
		/// </summary>
		/// <returns></returns>
		public ConsoleKeyInfo ReadKey()
		{
			return console.ReadKey();
		}

		/// <summary>
		/// Sets the display state on the underlying console, consisting of a prefix, body, suffix, and cursor
		/// position.
		/// </summary>
		/// <param name="state"></param>
		public void SetDisplay(LineDisplayState state)
		{
			Console.CursorVisible = false; // AAB
			var totalText = state.Prefix + state.LineBody + state.Suffix;
			var cursor = state.Prefix.Length + state.Cursor;
			this.SetText(totalText, cursor);
			Console.CursorVisible = true; // AAB
		}

		/// <summary>
		/// Sets the read line to contain the specified text and cursor position.
		/// </summary>
		/// <param name="totalText"></param>
		/// <param name="cursorPos"></param>
		private void SetText(FormattedText totalText, int cursorPos)
		{
			// The process of setting the input text requires us to find the difference between 
			// the last written text and the new text, then perform the minimum amount of character
			// writes necessary to make the two identical

			// First, we should determine what the new line needs to look like. If the new line is 
			// longer than the old line, we will write the new line exactly.  If it's shorter, we'll 
			// need to pad it out with empty characters 
			var writeText = (totalText.Length >= lastWrittenText.Length)
				? totalText
				: totalText + new string(' ', lastWrittenText.Length - totalText.Length);

			// Sweep through each character in the text to write and determine if an edit needs to be 
			// made (or does the FormattedChar match what was last written at this position?)
			// Cluster the edits into contiguous FormattedText objects, each with a cursor start position.
			var edits = new List<Tuple<int, FormattedText>>();

			Tuple<int, FormattedText> edit = null;

			for (int i = 0; i < writeText.Length; i++)
			{
				if (i < lastWrittenText.Length && writeText[i].Equals(lastWrittenText[i]))
				{
					if (edit != null)
					{
						edits.Add(edit);
						edit = null;
					}

					continue;
				}

				if (edit == null)
				{
					edit = new Tuple<int, FormattedText>(i, writeText[i]);
				}
				else
				{
					edit = new Tuple<int, FormattedText>(edit.Item1, edit.Item2 + writeText[i]);
				}

				/*
                int left = this.ColOffset(i);
                int top = this.RowOffset(i) + _startingRow;

                if (left != _console.CursorLeft)
                    _console.CursorLeft = left;
                if (top != _console.CursorTop)
                    _console.CursorTop = top;

                _console.Write(writeText[i]);
            */
			}
			if (edit != null)
				edits.Add(edit);

			foreach (var e in edits)
			{

				int left = this.ColOffset(e.Item1);
				int top = this.RowOffset(e.Item1) + startingRow;

				if (left != console.CursorLeft)
					console.CursorLeft = left;
				if (top != console.CursorTop)
					console.CursorTop = top;

				console.Write(e.Item2);
			}

			lastWrittenText = totalText;

			// Check if we shifted down the buffer. In certain cases, if we reach the end of the buffer
			// height and we skip a line, the System.Console shifts everything up, and our starting row
			// will effectively be less than where we started.  It will never move down.
			var writtenRowOffset = this.RowOffset(lastWrittenText.Length);
			if (writtenRowOffset + startingRow >= console.BufferHeight)
			{
				startingRow = console.BufferHeight - writtenRowOffset - 1;
			}

			console.CursorTop = startingRow + this.RowOffset(cursorPos);
			console.CursorLeft = this.ColOffset(cursorPos);
			lastWrittenCursor = cursorPos;
		}

		/// <summary>
		/// Writes a message out to the console out in the spot where the current read line input is, then
		/// immediately re-displays the line input on the next row.
		/// </summary>
		/// <param name="text">The text to write to the console, a newline char will be added automatically</param>
		public void InsertText(FormattedText text)
		{
			var currentText = lastWrittenText;
			var currentCursor = lastWrittenCursor;

			SetText(text, text.Length);
			console.WriteLine("");

			startingRow = console.CursorTop;
			lastWrittenText = "";
			lastWrittenCursor = 0;
			SetText(currentText, currentCursor);

		}

		public void Dispose()
		{
			this.Finish();
		}

		private void Start()
		{
			// _console.WriteLine(string.Empty);
			startingRow = console.CursorTop;
			startingCol = 1 + console.CursorLeft; // AAB
			// _console.CursorLeft = 0;
			lastWrittenText = string.Empty;
		}

		private void Finish()
		{
			console.WriteLine(string.Empty);
		}

		private int ColOffset(int length) => startingCol + length % console.BufferWidth;

		private int RowOffset(int length) => (length - this.ColOffset(length)) / console.BufferWidth;

		/// <summary>
		/// Provides a convenient static method of calling the ReadLine method on the System.Console
		/// </summary>
		/// <param name="config"></param>
		/// <returns></returns>
		public static string ReadLine(ReadLineConfig config = null)
		{
			var provider = new ConsoleReadLine();
			return provider.ReadLine(config ?? ReadLineConfig.Basic);
		}
	}
}