Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Unix] Console.ReadKey rewrite #72193

Merged
merged 42 commits into from
Aug 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
d929235
move WellKnownStrings to a separate file
adamsitnik Jun 28, 2022
c8887ec
move Database to separate file
adamsitnik Jun 28, 2022
cf77107
move factory logic to DatabaseFactory so the test project does not ne…
adamsitnik Jun 28, 2022
c6f3a60
move WellKnownNumbers to separate file
adamsitnik Jun 28, 2022
acd4f24
include Database in the test project
adamsitnik Jun 28, 2022
f5e3641
move TerminalFormatStrings to a separate file
adamsitnik Jun 28, 2022
d3cdb93
include TerminalFormatStrings in test project
adamsitnik Jun 28, 2022
7ea9f50
fix existing tests
adamsitnik Jun 28, 2022
dc0af6b
move the key mapping logic to a separate class, do NOT change it
adamsitnik Jun 29, 2022
c927091
simple tests for ASCII characters
adamsitnik Jun 29, 2022
f30f02e
test cases for xterm and xterm-256color
adamsitnik Jul 5, 2022
5ffdd67
add PuTTY and UXTern
adamsitnik Jul 5, 2022
9230c81
add Windows Terminal data
adamsitnik Jul 6, 2022
41a92bf
add more PuTTY test cases
adamsitnik Jul 6, 2022
af92ab3
handle empty encodings
adamsitnik Jul 6, 2022
9a2ed71
make it possible to run the tests on Windows so I can use my favourit…
adamsitnik Jul 7, 2022
69f12c9
add mappings for single characters
adamsitnik Jul 7, 2022
5bbac1d
add mappings for 3 characters
adamsitnik Jul 8, 2022
a9db7db
fix test cases where pressing Ctrl/Alt/Shift + other key produces two…
adamsitnik Jul 8, 2022
c2e02d8
handle more complex sequences (with modifiers)
adamsitnik Jul 8, 2022
620d1a0
handle edge cases properly
adamsitnik Jul 9, 2022
20593ef
add tmux test data
adamsitnik Jul 11, 2022
c612f4f
add rxvt-unicode test data and implementation for rxvt modifiers
adamsitnik Jul 11, 2022
3e62636
polishing
adamsitnik Jul 12, 2022
aa07430
switch to the new implementation and allow the users to differentiate…
adamsitnik Jul 12, 2022
254c762
add way more test cases and fix identified issues
adamsitnik Jul 12, 2022
4023725
polishing: reorder the tests
adamsitnik Jul 13, 2022
d65c6e7
fix compiler error (it's strange as I was not getting it when I was b…
adamsitnik Jul 14, 2022
8cd9e3d
add more SCO mappings
adamsitnik Jul 14, 2022
7fea037
Numeric Keypad
adamsitnik Jul 14, 2022
16e983f
Merge remote-tracking branch 'upstream/main' into consoleReadKey
adamsitnik Jul 14, 2022
dd07418
add Tmux 256 color test cases (TERM=screen-256color)
adamsitnik Jul 21, 2022
632267c
add two Numeric Keypad test cases: period & Enter
adamsitnik Jul 21, 2022
69f6434
fix issue discovered by adding more tmux test cases: ^[OM should be m…
adamsitnik Jul 21, 2022
9c352b4
address code review feedback: move TerminalFormatStrings classs out i…
adamsitnik Jul 21, 2022
f974992
address code review feedback: handle all variants of tmux when gettin…
adamsitnik Jul 21, 2022
b3366a8
address code review feedback: reduce number of out parameters
adamsitnik Jul 21, 2022
dc82fb5
fix TermInfo tests
adamsitnik Jul 21, 2022
214da94
add .NET 6 compat switch
adamsitnik Jul 21, 2022
7766ed3
Apply suggestions from code review
adamsitnik Aug 1, 2022
c8010c5
address code review feedback
adamsitnik Aug 1, 2022
c28d600
Merge branch 'main' into consoleReadKey
adamsitnik Aug 1, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ internal static partial class Sys
internal static unsafe partial int ReadStdin(byte* buffer, int bufferSize);

[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_InitializeConsoleBeforeRead")]
internal static partial void InitializeConsoleBeforeRead(byte minChars = 1, byte decisecondsTimeout = 0);
internal static partial void InitializeConsoleBeforeRead([MarshalAs(UnmanagedType.Bool)] bool distinguishNewLines, byte minChars = 1, byte decisecondsTimeout = 0);

[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_UninitializeConsoleAfterRead")]
internal static partial void UninitializeConsoleAfterRead();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ internal static partial class Sys
internal static partial int GetSignalForBreak();

[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetSignalForBreak")]
internal static partial int SetSignalForBreak(int signalForBreak);
internal static partial int SetSignalForBreak(int signalForBreak, [MarshalAs(UnmanagedType.Bool)] bool distinguishNewLines);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ internal static partial class Sys
{
[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_StdinReady")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool StdinReady();
internal static partial bool StdinReady([MarshalAs(UnmanagedType.Bool)] bool distinguishNewLines);
}
}
28 changes: 28 additions & 0 deletions src/libraries/Common/src/System/Console/ConsoleUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ internal static partial class ConsoleUtils
/// <summary>Whether to output ansi color strings.</summary>
private static volatile int s_emitAnsiColorCodes = -1;

private static volatile int s_useNet6KeyParser = -1;

/// <summary>Get whether to emit ANSI color codes.</summary>
public static bool EmitAnsiColorCodes
{
Expand Down Expand Up @@ -49,5 +51,31 @@ public static bool EmitAnsiColorCodes
return enabled;
}
}

internal static bool UseNet6KeyParser
{
get
{
int useNet6KeyParser = s_useNet6KeyParser;

if (useNet6KeyParser == -1)
{
useNet6KeyParser = s_useNet6KeyParser = GetNet6CompatReadKeySetting() ? 1 : 0;
}

return useNet6KeyParser == 1;

static bool GetNet6CompatReadKeySetting()
{
if (AppContext.TryGetSwitch("System.Console.UseNet6CompatReadKey", out bool fileConfig))
{
return fileConfig;
}

string? envVar = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_CONSOLE_USENET6COMPATREADKEY");
return envVar is not null && (envVar == "1" || envVar.Equals("true", StringComparison.OrdinalIgnoreCase));
}
}
}
}
}
7 changes: 7 additions & 0 deletions src/libraries/System.Console/src/System.Console.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,18 @@
<!-- Unix -->
<ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Unix'">
<Compile Include="System\ConsolePal.Unix.cs" />
<Compile Include="System\TerminalFormatStrings.cs" />
<Compile Include="$(CommonPath)System\Console\ConsoleUtils.cs"
Link="Common\System\Console\ConsoleUtils.cs" />
<Compile Include="System\TermInfo.cs" />
<Compile Include="System\TermInfo.WellKnownStrings.cs" />
<Compile Include="System\TermInfo.Database.cs" />
<Compile Include="System\TermInfo.DatabaseFactory.cs" />
<Compile Include="System\TermInfo.WellKnownNumbers.cs" />
<Compile Include="System\IO\StdInReader.cs" />
<Compile Include="System\IO\SyncTextReader.Unix.cs" />
<Compile Include="System\IO\KeyParser.cs" />
<Compile Include="System\IO\Net6KeyParser.cs" />
<Compile Include="$(CoreLibSharedDir)System\IO\PersistedFiles.Unix.cs"
Link="Common\System\IO\PersistedFiles.Unix.cs" />
<Compile Include="$(CoreLibSharedDir)System\IO\PersistedFiles.Names.Unix.cs"
Expand Down
326 changes: 21 additions & 305 deletions src/libraries/System.Console/src/System/ConsolePal.Unix.cs

Large diffs are not rendered by default.

392 changes: 392 additions & 0 deletions src/libraries/System.Console/src/System/IO/KeyParser.cs

Large diffs are not rendered by default.

180 changes: 180 additions & 0 deletions src/libraries/System.Console/src/System/IO/Net6KeyParser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace System.IO;

internal static class Net6KeyParser
adamsitnik marked this conversation as resolved.
Show resolved Hide resolved
adamsitnik marked this conversation as resolved.
Show resolved Hide resolved
{
internal static ConsoleKeyInfo Parse(char[] buffer, TerminalFormatStrings terminalFormatStrings, byte posixDisableValue, byte veraseCharacter, ref int startIndex, int endIndex)
{
MapBufferToConsoleKey(buffer, terminalFormatStrings, posixDisableValue, veraseCharacter, out ConsoleKey key,
out char ch, out bool isShift, out bool isAlt, out bool isCtrl, ref startIndex, endIndex);

// Replace the '\n' char for Enter by '\r' to match Windows behavior.
if (key == ConsoleKey.Enter && ch == '\n')
{
ch = '\r';
}

return new ConsoleKeyInfo(ch, key, isShift, isAlt, isCtrl);
}

private static bool MapBufferToConsoleKey(char[] buffer, TerminalFormatStrings terminalFormatStrings, byte posixDisableValue, byte veraseCharacter,
out ConsoleKey key, out char ch, out bool isShift, out bool isAlt, out bool isCtrl, ref int startIndex, int endIndex)
{
// Try to get the special key match from the TermInfo static information.
if (TryGetSpecialConsoleKey(buffer, startIndex, endIndex, terminalFormatStrings, posixDisableValue, veraseCharacter, out ConsoleKeyInfo keyInfo, out int 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) ? buffer[startIndex] : '\0'); // ignore keyInfo.KeyChar
startIndex += keyLength;
return true;
}

// Check if we can match Esc + combination and guess if alt was pressed.
if (buffer[startIndex] == (char)0x1B && // Alt is send as an escape character
endIndex - startIndex >= 2) // We have at least two characters to read
{
startIndex++;
if (MapBufferToConsoleKey(buffer, terminalFormatStrings, posixDisableValue, veraseCharacter, out key, out ch, out isShift, out _, out isCtrl, ref startIndex, endIndex))
{
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 = buffer[startIndex++];
key = GetKeyFromCharValue(ch, out isShift, out isCtrl);
isAlt = false;
return key != default(ConsoleKey);
}

private static bool TryGetSpecialConsoleKey(char[] givenChars, int startIndex, int endIndex,
TerminalFormatStrings terminalFormatStrings, byte posixDisableValue, byte veraseCharacter, out ConsoleKeyInfo key, out int keyLength)
{
int unprocessedCharCount = endIndex - startIndex;

// First process special control character codes. These override anything from terminfo.
if (unprocessedCharCount > 0)
{
// Is this an erase / backspace?
char c = givenChars[startIndex];
if (c != posixDisableValue && c == veraseCharacter)
{
key = new ConsoleKeyInfo(c, ConsoleKey.Backspace, shift: false, alt: false, control: false);
keyLength = 1;
return true;
}
}

// Then process terminfo mappings.
int minRange = terminalFormatStrings.MinKeyFormatLength;
if (unprocessedCharCount >= minRange)
{
int maxRange = Math.Min(unprocessedCharCount, terminalFormatStrings.MaxKeyFormatLength);

for (int i = maxRange; i >= minRange; i--)
{
var currentString = new ReadOnlyMemory<char>(givenChars, startIndex, i);

// Check if the string prefix matches.
if (terminalFormatStrings.KeyFormatToConsoleKey.TryGetValue(currentString, out key))
{
keyLength = currentString.Length;
return true;
}
}
}

// Otherwise, not a known special console key.
key = default(ConsoleKeyInfo);
keyLength = 0;
return false;
}

private static 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':
case '\r':
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 (char.IsBetween(x, (char)1, (char)26))
{
isCtrl = true;
return ConsoleKey.A + x - 1;
}

// 2. Numbers from 0 to 9.
if (char.IsAsciiDigit(x))
{
return ConsoleKey.D0 + x - '0';
}

//3. A to Z
if (char.IsAsciiLetterUpper(x))
{
isShift = true;
return ConsoleKey.A + (x - 'A');
}

// 4. a to z.
if (char.IsAsciiLetterLower(x))
{
return ConsoleKey.A + (x - 'a');
}

break;
}

return default(ConsoleKey);
}
}
Loading