Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
move factory logic to DatabaseFactory so the test project does not ne…
…ed to reference all sys-calls used for reading files
  • Loading branch information
adamsitnik committed Jun 28, 2022
commit cf77107555871c2c51240c259f5a2c71ebaa9de6
1 change: 1 addition & 0 deletions src/libraries/System.Console/src/System.Console.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@
<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\IO\StdInReader.cs" />
<Compile Include="System\IO\SyncTextReader.Unix.cs" />
<Compile Include="$(CoreLibSharedDir)System\IO\PersistedFiles.Unix.cs"
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Console/src/System/ConsolePal.Unix.cs
Original file line number Diff line number Diff line change
Expand Up @@ -961,7 +961,7 @@ internal sealed class TerminalFormatStrings
{
/// <summary>Gets the lazily-initialized terminal information for the terminal.</summary>
public static TerminalFormatStrings Instance { get { return s_instance.Value; } }
private static readonly Lazy<TerminalFormatStrings> s_instance = new Lazy<TerminalFormatStrings>(() => new TerminalFormatStrings(TermInfo.Database.ReadActiveDatabase()));
private static readonly Lazy<TerminalFormatStrings> s_instance = new Lazy<TerminalFormatStrings>(() => new TerminalFormatStrings(TermInfo.DatabaseFactory.ReadActiveDatabase()));

/// <summary>The format string to use to change the foreground color.</summary>
public readonly string? Foreground;
Expand Down
119 changes: 1 addition & 118 deletions src/libraries/System.Console/src/System/TermInfo.Database.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using Microsoft.Win32.SafeHandles;

namespace System;

Expand Down Expand Up @@ -42,7 +39,7 @@ internal sealed class Database
/// <summary>Initializes the database instance.</summary>
/// <param name="term">The name of the terminal.</param>
/// <param name="data">The data from the terminfo file.</param>
private Database(string term, byte[] data)
internal Database(string term, byte[] data)
{
_term = term;
_data = data;
Expand Down Expand Up @@ -84,120 +81,6 @@ private Database(string term, byte[] data)
/// <summary>The name of the associated terminfo, if any.</summary>
public string Term { get { return _term; } }

/// <summary>Read the database for the current terminal as specified by the "TERM" environment variable.</summary>
/// <returns>The database, or null if it could not be found.</returns>
internal static Database? ReadActiveDatabase()
{
string? term = Environment.GetEnvironmentVariable("TERM");
return !string.IsNullOrEmpty(term) ? ReadDatabase(term) : null;
}

/// <summary>
/// The default locations in which to search for terminfo databases.
/// This is the ordering of well-known locations used by ncurses.
/// </summary>
private static readonly string[] _terminfoLocations = new string[] {
"/etc/terminfo",
"/lib/terminfo",
"/usr/share/terminfo",
"/usr/share/misc/terminfo",
"/usr/local/share/terminfo"
};

/// <summary>Read the database for the specified terminal.</summary>
/// <param name="term">The identifier for the terminal.</param>
/// <returns>The database, or null if it could not be found.</returns>
private static Database? ReadDatabase(string term)
{
// This follows the same search order as prescribed by ncurses.
Database? db;

// First try a location specified in the TERMINFO environment variable.
string? terminfo = Environment.GetEnvironmentVariable("TERMINFO");
if (!string.IsNullOrWhiteSpace(terminfo) && (db = ReadDatabase(term, terminfo)) != null)
{
return db;
}

// Then try in the user's home directory.
string? home = PersistedFiles.GetHomeDirectory();
if (!string.IsNullOrWhiteSpace(home) && (db = ReadDatabase(term, home + "/.terminfo")) != null)
{
return db;
}

// Then try a set of well-known locations.
foreach (string terminfoLocation in _terminfoLocations)
{
if ((db = ReadDatabase(term, terminfoLocation)) != null)
{
return db;
}
}

// Couldn't find one
return null;
}

/// <summary>Attempt to open as readonly the specified file path.</summary>
/// <param name="filePath">The path to the file to open.</param>
/// <param name="fd">If successful, the opened file descriptor; otherwise, -1.</param>
/// <returns>true if the file was successfully opened; otherwise, false.</returns>
private static bool TryOpen(string filePath, [NotNullWhen(true)] out SafeFileHandle? fd)
{
fd = Interop.Sys.Open(filePath, Interop.Sys.OpenFlags.O_RDONLY | Interop.Sys.OpenFlags.O_CLOEXEC, 0);
if (fd.IsInvalid)
{
// Don't throw in this case, as we'll be polling multiple locations looking for the file.
fd = null;
return false;
}

return true;
}

/// <summary>Read the database for the specified terminal from the specified directory.</summary>
/// <param name="term">The identifier for the terminal.</param>
/// <param name="directoryPath">The path to the directory containing terminfo database files.</param>
/// <returns>The database, or null if it could not be found.</returns>
private static Database? ReadDatabase(string? term, string? directoryPath)
{
if (string.IsNullOrEmpty(term) || string.IsNullOrEmpty(directoryPath))
{
return null;
}

Span<char> stackBuffer = stackalloc char[256];
SafeFileHandle? fd;
if (!TryOpen(string.Create(null, stackBuffer, $"{directoryPath}/{term[0]}/{term}"), out fd) && // /directory/termFirstLetter/term (Linux)
!TryOpen(string.Create(null, stackBuffer, $"{directoryPath}/{(int)term[0]:X}/{term}"), out fd)) // /directory/termFirstLetterAsHex/term (Mac)
{
return null;
}

using (fd)
{
// Read in all of the terminfo data
long termInfoLength = Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_END)); // jump to the end to get the file length
Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_SET)); // reset back to beginning
const int MaxTermInfoLength = 4096; // according to the term and tic man pages, 4096 is the terminfo file size max
const int HeaderLength = 12;
if (termInfoLength <= HeaderLength || termInfoLength > MaxTermInfoLength)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}

