Skip to content

Commit

Permalink
[Unix] Console.ReadKey rewrite (#72193)
Browse files Browse the repository at this point in the history
* split TermInfo related logic into separate files, so they can be referenced from test project

* move the key mapping logic to a separate class, do NOT change it

* simple tests for ASCII characters

* test cases for xterm and xterm-256color

* add PuTTY

* add Windows Terminal data

* add more PuTTY test cases

* add mappings for single characters

* add mappings for 3 characters

* fix test cases where pressing Ctrl/Alt/Shift + other key produces two bytes which represent single UTF8 character by design

* handle more complex sequences (with modifiers)

* handle edge cases properly

* add tmux test data

* add rxvt-unicode test data and implementation for rxvt modifiers

* switch to the new implementation and allow the users to differentiate between Enter (\r) and Ctrl+Enter (\n) like we do on Windows

* add way more test cases and fix identified issues

* add more SCO mappings

* Numeric Keypad

* add Tmux 256 color test cases (TERM=screen-256color)

* fix issue discovered by adding more tmux test cases: ^[OM should be mapped to Enter

* address code review feedback

* add .NET 6 compat switch

* Apply suggestions from code review

Co-authored-by: David Cantú <dacantu@microsoft.com>

* address code review feedback

Co-authored-by: David Cantú <dacantu@microsoft.com>
  • Loading branch information
adamsitnik and jozkee authored Aug 1, 2022
1 parent 05c6f3d commit f1de614
Show file tree
Hide file tree
Showing 20 changed files with 3,337 additions and 972 deletions.
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
{
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

0 comments on commit f1de614

Please sign in to comment.