Initial commit

master
Avril 5 years ago
commit ccb6eb4379
Signed by: flanchan
GPG Key ID: 284488987C31F630

360
.gitignore vendored

@ -0,0 +1,360 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*[.json, .xml, .info]
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29609.76
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "termsync", "termsync\termsync.csproj", "{2CBA290C-FF91-4825-B96B-83A0F9151F9E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "test", "test\test.csproj", "{B4D9D0D8-C63A-479A-8443-48CCBFBB1C56}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2CBA290C-FF91-4825-B96B-83A0F9151F9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2CBA290C-FF91-4825-B96B-83A0F9151F9E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2CBA290C-FF91-4825-B96B-83A0F9151F9E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2CBA290C-FF91-4825-B96B-83A0F9151F9E}.Release|Any CPU.Build.0 = Release|Any CPU
{B4D9D0D8-C63A-479A-8443-48CCBFBB1C56}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B4D9D0D8-C63A-479A-8443-48CCBFBB1C56}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B4D9D0D8-C63A-479A-8443-48CCBFBB1C56}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B4D9D0D8-C63A-479A-8443-48CCBFBB1C56}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E035A5E5-8125-44B3-8F69-557971CAFB19}
EndGlobalSection
EndGlobal

@ -0,0 +1,200 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
namespace termsync.Tools
{
sealed class AsyncMutex : IDisposable
{
private readonly SemaphoreSlim sem;
public AsyncMutex()
{
sem = new SemaphoreSlim(1, 1);
}
private AsyncMutex(SemaphoreSlim from)
{
sem = from;
}
private class Lock : IDisposable
{
public AsyncMutex Parent { get; }
public Lock(AsyncMutex held)
{
Parent = held;
}
public void Dispose()
{
Parent.sem.Release();
}
}
public IDisposable Acquire(int msTimeout, CancellationToken token = default)
{
sem.Wait(msTimeout, token);
return new Lock(this);
}
public IDisposable Acquire(CancellationToken token)
{
sem.Wait(token);
return new Lock(this);
}
public IDisposable Acquire()
{
sem.Wait();
return new Lock(this);
}
public async Task<IDisposable> AcquireAsync(int msTimeout, CancellationToken token = default)
{
await sem.WaitAsync(msTimeout, token);
return new Lock(this);
}
public async Task<IDisposable> AcquireAsync(CancellationToken token = default)
{
await sem.WaitAsync(token);
return new Lock(this);
}
public void Dispose()
{
sem.Dispose();
}
public static AsyncMutex Semaphore(int count, int max)
{
SemaphoreSlim sem = new SemaphoreSlim(count, max);
return new AsyncMutex(sem);
}
public static AsyncMutex Semaphore(int count)
=> Semaphore(count, count);
}
static class ExAsyncTools
{
#region Then()
public static async Task Then(this Task t, Action lam)
{
await t;
lam();
}
public static Task Then(this Task t, Action lam, CancellationToken token)
=> Then(t, (_) => lam(), token);
public static async Task Then(this Task t, Action<CancellationToken> lam, CancellationToken token)
{
TaskCompletionSource<bool> fail = new TaskCompletionSource<bool>();
using (token.Register(() => fail.TrySetResult(false)))
{
if ((await Task.WhenAny(t, fail.Task)) == t)
{
lam(token);
}
token.ThrowIfCancellationRequested();
}
}
public static async Task Then(this Task t, Func<Task> lam)
{
await t;
await lam();
}
public static Task Then(this Task t, Func<Task> lam, CancellationToken token)
=> Then(t, (_) => lam(), token);
public static async Task Then(this Task t, Func<CancellationToken, Task> lam, CancellationToken token)
{
TaskCompletionSource<bool> fail = new TaskCompletionSource<bool>();
using (token.Register(() => fail.TrySetResult(false)))
{
if ((await Task.WhenAny(t, fail.Task)) == t)
{
await lam(token);
}
token.ThrowIfCancellationRequested();
}
}
public static async Task<T> Then<T>(this Task<T> t, Action<T> lam)
{
T res = await t;
lam(res);
return res;
}
public static Task<T> Then<T>(this Task<T> t, Action<T> lam, CancellationToken token)
=> Then(t, (v, _) => lam(v), token);
public static async Task<T> Then<T>(this Task<T> t, Action<T, CancellationToken> lam, CancellationToken token)
{
TaskCompletionSource<bool> fail = new TaskCompletionSource<bool>();
using (token.Register(() => fail.TrySetResult(false)))
{
if ((await Task.WhenAny(t, fail.Task)) == t)
{
var res = t.Result;
lam(res, token);
return res;
}
throw new OperationCanceledException();
}
}
public static async Task<T> Then<T>(this Task<T> t, Func<T, T> lam)
{
T res = await t;
return lam(res);
}
public static Task<T> Then<T>(this Task<T> t, Func<T, T> lam, CancellationToken token)
=> Then(t, (v, _) => lam(v), token);
public static async Task<T> Then<T>(this Task<T> t, Func<T, CancellationToken, T> lam, CancellationToken token)
{
TaskCompletionSource<bool> fail = new TaskCompletionSource<bool>();
using (token.Register(() => fail.TrySetResult(false)))
{
if ((await Task.WhenAny(t, fail.Task)) == t)
{
var res = t.Result;
res = lam(res, token);
return res;
}
throw new OperationCanceledException();
}
}
public static async Task<T> Then<T>(this Task<T> t, Func<T, Task<T>> lam)
{
return await lam(await t);
}
public static Task<T> Then<T>(this Task<T> t, Func<T, Task<T>> lam, CancellationToken token)
=> Then(t, (x, _) => lam(x), token);
public static async Task<T> Then<T>(this Task<T> t, Func<T, CancellationToken, Task<T>> lam, CancellationToken token)
{
TaskCompletionSource<bool> fail = new TaskCompletionSource<bool>();
using (token.Register(() => fail.TrySetResult(false)))
{
if ((await Task.WhenAny(t, fail.Task)) == t)
{
var res = t.Result;
res = await lam(res, token);
return res;
}
throw new OperationCanceledException();
}
}
#endregion
public static CancellationTokenSource Link(this in CancellationToken token, params CancellationToken[] others)
{
return CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken[] { token }.Concat(others).ToArray());
}
}
}

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace termsync
{
enum DeleteLocation
{
Before, //Backspace
After, //DEL
}
enum MoveDirection
{
Left,Right,
}
enum ControlType
{
Print, //WriteLine
Move, //Move the cursor
Delete, //Delete a character from input
Commit, //Commit input
Echo, // Add a character to input
ChangePrompt,
}
readonly struct ControlValue
{
public readonly ControlType Type;
public readonly object Value;
public readonly TaskCompletionSource<object> Processed;
public ControlValue(ControlType type, object value)
{
Type = type;
Value = value;
Processed = new TaskCompletionSource<object>();
}
}
}

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace termsync
{
static partial class Terminal
{
private static class Mutation
{
public static void ClearInputBuffer()
{
Console.CursorLeft = 0;
Console.Write(new string(' ', Console.WindowWidth - 1));
Console.CursorLeft = 0;
}
public static void RedrawInputBuffer(bool prompt=true)
{
if(prompt)
Console.Write(Prompt);
if (InputBuffer.Count > 0)
Console.Write(InputBuffer.ToArray());
if (InputAt > -1)
Console.CursorLeft -= InputBuffer.Count - InputAt;
}
public static void MoveBackOne()
{
Console.MoveBufferArea(Console.CursorLeft + 1, Console.CursorTop, InputBuffer.Count - InputAt, 1, Console.CursorLeft, Console.CursorTop);
}
public static void MoveForwardOne()
{
Console.MoveBufferArea(Console.CursorLeft, Console.CursorTop, InputBuffer.Count - InputAt, 1, Console.CursorLeft + 1, Console.CursorTop);
}
public static async Task FlushAsync(ChannelWriter<string> lines, CancellationToken token =default)
{
ClearInputBuffer();
var inp = new string(InputBuffer.ToArray());
var line_send= lines.WriteAsync(inp, token);
InputBuffer.Clear();
InputAt = -1;
RedrawInputBuffer();
if (WriteLineOnFlush)
await WriteLine(Prompt + inp, token);
await line_send;
}
}
}
}