byte[] data = new byte[(int)termInfoLength];
if (ConsolePal.Read(fd, data) != data.Length)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}

// Create the database from the data
return new Database(term, data);
}
}

/// <summary>The offset into data where the names section begins.</summary>
private const int NamesOffset = 12; // comes right after the header, which is always 12 bytes

Expand Down
128 changes: 128 additions & 0 deletions src/libraries/System.Console/src/System/TermInfo.DatabaseFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Licensed to the .NET Foundation under one or more agreements.
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've not changed any logic here, just moved it from TermInfo.cs

// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics.CodeAnalysis;
using System.IO;
using Microsoft.Win32.SafeHandles;

namespace System;

internal static partial class TermInfo
{
internal sealed class DatabaseFactory
{
/// <summary>
/// The default locations in which to search for terminfo databases.
/// This is the ordering of well-known locations used by ncurses.
/// </summary>
private static readonly string[] _terminfoLocations = new string[] {
"/etc/terminfo",
"/lib/terminfo",
"/usr/share/terminfo",
"/usr/share/misc/terminfo",
"/usr/local/share/terminfo"
};

/// <summary>Read the database for the current terminal as specified by the "TERM" environment variable.</summary>
/// <returns>The database, or null if it could not be found.</returns>
internal static Database? ReadActiveDatabase()
{
string? term = Environment.GetEnvironmentVariable("TERM");
return !string.IsNullOrEmpty(term) ? ReadDatabase(term) : null;
}

/// <summary>Read the database for the specified terminal.</summary>
/// <param name="term">The identifier for the terminal.</param>
/// <returns>The database, or null if it could not be found.</returns>
private static Database? ReadDatabase(string term)
{
// This follows the same search order as prescribed by ncurses.
Database? db;

// First try a location specified in the TERMINFO environment variable.
string? terminfo = Environment.GetEnvironmentVariable("TERMINFO");
if (!string.IsNullOrWhiteSpace(terminfo) && (db = ReadDatabase(term, terminfo)) != null)
{
return db;
}

// Then try in the user's home directory.
string? home = PersistedFiles.GetHomeDirectory();
if (!string.IsNullOrWhiteSpace(home) && (db = ReadDatabase(term, home + "/.terminfo")) != null)
{
return db;
}

// Then try a set of well-known locations.
foreach (string terminfoLocation in _terminfoLocations)
{
if ((db = ReadDatabase(term, terminfoLocation)) != null)
{
return db;
}
}

// Couldn't find one
return null;
}

/// <summary>Attempt to open as readonly the specified file path.</summary>
/// <param name="filePath">The path to the file to open.</param>
/// <param name="fd">If successful, the opened file descriptor; otherwise, -1.</param>
/// <returns>true if the file was successfully opened; otherwise, false.</returns>
private static bool TryOpen(string filePath, [NotNullWhen(true)] out SafeFileHandle? fd)
{
fd = Interop.Sys.Open(filePath, Interop.Sys.OpenFlags.O_RDONLY | Interop.Sys.OpenFlags.O_CLOEXEC, 0);
if (fd.IsInvalid)
{
// Don't throw in this case, as we'll be polling multiple locations looking for the file.
fd = null;
return false;
}

return true;
}

/// <summary>Read the database for the specified terminal from the specified directory.</summary>
/// <param name="term">The identifier for the terminal.</param>
/// <param name="directoryPath">The path to the directory containing terminfo database files.</param>
/// <returns>The database, or null if it could not be found.</returns>
private static Database? ReadDatabase(string? term, string? directoryPath)
{
if (string.IsNullOrEmpty(term) || string.IsNullOrEmpty(directoryPath))
{
return null;
}

Span<char> stackBuffer = stackalloc char[256];
SafeFileHandle? fd;
if (!TryOpen(string.Create(null, stackBuffer, $"{directoryPath}/{term[0]}/{term}"), out fd) && // /directory/termFirstLetter/term (Linux)
!TryOpen(string.Create(null, stackBuffer, $"{directoryPath}/{(int)term[0]:X}/{term}"), out fd)) // /directory/termFirstLetterAsHex/term (Mac)
{
return null;
}

using (fd)
{
// Read in all of the terminfo data
long termInfoLength = Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_END)); // jump to the end to get the file length
Interop.CheckIo(Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_SET)); // reset back to beginning
const int MaxTermInfoLength = 4096; // according to the term and tic man pages, 4096 is the terminfo file size max
const int HeaderLength = 12;
if (termInfoLength <= HeaderLength || termInfoLength > MaxTermInfoLength)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}

byte[] data = new byte[(int)termInfoLength];
if (ConsolePal.Read(fd, data) != data.Length)
{
throw new InvalidOperationException(SR.IO_TermInfoInvalid);
}

// Create the database from the data
return new Database(term, data);
}
}
}
}