Add support for setting encoding

This commit is contained in:
Patrik Svensson 2021-06-02 23:19:44 +02:00
Родитель 0e0d1bd1af
Коммит 28b951d919
3 изменённых файлов: 47 добавлений и 8 удалений

Просмотреть файл

@ -8,14 +8,20 @@ namespace Spectre.Terminals.Windows
internal sealed class WindowsTerminalReader : WindowsTerminalHandle, ITerminalReader
{
private readonly WindowsDriver _driver;
private Encoding _encoding;
public Encoding Encoding
{
get => _encoding;
set => SetEncoding(value);
}
public Encoding Encoding { get; }
public bool IsRawMode => _driver.IsRawMode;
public WindowsTerminalReader(WindowsDriver driver)
: base(STD_HANDLE_TYPE.STD_INPUT_HANDLE)
{
Encoding = EncodingHelper.GetEncodingFromCodePage((int)PInvoke.GetConsoleCP());
_encoding = EncodingHelper.GetEncodingFromCodePage((int)PInvoke.GetConsoleCP());
_driver = driver;
}
@ -45,5 +51,13 @@ namespace Spectre.Terminals.Windows
return (int)result;
}
private void SetEncoding(Encoding encoding)
{
if (PInvoke.SetConsoleCP((uint)encoding.CodePage))
{
_encoding = encoding;
}
}
}
}

Просмотреть файл

@ -11,7 +11,7 @@ namespace Spectre.Terminals
/// <summary>
/// Gets the encoding.
/// </summary>
Encoding Encoding { get; }
Encoding Encoding { get; set; }
/// <summary>
/// Gets a value indicating whether or not the reader has been redirected.

Просмотреть файл

@ -9,7 +9,12 @@ namespace Spectre.Terminals
private readonly object _lock;
private ITerminalReader? _redirected;
public Encoding Encoding => GetEncoding();
public Encoding Encoding
{
get => GetEncoding();
set => SetEncoding(value);
}
public bool IsRedirected => GetIsRedirected();
public TerminalInput(ITerminalReader reader)
@ -39,6 +44,19 @@ namespace Spectre.Terminals
}
}
private bool GetIsRedirected()
{
lock (_lock)
{
if (_redirected != null)
{
return _redirected.IsRedirected;
}
return _reader.IsRedirected;
}
}
private Encoding GetEncoding()
{
lock (_lock)
@ -52,16 +70,23 @@ namespace Spectre.Terminals
}
}
private bool GetIsRedirected()
private void SetEncoding(Encoding encoding)
{
if (encoding is null)
{
throw new ArgumentNullException(nameof(encoding));
}
lock (_lock)
{
if (_redirected != null)
{
return _redirected.IsRedirected;
_redirected.Encoding = encoding;
}
else
{
_reader.Encoding = encoding;
}
return _reader.IsRedirected;
}
}
}