@ -0,0 +1,466 @@
using System;
using System.Threading.Tasks;
using System.Threading;
using System.Threading.Channels;
using termsync.Tools;
using System.Collections.Generic;
namespace termsync
{
/// <summary>
/// A Write container that aquires a mutex on `Terminal`, preventing other writes while held.
/// </summary>
public sealed class TermLock : IDisposable
{
private readonly CancellationTokenSource cancel;
private readonly AsyncMutex GlobalMutex;
private IDisposable held_lock = null;
internal TermLock(AsyncMutex mutex, CancellationToken token=default)
{
GlobalMutex = mutex;
cancel = CancellationTokenSource.CreateLinkedTokenSource(token);
}
internal async Task Acquire()
{
held_lock = await GlobalMutex.AcquireAsync(cancel.Token);
}
/// <summary>
/// Write a line with lock held.
/// </summary>
public Task WriteLine(string line)
{
return Terminal.WriteLineAndWait(line, cancel.Token);
}
public void Dispose()
{
cancel.Cancel();
cancel.Dispose();
if(held_lock!=null)
{
held_lock.Dispose();
held_lock = null;
}
}
~TermLock()
{
if (held_lock != null)
{
held_lock.Dispose();
held_lock = null;
}
}
}
public sealed class TermStage : IAsyncDisposable
{
private readonly AsyncMutex mutex = new AsyncMutex();
private readonly List<string> lines = new List<string>();
private readonly CancellationTokenSource cancel;
private readonly AsyncMutex globalMutex;
private readonly CancellationToken originalToken;
internal TermStage(AsyncMutex globalM, CancellationToken token)
{
originalToken = token;
globalMutex = globalM;
cancel = CancellationTokenSource.CreateLinkedTokenSource(token);
}
public async Task WriteLine(string line)
{
using (await mutex.AcquireAsync(cancel.Token))
{
lines.Add(line);
}
}
public async ValueTask DisposeAsync()
{
await mutex.AcquireAsync(cancel.Token);
cancel.Cancel();
mutex.Dispose();
cancel.Dispose();
using (await globalMutex.AcquireAsync(originalToken))
{
foreach (var line in lines)
{
await Terminal.WriteLineAndWait(line, originalToken);
}
}
lines.Clear();
}
}
//TODO: WriteLine staging that doesn't block until read to commit all.
/// <summary>
/// Terminal control global state.
/// </summary>
public static partial class Terminal
{
#region Sync
private static readonly CancellationTokenSource CancelAll = new CancellationTokenSource();
private static ChannelReader<string> Input;
private static ChannelWriter<ControlValue> Output;
private static readonly AsyncMutex ConsoleMutex = new AsyncMutex();
#endregion
#region Buffer
private static readonly List<char> InputBuffer = new List<char>();
/// <summary>
/// The place in the <see cref="InputBuffer"/> that the user is writing to.
/// </summary>
private static int InputAt = -1;
public static string Prompt { get; private set; } = "> ";
private static bool WriteLineOnFlush = true;
#endregion
#region Control
private static readonly AsyncMutex UserWriteMutex = new AsyncMutex();
private static readonly AsyncMutex UserReadMutex = new AsyncMutex();
/// <summary>
/// Acquire global Write lock mutex.
/// </summary>
public static async Task<TermLock> Lock()
{
var l = new TermLock(UserWriteMutex, CancelAll.Token);
await l.Acquire();
return l;
}
/// <summary>
/// Create a staging container that will write all lines at once on DisposeAsync().
/// </summary>
public static TermStage Stage()
{
return new TermStage(UserWriteMutex, CancelAll.Token);
}
private static async Task<object> SendAndWait(ControlValue value, CancellationToken token = default)
{
TaskCompletionSource<bool> onCancel = new TaskCompletionSource<bool>();
using var reg = token.Register(() =>
{
onCancel.SetResult(false);
});
await Output.WriteAsync(value, token);
if (await Task.WhenAny(value.Processed.Task, onCancel.Task) == value.Processed.Task)
{
return value.Processed.Task.Result;
}
else throw new OperationCanceledException();
}
/// <summary>
/// Write a line to the Terminal and wait for it to appear.
/// </summary>
/// <param name="line">The line</param>
public static async Task WriteLine(string line)
{
using(await UserWriteMutex.AcquireAsync(CancelAll.Token))
{
await SendAndWait(new ControlValue(ControlType.Print, line), CancelAll.Token);
}
}
internal static ValueTask WriteLine(string str, CancellationToken token)
{
return Output.WriteAsync(new ControlValue(ControlType.Print, str), token);
}
internal static Task WriteLineAndWait(string str, CancellationToken token)
{
return SendAndWait(new ControlValue(ControlType.Print, str), token);
}
/// <summary>
/// Read a line from the user.
/// </summary>
public static async Task<string> ReadLine(CancellationToken token=default)
{
using var cancel = CancellationTokenSource.CreateLinkedTokenSource(CancelAll.Token, token);
token = cancel.Token;
using (await UserReadMutex.AcquireAsync(token))
{
return await Input.ReadAsync(token);
}
}
/// <summary>
/// Change the user prompt.
/// </summary>
/// <param name="prompt">New prompt.</param>
public static async Task ChangePrompt(string prompt)
{
using (await UserWriteMutex.AcquireAsync(CancelAll.Token))
{
await SendAndWait(new ControlValue(ControlType.ChangePrompt, prompt), CancelAll.Token);
}
}
#endregion
/// <summary>
/// Initialise terminal control. Writes go through <see cref="Terminal"/> after this.
/// </summary>
/// <returns>The control task.</returns>
public static Task Initialise()
{
var input = Channel.CreateUnbounded<string>();
var output = Channel.CreateBounded<ControlValue>(10);
Input = input.Reader;
Output = output.Writer;
AppDomain.CurrentDomain.ProcessExit += (_, __) => Cleanup();
var t_output = Task.Run(async () =>
{
try
{
await ctrl_output(output.Reader, input.Writer);
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
if (!CancelAll.IsCancellationRequested)
CancelAll.Cancel();
}
});
var t_input = Task.Run(async () =>
{
try
{
await ctrl_intput();
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
if(!CancelAll.IsCancellationRequested)
CancelAll.Cancel();
}
});
return Task.Run(async () =>
{
await Task.WhenAll(t_input, t_output);
});
}
private static async Task ctrl_output(ChannelReader<ControlValue> output, ChannelWriter<string> lines)
{
await foreach(var value in output.ReadAllAsync(CancelAll.Token))
{
object result = null;
try
{
switch (value.Type)
{
case ControlType.Print when value.Value is string line:
using (await ConsoleMutex.AcquireAsync(CancelAll.Token))
{
Mutation.ClearInputBuffer();
Console.WriteLine(line);
Mutation.RedrawInputBuffer();
}
break;
case ControlType.Move:
using (await ConsoleMutex.AcquireAsync(CancelAll.Token))
{
if (InputAt == -1) InputAt = InputBuffer.Count;
switch ((MoveDirection)value.Value)
{
case MoveDirection.Left:
if (InputAt > 0)
{
InputAt -= 1;
Console.CursorLeft -= 1;
}
break;
case MoveDirection.Right:
if (InputAt < InputBuffer.Count)
{
InputAt += 1;
Console.CursorLeft += 1;
}
break;
}
if (InputAt >= InputBuffer.Count)
InputAt = -1;
}
break;
case ControlType.Delete:
using (await ConsoleMutex.AcquireAsync(CancelAll.Token))
{
switch ((DeleteLocation)value.Value)
{
case DeleteLocation.After:
if (InputBuffer.Count > 0)
{
if (InputAt >= 0 && InputAt < InputBuffer.Count)
{
InputBuffer.RemoveAt(InputAt);
Console.Write(" \b");
Mutation.MoveBackOne();
}
}
break;
case DeleteLocation.Before:
if (InputBuffer.Count > 0)
{
if (InputAt > 0 && InputAt < InputBuffer.Count)
{
InputBuffer.RemoveAt(InputAt - 1);
InputAt -= 1;
Console.Write("\b");
Mutation.MoveBackOne();
}
else if (InputAt != 0)
{
InputBuffer.RemoveAt(InputBuffer.Count - 1);
Console.Write("\b \b");
}
}
break;
}
}
break;
case ControlType.Commit:
using (await ConsoleMutex.AcquireAsync(CancelAll.Token))
{
await Mutation.FlushAsync(lines, CancelAll.Token);
}
break;
case ControlType.Echo:
using (await ConsoleMutex.AcquireAsync(CancelAll.Token))
{
var input = value.Value as string;
if (input == null) continue;
for (int i = 0; i < input.Length; i++)
{
switch (input[i])
{
case '\n':
case '\r':
//Should be handled by `Commit`, something went wrong if they end up here.
break;
case '\b':
//Ditto for `Delete`.
break;
default:
{
if (((InputAt == -1) ? Console.CursorLeft : Console.CursorLeft + (InputBuffer.Count - InputAt)) >= Console.BufferWidth - 1) break; //TODO: Scrolling buffer?
if (InputAt >= 0 && InputAt < InputBuffer.Count)
{
InputBuffer.Insert(InputAt, input[i]);
InputAt += 1;
Mutation.MoveForwardOne();
}
else
{
InputBuffer.Add(input[i]);
}
Console.Write(input[i]);
}
break;
}
}
}
break;
case ControlType.ChangePrompt:
using (await ConsoleMutex.AcquireAsync(CancelAll.Token))
{
Prompt = (string)value.Value;
Mutation.ClearInputBuffer();
Mutation.RedrawInputBuffer();
}
break;
}
}
finally
{
value.Processed.SetResult(result);
}
}
lines.Complete();
InputBuffer.Clear();
}
/// <summary>
/// Read from the Console and pipe buffer control events to `Output`.
/// </summary>
private static async Task ctrl_intput()
{
while (!CancelAll.IsCancellationRequested)
{
var key = Console.ReadKey(true); // This blocks.
if (CancelAll.IsCancellationRequested) break;
switch (key.Key)
{
case ConsoleKey.LeftArrow:
await Output.WriteAsync(new ControlValue(ControlType.Move, MoveDirection.Left), CancelAll.Token);
break;
case ConsoleKey.RightArrow:
await Output.WriteAsync(new ControlValue(ControlType.Move, MoveDirection.Right), CancelAll.Token);
break;
case ConsoleKey.Delete:
await Output.WriteAsync(new ControlValue(ControlType.Delete, DeleteLocation.After), CancelAll.Token);
break;
case ConsoleKey.Backspace:
await Output.WriteAsync(new ControlValue(ControlType.Delete, DeleteLocation.Before), CancelAll.Token);
break;
case ConsoleKey.Enter:
await Output.WriteAsync(new ControlValue(ControlType.Commit, null), CancelAll.Token);
break;
default:
await Output.WriteAsync(new ControlValue(ControlType.Echo, new string(new[] { key.KeyChar })), CancelAll.Token);
break;
}
}
}
/// <summary>
/// Close all <see cref="Terminal"/> channels.
/// </summary>
public static void Close()
{
Output.Complete();
}
private static void Cleanup()
{
try
{
Output.Complete();
}
catch { }
if (!CancelAll.IsCancellationRequested)
CancelAll.Cancel();
CancelAll.Dispose();
ConsoleMutex.Dispose();
}
}
}

@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
</Project>

@ -0,0 +1,47 @@
using System;
using System.Threading.Tasks;
using termsync;
namespace test
{
class Program
{
static async Task Main(string[] args)
{
_ = Terminal.Initialise();
await Terminal.WriteLine("Hiya!");
await Terminal.WriteLine("Another line...");
var line = await Terminal.ReadLine();
await Terminal.WriteLine("Line: " + line);
await Task.WhenAll(Task.Run(async () =>
{
await using (var stage = Terminal.Stage())
{
await stage.WriteLine("One line");
await stage.WriteLine("Two line");
await stage.WriteLine("Three line");
await stage.WriteLine("Four");
}
}),
Task.Run(async () =>
{
using (var lck = await Terminal.Lock())
{
await lck.WriteLine("One line locked");
await lck.WriteLine("Two line locked");
await lck.WriteLine("Three line locked");
await lck.WriteLine("Four locked");
}
}));
await Terminal.ChangePrompt("USER> " + await Terminal.ReadLine()+":: ");
await Terminal.WriteLine("New prompt!");
await Terminal.ReadLine();
Terminal.Close();
}
}
}

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\termsync\termsync.csproj" />
</ItemGroup>
</Project>
Loading…
Cancel
Save